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/main
<repo_name>ajaynagar20bcs115/DSA-through-c<file_sep>/linked_list.c #include<stdio.h> #include<string.h> #include<stdlib.h> #define sci(n) scanf("%d",&n) #define scc(n) scanf("%c",&n); #define true printf("True") #define jumpline printf("\n") #define pri(n) printf("%d",n) #define prs(s) printf("%s",s); #define prdata_accsess printf("->") #define spc printf(" ") #define malloc(x) (x*)malloc(sizeof(x)) #define false printf("False") typedef struct node {int data; struct node* next;}node; int isEmpty(node*head) { if(head==NULL) return 1; else return 0; } void print_list(node* head) { node* ptr=head; if(isEmpty(ptr)) { printf("list is empty"); } else { while(ptr->next!=NULL) { pri(ptr->data);prdata_accsess; ptr=ptr->next; } pri(ptr->data); } } void insert_at_first(node**head) { int x;sci(x); node*ptr=malloc(node); ptr->data=x; ptr->next=*head; * head=ptr; } void insert_at_last(node*head) { int x;sci(x); node*temp=head; while(temp->next!=NULL) { temp=temp->next; } node* ptr=malloc(node); ptr->data=x; ptr->next=NULL; temp->next=ptr; } void del_from_last(node*head) { node*ptr,*pre; ptr=head; while(ptr->next->next!=NULL){ ptr=ptr->next; } free(ptr->next); ptr->next=NULL; } void del_from_start(node**head) { if(isEmpty(*head)) { printf("list is empty"); } else{ node* temp=(*head)->next,*deletable=*head; *head=temp; free(deletable);} } void insert_at_position(node*head) { int p,x; sci(p);sci(x); node*inserted=malloc(node),*linker=malloc(node),*ptr=malloc(node); inserted->data=x; p--;p--; ptr=head; while(p--) { ptr=ptr->next; } linker=ptr->next; ptr->next=inserted; inserted->next=linker; } void delete_from_position(node*head) { int p;sci(p); node*ptr=malloc(node),*temp=malloc(node); p=p-2; ptr=head; while(p--) { ptr=ptr->next; } temp=ptr->next; ptr->next=temp->next; free(temp); } int main(){ node*head=NULL; char choice; while(1){ scanf("%c",&choice); switch(choice) { case'a': { print_list(head); } break; case 'b': { insert_at_first(&head); } break; case 'c' : { insert_at_last(head); } break; case 'd' : { insert_at_position(head); } break; case 'e' : { del_from_start(&head); } break; case 'f' : { del_from_last(head); } break; case 'g' : { delete_from_position(head); } } } } <file_sep>/selection_sort.c #include<stdio.h> #include<string.h> #include<stdlib.h> #define sci(n) scanf("%d",&n) #define true printf("True") #define ln printf("\n") #define pri(n) printf("%d",n) #define prs(s) printf("%s",s) #define spc printf(" ") #define false printf("False") void selsort(int arr[],int n) { for(int i=0;i<=n-2;++i) { for(int j=i+1;j<n;++j) { if(arr[j]>arr[i]) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } for(int k=0;k<=i;++k) { pri(arr[k]);spc; } printf("\n"); } } int main(){ int n,key; sci(n); int a[n]; for(int i=0;i<n;++i) { sci(a[i]); } selsort(a,n); for(int i=0;i<n;++i) { pri(a[i]);spc; } spc; return 0; } <file_sep>/bubble_sort.c #include<stdio.h> #include<string.h> #include<stdlib.h> #define sci(n) scanf("%d",&n) #define true printf("True") #define ln printf("\n") #define pri(n) printf("%d",n) #define prs(s) printf("%s",s) #define spc printf(" ") #define false printf("False") void bubble (int arr[],int n) { //for bubble no of iteration needed is n-1 int ct=1; while(ct<=n-1) { for(int i=0;i<n-ct;++i) { if(arr[i+1]>arr[i]) { int temp=arr[i]; arr[i]=arr[i+1]; arr[i+1]=temp; } } ct++; } } int main(){ int n,key; sci(n); int a[n]; for(int i=0;i<n;++i) { sci(a[i]); } bubble(a,n); for(int i=0;i<n;++i) { pri(a[i]);spc; } return 0; } <file_sep>/README.md # DSA-through-c this has all code for basic DSAs <file_sep>/binearysearch.c #include<stdio.h> #include<string.h> #include<stdlib.h> #define sci(n) scanf("%d",&n) #define true printf("True") #define ln printf("\n") #define pri(n) printf("%d",n) #define prs(s) printf("%s",s) #define spc printf(" ") #define false printf("False") int find(int arr[],int n,int key) { int s=0,e=n-1; while(s<=e) { int mid=(s+e)/2; if(arr[mid]==key) return mid; if(arr[mid]>key) { e=mid-1; } if(arr[mid]<key) { s=mid+1; } } return -1; } int main(){ int n,key; sci(n); int a[n]; for(int i=0;i<n;++i) { sci(a[i]); } sci(key); int v=find(a,n,key); pri(v); } <file_sep>/temp.c #include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #define sci(n) scanf("%d",&n) #define true printf("True") #define jumpline printf("\n") #define pri(n) printf("%d",n) #define prs(s) printf("%s",s) #define spc printf(" ") #define false printf("False") #define fo(i,n) for(int i=0;i<n;i++) #define start int main(){ #define end } typedef struct node{ int data; struct node* next;}node; start int n;sci(n);pri(n); end
d33f4506c37428cd78dfb4d9a48d7007757e9d71
[ "Markdown", "C" ]
6
C
ajaynagar20bcs115/DSA-through-c
1b65800eb0902f97d0770e1b9b6c647b11b1dd44
8ddddabacd4982001b531c135e1f1e5f6824b171
refs/heads/master
<file_sep>public class Test { public static void main(String[] arg){ System.out.println("Hello Wim World!"); System.out.println("This is a Git Test"); } }
937dd45b6d1ef950baeadefcc5570b4aa5618ad8
[ "Java" ]
1
Java
willyblower/Test_repo
92ab90707d4f65313053b66c4faaf33fcfc1cc94
6ad18a9eadb83a194da23ba4b3a56216dbcad9aa
refs/heads/master
<repo_name>sadalsuud/procesadorDeTexto<file_sep>/src/src/WordUFPS.py # -*- coding: utf-8 -*- from PyQt4 import uic, QtGui, QtCore import vtnBuscar import VtnReemplazar import ListaCD QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot # Clase principal del editor, será un wrapper de la ventana a mostrar, en este # caso MainWindow class WordUFPS(QtGui.QMainWindow): def __init__(self, parent=None): super(WordUFPS, self).__init__(parent) # cargamos la interfaz gráfica desde el archivo textedito.ui self.ui es # ahora por llamarlo de alguna forma, un puntero al objeto MainWindow. self.ui = uic.loadUi('../share/ui/texteditor.ui', self) #referencia a los componentes de la ventana self.textEdit = self.ui.findChild(QtGui.QTextEdit) self.boton = self.ui.findChild(QtGui.QPushButton, "pushButton") self.optBuscar = self.ui.findChild(QtGui.QAction, "actionBuscar") self.optReemplazar = self.ui.findChild(QtGui.QAction, "actionReemplazar") self.optSalir = self.ui.findChild(QtGui.QAction, "actionSalir") self.optAbrir = self.ui.findChild(QtGui.QAction, "actionAbrir_archivo") self.optGuardar = self.ui.findChild(QtGui.QAction, "actionGuardar_archivo") # conectando signals y slots self.boton.clicked.connect(self.buscar) self.optBuscar.triggered.connect(self.buscar) self.optReemplazar.triggered.connect(self.reemplazar) self.optSalir.triggered.connect(self.close) self.optAbrir.triggered.connect(self.abrir) self.optGuardar.triggered.connect(self.guardar) # decoradores @QtCore.Slot() def buscar(self): contenido = self.textEdit.toPlainText() l = ListaCD.ListaCD([]) for i in contenido: l.addFin(str(i)) buscar = vtnBuscar.VtnBuscar(self, l) buscar.ui.exec_() @QtCore.Slot() def reemplazar(self): # variable = nombreDelArchivo.NombreDeLaClase reemplazar = VtnReemplazar.VtnReemplazar() reemplazar.ui.exec_() @QtCore.Slot() def abrir(self): filename = QtGui.QFileDialog.getOpenFileName(self, 'Abrir archivo', '.') fname = open(filename) data = fname.read() self.textEdit.setText(data) fname.close() @QtCore.Slot() def guardar(self): filename = QtGui.QFileDialog.getSaveFileName(self, 'Guardar archivo', '.') fname = open(filename, 'w') fname.write(self.textEdit.toPlainText()) fname.close() if __name__ == '__main__': app = QtGui.QApplication(["WordUFPSEditor"]) ProEditor = WordUFPS() ProEditor.show() app.exec_() <file_sep>/src/src/VtnReemplazar.py #!/usr/bin/env python # -*- coding: utf-8 -*- import sys from PyQt4 import uic, QtGui, QtCore QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot class VtnReemplazar(QtGui.QDialog): def __init__(self): super(VtnReemplazar, self).__init__(parent=None) self.ui = uic.loadUi('../share/ui/vtnReemplazar.ui', self) # referencia a los componentes de la ventana #self.linEdiBuscar = self.ui.findChild(QtGui.QLineEdit, "lineEdit") #self.linEdiReemplazar = self.ui.findChild(QtGui.QLineEdit, "lineEdit_2") self.btnReemplazar = self.ui.findChild(QtGui.QPushButton, "qpBtnReemplazar") # conectar signals y slots self.btnReemplazar.clicked.connect(self.reemplazar) @QtCore.Slot() def reemplazar(self): print "reeemplzando" if __name__ == '__main__': app = QtGui.QApplication(sys.argv) reemplazar = VtnReemplazar() reemplazar.ui.show() app.exec_() <file_sep>/src/src/vtnBuscar.py # -*- coding: utf-8 -*- import sys import ListaCD from PyQt4 import uic, QtGui, QtCore QtCore.Signal = QtCore.pyqtSignal QtCore.Slot = QtCore.pyqtSlot class VtnBuscar(QtGui.QDialog): # recibe por parametro en el contructor el texto que contiene el archivo def __init__(self, uiPri, l=None): super(VtnBuscar, self).__init__(parent=None) self.ui = uic.loadUi('../share/ui/vtnbuscar.ui', self) self.uiWordUfps = uiPri # referencia a la ventana principal self.l = l self.coincidencias = 0 # se hace referencia a los componentes de la ventana self.rta = self.ui.findChild(QtGui.QLabel,"qLbRta") self.busqueda = self.ui.findChild(QtGui.QLineEdit, "linEdBuscar") self.btnBuscar = self.ui.findChild(QtGui.QPushButton, "btnBuscar") # cuando el usuario presion el boton buscar self.btnBuscar.clicked.connect(self.buscar) @QtCore.Slot() def buscar(self): copia_lista = ListaCD.ListaCD(self.l) self.coincidencias = 0 # reinicia el conteo con cada nueva busqueda seq = [] # self.busqueda es un objeto QLineEdit y el texto se saca con .text() for c in self.busqueda.text(): seq.append(str(c)) # recorra toda el texto del archivo i = 0 for posicion in range(len(self.l)-1): # si coincide la primera letra de la busqueda y el texyo del archivo... pos = posicion #print "posicion ->", posicion while i < len(seq) and self.l.get(pos) == seq[i]: # si coinciden en el 1er simbolo del texto del archivo y el patron de búsqueda #print self.l.get(pos) i += 1 pos += 1 #print "i ->", i #print "pos ->", pos #print "fin de un ciclo de while" # si se alcanzo el final del tamaño de la busqueda if i == len(seq): self.coincidencias += 1 # por cada palabra que encuentr # pos - 1 porque aun no sé xD #print pos self.pintarCoincidencia(len(seq), pos -1, copia_lista) i = 0 #print "fin de un ciclo for" self.getCoincidencias() #print "se encontraron ", self.coincidencias, "coincidencias" # para obtener el numero de coincidencias def getCoincidencias(self): self.rta.setText(str(self.coincidencias) + " coincidencias") #return self.coincidencias def pintarCoincidencia(self, tam, pos, copia_lista): #~ print "tamaño de la busqueda", tam #~ print "posicion del ultimo caracter en la lista", pos # si la busqueda es un solo caracter if tam == 1: # pinte el caracter val = "<font color = '#E32828'>" + copia_lista.get(pos) + "</font>" copia_lista.set(pos, val) else: # inicie la pintada desde el primer caracter de la busqueda ini = "<font color ='#E32828'>" + copia_lista.get((pos - tam) + 1) # termine la pintada en el ultimo caracter de la busqueda fin = copia_lista.get(pos) + "</font>" #~ print "inicio de la palabra", ini #~ print "fin de la palaba", fin copia_lista.set((pos - tam) + 1, ini) copia_lista.set(pos, fin) html = "" # sacar el texto coloreado de la lisa para mostrarlo la interfaz for elem in copia_lista: html = html + elem self.uiWordUfps.textEdit.setHtml(html) #~ print html if __name__ == '__main__': app = QtGui.QApplication(sys.argv) buscar = VtnBuscar() buscar.ui.show() app.exec_() <file_sep>/src/src/ListaCD.py # -*- coding: utf-8 -*- # Clase para el manejo de una lista circular doble enlazada # @author <NAME> # @version 0.3 # hereda de la clase list class ListaCD(list): # constructor que sirve como parametrizado y contructor vacio def __init__(self, sequence=[]): super(ListaCD, self).__init__(sequence) self.pos = 0 # Adiciona un Elemento al Inicio de la Lista def addInicio(self, dato): self.insert(0, dato) self.pos = 0 # Inserta un Elemento al Final de la Lista def addFin(self, dato): self.append(dato) self.pos = len(self) - 1 # Borra un elemento de la lista dada una posicion def remove(self, i): self.pop(i) if i == 0 and self.size == 1: self.pos = 0 else: self.pos = i -1 # Retorna el Objeto de la posicion i def get(self, i): self.pos = i % len(self) return self[self.pos] # Modifica el dato en la posición i def set(self, i, dato): self.pos = i % len(self) self[self.pos] = dato # Borra la lista def removeAll(self): self.size = 0 del self[:] self.pos = 0 # Retorna true si la lista esta vacia, false en caso contrario def esVacia(self): return self == [] # Busca un elemento de la lista y devuelve su posicion. def indexOf(self, dato): return self.index(dato) # Me da el dato de la posición siguiente e a la actual def getSig(self, n=1): self.pos = (self.pos + n) % len(self) return self[self.pos] # Me da el dato y se para en el anterior def getAnt(self): i = self.pos self.pos -= 1 return self.getSig(i) if __name__ == '__main__': '''Clase testeada con unittest''' import unittest class Prueba(unittest.TestCase): def setUp(self): self.l = ListaCD([1, 2, 3, 15, "www", 'u']) def testAddInicio(self): aux = [1, 2, 3, 15, "www", 'u'] self.l.addInicio(3) self.assertEqual(self.l, [3] + aux) def testAddFin(self): aux = [1, 2, 3, 15, "www", 'u'] self.l.addFin(14) self.assertEqual(self.l, aux + [14]) def testRemove(self): aux = [1, 2, 15, "www", 'u'] self.l.remove(2) self.assertEqual(self.l, aux) def testGet(self): self.assertEqual(self.l.get(4), "www") self.assertEqual(self.l.get(8), 3) def testSet(self): self.l.set(4, "http") self.assertEqual(self.l.get(4), "http") def testRemoveAll(self): self.l.removeAll() self.assertEqual(self.l.size, 0) def testEsVacia(self): self.l.removeAll() self.assertEqual(self.l.esVacia(), True) def testIndexOf(self): self.assertEqual(self.l.indexOf("www"), 4) def testListaVacia(self): self.otra = ListaCD([]) self.assertEqual(self.otra.esVacia(), True) def testGetNext(self): self.assertEqual(self.l.get(5), 'u') self.assertEqual(self.l.getSig(), 1) def testGetAnt(self): self.assertEqual(self.l.get(0), 1) self.assertEqual(self.l.getAnt(), 'u') unittest.main() <file_sep>/README.md procesadorDeTexto ================= Una especie de procesador de texto que usa una lista circular doblemente enlazada para hacer busqueda de palabras en el texto y reemplazas palabras.
658435ad5604c94dcca34f46d3ccfc742c33a1f0
[ "Markdown", "Python" ]
5
Python
sadalsuud/procesadorDeTexto
cf18c266c877ea0ddbcee819a3fdac28f082230e
92d8bf425bb600d927afa722554446e6174f209a
refs/heads/master
<file_sep>(()=>{ const actions = { birdFlies(key){ if(key){ document.querySelector('[data-index="2"] .bird').style.transform = `translateX(${window.innerWidth}px`; }else{ document.querySelector('[data-index="2"] .bird').style.transform = `translateX(-100%)`; } }, birdFlies2(key){ if(key){ document.querySelector('[data-index="5"] .bird').style.transform = `translate(${window.innerWidth}px, -${window.innerHeight * 0.7}px)`; }else{ document.querySelector('[data-index="5"] .bird').style.transform = `translate(-100%)`; } } }; const stepElem = document.querySelectorAll('.step'); const graphicElem = document.querySelectorAll('.graphic-item'); let currentItem = graphicElem[0]; let io_index; const io = new IntersectionObserver((entries, observer)=>{ io_index = entries[0].target.dataset.index * 1; // 나타나거나 사라지는거 }); for(let i=0; i < stepElem.length; i++){ io.observe(stepElem[i]); //관찰대상등록 stepElem[i].setAttribute('data-index', i); graphicElem[i].setAttribute('data-index', i); //stepElem[i].dataset.index = i } function activate(action){ currentItem.classList.add('visible'); if (action) { actions[action](true); //객체의 메서드 호출 } } function inactivate(action){ currentItem.classList.remove('visible'); if (action) { actions[action](false); //객체의 메서드 호출 } } window.addEventListener('scroll', () =>{ let step; let boundingRect; let temp = 0; for(let i = io_index-1; i < io_index+1; i++){ step = stepElem[i]; if(!step) continue; boundingRect = step.getBoundingClientRect(); temp++; if((boundingRect.top > window.innerHeight * 0.1)&& (boundingRect.top < window.innerHeight * 0.8)){ inactivate(currentItem.dataset.action); currentItem = graphicElem[step.dataset.index]; activate(currentItem.dataset.action); } } }) activate(); window.addEventListener('load', ()=>{ setTimeout(() => scrollTo(0, 0), 100); //setTimeout 안하면 텍스트 스크롤 이벤트가 동작 안함 }) })();
c00d6ffb5afdb531db18c3150244a9dadaa7bc4e
[ "JavaScript" ]
1
JavaScript
minthing/1mincoding-bbc-covid19
76a174df0a88cc4227a133dd87047b5622c8bec5
29e88679c6e786f1beb38cc63b74cb48d234be52
refs/heads/master
<repo_name>beeragere/solveStringEquations<file_sep>/dummy.js function logName(){ console.log("shuhbs hello"); }<file_sep>/solve.js /* */ solveEquation = (equation) => { var eqLength = equation.length; var i = 0; var pivot, left, right, position; var leftNum, rightNum; //for ///////// while(i < eqLength){ if(equation[i] == '/'){ pivot = i; position = i; pivot++; while((checkSigns(equation[pivot]) == false) && (pivot < eqLength)){ pivot++; } right = pivot; pivot = i; pivot--; while((checkSigns(equation[pivot]) == false) && (pivot >= 0)){ pivot--; } left = pivot; leftNum = Number(equation.substring(position, left+1)); rightNum = Number(equation.substring(position+1, right)); equation = disintegrate(equation, ++left, right, leftNum/rightNum) i = 0; } i++; } //for ******** i = 0; while(i < eqLength){ if(equation[i] == '*'){ pivot = i; position = i; pivot++; while((checkSigns(equation[pivot]) == false) && (pivot < eqLength)){ pivot++; } right = pivot; pivot = i; pivot--; while((checkSigns(equation[pivot]) == false) && (pivot >= 0)){ pivot--; } left = pivot; leftNum = Number(equation.substring(position, left+1)); rightNum = Number(equation.substring(position+1, right)); equation = disintegrate(equation, ++left, right, leftNum*rightNum) i = 0; } i++; } //for ++++++ i = 0; while(i < eqLength){ if(equation[i] == '+'){ pivot = i; position = i; pivot++; while((checkSigns(equation[pivot]) == false) && (pivot < eqLength)){ pivot++; } right = pivot; pivot = i; pivot--; while((checkSigns(equation[pivot]) == false) && (pivot >= 0)){ pivot--; } left = pivot; leftNum = Number(equation.substring(position, left+1)); rightNum = Number(equation.substring(position+1, right)); equation = disintegrate(equation, ++left, right, leftNum+rightNum) i = 0; } i++; } //for ----- i = 0; while(i < eqLength){ if(equation[i] == '-'){ pivot = i; position = i; pivot++; while((checkSigns(equation[pivot]) == false) && (pivot < eqLength)){ pivot++; } right = pivot; pivot = i; pivot--; while((checkSigns(equation[pivot]) == false) && (pivot >= 0)){ pivot--; } left = pivot; leftNum = Number(equation.substring(position, left+1)); rightNum = Number(equation.substring(position+1, right)); equation = disintegrate(equation, ++left, right, leftNum-rightNum) i = 0; } i++; } return equation; } checkSigns = (symbol) =>{ if((symbol === '/') || (symbol === '-') || (symbol === '+') || (symbol === '*')){ return true; } else{ return false; } } function disintegrate(equation, left, right, replaceString){ return (equation.substring(0, left) + replaceString + equation.substring(right, (equation.length))); } function findBracketsAndSolve(equation){ var leftBracket, rightBracket, bracketCount; var eqLength, iterate; var slicedEquation, solved; //get the number of () in a given equation; eqLength = equation.length; iterate = 0; bracketCount = 0; while(iterate < eqLength){ if(equation[iterate] == '('){ bracketCount++; } iterate++; } while(bracketCount > 0){ //get the innermost () in the equation; iterate = 0; while(iterate < eqLength){ if(equation[iterate] == '('){ leftBracket = iterate; } iterate++; } iterate = leftBracket; while((equation[iterate] != ')') && (iterate < eqLength)){ iterate++; } rightBracket = iterate; slicedEquation = equation.slice(leftBracket+1, rightBracket); solved = solveEquation(slicedEquation); equation = disintegrate(equation, leftBracket, rightBracket+1, solved); bracketCount--; } equation = solveEquation(equation); return equation; } //actual calling of the functions; var equation = "100/(100/5)/5"; equation = findBracketsAndSolve(equation); console.log("final equation is ", equation);
00485295b2277ffb254eba952df5b8b6fd69864e
[ "JavaScript" ]
2
JavaScript
beeragere/solveStringEquations
3573f09a2ff96f19b9c7d78857027d9ad0c41fdb
047192f73bec60a914df8fc6511fcf7ae6a98bb7
refs/heads/main
<repo_name>herirudini/test_bootcamp_dumbwaysid_4<file_sep>/soal1.js var array_kode_barang = ["KD0023", "C42212", "D90312", "HI2020"]; var diskonA = 10 let harga_laptop_asus = 15000000 let harga_iphone = 12000000 let harga_xiaomi = 7000000 let harga_playstation = 15000000 var get_count = {} var AExist = false var BExist = false var CExist = false var DExist = false var harga_1 = 0 var harga_2 = 0 var harga_3 = 0 var harga_4 = 0 let subtotal = 0 console.log(checkout(array_kode_barang, diskonA)) ///gue bilang Capital letter itu untuk kode barang function checkout(array, diskonA) { console.log ("item yang dibeli : "); array_kode_barang.sort(); //access the x function array.forEach(function(x) { get_count[x] = (get_count[x] || 0) + 1; }); for (i = 0; i < array.length; i++) { switch(array[i]) { //when A case "KD0023": AExist = true break; //when B case "C42212": BExist = true break; //when C case "D90312": CExist = true break; //when D case "HI2020": DExist = true break; } } if (AExist) { console.log("Laptop Asus") console.log(harga_laptop_asus * get_count["KD0023"]) harga_1 = harga_laptop_asus * get_count["KD0023"] } if(BExist) { console.log("Iphone") console.log(harga_iphone * get_count["C42212"]) harga_2 = harga_iphone * get_count["C42212"] } if(CExist) { console.log("Xiaomi") console.log(harga_xiaomi * get_count["D90312"]) harga_3 = harga_xiaomi * get_count["D90312"] } if(DExist) { console.log("Playstation") console.log(harga_playstation * get_count["HI2020"]) harga_4 = harga_playstation * get_count["HI2020"] } var subtotal = harga_1 + harga_2 + harga_3 + harga_4 var diskon = subtotal * diskonA/100 console.log("Subtotal = " + subtotal) console.log("Diskon" + diskonA + "% = " + diskon) var totaltotal = subtotal - diskon console.log("Total Tagihan:") return totaltotal console.burn.all } <file_sep>/README.md # test_bootcamp_dumbwaysid_4 Test ikut bootcamp di DumbwaysId Batch 20 kloter 4 Tidak mampu mengerjakan soal nomor 1 pun
0144e21c539fcca8b6af71cce8c4bdad2e30bd2f
[ "JavaScript", "Markdown" ]
2
JavaScript
herirudini/test_bootcamp_dumbwaysid_4
ca3ebaaba749662d3fde3db3657323ed6eb5620d
c8c0e32eb9bd631007a008cf17ceeeeea27412ba
refs/heads/master
<repo_name>Santzo/react-interview<file_sep>/src/data/TodoData.js const todoData = [ { id: "1", name: 'Go to the supermarket', complete: false }, { id: "2", name: 'Call Alice', complete: false }, { id: "3", name: 'Ask Alice to call Bob', complete: false }, { id: "4", name: 'Do the dishes', complete: false }, { id: "5", name: 'Change car tyres', complete: false } ]; export default todoData; <file_sep>/src/tests/Todo.test.js import React from 'react'; import Enzyme, { shallow, mount } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import Todo from '../components/Todo' Enzyme.configure({ adapter: new Adapter() }); describe('Todo tests', () => { const props = { todo: { id: 0, name: 'TestTodo', complete: false }, onClick: jest.fn(), onRemoveClick: jest.fn() } const wrapper = shallow(<Todo {...props} />); const checkbox = wrapper.find('#check'); const todoName = wrapper.find('.todoName').first(); const removeBtn = wrapper.find('.btn'); test('checkbox should not be checked initially, todo not completed', () => { expect(checkbox.prop('defaultChecked')).toBe(false); }); test('todo value should match added name', () => { expect(todoName.text()).toBe(props.todo.name); }); test('check if onClick gets called when checkbox is clicked, todo completed', () => { checkbox.simulate('click'); expect(props.onClick).toHaveBeenCalled(); }) test('check if onRemoveClick gets called when remove button is clicked', () => { removeBtn.simulate('click'); expect(props.onRemoveClick).toHaveBeenCalled(); }) })<file_sep>/README.md Refactored the application to only use functional components, changed the structure around and gave the UI a deep blue look. Also wrote a unit test for the Todo -component. <file_sep>/src/components/Todo.js import React from 'react'; // Use React.memo to prevent unnecessary re-rendering. We will only re-render this component // if the length of the todo items array has changed size, which only happens when the user // either adds or removes todos from the list. const Todo = React.memo((props) => { // Changed the onClick events from having anonymous functions to avoid unnecessary re-rendering of the // component. The todo ID is stored in the JSX element value field instead. return ( <div className="wrapper todos-wrapper" > <h3 className="todoName">{props.todo.name}</h3> <label className="checkbox-wrapper"> <input type="checkbox" id="check" defaultChecked={props.todo.complete} value={props.todo.id} hidden onClick={props.onClick}> </input> <label htmlFor="check" className="checkmark"></label> </label> <button className="btn" value={props.todo.id} onClick={props.onRemoveClick}> Remove </button> </div > ); }, (prevProps, nextProps) => { return prevProps.itemsLength === nextProps.itemsLength; }); export default Todo; <file_sep>/src/components/AddTodo.js import React from 'react'; function AddTodo(props) { return ( <form className="wrapper" style={{ 'gridTemplateColumns': '7fr 2fr' }} onSubmit={props.onSubmit}> <input className="add-todo-input-field" placeholder="Add a new todo" value={props.newTodoName} onChange={props.onInputChange} /> <button className="btn btn-submit" type="submit" value="Submit"> Add </button> </form> ); } export default AddTodo;<file_sep>/src/App.js import React, { useState } from 'react'; import './App.css'; import TodoData from './data/TodoData'; import Todo from './components/Todo'; import TodoHeader from './components/TodoHeader'; import AddTodo from './components/AddTodo'; import { v4 } from 'uuid'; function App() { const [emptyTodoWarning, setEmptyTodoWarning] = useState(false); const [todos, setTodos] = useState(TodoData); const [newTodoName, setNewTodoName] = useState(''); const onTodoSubmit = event => { event.preventDefault(); // Check if the new todo doesnt have text in it and shows a warning message accordingly. if (newTodoName === '') { if (emptyTodoWarning) return; setEmptyTodoWarning(true); setTimeout(() => setEmptyTodoWarning(false), 3000); return; } const newTodos = [...todos]; // Generate an uuid for the new todo. Using array length as the ID would cause duplicate // IDs if the user removes a todo from the middle of the list and then adds new ones. newTodos.push({ id: v4(), name: newTodoName, complete: false }); setTodos(newTodos); setNewTodoName(''); } const onTodoCompletedClick = event => { const id = event.target.value; const todoItems = [...todos]; const item = todoItems.find(item => item.id === id); item.complete = !item.complete; setTodos(todoItems); } const onAddTodoInputChange = event => setNewTodoName(event.target.value); // Remove a todo by finding its array index const onTodoRemoveClick = event => { const id = event.target.value; const todoItems = [...todos]; const itemToRemove = todoItems.findIndex(item => item.id === id); todoItems.splice(itemToRemove, 1); setTodos(todoItems); } // Map through the todos array to show the todos for the user const getTodoItems = () => { return todos.map(todo => { return <Todo key={todo.id} todo={todo} itemsLength={todos.length} onClick={onTodoCompletedClick} onRemoveClick={onTodoRemoveClick} /> }); }; return ( <div> <h1>Todos</h1> <div className="main-wrapper"> {todos.length > 0 ? <div> < TodoHeader /> {getTodoItems()}</div> : <h3>No todos available.</h3>} </div> <div className="main-wrapper add-todos-wrapper"> {emptyTodoWarning && <h3 className="warning-text">Please enter some text for the todo.</h3>} <AddTodo onSubmit={onTodoSubmit} newTodoName={newTodoName} onInputChange={onAddTodoInputChange} /> </div> </div> ); } export default App;
c57e89b6b080d0775c737139382b0eb8e49dbbb9
[ "JavaScript", "Markdown" ]
6
JavaScript
Santzo/react-interview
5f8e0444759f56462fc59f3d423fea3ff2359809
628e52a156a1039277242d220e52d29c60b7b69a
refs/heads/master
<repo_name>thatguyish/warbler<file_sep>/test_message_model.py from unittest import TestCase from os import environ from models import db, Message, User, Follows environ['DATABASE_URL'] = "postgres:///warbler_test" from app import app class TestMessageModel(TestCase): """Test the message model""" def setup(self): self.user = User.query.get_all()[0] self.message = Message(text="This is some text",user_id=self.user.id) def Test_Create_message(self): """Tests creation of a message model""" self.assertTrue(self.message) def Test_Message_correct(self): """Test if message gets saved correctly""" self.message = "This is changed text" self.assertEqual(self.message.text,"This is changed text") def Test_Time(self): """Test if Time is present""" self.assertTrue(self.message.timestamp) <file_sep>/test_user_model.py """User model tests.""" # run these tests like: # # python -m unittest test_user_model.py import os from unittest import TestCase from models import db, User, Message, Follows # BEFORE we import our app, let's set an environmental variable # to use a different database for tests (we need to do this # before we import our app, since that will have already # connected to the database os.environ['DATABASE_URL'] = "postgres:///warbler_test" # Now we can import app from app import app # Create our tables (we do this here, so we only create the tables # once for all tests --- in each test, we'll delete the data # and create fresh new clean test data db.create_all() class UserModelTestCase(TestCase): """Test views for messages.""" def setUp(self): """Create test client, add sample data.""" Message.query.delete() User.query.delete() Follows.query.delete() self.client = app.test_client() def test_user_model(self): """Does basic model work?""" u = User( email="<EMAIL>", username="testuser", password="<PASSWORD>" ) db.session.add(u) # User should have no messages & no followers self.assertEqual(len(u.messages), 0) self.assertEqual(len(u.followers), 0) def test_user_signup(self): """Test if user create is working""" user = User( email="<EMAIL>", username="testuser", password="<PASSWORD>" ) user = user.signup(username=user.username,email=user.email,password=user.password,image_url=user.image_url) db.session.commit() #test user id matches one in database after adding self.assertEqual(user.id,User.query.get(user.id).id) #match password with user password after adding entry self.assertEqual(user.password,User.query.get(user.id).password) def test_user_authenticate(self): """Test if user authenticate is working""" user = User( email="<EMAIL>", username="testuser", password="<PASSWORD>" ) User.signup(username=user.username,email=user.email,password=user.password,image_url=user.image_url) db.session.commit() #authenticate on success self.assertTrue(User.authenticate(username=user.username,password=user.password)) #error on failure self.assertFalse(User.authenticate(username=user.username,password="<PASSWORD>")) def test_user_is_following(self): """Test if is following is working""" user1 = User( email="<EMAIL>", username="testuser", password="<PASSWORD>" ) user2 = User( email = "<EMAIL>", username = "testuser2", password = "<PASSWORD>" ) user1 = user1.signup(username=user1.username,password=<PASSWORD>,email=user1.email,image_url = user1.image_url) user2 = user2.signup(username=user2.username,password=<PASSWORD>,email=user2.email,image_url = user2.image_url) db.session.commit() follow_forward = Follows(user_being_followed_id=user1.id,user_following_id=user2.id) follow_backwords = Follows(user_being_followed_id=user2.id,user_following_id=user1.id) db.session.add(follow_backwords) db.session.add(follow_forward) db.session.commit() #check if user1 is following another self.assertTrue(user1.is_following(user2)) def test_user_is_followed_by(self): """Test if is followed by is working""" user1 = User( email="<EMAIL>", username="testuser", password="<PASSWORD>" ) user2 = User( email = "<EMAIL>", username = "testuser2", password = "<PASSWORD>" ) user1 = user1.signup(username=user1.username,password=<PASSWORD>,email=user1.email,image_url = user1.image_url) user2 = user2.signup(username=user2.username,password=<PASSWORD>,email=user2.email,image_url = user2.image_url) db.session.commit() follow_forward = Follows(user_being_followed_id=user1.id,user_following_id=user2.id) follow_backwords = Follows(user_being_followed_id=user2.id,user_following_id=user1.id) db.session.add(follow_backwords) db.session.add(follow_forward) db.session.commit() #check if user1 is being followed by another self.assertTrue(user1.is_following(user2)) def test_user_repr(self): """Test if repr function is working""" user1 = User( email="<EMAIL>", username="testuser", password="<PASSWORD>" ) #test if reppr function shows accurate information self.assertEqual(f"{user1}",f"<User #{user1.id}: {user1.username}, {user1.email}>")
fa91267fb24eee24c317cf7e4e4f12474033f869
[ "Python" ]
2
Python
thatguyish/warbler
5fa49b8e57ca428d002194a1f4fa4435965f2928
76ab2e736596611e329b4e0fc446f707678601b5
refs/heads/master
<repo_name>isauadh/Data-Processing-Reddit<file_sep>/distributionGraph.py import praw import json import os import datetime import random import string import pandas as pd from dateutil.parser import parse reddit = praw.Reddit(client_id='', \ client_secret='', \ user_agent='', \ username='isauadh', \ password='') # create a file with json objects def writeData(fp, data): outputfp = open(fp, "w") outputfp.write(json.dumps(data, sort_keys = True, indent = 4)) # function used to hide the redditor name with changes in first two, middle, and last two letters of the redditor name def hideUserid(name): s = list(name) length = len(name) s[int(length/2)] = random.choice(string.ascii_lowercase) s[0] = random.choice(string.ascii_lowercase) s[1] = random.choice(string.ascii_lowercase) s[(length-1)] = random.choice(string.ascii_lowercase) s[(length-2)] = random.choice(string.ascii_lowercase) return ("".join(s)) # create a directory with the necessary files in it def makeDir(name, data): os.mkdir(name) for key in data.keys(): writeData("{}.txt".format(os.path.join(name, hideUserid(key))), data[key]) # create a bar diagram to analyze frequency of the each bin(post count) def createDistribution(data): graphingData = {} for key in data.keys(): graphingData[key] = len(data[key][0]['post']) df = pd.DataFrame.from_dict(graphingData, orient = 'index', columns = ['count']) df['binned'] = pd.cut(df['count'], bins = 150) print(df['binned'].value_counts().plot.bar(figsize =(20,10))) # create a bar diagram to analyze time distribution of a redditor in a given subreddit def timeDistribution(authorName, data): graphingData = {} graphingData[authorName] = [] for i in range(0,len(data[authorName][0]['postTime'])): time = parse(str(datetime.datetime.fromtimestamp(data[authorName][0]['postTime'][i]))) graphingData[authorName].append(time.hour) df1 = pd.DataFrame.from_dict(graphingData) bins = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24] df1['binned'] = pd.cut(df1[authorName], bins = bins) print(df1['binned'].value_counts().plot.bar(figsize=(20,10))) # gather posts, comments, and their posted time off the top 1k submissions of all time of a subreddit # gathered information are sorted by redditor in the given subreddit def Subreddit(name, limitTo): redditors = {} subreddit = reddit.subreddit(name) submissions = subreddit.top(limit = limitTo) for submission in submissions: flag_sub = 0 for key in redditors.keys(): if submission.author == key: redditors[key][0]['post'].append(submission.selftext) redditors[key][0]['postTime'].append(submission.created) flag_sub = 1 if flag_sub == 0: redditors[str(submission.author)] = [{}] redditors[str(submission.author)][0]['post'] = [] redditors[str(submission.author)][0]['postTime'] = [] redditors[str(submission.author)][0]['post'].append(submission.selftext) redditors[str(submission.author)][0]['postTime'].append(submission.created) submission.comments.replace_more(limit= None) for comment in submission.comments.list(): flag = 0 for key in redditors.keys(): if comment.author == key: redditors[key][0]['post'].append(comment.body) redditors[key][0]['postTime'].append(comment.created_utc) flag = 1 break if flag==0: redditors[str(comment.author)] = [{}] redditors[str(comment.author)][0]['post'] = [] redditors[str(comment.author)][0]['postTime'] = [] redditors[str(comment.author)][0]['post'].append(comment.body) redditors[str(comment.author)][0]['postTime'].append(comment.created_utc) return redditors if __name__ == '__main__': # Please provide the subreddit name before running the program allPost = Subreddit('Subreddit_Name', None) # Please provide the directory name to store the gathered information makeDir('Directory_Name', allPost) createDistribution(allPost) # Please provide the redditor name to view the time distribution of his/her posts in the given subreddit timeDistribution('Redditor_Name', allPost) <file_sep>/Crawler.py import praw import json reddit = praw.Reddit(client_id='', \ client_secret='', \ user_agent='', \ username='isauadh', \ password='') def Subreddit(name, limitTO): print("Subreddit {}".format(name)) subreddit = reddit.subreddit(name) submissions = subreddit.top(limit=limitTO) submissionCount = 0 commentCount = 0 fcount = 0 redditData = {} redditData[str(subreddit)] = [{}] for submission in submissions: submissionCount += 1 submission.comments.replace_more(limit= None) redditData[str(subreddit)][0][str(submission.author)] = [{}] redditData[str(subreddit)][0][str(submission.author)][0]['Title'] = submission.title redditData[str(subreddit)][0][str(submission.author)][0]['Text'] = submission.selftext redditData[str(subreddit)][0][str(submission.author)][0]['Comment'] = [{}] for comment in submission.comments.list(): commentCount += 1 if(not userExistInComments(redditData[str(subreddit)][0][str(submission.author)][0]['Comment'][0], str(comment.author))): redditData[str(subreddit)][0][str(submission.author)][0]['Comment'][0][str(comment.author)]= [{}] redditData[str(subreddit)][0][str(submission.author)][0]['Comment'][0][str(comment.author)][0][str(comment)] = [{}] redditData[str(subreddit)][0][str(submission.author)][0]['Comment'][0][str(comment.author)][0][str(comment)][0]["Comment_Text"] = comment.body updateTerminal(submissionCount, commentCount) # each file holds maximum of 200 submissions if(submissionCount % 200 == 0): writeData("{}-{}.txt".format(name,fcount),redditData) fcount += 1 redditData = {} subreddit = reddit.subreddit(name) redditData[str(subreddit)] = [{}] def userExistInComments(commentList, user): if user in commentList: return True return False def updateTerminal( subCount, comCount): print("Downloaded: {} Submissions".format(subCount)) print("Downloaded: {} Comments".format(comCount)) def writeData(fp, data): outputfp = open(fp, "w") outputfp.write(json.dumps(data, sort_keys = True, indent = 4)) if __name__ == '__main__': # Please provide the subreddit Name before running the program Subreddit('Subreddit_Name', None) <file_sep>/README.md # Data -Processing-RedditAPI The project uses reddit API to collect data from subreddit 'Opiates' for the purpose to study addiction and recovery. ## Crawler.py The crawler program collects maximun of top 1k of all time submissions and comments off the given subreddit. ## Redditor\Submission&Comment.py First, this program collects redditors on a given subreddit. Second, the program iterates through the list of redditors and gather their all time top submission and comments (maximum of 1k) on any subreddit throughout reddit.com. ## Subreddit_Sort_Author.py This program goes through submissions and comments on a subreddit and sort them by redditor(Author). ## distributionGraph.py This program will generate a distribution graph of the number of post in a given subreddit. Also, can generate time distribution of a redditor post in a given subreddit. The program will create a directory with files containing submissions and comments of a redditor in a given subreddit. Filename will be the hidden version of the original redditor name. ## Opiates.Zip The folder has been zipped because it consists files more than the GitHub Limit. This folder consists of three different files. The first CSV folder consists of a csv file for each redditor under the second Opiates folder. The run.py is a python program that parses through the opiates folder to create a csv folder. The csv folder contains filename as numbers to hide redditor name. The index can be found in index_dict under csv folder. ## Authors <NAME> ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details <file_sep>/Subreddit_Sort_Author.py import praw import json reddit = praw.Reddit(client_id='', \ client_secret='', \ user_agent='', \ username='isauadh', \ password='') def writeData(fp, data): outputfp = open(fp, "w") outputfp.write(json.dumps(data, sort_keys = True, indent = 4)) def Subreddit(name, limitTo): subreddit = reddit.subreddit(name) submissions = subreddit.top(limit = limitTo) posts = {} for submission in submissions: flag_sub = 0 # check if the submission author already exist as a key in post dict for key in posts.keys(): if submission.author == key: posts[key].append(submission.selftext) flag_sub = 1 # create a list for new submission author and append submission text to it if flag_sub == 0: posts[str(submission.author)] = [] posts[str(submission.author)].append(submission.selftext) submission.comments.replace_more(limit= None) for comment in submission.comments.list(): flag = 0 # check if the comment author already exist as a key in post dict for key in posts.keys(): if comment.author == key: posts[key].append(comment.body) flag = 1 break # create a list for new comment author and append comment body to it if flag==0: posts[str(comment.author)] = [] posts[str(comment.author)].append(comment.body) writeData("{}.txt".format('Subreddit_Sort_Author'),posts) if __name__ == '__main__': # Please provide the subreddit before running the program. You can change the 'None' limit value as your want. Subreddit('Subreddit_Name', None) <file_sep>/Redditor\Submission&Comment.py import praw import json reddit = praw.Reddit(client_id='', \ client_secret='', \ user_agent='', \ username='isauadh', \ password='') def writeData(fp, data): outputfp = open(fp, "w") outputfp.write(json.dumps(data, sort_keys = True, indent = 4)) # This function will gather maximun of 1k all time submissions and comments of a redditor on any subreddit def redditorPost(userID, limitTo): redditor = {} redditor[userID] = [{}] redditor[userID][0]['Post'] = [] redditor[userID][0]['Comment'] = [] try: submissions = reddit.redditor(userID).submissions.top(limit = limitTo) for submission in submissions: redditor[userID][0]['Post'].append(submission.selftext) comments = reddit.redditor(userID).comments.top(limit = limitTo) for comment in comments: redditor[userID][0]['Comment'].append(comment.body) except: redditor[userID][0]['Post'].append("Page Doesn't Exist Anymore") redditor[userID][0]['Comment'].append("Page Doesn't Exist Anymore") finally: writeData("{}.txt".format(userID),redditor) # limitToSubreddit will limit the number of submissions to go through in a subreddit # limitToRedditor will limit the number of submissions and comments to go through in a redditor def Subreddit(name, limitToSubreddit, limitToRedditor): subreddit = reddit.subreddit(name) submissions = subreddit.top(limit = limitToSubreddit) redditors = {} redditors['redditors'] = [] for submission in submissions: submission.comments.replace_more(limit= limitToSubreddit) redditors['redditors'].append(str(submission.author)) for comment in submission.comments.list(): redditors['redditors'].append(str(comment.author)) # set will get rid of repeated redditors redditors['redditors'] = list(set(redditors['redditors'])) writeData("{}.txt".format('RedditorList'), redditors) for user in redditors['redditors']: redditorPost(user, limitToRedditor) if __name__ == '__main__': # Please provide the subreddit before running the program. You can also make changes to the 'None' limit parameters as your want. Subreddit('Subreddit_Name', None, None)
b143d6502a6c00967663a830a9007684f079044f
[ "Markdown", "Python" ]
5
Python
isauadh/Data-Processing-Reddit
7a68a4b5dfcae0314d4275ee9d76a95058423dc9
09d11d28ab6cf32e94c9b4df3a03eae41c7f28ac
refs/heads/master
<file_sep># websocketjsonrpc JSON-RPC over websocket ## Example usage ```go package main import ( "log" "net/http" "net/rpc" "net/rpc/jsonrpc" "github.com/gorilla/websocket" "github.com/s111/websocketjsonrpc" ) var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } type Args struct { A int B int } type Arith int func (t *Arith) Multiply(args *Args, reply *int) error { *reply = args.A * args.B return nil } func main() { rpc.Register(new(Arith)) http.HandleFunc("/ws", serveWs) err := http.ListenAndServe(":3001", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } func serveWs(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "Method not allowed", 405) return } ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade:", err) return } jsonrpc.ServeConn(websocketjsonrpc.NewConn(ws)) } ``` <file_sep>// Package websocketjsonrpc takes a *github.com/gorilla/websocket.Conn and wraps it with the io.ReaderWriterCloser interface. package websocketjsonrpc import ( "encoding/json" "github.com/gorilla/websocket" ) type conn struct { ws *websocket.Conn } // NewConn returns a new connection implementing the io.ReadWriteCloser interface func NewConn(ws *websocket.Conn) *conn { return &conn{ws} } func (c *conn) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } var raw json.RawMessage err := c.ws.ReadJSON(&raw) copy(p, raw) return len(raw), err } func (c *conn) Write(p []byte) (int, error) { return len(p), c.ws.WriteMessage(websocket.TextMessage, p) } func (c *conn) Close() error { return c.ws.Close() }
ac9e6bb95493ed2a5762be58b60fdad365617b19
[ "Markdown", "Go" ]
2
Markdown
s111/websocketjsonrpc
c52a809feb121fe5767cf71e2580826603818e85
d631cd8b8e09758296f42e5b1c95cc4e1cc18a04
refs/heads/main
<repo_name>wangdefa7/SQL-Note<file_sep>/dareway/重要sql/收费员+超期.sql select * from (select nvl(czy.czybh, '') czybh, msg.czyxm, msg.qdmc, msg.zfje, msg.zfbs, msg.tkje, msg.tkbs, msg.zje from (select nvl(dtl1.czybh, dtl3.czybh) czybh, case when nvl(dtl1.czyxm, dtl3.czyxm) is null then nvl(dtl1.czybh, dtl3.czybh) else nvl(dtl1.czyxm, dtl3.czyxm) end czyxm, nvl(dtl1.bz, dtl3.bz) qdmc, nvl(dtl1.jyje, 0) zfje, nvl(dtl1.jybs, 0) zfbs, nvl(dtl3.jyje, 0) tkje, nvl(dtl3.jybs, 0) tkbs, (nvl(dtl1.jyje, 0) - nvl(dtl3.jyje, 0)) as zje from (select dtl4.czybh, dtl4.czyxm, bank2.bz, sum(case when instr(bank2.bz, '统筹') > 0 then to_number(dtl4.zjlx) else dtl4.jyje end) jyje, count(dtl4.intradeno) jybs from ipay.order_detl dtl4 left join ipay.bank_info bank2 on bank2.yhid = dtl4.yhid where dtl4.paystate = 'paid' and dtl4.yhid != 'SPCLQY' and (dtl4.cqtfbs != '1' or dtl4.cqtfbs is null) and dtl4.jysj >= '20210309000000' and dtl4.jysj <= '20210309134221' group by dtl4.czybh, dtl4.czyxm, bank2.bz order by dtl4.czybh, dtl4.czyxm, bank2.bz) dtl1 full join (select dtl2.czybh, dtl2.czyxm, bank1.bz, sum(case when instr(bank1.bz, '统筹') > 0 then dtl2.zjlx else dtl2.jyje end) jyje, count(1) jybs from (select dtlrf.jyje, dtlrf.yhid, nvl(to_number(dtlrf.zjlx), 0) zjlx, dtlrf.czybh, dtlrf.czyxm, dtlrf.jysj from ipay.order_detl dtlrf where 1 = 1 and dtlrf.paystate = 'repaid' and (dtlrf.cqtfbs not in ('1', '2') or dtlrf.cqtfbs is null) -- 超期转现金部分 union select cash.jyje, 'XJZF' yhid, 0 zjlx, cash.czybh, cash.czyxm,cash.jysj from ipay.overtocash_refund cash where 1 = 1 and cash.state = 'repaid') dtl2 left join ipay.bank_info bank1 on bank1.yhid = dtl2.yhid where 1=1 and dtl2.jysj >= '20210309000000' and dtl2.jysj <= '20210309134221' group by dtl2.czybh, dtl2.czyxm, bank1.bz union select refund.czybh czybh, refund.czyxm czyxm, '超期' bz, sum(dtl5.jyje) jyje, count(1) jybs from ipay.overtime_refund dtl5 left join ipay.refund_detl refund on dtl5.refundno = refund.refundno where dtl5.state in ('repaid', 'refund', 'refunding', 'repaying', 'repayings') and dtl5.fqjysj >= '20210309000000' and dtl5.fqjysj <= '20210309134221' group by refund.czybh, refund.czyxm) dtl3 on dtl1.czybh = dtl3.czybh and dtl1.czyxm = dtl3.czyxm and dtl1.bz = dtl3.bz) msg left join (select substr(csmc, instr(csmc, '|', 1) + 1) czybh, csz czyid from URP.PARAM_DICT where 1 = 1 and cslx = 'skyVSdlyh' and zt = '0') czy on czy.czyid = msg.czybh) order by czybh, czyxm, qdmc <file_sep>/dareway/重要sql/清空ipay.sql --Çå¿Õipay truncate table ipay.ORG_BANK; truncate table ipay.ORG_INFO; truncate table ipay.BANK_INFO; truncate table ipay.order_detl; truncate table ipay.order_genl; truncate table ipay.overtime_refund; truncate table ipay.refund_detl; truncate table ipay.sdsz_trade_info; truncate table ipay.abnormal_order_detl; truncate table ipay.MONGODB_PARA; truncate table ipay.ABNORMAL_ORDER_DETL; truncate table ipay.overtocash_refund; --truncate table ipay.order_gen_det_list; --truncate table ipay.ucompos_management_info; truncate table ipay.order_settlepara; <file_sep>/dareway/2021-7-21/设备.sql prompt PL/SQL Developer import file prompt Created on 2021年7月21日 by Wdf set feedback off set define off prompt Creating E_EQUIPMENT_INFO... create table E_EQUIPMENT_INFO ( sbid VARCHAR2(32) default sys_guid() not null, sbbm VARCHAR2(30) not null, sbmc VARCHAR2(30), sbxlh VARCHAR2(30) not null, sbcsid VARCHAR2(32) not null, sbzt VARCHAR2(2) default 1 not null, jgbm VARCHAR2(15) not null, jlcjsj TIMESTAMP(6) default sysdate not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6) default sysdate, zhxgr VARCHAR2(20), bz VARCHAR2(100), sbcsbm VARCHAR2(30) not null ) tablespace URP_RUN pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); comment on column E_EQUIPMENT_INFO.sbid is '设备主键ID'; comment on column E_EQUIPMENT_INFO.sbbm is '设备编码'; comment on column E_EQUIPMENT_INFO.sbmc is '设备名称'; comment on column E_EQUIPMENT_INFO.sbxlh is '设备序列号'; comment on column E_EQUIPMENT_INFO.sbcsid is '所属设备厂商主键ID'; comment on column E_EQUIPMENT_INFO.sbzt is '设备状态'; comment on column E_EQUIPMENT_INFO.jgbm is '机构有编码'; comment on column E_EQUIPMENT_INFO.jlcjsj is '记录创建时间'; comment on column E_EQUIPMENT_INFO.cjr is '创建人'; comment on column E_EQUIPMENT_INFO.zhxgsj is '最后修改时间'; comment on column E_EQUIPMENT_INFO.zhxgr is '最后修改人'; comment on column E_EQUIPMENT_INFO.bz is '备注'; comment on column E_EQUIPMENT_INFO.sbcsbm is '设备厂商编码'; alter table E_EQUIPMENT_INFO add primary key (SBID) using index tablespace URP_RUN pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); prompt Loading E_EQUIPMENT_INFO... insert into E_EQUIPMENT_INFO (sbid, sbbm, sbmc, sbxlh, sbcsid, sbzt, jgbm, jlcjsj, cjr, zhxgsj, zhxgr, bz, sbcsbm) values ('08978939bda4488abcd9975b35dbaa56', 'eself', '自助机-dareway', 'eself', 'f971c7babf374641bc2f6e36996a1813', '1', 'csyy', to_timestamp('25-06-2021 16:21:16.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urp', to_timestamp('02-07-2021 19:09:22.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'wdf', '测试', 'SelfService'); insert into E_EQUIPMENT_INFO (sbid, sbbm, sbmc, sbxlh, sbcsid, sbzt, jgbm, jlcjsj, cjr, zhxgsj, zhxgr, bz, sbcsbm) values ('73a808fafba24253878edf974bc8fbd2', 'ehis', '院内His', '1', '6fd0652f57f14a80a93a84f709a11856', '0', 'csyy', to_timestamp('20-08-2020 14:36:28.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'wdf', to_timestamp('03-06-2021 18:15:19.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', null, 'Ehis'); insert into E_EQUIPMENT_INFO (sbid, sbbm, sbmc, sbxlh, sbcsid, sbzt, jgbm, jlcjsj, cjr, zhxgsj, zhxgr, bz, sbcsbm) values ('b8036942f41e44349142d1c06493ed01', 'eipay', '综合支付平台', '1111', '4fcc70d4706b4120abe0ae308595ae54', '1', 'csyy', to_timestamp('17-07-2020 15:15:18.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'wdf', to_timestamp('03-06-2021 18:15:40.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', null, 'ipay'); insert into E_EQUIPMENT_INFO (sbid, sbbm, sbmc, sbxlh, sbcsid, sbzt, jgbm, jlcjsj, cjr, zhxgsj, zhxgr, bz, sbcsbm) values ('b525a0a29fc4440c8ea7d803824271fb', 'eyunda', '韵达设备', 'eyunda', 'yundatbabf374641bc2f6e36996a1813', '1', 'csyy', to_timestamp('19-07-2021 16:50:04.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', to_timestamp('19-07-2021 16:50:04.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), null, null, 'yunda'); insert into E_EQUIPMENT_INFO (sbid, sbbm, sbmc, sbxlh, sbcsid, sbzt, jgbm, jlcjsj, cjr, zhxgsj, zhxgr, bz, sbcsbm) values ('99419a5ae26b4f9e824b0d16ffb4ffea', 'ealipayLife', '支付宝生活号-1', 'ealipayLife', 'alipayLifebabf3bc2f6e36996a1813', '1', 'csyy', to_timestamp('19-07-2021 16:50:43.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', to_timestamp('19-07-2021 16:50:43.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), null, null, 'alipayLife'); insert into E_EQUIPMENT_INFO (sbid, sbbm, sbmc, sbxlh, sbcsid, sbzt, jgbm, jlcjsj, cjr, zhxgsj, zhxgr, bz, sbcsbm) values ('376330df908b4b6c9208ca03e2f031ac', 'ewechatPublic', '微信公众号-1', 'ewechatPublic', 'wechatbabf374641bc2f6e36996a1813', '1', 'csyy', to_timestamp('19-07-2021 16:51:13.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', to_timestamp('19-07-2021 16:51:13.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), null, null, 'wechatPublic'); commit; prompt 6 records loaded set feedback on set define on prompt Done. <file_sep>/本地-Test-公司电脑.sql create table test( id number(5) primary key, name varchar(20) ); select * from wdf.test for update; insert into wdf.test values(1,'a'); <file_sep>/dareway/2021-4/union问题sql-2.sql select dtlrf.jyje, dtlrf.yhid, nvl(to_number(dtlrf.zjlx), 0) zjlx, dtlrf.czybh, dtlrf.czyxm, dtlrf.jysj from ipay.order_detl dtlrf where 1 = 1 and dtlrf.paystate = 'repaid' and (dtlrf.cqtfbs not in ('1', '2') or dtlrf.cqtfbs is null) and dtlrf.czybh = '493' and dtlrf.jyje = 500 and dtlrf.jysj >= '20210406000000' and dtlrf.jysj <= '20210406235918' order by dtlrf.jysj <file_sep>/dareway/重要sql/超期word统计.sql ---超期退费统计报表 select sum(b.zjjyje) zje, sum(b.zjjysxf) sxf, sum(b.cgbs) bs, count(b.pcs) pcs from (select a.khpch pcs, a.zjjyje, a.zjjysxf, a.cgbs from URP.GF_BANKTRANS_ACCOUNTS a where 1 = 1 and a.jyclzt in ('6', 'B') and a.jysj = '20210105' group by a.khpch, a.zjjyje, a.zjjysxf, a.cgbs) b; --- <file_sep>/dareway/重要sql/删除urp的已删除数据.sql select * from user_tab_comments ; delete from urp.alipay_transflow where sfsc = '1' ; delete from urp.cgbsmartpay_transflow where sfsc = '1'; delete from urp.medicare_transflow where sfsc = '1'; delete from urp.his_transflow where sfsc = '1'; delete from urp.wechat_transflow where sfsc = '1'; delete from urp.unionpay_transflow where sfsc = '1'; delete from urp.cashpay_transflow where sfsc = '1'; delete from urp.RECONRESULT_DETAIL where sfsc = '1'; delete from urp.RECONHIS_STATISTICS where sfsc = '1'; delete from urp.RECONFILE_INFO where sfsc = '1'; delete from urp.REALTIME_ALARM where sfsc = '1'; delete from urp.M_HIS_TRANSFLOW where sfsc = '1'; delete from urp.M_EQUIPMENT_TRANSFLOW where sfsc = '1'; delete from urp.GF_BANKTRANS_ACCOUNTS where sfsc = '1'; delete from urp.E_RECON_HISTORY where sfsc = '1'; delete from urp.e_Equipment_Reconresult where sfsc = '1'; delete from urp.E_RECONFILE_INFO where sfsc = '1'; delete from urp.E_HIS_TRANSFLOW where sfsc = '1'; delete from urp.E_FACTORY_RECONRESULT where sfsc = '1'; delete from urp.E_EQUIPMENT_TRANSFLOW where sfsc = '1'; delete from urp.E_EQUIPMENT_RECONRESULT where sfsc = '1'; delete from urp.CHANNEL_RECONRESULT where sfsc = '1'; delete from urp.CGBSMARTPAY_TRANSFLOW where sfsc = '1'; delete from urp.ARRIVALACCOUNT_STATISTICS where sfsc = '1'; delete from urp.ACCOUNTABLE_STATISTICS where sfsc = '1'; delete from urp.ABCPAY_TRANSFLOW where sfsc = '1'; <file_sep>/dareway/2021-2/存量数据迁移.sql select * from ipay.order_detl a where 1=1 and a.brsfzhm = 'test'; select * from ipay.order_detl a where 1=1 and a.yhid != 'SPCLQY' and czyxm like '自助机%' select count(1) from ipay.order_genl gen where 1=1 and gen.description = '存量数据迁移'; select * from ipay.v_trade_info_yndz d where rownum<=3 delete from ipay.order_detl a where 1=1 and a.brsfzhm = 'test'; delete from ipay.order_genl a where 1=1 and a.description = '存量数据迁移'; select a.accountid ,a.jyje from ipay.order_detl a where 1=1 and a.yhid = 'SPCLQY' and a.accountid = '218447' order by jyje desc <file_sep>/dareway/2021-4/union问题sql-1.sql select * from ipay.order_detl where jysj = '20210406112242' <file_sep>/本地Oracle.sql -- 本地Oracle 脚本 -- 查询该用户的下面的所有表和视图 select * from user_tab_comments -- 查询所有表的字段值 --select * from user_col_comments -- 用户 -- 创建用户(账号:wdf 密码:<PASSWORD>)赋予表空间:wdf_tablespace create user urp identified by urp default tablespace wdf_tablespace -- 修改密码(密码区分大小写) alter user IPAY identified by oracleipay -- 用户被锁定,解锁 ALTER USER IPAY ACCOUNT UNLOCK; -- 给用户 wdf 赋予CREATE SESSION权限 连接数据库权限 grant create session to wdf; -- 给用户 wdf 赋予CREATE TABLE权限 建立数据表权限 grant CREATE TABLE to wdf; -- 给用户 wdf 赋予 UNLIMITED TABLESPACE 权限 --表空间无限制权限(空间配额) grant UNLIMITED TABLESPACE to wdf; --系统权限传递: --增加WITH ADMIN OPTION选项,则得到的权限可以传递。//可以传递所获权限。 grant connect to IPAY with admin option; --系统权限回收:系统权限只能由DBA用户回收 Revoke connect, resource from user50; --查询用户拥有哪里权限(用户名字需要大写): select * from dba_role_privs where grantee = 'IPAY'; select * from dba_sys_privs; select * from role_sys_privs; --查自己拥有哪些系统权限 select * from session_privs; -- 查看角色(只能查看登陆用户拥有的角色)所包含的权限 select * from role_sys_privs; --删除用户 //加上cascade则将用户连同其创建的东西全部删除 drop user 用户名 cascade; -- 系统权限传递: -- 增加WITH ADMIN OPTION选项,则得到的权限可以传递。//可以传递所获权限。 grant connect, resorce to user50 with admin option; -- 系统权限回收:系统权限只能由DBA用户回收 Revoke connect, resource from user50; -- 对账项目赋予用户的角色:创建session角色,创建资源角色,Create table 等等,数据库管理员角色 grant connect,resource,dba to ipay; grant connect,resource,dba to urp; -- (start)plsql 提示 动态执行表不可访问,或在v$session... 中的错误,执行下列sql或者打开:工具->首选项->选项-> 去掉“自动统计”前面的勾选 -- 根据提示,用sys身份给 XX 用户授权 grant select on V_session to XX; grant select on V_$sesstat to XX; grant select on V_$statname to XX;   -- 给所有用户授权 grant select on V_$session to public; grant select on V_$sesstat to public; grant select on V_$statname to public; -- 表空间 -- 查询表空间 select file_name from dba_data_files select name from v$datafile -- 创建表空间(表空间的名字是自己起的,XX.dbf) size 后面配置的是表空间的大小 create tablespace wdf_tablespace datafile 'D:\SOFTWARE\SQL\ORACLE\MULU\ORADATA\ORCL\wdf_tablespace.DBF' size 5G --create tablespace TS_IPAY datafile 'D:\SOFTWARE\SQL\ORACLE\MULU\ORADATA\ORCL\TS_IPAY.DBF' size 1G -- 修改表空间名字 alter tablespace wdf_tablespace rename to urp_run --设置表空间默认用户 create user urp identified by urp default tablespace urp_run create user ipay identified by oracleipay default tablespace TS_IPAY -- 查看表空间默认用户(需要登录用户) select * from user_users; --Oracle中一个表空间可能是多个用户的默认表空间,下面语句统计了用户及其默认表空间情况,如果用户多个,用户之间通过逗号分隔。 select t.default_tablespace, to_char(wmsys.wm_concat(username)) all_users from dba_users t group by t.default_tablespace; ----1.查看所有用户: select * from dba_users; select * from all_users; select * from user_users; <file_sep>/qy/qy.sql /* Navicat Premium Data Transfer Source Server : 阿里云-WDF Source Server Type : MySQL Source Server Version : 50734 Source Host : 172.16.58.3:3306 Source Schema : qy Target Server Type : MySQL Target Server Version : 50734 File Encoding : 65001 Date: 13/07/2021 14:05:08 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for sys_role -- ---------------------------- DROP TABLE IF EXISTS `sys_role`; CREATE TABLE `sys_role` ( `id` int(11) NOT NULL, `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of sys_role -- ---------------------------- INSERT INTO `sys_role` VALUES (1, 'ROLE_ADMIN'); INSERT INTO `sys_role` VALUES (2, 'ROLE_USER'); -- ---------------------------- -- Table structure for sys_user_role -- ---------------------------- DROP TABLE IF EXISTS `sys_user_role`; CREATE TABLE `sys_user_role` ( `user_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, PRIMARY KEY (`user_id`, `role_id`) USING BTREE, INDEX `fk_role_id`(`role_id`) USING BTREE, CONSTRAINT `fk_role_id` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of sys_user_role -- ---------------------------- INSERT INTO `sys_user_role` VALUES (1, 1); INSERT INTO `sys_user_role` VALUES (2, 2); -- ---------------------------- -- Table structure for users -- ---------------------------- DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL, `password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL, `sex` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL, `perms` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of users -- ---------------------------- INSERT INTO `users` VALUES (1, 'admin', '123', '', ''); INSERT INTO `users` VALUES (2, 'jitwxs', '123', '', ''); INSERT INTO `users` VALUES (3, 'test1', '123', NULL, NULL); INSERT INTO `users` VALUES (4, 'wdf', 'wdf', NULL, NULL); INSERT INTO `users` VALUES (5, '17853318013', '17853318013', NULL, NULL); SET FOREIGN_KEY_CHECKS = 1; <file_sep>/dareway/2021-1/ipay-userObject.sql ------------------------------------------- -- Export file for user IPAY -- -- Created by Wdf on 2021/1/28, 15:05:08 -- ------------------------------------------- spool ipay-userObject.log prompt prompt Creating table ABNORMAL_ORDER_DETL prompt ================================== prompt create table IPAY.ABNORMAL_ORDER_DETL ( intradeno VARCHAR2(30) not null, glintradeno VARCHAR2(30), clsj VARCHAR2(20), clwcsj VARCHAR2(20), type VARCHAR2(30), yclx VARCHAR2(30), czybh VARCHAR2(32), czyxm VARCHAR2(32), cljg VARCHAR2(10), clms VARCHAR2(500), bz VARCHAR2(255), abnormalid VARCHAR2(50) ) ; comment on column IPAY.ABNORMAL_ORDER_DETL.intradeno is '交易订单号'; comment on column IPAY.ABNORMAL_ORDER_DETL.glintradeno is '关联交易订单号'; comment on column IPAY.ABNORMAL_ORDER_DETL.clsj is '处理时间'; comment on column IPAY.ABNORMAL_ORDER_DETL.clwcsj is '处理完成时间'; comment on column IPAY.ABNORMAL_ORDER_DETL.type is '处理类型'; comment on column IPAY.ABNORMAL_ORDER_DETL.yclx is '异常类型'; comment on column IPAY.ABNORMAL_ORDER_DETL.czybh is '操作员编号'; comment on column IPAY.ABNORMAL_ORDER_DETL.czyxm is '操作员姓名'; comment on column IPAY.ABNORMAL_ORDER_DETL.cljg is '处理结果(0:成功,1:失败)'; comment on column IPAY.ABNORMAL_ORDER_DETL.clms is '处理描述'; comment on column IPAY.ABNORMAL_ORDER_DETL.bz is '备注'; comment on column IPAY.ABNORMAL_ORDER_DETL.abnormalid is '主键'; prompt prompt Creating table BANK_INFO prompt ======================== prompt create table IPAY.BANK_INFO ( yhid VARCHAR2(20) not null, yhmc VARCHAR2(40), qybz VARCHAR2(1), yhiconpath VARCHAR2(100), yhjc VARCHAR2(20), bz VARCHAR2(50) ) ; comment on table IPAY.BANK_INFO is '银行基本信息'; comment on column IPAY.BANK_INFO.yhid is '银行id'; comment on column IPAY.BANK_INFO.yhmc is '银行名称'; comment on column IPAY.BANK_INFO.qybz is '启用标志'; comment on column IPAY.BANK_INFO.yhiconpath is '银行图标路径'; comment on column IPAY.BANK_INFO.yhjc is '银行简称'; comment on column IPAY.BANK_INFO.bz is '备注(目前记录总渠道)'; alter table IPAY.BANK_INFO add constraint PK_BANK_INFO primary key (YHID); prompt prompt Creating table MONGODB_PARA prompt =========================== prompt create table IPAY.MONGODB_PARA ( paraid VARCHAR2(100) not null, paraname VARCHAR2(100), value VARCHAR2(200) ) ; comment on table IPAY.MONGODB_PARA is 'mongoDB配置参数'; comment on column IPAY.MONGODB_PARA.paraid is '参数编号'; comment on column IPAY.MONGODB_PARA.paraname is '参数名称'; comment on column IPAY.MONGODB_PARA.value is '参数值'; alter table IPAY.MONGODB_PARA add constraint MONGODB_PARA_PKEY primary key (PARAID); prompt prompt Creating table ORDER_DETL prompt ========================= prompt create table IPAY.ORDER_DETL ( tradeno VARCHAR2(30) not null, intradeno VARCHAR2(30) not null, fqjysj VARCHAR2(20), jysj VARCHAR2(20), jyje NUMBER(16,2), yhid VARCHAR2(20), paystate VARCHAR2(20), jym_ibank VARCHAR2(30), type VARCHAR2(10), dsftradeno VARCHAR2(30), tkintradeno VARCHAR2(30), zjlx VARCHAR2(10), zjhm VARCHAR2(100), refundtype VARCHAR2(10), appid VARCHAR2(20), terminalno VARCHAR2(20), czybh VARCHAR2(32), czyxm VARCHAR2(50), czybz VARCHAR2(100), brynid VARCHAR2(32), brxm VARCHAR2(50), brsfzhm VARCHAR2(20), brlxfs VARCHAR2(30), cardno VARCHAR2(30), fkjgbh VARCHAR2(30), merchantno VARCHAR2(30), refundtradeno VARCHAR2(30), zflx VARCHAR2(10), ycbs VARCHAR2(32), ip VARCHAR2(32), jyqd VARCHAR2(32), fqjyzt VARCHAR2(2), dyflsh VARCHAR2(30), hisno VARCHAR2(50), jyfs VARCHAR2(20), jytj VARCHAR2(20), czyhmc VARCHAR2(32), jsyhmc VARCHAR2(32), ynkcode VARCHAR2(10), cqtfbs VARCHAR2(2), czlx VARCHAR2(10), jshid VARCHAR2(64), kye NUMBER(16,2), msg VARCHAR2(500), czlb VARCHAR2(10), slzdlx VARCHAR2(32), zddm VARCHAR2(128), yhkh VARCHAR2(32), accountid VARCHAR2(32), isclick VARCHAR2(10), ynjysj VARCHAR2(20) ) ; comment on table IPAY.ORDER_DETL is '订单辅表,支付明细表'; comment on column IPAY.ORDER_DETL.tradeno is '平台订单号'; comment on column IPAY.ORDER_DETL.intradeno is '调用ibank、预交金等的订单号'; comment on column IPAY.ORDER_DETL.fqjysj is '发起支付时间'; comment on column IPAY.ORDER_DETL.jysj is '支付时间'; comment on column IPAY.ORDER_DETL.jyje is '支付金额'; comment on column IPAY.ORDER_DETL.yhid is '支付银行'; comment on column IPAY.ORDER_DETL.paystate is '支付状态'; comment on column IPAY.ORDER_DETL.jym_ibank is 'ibank返回校验码'; comment on column IPAY.ORDER_DETL.type is '类型(支付、退款)'; comment on column IPAY.ORDER_DETL.dsftradeno is '交易返回订单号'; comment on column IPAY.ORDER_DETL.tkintradeno is '退款订单号'; comment on column IPAY.ORDER_DETL.zjlx is '证件类型'; comment on column IPAY.ORDER_DETL.zjhm is '证件号码'; comment on column IPAY.ORDER_DETL.refundtype is '退款类型(in:事中,after:事后)'; comment on column IPAY.ORDER_DETL.appid is '业务ID'; comment on column IPAY.ORDER_DETL.terminalno is '终端编号'; comment on column IPAY.ORDER_DETL.czybh is '操作员编号'; comment on column IPAY.ORDER_DETL.czyxm is '操作员姓名'; comment on column IPAY.ORDER_DETL.czybz is '操作员备注'; comment on column IPAY.ORDER_DETL.brynid is '病人院内ID'; comment on column IPAY.ORDER_DETL.brxm is '病人姓名'; comment on column IPAY.ORDER_DETL.brsfzhm is '病人身份证号码'; comment on column IPAY.ORDER_DETL.brlxfs is '病人联系方式'; comment on column IPAY.ORDER_DETL.cardno is '病人卡号'; comment on column IPAY.ORDER_DETL.fkjgbh is '发卡机构编号'; comment on column IPAY.ORDER_DETL.refundtradeno is '退款平台订单号'; comment on column IPAY.ORDER_DETL.zflx is '支付类型'; comment on column IPAY.ORDER_DETL.ycbs is '异常标识'; comment on column IPAY.ORDER_DETL.ip is '调用方IP'; comment on column IPAY.ORDER_DETL.jyqd is '交易渠道 (1:医保,2:银联卡)'; comment on column IPAY.ORDER_DETL.fqjyzt is '发起交易状态(0:未发起,1:已发起,默认0)'; comment on column IPAY.ORDER_DETL.dyflsh is '调用方流水号'; comment on column IPAY.ORDER_DETL.hisno is 'his调用流水号'; comment on column IPAY.ORDER_DETL.jyfs is '交易方式'; comment on column IPAY.ORDER_DETL.jytj is '交易途径'; comment on column IPAY.ORDER_DETL.czyhmc is '充值用户名称'; comment on column IPAY.ORDER_DETL.jsyhmc is '接收用户名称'; comment on column IPAY.ORDER_DETL.ynkcode is '院内卡状态(0:成功,1:失败,2:未知,3:已撤销)'; comment on column IPAY.ORDER_DETL.cqtfbs is '超期退费标识(0:不是,1:是,默认0)'; comment on column IPAY.ORDER_DETL.czlx is '充值类型(1:门诊,2:住院)'; comment on column IPAY.ORDER_DETL.jshid is '结算号ID'; comment on column IPAY.ORDER_DETL.kye is '卡余额(充值或者退款完成后,默认为null)'; comment on column IPAY.ORDER_DETL.msg is '错误信息'; comment on column IPAY.ORDER_DETL.czlb is '充值类别'; comment on column IPAY.ORDER_DETL.slzdlx is '受理终端类型'; comment on column IPAY.ORDER_DETL.zddm is '终端代码'; comment on column IPAY.ORDER_DETL.yhkh is '银行卡号'; comment on column IPAY.ORDER_DETL.accountid is '账户id'; comment on column IPAY.ORDER_DETL.isclick is '是否点击支付按钮(0:未点击,1:已点击)'; comment on column IPAY.ORDER_DETL.ynjysj is '院内交易时间'; alter table IPAY.ORDER_DETL add constraint PK_ORDER_DETL primary key (TRADENO, INTRADENO); prompt prompt Creating table ORDER_GENL prompt ========================= prompt create table IPAY.ORDER_GENL ( tradeno VARCHAR2(30) not null, outtradeno VARCHAR2(30), cjsj VARCHAR2(20), zje NUMBER(16,2), orgno VARCHAR2(20), terminalno VARCHAR2(20), appid VARCHAR2(20), yzdtje NUMBER(16,2), dzytje NUMBER(16,2), zfwcsj VARCHAR2(20), gatherstate VARCHAR2(20), jym VARCHAR2(6), medicalpay VARCHAR2(6), settletype VARCHAR2(6), sfpj BLOB, openflag VARCHAR2(2), description VARCHAR2(500) ) ; comment on table IPAY.ORDER_GENL is '订单主表'; comment on column IPAY.ORDER_GENL.yzdtje is '已支付金额'; comment on column IPAY.ORDER_GENL.dzytje is '待支付金额'; comment on column IPAY.ORDER_GENL.zfwcsj is '支付完成时间'; comment on column IPAY.ORDER_GENL.gatherstate is '平台订单状态'; comment on column IPAY.ORDER_GENL.medicalpay is '医保支付标志'; comment on column IPAY.ORDER_GENL.settletype is '结算类型'; comment on column IPAY.ORDER_GENL.sfpj is '收费票据'; comment on column IPAY.ORDER_GENL.openflag is 'url打开标志,0未打开,1已打开'; create index IPAY.ORDER_GENL$OUTTRADENO on IPAY.ORDER_GENL (OUTTRADENO); alter table IPAY.ORDER_GENL add constraint PK_ORDER_GENL primary key (TRADENO); prompt prompt Creating table ORDER_SETTLEPARA prompt =============================== prompt create table IPAY.ORDER_SETTLEPARA ( tradeno VARCHAR2(30) not null, sbjgbh VARCHAR2(20), czybh VARCHAR2(20), yybm VARCHAR2(20), jshid VARCHAR2(30), settlepara BLOB, settleresult BLOB, jsjyh VARCHAR2(50), cxjyh VARCHAR2(50), cxlsh VARCHAR2(50) ) ; comment on table IPAY.ORDER_SETTLEPARA is '医保结算参数表'; comment on column IPAY.ORDER_SETTLEPARA.tradeno is '订单编号'; comment on column IPAY.ORDER_SETTLEPARA.sbjgbh is '社保机构编号'; comment on column IPAY.ORDER_SETTLEPARA.czybh is '操作员编号'; comment on column IPAY.ORDER_SETTLEPARA.yybm is '医院编码'; comment on column IPAY.ORDER_SETTLEPARA.jshid is '病人结算号'; comment on column IPAY.ORDER_SETTLEPARA.settlepara is '结算参数'; comment on column IPAY.ORDER_SETTLEPARA.settleresult is '结算结果'; comment on column IPAY.ORDER_SETTLEPARA.jsjyh is '结算交易号'; comment on column IPAY.ORDER_SETTLEPARA.cxjyh is '撤销交易号'; comment on column IPAY.ORDER_SETTLEPARA.cxlsh is '冲销流水号'; prompt prompt Creating table ORG_BANK prompt ======================= prompt create table IPAY.ORG_BANK ( orgno VARCHAR2(20) not null, yhid VARCHAR2(20) not null, qybz VARCHAR2(2) ) ; comment on table IPAY.ORG_BANK is '接入机构银行信息'; comment on column IPAY.ORG_BANK.orgno is '机构编号'; comment on column IPAY.ORG_BANK.yhid is '银行编号'; comment on column IPAY.ORG_BANK.qybz is '启用标志'; alter table IPAY.ORG_BANK add constraint PK_ORG_BANK primary key (ORGNO, YHID); prompt prompt Creating table ORG_INFO prompt ======================= prompt create table IPAY.ORG_INFO ( orgno VARCHAR2(20) not null, orgname VARCHAR2(40), orgtype VARCHAR2(10) ) ; comment on table IPAY.ORG_INFO is '接入机构信息'; comment on column IPAY.ORG_INFO.orgno is '机构编号'; comment on column IPAY.ORG_INFO.orgname is '机构名称'; comment on column IPAY.ORG_INFO.orgtype is '机构类型(01:医院,02:基层医疗机构,03:药店,04:学校)'; alter table IPAY.ORG_INFO add constraint PK_ORG_INFO primary key (ORGNO); prompt prompt Creating table OVERTIME_REFUND prompt ============================== prompt create table IPAY.OVERTIME_REFUND ( refundno VARCHAR2(30) not null, jyje NUMBER(16,2) not null, fqjysj VARCHAR2(20) not null, jysj VARCHAR2(20), state VARCHAR2(30) not null, brxm VARCHAR2(50), cardno VARCHAR2(30), brsfzhm VARCHAR2(30), bryhkh VARCHAR2(30) not null, brlxfs VARCHAR2(30), shbs VARCHAR2(30) not null, shczybh VARCHAR2(30), shczyxm VARCHAR2(50), shsj VARCHAR2(20), fhbs VARCHAR2(30) not null, fhczybh VARCHAR2(30), fhczyxm VARCHAR2(50), fhsj VARCHAR2(20), batchno VARCHAR2(32), yhmc VARCHAR2(50), entseqno VARCHAR2(32), lhh VARCHAR2(32), yhdz VARCHAR2(200), bz VARCHAR2(500), type VARCHAR2(10), clienttype VARCHAR2(10), ewpseq VARCHAR2(30), errorreason VARCHAR2(500), zzczybh VARCHAR2(30), zzczyxm VARCHAR2(50), accountid VARCHAR2(32), czybh VARCHAR2(30), czyxm VARCHAR2(50), dyflsh VARCHAR2(30), hisno VARCHAR2(50) ) ; comment on column IPAY.OVERTIME_REFUND.refundno is '超期订单号(主键)'; comment on column IPAY.OVERTIME_REFUND.jyje is '退款金额'; comment on column IPAY.OVERTIME_REFUND.fqjysj is '发起交易时间'; comment on column IPAY.OVERTIME_REFUND.jysj is '交易完成时间'; comment on column IPAY.OVERTIME_REFUND.state is '退款状态'; comment on column IPAY.OVERTIME_REFUND.brxm is '病人姓名'; comment on column IPAY.OVERTIME_REFUND.cardno is '病人卡号'; comment on column IPAY.OVERTIME_REFUND.brsfzhm is '病人身份证号码'; comment on column IPAY.OVERTIME_REFUND.bryhkh is '病人银行卡号'; comment on column IPAY.OVERTIME_REFUND.brlxfs is '病人联系方式'; comment on column IPAY.OVERTIME_REFUND.shbs is '审核标识(1,已审核,0,未审核。默认0)'; comment on column IPAY.OVERTIME_REFUND.shczybh is '审核操作员编号'; comment on column IPAY.OVERTIME_REFUND.shczyxm is '审核操作员姓名'; comment on column IPAY.OVERTIME_REFUND.shsj is '审核时间'; comment on column IPAY.OVERTIME_REFUND.fhbs is '复核标识(1,已复核,0,未复核。默认0)'; comment on column IPAY.OVERTIME_REFUND.fhczybh is '复核操作员编号'; comment on column IPAY.OVERTIME_REFUND.fhczyxm is '复核操作员姓名'; comment on column IPAY.OVERTIME_REFUND.fhsj is '复核时间'; comment on column IPAY.OVERTIME_REFUND.batchno is '退费批次号'; comment on column IPAY.OVERTIME_REFUND.yhmc is '银行名称'; comment on column IPAY.OVERTIME_REFUND.entseqno is '财务系统流水号'; comment on column IPAY.OVERTIME_REFUND.lhh is '联行号'; comment on column IPAY.OVERTIME_REFUND.yhdz is '银行地址'; comment on column IPAY.OVERTIME_REFUND.bz is '备注(指明用途)'; comment on column IPAY.OVERTIME_REFUND.type is '交易类型(0:行内,1:跨行)'; comment on column IPAY.OVERTIME_REFUND.clienttype is '调用方类型(0:窗口,1:手机端,2:自助)'; comment on column IPAY.OVERTIME_REFUND.ewpseq is '电子回单号'; comment on column IPAY.OVERTIME_REFUND.errorreason is '错误原因'; comment on column IPAY.OVERTIME_REFUND.zzczybh is '转账操作员编号'; comment on column IPAY.OVERTIME_REFUND.zzczyxm is '转账操作员姓名'; comment on column IPAY.OVERTIME_REFUND.accountid is '账户id'; comment on column IPAY.OVERTIME_REFUND.czybh is '操作员编号'; comment on column IPAY.OVERTIME_REFUND.czyxm is '操作员姓名'; comment on column IPAY.OVERTIME_REFUND.dyflsh is '调用方流水号'; comment on column IPAY.OVERTIME_REFUND.hisno is 'his调用流水号'; alter table IPAY.OVERTIME_REFUND add primary key (REFUNDNO); prompt prompt Creating table REFUND_DETL prompt ========================== prompt create table IPAY.REFUND_DETL ( refundtradeno VARCHAR2(30) not null, cjsj VARCHAR2(20), sqtkje NUMBER(16,2) not null, sytkje NUMBER(16,2) not null, ytkje NUMBER(16,2) not null, status VARCHAR2(20) not null, mchid VARCHAR2(20) not null, brxm VARCHAR2(32), brxb VARCHAR2(5), brsfzhm VARCHAR2(32) not null, czybh VARCHAR2(32), czyxm VARCHAR2(50), terminalno VARCHAR2(20), jyqd VARCHAR2(20), rzbm VARCHAR2(20), cardno VARCHAR2(32) not null, brlxfs VARCHAR2(30), ip VARCHAR2(32), dyflsh VARCHAR2(30), cqtfje NUMBER(16,2), refundno VARCHAR2(30), clienttype VARCHAR2(10), kye NUMBER(16,2), jytj VARCHAR2(20), czyhmc VARCHAR2(32), jsyhmc VARCHAR2(32), jshid VARCHAR2(64) ) ; comment on column IPAY.REFUND_DETL.refundtradeno is '订单号'; comment on column IPAY.REFUND_DETL.cjsj is '创建时间'; comment on column IPAY.REFUND_DETL.sqtkje is '申请退款金额'; comment on column IPAY.REFUND_DETL.sytkje is '剩余退款金额'; comment on column IPAY.REFUND_DETL.ytkje is '已退款金额'; comment on column IPAY.REFUND_DETL.status is '订单状态'; comment on column IPAY.REFUND_DETL.mchid is '机构编号'; comment on column IPAY.REFUND_DETL.brxm is '姓名'; comment on column IPAY.REFUND_DETL.brxb is '性别'; comment on column IPAY.REFUND_DETL.brsfzhm is '病人身份证号'; comment on column IPAY.REFUND_DETL.czybh is '操作员编号'; comment on column IPAY.REFUND_DETL.czyxm is '操作员姓名'; comment on column IPAY.REFUND_DETL.terminalno is '交易来源编号'; comment on column IPAY.REFUND_DETL.jyqd is '交易渠道'; comment on column IPAY.REFUND_DETL.rzbm is '认证编码'; comment on column IPAY.REFUND_DETL.cardno is '病人卡号'; comment on column IPAY.REFUND_DETL.brlxfs is '病人联系方式'; comment on column IPAY.REFUND_DETL.ip is '调用方IP'; comment on column IPAY.REFUND_DETL.cqtfje is '超期退费金额'; comment on column IPAY.REFUND_DETL.refundno is '超期退款订单号'; comment on column IPAY.REFUND_DETL.clienttype is '调用方类型(0:窗口,1:手机端,2:自助)'; comment on column IPAY.REFUND_DETL.kye is '卡余额'; comment on column IPAY.REFUND_DETL.jytj is '交易途径'; comment on column IPAY.REFUND_DETL.czyhmc is '充值用户名称'; comment on column IPAY.REFUND_DETL.jsyhmc is '接收用户名称'; comment on column IPAY.REFUND_DETL.jshid is '结算号ID'; alter table IPAY.REFUND_DETL add primary key (REFUNDTRADENO); prompt prompt Creating table SDSZ_TRADE_INFO prompt ============================== prompt create table IPAY.SDSZ_TRADE_INFO ( jylsid VARCHAR2(32) default sys_guid() not null, jyddh VARCHAR2(30) not null, fqjysj VARCHAR2(20) not null, jysj VARCHAR2(20), jyje NUMBER(12,2), jylx VARCHAR2(10) not null, jyzt VARCHAR2(20) not null, fhlsh VARCHAR2(50), hzkh VARCHAR2(30), hzsfzh VARCHAR2(18), hzid VARCHAR2(30), hzxm VARCHAR2(50), hzxb VARCHAR2(10), ylsjh VARCHAR2(20), zhid VARCHAR2(30), kzt VARCHAR2(10), gsyy VARCHAR2(50), zhje NUMBER(12,2), zffs VARCHAR2(20), jytj VARCHAR2(20), ctbs VARCHAR2(10), gqtfbs VARCHAR2(20), czyhmc VARCHAR2(30), jsyhmc VARCHAR2(30), czjg VARCHAR2(10), tsxx VARCHAR2(500), bz VARCHAR2(100), czlx VARCHAR2(10), tfcxbs VARCHAR2(2), czlb VARCHAR2(10) ) ; comment on table IPAY.SDSZ_TRADE_INFO is '调用HIS账户验证、充值、退费接口,交易流水表'; comment on column IPAY.SDSZ_TRADE_INFO.jylsid is '交易流水表主键ID'; comment on column IPAY.SDSZ_TRADE_INFO.jyddh is '交易订单号(对应支付、退款交易订单号)'; comment on column IPAY.SDSZ_TRADE_INFO.fqjysj is '发起交易时间'; comment on column IPAY.SDSZ_TRADE_INFO.jysj is '交易时间'; comment on column IPAY.SDSZ_TRADE_INFO.jyje is '交易金额'; comment on column IPAY.SDSZ_TRADE_INFO.jylx is '交易类型(1:充值、2:退费、0:患者账户验证)'; comment on column IPAY.SDSZ_TRADE_INFO.jyzt is '交易状态(0:未知,1:验证中,2:验证成功,3:验证失败,4:充值中,5:充值成功,6:充值失败,7:退费中,8:退费成功,9:退费失败)'; comment on column IPAY.SDSZ_TRADE_INFO.fhlsh is '返回流水号(流水号+最新余额,格式“XXXXXXXX|FEE.00”)'; comment on column IPAY.SDSZ_TRADE_INFO.hzkh is '患者卡号'; comment on column IPAY.SDSZ_TRADE_INFO.hzsfzh is '患者身份证号'; comment on column IPAY.SDSZ_TRADE_INFO.hzid is '患者Id'; comment on column IPAY.SDSZ_TRADE_INFO.hzxm is '患者姓名'; comment on column IPAY.SDSZ_TRADE_INFO.hzxb is '患者性别'; comment on column IPAY.SDSZ_TRADE_INFO.ylsjh is '预留手机号'; comment on column IPAY.SDSZ_TRADE_INFO.zhid is '账户Id'; comment on column IPAY.SDSZ_TRADE_INFO.kzt is '卡状态'; comment on column IPAY.SDSZ_TRADE_INFO.gsyy is '挂失原因'; comment on column IPAY.SDSZ_TRADE_INFO.zhje is '账户金额'; comment on column IPAY.SDSZ_TRADE_INFO.zffs is '支付方式(1:现金,2:银行卡,3:支付宝,4:微信,5:医保,6:转卡,7:绑定解绑,8:门诊省医保,9、住院省医保,10:门诊异地,11:住院异地)'; comment on column IPAY.SDSZ_TRADE_INFO.jytj is '交易途径(1:原手机App,2:支付宝支付窗,3:网络医院,4:服务平台,5:自助机,6:微信)'; comment on column IPAY.SDSZ_TRADE_INFO.ctbs is '充退标识(0:退款,1:充值)'; comment on column IPAY.SDSZ_TRADE_INFO.gqtfbs is '过期退费标识(0:非过期,1:过期退费)'; comment on column IPAY.SDSZ_TRADE_INFO.czyhmc is '充值用户名称'; comment on column IPAY.SDSZ_TRADE_INFO.jsyhmc is '接收用户名称'; comment on column IPAY.SDSZ_TRADE_INFO.czjg is '操作结果'; comment on column IPAY.SDSZ_TRADE_INFO.tsxx is '提示信息'; comment on column IPAY.SDSZ_TRADE_INFO.bz is '备注'; comment on column IPAY.SDSZ_TRADE_INFO.czlx is '充值类型(1:门诊,2:住院)'; comment on column IPAY.SDSZ_TRADE_INFO.tfcxbs is '退费撤销标识(0:不是,1:是,默认0)'; comment on column IPAY.SDSZ_TRADE_INFO.czlb is '充值类别'; alter table IPAY.SDSZ_TRADE_INFO add constraint PK_SDSZ_TRADE_INFO primary key (JYLSID); prompt prompt Creating table UCOMPOS_MANAGEMENT_INFO prompt ====================================== prompt create table IPAY.UCOMPOS_MANAGEMENT_INFO ( jyid VARCHAR2(32) default sys_guid() not null, qqjybw CLOB, yybh VARCHAR2(20), rzbm VARCHAR2(30), czybh VARCHAR2(20), czyxm VARCHAR2(30), syjh VARCHAR2(20), syyh VARCHAR2(20), jyqd VARCHAR2(2), jylybh VARCHAR2(20), jkmc VARCHAR2(20), ptlsh VARCHAR2(30), jyddh VARCHAR2(50), fqjysj VARCHAR2(20) not null, wcjysj VARCHAR2(20), jyzt VARCHAR2(3) not null, jylx VARCHAR2(3), fhjybw CLOB, dyfwybs VARCHAR2(30), bz VARCHAR2(100) ) ; comment on table IPAY.UCOMPOS_MANAGEMENT_INFO is '调银商终端DLL管理类交易信息表'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.jyid is '管理类交易记录Id'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.qqjybw is '请求交易报文(调银商DLL接口报文)'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.yybh is '医院编号'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.rzbm is '认证编码'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.czybh is '操作员编号'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.czyxm is '操作员姓名'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.syjh is '收银机号'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.syyh is '收银员号'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.jyqd is '交易渠道(1:医保,2:银联卡,3:微信,4:云闪付)'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.jylybh is '交易来源编号(窗口POS、自助终端编号,以便从配置表找到对应的配置信息)'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.jkmc is '接口名称'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.ptlsh is '平台流水号'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.jyddh is '交易订单号'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.fqjysj is '发起交易时间'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.wcjysj is '完成交易时间'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.jyzt is '交易状态(1:成功,0:失败,2:未知,3:交易中)'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.jylx is '交易类型(00/005:签到,06/006:结算,04:余额查询)'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.fhjybw is '返回交易报文(银商DLL接口返回报文)'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.dyfwybs is '调用方唯一标识'; comment on column IPAY.UCOMPOS_MANAGEMENT_INFO.bz is '备注'; alter table IPAY.UCOMPOS_MANAGEMENT_INFO add constraint PK_UCOMPOS_MANAGEMENT_INFO primary key (JYID); prompt prompt Creating table USER_AUTHCODE prompt ============================ prompt create table IPAY.USER_AUTHCODE ( authcode VARCHAR2(50) not null, esicardno VARCHAR2(50), userid VARCHAR2(50) ) ; comment on table IPAY.USER_AUTHCODE is '用户授权码和支付宝UUID关系'; comment on column IPAY.USER_AUTHCODE.authcode is '支付宝授权码'; comment on column IPAY.USER_AUTHCODE.esicardno is '支付宝返回的UUID'; comment on column IPAY.USER_AUTHCODE.userid is '用户ID'; alter table IPAY.USER_AUTHCODE add constraint PK_USER_AUTHCODE primary key (AUTHCODE); prompt prompt Creating view ORDER_GEN_DET_LIST prompt ================================ prompt create or replace view ipay.order_gen_det_list as select decode(a.orgno, null, b.orgno, a.orgno) orgno, decode(a.yhid, null, b.yhid, a.yhid) yhid, decode(a.dzrq, null, b.dzrq, a.dzrq) dzrq, a.srbs, a.srje, b.zcbs, b.zcje from (select substr(b.jysj, 1, 8) dzrq, count(1) srbs, sum(b.jyje) srje,a.orgno,b.yhid from IPAY.order_genl a, IPAY.order_detl b where a.tradeno = b.tradeno and b.paystate = 'paid' group by substr(b.jysj, 1, 8), a.orgno, b.yhid order by dzrq) a full join (select substr(b.jysj, 1, 8) dzrq, count(1) zcbs, sum(b.jyje) zcje,a.orgno,b.yhid from IPAY.order_genl a, IPAY.order_detl b where a.tradeno = b.tradeno and b.paystate = 'repaid' group by substr(b.jysj, 1, 8),a.orgno,b.yhid order by dzrq) b on a.dzrq = b.dzrq and a.yhid = b.yhid and a.orgno = b.orgno order by dzrq desc; prompt prompt Creating view V_LINK_INFO prompt ========================= prompt create or replace view ipay.v_link_info as select dtl.intradeno,dtl.dsftradeno,dtl.yhid from IPAY.order_detl dtl where 1=1 and dtl.dsftradeno is not null; prompt prompt Creating view V_TRADE_CASHPAY_INFO prompt ================================== prompt create or replace view ipay.v_trade_cashpay_info as select "TRADENO","INTRADENO","FQJYSJ","JYSJ","JYJE","YHID","PAYSTATE","JYM_IBANK","TYPE","DSFTRADENO","TKINTRADENO","ZJLX","ZJHM","REFUNDTYPE","APPID","TERMINALNO","CZYBH","CZYXM","CZYBZ","BRYNID","BRXM","BRSFZHM","BRLXFS","CARDNO","FKJGBH","MERCHANTNO","REFUNDTRADENO","ZFLX","YCBS","IP","JYQD","FQJYZT","DYFLSH","HISNO","JYFS","JYTJ","CZYHMC","JSYHMC","YNKCODE","CQTFBS" from ipay.order_detl dt where yhid = 'XJZF' and dt.paystate in ('paid','repaid'); prompt prompt Creating view V_TRADE_INFO prompt ========================== prompt create or replace view ipay.v_trade_info as select distinct dt.tradeno, --平台订单号 dt.intradeno ddbh, --交易订单号(订单编号) dt.brxm, --病人姓名 dt.cardno brjzkh, --病人就诊卡号 dt.brsfzhm sfzhm, --病人身份证号码 dt.yhid, --支付银行 bk.yhjc qdmc, --渠道名称 bk.yhmc yhmc, --银行名称(实际的支付渠道) case bk.yhjc when '转账' then 'Transfer' when '广发银行' then 'CgbSmartPay' when '支付宝' then 'Alipay' when 'POS' then 'UnionPay' when '现金' then 'CashPay' when '医保' then 'Medicare' when '微信' then 'WeChat' end jyqdbs, --交易渠道标识 case dt.type when 'pay' then '支付' when 'refund' then '退款' end ywlx, --业务类型 nvl(dt.fqjysj,dt.jysj) as jlcjsj, --记录创建时间 dt.jysj, --支付时间 --dt.jyje, case dt.type when 'pay' then dt.jyje when 'refund' then -1*dt.jyje end jyje, --to_char(dt.jyje,'0.99') as jyje, --交易金额 gn.orgno mchid, --医院编号 case dt.paystate when 'paid' then '1' when 'repaid' then '1' when 'paying' then '2' when 'repaying' then '2' when 'refailed' then '0' when 'failed' then '0' when 'closed' then '2' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case dt.paystate when 'paid' then '已支付' when 'repaid' then '已退款' when 'paying' then '支付中' when 'repaying' then '退款中' when 'refailed' then '退款失败' when 'failed' then '支付失败' when 'closed' then '已关闭' else '未知' end jyztms, --交易状态描述 dt.tkintradeno, --退款原订单号 dt.czyxm yhryxm, --操作员姓名 dt.czybh yhrybh, --操作员编号 dt.zflx, --支付类型(0:充值,1:缴费) dt.terminalno jyzdbh, --交易终端编号 dt.merchantno jyshbh, --交易商户编号 dt.jyqd jyjz, --POS交易卡介质(医保,银联卡) dt.hisno hisno, -- his交易流水号 dt.ynkcode ynjyzt, --院内卡状态标识:ynjyzt对应于ynccode (0:成功,1:失败,2:未知) dt.jytj jytj --交易途径 from ipay.order_detl dt, ipay.bank_info bk, ipay.order_genl gn where dt.tradeno=gn.tradeno and dt.yhid=bk.yhid and (dt.cqtfbs <> '1' or dt.cqtfbs is null) and dt.paystate in ('paid','repaid','refailed','failed','closed'); prompt prompt Creating view V_TRADE_INFO_YNDZ prompt =============================== prompt create or replace view ipay.v_trade_info_yndz as select distinct dt.tradeno, --平台订单号 dt.intradeno ddbh,--交易订单号(订单编号) dt.hisno, --his调用流水号 dt.brxm, --病人姓名 dt.cardno brjzkh, --病人就诊卡号 dt.brsfzhm sfzhm, --病人身份证号码 dt.yhid, --支付银行/渠道 bk.yhjc qdmc, --支付银行/渠道名称 bk.yhmc yhmc, --银行名称(实际的支付渠道) case when dt.cqtfbs = '1' then 'Transfer' when instr(bk.yhjc, '可退金额') > 0 then 'SPCLQY' when instr(bk.yhjc, '广发') > 0 then 'CgbSmartPay' when instr(bk.yhjc, '支付宝') > 0 then 'Alipay' when instr(bk.yhjc, 'POS') > 0 then 'UnionPay' when instr(bk.yhjc, '现金') > 0 then 'CashPay' when bk.yhjc = '医保' then 'Medicare' when dt.yhid = 'SYBMZ' then 'Medicare' when dt.yhid = 'SYBZY' then 'Medicare' when bk.yhjc = '异地门诊' then 'Medicare' when bk.yhjc = '异地住院' then 'Medicare' when instr(bk.yhjc, '微信') > 0 then 'WeChat' else 'Other' end jyqdbs, --交易渠道标识 case dt.type when 'pay' then '支付' when 'refund' then '退款' end ywlx, --业务类型 nvl(dt.fqjysj,dt.jysj) as jlcjsj, --记录创建时间 nvl(dt.ynjysj,dt.jysj) jysj, --支付时间 case dt.type when 'pay' then dt.jyje when 'refund' then -1*dt.jyje end jyje, --交易金额 dt.ynkcode ynjyzt, --院内卡状态标识:ynjyzt对应于ynccode (0:成功,1:失败,2:未知) dt.ynkcode, gn.orgno mchid, --医院编号 case dt.paystate when 'paid' then '1' when 'repaid' then '1' when 'paying' then '2' when 'repaying' then '2' when 'refailed' then '0' when 'failed' then '0' when 'closed' then '2' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case dt.paystate when 'paid' then '已支付' when 'repaid' then '已退款' when 'paying' then '支付中' when 'repaying' then '退款中' when 'refailed' then '退款失败' when 'failed' then '支付失败' when 'closed' then '已关闭' else '未知' end jyztms, --交易状态描述 dt.tkintradeno yddbh, --退款原订单号 dt.dsftradeno jyckh, --交易参考号(终端)、结算号id (医保) case when instr(bk.yhjc, 'POS') > 0 then dt.jym_ibank when bk.yhjc = '医保' then dt.jshid when bk.yhjc = '省医保门诊' then dt.jshid when bk.yhjc = '省医保住院' then dt.jshid when bk.yhjc = '异地门诊' then dt.jshid when bk.yhjc = '异地住院' then dt.jshid else '' end jylsh, --交易流水号(终端) dt.czyxm yhryxm, --操作员姓名 dt.czybh yhrybh, --操作员编号 dt.zflx, --支付类型(0:充值,1:缴费) dt.terminalno jyzdbh, --交易终端编号 dt.merchantno jyshbh, --交易商户编号、 住院流水号(医保) dt.jyqd jykjz, --POS交易卡介质(医保,银联卡) dt.jyfs, --交易方式 case dt.jytj when '2' then 'dwzfbshh' when '5' then 'gwi' else 'Ehis' end sbcsbm, --设备厂商编码 dt.jytj jyylx, --交易途径 dt.zjlx tcje, --统筹金额 dt.zjhm gzje --个账金额 from ipay.order_detl dt, ipay.bank_info bk, ipay.order_genl gn where dt.tradeno=gn.tradeno and dt.yhid=bk.yhid and dt.paystate in ('paid','repaid','refailed','failed','closed') and (dt.cqtfbs <> '1' or dt.cqtfbs is null) --明细表剔除超期退费数据 union --超期退费数据 select distinct '' tradeno, --超期退费订单号 refund.refundno ddbh ,-- (订单编号) refund.hisno hisno, --his调用流水号 refund.brxm, --病人姓名 refund.cardno brjzkh, --病人就诊卡号 refund.brsfzhm sfzhm, --病人身份证号码 'UNIONCARD' yhid, --支付银行/渠道 '超期' qdmc, --支付银行/渠道名称 '超期' yhmc, --银行名称(实际的支付渠道) 'Transfer' jyqdbs, --交易渠道标识 '退款' ywlx, --业务类型 nvl(refund.fqjysj,refund.jysj) as jlcjsj, --记录创建时间 refund.fqjysj jysj, --支付时间 -1*refund.jyje jyje, --交易金额 dtl.ynkcode ynjyzt, --院内卡状态标识:ynjyzt对应于ynccode (0:成功,1:失败,2:未知) dtl.ynkcode, dtl.mchid mchid, --医院编号 case refund.state when 'refund' then '1' when 'repaying' then '1' when 'repayings' then '1' when 'repaid' then '1' when 'refunding' then '1' when 'failed' then '0' when 'refailed' then '0' when 'refailed' then '0' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case refund.state when 'refund' then '转账成功' when 'repaying' then '未审核' when 'repayings' then '审核通过,未复核' when 'repaid' then '审核通过,复核通过' when 'refunding' then '转账中' when 'failed' then '转账失败' when 'refailed' then '审核不通过' when 'refailed' then '审核通过,复核不通过' else '未知' end jyztms, --交易状态描述 '' yddbh, --退款原订单号 refund.bryhkh jyckh, --交易参考号(银行卡号) refund.bryhkh jylsh, --交易流水号(银行卡号) refund.czyxm yhryxm, --操作员姓名 refund.czybh yhrybh, --操作员编号 '' zflx, --支付类型(0:充值,1:缴费) '' jyzdbh, --交易终端编号 '' jyshbh, --交易商户编号、 住院流水号(医保)dt.merchantno '' jykjz, --POS交易卡介质(医保,银联卡) '' jyfs, --交易方式 '' sbcsbm, --设备厂商编码 '' jyylx, --交易途径 '' tcje, --统筹金额 '' gzje --个账金额 from ipay.overtime_refund refund left join ( select refuns.refundno,refuns.mchid,dtl1.ynkcode from ipay.refund_detl refuns left join ipay.order_detl dtl1 on dtl1.refundtradeno = refuns.refundtradeno ) dtl on dtl.refundno = refund.refundno where refund.state in ('repaid', 'refund', 'refunding', 'repaying', 'repayings'); prompt prompt Creating view V_TRADE_INFO_YNDZ2 prompt ================================ prompt create or replace view ipay.v_trade_info_yndz2 as select distinct dt.tradeno, --平台订单号 dt.intradeno ddbh,--交易订单号(订单编号) dt.hisno, --his调用流水号 dt.brxm, --病人姓名 dt.cardno brjzkh, --病人就诊卡号 dt.brsfzhm sfzhm, --病人身份证号码 dt.yhid, --支付银行/渠道 bk.yhjc qdmc, --支付银行/渠道名称 bk.yhmc yhmc, --银行名称(实际的支付渠道) case when dt.cqtfbs = '1' then 'Transfer' when instr(bk.yhjc, '可退金额') > 0 then 'SPCLQY' when instr(bk.yhjc, '广发') > 0 then 'CgbSmartPay' when instr(bk.yhjc, '支付宝') > 0 then 'Alipay' when instr(bk.yhjc, 'POS') > 0 then 'UnionPay' when instr(bk.yhjc, '现金') > 0 then 'CashPay' when bk.yhjc = '医保' then 'Medicare' when dt.yhid = 'SYBMZ' then 'Medicare' when dt.yhid = 'SYBZY' then 'Medicare' when bk.yhjc = '异地门诊' then 'Medicare' when bk.yhjc = '异地住院' then 'Medicare' when instr(bk.yhjc, '微信') > 0 then 'WeChat' else 'Other' end jyqdbs, --交易渠道标识 case dt.type when 'pay' then '支付' when 'refund' then '退款' end ywlx, --业务类型 nvl(dt.fqjysj,dt.jysj) as jlcjsj, --记录创建时间 dt.jysj, --支付时间 case dt.type when 'pay' then dt.jyje when 'refund' then -1*dt.jyje end jyje, --交易金额 dt.ynkcode, --院内卡状态 gn.orgno mchid, --医院编号 case dt.paystate when 'paid' then '1' when 'repaid' then '1' when 'paying' then '2' when 'repaying' then '2' when 'refailed' then '0' when 'failed' then '0' when 'closed' then '2' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case dt.paystate when 'paid' then '已支付' when 'repaid' then '已退款' when 'paying' then '支付中' when 'repaying' then '退款中' when 'refailed' then '退款失败' when 'failed' then '支付失败' when 'closed' then '已关闭' else '未知' end jyztms, --交易状态描述 dt.tkintradeno yddbh, --退款原订单号 dt.dsftradeno jyckh, --交易参考号(终端)、结算号id (医保) case when instr(bk.yhjc, 'POS') > 0 then dt.jym_ibank when bk.yhjc = '医保' then dt.jshid when bk.yhjc = '省医保门诊' then dt.jshid when bk.yhjc = '省医保住院' then dt.jshid when bk.yhjc = '异地门诊' then dt.jshid when bk.yhjc = '异地住院' then dt.jshid else '' end jylsh, --交易流水号(终端) dt.czyxm yhryxm, --操作员姓名 dt.czybh yhrybh, --操作员编号 dt.zflx, --支付类型(0:充值,1:缴费) dt.terminalno jyzdbh, --交易终端编号 dt.merchantno jyshbh, --交易商户编号、 住院流水号(医保) dt.jyqd jykjz, --POS交易卡介质(医保,银联卡) dt.jyfs, --交易方式 case dt.jytj when '2' then 'dwzfbshh' when '5' then 'gwi' else 'Ehis' end sbcsbm, --设备厂商编码 dt.jytj jyylx, --交易途径 dt.zjlx tcje, --统筹金额 dt.zjhm gzje --个账金额 from ipay.order_detl dt, ipay.bank_info bk, ipay.order_genl gn where dt.tradeno=gn.tradeno and dt.yhid=bk.yhid and dt.paystate in ('paid','repaid','refailed','failed','closed') and (dt.cqtfbs <> '1' or dt.cqtfbs is null) --明细表剔除超期退费数据 union --超期退费数据 select distinct refund.refundno tradeno, --超期退费订单号 refund.refundno ddbh,-- (订单编号) dtl.hisno hisno, --his调用流水号 refund.brxm, --病人姓名 refund.cardno brjzkh, --病人就诊卡号 refund.brsfzhm sfzhm, --病人身份证号码 dtl.yhid yhid, --支付银行/渠道 '超期' qdmc, --支付银行/渠道名称 '超期' yhmc, --银行名称(实际的支付渠道) 'Transfer' jyqdbs, --交易渠道标识 '退款' ywlx, --业务类型 nvl(refund.fqjysj,refund.jysj) as jlcjsj, --记录创建时间 refund.jysj, --支付时间 -1*refund.jyje jyje, --交易金额 '' ynkcode, --院内卡状态 refuns.mchid mchid, --医院编号 case refund.state when 'refund' then '1' when 'repaying' then '1' when 'repayings' then '1' when 'repaid' then '1' when 'refunding' then '0' when 'failed' then '0' when 'refailed' then '0' when 'refailed' then '0' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case refund.state when 'refund' then '转账成功' when 'repaying' then '未审核' when 'repayings' then '审核通过,未复核' when 'repaid' then '审核通过,复核通过' when 'refunding' then '转账中' when 'failed' then '转账失败' when 'refailed' then '审核不通过' when 'refailed' then '审核通过,复核不通过' else '未知' end jyztms, --交易状态描述 '' yddbh, --退款原订单号 refund.bryhkh jyckh, --交易参考号(银行卡号) refund.bryhkh jylsh, --交易流水号(银行卡号) refund.czyxm yhryxm, --操作员姓名 refund.czybh yhrybh, --操作员编号 '' zflx, --支付类型(0:充值,1:缴费) '' jyzdbh, --交易终端编号 '' jyshbh, --交易商户编号、 住院流水号(医保)dt.merchantno '' jykjz, --POS交易卡介质(医保,银联卡) '' jyfs, --交易方式 '' sbcsbm, --设备厂商编码 '' jyylx, --交易途径 '' tcje, --统筹金额 '' gzje --个账金额 from ipay.overtime_refund refund left join ipay.refund_detl refuns on refund.refundno = refuns.refundno left join ipay.order_detl dtl on dtl.refundtradeno = refuns.refundtradeno where refund.state in ('repaid', 'refund', 'refunding', 'repaying', 'repayings'); spool off <file_sep>/dareway/2021-7-21/厂商表.sql prompt PL/SQL Developer import file prompt Created on 2021年7月21日 by Wdf set feedback off set define off prompt Creating E_EQUIPMENT_FACTORY... create table E_EQUIPMENT_FACTORY ( sbcsid VARCHAR2(32) default sys_guid() not null, sbcsbm VARCHAR2(15) not null, sbcsmc VARCHAR2(30) not null, dzwjgs VARCHAR2(10), dzzq VARCHAR2(10), rqsj VARCHAR2(10), cszt VARCHAR2(2) default 1 not null, sfzddz VARCHAR2(2) default 1 not null, hqdzwjfs VARCHAR2(10) not null, dzwjxzdz VARCHAR2(100), ftpzh VARCHAR2(30), ftpmm VARCHAR2(20), ftpdk NUMBER(6), qmsf VARCHAR2(10), shzs VARCHAR2(100), ggzs VARCHAR2(100), dzwjxzml VARCHAR2(100), dzwjmc VARCHAR2(50), dzwjbdbclj VARCHAR2(100) not null, jgbm VARCHAR2(15) not null, dzwjxfsj VARCHAR2(10), jlcjsj TIMESTAMP(6) default sysdate not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6) default sysdate, zhxgr VARCHAR2(20), jkm VARCHAR2(50), jkcs VARCHAR2(1000), zhqdfs VARCHAR2(2), stmc VARCHAR2(30), sjklx VARCHAR2(20), bz VARCHAR2(100), bly VARCHAR2(50) ) tablespace URP_RUN pctfree 10 initrans 1 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); comment on table E_EQUIPMENT_FACTORY is '设备信息'; comment on column E_EQUIPMENT_FACTORY.sbcsid is '设备厂商ID,主键'; comment on column E_EQUIPMENT_FACTORY.sbcsbm is '设备厂商编码,用于区分设备厂商'; comment on column E_EQUIPMENT_FACTORY.sbcsmc is '设备厂商名称'; comment on column E_EQUIPMENT_FACTORY.dzwjgs is '对账文件格式'; comment on column E_EQUIPMENT_FACTORY.dzzq is '对账周期'; comment on column E_EQUIPMENT_FACTORY.rqsj is '日切时间'; comment on column E_EQUIPMENT_FACTORY.cszt is '厂商状态(1:正常,0:禁用)'; comment on column E_EQUIPMENT_FACTORY.sfzddz is '是否自动对账(0:否,1是)'; comment on column E_EQUIPMENT_FACTORY.hqdzwjfs is '获取对账文件方式(ftp、sftp、http、https、socket、webservice、视图)'; comment on column E_EQUIPMENT_FACTORY.dzwjxzdz is '对账文件下载地址(FTP:IP,接口:url,视图:数据库访问连接串)'; comment on column E_EQUIPMENT_FACTORY.ftpzh is 'ftp账号、视图数据库用户名'; comment on column E_EQUIPMENT_FACTORY.ftpmm is 'ftp密码、视图数据库密码'; comment on column E_EQUIPMENT_FACTORY.ftpdk is 'ftp端口、socket端口'; comment on column E_EQUIPMENT_FACTORY.qmsf is '签名算法'; comment on column E_EQUIPMENT_FACTORY.shzs is '商户证书(含路径和文件名)'; comment on column E_EQUIPMENT_FACTORY.ggzs is '公共证书(含路径和文件名)'; comment on column E_EQUIPMENT_FACTORY.dzwjxzml is '对账文件下载目录(ftp、sftp,静态的写死,动态的用{}括起来)'; comment on column E_EQUIPMENT_FACTORY.dzwjmc is '对账文件名称(静态的写死,动态的用{}括起来)'; comment on column E_EQUIPMENT_FACTORY.dzwjbdbclj is '对账文件本地保存路径(静态的写死,动态的用{}括起来)'; comment on column E_EQUIPMENT_FACTORY.jgbm is '机构编码'; comment on column E_EQUIPMENT_FACTORY.dzwjxfsj is '对账文件下发时间'; comment on column E_EQUIPMENT_FACTORY.jlcjsj is '记录创建时间'; comment on column E_EQUIPMENT_FACTORY.cjr is '创建人'; comment on column E_EQUIPMENT_FACTORY.zhxgsj is '最后修改日期'; comment on column E_EQUIPMENT_FACTORY.zhxgr is '最后修改人'; comment on column E_EQUIPMENT_FACTORY.jkm is '接口/方法名(如webservice)'; comment on column E_EQUIPMENT_FACTORY.jkcs is '接口参数(调用http、htps、socket、webservice接口所需的参数,静态的写死,动态的用{}括起来)'; comment on column E_EQUIPMENT_FACTORY.zhqdfs is '结算账户确定方式(1:商户号,2:商户号+终端号,3:结算账户账号)'; comment on column E_EQUIPMENT_FACTORY.stmc is '视图名称'; comment on column E_EQUIPMENT_FACTORY.sjklx is '数据库类型(oracle、MySQL等)'; comment on column E_EQUIPMENT_FACTORY.bz is '备注'; comment on column E_EQUIPMENT_FACTORY.bly is '保留域'; alter table E_EQUIPMENT_FACTORY add constraint E_EQUIPMENT_PRIMARYKEY primary key (SBCSID) using index tablespace URP_RUN pctfree 10 initrans 2 maxtrans 255 storage ( initial 64K next 1M minextents 1 maxextents unlimited ); prompt Loading E_EQUIPMENT_FACTORY... insert into E_EQUIPMENT_FACTORY (sbcsid, sbcsbm, sbcsmc, dzwjgs, dzzq, rqsj, cszt, sfzddz, hqdzwjfs, dzwjxzdz, ftpzh, ftpmm, ftpdk, qmsf, shzs, ggzs, dzwjxzml, dzwjmc, dzwjbdbclj, jgbm, dzwjxfsj, jlcjsj, cjr, zhxgsj, zhxgr, jkm, jkcs, zhqdfs, stmc, sjklx, bz, bly) values ('f971c7babf374641bc2f6e36996a1813', 'SelfService', '长城', 'txt', 'T', '00:00:00', '1', '1', 'ftp', 'ftp.tplweb.cn', 'urp', 'urp', 21, null, null, null, '/urp2.0/zzj_', 'zzj_{date}', './ereconfile/', 'csyy', '00:00:00', to_timestamp('24-07-2020 15:18:36.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'wdf', to_timestamp('20-07-2021 09:23:43.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', null, null, '1', null, null, null, null); insert into E_EQUIPMENT_FACTORY (sbcsid, sbcsbm, sbcsmc, dzwjgs, dzzq, rqsj, cszt, sfzddz, hqdzwjfs, dzwjxzdz, ftpzh, ftpmm, ftpdk, qmsf, shzs, ggzs, dzwjxzml, dzwjmc, dzwjbdbclj, jgbm, dzwjxfsj, jlcjsj, cjr, zhxgsj, zhxgr, jkm, jkcs, zhqdfs, stmc, sjklx, bz, bly) values ('6fd0652f57f14a80a93a84f709a11856', 'Ehis', '医院', 'txt', 'T', '00:00:00', '1', '1', 'ftp', 'ftp.tplweb.cn', 'urp', 'urp', 21, null, null, null, '/urp2.0/Ehis', 'csyy_Ehis_{date}', './ereconfile/', 'csyy', '10:00:00', to_timestamp('09-07-2020 15:09:46.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', to_timestamp('01-07-2021 18:16:03.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'wdf', null, null, '3', null, null, null, null); insert into E_EQUIPMENT_FACTORY (sbcsid, sbcsbm, sbcsmc, dzwjgs, dzzq, rqsj, cszt, sfzddz, hqdzwjfs, dzwjxzdz, ftpzh, ftpmm, ftpdk, qmsf, shzs, ggzs, dzwjxzml, dzwjmc, dzwjbdbclj, jgbm, dzwjxfsj, jlcjsj, cjr, zhxgsj, zhxgr, jkm, jkcs, zhqdfs, stmc, sjklx, bz, bly) values ('4fcc70d4706b4120abe0ae308595ae54', 'ipay', '支付平台', 'txt', 'T', '00:00:00', '1', '1', 'ftp', 'ftp.tplweb.cn', 'urp', 'urp', 21, null, null, null, '/urp2.0/Eipay', 'Payment_Platform_{date}', './ereconfile/', 'csyy', '00:00:00', to_timestamp('17-07-2020 11:01:51.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'wdf', to_timestamp('03-06-2021 17:11:08.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', null, null, '3', null, null, null, null); insert into E_EQUIPMENT_FACTORY (sbcsid, sbcsbm, sbcsmc, dzwjgs, dzzq, rqsj, cszt, sfzddz, hqdzwjfs, dzwjxzdz, ftpzh, ftpmm, ftpdk, qmsf, shzs, ggzs, dzwjxzml, dzwjmc, dzwjbdbclj, jgbm, dzwjxfsj, jlcjsj, cjr, zhxgsj, zhxgr, jkm, jkcs, zhqdfs, stmc, sjklx, bz, bly) values ('wechatbabf374641bc2f6e36996a1813', 'wechatPublic', '东软', 'txt', 'T', '00:00:00', '1', '1', 'ftp', 'ftp.tplweb.cn', 'urp', 'urp', 21, null, null, null, '/urp2.0/wechatPublic_', 'wechatPublic_{date}', './ereconfile/', 'csyy', '00:00:00', to_timestamp('24-07-2020 15:18:36.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'wdf', to_timestamp('20-07-2021 09:22:33.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', null, null, '1', null, null, null, null); insert into E_EQUIPMENT_FACTORY (sbcsid, sbcsbm, sbcsmc, dzwjgs, dzzq, rqsj, cszt, sfzddz, hqdzwjfs, dzwjxzdz, ftpzh, ftpmm, ftpdk, qmsf, shzs, ggzs, dzwjxzml, dzwjmc, dzwjbdbclj, jgbm, dzwjxfsj, jlcjsj, cjr, zhxgsj, zhxgr, jkm, jkcs, zhqdfs, stmc, sjklx, bz, bly) values ('alipayLifebabf3bc2f6e36996a1813', 'alipayLife', '众阳', 'txt', 'T', '00:00:00', '1', '1', 'ftp', 'ftp.tplweb.cn', 'urp', 'urp', 21, null, null, null, '/urp2.0/alipayLife_', 'alipayLife_{date}', './ereconfile/', 'csyy', '00:00:00', to_timestamp('24-07-2020 15:18:36.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'wdf', to_timestamp('20-07-2021 09:22:39.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', null, null, '1', null, null, null, null); insert into E_EQUIPMENT_FACTORY (sbcsid, sbcsbm, sbcsmc, dzwjgs, dzzq, rqsj, cszt, sfzddz, hqdzwjfs, dzwjxzdz, ftpzh, ftpmm, ftpdk, qmsf, shzs, ggzs, dzwjxzml, dzwjmc, dzwjbdbclj, jgbm, dzwjxfsj, jlcjsj, cjr, zhxgsj, zhxgr, jkm, jkcs, zhqdfs, stmc, sjklx, bz, bly) values ('yundatbabf374641bc2f6e36996a1813', 'yunda', '运达', 'txt', 'T', '00:00:00', '1', '1', 'ftp', 'ftp.tplweb.cn', 'urp', 'urp', 21, null, null, null, '/urp2.0/yunda_', 'yunda_{date}', './ereconfile/', 'csyy', '00:00:00', to_timestamp('24-07-2020 15:18:36.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'wdf', to_timestamp('20-07-2021 09:22:44.000000', 'dd-mm-yyyy hh24:mi:ss.ff'), 'urpadmin', null, null, '1', null, null, null, null); commit; prompt 6 records loaded set feedback on set define on prompt Done. <file_sep>/dareway/清空对账记录.sql delete from urp.ACCOUNTABLE_STATISTICS t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.ALIPAY_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.CHANNEL_RECONRESULT t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.HIS_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.MEDICARE_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.RECONFILE_INFO t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.RECONHIS_STATISTICS t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.RECONRESULT_DETAIL t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.SCANCODE_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.UNIONPAYCF_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.UNIONPAYOMNI_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.UNIONPAY_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.WECHAT_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.REALTIME_MONITOR t where to_char(jlcjsj,'yyyymmdd') = '20200917'; delete from urp.MSG_PUSH t where to_char(cjsj,'yyyymmdd') = '20200917'; delete from urp.CCBUNIONPAY_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.ABCPAY_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.EHCPAY_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.E_factory_RECONRESULT t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.E_HIS_TRANSFLOW t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.e_equipment_transflow t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.E_equipment_RECONRESULT t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.E_RECONFILE_INFO t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.E_RECON_history t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.E_RECONRESULT_DETAIL t where to_char(dzrq,'yyyymmdd') = '20200917'; delete from urp.m_his_transflow a where to_char(a.dzrq,'yyyyMMdd')='20200917'; delete from urp.m_equipment_transflow a where to_char(a.dzrq,'yyyyMMdd')='20200917'; delete from urp.e_realtime_monitor a where to_char(a.JLCJSJ,'yyyyMMdd')='20200917'; <file_sep>/dareway/重要sql/对账视图-ipay.sql -- 查询对账视图 select * from ipay.v_trade_info where jysj like '20210218%' and ywlx = '退款'; select * from ipay.v_trade_info_yndz where 1=1 --and qdmc = '医保' and ddbh = '20210306P00074417DAREWAY' order by jlcjsj desc; select * from ipay.v_trade_info_yndz where jysj between '20210401000000' and '20210402000000' --select * from ipay.v_trade_info_yndz where 1=1 select * from ipay.v_trade_info_yndz where 1=1 --and ddbh = '20210322P00098955DAREWAY' and jysj between '20210410000000' and '20210411000000' and jyqdbs = 'Medicare' and qdmc = '医保' and ddbh = '20210322P00098955DAREWAY'; select * from ipay.v_trade_info_yndz a where 1=1 and a.jysj >= '20210310000000' and a.jysj <= '20210310153113' and a.yhryxm = '刁静' and a.yhmc = '微信'; --超期表 select * from ipay.refund_detl where cjsj like '20210218%' and status = 'paid' cjsj between '20210218' and '20210218'; select * from ipay.overtime_refund where fqjysj between '20210126093414' and '20210126093914'; -- 创建视图(v_trade_info) 渠道对账 create or replace view v_trade_info as select distinct dt.tradeno, --平台订单号 dt.intradeno ddbh, --交易订单号(订单编号) dt.brxm, --病人姓名 dt.cardno brjzkh, --病人就诊卡号 dt.brsfzhm sfzhm, --病人身份证号码 dt.yhid, --支付银行 bk.yhjc qdmc, --渠道名称 bk.yhmc yhmc, --银行名称(实际的支付渠道) case bk.yhjc when '转账' then 'Transfer' when '广发银行' then 'CgbSmartPay' when '支付宝' then 'Alipay' when 'POS' then 'UnionPay' when '现金' then 'CashPay' when '医保' then 'Medicare' when '微信' then 'WeChat' end jyqdbs, --交易渠道标识 case dt.type when 'pay' then '支付' when 'refund' then '退款' end ywlx, --业务类型 nvl(dt.fqjysj,dt.jysj) as jlcjsj, --记录创建时间 dt.jysj, --支付时间 --dt.jyje, case dt.type when 'pay' then dt.jyje when 'refund' then -1*dt.jyje end jyje, --to_char(dt.jyje,'0.99') as jyje, --交易金额 gn.orgno mchid, --医院编号 case dt.paystate when 'paid' then '1' when 'repaid' then '1' when 'paying' then '2' when 'repaying' then '2' when 'refailed' then '0' when 'failed' then '0' when 'closed' then '2' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case dt.paystate when 'paid' then '已支付' when 'repaid' then '已退款' when 'paying' then '支付中' when 'repaying' then '退款中' when 'refailed' then '退款失败' when 'failed' then '支付失败' when 'closed' then '已关闭' else '未知' end jyztms, --交易状态描述 dt.tkintradeno, --退款原订单号 dt.czyxm yhryxm, --操作员姓名 dt.czybh yhrybh, --操作员编号 dt.zflx, --支付类型(0:充值,1:缴费) dt.terminalno jyzdbh, --交易终端编号 dt.merchantno jyshbh, --交易商户编号 dt.jyqd jyjz, --POS交易卡介质(医保,银联卡) dt.hisno hisno, -- his交易流水号 dt.ynkcode ynjyzt, --院内卡状态标识:ynjyzt对应于ynccode (0:成功,1:失败,2:未知) dt.jytj jytj --交易途径 from ipay.order_detl dt, ipay.bank_info bk, ipay.order_genl gn where dt.tradeno=gn.tradeno and dt.yhid=bk.yhid and (dt.cqtfbs <> '1' or dt.cqtfbs is null) and dt.paystate in ('paid','repaid','refailed','failed','closed'); -- 查询 院内对账 视图 select * from ipay.order_detl a where a.jysj like '20201224%'; select * from ipay.v_trade_info_yndz where jysj like '20201224%' and brjzkh = '060000018' order by jyqdbs ; select * from ipay.v_trade_info_yndz where jysj between '20200828000000' and '20200828240000'; --查询对账院内视图2.0 select * from ipay.v_trade_info_yndz where ddbh like '%' and yhrybh = '225' order by jysj desc; --对账院内视图2.0(已切换) create or replace view ipay.v_trade_info_yndz as select distinct dt.tradeno, --平台订单号 dt.intradeno ddbh,--交易订单号(订单编号) dt.hisno, --his调用流水号 dt.brxm, --病人姓名 dt.cardno brjzkh, --病人就诊卡号 dt.brsfzhm sfzhm, --病人身份证号码 dt.yhid, --支付银行/渠道 bk.yhjc qdmc, --支付银行/渠道名称 bk.bz yhmc, --银行名称(实际的支付渠道) case when dt.cqtfbs = '1' then 'Transfer' when instr(bk.yhjc, '可退金额') > 0 then 'SPCLQY' when instr(bk.yhjc, '广发') > 0 then 'CgbSmartPay' when instr(bk.yhjc, '支付宝') > 0 then 'Alipay' when instr(bk.yhjc, 'POS') > 0 then 'UnionPay' when instr(bk.yhjc, '现金') > 0 then 'CashPay' when instr(bk.yhjc, '医保') > 0 then 'Medicare' when dt.yhid = 'SYBMZ' then 'Medicare' when dt.yhid = 'SYBZY' then 'Medicare' when bk.yhjc = '异地门诊' then 'Medicare' when bk.yhjc = '异地住院' then 'Medicare' when instr(bk.yhjc, '微信') > 0 then 'WeChat' else 'Other' end jyqdbs, --交易渠道标识 case dt.type when 'pay' then '支付' when 'refund' then '退款' end ywlx, --业务类型 nvl(dt.fqjysj,dt.jysj) as jlcjsj, --记录创建时间 case when instr(bk.yhjc, '医保') > 0 then nvl(dt.ynjysj,dt.jysj) when dt.paystate = 'paid' then nvl(dt.ynjysj,dt.jysj) when dt.type ='refund' then nvl(dt.ynjysj,dt.jysj) else nvl(dt.ynjysj,'') end jysj, --支付时间 case dt.type when 'pay' then dt.jyje when 'refund' then -1*dt.jyje end jyje, --交易金额 --case when instr(bk.yhjc, '医保') > 0 and dt.type = 'pay' then (case when dt.zjlx = '0' then to_number(dt.zjhm) else to_number(dt.zjlx) end) --when instr(bk.yhjc, '医保') > 0 and dt.type = 'refund' then (case when dt.zjlx = '0' then -1*to_number(dt.zjhm) else -1*to_number(dt.zjlx) end) --else (case dt.type when 'pay' then dt.jyje when 'refund' then -1*dt.jyje end) end jyje, --交易金额 dt.ynkcode ynjyzt, --院内卡状态标识:ynjyzt对应于ynccode (0:成功,1:失败,2:未知) dt.ynkcode, gn.orgno mchid, --医院编号 case dt.paystate when 'paid' then '1' when 'repaid' then '1' when 'paying' then '2' when 'repaying' then '2' when 'refailed' then '0' when 'failed' then '0' when 'closed' then '2' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case dt.paystate when 'paid' then '已支付' when 'repaid' then '已退款' when 'paying' then '支付中' when 'repaying' then '退款中' when 'refailed' then '退款失败' when 'failed' then '支付失败' when 'closed' then '已关闭' else '未知' end jyztms, --交易状态描述 dt.tkintradeno yddbh, --退款原订单号 dt.brlxfs jyckh, --交易参考号(终端)、结算号id (医保) case when instr(bk.yhjc, 'POS') > 0 then dt.jym_ibank when bk.yhjc = '医保' then dt.jshid when bk.yhjc = '省医保门诊' then dt.jshid when bk.yhjc = '省医保住院' then dt.jshid when bk.yhjc = '异地门诊' then dt.jshid when bk.yhjc = '异地住院' then dt.jshid else '' end jylsh, --交易流水号(终端) dt.czyxm yhryxm, --操作员姓名 dt.czybh yhrybh, --操作员编号 dt.zflx, --支付类型(0:充值,1:缴费) dt.terminalno jyzdbh, --交易终端编号 dt.merchantno jyshbh, --交易商户编号、 住院流水号(医保) dt.jyqd jykjz, --POS交易卡介质(医保,银联卡) dt.jyfs, --交易方式 case dt.jytj when '2' then 'dwzfbshh' when '5' then 'gwi' else 'Ehis' end sbcsbm, --设备厂商编码 dt.jytj jyylx, --交易途径 nvl(dt.zjlx,'0') tcje, --统筹金额 nvl(dt.zjhm,'0') gzje --个账金额 from ipay.order_detl dt, ipay.bank_info bk, ipay.order_genl gn where dt.tradeno=gn.tradeno and dt.yhid=bk.yhid and dt.yhid != 'SPCLQY' and dt.paystate in ('paid','repaid','refailed','failed','closed') --测试,记得删除 --and bk.yhjc = '医保' and (dt.cqtfbs not in ('1','2') or dt.cqtfbs is null) --明细表剔除超期退费数据和超期转现金部分 union --超期退费数据(批量转账) select distinct '' tradeno, --超期退费订单号 refund.refundno ddbh ,-- (订单编号) refund.hisno hisno, --his调用流水号 refund.brxm, --病人姓名 refund.cardno brjzkh, --病人就诊卡号 refund.brsfzhm sfzhm, --病人身份证号码 'UNIONCARD' yhid, --支付银行/渠道 '超期' qdmc, --支付银行/渠道名称 '超期' yhmc, --银行名称(实际的支付渠道) 'Transfer' jyqdbs, --交易渠道标识 '退款' ywlx, --业务类型 nvl(refund.fqjysj,refund.jysj) as jlcjsj, --记录创建时间 refund.fqjysj jysj, --支付时间 -1*refund.jyje jyje, --交易金额 dtl.ynkcode ynjyzt, --院内卡状态标识:ynjyzt对应于ynccode (0:成功,1:失败,2:未知) dtl.ynkcode, dtl.mchid mchid, --医院编号 case refund.state when 'refund' then '1' when 'repaying' then '1' when 'repayings' then '1' when 'repaid' then '1' when 'refunding' then '1' when 'failed' then '0' when 'refailed' then '0' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case refund.state when 'refund' then '转账成功' when 'repaying' then '未审核' when 'repayings' then '审核通过,未复核' when 'repaid' then '审核通过,复核通过' when 'refunding' then '转账中' when 'failed' then '转账失败' when 'refailed' then '审核/复核不通过' else '未知' end jyztms, --交易状态描述 '' yddbh, --退款原订单号 refund.brlxfs jyckh, --交易参考号(银行卡号) refund.bryhkh jylsh, --交易流水号(银行卡号) refund.czyxm yhryxm, --操作员姓名 refund.czybh yhrybh, --操作员编号 '' zflx, --支付类型(0:充值,1:缴费) '' jyzdbh, --交易终端编号 '' jyshbh, --交易商户编号、 住院流水号(医保)dt.merchantno '' jykjz, --POS交易卡介质(医保,银联卡) '' jyfs, --交易方式 '' sbcsbm, --设备厂商编码 '' jyylx, --交易途径 '0' tcje, --统筹金额 '0' gzje --个账金额 from ipay.overtime_refund refund left join ( select refuns.refundno, refuns.mchid, dtl1.ynkcode from ipay.refund_detl refuns left join ipay.order_detl dtl1 on dtl1.refundtradeno = refuns.refundtradeno where dtl1.cqtfbs = '1' group by refuns.refundno, refuns.mchid, dtl1.ynkcode ) dtl on dtl.refundno = refund.refundno where refund.state in ('repaid', 'refund', 'refunding', 'repaying', 'repayings') --超期退费数据(转现金) union select distinct '' tradeno, --超期退费订单号 cash.refundno ddbh ,-- (订单编号) cash.hisno hisno, --his调用流水号 cash.brxm, --病人姓名 cash.cardno brjzkh, --病人就诊卡号 cash.brsfzhm sfzhm, --病人身份证号码 'XJZF' yhid, --支付银行/渠道 '现金' qdmc, --支付银行/渠道名称 '现金' yhmc, --银行名称(实际的支付渠道) 'CashPay' jyqdbs, --交易渠道标识 '退款' ywlx, --业务类型 nvl(cash.fqjysj,'') as jlcjsj, --记录创建时间 nvl(cash.jysj,cash.fqjysj) jysj, --支付时间 -1*cash.jyje jyje, --交易金额 dtlcash2.ynkcode ynjyzt, --院内卡状态标识:ynjyzt对应于ynccode (0:成功,1:失败,2:未知) dtlcash2.ynkcode, dtlcash2.mchid mchid, --医院编号 case cash.state when 'repaid' then '1' when 'refailed' then '0' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case cash.state when 'repaid' then '已退款(超期)' when 'refailed' then '退款失败(超期)' else '未知(超期)' end jyztms, --交易状态描述 '' yddbh, --退款原订单号 cash.brlxfs jyckh, --交易参考号(银行卡号) '' jylsh, --交易流水号(银行卡号) cash.czyxm yhryxm, --操作员姓名 cash.czybh yhrybh, --操作员编号 '' zflx, --支付类型(0:充值,1:缴费) '' jyzdbh, --交易终端编号 '' jyshbh, --交易商户编号、 住院流水号(医保)dt.merchantno '' jykjz, --POS交易卡介质(医保,银联卡) '' jyfs, --交易方式 '' sbcsbm, --设备厂商编码 '' jyylx, --交易途径 '0' tcje, --统筹金额 '0' gzje --个账金额 from ipay.overtocash_refund cash left join ( select refuns.refundno, refuns.mchid, dtlcash.ynkcode from ipay.refund_detl refuns left join ipay.order_detl dtlcash on dtlcash.refundtradeno = refuns.refundtradeno where dtlcash.cqtfbs = '2' group by refuns.refundno, refuns.mchid, dtlcash.ynkcode ) dtlcash2 on dtlcash2.refundno = cash.refundno where cash.state in ('repaid'); <file_sep>/dareway/重要sql/aa.sql prompt PL/SQL Developer import file prompt Created on 2021Äê6ÔÂ5ÈÕ by Wdf set feedback off set define off prompt Creating AODARCRECORDS... create table AODARCRECORDS ( aodid VARCHAR2(20) not null, archivingambm VARCHAR2(6) not null, declaredambm VARCHAR2(6) not null, declaredambmtime DATE not null ) ; alter table AODARCRECORDS add primary key (AODID); prompt Creating AODREGION... create table AODREGION ( aodid VARCHAR2(30) not null, regionid VARCHAR2(30) not null ) ; alter table AODREGION add primary key (AODID, REGIONID); prompt Creating AODSLAVETABLE... create table AODSLAVETABLE ( aodid VARCHAR2(20) not null, username VARCHAR2(40) not null, tablename VARCHAR2(40) not null ) ; alter table AODSLAVETABLE add primary key (USERNAME, TABLENAME); prompt Creating AODTENANT... create table AODTENANT ( aodid VARCHAR2(30) not null, tenantid VARCHAR2(30) not null ) ; alter table AODTENANT add primary key (AODID, TENANTID); prompt Creating AODVIEW... create table AODVIEW ( aodid VARCHAR2(20) not null, username VARCHAR2(40) not null, viewname VARCHAR2(40) not null ) ; alter table AODVIEW add primary key (AODID, USERNAME, VIEWNAME); prompt Creating AOI_RECORD... create table AOI_RECORD ( aodid VARCHAR2(20) not null, aoiid VARCHAR2(30) not null, regionid VARCHAR2(30) not null, tenantid VARCHAR2(30) not null ) ; alter table AOI_RECORD add primary key (AODID, AOIID); prompt Creating ARCAODDEFINE... create table ARCAODDEFINE ( aodid VARCHAR2(20) not null, arcdbid VARCHAR2(30) not null, beginmonth VARCHAR2(6) not null, endmonth VARCHAR2(6) not null ) ; alter table ARCAODDEFINE add primary key (AODID); prompt Creating ARCDBS... create table ARCDBS ( arcdbid VARCHAR2(30) not null, dbaddress VARCHAR2(200) not null, status VARCHAR2(20) not null ) ; alter table ARCDBS add primary key (ARCDBID); prompt Creating ARCHIVER... create table ARCHIVER ( aodid VARCHAR2(20) not null ) ; alter table ARCHIVER add primary key (AODID); prompt Creating ARCHIVINGROOM... create table ARCHIVINGROOM ( aodid VARCHAR2(40) not null, ts NUMBER(18) not null, archivingaoiid VARCHAR2(64), aoibeginbizmonth VARCHAR2(6), aoiendbizmonth VARCHAR2(6), suspend2time DATE, regionid VARCHAR2(10), tenantid VARCHAR2(30) ) ; alter table ARCHIVINGROOM add primary key (AODID); prompt Creating ASSERTNOTEMPTYCONSTRAINTS... create table ASSERTNOTEMPTYCONSTRAINTS ( username VARCHAR2(40) not null, tablename VARCHAR2(40) not null ) ; alter table ASSERTNOTEMPTYCONSTRAINTS add primary key (USERNAME, TABLENAME); prompt Creating ASSERTNOTEMPTYCONSTRAINTSLOG... create table ASSERTNOTEMPTYCONSTRAINTSLOG ( username VARCHAR2(40) not null, tablename VARCHAR2(40) not null, columnname VARCHAR2(40) not null ) ; alter table ASSERTNOTEMPTYCONSTRAINTSLOG add primary key (USERNAME, TABLENAME, COLUMNNAME); prompt Creating ASSERTNOTEMPTYTRIGGER... create table ASSERTNOTEMPTYTRIGGER ( username VARCHAR2(40) not null, tablename VARCHAR2(40) not null ) ; alter table ASSERTNOTEMPTYTRIGGER add primary key (USERNAME, TABLENAME); prompt Creating ASSERTNOTEMPTYTRIGGERLOG... create table ASSERTNOTEMPTYTRIGGERLOG ( username VARCHAR2(40) not null, tablename VARCHAR2(40) not null, columnname VARCHAR2(40) not null, assertnotemptytime DATE ) ; alter table ASSERTNOTEMPTYTRIGGERLOG add primary key (USERNAME, TABLENAME, COLUMNNAME); prompt Creating A_TRIGGER_PREVENT_EMPTY_COLUMN... create table A_TRIGGER_PREVENT_EMPTY_COLUMN ( username VARCHAR2(40) not null, tablename VARCHAR2(40) not null, columnname VARCHAR2(40) not null ) ; alter table A_TRIGGER_PREVENT_EMPTY_COLUMN add primary key (USERNAME, TABLENAME, COLUMNNAME); prompt Creating DDSBASE... create table DDSBASE ( ddsname VARCHAR2(30) not null, arcdbid VARCHAR2(30), ddszone_version VARCHAR2(20) not null, bigversion NUMBER(4) not null, smallversion NUMBER(4) not null ) ; alter table DDSBASE add primary key (DDSNAME); prompt Creating DDSLOGICALUSER... create table DDSLOGICALUSER ( ddslogicalusername VARCHAR2(30) not null, ddslogicalusertype VARCHAR2(30) not null ) ; alter table DDSLOGICALUSER add primary key (DDSLOGICALUSERNAME); prompt Creating DDSPHYSICALUSER... create table DDSPHYSICALUSER ( ddsphysicalusername VARCHAR2(30) not null, ddslogicalusername VARCHAR2(30) not null, region VARCHAR2(20) ) ; alter table DDSPHYSICALUSER add primary key (DDSPHYSICALUSERNAME); prompt Creating DEDP... create table DEDP ( dedp NUMBER(2) not null ) ; alter table DEDP add primary key (DEDP); prompt Creating FORBIDDEN_DDAENGINE_VERSION... create table FORBIDDEN_DDAENGINE_VERSION ( bigversion NUMBER(4) not null, smallversion NUMBER(4) not null, register VARCHAR2(20) ) ; alter table FORBIDDEN_DDAENGINE_VERSION add primary key (BIGVERSION, SMALLVERSION); prompt Creating REGION... create table REGION ( regionid VARCHAR2(30) not null, regionname VARCHAR2(40) ) ; alter table REGION add primary key (REGIONID); prompt Creating REGIONUSER... create table REGIONUSER ( regionuser VARCHAR2(40) not null ) ; alter table REGIONUSER add primary key (REGIONUSER); prompt Creating RELATION_ALTERATION_RECORD... create table RELATION_ALTERATION_RECORD ( username VARCHAR2(30) not null, relationname VARCHAR2(30) not null, ts NUMBER(4), md5 VARCHAR2(40) not null ) ; alter table RELATION_ALTERATION_RECORD add primary key (USERNAME, RELATIONNAME); prompt Creating SEQUENCE_INFO... create table SEQUENCE_INFO ( sequencename VARCHAR2(30) not null, minvalue_ VARCHAR2(20) not null, maxvalue_ VARCHAR2(20) not null, currentvalue VARCHAR2(20) not null, cycle_ VARCHAR2(1) not null, increment_ NUMBER(2) not null ) ; alter table SEQUENCE_INFO add primary key (SEQUENCENAME); prompt Creating STORED_PROCEDURE... create table STORED_PROCEDURE ( spname VARCHAR2(120) not null, valuetype VARCHAR2(1) not null, paratypelist VARCHAR2(10) ) ; alter table STORED_PROCEDURE add primary key (SPNAME); prompt Creating SYNCHFRIENDTABLE... create table SYNCHFRIENDTABLE ( aodid VARCHAR2(20) not null, username VARCHAR2(40) not null, tablename VARCHAR2(40) not null, isaugmenter VARCHAR2(1) not null, uniquecolumns VARCHAR2(100) ) ; alter table SYNCHFRIENDTABLE add primary key (USERNAME, TABLENAME); prompt Creating SYNCHFRIENDVIEW... create table SYNCHFRIENDVIEW ( aodid VARCHAR2(20) not null, username VARCHAR2(40) not null, viewname VARCHAR2(40) not null ) ; alter table SYNCHFRIENDVIEW add primary key (USERNAME, VIEWNAME); prompt Creating SYNCHTABLEARCRECORDS... create table SYNCHTABLEARCRECORDS ( username VARCHAR2(40) not null, tablename VARCHAR2(40) not null, arcdbid VARCHAR2(30) not null, synchdate VARCHAR2(6) ) ; alter table SYNCHTABLEARCRECORDS add primary key (USERNAME, TABLENAME); prompt Creating TENANT... create table TENANT ( tenantid VARCHAR2(30) not null, tenantname VARCHAR2(40), enabled VARCHAR2(1) not null ) ; alter table TENANT add primary key (TENANTID); prompt Creating TENANTUSER... create table TENANTUSER ( username VARCHAR2(40) not null ) ; alter table TENANTUSER add primary key (USERNAME); prompt Creating TRUST_NOT_EMPTY_COLUMN... create table TRUST_NOT_EMPTY_COLUMN ( username VARCHAR2(40) not null, tablename VARCHAR2(40) not null, columnname VARCHAR2(40) not null ) ; alter table TRUST_NOT_EMPTY_COLUMN add primary key (USERNAME, TABLENAME, COLUMNNAME); prompt Creating UNARCHIVINGPROTECT... create table UNARCHIVINGPROTECT ( aodid VARCHAR2(20) not null, aoiid VARCHAR2(64) not null, protect2month VARCHAR2(6) not null ) ; alter table UNARCHIVINGPROTECT add primary key (AODID, AOIID); prompt Creating UNARCHIVINGROOM... create table UNARCHIVINGROOM ( aodid VARCHAR2(40) not null, ts NUMBER(18) not null, unarchivingaoiid VARCHAR2(64), fromarcdbid VARCHAR2(30), regionid VARCHAR2(30), tenantid VARCHAR2(30) ) ; alter table UNARCHIVINGROOM add primary key (AODID); prompt Loading AODARCRECORDS... prompt Table is empty prompt Loading AODREGION... prompt Table is empty prompt Loading AODSLAVETABLE... prompt Table is empty prompt Loading AODTENANT... prompt Table is empty prompt Loading AODVIEW... prompt Table is empty prompt Loading AOI_RECORD... prompt Table is empty prompt Loading ARCAODDEFINE... prompt Table is empty prompt Loading ARCDBS... prompt Table is empty prompt Loading ARCHIVER... prompt Table is empty prompt Loading ARCHIVINGROOM... prompt Table is empty prompt Loading ASSERTNOTEMPTYCONSTRAINTS... prompt Table is empty prompt Loading ASSERTNOTEMPTYCONSTRAINTSLOG... prompt Table is empty prompt Loading ASSERTNOTEMPTYTRIGGER... prompt Table is empty prompt Loading ASSERTNOTEMPTYTRIGGERLOG... prompt Table is empty prompt Loading A_TRIGGER_PREVENT_EMPTY_COLUMN... prompt Table is empty prompt Loading DDSBASE... insert into DDSBASE (ddsname, arcdbid, ddszone_version, bigversion, smallversion) values ('dataSource', null, '1.8', 1, 8); commit; prompt 1 records loaded prompt Loading DDSLOGICALUSER... insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('qs_cb', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('qs_ws', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('mtssys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('blake', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('adams', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('odm', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('odm_mtr', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('qs_adm', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('jones', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('qs_cbadm', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('qs_cs', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('tsmsys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('qs_es', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('dmsys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('clark', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('qs_os', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('wksys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('qs', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('anonymous', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('ctxsys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('dbsnmp', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('exfsys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('mddata', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('mdsys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('mgmt_view', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('olapsys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('ordplugins', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('outln', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('ordsys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('scott', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('si_informtn_schema', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('sys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('sysman', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('system', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('wktest', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('wmsys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('xdb', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('owbsys_audit', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('owbsys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('appqossys', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('orddata', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('spatial_csw_admin_usr', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('spatial_wfs_admin_usr', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('oracle_ocm', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('xs$null', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('apex_public_user', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('flows_files', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('apex_030200', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('bi', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('pm', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('ix', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('sh', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('dip', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('oe', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('hr', 'dbmssysuser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('activemq', 'accessibleouteruser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('apolloconfigdb', 'accessibleouteruser'); insert into DDSLOGICALUSER (ddslogicalusername, ddslogicalusertype) values ('apolloportaldb', 'accessibleouteruser'); commit; prompt 58 records loaded prompt Loading DDSPHYSICALUSER... insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('qs_cb', 'qs_cb', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('qs_ws', 'qs_ws', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('mtssys', 'mtssys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('blake', 'blake', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('adams', 'adams', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('odm', 'odm', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('odm_mtr', 'odm_mtr', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('qs_adm', 'qs_adm', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('jones', 'jones', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('qs_cbadm', 'qs_cbadm', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('qs_cs', 'qs_cs', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('tsmsys', 'tsmsys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('qs_es', 'qs_es', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('dmsys', 'dmsys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('clark', 'clark', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('qs_os', 'qs_os', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('wksys', 'wksys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('qs', 'qs', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('anonymous', 'anonymous', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('ctxsys', 'ctxsys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('dbsnmp', 'dbsnmp', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('exfsys', 'exfsys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('mddata', 'mddata', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('mdsys', 'mdsys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('mgmt_view', 'mgmt_view', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('olapsys', 'olapsys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('ordplugins', 'ordplugins', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('outln', 'outln', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('ordsys', 'ordsys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('scott', 'scott', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('si_informtn_schema', 'si_informtn_schema', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('sys', 'sys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('sysman', 'sysman', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('system', 'system', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('wktest', 'wktest', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('wmsys', 'wmsys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('xdb', 'xdb', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('owbsys_audit', 'owbsys_audit', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('owbsys', 'owbsys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('appqossys', 'appqossys', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('orddata', 'orddata', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('spatial_csw_admin_usr', 'spatial_csw_admin_usr', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('spatial_wfs_admin_usr', 'spatial_wfs_admin_usr', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('oracle_ocm', 'oracle_ocm', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('xs$null', 'xs$null', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('apex_public_user', 'apex_public_user', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('flows_files', 'flows_files', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('apex_030200', 'apex_030200', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('bi', 'bi', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('pm', 'pm', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('ix', 'ix', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('sh', 'sh', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('dip', 'dip', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('oe', 'oe', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('hr', 'hr', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('activemq', 'activemq', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('apolloconfigdb', 'apolloconfigdb', null); insert into DDSPHYSICALUSER (ddsphysicalusername, ddslogicalusername, region) values ('apolloportaldb', 'apolloportaldb', null); commit; prompt 58 records loaded prompt Loading DEDP... insert into DEDP (dedp) values (1); commit; prompt 1 records loaded prompt Loading FORBIDDEN_DDAENGINE_VERSION... insert into FORBIDDEN_DDAENGINE_VERSION (bigversion, smallversion, register) values (1, 0, '1.19'); insert into FORBIDDEN_DDAENGINE_VERSION (bigversion, smallversion, register) values (1, 1, '1.19'); commit; prompt 2 records loaded prompt Loading REGION... prompt Table is empty prompt Loading REGIONUSER... prompt Table is empty prompt Loading RELATION_ALTERATION_RECORD... insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_realtime_monitor', 0, '0cd403c48b699bfa10dc2b36716e193c'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'reconresult_detail', 0, 'fbc6b5118006f8acded2583f7e8cfa59'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'org_info', 0, '095ab4931d535a4014d6fc8120c17f63'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'org_bank', 0, '5599f25a1ac4db772afed2121e04e774'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'mongodb_para', 0, 'e8732c31265e9c7c93c075d20f92fd00'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'address_book', 0, 'cd51b3d213f13b77b6feec0584415cb9'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'realtime_monitor', 0, 'a2946b4d58fb7ca28367fc2eb5418d12'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'reconfile_redownload', 0, '8b5f1ad06cb48dd732d0bc5209a9ad47'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'msg_push', 0, 'ef22d9ef1513ac5e9d843ffe8e905c07'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'monitor_config', 0, '4315886e77eea8c75f3d742b6bcf0852'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'arrivalaccount_statistics', 0, 'cd091652a48e66f3705bf7e8681abcef'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'param_dict', 0, '9c5abf698bcc02165ae70d080e699729'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'inst_info', 0, '41315fc3aea09d953cc6d45a89f859a1'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'accountable_statistics', 0, '5981647beeea17ab1be7a7e6951cef35'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'channel_account', 0, '4b42d057c67a0822cafb302aaf0764bc'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'channel_info', 0, '47c60543f9023d1663b8ff38e0727c7a'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'operation_log', 0, '022d7ee7361b95d35323a96261c806a9'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'medicare_transflow', 0, '8b7e9e3cc74d42d76b47fa906ff12c66'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'unionpay_transflow', 0, '57709299b593e57dd25e6976cc703a06'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'alipay_transflow', 0, 'e21bf7cd1068754a8147e6f15a9db507'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_equipment_factory', 0, '0ffe8ccc984aaa4e66c520abfdd8506e'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'v_trade_info_yndz', 0, '434c5ae8d4c489276ae0573f1fb9b45f'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'cashpay_transflow', 0, '89d4d70fa66bda5798ec2928689fe34a'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'abnormal_order_detl', 0, '398b62a23d982d84048e6e5dadc96fec'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'order_gen_det_list', 0, '00b94dc4d20ad7721722b654bca7060a'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'bank_info', 0, '968b625e38a9349b0f9007147041b686'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'order_genl', 0, '7cc78d0ee84d7b0919c945d37313eaa4'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'order_detl', 0, '883a5aca2236820076acc01effbcb972'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'his_transflow', 0, 'f84c0b9651c2a9b1ceea03663b4f6b91'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'channel_reconresult', 0, 'ce4925cbe14a7901902d1dc575500791'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'reconhis_statistics', 0, '0ef7f068ef4cecd269ab1526060de43e'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'sdsz_trade_info', 0, '73106276e597120b131b1fd3d5d5255c'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'realtime_alarm', 0, '7be85bc3e150ad3116b7bc86cc1f3fc1'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'order_settlepara', 0, 'd5b9c04b7586e4cd7393e4952901ea0d'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_reconresult_detail', 0, '18044cc158c3a7382025c20c792460a2'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_his_transflow', 0, '03d41e8fd7bcf3feaf52f090bcb94d4f'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_equipment_transflow', 0, '50fcb1fea2af4750d032c4cc334f7ec9'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'wechat_transflow', 0, 'e21bf7cd1068754a8147e6f15a9db507'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_factory_reconresult', 0, 'a8e5b084a765a70dd86d7e176b40c6b3'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_reconfile_redownload', 0, '9bb86f3c4356deaa61be9d27839a96fc'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'ehcpay_transflow', 0, 'e21bf7cd1068754a8147e6f15a9db507'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'unionpayomni_transflow', 0, '5b8612adab1dc1a17c32d2838ec8bb85'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'overtocash_refund', 0, '25367b5869917910cb753c97bb0689f5'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'refund_detl', 0, '824ef3ac52f27154cdf0a49ed90c1af0'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'ucompos_management_info', 0, '5c226c0f2c35dbbf058da3fb430ef57c'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_equipment_reconresult', 0, 'ce19b8961f4fed96dc1ac7206e6c4835'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_equipment_info', 0, 'b4842282a1a88e9a558a87d9a7efed6e'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'reconfile_info', 0, 'c4dcb856602feb7491bd2557d19398db'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_reconfile_info', 0, '56c374fbf0231ecf47e89ddcd6e844a1'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'gf_banktrans', 0, '5180594f0bfbae213fd39e9613d1b8bb'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('hengine', 'pt_template_info', 0, '721bbda2e8f39461b9351ef17e1798b5'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('hengine', 'pt_template_body', 0, '5e3b8b1714025d8bccfdfccafc6e17b7'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('hengine', 'pt_template_printer', 0, '301e3e7b4b81924e37fd45f4f8b88f70'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'm_his_transflow', 0, '6fc7933404f338af84e964195ac07061'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'm_equipment_transflow', 0, 'cd287cae5bd9a35cdf4c0d25c89e9b3b'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'ucompos_trade_info', 0, 'ce50a1f048e6dc7e8024e98ee921c3f7'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ddszone', 'forbidden_ddaengine_version', 0, 'a8a62c3c07a186dc572f2aca289ee8c1'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ddszone', 'ddsbase', 0, '5edbb178ab8155b9e84d88f34cbdcd43'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ei', 'invoice_record', 0, 'b4297eea2e92fc05e6e46f918730adef'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('ipay', 'overtime_refund', 0, '8ab154c25da74402a746106a1ea883b0'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'cgbsmartpay_transflow', 0, 'd972c6db5968a4b33f5c1c984dfff06d'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'e_recon_history', 0, '4d4b5fe5d88e0b1201025ca553c8c7fb'); insert into RELATION_ALTERATION_RECORD (username, relationname, ts, md5) values ('urp', 'gf_banktrans_accounts', 0, 'ddc8185822fdbe2ff92832133e3e67fb'); commit; prompt 63 records loaded prompt Loading SEQUENCE_INFO... insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('ipay_batchno_seq', '1', '9999999999', '435', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('dstid', '1', '9999999999999', '1', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('deleteSign', '1', '9999999999999', '1', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('tsid', '1', '9999', '1', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('ipay_tradeno_seq', '1', '99999999', '294792', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('urp_csid', '1', '999999999', '100367', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('seq_dccs_directory', '10000000', '99999999', '10000150', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('seq_dccs_matchResult', '10000000', '99999999', '10000913', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('seq_pms_medical_stu_dire', '10000000', '99999999', '10000090', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('seq_pms_medi_item_dire', '10000000', '99999999', '10000009', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('seq_pms_m_consumble_dire', '10000000', '99999999', '10000025', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('ipay_enseqno_seq', '1', '9999999999', '384', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('ipay_refundno_seq', '1', '9999999999', '7244', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('seq_hengine_miid', '10000000', '99999999', '10000398', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('seq_hengine_template_id', '10000000', '99999999', '10000024', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('seq_hengine_tpid', '10000000', '99999999', '10000023', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('ei_busno_seq', '1', '99999999', '24', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('ipay_intradeno_seq', '1', '9999999999', '216453', '1', 1); insert into SEQUENCE_INFO (sequencename, minvalue_, maxvalue_, currentvalue, cycle_, increment_) values ('ipay_refundtradeno_seq', '1', '9999999999', '67034', '1', 1); commit; prompt 19 records loaded prompt Loading STORED_PROCEDURE... prompt Table is empty prompt Loading SYNCHFRIENDTABLE... prompt Table is empty prompt Loading SYNCHFRIENDVIEW... prompt Table is empty prompt Loading SYNCHTABLEARCRECORDS... prompt Table is empty prompt Loading TENANT... prompt Table is empty prompt Loading TENANTUSER... prompt Table is empty prompt Loading TRUST_NOT_EMPTY_COLUMN... prompt Table is empty prompt Loading UNARCHIVINGPROTECT... prompt Table is empty prompt Loading UNARCHIVINGROOM... prompt Table is empty set feedback on set define on prompt Done. <file_sep>/dareway/kettle-药店.sql -- 查询所有表以及备注 select * from user_tab_comments; -- 医保局信息表 select * From Bt_Medicare_Bureau; --for update truncate table Bt_Medicare_Bureau; -- 明细表 select a.yybm 药店编码, (select b.jgmc from mhs5.odr_org_info b where a.yybm = b.jgid) 药店名称, a.sbjgbh 医保局编码, (select c.sbjgmc from mhs5.si_hosp_rela c where a.yybm = c.yybm and a.sbjgbh = c.sbjgbh) 医保局名称, a.xm 姓名, a.grbh 个人编号, (nvl ((select bz from mhs5.channel_no_gl d where a.channel_no = d.channel_no),'社保卡')) 结算方式, a.zje 交易金额, a.scsj 交易时间, 0 统筹金额, a.grzhzf 个账金额, a.xjzf 线自费金额, a.jshid 结算号, a.zdlsh 流水号 from mhs5.dips_order a where a.yybm = '012124' and a.statecode = '03' and to_char(a.scsj, 'yyyymm') = '202006'; -- 1、药店编码 012124; -- 明细表 201910 select a.yybm 药店编码, (select b.jgmc from mhs5.odr_org_info b where a.yybm = b.jgid) 药店名称, a.sbjgbh 医保局编码, (select c.sbjgmc from mhs5.si_hosp_rela c where a.yybm = c.yybm and a.sbjgbh = c.sbjgbh) 医保局名称, a.xm 姓名, a.grbh 个人编号, (nvl ((select bz from mhs5.channel_no_gl d where a.channel_no = d.channel_no),'社保卡')) 结算方式, a.zje 交易金额, a.scsj 交易时间, -- to_char(a.scsj, 'yyyymm') 时间, 0 统筹金额, a.grzhzf 个账金额, a.xjzf 线自费金额, a.jshid 结算号, a.zdlsh 流水号 from mhs5.dips_order a where a.yybm = '012124' and a.statecode = '03' and to_char(a.scsj, 'yyyymm') = '202002'; --dips_order 表 select * from mhs5.dips_order -- 漱玉对账汇总表 201910 select a.yybm 药店编码, (select b.jgmc from mhs5.odr_org_info b where a.yybm = b.jgid) 药店名称, a.sbjgbh 医保局编码, (select c.sbjgmc from mhs5.si_hosp_rela c where a.yybm = c.yybm and a.sbjgbh = c.sbjgbh) 医保局名称, count(1) 总笔数, sum(nvl(a.zje, 0)) 总金额, sum(nvl(a.grzhzf, 0)) 个账总金额, sum(nvl(a.grzhzf, 0)) * 0.05 扣除质保金, sum(nvl(a.grzhzf, 0)) * 0.95 实际拨付金额, to_char(a.czsj, 'yyyymm') 汇总年月 from (select yybm,sbjgbh,statecode,scsj czsj,zje,grzhzf from mhs5.dips_order where statecode ='03' union select yybm,sbjgbh,statecode,cxsj czsj,-abs(zje) zje,-abs(grzhzf) grzhzf from mhs5.dips_order where statecode ='06' and to_char(scsj,'yyyymm') != to_char(cxsj,'yyyymm') )a where a.yybm = '012124' and to_char(a.czsj, 'yyyymm') = '202003' group by a.sbjgbh, a.yybm,to_char(a.czsj, 'yyyymm') -- 医保定点 汇总表 md_summary select * from md_summary --truncate table md_summary -- 医保定点 明细表 md_details select * from md_details order by jysj desc; -- 关联查询测试 select d.jysj ,s.ddhzid,s.hzny from md_details d left join md_summary s on d.ddhzid = s.ddhzid; select sum(m.jyje) from md_details m where m.ddhzid = 'C8E98CB60440000177B1B1BA1BF0102B' --truncate table md_details -- 基础表 机构表 select * from bt_inst_info for update -- 基础表 机构 门店表 select * from bt_inst_store for update -- 基础表 医保局表 select * from mc_medicare_bureau <file_sep>/dareway/重要sql/查询pos金额在银联交易中--通过终端号.sql --查询所有的社保终端号 select csz from param_dict dict where 1=1 and dict.cslx = 'SbPosShh' and dict.zt = '0'; -- 查询pos社保交易的交易金额 手续费 -- 银联总金额中 减掉这部分 手续费加到医保的手续费中 select sum(yl.jyje) jyje, sum(yl.sxf), sxf from urp.Unionpay_Transflow yl where 1 = 1 and yl.shbh in (select csz as zdbh from param_dict dict where 1 = 1 and dict.cslx = 'SbPosShh' and dict.zt = '0') and yl.dzrq = '' and yl.sfsc = '' -- 医保的终端号 86315097 86315098 86315099 86315100 86315101 86315102 86396851 86396852 86396853 86396854 <file_sep>/dareway/重要sql/URP-清除数据.sql truncate table urp.alipay_transflow; truncate table urp.cgbsmartpay_transflow; truncate table urp.medicare_transflow; truncate table urp.his_transflow; truncate table urp.wechat_transflow; truncate table urp.unionpay_transflow; truncate table urp.cashpay_transflow; truncate table urp.UCOMPOS_TRADE_INFO; truncate table urp.RECONRESULT_DETAIL; truncate table urp.RECONHIS_STATISTICS; truncate table urp.RECONFILE_REDOWNLOAD; truncate table urp.RECONFILE_INFO; truncate table urp.REALTIME_ALARM; truncate table urp.OPERATION_LOG; truncate table urp.M_HIS_TRANSFLOW; truncate table urp.M_EQUIPMENT_TRANSFLOW; truncate table urp.MSG_PUSH; truncate table urp.GF_BANKTRANS_ACCOUNTS; truncate table urp.Gf_Banktrans; truncate table urp.E_RECON_HISTORY; truncate table urp.e_Equipment_Reconresult; truncate table urp.E_RECONFILE_REDOWNLOAD; truncate table urp.E_RECONFILE_INFO; truncate table urp.E_HIS_TRANSFLOW; truncate table urp.E_FACTORY_RECONRESULT; truncate table urp.E_EQUIPMENT_TRANSFLOW; truncate table urp.E_EQUIPMENT_RECONRESULT; truncate table urp.e_equipment_factory; truncate table urp.CHANNEL_RECONRESULT; truncate table urp.CGBSMARTPAY_TRANSFLOW; truncate table urp.ARRIVALACCOUNT_STATISTICS; truncate table urp.ACCOUNTABLE_STATISTICS; truncate table urp.ABCPAY_TRANSFLOW; truncate table urp.e_Reconresult_Detail; truncate table urp.param_dict; truncate table urp.UCOMPOS_LOG_INFO; truncate table urp.E_EQUIPMENT_INFO; truncate table urp.INST_INFO; truncate table urp.address_book; truncate table urp.channel_info; <file_sep>/dareway/2021-1/urp-userObject.sql ------------------------------------------- -- Export file for user URP -- -- Created by Wdf on 2021/1/28, 15:46:31 -- ------------------------------------------- spool urp-userObject.log prompt prompt Creating table ABCPAY_TRANSFLOW prompt =============================== prompt create table URP.ABCPAY_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50), jylsh VARCHAR2(50), qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(50) not null, zdhm VARCHAR2(50), spmc VARCHAR2(100), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50) ) ; comment on table URP.ABCPAY_TRANSFLOW is '农行网付对账流水表'; comment on column URP.ABCPAY_TRANSFLOW.lsid is '农行网付流水主键ID'; comment on column URP.ABCPAY_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.ABCPAY_TRANSFLOW.shbh is '商户编号'; comment on column URP.ABCPAY_TRANSFLOW.zdbh is '终端编号'; comment on column URP.ABCPAY_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.ABCPAY_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.ABCPAY_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.ABCPAY_TRANSFLOW.yjylsh is '原交易流水号/原交易订单号:交易为后续类交易时有值'; comment on column URP.ABCPAY_TRANSFLOW.shddh is '商户订单号'; comment on column URP.ABCPAY_TRANSFLOW.zdhm is '账单号码'; comment on column URP.ABCPAY_TRANSFLOW.spmc is '商品名称'; comment on column URP.ABCPAY_TRANSFLOW.jysj is '交易时间'; comment on column URP.ABCPAY_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.ABCPAY_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.ABCPAY_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.ABCPAY_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.ABCPAY_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.ABCPAY_TRANSFLOW.jybz is '交易备注'; comment on column URP.ABCPAY_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.ABCPAY_TRANSFLOW.dzrq is '对账日期'; comment on column URP.ABCPAY_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.ABCPAY_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.ABCPAY_TRANSFLOW.jgbm is '机构编码'; comment on column URP.ABCPAY_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.ABCPAY_TRANSFLOW.bly1 is '保留域1'; comment on column URP.ABCPAY_TRANSFLOW.bly2 is '保留域2'; comment on column URP.ABCPAY_TRANSFLOW.bly3 is '保留域3'; comment on column URP.ABCPAY_TRANSFLOW.dzbh is '对账编号'; alter table URP.ABCPAY_TRANSFLOW add constraint ABCPAY_PRIMARYKEY primary key (LSID); prompt prompt Creating table ACCOUNTABLE_STATISTICS prompt ===================================== prompt create table URP.ACCOUNTABLE_STATISTICS ( qdzhydzid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32) not null, ydzzje NUMBER(12,2) not null, qdzje NUMBER(12,2), dzrq DATE not null, jlcjsj TIMESTAMP(6) not null, dzbs VARCHAR2(2) not null, dzwhfjmc VARCHAR2(50), dzwhfjbclj VARCHAR2(100), dzwhclbz VARCHAR2(100), dzwhsj TIMESTAMP(6), dzwhr VARCHAR2(20), dzsj TIMESTAMP(6), bz VARCHAR2(100), sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.ACCOUNTABLE_STATISTICS is '应到账统计表'; comment on column URP.ACCOUNTABLE_STATISTICS.qdzhydzid is '渠道账户应到账主键ID'; comment on column URP.ACCOUNTABLE_STATISTICS.qdzhid is '渠道账户主键ID'; comment on column URP.ACCOUNTABLE_STATISTICS.ydzzje is '应到账总金额(支持随应到账处理变化)'; comment on column URP.ACCOUNTABLE_STATISTICS.qdzje is '渠道总金额(以HIS流水统计)'; comment on column URP.ACCOUNTABLE_STATISTICS.dzrq is '对账日期'; comment on column URP.ACCOUNTABLE_STATISTICS.jlcjsj is '账户应到账记录创建时间'; comment on column URP.ACCOUNTABLE_STATISTICS.dzbs is '到账标识(1:已到账,0:未到账)'; comment on column URP.ACCOUNTABLE_STATISTICS.dzwhfjmc is '到账维护附件名称'; comment on column URP.ACCOUNTABLE_STATISTICS.dzwhfjbclj is '到账维护附件保存路径'; comment on column URP.ACCOUNTABLE_STATISTICS.dzwhclbz is '到账维护处理备注'; comment on column URP.ACCOUNTABLE_STATISTICS.dzwhsj is '到账维护时间'; comment on column URP.ACCOUNTABLE_STATISTICS.dzwhr is '到账维护人'; comment on column URP.ACCOUNTABLE_STATISTICS.dzsj is '到账时间'; comment on column URP.ACCOUNTABLE_STATISTICS.bz is '备注'; comment on column URP.ACCOUNTABLE_STATISTICS.sfsc is '是否删除(1:是,0:否)'; comment on column URP.ACCOUNTABLE_STATISTICS.bly1 is '保留域1'; comment on column URP.ACCOUNTABLE_STATISTICS.bly2 is '保留域2'; comment on column URP.ACCOUNTABLE_STATISTICS.bly3 is '保留域3 '; create index URP.QDZHID_DZRQ_SFSC on URP.ACCOUNTABLE_STATISTICS (DZRQ, SFSC, QDZHID); alter table URP.ACCOUNTABLE_STATISTICS add constraint ACCOUNTABLE_STATISTICS_PK primary key (QDZHYDZID); prompt prompt Creating table ADDRESS_BOOK prompt =========================== prompt create table URP.ADDRESS_BOOK ( txlid VARCHAR2(32) default sys_guid() not null, xm VARCHAR2(30) not null, xb VARCHAR2(2), sjhm VARCHAR2(11) not null, ghhm VARCHAR2(20), dzyx VARCHAR2(30) not null, wxh VARCHAR2(30), wxpzid VARCHAR2(32), openid VARCHAR2(50), unionid VARCHAR2(50), csrq VARCHAR2(20), sfzh VARCHAR2(18), yhbq VARCHAR2(2), ssks VARCHAR2(50), sfsc VARCHAR2(2) default 0 not null, jlssr VARCHAR2(20), jgbm VARCHAR2(15) not null, jlcjsj TIMESTAMP(6) default sysdate not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6) default sysdate not null, zhxgr VARCHAR2(20), bz VARCHAR2(100), bly VARCHAR2(50), push VARCHAR2(10) default 0 ) ; comment on table URP.ADDRESS_BOOK is '通讯录表'; comment on column URP.ADDRESS_BOOK.txlid is '通讯录主键Id'; comment on column URP.ADDRESS_BOOK.xm is '姓名'; comment on column URP.ADDRESS_BOOK.xb is '性别(0:男,1:女)'; comment on column URP.ADDRESS_BOOK.sjhm is '手机号码'; comment on column URP.ADDRESS_BOOK.ghhm is '固定电话号码'; comment on column URP.ADDRESS_BOOK.dzyx is '电子邮箱'; comment on column URP.ADDRESS_BOOK.wxh is '微信号'; comment on column URP.ADDRESS_BOOK.wxpzid is '微信配置表主键Id'; comment on column URP.ADDRESS_BOOK.openid is '指定微信公众号下的个人openId'; comment on column URP.ADDRESS_BOOK.unionid is '指定微信公众号下的个人unionid'; comment on column URP.ADDRESS_BOOK.csrq is '出生日期'; comment on column URP.ADDRESS_BOOK.sfzh is '身份证号'; comment on column URP.ADDRESS_BOOK.yhbq is '用户标签(同事、朋友……)'; comment on column URP.ADDRESS_BOOK.ssks is '所属科室'; comment on column URP.ADDRESS_BOOK.sfsc is '是否删除(0:否,1:是)'; comment on column URP.ADDRESS_BOOK.jlssr is '记录所属人(系统登录名:用于个人维护通信录)'; comment on column URP.ADDRESS_BOOK.jgbm is '所属机构'; comment on column URP.ADDRESS_BOOK.jlcjsj is '记录创建时间'; comment on column URP.ADDRESS_BOOK.cjr is '创建人(系统登录名)'; comment on column URP.ADDRESS_BOOK.zhxgsj is '最后修改时间'; comment on column URP.ADDRESS_BOOK.zhxgr is '最后修改人'; comment on column URP.ADDRESS_BOOK.bz is '备注'; comment on column URP.ADDRESS_BOOK.bly is '保留域'; comment on column URP.ADDRESS_BOOK.push is '推送人标识(0:不推送,1推送)设成推送后,有了异常信息便会推送给他'; alter table URP.ADDRESS_BOOK add constraint ADDRESS_BOOK_PRIMARYKEY primary key (TXLID); prompt prompt Creating table ALIPAY_TRANSFLOW prompt =============================== prompt create table URP.ALIPAY_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50), jylsh VARCHAR2(50), qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30), zdhm VARCHAR2(50), spmc VARCHAR2(100), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50), ejbs VARCHAR2(15), sxf NUMBER(12,2) default 0.00 not null, qsje NUMBER(12,2) default 0.00, qsrq VARCHAR2(20) ) ; comment on table URP.ALIPAY_TRANSFLOW is '支付宝交易流水表'; comment on column URP.ALIPAY_TRANSFLOW.lsid is '支付宝流水主键ID'; comment on column URP.ALIPAY_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.ALIPAY_TRANSFLOW.shbh is '商户编号'; comment on column URP.ALIPAY_TRANSFLOW.zdbh is '终端编号'; comment on column URP.ALIPAY_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.ALIPAY_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.ALIPAY_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.ALIPAY_TRANSFLOW.yjylsh is '原交易流水号:交易为后续类交易时有值'; comment on column URP.ALIPAY_TRANSFLOW.shddh is '商户订单号'; comment on column URP.ALIPAY_TRANSFLOW.zdhm is '账单号码'; comment on column URP.ALIPAY_TRANSFLOW.spmc is '商品名称'; comment on column URP.ALIPAY_TRANSFLOW.jysj is '交易时间'; comment on column URP.ALIPAY_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.ALIPAY_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.ALIPAY_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.ALIPAY_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.ALIPAY_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.ALIPAY_TRANSFLOW.jybz is '交易备注'; comment on column URP.ALIPAY_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.ALIPAY_TRANSFLOW.dzrq is '对账日期'; comment on column URP.ALIPAY_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.ALIPAY_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.ALIPAY_TRANSFLOW.jgbm is '机构编码'; comment on column URP.ALIPAY_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.ALIPAY_TRANSFLOW.bly1 is '保留域1'; comment on column URP.ALIPAY_TRANSFLOW.bly2 is '保留域2'; comment on column URP.ALIPAY_TRANSFLOW.bly3 is '保留域3->就诊卡号'; comment on column URP.ALIPAY_TRANSFLOW.dzbh is '对账编号'; comment on column URP.ALIPAY_TRANSFLOW.ejbs is '二级标识'; comment on column URP.ALIPAY_TRANSFLOW.sxf is '手续费(单位:元)'; comment on column URP.ALIPAY_TRANSFLOW.qsje is '清算金额(单位:元)'; comment on column URP.ALIPAY_TRANSFLOW.qsrq is '清算日期'; create index URP.ALI_QJD on URP.ALIPAY_TRANSFLOW (DZRQ, JGBM, QDZHID); create index URP.ALI_SFSC_DZBS on URP.ALIPAY_TRANSFLOW (DZBS, SFSC); create index URP.ALI_SJ on URP.ALIPAY_TRANSFLOW (SHDDH, JYLSH); alter table URP.ALIPAY_TRANSFLOW add constraint ALIPAY_TRANSFLOW_PRIMARYKEY primary key (LSID); prompt prompt Creating table ARRIVALACCOUNT_STATISTICS prompt ======================================== prompt create table URP.ARRIVALACCOUNT_STATISTICS ( qdzhdzid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32) not null, dzzje NUMBER(12,2) not null, dzpc VARCHAR2(2) default 1 not null, dzrq DATE not null, jlcjsj TIMESTAMP(6) not null, dzbs VARCHAR2(2) default 0 not null, dzwhfjmc VARCHAR2(50), dzwhfjbclj VARCHAR2(100), dzwhclbz VARCHAR2(100), dzwhzje NUMBER(12,2), dzwhsj TIMESTAMP(6), dzwhr VARCHAR2(20), dzsj TIMESTAMP(6), sfsc VARCHAR2(2) default 0 not null, bz VARCHAR2(100), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.ARRIVALACCOUNT_STATISTICS is '到账统计表'; comment on column URP.ARRIVALACCOUNT_STATISTICS.qdzhdzid is '渠道账户到账主键ID'; comment on column URP.ARRIVALACCOUNT_STATISTICS.qdzhid is '渠道账户主键ID'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzzje is '到账总金额(医保渠道-实际垫付资金)'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzpc is '到账批次'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzrq is '对账日期'; comment on column URP.ARRIVALACCOUNT_STATISTICS.jlcjsj is '账户到账记录创建时间'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzbs is '到账标识(1:已到账,0:未到账)'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzwhfjmc is '到账维护附件名称'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzwhfjbclj is '到账维护附件保存路径'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzwhclbz is '到账维护处理备注'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzwhzje is '到账维护总金额'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzwhsj is '到账维护时间'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzwhr is '到账维护人'; comment on column URP.ARRIVALACCOUNT_STATISTICS.dzsj is '到账时间'; comment on column URP.ARRIVALACCOUNT_STATISTICS.sfsc is '是否删除(1:是,0:否)'; comment on column URP.ARRIVALACCOUNT_STATISTICS.bz is '备注(医保渠道-到账月份)'; comment on column URP.ARRIVALACCOUNT_STATISTICS.bly1 is '保留域1(医保渠道-不合理费用)'; comment on column URP.ARRIVALACCOUNT_STATISTICS.bly2 is '保留域2(医保渠道-预留保证金)'; comment on column URP.ARRIVALACCOUNT_STATISTICS.bly3 is '保留域3'; create index URP.IDX_QDZHID_DZRQ_SFSC on URP.ARRIVALACCOUNT_STATISTICS (DZRQ, SFSC, QDZHID); alter table URP.ARRIVALACCOUNT_STATISTICS add constraint ARRIVALACCOUNT_STATISTICS_PK primary key (QDZHDZID); prompt prompt Creating table CASHPAY_TRANSFLOW prompt ================================ prompt create table URP.CASHPAY_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50), jylsh VARCHAR2(50), qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30), zdhm VARCHAR2(50), spmc VARCHAR2(30), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, dzbh VARCHAR2(50), ejbs VARCHAR2(30), jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), sxf NUMBER(12,2) default 0.00, qsje NUMBER(12,2) default 0.00, qsrq VARCHAR2(20) ) ; comment on table URP.CASHPAY_TRANSFLOW is '现金交易流水表'; comment on column URP.CASHPAY_TRANSFLOW.lsid is '微信流水主键ID'; comment on column URP.CASHPAY_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.CASHPAY_TRANSFLOW.shbh is '商户编号'; comment on column URP.CASHPAY_TRANSFLOW.zdbh is '终端编号'; comment on column URP.CASHPAY_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.CASHPAY_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.CASHPAY_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.CASHPAY_TRANSFLOW.yjylsh is '原交易流水号:交易为后续类交易时有值'; comment on column URP.CASHPAY_TRANSFLOW.shddh is '商户订单号'; comment on column URP.CASHPAY_TRANSFLOW.zdhm is '账单号码'; comment on column URP.CASHPAY_TRANSFLOW.spmc is '商品名称'; comment on column URP.CASHPAY_TRANSFLOW.jysj is '交易时间'; comment on column URP.CASHPAY_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.CASHPAY_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.CASHPAY_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.CASHPAY_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.CASHPAY_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.CASHPAY_TRANSFLOW.jybz is '交易备注'; comment on column URP.CASHPAY_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.CASHPAY_TRANSFLOW.dzrq is '对账日期'; comment on column URP.CASHPAY_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.CASHPAY_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.CASHPAY_TRANSFLOW.dzbh is '对账编号'; comment on column URP.CASHPAY_TRANSFLOW.ejbs is '二级标识(实际支付渠道/服务商)'; comment on column URP.CASHPAY_TRANSFLOW.jgbm is '机构编码'; comment on column URP.CASHPAY_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.CASHPAY_TRANSFLOW.bly1 is '保留域1'; comment on column URP.CASHPAY_TRANSFLOW.bly2 is '保留域2'; comment on column URP.CASHPAY_TRANSFLOW.bly3 is '保留域3'; comment on column URP.CASHPAY_TRANSFLOW.sxf is '手续费(单位:元)'; comment on column URP.CASHPAY_TRANSFLOW.qsje is '清算金额(单位:元)'; comment on column URP.CASHPAY_TRANSFLOW.qsrq is '清算日期'; create index URP.DZRQ_SFSC_DZBS_JGBM_DDH_QDZH on URP.CASHPAY_TRANSFLOW (QDZHID, SHDDH, DZRQ, DZBS, JGBM, SFSC); alter table URP.CASHPAY_TRANSFLOW add constraint CASHPAY_TRANSFLOW_PRIMARYKEY primary key (LSID); prompt prompt Creating table CCBUNIONPAY_TRANSFLOW prompt ==================================== prompt create table URP.CCBUNIONPAY_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50), jylsh VARCHAR2(50), qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30) not null, zdhm VARCHAR2(50), spmc VARCHAR2(30), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50), ejbs VARCHAR2(15) ) ; comment on table URP.CCBUNIONPAY_TRANSFLOW is '建行聚合付对账流水表'; comment on column URP.CCBUNIONPAY_TRANSFLOW.lsid is '建行聚合付流水主键ID'; comment on column URP.CCBUNIONPAY_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.CCBUNIONPAY_TRANSFLOW.shbh is '商户编号'; comment on column URP.CCBUNIONPAY_TRANSFLOW.zdbh is '终端编号'; comment on column URP.CCBUNIONPAY_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.CCBUNIONPAY_TRANSFLOW.yjylsh is '原交易流水号/原交易订单号:交易为后续类交易时有值'; comment on column URP.CCBUNIONPAY_TRANSFLOW.shddh is '商户订单号'; comment on column URP.CCBUNIONPAY_TRANSFLOW.zdhm is '账单号码'; comment on column URP.CCBUNIONPAY_TRANSFLOW.spmc is '商品名称'; comment on column URP.CCBUNIONPAY_TRANSFLOW.jysj is '交易时间'; comment on column URP.CCBUNIONPAY_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.jybz is '交易备注'; comment on column URP.CCBUNIONPAY_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.CCBUNIONPAY_TRANSFLOW.dzrq is '对账日期'; comment on column URP.CCBUNIONPAY_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.jgbm is '机构编码'; comment on column URP.CCBUNIONPAY_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.CCBUNIONPAY_TRANSFLOW.bly1 is '保留域1'; comment on column URP.CCBUNIONPAY_TRANSFLOW.bly2 is '保留域2'; comment on column URP.CCBUNIONPAY_TRANSFLOW.bly3 is '保留域3'; comment on column URP.CCBUNIONPAY_TRANSFLOW.dzbh is '对账编号'; comment on column URP.CCBUNIONPAY_TRANSFLOW.ejbs is '二级标识'; alter table URP.CCBUNIONPAY_TRANSFLOW add constraint CCBUNIONPAY_PRIMARYKEY primary key (LSID); prompt prompt Creating table CGBSMARTPAY_TRANSFLOW prompt ==================================== prompt create table URP.CGBSMARTPAY_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50), jylsh VARCHAR2(50), qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(50) not null, zdhm VARCHAR2(50), spmc VARCHAR2(100), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20), jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50), ejbs VARCHAR2(30), sxf NUMBER(12,2) default 0.00 not null, qsje NUMBER(12,2) default 0.00, qsrq VARCHAR2(20) ) ; comment on table URP.CGBSMARTPAY_TRANSFLOW is '广发慧收款对账流水表'; comment on column URP.CGBSMARTPAY_TRANSFLOW.lsid is '广发慧收款流水主键ID'; comment on column URP.CGBSMARTPAY_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.CGBSMARTPAY_TRANSFLOW.shbh is '商户编号'; comment on column URP.CGBSMARTPAY_TRANSFLOW.zdbh is '终端编号'; comment on column URP.CGBSMARTPAY_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.CGBSMARTPAY_TRANSFLOW.yjylsh is '原交易流水号/原交易订单号:交易为后续类交易时有值'; comment on column URP.CGBSMARTPAY_TRANSFLOW.shddh is '商户订单号'; comment on column URP.CGBSMARTPAY_TRANSFLOW.zdhm is '账单号码'; comment on column URP.CGBSMARTPAY_TRANSFLOW.spmc is '商品名称'; comment on column URP.CGBSMARTPAY_TRANSFLOW.jysj is '交易时间'; comment on column URP.CGBSMARTPAY_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.jybz is '交易备注'; comment on column URP.CGBSMARTPAY_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.CGBSMARTPAY_TRANSFLOW.dzrq is '对账日期'; comment on column URP.CGBSMARTPAY_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.jgbm is '机构编码'; comment on column URP.CGBSMARTPAY_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.bly1 is '保留域1'; comment on column URP.CGBSMARTPAY_TRANSFLOW.bly2 is '保留域2'; comment on column URP.CGBSMARTPAY_TRANSFLOW.bly3 is '保留域3->就诊卡号'; comment on column URP.CGBSMARTPAY_TRANSFLOW.dzbh is '对账编号'; comment on column URP.CGBSMARTPAY_TRANSFLOW.ejbs is '二级标识(现存->退款状态)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.sxf is '手续费(单位:元)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.qsje is '清算金额(单位:元)'; comment on column URP.CGBSMARTPAY_TRANSFLOW.qsrq is '清算日期'; create index URP.CGB_SFSC_DZBS on URP.CGBSMARTPAY_TRANSFLOW (DZBS, SFSC); create index URP.IDX_QJD on URP.CGBSMARTPAY_TRANSFLOW (QDZHID, JGBM, DZRQ); create index URP.IDX_SJ on URP.CGBSMARTPAY_TRANSFLOW (SHDDH, JYLSH); alter table URP.CGBSMARTPAY_TRANSFLOW add constraint CGBSMARTPAY_PRIMARYKEY primary key (LSID); prompt prompt Creating table CHANNEL_ACCOUNT prompt ============================== prompt create table URP.CHANNEL_ACCOUNT ( qdzhid VARCHAR2(32) default sys_guid() not null, qdid VARCHAR2(32) not null, shbh VARCHAR2(20), zdbh VARCHAR2(20), zhmc VARCHAR2(30), zhbh VARCHAR2(30) not null, zhzt VARCHAR2(2) not null, jlcjsj TIMESTAMP(6) default sysdate, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6) default sysdate, zhxgr VARCHAR2(20), bz VARCHAR2(100), khh VARCHAR2(50) ) ; comment on table URP.CHANNEL_ACCOUNT is '渠道账户'; comment on column URP.CHANNEL_ACCOUNT.qdzhid is '渠道账户ID,用于区分账户'; comment on column URP.CHANNEL_ACCOUNT.qdid is '渠道ID,用于区分渠道'; comment on column URP.CHANNEL_ACCOUNT.shbh is '商户编号'; comment on column URP.CHANNEL_ACCOUNT.zdbh is '终端编号'; comment on column URP.CHANNEL_ACCOUNT.zhmc is '账户名称'; comment on column URP.CHANNEL_ACCOUNT.zhbh is '账户编号'; comment on column URP.CHANNEL_ACCOUNT.zhzt is '账户状态(1:正常,0:禁用/删除)'; comment on column URP.CHANNEL_ACCOUNT.jlcjsj is '记录创建时间'; comment on column URP.CHANNEL_ACCOUNT.cjr is '创建人'; comment on column URP.CHANNEL_ACCOUNT.zhxgsj is '最后修改时间'; comment on column URP.CHANNEL_ACCOUNT.zhxgr is '最后修改人'; comment on column URP.CHANNEL_ACCOUNT.bz is '备注'; comment on column URP.CHANNEL_ACCOUNT.khh is '开户行'; create index URP.QDID_SHBH_ZHBH on URP.CHANNEL_ACCOUNT (QDID, SHBH, ZHBH); alter table URP.CHANNEL_ACCOUNT add constraint CHANNEL_ACCOUNT_PRIMARYKEY primary key (QDZHID); prompt prompt Creating table CHANNEL_INFO prompt =========================== prompt create table URP.CHANNEL_INFO ( qdid VARCHAR2(32) default sys_guid() not null, qdbm VARCHAR2(15) not null, qdmc VARCHAR2(30) not null, dzwjgs VARCHAR2(10), dzzq VARCHAR2(10) not null, rqsj VARCHAR2(10), qdzt VARCHAR2(2) default 1 not null, sfzddz VARCHAR2(2) default 1 not null, hqdzwjfs VARCHAR2(10) not null, dzwjxzdz VARCHAR2(100), ftpzh VARCHAR2(30), ftpmm VARCHAR2(20), ftpdk NUMBER(6), qmsf VARCHAR2(10), shzs VARCHAR2(100), ggzs VARCHAR2(100), dzwjxzml VARCHAR2(100), dzwjmc VARCHAR2(100), dzwjbdbclj VARCHAR2(100) not null, jgbm VARCHAR2(15) not null, dzwjxfsj VARCHAR2(10), jlcjsj TIMESTAMP(6) default sysdate not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6) default sysdate, zhxgr VARCHAR2(20), bz VARCHAR2(100), bly VARCHAR2(50), jkm VARCHAR2(50), jkcs VARCHAR2(1000), zhqdfs VARCHAR2(2), stmc VARCHAR2(30), sjklx VARCHAR2(20) ) ; comment on table URP.CHANNEL_INFO is '渠道信息'; comment on column URP.CHANNEL_INFO.qdid is '渠道ID,主键'; comment on column URP.CHANNEL_INFO.qdbm is '渠道编码,用于区分渠道'; comment on column URP.CHANNEL_INFO.qdmc is '渠道名称'; comment on column URP.CHANNEL_INFO.dzwjgs is '对账文件格式'; comment on column URP.CHANNEL_INFO.dzzq is '对账周期'; comment on column URP.CHANNEL_INFO.rqsj is '日切时间'; comment on column URP.CHANNEL_INFO.qdzt is '渠道状态(1:正常,0:禁用)'; comment on column URP.CHANNEL_INFO.sfzddz is '是否自动对账(0:否,1是)'; comment on column URP.CHANNEL_INFO.hqdzwjfs is '获取对账文件方式(ftp、sftp、http、https、socket、webservice、视图)'; comment on column URP.CHANNEL_INFO.dzwjxzdz is '对账文件下载地址(FTP:IP,接口:url,视图:数据库访问连接串)'; comment on column URP.CHANNEL_INFO.ftpzh is 'ftp账号、视图数据库用户名'; comment on column URP.CHANNEL_INFO.ftpmm is 'ftp密码、视图数据库密码'; comment on column URP.CHANNEL_INFO.ftpdk is 'ftp端口、socket端口'; comment on column URP.CHANNEL_INFO.qmsf is '签名算法'; comment on column URP.CHANNEL_INFO.shzs is '商户证书(含路径和文件名)'; comment on column URP.CHANNEL_INFO.ggzs is '公共证书(含路径和文件名)'; comment on column URP.CHANNEL_INFO.dzwjxzml is '对账文件下载目录(ftp、sftp,静态的写死,动态的用{}括起来)'; comment on column URP.CHANNEL_INFO.dzwjmc is '对账文件名称(静态的写死,动态的用{}括起来)'; comment on column URP.CHANNEL_INFO.dzwjbdbclj is '对账文件本地保存路径(静态的写死,动态的用{}括起来)'; comment on column URP.CHANNEL_INFO.jgbm is '机构编码'; comment on column URP.CHANNEL_INFO.dzwjxfsj is '对账文件下发时间'; comment on column URP.CHANNEL_INFO.jlcjsj is '记录创建时间'; comment on column URP.CHANNEL_INFO.cjr is '创建人'; comment on column URP.CHANNEL_INFO.zhxgsj is '最后修改日期'; comment on column URP.CHANNEL_INFO.zhxgr is '最后修改人'; comment on column URP.CHANNEL_INFO.bz is '备注'; comment on column URP.CHANNEL_INFO.bly is '保留域'; comment on column URP.CHANNEL_INFO.jkm is '接口/方法名(如webservice)'; comment on column URP.CHANNEL_INFO.jkcs is '接口参数(调用http、htps、socket、webservice接口所需的参数,静态的写死,动态的用{}括起来)'; comment on column URP.CHANNEL_INFO.zhqdfs is '结算账户确定方式(1:商户号,2:商户号+终端号,3:结算账户账号)'; comment on column URP.CHANNEL_INFO.stmc is '视图名称'; comment on column URP.CHANNEL_INFO.sjklx is '数据库类型(oracle、MySQL等)'; create index URP.QDID_QDBM_QDZT_JGBM on URP.CHANNEL_INFO (QDID, QDBM, JGBM, QDZT); alter table URP.CHANNEL_INFO add constraint CHANNEL_PRIMARYKEY primary key (QDID); prompt prompt Creating table CHANNEL_RECONRESULT prompt ================================== prompt create table URP.CHANNEL_RECONRESULT ( qddzjgid VARCHAR2(32) default sys_guid() not null, qdid VARCHAR2(32) not null, dzbs VARCHAR2(2) not null, dzjg VARCHAR2(2) not null, dzjgms VARCHAR2(100), qdjyzje NUMBER(12,2), qdjyzbs NUMBER(8), qdycjyzje NUMBER(12,2), ycjyzbs NUMBER(8), qdjyzb VARCHAR2(10), qdjylszb VARCHAR2(10), qdjyhbzb VARCHAR2(10), dzrq DATE default sysdate not null, jlcjsj TIMESTAMP(6) default sysdate not null, dzfs VARCHAR2(2) default 0 not null, dzfqr VARCHAR2(20), sfsc VARCHAR2(100) default 0 not null, bz VARCHAR2(2), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), hisjyzje NUMBER(12,2), hisjyzbs NUMBER(8), hisycjyzje NUMBER(12,2), qdycjyzbs NUMBER(8), hisycjyzbs NUMBER(8), sxf NUMBER(12,2) default 0.00 not null, qsje NUMBER(12,2) default 0.00, qsrq VARCHAR2(20), qdzfbs NUMBER(8), qdtkbs NUMBER(8) ) ; comment on table URP.CHANNEL_RECONRESULT is '渠道对账结果表'; comment on column URP.CHANNEL_RECONRESULT.qddzjgid is '渠道对账结果主键ID,用于区分渠道对账结果'; comment on column URP.CHANNEL_RECONRESULT.qdid is '渠道主键id'; comment on column URP.CHANNEL_RECONRESULT.dzbs is '对账标识(1:已完成、0:未完成、2未对账)'; comment on column URP.CHANNEL_RECONRESULT.dzjg is '对账结果(1账平、0账不平、2未对账、3无交易)'; comment on column URP.CHANNEL_RECONRESULT.dzjgms is '对账结果描述'; comment on column URP.CHANNEL_RECONRESULT.qdjyzje is '本次对账该渠道交易总金额(含异常交易)'; comment on column URP.CHANNEL_RECONRESULT.qdjyzbs is '本次对账该渠道交易总笔数(含异常交易)'; comment on column URP.CHANNEL_RECONRESULT.qdycjyzje is '本次对账该渠道异常交易总金额(渠道交易总金额-正常交易总金额)'; comment on column URP.CHANNEL_RECONRESULT.ycjyzbs is '本次对账异常交易总笔数(His和渠道异常并集)'; comment on column URP.CHANNEL_RECONRESULT.qdjyzb is '本次对账渠道交易占比(本次对账该渠道交易笔数/所有渠道本次对账交易总笔数)'; comment on column URP.CHANNEL_RECONRESULT.qdjylszb is '本次对账渠道交易历史占比(本次对账该渠道交易笔数/所有渠道所有交易总笔数)'; comment on column URP.CHANNEL_RECONRESULT.qdjyhbzb is '本次对账渠道交易环比占比'; comment on column URP.CHANNEL_RECONRESULT.dzrq is '对账日期'; comment on column URP.CHANNEL_RECONRESULT.jlcjsj is '对账完成时间/记录创建时间'; comment on column URP.CHANNEL_RECONRESULT.dzfs is '对账方式(0:自动对账、1:手动对账、2:手动 重对账)'; comment on column URP.CHANNEL_RECONRESULT.dzfqr is '对账发起人'; comment on column URP.CHANNEL_RECONRESULT.sfsc is '是否删除(1:是,0:否)'; comment on column URP.CHANNEL_RECONRESULT.bz is '备注'; comment on column URP.CHANNEL_RECONRESULT.bly1 is '保留域1'; comment on column URP.CHANNEL_RECONRESULT.bly2 is '保留域2'; comment on column URP.CHANNEL_RECONRESULT.bly3 is '保留域3'; comment on column URP.CHANNEL_RECONRESULT.hisjyzje is '本次对账对应该渠道的His交易总金额(含异常交易)'; comment on column URP.CHANNEL_RECONRESULT.hisjyzbs is '本次对账对应该渠道的His交易总笔数(含异常交易)'; comment on column URP.CHANNEL_RECONRESULT.hisycjyzje is '本次对账对应该渠道的His异常交易总金额(His交易总金额-正常交易总金额)'; comment on column URP.CHANNEL_RECONRESULT.qdycjyzbs is '本次对账渠道异常交易总笔数'; comment on column URP.CHANNEL_RECONRESULT.hisycjyzbs is '本次对账对应该渠道的His异常交易总笔数'; comment on column URP.CHANNEL_RECONRESULT.sxf is '手续费(单位:元)'; comment on column URP.CHANNEL_RECONRESULT.qsje is '清算金额(单位:元)'; comment on column URP.CHANNEL_RECONRESULT.qsrq is '清算日期'; comment on column URP.CHANNEL_RECONRESULT.qdzfbs is '渠道支付笔数'; comment on column URP.CHANNEL_RECONRESULT.qdtkbs is '渠道退款笔数'; create index URP.QDID_DZRQ_SFSC on URP.CHANNEL_RECONRESULT (QDID, DZRQ, SFSC); alter table URP.CHANNEL_RECONRESULT add constraint CHANNELRECONRESULT_PRIMARYKEY primary key (QDDZJGID); prompt prompt Creating table EHCPAY_TRANSFLOW prompt =============================== prompt create table URP.EHCPAY_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50), jylsh VARCHAR2(50), qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30), zdhm VARCHAR2(50), spmc VARCHAR2(30), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50) ) ; comment on table URP.EHCPAY_TRANSFLOW is '电子健康卡交易流水表'; comment on column URP.EHCPAY_TRANSFLOW.lsid is '电子健康卡流水主键ID'; comment on column URP.EHCPAY_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.EHCPAY_TRANSFLOW.shbh is '商户编号'; comment on column URP.EHCPAY_TRANSFLOW.zdbh is '终端编号'; comment on column URP.EHCPAY_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.EHCPAY_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.EHCPAY_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.EHCPAY_TRANSFLOW.yjylsh is '原交易流水号:交易为后续类交易时有值'; comment on column URP.EHCPAY_TRANSFLOW.shddh is '商户订单号'; comment on column URP.EHCPAY_TRANSFLOW.zdhm is '账单号码'; comment on column URP.EHCPAY_TRANSFLOW.spmc is '商品名称'; comment on column URP.EHCPAY_TRANSFLOW.jysj is '交易时间'; comment on column URP.EHCPAY_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.EHCPAY_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.EHCPAY_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.EHCPAY_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.EHCPAY_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.EHCPAY_TRANSFLOW.jybz is '交易备注(原交易订单号)'; comment on column URP.EHCPAY_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.EHCPAY_TRANSFLOW.dzrq is '对账日期'; comment on column URP.EHCPAY_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.EHCPAY_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.EHCPAY_TRANSFLOW.jgbm is '机构编码'; comment on column URP.EHCPAY_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.EHCPAY_TRANSFLOW.bly1 is '保留域1'; comment on column URP.EHCPAY_TRANSFLOW.bly2 is '保留域2'; comment on column URP.EHCPAY_TRANSFLOW.bly3 is '保留域3'; comment on column URP.EHCPAY_TRANSFLOW.dzbh is '对账编号'; create index URP.DQ_SC_DZS_JGBM_DDH_QDZH on URP.EHCPAY_TRANSFLOW (SHDDH, DZRQ, SFSC, DZBS, JGBM, QDZHID); alter table URP.EHCPAY_TRANSFLOW add constraint EHCPAY_TRANSFLOW_PRIMARYKEY primary key (LSID); prompt prompt Creating table E_EQUIPMENT_FACTORY prompt ================================== prompt create table URP.E_EQUIPMENT_FACTORY ( sbcsid VARCHAR2(32) default sys_guid() not null, sbcsbm VARCHAR2(15) not null, sbcsmc VARCHAR2(30) not null, dzwjgs VARCHAR2(10), dzzq VARCHAR2(10), rqsj VARCHAR2(10), cszt VARCHAR2(2) default 1 not null, sfzddz VARCHAR2(2) default 1 not null, hqdzwjfs VARCHAR2(10) not null, dzwjxzdz VARCHAR2(100), ftpzh VARCHAR2(30), ftpmm VARCHAR2(20), ftpdk NUMBER(6), qmsf VARCHAR2(10), shzs VARCHAR2(100), ggzs VARCHAR2(100), dzwjxzml VARCHAR2(100), dzwjmc VARCHAR2(50), dzwjbdbclj VARCHAR2(100) not null, jgbm VARCHAR2(15) not null, dzwjxfsj VARCHAR2(10), jlcjsj TIMESTAMP(6) default sysdate not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6) default sysdate, zhxgr VARCHAR2(20), jkm VARCHAR2(50), jkcs VARCHAR2(1000), zhqdfs VARCHAR2(2), stmc VARCHAR2(30), sjklx VARCHAR2(20), bz VARCHAR2(100), bly VARCHAR2(50) ) ; comment on table URP.E_EQUIPMENT_FACTORY is '设备信息'; comment on column URP.E_EQUIPMENT_FACTORY.sbcsid is '设备厂商ID,主键'; comment on column URP.E_EQUIPMENT_FACTORY.sbcsbm is '设备厂商编码,用于区分设备厂商'; comment on column URP.E_EQUIPMENT_FACTORY.sbcsmc is '设备厂商名称'; comment on column URP.E_EQUIPMENT_FACTORY.dzwjgs is '对账文件格式'; comment on column URP.E_EQUIPMENT_FACTORY.dzzq is '对账周期'; comment on column URP.E_EQUIPMENT_FACTORY.rqsj is '日切时间'; comment on column URP.E_EQUIPMENT_FACTORY.cszt is '厂商状态(1:正常,0:禁用)'; comment on column URP.E_EQUIPMENT_FACTORY.sfzddz is '是否自动对账(0:否,1是)'; comment on column URP.E_EQUIPMENT_FACTORY.hqdzwjfs is '获取对账文件方式(ftp、sftp、http、https、socket、webservice、视图)'; comment on column URP.E_EQUIPMENT_FACTORY.dzwjxzdz is '对账文件下载地址(FTP:IP,接口:url,视图:数据库访问连接串)'; comment on column URP.E_EQUIPMENT_FACTORY.ftpzh is 'ftp账号、视图数据库用户名'; comment on column URP.E_EQUIPMENT_FACTORY.ftpmm is 'ftp密码、视图数据库密码'; comment on column URP.E_EQUIPMENT_FACTORY.ftpdk is 'ftp端口、socket端口'; comment on column URP.E_EQUIPMENT_FACTORY.qmsf is '签名算法'; comment on column URP.E_EQUIPMENT_FACTORY.shzs is '商户证书(含路径和文件名)'; comment on column URP.E_EQUIPMENT_FACTORY.ggzs is '公共证书(含路径和文件名)'; comment on column URP.E_EQUIPMENT_FACTORY.dzwjxzml is '对账文件下载目录(ftp、sftp,静态的写死,动态的用{}括起来)'; comment on column URP.E_EQUIPMENT_FACTORY.dzwjmc is '对账文件名称(静态的写死,动态的用{}括起来)'; comment on column URP.E_EQUIPMENT_FACTORY.dzwjbdbclj is '对账文件本地保存路径(静态的写死,动态的用{}括起来)'; comment on column URP.E_EQUIPMENT_FACTORY.jgbm is '机构编码'; comment on column URP.E_EQUIPMENT_FACTORY.dzwjxfsj is '对账文件下发时间'; comment on column URP.E_EQUIPMENT_FACTORY.jlcjsj is '记录创建时间'; comment on column URP.E_EQUIPMENT_FACTORY.cjr is '创建人'; comment on column URP.E_EQUIPMENT_FACTORY.zhxgsj is '最后修改日期'; comment on column URP.E_EQUIPMENT_FACTORY.zhxgr is '最后修改人'; comment on column URP.E_EQUIPMENT_FACTORY.jkm is '接口/方法名(如webservice)'; comment on column URP.E_EQUIPMENT_FACTORY.jkcs is '接口参数(调用http、htps、socket、webservice接口所需的参数,静态的写死,动态的用{}括起来)'; comment on column URP.E_EQUIPMENT_FACTORY.zhqdfs is '结算账户确定方式(1:商户号,2:商户号+终端号,3:结算账户账号)'; comment on column URP.E_EQUIPMENT_FACTORY.stmc is '视图名称'; comment on column URP.E_EQUIPMENT_FACTORY.sjklx is '数据库类型(oracle、MySQL等)'; comment on column URP.E_EQUIPMENT_FACTORY.bz is '备注'; comment on column URP.E_EQUIPMENT_FACTORY.bly is '保留域'; alter table URP.E_EQUIPMENT_FACTORY add constraint E_EQUIPMENT_PRIMARYKEY primary key (SBCSID); prompt prompt Creating table E_EQUIPMENT_INFO prompt =============================== prompt create table URP.E_EQUIPMENT_INFO ( sbid VARCHAR2(32) default sys_guid() not null, sbbm VARCHAR2(30) not null, sbmc VARCHAR2(30), sbxlh VARCHAR2(30) not null, sbcsid VARCHAR2(32) not null, sbzt VARCHAR2(2) default 1 not null, jgbm VARCHAR2(15) not null, jlcjsj TIMESTAMP(6) default sysdate not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6) default sysdate, zhxgr VARCHAR2(20), bz VARCHAR2(100), sbcsbm VARCHAR2(30) not null ) ; comment on column URP.E_EQUIPMENT_INFO.sbid is '设备主键ID'; comment on column URP.E_EQUIPMENT_INFO.sbbm is '设备编码'; comment on column URP.E_EQUIPMENT_INFO.sbmc is '设备名称'; comment on column URP.E_EQUIPMENT_INFO.sbxlh is '设备序列号'; comment on column URP.E_EQUIPMENT_INFO.sbcsid is '所属设备厂商主键ID'; comment on column URP.E_EQUIPMENT_INFO.sbzt is '设备状态(1:正常,0:禁用)'; comment on column URP.E_EQUIPMENT_INFO.jgbm is '机构有编码'; comment on column URP.E_EQUIPMENT_INFO.jlcjsj is '记录创建时间'; comment on column URP.E_EQUIPMENT_INFO.cjr is '创建人'; comment on column URP.E_EQUIPMENT_INFO.zhxgsj is '最后修改时间'; comment on column URP.E_EQUIPMENT_INFO.zhxgr is '最后修改人'; comment on column URP.E_EQUIPMENT_INFO.bz is '备注'; comment on column URP.E_EQUIPMENT_INFO.sbcsbm is '设备厂商编码'; alter table URP.E_EQUIPMENT_INFO add primary key (SBID); prompt prompt Creating table E_EQUIPMENT_RECONRESULT prompt ====================================== prompt create table URP.E_EQUIPMENT_RECONRESULT ( sbdzjgid VARCHAR2(32) default sys_guid() not null, sbcsid VARCHAR2(32) not null, sbid VARCHAR2(32), dzbs VARCHAR2(2) not null, dzjg VARCHAR2(2) not null, dzjgms VARCHAR2(100), ycjyzbs NUMBER(8) default 0, sbjyzbs NUMBER(8) default 0, sbjyzje NUMBER(12,2) default 0.00, sbycjyzbs NUMBER(8) default 0, sbycjyzje NUMBER(12,2) default 0.00, hisjyzje NUMBER(12,2) default 0.00, hisjyzbs NUMBER(8) default 0, hisycjyzje NUMBER(12,2) default 0.00, hisycjyzbs NUMBER(8) default 0, jyhztj VARCHAR2(1000), dzrq DATE default sysdate not null, jlcjsj TIMESTAMP(6) default sysdate not null, dzfs VARCHAR2(2) default 0 not null, dzfqr VARCHAR2(20), sfsc VARCHAR2(100) default 0 not null, bz VARCHAR2(2), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.E_EQUIPMENT_RECONRESULT is '设备对账结果表'; comment on column URP.E_EQUIPMENT_RECONRESULT.sbdzjgid is '厂商设备对账结果主键ID,用于区分每个厂商下每个设备的对账结果'; comment on column URP.E_EQUIPMENT_RECONRESULT.sbcsid is '设备厂商主键id'; comment on column URP.E_EQUIPMENT_RECONRESULT.sbid is '设备主键ID'; comment on column URP.E_EQUIPMENT_RECONRESULT.dzbs is '对账标识(1:已完成、0:未完成、2未对账)'; comment on column URP.E_EQUIPMENT_RECONRESULT.dzjg is '对账结果(1账平、0账不平、2未对账)'; comment on column URP.E_EQUIPMENT_RECONRESULT.dzjgms is '对账结果描述'; comment on column URP.E_EQUIPMENT_RECONRESULT.ycjyzbs is '本次对账异常交易总笔数'; comment on column URP.E_EQUIPMENT_RECONRESULT.sbjyzbs is '该设备交易总笔数'; comment on column URP.E_EQUIPMENT_RECONRESULT.sbjyzje is '该设备交易总金额'; comment on column URP.E_EQUIPMENT_RECONRESULT.sbycjyzbs is '该设备异常交易总笔数'; comment on column URP.E_EQUIPMENT_RECONRESULT.sbycjyzje is '该设备异常交易总金额'; comment on column URP.E_EQUIPMENT_RECONRESULT.hisjyzje is '本次对账对应该设备的His交易总金额(含异常交易)'; comment on column URP.E_EQUIPMENT_RECONRESULT.hisjyzbs is '本次对账对应该设备的His交易总笔数(含异常交易)'; comment on column URP.E_EQUIPMENT_RECONRESULT.hisycjyzje is '本次对账对应该设备的His异常交易总金额(His交易总金额-正常交易总金额)'; comment on column URP.E_EQUIPMENT_RECONRESULT.hisycjyzbs is '本次对账对应该设备的His异常交易总笔数'; comment on column URP.E_EQUIPMENT_RECONRESULT.jyhztj is '交易汇总信息分类统计(统计设备上的每个渠道,设备/His交易总笔数、总金额、异常笔数、异常金额,以“|”分割)'; comment on column URP.E_EQUIPMENT_RECONRESULT.dzrq is '对账日期'; comment on column URP.E_EQUIPMENT_RECONRESULT.jlcjsj is '对账完成时间/记录创建时间'; comment on column URP.E_EQUIPMENT_RECONRESULT.dzfs is '对账方式(0:自动对账、1:手动对账、2:手动 重对账)'; comment on column URP.E_EQUIPMENT_RECONRESULT.dzfqr is '对账发起人'; comment on column URP.E_EQUIPMENT_RECONRESULT.sfsc is '是否删除(1:是,0:否)'; comment on column URP.E_EQUIPMENT_RECONRESULT.bz is '备注'; comment on column URP.E_EQUIPMENT_RECONRESULT.bly1 is '保留域1'; comment on column URP.E_EQUIPMENT_RECONRESULT.bly2 is '保留域2'; comment on column URP.E_EQUIPMENT_RECONRESULT.bly3 is '保留域3'; alter table URP.E_EQUIPMENT_RECONRESULT add constraint EQUIPMENTCONRESULT_PRIMARYKEY primary key (SBDZJGID); prompt prompt Creating table E_EQUIPMENT_TRANSFLOW prompt ==================================== prompt create table URP.E_EQUIPMENT_TRANSFLOW ( ynsblsid VARCHAR2(32) default sys_guid() not null, yhrybh VARCHAR2(30) not null, brjzkh VARCHAR2(30), blh VARCHAR2(30), brxm VARCHAR2(100) not null, fpbh VARCHAR2(50), jyqdbs VARCHAR2(20) not null, ywlx VARCHAR2(10) not null, jyje NUMBER(12,2) not null, khh VARCHAR2(30), khzh VARCHAR2(30), jylsh VARCHAR2(50), jyckh VARCHAR2(50), ddbh VARCHAR2(50) not null, yjyh VARCHAR2(50), ybfdje NUMBER(12,2), grzhzfje NUMBER(12,2), xjzfje NUMBER(12,2), yljmje NUMBER(12,2), ylbzje NUMBER(12,2), zdbh VARCHAR2(32), brjzkye NUMBER(12,2), czm VARCHAR2(20), jysj VARCHAR2(20) not null, jyylx VARCHAR2(10), jyshbh VARCHAR2(50), jyzdbh VARCHAR2(50), jysbbs VARCHAR2(50), jyrzzh VARCHAR2(50), yhlsh VARCHAR2(30), yhckh VARCHAR2(50), pch VARCHAR2(10), jyzt VARCHAR2(2) not null, jgbm VARCHAR2(15) not null, zdjybs VARCHAR2(2), mzzybs VARCHAR2(2), sbcsid VARCHAR2(32) not null, sfsc VARCHAR2(2) default 0 not null, jlcjsj TIMESTAMP(6) not null, dzrq DATE not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, dzbh VARCHAR2(50) not null, bz VARCHAR2(100), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.E_EQUIPMENT_TRANSFLOW is '设备对账流水表'; comment on column URP.E_EQUIPMENT_TRANSFLOW.ynsblsid is '设备对账流水主键ID'; comment on column URP.E_EQUIPMENT_TRANSFLOW.yhrybh is '医护人员(操作员)编号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.brjzkh is '病人就诊卡号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.blh is '病人病历号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.brxm is '病人姓名'; comment on column URP.E_EQUIPMENT_TRANSFLOW.fpbh is '发票编号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jyqdbs is '交易渠道标识(微信、支付宝、医保等)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.ywlx is '原交易流水号:交易为后续类交易时有值'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jyje is '交易总金额'; comment on column URP.E_EQUIPMENT_TRANSFLOW.khh is '交易所用银行卡开户行'; comment on column URP.E_EQUIPMENT_TRANSFLOW.khzh is '交易所用银行卡账号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jylsh is '交易流水号(作为对账唯一标识时不能为空)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jyckh is '交易参考号(作为对账唯一标识时不能为空)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.ddbh is '订单编号(默认作为对账唯一标识)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.yjyh is '原交易订单号/流水号(反向交易时不为空)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.ybfdje is '医保负担/报销总金额(医保支付时赋值)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.grzhzfje is '个人账户支付金额(医保支付时赋值)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.xjzfje is '现金支付金额(医保支付时赋值)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.yljmje is '医疗减免金额(医保支付时赋值)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.ylbzje is '医疗补助金额(医保支付时赋值)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.zdbh is '账单编号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.brjzkye is '病人就诊卡余额'; comment on column URP.E_EQUIPMENT_TRANSFLOW.czm is '操作码'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jysj is '交易时间'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jyylx is '交易源类型(1:窗口、2:自助终端、3:诊间POS)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jyshbh is '交易商户编号(需用此确定结算账户时不能为空)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jyzdbh is '交易终端编号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jysbbs is '交易设备标识(用以判断哪台设备:如设备编号/设备序列号)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jyrzzh is '交易入账账号(结算账户号:需用此确定结算账户时不能为空)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.yhlsh is '银行流水号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.yhckh is '银行参考号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.pch is '批次号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jgbm is '所属机构(医院)编码'; comment on column URP.E_EQUIPMENT_TRANSFLOW.zdjybs is '是否自助终端交易标识(1:是,0:否)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.mzzybs is '门诊住院标识(1:门诊,2:住院)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.sbcsid is '设备厂商主键ID'; comment on column URP.E_EQUIPMENT_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.E_EQUIPMENT_TRANSFLOW.dzrq is '对账日期'; comment on column URP.E_EQUIPMENT_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.E_EQUIPMENT_TRANSFLOW.dzbh is '对账编号'; comment on column URP.E_EQUIPMENT_TRANSFLOW.bz is '备注'; comment on column URP.E_EQUIPMENT_TRANSFLOW.bly1 is '保留域1'; comment on column URP.E_EQUIPMENT_TRANSFLOW.bly2 is '保留域2'; comment on column URP.E_EQUIPMENT_TRANSFLOW.bly3 is '保留域3'; alter table URP.E_EQUIPMENT_TRANSFLOW add primary key (YNSBLSID); prompt prompt Creating table E_FACTORY_RECONRESULT prompt ==================================== prompt create table URP.E_FACTORY_RECONRESULT ( sbcsdzjgid VARCHAR2(32) default sys_guid() not null, sbcsid VARCHAR2(32) not null, dzbs VARCHAR2(2) not null, dzjg VARCHAR2(2) not null, dzjgms VARCHAR2(100), ycjyzbs NUMBER(8) default 0, sbcsjyzbs NUMBER(8) default 0, sbcsjyzje NUMBER(12,2) default 0.00, sbcsycjyzbs NUMBER(8) default 0, sbcsycjyzje NUMBER(12,2) default 0.00, hisjyzje NUMBER(12,2) default 0.00, hisjyzbs NUMBER(8) default 0, hisycjyzje NUMBER(12,2) default 0.00, hisycjyzbs NUMBER(8) default 0, ycsbzs NUMBER(8) default 0, zcsbzs NUMBER(8) default 0, jyhztj VARCHAR2(1000), dzrq DATE default sysdate not null, jlcjsj TIMESTAMP(6) default sysdate not null, dzfs VARCHAR2(2) default 0 not null, dzfqr VARCHAR2(20), sfsc VARCHAR2(100) default 0 not null, bz VARCHAR2(2), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.E_FACTORY_RECONRESULT is '设备厂商对账结果表'; comment on column URP.E_FACTORY_RECONRESULT.sbcsdzjgid is '厂商对账结果主键ID,用于区分每个厂商的对账结果'; comment on column URP.E_FACTORY_RECONRESULT.sbcsid is '设备厂商主键id'; comment on column URP.E_FACTORY_RECONRESULT.dzbs is '对账标识(1:已完成、0:未完成、2未对账)'; comment on column URP.E_FACTORY_RECONRESULT.dzjg is '对账结果(1账平、0账不平、2未对账)'; comment on column URP.E_FACTORY_RECONRESULT.dzjgms is '对账结果描述'; comment on column URP.E_FACTORY_RECONRESULT.ycjyzbs is '本次对账异常交易总笔数'; comment on column URP.E_FACTORY_RECONRESULT.sbcsjyzbs is '该设备厂商交易总笔数'; comment on column URP.E_FACTORY_RECONRESULT.sbcsjyzje is '该设备厂商交易总金额'; comment on column URP.E_FACTORY_RECONRESULT.sbcsycjyzbs is '该设备厂商异常交易总笔数'; comment on column URP.E_FACTORY_RECONRESULT.sbcsycjyzje is '该设备厂商异常交易总金额'; comment on column URP.E_FACTORY_RECONRESULT.hisjyzje is '本次对账对应该设备的His交易总金额(含异常交易)'; comment on column URP.E_FACTORY_RECONRESULT.hisjyzbs is '本次对账对应该设备的His交易总笔数(含异常交易)'; comment on column URP.E_FACTORY_RECONRESULT.hisycjyzje is '本次对账对应该设备的His异常交易总金额(His交易总金额-正常交易总金额)'; comment on column URP.E_FACTORY_RECONRESULT.hisycjyzbs is '本次对账对应该设备的His异常交易总笔数'; comment on column URP.E_FACTORY_RECONRESULT.ycsbzs is '异常设备总数'; comment on column URP.E_FACTORY_RECONRESULT.zcsbzs is '正常设备总数'; comment on column URP.E_FACTORY_RECONRESULT.jyhztj is '交易汇总信息分类统计(统计每个厂商下所有设备,设备/His交易总笔数、总金额、异常笔数、异常金额,以“|”分割)'; comment on column URP.E_FACTORY_RECONRESULT.dzrq is '对账日期'; comment on column URP.E_FACTORY_RECONRESULT.jlcjsj is '对账完成时间/记录创建时间'; comment on column URP.E_FACTORY_RECONRESULT.dzfs is '对账方式(0:自动对账、1:手动对账、2:手动 重对账)'; comment on column URP.E_FACTORY_RECONRESULT.dzfqr is '对账发起人'; comment on column URP.E_FACTORY_RECONRESULT.sfsc is '是否删除(1:是,0:否)'; comment on column URP.E_FACTORY_RECONRESULT.bz is '备注'; comment on column URP.E_FACTORY_RECONRESULT.bly1 is '保留域1'; comment on column URP.E_FACTORY_RECONRESULT.bly2 is '保留域2'; comment on column URP.E_FACTORY_RECONRESULT.bly3 is '保留域3'; alter table URP.E_FACTORY_RECONRESULT add primary key (SBCSDZJGID); prompt prompt Creating table E_HIS_TRANSFLOW prompt ============================== prompt create table URP.E_HIS_TRANSFLOW ( ynhislsid VARCHAR2(32) default sys_guid() not null, sbcsid VARCHAR2(32), yhrybh VARCHAR2(30), brjzkh VARCHAR2(30), brxm VARCHAR2(100) not null, fpbh VARCHAR2(50), jyqdbs VARCHAR2(20) not null, ywlx VARCHAR2(10), jyje NUMBER(12,2) not null, khh VARCHAR2(30), khzh VARCHAR2(30), jylsh VARCHAR2(30), jyckh VARCHAR2(50), ddbh VARCHAR2(50), zdbh VARCHAR2(32), brjzkye NUMBER(12,2), czm VARCHAR2(20), jysj VARCHAR2(25), jyylx VARCHAR2(10), jyshbh VARCHAR2(20), jyzdbh VARCHAR2(30), jysbbs VARCHAR2(32), jyrzzh VARCHAR2(50), yhlsh VARCHAR2(30), yhckh VARCHAR2(50), pch VARCHAR2(10), sfsc VARCHAR2(2) default 0 not null, jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jyzt VARCHAR2(2) default 1 not null, jgbm VARCHAR2(15) not null, blh VARCHAR2(30), yjyh VARCHAR2(30), ybfdje NUMBER(12,2), grzhzfje NUMBER(12,2), xjzfje NUMBER(12,2), yljmje NUMBER(12,2), ylbzje NUMBER(12,2), flag VARCHAR2(2), mzzybs VARCHAR2(2), dzbh VARCHAR2(50) not null, bz VARCHAR2(100), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), yhryxm VARCHAR2(50), sfzhm VARCHAR2(18), bcjywybs VARCHAR2(30) not null ) ; comment on table URP.E_HIS_TRANSFLOW is '设备HIS 流水表'; comment on column URP.E_HIS_TRANSFLOW.ynhislsid is '院内对账His流水Id, 主键'; comment on column URP.E_HIS_TRANSFLOW.sbcsid is '设备厂商主键id, 对应设备厂商管理表'; comment on column URP.E_HIS_TRANSFLOW.yhrybh is '医护人员编号'; comment on column URP.E_HIS_TRANSFLOW.brjzkh is '病人就诊卡号'; comment on column URP.E_HIS_TRANSFLOW.brxm is '病人姓名'; comment on column URP.E_HIS_TRANSFLOW.fpbh is '发票编号'; comment on column URP.E_HIS_TRANSFLOW.jyqdbs is '交易渠道标识(微信、支付宝、医保)'; comment on column URP.E_HIS_TRANSFLOW.ywlx is '业务类型'; comment on column URP.E_HIS_TRANSFLOW.jyje is '交易金额'; comment on column URP.E_HIS_TRANSFLOW.khh is '交易账户开户行'; comment on column URP.E_HIS_TRANSFLOW.khzh is '交易账户开户账号'; comment on column URP.E_HIS_TRANSFLOW.jylsh is '交易流水号'; comment on column URP.E_HIS_TRANSFLOW.jyckh is '交易参考号'; comment on column URP.E_HIS_TRANSFLOW.ddbh is '订单编号'; comment on column URP.E_HIS_TRANSFLOW.zdbh is '账单编号'; comment on column URP.E_HIS_TRANSFLOW.brjzkye is '病人就诊卡余额'; comment on column URP.E_HIS_TRANSFLOW.czm is '操作码'; comment on column URP.E_HIS_TRANSFLOW.jysj is '交易时间'; comment on column URP.E_HIS_TRANSFLOW.jyylx is '交易源类型(自助、窗口、诊间)'; comment on column URP.E_HIS_TRANSFLOW.jyshbh is '交易商户编号'; comment on column URP.E_HIS_TRANSFLOW.jyzdbh is '交易终端编号(终端号或医院终端标识)'; comment on column URP.E_HIS_TRANSFLOW.jysbbs is '交易设备标识(用以判断哪台设备:如设备编号/设备序列号)'; comment on column URP.E_HIS_TRANSFLOW.jyrzzh is '交易入账账号'; comment on column URP.E_HIS_TRANSFLOW.yhlsh is '银行流水号'; comment on column URP.E_HIS_TRANSFLOW.yhckh is '银行参考号'; comment on column URP.E_HIS_TRANSFLOW.pch is '批次号'; comment on column URP.E_HIS_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.E_HIS_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.E_HIS_TRANSFLOW.dzrq is '对账日期'; comment on column URP.E_HIS_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.E_HIS_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.E_HIS_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.E_HIS_TRANSFLOW.jgbm is '机构编码'; comment on column URP.E_HIS_TRANSFLOW.blh is '病人病历号'; comment on column URP.E_HIS_TRANSFLOW.yjyh is '原交易订单号/流水号(反向交易时不为空)'; comment on column URP.E_HIS_TRANSFLOW.ybfdje is '医保负担/报销总金额(医保支付时赋值)'; comment on column URP.E_HIS_TRANSFLOW.grzhzfje is '个人账户支付金额(医保支付时赋值)'; comment on column URP.E_HIS_TRANSFLOW.xjzfje is '现金支付金额(医保支付时赋值)'; comment on column URP.E_HIS_TRANSFLOW.yljmje is '医疗减免金额(医保支付时赋值)'; comment on column URP.E_HIS_TRANSFLOW.ylbzje is '医疗补助金额(医保支付时赋值)'; comment on column URP.E_HIS_TRANSFLOW.flag is '是否自助(1:是,0:否)'; comment on column URP.E_HIS_TRANSFLOW.mzzybs is '门诊住院标识(1:门诊,2:住院)'; comment on column URP.E_HIS_TRANSFLOW.dzbh is '对账编号'; comment on column URP.E_HIS_TRANSFLOW.bz is '备注'; comment on column URP.E_HIS_TRANSFLOW.bly1 is '保留域1(过期退费标志 0:非过期,1:过期退费)'; comment on column URP.E_HIS_TRANSFLOW.bly2 is '保留域2'; comment on column URP.E_HIS_TRANSFLOW.bly3 is '保留域3'; comment on column URP.E_HIS_TRANSFLOW.yhryxm is '医护人员(操作员)姓名'; comment on column URP.E_HIS_TRANSFLOW.sfzhm is '患者身份证号码'; comment on column URP.E_HIS_TRANSFLOW.bcjywybs is '本次就医唯一标识(可为就诊卡号或身份证号或医保卡号等,必须能唯一标识本次就医)'; alter table URP.E_HIS_TRANSFLOW add constraint E_HISTRANSFLOW_PRIMARYKEY primary key (YNHISLSID); prompt prompt Creating table E_REALTIME_MONITOR prompt ================================= prompt create table URP.E_REALTIME_MONITOR ( ssjkid VARCHAR2(32) default sys_guid() not null, ynjksblsid VARCHAR2(32), ynjkhislsid VARCHAR2(32), ycdl VARCHAR2(10), ycxl VARCHAR2(10), ycnr VARCHAR2(256), jlcjsj TIMESTAMP(6) default sysdate not null, cljg VARCHAR2(2) default 0, clwcsj TIMESTAMP(6), ycclbs VARCHAR2(2) default 0, ycclfjmc VARCHAR2(50), ycclfjlj VARCHAR2(200), ycclms VARCHAR2(100), ycclsj TIMESTAMP(6), ycclr VARCHAR2(20), sfsc VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, bz VARCHAR2(100), bly VARCHAR2(50) ) ; comment on table URP.E_REALTIME_MONITOR is '设备实时监控表'; comment on column URP.E_REALTIME_MONITOR.ssjkid is '实时监控id, 主键'; comment on column URP.E_REALTIME_MONITOR.ynjksblsid is '院内对账监控--设备对账流水主键ID'; comment on column URP.E_REALTIME_MONITOR.ynjkhislsid is '院内对账监控--His对账流水表主键ID'; comment on column URP.E_REALTIME_MONITOR.ycdl is '异常大类'; comment on column URP.E_REALTIME_MONITOR.ycxl is '异常小类'; comment on column URP.E_REALTIME_MONITOR.ycnr is '异常内容'; comment on column URP.E_REALTIME_MONITOR.jlcjsj is '记录创建时间'; comment on column URP.E_REALTIME_MONITOR.cljg is '处理结果(0:未处理,1:处理成功,2:处理失败)'; comment on column URP.E_REALTIME_MONITOR.clwcsj is '处理完成时间'; comment on column URP.E_REALTIME_MONITOR.ycclbs is '异常处理标识(1:已处理,0:未处理)'; comment on column URP.E_REALTIME_MONITOR.ycclfjmc is '异常处理附件名称'; comment on column URP.E_REALTIME_MONITOR.ycclfjlj is '异常处理附件保存路径'; comment on column URP.E_REALTIME_MONITOR.ycclms is '异常处理描述'; comment on column URP.E_REALTIME_MONITOR.ycclsj is '异常处理时间'; comment on column URP.E_REALTIME_MONITOR.ycclr is '异常处理人'; comment on column URP.E_REALTIME_MONITOR.sfsc is '是否删除(0:未删除,1:已删除)'; comment on column URP.E_REALTIME_MONITOR.jgbm is '机构编码'; comment on column URP.E_REALTIME_MONITOR.bz is '备注(失败次数)'; comment on column URP.E_REALTIME_MONITOR.bly is '保留域'; alter table URP.E_REALTIME_MONITOR add constraint E_REALTIMEMONITOR_PRIMARYKEY primary key (SSJKID); prompt prompt Creating table E_RECONFILE_INFO prompt =============================== prompt create table URP.E_RECONFILE_INFO ( dzwjid VARCHAR2(32) default sys_guid() not null, sbcsid VARCHAR2(32) not null, wjmc VARCHAR2(50) not null, wjlj VARCHAR2(100) not null, czsj TIMESTAMP(6) default sysdate not null, czjg VARCHAR2(2) not null, czjgms VARCHAR2(100), dzrq DATE not null, rkzt VARCHAR2(2) default 0 not null, bz VARCHAR2(100), sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.E_RECONFILE_INFO is '设备对账文件 管理表'; comment on column URP.E_RECONFILE_INFO.dzwjid is '对账文件ID,区分文件'; comment on column URP.E_RECONFILE_INFO.sbcsid is '设备厂商主键id'; comment on column URP.E_RECONFILE_INFO.wjmc is '对账文件名称'; comment on column URP.E_RECONFILE_INFO.wjlj is '对账文件下载后存放路径'; comment on column URP.E_RECONFILE_INFO.czsj is '操作时间(对账文件下载/上传时间)'; comment on column URP.E_RECONFILE_INFO.czjg is '操作结果(对账文件下载/上传结果(1:成功,0:失败))'; comment on column URP.E_RECONFILE_INFO.czjgms is '操作结果描述(对账文件下载/上传结果描述)'; comment on column URP.E_RECONFILE_INFO.dzrq is '对账日期(手工对账时可指定)'; comment on column URP.E_RECONFILE_INFO.rkzt is '对账文件入库状态(0:未入库,1:已入库,2:入库失败)'; comment on column URP.E_RECONFILE_INFO.bz is '备注'; comment on column URP.E_RECONFILE_INFO.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.E_RECONFILE_INFO.bly1 is '保留域1'; comment on column URP.E_RECONFILE_INFO.bly2 is '保留域2'; comment on column URP.E_RECONFILE_INFO.bly3 is '保留域3'; alter table URP.E_RECONFILE_INFO add constraint E_RECONFILEINFO_PRIMARYKEY primary key (DZWJID); prompt prompt Creating table E_RECONFILE_REDOWNLOAD prompt ===================================== prompt create table URP.E_RECONFILE_REDOWNLOAD ( dzwjcxzid VARCHAR2(32) default sys_guid() not null, sbcsid VARCHAR2(32) not null, dzrq DATE not null, xzjg VARCHAR2(2) not null, sbyy VARCHAR2(50), xzcs NUMBER default 0 not null, jlcjsj TIMESTAMP(6) not null, zhxzsj TIMESTAMP(6) not null, jgbm VARCHAR2(15) not null, bz VARCHAR2(100) ) ; comment on table URP.E_RECONFILE_REDOWNLOAD is '对账文件重下载表'; comment on column URP.E_RECONFILE_REDOWNLOAD.dzwjcxzid is '对账文件重下载ID'; comment on column URP.E_RECONFILE_REDOWNLOAD.sbcsid is '设备厂商主键id'; comment on column URP.E_RECONFILE_REDOWNLOAD.dzrq is '对账日期'; comment on column URP.E_RECONFILE_REDOWNLOAD.xzjg is '下载结果(0:失败,1:成功)'; comment on column URP.E_RECONFILE_REDOWNLOAD.sbyy is '下载失败原因'; comment on column URP.E_RECONFILE_REDOWNLOAD.xzcs is '下载次数'; comment on column URP.E_RECONFILE_REDOWNLOAD.jlcjsj is '记录创建时间'; comment on column URP.E_RECONFILE_REDOWNLOAD.zhxzsj is '最后下载时间'; comment on column URP.E_RECONFILE_REDOWNLOAD.jgbm is '机构编码'; comment on column URP.E_RECONFILE_REDOWNLOAD.bz is '备注'; alter table URP.E_RECONFILE_REDOWNLOAD add constraint ERECONFILEREDOWNLOADPRIMARYKEY primary key (DZWJCXZID); prompt prompt Creating table E_RECONRESULT_DETAIL prompt =================================== prompt create table URP.E_RECONRESULT_DETAIL ( yndzjgmxid VARCHAR2(32) default sys_guid() not null, sbid VARCHAR2(32) not null, sbcsid VARCHAR2(32) not null, ynhislsid VARCHAR2(32), ynsblsid VARCHAR2(32), dzjg VARCHAR2(2) default 1 not null, yclx VARCHAR2(2), dzjgms VARCHAR2(100), dzrq DATE default sysdate not null, jlsj TIMESTAMP(6) not null, qdzhid VARCHAR2(32), ycclbs VARCHAR2(2), ycclfjmc VARCHAR2(50), ycclfjlj VARCHAR2(100), ycclms VARCHAR2(100), ycclsj TIMESTAMP(6), ycclr VARCHAR2(20), bz VARCHAR2(100), sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.E_RECONRESULT_DETAIL is '设备对账结果明细表'; comment on column URP.E_RECONRESULT_DETAIL.yndzjgmxid is '院内对账结果明细表主键Id'; comment on column URP.E_RECONRESULT_DETAIL.sbid is '设备主键Id'; comment on column URP.E_RECONRESULT_DETAIL.sbcsid is '设备厂商主键id'; comment on column URP.E_RECONRESULT_DETAIL.ynhislsid is '院内对账--HIS对账流水表主键ID'; comment on column URP.E_RECONRESULT_DETAIL.ynsblsid is '院内对账--设备对账流水主键 ID'; comment on column URP.E_RECONRESULT_DETAIL.dzjg is '对账结果(1:正常交易/0:异常交易)'; comment on column URP.E_RECONRESULT_DETAIL.yclx is '根据对账结果,为交易打上标识(0:正常交易,1:HIS有设备无,2:His无设备有,3:设备成功、HIS失败,4:HIS成功、设备失败,5:HIS一条记录、设备多条记录,6:HIS多条记录、设备一条记录,7:HIS与设备金额不一致)'; comment on column URP.E_RECONRESULT_DETAIL.dzjgms is '对账结果描述'; comment on column URP.E_RECONRESULT_DETAIL.dzrq is '对账日期'; comment on column URP.E_RECONRESULT_DETAIL.jlsj is '对账结果记录时间'; comment on column URP.E_RECONRESULT_DETAIL.qdzhid is '渠道账户表主键ID'; comment on column URP.E_RECONRESULT_DETAIL.ycclbs is '异常处理标识(1:已处理,0:未处理)'; comment on column URP.E_RECONRESULT_DETAIL.ycclfjmc is '异常处理附件名称'; comment on column URP.E_RECONRESULT_DETAIL.ycclfjlj is '异常处理附件保存路径'; comment on column URP.E_RECONRESULT_DETAIL.ycclms is '异常处理描述(备注)'; comment on column URP.E_RECONRESULT_DETAIL.ycclsj is '异常处理时间'; comment on column URP.E_RECONRESULT_DETAIL.ycclr is '异常处理人'; comment on column URP.E_RECONRESULT_DETAIL.bz is '备注'; comment on column URP.E_RECONRESULT_DETAIL.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.E_RECONRESULT_DETAIL.bly1 is '保留域1'; comment on column URP.E_RECONRESULT_DETAIL.bly2 is '保留域2'; comment on column URP.E_RECONRESULT_DETAIL.bly3 is '保留域3'; alter table URP.E_RECONRESULT_DETAIL add constraint ERECONRESULT_DETAIL_PRIMARYKEY primary key (YNDZJGMXID); prompt prompt Creating table E_RECON_HISTORY prompt ============================== prompt create table URP.E_RECON_HISTORY ( dzjglstjid VARCHAR2(32) default sys_guid() not null, dzrq DATE not null, dzcs VARCHAR2(100), wcdzcs VARCHAR2(100), wwcdzcs VARCHAR2(100), wdzcs VARCHAR2(100), zpcs VARCHAR2(100), zbpcs VARCHAR2(50), dzcssl NUMBER default 0, wcdzcssl NUMBER default 0, wwcdzcssl NUMBER default 0, wdzcssl NUMBER default 0, zpcssl NUMBER default 0, zbpcssl NUMBER default 0, csjyzbs NUMBER default 0, csjyzje NUMBER(12,2) default 0.00, csycjyzbs NUMBER default 0, csycjyzje NUMBER(12,2) default 0.00, hisjyzbs NUMBER default 0, hisjyzje NUMBER(12,2) default 0.00, hisycjyzje NUMBER(12,2) default 0.00, hisycjyzbs NUMBER default 0, jyhztj VARCHAR2(1000), jgbm VARCHAR2(15), sfsc VARCHAR2(2), bz VARCHAR2(100), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.E_RECON_HISTORY is '设备对账结果历史统计表'; comment on column URP.E_RECON_HISTORY.dzjglstjid is '对账结果历史统计表Id'; comment on column URP.E_RECON_HISTORY.dzrq is '对账日期'; comment on column URP.E_RECON_HISTORY.dzcs is '对账厂商'; comment on column URP.E_RECON_HISTORY.wcdzcs is '完成对账厂商'; comment on column URP.E_RECON_HISTORY.wwcdzcs is '未完成对账厂商'; comment on column URP.E_RECON_HISTORY.wdzcs is '未对账厂商'; comment on column URP.E_RECON_HISTORY.zpcs is '账平厂商'; comment on column URP.E_RECON_HISTORY.zbpcs is '账不平厂商'; comment on column URP.E_RECON_HISTORY.dzcssl is '对账厂商数量'; comment on column URP.E_RECON_HISTORY.wcdzcssl is '完成对账厂商数量'; comment on column URP.E_RECON_HISTORY.wwcdzcssl is '未完成对账厂商数量'; comment on column URP.E_RECON_HISTORY.wdzcssl is '未对账厂商数量'; comment on column URP.E_RECON_HISTORY.zpcssl is '账平厂商数量'; comment on column URP.E_RECON_HISTORY.zbpcssl is '账不平厂商数量'; comment on column URP.E_RECON_HISTORY.csjyzbs is '厂商交易总笔数'; comment on column URP.E_RECON_HISTORY.csjyzje is '厂商交易总金额'; comment on column URP.E_RECON_HISTORY.csycjyzbs is '厂商异常交易总笔数'; comment on column URP.E_RECON_HISTORY.csycjyzje is '厂商异常交易总金额'; comment on column URP.E_RECON_HISTORY.hisjyzbs is 'His交易总笔数'; comment on column URP.E_RECON_HISTORY.hisjyzje is 'His交易总金额'; comment on column URP.E_RECON_HISTORY.hisycjyzje is 'His异常交易总金额'; comment on column URP.E_RECON_HISTORY.hisycjyzbs is 'His异常交易总笔数'; comment on column URP.E_RECON_HISTORY.jyhztj is '交易汇总信息分类统计(统计每个厂商,设备/His交易总笔数、总金额、异常笔数、异常金额,以“|”分割)'; comment on column URP.E_RECON_HISTORY.jgbm is '机构编码'; comment on column URP.E_RECON_HISTORY.sfsc is '是否删除(1:已删除,0:未删除)'; comment on column URP.E_RECON_HISTORY.bz is '备注'; comment on column URP.E_RECON_HISTORY.bly1 is '保留域1'; comment on column URP.E_RECON_HISTORY.bly2 is '保留域2'; comment on column URP.E_RECON_HISTORY.bly3 is '保留域3'; alter table URP.E_RECON_HISTORY add constraint E_RECONHISSTATISTICS_PK primary key (DZJGLSTJID); prompt prompt Creating table GF_BANKTRANS prompt =========================== prompt create table URP.GF_BANKTRANS ( yyzh VARCHAR2(32) not null, fhjybs NUMBER(15), ybs VARCHAR2(2), xyjyrq VARCHAR2(10), xycbsjylsh VARCHAR2(12), xyjydh VARCHAR2(5), jyxh VARCHAR2(20), jyrq DATE, jdbz VARCHAR2(2), jyje NUMBER(20,2), zfbz VARCHAR2(2), kyye NUMBER(20,2), ywms VARCHAR2(32), jyhs VARCHAR2(40), pzhm VARCHAR2(16), dfzh VARCHAR2(32) not null, dfhm VARCHAR2(82), dsfhh VARCHAR2(14), jysj DATE, fjxx VARCHAR2(30), jyqd VARCHAR2(20), bz VARCHAR2(22), fy VARCHAR2(102), dszhlx VARCHAR2(2), wybsm VARCHAR2(32) not null, cbsjyxh VARCHAR2(5), kjrq VARCHAR2(50), qycwlsh VARCHAR2(50) not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50) ) ; comment on column URP.GF_BANKTRANS.yyzh is '医院账号'; comment on column URP.GF_BANKTRANS.fhjybs is '返回交易笔数'; comment on column URP.GF_BANKTRANS.ybs is '页标识,0:不存在下一页 1:存在下一页'; comment on column URP.GF_BANKTRANS.xyjyrq is '下页交易日期,当“页标识”为1时,此域不为空 日期格式(YYYYMMDD)'; comment on column URP.GF_BANKTRANS.xycbsjylsh is '下页CBS交易流水号,当“页标识”为1时,此域不为空'; comment on column URP.GF_BANKTRANS.xyjydh is '下页交易代号,当“页标识”为1时,此域不为空'; comment on column URP.GF_BANKTRANS.jyxh is '交易序号,循环域'; comment on column URP.GF_BANKTRANS.jyrq is '交易日期,循环域 日期格式(YYYYMMDD)'; comment on column URP.GF_BANKTRANS.jdbz is '借贷标志,循环域 +/-'; comment on column URP.GF_BANKTRANS.jyje is '交易金额,循环域 实际数字是(19,2)小数点占一位,整数部分占17位'; comment on column URP.GF_BANKTRANS.zfbz is '正负标志,循环域 +/-'; comment on column URP.GF_BANKTRANS.kyye is '可用余额,循环域 实际数字是(19,2)小数点占一位,整数部分占17位'; comment on column URP.GF_BANKTRANS.ywms is '业务描述,循环域 如: 资金上拔 资金下划'; comment on column URP.GF_BANKTRANS.jyhs is '交易行所,循环域'; comment on column URP.GF_BANKTRANS.pzhm is '凭证号码,循环域'; comment on column URP.GF_BANKTRANS.dfzh is '对方账号,循环域'; comment on column URP.GF_BANKTRANS.dfhm is '对方户名,循环域'; comment on column URP.GF_BANKTRANS.dsfhh is '对手方行号,循环域 行内交易显示行所号,行外交易显示联行号'; comment on column URP.GF_BANKTRANS.jysj is '交易时间,循环域 时间格式(HHMMSS)'; comment on column URP.GF_BANKTRANS.fjxx is '附加信息,循环域'; comment on column URP.GF_BANKTRANS.jyqd is '交易渠道,循环域'; comment on column URP.GF_BANKTRANS.bz is '备注,循环域'; comment on column URP.GF_BANKTRANS.fy is '附言,循环域'; comment on column URP.GF_BANKTRANS.dszhlx is '对手账号类型,循环域 1-对公 0-对私 空-非我行账号'; comment on column URP.GF_BANKTRANS.wybsm is '唯一标识码,循环域 可全行标识交易唯一性 '; comment on column URP.GF_BANKTRANS.cbsjyxh is 'CBS交易序号,循环域'; comment on column URP.GF_BANKTRANS.kjrq is '会计日期,循环域'; comment on column URP.GF_BANKTRANS.qycwlsh is '企业财务流水号,循环域,批量转账交易为客户批次流水号'; comment on column URP.GF_BANKTRANS.bly1 is '预留字段1,暂时未使用'; comment on column URP.GF_BANKTRANS.bly2 is '预留字段2,暂时未使用'; alter table URP.GF_BANKTRANS add primary key (WYBSM); prompt prompt Creating table GF_BANKTRANS_ACCOUNTS prompt ==================================== prompt create table URP.GF_BANKTRANS_ACCOUNTS ( id VARCHAR2(32) default sys_guid() not null, khpch VARCHAR2(20), fkzh VARCHAR2(20), zjjybs NUMBER(16), zjjyje NUMBER(16,2), zjjysxf NUMBER(16,2), cgbs NUMBER(5), sbbs NUMBER(5), zzclbs NUMBER(5), khpczlsh VARCHAR2(20) not null, sxf NUMBER(16,2), jyclzt VARCHAR2(15), dzhdjym VARCHAR2(6), dzhdh VARCHAR2(20), sbyy VARCHAR2(200), sfsc VARCHAR2(1), czr VARCHAR2(2), czsj TIMESTAMP(6) default sysdate, zhxgr VARCHAR2(2), zhxgsj TIMESTAMP(6), jysj VARCHAR2(20), bz VARCHAR2(200), jyje NUMBER(12,2) default 0, inname VARCHAR2(60), inacc VARCHAR2(40), errcode VARCHAR2(25), businesstype VARCHAR2(2) ) ; comment on column URP.GF_BANKTRANS_ACCOUNTS.id is '主键Id'; comment on column URP.GF_BANKTRANS_ACCOUNTS.khpch is '客户批次号customerBatchNo_批次信息(一批包含多个子流水)'; comment on column URP.GF_BANKTRANS_ACCOUNTS.fkzh is '付款账号accountNo_批次信息'; comment on column URP.GF_BANKTRANS_ACCOUNTS.zjjybs is '总计交易笔数allCount_批次信息'; comment on column URP.GF_BANKTRANS_ACCOUNTS.zjjyje is '总计交易金额allSalary_批次信息'; comment on column URP.GF_BANKTRANS_ACCOUNTS.zjjysxf is '总计交易手续费allHandlefee_批次信息'; comment on column URP.GF_BANKTRANS_ACCOUNTS.cgbs is '成功笔数count_批次信息'; comment on column URP.GF_BANKTRANS_ACCOUNTS.sbbs is '失败笔数errCount_批次信息'; comment on column URP.GF_BANKTRANS_ACCOUNTS.zzclbs is '正在处理笔数unknowCount_批次信息'; comment on column URP.GF_BANKTRANS_ACCOUNTS.khpczlsh is '客户批次子流水号,(主键)customerSalarySeq'; comment on column URP.GF_BANKTRANS_ACCOUNTS.sxf is '手续费fee'; comment on column URP.GF_BANKTRANS_ACCOUNTS.jyclzt is '交易处理状态state(failed:转账失败,transferred:转账、退款成功,transferring:转账中)'; comment on column URP.GF_BANKTRANS_ACCOUNTS.dzhdjym is '电子回单校验码'; comment on column URP.GF_BANKTRANS_ACCOUNTS.dzhdh is '电子回单号ewpSequence'; comment on column URP.GF_BANKTRANS_ACCOUNTS.sbyy is '失败原因errorreason'; comment on column URP.GF_BANKTRANS_ACCOUNTS.sfsc is '是否删除(0:是,1:否)'; comment on column URP.GF_BANKTRANS_ACCOUNTS.czr is '操作人'; comment on column URP.GF_BANKTRANS_ACCOUNTS.czsj is '操作时间'; comment on column URP.GF_BANKTRANS_ACCOUNTS.zhxgr is '最后修改人'; comment on column URP.GF_BANKTRANS_ACCOUNTS.zhxgsj is '最后修改时间'; comment on column URP.GF_BANKTRANS_ACCOUNTS.jysj is '交易时间_子流水交易时间jysj(yyyymmdd)'; comment on column URP.GF_BANKTRANS_ACCOUNTS.bz is '备注'; comment on column URP.GF_BANKTRANS_ACCOUNTS.jyje is '交易金额'; comment on column URP.GF_BANKTRANS_ACCOUNTS.inname is '转入户名'; comment on column URP.GF_BANKTRANS_ACCOUNTS.inacc is '转入账号'; comment on column URP.GF_BANKTRANS_ACCOUNTS.errcode is '失败错误码'; comment on column URP.GF_BANKTRANS_ACCOUNTS.businesstype is '业务类型:1、费用报销,2、其他代付,3、代发工资,4、慧支付,6、代付理赔'; alter table URP.GF_BANKTRANS_ACCOUNTS add primary key (ID); prompt prompt Creating table HIS_TRANSFLOW prompt ============================ prompt create table URP.HIS_TRANSFLOW ( hislsid VARCHAR2(32) default sys_guid() not null, qdid VARCHAR2(32) not null, yhrybh VARCHAR2(30), brjzkh VARCHAR2(30), brxm VARCHAR2(100), fpbh VARCHAR2(50), jyqdbs VARCHAR2(20) not null, ywlx VARCHAR2(10), jyje NUMBER(12,2) not null, khh VARCHAR2(30), khzh VARCHAR2(30), jylsh VARCHAR2(30), jyckh VARCHAR2(50), ddbh VARCHAR2(50), zdbh VARCHAR2(32), brjzkye NUMBER(12,2), czm VARCHAR2(20), jysj VARCHAR2(25), jyylx VARCHAR2(10), jyshbh VARCHAR2(20), jyzdbh VARCHAR2(30), jyrzzh VARCHAR2(50), yhlsh VARCHAR2(30), yhckh VARCHAR2(50), pch VARCHAR2(10), sfsc VARCHAR2(2) default 0 not null, jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jyzt VARCHAR2(2) default 1 not null, bz VARCHAR2(100), bly1 VARCHAR2(50) default 0, bly2 VARCHAR2(50), bly3 VARCHAR2(50), jgbm VARCHAR2(15) not null, blh VARCHAR2(30), yjyh VARCHAR2(30), ybfdje NUMBER(12,2), grzhzfje NUMBER(12,2), xjzfje NUMBER(12,2), yljmje NUMBER(12,2), ylbzje NUMBER(12,2), flag VARCHAR2(2), mzzybs VARCHAR2(2), dzbh VARCHAR2(50) not null, jysbbs VARCHAR2(30), sbcsbm VARCHAR2(30), yhryxm VARCHAR2(50), sfzhm VARCHAR2(18), bcjywybs VARCHAR2(30) ) ; comment on table URP.HIS_TRANSFLOW is 'HIS 流水表'; comment on column URP.HIS_TRANSFLOW.hislsid is '流水id, 主键'; comment on column URP.HIS_TRANSFLOW.qdid is '渠道id, 对应交易流水渠道'; comment on column URP.HIS_TRANSFLOW.yhrybh is '医护人员编号'; comment on column URP.HIS_TRANSFLOW.brjzkh is '病人就诊卡号'; comment on column URP.HIS_TRANSFLOW.brxm is '病人姓名'; comment on column URP.HIS_TRANSFLOW.fpbh is '发票编号'; comment on column URP.HIS_TRANSFLOW.jyqdbs is '交易渠道标识(微信、支付宝、医保)'; comment on column URP.HIS_TRANSFLOW.ywlx is '业务类型'; comment on column URP.HIS_TRANSFLOW.jyje is '交易金额'; comment on column URP.HIS_TRANSFLOW.khh is '交易账户开户行'; comment on column URP.HIS_TRANSFLOW.khzh is '交易账户开户账号'; comment on column URP.HIS_TRANSFLOW.jylsh is '交易流水号'; comment on column URP.HIS_TRANSFLOW.jyckh is '交易参考号(-> jshid)'; comment on column URP.HIS_TRANSFLOW.ddbh is '订单编号'; comment on column URP.HIS_TRANSFLOW.zdbh is '账单编号'; comment on column URP.HIS_TRANSFLOW.brjzkye is '病人就诊卡余额'; comment on column URP.HIS_TRANSFLOW.czm is '操作码'; comment on column URP.HIS_TRANSFLOW.jysj is '交易时间'; comment on column URP.HIS_TRANSFLOW.jyylx is '交易源类型(自助、窗口、诊间)'; comment on column URP.HIS_TRANSFLOW.jyshbh is '交易商户编号'; comment on column URP.HIS_TRANSFLOW.jyzdbh is '交易终端编号(终端号或医院终端标识)'; comment on column URP.HIS_TRANSFLOW.jyrzzh is '交易入账账号'; comment on column URP.HIS_TRANSFLOW.yhlsh is '银行流水号(->his的住院流水号)'; comment on column URP.HIS_TRANSFLOW.yhckh is '银行参考号'; comment on column URP.HIS_TRANSFLOW.pch is '批次号'; comment on column URP.HIS_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.HIS_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.HIS_TRANSFLOW.dzrq is '对账日期'; comment on column URP.HIS_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.HIS_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.HIS_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.HIS_TRANSFLOW.bz is '备注'; comment on column URP.HIS_TRANSFLOW.bly1 is '含义:1.记录广发的具体渠道,2.医保交易时(pos交易为:UnionPay,省统筹交易:记录省统筹的的医保总金额【除pos和市医保之外 】)'; comment on column URP.HIS_TRANSFLOW.bly2 is '保留域2(记录his对应的医保特殊类型,如 8:门诊省医保(mzsyb),9、住院省医保(zysyb),10:门诊异地医保(mzydyb),11:住院异地医保(zyydyb),12:门诊省医保POS(mzsybpos),13:住院省医保POS(zysybpos),14:门诊异地医保POS(mzydybpos),15:住院异地医保POS(zyydybpos) )'; comment on column URP.HIS_TRANSFLOW.bly3 is '保留域3(操作员编码 对应his的operatorCode)'; comment on column URP.HIS_TRANSFLOW.jgbm is '机构编码'; comment on column URP.HIS_TRANSFLOW.blh is '病人病历号'; comment on column URP.HIS_TRANSFLOW.yjyh is '原交易订单号/流水号(反向交易时不为空)'; comment on column URP.HIS_TRANSFLOW.ybfdje is '医保负担/报销总金额(医保支付时赋值)'; comment on column URP.HIS_TRANSFLOW.grzhzfje is '个人账户支付金额(医保支付时赋值)'; comment on column URP.HIS_TRANSFLOW.xjzfje is '现金支付金额(医保支付时赋值)'; comment on column URP.HIS_TRANSFLOW.yljmje is '医疗减免金额(医保支付时赋值)'; comment on column URP.HIS_TRANSFLOW.ylbzje is '医疗补助金额(医保支付时赋值)'; comment on column URP.HIS_TRANSFLOW.flag is '是否自助终端(1:是,0:否)'; comment on column URP.HIS_TRANSFLOW.mzzybs is '门诊住院标识(1:门诊,2:住院)'; comment on column URP.HIS_TRANSFLOW.dzbh is '对账编号'; comment on column URP.HIS_TRANSFLOW.jysbbs is '交易设备标识(设备编号)'; comment on column URP.HIS_TRANSFLOW.sbcsbm is '设备厂商编码'; comment on column URP.HIS_TRANSFLOW.yhryxm is '医护人员(操作员)姓名'; comment on column URP.HIS_TRANSFLOW.sfzhm is '患者身份证号码'; comment on column URP.HIS_TRANSFLOW.bcjywybs is '本次就医唯一标识(可为就诊卡号或身份证号或医保卡号等,必须能唯一标识本次就医)'; create index URP.HIS_SFSC_DZBS on URP.HIS_TRANSFLOW (SFSC, DZBS); create index URP.IDX_BB_QD on URP.HIS_TRANSFLOW (QDID, DDBH, BRXM, BRJZKH); create index URP.IDX_DJQ on URP.HIS_TRANSFLOW (DZRQ, JGBM, JYQDBS, JYRZZH); alter table URP.HIS_TRANSFLOW add constraint HISTRANSFLOW_PRIMARYKEY primary key (HISLSID); prompt prompt Creating table ICASHIER_TRANSFLOW prompt ================================= prompt create table URP.ICASHIER_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50), jylsh VARCHAR2(50), qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30), zdhm VARCHAR2(50), spmc VARCHAR2(30), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50) ) ; comment on table URP.ICASHIER_TRANSFLOW is '融合支付交易流水表'; comment on column URP.ICASHIER_TRANSFLOW.lsid is '融合支付流水主键ID'; comment on column URP.ICASHIER_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.ICASHIER_TRANSFLOW.shbh is '商户编号'; comment on column URP.ICASHIER_TRANSFLOW.zdbh is '终端编号'; comment on column URP.ICASHIER_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.ICASHIER_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.ICASHIER_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.ICASHIER_TRANSFLOW.yjylsh is '原交易流水号:交易为后续类交易时有值'; comment on column URP.ICASHIER_TRANSFLOW.shddh is '商户订单号'; comment on column URP.ICASHIER_TRANSFLOW.zdhm is '账单号码'; comment on column URP.ICASHIER_TRANSFLOW.spmc is '商品名称'; comment on column URP.ICASHIER_TRANSFLOW.jysj is '交易时间'; comment on column URP.ICASHIER_TRANSFLOW.yhjyzh is '用户交易账号(ICASHIER账号/银行卡号)'; comment on column URP.ICASHIER_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.ICASHIER_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.ICASHIER_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.ICASHIER_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.ICASHIER_TRANSFLOW.jybz is '交易备注'; comment on column URP.ICASHIER_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.ICASHIER_TRANSFLOW.dzrq is '对账日期'; comment on column URP.ICASHIER_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.ICASHIER_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.ICASHIER_TRANSFLOW.jgbm is '机构编码'; comment on column URP.ICASHIER_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.ICASHIER_TRANSFLOW.bly1 is '保留域1'; comment on column URP.ICASHIER_TRANSFLOW.bly2 is '保留域2'; comment on column URP.ICASHIER_TRANSFLOW.bly3 is '保留域3'; comment on column URP.ICASHIER_TRANSFLOW.dzbh is '对账编号'; alter table URP.ICASHIER_TRANSFLOW add constraint ICASHIER_TRANSFLOW_PRIMARYKEY primary key (LSID); prompt prompt Creating table INST_INFO prompt ======================== prompt create table URP.INST_INFO ( jgbm VARCHAR2(15) not null, jgmc VARCHAR2(50) not null, jgzt VARCHAR2(2) not null, jlcjsj TIMESTAMP(6) default sysdate, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6) default sysdate, zhxgr VARCHAR2(20), bz VARCHAR2(100), crssid VARCHAR2(32) ) ; comment on table URP.INST_INFO is '机构(医院)信息'; comment on column URP.INST_INFO.jgbm is '主键,机构编码,用于区分机构'; comment on column URP.INST_INFO.jgmc is '机构名称'; comment on column URP.INST_INFO.jgzt is '机构状态(1:正常,0:禁用/删除)'; comment on column URP.INST_INFO.jlcjsj is '记录创建时间'; comment on column URP.INST_INFO.cjr is '创建人'; comment on column URP.INST_INFO.zhxgsj is '最后更新时间'; comment on column URP.INST_INFO.zhxgr is '最后更新人'; comment on column URP.INST_INFO.bz is '备注'; comment on column URP.INST_INFO.crssid is 'crss中对应机构唯一标识'; create index URP.JGBM_JGZT on URP.INST_INFO (JGBM, JGZT); alter table URP.INST_INFO add constraint INST_PRIMARYKEY primary key (JGBM); prompt prompt Creating table MEDICARE_TRANSFLOW prompt ================================= prompt create table URP.MEDICARE_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), jshid VARCHAR2(50) not null, jyje NUMBER(12,2) not null, ybfdje NUMBER(12,2), grzhzfje NUMBER(12,2), xjzfje NUMBER(12,2), yljmje NUMBER(12,2), ylbzje NUMBER(12,2), qzjbzhzfje NUMBER(12,2), jysj VARCHAR2(20), grbh VARCHAR2(32), xm VARCHAR2(30), yltclb VARCHAR2(2), xzbz VARCHAR2(2), jsbz VARCHAR2(2), jyzt VARCHAR2(2) default 1 not null, jlcjsj TIMESTAMP(6) not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50), jylsh VARCHAR2(50), ejbs VARCHAR2(15), sxf NUMBER(12,2) default 0.00, qsje NUMBER(12,2) default 0.00, qsrq VARCHAR2(20), shddh VARCHAR2(30) ) ; comment on table URP.MEDICARE_TRANSFLOW is '医保对账流水表'; comment on column URP.MEDICARE_TRANSFLOW.lsid is '医保对账流水主键Id'; comment on column URP.MEDICARE_TRANSFLOW.qdzhid is '渠道结算账户Id'; comment on column URP.MEDICARE_TRANSFLOW.jshid is '结算号Id'; comment on column URP.MEDICARE_TRANSFLOW.jyje is '交易总金额(单位:元)'; comment on column URP.MEDICARE_TRANSFLOW.ybfdje is '医保负担/报销总金额'; comment on column URP.MEDICARE_TRANSFLOW.grzhzfje is '个人账户支付金额'; comment on column URP.MEDICARE_TRANSFLOW.xjzfje is '现金支付金额'; comment on column URP.MEDICARE_TRANSFLOW.yljmje is '医疗减免金额'; comment on column URP.MEDICARE_TRANSFLOW.ylbzje is '医疗补助金额'; comment on column URP.MEDICARE_TRANSFLOW.qzjbzhzfje is '其中基本账户支付金额'; comment on column URP.MEDICARE_TRANSFLOW.jysj is '交易时间(病人结算日期)'; comment on column URP.MEDICARE_TRANSFLOW.grbh is '个人编号'; comment on column URP.MEDICARE_TRANSFLOW.xm is '姓名'; comment on column URP.MEDICARE_TRANSFLOW.yltclb is '医疗统筹类别(4:门诊大病,5:意外伤害,6:普通门诊统筹,其他具体值调用数据字典接口获取,代码编号:YLTCLB)'; comment on column URP.MEDICARE_TRANSFLOW.xzbz is '险种标志(C:医疗,D:工伤,E:生育)'; comment on column URP.MEDICARE_TRANSFLOW.jsbz is '结算标志(0:已撤销;1:未撤销)'; comment on column URP.MEDICARE_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.MEDICARE_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.MEDICARE_TRANSFLOW.dzrq is '对账日期'; comment on column URP.MEDICARE_TRANSFLOW.dzbs is '对账标识(1:已对账/0:未对账)'; comment on column URP.MEDICARE_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.MEDICARE_TRANSFLOW.jgbm is '机构编码'; comment on column URP.MEDICARE_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.MEDICARE_TRANSFLOW.bly1 is '保留域1'; comment on column URP.MEDICARE_TRANSFLOW.bly2 is '保留域2'; comment on column URP.MEDICARE_TRANSFLOW.bly3 is '保留域3->就诊卡号'; comment on column URP.MEDICARE_TRANSFLOW.dzbh is '对账编号'; comment on column URP.MEDICARE_TRANSFLOW.jylsh is '交易流水号(住院流水号)'; comment on column URP.MEDICARE_TRANSFLOW.ejbs is '二级标识'; comment on column URP.MEDICARE_TRANSFLOW.sxf is '手续费(单位:元)'; comment on column URP.MEDICARE_TRANSFLOW.qsje is '清算金额(单位:元)'; comment on column URP.MEDICARE_TRANSFLOW.qsrq is '清算日期'; comment on column URP.MEDICARE_TRANSFLOW.shddh is '商户订单号'; create index URP.MED_JXG on URP.MEDICARE_TRANSFLOW (JSHID, XM, GRBH); create index URP.MED_QJD on URP.MEDICARE_TRANSFLOW (DZRQ, JGBM, QDZHID); create index URP.MED_SFSC_DZBS on URP.MEDICARE_TRANSFLOW (DZBS, SFSC); alter table URP.MEDICARE_TRANSFLOW add constraint MEDICARE_TRANSFLOW_PK primary key (LSID); prompt prompt Creating table MONITOR_CONFIG prompt ============================= prompt create table URP.MONITOR_CONFIG ( jyjkpzid VARCHAR2(32) default sys_guid() not null, dxbm VARCHAR2(30) not null, jgbm VARCHAR2(15) not null, jyzhhqsj VARCHAR2(20) not null, sfsc VARCHAR2(2) default 0 not null, cjsj TIMESTAMP(6) not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6), zhxgr VARCHAR2(20), bz VARCHAR2(100) ) ; comment on table URP.MONITOR_CONFIG is '实时交易监控配置表'; comment on column URP.MONITOR_CONFIG.jyjkpzid is '实时交易监控配置表ID'; comment on column URP.MONITOR_CONFIG.dxbm is '监控对象编码(渠道:CHANNEL、设备:EQUIPMENT)'; comment on column URP.MONITOR_CONFIG.jgbm is '机构编码'; comment on column URP.MONITOR_CONFIG.jyzhhqsj is '交易最后获取时间(用于本次获取交易开始时间)'; comment on column URP.MONITOR_CONFIG.sfsc is '是否删除'; comment on column URP.MONITOR_CONFIG.cjsj is '创建时间'; comment on column URP.MONITOR_CONFIG.cjr is '创建人'; comment on column URP.MONITOR_CONFIG.zhxgsj is '最后修改时间'; comment on column URP.MONITOR_CONFIG.zhxgr is '最后修改人'; comment on column URP.MONITOR_CONFIG.bz is '备注'; alter table URP.MONITOR_CONFIG add constraint PK_MONITOR_CONFIG primary key (JYJKPZID); prompt prompt Creating table MSG_PUSH prompt ======================= prompt create table URP.MSG_PUSH ( tztsid VARCHAR2(32) default sys_guid() not null, ssjkid VARCHAR2(32) not null, cjsj DATE not null, fsfs VARCHAR2(10), jszh VARCHAR2(300), tszt VARCHAR2(2) not null, bz VARCHAR2(200) ) ; comment on table URP.MSG_PUSH is '消息推送表'; comment on column URP.MSG_PUSH.tztsid is '通知推送id,主键'; comment on column URP.MSG_PUSH.ssjkid is '实时流水监控主键'; comment on column URP.MSG_PUSH.cjsj is '创建时间'; comment on column URP.MSG_PUSH.fsfs is '发送方式(0:短信,1:微信,2:邮件)'; comment on column URP.MSG_PUSH.jszh is '接收账号'; comment on column URP.MSG_PUSH.tszt is '推送状态(1:推送成功、0:未推送,2:推送失败)'; comment on column URP.MSG_PUSH.bz is '备注'; alter table URP.MSG_PUSH add constraint MSGPUSH_PRIMARYKEY primary key (TZTSID); prompt prompt Creating table M_EQUIPMENT_TRANSFLOW prompt ==================================== prompt create table URP.M_EQUIPMENT_TRANSFLOW ( ynjksblsid VARCHAR2(32) default sys_guid() not null, yhrybh VARCHAR2(30) not null, brjzkh VARCHAR2(30), blh VARCHAR2(30), brxm VARCHAR2(100) not null, fpbh VARCHAR2(50), jyqdbs VARCHAR2(20) not null, ywlx VARCHAR2(10) not null, jyje NUMBER(12,2) not null, khh VARCHAR2(30), khzh VARCHAR2(30), jylsh VARCHAR2(30), jyckh VARCHAR2(50), ddbh VARCHAR2(50) not null, yjyh VARCHAR2(30), ybfdje NUMBER(12,2), grzhzfje NUMBER(12,2), xjzfje NUMBER(12,2), yljmje NUMBER(12,2), ylbzje NUMBER(12,2), zdbh VARCHAR2(32), brjzkye NUMBER(12,2), czm VARCHAR2(20), jysj VARCHAR2(20) not null, jyylx VARCHAR2(10), jyshbh VARCHAR2(20), jyzdbh VARCHAR2(30), jysbbs VARCHAR2(30) not null, jyrzzh VARCHAR2(50), yhlsh VARCHAR2(30), yhckh VARCHAR2(50), pch VARCHAR2(10), jyzt VARCHAR2(2) not null, jgbm VARCHAR2(15) not null, zdjybs VARCHAR2(2), mzzybs VARCHAR2(2), sbcsid VARCHAR2(32) not null, sfsc VARCHAR2(2) default 0 not null, jlcjsj TIMESTAMP(6) not null, dzrq DATE not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, dzbh VARCHAR2(50) not null, bz VARCHAR2(100), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.M_EQUIPMENT_TRANSFLOW is '设备对账流水表'; comment on column URP.M_EQUIPMENT_TRANSFLOW.ynjksblsid is '设备对账流水主键ID'; comment on column URP.M_EQUIPMENT_TRANSFLOW.yhrybh is '医护人员(操作员)编号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.brjzkh is '病人就诊卡号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.blh is '病人病历号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.brxm is '病人姓名'; comment on column URP.M_EQUIPMENT_TRANSFLOW.fpbh is '发票编号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jyqdbs is '交易渠道标识(微信、支付宝、医保等)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.ywlx is '原交易流水号:交易为后续类交易时有值'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jyje is '交易总金额'; comment on column URP.M_EQUIPMENT_TRANSFLOW.khh is '交易所用银行卡开户行'; comment on column URP.M_EQUIPMENT_TRANSFLOW.khzh is '交易所用银行卡账号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jylsh is '交易流水号(作为对账唯一标识时不能为空)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jyckh is '交易参考号(作为对账唯一标识时不能为空)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.ddbh is '订单编号(默认作为对账唯一标识)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.yjyh is '原交易订单号/流水号(反向交易时不为空)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.ybfdje is '医保负担/报销总金额(医保支付时赋值)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.grzhzfje is '个人账户支付金额(医保支付时赋值)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.xjzfje is '现金支付金额(医保支付时赋值)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.yljmje is '医疗减免金额(医保支付时赋值)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.ylbzje is '医疗补助金额(医保支付时赋值)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.zdbh is '账单编号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.brjzkye is '病人就诊卡余额'; comment on column URP.M_EQUIPMENT_TRANSFLOW.czm is '操作码'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jysj is '交易时间'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jyylx is '交易源类型(1:窗口、2:自助终端、3:诊间POS)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jyshbh is '交易商户编号(需用此确定结算账户时不能为空)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jyzdbh is '交易终端编号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jysbbs is '交易设备标识(用以判断哪台设备:如设备编号/设备序列号)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jyrzzh is '交易入账账号(结算账户号:需用此确定结算账户时不能为空)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.yhlsh is '银行流水号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.yhckh is '银行参考号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.pch is '批次号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jgbm is '所属机构(医院)编码'; comment on column URP.M_EQUIPMENT_TRANSFLOW.zdjybs is '是否自助终端交易标识(1:是,0:否)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.mzzybs is '门诊住院标识(1:门诊,2:住院)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.sbcsid is '设备厂商主键ID'; comment on column URP.M_EQUIPMENT_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.M_EQUIPMENT_TRANSFLOW.dzrq is '对账日期'; comment on column URP.M_EQUIPMENT_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.M_EQUIPMENT_TRANSFLOW.dzbh is '对账编号'; comment on column URP.M_EQUIPMENT_TRANSFLOW.bz is '备注'; comment on column URP.M_EQUIPMENT_TRANSFLOW.bly1 is '保留域1'; comment on column URP.M_EQUIPMENT_TRANSFLOW.bly2 is '保留域2'; comment on column URP.M_EQUIPMENT_TRANSFLOW.bly3 is '保留域3'; alter table URP.M_EQUIPMENT_TRANSFLOW add primary key (YNJKSBLSID); prompt prompt Creating table M_HIS_TRANSFLOW prompt ============================== prompt create table URP.M_HIS_TRANSFLOW ( ynjkhislsid VARCHAR2(32) default sys_guid() not null, sbcsid VARCHAR2(32) not null, yhrybh VARCHAR2(30), brjzkh VARCHAR2(30), brxm VARCHAR2(100) not null, fpbh VARCHAR2(50), jyqdbs VARCHAR2(20) not null, ywlx VARCHAR2(10), jyje NUMBER(12,2) not null, khh VARCHAR2(30), khzh VARCHAR2(30), jylsh VARCHAR2(30), jyckh VARCHAR2(50), ddbh VARCHAR2(50), zdbh VARCHAR2(32), brjzkye NUMBER(12,2), czm VARCHAR2(20), jysj VARCHAR2(20), jyylx VARCHAR2(10), jyshbh VARCHAR2(20), jyzdbh VARCHAR2(30), jysbbs VARCHAR2(30) not null, jyrzzh VARCHAR2(50), yhlsh VARCHAR2(30), yhckh VARCHAR2(50), pch VARCHAR2(10), sfsc VARCHAR2(2) default 0 not null, jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jyzt VARCHAR2(2) default 1 not null, jgbm VARCHAR2(15) not null, blh VARCHAR2(30), yjyh VARCHAR2(30), ybfdje NUMBER(12,2), grzhzfje NUMBER(12,2), xjzfje NUMBER(12,2), yljmje NUMBER(12,2), ylbzje NUMBER(12,2), flag VARCHAR2(2), mzzybs VARCHAR2(2), dzbh VARCHAR2(50) not null, bz VARCHAR2(100), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.M_HIS_TRANSFLOW is '设备HIS 流水表'; comment on column URP.M_HIS_TRANSFLOW.ynjkhislsid is '院内对账His流水Id, 主键'; comment on column URP.M_HIS_TRANSFLOW.sbcsid is '设备厂商主键id, 对应设备厂商管理表'; comment on column URP.M_HIS_TRANSFLOW.yhrybh is '医护人员编号'; comment on column URP.M_HIS_TRANSFLOW.brjzkh is '病人就诊卡号'; comment on column URP.M_HIS_TRANSFLOW.brxm is '病人姓名'; comment on column URP.M_HIS_TRANSFLOW.fpbh is '发票编号'; comment on column URP.M_HIS_TRANSFLOW.jyqdbs is '交易渠道标识(微信、支付宝、医保)'; comment on column URP.M_HIS_TRANSFLOW.ywlx is '业务类型'; comment on column URP.M_HIS_TRANSFLOW.jyje is '交易金额'; comment on column URP.M_HIS_TRANSFLOW.khh is '交易账户开户行'; comment on column URP.M_HIS_TRANSFLOW.khzh is '交易账户开户账号'; comment on column URP.M_HIS_TRANSFLOW.jylsh is '交易流水号'; comment on column URP.M_HIS_TRANSFLOW.jyckh is '交易参考号'; comment on column URP.M_HIS_TRANSFLOW.ddbh is '订单编号'; comment on column URP.M_HIS_TRANSFLOW.zdbh is '账单编号'; comment on column URP.M_HIS_TRANSFLOW.brjzkye is '病人就诊卡余额'; comment on column URP.M_HIS_TRANSFLOW.czm is '操作码'; comment on column URP.M_HIS_TRANSFLOW.jysj is '交易时间'; comment on column URP.M_HIS_TRANSFLOW.jyylx is '交易源类型(自助、窗口、诊间)'; comment on column URP.M_HIS_TRANSFLOW.jyshbh is '交易商户编号'; comment on column URP.M_HIS_TRANSFLOW.jyzdbh is '交易终端编号(终端号或医院终端标识)'; comment on column URP.M_HIS_TRANSFLOW.jysbbs is '交易设备标识(用以判断哪台设备:如设备编号/设备序列号)'; comment on column URP.M_HIS_TRANSFLOW.jyrzzh is '交易入账账号'; comment on column URP.M_HIS_TRANSFLOW.yhlsh is '银行流水号'; comment on column URP.M_HIS_TRANSFLOW.yhckh is '银行参考号'; comment on column URP.M_HIS_TRANSFLOW.pch is '批次号'; comment on column URP.M_HIS_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.M_HIS_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.M_HIS_TRANSFLOW.dzrq is '对账日期'; comment on column URP.M_HIS_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.M_HIS_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.M_HIS_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.M_HIS_TRANSFLOW.jgbm is '机构编码'; comment on column URP.M_HIS_TRANSFLOW.blh is '病人病历号'; comment on column URP.M_HIS_TRANSFLOW.yjyh is '原交易订单号/流水号(反向交易时不为空)'; comment on column URP.M_HIS_TRANSFLOW.ybfdje is '医保负担/报销总金额(医保支付时赋值)'; comment on column URP.M_HIS_TRANSFLOW.grzhzfje is '个人账户支付金额(医保支付时赋值)'; comment on column URP.M_HIS_TRANSFLOW.xjzfje is '现金支付金额(医保支付时赋值)'; comment on column URP.M_HIS_TRANSFLOW.yljmje is '医疗减免金额(医保支付时赋值)'; comment on column URP.M_HIS_TRANSFLOW.ylbzje is '医疗补助金额(医保支付时赋值)'; comment on column URP.M_HIS_TRANSFLOW.flag is '是否自助(1:是,0:否)'; comment on column URP.M_HIS_TRANSFLOW.mzzybs is '门诊住院标识(1:门诊,2:住院)'; comment on column URP.M_HIS_TRANSFLOW.dzbh is '对账编号'; comment on column URP.M_HIS_TRANSFLOW.bz is '备注'; comment on column URP.M_HIS_TRANSFLOW.bly1 is '保留域1'; comment on column URP.M_HIS_TRANSFLOW.bly2 is '保留域2'; comment on column URP.M_HIS_TRANSFLOW.bly3 is '保留域3'; alter table URP.M_HIS_TRANSFLOW add constraint M_HISTRANSFLOW_PRIMARYKEY primary key (YNJKHISLSID); prompt prompt Creating table OPERATION_LOG prompt ============================ prompt create table URP.OPERATION_LOG ( rzid VARCHAR2(32) default sys_guid() not null, glid VARCHAR2(32), glywb VARCHAR2(50), czlj VARCHAR2(100), jgbm VARCHAR2(15) not null, czdl VARCHAR2(10) not null, czxl VARCHAR2(10), czr VARCHAR2(20) not null, jlcjsj DATE not null, rznr NVARCHAR2(2000) not null, bz VARCHAR2(200), czjg VARCHAR2(2) ) ; comment on table URP.OPERATION_LOG is '操作日志表'; comment on column URP.OPERATION_LOG.rzid is '日志id,主键'; comment on column URP.OPERATION_LOG.glid is '关联业务主键'; comment on column URP.OPERATION_LOG.glywb is '关联业务表'; comment on column URP.OPERATION_LOG.czlj is '操作路径'; comment on column URP.OPERATION_LOG.jgbm is '机构编码'; comment on column URP.OPERATION_LOG.czdl is '操作大类'; comment on column URP.OPERATION_LOG.czxl is '操作小类'; comment on column URP.OPERATION_LOG.czr is '操作人'; comment on column URP.OPERATION_LOG.jlcjsj is '记录创建时间'; comment on column URP.OPERATION_LOG.rznr is '日志内容'; comment on column URP.OPERATION_LOG.bz is '备注'; comment on column URP.OPERATION_LOG.czjg is '操作结果'; create index URP.JGBM_JLCJSJ on URP.OPERATION_LOG (JGBM, JLCJSJ); alter table URP.OPERATION_LOG add constraint OPERATIONLOG_PRIMARYKEY primary key (RZID); prompt prompt Creating table PARAM_DICT prompt ========================= prompt create table URP.PARAM_DICT ( csid VARCHAR2(15) not null, jgbm VARCHAR2(15), cslx VARCHAR2(20) not null, csmc VARCHAR2(50) not null, csz VARCHAR2(20) not null, sx NUMBER(2), zt VARCHAR2(2) default 0 not null, bz VARCHAR2(100) ) ; comment on table URP.PARAM_DICT is '数据字典(系统参数)'; comment on column URP.PARAM_DICT.csid is '主键,编码'; comment on column URP.PARAM_DICT.jgbm is '机构编码'; comment on column URP.PARAM_DICT.cslx is '参数类型'; comment on column URP.PARAM_DICT.csmc is '名称(中文描述)'; comment on column URP.PARAM_DICT.csz is '参数值'; comment on column URP.PARAM_DICT.sx is '顺序'; comment on column URP.PARAM_DICT.zt is '状态(0:正常,1:禁用)'; comment on column URP.PARAM_DICT.bz is '备注'; create index URP.JGBM_CSLX_CSZ_ZT on URP.PARAM_DICT (JGBM, CSLX, CSZ, ZT); alter table URP.PARAM_DICT add constraint DICT_PRIMARYKEY primary key (CSID); prompt prompt Creating table REALTIME_ALARM prompt ============================= prompt create table URP.REALTIME_ALARM ( ssbjid VARCHAR2(32) default sys_guid() not null, yhrybh VARCHAR2(30), yhryxm VARCHAR2(30), brjzkh VARCHAR2(30), brxm VARCHAR2(30), sfzhm VARCHAR2(18), jyqdbs VARCHAR2(20), ywlx VARCHAR2(10), jyje NUMBER(12,2) not null, jylsh VARCHAR2(30), jyckh VARCHAR2(50), ddbh VARCHAR2(30), jysj VARCHAR2(20), jyshbh VARCHAR2(20), jyzdbh VARCHAR2(30), pch VARCHAR2(10), jyzt VARCHAR2(2), hisjyzt VARCHAR2(2), hisjyje NUMBER(12,2), jgbm VARCHAR2(15) not null, cljg VARCHAR2(2) default 0, sfsc VARCHAR2(2) default 0 not null, jlcjsj TIMESTAMP(6) default sysdate not null, ycdl VARCHAR2(10), ycxl VARCHAR2(10), ycnr VARCHAR2(256), clwcsj TIMESTAMP(6), ycclbs VARCHAR2(2) default 0, ycclfjmc VARCHAR2(50), ycclfjlj VARCHAR2(200), ycclms VARCHAR2(100), ycclsj TIMESTAMP(6), ycclr VARCHAR2(20), bz VARCHAR2(100), bly VARCHAR2(50), jytj VARCHAR2(20), czyxm VARCHAR2(50), hisno VARCHAR2(35) ) ; comment on table URP.REALTIME_ALARM is '实时报警表'; comment on column URP.REALTIME_ALARM.ssbjid is '实时报警Id, 主键'; comment on column URP.REALTIME_ALARM.yhrybh is '操作员(医护人员)编号'; comment on column URP.REALTIME_ALARM.yhryxm is '操作员(医护人员)姓名'; comment on column URP.REALTIME_ALARM.brjzkh is '病人就诊卡号'; comment on column URP.REALTIME_ALARM.brxm is '病人姓名'; comment on column URP.REALTIME_ALARM.sfzhm is '患者身份证号码'; comment on column URP.REALTIME_ALARM.jyqdbs is '交易渠道标识(交易渠道编码)'; comment on column URP.REALTIME_ALARM.ywlx is '业务类型'; comment on column URP.REALTIME_ALARM.jyje is '交易金额'; comment on column URP.REALTIME_ALARM.jylsh is '交易流水号'; comment on column URP.REALTIME_ALARM.jyckh is '交易参考号'; comment on column URP.REALTIME_ALARM.ddbh is '订单编号'; comment on column URP.REALTIME_ALARM.jysj is '交易时间'; comment on column URP.REALTIME_ALARM.jyshbh is '交易商户编号'; comment on column URP.REALTIME_ALARM.jyzdbh is '交易终端编号'; comment on column URP.REALTIME_ALARM.pch is '批次号'; comment on column URP.REALTIME_ALARM.jyzt is '平台交易状态(0:失败,1:成功,2:未知)'; comment on column URP.REALTIME_ALARM.hisjyzt is 'HIS交易状态(0:失败,1:成功,2:未知)'; comment on column URP.REALTIME_ALARM.hisjyje is 'HIS交易金额'; comment on column URP.REALTIME_ALARM.jgbm is '机构编码'; comment on column URP.REALTIME_ALARM.cljg is '处理结果(0:未处理,1:处理成功,2:处理失败)'; comment on column URP.REALTIME_ALARM.sfsc is '是否删除(0:未删除,1:已删除)'; comment on column URP.REALTIME_ALARM.jlcjsj is '记录创建时间'; comment on column URP.REALTIME_ALARM.ycdl is '异常大类'; comment on column URP.REALTIME_ALARM.ycxl is '异常小类'; comment on column URP.REALTIME_ALARM.ycnr is '异常内容'; comment on column URP.REALTIME_ALARM.clwcsj is '勾兑处理完成时间'; comment on column URP.REALTIME_ALARM.ycclbs is '异常处理标识(1:已处理,0:未处理)'; comment on column URP.REALTIME_ALARM.ycclfjmc is '异常处理附件名称'; comment on column URP.REALTIME_ALARM.ycclfjlj is '异常处理附件保存路径'; comment on column URP.REALTIME_ALARM.ycclms is '异常处理描述'; comment on column URP.REALTIME_ALARM.ycclsj is '异常处理时间'; comment on column URP.REALTIME_ALARM.ycclr is '异常处理人'; comment on column URP.REALTIME_ALARM.bz is '备注(失败次数)'; comment on column URP.REALTIME_ALARM.bly is '保留域'; comment on column URP.REALTIME_ALARM.jytj is '交易途径(his)'; comment on column URP.REALTIME_ALARM.czyxm is '操作员姓名'; comment on column URP.REALTIME_ALARM.hisno is 'his流水号'; create index URP.JYQDBS_SFSC_JGBM on URP.REALTIME_ALARM (JYQDBS, JGBM, SFSC); alter table URP.REALTIME_ALARM add constraint PK_REALTIME_ALARM primary key (SSBJID); prompt prompt Creating table REALTIME_MONITOR prompt =============================== prompt create table URP.REALTIME_MONITOR ( ssjkid VARCHAR2(32) default sys_guid() not null, qdid VARCHAR2(32) not null, yhrybh VARCHAR2(30), brjzkh VARCHAR2(30) not null, brxm VARCHAR2(20) not null, fpbh VARCHAR2(50), jyqdbs VARCHAR2(20) not null, ywlx VARCHAR2(10), jyje NUMBER(12,2) not null, khh VARCHAR2(30), khzh VARCHAR2(30), jylsh VARCHAR2(30), jyckh VARCHAR2(50) not null, ddbh VARCHAR2(30), zdbh VARCHAR2(32), brjzkye NUMBER(12,2), czm VARCHAR2(20), jysj VARCHAR2(20), jyylx VARCHAR2(10), jyshbh VARCHAR2(20), jyzdbh VARCHAR2(30) not null, jyrzzh VARCHAR2(30), yhlsh VARCHAR2(30), yhckh VARCHAR2(50), pch VARCHAR2(10), jyzt VARCHAR2(2) not null, qdsfcz VARCHAR2(2), qdjyzt VARCHAR2(2), jyztms VARCHAR2(256), qdjyje NUMBER(12,2), zfwcsj VARCHAR2(20), qdshh VARCHAR2(32), qdzshh VARCHAR2(32), zdsbh VARCHAR2(32), yhbs VARCHAR2(128), fkzh VARCHAR2(500), jylx VARCHAR2(20), fkyh VARCHAR2(30), jgbm VARCHAR2(15) not null, cljg VARCHAR2(2) default 0, sfsc VARCHAR2(2) default 0 not null, jlcjsj TIMESTAMP(6) default sysdate not null, ycdl VARCHAR2(10), ycxl VARCHAR2(10), ycnr VARCHAR2(256), clwcsj TIMESTAMP(6), ycclbs VARCHAR2(2) default 0, ycclfjmc VARCHAR2(50), ycclfjlj VARCHAR2(200), ycclms VARCHAR2(100), ycclsj TIMESTAMP(6), ycclr VARCHAR2(20), bz VARCHAR2(100), bly VARCHAR2(50) ) ; comment on table URP.REALTIME_MONITOR is '实时监控表'; comment on column URP.REALTIME_MONITOR.ssjkid is '实时监控id, 主键'; comment on column URP.REALTIME_MONITOR.qdid is '渠道id, 对应交易流水渠道'; comment on column URP.REALTIME_MONITOR.yhrybh is '医护人员编号'; comment on column URP.REALTIME_MONITOR.brjzkh is '病人就诊卡号'; comment on column URP.REALTIME_MONITOR.brxm is '病人姓名'; comment on column URP.REALTIME_MONITOR.fpbh is '发票编号'; comment on column URP.REALTIME_MONITOR.jyqdbs is '交易渠道标识(微信、支付宝、医保)'; comment on column URP.REALTIME_MONITOR.ywlx is '业务类型'; comment on column URP.REALTIME_MONITOR.jyje is '交易金额'; comment on column URP.REALTIME_MONITOR.khh is '开户行'; comment on column URP.REALTIME_MONITOR.khzh is '开户账号'; comment on column URP.REALTIME_MONITOR.jylsh is '交易流水号'; comment on column URP.REALTIME_MONITOR.jyckh is '交易参考号'; comment on column URP.REALTIME_MONITOR.ddbh is '订单编号'; comment on column URP.REALTIME_MONITOR.zdbh is '账单编号'; comment on column URP.REALTIME_MONITOR.brjzkye is '病人就诊卡余额'; comment on column URP.REALTIME_MONITOR.czm is '操作码'; comment on column URP.REALTIME_MONITOR.jysj is '交易时间'; comment on column URP.REALTIME_MONITOR.jyylx is '交易源类型(自助、窗口、诊间)'; comment on column URP.REALTIME_MONITOR.jyshbh is '交易商户编号'; comment on column URP.REALTIME_MONITOR.jyzdbh is '交易终端编号(终端号或医院终端标识)'; comment on column URP.REALTIME_MONITOR.jyrzzh is '交易入账账号'; comment on column URP.REALTIME_MONITOR.yhlsh is '银行流水号'; comment on column URP.REALTIME_MONITOR.yhckh is '银行参考号'; comment on column URP.REALTIME_MONITOR.pch is '批次号'; comment on column URP.REALTIME_MONITOR.jyzt is 'HIS交易状态(0:失败,1:成功,2:未知)'; comment on column URP.REALTIME_MONITOR.qdsfcz is '渠道是否存在该笔交易(1:存在,0:不存在)'; comment on column URP.REALTIME_MONITOR.qdjyzt is '渠道交易状态(1:成功,0:失败,2:其他情况)'; comment on column URP.REALTIME_MONITOR.jyztms is '交易状态描述'; comment on column URP.REALTIME_MONITOR.qdjyje is '渠道交易金额'; comment on column URP.REALTIME_MONITOR.zfwcsj is '支付完成时间'; comment on column URP.REALTIME_MONITOR.qdshh is '渠道商户号'; comment on column URP.REALTIME_MONITOR.qdzshh is '渠道子商户号'; comment on column URP.REALTIME_MONITOR.zdsbh is '终端设备号'; comment on column URP.REALTIME_MONITOR.yhbs is '用户标识'; comment on column URP.REALTIME_MONITOR.fkzh is '付款账号'; comment on column URP.REALTIME_MONITOR.jylx is '交易类型'; comment on column URP.REALTIME_MONITOR.fkyh is '资金渠道(银行标识)'; comment on column URP.REALTIME_MONITOR.jgbm is '机构编码'; comment on column URP.REALTIME_MONITOR.cljg is '处理结果(0:未处理,1:处理成功,2:处理失败)'; comment on column URP.REALTIME_MONITOR.sfsc is '是否删除(0:未删除,1:已删除)'; comment on column URP.REALTIME_MONITOR.jlcjsj is '记录创建时间'; comment on column URP.REALTIME_MONITOR.ycdl is '异常大类'; comment on column URP.REALTIME_MONITOR.ycxl is '异常小类'; comment on column URP.REALTIME_MONITOR.ycnr is '异常内容'; comment on column URP.REALTIME_MONITOR.clwcsj is '勾兑处理完成时间'; comment on column URP.REALTIME_MONITOR.ycclbs is '异常处理标识(1:已处理,0:未处理)'; comment on column URP.REALTIME_MONITOR.ycclfjmc is '异常处理附件名称'; comment on column URP.REALTIME_MONITOR.ycclfjlj is '异常处理附件保存路径'; comment on column URP.REALTIME_MONITOR.ycclms is '异常处理描述'; comment on column URP.REALTIME_MONITOR.ycclsj is '异常处理时间'; comment on column URP.REALTIME_MONITOR.ycclr is '异常处理人'; comment on column URP.REALTIME_MONITOR.bz is '备注(失败次数)'; comment on column URP.REALTIME_MONITOR.bly is '保留域'; create index URP.QDID_SFSC_JGBM on URP.REALTIME_MONITOR (QDID, JGBM, SFSC); alter table URP.REALTIME_MONITOR add constraint REALTIMEMONITOR_PRIMARYKEY primary key (SSJKID); prompt prompt Creating table RECONFILE_INFO prompt ============================= prompt create table URP.RECONFILE_INFO ( dzwjid VARCHAR2(32) default sys_guid() not null, qdid VARCHAR2(32) not null, wjmc VARCHAR2(100) not null, wjlj VARCHAR2(100) not null, czsj TIMESTAMP(6) default sysdate not null, czjg VARCHAR2(2) not null, czjgms VARCHAR2(100), dzrq DATE not null, rkzt VARCHAR2(2) default 0 not null, bz VARCHAR2(100), sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.RECONFILE_INFO is '渠道对账文件 管理表'; comment on column URP.RECONFILE_INFO.dzwjid is '对账文件ID,区分文件'; comment on column URP.RECONFILE_INFO.qdid is '渠道主键id'; comment on column URP.RECONFILE_INFO.wjmc is '对账文件名称'; comment on column URP.RECONFILE_INFO.wjlj is '对账文件下载后存放路径'; comment on column URP.RECONFILE_INFO.czsj is '操作时间(对账文件下载/上传时间)'; comment on column URP.RECONFILE_INFO.czjg is '操作结果(对账文件下载/上传结果(1:成功,0:失败))'; comment on column URP.RECONFILE_INFO.czjgms is '操作结果描述(对账文件下载/上传结果描述)'; comment on column URP.RECONFILE_INFO.dzrq is '对账日期(手工对账时可指定)'; comment on column URP.RECONFILE_INFO.rkzt is '对账文件入库状态(0:未入库,1:已入库,2:入库失败)'; comment on column URP.RECONFILE_INFO.bz is '备注'; comment on column URP.RECONFILE_INFO.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.RECONFILE_INFO.bly1 is '保留域1'; comment on column URP.RECONFILE_INFO.bly2 is '保留域2'; comment on column URP.RECONFILE_INFO.bly3 is '保留域3'; create index URP.QDID_SFSC_DZRQ on URP.RECONFILE_INFO (QDID, DZRQ, SFSC); alter table URP.RECONFILE_INFO add constraint RECONFILEINFO_PRIMARYKEY primary key (DZWJID); prompt prompt Creating table RECONFILE_REDOWNLOAD prompt =================================== prompt create table URP.RECONFILE_REDOWNLOAD ( dzwjcxzid VARCHAR2(32) default sys_guid() not null, qdid VARCHAR2(32) not null, dzrq DATE not null, xzjg VARCHAR2(2) not null, sbyy VARCHAR2(50), xzcs NUMBER default 0 not null, jlcjsj TIMESTAMP(6) not null, zhxzsj TIMESTAMP(6) not null, jgbm VARCHAR2(15) not null, bz VARCHAR2(100) ) ; comment on table URP.RECONFILE_REDOWNLOAD is '对账文件重下载表'; comment on column URP.RECONFILE_REDOWNLOAD.dzwjcxzid is '对账文件重下载ID'; comment on column URP.RECONFILE_REDOWNLOAD.qdid is '渠道id'; comment on column URP.RECONFILE_REDOWNLOAD.dzrq is '对账日期'; comment on column URP.RECONFILE_REDOWNLOAD.xzjg is '下载结果(0:失败,1:成功)'; comment on column URP.RECONFILE_REDOWNLOAD.sbyy is '下载失败原因'; comment on column URP.RECONFILE_REDOWNLOAD.xzcs is '下载次数'; comment on column URP.RECONFILE_REDOWNLOAD.jlcjsj is '记录创建时间'; comment on column URP.RECONFILE_REDOWNLOAD.zhxzsj is '最后下载时间'; comment on column URP.RECONFILE_REDOWNLOAD.jgbm is '机构编码'; comment on column URP.RECONFILE_REDOWNLOAD.bz is '备注'; alter table URP.RECONFILE_REDOWNLOAD add constraint RECONFILEREDOWNLOAD_PRIMARYKEY primary key (DZWJCXZID); prompt prompt Creating table RECONHIS_STATISTICS prompt ================================== prompt create table URP.RECONHIS_STATISTICS ( dzjglstjid VARCHAR2(32) default sys_guid() not null, dzrq DATE not null, dzqd VARCHAR2(100), wcdzqd VARCHAR2(100), wwcdzqd VARCHAR2(100), wdzqd VARCHAR2(100), zpqd VARCHAR2(100), zbpqd VARCHAR2(50), dzqdsl NUMBER default 0, wcdzqdsl NUMBER default 0, wwcdzqdsl NUMBER default 0, wdzqdsl NUMBER default 0, zpqdsl NUMBER default 0, zbpqdsl NUMBER default 0, qdjyzbs NUMBER default 0, qdjyzje NUMBER(12,2), ycjyzbs NUMBER default 0, qdycjyzje NUMBER(12,2), jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bz VARCHAR2(100), bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), hisjyzbs NUMBER, hisjyzje NUMBER(12,2), hisycjyzje NUMBER(12,2), qdycjyzbs NUMBER, hisycjyzbs NUMBER ) ; comment on table URP.RECONHIS_STATISTICS is '对账结果历史统计表'; comment on column URP.RECONHIS_STATISTICS.dzjglstjid is '对账结果历史统计表Id'; comment on column URP.RECONHIS_STATISTICS.dzrq is '对账日期'; comment on column URP.RECONHIS_STATISTICS.dzqd is '对账渠道'; comment on column URP.RECONHIS_STATISTICS.wcdzqd is '完成对账渠道'; comment on column URP.RECONHIS_STATISTICS.wwcdzqd is '未完成对账渠道'; comment on column URP.RECONHIS_STATISTICS.wdzqd is '未对账渠道'; comment on column URP.RECONHIS_STATISTICS.zpqd is '账平渠道'; comment on column URP.RECONHIS_STATISTICS.zbpqd is '账不平渠道 '; comment on column URP.RECONHIS_STATISTICS.dzqdsl is '对账渠道数量'; comment on column URP.RECONHIS_STATISTICS.wcdzqdsl is '完成对账渠道数量'; comment on column URP.RECONHIS_STATISTICS.wwcdzqdsl is '未完成对账渠道数量'; comment on column URP.RECONHIS_STATISTICS.wdzqdsl is '未对账渠道数量'; comment on column URP.RECONHIS_STATISTICS.zpqdsl is '账平渠道数量'; comment on column URP.RECONHIS_STATISTICS.zbpqdsl is '账不平渠道数量'; comment on column URP.RECONHIS_STATISTICS.qdjyzbs is '渠道交易总笔数'; comment on column URP.RECONHIS_STATISTICS.qdjyzje is '渠道交易总金额'; comment on column URP.RECONHIS_STATISTICS.ycjyzbs is '异常交易总笔数(渠道和His并集)'; comment on column URP.RECONHIS_STATISTICS.qdycjyzje is '渠道异常交易总金额'; comment on column URP.RECONHIS_STATISTICS.jgbm is '机构编码'; comment on column URP.RECONHIS_STATISTICS.sfsc is '是否删除(1:已删除,0:未删除)'; comment on column URP.RECONHIS_STATISTICS.bz is '备注'; comment on column URP.RECONHIS_STATISTICS.bly1 is '保留域1'; comment on column URP.RECONHIS_STATISTICS.bly2 is '保留域2'; comment on column URP.RECONHIS_STATISTICS.bly3 is '保留域3'; comment on column URP.RECONHIS_STATISTICS.hisjyzbs is 'His交易总笔数'; comment on column URP.RECONHIS_STATISTICS.hisjyzje is 'His交易总金额'; comment on column URP.RECONHIS_STATISTICS.hisycjyzje is 'His异常交易总金额'; comment on column URP.RECONHIS_STATISTICS.qdycjyzbs is '渠道异常交易总笔数'; comment on column URP.RECONHIS_STATISTICS.hisycjyzbs is 'His异常交易总笔数'; create index URP.DZRQ_JGBM_SFSC on URP.RECONHIS_STATISTICS (DZRQ, JGBM, SFSC); alter table URP.RECONHIS_STATISTICS add constraint RECONHISSTATISTICS_PK primary key (DZJGLSTJID); prompt prompt Creating table RECONRESULT_DETAIL prompt ================================= prompt create table URP.RECONRESULT_DETAIL ( dzjgmxid VARCHAR2(32) default sys_guid() not null, qdid VARCHAR2(32) not null, hisid VARCHAR2(32), qdlsid VARCHAR2(32), dzjg VARCHAR2(2) default 1 not null, yclx VARCHAR2(2), dzjgms VARCHAR2(100), dzrq DATE default sysdate not null, jlsj TIMESTAMP(6) not null, ydzje NUMBER(12,2) not null, ydzclbs VARCHAR2(2), ydzfjmc VARCHAR2(50), ydzfjlj VARCHAR2(100), ydzclms VARCHAR2(100), ydzclsj TIMESTAMP(6), ydzclr VARCHAR2(20), bz VARCHAR2(100), sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50) ) ; comment on table URP.RECONRESULT_DETAIL is '对账结果明细表'; comment on column URP.RECONRESULT_DETAIL.dzjgmxid is '结果明细表主键id'; comment on column URP.RECONRESULT_DETAIL.qdid is '渠道主键Id(为交易渠道,不含HIS)'; comment on column URP.RECONRESULT_DETAIL.hisid is 'HIS流水表主键ID'; comment on column URP.RECONRESULT_DETAIL.qdlsid is '交易渠道主键 ID,与channel_id匹配决定渠道流水表'; comment on column URP.RECONRESULT_DETAIL.dzjg is '对账结果(1:正常交易/0:异常交易)'; comment on column URP.RECONRESULT_DETAIL.yclx is '异常类型,交易结果为异常交易时填写(0:正常交易,1:HIS有渠道无,2:His无渠道有,3:渠道成功、HIS失败,4:HIS成功、渠道失败,5:HIS一条记录、渠道多条记录,6:HIS多条记录、渠道一条记录,7:HIS与渠道金额不一致)'; comment on column URP.RECONRESULT_DETAIL.dzjgms is '对账结果描述'; comment on column URP.RECONRESULT_DETAIL.dzrq is '对账日期'; comment on column URP.RECONRESULT_DETAIL.jlsj is '对账结果记录时间'; comment on column URP.RECONRESULT_DETAIL.ydzje is '应到账金额,默认为HIS交易金额(交易渠道应与实际到账匹配,故统计无意义)'; comment on column URP.RECONRESULT_DETAIL.ydzclbs is '应到账处理标识(1:已处理,0:未处理)'; comment on column URP.RECONRESULT_DETAIL.ydzfjmc is '应到账处理附件名称'; comment on column URP.RECONRESULT_DETAIL.ydzfjlj is '应到账处理附件保存路径'; comment on column URP.RECONRESULT_DETAIL.ydzclms is '应到账处理备注'; comment on column URP.RECONRESULT_DETAIL.ydzclsj is '应到账处理时间'; comment on column URP.RECONRESULT_DETAIL.ydzclr is '应到账处理人'; comment on column URP.RECONRESULT_DETAIL.bz is '备注'; comment on column URP.RECONRESULT_DETAIL.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.RECONRESULT_DETAIL.bly1 is '保留域1'; comment on column URP.RECONRESULT_DETAIL.bly2 is '保留域2'; comment on column URP.RECONRESULT_DETAIL.bly3 is '保留域3'; create index URP.RETS_QH on URP.RECONRESULT_DETAIL (HISID, QDLSID); create index URP.RETS_QY on URP.RECONRESULT_DETAIL (QDID, YCLX); create index URP.RETS_SD on URP.RECONRESULT_DETAIL (SFSC, DZRQ); alter table URP.RECONRESULT_DETAIL add constraint RECONRESULT_DETAIL_PRIMARYKEY primary key (DZJGMXID); prompt prompt Creating table SCANCODE_TRANSFLOW prompt ================================= prompt create table URP.SCANCODE_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50) not null, jylsh VARCHAR2(50), qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30), zdhm VARCHAR2(50), spmc VARCHAR2(30), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), jgbm VARCHAR2(15) not null, dzbh VARCHAR2(50) ) ; comment on table URP.SCANCODE_TRANSFLOW is '扫码交易对账流水表'; comment on column URP.SCANCODE_TRANSFLOW.lsid is '扫码交易流水主键ID'; comment on column URP.SCANCODE_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.SCANCODE_TRANSFLOW.shbh is '商户编号'; comment on column URP.SCANCODE_TRANSFLOW.zdbh is '终端编号'; comment on column URP.SCANCODE_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.SCANCODE_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.SCANCODE_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.SCANCODE_TRANSFLOW.yjylsh is '原交易流水号:交易为后续类交易时有值'; comment on column URP.SCANCODE_TRANSFLOW.shddh is '商户订单号'; comment on column URP.SCANCODE_TRANSFLOW.zdhm is '账单号码'; comment on column URP.SCANCODE_TRANSFLOW.spmc is '商品名称'; comment on column URP.SCANCODE_TRANSFLOW.jysj is '交易时间'; comment on column URP.SCANCODE_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.SCANCODE_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.SCANCODE_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.SCANCODE_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.SCANCODE_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.SCANCODE_TRANSFLOW.jybz is '交易备注'; comment on column URP.SCANCODE_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.SCANCODE_TRANSFLOW.dzrq is '对账日期'; comment on column URP.SCANCODE_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.SCANCODE_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.SCANCODE_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.SCANCODE_TRANSFLOW.bly1 is '保留域1'; comment on column URP.SCANCODE_TRANSFLOW.bly2 is '保留域2'; comment on column URP.SCANCODE_TRANSFLOW.bly3 is '保留域3'; comment on column URP.SCANCODE_TRANSFLOW.jgbm is '机构编码'; comment on column URP.SCANCODE_TRANSFLOW.dzbh is '对账编号'; create index URP.SHBH_JYCKH_DZRQ_SFSC_DZBS_JGBM on URP.SCANCODE_TRANSFLOW (SHBH, JYCKH, DZRQ, DZBS, SFSC, JGBM); alter table URP.SCANCODE_TRANSFLOW add constraint SCANCODE_TRANSFLOW_PK primary key (LSID); prompt prompt Creating table TRADEHANDLE_WATER prompt ================================ prompt create table URP.TRADEHANDLE_WATER ( jycllsid VARCHAR2(32) not null, cljlid VARCHAR2(32) not null, ptlsh VARCHAR2(32) not null, ptddh VARCHAR2(30), jyddh VARCHAR2(30), jylsh VARCHAR2(30), jyckh VARCHAR2(30), pch VARCHAR2(10), cxlsh VARCHAR2(30), yjyddh VARCHAR2(30), jyje NUMBER(12,2) not null, jysj VARCHAR2(20) not null, fhm VARCHAR2(30), fhjgms VARCHAR2(100), jylx VARCHAR2(30), jyzt VARCHAR2(2), sfsc VARCHAR2(2) not null, jgbm VARCHAR2(15) not null, jlcjsj TIMESTAMP(6) not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6), zhxgr VARCHAR2(20), bz VARCHAR2(100), bly VARCHAR2(50) ) ; comment on table URP.TRADEHANDLE_WATER is '交易处理流水表'; comment on column URP.TRADEHANDLE_WATER.jycllsid is '交易处理流水表主键Id'; comment on column URP.TRADEHANDLE_WATER.cljlid is '处理记录ID(实时监控表ID或对账结果明细表ID)'; comment on column URP.TRADEHANDLE_WATER.ptlsh is '对账平台流水号'; comment on column URP.TRADEHANDLE_WATER.ptddh is '平台订单号'; comment on column URP.TRADEHANDLE_WATER.jyddh is '交易订单号/商户订单号'; comment on column URP.TRADEHANDLE_WATER.jylsh is '交易流水号'; comment on column URP.TRADEHANDLE_WATER.jyckh is '交易参考号'; comment on column URP.TRADEHANDLE_WATER.pch is '批次号'; comment on column URP.TRADEHANDLE_WATER.cxlsh is '查询流水号'; comment on column URP.TRADEHANDLE_WATER.yjyddh is '原交易订单号(反向交易时用于查询原交易)'; comment on column URP.TRADEHANDLE_WATER.jyje is '交易金额'; comment on column URP.TRADEHANDLE_WATER.jysj is '交易时间'; comment on column URP.TRADEHANDLE_WATER.fhm is '返回码'; comment on column URP.TRADEHANDLE_WATER.fhjgms is '返回结果描述'; comment on column URP.TRADEHANDLE_WATER.jylx is '交易类型'; comment on column URP.TRADEHANDLE_WATER.jyzt is '交易状态'; comment on column URP.TRADEHANDLE_WATER.sfsc is '是否删除'; comment on column URP.TRADEHANDLE_WATER.jgbm is '机构编码'; comment on column URP.TRADEHANDLE_WATER.jlcjsj is '创建日期'; comment on column URP.TRADEHANDLE_WATER.cjr is '创建人'; comment on column URP.TRADEHANDLE_WATER.zhxgsj is '最后修改日期'; comment on column URP.TRADEHANDLE_WATER.zhxgr is '最后修改人'; comment on column URP.TRADEHANDLE_WATER.bz is '备注'; comment on column URP.TRADEHANDLE_WATER.bly is '保留域'; alter table URP.TRADEHANDLE_WATER add constraint TRADEHANDLE_JYCLLSID primary key (JYCLLSID); prompt prompt Creating table UCOMPOS_CONFIG prompt ============================= prompt create table URP.UCOMPOS_CONFIG ( pzid VARCHAR2(32) default sys_guid() not null, yybh VARCHAR2(20) not null, rzbm VARCHAR2(30) not null, jylybh VARCHAR2(20) not null, shbh VARCHAR2(30) not null, zdbh VARCHAR2(20) not null, ip VARCHAR2(15), sfsc VARCHAR2(2) not null, cjsj TIMESTAMP(6) default sysdate not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6), zhxgr VARCHAR2(20), bz VARCHAR2(100) ) ; comment on table URP.UCOMPOS_CONFIG is '调银商TCOMPOS终端DLL配置信息表'; comment on column URP.UCOMPOS_CONFIG.pzid is '配置表Id'; comment on column URP.UCOMPOS_CONFIG.yybh is '医院编号'; comment on column URP.UCOMPOS_CONFIG.rzbm is '认证编码'; comment on column URP.UCOMPOS_CONFIG.jylybh is '交易来源编号(为每个交易窗口或自助编的唯一编号)'; comment on column URP.UCOMPOS_CONFIG.shbh is '商户编号'; comment on column URP.UCOMPOS_CONFIG.zdbh is '终端编号'; comment on column URP.UCOMPOS_CONFIG.ip is '终端所在电脑IP地址'; comment on column URP.UCOMPOS_CONFIG.sfsc is '是否删除(1:是,0:否)'; comment on column URP.UCOMPOS_CONFIG.cjsj is '创建时间'; comment on column URP.UCOMPOS_CONFIG.cjr is '创建人'; comment on column URP.UCOMPOS_CONFIG.zhxgsj is '最后修改时间'; comment on column URP.UCOMPOS_CONFIG.zhxgr is '最后修改人'; comment on column URP.UCOMPOS_CONFIG.bz is '备注'; alter table URP.UCOMPOS_CONFIG add constraint PK_UCOMPOS_CONFIG primary key (PZID); prompt prompt Creating table UCOMPOS_LOG_INFO prompt =============================== prompt create table URP.UCOMPOS_LOG_INFO ( rzid VARCHAR2(32) default sys_guid() not null, sblx VARCHAR2(2), yybh VARCHAR2(15) not null, jlcjsj VARCHAR2(20) not null, rznr CLOB not null, bz VARCHAR2(100) ) ; comment on column URP.UCOMPOS_LOG_INFO.rzid is '设备日志id,主键'; comment on column URP.UCOMPOS_LOG_INFO.sblx is '设备类型(0:pos,1:自助)'; comment on column URP.UCOMPOS_LOG_INFO.yybh is '医院编号'; comment on column URP.UCOMPOS_LOG_INFO.jlcjsj is '记录创建时间'; comment on column URP.UCOMPOS_LOG_INFO.rznr is '日志内容'; comment on column URP.UCOMPOS_LOG_INFO.bz is '备注'; alter table URP.UCOMPOS_LOG_INFO add constraint EQUIPMENTLOG_PRIMARYKEY primary key (RZID); prompt prompt Creating table UCOMPOS_TRADE_INFO prompt ================================= prompt create table URP.UCOMPOS_TRADE_INFO ( jylsid VARCHAR2(32) default sys_guid() not null, qqjybw CLOB, yybh VARCHAR2(20), rzbm VARCHAR2(30), czybh VARCHAR2(20), czyxm VARCHAR2(30), hzxm VARCHAR2(30), hzblh VARCHAR2(30), bcjyjzkh VARCHAR2(50), jyqd VARCHAR2(2), jylybh VARCHAR2(20), jkmc VARCHAR2(20), ptlsh VARCHAR2(30), jyddh VARCHAR2(50), yjyddh VARCHAR2(50), yspzh VARCHAR2(20), ysjyckh VARCHAR2(30), yyspzh VARCHAR2(20), yysjyckh VARCHAR2(30), fqjysj VARCHAR2(20) not null, wcjysj VARCHAR2(20), jyzt VARCHAR2(2) not null, jylx VARCHAR2(2), fhjybw CLOB, dyfwybs VARCHAR2(30), bz VARCHAR2(100), jyje VARCHAR2(25) ) ; comment on table URP.UCOMPOS_TRADE_INFO is '调银商TCOMPOS终端DLL交易信息表'; comment on column URP.UCOMPOS_TRADE_INFO.jylsid is '交易流水Id'; comment on column URP.UCOMPOS_TRADE_INFO.qqjybw is '请求交易报文(调银商DLL接口报文)'; comment on column URP.UCOMPOS_TRADE_INFO.yybh is '医院编号'; comment on column URP.UCOMPOS_TRADE_INFO.rzbm is '认证编码'; comment on column URP.UCOMPOS_TRADE_INFO.czybh is '操作员编号'; comment on column URP.UCOMPOS_TRADE_INFO.czyxm is '操作员姓名'; comment on column URP.UCOMPOS_TRADE_INFO.hzxm is '患者姓名'; comment on column URP.UCOMPOS_TRADE_INFO.hzblh is '患者病历号'; comment on column URP.UCOMPOS_TRADE_INFO.bcjyjzkh is '本次就医介质卡号'; comment on column URP.UCOMPOS_TRADE_INFO.jyqd is '交易渠道(1:医保,2:银联卡,3:微信,4:云闪付)'; comment on column URP.UCOMPOS_TRADE_INFO.jylybh is '交易来源编号(窗口POS、自助终端编号,以便从配置表找到对应的配置信息)'; comment on column URP.UCOMPOS_TRADE_INFO.jkmc is '接口名称'; comment on column URP.UCOMPOS_TRADE_INFO.ptlsh is '平台流水号'; comment on column URP.UCOMPOS_TRADE_INFO.jyddh is '交易订单号'; comment on column URP.UCOMPOS_TRADE_INFO.yjyddh is '原交易订单号(撤销时用)'; comment on column URP.UCOMPOS_TRADE_INFO.yspzh is '银商凭证号'; comment on column URP.UCOMPOS_TRADE_INFO.ysjyckh is '银商交易参考号'; comment on column URP.UCOMPOS_TRADE_INFO.yyspzh is '原银商凭证号'; comment on column URP.UCOMPOS_TRADE_INFO.yysjyckh is '原银商交易参考号'; comment on column URP.UCOMPOS_TRADE_INFO.fqjysj is '发起交易时间'; comment on column URP.UCOMPOS_TRADE_INFO.wcjysj is '完成交易时间'; comment on column URP.UCOMPOS_TRADE_INFO.jyzt is '交易状态(1:成功,0:失败,2:未知,3:交易中)'; comment on column URP.UCOMPOS_TRADE_INFO.jylx is '交易类型(1:消费,2:撤销,3:退货)'; comment on column URP.UCOMPOS_TRADE_INFO.fhjybw is '返回交易报文(银商DLL接口返回报文)'; comment on column URP.UCOMPOS_TRADE_INFO.dyfwybs is '调用方唯一标识'; comment on column URP.UCOMPOS_TRADE_INFO.bz is '备注'; comment on column URP.UCOMPOS_TRADE_INFO.jyje is '交易金额'; alter table URP.UCOMPOS_TRADE_INFO add constraint PK_UCOMPOS_TRADE_INFO primary key (JYLSID); prompt prompt Creating table UNIONPAYCF_TRANSFLOW prompt =================================== prompt create table URP.UNIONPAYCF_TRANSFLOW ( ylysflsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50), jylsh VARCHAR2(50) not null, qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30), zdhm VARCHAR2(50), spmc VARCHAR2(30), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50) ) ; comment on table URP.UNIONPAYCF_TRANSFLOW is '银联云闪付交易流水表'; comment on column URP.UNIONPAYCF_TRANSFLOW.ylysflsid is '银联云闪付流水主键ID'; comment on column URP.UNIONPAYCF_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.UNIONPAYCF_TRANSFLOW.shbh is '商户编号'; comment on column URP.UNIONPAYCF_TRANSFLOW.zdbh is '终端编号'; comment on column URP.UNIONPAYCF_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.UNIONPAYCF_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.UNIONPAYCF_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.UNIONPAYCF_TRANSFLOW.yjylsh is '原交易流水号:交易为后续类交易时有值'; comment on column URP.UNIONPAYCF_TRANSFLOW.shddh is '商户订单号'; comment on column URP.UNIONPAYCF_TRANSFLOW.zdhm is '账单号码'; comment on column URP.UNIONPAYCF_TRANSFLOW.spmc is '商品名称'; comment on column URP.UNIONPAYCF_TRANSFLOW.jysj is '交易时间'; comment on column URP.UNIONPAYCF_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.UNIONPAYCF_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.UNIONPAYCF_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.UNIONPAYCF_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.UNIONPAYCF_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.UNIONPAYCF_TRANSFLOW.jybz is '交易备注'; comment on column URP.UNIONPAYCF_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.UNIONPAYCF_TRANSFLOW.dzrq is '对账日期'; comment on column URP.UNIONPAYCF_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.UNIONPAYCF_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.UNIONPAYCF_TRANSFLOW.jgbm is '机构编码'; comment on column URP.UNIONPAYCF_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.UNIONPAYCF_TRANSFLOW.bly1 is '保留域1'; comment on column URP.UNIONPAYCF_TRANSFLOW.bly2 is '保留域2'; comment on column URP.UNIONPAYCF_TRANSFLOW.bly3 is '保留域3'; comment on column URP.UNIONPAYCF_TRANSFLOW.dzbh is '对账编号'; create index URP.QDZH_JYCKH_DZRQ_SFSC_DZBS_JGBM on URP.UNIONPAYCF_TRANSFLOW (QDZHID, JYCKH, DZRQ, DZBS, JGBM, SFSC); alter table URP.UNIONPAYCF_TRANSFLOW add constraint UNIONPAYCF_TRANSFLOW_PK primary key (YLYSFLSID); prompt prompt Creating table UNIONPAYOMNI_TRANSFLOW prompt ===================================== prompt create table URP.UNIONPAYOMNI_TRANSFLOW ( ylqqdlsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50) not null, jylsh VARCHAR2(50) not null, qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30), zdhm VARCHAR2(50), spmc VARCHAR2(30), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50) ) ; comment on table URP.UNIONPAYOMNI_TRANSFLOW is '银联全渠道对账流水表'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.ylqqdlsid is '银联全渠道流水主键ID'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.shbh is '商户编号'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.zdbh is '终端编号'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.yjylsh is '原交易流水号:交易为后续类交易时有值'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.shddh is '商户订单号'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.zdhm is '账单号码'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.spmc is '商品名称'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.jysj is '交易时间'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.jybz is '交易备注'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.dzrq is '对账日期'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.jgbm is '机构编码'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.bly1 is '保留域1'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.bly2 is '保留域2'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.bly3 is '保留域3'; comment on column URP.UNIONPAYOMNI_TRANSFLOW.dzbh is '对账编号'; create index URP.QDZH_CKH_DZRQ_SFSC_DZBS_JGBM on URP.UNIONPAYOMNI_TRANSFLOW (QDZHID, JYCKH, DZRQ, DZBS, JGBM, SFSC); alter table URP.UNIONPAYOMNI_TRANSFLOW add constraint UNIONPAYOMNI_PRIMARYKEY primary key (YLQQDLSID); prompt prompt Creating table UNIONPAY_TRANSFLOW prompt ================================= prompt create table URP.UNIONPAY_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50) not null, jylsh VARCHAR2(50) not null, qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30), zdhm VARCHAR2(50), spmc VARCHAR2(30), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50), ejbs VARCHAR2(50), sxf NUMBER(12,2) default 0.00 not null, qsje NUMBER(12,2) default 0.00, qsrq VARCHAR2(20) ) ; comment on table URP.UNIONPAY_TRANSFLOW is '银联卡对账流水表'; comment on column URP.UNIONPAY_TRANSFLOW.lsid is '银联卡流水主键ID'; comment on column URP.UNIONPAY_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.UNIONPAY_TRANSFLOW.shbh is '商户编号'; comment on column URP.UNIONPAY_TRANSFLOW.zdbh is '终端编号'; comment on column URP.UNIONPAY_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.UNIONPAY_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.UNIONPAY_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.UNIONPAY_TRANSFLOW.yjylsh is '原交易流水号:交易为后续类交易时有值'; comment on column URP.UNIONPAY_TRANSFLOW.shddh is '商户订单号'; comment on column URP.UNIONPAY_TRANSFLOW.zdhm is '账单号码'; comment on column URP.UNIONPAY_TRANSFLOW.spmc is '商品名称'; comment on column URP.UNIONPAY_TRANSFLOW.jysj is '交易时间'; comment on column URP.UNIONPAY_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.UNIONPAY_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.UNIONPAY_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.UNIONPAY_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.UNIONPAY_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.UNIONPAY_TRANSFLOW.jybz is '交易备注'; comment on column URP.UNIONPAY_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.UNIONPAY_TRANSFLOW.dzrq is '对账日期'; comment on column URP.UNIONPAY_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.UNIONPAY_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.UNIONPAY_TRANSFLOW.jgbm is '机构编码'; comment on column URP.UNIONPAY_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.UNIONPAY_TRANSFLOW.bly1 is '保留域1'; comment on column URP.UNIONPAY_TRANSFLOW.bly2 is '保留域2(清算金额)'; comment on column URP.UNIONPAY_TRANSFLOW.bly3 is '保留域3->就诊卡号'; comment on column URP.UNIONPAY_TRANSFLOW.dzbh is '对账编号'; comment on column URP.UNIONPAY_TRANSFLOW.ejbs is '二级标识(生殖医院-> 发卡行)'; comment on column URP.UNIONPAY_TRANSFLOW.sxf is '手续费(单位:元)'; comment on column URP.UNIONPAY_TRANSFLOW.qsje is '清算金额(单位:元)'; comment on column URP.UNIONPAY_TRANSFLOW.qsrq is '清算日期'; create index URP.PQDZH_CKH_DZRQ_SFSC_DZBS_JGBM on URP.UNIONPAY_TRANSFLOW (QDZHID, DZRQ, DZBS, JGBM, SFSC, JYCKH); alter table URP.UNIONPAY_TRANSFLOW add constraint UNIONPAY_TRANSFLOW_PRIMARYKEY primary key (LSID); prompt prompt Creating table WECHAT_CONFIG prompt ============================ prompt create table URP.WECHAT_CONFIG ( wxpzid VARCHAR2(32) not null, appid VARCHAR2(30) not null, app_secret VARCHAR2(50), original_id VARCHAR2(20) not null, access_token VARCHAR2(130), lpgxsj VARCHAR2(30) not null, lpxcsxsj VARCHAR2(30) not null, jsapiticket VARCHAR2(130), pjgxsj VARCHAR2(50), pjxcsxsj VARCHAR2(50), wxmc VARCHAR2(20), wxhm VARCHAR2(20), wxlx VARCHAR2(2), wxms VARCHAR2(50), sfsc VARCHAR2(2) not null, jgbm VARCHAR2(15) not null, cjsj TIMESTAMP(6) not null, cjr VARCHAR2(20), zhxgsj TIMESTAMP(6) not null, zhxgr VARCHAR2(20), bz VARCHAR2(100), bly VARCHAR2(50) ) ; comment on table URP.WECHAT_CONFIG is '微信配置表'; comment on column URP.WECHAT_CONFIG.wxpzid is '微信配置表主键Id'; comment on column URP.WECHAT_CONFIG.appid is '微信公众号APPID'; comment on column URP.WECHAT_CONFIG.app_secret is '微信公众号秘钥'; comment on column URP.WECHAT_CONFIG.original_id is '微信公众号原始ID'; comment on column URP.WECHAT_CONFIG.access_token is '微信公众号的访问令牌,有效期2小时'; comment on column URP.WECHAT_CONFIG.lpgxsj is '令牌更新时间'; comment on column URP.WECHAT_CONFIG.lpxcsxsj is '令牌下次刷新时间'; comment on column URP.WECHAT_CONFIG.jsapiticket is '微信公众号JSAPI票据'; comment on column URP.WECHAT_CONFIG.pjgxsj is '票据更新时间'; comment on column URP.WECHAT_CONFIG.pjxcsxsj is '票据下次刷新时间'; comment on column URP.WECHAT_CONFIG.wxmc is '微信名称'; comment on column URP.WECHAT_CONFIG.wxhm is '微信号码'; comment on column URP.WECHAT_CONFIG.wxlx is '微信公众号类型(订阅号、服务号、企业号)'; comment on column URP.WECHAT_CONFIG.wxms is '微信公众号描述'; comment on column URP.WECHAT_CONFIG.sfsc is '是否删除'; comment on column URP.WECHAT_CONFIG.jgbm is '机构编码'; comment on column URP.WECHAT_CONFIG.cjsj is '创建时间'; comment on column URP.WECHAT_CONFIG.cjr is '创建人'; comment on column URP.WECHAT_CONFIG.zhxgsj is '最后修改时间'; comment on column URP.WECHAT_CONFIG.zhxgr is '最后修改人'; comment on column URP.WECHAT_CONFIG.bz is '备注'; comment on column URP.WECHAT_CONFIG.bly is '保留域'; alter table URP.WECHAT_CONFIG add constraint WECHAT_CONFIG_WXPZID primary key (WXPZID); prompt prompt Creating table WECHAT_TRANSFLOW prompt =============================== prompt create table URP.WECHAT_TRANSFLOW ( lsid VARCHAR2(32) default sys_guid() not null, qdzhid VARCHAR2(32), shbh VARCHAR2(20), zdbh VARCHAR2(20), jyckh VARCHAR2(50), jylsh VARCHAR2(50), qqflsh VARCHAR2(50), yjylsh VARCHAR2(50), shddh VARCHAR2(30), zdhm VARCHAR2(50), spmc VARCHAR2(30), jysj VARCHAR2(20) not null, yhjyzh VARCHAR2(30), jyje NUMBER(12,2) default 0.00 not null, jyzt VARCHAR2(2) default 1 not null, zhye NUMBER(12,2) default 0.00, ywlx VARCHAR2(20) not null, jybz VARCHAR2(100), jlcjsj TIMESTAMP(6) default sysdate not null, dzrq DATE default sysdate not null, dzbs VARCHAR2(2) default 0 not null, crkbs VARCHAR2(2) default 0 not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) default 0 not null, bly1 VARCHAR2(50), bly2 VARCHAR2(50), bly3 VARCHAR2(50), dzbh VARCHAR2(50), ejbs VARCHAR2(15), sxf NUMBER(12,2) default 0.00 not null, qsje NUMBER(12,2) default 0.00, qsrq VARCHAR2(20) ) ; comment on table URP.WECHAT_TRANSFLOW is '微信交易流水表'; comment on column URP.WECHAT_TRANSFLOW.lsid is '微信流水主键ID'; comment on column URP.WECHAT_TRANSFLOW.qdzhid is '渠道结算账户ID'; comment on column URP.WECHAT_TRANSFLOW.shbh is '商户编号'; comment on column URP.WECHAT_TRANSFLOW.zdbh is '终端编号'; comment on column URP.WECHAT_TRANSFLOW.jyckh is '交易参考号(系统跟踪号、业务流水号)'; comment on column URP.WECHAT_TRANSFLOW.jylsh is '交易流水号(账务流水号)'; comment on column URP.WECHAT_TRANSFLOW.qqflsh is '请求方流水号'; comment on column URP.WECHAT_TRANSFLOW.yjylsh is '原交易流水号:交易为后续类交易时有值'; comment on column URP.WECHAT_TRANSFLOW.shddh is '商户订单号'; comment on column URP.WECHAT_TRANSFLOW.zdhm is '账单号码'; comment on column URP.WECHAT_TRANSFLOW.spmc is '商品名称'; comment on column URP.WECHAT_TRANSFLOW.jysj is '交易时间'; comment on column URP.WECHAT_TRANSFLOW.yhjyzh is '用户交易账号(支付宝账号/银行卡号)'; comment on column URP.WECHAT_TRANSFLOW.jyje is '交易金额(单位:元)'; comment on column URP.WECHAT_TRANSFLOW.jyzt is '交易状态(0:失败,1:成功,2:未知)'; comment on column URP.WECHAT_TRANSFLOW.zhye is '账户余额(单位:元)'; comment on column URP.WECHAT_TRANSFLOW.ywlx is '业务类型(在线支付、交易退款)'; comment on column URP.WECHAT_TRANSFLOW.jybz is '交易备注'; comment on column URP.WECHAT_TRANSFLOW.jlcjsj is '记录创建时间'; comment on column URP.WECHAT_TRANSFLOW.dzrq is '对账日期'; comment on column URP.WECHAT_TRANSFLOW.dzbs is '对账标识(1:已对账,0:未对账)'; comment on column URP.WECHAT_TRANSFLOW.crkbs is '重入库标识(1:重入库,0:原始入库)'; comment on column URP.WECHAT_TRANSFLOW.jgbm is '机构编码'; comment on column URP.WECHAT_TRANSFLOW.sfsc is '删除状态(1:删除,0:未删除)'; comment on column URP.WECHAT_TRANSFLOW.bly1 is '保留域1'; comment on column URP.WECHAT_TRANSFLOW.bly2 is '保留域2'; comment on column URP.WECHAT_TRANSFLOW.bly3 is '保留域3->就诊卡号'; comment on column URP.WECHAT_TRANSFLOW.dzbh is '对账编号'; comment on column URP.WECHAT_TRANSFLOW.ejbs is '二级标识'; comment on column URP.WECHAT_TRANSFLOW.sxf is '手续费(单位:元)'; comment on column URP.WECHAT_TRANSFLOW.qsje is '清算金额(单位:元)'; comment on column URP.WECHAT_TRANSFLOW.qsrq is '清算日期'; create index URP.DZRQ_SFSC_DZS_JGBM_SHDDH_QDZH on URP.WECHAT_TRANSFLOW (QDZHID, SHDDH, DZRQ, DZBS, JGBM, SFSC); alter table URP.WECHAT_TRANSFLOW add constraint WECHAT_TRANSFLOW_PRIMARYKEY primary key (LSID); prompt prompt Creating table WF_ABNORMAL_ORDER prompt ================================ prompt create table URP.WF_ABNORMAL_ORDER ( ycddid VARCHAR2(32) default sys_guid() not null, sqdid VARCHAR2(32) not null, gllsbmc VARCHAR2(15), gllsbid VARCHAR2(32), ddbh VARCHAR2(30) not null, ddje NUMBER(12,2) not null, yclx VARCHAR2(2) not null, ycms VARCHAR2(50), ddlx VARCHAR2(2) not null, ddclzt VARCHAR2(2) not null, jysj VARCHAR2(20), jlcjsj TIMESTAMP(6) default sysdate, jlcjr VARCHAR2(20), zhxgsj TIMESTAMP(6), zhxgr VARCHAR2(20), jgbm VARCHAR2(15) not null, bz VARCHAR2(100), bly VARCHAR2(50) ) ; comment on table URP.WF_ABNORMAL_ORDER is '异常订单信息表'; comment on column URP.WF_ABNORMAL_ORDER.ycddid is '异常订单Id'; comment on column URP.WF_ABNORMAL_ORDER.sqdid is '申请记录表主键Id'; comment on column URP.WF_ABNORMAL_ORDER.gllsbmc is '关联流水表名称'; comment on column URP.WF_ABNORMAL_ORDER.gllsbid is '关联流水表主键Id'; comment on column URP.WF_ABNORMAL_ORDER.ddbh is '订单编号'; comment on column URP.WF_ABNORMAL_ORDER.ddje is '订单金额'; comment on column URP.WF_ABNORMAL_ORDER.yclx is '异常类型(对账异常类型+His与渠道都不存在)'; comment on column URP.WF_ABNORMAL_ORDER.ycms is '异常描述'; comment on column URP.WF_ABNORMAL_ORDER.ddlx is '订单类型(0:需医院处理,1:需HIS处理流程)'; comment on column URP.WF_ABNORMAL_ORDER.ddclzt is '订单处理状态(0:新增,1:已作废,10:会计确认处理中,11:财务审批通过,12:财务审批不通过,13:会计退回,14:会计处理中,15:会计审批通过,16:会计审批不通过,17:财务审批中,18:会计审批中,2:已完成,3:HIS退回,4:HIS处理中,5:HIS确认退回,6:HIS确认处理中,7:地纬确认退回,8:地纬确认处理中,9:会计确认退回)'; comment on column URP.WF_ABNORMAL_ORDER.jysj is '交易时间'; comment on column URP.WF_ABNORMAL_ORDER.jlcjsj is '记录创建时间'; comment on column URP.WF_ABNORMAL_ORDER.jlcjr is '记录创建人'; comment on column URP.WF_ABNORMAL_ORDER.zhxgsj is '最后修改时间'; comment on column URP.WF_ABNORMAL_ORDER.zhxgr is '最后修改人'; comment on column URP.WF_ABNORMAL_ORDER.jgbm is '机构编码'; comment on column URP.WF_ABNORMAL_ORDER.bz is '备注'; comment on column URP.WF_ABNORMAL_ORDER.bly is '保留域'; create index URP.IDX_DDCLZT on URP.WF_ABNORMAL_ORDER (DDCLZT, SQDID, DDBH); alter table URP.WF_ABNORMAL_ORDER add primary key (YCDDID); prompt prompt Creating table WF_APPLY_RECORD prompt ============================== prompt create table URP.WF_APPLY_RECORD ( sqdid VARCHAR2(32) default sys_guid() not null, sqdbh VARCHAR2(30) not null, hzxm VARCHAR2(50) not null, hzzyh VARCHAR2(32), hzjzkh VARCHAR2(20), hzsfzh VARCHAR2(18), sqdlx VARCHAR2(30) not null, sqdclzt VARCHAR2(2) not null, sqcjsj TIMESTAMP(6) default sysdate not null, sqcjr VARCHAR2(20), jgbm VARCHAR2(15) not null, bz VARCHAR2(100), bly VARCHAR2(50) ) ; comment on table URP.WF_APPLY_RECORD is '申请记录表'; comment on column URP.WF_APPLY_RECORD.sqdid is '申请记录主键Id'; comment on column URP.WF_APPLY_RECORD.sqdbh is '申请单编号(唯一标识)'; comment on column URP.WF_APPLY_RECORD.hzxm is '患者姓名'; comment on column URP.WF_APPLY_RECORD.hzzyh is '患者住院号'; comment on column URP.WF_APPLY_RECORD.hzjzkh is '患者就诊卡号'; comment on column URP.WF_APPLY_RECORD.hzsfzh is '患者身份证号'; comment on column URP.WF_APPLY_RECORD.sqdlx is '申请单类型(0:医院处理,1:HIS处理,2:医院和HIS共同处理)'; comment on column URP.WF_APPLY_RECORD.sqdclzt is '申请单处理状态(0:新增,1:处理中,2:已完成,3:部分已完成,4:已退回,5:部分已退回,6:已作废,7:部分已作废)'; comment on column URP.WF_APPLY_RECORD.sqcjsj is '申请创建时间'; comment on column URP.WF_APPLY_RECORD.sqcjr is '申请创建人'; comment on column URP.WF_APPLY_RECORD.jgbm is '机构编码'; comment on column URP.WF_APPLY_RECORD.bz is '备注'; comment on column URP.WF_APPLY_RECORD.bly is '保留域'; alter table URP.WF_APPLY_RECORD add primary key (SQDID); alter table URP.WF_APPLY_RECORD add constraint UK_APPLY_RECORD unique (SQDBH); prompt prompt Creating table WF_HPHANDLE_INFO prompt =============================== prompt create table URP.WF_HPHANDLE_INFO ( hjdclid VARCHAR2(32) default sys_guid() not null, sqdid VARCHAR2(32) not null, cljd VARCHAR2(2) not null, cllx VARCHAR2(2) not null, clms VARCHAR2(100) not null, fjmc1 VARCHAR2(50), fjbclj1 VARCHAR2(100), fjmc2 VARCHAR2(50), fjbclj2 VARCHAR2(100), clsj TIMESTAMP(6) default sysdate not null, clr VARCHAR2(20), zhxgsj TIMESTAMP(6), zhxgr VARCHAR2(20), jdqm VARCHAR2(20), jgbm VARCHAR2(15) not null, bz VARCHAR2(100), bly VARCHAR2(50) ) ; comment on table URP.WF_HPHANDLE_INFO is 'HIS流程--节点处理信息表'; comment on column URP.WF_HPHANDLE_INFO.hjdclid is 'HIS流程节点处理主键Id'; comment on column URP.WF_HPHANDLE_INFO.sqdid is '申请记录主键Id'; comment on column URP.WF_HPHANDLE_INFO.cljd is '处理节点'; comment on column URP.WF_HPHANDLE_INFO.cllx is '处理类型(1:提交,2:确认,3:退回,4:审批通过,5:审批不通过,6:处理,7:作废,8:保存,9:退回保存)'; comment on column URP.WF_HPHANDLE_INFO.clms is '处理描述'; comment on column URP.WF_HPHANDLE_INFO.fjmc1 is '附件名称1'; comment on column URP.WF_HPHANDLE_INFO.fjbclj1 is '附件保存路径1'; comment on column URP.WF_HPHANDLE_INFO.fjmc2 is '附件名称2'; comment on column URP.WF_HPHANDLE_INFO.fjbclj2 is '附件保存路径2'; comment on column URP.WF_HPHANDLE_INFO.clsj is '处理时间'; comment on column URP.WF_HPHANDLE_INFO.clr is '处理人'; comment on column URP.WF_HPHANDLE_INFO.zhxgsj is '最后修改时间'; comment on column URP.WF_HPHANDLE_INFO.zhxgr is '最后修改人'; comment on column URP.WF_HPHANDLE_INFO.jdqm is '节点签名'; comment on column URP.WF_HPHANDLE_INFO.jgbm is '机构编码'; comment on column URP.WF_HPHANDLE_INFO.bz is '备注'; comment on column URP.WF_HPHANDLE_INFO.bly is '保留域'; alter table URP.WF_HPHANDLE_INFO add constraint PK_HPHANDLE_INFO primary key (HJDCLID); prompt prompt Creating table WF_MPHANDLE_INFO prompt =============================== prompt create table URP.WF_MPHANDLE_INFO ( mjdclid VARCHAR2(32) default sys_guid() not null, sqdid VARCHAR2(32) not null, cljd VARCHAR2(2) not null, cllx VARCHAR2(2) not null, clms VARCHAR2(100) not null, fjmc1 VARCHAR2(50), fjbclj1 VARCHAR2(100), fjmc2 VARCHAR2(50), fjbclj2 VARCHAR2(100), clsj TIMESTAMP(6) default sysdate not null, clr VARCHAR2(20), zhxgsj TIMESTAMP(6), zhxgr VARCHAR2(20), jdqm VARCHAR2(20), jgbm VARCHAR2(15) not null, bz VARCHAR2(100), bly VARCHAR2(50) ) ; comment on table URP.WF_MPHANDLE_INFO is '医院流程--节点处理信息表'; comment on column URP.WF_MPHANDLE_INFO.mjdclid is '医院流程节点处理主键Id'; comment on column URP.WF_MPHANDLE_INFO.sqdid is '申请记录主键Id'; comment on column URP.WF_MPHANDLE_INFO.cljd is '处理节点'; comment on column URP.WF_MPHANDLE_INFO.cllx is '处理类型(1:提交,2:确认,3:退回,4:审批通过,5:审批不通过,6:处理,7:作废,8:保存,9:退回保存)'; comment on column URP.WF_MPHANDLE_INFO.clms is '处理描述'; comment on column URP.WF_MPHANDLE_INFO.fjmc1 is '附件名称1'; comment on column URP.WF_MPHANDLE_INFO.fjbclj1 is '附件保存路径1'; comment on column URP.WF_MPHANDLE_INFO.fjmc2 is '附件名称2'; comment on column URP.WF_MPHANDLE_INFO.fjbclj2 is '附件保存路径2'; comment on column URP.WF_MPHANDLE_INFO.clsj is '处理时间'; comment on column URP.WF_MPHANDLE_INFO.clr is '处理人'; comment on column URP.WF_MPHANDLE_INFO.zhxgsj is '最后修改时间'; comment on column URP.WF_MPHANDLE_INFO.zhxgr is '最后修改人'; comment on column URP.WF_MPHANDLE_INFO.jdqm is '节点签名'; comment on column URP.WF_MPHANDLE_INFO.jgbm is '机构编码'; comment on column URP.WF_MPHANDLE_INFO.bz is '备注'; comment on column URP.WF_MPHANDLE_INFO.bly is '保留域'; alter table URP.WF_MPHANDLE_INFO add primary key (MJDCLID); prompt prompt Creating table WF_STATISTICS prompt ============================ prompt create table URP.WF_STATISTICS ( xxtjid VARCHAR2(32) default sys_guid() not null, yclx VARCHAR2(2) not null, ycddzs NUMBER not null, ycddzje NUMBER(12,2) not null, yclycddzs NUMBER not null, yclycddzje NUMBER(12,2) not null, tjqsrq DATE not null, tjzzrq DATE not null, yclddzs NUMBER not null, yclddzje NUMBER(12,2) not null, yzfddzs NUMBER not null, yzfddzje NUMBER(12,2) not null, sqdzs VARCHAR2(30), sqdzje VARCHAR2(20) not null, jlcjsj TIMESTAMP(6) not null, jgbm VARCHAR2(15) not null, sfsc VARCHAR2(2) not null, bz VARCHAR2(100) default '', bly VARCHAR2(50) ) ; comment on table URP.WF_STATISTICS is '信息统计表'; comment on column URP.WF_STATISTICS.xxtjid is '信息统计主键Id'; comment on column URP.WF_STATISTICS.yclx is '异常类型'; comment on column URP.WF_STATISTICS.ycddzs is '异常订单总数'; comment on column URP.WF_STATISTICS.ycddzje is '异常订单总金额'; comment on column URP.WF_STATISTICS.yclycddzs is '已处理异常订单总数'; comment on column URP.WF_STATISTICS.yclycddzje is '已处理异常订单总金额'; comment on column URP.WF_STATISTICS.tjqsrq is '统计起始日期'; comment on column URP.WF_STATISTICS.tjzzrq is '统计终止日期'; comment on column URP.WF_STATISTICS.yclddzs is '已处理订单总数'; comment on column URP.WF_STATISTICS.yclddzje is '已处理订单总金额'; comment on column URP.WF_STATISTICS.yzfddzs is '已作废订单总数'; comment on column URP.WF_STATISTICS.yzfddzje is '已作废订单总金额'; comment on column URP.WF_STATISTICS.sqdzs is '申请单总数'; comment on column URP.WF_STATISTICS.sqdzje is '申请单总金额'; comment on column URP.WF_STATISTICS.jlcjsj is '创建日期'; comment on column URP.WF_STATISTICS.jgbm is '机构编码'; comment on column URP.WF_STATISTICS.sfsc is '是否删除'; comment on column URP.WF_STATISTICS.bz is '备注'; comment on column URP.WF_STATISTICS.bly is '保留域'; alter table URP.WF_STATISTICS add constraint PK_STATISTICS primary key (XXTJID); prompt prompt Creating sequence ACT_EVT_LOG_SEQ prompt ================================= prompt create sequence URP.ACT_EVT_LOG_SEQ minvalue 1 maxvalue 9999999999999999999999999999 start with 1 increment by 1 cache 20; spool off <file_sep>/dareway/2021-3/统计医保负担金额及笔数.sql select meda.qdjyje, meda.jybs - nvl((medb.jybs * 2), 0) jybs from (select sum(med.ybfdje + med.grzhzfje) qdjyje, count(1) jybs from urp.medicare_transflow med where 1 = 1 and to_char(med.dzrq, 'yyyy-mm-dd') = '2021-03-04' and med.sfsc = '0') meda, (select count(1) jybs from urp.medicare_transflow med2 where 1 = 1 and to_char(med2.dzrq, 'yyyy-mm-dd') = '2021-03-04' and med2.sfsc = '0' and med2.jsbz = '0') medb select * from urp.medicare_transflow med where 1 = 1 and to_char(med.dzrq, 'yyyy-mm-dd') = '2021-03-04' and med.sfsc = '0' <file_sep>/dareway/重要sql/广发接口对于原表的修改.sql select * from URP.GF_BANKTRANS_ACCOUNTS; -- 广发新接口增加字段 alter table urp.gf_banktrans_accounts add ( jyje number(12,2) default 0, inname varchar2(60), inacc varchar2(40), errCode varchar2(25), businessType varchar(2) ); -- 新增字段的注释 comment on column urp.gf_banktrans_accounts.jyje is '交易金额'; comment on column urp.gf_banktrans_accounts.inname is '转入户名'; comment on column urp.gf_banktrans_accounts.inacc is '转入账号'; comment on column urp.gf_banktrans_accounts.errCode is '失败错误码'; comment on column urp.gf_banktrans_accounts.businessType is '业务类型:1、费用报销,2、其他代付,3、代发工资,4、慧支付,6、代付理赔'; <file_sep>/dareway/重要sql/生活号.sql ------增加字段 ------------------------------------------------- alter table polymer.patient_care_info add ppatientid varchar2(60) ; alter table polymer.appointdoc_record add ppatientid varchar2(60) ; ------增加字段 --------------------------- ---------------------- 连上199的数据库 执行一下这2个语句吧 select * from polymer.ssh_mouldnews; insert into polymer.ssh_mouldnews (APPID, MOULDNEWSID, MOULDNEWSNNAME, XXGNID, REMARK) values ('2021001174638512', '6533b31573a548599aa5153dc25d5046', '预约成功通知', 'yygh', '测试'); insert into polymer.ssh_mouldnews (APPID, MOULDNEWSID, MOULDNEWSNNAME, XXGNID, REMARK) values ('2021001174638512', 'be200ae8f9aa4b16a858fe0ec257e98a', '取消预约成功通知', 'qxyy', '测试'); insert into polymer.ssh_mouldnews (APPID, MOULDNEWSID, MOULDNEWSNNAME, XXGNID, REMARK) values ('2021001174638512', 'b5522c23530a4f16a846b815c3aaac6c', '就诊卡充值成功', 'jzkczcg', '测试'); select * from polymer.hospital_info a select * from polymer.hospital_info a; --truncate table polymer.hospital_info ; --2021-2-23 删除数据 select * from polymer.user_info a where a.patientid='2088012673611445'; delete from polymer.user_info a where a.patientid='2088012673611445'; select a.patientid,a.isbinding,a.ppatientid,a.working from polymer.user_info a where a.patientid='2088012673611445'; <file_sep>/dareway/2021-3/汇总统计对账结果+超期+普通渠道.sql select * from channel_reconresult; select * from urp.gf_banktrans_accounts gf where 1 = 1 and gf.jyclzt = '1' and gf.fqjysj >= '20210307' and gf.fqjysj <= '20210307'; select ci.qdmc, nvl(sum(cr.qdjyzje), 0) qdjyzje, nvl(sum(cr.qdjyzbs), 0) qdjyzbs, nvl(sum(cr.qdycjyzje), 0) qdycjyzje, nvl(sum(cr.qdycjyzbs), 0) qdycjyzbs, nvl(sum(cr.sxf), 0) sxf, nvl(sum(cr.qdzfbs), 0) qdzfbs, nvl(sum(cr.qdtkbs), 0) qdtkbs from urp.channel_reconresult cr left join urp.channel_info ci on cr.qdid = ci.qdid where 1 = 1 and cr.sfsc = '0' and cr.dzbs = '1' and to_char(cr.dzrq, 'yyyymmdd') >= '20210308' and to_char(cr.dzrq, 'yyyymmdd') <= '20210308' group by cr.qdid, ci.qdmc union select nvl(null,'³¬ĘŚ') qdmc, nvl(sum(gf2.jyje),0) qdjyzje, nvl(sum(gf2.zjjybs),0) qdjyzbs, nvl(sum(zjjyje - gf2.jyje),0) qdycjyzje, nvl(sum(gf2.sbbs),0) qdycjyzbs, nvl(sum(gf2.sxf),0) sxf, nvl(null,0) qdzfbs, nvl(sum(gf2.cgbs),0) qdtkbs from (select gf.khpch, gf.fqjysj, gf.zjjybs, gf.zjjyje, gf.cgbs, gf.sbbs, sum(jyje) jyje, gf.zjjysxf, nvl(sum(gf.sxf), 0.00) sxf from urp.gf_banktrans_accounts gf where 1 = 1 and gf.jyclzt = '1' and gf.fqjysj >= '20210307' and gf.fqjysj <= '20210307' group by gf.khpch, gf.zjjybs, gf.zjjyje, gf.zjjyje, gf.cgbs, gf.sbbs, gf.fqjysj, gf.zjjysxf order by gf.fqjysj) gf2 <file_sep>/Sql笔记-本地.sql  --系统权限传递: --增加WITH ADMIN OPTION选项,则得到的权限可以传递。//可以传递所获权限。 grant connect, resorce to user50 with admin option; --系统权限回收:系统权限只能由DBA用户回收 Revoke connect, resource from user50;    --查询用户拥有哪里权限(用户名字需要大写): select * from dba_role_privs where grantee = 'ddszone'; select distinct a.GRANTEE from dba_sys_privs a; select * from role_sys_privs; --查自己拥有哪些系统权限 select * from session_privs; -- 查看角色(只能查看登陆用户拥有的角色)所包含的权限 select * from role_sys_privs; --删除用户 //加上cascade则将用户连同其创建的东西全部删除 drop user 用户名 cascade; -- 系统权限传递: -- 增加WITH ADMIN OPTION选项,则得到的权限可以传递。//可以传递所获权限。 grant connect, resorce to user50 with admin option; -- 系统权限回收:系统权限只能由DBA用户回收 Revoke connect, resource from user50; -- 查询表空间 select * from dba_data_files; select file_name from dba_data_files select name from v$datafile -- 设置表空间自动扩容 alter database datafile '/opt/oracle/oradata/orcl/ts_hass_1.dbf' autoextend on; -- 创建表空间(表空间的名字是自己起的,XX.dbf) size 后面配置的是表空间的大小 create tablespace wdf datafile 'D:\software\sql\oracle\mulu\oradata\orcl\WDF.DBF' size 1G; -- 修改表空间名字 alter tablespace ddszone rename to TS_DDS; --设置表空间默认用户 create user wdf identified by wdf default tablespace wdf; --修改用户的永久表空间可以执行命令: alter user urp default tablespace URP_RUN; -- 查看表空间默认用户(需要登录用户) select * from user_users; --Oracle中一个表空间可能是多个用户的默认表空间,下面语句统计了用户及其默认表空间情况,如果用户多个,用户之间通过逗号分隔。 select t.default_tablespace, to_char(wmsys.wm_concat(username)) all_users from dba_users t group by t.default_tablespace; -- 创建用户(账号:wdf 密码:<PASSWORD>)赋予表空间:wdf_tablespace create user ddszone identified by ddszone default tablespace ddszone; -- 修改用户密码 alter user urp identified by urp; -- 给用户 wdf 赋予CREATE SESSION权限 连接数据库权限 grant create session to ipay; -- 给用户 wdf 赋予CREATE TABLE权限 建立数据表权限 grant CREATE TABLE to ipay; -- 给用户 wdf 赋予 UNLIMITED TABLESPACE 权限 --表空间无限制权限(空间配额) grant UNLIMITED TABLESPACE to ipay; -- 对账项目赋予用户的角色:创建session角色,创建资源角色,Create table 等等,数据库管理员角色 grant connect,resource,dba to wdf; -- (start)plsql 提示 动态执行表不可访问,或在v$session... 中的错误,执行下列sql或者打开:工具->首选项->选项-> 去掉“自动统计”前面的勾选 -- 根据提示,用sys身份给 XX 用户授权 grant select on V_session to XX; grant select on V_$sesstat to XX; grant select on V_$statname to XX;   -- 给所有用户授权 grant select on V_$session to public; grant select on V_$sesstat to public; grant select on V_$statname to public; -- 查询用户的密码过期时间 select * from dba_profiles where profile = 'DEFAULT' and resource_name = 'PASSWORD_LIFE_TIME'; -- 修改密码为永久 alter profile default limit password_life_time unlimited; commit; -- (end) select * from user_tab_comments -- 查询本用户的表,视图等。 select * from wdf.test_wdf; --如果有删除用户的权限,则可以(加了cascade就可以把 用户 连带的数据全部删掉。): drop user ddszone cascade; -- oracle 分页(两层) SELECT * FROM (SELECT ROWNUM AS rowno, t.* FROM his_transflow t WHERE -- 这里可以添加相应的条件以及排序方式等,用and符号连接 ROWNUM <= 20 ) table_alias WHERE table_alias.rowno >= 10; -- oracl 分页加排序(三层) SELECT * FROM ( select a.* from( SELECT ROWNUM AS rowno, t.* FROM his_transflow t order by t.jyje ) a WHERE a.rowno <= 20 ) table_alias WHERE table_alias.rowno >= 10; -- oracle sql 查询前十条数据 select * from b2c_code where rownum <= '10'; -- sql server 查询前十条数据 select top 10 * from b2c_code; -- oracle 数据导出 exp 这个命令需要在cmd执行 @服务名字 例如在本地net manager配置的远程数据库的服务名字 -- exp/imp 实例 -- exp help=y 查看帮助 -- 导出单个表 exp usr/pwd@sid file=c:\tb.dump tables=tb1 exp urp/urp@urp file=e:\tb.dump tables=(user_signature) -- 删除表 drop table user_signature --找回删除数据 select dbms_flashback.get_system_change_number from dual; select count(*) from URP.E_EQUIPMENT_FACTORY as of scn 20721406; --在这个点上查到数据 select count(*) from URP.E_EQUIPMENT_FACTORY as of scn 20660000; -- 方法二 select * from URP.E_EQUIPMENT_FACTORY as of timestamp to_timestamp('2020-09-09 15:29:00','yyyy-mm-dd hh24:mi:ss'); -- 查看当前锁定的表 select object_name, machine, s.sid, s.serial# from v$locked_object l, dba_objects o, v$session s where l.object_id  =  o.object_id and l.session_id = s.sid; -- 修改锁表的状态 alter system kill session 'SID,serial#'; -- 例子 alter system kill session '199,35435'; --查看当前数据库实例名(SID) select instance_name from v$instance; /*查看sid*/ select * from v$instance select * from v$version -- 确认用户所使用的概要文件: select username,profile from dba_users; --查看概要文件中有关登录次数的限制: select * from dba_profiles where profile='DEFAULT' and resource_name='FAILED_LOGIN_ATTEMPTS'; --如果尝试登录次数限制为10次,将尝试登录次数的限制修改为不受限: alter profile default limit failed_login_attempts unlimited;  --修改后,还没有被提示ORA-28000警告的账户不会再碰到同样的问题,已被锁定用户仍需解锁,方法如下: alter user urp account unlock; -- 查询修改死锁的数据 select Distinct 'alter system kill session ' || chr(39) || b.sid || ',' || b.serial# || chr(39) || ';' As cmd, b.username, b.logon_time from v$locked_object a, v$session b where a.session_id = b.sid; -- 释放死锁数据 alter system kill session '1621,33463'; --expdp导出datadump --创建目录 create directory exportDB as 'E:\OracleDB'; --查询目录 SELECT * FROM dba_directories; --导出文件 $expdp urp/urp@urp directory=exportDB dumpfile =20210531.dmp logfile=20210531.log FULL=y; SELECT * FROM dba_directories; -- 删除文件,需要权限 delete from dba_directories a where a.directory_name = 'ORACLEDB'; --- 用户配置 alter user ddszone rename to ddszone1 identified by ddszone; select * from user$ where NAME in ('DDSZONE'); --1、用sysdba账号登入数据库,然后查询到要更改的用户信息:   SELECT user#,name FROM user$; select user#,name from user$ where name = 'ddszone'; --2、更改用户名并提交: UPDATE USER$ SET NAME='ddszone1' WHERE user#=93; COMMIT; --3、强制刷新: ALTER SYSTEM CHECKPOINT; ALTER SYSTEM FLUSH SHARED_POOL; --4、更新用户的密码: ALTER USER PORTAL IDENTIFIED BY 123; -- 查看数据库连接情况 select count(*) from v$session where status='ACTIVE'; select username,count(username) from v$session where username is not null group by username; --查看系统资源 SELECT resource_name, current_utilization, max_utilization, LIMIT, ROUND (max_utilization / LIMIT * 100) || '%' rate FROM (SELECT resource_name, current_utilization, max_utilization, TO_NUMBER (initial_allocation) LIMIT FROM v$resource_limit WHERE resource_name IN ('processes', 'sessions') AND max_utilization > 0); <file_sep>/dareway/2021-6/院内对账结果明细表.sql select count(*) --select * from urp.e_reconresult_detail rd --left join urp.e_equipment_transflow cnt on rd.ynsblsid = cnt.ynsblsid where 1=1 -- 1244笔 ipay对账后的账平=1284 -- and rd.sbcsid = 'f971c7babf374641bc2f6e36996a1813' -- and rd.sbid = '08978939bda4488abcd9975b35dbaa56' -- 6099 6095 -- 对账时 账平 6093 and rd.sbcsid = '4fcc70d4706b4120abe0ae308595ae54' and rd.sbid = 'b8036942f41e44349142d1c06493ed01' and rd.sfsc = '0' and rd.dzrq = to_date('2021-06-28','yyyy-MM-dd') and rd.yclx is null --and rd.dzjg != '1' <file_sep>/dareway/重要sql/收费员报账普通渠道+超期转现金.sql select dtl2.*,bank1.bz from (select dtlrf.jyje, dtlrf.yhid, nvl(to_number(dtlrf.zjlx), 0) zjlx, dtlrf.czybh, dtlrf.czyxm, dtlrf.jysj from ipay.order_detl dtlrf where 1 = 1 and dtlrf.paystate = 'repaid' and (dtlrf.cqtfbs not in ('1', '2') or dtlrf.cqtfbs is null) -- 超期转现金部分 union select cash.jyje, 'XJZF' yhid, 0 zjlx, cash.czybh, cash.czyxm,cash.jysj from ipay.overtocash_refund cash where 1 = 1 and cash.state = 'repaid') dtl2 left join ipay.bank_info bank1 on bank1.yhid = dtl2.yhid where 1=1 and dtl2.jysj >= '20210309000000' and dtl2.jysj <= '20210309134221' order by dtl2.jyje <file_sep>/dareway/重要sql/收款员1.sql select case when dtl1.czybh is not null then dtl1.czybh else dtl3.czybh end czybh, case when dtl1.czyxm is not null then dtl1.czyxm else dtl3.czyxm end czyxm, case when dtl1.bz is not null then dtl1.bz else dtl3.bz end qdmc, nvl(dtl1.jyje, 0) zfje, nvl(dtl1.jybs, 0) zfbs, nvl(dtl3.jyje, 0) tkje, nvl(dtl3.jybs, 0) tkbs, (nvl(dtl1.jyje, 0) - nvl(dtl3.jyje, 0)) as zje from (select dtl4.czybh, dtl4.czyxm, bank2.bz, sum(dtl4.jyje) jyje, count(dtl4.intradeno) jybs from ipay.order_detl dtl4 left join ipay.bank_info bank2 on bank2.yhid = dtl4.yhid where dtl4.paystate = 'paid' and dtl4.czybh = '001' and dtl4.jysj > '20191219000000' and dtl4.jysj < '20201219095114' group by dtl4.czybh, dtl4.czyxm, bank2.bz order by dtl4.czybh, dtl4.czyxm, bank2.bz) dtl1 full join (select dtl2.czybh, dtl2.czyxm, bank1.bz, sum(dtl2.jyje) jyje, count(1) jybs from ipay.order_detl dtl2 left join ipay.bank_info bank1 on bank1.yhid = dtl2.yhid where dtl2.paystate = 'repaid' and dtl2.czybh = '001' and dtl2.jysj > '20191219000000' and dtl2.jysj < '20201219095114' group by dtl2.czybh, dtl2.czyxm, bank1.bz order by dtl2.czybh, dtl2.czyxm, bank1.bz) dtl3 on dtl1.czybh = dtl3.czybh and dtl1.czyxm = dtl3.czyxm and dtl1.bz = dtl3.bz order by dtl1.czybh, dtl1.czyxm, dtl1.bz --, dtl3.bz <file_sep>/dareway/生殖.sql --select * from ipay.order_detl b where yhid = 'POS' order by b.fqjysj desc for update; --mongoDB -- 查询所有表 select * from user_tab_comments; -- 框架配置表 select * from ddszone.sequence_info --for update; select ddsname,ddszone_version,bigversion,smallversion from ddszone.ddsbase where arcdbid is null; -- mongodb select * from mongodb_para --for update; select * from ipay.UCOMPOS_MANAGEMENT_INFO --视图order_gen_det_list select * from order_gen_det_list; -- detl细表 select distinct dtl.yhid,dtl.terminalno from ipay.order_detl dtl where 1=1 and dtl.terminalno is not null; select dtl.terminalno,count(dtl.terminalno) from ipay.order_detl dtl where 1=1 and dtl.yhid like 'U%' and msg like '%ER%' group by dtl.terminalno and dtl.fqjysj like '2021032413%' and dtl.ip like '172.16.88.17' and dtl.paystate in ('repaid') order by dtl.fqjysj desc; dtl.cqtfbs = '1' order by dtl.fqjysj desc; --hisno select dtl.* from ipay.order_detl dtl where 1=1 and dtl.hisno = '20210305050478'; -- truncate table ipay.order_detl -- jshid select * from ipay.order_detl a where 1=1 and a.jshid like '%*99024121040425613284%' order by a.fqjysj desc; select * from ipay.order_detl a where 1=1 and a.jyje = 495.30 and a.jysj like '20210409%' order by a.fqjysj desc; select * from ipay.order_detl a where 1=1 and a.brxm like '侯占风%'and a.intradeno != '20210228P00066395DAREWAY' ; update ipay.order_detl a set a.paystate = 'paying',a.ip = '172.16.93.177' where 1=1 and a.yhid = 'UNIONCARD' and a.brxm = '侯占风' and a.intradeno != '20210228P00066395DAREWAY'; -- and a.intradeno = '20210228P00066385DAREWAY'; -- yhid select * from ipay.order_detl a where 1=1 --and a.yhid = 'YB' and a.yhid like '%YB%' --and a.paystate = 'paid' --and a.cardno = '571499' order by a.fqjysj desc; -- 超期转现金 select * from ipay.OVERTOCASH_REFUND -- 查询所有支付状态 select distinct a.paystate from ipay.order_detl a ; -- intradeno select * from ipay.order_detl a where 1=1 --order by intradeno desc; and intradeno like '%20210228P00066388DAREWAY%' --and a.paystate = 'refundclose' -- and a.yhid = 'UNIONCARD' --and a.brxm = '许树林' --and a.jysj like '20210220%' -- order by fqjysj desc; --and tradeno = 'IPA200921100018802' and tradeno = 'IPA210303100185767' and intradeno = '20210221P00059126DAREWAY' union select * from ipay.order_detl a where 1=1 -- and a.brxm = '张春荣' --and a.tradeno = 'IPA21022026285712' --and intradeno in('20210322P00098955DAREWAY','') and a.cardno in('571499','580315') order by a.fqjysj ; --- 删除医保撤销数据 --delete from ipay.order_detl d where 1=1 and d.intradeno = '20210315P00087248DAREWAY' select * from ipay.order_detl a where 1=1 --and a.ynkcode = '3' and a.jysj like '20210407%' -- and a.jysj <= '20210310153113' and a.czyxm = '刁静' order by jysj and a.yhmc = '微信' -- paystate czybh select * from ipay.order_detl a where 1=1 and a.czybh = '226'and a.cqtfbs = '1' and a.czybh = '493' and ycbs = '0' order by a.fqjysj desc; -- tradeno select * from ipay.order_detl where tradeno = 'IPA201216100159856' -- fqjysj select * from ipay.order_detl b where 1=1 and fqjysj between '20200914000000' and '20200914162139' order by fqjysj desc ; -- 细表超期 select * from ipay.order_detl b where b.cqtfbs = '1' order by b.fqjysj desc; -- 超期退费表 select a.*from ipay.overtime_refund a where 1=1 order by fqjysj desc ; select * from ipay.overtime_refund a where a.refundno = '20210318D00003190'; --select distinct state from ipay.overtime_refund ; -- 超期退费状态 -- 退款表 select * from ipay.refund_detl order by cjsj desc; --update ipay.ORDER_DETL set jysj='20200723122522' where intradeno='20200723P00001076DAREWAY' -- update ipay.ORDER_DETL set paystate=:paystate ,jysj=:jysj ,jym_ibank=:jym_ibank ,dsftradeno=:dsftradeno where intradeno=:intradeno select * from ipay.order_detl order by intradeno desc -- for update select * from ipay.order_genl g where g.tradeno = 'IPA21022026285712' and g.appid is not null-- order by --jysj desc ; select * from ipay.order_genl gen where 1=1 and gen.description = '存量迁移数据' and gen.tradeno = 'IPA210220263510710'-- for update select * from IPAY.SDSZ_TRADE_INFO tr order by tr.jyddh desc --退款明细 select * from ipay.refund_detl order by cjsj desc; --银行 select yhid,bz from ipay.bank_info where bz like '%医保%' --for update select distinct bz,yhid from ipay.bank_info select * from ipay.bank_info where yhid = 'POS'; select * from urp.ucompos_trade_info s order by s.fqjysj desc -- 托盘程序的表 Select * From ucompos_trade_info where (1>0) and dyfwybs ='20200616P00000303DAREWAY' and jyzt ='1' -- 退费失败 Select * From ucompos_trade_info where (1>0) and dyfwybs ='20200618P00000432DAREWAY' -- 支付成功未退费 Select * From ucompos_trade_info where (1>0) and dyfwybs ='20200618P00000420DAREWAY' and jyzt ='1' --成功 Select * From ucompos_trade_info order by fqjysj desc Select * From ucompos_trade_info where (1>0) and ( dyfwybs ='20200618P00000432DAREWAY' or dyfwybs ='20200618P00000420DAREWAY' or dyfwybs ='20200616P00000303DAREWAY') --发起调用的时候查询配置 Select * From ucompos_config where (1>0) and yybh ='10001' and rzbm ='dw1001' Select * From ucompos_config where (1>0) and yybh ='10001' and rzbm ='dw1001' --查询指定退款记录 select distinct a.yzdtje,a.description,a.zje,a.dzytje,b.jyje,b.tkintradeno, --d2c(c2d(b.jysj,'yyyymmdd hh24:mi:ss'),'yyyy-mm-dd hh24:mi:ss') b.jysj, b.tradeno,b.intradeno,c.yhmc,b.yhid,b.paystate,b.fkjgbh,a.orgno, d.rzbm,d.czybh,d.czyxm,d.terminalno,d.jyqd ,d.cjsj from ipay.order_genl a, ipay.order_detl b, ipay.bank_info c,ipay.refund_detl d where b.yhid = c.yhid and d.refundtradeno = b.refundtradeno and a.tradeno = b.tradeno and d.refundtradeno = '20200616000000050' and a.yzdtje > 0 and b.paystate = 'paid' and c.yhid = 'POS' order by b.jysj desc --order by d.cjsj desc -- 查询所有表 select * from user_tab_comments 1 USER_AUTHCODE TABLE 用户授权码和支付宝UUID关系 2 UCOMPOS_MANAGEMENT_INFO TABLE 调银商终端DLL管理类交易信息表 3 SDSZ_TRADE_INFO TABLE 调用HIS账户验证、充值、退费接口,交易流水表 4 REFUND_DETL TABLE 5 OVERTIME_REFUND TABLE 6 ORG_INFO TABLE 接入机构信息 7 ORG_BANK TABLE 接入机构银行信息 8 ORDER_SETTLEPARA TABLE 医保结算参数表 9 ORDER_GENL TABLE 订单主表 10 ORDER_DETL TABLE 订单辅表,支付明细表 11 MONGODB_PARA TABLE mongoDB配置参数 12 BANK_INFO TABLE 银行基本信息 13 ORDER_GEN_DET_LIST VIEW --订单主表 select * from ipay.order_genl order by cjsj desc ; -- 订单辅表,支付明细表 select * from ORDER_DETL -- 接入机构信息 select * from ORG_INFO -- 调用HIS账户验证、充值、退费接口,交易流水表 select * from SDSZ_TRADE_INFO -- 调银商终端DLL管理类交易信息表 select * from UCOMPOS_MANAGEMENT_INFO select * from urp.ucompos_config; -- 银行基本信息 select * from ipay.bank_info --for update select distinct bz from ipay.bank_info --for update select * from ipay.order_detl where (cqtfbs is null or cqtfbs = '0') order by intradeno desc; select * from ipay.order_detl where cqtfbs = '1' and jysj like '20210106%' and czybh = '102' and order by intradeno desc; -- 对账视图 select * from ipay.v_trade_info; select text from user_views where view_name = 'V_TRADE_INFO'; select view_name from user_views; select * from ipay.v_trade_info_yndz a where a.jysj like '20210222%' and a.yhid in ('WXXCX') -- 创建视图(v_trade_info) create or replace view ipay.v_trade_info as select distinct dt.tradeno, --平台订单号 dt.intradeno ddbh, --交易订单号(订单编号) dt.brxm, --病人姓名 dt.cardno brjzkh, --病人就诊卡号 dt.brsfzhm sfzhm, --病人身份证号码 dt.yhid, --支付银行 bk.yhjc qdmc, --渠道名称 case bk.yhjc when '转账' then 'Transfer' when '广发银行' then 'CgbSmartPay' when '支付宝' then 'Alipay' when 'POS' then 'UnionPay' when '现金' then 'CashPay' when '医保' then 'Medicare' when '微信' then 'WeChat' end jyqdbs, --交易渠道标识 case dt.type when 'pay' then '支付' when 'refund' then '退款' end ywlx, --业务类型 nvl(dt.fqjysj,dt.jysj) as jlcjsj, --记录创建时间 dt.jysj, --支付时间 --dt.jyje, case dt.type when 'pay' then dt.jyje when 'refund' then -1*dt.jyje end jyje, --to_char(dt.jyje,'0.99') as jyje, --交易金额 gn.orgno mchid, --医院编号 case dt.paystate when 'paid' then '1' when 'repaid' then '1' when 'paying' then '2' when 'repaying' then '2' when 'refailed' then '0' when 'failed' then '0' when 'closed' then '2' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case dt.paystate when 'paid' then '已支付' when 'repaid' then '已退款' when 'paying' then '支付中' when 'repaying' then '退款中' when 'refailed' then '退款失败' when 'failed' then '支付失败' when 'closed' then '已关闭' else '未知' end jyztms, --交易状态描述 dt.tkintradeno, --退款原订单号 dt.czyxm yhryxm, --操作员姓名 dt.czybh yhrybh, --操作员编号 dt.zflx, --支付类型(0:充值,1:缴费) dt.terminalno jyzdbh, --交易终端编号 dt.merchantno jyshbh, --交易商户编号 dt.jyqd jyjz, --POS交易卡介质(医保,银联卡) dt.hisno hisno, -- his交易流水号 dt.ynkcode ynjyzt, --院内卡状态标识:ynjyzt对应于ynccode (0:成功,1:失败,2:未知) dt.jytj jytj --交易途径 from ipay.order_detl dt, ipay.bank_info bk, ipay.order_genl gn where dt.tradeno=gn.tradeno and dt.yhid=bk.yhid and dt.paystate in ('paid','repaid','refailed','failed','closed') ; ------------------ select * from ipay.order_detl a where a.jysj like '20201224%'; select * from ipay.v_trade_info_yndz where jysj like '2021022423%' select * from ipay.v_trade_info_yndz where jysj like '2021022500%' and brjzkh = '060000018' order by jyqdbs ; select * from ipay.v_trade_info_yndz where jysj between '20200828000000' and '20200828240000'; -- 交易视图 院内对账 create or replace view ipay.v_trade_info_yndz as select distinct dt.tradeno, --平台订单号 dt.intradeno ddbh,--交易订单号(订单编号) dt.hisno, --his调用流水号 dt.brxm, --病人姓名 dt.cardno brjzkh, --病人就诊卡号 dt.brsfzhm sfzhm, --病人身份证号码 dt.yhid, --支付银行/渠道 bk.yhjc qdmc, --支付银行/渠道名称 case when instr(bk.yhjc, '转账') > 0 or dt.cqtfbs = '1' then 'Transfer' when instr(bk.yhjc, '广发') > 0 then 'CgbSmartPay' when instr(bk.yhjc, '支付宝') > 0 then 'Alipay' when instr(bk.yhjc, 'POS') > 0 then 'UnionPay' when instr(bk.yhjc, '现金') > 0 then 'CashPay' when bk.yhjc = '医保' then 'Medicare' when dt.yhid = 'SYBMZ' then 'Medicare' when dt.yhid = 'SYBZY' then 'Medicare' when bk.yhjc = '异地门诊' then 'Medicare' when bk.yhjc = '异地住院' then 'Medicare' when instr(bk.yhjc, '微信') > 0 then 'WeChat' else 'Other' end jyqdbs, --交易渠道标识 case dt.type when 'pay' then '支付' when 'refund' then '退款' end ywlx, --业务类型 nvl(dt.fqjysj,dt.jysj) as jlcjsj, --记录创建时间 dt.jysj, --支付时间 case dt.type when 'pay' then dt.jyje when 'refund' then -1*dt.jyje end jyje, --交易金额 dt.ynkcode, --院内卡状态 gn.orgno mchid, --医院编号 case dt.paystate when 'paid' then '1' when 'repaid' then '1' when 'paying' then '2' when 'repaying' then '2' when 'refailed' then '0' when 'failed' then '0' when 'closed' then '2' else '2' end jyzt, --交易状态(0:失败,1:成功,2:未知) case dt.paystate when 'paid' then '已支付' when 'repaid' then '已退款' when 'paying' then '支付中' when 'repaying' then '退款中' when 'refailed' then '退款失败' when 'failed' then '支付失败' when 'closed' then '已关闭' else '未知' end jyztms, --交易状态描述 dt.tkintradeno yddbh, --退款原订单号 dt.dsftradeno jyckh, --交易参考号(终端)、结算号id (医保) case when instr(bk.yhjc, 'POS') > 0 then dt.jym_ibank when bk.yhjc = '医保' then dt.jshid when bk.yhjc = '省医保门诊' then dt.jshid when bk.yhjc = '省医保住院' then dt.jshid when bk.yhjc = '异地门诊' then dt.jshid when bk.yhjc = '异地住院' then dt.jshid else '' end jylsh, --交易流水号(终端) dt.czyxm yhryxm, --操作员姓名 dt.czybh yhrybh, --操作员编号 dt.zflx, --支付类型(0:充值,1:缴费) dt.terminalno jyzdbh, --交易终端编号 dt.merchantno jyshbh, --交易商户编号、 住院流水号(医保) dt.jyqd jykjz, --POS交易卡介质(医保,银联卡) dt.jyfs, --交易方式 case dt.jytj when '2' then 'dwzfbshh' when '5' then 'gwi' else 'Ehis' end sbcsbm, --设备厂商编码 dt.jytj jyylx, --交易途径 dt.zjlx tcje, --统筹金额 dt.zjhm gzje --个账金额 from ipay.order_detl dt, ipay.bank_info bk, ipay.order_genl gn where dt.tradeno=gn.tradeno and dt.yhid=bk.yhid and dt.paystate in ('paid','repaid','refailed','failed','closed') ; select jyfs from ipay.order_detl a where a.tradeno = '' where a.tradeno select * from ipay.v_trade_cashpay_info -- 现金支付视图 create or replace view ipay.v_trade_cashpay_info as select * from ipay.order_detl dt where yhid = 'XJZF' and dt.paystate in ('paid','repaid') -- 邓伟浩增加字段 alter table ipay.order_detl add czlx varchar2(10); comment on column ipay.order_detl.czlx is '充值类型(1:门诊,2:住院)'; alter table ipay.SDSZ_TRADE_INFO add czlx varchar2(10); comment on column ipay.SDSZ_TRADE_INFO.czlx is '充值类型(1:门诊,2:住院)'; select a.tradeno, a.intradeno, a.fqjysj, a.jysj, a.jyje, a.type, a.brxm , a.brsfzhm , a.brynid, a.cardno, a.brlxfs , a.paystate, a.type handle, a.ynkcode, a.ip, a.czybh, a.czyxm, a.appid, a.terminalno,a.zflx, a.hisno, b.yhid, b.yhmc, c.orgno from ipay.order_detl a, ipay.bank_info b, ipay.order_genl c where a.yhid = b.yhid and a.tradeno = c.tradeno and a.fqjysj >= '20200819000000' and a.fqjysj <= '20200819235959' order by a.fqjysj desc -- 超期退费查询渠道 select * from ipay.overtime_refund; select * from ipay.refund_detl; select a.* from ipay.order_detl a where a.jysj like '20200821%' select distinct a.jyfs from ipay.order_detl a left join ipay.order_genl b on b.tradeno = a.tradeno where a.jysj like '20200821%' ; select * from ipay.bank_info -- for update; <file_sep>/dareway/hop.sql -- lujingting select * from hop.PATIENTS_INFO select yybh,yymc,nvl(s1.c1,0) lx1,nvl(s2.c2,0) lx2,nvl(s3.c3,0) lx3 from (select count(distinct hpi.hzid) c1,hpi.yybh,hhi.yymc from hop.PATIENTS_INFO hpi left join hop.HOSPITAL_INFO hhi on hpi.yybh= hhi.yybh where hpi.hzlx='1' group by hpi.yybh,hhi.yymc order by hpi.yybh)s1 left join (select count(distinct hpi2.hzid) c2,hpi2.yybh yybh2 from hop.PATIENTS_INFO hpi2 left join hop.HOSPITAL_INFO hhi2 on hpi2.yybh= hhi2.yybh where hpi2.hzlx='2' group by hpi2.yybh)s2 on s1.yybh=s2.yybh2 left join (select count(distinct hpi3.hzid) c3,hpi3.yybh yybh3 from hop.PATIENTS_INFO hpi3 left join hop.HOSPITAL_INFO hhi3 on hpi3.yybh= hhi3.yybh where hpi3.hzlx='3' group by hpi3.yybh)s3 on s1.yybh=s3.yybh3 order by yybh select a.yybh,b.yymc,a.c1,a.c2,a.c3 from ( SELECT hpi.yybh, SUM(CASE WHEN hpi.hzlx = 1 THEN 1 ELSE 0 END) c1, SUM(CASE WHEN hpi.hzlx = 2 THEN 1 ELSE 0 END) c2, SUM(CASE WHEN hpi.hzlx = 3 THEN 1 ELSE 0 END) c3 FROM hop.PATIENTS_INFO HPI GROUP BY hpi.yybh ) a left join hop.HOSPITAL_INFO b on a.yybh = b.yybh select count(distinct hpi3.hzid) c3,hpi3.yybh yybh3 from hop.PATIENTS_INFO hpi3 --left join hop.HOSPITAL_INFO hhi3 on hpi3.yybh= hhi3.yybh where hpi3.hzlx='3' group by hpi3.yybh <file_sep>/dareway/重要sql/生殖医院-查询个帐中的pos金额-从总医保里面剔除.sql select sum(case when dtl.paystate = 'repaid' then -1 * dtl.jyje else dtl.jyje end) jyje from ipay.order_detl dtl where 1 = 1 and dtl.paystate in ('paid', 'repaid') and dtl.yhid like '%POS%' and dtl.jshid in (select a.jshid from urp.medicare_transflow a where 1 = 1 and a.grzhzfje != 0 and to_char(a.dzrq, 'yyyy-mm-dd') = '2021-05-29' and a.sfsc = '0') <file_sep>/dareway/生殖医院对账测试.sql -- 查询对账明细表的已经对账的记录数量 select count(*) total from URP.E_RECONRESULT_DETAIL rd where 1=1 and not exists ( select 1 from ( SELECT rd1.yndzjgmxid FROM URP.e_reconresult_detail rd1 where 1=1 and rd1.sbid = 'b8036942f41e44349142d1c06493ed01' and to_char(rd1.dzrq,'yyyy-MM-dd') = '2020-08-21' and rd1.sfsc = '0' and ( rd1.ynhislsid is not null or rd1.ynsblsid is not null) ) --T where rd.yndzjgmxid = T.yndzjgmxid ) and to_char(rd.dzrq,'yyyy-MM-dd') = '2020-08-21' --and rd.sfsc = '0' -- 修正sql select count(*) from ( SELECT rd1.yndzjgmxid FROM URP.e_reconresult_detail rd1 where 1=1 and rd1.sbid = 'b8036942f41e44349142d1c06493ed01' and to_char(rd1.dzrq,'yyyy-MM-dd') = '2020-08-21' and rd1.sfsc = '0' and ( rd1.ynhislsid is not null or rd1.ynsblsid is not null) ) --select t.* from( --select 1 from URP.e_reconresult_detail --) t where t.sbid = '1' -- 更新对账明细表的数据 update URP.E_RECONRESULT_DETAIL rd set rd.sfsc = :newsfsc where 1=1 and rd.sbcsid = :sbcsid and rd.sbid = :sbid and to_char(rd.dzrq,'yyyy-MM-dd') = :dzrq and rd.sfsc = :oldsfsc select sbdzjgid,sbcsid,sbid,dzbs,dzjg,dzjgms,ycjyzbs,sbjyzbs,sbjyzje,sbycjyzbs,sbycjyzje,hisjyzje,hisjyzbs, hisycjyzje,hisycjyzbs,jyhztj,dzrq,jlcjsj,dzfs,dzfqr,sfsc,bz,bly1,bly2,bly3 from URP.E_EQUIPMENT_RECONRESULT where 1=1 and sbid = 'b8036942f41e44349142d1c06493ed01' and to_char(dzrq,'yyyy-MM-dd') = '2020-08-21' and sfsc = '0' -- 设备统计数据 select cr.sbid, ci.sbbm, ci.sbmc, cr.sbdzjgid,case when ydzcl.yclbs is null then 0 else ydzcl.yclbs end yclbs, cr.dzrq , cr.jlcjsj, ron.csmc dzbsms, rr.csmc dzjgms, rt.csmc dzfsms, cr.dzbs, cr.dzjg, cr.dzfs, cr.sbjyzbs,cr.bz,cr.ycjyzbs, cr.sbjyzje, cr.sbycjyzje,cr.hisjyzje,cr.hisjyzbs,cr.hisycjyzje,cr.sbycjyzbs,cr.hisycjyzbs from URP.E_EQUIPMENT_RECONRESULT cr left join URP.e_equipment_info ci on(ci.sbid = cr.sbid and ci.sbzt = '1' and ci.jgbm = 'sdfsszyy' ) left join URP.param_dict ron on (ron.cslx = 'ReconFlag' and ron.csz = cr.dzbs and ron.jgbm = ci.jgbm ) left join URP.param_dict rr on (rr.cslx = 'ReconResult' and rr.csz = cr.dzjg and rr.jgbm = ci.jgbm ) left join URP.param_dict rt on (rt.cslx = 'ReconType' and rt.csz = cr.dzfs and rt.jgbm = ci.jgbm ) left join ( select sbid, count(ycclbs) yclbs from URP.e_reconresult_detail where to_char(dzrq,'yyyy-MM-dd') = '2020-08-21' and sfsc = '0' and ycclbs = '1' group by sbid ) ydzcl on (cr.sbid = ydzcl.sbid) where 1 = 1 and cr.sfsc = '0' and to_char(cr.dzrq,'yyyy-MM-dd') = '2020-08-21' and ci.sbcsid = '4fcc70d4706b4120abe0ae308595ae54' select * from URP.e_reconresult_detail where to_char(dzrq,'yyyy-MM-dd') = '2020-08-21' and sfsc = '0' and ycclbs = '1'--group by sbid -- 查询渠道对账信息 select cnt.jylsh qdjylsh,cnt.jysj jysj,cnt.zdbh zdbh,cnt.jyje jyje,cnt.bly2 qsje,cnt.bly1 sxf,cnt.bly3 jylx,cnt.dzbh From URP.UNIONPAY_TRANSFLOW cnt where to_char(cnt.dzrq,'yyyy-MM-dd') = '2020-08-22' select * from ipay.order_detl a where a.intradeno = '20200826P00002135DAREWAY'; select * from urp.alipay_transflow a; select sum(a.jyje) from his_transflow a where to_char(a.dzrq, 'yyyyMMdd') = '20200827' and a.sfsc = '0' select rd.yndzjgmxid, his.ynhislsid,cnt.ynsblsid, his.ddbh hddbh,his.ddbh,his.jysj hsj,his.jyje hje, his.yhrybh,mzpd.csmc mzzybsmc, cnt.jylsh,cnt.jyshbh,cnt.jysj csj,cnt.ddbh eddbh, cnt.jyzdbh zdbh,cnt.ywlx cyw,cnt.jyje cje,cnt.zdbh zdhm,cnt.jyzt czt, his.jyje,rd.dzjg, rd.dzjgms,rd.yclx,his.brxm,his.blh,his.brjzkh, rd.ycclbs,rd.ycclfjmc,rd.ycclfjlj,rd.ycclms,ei.sbmc,ei.sbbm,his.ywlx hyw,his.jyzdbh, his.jyzt hzt,hpd.csmc hztmc,cpd.csmc cztmc,to_char(rd.dzrq,'yyyy-MM-dd') dzrq, ef.sbcsbm,ef.sbcsmc,case when ci.qdmc is null then ci2.qdmc else ci.qdmc end from URP.E_RECONRESULT_DETAIL rd left join URP.e_his_transflow his on his.ynhislsid = rd.ynhislsid left join URP.E_EQUIPMENT_TRANSFLOW cnt on ( cnt.ynsblsid = rd.ynsblsid) left join URP.CHANNEL_INFO ci on cnt.jyqdbs = ci.qdbm left join URP.CHANNEL_INFO ci2 on his.jyqdbs = ci2.qdbm left join URP.E_EQUIPMENT_INFO ei on ei.sbid = rd.sbid left join URP.E_EQUIPMENT_FACTORY ef on ef.sbcsid = rd.sbcsid left join URP.param_dict hpd on his.jyzt = hpd.csz and hpd.cslx='TransStatus' and hpd.jgbm = his.jgbm left join URP.param_dict cpd on cnt.jyzt = cpd.csz and cpd.cslx='TransStatus' and cpd.jgbm = cnt.jgbm left join URP.param_dict mzpd on his.mzzybs = mzpd.csz and mzpd.cslx='mzzybs' and mzpd.jgbm = his.jgbm where 1 = 1 and rd.sbid = 'b8036942f41e44349142d1c06493ed01' and to_char(rd.dzrq,'yyyy-MM-dd') = '2020-08-21' and rd.sfsc = '0' and ei.jgbm = 'sdfsszyy' order by rd.yclx,his.jyckh -- 实时报警 select * from E_REALTIME_MONITOR select rm.ssjkid,pd1.csmc ycdl ,pd2.csmc ycxl,to_char(rm.jlcjsj,'yyyy-MM-dd HH24:mm:ss') cjsj, rm.ycnr,rm.bz,et.ddbh eddbh,et.yhrybh eyhrybh,nvl(et.brjzkh,ht.brjzkh) brjzkh, ht.ddbh hddbh,ht.yhrybh hyhrybh,ht.brjzkh hbrjzkh,rm.ycclbs,rm.cljg, et.jyje ejyje,et.jysj ejysj,et.jysbbs ejysbbs,et.jyckh ejyckh,et.jyshbh ejyshbh, ht.jyje hjyje,ht.jysj hjysj,ht.jysbbs hjysbbs,ht.jyckh hjyckh,ht.jyshbh hjyshbh, rm.ycclfjmc,rm.ycclfjlj,rm.ycclms,ef.sbcsbm,ef.sbcsmc,nvl(et.brxm,ht.brxm) brxm from URP.E_REALTIME_MONITOR rm left join URP.M_EQUIPMENT_TRANSFLOW et on et.ynjksblsid = rm.ynjksblsid left join URP.M_HIS_TRANSFLOW ht on ht.ynjkhislsid = rm.ynjkhislsid left join URP.E_EQUIPMENT_FACTORY ef on et.sbcsid = ef.sbcsid left join URP.param_dict pd1 on pd1.cslx = 'AbnormalMain' and pd1.csz = rm.ycdl and pd1.jgbm = rm.jgbm left join URP.param_dict pd2 on pd2.cslx = 'AbnormalSub' and pd2.csz = rm.ycxl and pd2.jgbm = rm.jgbm where rm.ssjkid=:ssjkid E_EQUIPMENT_FACTORY select distinct * from URP.CHANNEL_INFO,URP.E_EQUIPMENT_FACTORY select * from HIS_TRANSFLOW t where t.bly2 = 'mzsyb' for update; select * from RECONRESULT_DETAIL t where t.qdid = '71cde7b3a82243f0bfa7871f6478bb91' for update; -- 医保报表中 his和支付平台的统计数据汇总(单天统计) select me.jyrq,sum(me.dsyb) dsyb,sum(me.zysyb) zysyb,sum(me.mzsyb) mzsyb, sum(me.mzydyb) mzydyb, sum(me.zyydyb) zyydyb, sum(me.mzsybpos) mzsybpos,sum(me.zysybpos) zysybpos,sum(me.mzydybpos) mzydybpos,sum(me.zyydybpos) zyydybpos from ( select to_char(to_date(his.jysj,'yyyy-mm-dd hh24:mi:ss'),'yyyy-mm-dd') jyrq,sum(his.jyje) jyje, case when his.bly2 = 'dsyb' then sum(his.jyje) else 0 end dsyb, case when his.bly2 = 'zysyb' then sum(his.jyje) else 0 end zysyb, case when his.bly2 = 'mzsyb' then sum(his.jyje) else 0 end mzsyb, case when his.bly2 = 'mzydyb' then sum(his.jyje) else 0 end mzydyb, case when his.bly2 = 'zyydyb' then sum(his.jyje) else 0 end zyydyb, case when his.bly2 = 'mzsybpos' then sum(his.jyje) else 0 end mzsybpos, case when his.bly2 = 'zysybpos' then sum(his.jyje) else 0 end zysybpos, case when his.bly2 = 'mzydybpos' then sum(his.jyje) else 0 end mzydybpos, case when his.bly2 = 'zyydybpos' then sum(his.jyje) else 0 end zyydybpos from URP.RECONRESULT_DETAIL rd left join URP.HIS_TRANSFLOW his on rd.hisid = his.hislsid where 1=1 and rd.dzjg = '1' and rd.sfsc = '0' and his.jyqdbs = 'Medicare' and to_char(rd.dzrq,'yyyy-mm') = '2020-08' group by his.bly2,to_char(to_date(his.jysj,'yyyy-mm-dd hh24:mi:ss'),'yyyy-mm-dd') order by to_char(to_date(his.jysj,'yyyy-mm-dd hh24:mi:ss'),'yyyy-mm-dd') ) me group by me.jyrq order by me.jyrq -- 医保报表中 his和支付平台的统计数据汇总(单月统计) select sum(his.jyje) jyje from URP.RECONRESULT_DETAIL rd left join URP.HIS_TRANSFLOW his on rd.hisid = his.hislsid where 1 = 1 and rd.dzjg = '1' and rd.sfsc = '0' and his.jgbm = 'sdfsszyy' and his.jyqdbs = 'Medicare' and to_char(rd.dzrq, 'yyyy-mm') = '2020-08' --order by to_char(to_date(his.jysj,'yyyy-mm-dd hh24:mi:ss'),'yyyy-mm-dd') -- 汇总单日报表 select ci.qdid, ci.qdbm, ci.qdmc, cr.qddzjgid, to_char(cr.dzrq,'yyyy-MM-dd') dzrq, cr.jlcjsj, ron.csmc dzbsms, rr.csmc dzjgms, rt.csmc dzfsms, cr.dzbs, cr.dzjg, cr.dzfs, nvl(cr.qdjyzje, 0.00) qdjyzje, nvl(cr.qdjyzbs, 0) qdjyzbs, nvl(cr.hisjyzje, 0.00) hisjyzje, nvl(cr.hisjyzbs, 0) hisjyzbs, ci.jgbm, nvl(cr.qdycjyzje, 0.00) qdycjyzje, nvl(cr.qdycjyzbs, 0) qdycjyzbs, nvl(cr.hisycjyzje, 0.00) hisycjyzje, nvl(cr.hisycjyzbs, 0) hisycjyzbs from URP.channel_reconresult cr left join URP.channel_info ci on(ci.qdid = cr.qdid and ci.qdzt = '1' ) left join URP.param_dict ron on (ron.cslx = 'ReconFlag' and ron.csz = cr.dzbs and ron.jgbm = ci.jgbm ) left join URP.param_dict rr on (rr.cslx = 'ReconResult' and rr.csz = cr.dzjg and rr.jgbm = ci.jgbm ) left join URP.param_dict rt on (rt.cslx = 'ReconType' and rt.csz = cr.dzfs and rt.jgbm = ci.jgbm ) where 1 = 1 and to_char(cr.dzrq,'yyyy-MM-dd') = '2020-09-02' and cr.sfsc = '0' and cr.dzbs = '1' and ci.jgbm = 'sdfsszyy' update URP.MONITOR_CONFIG set dxbm = :dxbm ,jgbm = :jgbm , jyzhhqsj = :jyzhhqsj , sfsc = :sfsc , cjsj = :cjsj , zhxgsj = :zhxgsj where 1=1 and jyjkpzid = :jyjkpzid select rm.ssbjid,pd1.csmc ycdl ,pd2.csmc ycxl,to_char(rm.clwcsj,'yyyy-MM-dd HH24:mm:ss') clwcsj, rm.ycnr,rm.bz,ci.qdmc,rm.ycclbs from URP.REALTIME_ALARM rm left join URP.channel_info ci on ci.qdbm = rm.jyqdbs and ci.jgbm = rm.jgbm left join URP.param_dict pd1 on pd1.cslx = 'AbnormalMain' and pd1.csz = rm.ycdl and pd1.jgbm = rm.jgbm left join URP.param_dict pd2 on pd2.cslx = 'AbnormalSub' and pd2.csz = rm.ycxl and pd2.jgbm = rm.jgbm where 1=1 and rm.jgbm = 'sdfsszyy' and ci.qdbm in ('UnionPay','UnionPayCF','Alipay','WeChat','Medicare','ScanCode','UnionPayOmni','His','ccbUnionPay','Icashier','ABCPay','EhcPay','CgbSmartPay','CashPay') and rm.sfsc = '0' order by rm.clwcsj desc,rm.jlcjsj desc --delete from URP.E_EQUIPMENT_TRANSFLOW where 1=1 and to_char(dzrq,'yyyy-MM-dd') = '2020-09-14' select * from URP.e_reconresult_detail where 1=1 and to_char(dzrq,'yyyy-MM-dd') = '2020-09-14' and yclx = '0'--and dzbh = '20200914P00002365DAREWAY' select * from URP.e_His_Transflow where 1=1 and sfsc='0' and to_char(dzrq,'yyyy-MM-dd') = '2020-09-14' --and dzbh = '20200914P00002365DAREWAY' and jyqdbs = 'UnionPay' select * from URP.E_EQUIPMENT_TRANSFLOW where 1=1 and sfsc='0' and to_char(dzrq,'yyyy-MM-dd') = '2020-09-14' -- and dzbh = '20200914P00002365DAREWAY' and jyqdbs = 'UnionPay' --- 查询三方对账的正常交易集合 select his.jylsh hisjylsh,his.jyje hisjyje,his.bcjywybs,his.jysj hisjysj,his.dzbh hisdzbh,his.brjzkh kh, eq.ddbh zzls,eq.jysj zzjysj,eq.zdbh zdbh,eq.jyje zzjyje, cn.qdmc zzjylx,eq.dzbh eqdzbh from URP.e_reconresult_detail eqrs inner join URP.E_EQUIPMENT_TRANSFLOW eq on eq.ynsblsid = eqrs.ynsblsid inner join URP.e_His_Transflow his on his.dzbh = eq.dzbh inner join URP.Channel_Info cn on cn.qdbm = eq.jyqdbs --or cn.qdbm = his.jyqdbs where 1=1 and to_char(eqrs.dzrq,'yyyy-MM-dd') = '2020-09-14' and eqrs.yclx = '0' and cn.qdbm = 'UnionPay' --and eq.sbcsid = '4fcc70d4706b4120abe0ae308595ae54' and eqrs.sfsc = '0'; --- 查询三方对账的异常交易集合 select his.jylsh hisjylsh,his.jyje hisjyje,his.bcjywybs,his.jysj hisjysj,his.dzbh hisdzbh,his.brjzkh kh, eq.ddbh zzls,eq.jysj zzjysj,eq.zdbh zdbh,eq.jyje zzjyje, cn.qdmc zzjylx,eq.dzbh eqdzbh from URP.e_reconresult_detail eqrs left join URP.E_EQUIPMENT_TRANSFLOW eq on eq.ynsblsid = eqrs.ynsblsid left join URP.e_His_Transflow his on his.ynhislsid = eqrs.ynhislsid left join URP.Channel_Info cn on cn.qdbm = eq.jyqdbs or cn.qdbm = his.jyqdbs where 1=1 and to_char(eqrs.dzrq,'yyyy-MM-dd') = '2020-09-14' and eqrs.yclx != '0' and cn.qdbm = 'UnionPay' --and eq.sbcsid = '4fcc70d4706b4120abe0ae308595ae54' and eqrs.sfsc = '0'; select * from URP.ALIPAY_TRANSFLOW where dzbh = '20200915P00005400DAREWAY' select case when a.bly3 is null then '11' end jylsh from URP.ALIPAY_TRANSFLOW a where dzbh = '20200915P00005400DAREWAY' --根据对账日期查询对账结果表的数据(包含渠道编码) select cn.qdbm,rs.dzbs,rs.dzjg,rs.dzjgms,rs.qdjyzje,rs.qdjyzbs,rs.qdycjyzje,rs.ycjyzbs,rs.qdjyzb,rs.qdjylszb,rs. qdjyhbzb,rs.dzrq,rs.jlcjsj,rs.dzfs,rs.dzfqr,rs.sfsc,rs.bz,rs.bly1,rs.bly2,rs.bly3,rs.hisjyzje,rs.hisjyzbs,rs.hisycjyzje,rs. qdycjyzbs,rs.hisycjyzbs from URP.CHANNEL_RECONRESULT rs left join URP.CHANNEL_INFO cn on cn.qdid = rs.QDID where 1=1 and to_char(dzrq,'yyyy-MM-dd') = '2020-09-15' and rs.sfsc = '0' -- 统计his的退款笔数 select count(1) tkzbs from HIS_TRANSFLOW his where 1=1 and to_char(his.dzrq,'yyyy-MM-dd') = '2020-09-15' and his.sfsc = '0' and his.ywlx = '退款' -- 统计 手续费 select sum(sxf) sxf from (select sum(qd1.sxf) sxf from URP.Unionpay_Transflow qd1 where 1 = 1 and to_char(qd1.dzrq,'yyyy-MM-dd') = '2020-09-15' and qd1.sfsc = '0' union select sum(qd2.sxf) sxf from URP.CGBSMARTPAY_TRANSFLOW qd2 where 1 = 1 and to_char(qd2.dzrq,'yyyy-MM-dd') = '2020-09-15' and qd2.sfsc = '0' union select sum(qd3.sxf) sxf from URP.ALIPAY_TRANSFLOW qd3 where 1 = 1 and to_char(qd3.dzrq,'yyyy-MM-dd') = '2020-09-15' and qd3.sfsc = '0' union select sum(qd4.sxf) sxf from URP.Medicare_Transflow qd4 where 1 = 1 and to_char(qd4.dzrq,'yyyy-MM-dd') = '2020-09-15' and qd4.sfsc = '0' union select sum(qd5.sxf) sxf from URP.Wechat_transflow qd5 where 1 = 1 and to_char(qd5.dzrq,'yyyy-MM-dd') = '2020-09-15' and qd5.sfsc = '0') -- E-his超期总金额,总比数(交易当天的流水) select sum(his.jyje) jyje,count(1) total from URP.E_HIS_TRANSFLOW his where 1=1 and to_char(his.dzrq,'yyyy-MM-dd') = '2020-09-14' and his.sfsc = '0' and his.jyqdbs = 'Transfer' -- ipay 查询超期总金额,总比数(交易当天的流水) select sum(flow.jyje) jyje, count(1) total from URP.E_EQUIPMENT_TRANSFLOW flow inner join URP.E_EQUIPMENT_FACTORY eq on flow.sbcsid = eq.sbcsid and eq.sbcsbm = 'ipay' where 1 = 1 and to_char(flow.dzrq, 'yyyy-MM-dd') = '2020-09-14' and flow.sfsc = '0' and flow.jyqdbs = 'Transfer' -- 根据对账结果明细id 查询银联的交易(437b28dc39884612903436d3b3854b00) select cnt.jyckh,cnt.jylsh,cnt.jysj,cnt.jyje from URP.UNIONPAY_TRANSFLOW cnt where 1 = 1 and cnt.lsid = (select re.qdlsid from URP.RECONRESULT_DETAIL re where 1 = 1 and re.dzjgmxid = '12c363ffd078479bad48dff3c4bf165d' and re.sfsc = '0') -- 查询ipay detl select distinct d.paystate from ipay.order_detl d; select * from ipay.order_detl d where d.paystate = 'repaying'and yhid = 'UNIONCARD'; select * from ipay.order_detl where yhid = 'UNIONCARD' intradeno = '20200924P00002671DAREWAY' --for update select * from ipay.order_detl dl where 1 = 1 and dl.yhid = 'UNIONCARD' and dl.cardno = '260264' and dl.jyje = '0.01' and dl.fqjysj like '20200925%'; -- 院内卡充值情况记录表 select * from ipay.sdsz_trade_info where jyddh = '20200925P00002719DAREWAY'; select case when dl.paystate = 'paid' then '已支付' when dl.paystate = 'repaid' then '已退款' when dl.paystate = 'failed' then '支付失败' when dl.paystate = 'paying' then '正在支付' when dl.paystate = 'repaying' then '正在退款' when dl.paystate = 'refailed' then '退款失败' when dl.paystate = 'closed' then '订单关闭' when dl.paystate = 'na' then '未知' when dl.paystate = 'nopay' then '未支付' else '未知' end paystate, TO_DATE(dl.jysj, 'yyyy-mm-dd hh24:mi:ss') jysj, dl.jyje, dl.terminalno, dl.brxm, dl.brsfzhm, dl.czyhmc, dl.czyxm from ipay.order_detl dl where 1 = 1 and dl.yhid = 'UNIONCARD' and dl.cardno = '260264' and dl.jyje = '0.01' and dl.fqjysj like '20200925%' <file_sep>/dareway/2021-4/收费员报表-4-9-完善了现金和两种微信的问题.sql select * from (select nvl(czy.czybh, '') czybh, msg.czyxm, msg.qdmc, msg.zfje, msg.zfbs, msg.tkje, msg.tkbs, msg.zje from (select nvl(dtl1.czybh, dtl3.czybh) czybh, case when nvl(dtl1.czyxm, dtl3.czyxm) is null then nvl(dtl1.czybh, dtl3.czybh) else nvl(dtl1.czyxm, dtl3.czyxm) end czyxm, nvl(dtl1.bz, dtl3.bz) qdmc, nvl(dtl1.jyje, 0) zfje, nvl(dtl1.jybs, 0) zfbs, nvl(dtl3.jyje, 0) tkje, nvl(dtl3.jybs, 0) tkbs, (nvl(dtl1.jyje, 0) - nvl(dtl3.jyje, 0)) as zje from (select dtl4.czybh, dtl4.czyxm, bank2.bz, sum(case when instr(bank2.bz, '统筹') > 0 then to_number(dtl4.zjlx) else dtl4.jyje end) jyje, count(dtl4.intradeno) jybs from ipay.order_detl dtl4 left join ipay.bank_info bank2 on bank2.yhid = dtl4.yhid where dtl4.paystate = 'paid' and dtl4.yhid != 'SPCLQY' and (dtl4.cqtfbs != '1' or dtl4.cqtfbs is null) and dtl4.czybh = '493' and dtl4.jysj >= '20210406000000' and dtl4.jysj <= '20210406235017' group by dtl4.czybh, dtl4.czyxm, bank2.bz order by dtl4.czybh, dtl4.czyxm, bank2.bz) dtl1 full join (select refd.czybh, refd.czyxm, refd.bz, sum(refd.jyje) jyje, sum(refd.jybs) jybs from (select dtlrf.czybh, dtlrf.czyxm, bank3.bz, sum(case when instr(bank3.bz, '统筹') > 0 then to_number(dtlrf.zjlx) else dtlrf.jyje end) jyje, count(1) jybs from ipay.order_detl dtlrf left join ipay.bank_info bank3 on bank3.yhid = dtlrf.yhid where 1 = 1 and dtlrf.paystate = 'repaid' and (dtlrf.cqtfbs not in ('1', '2') or dtlrf.cqtfbs is null) and dtlrf.czybh = '493' and dtlrf.fqjysj >= '20210406000000' and dtlrf.fqjysj <= '20210406235017' group by dtlrf.czybh, dtlrf.czyxm, bank3.bz union select cash.czybh, cash.czyxm, '现金' bz, sum(cash.jyje) jyje, count(1) jybs from ipay.overtocash_refund cash where 1 = 1 and cash.state = 'repaid' and cash.czybh = '493' and cash.fqjysj >= '20210406000000' and cash.fqjysj <= '20210406235017' group by cash.czybh, cash.czyxm) refd group by refd.czybh, refd.czyxm, refd.bz union select refund.czybh czybh, refund.czyxm czyxm, '超期' bz, sum(dtl5.jyje) jyje, count(1) jybs from ipay.overtime_refund dtl5 left join ipay.refund_detl refund on dtl5.refundno = refund.refundno where dtl5.state in ('repaid', 'refund', 'refunding', 'repaying', 'repayings') and refund.czybh = '493' and dtl5.fqjysj >= '20210406000000' and dtl5.fqjysj <= '20210406235017' group by refund.czybh, refund.czyxm) dtl3 on dtl1.czybh = dtl3.czybh and dtl1.czyxm = dtl3.czyxm and dtl1.bz = dtl3.bz) msg left join (select substr(csmc, instr(csmc, '|', 1) + 1) czybh, csz czyid from URP.PARAM_DICT where 1 = 1 and cslx = 'skyVSdlyh' and zt = '0') czy on czy.czyid = msg.czybh) order by czybh, czyxm, qdmc <file_sep>/dareway/重要sql/收款员.sql SELECT dt.yhid, dt.czybh, dt.czyxm, CASE WHEN dt.paystate = 'paid' THEN count(1) ELSE 0 END zfbs, CASE WHEN dt.paystate = 'paid' THEN sum(dt.jyje) ELSE 0.00 END zfje, CASE WHEN dt.paystate = 'repaid' THEN count(1) ELSE 0 END tkbs, CASE WHEN dt.paystate = 'repaid' THEN sum(dt.jyje) ELSE 0.00 END tkje, count(1) hjbs, sum(dt.jyje) hjje FROM ipay.order_detl dt left join ipay.bank_info bi on dt.yhid = bi.yhid where 1 = 1 and subStr(dt.jysj, 0, 8) = '20201216' and czybh = '4' and dt.paystate in ('paid', 'repaid') group by dt.czybh, dt.czyxm, dt.yhid, dt.paystate order by dt.czybh; select * from ipay.order_detl dt where 1=1 ; SELECT dt.yhid, dt.czybh, dt.czyxm, CASE WHEN dt.paystate = 'paid' THEN count(1) ELSE 0 END zfbs, CASE WHEN dt.paystate = 'paid' THEN sum(dt.jyje) ELSE 0.00 END zfje, CASE WHEN dt.paystate = 'repaid' THEN count(1) ELSE 0 END tkbs, CASE WHEN dt.paystate = 'repaid' THEN sum(dt.jyje) ELSE 0.00 END tkje, count(1) hjbs, sum(dt.jyje) hjje FROM ( ) dt left join ipay.bank_info bi on dt.yhid = bi.yhid where 1 = 1 and subStr(dt.jysj, 0, 8) = '20201216' and czybh = '4' and dt.paystate in ('paid', 'repaid') group by dt.yhid ,dt.czybh, dt.czyxm,dt.paystate order by dt.czybh; select dtl1.jysj,dtl1.jyje,dtl1.czybh,dtl1.paystate,dtl1.czyxm,dtl1.yhid,row_number() over (partition by yhid order by dtl1.czybh desc) column_num from ipay.order_detl dtl1; select dtl1.czybh, dtl1.yhid, sum(dtl1.jyje) zfje, count(dtl1.intradeno) zfbs, dtl3.jyje tkje, dtl3.jybs tkbs from ipay.order_detl dtl1 left join (select dtl2.czybh, dtl2.yhid, sum(dtl2.jyje) jyje, count(1) jybs from ipay.order_detl dtl2 where dtl2.paystate = 'repaid' group by dtl2.yhid, dtl2.czybh) dtl3 on dtl1.czybh = dtl3.czybh and dtl1.yhid = dtl3.yhid where dtl1.paystate = 'paid' group by dtl1.yhid, dtl1.czybh order by dtl1.czybh; ---2 ·Ö¿ªºóÁ´½Ó select case when dtl1.czybh is not null then dtl1.czybh else dtl3.czybh end czybh, case when dtl1.bz is not null then dtl1.bz else dtl3.bz end qdmc, case when dtl1.czyxm is not null then dtl1.czyxm else dtl3.czyxm end czyxm, nvl(dtl1.jyje,0) zfje, nvl(dtl1.jybs,0) zfbs, nvl(dtl3.jyje,0) tkje, nvl(dtl3.jybs,0) tkbs, (nvl(dtl1.jyje,0) - nvl( dtl3.jyje,0)) as zje from (select dtl4.czybh,dtl4.czyxm, bank2.bz, sum(dtl4.jyje) jyje, count(dtl4.intradeno) jybs from ipay.order_detl dtl4 left join ipay.bank_info bank2 on bank2.yhid = dtl4.yhid where dtl4.paystate = 'paid' and dtl4.cqtfbs != '1' or dtl4.cqtfbs is null and dtl4.czybh = '001' and dtl4.jysj > '20201216000000' and dtl4.jysj < '20201217000000' group by bank2.bz,dtl4.czybh,dtl4.czyxm order by dtl4.czybh) dtl1 full join (select dtl2.czybh, dtl2.czyxm, bank1.bz, sum(dtl2.jyje) jyje, count(1) jybs from ipay.order_detl dtl2 left join ipay.bank_info bank1 on bank1.yhid = dtl2.yhid where dtl2.paystate = 'repaid' and dtl2.cqtfbs != '1' or dtl2.cqtfbs is null and dtl2.czybh = '001' and dtl2.jysj > '20201216' and dtl2.jysj < '20201217' group by bank1.bz, dtl2.czybh,dtl2.czyxm) dtl3 on dtl1.czybh = dtl3.czybh and dtl1.bz = dtl3.bz order by dtl1.czybh; select count(czybh),czybh from ipay.order_detl where and jysj > '20201216' and jysj < '20201217' group by czybh; select * from ipay.order_detl where jysj > '20201216' and jysj < '20201217' and czybh ='001' ; <file_sep>/dareway/2021-6/排除ipay的三方对账查询.sql select ei.sbbm, ei.sbmc, rd.yndzjgmxid, his.ynhislsid,cnt.ynsblsid,his.brxm hxm,cnt.brxm csxm, his.jyckh hisjyckh, his.jylsh hisjylsh, his.ddbh hisddbh, his.jysj hisjysj, his.sfzhm hzsfzh,his.dzbh hisdzbh, his.jyqdbs hisqdbm, cnt.jyckh csjyckh, cnt.jylsh csjylsh, cnt.ddbh csddbh, cnt.jysj csjysj,cnt.jyje cje, cnt.dzbh sbdzbh, cnt.jyqdbs sbqdbm, his.jyje hje,rd.dzjg, rd.dzjgms, rd.yclx, ci.qdmc, his.jyzdbh, ei.sbid, rd.ycclbs, ef.sbcsbm, ef.sbcsmc , case when his.brjzkh is null then cnt.brjzkh else his.brjzkh end brjzkh from urp.e_reconresult_detail rd left join urp.e_equipment_transflow cnt on rd.ynsblsid = cnt.ynsblsid left join urp.e_his_transflow his on rd.ynhislsid = his.ynhislsid inner join URP.CHANNEL_INFO ci on ci.qdbm = cnt.jyqdbs left join URP.E_EQUIPMENT_FACTORY ef on ef.sbcsid = rd.sbcsid left join URP.E_EQUIPMENT_INFO ei on rd.sbcsid = ei.sbcsid where 1=1 and rd.sbcsid != 'b8036942f41e44349142d1c06493ed01' and rd.dzrq = to_date('2021-06-28','yyyy-MM-dd') and rd.dzjg = '0' and rd.sfsc = '0' --and ci.qdid = '35d05440888c4acd8a7de971b9049484' <file_sep>/dareway/重要sql/统计支付平台医保交易-单个支付或退款.sql select dt3.jyrq, sum(dt3.dsyb) dsyb, sum(dt3.zysyb) zysyb, sum(dt3.mzsyb) mzsyb, sum(dt3.mzydyb) mzydyb, sum(dt3.zyydyb) zyydyb, sum(dt3.mzsybpos) mzsybpos, sum(dt3.zysybpos) zysybpos, sum(dt3.mzydybpos) mzydybpos, sum(dt3.zyydybpos) zyydybpos from ( SELECT dt4.yhid,to_char(to_date(dt4.jysj, 'yyyy-mm-dd hh24:mi:ss'), 'yyyy-mm-dd') jyrq, CASE WHEN dt4.yhid = 'YB' THEN -1 * sum(dt4.jyje) ELSE 0 END dsyb, CASE WHEN dt4.yhid = 'SYBZY' THEN -1 * sum(dt4.jyje) ELSE 0 END zysyb, CASE WHEN dt4.yhid = 'SYBMZ' THEN -1 * sum(dt4.jyje) ELSE 0 END mzsyb, CASE WHEN dt4.yhid = 'YDMZ' THEN -1 * sum(dt4.jyje) ELSE 0 END mzydyb, CASE WHEN dt4.yhid = 'YDZY' THEN -1 * sum(dt4.jyje) ELSE 0 END zyydyb, CASE WHEN dt4.yhid = 'SYBMZPOS' THEN -1 * sum(dt4.jyje) ELSE 0 END mzsybpos, CASE WHEN dt4.yhid = 'SYBZYPOS' THEN -1 * sum(dt4.jyje) ELSE 0 END zysybpos, CASE WHEN dt4.yhid = 'YDMZPOS' THEN -1 * sum(dt4.jyje) ELSE 0 END mzydybpos, CASE WHEN dt4.yhid = 'YDZYPOS' THEN -1 * sum(dt4.jyje) ELSE 0 END zyydybpos FROM ipay.order_detl dt4 where 1 = 1 and dt4.jysj like '202012%' and dt4.paystate = 'paid' and dt4.yhid in ('YB','YDZY','YDMZ','SYBZYPOS','SYBMZPOS','YDMZPOS','YDZYPOS','SYBMZ','SYBZY') group by dt4.yhid,to_char(to_date(dt4.jysj, 'yyyy-mm-dd hh24:mi:ss'), 'yyyy-mm-dd') order by to_char(to_date(dt4.jysj, 'yyyy-mm-dd hh24:mi:ss'), 'yyyy-mm-dd') )dt3 group by dt3.jyrq order by dt3.jyrq
31b7bc9e911fcd85cd9b4da0695322706f2a376b
[ "SQL" ]
36
SQL
wangdefa7/SQL-Note
ef6246a3610cd79592f9cc47d583e18094355d01
f2986e70d02a266f4f51efe627a4bfdbc35d10e9
refs/heads/master
<repo_name>azamikram919/laravel-task<file_sep>/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Product; use App\Models\Cart; use App\Models\Order; use App\Models\User; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { return View('admin.dashboard') ->with('total_products', Product::all()->count()) ->with('total_users', User::all()->count()); } public function adminAddProduct(Request $request) { if ($request->hasFile('thumbnail') && $request->thumbnail->isValid()) { $extension = $request->thumbnail->extension(); $filename = time() . "." . $extension; $request->thumbnail->move(public_path('images'), $filename); } else { $filename = 'no-image.jpg'; } $created = Post::create([ 'title' => $request->title, 'body' => $request->body, 'thumbnail' => $filename, ]); if ($created) { $this->validate($request, [ 'title' => 'required|unique:posts|max:255|min:5', 'body' => 'required', ]); if ($created) { return redirect('posts') ->with('message', 'Post Successfully Created'); } } return view('admin.add_product'); } }
7c28bc39824fcee279ec5289ca82ec45b6590908
[ "PHP" ]
1
PHP
azamikram919/laravel-task
3e51ad09e588ea1cce6ae528fcc9c0167f862a82
9f69b22b070be91eb0bf00ece492bf6c256ffca3
refs/heads/master
<repo_name>low-orbit-flux/boulder-valley<file_sep>/web_gui.py # export FLASK_APP=web_gui.py # flask run --host=0.0.0.0 #navigation buttons #add cols #del cols #edit row data #search #hardcoded host, user, password from flask import Flask from flask import render_template from flask import request import re import my_crud app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route("/database", methods=['POST', 'GET']) def database(): if request.method == 'POST': if 'dbname' in request.form: my_crud.create_db("127.0.0.1", "root", "xxxxxxxx", request.form['dbname']) if 'delete' in request.form: my_crud.drop_db("127.0.0.1", "root", "xxxxxxxx", request.form['delete']) delete_db_form1 = '<form action="/database" method="post" style="display: inline;"><input type="hidden" name="delete" value="' delete_db_form2 = '"><input type="image" src="static/delete.png" alt="Submit"></form>' list_table_form1 = '<form action="/table-list" method="post" style="display: inline;"><input type="hidden" name="dbname" value="' list_table_form2 = '"><input type="image" src="static/menu.png" alt="Submit"></form>' junk2 = my_crud.list_dbs("127.0.0.1", "root", "xxxxxxxx") db_list = "<table>" for i in junk2: db_list = db_list + "<tr><td>" + delete_db_form1 + i[0] + delete_db_form2 + list_table_form1 + i[0] + list_table_form2 + i[0] + "</td></tr>" db_list = db_list + "</table>" return render_template('database.html', db_list=db_list) @app.route("/table-list", methods=['POST', 'GET']) def table_list(): db_name = "" if request.method == 'POST': if 'dbname' in request.form: db_name = request.form['dbname'] else: return "No DB name set" if 'action' in request.form: if 'action' in request.form: if request.form['action'] == 'delete': if 'table-name' in request.form: my_crud.drop_table("127.0.0.1", "root", "xxxxxxxx", db_name, request.form['table-name']) if request.form['action'] == 'create': if 'table-name' in request.form and 'table-fields' in request.form: p1 = re.compile(r',') the_table_fields = p1.split(request.form['table-fields']) my_crud.create_table("127.0.0.1", "root", "xxxxxxxx", request.form['dbname'], request.form['table-name'], the_table_fields) else: return "Can't create table without table name or fields" else: return "Nothing posted...." junk2 = my_crud.list_tables("127.0.0.1", "root", "xxxxxxxx", db_name) html1 = "<table>" for i in junk2: html1 = html1 + "<tr><td>" html1 = html1 + '<form action="/table-list" method="post" style="display: inline;">' html1 = html1 + '<input type="hidden" name="dbname" value="' + db_name + '">' html1 = html1 + '<input type="hidden" name="table-name" value="' + i[0] + '">' html1 = html1 + '<input type="hidden" name="action" value="delete">' html1 = html1 + '<input type="image" src="static/delete.png" alt="Submit"></form>' html1 = html1 + '<form action="/table-row" method="post" style="display: inline;">' html1 = html1 + '<input type="hidden" name="dbname" value="' + db_name + '">' html1 = html1 + '<input type="hidden" name="table-name" value="' + i[0] + '">' html1 = html1 + '<input type="hidden" name="action" value="list">' html1 = html1 + '<input type="image" src="static/menu.png" alt="Submit"></form>' html1 = html1 + i[0] + "</td></tr>" html1 = html1 + "</table>" return render_template('table-list.html', db_name=db_name, table_list=html1) @app.route("/table-row", methods=['POST', 'GET']) def table_row(): db_name = "" if request.method == 'POST': if 'dbname' in request.form and 'table-name' in request.form: db_name = request.form['dbname'] # goes up here because we need the row descriptions for the create from junk3 = my_crud.describe_table("127.0.0.1", "root", "xxxxxxxx", db_name, request.form['table-name']) else: return "No DB name or table name set" if 'action' in request.form: if request.form['action'] == 'create': fields = [] for i in junk3: if i != "ID": fields.append(request.form[i]) my_crud.insert_data("127.0.0.1", "root", "xxxxxxxx", db_name, request.form['table-name'], fields) if request.form['action'] == 'delete': if 'row-id' in request.form: my_crud.delete_data("127.0.0.1", "root", "xxxxxxxx", db_name, request.form['table-name'], request.form['row-id']) else: return "No row-id" else: return "Nothing posted...." # goes down here so we have updated info after inserting new rows junk2 = my_crud.print_all("127.0.0.1", "root", "xxxxxxxx", db_name, request.form['table-name']) form1 = '<form action="/table-row" method="post">' form1 = form1 + '<input type="hidden" name="action" value="create">' form1 = form1 + '<input type="hidden" name="dbname" value="' + db_name + '">' form1 = form1 + '<input type="hidden" name="table-name" value="' + request.form['table-name'] + '">' for i in junk3: if i != "ID": form1 = form1 + i + ': <input type="text" name="' + i + '">' form1 = form1 + '<input type="image" src="static/new.png" alt="Submit"></form>' html1 = "<table>" html1 = html1 + "<tr>" html1 = html1 + "<th></th>" for i in junk3: html1 = html1 + "<th>" + str(i) + "</th>" html1 = html1 + "</tr>" for i in junk2: row_id = i[0] html1 = html1 + "<tr>" html1 = html1 + "<td>" html1 = html1 + '<form action="/table-row" method="post" style="display: inline;">' html1 = html1 + '<input type="hidden" name="dbname" value="' + db_name + '">' html1 = html1 + '<input type="hidden" name="table-name" value="' + request.form['table-name'] + '">' html1 = html1 + '<input type="hidden" name="row-id" value="' + str(row_id) + '">' html1 = html1 + '<input type="hidden" name="action" value="delete">' html1 = html1 + '<input type="image" src="static/delete.png" alt="Submit"></form>' # LAUNCH a New page for editing a row.... #html1 = html1 + '<form action="/table-row" method="post" style="display: inline;">' #html1 = html1 + '<input type="hidden" name="dbname" value="' + db_name + '">' #html1 = html1 + '<input type="hidden" name="table-name" value="' + 'xxxx' + '">' #html1 = html1 + '<input type="hidden" name="action" value="list">' #html1 = html1 + '<input type="image" src="static/menu.png" alt="Submit"></form>' html1 = html1 + "</td>" for x in i: html1 = html1 + "<td>" + str(x) + "</td>" html1 = html1 + "</tr>" html1 = html1 + "</table>" return render_template('table-row.html', db_name=db_name, table_name=request.form['table-name'], row_list=html1, form1=form1) @app.route("/row", methods=['POST', 'GET']) def row(): db_name = "" if request.method == 'POST': if 'dbname' in request.form and 'table-name' in request.form: db_name = request.form['dbname'] else: return "No DB name or table name set" if 'action' in request.form: pass return render_template('row.html', db_name=db_name, table_name=request.form['table-name']) if __name__ == "__main__": app.run() <file_sep>/my_crud.py # x create / delete db # x create / delete table # x add / remove column # x insert data # x remove data # x update data # x search / return data # x list tables # x list databases # PK auto increment is only setup for MySQL # pip install MySQL-python # needs mysql bin in the path and gcc import MySQLdb def create_db(db_host, db_user, db_password, db_name): con = MySQLdb.connect(db_host, db_user, db_password) cur = con.cursor() cur.execute('CREATE DATABASE ' + db_name) con.commit() con.close() def drop_db(db_host, db_user, db_password, db_name): sql_command = 'DROP DATABASE ' + db_name con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) con.commit() con.close() def create_table(db_host, db_user, db_password, db_name, table_name, fields): sql_command = 'CREATE TABLE if not exists ' + table_name + ' ( ID int NOT NULL AUTO_INCREMENT PRIMARY KEY, ' first = True for i in fields: i_type = i[0] i_name = i[1] if first: first = False if i_type == "varchar": sql_command = sql_command + ' ' + i_name + ' varchar(255) ' elif i_type == "int": sql_command = sql_command + ' ' + i_name + ' int ' else: return "Error: need type" else: if i_type == "varchar": sql_command = sql_command + ', ' + i_name + ' varchar(255) ' elif i_type == "int": sql_command = sql_command + ', ' + i_name + ' int ' else: return "Error: need type" sql_command = sql_command + ' )' con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) con.commit() con.close() def drop_table(db_host, db_user, db_password, db_name, table_name): sql_command = 'DROP TABLE ' + table_name con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) con.commit() con.close() def add_col(db_host, db_user, db_password, db_name, table_name, new_col): i_type = new_col[0] i_name = new_col[1] if i_type == "varchar": sql_command = 'ALTER TABLE ' + table_name + ' ADD ' + i_name + ' varchar(255)' elif i_type == "int": sql_command = 'ALTER TABLE ' + table_name + ' ADD ' + i_name + ' int' else: return "Error: need type" con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) con.commit() con.close() def drop_col(db_host, db_user, db_password, db_name, table_name, new_col): sql_command = 'ALTER TABLE ' + table_name + ' DROP COLUMN ' + new_col con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) con.commit() con.close() def insert_data(db_host, db_user, db_password, db_name, table_name, fields): sql_command = 'INSERT INTO ' + table_name + ' VALUES (null, ' first = True for i in fields: i_type = i[0] i_name = i[1] if first: first = False if i_type == "varchar": sql_command = sql_command + ' \'' + i_name + '\'' elif i_type == "int": sql_command = sql_command + ' ' + i_name else: return "Error: need type, got: " + i_type else: if i_type == "varchar": sql_command = sql_command + ', \'' + i_name + '\'' elif i_type == "int": sql_command = sql_command + ', ' + i_name else: return "Error: need type, got: " + i_type sql_command = sql_command + ')' #print "\n\n" + sql_command + "\n\n" con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) con.commit() con.close() def delete_data(db_host, db_user, db_password, db_name, table_name, row_id): sql_command = 'DELETE FROM ' + table_name + ' WHERE ID = ' + row_id con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) con.commit() con.close() def update_data(db_host, db_user, db_password, db_name, table_name, row_id, field_map): sql_command = 'UPDATE ' + table_name + ' SET ' first = True for i in field_map: i_type = field_map[i][0] i_name = field_map[i][1] if first: first = False if i_type == "varchar": sql_command = sql_command + i + '=\'' + i_name + '\'' elif i_type == "int": sql_command = sql_command + i + '=' + i_name else: return "Error: need type" else: if i_type == "varchar": sql_command = sql_command + ', ' + i + '=\'' + i_name + '\'' elif i_type == "int": sql_command = sql_command + ', ' + i + '=' + i_name else: return "Error: need type" sql_command = sql_command + ' WHERE ID = ' + row_id print(sql_command) con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) con.commit() con.close() def print_all(db_host, db_user, db_password, db_name, table_name): sql_command = 'SELECT * FROM ' + table_name con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) rows = cur.fetchall() con.commit() con.close() return rows def search(db_host, db_user, db_password, db_name, table_name, field_map): sql_command = 'SELECT * FROM ' + table_name + ' WHERE ' first = True for i in field_map: i_type = field_map[i][0] i_name = field_map[i][1] if first: first = False if i_type == "varchar": sql_command = sql_command + i + '=\'' + i_name + '\'' elif i_type == "int": sql_command = sql_command + i + '=' + i_name else: return "Error: need type" else: if i_type == "varchar": sql_command = sql_command + ' and ' + i + '=\'' + i_name + '\'' elif i_type == "int": sql_command = sql_command + ' and ' + i + '=' + i_name else: return "Error: need type" con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) rows = cur.fetchall() con.commit() con.close() return rows def list_tables(db_host, db_user, db_password, db_name): sql_command = 'SHOW TABLES' con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) rows = cur.fetchall() con.commit() con.close() return rows def list_dbs(db_host, db_user, db_password): sql_command = 'SHOW DATABASES' con = MySQLdb.connect(db_host, db_user, db_password) cur = con.cursor() cur.execute(sql_command) rows = cur.fetchall() con.commit() con.close() return rows def describe_table(db_host, db_user, db_password, db_name, table_name): sql_command = 'describe ' + table_name con = MySQLdb.connect(db_host, db_user, db_password, db_name) cur = con.cursor() cur.execute(sql_command) rows = cur.fetchall() con.commit() con.close() cols = [] for i in rows: cols.append(i[0]) return cols def run_stuff(): #create_db("127.0.0.1", "root", "xxxxxxxx", "asdf") fields = ['a', 'b', 'c'] data = ["fish", "tree", "house"] data2 = {'a': 'cloud', 'b':'rock', 'c':'river'} data3 = {'b': 'xxxxxx'} data4 = {'a': 'cloud'} #create_table("127.0.0.1", "root", "xxxxxxxx", "asdf", "zoidberg", fields) #add_col("127.0.0.1", "root", "xxxxxxxx", "asdf", "zoidberg", "some_more_junk") #drop_col("127.0.0.1", "root", "xxxxxxxx", "asdf", "zoidberg", "some_more_junk") #drop_table("127.0.0.1", "root", "xxxxxxxx", "asdf", "zoidberg") #drop_db("127.0.0.1", "root", "xxxxxxxx", "asdf") #insert_data("127.0.0.1", "root", "xxxxxxxx", "asdf", "zoidberg", data) #delete_data("127.0.0.1", "root", "xxxxxxxx", "asdf", "frog", "1") #update_data("127.0.0.1", "root", "xxxxxxxx", "asdf", "frog", "5", data2) # update row id 5 with dict data2 #print_all("127.0.0.1", "root", "xxxxxxxx", "asdf", "frog") #junk = search("127.0.0.1", "root", "xxxxxxxx", "asdf", "frog", data4) #print junk #junk2 = list_dbs("127.0.0.1", "root", "xxxxxxxx") #junk3 = list_tables("127.0.0.1", "root", "xxxxxxxx", "asdf") #print "DBs: " + str(junk2) #print "Tables in asdf: " + str(junk3) #junk3 = describe_table("127.0.0.1", "root", "xxxxxxxx", "test", "test1") #print junk3 results = search("127.0.0.1", "root", "xxxxxxxx", "asdf", "zoidberg", data23) print results #search if __name__ == "__main__": pass run_stuff() <file_sep>/web_test.py # export FLASK_APP=web_gui.py # flask run --host=0.0.0.0 from flask import Flask from flask import render_template from flask import request app = Flask(__name__) @app.route("/") def index(): return "The index" @app.route('/hello') @app.route('/blah') def hello(): return 'Hello, World' @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return 'User %s' % username @app.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id, the id is an integer return 'Post %d' % post_id @app.route('/projects/') # without slash will redirect to this def projects(): return 'The project page' @app.route('/about') # with slash will 404 def about(): return 'The about page' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': do_the_login() else: show_the_login_form() @app.route('/test2/') @app.route('/test2/<name>') def test2(name=None): return render_template('test2.html', name=name) @app.route('/login', methods=['POST', 'GET']) def login(): error = None if request.method == 'POST': if valid_login(request.form['username'], request.form['password']): return log_the_user_in(request.form['username']) else: error = 'Invalid username/password' # the code below is executed if the request method # was GET or the credentials were invalid return render_template('login.html', error=error) ## for GET method params ## searchword = request.args.get('key', '') @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/uploaded_file.txt') from flask import request from werkzeug.utils import secure_filename @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['the_file'] f.save('/var/www/uploads/' + secure_filename(f.filename)) if __name__ == "__main__": app.run()
b3cc2b0beed203711936f018246d2f5c98cb9f75
[ "Python" ]
3
Python
low-orbit-flux/boulder-valley
5148d2f6828c1f452e995ac9e7fa41aafee673aa
a271b4f009d8ab0164a8aa53e70febeacbc6932d
refs/heads/master
<repo_name>tengfei527/AutoUpdateProject<file_sep>/.svn/pristine/bb/bb41fd721dab06bfd1465d9884ebd9f2d160d767.svn-base using System; using System.Collections.Generic; using System.Linq; using System.Text; using SuperSocket.SocketBase; using SuperSocket.SocketBase.Config; using SuperSocket.SocketBase.Protocol; namespace AU.Monitor.Server { public class MonitorServer : AppServer<MonitorSession> { public MonitorServer() : base(new SuperSocket.SocketBase.Protocol.CommandLineReceiveFilterFactory(Encoding.UTF8, new BasicRequestInfoParser(":", "&"))) { } protected override bool Setup(IRootConfig rootConfig, IServerConfig config) { return base.Setup(rootConfig, config); } protected override void OnStarted() { base.OnStarted(); } protected override void OnStopped() { base.OnStopped(); } } } <file_sep>/Infrastructure/UnityExtensions/UnityInstanceContextLifetimeManager.cs using System.ServiceModel; namespace Infrastructure.UnityExtensions { /// <summary> /// Unity lifetime manager to support <see cref="System.ServiceModel.InstanceContext"/>. /// </summary> public class UnityInstanceContextLifetimeManager : UnityWcfLifetimeManager<InstanceContext> { /// <summary> /// Initializes a new instance of the <see cref="UnityInstanceContextLifetimeManager"/> class. /// </summary> public UnityInstanceContextLifetimeManager() : base() { } /// <summary> /// Returns the appropriate extension for the current lifetime manager. /// </summary> /// <returns>The registered extension for the current lifetime manager, otherwise, null if the extension is not registered.</returns> protected override UnityWcfExtension<InstanceContext> FindExtension() { return UnityInstanceContextExtension.Current; } } } <file_sep>/.svn/pristine/3b/3b99692c8ed92bd68d15164961534c37640c19fe.svn-base using System; namespace Infrastructure.Transactions { public interface ITransactionCoordinator : IUnitOfWork, IDisposable { } } <file_sep>/.svn/pristine/ed/edc633662fc9cfe3690c27565c7d5bbe3f650124.svn-base using Domain; using Domain.Model; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; namespace Repository.EntityFramework.ModelConfigurations { /// <summary> /// Represents the entity type configuration for the <see cref="Customer"/> entity. /// </summary> public class CommonConfiguration<T> : EntityTypeConfiguration<T> where T : class, IAggregateRoot { #region Ctor /// <summary> /// Initializes a new instance of <c>CustomerTypeConfiguration</c> class. /// </summary> public CommonConfiguration(Action<CommonConfiguration<T>> action) { HasKey(c => c.Id); Property(c => c.Id) .IsRequired() .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(c => c.Rid) .IsRequired(); if (action != null) action(this); //Property(c => c.ProjectNo) // .IsRequired() // .HasMaxLength(36); //Property(c => c.Name) // .IsRequired() // .HasMaxLength(30); var t = this; ToTable(typeof(T).Name); } #endregion } } <file_sep>/AuClient/MainForm.cs using AU.Common; using SuperSocket.SocketBase; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Text; using System.Threading; using System.Windows.Forms; namespace AuClient { public partial class MainForm : Form { /// <summary> /// 更新文件个数 /// </summary> private int AvailableUpdate = -1; /// <summary> /// 更新辅助类 /// </summary> private AppUpdater auUpdater = null; /// <summary> /// 获取更新文件列表 /// </summary> private AuPackage htUpdateFile = null; /// <summary> /// 发布包信息 /// </summary> AuPublishHelp auPublishHelp = null; /// <summary> /// 日志接口 /// </summary> public log4net.ILog log = log4net.LogManager.GetLogger(typeof(MainForm)); /// <summary> /// 主窗体是否显示 /// </summary> public bool IsShow { get { bool show = this.WindowState != FormWindowState.Minimized && this.Visible; return show; } } /// <summary> /// 初始化系统参数 /// </summary> public MainForm() { InitializeComponent(); this.WindowState = FormWindowState.Minimized; linkLabel1.Text = AppConfig.Current.LinkUrl; this.auPublishHelp = new AuPublishHelp(this); } /// <summary> /// 静默更新 /// </summary> /// <param name="path"></param> /// <param name="subsystem"></param> /// <param name="systemPath"></param> /// <returns></returns> private bool DoUpgrade(string path, string subsystem, string systemPath) { try { this.AvailableUpdate = Check(path, subsystem, systemPath); if (AvailableUpdate > 0) { iisOperate(subsystem, false); //升级 this.auUpdater.Upgrade(htUpdateFile); this.MainAppRun(); this.AvailableUpdate = 0; return true; } else { this.MainAppRun(); //删除临时目录 if (string.IsNullOrWhiteSpace(path) && System.IO.Directory.Exists(AppConfig.GetUpdateTempPath(subsystem))) System.IO.Directory.Delete(AppConfig.GetUpdateTempPath(subsystem), true); } } catch (Exception e) { log.Error(string.Format("执行静默升级失败,参数{0},{1},{2}", path, subsystem, systemPath), e); //log MessageBox.Show("升级失败!,详情" + e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { iisOperate(subsystem, true); } return false; } private int Check(string path, string subsystem, string systemPath) { string updateTempPath = AppConfig.GetUpdateTempPath(subsystem); //更新 auUpdater = new AppUpdater(systemPath, updateTempPath, AppConfig.GetAuBackupPath(subsystem), systemPath, subsystem); if (auUpdater.UpdateAuPackage.LocalAuList == null && System.IO.File.Exists(path)) { //解压一个文件 string temp = AU.Common.Utility.ZipUtility.DecompressFile(path, AuPackage.PackageName, System.Text.Encoding.UTF8); AuList a = Newtonsoft.Json.JsonConvert.DeserializeObject<AuList>(temp); auUpdater.UpdateAuPackage.SetPackage(a, subsystem); } auUpdater.Notify += Au_Notify; int up = auUpdater.CheckForUpdate(subsystem, out htUpdateFile); if (up > 0) { //解压临时包 if (!System.IO.Directory.Exists(updateTempPath)) { AU.Common.Utility.ZipUtility.Decompress(path, updateTempPath); } else { //验证是否最新 } } return up; } private void iisOperate(string subsystem, bool start = true) { try { if (subsystem == SystemType.coreserver.ToString() || subsystem == SystemType.managerserver.ToString() || subsystem == SystemType.handsetserver.ToString() || subsystem == SystemType.imageserver.ToString()) { Process p = new Process(); p.StartInfo.FileName = "iisreset";//要执行的程序名称 p.StartInfo.CreateNoWindow = true; //不显示程序窗口 p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; if (start) p.StartInfo.Arguments = "/start"; else p.StartInfo.Arguments = "/stop"; log.InfoFormat("{0} 开始操作[{1} {2}]", subsystem, p.StartInfo.FileName, p.StartInfo.Arguments); p.Start();//启动程序 p.WaitForExit(); log.InfoFormat("{0} 结束操作[{1} {2}]", subsystem, p.StartInfo.FileName, p.StartInfo.Arguments); } } catch (Exception e) { log.Error("操作 iisreset 命令失败", e); //log MessageBox.Show(e.Message); } } /// <summary> /// 显示更新 /// </summary> public bool ShowUpdate(string path, string subsystem, string systemPath) { bool result = false; try { if (this.IsShow) return result; this.InvalidateControl(false); AvailableUpdate = Check(path, subsystem, systemPath); if (AvailableUpdate > 0) { btnNext.Tag = subsystem; tbUpdateMsg.Text = htUpdateFile.LocalAuList.Description; lvUpdateList.Items.Clear(); htUpdateFile.LocalAuList.Files.ForEach(d => lvUpdateList.Items.Add(new ListViewItem( new string[] { d.No,d.Version,"",d.WritePath,d.SHA256 }))); //有更新 this.Text = "【" + SubSystem.Dic[subsystem] + "】自动更新"; if (this.WindowState == FormWindowState.Minimized) this.WindowState = FormWindowState.Normal; this.Show(); result = true; } else { //删除临时目录 if (string.IsNullOrWhiteSpace(path) && System.IO.Directory.Exists(AppConfig.GetUpdateTempPath(subsystem))) System.IO.Directory.Delete(AppConfig.GetUpdateTempPath(subsystem), true); } } catch (Exception e) { log.Error(string.Format("执行窗口升级失败,参数{0},{1},{2}", path, subsystem, systemPath), e); MessageBox.Show("升级失败!详情:" + e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } finally { } return result; } /// <summary> /// 系统加载 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_Load(object sender, EventArgs e) { try { auPublishHelp.Start(); bgw.RunWorkerAsync(); } catch (Exception ex) { log.Error("窗体加载失败", ex); MessageBox.Show(ex.Message); } } /// <summary> /// 消息通知 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Au_Notify(object sender, NotifyMessage e) { this.log.InfoFormat("类型:[{0}] 消息:[{1}] 附加内:[{2}]", e.NotifyType, e.Message, e.Attachment); if (!AppConfig.Current.AllowUI) return; this.Invoke((MethodInvoker)delegate () { switch (e.NotifyType) { case NotifyType.Error: MessageBox.Show(e.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case NotifyType.StartDown: this.Cursor = Cursors.WaitCursor; lbState.Text = e.Message; break; case NotifyType.Normal: lbState.Text = e.Message; break; case NotifyType.Process: pbDownFile.Minimum = 0; lbState.Text = e.Message; pbDownFile.Maximum = Convert.ToInt32(e.Attachment); break; case NotifyType.UpProcess: int v = pbDownFile.Value + Convert.ToInt32(e.Attachment); string[] arg = e.Message.Split(':'); lvUpdateList.Items[Convert.ToInt32(arg[0])].SubItems[2].Text = arg[1]; pbDownFile.Value = v > pbDownFile.Maximum ? pbDownFile.Maximum : v; break; case NotifyType.StopDown: this.InvalidateControl(); this.Cursor = Cursors.Default; btnNext.Enabled = true; lbState.Text = e.Message; break; } }); } /// <summary> /// 执行更新 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnNext_Click(object sender, EventArgs e) { if (tabPageMain.SelectedTab == tabPageMsg) { tabPageMain.TabPages.Clear(); tabPageMain.TabPages.Add(tabPageList); return; } if (AvailableUpdate > 0) { //if (threadDown != null && threadDown.ThreadState != System.Threading.ThreadState.Running) //{ this.Cursor = Cursors.WaitCursor; iisOperate(btnNext.Tag?.ToString(), false); //this.Cursor = Cursors.Default; Thread threadDown = new Thread(new ParameterizedThreadStart(auUpdater.Upgrade)); threadDown.IsBackground = true; threadDown.Start(htUpdateFile); btnNext.Enabled = false; btnCancel.Enabled = false; } else { MessageBox.Show("没有可用的更新!", "自动更新", MessageBoxButtons.OK, MessageBoxIcon.Information); tabPageMain.TabPages.Clear(); tabPageMain.TabPages.Add(tabPageSucess); return; } } /// <summary> /// 取消更新 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCancel_Click(object sender, EventArgs e) { try { iisOperate(btnNext.Tag?.ToString(), true); this.Hide(); this.MainAppRun(); this.AvailableUpdate = 0; if (!this.bgw.IsBusy) bgw.RunWorkerAsync(); } catch (Exception ex) { log.Error(ex); MessageBox.Show(ex.Message); } } /// <summary> /// 执行链接 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { //打开首页 System.Diagnostics.Process.Start(linkLabel1.Text); } /// <summary> /// 重新绘制窗体部分控件属性 /// </summary> /// <param name="sucess">sucess 完成=true 下一步=false</param> private void InvalidateControl(bool sucess = true) { btnCancel.Enabled = true; if (sucess) { tabPageMain.TabPages.Clear(); tabPageMain.TabPages.Add(tabPageSucess); btnNext.Visible = false; btnCancel.Text = "完成"; } else { tabPageMain.TabPages.Clear(); tabPageMain.TabPages.Add(tabPageMsg); lbState.Text = "点击“下一步”开始更新文件"; pbDownFile.Value = 0; btnNext.Visible = true; btnCancel.Text = "取消"; } } private void MainAppRun() { try { string path = string.Empty; string args = string.Empty; if (!IsMainAppRun(out path, out args)) { if (System.IO.File.Exists(path)) { System.Diagnostics.Process.Start(path, args); } } } catch (Exception e) { log.Error(e); MessageBox.Show(e.Message); } } /// <summary> /// 判断主应用程序是否正在运行 /// </summary> /// <returns></returns> private bool IsMainAppRun(out string applicationPath, out string args) { string name = args = applicationPath = string.Empty; if (auUpdater == null) return true; if (auUpdater.IsUpgrade) { if (htUpdateFile.LocalAuList.Application.StartType != 1) { return true; } name = htUpdateFile.LocalAuList.Application.EntryPoint.ToLower(); applicationPath = auUpdater.SystemPath + "\\" + htUpdateFile.LocalAuList.Application.Location + "\\" + htUpdateFile.LocalAuList.Application.EntryPoint; args = htUpdateFile.LocalAuList.Application.StartArgs; } else { if (auUpdater.TargetAuPackage == null) return true; else if (auUpdater.TargetAuPackage.LocalAuList == null) { if (htUpdateFile != null && htUpdateFile.LocalAuList != null && htUpdateFile.LocalAuList.Application.StartType != 0) { name = htUpdateFile.LocalAuList.Application.EntryPoint.ToLower(); applicationPath = auUpdater.SystemPath + "\\" + htUpdateFile.LocalAuList.Application.Location + "\\" + htUpdateFile.LocalAuList.Application.EntryPoint; args = htUpdateFile.LocalAuList.Application.StartArgs; } //return true; } else if (auUpdater.TargetAuPackage.LocalAuList.Application.StartType != 1) { return true; } else { name = auUpdater.TargetAuPackage.LocalAuList.Application.EntryPoint.ToLower(); applicationPath = auUpdater.SystemPath + "\\" + auUpdater.TargetAuPackage.LocalAuList.Application.Location + "\\" + auUpdater.TargetAuPackage.LocalAuList.Application.EntryPoint; args = auUpdater.TargetAuPackage.LocalAuList.Application.StartArgs; } } bool isRun = AU.Common.Utility.ToolsHelp.IsRunApplication(name); //Process[] allProcess = Process.GetProcesses(); //foreach (Process p in allProcess) //{ // if (p.ProcessName.ToLower() + ".exe" == name) // { // isRun = true; // //break; // } //} return isRun; } private void bgw_DoWork(object sender, DoWorkEventArgs e) { //去通知消息 while (true) { if (this.IsShow) return; UpgradeMessage um; if (!this.auPublishHelp.UpgradeMessageQueue.TryDequeue(out um)) { foreach (var d in this.auPublishHelp.SubSystemDic) { if (System.IO.Directory.Exists(AppConfig.GetUpdateTempPath(d.Key)) && !this.IsShow) { log.InfoFormat("存在升级临时目录 {0},{1}", d.Key, d.Value); um = new UpgradeMessage() { UpdatePackFile = "", SubSystem = d.Key, UpgradePath = d.Value }; break; } } } if (um != null) { if (um.SubSystem == "auclient") { this.auPublishHelp.Stop(); DoUpdate du = new DoUpdate(); if (du.Start(um.UpdatePackFile, um.UpgradePath)) { this.BeginInvoke((MethodInvoker)delegate () { this.Close(); }); return; } this.auPublishHelp.Start(); } else { if (AppConfig.Current.AllowUI) { this.BeginInvoke((MethodInvoker)delegate () { this.ShowUpdate(um.UpdatePackFile, um.SubSystem, um.UpgradePath); }); } else this.DoUpgrade(um.UpdatePackFile, um.SubSystem, um.UpgradePath); } } System.Threading.Thread.Sleep(AppConfig.Current.Interval); } } public void CheckRun() { if (!this.IsShow && !bgw.IsBusy) bgw.RunWorkerAsync(); } private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //没有显示UI if (!this.IsShow) { System.Threading.Thread.Sleep(AppConfig.Current.Interval); log.Info("执行后台服务"); bgw.RunWorkerAsync(); } } } } <file_sep>/UtilityTools/ListTextWriter.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; namespace UtilityTools { public class ListTextWriter : TextWriter { private ListBox listBox; private delegate void VoidAction(); private log4net.ILog log = log4net.LogManager.GetLogger(typeof(ListTextWriter)); public ListTextWriter(ListBox box, long lastCount = 3000) { listBox = box; System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(() => { while (true) { if (listBox.Items.Count >= lastCount) { VoidAction action = delegate { listBox.Items.Clear(); }; listBox.BeginInvoke(action); } System.Threading.Thread.Sleep(3000); } }); t.Start(); } public override void Write(string value) { VoidAction action = delegate { try { string msg = string.Format("[{0:HH:mm:ss}]{1}", DateTime.Now, value); log.Info(msg); listBox.Items.Insert(0, msg); } catch (Exception e) { log.Error(e); listBox.Items.Insert(0, e.Message); } }; listBox.BeginInvoke(action); } public override void WriteLine(string value) { VoidAction action = delegate { try { string msg = string.Format("[{0:HH:mm:ss}]{1}", DateTime.Now, value); log.Info(msg); listBox.Items.Insert(0, string.Format("[{0:HH:mm:ss}]{1}", DateTime.Now, value)); } catch (Exception e) { log.Error(e); listBox.Items.Insert(0, e.Message); } }; listBox.BeginInvoke(action); } public override Encoding Encoding { get { return System.Text.Encoding.UTF8; } } } }<file_sep>/.svn/pristine/a5/a51aef496270a74c65659e19bf3335cdc2abf2a3.svn-base namespace AuWriter { partial class AuWriterForm { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要修改 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AuWriterForm)); this.ofdExpt = new System.Windows.Forms.OpenFileDialog(); this.ofdSrc = new System.Windows.Forms.OpenFileDialog(); this.tbpOpt = new System.Windows.Forms.TabPage(); this.sfdDest = new System.Windows.Forms.SaveFileDialog(); this.cbPackage = new System.Windows.Forms.CheckBox(); this.txtUrl = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.tbpBase = new System.Windows.Forms.TabPage(); this.panelAuclient = new System.Windows.Forms.Panel(); this.btnAuClientPub = new System.Windows.Forms.Button(); this.btnbtnAuClientSelect = new System.Windows.Forms.Button(); this.tbVersion = new System.Windows.Forms.TextBox(); this.gbPublish = new System.Windows.Forms.GroupBox(); this.txtExpt = new System.Windows.Forms.TextBox(); this.btnExit = new System.Windows.Forms.Button(); this.cbFilter = new System.Windows.Forms.CheckBox(); this.label3 = new System.Windows.Forms.Label(); this.btnExpt = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.btnDir = new System.Windows.Forms.Button(); this.prbProd = new System.Windows.Forms.ProgressBar(); this.btnSrc = new System.Windows.Forms.Button(); this.tbUpdateMsg = new System.Windows.Forms.TextBox(); this.btnDest = new System.Windows.Forms.Button(); this.txtDest = new System.Windows.Forms.TextBox(); this.btnProduce = new System.Windows.Forms.Button(); this.panel2 = new System.Windows.Forms.Panel(); this.label6 = new System.Windows.Forms.Label(); this.cbSubSystem = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.txtSrc = new System.Windows.Forms.TextBox(); this.tabControlMain = new System.Windows.Forms.TabControl(); this.tbpControl = new System.Windows.Forms.TabPage(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.tvTerminal = new System.Windows.Forms.TreeView(); this.tbFind = new System.Windows.Forms.TextBox(); this.tabControlCmd = new System.Windows.Forms.TabControl(); this.tbpCmd = new System.Windows.Forms.TabPage(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.tbMsg = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label7 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.tbParameter = new System.Windows.Forms.TextBox(); this.cmbCmdType = new System.Windows.Forms.ComboBox(); this.cmbCmd = new System.Windows.Forms.ComboBox(); this.btnSend = new System.Windows.Forms.Button(); this.tabControlLog = new System.Windows.Forms.TabControl(); this.tbpLog = new System.Windows.Forms.TabPage(); this.lbLog = new System.Windows.Forms.ListBox(); this.tbpTerminal = new System.Windows.Forms.TabPage(); this.rtbTerminial = new System.Windows.Forms.RichTextBox(); this.tbpSqlData = new System.Windows.Forms.TabPage(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.lbSQLMsg = new System.Windows.Forms.Label(); this.tbpRes = new System.Windows.Forms.TabPage(); this.splitContainer3 = new System.Windows.Forms.SplitContainer(); this.lb_remoteexplorer = new System.Windows.Forms.Label(); this.lvRemoteDisk = new System.Windows.Forms.ListView(); this.columnHeaderRName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderRDate = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderRType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderRSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.iml_ExplorerImages = new System.Windows.Forms.ImageList(this.components); this.gbRemoteDisk = new System.Windows.Forms.GroupBox(); this.panelUpload = new System.Windows.Forms.Panel(); this.btnUploadCancle = new System.Windows.Forms.Button(); this.label8 = new System.Windows.Forms.Label(); this.lbUpload = new System.Windows.Forms.Label(); this.pgbUpLoad = new System.Windows.Forms.ProgressBar(); this.txt_remoteexplorer = new System.Windows.Forms.TextBox(); this.lb_myexplorer = new System.Windows.Forms.Label(); this.lvLocalDisk = new System.Windows.Forms.ListView(); this.columnHeaderName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderDate = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.gbLocalDisk = new System.Windows.Forms.GroupBox(); this.panelDownload = new System.Windows.Forms.Panel(); this.btnDownloadCancle = new System.Windows.Forms.Button(); this.label10 = new System.Windows.Forms.Label(); this.lbDownload = new System.Windows.Forms.Label(); this.pgbDownload = new System.Windows.Forms.ProgressBar(); this.txt_myexplorer = new System.Windows.Forms.TextBox(); this.fbdSrc = new System.Windows.Forms.FolderBrowserDialog(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.系统ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.启动服务ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.停止服务ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.视图ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.资源列表显示方式ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.lbl_Display = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.tsmRemoteResource = new System.Windows.Forms.ToolStripMenuItem(); this.断开连接ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.cms_Disk = new System.Windows.Forms.ContextMenuStrip(this.components); this.DownloadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.UploadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.DeleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.BrowseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.RefreshToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components); this.tbpBase.SuspendLayout(); this.panelAuclient.SuspendLayout(); this.gbPublish.SuspendLayout(); this.tabControlMain.SuspendLayout(); this.tbpControl.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.tabControlCmd.SuspendLayout(); this.tbpCmd.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.groupBox2.SuspendLayout(); this.tabControlLog.SuspendLayout(); this.tbpLog.SuspendLayout(); this.tbpTerminal.SuspendLayout(); this.tbpSqlData.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.groupBox1.SuspendLayout(); this.tbpRes.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).BeginInit(); this.splitContainer3.Panel1.SuspendLayout(); this.splitContainer3.Panel2.SuspendLayout(); this.splitContainer3.SuspendLayout(); this.gbRemoteDisk.SuspendLayout(); this.panelUpload.SuspendLayout(); this.gbLocalDisk.SuspendLayout(); this.panelDownload.SuspendLayout(); this.menuStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); this.cms_Disk.SuspendLayout(); this.SuspendLayout(); // // ofdExpt // this.ofdExpt.DefaultExt = "*.*"; this.ofdExpt.Filter = "所有文件(*.*)|*.*"; this.ofdExpt.Multiselect = true; this.ofdExpt.Title = "请选择主程序文件"; this.ofdExpt.FileOk += new System.ComponentModel.CancelEventHandler(this.ofdExpt_FileOk); // // ofdSrc // this.ofdSrc.DefaultExt = "*.exe"; this.ofdSrc.Filter = "程序文件(*.exe)|*.exe|所有文件(*.*)|*.*"; this.ofdSrc.Title = "请选择主程序文件"; this.ofdSrc.FileOk += new System.ComponentModel.CancelEventHandler(this.ofdSrc_FileOk); // // tbpOpt // this.tbpOpt.Location = new System.Drawing.Point(4, 22); this.tbpOpt.Name = "tbpOpt"; this.tbpOpt.Padding = new System.Windows.Forms.Padding(3); this.tbpOpt.Size = new System.Drawing.Size(974, 497); this.tbpOpt.TabIndex = 1; this.tbpOpt.Text = "※选项"; this.tbpOpt.UseVisualStyleBackColor = true; // // sfdDest // this.sfdDest.CheckPathExists = false; this.sfdDest.DefaultExt = "*.xml"; this.sfdDest.FileName = "aupackage.json"; this.sfdDest.Filter = "json文件(*.json)|*.json"; this.sfdDest.Title = "请选择aupackage保存位置"; this.sfdDest.FileOk += new System.ComponentModel.CancelEventHandler(this.sfdDest_FileOk); // // cbPackage // this.cbPackage.AutoSize = true; this.cbPackage.Location = new System.Drawing.Point(502, 199); this.cbPackage.Name = "cbPackage"; this.cbPackage.Size = new System.Drawing.Size(48, 16); this.cbPackage.TabIndex = 11; this.cbPackage.Text = "打包"; this.cbPackage.UseVisualStyleBackColor = true; this.cbPackage.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged); // // txtUrl // this.txtUrl.Location = new System.Drawing.Point(98, 14); this.txtUrl.Name = "txtUrl"; this.txtUrl.ReadOnly = true; this.txtUrl.Size = new System.Drawing.Size(513, 21); this.txtUrl.TabIndex = 1; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(33, 17); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(59, 12); this.label5.TabIndex = 9; this.label5.Text = "更新网址:"; // // tbpBase // this.tbpBase.Controls.Add(this.panelAuclient); this.tbpBase.Controls.Add(this.tbVersion); this.tbpBase.Controls.Add(this.gbPublish); this.tbpBase.Controls.Add(this.panel2); this.tbpBase.Controls.Add(this.label6); this.tbpBase.Controls.Add(this.cbSubSystem); this.tbpBase.Controls.Add(this.txtUrl); this.tbpBase.Controls.Add(this.label5); this.tbpBase.Controls.Add(this.label2); this.tbpBase.Controls.Add(this.txtSrc); this.tbpBase.Location = new System.Drawing.Point(4, 22); this.tbpBase.Name = "tbpBase"; this.tbpBase.Padding = new System.Windows.Forms.Padding(3); this.tbpBase.Size = new System.Drawing.Size(974, 497); this.tbpBase.TabIndex = 0; this.tbpBase.Text = "※基本信息"; this.tbpBase.UseVisualStyleBackColor = true; // // panelAuclient // this.panelAuclient.Controls.Add(this.btnAuClientPub); this.panelAuclient.Controls.Add(this.btnbtnAuClientSelect); this.panelAuclient.Location = new System.Drawing.Point(438, 38); this.panelAuclient.Name = "panelAuclient"; this.panelAuclient.Size = new System.Drawing.Size(173, 28); this.panelAuclient.TabIndex = 18; this.panelAuclient.Visible = false; // // btnAuClientPub // this.btnAuClientPub.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnAuClientPub.Location = new System.Drawing.Point(90, 3); this.btnAuClientPub.Name = "btnAuClientPub"; this.btnAuClientPub.Size = new System.Drawing.Size(79, 21); this.btnAuClientPub.TabIndex = 17; this.btnAuClientPub.Text = "发布"; this.btnAuClientPub.UseVisualStyleBackColor = true; this.btnAuClientPub.Click += new System.EventHandler(this.btnAuClientPub_Click); // // btnbtnAuClientSelect // this.btnbtnAuClientSelect.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnbtnAuClientSelect.Location = new System.Drawing.Point(6, 3); this.btnbtnAuClientSelect.Name = "btnbtnAuClientSelect"; this.btnbtnAuClientSelect.Size = new System.Drawing.Size(79, 21); this.btnbtnAuClientSelect.TabIndex = 17; this.btnbtnAuClientSelect.Text = "选择程序(&S)"; this.btnbtnAuClientSelect.UseVisualStyleBackColor = true; this.btnbtnAuClientSelect.Click += new System.EventHandler(this.btnbtnAuClientSelect_Click); // // tbVersion // this.tbVersion.Location = new System.Drawing.Point(439, 71); this.tbVersion.Name = "tbVersion"; this.tbVersion.Size = new System.Drawing.Size(172, 21); this.tbVersion.TabIndex = 6; // // gbPublish // this.gbPublish.Controls.Add(this.txtExpt); this.gbPublish.Controls.Add(this.btnExit); this.gbPublish.Controls.Add(this.cbFilter); this.gbPublish.Controls.Add(this.cbPackage); this.gbPublish.Controls.Add(this.label3); this.gbPublish.Controls.Add(this.btnExpt); this.gbPublish.Controls.Add(this.label4); this.gbPublish.Controls.Add(this.btnDir); this.gbPublish.Controls.Add(this.prbProd); this.gbPublish.Controls.Add(this.btnSrc); this.gbPublish.Controls.Add(this.tbUpdateMsg); this.gbPublish.Controls.Add(this.btnDest); this.gbPublish.Controls.Add(this.txtDest); this.gbPublish.Controls.Add(this.btnProduce); this.gbPublish.Location = new System.Drawing.Point(3, 95); this.gbPublish.Name = "gbPublish"; this.gbPublish.Size = new System.Drawing.Size(634, 399); this.gbPublish.TabIndex = 16; this.gbPublish.TabStop = false; this.gbPublish.Visible = false; // // txtExpt // this.txtExpt.Location = new System.Drawing.Point(95, 67); this.txtExpt.Multiline = true; this.txtExpt.Name = "txtExpt"; this.txtExpt.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtExpt.Size = new System.Drawing.Size(455, 124); this.txtExpt.TabIndex = 8; // // btnExit // this.btnExit.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnExit.Location = new System.Drawing.Point(544, 368); this.btnExit.Name = "btnExit"; this.btnExit.Size = new System.Drawing.Size(64, 23); this.btnExit.TabIndex = 15; this.btnExit.Text = "退出(&X)"; this.btnExit.UseVisualStyleBackColor = true; this.btnExit.Click += new System.EventHandler(this.btnExit_Click); // // cbFilter // this.cbFilter.AutoSize = true; this.cbFilter.Checked = true; this.cbFilter.CheckState = System.Windows.Forms.CheckState.Checked; this.cbFilter.Location = new System.Drawing.Point(95, 45); this.cbFilter.Name = "cbFilter"; this.cbFilter.Size = new System.Drawing.Size(300, 16); this.cbFilter.TabIndex = 7; this.cbFilter.Text = "过滤文件(*.log,*.config,*.db,*.dat,unins000.*)"; this.cbFilter.UseVisualStyleBackColor = true; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(29, 196); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(59, 12); this.label3.TabIndex = 3; this.label3.Text = "保存位置:"; // // btnExpt // this.btnExpt.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnExpt.Location = new System.Drawing.Point(556, 67); this.btnExpt.Name = "btnExpt"; this.btnExpt.Size = new System.Drawing.Size(53, 21); this.btnExpt.TabIndex = 9; this.btnExpt.Text = "选择(&S)"; this.btnExpt.UseVisualStyleBackColor = true; this.btnExpt.Click += new System.EventHandler(this.btnExpt_Click); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(30, 67); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(59, 12); this.label4.TabIndex = 6; this.label4.Text = "排除文件:"; // // btnDir // this.btnDir.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnDir.Location = new System.Drawing.Point(195, 14); this.btnDir.Name = "btnDir"; this.btnDir.Size = new System.Drawing.Size(79, 21); this.btnDir.TabIndex = 4; this.btnDir.Text = "选择目录(&D)"; this.btnDir.UseVisualStyleBackColor = true; this.btnDir.Click += new System.EventHandler(this.btnDir_Click); // // prbProd // this.prbProd.Location = new System.Drawing.Point(94, 368); this.prbProd.Name = "prbProd"; this.prbProd.Size = new System.Drawing.Size(370, 23); this.prbProd.TabIndex = 2; this.prbProd.Visible = false; // // btnSrc // this.btnSrc.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnSrc.Location = new System.Drawing.Point(95, 14); this.btnSrc.Name = "btnSrc"; this.btnSrc.Size = new System.Drawing.Size(79, 21); this.btnSrc.TabIndex = 3; this.btnSrc.Text = "选择程序(&S)"; this.btnSrc.UseVisualStyleBackColor = true; this.btnSrc.Click += new System.EventHandler(this.btnSrc_Click); // // tbUpdateMsg // this.tbUpdateMsg.Location = new System.Drawing.Point(94, 219); this.tbUpdateMsg.Multiline = true; this.tbUpdateMsg.Name = "tbUpdateMsg"; this.tbUpdateMsg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.tbUpdateMsg.Size = new System.Drawing.Size(514, 143); this.tbUpdateMsg.TabIndex = 13; this.tbUpdateMsg.Text = "更新说明:"; // // btnDest // this.btnDest.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnDest.Location = new System.Drawing.Point(556, 196); this.btnDest.Name = "btnDest"; this.btnDest.Size = new System.Drawing.Size(52, 21); this.btnDest.TabIndex = 12; this.btnDest.Text = "选择(&S)"; this.btnDest.UseVisualStyleBackColor = true; this.btnDest.Click += new System.EventHandler(this.btnDest_Click); // // txtDest // this.txtDest.Location = new System.Drawing.Point(94, 192); this.txtDest.Name = "txtDest"; this.txtDest.Size = new System.Drawing.Size(402, 21); this.txtDest.TabIndex = 10; // // btnProduce // this.btnProduce.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnProduce.Location = new System.Drawing.Point(478, 368); this.btnProduce.Name = "btnProduce"; this.btnProduce.Size = new System.Drawing.Size(60, 23); this.btnProduce.TabIndex = 14; this.btnProduce.Text = "生成(&G)"; this.btnProduce.UseVisualStyleBackColor = true; this.btnProduce.Click += new System.EventHandler(this.btnProduce_Click); // // panel2 // this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel2.Location = new System.Drawing.Point(3, 455); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(968, 39); this.panel2.TabIndex = 4; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(31, 45); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(59, 12); this.label6.TabIndex = 13; this.label6.Text = "升级类型:"; // // cbSubSystem // this.cbSubSystem.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbSubSystem.FormattingEnabled = true; this.cbSubSystem.Location = new System.Drawing.Point(98, 42); this.cbSubSystem.Name = "cbSubSystem"; this.cbSubSystem.Size = new System.Drawing.Size(336, 20); this.cbSubSystem.TabIndex = 2; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(43, 75); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(47, 12); this.label2.TabIndex = 0; this.label2.Text = "主程序:"; // // txtSrc // this.txtSrc.Location = new System.Drawing.Point(97, 71); this.txtSrc.Name = "txtSrc"; this.txtSrc.Size = new System.Drawing.Size(336, 21); this.txtSrc.TabIndex = 5; // // tabControlMain // this.tabControlMain.Controls.Add(this.tbpBase); this.tabControlMain.Controls.Add(this.tbpOpt); this.tabControlMain.Controls.Add(this.tbpControl); this.tabControlMain.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControlMain.Location = new System.Drawing.Point(0, 25); this.tabControlMain.Name = "tabControlMain"; this.tabControlMain.SelectedIndex = 0; this.tabControlMain.Size = new System.Drawing.Size(982, 523); this.tabControlMain.TabIndex = 0; // // tbpControl // this.tbpControl.Controls.Add(this.splitContainer1); this.tbpControl.Location = new System.Drawing.Point(4, 22); this.tbpControl.Name = "tbpControl"; this.tbpControl.Padding = new System.Windows.Forms.Padding(3); this.tbpControl.Size = new System.Drawing.Size(974, 497); this.tbpControl.TabIndex = 2; this.tbpControl.Text = "※控制"; this.tbpControl.UseVisualStyleBackColor = true; // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(3, 3); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.tvTerminal); this.splitContainer1.Panel1.Controls.Add(this.tbFind); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.tabControlCmd); this.splitContainer1.Size = new System.Drawing.Size(968, 491); this.splitContainer1.SplitterDistance = 172; this.splitContainer1.TabIndex = 9; // // tvTerminal // this.tvTerminal.Dock = System.Windows.Forms.DockStyle.Fill; this.tvTerminal.HideSelection = false; this.tvTerminal.HotTracking = true; this.tvTerminal.Location = new System.Drawing.Point(0, 0); this.tvTerminal.Name = "tvTerminal"; this.tvTerminal.ShowNodeToolTips = true; this.tvTerminal.Size = new System.Drawing.Size(172, 470); this.tvTerminal.TabIndex = 0; this.tvTerminal.NodeMouseClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.tvTerminal_NodeMouseClick); // // tbFind // this.tbFind.Dock = System.Windows.Forms.DockStyle.Bottom; this.tbFind.Location = new System.Drawing.Point(0, 470); this.tbFind.Name = "tbFind"; this.tbFind.Size = new System.Drawing.Size(172, 21); this.tbFind.TabIndex = 1; this.tbFind.TextChanged += new System.EventHandler(this.tbFind_TextChanged); // // tabControlCmd // this.tabControlCmd.Controls.Add(this.tbpCmd); this.tabControlCmd.Controls.Add(this.tbpRes); this.tabControlCmd.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControlCmd.Location = new System.Drawing.Point(0, 0); this.tabControlCmd.Name = "tabControlCmd"; this.tabControlCmd.SelectedIndex = 0; this.tabControlCmd.Size = new System.Drawing.Size(792, 491); this.tabControlCmd.TabIndex = 2; // // tbpCmd // this.tbpCmd.Controls.Add(this.splitContainer2); this.tbpCmd.Location = new System.Drawing.Point(4, 22); this.tbpCmd.Name = "tbpCmd"; this.tbpCmd.Padding = new System.Windows.Forms.Padding(3); this.tbpCmd.Size = new System.Drawing.Size(784, 465); this.tbpCmd.TabIndex = 0; this.tbpCmd.Text = "命令交互"; this.tbpCmd.UseVisualStyleBackColor = true; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(3, 3); this.splitContainer2.Name = "splitContainer2"; this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.tbMsg); this.splitContainer2.Panel1.Controls.Add(this.groupBox2); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.tabControlLog); this.splitContainer2.Size = new System.Drawing.Size(778, 459); this.splitContainer2.SplitterDistance = 134; this.splitContainer2.TabIndex = 1; // // tbMsg // this.tbMsg.Dock = System.Windows.Forms.DockStyle.Fill; this.tbMsg.Location = new System.Drawing.Point(0, 64); this.tbMsg.Multiline = true; this.tbMsg.Name = "tbMsg"; this.tbMsg.Size = new System.Drawing.Size(778, 70); this.tbMsg.TabIndex = 3; // // groupBox2 // this.groupBox2.Controls.Add(this.label7); this.groupBox2.Controls.Add(this.label9); this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.tbParameter); this.groupBox2.Controls.Add(this.cmbCmdType); this.groupBox2.Controls.Add(this.cmbCmd); this.groupBox2.Controls.Add(this.btnSend); this.groupBox2.Dock = System.Windows.Forms.DockStyle.Top; this.groupBox2.Location = new System.Drawing.Point(0, 0); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(778, 64); this.groupBox2.TabIndex = 7; this.groupBox2.TabStop = false; // // label7 // this.label7.Location = new System.Drawing.Point(328, 15); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(94, 16); this.label7.TabIndex = 7; this.label7.Text = "参数:以\",\"分割"; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(165, 15); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(35, 12); this.label9.TabIndex = 7; this.label9.Text = "类别:"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(3, 17); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(35, 12); this.label1.TabIndex = 7; this.label1.Text = "指令:"; // // tbParameter // this.tbParameter.Location = new System.Drawing.Point(447, 12); this.tbParameter.Multiline = true; this.tbParameter.Name = "tbParameter"; this.tbParameter.Size = new System.Drawing.Size(206, 30); this.tbParameter.TabIndex = 4; // // cmbCmdType // this.cmbCmdType.FormattingEnabled = true; this.cmbCmdType.Location = new System.Drawing.Point(201, 12); this.cmbCmdType.Name = "cmbCmdType"; this.cmbCmdType.Size = new System.Drawing.Size(121, 20); this.cmbCmdType.TabIndex = 1; // // cmbCmd // this.cmbCmd.FormattingEnabled = true; this.cmbCmd.Items.AddRange(new object[] { "AUVERSION", "TRANSFER", "TRANSFERONE", "TERMINAL", "RESOURCE", "SCRIPT"}); this.cmbCmd.Location = new System.Drawing.Point(38, 13); this.cmbCmd.Name = "cmbCmd"; this.cmbCmd.Size = new System.Drawing.Size(121, 20); this.cmbCmd.TabIndex = 1; this.cmbCmd.SelectedIndexChanged += new System.EventHandler(this.cmbCmd_SelectedIndexChanged); // // btnSend // this.btnSend.Location = new System.Drawing.Point(237, 38); this.btnSend.Name = "btnSend"; this.btnSend.Size = new System.Drawing.Size(85, 20); this.btnSend.TabIndex = 5; this.btnSend.Text = "发送"; this.btnSend.UseVisualStyleBackColor = true; this.btnSend.Click += new System.EventHandler(this.btnSend_Click); // // tabControlLog // this.tabControlLog.Controls.Add(this.tbpLog); this.tabControlLog.Controls.Add(this.tbpTerminal); this.tabControlLog.Controls.Add(this.tbpSqlData); this.tabControlLog.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControlLog.Location = new System.Drawing.Point(0, 0); this.tabControlLog.Name = "tabControlLog"; this.tabControlLog.SelectedIndex = 0; this.tabControlLog.Size = new System.Drawing.Size(778, 321); this.tabControlLog.TabIndex = 8; // // tbpLog // this.tbpLog.Controls.Add(this.lbLog); this.tbpLog.Location = new System.Drawing.Point(4, 22); this.tbpLog.Name = "tbpLog"; this.tbpLog.Padding = new System.Windows.Forms.Padding(3); this.tbpLog.Size = new System.Drawing.Size(770, 295); this.tbpLog.TabIndex = 0; this.tbpLog.Text = "日志"; this.tbpLog.UseVisualStyleBackColor = true; // // lbLog // this.lbLog.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(30)))), ((int)(((byte)(30)))), ((int)(((byte)(30))))); this.lbLog.Dock = System.Windows.Forms.DockStyle.Fill; this.lbLog.ForeColor = System.Drawing.SystemColors.HighlightText; this.lbLog.FormattingEnabled = true; this.lbLog.HorizontalScrollbar = true; this.lbLog.ItemHeight = 12; this.lbLog.Location = new System.Drawing.Point(3, 3); this.lbLog.Name = "lbLog"; this.lbLog.ScrollAlwaysVisible = true; this.lbLog.Size = new System.Drawing.Size(764, 289); this.lbLog.TabIndex = 6; this.lbLog.SelectedIndexChanged += new System.EventHandler(this.lbLog_SelectedIndexChanged); this.lbLog.DoubleClick += new System.EventHandler(this.lbLog_DoubleClick); // // tbpTerminal // this.tbpTerminal.Controls.Add(this.rtbTerminial); this.tbpTerminal.Location = new System.Drawing.Point(4, 22); this.tbpTerminal.Name = "tbpTerminal"; this.tbpTerminal.Padding = new System.Windows.Forms.Padding(3); this.tbpTerminal.Size = new System.Drawing.Size(770, 295); this.tbpTerminal.TabIndex = 2; this.tbpTerminal.Text = "终端消息"; this.tbpTerminal.UseVisualStyleBackColor = true; // // rtbTerminial // this.rtbTerminial.Dock = System.Windows.Forms.DockStyle.Fill; this.rtbTerminial.Location = new System.Drawing.Point(3, 3); this.rtbTerminial.Name = "rtbTerminial"; this.rtbTerminial.Size = new System.Drawing.Size(764, 289); this.rtbTerminial.TabIndex = 1; this.rtbTerminial.Text = ""; this.rtbTerminial.MouseDown += new System.Windows.Forms.MouseEventHandler(this.rtbTerminial_MouseDown); // // tbpSqlData // this.tbpSqlData.Controls.Add(this.dataGridView1); this.tbpSqlData.Controls.Add(this.groupBox1); this.tbpSqlData.Location = new System.Drawing.Point(4, 22); this.tbpSqlData.Name = "tbpSqlData"; this.tbpSqlData.Padding = new System.Windows.Forms.Padding(3); this.tbpSqlData.Size = new System.Drawing.Size(770, 295); this.tbpSqlData.TabIndex = 3; this.tbpSqlData.Text = "SQL脚本结果数据"; this.tbpSqlData.UseVisualStyleBackColor = true; // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.AllowUserToOrderColumns = true; this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView1.Location = new System.Drawing.Point(3, 3); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowTemplate.Height = 23; this.dataGridView1.Size = new System.Drawing.Size(764, 258); this.dataGridView1.TabIndex = 1; this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dataGridView1_RowPostPaint); // // groupBox1 // this.groupBox1.Controls.Add(this.lbSQLMsg); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Bottom; this.groupBox1.Location = new System.Drawing.Point(3, 261); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(764, 31); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; // // lbSQLMsg // this.lbSQLMsg.AutoSize = true; this.lbSQLMsg.Dock = System.Windows.Forms.DockStyle.Right; this.lbSQLMsg.Location = new System.Drawing.Point(732, 17); this.lbSQLMsg.Name = "lbSQLMsg"; this.lbSQLMsg.Size = new System.Drawing.Size(29, 12); this.lbSQLMsg.TabIndex = 0; this.lbSQLMsg.Text = "描述"; // // tbpRes // this.tbpRes.Controls.Add(this.splitContainer3); this.tbpRes.Location = new System.Drawing.Point(4, 22); this.tbpRes.Name = "tbpRes"; this.tbpRes.Padding = new System.Windows.Forms.Padding(3); this.tbpRes.Size = new System.Drawing.Size(784, 465); this.tbpRes.TabIndex = 1; this.tbpRes.Text = "资源交互"; this.tbpRes.UseVisualStyleBackColor = true; // // splitContainer3 // this.splitContainer3.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer3.Location = new System.Drawing.Point(3, 3); this.splitContainer3.Name = "splitContainer3"; // // splitContainer3.Panel1 // this.splitContainer3.Panel1.Controls.Add(this.lb_remoteexplorer); this.splitContainer3.Panel1.Controls.Add(this.lvRemoteDisk); this.splitContainer3.Panel1.Controls.Add(this.gbRemoteDisk); // // splitContainer3.Panel2 // this.splitContainer3.Panel2.Controls.Add(this.lb_myexplorer); this.splitContainer3.Panel2.Controls.Add(this.lvLocalDisk); this.splitContainer3.Panel2.Controls.Add(this.gbLocalDisk); this.splitContainer3.Size = new System.Drawing.Size(778, 459); this.splitContainer3.SplitterDistance = 380; this.splitContainer3.TabIndex = 0; // // lb_remoteexplorer // this.lb_remoteexplorer.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lb_remoteexplorer.AutoSize = true; this.lb_remoteexplorer.Location = new System.Drawing.Point(4, 444); this.lb_remoteexplorer.Name = "lb_remoteexplorer"; this.lb_remoteexplorer.Size = new System.Drawing.Size(11, 12); this.lb_remoteexplorer.TabIndex = 4; this.lb_remoteexplorer.Text = ":"; // // lvRemoteDisk // this.lvRemoteDisk.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderRName, this.columnHeaderRDate, this.columnHeaderRType, this.columnHeaderRSize}); this.lvRemoteDisk.Dock = System.Windows.Forms.DockStyle.Fill; this.lvRemoteDisk.LargeImageList = this.iml_ExplorerImages; this.lvRemoteDisk.Location = new System.Drawing.Point(0, 78); this.lvRemoteDisk.MultiSelect = false; this.lvRemoteDisk.Name = "lvRemoteDisk"; this.lvRemoteDisk.Size = new System.Drawing.Size(380, 381); this.lvRemoteDisk.SmallImageList = this.iml_ExplorerImages; this.lvRemoteDisk.StateImageList = this.iml_ExplorerImages; this.lvRemoteDisk.TabIndex = 2; this.lvRemoteDisk.UseCompatibleStateImageBehavior = false; this.lvRemoteDisk.SelectedIndexChanged += new System.EventHandler(this.lvRemoteDisk_SelectedIndexChanged); this.lvRemoteDisk.DoubleClick += new System.EventHandler(this.lvRemoteDisk_DoubleClick); this.lvRemoteDisk.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lvRemoteDisk_MouseDown); // // columnHeaderRName // this.columnHeaderRName.Text = "名称"; this.columnHeaderRName.Width = 280; // // columnHeaderRDate // this.columnHeaderRDate.Text = "修改日期"; this.columnHeaderRDate.Width = 130; // // columnHeaderRType // this.columnHeaderRType.Text = "类型"; this.columnHeaderRType.Width = 100; // // columnHeaderRSize // this.columnHeaderRSize.Text = "大小"; this.columnHeaderRSize.Width = 100; // // iml_ExplorerImages // this.iml_ExplorerImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("iml_ExplorerImages.ImageStream"))); this.iml_ExplorerImages.TransparentColor = System.Drawing.Color.Transparent; this.iml_ExplorerImages.Images.SetKeyName(0, "Disk"); this.iml_ExplorerImages.Images.SetKeyName(1, "Directory"); this.iml_ExplorerImages.Images.SetKeyName(2, "midi"); this.iml_ExplorerImages.Images.SetKeyName(3, "txt"); this.iml_ExplorerImages.Images.SetKeyName(4, "css"); this.iml_ExplorerImages.Images.SetKeyName(5, "html"); this.iml_ExplorerImages.Images.SetKeyName(6, "jpg"); this.iml_ExplorerImages.Images.SetKeyName(7, "asa"); this.iml_ExplorerImages.Images.SetKeyName(8, "asax"); this.iml_ExplorerImages.Images.SetKeyName(9, "asp"); this.iml_ExplorerImages.Images.SetKeyName(10, "aspx"); this.iml_ExplorerImages.Images.SetKeyName(11, "avi"); this.iml_ExplorerImages.Images.SetKeyName(12, "bat"); this.iml_ExplorerImages.Images.SetKeyName(13, "bmp"); this.iml_ExplorerImages.Images.SetKeyName(14, "c"); this.iml_ExplorerImages.Images.SetKeyName(15, "doc"); this.iml_ExplorerImages.Images.SetKeyName(16, "chm"); this.iml_ExplorerImages.Images.SetKeyName(17, "class"); this.iml_ExplorerImages.Images.SetKeyName(18, "config"); this.iml_ExplorerImages.Images.SetKeyName(19, "cpp"); this.iml_ExplorerImages.Images.SetKeyName(20, "cs"); this.iml_ExplorerImages.Images.SetKeyName(21, "dll"); this.iml_ExplorerImages.Images.SetKeyName(22, "h"); this.iml_ExplorerImages.Images.SetKeyName(23, "dsw"); this.iml_ExplorerImages.Images.SetKeyName(24, "dvd"); this.iml_ExplorerImages.Images.SetKeyName(25, "exe"); this.iml_ExplorerImages.Images.SetKeyName(26, "fon"); this.iml_ExplorerImages.Images.SetKeyName(27, "gif"); this.iml_ExplorerImages.Images.SetKeyName(28, "htm"); this.iml_ExplorerImages.Images.SetKeyName(29, "hlp"); this.iml_ExplorerImages.Images.SetKeyName(30, "hpp"); this.iml_ExplorerImages.Images.SetKeyName(31, "ico"); this.iml_ExplorerImages.Images.SetKeyName(32, "ima"); this.iml_ExplorerImages.Images.SetKeyName(33, "iso"); this.iml_ExplorerImages.Images.SetKeyName(34, "java"); this.iml_ExplorerImages.Images.SetKeyName(35, "png"); this.iml_ExplorerImages.Images.SetKeyName(36, "jpg"); this.iml_ExplorerImages.Images.SetKeyName(37, "js"); this.iml_ExplorerImages.Images.SetKeyName(38, "jsl"); this.iml_ExplorerImages.Images.SetKeyName(39, "lnk"); this.iml_ExplorerImages.Images.SetKeyName(40, "mdb"); this.iml_ExplorerImages.Images.SetKeyName(41, "mdf"); this.iml_ExplorerImages.Images.SetKeyName(42, "mht"); this.iml_ExplorerImages.Images.SetKeyName(43, "mkv"); this.iml_ExplorerImages.Images.SetKeyName(44, "mov"); this.iml_ExplorerImages.Images.SetKeyName(45, "mp3"); this.iml_ExplorerImages.Images.SetKeyName(46, "mp4"); this.iml_ExplorerImages.Images.SetKeyName(47, "mpg"); this.iml_ExplorerImages.Images.SetKeyName(48, "obj"); this.iml_ExplorerImages.Images.SetKeyName(49, "ogm"); this.iml_ExplorerImages.Images.SetKeyName(50, "png"); this.iml_ExplorerImages.Images.SetKeyName(51, "user"); this.iml_ExplorerImages.Images.SetKeyName(52, "ppt"); this.iml_ExplorerImages.Images.SetKeyName(53, "psd"); this.iml_ExplorerImages.Images.SetKeyName(54, "rar"); this.iml_ExplorerImages.Images.SetKeyName(55, "rc"); this.iml_ExplorerImages.Images.SetKeyName(56, "reg"); this.iml_ExplorerImages.Images.SetKeyName(57, "res"); this.iml_ExplorerImages.Images.SetKeyName(58, "rm"); this.iml_ExplorerImages.Images.SetKeyName(59, "sln"); this.iml_ExplorerImages.Images.SetKeyName(60, "sql"); this.iml_ExplorerImages.Images.SetKeyName(61, "swf"); this.iml_ExplorerImages.Images.SetKeyName(62, "tif"); this.iml_ExplorerImages.Images.SetKeyName(63, "ttf"); this.iml_ExplorerImages.Images.SetKeyName(64, "txt"); this.iml_ExplorerImages.Images.SetKeyName(65, "url"); this.iml_ExplorerImages.Images.SetKeyName(66, "user"); this.iml_ExplorerImages.Images.SetKeyName(67, "vb"); this.iml_ExplorerImages.Images.SetKeyName(68, "vbs"); this.iml_ExplorerImages.Images.SetKeyName(69, "wav"); this.iml_ExplorerImages.Images.SetKeyName(70, "wma"); this.iml_ExplorerImages.Images.SetKeyName(71, "wmv"); this.iml_ExplorerImages.Images.SetKeyName(72, "LastPath"); this.iml_ExplorerImages.Images.SetKeyName(73, "xls"); this.iml_ExplorerImages.Images.SetKeyName(74, "xml"); this.iml_ExplorerImages.Images.SetKeyName(75, "Unknown"); this.iml_ExplorerImages.Images.SetKeyName(76, "zip"); // // gbRemoteDisk // this.gbRemoteDisk.Controls.Add(this.panelUpload); this.gbRemoteDisk.Controls.Add(this.txt_remoteexplorer); this.gbRemoteDisk.Dock = System.Windows.Forms.DockStyle.Top; this.gbRemoteDisk.Location = new System.Drawing.Point(0, 0); this.gbRemoteDisk.Name = "gbRemoteDisk"; this.gbRemoteDisk.Size = new System.Drawing.Size(380, 78); this.gbRemoteDisk.TabIndex = 0; this.gbRemoteDisk.TabStop = false; this.gbRemoteDisk.Text = "远程磁盘"; // // panelUpload // this.panelUpload.Controls.Add(this.btnUploadCancle); this.panelUpload.Controls.Add(this.label8); this.panelUpload.Controls.Add(this.lbUpload); this.panelUpload.Controls.Add(this.pgbUpLoad); this.panelUpload.Dock = System.Windows.Forms.DockStyle.Bottom; this.panelUpload.Location = new System.Drawing.Point(3, 26); this.panelUpload.Name = "panelUpload"; this.panelUpload.Size = new System.Drawing.Size(374, 28); this.panelUpload.TabIndex = 2; this.panelUpload.Visible = false; // // btnUploadCancle // this.btnUploadCancle.Dock = System.Windows.Forms.DockStyle.Right; this.btnUploadCancle.Location = new System.Drawing.Point(327, 0); this.btnUploadCancle.Name = "btnUploadCancle"; this.btnUploadCancle.Size = new System.Drawing.Size(47, 28); this.btnUploadCancle.TabIndex = 5; this.btnUploadCancle.Text = "取消"; this.btnUploadCancle.UseVisualStyleBackColor = true; this.btnUploadCancle.Click += new System.EventHandler(this.btnUploadCancle_Click); // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(3, 9); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(59, 12); this.label8.TabIndex = 4; this.label8.Text = "上传进度:"; // // lbUpload // this.lbUpload.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lbUpload.AutoSize = true; this.lbUpload.Location = new System.Drawing.Point(269, 9); this.lbUpload.Name = "lbUpload"; this.lbUpload.Size = new System.Drawing.Size(0, 12); this.lbUpload.TabIndex = 3; // // pgbUpLoad // this.pgbUpLoad.Location = new System.Drawing.Point(64, 2); this.pgbUpLoad.Name = "pgbUpLoad"; this.pgbUpLoad.Size = new System.Drawing.Size(197, 23); this.pgbUpLoad.TabIndex = 2; // // txt_remoteexplorer // this.txt_remoteexplorer.Dock = System.Windows.Forms.DockStyle.Bottom; this.txt_remoteexplorer.Location = new System.Drawing.Point(3, 54); this.txt_remoteexplorer.Name = "txt_remoteexplorer"; this.txt_remoteexplorer.Size = new System.Drawing.Size(374, 21); this.txt_remoteexplorer.TabIndex = 0; // // lb_myexplorer // this.lb_myexplorer.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lb_myexplorer.AutoSize = true; this.lb_myexplorer.Location = new System.Drawing.Point(5, 443); this.lb_myexplorer.Name = "lb_myexplorer"; this.lb_myexplorer.Size = new System.Drawing.Size(11, 12); this.lb_myexplorer.TabIndex = 4; this.lb_myexplorer.Text = ":"; // // lvLocalDisk // this.lvLocalDisk.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderName, this.columnHeaderDate, this.columnHeaderType, this.columnHeaderSize}); this.lvLocalDisk.Dock = System.Windows.Forms.DockStyle.Fill; this.lvLocalDisk.LargeImageList = this.iml_ExplorerImages; this.lvLocalDisk.Location = new System.Drawing.Point(0, 78); this.lvLocalDisk.MultiSelect = false; this.lvLocalDisk.Name = "lvLocalDisk"; this.lvLocalDisk.Size = new System.Drawing.Size(394, 381); this.lvLocalDisk.SmallImageList = this.iml_ExplorerImages; this.lvLocalDisk.StateImageList = this.iml_ExplorerImages; this.lvLocalDisk.TabIndex = 2; this.lvLocalDisk.UseCompatibleStateImageBehavior = false; this.lvLocalDisk.SelectedIndexChanged += new System.EventHandler(this.lvLocalDisk_SelectedIndexChanged); this.lvLocalDisk.DoubleClick += new System.EventHandler(this.lvLocalDisk_DoubleClick); this.lvLocalDisk.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lvLocalDisk_MouseDown); // // columnHeaderName // this.columnHeaderName.Text = "名称"; this.columnHeaderName.Width = 280; // // columnHeaderDate // this.columnHeaderDate.Text = "修改日期"; this.columnHeaderDate.Width = 130; // // columnHeaderType // this.columnHeaderType.Text = "类型"; this.columnHeaderType.Width = 100; // // columnHeaderSize // this.columnHeaderSize.Text = "大小"; this.columnHeaderSize.Width = 100; // // gbLocalDisk // this.gbLocalDisk.Controls.Add(this.panelDownload); this.gbLocalDisk.Controls.Add(this.txt_myexplorer); this.gbLocalDisk.Dock = System.Windows.Forms.DockStyle.Top; this.gbLocalDisk.Location = new System.Drawing.Point(0, 0); this.gbLocalDisk.Name = "gbLocalDisk"; this.gbLocalDisk.Size = new System.Drawing.Size(394, 78); this.gbLocalDisk.TabIndex = 1; this.gbLocalDisk.TabStop = false; this.gbLocalDisk.Text = "本地磁盘"; // // panelDownload // this.panelDownload.Controls.Add(this.btnDownloadCancle); this.panelDownload.Controls.Add(this.label10); this.panelDownload.Controls.Add(this.lbDownload); this.panelDownload.Controls.Add(this.pgbDownload); this.panelDownload.Dock = System.Windows.Forms.DockStyle.Bottom; this.panelDownload.Location = new System.Drawing.Point(3, 26); this.panelDownload.Name = "panelDownload"; this.panelDownload.Size = new System.Drawing.Size(388, 28); this.panelDownload.TabIndex = 3; this.panelDownload.Visible = false; // // btnDownloadCancle // this.btnDownloadCancle.Dock = System.Windows.Forms.DockStyle.Right; this.btnDownloadCancle.Location = new System.Drawing.Point(341, 0); this.btnDownloadCancle.Name = "btnDownloadCancle"; this.btnDownloadCancle.Size = new System.Drawing.Size(47, 28); this.btnDownloadCancle.TabIndex = 6; this.btnDownloadCancle.Text = "取消"; this.btnDownloadCancle.UseVisualStyleBackColor = true; this.btnDownloadCancle.Click += new System.EventHandler(this.btnDownloadCancle_Click); // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(4, 9); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(59, 12); this.label10.TabIndex = 4; this.label10.Text = "下载进度:"; // // lbDownload // this.lbDownload.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lbDownload.AutoSize = true; this.lbDownload.Location = new System.Drawing.Point(272, 10); this.lbDownload.Name = "lbDownload"; this.lbDownload.Size = new System.Drawing.Size(0, 12); this.lbDownload.TabIndex = 3; // // pgbDownload // this.pgbDownload.Location = new System.Drawing.Point(69, 3); this.pgbDownload.Name = "pgbDownload"; this.pgbDownload.Size = new System.Drawing.Size(197, 23); this.pgbDownload.TabIndex = 2; // // txt_myexplorer // this.txt_myexplorer.Dock = System.Windows.Forms.DockStyle.Bottom; this.txt_myexplorer.Location = new System.Drawing.Point(3, 54); this.txt_myexplorer.Name = "txt_myexplorer"; this.txt_myexplorer.Size = new System.Drawing.Size(388, 21); this.txt_myexplorer.TabIndex = 0; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.系统ToolStripMenuItem, this.视图ToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(982, 25); this.menuStrip1.TabIndex = 1; this.menuStrip1.Text = "menuStrip1"; // // 系统ToolStripMenuItem // this.系统ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.启动服务ToolStripMenuItem, this.停止服务ToolStripMenuItem}); this.系统ToolStripMenuItem.Name = "系统ToolStripMenuItem"; this.系统ToolStripMenuItem.Size = new System.Drawing.Size(44, 21); this.系统ToolStripMenuItem.Text = "系统"; // // 启动服务ToolStripMenuItem // this.启动服务ToolStripMenuItem.Name = "启动服务ToolStripMenuItem"; this.启动服务ToolStripMenuItem.Size = new System.Drawing.Size(124, 22); this.启动服务ToolStripMenuItem.Text = "启动服务"; this.启动服务ToolStripMenuItem.Click += new System.EventHandler(this.启动服务ToolStripMenuItem_Click); // // 停止服务ToolStripMenuItem // this.停止服务ToolStripMenuItem.Name = "停止服务ToolStripMenuItem"; this.停止服务ToolStripMenuItem.Size = new System.Drawing.Size(124, 22); this.停止服务ToolStripMenuItem.Text = "停止服务"; this.停止服务ToolStripMenuItem.Click += new System.EventHandler(this.停止服务ToolStripMenuItem_Click); // // 视图ToolStripMenuItem // this.视图ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.资源列表显示方式ToolStripMenuItem}); this.视图ToolStripMenuItem.Name = "视图ToolStripMenuItem"; this.视图ToolStripMenuItem.Size = new System.Drawing.Size(44, 21); this.视图ToolStripMenuItem.Text = "视图"; // // 资源列表显示方式ToolStripMenuItem // this.资源列表显示方式ToolStripMenuItem.Name = "资源列表显示方式ToolStripMenuItem"; this.资源列表显示方式ToolStripMenuItem.Size = new System.Drawing.Size(172, 22); this.资源列表显示方式ToolStripMenuItem.Text = "资源列表显示方式"; this.资源列表显示方式ToolStripMenuItem.Click += new System.EventHandler(this.资源列表显示方式ToolStripMenuItem_Click); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.lbl_Display, this.toolStripStatusLabel1}); this.statusStrip1.Location = new System.Drawing.Point(0, 548); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(982, 22); this.statusStrip1.TabIndex = 6; this.statusStrip1.Text = "statusStrip1"; // // lbl_Display // this.lbl_Display.Name = "lbl_Display"; this.lbl_Display.Size = new System.Drawing.Size(0, 17); // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(0, 17); // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tsmRemoteResource, this.断开连接ToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(125, 48); // // tsmRemoteResource // this.tsmRemoteResource.Name = "tsmRemoteResource"; this.tsmRemoteResource.Size = new System.Drawing.Size(124, 22); this.tsmRemoteResource.Text = "浏览资源"; this.tsmRemoteResource.Click += new System.EventHandler(this.tsmRemoteResource_Click); // // 断开连接ToolStripMenuItem // this.断开连接ToolStripMenuItem.Name = "断开连接ToolStripMenuItem"; this.断开连接ToolStripMenuItem.Size = new System.Drawing.Size(124, 22); this.断开连接ToolStripMenuItem.Text = "断开连接"; this.断开连接ToolStripMenuItem.Click += new System.EventHandler(this.断开连接ToolStripMenuItem_Click); // // cms_Disk // this.cms_Disk.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.DownloadToolStripMenuItem, this.UploadToolStripMenuItem, this.DeleteToolStripMenuItem, this.BrowseToolStripMenuItem, this.RefreshToolStripMenuItem}); this.cms_Disk.Name = "cms_Disk"; this.cms_Disk.Size = new System.Drawing.Size(101, 114); // // DownloadToolStripMenuItem // this.DownloadToolStripMenuItem.Name = "DownloadToolStripMenuItem"; this.DownloadToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.DownloadToolStripMenuItem.Text = "下载"; this.DownloadToolStripMenuItem.Click += new System.EventHandler(this.DownloadToolStripMenuItem_Click); // // UploadToolStripMenuItem // this.UploadToolStripMenuItem.Name = "UploadToolStripMenuItem"; this.UploadToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.UploadToolStripMenuItem.Text = "上传"; this.UploadToolStripMenuItem.Click += new System.EventHandler(this.UploadToolStripMenuItem_Click); // // DeleteToolStripMenuItem // this.DeleteToolStripMenuItem.Name = "DeleteToolStripMenuItem"; this.DeleteToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.DeleteToolStripMenuItem.Text = "删除"; this.DeleteToolStripMenuItem.Click += new System.EventHandler(this.DeleteToolStripMenuItem_Click); // // BrowseToolStripMenuItem // this.BrowseToolStripMenuItem.Name = "BrowseToolStripMenuItem"; this.BrowseToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.BrowseToolStripMenuItem.Text = "浏览"; this.BrowseToolStripMenuItem.Click += new System.EventHandler(this.BrowseToolStripMenuItem_Click); // // RefreshToolStripMenuItem // this.RefreshToolStripMenuItem.Name = "RefreshToolStripMenuItem"; this.RefreshToolStripMenuItem.Size = new System.Drawing.Size(100, 22); this.RefreshToolStripMenuItem.Text = "刷新"; this.RefreshToolStripMenuItem.Click += new System.EventHandler(this.RefreshToolStripMenuItem_Click); // // notifyIcon1 // this.notifyIcon1.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; this.notifyIcon1.BalloonTipText = "管理界面已隐藏,可点击小图标可显示管理器控制面板!"; this.notifyIcon1.BalloonTipTitle = "E7 升级包发布服务器"; this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon"))); this.notifyIcon1.Text = "E7 升级包发布服务器"; this.notifyIcon1.Visible = true; this.notifyIcon1.Click += new System.EventHandler(this.notifyIcon1_Click); // // AuWriterForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(982, 570); this.Controls.Add(this.tabControlMain); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.menuStrip1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Name = "AuWriterForm"; this.Text = "E7升级包发布服务器"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.AuWriterForm_FormClosing); this.Load += new System.EventHandler(this.Form1_Load); this.SizeChanged += new System.EventHandler(this.AuWriterForm_SizeChanged); this.tbpBase.ResumeLayout(false); this.tbpBase.PerformLayout(); this.panelAuclient.ResumeLayout(false); this.gbPublish.ResumeLayout(false); this.gbPublish.PerformLayout(); this.tabControlMain.ResumeLayout(false); this.tbpControl.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel1.PerformLayout(); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.tabControlCmd.ResumeLayout(false); this.tbpCmd.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel1.PerformLayout(); this.splitContainer2.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit(); this.splitContainer2.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.tabControlLog.ResumeLayout(false); this.tbpLog.ResumeLayout(false); this.tbpTerminal.ResumeLayout(false); this.tbpSqlData.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.tbpRes.ResumeLayout(false); this.splitContainer3.Panel1.ResumeLayout(false); this.splitContainer3.Panel1.PerformLayout(); this.splitContainer3.Panel2.ResumeLayout(false); this.splitContainer3.Panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer3)).EndInit(); this.splitContainer3.ResumeLayout(false); this.gbRemoteDisk.ResumeLayout(false); this.gbRemoteDisk.PerformLayout(); this.panelUpload.ResumeLayout(false); this.panelUpload.PerformLayout(); this.gbLocalDisk.ResumeLayout(false); this.gbLocalDisk.PerformLayout(); this.panelDownload.ResumeLayout(false); this.panelDownload.PerformLayout(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.contextMenuStrip1.ResumeLayout(false); this.cms_Disk.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.OpenFileDialog ofdExpt; private System.Windows.Forms.OpenFileDialog ofdSrc; private System.Windows.Forms.TabPage tbpOpt; private System.Windows.Forms.SaveFileDialog sfdDest; private System.Windows.Forms.CheckBox cbPackage; private System.Windows.Forms.TextBox txtUrl; private System.Windows.Forms.Label label5; private System.Windows.Forms.TabPage tbpBase; private System.Windows.Forms.Button btnExpt; private System.Windows.Forms.TextBox txtExpt; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button btnDest; private System.Windows.Forms.TextBox txtDest; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button btnSrc; private System.Windows.Forms.TextBox txtSrc; private System.Windows.Forms.Label label2; private System.Windows.Forms.TabControl tabControlMain; private System.Windows.Forms.ProgressBar prbProd; private System.Windows.Forms.Button btnExit; private System.Windows.Forms.Button btnProduce; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.Button btnDir; private System.Windows.Forms.FolderBrowserDialog fbdSrc; private System.Windows.Forms.ComboBox cbSubSystem; private System.Windows.Forms.Label label6; private System.Windows.Forms.CheckBox cbFilter; private System.Windows.Forms.TextBox tbVersion; private System.Windows.Forms.TabPage tbpControl; private System.Windows.Forms.TextBox tbUpdateMsg; private System.Windows.Forms.ListBox lbLog; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.TextBox tbMsg; private System.Windows.Forms.Button btnSend; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem 系统ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem 启动服务ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem 停止服务ToolStripMenuItem; private System.Windows.Forms.ComboBox cmbCmd; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.TextBox tbParameter; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label1; private System.Windows.Forms.TabControl tabControlLog; private System.Windows.Forms.TabPage tbpLog; private System.Windows.Forms.TreeView tvTerminal; private System.Windows.Forms.Label label9; private System.Windows.Forms.ComboBox cmbCmdType; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.TabControl tabControlCmd; private System.Windows.Forms.TabPage tbpCmd; private System.Windows.Forms.TabPage tbpRes; private System.Windows.Forms.SplitContainer splitContainer3; private System.Windows.Forms.GroupBox gbLocalDisk; private System.Windows.Forms.GroupBox gbRemoteDisk; private System.Windows.Forms.ListView lvLocalDisk; private System.Windows.Forms.ListView lvRemoteDisk; private System.Windows.Forms.TextBox txt_myexplorer; private System.Windows.Forms.ToolStripStatusLabel lbl_Display; private System.Windows.Forms.ImageList iml_ExplorerImages; private System.Windows.Forms.TextBox txt_remoteexplorer; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem tsmRemoteResource; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private System.Windows.Forms.Label lbUpload; private System.Windows.Forms.ProgressBar pgbUpLoad; private System.Windows.Forms.ToolStripMenuItem 断开连接ToolStripMenuItem; private System.Windows.Forms.ContextMenuStrip cms_Disk; private System.Windows.Forms.ToolStripMenuItem DownloadToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem UploadToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem DeleteToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem BrowseToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem RefreshToolStripMenuItem; private System.Windows.Forms.Panel panelDownload; private System.Windows.Forms.Label lbDownload; private System.Windows.Forms.ProgressBar pgbDownload; private System.Windows.Forms.Panel panelUpload; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label10; private System.Windows.Forms.Button btnUploadCancle; private System.Windows.Forms.Button btnDownloadCancle; private System.Windows.Forms.TabPage tbpTerminal; private System.Windows.Forms.RichTextBox rtbTerminial; private System.Windows.Forms.GroupBox gbPublish; private System.Windows.Forms.Button btnAuClientPub; private System.Windows.Forms.Button btnbtnAuClientSelect; private System.Windows.Forms.Panel panelAuclient; private System.Windows.Forms.NotifyIcon notifyIcon1; private System.Windows.Forms.ToolStripMenuItem 视图ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem 资源列表显示方式ToolStripMenuItem; private System.Windows.Forms.ColumnHeader columnHeaderName; private System.Windows.Forms.ColumnHeader columnHeaderDate; private System.Windows.Forms.ColumnHeader columnHeaderType; private System.Windows.Forms.ColumnHeader columnHeaderSize; private System.Windows.Forms.ColumnHeader columnHeaderRName; private System.Windows.Forms.ColumnHeader columnHeaderRDate; private System.Windows.Forms.ColumnHeader columnHeaderRType; private System.Windows.Forms.ColumnHeader columnHeaderRSize; private System.Windows.Forms.Label lb_myexplorer; private System.Windows.Forms.Label lb_remoteexplorer; private System.Windows.Forms.TabPage tbpSqlData; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label lbSQLMsg; private System.Windows.Forms.TextBox tbFind; } } <file_sep>/AuClient/UpgradeMessage.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AuClient { /// <summary> /// 升级消息 /// </summary> public class UpgradeMessage { /// <summary> /// 子系统 /// </summary> public string SubSystem { get; set; } /// <summary> /// 升级包 /// </summary> public string UpdatePackFile { get; set; } /// <summary> /// 升级系统路径 /// </summary> public string UpgradePath { get; set; } } } <file_sep>/AU.Monitor.Server/MonitorSession.cs # define DEBUG using System; using System.Collections.Generic; using System.Linq; using System.Text; using SuperSocket.SocketBase; using SuperSocket.SocketBase.Protocol; namespace AU.Monitor.Server { /// <summary> /// 会话 /// </summary> public class MonitorSession : AppSession<MonitorSession> { protected override void OnSessionStarted() { #if DEBUG this.Send("This is Monitor Server"); #endif base.OnSessionStarted(); } protected override void HandleUnknownRequest(StringRequestInfo requestInfo) { #if DEBUG this.Send("Unknow request >> " + requestInfo.Key + " " + requestInfo.Body); #endif base.HandleUnknownRequest(requestInfo); } protected override void HandleException(Exception e) { #if DEBUG this.Send("Application error >> {0}", e.Message); #endif base.HandleException(e); } protected override void OnSessionClosed(CloseReason reason) { base.OnSessionClosed(reason); } } } <file_sep>/AU.Common/AppPublish.cs using System; using System.Web; using System.IO; using System.Net; using System.Xml; using System.Collections; using System.ComponentModel; using AU.Common.Utility; using AU.Common; using System.Collections.Generic; using System.Diagnostics; namespace AU.Common { /// <summary> /// updater 的摘要说明。 /// </summary> public class AppPublish : IDisposable { #region 成员与字段属性 private bool disposed = false; private IntPtr handle; private Component component = new Component(); [System.Runtime.InteropServices.DllImport("Kernel32")] private extern static Boolean CloseHandle(IntPtr handle); /// <summary> /// 消息通知 /// </summary> public event EventHandler<NotifyMessage> Notify; /// <summary> /// 本地包配置 /// </summary> public AuPublish MyPublish { get; set; } /// <summary> /// 配置名称 /// </summary> public static readonly string PackageName = "aupublish.json"; /// <summary> /// 本地配置路径 /// </summary> public string LocalPath { get; private set; } /// <summary> /// 本地包路径 /// </summary> public string PackagePath { get; private set; } /// <summary> /// 更新地址 /// </summary> public string UpdaterUrl { get; set; } /// <summary> /// 发布地址 /// </summary> public string PublishAddress { get; set; } /// <summary> /// 子系统 /// </summary> public string SubSystem { get; set; } #endregion public AppPublish() { } /// <summary> /// AppUpdater构造函数 /// </summary> /// <param name="subsystem">子系统</param> /// <param name="path">配置文件的相对路径</param> /// <param name="publishaddress">发布地址</param> public AppPublish(string subsystem, string path, string publishaddress) { this.SubSystem = subsystem; this.PublishAddress = publishaddress + "/package"; this.LocalPath = path; this.PackagePath = this.LocalPath + "\\" + PackageName; this.MyPublish = ReadPackage(this.PackagePath); if (this.MyPublish != null) this.UpdaterUrl = this.MyPublish.Url + "/" + PackageName; } /// <summary> /// 初始化 /// </summary> public static AuPublish ReadPackage(string path) { try { if (!File.Exists(path)) return null; using (StreamReader sr = new StreamReader(path, System.Text.Encoding.UTF8)) { string json = sr.ReadToEnd(); sr.Close(); return Newtonsoft.Json.JsonConvert.DeserializeObject<AuPublish>(json); } } catch { return null; } } /// <summary> /// 销毁 /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// 销毁 /// </summary> /// <param name="disposing"></param> private void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { component.Dispose(); } CloseHandle(handle); handle = IntPtr.Zero; } disposed = true; } /// <summary> /// 析构函数 /// </summary> ~AppPublish() { Dispose(false); } string TempUpdatePath = string.Empty; /// <summary> /// 检查更新文件 /// </summary> /// <param name="updatePackage"></param> /// <returns></returns> public int CheckForUpdate(out AuPublish updatePackage) { updatePackage = null; if (this.MyPublish == null) return -1; //临时目录 this.TempUpdatePath = Environment.GetEnvironmentVariable("Temp") + "\\" + "_" + this.MyPublish.SHA256 + "\\"; //异常处理 string package = ToolsHelp.DownAutoUpdateFile(this.UpdaterUrl, this.TempUpdatePath, AppPublish.PackageName); //this.DownAutoUpdateFile(tempUpdatePath); if (!File.Exists(package)) { return -1; } updatePackage = ReadPackage(package); if (updatePackage == null) return -1; //有更新 if (updatePackage.No.CompareTo(this.MyPublish.No) > 0) { return 1; } return 0; } /// <summary> /// 通知消息 /// </summary> /// <param name="state"></param> private void NotifyMessage(NotifyMessage state) { if (Notify != null) { Notify.Invoke(this, state); } } /// <summary> /// 是否下载 /// </summary> public bool IsDownLoad = false; /// <summary> /// 是否发布 /// </summary> public bool IsPublish = false; /// <summary> /// 下载文件 /// </summary> /// <param name="upgradeFiles"></param> /// <returns></returns> public string DownUpdateFile(AuPublish upgradeFiles, bool allowPublish = false) { if (upgradeFiles == null) { IsDownLoad = false; return string.Empty; } try { int index = 0; string down = string.Format("{0}{1}/{2}", upgradeFiles.Url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ? "" : "http://", upgradeFiles.Url, upgradeFiles.DownPath); NotifyMessage(new Common.NotifyMessage(NotifyType.StartDown, "开始下载文件")); string tempPath = this.TempUpdatePath + "\\" + upgradeFiles.DownPath; ToolsHelp.CreateDirtory(tempPath); WebRequest webReq = WebRequest.Create(down); WebResponse webRes = webReq.GetResponse(); NotifyMessage(new Common.NotifyMessage(NotifyType.Process, "正在下载[" + upgradeFiles.DownPath + "]文件,请稍后...", 100000)); Stream srm = webRes.GetResponseStream(); Stream outStream = System.IO.File.Create(tempPath); byte[] buffer = new byte[1024]; int l; int startByte = 0; do { l = srm.Read(buffer, 0, buffer.Length); if (l > 0) { startByte += l; outStream.Write(buffer, 0, l); NotifyMessage(new Common.NotifyMessage(NotifyType.UpProcess, index + ":" + Convert.ToInt32((startByte / 100000) * 100).ToString() + "%", l)); } } while (l > 0); outStream.Flush(); outStream.Close(); srm.Close(); index++; IsDownLoad = true; if (allowPublish) return this.Publis(upgradeFiles, tempPath); return tempPath; } catch (WebException ex) { NotifyMessage(new Common.NotifyMessage(NotifyType.Error, "更新文件下载失败", ex)); IsDownLoad = false; return string.Empty; } finally { NotifyMessage(new Common.NotifyMessage(NotifyType.StopDown, "更新完成")); } } /// <summary> /// 发布 /// </summary> /// <param name="auPublish"></param> /// <param name="filePath"></param> /// <returns></returns> public string Publis(AuPublish auPublish, string filePath) { //发布地址转换 auPublish.Url = this.PublishAddress + "/" + this.SubSystem; string targetPath = this.LocalPath + "\\package\\" + this.SubSystem + "\\" + auPublish.DownPath; ToolsHelp.CreateDirtory(targetPath); File.Copy(filePath, targetPath, true); //写发布 StreamWriter swau = new StreamWriter(this.LocalPath + "\\package\\" + this.SubSystem + "\\" + AppPublish.PackageName, false, System.Text.Encoding.UTF8); swau.Write(Newtonsoft.Json.JsonConvert.SerializeObject(auPublish)); swau.Close(); //更新本地包 File.Copy(this.TempUpdatePath + AppPublish.PackageName, this.PackagePath, true); //删除临时目录 System.IO.Directory.Delete(this.TempUpdatePath, true); return targetPath; } } } <file_sep>/Domain/Model/Operator.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Domain.Model { public class Operator : AggregateRoot { /// <summary> /// 登陆名称 /// </summary> public string LoginId { get; set; } /// <summary> /// 密码 /// </summary> public string Password { get; set; } /// <summary> /// 用户名 /// </summary> public string OperName { get; set; } /// <summary> /// 状态 /// </summary> public int State { get; set; } } } <file_sep>/.svn/pristine/c3/c383a470e98019fac9b2a2bc3ad4317457d09beb.svn-base using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Domain { /// <summary> /// 表示继承于该接口的类型是领域实体类。 /// </summary> public interface IEntity { #region Properties /// <summary> /// 序号 /// </summary> long Id { get; set; } /// <summary> /// 获取当前领域实体类的全局唯一标识。 /// </summary> Guid Rid { get; } #endregion } } <file_sep>/TestDomain/Form1.cs using Domain.Model; using Repository.EntityFramework; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace TestDomain { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { var context1 = Infrastructure.ServiceLocator.Instance.GetService<Domain.Repositories.IRepositoryContext>(); Domain.Repositories.IRepositoryContext context = new Repository.EntityFramework.EntityFrameworkRepositoryContext(); EntityFrameworkRepository<Project> project = new EntityFrameworkRepository<Project>(context); project.Add(new Project() { ProjectNo = Guid.NewGuid().ToString(), Name = "小船儿轻轻" }); project.Context.Commit(); } } } <file_sep>/.svn/pristine/42/4253244fcb44529d311665367007bdee4bea8472.svn-base using Microsoft.VisualStudio.TestTools.UnitTesting; using AU.Common.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AU.Common.Utility.Tests { [TestClass()] public class HttpHelperTests { [TestMethod()] public void SendPostRequestTest() { System.Net.HttpStatusCode cod; var rs = HttpHelper.SendGetRequest<string>("http://192.168.5.112:60009/api/SystemServiceDate/info", out cod, 5000); if (cod == System.Net.HttpStatusCode.OK) { dynamic record = Newtonsoft.Json.Linq.JObject.Parse(rs); Newtonsoft.Json.Linq.JObject jb = (record != null && record.State != null) ? record.State : null; if (jb != null && jb["Code"].ToString() == "0") { Newtonsoft.Json.Linq.JArray jmdoel = (record != null && record.Models != null) ? record.Models : null; if (jmdoel != null && jmdoel.Count > 0) { var Project = jmdoel[0]["projectNo"]; } } } Assert.Fail(); } } }<file_sep>/Infrastructure/UnityExtensions/UnityServiceHostBaseExtension.cs using System.ServiceModel; namespace Infrastructure.UnityExtensions { /// <summary> /// Implements the lifetime manager storage for the <see cref="System.ServiceModel.ServiceHostBase"/> extension. /// </summary> public class UnityServiceHostBaseExtension : UnityWcfExtension<ServiceHostBase> { /// <summary> /// Initializes a new instance of the <see cref="UnityServiceHostBaseExtension"/> class. /// </summary> public UnityServiceHostBaseExtension() : base() { } /// <summary> /// Gets the <see cref="UnityServiceHostBaseExtension"/> for the current service host. /// </summary> public static UnityServiceHostBaseExtension Current { get { return OperationContext.Current.Host.Extensions.Find<UnityServiceHostBaseExtension>(); } } } } <file_sep>/.svn/pristine/dc/dc5fd3a4458d34c896b113272e5b1a7ba1af37ba.svn-base using Microsoft.VisualStudio.TestTools.UnitTesting; using AU.Common.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.IO; using System.Net.NetworkInformation; namespace AU.Common.Utility.Tests { [TestClass()] public class ZipUtilityTests { public string password = "123"; [TestMethod()] public void ComTest() { int count = ZipUtility.Compress(@"C:\Users\ftf\Desktop\F6", @"C:\Users\ftf\Desktop\F6.zip", ZipUtility.CompressLevel.Level6, password: password); Assert.IsTrue(count > 0); } [TestMethod()] public void DecompressTest() { bool result = ZipUtility.Decompress(@"C:\Users\ftf\Desktop\F6.zip", @"C:\Users\ftf\Desktop\F62", password); Assert.IsTrue(result); } [TestMethod()] public void FileTest() { var f = File.Open(@"C:\Users\ftf\Desktop\test.txt", FileMode.Open); var f2 = File.Open(@"C:\Users\ftf\Desktop\test2.txt", FileMode.OpenOrCreate); byte[] buff = new byte[1024]; int count = 0; do { count = f.Read(buff, 0, 1024); if (count == 1024) { string b = byteToHexStr(buff); var t = Encoding.UTF8.GetBytes(b); var s = Encoding.UTF8.GetString(t); byte[] temp1 = strToToHexByte(s); f2.Write(temp1, 0, temp1.Length); f2.Flush(); } else if (count > 0) { byte[] temp = new byte[count]; Array.Copy(buff, 0, temp, 0, count); string b = byteToHexStr(temp); var t = Encoding.UTF8.GetBytes(b); var s = Encoding.UTF8.GetString(t); byte[] temp1 = strToToHexByte(s); f2.Write(temp1, 0, temp1.Length); f2.Flush(); } } while (count != 0); f.Close(); f2.Close(); } /// <summary> /// 字节数组转16进制字符串 /// </summary> /// <param name=”bytes”></param> /// <returns></returns> public static string byteToHexStr(byte[] bytes) { string returnStr = ""; if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { returnStr += bytes[i].ToString("x2"); } } return returnStr; } /// <summary> /// 字符串转16进制字节数组 /// </summary> /// <param name=”hexString”></param> /// <returns></returns> public static byte[] strToToHexByte(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; } [TestMethod] public void TestCmd() { Cmd c = new Cmd(); string r = c.Run("ping 192.168.1.1"); string v = c.Run("dir"); string d = c.Run("ping -t 192.168.1.1"); } [TestMethod] public void TestIp() { string gw = GetGateway(); string ip = GetLocalIP(); } [TestMethod] public void TestFile() { string path = @"C:\Program Files\fujica\E7服务器\Manage\OneCardSystem.SyncTokenControl.exe"; try { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { byte[] buff = new byte[1024]; int t = fs.Read(buff, 0, 1024); fs.Close(); } } catch (Exception e) { } } /// <summary> /// 得到本机IP /// </summary> public string GetLocalIP() { //本机IP地址 string strLocalIP = ""; //得到计算机名 string strPcName = Dns.GetHostName(); //得到本机IP地址数组 IPHostEntry ipEntry = Dns.GetHostEntry(strPcName); //遍历数组 foreach (var IPadd in ipEntry.AddressList) { //判断当前字符串是否为正确IP地址 if (IPadd.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { //得到本地IP地址 strLocalIP = IPadd.ToString(); //结束循环 break; } } //返回本地IP地址 return strLocalIP; } /// <summary> /// 得到网关地址 /// </summary> /// <returns></returns> public string GetGateway() { //网关地址 string strGateway = ""; //获取所有网卡 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); //遍历数组 foreach (var netWork in nics) { //单个网卡的IP对象 IPInterfaceProperties ip = netWork.GetIPProperties(); //获取该IP对象的网关 GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses; foreach (var gateWay in gateways) { //如果能够Ping通网关 if (gateWay.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { //得到网关地址 strGateway = gateWay.Address.ToString(); //跳出循环 break; } } //如果已经得到网关地址 if (strGateway.Length > 0) { //跳出循环 break; } } //返回网关地址 return strGateway; } } public class Cmd { public System.Diagnostics.Process MyProcess { get; private set; } public Cmd() { MyProcess = new System.Diagnostics.Process(); //设定程序名 MyProcess.StartInfo.FileName = "cmd.exe"; //关闭Shell的使用 MyProcess.StartInfo.UseShellExecute = false; //重定向标准输入 MyProcess.StartInfo.RedirectStandardInput = true; //重定向标准输出 MyProcess.StartInfo.RedirectStandardOutput = true; //重定向错误输出 MyProcess.StartInfo.RedirectStandardError = true; //设置不显示窗口 MyProcess.StartInfo.CreateNoWindow = true; MyProcess.OutputDataReceived += MyProcess_OutputDataReceived; //执行VER命令 MyProcess.Start(); // Start the asynchronous read of the sort output stream. MyProcess.BeginOutputReadLine(); } private void MyProcess_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) { Console.WriteLine(e.Data); } public string Run(string cmd) { MyProcess.StandardInput.WriteLine(cmd); return ""; } } }<file_sep>/.svn/pristine/a4/a43b2418c31aee3c9c4565f8b3a9ef2cd8e817b0.svn-base //=============================================================================== // This file is based on the Microsoft Data Access Application Block for .NET // For more information please go to // http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp //=============================================================================== using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Collections; using System.IO; namespace OneCardSystem.DAL.DBUtility { /// <summary> /// The SqlHelper class is intended to encapsulate high performance, /// scalable best practices for common uses of SqlClient. /// </summary> public abstract class SqlHelper { //Database connection strings public static string ConnectionStringLocalTransaction = ""; // public static readonly string ConnectionStringInventoryDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString2"].ConnectionString; // public static readonly string ConnectionStringOrderDistributedTransaction = ConfigurationManager.ConnectionStrings["SQLConnString3"].ConnectionString; //public static readonly string ConnectionStringProfile = ConfigurationManager.ConnectionStrings["SQLProfileConnString"].ConnectionString; // Hashtable to store cached parameters private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); /// <summary> /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(ConnectionStringLocalTransaction)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } /// <summary> /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a SqlConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } /// <summary> /// Execute a SqlCommand (that returns no resultset) against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /// <summary> /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="trans">an existing sql transaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /// <summary> /// Execute a SqlCommand that returns a resultset against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a SqlConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>A SqlDataReader containing the results</returns> public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connectionString); // we use a try/catch here because if the method throws an exception we want to // close the connection throw code, because no datareader will exist, hence the // commandBehaviour.CloseConnection will not work try { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { conn.Close(); throw; } } /// <summary> /// 获取数据集 /// </summary> /// <param name="connection">连接</param> /// <param name="cmdType">SQL类型</param> /// <param name="cmdText">指令</param> /// <param name="commandParameters">参数</param> /// <returns></returns> public static DataSet ExecuteTable(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); DataSet dt = new DataSet(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; adapter.Fill(dt); return dt; } /// <summary> /// 获取数据集 /// </summary> /// <param name="cmdType">SQL类型</param> /// <param name="cmdText">指令</param> /// <param name="commandParameters">参数</param> /// <returns>数据集</returns> public static DataTable ExecuteTable(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); DataTable dt = new DataTable(); try { using (SqlConnection connection = new SqlConnection(ConnectionStringLocalTransaction)) { PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; adapter.Fill(dt); } } catch (SqlException e) { throw e; } return dt; } /// <summary> /// 分页存储过程 /// </summary> /// <param name="tblName">TableName</param> /// <param name="strGetFields">Select field</param> /// <param name="fldName">Primary field name</param> /// <param name="PageSize">Page size</param> /// <param name="PageIndex">Page index</param> /// <param name="orderType">SortType, not 0 is DESC</param> /// <param name="strWhere">QueryCodition(Note: Don't include where) </param> /// <param name="totalCount">Total Count</param> /// <returns>DataSet</returns> public static DataSet ExecutePage(string tblName, string strGetFields, string fldName, int PageSize, int PageIndex, bool orderType, string strWhere, out int totalCount) { DataSet ds = new DataSet(); try { using (SqlConnection conn = new SqlConnection(ConnectionStringLocalTransaction)) { SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SetPageParams(cmd); cmd.Parameters[0].Value = tblName; cmd.Parameters[1].Value = strGetFields; cmd.Parameters[2].Value = fldName; cmd.Parameters[3].Value = PageSize; cmd.Parameters[4].Value = PageIndex; cmd.Parameters[5].Value = orderType ? 1 : 0; cmd.Parameters[6].Value = strWhere; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "sp_ReacordPage"; cmd.CommandTimeout = 180; SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; DataSet source = new DataSet(); adapter.Fill(ds); object o = cmd.Parameters["@total"].Value; totalCount = (o == null || o == DBNull.Value) ? 0 : System.Convert.ToInt32(o); } } catch (SqlException e) { throw e; } return ds; } /// <summary> /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); using (SqlConnection connection = new SqlConnection(ConnectionStringLocalTransaction)) { connection.Open(); SqlTransaction sqlTran = connection.BeginTransaction(); try { PrepareCommand(cmd, connection, sqlTran, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); //cmd.Parameters.Clear(); sqlTran.Commit(); return val; } catch (Exception e) { sqlTran.Rollback(); throw e; } } } /// <summary> /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a SqlConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); using (SqlConnection connection = new SqlConnection(connectionString)) { PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } /// <summary> /// Execute a SqlCommand that returns the first column of the first record against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } /// <summary> /// add parameter array to the cache /// </summary> /// <param name="cacheKey">Key to the parameter cache</param> /// <param name="cmdParms">an array of SqlParamters to be cached</param> public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters) { parmCache[cacheKey] = commandParameters; } /// <summary> /// Retrieve cached parameters /// </summary> /// <param name="cacheKey">key used to lookup parameters</param> /// <returns>Cached SqlParamters array</returns> public static SqlParameter[] GetCachedParameters(string cacheKey) { SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey]; if (cachedParms == null) return null; SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length]; for (int i = 0, j = cachedParms.Length; i < j; i++) clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms; } /// <summary> /// Prepare a command for execution /// </summary> /// <param name="cmd">SqlCommand object</param> /// <param name="conn">SqlConnection object</param> /// <param name="trans">SqlTransaction object</param> /// <param name="cmdType">Cmd type e.g. stored procedure or text</param> /// <param name="cmdText">Command text, e.g. Select * from Products</param> /// <param name="cmdParms">SqlParameters to use in the command</param> private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = cmdType; if (cmdParms != null) { foreach (SqlParameter parm in cmdParms) cmd.Parameters.Add(parm); } } /// <summary> /// 设置分页存储过程 /// </summary> /// <param name="cmd">SQL Command</param> private static void SetPageParams(SqlCommand cmd) { cmd.Parameters.Add(new SqlParameter("@tblName", SqlDbType.VarChar, 255)); cmd.Parameters.Add(new SqlParameter("@strGetFields", SqlDbType.VarChar, 1000)); cmd.Parameters.Add(new SqlParameter("@fldName", SqlDbType.VarChar, 255)); cmd.Parameters.Add(new SqlParameter("@PageSize", SqlDbType.Int)); cmd.Parameters.Add(new SqlParameter("@PageIndex", SqlDbType.Int)); cmd.Parameters.Add(new SqlParameter("@OrderType", SqlDbType.Bit)); cmd.Parameters.Add(new SqlParameter("@strWhere", SqlDbType.VarChar, 1500)); SqlParameter param = new SqlParameter("@total", SqlDbType.Int); param.Direction = ParameterDirection.Output; cmd.Parameters.Add(param); } /// <summary> /// 数据库备份脚本 /// 要求当前连接为master /// </summary> public static readonly string BackupDatabaseSQL = "BACKUP DATABASE {0} TO DISK = '{1}.bak' "; public static readonly string RestoreDatabaseSQL = "RESTORE DATABASE {0} FROM DISK = '{1}'"; public static readonly string SPIDSQL = "SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='{0}'"; public static readonly string KILLSPID = "KILL {0}"; } }<file_sep>/.svn/pristine/84/84d9a785c6085733e5434bf0aa646d0cd6230cdc.svn-base using System; using System.Collections.Generic; using System.Text; namespace AU.Common { /// <summary> /// 命令类别 /// </summary> public class CommandType { /// <summary> /// 心跳 /// </summary> public static readonly string HEART = "HEART"; /// <summary> /// 登陆 /// </summary> public static readonly string LOGIN = "LOGIN"; /// <summary> /// 会话 /// </summary> public static readonly string SESSION = "SESSION"; /// <summary> /// 服务器更新通知 /// </summary> public static readonly string AUVERSION = "AUVERSION"; /// <summary> /// 中转命令 /// </summary> public static readonly string TRANSFER = "TRANSFER"; /// <summary> /// 指定中转命令 /// </summary> public static readonly string TRANSFERONE = "TRANSFERONE"; /// <summary> /// 终端指令 /// </summary> public static readonly string TERMINAL = "TERMINAL"; /// <summary> /// 资源指令 /// </summary> public static readonly string RESOURCE = "RESOURCE"; /// <summary> /// 脚本指令 /// </summary> public static readonly string SCRIPT = "SCRIPT"; /// <summary> /// 错误 /// </summary> public static readonly string ERROR = "ERROR"; /// <summary> /// 控制 /// </summary> public static readonly string CONTROLL = "CONTROLL"; } } <file_sep>/.svn/pristine/91/9158bda9e6095c3a4359943a4b75a9fcf87d5b2a.svn-base using Newtonsoft.Json; using System; using System.IO; using System.Net; using System.Text; namespace AU.Common.Utility { public static class HttpHelper { ///// <summary> ///// Send a GET request to the specified resource URL and return and object of type T ///// </summary> public static T SendGetRequest<T>(string url) { WebClient wc = new WebClient(); wc.UseDefaultCredentials = true; string response = wc.DownloadString(url); if (typeof(T) == typeof(string)) return (T)Convert.ChangeType(response, typeof(T)); return JsonConvert.DeserializeObject<T>(response); } /// <summary> /// Download a binary file at the specified URL and return a byte array /// </summary> public static byte[] DownloadBinaryFile(string resourceUrl) { var filePath = string.Format("{0}", DateTime.Now.ToString("yyyy.MM.dd.hh.mm.ss.ff")); DownloadBinaryFile(resourceUrl, filePath); byte[] file = File.ReadAllBytes(filePath); File.Delete(filePath); return file; } /// <summary> /// Download a binary file at the specified URL and save it to the destination path /// </summary> public static void DownloadBinaryFile(string resourceUrl, string destinationFilePath) { using (var client = new WebClient()) { client.DownloadFile(resourceUrl, destinationFilePath); } } /// <summary> /// Send a POST request with object of type T in the body and return true if response status code = 200 /// </summary> public static bool SendPostRequest<T>(string resourceUrl, T objectToPost, string encodingName = "utf-8") { HttpWebRequest http = (HttpWebRequest)WebRequest.Create(new Uri(resourceUrl)); http.Accept = "application/json"; http.ContentType = "application/json"; http.Method = "POST"; string parsedContent = JsonConvert.SerializeObject(objectToPost); Encoding encoding = Encoding.GetEncoding(encodingName); Byte[] bytes = encoding.GetBytes(parsedContent); Stream newStream = http.GetRequestStream(); newStream.Write(bytes, 0, bytes.Length); newStream.Close(); HttpWebResponse response = (HttpWebResponse)http.GetResponse(); return response.StatusCode == HttpStatusCode.OK; } /// <summary> /// Send a POST request with object of type J in the body and return and object of type T /// </summary> public static T SendPostRequest<T, J>(string resourceUrl, J objectToPost, string encodingName = "utf-8") { var http = (HttpWebRequest)WebRequest.Create(new Uri(resourceUrl)); http.Accept = "application/json"; http.ContentType = "application/json"; http.Method = "POST"; string parsedContent = JsonConvert.SerializeObject(objectToPost); Encoding encoding = Encoding.GetEncoding(encodingName); Byte[] bytes = encoding.GetBytes(parsedContent); Stream newStream = http.GetRequestStream(); newStream.Write(bytes, 0, bytes.Length); newStream.Close(); var response = http.GetResponse(); var stream = response.GetResponseStream(); var sr = new StreamReader(stream); var content = sr.ReadToEnd(); return JsonConvert.DeserializeObject<T>(content); } public static T SendGetRequest<T>(string resourceUrl, out HttpStatusCode code, int timeOut = 5000) { var http = (HttpWebRequest)WebRequest.Create(new Uri(resourceUrl)); http.Accept = "application/json"; http.ContentType = "application/json"; http.Method = "GET"; http.Timeout = timeOut; string content = string.Empty; try { System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)http.GetResponse(); code = response.StatusCode; //response.StatuCode var stream = response.GetResponseStream(); var sr = new StreamReader(stream); content = sr.ReadToEnd(); } catch (WebException we) { if (we.Status == WebExceptionStatus.Timeout) code = HttpStatusCode.GatewayTimeout; else code = ((System.Net.HttpWebResponse)we.Response).StatusCode; content = we.Message; } catch (Exception e) { code = HttpStatusCode.GatewayTimeout; content = e.Message; } if (typeof(T) == typeof(string)) return (T)Convert.ChangeType(content, typeof(T)); return JsonConvert.DeserializeObject<T>(content); } /// <summary> /// Get a valid url for the provided base url and query string. Prevents issues when the trailing slash is missing. /// </summary> public static string GetUrl(string baseUrl, string queryString) { if (string.IsNullOrEmpty(baseUrl)) return string.Empty; var uriBuilder = new UriBuilder(baseUrl); uriBuilder.Query = queryString; return uriBuilder.ToString(); } /// <summary> /// Get a valid url for the provided base url, path, and query string. Prevents issues when the trailing slash is missing. /// </summary> public static string GetUrl(string baseUrl, string path, string queryString) { if (string.IsNullOrEmpty(baseUrl)) return string.Empty; var uriBuilder = new UriBuilder(baseUrl); uriBuilder.Path = path; uriBuilder.Query = queryString; return uriBuilder.ToString(); } ///// <summary> ///// post请求 ///// </summary> ///// <param name="url">服务端api地址</param> ///// <param name="verb">控制器地址</param> ///// <param name="requestJson">请求参数</param> ///// /// <returns></returns> //public static string HttpPost(string url, string verb, string requestJson) //{ // HttpClient client = null; // bool isUrl = string.IsNullOrEmpty(url); // if (KeepAlive && isUrl) // { // client = _client; // } // else // { // client = new HttpClient(); // client.Timeout = TimeSpan.FromMilliseconds(TimeOut); // client.BaseAddress = new Uri(new Uri(isUrl ? ApiUrl : url), "Api/"); // } // if (IsAuthentication) // { // client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", GetAccessToken(url)); // } // HttpContent content = new StringContent(requestJson); // content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); // string result = ""; // try // { // HttpResponseMessage hrm = client.PostAsync(verb, content).Result; // result = hrm.Content.ReadAsStringAsync().Result; // } // catch (Exception ex) // { // if (log.IsErrorEnabled) // log.Error("Post请求 [" + verb + "] 参数 [" + requestJson + "] 失败", ex); // } // return result; //} ///// <summary> ///// Get 请求 ///// </summary> ///// <param name="url">服务器地址</param> ///// <param name="verb">请求地址</param> ///// <returns>请求结果</returns> //public static string HttpGet(string url, string verb) //{ // HttpClient client = null; // bool isUrl = string.IsNullOrEmpty(url); // if (KeepAlive && isUrl) // { // client = _client; // } // else // { // client = new HttpClient(); // client.Timeout = TimeSpan.FromMilliseconds(TimeOut); // client.BaseAddress = new Uri(new Uri(isUrl ? ApiUrl : url), "Api/"); // } // if (IsAuthentication) // { // client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", GetAccessToken(url)); // } // string result = ""; // try // { // HttpResponseMessage hrm = client.GetAsync(verb).Result; // result = hrm.Content.ReadAsStringAsync().Result; // } // catch (Exception err) // { // if (log.IsErrorEnabled) // log.Error("Get请求 [" + verb + "] ", err); // } // return result; //} } } <file_sep>/.svn/pristine/23/234f61703648636ed13cd47929ab453aea7512e5.svn-base using System; using System.Collections.Generic; using System.Text; namespace AU.Common { /// <summary> /// 客户端实体 /// </summary> public class SessionModel { /// <summary> /// 客户端编号 /// </summary> public string SessionId { get; set; } /// <summary> /// 客户端版本 /// </summary> public string Version { get; set; } /// <summary> /// 客户端名称 /// </summary> public string Name { get; set; } /// <summary> /// 客户端IP /// </summary> public string RemoteEndPoint { get; set; } } } <file_sep>/.svn/pristine/45/45bd46a8f5efb189b948b794b526b5958b29e6e8.svn-base using System.ServiceModel; namespace Infrastructure.UnityExtensions { /// <summary> /// Unity lifetime manager to support <see cref="System.ServiceModel.ServiceHostBase"/>. /// </summary> public class UnityServiceHostBaseLifetimeManager : UnityWcfLifetimeManager<ServiceHostBase> { /// <summary> /// Initializes a new instance of the <see cref="UnityServiceHostBaseLifetimeManager"/> class. /// </summary> public UnityServiceHostBaseLifetimeManager() : base() { } /// <summary> /// Returns the appropriate extension for the current lifetime manager. /// </summary> /// <returns>The registered extension for the current lifetime manager, otherwise, null if the extension is not registered.</returns> protected override UnityWcfExtension<ServiceHostBase> FindExtension() { return UnityServiceHostBaseExtension.Current; } } } <file_sep>/AuClient/MyBootstrapper.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AuClient { /// <summary> /// 配置 /// </summary> public class MyBootstrapper : Nancy.DefaultNancyBootstrapper { protected override void ConfigureConventions(Nancy.Conventions.NancyConventions nancyConventions) { base.ConfigureConventions(nancyConventions); nancyConventions.StaticContentsConventions.Add(Nancy.Conventions.StaticContentConventionBuilder.AddDirectory("package")); } } } <file_sep>/AU.Monitor.Client/FakeReceiveFilter.cs using AU.Monitor.Client.Extensions; using SuperSocket.ProtoBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AU.Monitor.Client { public class FakeReceiveFilter : TerminatorReceiveFilter<StringPackageInfo> { public System.Text.Encoding MessageEncoding { get; private set; } public FakeReceiveFilter(System.Text.Encoding m_Encoding, string terminator = "\r\n") : base(m_Encoding.GetBytes(terminator)) { this.MessageEncoding = m_Encoding; } public override StringPackageInfo ResolvePackage(IBufferStream bufferStream) { var buffer = bufferStream.Read(); string msg = MessageEncoding.GetString(buffer); return new StringPackageInfo(msg.Substring(0, msg.Length - 2), new BasicStringParser(":", ",")); } } } <file_sep>/.svn/pristine/3b/3bf1a44bc82d6a5a29ab1ecddd94f937da4b6645.svn-base using System; using System.Collections.Generic; using System.IO; using System.Text; namespace AU.Common { public class AuPackage { /// <summary> /// 配置名称 /// </summary> public static readonly string PackageName = "aupackage.json"; /// <summary> /// 本地配置路径 /// </summary> public string LocalPath { get; protected set; } /// <summary> /// 本地包路径 /// </summary> public string PackagePath { get; protected set; } /// <summary> /// 本地包配置 /// </summary> public AuList LocalAuList { get; protected set; } /// <summary> /// 子系统 /// </summary> public string SubSystem { get; protected set; } /// <summary> /// 初始化本地路径 /// </summary> /// <param name="localPath">本地配置目录</param> public AuPackage(string localPath, string subsystem) { this.SubSystem = subsystem; this.LocalPath = localPath; this.PackagePath = System.IO.Path.Combine(this.LocalPath, PackageName); this.LocalAuList = ReadPackage(this.PackagePath); } public void SetPackage(AuList au, string subsystem) { this.SubSystem = subsystem; this.LocalAuList = au; } /// <summary> /// 初始化 /// </summary> public AuList ReadPackage(string path) { try { if (!File.Exists(path)) return null; using (StreamReader sr = new StreamReader(path, Encoding.UTF8)) { string json = sr.ReadToEnd(); sr.Close(); return Newtonsoft.Json.JsonConvert.DeserializeObject<AuList>(json); } } catch { return null; } } } } <file_sep>/AU.Common/AuApplication.cs using System; using System.Collections.Generic; using System.Text; namespace AU.Common { /// <summary> /// 主应用详情 /// </summary> public class AuApplication { /// <summary> /// 更新完成启动方式: 0=不启动 1=启动 /// </summary> public int StartType { get; set; } /// <summary> /// 启动参数 /// </summary> public string StartArgs { get; set; } /// <summary> /// 关闭类型 0=进城关闭 1=参数关闭 /// </summary> public int CloseType { get; set; } /// <summary> /// 关闭参数 /// </summary> public string CloseArgs { get; set; } /// <summary> /// 应用编号 /// </summary> public string ApplicationId { get; set; } /// <summary> /// 入口点 /// </summary> public string EntryPoint { get; set; } /// <summary> /// 位置 /// </summary> public string Location { get; set; } /// <summary> /// 主版本 /// </summary> public string Version { get; set; } } } <file_sep>/AuWriter/Modules/ChannelModule.cs using Nancy; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AuWriter.Modules { public class ChannelModule : NancyModule { public ChannelModule() { Get["/Channel/test"] = args => { return View["test"]; }; } } } <file_sep>/.svn/pristine/47/476b95112b7147607d8e5696affa6b94143ccbc8.svn-base using System; /// <summary> /// 文件功能描述:涉及到文件管理的指令-"所有磁盘"指令类。 /// </summary> namespace AU.Common.Codes { /// <summary> /// "所有磁盘"指令类(作为序列化指令在网络上传输) /// </summary> [Serializable] public class DisksCode : BaseCode { private DiskStruct[] disks; /// <summary> /// 磁盘数组 /// </summary> public DiskStruct[] Disks { get { return disks; } set { disks = value; } } public DisksCode() { base.Head = CodeHead.SEND_DISKS; } } } <file_sep>/Events/Bus/IEventBus.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Events.Bus { public interface IEventBus : IBus { } } <file_sep>/.svn/pristine/56/566051553cf84cc00f38fecc67d782fc167c10e0.svn-base using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Text.RegularExpressions; namespace AU.Common.Utility { /// <summary> /// IP辅助类 /// </summary> public class IpHelp { /// <summary> /// 得到本机IP /// </summary> public static string GetLocalIP() { //本机IP地址 string strLocalIP = ""; //得到计算机名 string strPcName = Dns.GetHostName(); //得到本机IP地址数组 IPHostEntry ipEntry = Dns.GetHostEntry(strPcName); //遍历数组 foreach (var IPadd in ipEntry.AddressList) { //判断当前字符串是否为正确IP地址 if (IPadd.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { //得到本地IP地址 strLocalIP = IPadd.ToString(); //结束循环 break; } } //返回本地IP地址 return strLocalIP; } /// <summary> /// 得到网关地址 /// </summary> /// <returns></returns> public static string GetGateway() { //网关地址 string strGateway = ""; //获取所有网卡 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); //遍历数组 foreach (var netWork in nics) { //单个网卡的IP对象 IPInterfaceProperties ip = netWork.GetIPProperties(); //获取该IP对象的网关 GatewayIPAddressInformationCollection gateways = ip.GatewayAddresses; foreach (var gateWay in gateways) { //如果能够Ping通网关 if (IsPingIP(gateWay.Address.ToString())) { //得到网关地址 strGateway = gateWay.Address.ToString(); //跳出循环 break; } } //如果已经得到网关地址 if (strGateway.Length > 0) { //跳出循环 break; } } //返回网关地址 return strGateway; } /// <summary> /// 判断是否为正确的IP地址 /// </summary> /// <param name="strIPadd">需要判断的字符串</param> /// <returns>true = 是 false = 否</returns> public static bool IsRightIP(string strIPadd) { //利用正则表达式判断字符串是否符合IPv4格式 if (Regex.IsMatch(strIPadd, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")) { //根据小数点分拆字符串 string[] ips = strIPadd.Split('.'); if (ips.Length == 4 || ips.Length == 6) { //如果符合IPv4规则 if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256) //正确 return true; //如果不符合 else //错误 return false; } else //错误 return false; } else //错误 return false; } /// <summary> /// 尝试Ping指定IP是否能够Ping通 /// </summary> /// <param name="strIP">指定IP</param> /// <returns>true 是 false 否</returns> public static bool IsPingIP(string strIP) { try { //创建Ping对象 Ping ping = new Ping(); //接受Ping返回值 PingReply reply = ping.Send(strIP, 1000); //Ping通 return true; } catch { //Ping失败 return false; } } /// <summary> /// 验证 IPEndPoint 合法性 /// </summary> /// <param name="address"></param> /// <returns></returns> public static bool IsValidIPEndPoint(string address) { string[] p = address.Split(':'); if (p.Length < 2) return false; IPAddress ip; if (!IPAddress.TryParse(p[0], out ip)) return false; int port; if (!int.TryParse(p[1], out port)) return false; return true; } } } <file_sep>/.svn/pristine/c1/c1bf8c1602f0c781b55d4841206e52ef0efd4ab8.svn-base using System; using System.Collections.Generic; using System.Text; namespace AU.Common.Utility { public class CmdUtility { /// <summary> /// 进程 /// </summary> public System.Diagnostics.Process MyProcess { get; private set; } /// <summary> /// 应用程序名称 /// </summary> /// <param name="application"></param> public CmdUtility(string application = "cmd.exe", params string[] args) { MyProcess = new System.Diagnostics.Process(); //设定程序名 MyProcess.StartInfo.FileName = application; MyProcess.StartInfo.Arguments = args?.Length > 0 ? args[0] : ""; //关闭Shell的使用 MyProcess.StartInfo.UseShellExecute = false; //重定向标准输入 MyProcess.StartInfo.RedirectStandardInput = true; //重定向标准输出 MyProcess.StartInfo.RedirectStandardOutput = true; //重定向错误输出 MyProcess.StartInfo.RedirectStandardError = true; //设置不显示窗口 MyProcess.StartInfo.CreateNoWindow = true; //执行VER命令 MyProcess.Start(); // Start the asynchronous read of the sort output stream. MyProcess.BeginOutputReadLine(); MyProcess.BeginErrorReadLine(); } /// <summary> /// 执行命令 /// </summary> /// <param name="cmd"></param> public void Run(string cmd) { if (MyProcess != null) MyProcess.StandardInput.WriteLine(cmd); } /// <summary> /// 关闭 /// </summary> public void Close() { if (MyProcess == null) return; MyProcess.Close(); MyProcess.Dispose(); } } } <file_sep>/.svn/pristine/c2/c2fce644e5da59011bb35762288f71b0d0814aa2.svn-base using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AuUpdate { public class AuUpdateHelp { public string ApplicationName { get; protected set; } public AuUpdateHelp(string applicationName) { this.ApplicationName = applicationName; } /// <summary> /// 关闭客户端 /// </summary> /// <param name="msg"></param> /// <returns></returns> public bool CloseAuClient(out string msg) { msg = string.Empty; try { var process = System.Diagnostics.Process.GetProcessesByName(this.ApplicationName); if (process != null) foreach (var p in process) { for (int i = 0; i < p.Threads.Count; i++) p.Threads[i].Dispose(); p.Kill(); } System.Threading.Thread.Sleep(3000); } catch (Exception e) { msg = e.Message; return false; } return true; } /// <summary> /// 创建AuClient( /// </summary> /// <param name="path"></param> public bool CreateAuClient(string path) { var process = System.Diagnostics.Process.GetProcessesByName(this.ApplicationName); if (process.Length == 0 && System.IO.File.Exists(path)) { try { System.Diagnostics.ProcessStartInfo processInfo = new System.Diagnostics.ProcessStartInfo(); processInfo.FileName = path; //processInfo.Verb = "runas"; processInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(path); processInfo.UseShellExecute = false; //processInfo.CreateNoWindow = true; var proc = System.Diagnostics.Process.Start(processInfo); return true; } catch (Exception e) { Console.WriteLine(DateTime.Now.ToString() + ":" + e); } } else { Console.WriteLine(DateTime.Now.ToString() + ":" + this.ApplicationName + "进程已存在!"); } return false; } public bool Upgrade(string filepath, string runpath) { string err = string.Empty; if (!CloseAuClient(out err)) { Console.WriteLine(DateTime.Now.ToString() + ":" + "关闭进程[" + this.ApplicationName + "]失败," + err); return false; } try { System.IO.File.Copy(filepath, runpath, true); //启动服务 return true; } catch (Exception e) { Console.WriteLine(DateTime.Now.ToString() + ":" + e); return false; } } } } <file_sep>/.svn/pristine/02/0200647ec4a9450677ea3410974a45b06e5e9886.svn-base using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AU.Monitor.Server { /// <summary> /// 中转指令 /// </summary> public class TransferPackage { /// <summary> /// 指令 /// </summary> public string Cmd { get; set; } /// <summary> /// 消息内容 /// </summary> public string Message { get; set; } /// <summary> /// 路由 > /// </summary> public string[] Route { get; set; } /// <summary> /// 路由节点 /// </summary> public int RouteIndex { get; set; } /// <summary> /// 附加信息 /// </summary> public string Attachment { get; set; } } } <file_sep>/.svn/pristine/70/705a029ad3af144cf018a8289860cd8ccb94846b.svn-base using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Infrastructure.Transactions { internal sealed class SuppressedTransactionCoordinator : TransactionCoordinator { public SuppressedTransactionCoordinator(params IUnitOfWork[] unitOfWorks) : base(unitOfWorks) { } } } <file_sep>/AU.Common/Utility/ZipUtility.cs using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; namespace AU.Common.Utility { public class ZipUtility { /// <summary> /// 缓冲区 /// </summary> public const int BUFFER_SIZE = 2048; #region CompressLevel // 0 - store only to 9 - means best compression public enum CompressLevel { Store = 0, Level1, Level2, Level3, Level4, Level5, Level6, Level7, Level8, Best } #endregion /// <summary> /// 压缩 /// </summary> /// <param name="source">源</param> /// <param name="tartgetfile">目标</param> /// <param name="level">压缩级别</param> /// <param name="password">密码</param> /// <returns>文件数</returns> public static int Compress(string source, string tartgetfile, CompressLevel level = CompressLevel.Level6, string password = "") { int count = 0; Directory.CreateDirectory(Path.GetDirectoryName(tartgetfile)); using (ZipOutputStream s = new ZipOutputStream(File.Create(tartgetfile))) { //Specify Password if (password != null && password.Trim().Length > 0) { s.Password = <PASSWORD>; } s.SetLevel(Convert.ToInt32(level)); count += Compress(source, s, source); s.Finish(); s.Close(); } return count; } /// <summary> /// 压缩 /// </summary> /// <param name="source">源目录</param> /// <param name="s">ZipOutputStream对象</param> /// <param name="basepath">根目录</param> /// <returns>文件数</returns> public static int Compress(string source, ZipOutputStream s, string basepath = "") { int count = 0; string[] filenames = Directory.GetFileSystemEntries(source); foreach (string file in filenames) { if (Directory.Exists(file)) { count += Compress(file, s, basepath); //递归压缩子文件夹 } else { using (FileStream fs = File.OpenRead(file)) { byte[] buffer = new byte[2 * BUFFER_SIZE]; //ZipEntry entry = new ZipEntry(file.Replace(Path.GetPathRoot(file), "")); //此处去掉盘符,如D:\123\1.txt 去掉D: ZipEntry entry = new ZipEntry(file.Replace(basepath, "").TrimStart(new char[] { '\\', '/' })); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } count++; } return count; } /// <summary> /// 解压缩 /// </summary> /// <param name="sourceFile">源文件</param> /// <param name="targetPath">目标</param> /// <param name="password">密码</param> /// <returns></returns> public static bool Decompress(string sourceFile, string targetPath, string password = "") { if (!File.Exists(sourceFile)) { throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile)); } if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } using (var s = new ZipInputStream(File.OpenRead(sourceFile))) { //Specify Password if (password != null && password.Trim().Length > 0) { s.Password = password; } ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { if (theEntry.IsDirectory) continue; string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name)); string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name)); if (!Directory.Exists(directorName)) { Directory.CreateDirectory(directorName); } if (!String.IsNullOrEmpty(fileName)) { using (FileStream streamWriter = File.Create(fileName)) { int size = BUFFER_SIZE; byte[] data = new byte[size]; while (size > 0) { size = s.Read(data, 0, data.Length); streamWriter.Write(data, 0, size); } } } } } return true; } /// <summary> /// 解压缩 /// </summary> /// <param name="sourceFile">源文件</param> /// <param name="targetPath">目标</param> /// <param name="password">密码</param> /// <returns></returns> public static string DecompressFile(string sourceFile, string targetFile, Encoding en, string password = "") { string result = string.Empty; if (!File.Exists(sourceFile)) { throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile)); } using (var s = new ZipInputStream(File.OpenRead(sourceFile))) { //Specify Password if (password != null && password.Trim().Length > 0) { s.Password = <PASSWORD>; } ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { if (theEntry.IsDirectory || !Path.GetFileName(theEntry.Name).Equals(targetFile, StringComparison.InvariantCultureIgnoreCase)) continue; StreamReader sr = new StreamReader(s, en); result = sr.ReadToEnd(); break; //byte[] buff = new byte[s.Length]; //s.Read(buff, 0, buff.Length); //return buff; } } return result; } } }<file_sep>/.svn/pristine/b2/b2480c69dc086835953214cb8260cb957979437f.svn-base using System.ServiceModel; namespace Infrastructure.UnityExtensions { /// <summary> /// Implements the lifetime manager storage for the <see cref="System.ServiceModel.OperationContext"/> extension. /// </summary> public class UnityOperationContextExtension : UnityWcfExtension<OperationContext> { /// <summary> /// Initializes a new instance of the <see cref="UnityOperationContextExtension"/> class. /// </summary> public UnityOperationContextExtension() : base() { } /// <summary> /// Gets the <see cref="UnityOperationContextExtension"/> for the current operation context. /// </summary> public static UnityOperationContextExtension Current { get { return OperationContext.Current.Extensions.Find<UnityOperationContextExtension>(); } } } } <file_sep>/.svn/pristine/dd/dd3bdce158061c23bf97b846d128aa1f608ecd5e.svn-base using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; namespace Au.Service { partial class AuGuardService : ServiceBase { public AuGuardService() { InitializeComponent(); } private bool IsRun = true; private System.Threading.Thread task = null; protected override void OnStart(string[] args) { System.IO.StreamWriter sw = new System.IO.StreamWriter("D:\\log.txt", true); try { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start."); sw.WriteLine("par:" + string.Join(",", args)); string runpath = string.Empty; //string lo = System.Reflection.Assembly.GetCallingAssembly().Location; //sw.WriteLine(lo); switch (args?.Length > 0 ? args[0].ToLower() : "") { case "-u": case "/u": { //升级 string filepath = args?[1]; if (!System.IO.File.Exists(filepath)) { sw.WriteLine(filepath + "不存在"); break; } runpath = args?[2]; if (!System.IO.File.Exists(runpath)) { sw.WriteLine(runpath + "不存在"); break; } string err = string.Empty; if (!CloseAuClient(out err)) { sw.WriteLine("关闭进程[" + Au.Service.Properties.Resources.Core + "]失败," + err); break; } try { System.IO.File.Copy(filepath, runpath, true); //启动服务 } catch (Exception e) { sw.WriteLine(e); } //关闭主进程 } break; case "/s": case "-s": { //已在运行 if (IsRun && task != null && task.ThreadState == System.Threading.ThreadState.Running) { return; } runpath = args?[1]; } break; } if (string.IsNullOrEmpty(runpath) && !System.IO.File.Exists(runpath)) return; task = new System.Threading.Thread(() => { this.IsRun = true; while (IsRun) { //判断是否存在Au.Client CreateAuClient(runpath); System.Threading.Thread.Sleep(1000); } }); task.Start(); } catch (Exception e) { sw.WriteLine(e); //sw.WriteLine("par:" + string.Join(",", args)); } finally { sw.Flush(); sw.Close(); sw.Dispose(); } } protected override void OnStop() { StopTask(); // TODO: 在此处添加代码以执行停止服务所需的关闭操作。 using (System.IO.StreamWriter sw = new System.IO.StreamWriter("D:\\log.txt", true)) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Stop."); sw.Flush(); sw.Close(); sw.Dispose(); } } private void StopTask() { this.IsRun = false; if (task != null) { task.Join(2000); } if (task != null && task.ThreadState == System.Threading.ThreadState.Running) { try { task.Abort(); } catch { } } task = null; } private bool CloseAuClient(out string msg) { msg = string.Empty; try { StopTask(); var process = System.Diagnostics.Process.GetProcessesByName(Au.Service.Properties.Resources.Core); if (process != null) foreach (var p in process) { for (int i = 0; i < p.Threads.Count; i++) p.Threads[i].Dispose(); p.Kill(); } } catch (Exception e) { msg = e.Message; return false; } return true; } /// <summary> /// 创建AuClient( /// </summary> /// <param name="path"></param> private bool CreateAuClient(string path) { var process = System.Diagnostics.Process.GetProcessesByName(Au.Service.Properties.Resources.Core); if (process.Length == 0) { try { System.Diagnostics.ProcessStartInfo processInfo = new System.Diagnostics.ProcessStartInfo(); processInfo.FileName = path; //processInfo.Verb = "runas"; processInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(path); processInfo.UseShellExecute = false; //processInfo.CreateNoWindow = true; var proc = System.Diagnostics.Process.Start(processInfo); } catch (Exception e) { return false; } } return true; } } } <file_sep>/.svn/pristine/37/377b97a49965ab1a94da35c8f94b659cbf5dffd9.svn-base using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Text; using System.Xml; namespace AU.Common.Utility { public static class ConfigUtility { /// <summary> /// Gets the connection string that matches connectionStringName from the specified web.config. /// </summary> /// <param name="webConfigPath">Path to the web.config</param> /// <param name="connectionStringName">Name attribute of the connectionString in the web.config</param> /// <returns></returns> public static string GetConnectionStringFromWebConfig(string webConfigPath, string connectionStringName) { try { var webConfigContents = File.ReadAllText(webConfigPath); using (XmlReader reader = XmlReader.Create(new StringReader(webConfigContents))) { reader.ReadToFollowing("connectionStrings"); using (XmlReader rdr = reader.ReadSubtree()) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { reader.MoveToAttribute("name"); if (reader.Value.ToLower() == connectionStringName.ToLower()) { reader.MoveToAttribute("connectionString"); return reader.Value; } } } } } } catch { } return string.Empty; } public static string GetApiDbConnect(string webConfigPath) { try { XmlDocument doc = new XmlDocument(); doc.Load(webConfigPath); XmlNode node = doc.SelectSingleNode(@"//add[@key='IsCiphertext']"); bool IsCiphertext = "true".Equals(((XmlElement)node).GetAttribute("value")); node = doc.SelectSingleNode(@"//add[@key='DbHelperConnectionString']"); string DbHelperConnectionString = ((XmlElement)node).GetAttribute("value"); if (IsCiphertext) { DbHelperConnectionString = CryptoHelp.DesDecrypt(DbHelperConnectionString, "ftf"); } return DbHelperConnectionString; } catch { return ""; } } /// <summary> /// 获取配置信息 /// </summary> /// <param name="name"></param> /// <returns></returns> public static string GetAddValueFromWebConfig(string webConfigPath, string name) { try { XmlDocument doc = new XmlDocument(); doc.Load(webConfigPath); XmlNode node = doc.SelectSingleNode(@"//add[@key='" + name + "']"); XmlElement ele = (XmlElement)node; return ele.GetAttribute("value"); } catch { return ""; } } /// <summary> /// 更新配置文件信息 /// </summary> /// <param name="name">配置文件字段名称</param> /// <param name="Xvalue">值</param> public static void UpdateAddValueFromWebConfig(string webConfigPath, string name, string Xvalue) { XmlDocument doc = new XmlDocument(); doc.Load(webConfigPath); XmlNode node = doc.SelectSingleNode(@"//add[@key='" + name + "']"); XmlElement ele = (XmlElement)node; ele.SetAttribute("value", Xvalue); doc.Save(webConfigPath); } } } <file_sep>/.svn/pristine/d8/d8a68c9d646d0c8ae66f38999373882df9ff2b85.svn-base using System; using System.Collections.Generic; using System.Web; namespace AU.Common.Utility { public class Logger { public static void LogError(Exception exception, string message, string customerName) { try { string exceptionMessage = exception.Message; if (exception.InnerException != null) exceptionMessage += "/r/n" + exception.InnerException.Message; SendToConsole(message, exceptionMessage); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } public static void LogInfo(string logAction, string logDetail, string customerName) { try { SendToConsole(logAction, logDetail); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } private static void SendToConsole(string logAction, string logDetail) { Console.WriteLine(string.Empty); //Console.WriteLine(string.Format("============= {0} ===============================================", DateTime.Now.ToString("HH:mm:ss:ff"))); Console.WriteLine(string.Format("== {0} ==", DateTime.Now.ToString("HH:mm:ss:ff"))); Console.WriteLine(string.Empty); Console.WriteLine(logAction); Console.WriteLine(logDetail); } } }<file_sep>/.svn/pristine/d4/d44f4f6f27d2b2744774ad4cabeb65e271e55307.svn-base using AU.Common; using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Threading.Tasks; using SuperSocket.SocketBase; using System.Collections.Concurrent; using System.Collections; using AU.Common.Utility; using System.IO; namespace AuClient { /// <summary> /// 包发布 /// </summary> public class AuPublishHelp { /// <summary> /// 监听发布 /// </summary> Nancy.Hosting.Self.NancyHost nancySelfHost = null; /// <summary> /// 取消控制变量 /// </summary> private System.Threading.CancellationTokenSource cts; public Dictionary<string, string> SubSystemDic { get; private set; } private SuperSocket.ClientEngine.EasyClient easyClient = new SuperSocket.ClientEngine.EasyClient(); private ConcurrentQueue<AuPublish> AuPublishQueue = new ConcurrentQueue<AuPublish>(); public MainForm UI = null; /// <summary> /// 升级消息 /// </summary> public ConcurrentQueue<UpgradeMessage> UpgradeMessageQueue = new ConcurrentQueue<UpgradeMessage>(); AppRemotePublish AppRemotePublishConten { get; set; } /// <summary> /// 客户端 /// </summary> public Hashtable SessionTable { get; set; } /// <summary> /// 本地路径 /// </summary> public string LocalPath { get; set; } /// <summary> /// 终端 /// </summary> private Dictionary<string, CmdUtility> DicTerminal = new Dictionary<string, CmdUtility>(); /// <summary> /// 文件哈希 /// </summary> public string Hash256 { get; private set; } /// <summary> /// 日志接口 /// </summary> public log4net.ILog log = log4net.LogManager.GetLogger(typeof(AuPublishHelp)); /// <summary> /// 服务器管理 /// </summary> //MyServiceControll mc = new MyServiceControll(); //public AU.Monitor.Server.MonitorServerHelp ms { get; private set; } /// <summary> /// 构造函数 /// </summary> public AuPublishHelp(MainForm ui) { this.Hash256 = AU.Common.Utility.ToolsHelp.ComputeSHA256(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); this.LocalPath = AppConfig.Current.UpdateConfigPath + "\\package\\"; this.AppRemotePublishConten = new AppRemotePublish(AppConfig.Current.PublishAddress, this.LocalPath); this.UI = ui; if (AppConfig.Current.AllowPublish) { try { nancySelfHost = new Nancy.Hosting.Self.NancyHost(new Uri("http://localhost:" + AppConfig.Current.PublishPort), new MyBootstrapper()); } catch (Exception e) { log.Error(e); //Console.WriteLine(e); } //Server SessionTable = new Hashtable(); AU.Monitor.Server.ServerBootstrap.Init(Ms_NewSessionConnected, Ms_SessionClosed, Ms_NewRequestReceived); //InitSocketServer(); } easyClient.Initialize(new AU.Monitor.Client.FakeReceiveFilter(System.Text.Encoding.UTF8), clienthandler); //mc.Start(System.Reflection.Assembly.GetCallingAssembly().Location); } private System.Collections.Hashtable FilePackage = new System.Collections.Hashtable(); private FileStream Fs; public void clienthandler(SuperSocket.ProtoBase.StringPackageInfo p) { string body = p.Body; string key = p.Key; string[] par = p.Parameters; if (key != body) log.InfoFormat("{0}:{1}", key, body); //Console.WriteLine("{0}:{1}", key, body); else log.Info(key); //Console.WriteLine(key); try { switch (key) { case "AUVERSION": List<AuPublish> aulist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<AuPublish>>(p.Body); if (aulist != null) { foreach (var a in aulist) AuPublishQueue.Enqueue(a); } break; case "SCRIPT": { if (string.IsNullOrEmpty(p.Body) && !this.SubSystemDic.ContainsKey(SystemType.coreserver.ToString())) break; string config = this.SubSystemDic[SystemType.coreserver.ToString()] + "\\Core\\Web.config"; if (System.IO.File.Exists(config)) { string con = AU.Common.Utility.ConfigUtility.GetApiDbConnect(config); if (!string.IsNullOrEmpty(con)) { var cp = Newtonsoft.Json.JsonConvert.DeserializeObject<AU.Monitor.Server.CommandPackage>(p.Body); string result = AuDataBase.RunScriptString(con, cp.Key, cp.Body, cp.Parameters); AU.Monitor.Server.CommandPackage cpackage = new AU.Monitor.Server.CommandPackage() { Key = cp.Key, Body = result, }; this.Send(CommandType.SCRIPT, Newtonsoft.Json.JsonConvert.SerializeObject(cpackage)); } } } break; case "TRANSFER"://通知当前客户端 { this.Transfer(p); } break; case "TRANSFERONE"://通知指定客户端 { this.Transfer(p); } break; case "RESOURCE": { string[] Parameters = null; if (string.IsNullOrEmpty(p.Body)) break; var cp = Newtonsoft.Json.JsonConvert.DeserializeObject<AU.Monitor.Server.CommandPackage>(p.Body); string result = string.Empty; switch (cp.Key) { case "SEND_DISKS": AU.Common.Codes.DisksCode diskcode = IO.GetDisks(); result = Newtonsoft.Json.JsonConvert.SerializeObject(diskcode); break; case "GET_DIRECTORY_DETIAL": AU.Common.Codes.ExplorerCode explorer = new AU.Common.Codes.ExplorerCode(); explorer.Enter(cp.Body); result = Newtonsoft.Json.JsonConvert.SerializeObject(explorer); break; case "GET_FILE_DETIAL": result = AU.Common.Utility.IO.GetFileDetial(cp.Body); break; case "GET_FILE": SendFile(cp.Body); return; case "DELETE_FILE": try { if (System.IO.File.Exists(cp.Body)) System.IO.File.Delete(cp.Body); Parameters = new string[] { "1" }; result = "已删除"; } catch (Exception e) { result = e.Message; Parameters = new string[] { "0" }; } break; } AU.Monitor.Server.CommandPackage cpackage = new AU.Monitor.Server.CommandPackage() { Key = cp.Key, Body = result, Parameters = Parameters, }; this.Send(CommandType.RESOURCE, Newtonsoft.Json.JsonConvert.SerializeObject(cpackage)); } break; case "F": { if (Fs == null) { string path = p.Body; Fs = File.Open(path, FileMode.OpenOrCreate); //发送通知消息 } } break; case "FS": { if (Fs != null) { byte[] buff = AU.Common.Utility.ToolsHelp.HexStringToByte(p.Body); Fs.Write(buff, 0, buff.Length); Fs.Flush(); } //发送通知消息 } return; case "FE": { if (Fs != null) { Fs.Close(); Fs.Dispose(); Fs = null; } } break; case "TERMINAL": { if (string.IsNullOrEmpty(p.Body)) break; var cp = Newtonsoft.Json.JsonConvert.DeserializeObject<AU.Monitor.Server.CommandPackage>(p.Body); string result = string.Empty; switch (cp.Key) { case "START": if (!DicTerminal.ContainsKey(cp.Body)) { var cmd = new CmdUtility(cp.Body, cp.Parameters); cmd.MyProcess.OutputDataReceived += MyProcess_OutputDataReceived; cmd.MyProcess.ErrorDataReceived += MyProcess_ErrorDataReceived; DicTerminal.Add(cp.Body, cmd); } break; case "STOP": if (DicTerminal.ContainsKey(cp.Body)) { DicTerminal[cp.Body].Close(); DicTerminal.Remove(cp.Body); } break; default: if (DicTerminal.ContainsKey(cp.Key)) try { DicTerminal[cp.Key].Run(cp.Body); } catch { DicTerminal[cp.Key].Close(); DicTerminal.Remove(cp.Key); } break; } } break; case "CONTROLL": { if (string.IsNullOrEmpty(p.Body)) break; var cp = Newtonsoft.Json.JsonConvert.DeserializeObject<AU.Monitor.Server.CommandPackage>(p.Body); string result = string.Empty; switch (cp.Key) { case "CLOSE": { AU.Monitor.Server.ServerBootstrap.Close(cp.Body); } break; } } break; } } catch (Exception e) { this.Send(CommandType.ERROR, e.Message); //log log.Error(e); //Console.WriteLine(e); } } private void Transfer(SuperSocket.ProtoBase.StringPackageInfo p) { var cp = Newtonsoft.Json.JsonConvert.DeserializeObject<AU.Monitor.Server.TransferPackage>(p.Body); //中转 if (cp.Route != null && cp.Route.Length > 0 && cp.RouteIndex < cp.Route.Length - 1) { cp.RouteIndex++; //ms.Send(cp.Route[cp.RouteIndex], p.Key, Newtonsoft.Json.JsonConvert.SerializeObject(cp)); AU.Monitor.Server.ServerBootstrap.Send(cp.Route[cp.RouteIndex], p.Key, Newtonsoft.Json.JsonConvert.SerializeObject(cp)); } else { clienthandler(new SuperSocket.ProtoBase.StringPackageInfo(cp.Cmd, cp.Message, cp.Message.Split('&'))); } } public string cmdSpilts = "\r\n"; //单线程操作 private void SendFile(string path) { new System.Threading.Tasks.Task(() => { try { if (!System.IO.File.Exists(path)) return; byte[] sp = System.Text.Encoding.UTF8.GetBytes(cmdSpilts); using (FileStream f = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { easyClient.Send(System.Text.Encoding.UTF8.GetBytes("F:" + f.Length / 1024 + "&" + System.IO.Path.GetFileName(path) + cmdSpilts)); byte[] head = System.Text.Encoding.UTF8.GetBytes("FS:"); int len = 1024; byte[] buff = new byte[len]; int count = 0; do { count = f.Read(buff, 0, len); if (count == len) {//分片包编号后期扩展 var temp = Encoding.UTF8.GetBytes(AU.Common.Utility.ToolsHelp.ByteToHexString(buff)); byte[] send = new byte[head.Length + temp.Length + sp.Length]; //head Array.Copy(head, 0, send, 0, head.Length); //msg Array.Copy(temp, 0, send, head.Length, temp.Length); //sp Array.Copy(sp, 0, send, head.Length + temp.Length, sp.Length); //发送消息 easyClient.Send(send); } else if (count > 0) { //ArraySegment<byte> b = new ArraySegment<byte>(buff, 0, count); byte[] b = new byte[count]; Array.Copy(buff, 0, b, 0, count); var temp = Encoding.UTF8.GetBytes(AU.Common.Utility.ToolsHelp.ByteToHexString(b)); byte[] send = new byte[head.Length + temp.Length + sp.Length]; //head Array.Copy(head, 0, send, 0, head.Length); //msg Array.Copy(temp, 0, send, head.Length, temp.Length); //sp Array.Copy(sp, 0, send, head.Length + temp.Length, sp.Length); //发送消息 easyClient.Send(send); } System.Threading.Thread.Sleep(1); } while (count != 0); f.Close(); f.Dispose(); easyClient.Send(System.Text.Encoding.UTF8.GetBytes("FE:1&传输完成" + cmdSpilts)); } } catch (Exception e) { easyClient.Send(System.Text.Encoding.UTF8.GetBytes("FE:0&传输失败详情," + e.Message + cmdSpilts)); } }).Start(); } /// <summary> /// 发送消息 /// </summary> /// <param name="key">命令</param> /// <param name="body">消息</param> private void Send(string key, string body) { try { byte[] sp = System.Text.Encoding.UTF8.GetBytes(cmdSpilts); string id = Guid.NewGuid().ToString(); string par = "P:" + id + "&"; string message = (key + ":" + body).Replace(cmdSpilts, ""); byte[] b = System.Text.Encoding.UTF8.GetBytes(message); int t = b.Length / 1024; if (t > 0) { byte[] buff; //easyClient.Send(System.Text.Encoding.UTF8.GetBytes(("PS:" + id + cmdSpilts))); for (int i = 0; i <= t; i++) { byte[] head = System.Text.Encoding.UTF8.GetBytes(par + i.ToString() + "&"); if (i == t) { buff = new byte[head.Length + b.Length - i * 1024 + sp.Length]; //head Array.Copy(head, 0, buff, 0, head.Length); //消息体 Array.Copy(b, i * 1024, buff, head.Length, buff.Length - sp.Length - head.Length); Array.Copy(sp, 0, buff, buff.Length - sp.Length, sp.Length); } else { buff = new byte[head.Length + 1024 + sp.Length]; Array.Copy(head, 0, buff, 0, head.Length); Array.Copy(b, i * 1024, buff, head.Length, 1024); Array.Copy(sp, 0, buff, buff.Length - sp.Length, sp.Length); } easyClient.Send(buff); } //发送分包结束 easyClient.Send(System.Text.Encoding.UTF8.GetBytes(("PE:" + id + cmdSpilts))); } else easyClient.Send(System.Text.Encoding.UTF8.GetBytes(message + cmdSpilts)); } catch (Exception e) { log.Error(e); //Console.WriteLine(e); } } private void InitSocketServer() { //ms = new AU.Monitor.Server.MonitorServerHelp(); //var serverConfig = new SuperSocket.SocketBase.Config.ServerConfig //{ // Port = AppConfig.Current.MsPort, // TextEncoding = AppConfig.Current.TextEncoding, // ReceiveBufferSize = AppConfig.Current.ReceiveBufferSize, // MaxConnectionNumber = AppConfig.Current.MaxConnectionNumber, // SendBufferSize = AppConfig.Current.SendBufferSize, // MaxRequestLength = AppConfig.Current.MaxRequestLength // //set the listening port //}; //ms.Init(serverConfig, Ms_NewSessionConnected, Ms_SessionClosed, Ms_NewRequestReceived); SessionTable = new Hashtable(); //ms.ms.Start(); AU.Monitor.Server.ServerBootstrap.Init(Ms_NewSessionConnected, Ms_SessionClosed, Ms_NewRequestReceived); } public System.Net.IPAddress ServerIp { get; protected set; } private void StartSocketClient() { var ips = AppConfig.Current.SocketServer.Split(':'); ServerIp = System.Net.IPAddress.Parse(ips[0]); int port = Convert.ToInt32(ips[1]); System.Threading.Tasks.Task client = new System.Threading.Tasks.Task(() => { int count = 60; while (this.IsUpdateCheckRun) { try { count--; if (!easyClient.IsConnected) { var res = easyClient.ConnectAsync(new System.Net.IPEndPoint(ServerIp, port)); System.Threading.Tasks.Task.WaitAll(res); //推送指令 if (res.Result) { //登陆 //通知服务器 AU.Common.LoginModel lm = new LoginModel(); if (this.SubSystemDic.ContainsKey("coreserver")) { lm = PeculiarHelp.GetProject(); } if (this.SubSystemDic.ContainsKey("vmsclient")) { //获取车场版本 lm.Park = PeculiarHelp.GetVersion(this.SubSystemDic["vmsclient"]); } lm.Version = Application.ProductVersion.ToString(); lm.Password = "ftf"; lm.UserName = "客户端"; this.Send(AU.Common.CommandType.LOGIN, Newtonsoft.Json.JsonConvert.SerializeObject(lm)); System.Threading.Thread.Sleep(10); //通知当前客户端版本 SessionOper(-1, null); } } else if (count % 20 == 0) { //发送心跳包 this.Send(AU.Common.CommandType.HEART, ""); } if (count <= 0) { count = 60; //清理注册表错误数据 AU.Common.Utility.RegistryHelper.DeleteRegist(Microsoft.Win32.Registry.LocalMachine, "SYSTEM\\E7\\", "AuError"); } } catch (Exception ex) { //log log.Error(ex); //Console.WriteLine(ex); } System.Threading.Thread.Sleep(AppConfig.Current.Interval); } }); client.Start(); } /// <summary> /// 新消息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MyProcess_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { //发送消息 this.Send(CommandType.TERMINAL, e.Data); } } private void MyProcess_ErrorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { //发送消息 this.Send(CommandType.TERMINAL, e.Data); } } private void SessionOper(int oper, AU.Monitor.Server.MonitorSession session, AU.Common.SessionModel sm = null) { if (oper == 0) { if (SessionTable.ContainsKey(session.SessionID)) SessionTable.Remove(session.SessionID); } else if (oper == 1) { if (SessionTable.ContainsKey(session.SessionID)) SessionTable[session.SessionID] = sm; else SessionTable.Add(session.SessionID, sm); } //通知服务器 this.Send(AU.Common.CommandType.SESSION, Newtonsoft.Json.JsonConvert.SerializeObject(SessionTable.Values)); } /// <summary> /// 新客户端连接 /// </summary> /// <param name="session"></param> private void Ms_NewSessionConnected(AU.Monitor.Server.MonitorSession session) { log.Info("New Connected ID=[" + session.SessionID + "] IP=" + session.RemoteEndPoint.ToString()); //Console.WriteLine("New Connected ID=[" + session.SessionID + "] IP=" + session.RemoteEndPoint.ToString()); //this.SessionOper(1, session, new SessionModel() //{ // SessionId = session.SessionID, // RemoteEndPoint = session.RemoteEndPoint.ToString(), // Name = "客户端", // Version = "0.0.0.0", //}); session.Send("Welcome to AuClient Socket Server"); } private void Ms_SessionClosed(AU.Monitor.Server.MonitorSession session, SuperSocket.SocketBase.CloseReason value) { this.SessionOper(0, session); log.Info("Session Closed ID=[" + session.SessionID + "] IP=" + session.RemoteEndPoint.ToString() + " Reason=" + value); //Console.WriteLine("Session Closed ID=[" + session.SessionID + "] IP=" + session.RemoteEndPoint.ToString() + " Reason=" + value); } private void Ms_NewRequestReceived(AU.Monitor.Server.MonitorSession session, SuperSocket.SocketBase.Protocol.StringRequestInfo requestInfo) { //中转 //发送分包结束 switch (requestInfo.Key) { case "HEART": case "SESSION": break; case "LOGIN": { var mode = Newtonsoft.Json.JsonConvert.DeserializeObject<AU.Common.LoginModel>(requestInfo.Body);// this.SessionOper(1, session, new SessionModel() { SessionId = session.SessionID, RemoteEndPoint = session.RemoteEndPoint.ToString(), Name = mode == null ? "客户端" : mode.UserName + ":" + mode.Park, Version = mode == null ? "0.0.0.0" : mode.Version, }); } break; case "P": case "F": case "FE": case "FS": easyClient.Send(System.Text.Encoding.UTF8.GetBytes(requestInfo.Key + ":" + requestInfo.Body + cmdSpilts)); break; default: this.Send(requestInfo.Key, requestInfo.Body); break; } //Console.WriteLine("Session Message ID=[" + session.SessionID + "] IP=" + session.RemoteEndPoint.ToString() + "Key= " + requestInfo.Key + " Message=" + requestInfo.Body); } /// <summary> /// 最后读注册表时间 /// </summary> public static DateTime ReadRegistryTime; /// <summary> /// 子系统锁 /// </summary> private object lockSubSystemDic = new object(); /// <summary> /// 读取注册表 /// </summary> public void ReadRegistry() { try { int s = (AppConfig.Current.Interval / 1000) + 1; if (ReadRegistryTime.AddMinutes(s) < DateTime.Now) { ReadRegistryTime = DateTime.Now; //读注册表 lock (lockSubSystemDic) { SubSystemDic = AU.Common.Utility.RegistryHelper.GetRegistrySubs(Microsoft.Win32.Registry.LocalMachine, "SYSTEM\\E7"); if (!SubSystemDic.ContainsKey("auclient")) SubSystemDic.Add(SystemType.auclient.ToString(), System.Reflection.Assembly.GetCallingAssembly().Location); } } } catch (Exception e) { log.Error(e); //Console.WriteLine(e); } } /// <summary> /// 启动 /// </summary> /// <returns>启动结果</returns> public bool Start() { //读注册表 this.ReadRegistry(); //cts = new System.Threading.CancellationTokenSource(); //Task engineTask = new Task(() => Engine(cts.Token), cts.Token); //engineTask.Start(); cts = new System.Threading.CancellationTokenSource(); Task engineTask = new Task(() => UpdateProcess(cts.Token), cts.Token); engineTask.Start(); this.StartUpdateCheck(); if (AppConfig.Current.AllowPublish) { StartResult result = AU.Monitor.Server.ServerBootstrap.Start(); log.InfoFormat("Start result: {0}!", result); //Console.WriteLine("Start result: {0}!", result); nancySelfHost?.Start(); } StartSocketClient(); return true; } /// <summary> /// 关闭 /// </summary> /// <returns></returns> public void Stop() { this.IsUpdateCheckRun = false; if (cts != null) cts.Cancel(); if (AppConfig.Current.AllowPublish) { AU.Monitor.Server.ServerBootstrap.Stop(); log.Info("Stop Au Monitor Server"); //Console.WriteLine("Stop Au Monitor Server"); nancySelfHost?.Stop(); } easyClient.Close(); log.Info("Stop EasyClient"); } public void StartUpdateCheck() { this.IsUpdateCheckRun = true; } private bool IsUpdateCheckRun { get; set; } /// <summary> /// 更新消息到达 /// </summary> public void UpdateProcess(System.Threading.CancellationToken ct) { AuPublish a = null; while (true) { try { if (ct.IsCancellationRequested) break; //读取注册表 this.ReadRegistry(); //检查UI服务是否运行 this.UI.BeginInvoke((MethodInvoker)delegate () { this.UI.CheckRun(); }); if (!this.IsUpdateCheckRun) { System.Threading.Thread.Sleep(AppConfig.Current.Interval); continue; } //通知消息 if (!AuPublishQueue.TryDequeue(out a)) { System.Threading.Thread.Sleep(AppConfig.Current.Interval); continue; } //识别子系统 if (!Enum.IsDefined(typeof(SystemType), a.PublishType)) { System.Threading.Thread.Sleep(AppConfig.Current.Interval); continue; } AuPublish notify = null; ////客户端升级 //if ((int)SystemType.auclient == a.PublishType && !a.SHA256.Equals(this.Hash256, StringComparison.InvariantCultureIgnoreCase)) //{ // //自升级 // //获取升级包 // string file = this.AppRemotePublishConten.DownUpdateFile(SystemType.auclient.ToString(), a, out notify, true); // if (System.IO.File.Exists(file)) // { // //启动自升级 // this.Stop(); // if (du.Start(file, System.Reflection.Assembly.GetCallingAssembly().Location)) // return; // } //} string sub = ((SystemType)a.PublishType).ToString(); //管理及发布? if (!this.SubSystemDic.ContainsKey(sub) && !AppConfig.Current.AllowPublish) { System.Threading.Thread.Sleep(AppConfig.Current.Interval); continue; } //检查升级包 if ((sub == "auclient" && this.Hash256.ToLower() != a.SHA256.ToLower()) || (sub != "auclient" && this.AppRemotePublishConten.CheckForUpdate(sub, a) > 0)) { //获取升级包 string file = this.AppRemotePublishConten.DownUpdateFile(sub, ServerIp?.ToString(), a, out notify, AppConfig.Current.AllowPublish); //显示升级服务 if (this.SubSystemDic.ContainsKey(sub) && System.IO.File.Exists(file)) { //通知消息 UpgradeMessageQueue.Enqueue(new UpgradeMessage() { SubSystem = sub, UpdatePackFile = file, UpgradePath = this.SubSystemDic[sub] }); } } else { notify = AppPublish.ReadPackage(this.LocalPath + "\\" + sub + "\\" + AppPublish.PackageName); //检查服务器和包是否一直 if (sub != "auclient" && this.SubSystemDic.ContainsKey(sub) && notify != null) UpgradeMessageQueue.Enqueue(new UpgradeMessage() { SubSystem = sub, UpdatePackFile = this.LocalPath + "\\" + sub + "\\" + notify.DownPath, UpgradePath = this.SubSystemDic[sub] }); } //通知客户端消息 if (notify != null && AppConfig.Current.AllowPublish) { //ms.Send("", AU.Common.CommandType.AUVERSION, Newtonsoft.Json.JsonConvert.SerializeObject(new List<AuPublish>() { notify })); AU.Monitor.Server.ServerBootstrap.Send("", AU.Common.CommandType.AUVERSION, Newtonsoft.Json.JsonConvert.SerializeObject(new List<AuPublish>() { notify })); } if (ct.IsCancellationRequested) break; } catch (Exception e) { log.Info(e); //Console.WriteLine(e.Message); } System.Threading.Thread.Sleep(AppConfig.Current.Interval); } this.IsUpdateCheckRun = false; } } } <file_sep>/AU.Common/AuList.cs using System; using System.Collections.Generic; using System.Text; namespace AU.Common { public class AuList { public AuList() { this.Files = new List<AuFile>(); this.Application = new AuApplication(); } /// <summary> /// 升级号 /// </summary> public string No { get; set; } /// <summary> /// 描述 /// </summary> public string Description { get; set; } ///// <summary> ///// 更新URL地址 ///// </summary> //public string Url { get; set; } /// <summary> /// 发布类型 0=标准 1=非标 /// </summary> public int PublishType { get; set; } /// <summary> /// 更新类型 -1=允许跳过此版本 0=正常更新 1=强制更新 /// </summary> public int UpdateType { get; set; } /// <summary> /// 最后更新时间 /// </summary> public DateTime LastUpdateTime { get; set; } /// <summary> /// 主应用程序 /// </summary> public AuApplication Application { get; set; } /// <summary> /// 更新文件列表 /// </summary> public List<AuFile> Files { get; set; } } } <file_sep>/Domain/Model/Project.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domain.Model { /// <summary> /// 项目表 /// </summary> public class Project : AggregateRoot { /// <summary> /// 项目编号 /// </summary> public string ProjectNo { get; set; } /// <summary> /// 项目名称 /// </summary> public string Name { get; set; } /// <summary> /// 区域编号 /// </summary> public string ZoneId { get; set; } /// <summary> /// 项目类别 /// </summary> public int ProjectType { get; set; } /// <summary> /// 默认网关 /// </summary> public string GateWay { get; set; } /// <summary> /// 备注 /// </summary> public string Remark { get; set; } /// <summary> /// X坐标 /// </summary> public decimal PositionX { get; set; } /// <summary> /// Y坐标 /// </summary> public decimal PositionY { get; set; } /// <summary> /// 标识 0=标准 1=非标 /// </summary> public int Flag { get; set; } /// <summary> /// 升级状态 /// </summary> public int UpStatus { get; set; } /// <summary> /// 最后更新时间 /// </summary> public DateTime? LastUpdate { get; set; } = DateTime.Today; /// <summary> /// 项目编号 /// </summary> public string Gid { get; set; } } } <file_sep>/MonitorClient/MainForm.cs using AU.Monitor.Client; using AU.Monitor.Client.Extensions; using SuperSocket.ClientEngine; using SuperSocket.ProtoBase; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MonitorClient { public partial class MainForm : Form { private List<EasyClient> easyClients = new List<SuperSocket.ClientEngine.EasyClient>(); private readonly Encoding m_Encoding; public string cmdSpilts = "\r\n"; public MainForm() { InitializeComponent(); Console.SetOut(new Monitor.Common.ListTextWriter(this.lbLog)); m_Encoding = System.Text.Encoding.UTF8; } System.Net.IPAddress ip; private void btnConnect_Click(object sender, EventArgs e) { if (btnConnect.Text == "连接") { if (System.Net.IPAddress.TryParse(tbIP.Text.Trim(), out ip)) { btnConnect.Enabled = false; new Task(() => { for (int i = 0; i < numericUpDown2.Value; i++) { var d = new EasyClient(); d.Initialize(new FakeReceiveFilter(m_Encoding), (p => { string body = p.Body; string key = p.Key; string[] par = p.Parameters; if (key != body) Console.WriteLine("{0}:{1}", key, body); else Console.WriteLine(key); })); this.Invoke((MethodInvoker)delegate () { comboBox1.Items.Add(i); }); Task<bool> result = d.ConnectAsync(new System.Net.IPEndPoint(ip, (int)numericUpDown1.Value)); Task.WaitAll(result); Console.WriteLine("{0}:启动[{1}]", i, result.Result); this.easyClients.Add(d); System.Threading.Thread.Sleep(10); } this.Invoke((MethodInvoker)delegate () { btnConnect.Text = "断开"; btnSend.Enabled = true; btnConnect.Enabled = true; }); }).Start(); } else { string msg = "服务器地址为空,请填写服务器地址"; Console.WriteLine(msg); MessageBox.Show(msg); } } else { int i = 0; foreach (var d in easyClients) { bool rs = true; if (d.IsConnected) { Task<bool> result = d.Close(); Task.WaitAll(result); System.Threading.Thread.Sleep(10); } Console.WriteLine("{0}:关闭[{1}]", i, rs); } easyClients.Clear(); comboBox1.Items.Clear(); btnSend.Enabled = false; btnConnect.Text = "连接"; } } private void btnSend_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex < 0) { MessageBox.Show("请选择发送终端"); return; } var c = easyClients[comboBox1.SelectedIndex]; if (!c.IsConnected) { Task<bool> result = c.ConnectAsync(new System.Net.IPEndPoint(ip, (int)numericUpDown1.Value)); Task.WaitAll(result); Console.WriteLine("{0}:启动[{1}]", comboBox1.SelectedIndex, result.Result); } if (!c.IsConnected) { MessageBox.Show("终端无法连接服务,请稍后继续"); return; } byte[] b = m_Encoding.GetBytes(tbMsg.Text.Trim().Replace("\r\n", "") + cmdSpilts); int t = b.Length / 1024; byte[] buff; for (int i = 0; i <= t; i++) { if (i == t) { buff = new byte[b.Length - i * 1024]; Array.Copy(b, i * 1024, buff, 0, buff.Length); } else { buff = new byte[1024]; Array.Copy(b, i * 1024, buff, 0, 1024); } c.Send(buff); } } } } <file_sep>/MonitorServer/MonitorForm.cs using SuperSocket.SocketBase; using SuperSocket.SocketEngine; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MonitorServer { public partial class MainForm : Form { private IBootstrap bootstrap = BootstrapFactory.CreateBootstrap(); public MainForm() { InitializeComponent(); Console.SetOut(new Monitor.Common.ListTextWriter(this.lbLog)); } private void btnStart_Click(object sender, EventArgs e) { try { StartResult result = bootstrap.Start(); Console.WriteLine("Start result: {0}!", result); btnStop.Enabled = result != StartResult.Failed; btnStart.Enabled = !btnStop.Enabled; } catch (Exception ex) { Console.WriteLine(ex); } } private void btnStop_Click(object sender, EventArgs e) { try { bootstrap.Stop(); btnStart.Enabled = true; btnStop.Enabled = !btnStart.Enabled; Console.WriteLine("The server was stopped!"); } catch (Exception ex) { Console.WriteLine(ex); } } private void MainForm_Load(object sender, EventArgs e) { if (!bootstrap.Initialize()) { Console.WriteLine("Failed to initialize!"); } } } } <file_sep>/.svn/pristine/bc/bc60cbca1f6a2df4c2aaf32cebd9f4f6e96c25dc.svn-base using AU.Common.Utility; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Net; using System.Text; namespace AU.Common { public class AppRemotePublish : IDisposable { #region 成员与字段属性 private bool disposed = false; private IntPtr handle; private Component component = new Component(); [System.Runtime.InteropServices.DllImport("Kernel32")] private extern static Boolean CloseHandle(IntPtr handle); /// <summary> /// 消息通知 /// </summary> public event EventHandler<NotifyMessage> Notify; /// <summary> /// 配置名称 /// </summary> public static readonly string PackageName = "aupublish.json"; /// <summary> /// 发布地址 /// </summary> public string PublishAddress { get; set; } /// <summary> /// 本地包地址 /// </summary> public string LocalPath { get; set; } #endregion public AppRemotePublish(string publishaddress, string localPath) { this.LocalPath = localPath; this.PublishAddress = publishaddress + "/package"; } /// <summary> /// 销毁 /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// 销毁 /// </summary> /// <param name="disposing"></param> private void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { component.Dispose(); } CloseHandle(handle); handle = IntPtr.Zero; } disposed = true; } /// <summary> /// 析构函数 /// </summary> ~AppRemotePublish() { Dispose(false); } /// <summary> /// 检查更新文件 /// </summary> /// <param name="updatePackage"></param> /// <returns></returns> public int CheckForUpdate(string subsystem, AuPublish remote) { var local = AppPublish.ReadPackage(this.LocalPath + "\\" + subsystem + "\\" + PackageName); //本地空 if (local == null) return 1; if (remote == null) return -1; string filepath = this.LocalPath + "\\" + subsystem + "\\" + local.DownPath; //有更新 if (remote.No.CompareTo(local.No) > 0) { return 1; } else if (!System.IO.File.Exists(filepath)) //判断本地文件是否存在,且hash值相同 { return 1; } else if (ToolsHelp.ComputeSHA256(filepath).ToLower() != remote.SHA256.ToLower()) { return 1; } return 0; } /// <summary> /// 通知消息 /// </summary> /// <param name="state"></param> private void NotifyMessage(NotifyMessage state) { if (Notify != null) { Notify.Invoke(this, state); } } /// <summary> /// 下载文件 /// </summary> /// <param name="upgradeFiles"></param> /// <returns></returns> public string DownUpdateFile(string subSystem, string standbyIp, AuPublish upgradeFiles, out AuPublish notify, bool allowPublish = false) { notify = null; if (upgradeFiles == null) { return string.Empty; } try { int index = 0; string down = string.Format("{0}{1}/{2}", upgradeFiles.Url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ? "" : "http://", upgradeFiles.Url, upgradeFiles.DownPath); NotifyMessage(new Common.NotifyMessage(NotifyType.StartDown, "开始下载文件")); string temproot = Environment.GetEnvironmentVariable("Temp") + "\\AuUpdate\\" + subSystem; string tempPath = temproot + "\\" + upgradeFiles.SHA256 + "\\" + upgradeFiles.DownPath; //删除临时目录 ToolsHelp.DeleteDirectory(temproot, upgradeFiles.SHA256); ToolsHelp.CreateDirtory(tempPath); if (!(System.IO.File.Exists(tempPath) && ToolsHelp.ComputeSHA256(tempPath).ToLower() == upgradeFiles.SHA256.ToLower())) { WebRequest webReq = WebRequest.Create(down); WebResponse webRes = null; try { webRes = webReq.GetResponse(); } catch { Uri u = new Uri(down); string url = string.Format("http://{0}:{1}{2}", standbyIp, u.Port, u.AbsolutePath); webReq = WebRequest.Create(url); webRes = webReq.GetResponse(); } NotifyMessage(new Common.NotifyMessage(NotifyType.Process, "正在下载[" + upgradeFiles.DownPath + "]文件,请稍后...", 100000)); Stream srm = webRes.GetResponseStream(); Stream outStream = System.IO.File.Create(tempPath); byte[] buffer = new byte[1024]; int l; int startByte = 0; do { l = srm.Read(buffer, 0, buffer.Length); if (l > 0) { startByte += l; outStream.Write(buffer, 0, l); NotifyMessage(new Common.NotifyMessage(NotifyType.UpProcess, index + ":" + Convert.ToInt32((startByte / 100000) * 100).ToString() + "%", l)); } } while (l > 0); outStream.Flush(); outStream.Close(); srm.Close(); index++; } if (allowPublish) return this.Publis(subSystem, upgradeFiles, tempPath, out notify); return tempPath; } catch (WebException ex) { NotifyMessage(new Common.NotifyMessage(NotifyType.Error, "更新文件下载失败", ex)); return string.Empty; } finally { NotifyMessage(new Common.NotifyMessage(NotifyType.StopDown, "更新完成")); } } /// <summary> /// 发布 /// </summary> /// <param name="auPublish"></param> /// <param name="filePath"></param> /// <returns></returns> public string Publis(string subSystem, AuPublish auPublish, string filePath, out AuPublish notify) { //发布地址转换] auPublish.Url = this.PublishAddress + "/" + subSystem; string targetPath = this.LocalPath + subSystem + "\\" + auPublish.DownPath; ToolsHelp.CreateDirtory(targetPath); File.Copy(filePath, targetPath, true); //写发布 StreamWriter swau = new StreamWriter(this.LocalPath + subSystem + "\\" + AppPublish.PackageName, false, System.Text.Encoding.UTF8); swau.Write(Newtonsoft.Json.JsonConvert.SerializeObject(auPublish)); swau.Close(); //删除临时目录 //System.IO.Directory.Delete(System.IO.Path.GetDirectoryName(filePath), true); //删除不必要文件 ToolsHelp.DeleteFile(System.IO.Path.GetDirectoryName(targetPath), true, auPublish.DownPath, AppPublish.PackageName); notify = auPublish; return targetPath; } } } <file_sep>/.svn/pristine/65/6512f690a5e71837d81745db5f5dc3ffa4024b70.svn-base using System; using System.Collections.Generic; using System.Text; namespace AU.Common { /// <summary> /// 通知类别 /// </summary> public enum NotifyType { /// <summary> /// 异常 /// </summary> Error = -1, /// <summary> /// 正常通知 /// </summary> Normal = 0, /// <summary> /// 运行中 /// </summary> Running = 1, /// <summary> /// 停止 /// </summary> Stop = 2, /// <summary> /// 开始下载 /// </summary> StartDown = 3, /// <summary> /// 进度 /// </summary> Process = 4, /// <summary> /// 更新 /// </summary> UpProcess=5, /// <summary> /// 停止更新 /// </summary> StopDown = 6, /// <summary> /// 执行成功 /// </summary> RunSucess = 10, /// <summary> /// 执行错误 /// </summary> RunError = 20, /// <summary> /// 其他 /// </summary> Other = 30, } } <file_sep>/.svn/pristine/79/79f3c7638ddeda92eb573e48081de57d26b057af.svn-base using System.ServiceModel; namespace Infrastructure.UnityExtensions { /// <summary> /// Implements the lifetime manager storage for the <see cref="System.ServiceModel.IContextChannel"/> extension. /// </summary> public class UnityContextChannelExtension : UnityWcfExtension<IContextChannel> { /// <summary> /// Initializes a new instance of the <see cref="UnityContextChannelExtension"/> class. /// </summary> public UnityContextChannelExtension() : base() { } /// <summary> /// Gets the <see cref="UnityContextChannelExtension"/> for the current channel. /// </summary> public static UnityContextChannelExtension Current { get { return OperationContext.Current.Channel.Extensions.Find<UnityContextChannelExtension>(); } } } } <file_sep>/.svn/pristine/11/1134746c89b0ca44f118552fdca8a399abc687a3.svn-base using Infrastructure; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Domain.Services { public interface IProjectService : IApplicationServiceContract { #region Methods #endregion } } <file_sep>/AU.Monitor.Server/MonitorServerHelp.cs using SuperSocket.SocketBase; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AU.Monitor.Server { public class MonitorServerHelp { public MonitorServer ms { get; private set; } public void Init(SuperSocket.SocketBase.Config.ServerConfig sc, SessionHandler<MonitorSession> SessionConnectedEvent, SessionHandler<MonitorSession, CloseReason> SessionClosedEvent, RequestHandler<MonitorSession, SuperSocket.SocketBase.Protocol.StringRequestInfo> NewRequestReceived) { ms = new MonitorServer(); if (SessionConnectedEvent != null) ms.NewSessionConnected += SessionConnectedEvent; if (SessionClosedEvent != null) ms.SessionClosed += SessionClosedEvent; if (NewRequestReceived != null) ms.NewRequestReceived += NewRequestReceived; ms.Setup(sc); } /// <summary> /// 发送消息 /// </summary> /// <param name="sessionid">会话编号</param> /// <param name="Message">消息体</param> public void Send(string sessionid, string Message) { try { if (string.IsNullOrEmpty(sessionid)) foreach (var s in ms.GetAllSessions()) { s.Send(Message.Replace("\r\n", "")); } else { var s = ms.GetSessionByID(sessionid); if (s != null) s.Send(Message.Replace("\r\n", "")); } } catch (Exception e) { Console.WriteLine(e.Message); } } /// <summary> /// 发送消息 /// </summary> /// <param name="sessionid">会话编号</param> /// <param name="key">命令</param> /// <param name="body">命令内容</param> public void Send(string sessionid, string key, string body) { string message = key + ":" + body; Send(sessionid, message); } } }
fa9865d5d1c64c58274550e84e0fb2c0de95a642
[ "C#" ]
48
C#
tengfei527/AutoUpdateProject
190e04b72a0d932d4cd5a48f0467274962bb8aff
504807a58dab807e08fed75d72f1192563831c4f
refs/heads/master
<repo_name>rheehot/FakeChat<file_sep>/app/src/main/java/net/jspiner/fakechat/main/MainPagerAdapter.kt package net.jspiner.fakechat.main import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import net.jspiner.fakechat.main.chat.ChatListFragment import net.jspiner.fakechat.main.friend.FriendListFragment class MainPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { override fun getItem(position: Int) = when(position) { 0 -> FriendListFragment() 1 -> ChatListFragment() 2 -> ChatListFragment() // TODO 3 -> ChatListFragment() // TODO else -> throw UnsupportedOperationException("") } override fun getCount() = 4 override fun getPageTitle(position: Int) = when (position) { 0 -> "친구" 1 -> "채팅" 2 -> "검색" 3 -> "설정" else -> throw UnsupportedOperationException("") } }<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/FriendListAdapter.kt package net.jspiner.fakechat.main.friend import android.view.ViewGroup import androidx.databinding.ViewDataBinding import net.jspiner.ask.ui.base.BaseAdapter import net.jspiner.ask.ui.base.BaseViewHolder import net.jspiner.fakechat.R import net.jspiner.fakechat.main.friend.item.DividerItem import net.jspiner.fakechat.main.friend.item.FriendProfileItem import net.jspiner.fakechat.main.friend.item.ListItem import net.jspiner.fakechat.main.friend.item.MyProfileItem import net.jspiner.fakechat.main.friend.viewHolder.DividerViewHolder import net.jspiner.fakechat.main.friend.viewHolder.FriendViewHolder import net.jspiner.fakechat.main.friend.viewHolder.MyProfileViewHolder class FriendListAdapter : BaseAdapter<ListItem>() { private var myProfile = MyProfileItem.EMPTY private var friendProfileList: List<FriendProfileItem> = emptyList() override fun onCreateViewHolderInternal( parent: ViewGroup, viewType: Int ): BaseViewHolder<out ViewDataBinding, ListItem> { @Suppress("UNCHECKED_CAST") return when (viewType) { VIEW_TYPE_DIVIDER -> DividerViewHolder(parent, R.layout.item_divider) VIEW_TYPE_MY_PROFILE -> MyProfileViewHolder(parent, R.layout.item_my_profile) VIEW_TYPE_FRIEND_PROFILE -> FriendViewHolder(parent, R.layout.item_friend_profile) else -> throw UnsupportedOperationException("") } as BaseViewHolder<out ViewDataBinding, ListItem> } override fun onBindViewHolder( holder: BaseViewHolder<ViewDataBinding, ListItem>, position: Int ) { holder.setData(dataList[position]) } override fun getItemViewType(position: Int) = when (dataList[position]) { is DividerItem -> VIEW_TYPE_DIVIDER is MyProfileItem -> VIEW_TYPE_MY_PROFILE is FriendProfileItem -> VIEW_TYPE_FRIEND_PROFILE else -> throw UnsupportedOperationException("") } fun updateMyProfile(profile: MyProfileItem) { this.myProfile = profile updateDisplayList() } fun updateFriendProfileList(list: List<FriendProfileItem>) { this.friendProfileList = list updateDisplayList() } private fun updateDisplayList() { update( listOf(myProfile, DividerItem("친구 ${friendProfileList.count()}")) + friendProfileList ) } companion object { const val VIEW_TYPE_DIVIDER = 1 const val VIEW_TYPE_MY_PROFILE = 2 const val VIEW_TYPE_FRIEND_PROFILE = 3 } }<file_sep>/app/src/main/java/net/jspiner/fakechat/main/chat/ChatListViewModel.kt package net.jspiner.fakechat.main.chat import net.jspiner.ask.ui.base.BaseViewModel class ChatListViewModel : BaseViewModel()<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/item/FriendProfileItem.kt package net.jspiner.fakechat.main.friend.item data class FriendProfileItem( override val profileId: Int, override val profileImage: String, override val name: String, override val statusMessage: String ) : ProfileItem(profileId, profileImage, name, statusMessage)<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/FriendListFragment.kt package net.jspiner.fakechat.main.friend import android.os.Bundle import android.view.View import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import net.jspiner.ask.ui.base.BaseFragment import net.jspiner.fakechat.R import net.jspiner.fakechat.databinding.FragmentFriendListBinding import net.jspiner.fakechat.repository.database.FakeChatDatabase class FriendListFragment : BaseFragment<FragmentFriendListBinding, FriendListViewModel>() { private val adapter by lazy { FriendListAdapter() } override fun getLayoutId() = R.layout.fragment_friend_list override fun createViewModel() = FriendListViewModel( FakeChatDatabase.getInstance(context).myProfileDao(), FakeChatDatabase.getInstance(context).profileDao() ) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerView.layoutManager = LinearLayoutManager(context) binding.recyclerView.adapter = adapter binding.recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) binding.toolbar.elevation = if(recyclerView.canScrollVertically(-1)) { 50f } else 0f } }) observeViewModel() viewModel.loadMyProfile() viewModel.loadFriendList() } private fun observeViewModel() { viewModel.myProfile.observe(viewLifecycleOwner, Observer { profile -> adapter.updateMyProfile(profile) }) viewModel.friendProfileList.observe(viewLifecycleOwner, Observer { list -> adapter.updateFriendProfileList(list) }) } }<file_sep>/app/src/androidTest/java/net/jspiner/fakechat/ProfileTest.kt package net.jspiner.fakechat import androidx.test.ext.junit.runners.AndroidJUnit4 import net.jspiner.fakechat.repository.database.FakeChatDatabase import net.jspiner.fakechat.repository.entity.Profile import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ProfileTest { @Test fun addDummyProfiles() { // FakeChatDatabase.getInstance() // (0..100).map { id -> // profileDao.insertProfile( // Profile( // profileImage = "https://picsum.photos/200?seed=$id", // name = "랜덤프로필$id", // statusMessage = "랜덤" // ) // ) // } } }<file_sep>/app/src/main/java/net/jspiner/fakechat/repository/database/FakeChatDatabase.kt package net.jspiner.fakechat.repository.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import net.jspiner.fakechat.repository.dao.MyProfileDao import net.jspiner.fakechat.repository.dao.ProfileDao import net.jspiner.fakechat.repository.entity.MyProfileEntity import net.jspiner.fakechat.repository.entity.Profile @Database(entities = [Profile::class, MyProfileEntity::class], version = 1) abstract class FakeChatDatabase : RoomDatabase() { abstract fun myProfileDao(): MyProfileDao abstract fun profileDao(): ProfileDao companion object { @Volatile private var INSTANCE: FakeChatDatabase? = null fun getInstance(context: Context): FakeChatDatabase = INSTANCE ?: synchronized(this) { INSTANCE ?: buildDatabase(context).also { INSTANCE = it } } private fun buildDatabase(context: Context) = Room.databaseBuilder( context.applicationContext, FakeChatDatabase::class.java, "Sample.db" ).build() } }<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/item/ProfileItem.kt package net.jspiner.fakechat.main.friend.item abstract class ProfileItem( open val profileId: Int, open val profileImage: String, open val name: String, open val statusMessage: String ): ListItem()<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/item/ListItem.kt package net.jspiner.fakechat.main.friend.item import net.jspiner.ask.ui.base.Diffable abstract class ListItem: Diffable { override fun isSameItem(other: Diffable) = false // TODO }<file_sep>/settings.gradle include ':app', ':android-starter-kit' rootProject.name = "FakeChatApplication"<file_sep>/app/src/main/java/net/jspiner/fakechat/main/MainActivity.kt package net.jspiner.fakechat.main import android.os.Bundle import android.view.Menu import android.view.MenuItem import net.jspiner.ask.ui.base.BaseActivity import net.jspiner.fakechat.R import net.jspiner.fakechat.databinding.ActivityMainBinding class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>() { override fun getLayoutId() = R.layout.activity_main override fun createViewModel() = MainViewModel() override fun loadState(bundle: Bundle) { // no-op } override fun saveState(bundle: Bundle) { // no-op } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initView() } private fun initView() { binding.pager.adapter = MainPagerAdapter(supportFragmentManager) binding.tab.setupWithViewPager(binding.pager) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } }<file_sep>/app/src/main/java/net/jspiner/fakechat/repository/dao/ProfileDao.kt package net.jspiner.fakechat.repository.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import io.reactivex.Completable import io.reactivex.Single import net.jspiner.fakechat.repository.entity.Profile @Dao interface ProfileDao { @Insert fun insertProfile(profile: Profile): Completable @Query("SELECT * FROM profile ORDER BY name") fun loadFriendProfiles(): Single<List<Profile>> }<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/FriendListViewModel.kt package net.jspiner.fakechat.main.friend import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import net.jspiner.ask.ui.base.BaseViewModel import net.jspiner.ask.util.bindLifecycle import net.jspiner.fakechat.main.friend.item.FriendProfileItem import net.jspiner.fakechat.main.friend.item.MyProfileItem import net.jspiner.fakechat.repository.dao.MyProfileDao import net.jspiner.fakechat.repository.dao.ProfileDao class FriendListViewModel( private val myProfileDao: MyProfileDao, private val profileDao: ProfileDao ) : BaseViewModel() { private val _myProfile = MutableLiveData<MyProfileItem>(MyProfileItem.EMPTY) val myProfile: LiveData<MyProfileItem> = _myProfile private val _friendProfileList = MutableLiveData<List<FriendProfileItem>>(emptyList()) val friendProfileList: LiveData<List<FriendProfileItem>> = _friendProfileList fun loadMyProfile() { myProfileDao.getMyProfile() .map { MyProfileItem( it.profile.id, it.profile.profileImage, it.profile.name, it.profile.statusMessage ) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { profile -> _myProfile.value = profile }.bindLifecycle(lifecycle) } fun loadFriendList() { profileDao.loadFriendProfiles() .map { list -> list.map { FriendProfileItem( it.id, it.profileImage, it.name, it.statusMessage ) } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { profiles -> _friendProfileList.value = profiles }.bindLifecycle(lifecycle) } }<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/viewHolder/FriendViewHolder.kt package net.jspiner.fakechat.main.friend.viewHolder import android.view.ViewGroup import net.jspiner.ask.ui.base.BaseViewHolder import net.jspiner.ask.util.loadSquirclely import net.jspiner.fakechat.databinding.ItemFriendProfileBinding import net.jspiner.fakechat.main.friend.item.FriendProfileItem class FriendViewHolder(parent: ViewGroup, layoutResId: Int) : BaseViewHolder<ItemFriendProfileBinding, FriendProfileItem>(parent, layoutResId) { override fun setData(data: FriendProfileItem) { super.setData(data) binding.profileImage.loadSquirclely(data.profileImage) binding.profile = data } }<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/item/DividerItem.kt package net.jspiner.fakechat.main.friend.item data class DividerItem( val text: String ) : ListItem()<file_sep>/app/src/main/java/net/jspiner/fakechat/repository/entity/Profile.kt package net.jspiner.fakechat.repository.entity import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Profile( @PrimaryKey(autoGenerate = true) val id: Int = 0, val name: String, val profileImage: String, val statusMessage: String )<file_sep>/app/src/main/java/net/jspiner/fakechat/repository/dao/MyProfileDao.kt package net.jspiner.fakechat.repository.dao import androidx.room.* import io.reactivex.Completable import io.reactivex.Single import net.jspiner.fakechat.repository.entity.MyProfile import net.jspiner.fakechat.repository.entity.MyProfileEntity @Dao interface MyProfileDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun setMyProfile(myProfile: MyProfileEntity): Completable @Transaction @Query("SELECT * FROM my_profile_entity") fun getMyProfile(): Single<MyProfile> }<file_sep>/app/src/main/java/net/jspiner/fakechat/main/chat/ChatListFragment.kt package net.jspiner.fakechat.main.chat import net.jspiner.ask.ui.base.BaseFragment import net.jspiner.fakechat.R import net.jspiner.fakechat.databinding.FragmentChatListBinding class ChatListFragment : BaseFragment<FragmentChatListBinding, ChatListViewModel>() { override fun getLayoutId() = R.layout.fragment_chat_list override fun createViewModel() = ChatListViewModel() }<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/viewHolder/MyProfileViewHolder.kt package net.jspiner.fakechat.main.friend.viewHolder import android.view.ViewGroup import net.jspiner.ask.ui.base.BaseViewHolder import net.jspiner.ask.util.loadSquirclely import net.jspiner.fakechat.databinding.ItemMyProfileBinding import net.jspiner.fakechat.main.friend.item.MyProfileItem class MyProfileViewHolder(parent: ViewGroup, layoutResId: Int) : BaseViewHolder<ItemMyProfileBinding, MyProfileItem>(parent, layoutResId) { override fun setData(data: MyProfileItem) { super.setData(data) binding.profileImage.loadSquirclely(data.profileImage) binding.profile = data } }<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/viewHolder/DividerViewHolder.kt package net.jspiner.fakechat.main.friend.viewHolder import android.view.ViewGroup import net.jspiner.ask.ui.base.BaseViewHolder import net.jspiner.fakechat.databinding.ItemDividerBinding import net.jspiner.fakechat.main.friend.item.DividerItem class DividerViewHolder(parent: ViewGroup, layoutResId: Int) : BaseViewHolder<ItemDividerBinding, DividerItem>(parent, layoutResId) { override fun setData(data: DividerItem) { super.setData(data) binding.item = data } }<file_sep>/app/src/main/java/net/jspiner/fakechat/repository/entity/MyProfileEntity.kt package net.jspiner.fakechat.repository.entity import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.Relation @Entity(tableName = "my_profile_entity") data class MyProfileEntity( @PrimaryKey val id: Int = 1, val profileId: Int ) data class MyProfile( @Embedded val myProfile: MyProfileEntity, @Relation( parentColumn = "profileId", entityColumn = "id" ) val profile: Profile )<file_sep>/app/src/main/java/net/jspiner/fakechat/main/MainViewModel.kt package net.jspiner.fakechat.main import net.jspiner.ask.ui.base.BaseViewModel class MainViewModel: BaseViewModel()<file_sep>/app/src/main/java/net/jspiner/fakechat/main/friend/item/MyProfileItem.kt package net.jspiner.fakechat.main.friend.item data class MyProfileItem( override val profileId: Int, override val profileImage: String, override val name: String, override val statusMessage: String ) : ProfileItem(profileId, profileImage, name, statusMessage) { companion object { val EMPTY = MyProfileItem( -1, "", "계정을 생성 해주세요.", "" ) } }
58f130992eb8c2e3a022866bc6a6bcdcdd74797a
[ "Kotlin", "Gradle" ]
23
Kotlin
rheehot/FakeChat
c2b64325a9b3932d7091fc9e9e5872eb52318b04
2f6876b026e8bf55fe93eb3b05eeef77ef0fb17b
refs/heads/master
<file_sep>#coding:utf-8 from queue import Queue class PCB: ready_queue = Queue() block_queue = Queue() PCBnum = 0 def __init__(self, name, time, status): self.name = name self.time = time self.status = status def CREAT_PCB(self): self.name = input("请输入进程名:\n") self.time = input("请输入运行时间:\n") self.status = "R" PCB.ready_queue.put(PCB(self.name, self.time, self.status)) print("进程创建成功") def Run_Finsh(self): print("运行进程 %s")%self.name if PCB.ready_queue.get().name == self.name: print("程序运行成功") PCB.ready_queue.get().status = "E" print("运行结束") else: print("Error") def Run_WAIT(self): print("阻塞进程") if PCB.ready_queue.get().name == self.name: pcb = PCB.ready_queue.get() pcb.status = "B" PCB.block_queue.put(pcb) print("阻塞成功") else: print("Error") def Run_SIGNAL(self): print("唤醒进程") if PCB.block_queue.get().name == self.name: pcb = PCB.block_queue.get() pcb.status = "R" PCB.ready_queue.put(pcb) print("唤醒成功") else: print("Error") def show(self): print("进程" + self.name + ": 运行时间: " + self.time+"进程状态: " + self.status) if self.status == "R": print("就绪") elif self.status == "E": print("结束") else: print("阻塞") def main(): num = 0 while num <= 5: print("-------------------------------------------") print("New:新建进程\t\tRun<Finish>:运行程序并结束") print("Run<Wait>:运行后阻塞\t\tSignal:唤醒阻塞进程") print("Show:显示当前所有运行进程\t\tExit:退出程序") print("---------------------------------------") a = input("请输入命令:") if a == "New": if num <= 5: PCB("","","").CREAT_PCB() num += 1 else: print("进程超出") exit(0) elif a == "Run<Finish>": if not PCB.ready_queue.empty(): PCB.Run_Finsh() num -= num print("运行成功") else: print("无可运行进程") elif a == "Run<Wait>": if not PCB.ready_queue.empty(): PCB.Run_WAIT() else: print("无就绪进程") elif a == "Signal": if not PCB.block_queue.empty(): PCB.Run_SIGNAL() print("唤醒成功") else: print("无可唤醒进程") elif a == "Show": if num == 0: print("无进程") else: for i in range(PCB.ready_queue.qsize()): pcb = PCB.ready_queue.get() PCB(pcb.name,pcb.time,pcb.status).show() i += i for a in range(PCB.block_queue.qsize()): pcb = PCB.block_queue.get() PCB(pcb.name,pcb.time,pcb.status).show() a += a elif a == "Exit": exit(0) else: input("输出错误,请重新输入命令:") if __name__ == '__main__': main()<file_sep># -*- coding:utf-8 -*- ''' @author: leisun @contact: <EMAIL> @file: 银行家算法.py @time: 2018/4/23 下午7:01 ''' def Bigger(list_1,list_2): #比较两个列表中各个值大小 for i in range(len(list_1)): if list_1[i] >= list_2[i]: i += 1 else: return False return True def sum(list_1, list_2, operator): #重新定义两个列表加减 if len(list_1) == len(list_2): res =[] for i in range(len(list_2)): res.append(list_1[i]+list_2[i])\ if operator == "+"\ else res.append(list_1[i]-list_2[i]) return res else: return "" def Bank(Available): #银行家算法 Max = { "P0": [7, 5, 3], "P1": [3, 2, 2], "P2": [9, 0, 2], "P3": [2, 2, 2], "P4": [4, 3, 3] } Allocation = { "P0": [0, 1, 0], "P1": [2, 0, 0], "P2": [3, 0, 2], "P3": [2, 1, 1], "P4": [0, 0, 2] } Need = {} # 赋值给各进程需要最大需求量以及占用资源量 for key in Max.keys(): # print(Bigger(Max[key], Allocation[key])) if Bigger(Max[key], Allocation[key]): # print(Max[key], Allocation[key]) Need[key] = sum(Max[key], Allocation[key], "-") # 求出各进程还需要的资源量 else: print("进程占用资源大于Max") return Available # print(Need) process = input("请输入请求的进程名:\n") req = input("请输入进程请求的资源数量,格式为:(x,y,z)\n") requset = [] for each in req: if each.isdigit(): requset.append(int(each)) if Bigger(Need[process], requset): if Bigger(Available, requset): Available = sum(Available, requset, "-") Allocation[process] = sum(Allocation[process], requset, "+") #系统分配资源并修改对应数据结构值 Need[process] = sum(Need[process], requset, "-") print("\t\tMax\t\tAllocation\t\tNeed\t Available") print("\t\tA B C\t\tA B C\t\tA B C\t\tA B C") for key in Max.keys(): if key == process: print(key, " ", Max[key], "\t", Allocation[key], "\t", Need[key], "\t ", Available) else: print(key, " ", Max[key], "\t", Allocation[key], "\t", Need[key]) Safe(Available, Allocation, Need) else: print("需求过多,无法成功分配资源,无安全序列") else: print("进程{}对资源的申请量大于其说明的最大值,请重新输入".format(process)) return Bank(Available) return Available def Safe(Available, Allocation, Need): #安全性算法 Work = Available Finish = {} for i in range(0,5): key = "P" + str(i) #为Finish向量赋初值 Finish[key] = False safe = [] for i in range(len(Finish.keys())): for key in Finish.keys(): if Finish[key] is False and Bigger(Work, Need[key]): Finish[key] = True Work = sum(Work, Allocation[key], "+") safe.append(key) else: i += 1 for val in Finish.values(): if val is False: print("无安全序列") break if safe: print("安全序列为:{", end="") for i in range(len(safe)): if i < 4: print(safe[i], end=",") else: print(safe[i], end="") print("}") def main(Available): print("Apply:申请资源\t\tExit:退出\n") command = input("请输入命令:\n") if command == "Exit": exit(0) elif command == "Apply": Available = Bank(Available) print("\n\n") return main(Available) else: input("命令错误,请重新输入:\n") return main(Available) if __name__ == '__main__': Available = ([3, 3, 2]) main(Available)
44b2c80a15eb5b1b52cc0538a075c75d5b9b67b1
[ "Python" ]
2
Python
leisun123/OS
1432af918ef1678f2bf36ea118d79ad88ffd50f7
4711afc381fc95d015bd6e46b5f695334664329c
refs/heads/master
<repo_name>hoest/jelledejong<file_sep>/content/test.md Title: Test document Summary: This document is used for testing purposes Author: <NAME> Date: 2012-08-31 Keywords: test, web, page Test document === This document is _used_ for **test** purposes.<file_sep>/requirements.txt Flask==0.9 Jinja2==2.6 Markdown==2.2.0 Werkzeug==0.8.3 distribute==0.6.27 gevent==0.13.7 greenlet==0.4.0 gunicorn==0.14.6 wsgiref==0.1.2 <file_sep>/gunicorn.conf.dev.py import os bind = "0.0.0.0:8080" workers = 3 backlog = 2048 worker_class = "gevent" debug = True loglevel = "debug"<file_sep>/content/home.md Title: Curriculum Vitae (CV) Summary: Het Curriculum Vitae (CV) van <NAME>ong uit Soest. Author: <NAME> Date: 1 september 2012 Keywords: <NAME>, Soest, Nederland, Curriculum Vitae, CV, software ontwikkelaar, website, site, python, C#, .net, asp.net, microsoft, php, javascript, html, html5, jquery, css, sql Curriculum Vitae === <NAME> --- [Soest][1], [Nederland][2] Kennis van --- ###Talen/frameworks C#, ASP.NET, XML, XSLT, HTML(5), CSS, JavaScript, PowerShell, Python, CoffeeScript ###Producten Visual Studio, (N)Ant, CVS, Git, TeamCity (Continuous Integration), Vim, Sublime Text, Windows, Linux, OSX ###GitHub Mijn [GitHub](https://github.com/hoest/)-account. Werkervaring --- ###Senior Developer Waar: [InfoProjects][3] Periode: 2003 - heden Na mijn studie ben ik gestart bij InfoProjects. In 2003 kwam ik daar terecht als junior developer en ik heb me in korte tijd ontwikkeld tot stabiele kracht binnen het team van ontwikkelaars en inmiddels ben ik werkzaam als senior developer en technisch verantwoordelijk voor vele projecten, waaronder het IPROX-CMS, IPROX-Modules, IPROX-FORMS en diverse implementaties van deze producten. Daarnaast ben ik samen met een collega verantwoordelijk voor de implementatie van onze eigen '[Continuous Integration & Deployment][8]' straat. Het is nu mogelijk om met slechts enkele acties, een nieuw ontwikkelde feature vanuit de ontwikkelomgeving live te zetten in de productieomgeving. Naast het ontwikkelen van websites zijn we begin 2013 gestart met het bouwen van mobiele applicaties met behulp van het [Apache Cordova](http://cordova.apache.org/) platform voor iOS, Android en WindowsPhone 8. De basis van de apps bestaat uit een single page application in HTML5 i.c.m. [AngularJS](https://angularjs.org/). Een kleine greep van uitgevoerde projecten is te bekijken op de website van [InfoProjects BV][3]. De technieken die gebruikt worden binnen InfoProjects zijn: C#, ASP.NET, SQL (Microsoft SQL of Oracle), XML, XSLT, HTML(5), JavaScript en CSS. ###Directeur Waar: Ho<NAME> Periode: 1999 - 2003 Dit bedrijf heb ik tijdens mijn studie economie opgezet. Tijdens mijn studie Informatica is het gegroeid naar een bedrijf met diverse vaste klanten waarbij ik veel opgedane kennis kon uitvoeren in de praktijk. Meest gebruikte technieken waren toentertijd PHP, XML, SQL (MySQL), JavaScript en CSS. ###Afstudeerstage Waar: [JTeam][4] (tegenwoordig: _Orange11_) Periode: 2003 Gedurende mijn laatste jaar van mijn studie Informatica heb ik bij JTeam veel ervaring opgedaan in het ontwikkelen van een grote (web)applicatie, geschreven met een team en in Java. Hier heb ik kennis opgedaan van bijvoorbeeld het belang van versiebeheer en van diverse methodieken, zoals eXtreme Programming en diverse Design Patterns. ###Eerste stage Waar: Omni Trade BV Periode: 2002 Als student heb ik bij Omni Trade BV te Soest mijn eerste stage gelopen. Hier ben ik actief geweest in de automatisering, het aanleggen van uitgebreide netwerken tot installaties van Windows en Linux server-/client-omgevingen, diverse dingen zijn op mijn pad gekomen. Opleidingen --- ###Hogere Informatica Waar: [Hogesch<NAME> Utrecht][5] Periode: 1999-2003 Relevante kennis: UML, Java, SQL, C++, diverse Microsoft producten ###Economie Waar: [Vrije Universiteit Amsterdam][6] Periode: 1997-1999 ###VWO Waar: [<NAME>][7] Periode: 1991-1997 Vakkenpakket: Nederlands, Engels, Economie I, Economie II, Natuurkunde, Scheikunde, Wiskunde B [1]: https://maps.google.com/maps?q=Soest,+Nederland [2]: https://maps.google.com/maps?q=Nederland [3]: http://www.infoprojects.nl/ [4]: http://www.orange11.nl/ [5]: http://www.hu.nl/ [6]: http://www.vu.nl/ [7]: http://www.hetbaarnschlyceum.nl/ [8]: http://en.wikipedia.org/wiki/Continuous_integration <file_sep>/gunicorn.conf.prod.py import os bind = "0.0.0.0:23779" workers = 3 backlog = 2048 worker_class = "gevent" errorlog = "./logs/error.log" accesslog = "./logs/access.log" <file_sep>/readme.md Simple site === This is a simple Python/Flask/Markdown based website for my jelledejong.org/.info domain.<file_sep>/gnojed_tests.py import os import gnojed import unittest import tempfile class GnojEdTestCase(unittest.TestCase): def setUp(self): self.app = gnojed.app.test_client() def tearDown(self): pass def test_baserequest(self): rv = self.app.get("/") assert "</html>" in rv.data assert "<div class=\"main\">" in rv.data def test_output(self): rv = self.app.get("/test/") assert "<h1>Test document</h1>" in rv.data assert "<p>This document is <em>used</em> for <strong>test</strong> purposes.</p>" in rv.data if __name__ == "__main__": unittest.main()<file_sep>/gnojed.py import markdown import os.path import datetime from flask import abort from flask import flash from flask import Flask from flask import Markup from flask import redirect from flask import render_template from flask import request from flask import make_response from flask import url_for app = Flask(__name__) app.secret_key = os.urandom(24) @app.route("/") @app.route("/<page>") @app.route("/<page>/") def show(page = "home"): md = markdown.Markdown(extensions = ["meta", "abbr", "footnotes", "tables", "nl2br"], output_format = "html5") # Each URL maps to the corresponding .txt file in ./content/ page_file = "./content/%s.md" % page # Try to open the text file, returning a 404 upon failure try: with open(page_file, "r") as f: # Read the entire file, converting Markdown content to HTML content = f.read() content = Markup(md.convert(content)) meta = md.Meta template = "%s.html" % page if not os.path.exists("/templates/%s" % template): template = "home.html" # set last-modified header response = make_response(render_template(template, **locals())) lastModified = os.path.getmtime(page_file) lastModifiedUtc = datetime.datetime.utcfromtimestamp(lastModified) response.headers.add("Last-Modified", lastModifiedUtc.strftime("%a, %d %b %Y %H:%M:%S GMT")) return response; except IOError as e: return abort(404) if __name__ == "__main__": app.run(host = "0.0.0.0", debug = True)
754c3bddf52fa29d1d0f30a0af0ac3f76b568c40
[ "Markdown", "Python", "Text" ]
8
Markdown
hoest/jelledejong
6524ef84f364dda82475944cadbbce06e4c3ac6c
8828ad803fd8a2ffc95ac15ec2d4f6adf7faa581
refs/heads/master
<file_sep>package com.get.employee.service; public class EmployeeService { } <file_sep>server.port=9987 spring.application.name=SpringBoot-Admin spring.security.username=Harini spring.security.password=<PASSWORD> <file_sep>package com.fetch.employee.service; import java.util.List; import com.fetch.employee.entity.Employee; public interface EmployeeServiceI { List<Employee> fetchAllEmployees(); } <file_sep>server.port=9675 spring.datasource.url=jdbc:oracle:thin:@localhost:1521/XE spring.datasource.username=harini spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.jpa.hibernate.ddl-auto=create spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect spring.boot.admin.username=harini spring.boot.admin.password=<PASSWORD> © 2020 GitHub, Inc. <file_sep>package com.delete.employee.service; import com.delete.employee.exceptions.IdNotFoundException; public interface EmployeeServiceI { String deleteEmployee(Integer empId) throws IdNotFoundException; } <file_sep>package com.fetch.employee.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fetch.employee.entity.Employee; import com.fetch.employee.dao.EmployeeRepository; @Service public class EmployeeService implements EmployeeServiceI{ @Autowired EmployeeRepository dao; @Override public List<Employee> fetchAllEmployees() { // TODO Auto-generated method stub return dao.findAll(); } }<file_sep>package com.get.employee.controller; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import com.get.employee.entity.Employee; import com.get.employee.exceptions.IdNotFoundException; import com.get.employee.service.EmployeeServiceI; public class EmployeeController { @Autowired private EmployeeServiceI service; @GetMapping("/findById/{empId}") public Optional<Employee> getEmployeeDetails(@PathVariable Integer empId) throws IdNotFoundException { Optional<Employee> result=service.getEmployee(empId); if(result== null) { throw new IdNotFoundException("Employee with "+empId+" doesn't exist....!"); } else { return result; } } } <file_sep>package com.get.employee.exceptions; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; public class MyControllerAdvice { @ExceptionHandler(IdNotFoundException.class) public ResponseEntity<String> employeeNotFound(IdNotFoundException e){ return new ResponseEntity<String>(e.getMessage(),HttpStatus.NOT_FOUND); } }<file_sep>package com.delete.employee.service; import com.delete.employee.exceptions.IdNotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.delete.employee.dao.EmployeeRepository; @Service public class EmployeeService implements EmployeeServiceI { @Autowired private EmployeeRepository dao; @Override public String deleteEmployee(Integer empId) { // TODO Auto-generated method stub dao.delete(empId); return "Deleted Successfully"; } }<file_sep>server.port=2222 spring.application.name=employee-service spring.cloud.config.server.git.uri:https://github.com/Harinidara/config_server.git management.security.enabled=false
ee19e4fbc9e63ebfd1419dd0fa047b3497393ab5
[ "Java", "INI" ]
10
Java
Harinidara/config_server
0b24935a98eee8f04c97338756c80086fa95ded9
35beaa18b7d4b7fc880cf4a11c16a96bbec6a7fc
refs/heads/master
<file_sep>{% extends "base.html" %} {% load static i18n %} {% block content %} <img class="bg-style" src="{% static 'images/2-banner.webp' %}"> <div class="container"> <h1 class="title-style">Terms and Conditions</h1> <div class="row"> <div class="col-sm-12"> <h5><strong>Terms & Agreements</strong></h5> <hr> <p>The document below is the Legal statement and Acceptable Use Policy for the score website which is the property of and run by Amerigo Marketing LTD, Athinon 82, Limassol 3040, Cyprus.</p> <p> “Usagreencard.online” includes the company’s any subsidiaries, affiliations, divisions, representatives, agents, managers, employs or working directly or indirectly for the company.</p> <h5><strong>General</strong></h5> <hr> <p>Our services may only be used by you after you have gone through, understood and confirmed to the said terms of this agreement. You have to show your validation of this agreement and its constituent terms by clicking on the “I Agree” button. The terms “user”, “your”, and “you” are the same in the case of this agreement and used for anybody that in any manner, uses our services.</p> <p>Someone whose required data to allow him/her to submit immigration form through the services has been received by Usagreencard.online, may become a registered user. Following the terms and conditions of the agreement is mandatory on that person.</p> <p>Whoever that has access to the Internet can use and access, from anywhere on the globe , any of the services provided by the Usagreencard.online. The use of the services and access to the website are governed by the terms and conditions of this agreement also by the copyright and trademark laws. By using this site and any of our services you agree to all the terms and conditions of this agreement and copyright and trademark laws without any omissions or limitations. It is allowed for Usagreencard.online and its affiliates to make amends to the terms and condition at any time. You show your agreement to any amends in the terms and conditions by continuing the use of the website and services after the amendments appear to the screen.</p> <p>The client bears the responsibility for all the terms and condition of the transactions made using or as a result of the site and services. All terms about shipping, warranties, all fees and taxes, duty charges, governmental levies, licensing fees, fines, title, permits, and returns in addition to the charged fees for using services of the company are also included in the client’s responsibility.</p> <p>The client hereby agrees to pay any taxes or duties to Usagreencard.online if the law mandates the collection or to withholding of any.</p> <p>The laws of the Cyprus govern this website.</p> <h5><strong>Limited Warranty</strong></h5> <hr> <p>The company promise no warranties of any sorts regarding the organizations, government agencies or any individual named in the services or the websites, express or implied. This also refers to the warranties given regarding fitness or title for any purpose. Warranties that cannot be omitted, amended, or restricted under the laws regarding the agreement are exceptions. The company and its affiliates are not liable for enforcing that the opinions, statements or advice given regarding other organizations or agencies is right or accurate. You also acknowledge, by agreeing to this agreement, that due to technical faults and availability of the means of your communication that you use to access the website or that which are used by the immigration authorities to transmit information may result in temporary unavailability of the services or their operations. In such cases, the company is not responsible for the unavailability of services. But in any of the above cases, the company will bear the limited financial liability for only the amount paid by you for any services you used. The resulting incidental, indirect or consequential damages including loss of immigration status or deportation is not the responsibility of Usagreencard.online.</p> <p>The fundamental tenets of the agreement between you and the company are outlined in this agreement are the limitations of the liability or damages. By clicking on “I Agree” you agree to these limitations and also fully comprehend that the provided service will cease to be provided without them on an economic basis. You also acknowledge that the company is not responsible for the submission of your application after a third-party act or failure to act.</p> <h5><strong>Note</strong></h5> <hr> <p>The process with the application will be started right after the payment is processed with the agent. Your Card will be debited right upon completing your order.</p> <p>As the American government legislates the Diversity Via program, it is allowed for the government to suspend, suspend, prohibit or cause the program to stop operations. In doing so, either permanently or temporarily, the company will not be responsible. If any payments are made after any such announcements of stopping of the program, no refund will be offered to users.</p> <h5><strong>Assuming Risk</strong></h5> <hr> <p>You agree to use the services and the website at your own risk. Usagreencard.online shall not be held accountable to anyone in the case of any injury, indirect or direct, by the user of the service or the website. The company will be no responsibility for the information displayed on the website or any actions made due to that information. By agreeing to this agreement, you also agree to waive off any claims against the company, its representatives, affiliates, agents, divisions that may appear upon your usage of the service or the site or any information displayed on it.</p> <h5><strong>Communications</strong></h5> <hr> <p>The information was given by the user or anyhow provided to the company will not be treated as confidential or proprietary. The full liability is held by the user for any information that he or she may share or provide to the company and the company reserves the rights to use that information for any reason or to copy, distribute or publish the information given to it. The reasons may include but to no limitation, the registration of the Usagreencard.online program. The websites linked to ours are not monitored by us and therefore we are not responsible for the information or any content on those websites. The linking to those websites or use of information given on those websites on their own liability.</p> <p>It must be noted that others may use or collect any information you may provide yourself in your username or email address and also in chat rooms, bulletin boards, chat rooms or any other pages that are created by the members. This may cause you to receive messages from others that had access to that information. You also agree not to post anything in the site’s bulletin board, chat rooms or any other pages created by the members, that is unlawful or something that may be considered as offensive, profane, threatening, abusive, vulgar, hateful or otherwise objectionable. You also agree not to post anything that is against any law. If any case arises against you due to anything that you posted, you will be the only one held responsible and not Usagreencard.online or any of its agents, divisions or affiliates.</p> <h5><strong>Security</strong></h5> <hr> <p>Credit card numbers are the only confidential information that we accept from the clients over the Internet. Any other non-personal information conveyed to us by you will be treated as non-confidential. By sending us this information you acknowledge that Usagreencard.online has used, distribute or transmit this information without any restriction. You also agree that we are allowed to use any concepts, ideas or techniques sent to us by you.</p> <h5><strong>Your responsibility</strong></h5> <hr> <p>You are responsible for:</p> <p>Timely provision of all the required information to Usagreencard.online. Those applicants that miss any required information may not be contacted. Also, the application will only be submitted for the green card if the information is received on time. Making sure that you have gone through the eligibility terms of the diversity program and only if you are eligible to enroll in it. In order for the clients to completely comprehend and easily read the necessary information, they are advised to print the requirements, payment methods, cancellation policies, and transaction data.</p> <h5><strong>Refund & Cancellation Policy</strong></h5> <hr> <p>Only in a week’s time of the purchase date will the client be able to get a refund and within compliance of the terms and conditions of the company. The company will take the decision about the refund in complete discretion.</p> <p>In case the payment was refunded, it will appear in the customer’s card within 31 business days (Depend on the customer’s settlement date with their Credit Card company)</p> <h5><strong>No Guarantee of outcome</strong></h5> <hr> <p>By agreeing to the terms and conditions you acknowledge the fact that we do not guarantee the winning of your visas. All the application received by the computer undergo random drawing and hence the ones submitted using our services have no advantage over the others. Usagreencard.online is not in any way involved in the selection or the results of the draws.</p> <h5><strong>Use of Service</strong></h5> <hr> <p>The user is allowed to use the services of Usagreencard.online to prepare a green card program. These services may only be used for this purpose only and not any other. You agree to not try to or to access any part of the system that is not available for the public use. You are not allowed to allow any other person besides yourself to login in our system using your unique user ID and password. You will not allow access to it to anyone else. This information is confidential and you may request for us to send you a recovery password to the account you provided during the registration stage if you are to forget your information.</p> <p>Any damages or intrusion to the data saved by the Usagreencard.online is not liable on the company but nonetheless, Usagreencard.online has made every possible effort to make sure the information provided by you is secure and confidential.</p> <p>All the users who win a green card through us in the DV program are granted a free airline ticket to the United States. Restrictions apply.</p> <p>The usage of this website is prohibited by anyone who is under the age of 18.</p> <h5><strong>Modifications</strong></h5> <hr> <p>Any feature of the services can be modified or discontinued and Usagreencard.online holds the right to do so at any time for any possible reason. It includes the functionality or pricing of the services, content as well as the availability of services but is not only limited to that.</p> <h5><strong>Immigration Laws</strong></h5> <hr> <p>If you want to gather information about any particular circumstances by consulting with an immigration advisor then you are responsible for it.</p> <h5><strong>Trademarks & Copyrights</strong></h5> <hr> <p>The logos, all trademarks, and service marks that are displayed on the website are the exclusive property of Usagreencard.online. Prior written consent of Usagreencard.online is required to use any of these marks and you may not use any of the marks without it. The trademark of “Usagreencard.online” is registered to the organization of Usagreencard.online. No user can take the liberty to use any of our trademarks without the prior written consent.</p> <p>Every piece of information this website contains is copyright protected. All the photographs, text, illustrations, artwork, logos, music, trademarks, all other content and the service marks are included in the copyright protection. The users can display all the content only for personal and non-commercial use. You agree not to reproduce, modify, sell, broadcast, publish, distribute or use any of the material otherwise without the express written permission.</p> <h5><strong>Purchase</strong></h5> <hr> <p>All our products can be purchased via our call center. <br> Immigration Book Part 1: (69 USD) <br> Immigration Book Part 2: (59 USD) <br> Immigration Book Part 3: (59 USD) <br> Typing Instructor cd: (49 USD) <br> Resume maker cd: (49 USD) <br> Easy English cd: (49 USD) </p> <p> Delivery <br> The address that you have supplied to us serves as the place of delivery. <br> We will deliver accepted orders as indicated here, within 14 business days of acceptance unless a longer delivery period has been agreed. </p> <p> Returns <br> We gladly accept returns for all products within 30 days of purchase. Returned products must be new and unused.(close box / not used) Please note: <br> • The Return Policy is neither a trial period nor an extension of any warranty and damage claim period. <br> • Opening a box to verify contents does not disallow a return. Products showing signs of use or missing inner packaging are not considered new, and are thus non-returnable. <br> • The condition and packaging of a returned product must be as it was when received, complete with all original packaging. <br> • Please be careful when opening your item(s) so that you can get a refund should the item not be what you imagined. <br> • All return shipping charges and materials are your responsibility. <br> • The original shipping charges or express shipping charges are non-refundable. <br> • If you refuse the delivery of a package, you’ll be charged for return shipping, (and in case of free shipping also for the original shipping costs). </p> <h5><strong>Customs holds</strong></h5> <hr> <p>In case there is a custom hold, you will be required to resolve the matter by communicating directly with the customs department of your country. We will do our best to provide you with the additional documents required in order to get the necessary clearance for your goods. Please note that the customs department of your country can hold the goods indefinitely and in most cases, the decision is not subject to appeal. However, in the majority of the cases, it takes a period of 1 day to 6 months until the goods are released.</p> <p>If the goods were not allowed to enter then the shipment will either be destroyed or shipped back to <a href="{% url 'pages_app:home' %}">usagreencard.online</a> </p> <p>The users will not get a refund or entitled to it if:</p> <br> •The user refuses to accept the goods. <br> •For being in a restricted category, goods could not clear the customs department. <br> •The user refuses to pay and accept the applicable taxes that are associated with the import procedure. <br> •The user is unable to accept the goods because it is in direct contradiction to the laws in that country (like not having the import license for the goods). <br> •We already notified the increased risk of delivery problems but the user insisted and explicitly agreed to proceed. <h5><strong>Jurisdictions</strong></h5> <hr> <p>Legal Restrictions – Laws regarding financial contracts are not same everywhere around the world so without limiting the mentioned provisions, the responsibility is yours’ to ensure that you comply with any law properly and with the guidelines and regulations of your country of residence in regard to using the website. To clear the doubts, the ability to access our site to use our services or your activities through the site does not necessarily mean that it is legal under the laws or directives and regulations of your home country.</p> <h5><strong>Miscellaneous</strong></h5> <hr> <p>Usagreencard.online hold the right to terminate your access immediately to our services if we discover that you are in violation of this agreement.</p> <p style="margin-bottom: 50px">Amerigo Marketing LTD. Our office is located in 82 Athinon | Akinita lerad Mitropoleos | Office 206, 3040 | Limassol, Cyprus.</p> </div> </div> </div> {% endblock %} <file_sep>from django.urls import path from .views import DvProgramView from django.views.generic import TemplateView app_name = "pages_app" urlpatterns = [ path("home/", TemplateView.as_view(template_name="pages_app/home.html"), name="home"), path("dv-program/", TemplateView.as_view(template_name="pages_app/dv_program.html"), name="dv-program"), path("contact/", TemplateView.as_view(template_name="pages_app/contact.html"), name="contact"), path("about/", TemplateView.as_view(template_name="pages_app/about.html"), name="about"), path("how-to-reg/", TemplateView.as_view(template_name="pages_app/how_to_reg.html"), name="how_to_reg"), path("requirements/", TemplateView.as_view(template_name="pages_app/requirements.html"), name="requirements"), path("green-card-process/", TemplateView.as_view(template_name="pages_app/green_card_process.html"), name="green_card_process"), path("advantages/", TemplateView.as_view(template_name="pages_app/advantages.html"), name="advantages"), path("private-entity/", TemplateView.as_view(template_name="pages_app/private_entity.html"), name="private_entity"), path("testimonials/", TemplateView.as_view(template_name="pages_app/testimonials.html"), name="testimonials"), path("terms-conditions/", TemplateView.as_view(template_name="pages_app/terms_conds.html"), name="terms_conds"), path("privacy-policy/", TemplateView.as_view(template_name="pages_app/privacy_policy.html"), name="privacy_policy"), path("eligible-countries/", TemplateView.as_view(template_name="pages_app/eligible_countries.html"), name="eligible_countries"), path("register/", TemplateView.as_view(template_name="pages_app/register.html"), name="register"), ] <file_sep>from django.urls import path from django.views.generic import TemplateView class DvProgramView(TemplateView): template_name = 'pages_app/dv_program.html' class ContactUsView(TemplateView): template_name = 'pages_app/contact.html'
03948db200ea8d0bd24c7d5a806b0972d3ca0575
[ "Python", "HTML" ]
3
HTML
DancingChaos/USA_GreenCard
675bd54b003da548f4175d0c8121e5c0e3ea65ce
a5fc81e199b493f49fe3f504dd03ce92d0cd4e42
refs/heads/master
<file_sep>#Return the index of the number you are searching for array = [] def create_array(top): for i in top: array.append(i) create_array(list(range(90))) def binary_search(array, number_to_search): pivot = int((len(array)/2)) if number_to_search > array[-1] or number_to_search < array[0]: return "Number is not on the list" if number_to_search == array[pivot]: return True if number_to_search < array[pivot]: return binary_search(array[:pivot], number_to_search) if number_to_search > array[pivot]: return binary_search(array[(pivot+1):], number_to_search) return False array2 = [3,4,5,6,7] print(binary_search(array2, 3))
edaf2451160c1521b4d7709bc5f039b7296f5f9a
[ "Python" ]
1
Python
dvilla/binary_search_python
1a77789f77757444bd956dfd36429f049f77182a
6b926ad6b8a7d3e9dbf04517d987361ef47d9186
refs/heads/master
<file_sep># Tic-Tac-Toe-JS In this project i have made a tic tac toe game using html , css , JavaScript. Github website link https://sachinprajapati8604.github.io/Tic-Tac-Toe-JS/ <file_sep>// making a onload function to take name function my_code(){ var name=prompt("Enter your name "); if(name!=""){ document.getElementById("msg").innerHTML="Hello "+name+" let's play Tic Tac Toe with <NAME> "; document.getElementById("oppo").innerHTML=name+" symbol - X"; document.getElementById("me").innerHTML="<NAME> symbol - O"; } if(name=="" ||name==null){ my_code(); } } window.onload=my_code(); var x=document.getElementById('X'); var o=document.getElementById('O'); var turn=document.getElementById('turn'); var player=""; var winOfX=0; var winofO=0; var count = 1; function fill(control) { //now we are binding the condition if we fill all 9 box if (count <= 9) { if (count % 2 != 0) { //this will return the clicked box id because i have used this object in click function document.getElementById(control.id).innerHTML = "X"; player="X Win"; } else { document.getElementById(control.id).innerHTML = "O"; player="O Win"; } //toggling if(document.getElementById(control.id).innerHTML=="X"){ turn.innerHTML="O-turn" o.style.background="green"; x.style.background="#fff"; }else{ turn.innerHTML="X-turn"; x.style.background="green"; o.style.background="#fff"; } count++; if (checkWin()) { if(player=="X Win"){ winOfX++; }else{ winofO++; } document.getElementById('xwin').innerHTML="X-Win - "+winOfX; document.getElementById('owin').innerHTML="O-Win - "+winofO; turn.innerHTML=player; reset(); } } else { turn.innerHTML="Game Draw"; reset(); } } //to reset all boxes after all filled function reset() { for (var i = 1; i <= 9; i++) { document.getElementById('box' + i).innerHTML = ""; } // turn.innerHTML="X-turn" x.style.background="green"; o.style.background="#fff"; count=1; //set the value of count to 1 after reset } //to check win function checkWin() { if(checkCondition('box1','box2','box3') || checkCondition('box4','box5','box6') || checkCondition('box7','box8','box9') || checkCondition('box1','box4','box7') || checkCondition('box2','box5','box8') || checkCondition('box3','box6','box9') || checkCondition('box1','box5','box9') || checkCondition('box3','box5','box7')){ return true; } } function getData(box){ return document.getElementById(box).innerHTML; } function checkCondition(box1,box2,box3){ if(getData(box1)!="" && getData(box2)!="" && getData(box3)!="" && getData(box1)==getData(box2) &&getData(box2)==getData(box3)){ return true; } }
ad4b9c4e7833fda116d8bde62a003e8b6ecd30d0
[ "Markdown", "JavaScript" ]
2
Markdown
KryshnaRathod/Tic-Tac-Toe
a2ef0f8f4e7610591c8cc6263a718911f5066f88
4e4b1ccf040949623ddf8f255a2271a85dfc200f
refs/heads/master
<repo_name>vibhatha/fti<file_sep>/travisScripts/install-openmpi-1.10.sh #!/bin/bash MPIVER="1.10.7" wget --no-check-certificate https://www.open-mpi.org/software/ompi/v1.10/downloads/openmpi-1.10.7.tar.gz tar -zxf openmpi-1.10.7.tar.gz cd openmpi-1.10.7 echo "CONFIGURE OPENMPI (VER: $MPIVER)" bash ./configure --prefix=$HOME/openmpi-$MPIVER CC=gcc CXX=g++ > /dev/null 2>&1 echo "MAKE OPENMPI (VER: $MPIVER)" make -j 4 > /dev/null 2>&1 echo "INSTALL OPENMPI (VER: $MPIVER)" sudo make install > /dev/null 2>&1 export PATH=$HOME/openmpi-$MPIVER/bin:$PATH export LD_LIBRARY_PATH=$HOME/openmpi-$MPIVER/lib/:$LD_LIBRARY_PATH <file_sep>/src/checkpoint.c /** * Copyright (c) 2017 <NAME> * All rights reserved * * FTI - A multi-level checkpointing library for C/C++/Fortran applications * * Revision 1.0 : Fault Tolerance Interface (FTI) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file checkpoint.c * @date October, 2017 * @brief Checkpointing functions for the FTI library. */ #ifndef LUSTRE # define _POSIX_C_SOURCE 200809L #endif #include <string.h> #include "interface.h" #include "ftiff.h" #include "api_cuda.h" #include "utility.h" /*-------------------------------------------------------------------------*/ /** @brief It updates the local and global mean iteration time. @param FTI_Exec Execution metadata. @return integer FTI_SCES if successful. This function updates the local and global mean iteration time. It also recomputes the checkpoint interval in iterations and corrects the next checkpointing iteration based on the observed mean iteration duration. **/ /*-------------------------------------------------------------------------*/ int FTI_UpdateIterTime(FTIT_execution* FTI_Exec) { int nbProcs, res; char str[FTI_BUFS]; double last = FTI_Exec->iterTime; FTI_Exec->iterTime = MPI_Wtime(); if (FTI_Exec->ckptIcnt > 0) { FTI_Exec->lastIterTime = FTI_Exec->iterTime - last; FTI_Exec->totalIterTime = FTI_Exec->totalIterTime + FTI_Exec->lastIterTime; if (FTI_Exec->ckptIcnt % FTI_Exec->syncIter == 0) { FTI_Exec->meanIterTime = FTI_Exec->totalIterTime / FTI_Exec->ckptIcnt; MPI_Allreduce(&FTI_Exec->meanIterTime, &FTI_Exec->globMeanIter, 1, MPI_DOUBLE, MPI_SUM, FTI_COMM_WORLD); MPI_Comm_size(FTI_COMM_WORLD, &nbProcs); FTI_Exec->globMeanIter = FTI_Exec->globMeanIter / nbProcs; if (FTI_Exec->globMeanIter > 60) { FTI_Exec->ckptIntv = 1; } else { FTI_Exec->ckptIntv = rint(60.0 / FTI_Exec->globMeanIter); } res = FTI_Exec->ckptLast + FTI_Exec->ckptIntv; if (FTI_Exec->ckptLast == 0) { res = res + 1; } if (res >= FTI_Exec->ckptIcnt) { FTI_Exec->ckptNext = res; } snprintf(str, FTI_BUFS, "Current iter : %d ckpt intv. : %d . Next ckpt. at iter. %d . Sync. intv. : %d", FTI_Exec->ckptIcnt, FTI_Exec->ckptIntv, FTI_Exec->ckptNext, FTI_Exec->syncIter); FTI_Print(str, FTI_DBUG); if ((FTI_Exec->syncIter < (FTI_Exec->ckptIntv / 2)) && (FTI_Exec->syncIter < FTI_Exec->syncIterMax)) { FTI_Exec->syncIter = FTI_Exec->syncIter * 2; snprintf(str, FTI_BUFS, "Iteration frequency : %.2f sec/iter => %d iter/min. Resync every %d iter.", FTI_Exec->globMeanIter, FTI_Exec->ckptIntv, FTI_Exec->syncIter); FTI_Print(str, FTI_DBUG); if (FTI_Exec->syncIter == FTI_Exec->syncIterMax) { snprintf(str, FTI_BUFS, "Sync. intv. has reached max value => %i iterations", FTI_Exec->syncIterMax); FTI_Print(str, FTI_DBUG); } } } } FTI_Exec->ckptIcnt++; // Increment checkpoint loop counter return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief It writes the checkpoint data in the target file. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function checks whether the checkpoint needs to be local or remote, opens the target file and writes dataset per dataset, the checkpoint data, it finally flushes and closes the checkpoint file. **/ /*-------------------------------------------------------------------------*/ int FTI_WriteCkpt(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { char str[FTI_BUFS]; //For console output snprintf(str, FTI_BUFS, "Starting writing checkpoint (ID: %d, Lvl: %d)", FTI_Exec->ckptID, FTI_Exec->ckptLvel); FTI_Print(str, FTI_DBUG); //update ckpt file name snprintf(FTI_Exec->meta[0].ckptFile, FTI_BUFS, "Ckpt%d-Rank%d.fti", FTI_Exec->ckptID, FTI_Topo->myRank); #ifdef ENABLE_HDF5 //If HDF5 is installed overwrite the name if (FTI_Conf->ioMode == FTI_IO_HDF5) { snprintf(FTI_Exec->meta[0].ckptFile, FTI_BUFS, "Ckpt%d-Rank%d.h5", FTI_Exec->ckptID, FTI_Topo->myRank); } #endif //If checkpoint is inlin and level 4 save directly to PFS int res; //response from writing funcitons if (FTI_Ckpt[4].isInline && FTI_Exec->ckptLvel == 4) { if ( !(FTI_Conf->dcpEnabled && FTI_Ckpt[4].isDcp) ) { FTI_Print("Saving to temporary global directory", FTI_DBUG); //Create global temp directory if (mkdir(FTI_Conf->gTmpDir, 0777) == -1) { if (errno != EEXIST) { FTI_Print("Cannot create global directory", FTI_EROR); return FTI_NSCS; } } } else { if ( !FTI_Ckpt[4].hasDcp ) { if (mkdir(FTI_Ckpt[4].dcpDir, 0777) == -1) { if (errno != EEXIST) { FTI_Print("Cannot create global dCP directory", FTI_EROR); return FTI_NSCS; } } } } switch (FTI_Conf->ioMode) { case FTI_IO_POSIX: res = FTI_Try(FTI_WritePosix(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt, FTI_Data), "write checkpoint to PFS (POSIX I/O)."); break; case FTI_IO_MPI: res = FTI_Try(FTI_WriteMPI(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Data), "write checkpoint to PFS (MPI-IO)."); break; #ifdef ENABLE_SIONLIB //If SIONlib is installed case FTI_IO_SIONLIB: res = FTI_Try(FTI_WriteSionlib(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Data), "write checkpoint to PFS (Sionlib)."); break; #endif case FTI_IO_FTIFF: res = FTI_Try(FTIFF_WriteFTIFF(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt, FTI_Data), "write checkpoint to PFS (FTI-FF)."); break; #ifdef ENABLE_HDF5 //If HDF5 is installed case FTI_IO_HDF5: res = FTI_Try(FTI_WriteHDF5(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt, FTI_Data), "write checkpoint to PFS (HDF5)."); break; #endif } } else { if ( !(FTI_Conf->dcpEnabled && FTI_Ckpt[4].isDcp) ) { FTI_Print("Saving to temporary local directory", FTI_DBUG); //Create local temp directory if (mkdir(FTI_Conf->lTmpDir, 0777) == -1) { if (errno != EEXIST) { FTI_Print("Cannot create local directory", FTI_EROR); } } } else { if ( !FTI_Ckpt[4].hasDcp ) { if (mkdir(FTI_Ckpt[1].dcpDir, 0777) == -1) { if (errno != EEXIST) { FTI_Print("Cannot create global dCP directory", FTI_EROR); return FTI_NSCS; } } } } switch (FTI_Conf->ioMode) { case FTI_IO_FTIFF: res = FTI_Try(FTIFF_WriteFTIFF(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt, FTI_Data), "write checkpoint using FTI-FF."); break; #ifdef ENABLE_HDF5 //If HDF5 is installed case FTI_IO_HDF5: res = FTI_Try(FTI_WriteHDF5(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt, FTI_Data), "write checkpoint (HDF5)."); break; #endif default: res = FTI_Try(FTI_WritePosix(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt, FTI_Data),"write checkpoint."); break; } } //Check if all processes have written correctly (every process must succeed) int allRes; MPI_Allreduce(&res, &allRes, 1, MPI_INT, MPI_SUM, FTI_COMM_WORLD); if (allRes != FTI_SCES) { return FTI_NSCS; } if ( FTI_Conf->dcpEnabled && FTI_Ckpt[4].isDcp ) { // After dCP update store total data and dCP sizes in application rank 0 long dcpStats[2]; // 0:totalDcpSize, 1:totalDataSize long sendBuf[] = { FTI_Exec->FTIFFMeta.dcpSize, FTI_Exec->FTIFFMeta.pureDataSize }; MPI_Reduce( sendBuf, dcpStats, 2, MPI_LONG, MPI_SUM, 0, FTI_COMM_WORLD ); if ( FTI_Topo->splitRank == 0 ) { FTI_Exec->FTIFFMeta.dcpSize = dcpStats[0]; FTI_Exec->FTIFFMeta.pureDataSize = dcpStats[1]; } } res = FTI_Try(FTI_CreateMetadata(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt, FTI_Data), "create metadata."); if ( (FTI_Conf->dcpEnabled || FTI_Conf->keepL4Ckpt) && (FTI_Topo->splitRank == 0) ) { FTI_WriteCkptMetaData( FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt ); } return res; } /*-------------------------------------------------------------------------*/ /** @brief Decides wich action start depending on the ckpt. level. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @return integer FTI_SCES if successful. This function launches the required action dependeing on the ckpt. level. It does that for each group (application process in the node) if executed by the head, or only locally if executed by an application process. The parameter pr determines if the for loops have 1 or number of App. procs. iterations. The group parameter helps determine the groupID in both cases. **/ /*-------------------------------------------------------------------------*/ int FTI_PostCkpt(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt) { char str[FTI_BUFS]; //For console output double t1 = MPI_Wtime(); //Start time int res; //Response from post-processing functions switch (FTI_Exec->ckptLvel) { case 4: res = FTI_Flush(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt, 0); break; case 3: res = FTI_RSenc(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt); break; case 2: res = FTI_Ptner(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt); break; case 1: res = FTI_Local(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt); break; } //Check if all processes done post-processing correctly int allRes; MPI_Allreduce(&res, &allRes, 1, MPI_INT, MPI_SUM, FTI_COMM_WORLD); if (allRes != FTI_SCES) { FTI_Print("Error postprocessing checkpoint. Discarding current checkpoint...", FTI_WARN); FTI_Clean(FTI_Conf, FTI_Topo, FTI_Ckpt, 0); //Remove temporary files return FTI_NSCS; } double t2 = MPI_Wtime(); //Post-processing time // rename l4 checkpoint file before deleting l4 folder if keepL4Ckpt enabled if ( FTI_Conf->keepL4Ckpt && FTI_Exec->ckptLvel == 4 ) { if ( FTI_Ckpt[4].hasCkpt ) { FTI_ArchiveL4Ckpt( FTI_Conf, FTI_Exec, FTI_Ckpt, FTI_Topo ); } // store current ckpt file name in meta data. if ( !FTI_Topo->amIaHead ) { strncpy(FTI_Exec->meta[0].currentL4CkptFile, FTI_Exec->meta[0].ckptFile, FTI_BUFS); } else { int i; for( i=1; i<FTI_Topo->nodeSize; ++i ) { strncpy(&FTI_Exec->meta[0].currentL4CkptFile[i * FTI_BUFS], &FTI_Exec->meta[0].ckptFile[i * FTI_BUFS], FTI_BUFS); } } } FTI_Clean(FTI_Conf, FTI_Topo, FTI_Ckpt, FTI_Exec->ckptLvel); //delete previous files on this checkpoint level int nodeFlag = (((!FTI_Topo->amIaHead) && ((FTI_Topo->nodeRank - FTI_Topo->nbHeads) == 0)) || (FTI_Topo->amIaHead)) ? 1 : 0; nodeFlag = (!FTI_Ckpt[4].isDcp && (nodeFlag != 0)); if (nodeFlag) { //True only for one process in the node. //Debug message needed to test nodeFlag (./tests/nodeFlag/nodeFlag.c) snprintf(str, FTI_BUFS, "Has nodeFlag = 1 and nodeID = %d. CkptLvel = %d.", FTI_Topo->nodeID, FTI_Exec->ckptLvel); FTI_Print(str, FTI_DBUG); if (!(FTI_Ckpt[4].isInline && FTI_Exec->ckptLvel == 4)) { //checkpoint was not saved in global temporary directory int level = (FTI_Exec->ckptLvel != 4) ? FTI_Exec->ckptLvel : 1; //if level 4: head moves local ckpt files to PFS if (rename(FTI_Conf->lTmpDir, FTI_Ckpt[level].dir) == -1) { char dbg_str[FTI_BUFS]; snprintf(dbg_str, FTI_BUFS, "Cannot rename local directory (%s)", FTI_Conf->lTmpDir); FTI_Print(dbg_str, FTI_EROR); } else { FTI_Print("Local directory renamed", FTI_DBUG); } } } int globalFlag = !FTI_Topo->splitRank; globalFlag = (!FTI_Ckpt[4].isDcp && (globalFlag != 0)); if (globalFlag) { //True only for one process in the FTI_COMM_WORLD. if (FTI_Exec->ckptLvel == 4) { if (rename(FTI_Conf->gTmpDir, FTI_Ckpt[4].dir) == -1) { FTI_Print("Cannot rename global directory", FTI_EROR); } } // there is no temp meta data folder for FTI-FF if ( FTI_Conf->ioMode != FTI_IO_FTIFF ) { if (rename(FTI_Conf->mTmpDir, FTI_Ckpt[FTI_Exec->ckptLvel].metaDir) == -1) { FTI_Print("Cannot rename meta directory", FTI_EROR); } } } MPI_Barrier(FTI_COMM_WORLD); //barrier needed to wait for process to rename directories (new temporary could be needed in next checkpoint) double t3 = MPI_Wtime(); //Renaming directories time snprintf(str, FTI_BUFS, "Post-checkpoint took %.2f sec. (Pt:%.2fs, Cl:%.2fs)", t3 - t1, t2 - t1, t3 - t2); FTI_Print(str, FTI_INFO); // expose to FTI that a checkpoint exists for level FTI_Ckpt[FTI_Exec->ckptLvel].hasCkpt = true; return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief It listens for checkpoint notifications. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @return integer FTI_SCES if successful. This function listens for notifications from the application processes and takes the required actions after notification. This function is only executed by the head of the nodes and its complementary with the FTI_Checkpoint function in terms of communications. **/ /*-------------------------------------------------------------------------*/ int FTI_Listen(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt) { MPI_Status ckpt_status; int ckpt_flag = 0; MPI_Status stage_status; int stage_flag = 0; MPI_Status finalize_status; int finalize_flag = 0; FTI_Print("Head starts listening...", FTI_DBUG); while (1) { //heads can stop only by receiving FTI_ENDW FTI_Print("Head waits for message...", FTI_DBUG); MPI_Iprobe( MPI_ANY_SOURCE, FTI_Conf->finalTag, FTI_Exec->globalComm, &finalize_flag, &finalize_status ); if ( FTI_Conf->stagingEnabled ) { MPI_Iprobe( MPI_ANY_SOURCE, FTI_Conf->stageTag, FTI_Exec->nodeComm, &stage_flag, &stage_status ); } MPI_Iprobe( MPI_ANY_SOURCE, FTI_Conf->ckptTag, FTI_Exec->globalComm, &ckpt_flag, &ckpt_status ); if( ckpt_flag ) { // head will process the whole checkpoint // (treated second due to priority) FTI_HandleCkptRequest( FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt ); ckpt_flag = 0; continue; } if ( stage_flag ) { // head will process each unstage request on its own // [A MAYBE: we could interrupt the unstageing process if // we receive a checkpoint request.] FTI_HandleStageRequest( FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt, stage_status.MPI_SOURCE ); stage_flag = 0; continue; } // the 'continue' statement ensures that we first process all // checkpoint and staging request before we call finalize. if ( finalize_flag ) { char str[FTI_BUFS]; FTI_Print("Head waits for message...", FTI_DBUG); int val = 0, i; for (i = 0; i < FTI_Topo->nbApprocs; i++) { // Iterate on the application processes in the node int buf; MPI_Recv(&buf, 1, MPI_INT, FTI_Topo->body[i], FTI_Conf->finalTag, FTI_Exec->globalComm, MPI_STATUS_IGNORE); snprintf(str, FTI_BUFS, "The head received a %d message", buf); FTI_Print(str, FTI_DBUG); val += buf; } val /= FTI_Topo->nbApprocs; if ( val != FTI_ENDW) { // If we were asked to finalize FTI_Print( "Inconsistency in Finalize request.", FTI_WARN ); } FTI_Print("Head stopped listening.", FTI_DBUG); FTI_Finalize(); if ( FTI_Conf->keepHeadsAlive ) { break; } } } // will be reached only if keepHeadsAlive is TRUE return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief handles checkpoint requests from application ranks (if head). @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ int FTI_HandleCkptRequest(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt) { char str[FTI_BUFS]; //For console output int flags[7]; //Increment index if get corresponding value from application process //(index (1 - 4): checkpoint level; index 5: stops head; index 6: reject checkpoint) int i; for (i = 0; i < 7; i++) { // Initialize flags flags[i] = 0; } FTI_Print("Head waits for message...", FTI_DBUG); for (i = 0; i < FTI_Topo->nbApprocs; i++) { // Iterate on the application processes in the node int buf; MPI_Recv(&buf, 1, MPI_INT, FTI_Topo->body[i], FTI_Conf->ckptTag, FTI_Exec->globalComm, MPI_STATUS_IGNORE); snprintf(str, FTI_BUFS, "The head received a %d message", buf); FTI_Print(str, FTI_DBUG); flags[buf - FTI_BASE] = flags[buf - FTI_BASE] + 1; } for (i = 1; i < 7; i++) { if (flags[i] == FTI_Topo->nbApprocs) { // Determining checkpoint level FTI_Exec->ckptLvel = i; } } if (flags[6] > 0) { FTI_Exec->ckptLvel = 6; } int isDcpCnt = 0; // FTI-FF: receive meta data information from the application ranks. if ( FTI_Conf->ioMode == FTI_IO_FTIFF && FTI_Exec->ckptLvel != 6 && FTI_Exec->ckptLvel != 5 ) { // init headInfo FTIFF_headInfo *headInfo; headInfo = malloc(FTI_Topo->nbApprocs * sizeof(FTIFF_headInfo)); int k; for (i = 0; i < FTI_Topo->nbApprocs; i++) { // Iterate on the application processes in the node k = i+1; MPI_Recv(&(headInfo[i]), 1, FTIFF_MpiTypes[FTIFF_HEAD_INFO], FTI_Topo->body[i], FTI_Conf->generalTag, FTI_Exec->globalComm, MPI_STATUS_IGNORE); FTI_Exec->meta[0].exists[k] = headInfo[i].exists; FTI_Exec->meta[0].nbVar[k] = headInfo[i].nbVar; FTI_Exec->meta[0].maxFs[k] = headInfo[i].maxFs; FTI_Exec->meta[0].fs[k] = headInfo[i].fs; FTI_Exec->meta[0].pfs[k] = headInfo[i].pfs; isDcpCnt += headInfo[i].isDcp; MPI_Recv(&(FTI_Exec->meta[0].varID[k * FTI_BUFS]), headInfo[i].nbVar, MPI_INT, FTI_Topo->body[i], FTI_Conf->generalTag, FTI_Exec->globalComm, MPI_STATUS_IGNORE); MPI_Recv(&(FTI_Exec->meta[0].varSize[k * FTI_BUFS]), headInfo[i].nbVar, MPI_LONG, FTI_Topo->body[i], FTI_Conf->generalTag, FTI_Exec->globalComm, MPI_STATUS_IGNORE); strncpy(&(FTI_Exec->meta[0].ckptFile[k * FTI_BUFS]), headInfo[i].ckptFile , FTI_BUFS); sscanf(&(FTI_Exec->meta[0].ckptFile[k * FTI_BUFS]), "Ckpt%d", &FTI_Exec->ckptID); } strcpy(FTI_Exec->meta[FTI_Exec->ckptLvel].ckptFile, FTI_Exec->meta[0].ckptFile); if ( FTI_Conf->dcpEnabled ) { if ( (isDcpCnt == FTI_Topo->nbApprocs) && FTI_Conf->dcpEnabled ) { FTI_Ckpt[4].isDcp = true; } } else { isDcpCnt = 0; } free(headInfo); } //Check if checkpoint was written correctly by all processes int res = (FTI_Exec->ckptLvel == 6) ? FTI_NSCS : FTI_SCES; // check for consistency of dCP request (isDcpCnt is 0 if dCP is disabled) if ( (isDcpCnt > 0) && (isDcpCnt < FTI_Topo->nbApprocs) ) { FTI_Print( "dCP was requested by some but not all ranks, discarding checkpoint request!", FTI_WARN ); res = FTI_NSCS; } int allRes; MPI_Allreduce(&res, &allRes, 1, MPI_INT, MPI_SUM, FTI_COMM_WORLD); if (allRes == FTI_SCES) { //If checkpoint was written correctly do post-processing res = FTI_Try(FTI_PostCkpt(FTI_Conf, FTI_Exec, FTI_Topo, FTI_Ckpt), "postprocess the checkpoint."); if (res == FTI_SCES) { res = FTI_Exec->ckptLvel; //return ckptLvel if post-processing succeeds } } else { //If checkpoint wasn't written correctly FTI_Print("Checkpoint have not been witten correctly. Discarding current checkpoint...", FTI_WARN); FTI_Clean(FTI_Conf, FTI_Topo, FTI_Ckpt, 0); //Remove temporary files res = FTI_NSCS; } for (i = 0; i < FTI_Topo->nbApprocs; i++) { // Send msg. to avoid checkpoint collision MPI_Send(&res, 1, MPI_INT, FTI_Topo->body[i], FTI_Conf->generalTag, FTI_Exec->globalComm); } return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Writes ckpt to PFS using POSIX. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ int FTI_WritePosix(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { int res = FTI_SCES; FTI_Print("I/O mode: Posix.", FTI_DBUG); char str[FTI_BUFS], fn[FTI_BUFS]; int level = FTI_Exec->ckptLvel; if (level == 4 && FTI_Ckpt[4].isInline) { //If inline L4 save directly to global directory snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->gTmpDir, FTI_Exec->meta[0].ckptFile); } else { snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->lTmpDir, FTI_Exec->meta[0].ckptFile); } // open task local ckpt file FILE* fd = fopen(fn, "wb"); if (fd == NULL) { snprintf(str, FTI_BUFS, "FTI checkpoint file (%s) could not be opened.", fn); FTI_Print(str, FTI_EROR); return FTI_NSCS; } // write data into ckpt file int i; for (i = 0; i < FTI_Exec->nbVar; i++) { clearerr(fd); if (!ferror(fd)) { errno = 0; // if data are stored to CPU just write them if ( !(FTI_Data[i].isDevicePtr) ){ snprintf(str, FTI_BUFS, "ID: %d Data are . %d %p %p", FTI_Data[i].id,FTI_Data[i].isDevicePtr,FTI_Data[i].ptr,FTI_Data[i].devicePtr); FTI_Print(str,FTI_DBUG); if (( res = FTI_Try( write_posix(FTI_Data[i].ptr, FTI_Data[i].size, fd), "Storing Data to Checkpoint File"))!=FTI_SCES){ snprintf(str, FTI_BUFS, "Dataset #%d could not be written.", FTI_Data[i].id); FTI_Print(str, FTI_EROR); fclose(fd); return res; } } #ifdef GPUSUPPORT // if data are stored to the GPU move them from device // memory to cpu memory and store them. else { if ((res = FTI_Try( FTI_TransferDeviceMemToFileAsync(&FTI_Data[i], write_posix, fd), "moving data from GPU to storage")) != FTI_SCES) { snprintf(str, FTI_BUFS, "Dataset #%d could not be written.", FTI_Data[i].id); FTI_Print(str, FTI_EROR); fclose(fd); return res; } } #endif } if (ferror(fd)) { char error_msg[FTI_BUFS]; error_msg[0] = 0; strerror_r(errno, error_msg, FTI_BUFS); snprintf(str, FTI_BUFS, "%d Dataset #%d could not be written: %s.",__LINE__, FTI_Data[i].id, error_msg); FTI_Print(str, FTI_EROR); fclose(fd); return FTI_NSCS; } } // close file if (fclose(fd) != 0) { FTI_Print("FTI checkpoint file could not be closed.", FTI_EROR); return FTI_NSCS; } return res; } /*-------------------------------------------------------------------------*/ /** @brief Writes ckpt to PFS using MPI I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. In here it is taken into account, that in MPIIO the count parameter in both, MPI_Type_contiguous and MPI_File_write_at, are integer types. The ckpt data is split into chunks of maximal (MAX_INT-1)/2 elements to form contiguous data types. It was experienced, that if the size is greater then that, it may lead to problems. **/ /*-------------------------------------------------------------------------*/ int FTI_WriteMPI(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_dataset* FTI_Data) { WriteMPIInfo_t write_info; int res; FTI_Print("I/O mode: MPI-IO.", FTI_DBUG); char str[FTI_BUFS], mpi_err[FTI_BUFS]; write_info.FTI_Conf = FTI_Conf; // enable collective buffer optimization MPI_Info info; MPI_Info_create(&info); MPI_Info_set(info, "romio_cb_write", "enable"); // TODO enable to set stripping unit in the config file (Maybe also other hints) // set stripping unit to 4MB MPI_Info_set(info, "stripping_unit", "4194304"); MPI_Offset chunkSize = FTI_Exec->ckptSize; // collect chunksizes of other ranks MPI_Offset* chunkSizes = talloc(MPI_Offset, FTI_Topo->nbApprocs * FTI_Topo->nbNodes); MPI_Allgather(&chunkSize, 1, MPI_OFFSET, chunkSizes, 1, MPI_OFFSET, FTI_COMM_WORLD); char gfn[FTI_BUFS], ckptFile[FTI_BUFS]; snprintf(ckptFile, FTI_BUFS, "Ckpt%d-mpiio.fti", FTI_Exec->ckptID); snprintf(gfn, FTI_BUFS, "%s/%s", FTI_Conf->gTmpDir, ckptFile); // open parallel file (collective call) // MPI_File pfh; #ifdef LUSTRE if (FTI_Topo->splitRank == 0) { res = llapi_file_create(gfn, FTI_Conf->stripeUnit, FTI_Conf->stripeOffset, FTI_Conf->stripeFactor, 0); if (res) { char error_msg[FTI_BUFS]; error_msg[0] = 0; strerror_r(-res, error_msg, FTI_BUFS); snprintf(str, FTI_BUFS, "[Lustre] %s.", error_msg); FTI_Print(str, FTI_WARN); } else { snprintf(str, FTI_BUFS, "[LUSTRE] file:%s striping_unit:%i striping_factor:%i striping_offset:%i", ckptFile, FTI_Conf->stripeUnit, FTI_Conf->stripeFactor, FTI_Conf->stripeOffset); FTI_Print(str, FTI_DBUG); } } #endif res = MPI_File_open(FTI_COMM_WORLD, gfn, MPI_MODE_WRONLY|MPI_MODE_CREATE, info, &(write_info.pfh)); // check if successful if (res != 0) { errno = 0; int reslen; MPI_Error_string(res, mpi_err, &reslen); snprintf(str, FTI_BUFS, "unable to create file [MPI ERROR - %i] %s", res, mpi_err); FTI_Print(str, FTI_EROR); free(chunkSizes); return FTI_NSCS; } // set file offset write_info.offset = 0; int i; for (i = 0; i < FTI_Topo->splitRank; i++) { write_info.offset += chunkSizes[i]; } free(chunkSizes); for (i = 0; i < FTI_Exec->nbVar; i++) { // determine the type of data pointer // Data are stored in the CPU side. if ( !(FTI_Data[i].isDevicePtr) ){ res = write_mpi(FTI_Data[i].ptr, FTI_Data[i].size, &write_info); } #ifdef GPUSUPPORT // dowload data from the GPU if necessary // Data are stored in the GPU side. else { if ((res = FTI_Try( FTI_TransferDeviceMemToFileAsync(&FTI_Data[i], write_mpi, &write_info), "moving data from GPU to storage")) != FTI_SCES) { snprintf(str, FTI_BUFS, "Dataset #%d could not be written.", FTI_Data[i].id); FTI_Print(str, FTI_EROR); MPI_File_close(&write_info.pfh); return res; } } #endif // check if successful if (res != 0) { errno = 0; int reslen; MPI_Error_string(write_info.err, mpi_err, &reslen); snprintf(str, FTI_BUFS, "Failed to write protected_var[%i] to PFS [MPI ERROR - %i] %s", i, write_info.err, mpi_err); FTI_Print(str, FTI_EROR); MPI_File_close(&write_info.pfh); return FTI_NSCS; } } MPI_File_close(&write_info.pfh); MPI_Info_free(&info); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Writes ckpt to PFS using SIONlib. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ #ifdef ENABLE_SIONLIB // --> If SIONlib is installed int FTI_WriteSionlib(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo,FTIT_dataset* FTI_Data) { int numFiles = 1; int nlocaltasks = 1; int* file_map = calloc(1, sizeof(int)); int* ranks = talloc(int, 1); int* rank_map = talloc(int, 1); sion_int64* chunkSizes = talloc(sion_int64, 1); int fsblksize = -1; chunkSizes[0] = FTI_Exec->ckptSize; ranks[0] = FTI_Topo->splitRank; rank_map[0] = FTI_Topo->splitRank; // open parallel file char fn[FTI_BUFS], str[FTI_BUFS]; snprintf(str, FTI_BUFS, "Ckpt%d-sionlib.fti", FTI_Exec->ckptID); snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->gTmpDir, str); int sid = sion_paropen_mapped_mpi(fn, "wb,posix", &numFiles, FTI_COMM_WORLD, &nlocaltasks, &ranks, &chunkSizes, &file_map, &rank_map, &fsblksize, NULL); // check if successful if (sid == -1) { errno = 0; FTI_Print("SIONlib: File could no be opened", FTI_EROR); free(file_map); free(rank_map); free(ranks); free(chunkSizes); return FTI_NSCS; } // set file pointer to corresponding block in sionlib file int res = sion_seek(sid, FTI_Topo->splitRank, SION_CURRENT_BLK, SION_CURRENT_POS); // check if successful if (res != SION_SUCCESS) { errno = 0; FTI_Print("SIONlib: Could not set file pointer", FTI_EROR); sion_parclose_mapped_mpi(sid); free(file_map); free(rank_map); free(ranks); free(chunkSizes); return FTI_NSCS; } // write datasets into file int i; for (i = 0; i < FTI_Exec->nbVar; i++) { // SIONlib write call if ( !(FTI_Data[i].isDevicePtr) ){ res = write_sion(FTI_Data[i].ptr, FTI_Data[i].size, &sid); } #ifdef GPUSUPPORT // if data are stored to the GPU move them from device // memory to cpu memory and store them. else { if ((res = FTI_Try( TransferDeviceMemToFileAsync(&FTI_Data[i], write_sion, &sid), "moving data from GPU to storage")) != FTI_SCES) { snprintf(str, FTI_BUFS, "Dataset #%d could not be written.", FTI_Data[i].id); FTI_Print(str, FTI_EROR); errno = 0; FTI_Print("SIONlib: Data could not be written", FTI_EROR); res = sion_parclose_mapped_mpi(sid); free(file_map); free(rank_map); free(ranks); free(chunkSizes); return res; } } #endif } // close parallel file if (sion_parclose_mapped_mpi(sid) == -1) { FTI_Print("Cannot close sionlib file.", FTI_WARN); free(file_map); free(rank_map); free(ranks); free(chunkSizes); return FTI_NSCS; } free(file_map); free(rank_map); free(ranks); free(chunkSizes); return FTI_SCES; } #endif <file_sep>/src/utility.c #include <string.h> #include "interface.h" #include "ftiff.h" #include "api_cuda.h" #include "utility.h" /*-------------------------------------------------------------------------*/ /** @brief Writes data to a file using the posix library @param src The location of the data to be written @param size The number of bytes that I need to write @param opaque A pointer to the File descriptor @return integer FTI_SCES if successful. Writes the data to a file using the posix library. **/ /*-------------------------------------------------------------------------*/ int write_posix(void *src, size_t size, void *opaque) { FILE *fd = (FILE *)opaque; size_t written = 0; int fwrite_errno; char str[FTI_BUFS]; while (written < size && !ferror(fd)) { errno = 0; written += fwrite(((char *)src) + written, 1, size - written, fd); fwrite_errno = errno; } if (ferror(fd)){ char error_msg[FTI_BUFS]; error_msg[0] = 0; strerror_r(fwrite_errno, error_msg, FTI_BUFS); snprintf(str, FTI_BUFS, "utility:c: (write_posix) Dataset could not be written: %s.", error_msg); FTI_Print(str, FTI_EROR); fclose(fd); return FTI_NSCS; } else return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Writes data to a file using the MPI-IO library @param src The location of the data to be written @param size The number of bytes that I need to write @param opaque A pointer to the struct that describes the MPI-IO file @return integer FTI_SCES if successful. Writes the data to a file using the MPI library. **/ /*-------------------------------------------------------------------------*/ int write_mpi(void *src, size_t size, void *opaque) { WriteMPIInfo_t *write_info = (WriteMPIInfo_t *)opaque; size_t pos = 0; size_t bSize = write_info->FTI_Conf->transferSize; while (pos < size) { if ((size - pos) < write_info->FTI_Conf->transferSize) { bSize = size - pos; } MPI_Datatype dType; MPI_Type_contiguous(bSize, MPI_BYTE, &dType); MPI_Type_commit(&dType); write_info->err = MPI_File_write_at(write_info->pfh, write_info->offset, src, 1, dType, MPI_STATUS_IGNORE); // check if successful if (write_info->err != 0) { errno = 0; return FTI_NSCS; } MPI_Type_free(&dType); src += bSize; write_info->offset += bSize; pos = pos + bSize; } return FTI_SCES; } #ifdef ENABLE_SIONLIB /*-------------------------------------------------------------------------*/ /** @brief Writes data to a file using the SION library @param src The location of the data to be written @param size The number of bytes that I need to write @param opaque A pointer to the file descriptor @return integer FTI_SCES if successful. Writes the data to a file using the SION library. **/ /*-------------------------------------------------------------------------*/ int write_sion(void *src, size_t size, void *opaque) { int *sid= (int *)opaque; int res = sion_fwrite(src, size, 1, *sid); if (res < 0 ){ return FTI_NSCS; } return FTI_SCES; } #endif /*-------------------------------------------------------------------------*/ /** @brief copies all data of GPU variables to a CPU memory location @param FTI_Exec Execution Meta data. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. Copis data from the GPU side to the CPU memory **/ /*-------------------------------------------------------------------------*/ int copyDataFromDevive(FTIT_execution* FTI_Exec, FTIT_dataset* FTI_Data){ #ifdef GPUSUPPORT int i; for (i = 0; i < FTI_Exec->nbVar; i++) { if ( FTI_Data[i].isDevicePtr ){ FTI_copy_from_device( FTI_Data[i].ptr, FTI_Data[i].devicePtr,FTI_Data[i].size,FTI_Exec); } } #endif return FTI_SCES; } <file_sep>/test/local/variateProcessorRestart/checkVPR.sh.in cd @CMAKE_SOURCE_DIR@/test/local/variateProcessorRestart if [ $1 = 1 ]; then make run-head RTN=$? elif [ $1 = 0 ]; then make run-nohead RTN=$? fi make clean cd @CMAKE_BINARY_DIR@/test/local exit $RTN <file_sep>/src/incremental-checkpoint.c #include <fti-int/incremental_checkpoint.h> #include "interface.h" #include "utility.h" /*-------------------------------------------------------------------------*/ /** @brief Initializes iCP for POSIX I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed before protected variables may be added to the checkpoint files. **/ /*-------------------------------------------------------------------------*/ int FTI_InitPosixICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { char str[FTI_BUFS]; //For console output snprintf(str, FTI_BUFS, "Initialize incremental checkpoint (ID: %d, Lvl: %d, I/O: POSIX)", FTI_Exec->ckptID, FTI_Exec->ckptLvel); FTI_Print(str, FTI_DBUG); //update ckpt file name snprintf(FTI_Exec->meta[0].ckptFile, FTI_BUFS, "Ckpt%d-Rank%d.fti", FTI_Exec->ckptID, FTI_Topo->myRank); char fn[FTI_BUFS]; int level = FTI_Exec->ckptLvel; if (level == 4 && FTI_Ckpt[4].isInline) { //If inline L4 save directly to global directory snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->gTmpDir, FTI_Exec->meta[0].ckptFile); } else { snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->lTmpDir, FTI_Exec->meta[0].ckptFile); } // open task local ckpt file FILE *fd = fopen(fn, "wb"); if (fd == NULL) { snprintf(str, FTI_BUFS, "FTI checkpoint file (%s) could not be opened.", fn); FTI_Print(str, FTI_EROR); return FTI_NSCS; } memcpy( FTI_Exec->iCPInfo.fh, &fd, sizeof(FTI_PO_FH) ); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Writes dataset into ckpt file using POSIX. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ int FTI_WritePosixVar(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { FILE *fd; int res; memcpy( &fd, FTI_Exec->iCPInfo.fh, sizeof(FTI_PO_FH) ); char str[FTI_BUFS]; long offset = 0; // write data into ckpt file int i; for (i = 0; i < FTI_Exec->nbVar; i++) { if( FTI_Data[i].id == varID ) { clearerr(fd); if ( fseek( fd, offset, SEEK_SET ) == -1 ) { FTI_Print("Error on fseek in writeposixvar", FTI_EROR ); return FTI_NSCS; } if ( !(FTI_Data[i].isDevicePtr) ){ FTI_Print(str,FTI_INFO); if (( res = FTI_Try(write_posix(FTI_Data[i].ptr, FTI_Data[i].size, fd),"Storing Data to Checkpoint file")) != FTI_SCES){ snprintf(str, FTI_BUFS, "Dataset #%d could not be written.", FTI_Data[i].id); FTI_Print(str, FTI_EROR); fclose(fd); return FTI_NSCS; } } #ifdef GPUSUPPORT // if data are stored to the GPU move them from device // memory to cpu memory and store them. else { FTI_Print(str,FTI_INFO); if ((res = FTI_Try( FTI_TransferDeviceMemToFileAsync(&FTI_Data[i], write_posix, fd), "moving data from GPU to storage")) != FTI_SCES) { snprintf(str, FTI_BUFS, "Dataset #%d could not be written.", FTI_Data[i].id); FTI_Print(str, FTI_EROR); fclose(fd); return FTI_NSCS; } } #endif if (ferror(fd)) { return FTI_NSCS; } } offset += FTI_Data[i].count*FTI_Data[i].eleSize; } FTI_Exec->iCPInfo.result = FTI_SCES; return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Finalizes iCP for POSIX I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed to finalize iCP. **/ /*-------------------------------------------------------------------------*/ int FTI_FinalizePosixICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { if ( FTI_Exec->iCPInfo.status == FTI_ICP_FAIL ) { return FTI_NSCS; } FILE *fd; memcpy( &fd, FTI_Exec->iCPInfo.fh, sizeof(FTI_PO_FH) ); // close file if (fclose(fd) != 0) { FTI_Print("FTI checkpoint file could not be closed.", FTI_EROR); return FTI_NSCS; } return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Initializes iCP for MPI I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed before protected variables may be added to the checkpoint files. **/ /*-------------------------------------------------------------------------*/ int FTI_InitMpiICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { int res; FTI_Print("I/O mode: MPI-IO.", FTI_DBUG); char str[FTI_BUFS], mpi_err[FTI_BUFS]; // enable collective buffer optimization MPI_Info info; MPI_Info_create(&info); MPI_Info_set(info, "romio_cb_write", "enable"); /* * update ckpt file name (neccessary for the restart!) * not very nice TODO we should think about another mechanism */ snprintf(FTI_Exec->meta[0].ckptFile, FTI_BUFS, "Ckpt%d-Rank%d.fti", FTI_Exec->ckptID, FTI_Topo->myRank); // TODO enable to set stripping unit in the config file (Maybe also other hints) // set stripping unit to 4MB MPI_Info_set(info, "stripping_unit", "4194304"); char gfn[FTI_BUFS], ckptFile[FTI_BUFS]; snprintf(ckptFile, FTI_BUFS, "Ckpt%d-mpiio.fti", FTI_Exec->ckptID); snprintf(gfn, FTI_BUFS, "%s/%s", FTI_Conf->gTmpDir, ckptFile); // open parallel file (collective call) MPI_File pfh; #ifdef LUSTRE if (FTI_Topo->splitRank == 0) { res = llapi_file_create(gfn, FTI_Conf->stripeUnit, FTI_Conf->stripeOffset, FTI_Conf->stripeFactor, 0); if (res) { char error_msg[FTI_BUFS]; error_msg[0] = 0; strerror_r(-res, error_msg, FTI_BUFS); snprintf(str, FTI_BUFS, "[Lustre] %s.", error_msg); FTI_Print(str, FTI_WARN); } else { snprintf(str, FTI_BUFS, "[LUSTRE] file:%s striping_unit:%i striping_factor:%i striping_offset:%i", ckptFile, FTI_Conf->stripeUnit, FTI_Conf->stripeFactor, FTI_Conf->stripeOffset); FTI_Print(str, FTI_DBUG); } } #endif res = MPI_File_open(FTI_COMM_WORLD, gfn, MPI_MODE_WRONLY|MPI_MODE_CREATE, info, &pfh); // check if successful if (res != 0) { errno = 0; int reslen; MPI_Error_string(res, mpi_err, &reslen); snprintf(str, FTI_BUFS, "unable to create file %s [MPI ERROR - %i] %s", gfn, res, mpi_err); FTI_Print(str, FTI_EROR); return FTI_NSCS; } MPI_Offset chunkSize = FTI_Exec->ckptSize; // collect chunksizes of other ranks MPI_Offset* chunkSizes = talloc(MPI_Offset, FTI_Topo->nbApprocs * FTI_Topo->nbNodes); MPI_Allgather(&chunkSize, 1, MPI_OFFSET, chunkSizes, 1, MPI_OFFSET, FTI_COMM_WORLD); // set file offset MPI_Offset offset = 0; int i; for (i = 0; i < FTI_Topo->splitRank; i++) { offset += chunkSizes[i]; } free(chunkSizes); FTI_Exec->iCPInfo.offset = offset; memcpy( FTI_Exec->iCPInfo.fh, &pfh, sizeof(FTI_MI_FH) ); MPI_Info_free(&info); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Writes dataset into ckpt file using MPI-IO. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ int FTI_WriteMpiVar(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { char str[FTI_BUFS]; WriteMPIInfo_t write_info; int res; memcpy( &write_info.pfh, FTI_Exec->iCPInfo.fh, sizeof(FTI_MI_FH) ); write_info.offset = FTI_Exec->iCPInfo.offset; write_info.FTI_Conf = FTI_Conf; int i; for (i = 0; i < FTI_Exec->nbVar; i++) { if ( FTI_Data[i].id == varID ) { if ( !(FTI_Data[i].isDevicePtr) ){ FTI_Print(str,FTI_INFO); if (( res = write_mpi(FTI_Data[i].ptr, FTI_Data[i].size, &write_info), "Storing Data to checkpoint file")!=FTI_SCES){ snprintf(str, FTI_BUFS, "Dataset #%d could not be written.", FTI_Data[i].id); FTI_Print(str, FTI_EROR); MPI_File_close(&write_info.pfh); return res; } } #ifdef GPUSUPPORT // dowload data from the GPU if necessary // Data are stored in the GPU side. else { snprintf(str, FTI_BUFS, "Dataset #%d Writing GPU Data.", FTI_Data[i].id); FTI_Print(str,FTI_INFO); if ((res = FTI_Try( FTI_TransferDeviceMemToFileAsync(&FTI_Data[i], write_mpi, &write_info), "moving data from GPU to storage")) != FTI_SCES) { snprintf(str, FTI_BUFS, "Dataset #%d could not be written.", FTI_Data[i].id); FTI_Print(str, FTI_EROR); MPI_File_close(&write_info.pfh); return res; } } #endif } write_info.offset += FTI_Data[i].size; } FTI_Exec->iCPInfo.result = FTI_SCES; return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Finalizes iCP for MPI I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed to finalize iCP. **/ /*-------------------------------------------------------------------------*/ int FTI_FinalizeMpiICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { if ( FTI_Exec->iCPInfo.status == FTI_ICP_FAIL ) { return FTI_NSCS; } MPI_File pfh; memcpy( &pfh, FTI_Exec->iCPInfo.fh, sizeof(FTI_MI_FH) ); MPI_File_close(&pfh); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Initializes iCP for FTI-FF I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed before protected variables may be added to the checkpoint files. **/ /*-------------------------------------------------------------------------*/ int FTI_InitFtiffICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { char fn[FTI_BUFS], strerr[FTI_BUFS]; FTI_Print("I/O mode: FTI File Format.", FTI_DBUG); //update ckpt file name snprintf(FTI_Exec->meta[0].ckptFile, FTI_BUFS, "Ckpt%d-Rank%d.fti", FTI_Exec->ckptID, FTI_Topo->myRank); // only for printout of dCP share in FTI_Checkpoint FTI_Exec->FTIFFMeta.dcpSize = 0; // important for reading and writing operations FTI_Exec->FTIFFMeta.dataSize = 0; FTI_Exec->FTIFFMeta.pureDataSize = 0; //If inline L4 save directly to global directory int level = FTI_Exec->ckptLvel; if (level == 4 && FTI_Ckpt[4].isInline) { if( FTI_Conf->dcpEnabled && FTI_Ckpt[4].isDcp ) { snprintf(fn, FTI_BUFS, "%s/%s", FTI_Ckpt[4].dcpDir, FTI_Ckpt[4].dcpName); } else { snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->gTmpDir, FTI_Exec->meta[0].ckptFile); } } else if ( level == 4 && !FTI_Ckpt[4].isInline ) if( FTI_Conf->dcpEnabled && FTI_Ckpt[4].isDcp ) { snprintf(fn, FTI_BUFS, "%s/%s", FTI_Ckpt[1].dcpDir, FTI_Ckpt[4].dcpName); } else { snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->lTmpDir, FTI_Exec->meta[0].ckptFile); } else { snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->lTmpDir, FTI_Exec->meta[0].ckptFile); } int fd; // for dCP: create if not exists, open if exists if ( FTI_Conf->dcpEnabled && FTI_Ckpt[4].isDcp ) { if (access(fn,R_OK) != 0) { fd = open( fn, O_WRONLY|O_CREAT, (mode_t) 0600 ); } else { fd = open( fn, O_WRONLY ); } } else { fd = open( fn, O_WRONLY|O_CREAT, (mode_t) 0600 ); } if (fd == -1) { snprintf(strerr, FTI_BUFS, "FTI checkpoint file (%s) could not be opened.", fn); FTI_Print(strerr, FTI_EROR); return FTI_NSCS; } memcpy( FTI_Exec->iCPInfo.fh, &fd, sizeof(FTI_FF_FH) ); strcpy( FTI_Exec->iCPInfo.fn, fn ); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Writes dataset into ckpt file using FTI-FF. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ int FTI_WriteFtiffVar(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { char str[FTI_BUFS]; FTIFF_db *db = FTI_Exec->firstdb; FTIFF_dbvar *dbvar = NULL; unsigned char *dptr; int dbvar_idx, dbcounter=0; int isnextdb; // block size for fwrite buffer in file. long dcpSize = 0; long dataSize = 0; long pureDataSize = 0; int pvar_idx = -1, pvar_idx_; for( pvar_idx_=0; pvar_idx_<FTI_Exec->nbVar; pvar_idx_++ ) { if( FTI_Data[pvar_idx_].id == varID ) { pvar_idx = pvar_idx_; } } if( pvar_idx == -1 ) { FTI_Print("FTI_WriteFtiffVar: Illegal ID", FTI_WARN); return FTI_NSCS; } FTIFF_UpdateDatastructVarFTIFF( FTI_Exec, FTI_Data, FTI_Conf, pvar_idx ); // check if metadata exists if( FTI_Exec->firstdb == NULL ) { FTI_Print("No data structure found to write data to file. Discarding checkpoint.", FTI_WARN); return FTI_NSCS; } int fd; memcpy( &fd, FTI_Exec->iCPInfo.fh, sizeof(FTI_FF_FH) ); db = FTI_Exec->firstdb; do { isnextdb = 0; for(dbvar_idx=0;dbvar_idx<db->numvars;dbvar_idx++) { dbvar = &(db->dbvars[dbvar_idx]); if( dbvar->id == varID ) { unsigned char hashchk[MD5_DIGEST_LENGTH]; // important for dCP! // TODO check if we can use: // 'dataSize += dbvar->chunksize' // for dCP disabled dataSize += dbvar->containersize; if( dbvar->hascontent ) pureDataSize += dbvar->chunksize; FTI_ProcessDBVar(FTI_Exec, FTI_Conf, dbvar , FTI_Data, hashchk, fd, FTI_Exec->iCPInfo.fn , &dcpSize, &dptr); // create hash for datachunk and assign to member 'hash' if( dbvar->hascontent ) { memcpy( dbvar->hash, hashchk, MD5_DIGEST_LENGTH ); } // debug information snprintf(str, FTI_BUFS, "FTIFF: CKPT(id:%i) dataBlock:%i/dataBlockVar%i id: %i, idx: %i" ", dptr: %ld, fptr: %ld, chunksize: %ld, " "base_ptr: 0x%" PRIxPTR " ptr_pos: 0x%" PRIxPTR " ", FTI_Exec->ckptID, dbcounter, dbvar_idx, dbvar->id, dbvar->idx, dbvar->dptr, dbvar->fptr, dbvar->chunksize, (uintptr_t)FTI_Data[dbvar->idx].ptr, (uintptr_t)dptr); FTI_Print(str, FTI_DBUG); } } if (db->next) { db = db->next; isnextdb = 1; } dbcounter++; } while( isnextdb ); // only for printout of dCP share in FTI_Checkpoint FTI_Exec->FTIFFMeta.dcpSize += dcpSize; FTI_Exec->FTIFFMeta.pureDataSize += pureDataSize; // important for reading and writing operations FTI_Exec->FTIFFMeta.dataSize += dataSize; FTI_Exec->iCPInfo.result = FTI_SCES; return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Finalizes iCP for FTI-FF I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed to finalize iCP. **/ /*-------------------------------------------------------------------------*/ int FTI_FinalizeFtiffICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { if ( FTI_Exec->iCPInfo.status == FTI_ICP_FAIL ) { return FTI_NSCS; } int fd; memcpy( &fd, FTI_Exec->iCPInfo.fh, sizeof(FTI_FF_FH) ); if ( FTI_Try( FTIFF_CreateMetadata( FTI_Exec, FTI_Topo, FTI_Data, FTI_Conf ), "Create FTI-FF meta data" ) != FTI_SCES ) { return FTI_NSCS; } FTIFF_writeMetaDataFTIFF( FTI_Exec, fd ); fdatasync( fd ); close( fd ); return FTI_SCES; } #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief Initializes iCP for HDF5 I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed before protected variables may be added to the checkpoint files. **/ /*-------------------------------------------------------------------------*/ int FTI_InitHdf5ICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { FTI_Print("I/O mode: HDF5.", FTI_DBUG); char str[FTI_BUFS], fn[FTI_BUFS]; if (FTI_Conf->ioMode == FTI_IO_HDF5) { snprintf(FTI_Exec->meta[0].ckptFile, FTI_BUFS, "Ckpt%d-Rank%d.h5", FTI_Exec->ckptID, FTI_Topo->myRank); } int level = FTI_Exec->ckptLvel; if (level == 4 && FTI_Ckpt[4].isInline) { //If inline L4 save directly to global directory snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->gTmpDir, FTI_Exec->meta[0].ckptFile); } else { snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->lTmpDir, FTI_Exec->meta[0].ckptFile); } //Creating new hdf5 file hid_t file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); if (file_id < 0) { sprintf(str, "FTI checkpoint file (%s) could not be opened.", fn); FTI_Print(str, FTI_EROR); return FTI_NSCS; } FTI_Exec->H5groups[0]->h5groupID = file_id; FTIT_H5Group* rootGroup = FTI_Exec->H5groups[0]; int i; for (i = 0; i < rootGroup->childrenNo; i++) { FTI_CreateGroup(FTI_Exec->H5groups[rootGroup->childrenID[i]], file_id, FTI_Exec->H5groups); } memcpy( FTI_Exec->iCPInfo.fh, &file_id, sizeof(FTI_H5_FH) ); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Writes dataset into ckpt file using HDF5. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ int FTI_WriteHdf5Var(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { if ( FTI_Exec->iCPInfo.status == FTI_ICP_FAIL ) { return FTI_NSCS; } char str[FTI_BUFS]; hid_t file_id; memcpy( &file_id, FTI_Exec->iCPInfo.fh, sizeof(FTI_H5_FH) ); FTIT_H5Group* rootGroup = FTI_Exec->H5groups[0]; // write data into ckpt file int i; for (i = 0; i < FTI_Exec->nbVar; i++) { if( FTI_Data[i].id == varID ) { int toCommit = 0; if (FTI_Data[i].type->h5datatype < 0) { toCommit = 1; } sprintf(str, "Calling CreateComplexType [%d] with hid_t %ld", FTI_Data[i].type->id, (long)FTI_Data[i].type->h5datatype); FTI_Print(str, FTI_DBUG); FTI_CreateComplexType(FTI_Data[i].type, FTI_Exec->FTI_Type); if (toCommit == 1) { char name[FTI_BUFS]; if (FTI_Data[i].type->structure == NULL) { //this is the array of bytes with no name sprintf(name, "Type%d", FTI_Data[i].type->id); } else { strncpy(name, FTI_Data[i].type->structure->name, FTI_BUFS); } herr_t res = H5Tcommit(FTI_Data[i].type->h5group->h5groupID, name, FTI_Data[i].type->h5datatype, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); if (res < 0) { sprintf(str, "Datatype #%d could not be commited", FTI_Data[i].id); FTI_Print(str, FTI_EROR); int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } H5Fclose(file_id); return FTI_NSCS; } } //convert dimLength array to hsize_t if ( FTI_Try(FTI_WriteHDF5Var(&FTI_Data[i]) , "Writing data to HDF5 filesystem") != FTI_SCES){ sprintf(str, "Dataset #%d could not be written", FTI_Data[i].id); FTI_Print(str, FTI_EROR); int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } H5Fclose(file_id); return FTI_NSCS; } } } FTI_Exec->iCPInfo.result = FTI_SCES; return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Finalizes iCP for HDF5 I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed to finalize iCP. **/ /*-------------------------------------------------------------------------*/ int FTI_FinalizeHdf5ICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { hid_t file_id; memcpy( &file_id, FTI_Exec->iCPInfo.fh, sizeof(FTI_H5_FH) ); FTIT_H5Group* rootGroup = FTI_Exec->H5groups[0]; int i; for (i = 0; i < FTI_Exec->nbVar; i++) { FTI_CloseComplexType(FTI_Data[i].type, FTI_Exec->FTI_Type); } int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } // close file FTI_Exec->H5groups[0]->h5groupID = -1; if (H5Fclose(file_id) < 0) { FTI_Print("FTI checkpoint file could not be closed.", FTI_EROR); return FTI_NSCS; } return FTI_SCES; } #endif /* * As long SIONlib does not support seek in a single file * FTI does not support SIONlib I/O for incremental * checkpointing */ #if 0 #ifdef ENABLE_SIONLIB // --> If SIONlib is installed /*-------------------------------------------------------------------------*/ /** @brief Initializes iCP for SIONlib I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed before protected variables may be added to the checkpoint files. **/ /*-------------------------------------------------------------------------*/ int FTI_InitSionlibICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { int res; FTI_Print("I/O mode: SIONlib.", FTI_DBUG); int numFiles = 1; int nlocaltasks = 1; int* file_map = calloc(1, sizeof(int)); int* ranks = talloc(int, 1); int* rank_map = talloc(int, 1); sion_int64* chunkSizes = talloc(sion_int64, 1); int fsblksize = -1; chunkSizes[0] = FTI_Exec->ckptSize; ranks[0] = FTI_Topo->splitRank; rank_map[0] = FTI_Topo->splitRank; // open parallel file char fn[FTI_BUFS], str[FTI_BUFS]; snprintf(str, FTI_BUFS, "Ckpt%d-sionlib.fti", FTI_Exec->ckptID); snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->gTmpDir, str); int sid = sion_paropen_mapped_mpi(fn, "wb,posix", &numFiles, FTI_COMM_WORLD, &nlocaltasks, &ranks, &chunkSizes, &file_map, &rank_map, &fsblksize, NULL); // check if successful if (sid == -1) { errno = 0; FTI_Print("SIONlib: File could no be opened", FTI_EROR); free(file_map); free(rank_map); free(ranks); free(chunkSizes); return FTI_NSCS; } memcpy(FTI_Exec->iCPInfo.fh, &sid, sizeof(int)); free(file_map); free(rank_map); free(ranks); free(chunkSizes); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Writes dataset into ckpt file using SIONlib. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ int FTI_WriteSionlibVar(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { int sid; memcpy( &sid, FTI_Exec->iCPInfo.fh, sizeof(FTI_SL_FH) ); unsigned long offset = 0; // write datasets into file int i; for (i = 0; i < FTI_Exec->nbVar; i++) { if( FTI_Data[i].id == varID ) { // set file pointer to corresponding block in sionlib file int res = sion_seek(sid, FTI_Topo->splitRank, SION_CURRENT_BLK, offset); // check if successful if (res != SION_SUCCESS) { errno = 0; FTI_Print("SIONlib: Could not set file pointer", FTI_EROR); sion_parclose_mapped_mpi(sid); return FTI_NSCS; } // SIONlib write call res = sion_fwrite(FTI_Data[i].ptr, FTI_Data[i].size, 1, sid); // check if successful if (res < 0) { errno = 0; FTI_Print("SIONlib: Data could not be written", FTI_EROR); res = sion_parclose_mapped_mpi(sid); return FTI_NSCS; } } offset += FTI_Data[i].size; } FTI_Exec->iCPInfo.result = FTI_SCES; return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Finalizes iCP for SIONlib I/O. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function takes care of the I/O specific actions needed to finalize iCP. **/ /*-------------------------------------------------------------------------*/ int FTI_FinalizeSionlibICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { int sid; memcpy( &sid, FTI_Exec->iCPInfo.fh, sizeof(FTI_SL_FH) ); // close parallel file if (sion_parclose_mapped_mpi(sid) == -1) { FTI_Print("Cannot close sionlib file.", FTI_WARN); return FTI_NSCS; } return FTI_SCES; } #endif // SIONlib enabled #endif <file_sep>/src/hdf5.c /** * Copyright (c) 2017 <NAME> * All rights reserved * * FTI - A multi-level checkpointing library for C/C++/Fortran applications * * Revision 1.0 : Fault Tolerance Interface (FTI) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file hdf5.c * @date November, 2017 * @brief Funtions to support HDF5 checkpointing. */ #ifdef ENABLE_HDF5 #include "interface.h" #include "utility.h" #include "api_cuda.h" /*-------------------------------------------------------------------------*/ /** @brief It checks if an hdf5 file exist and the contents are 'correct'. @param fn The ckpt. file name to check. @param fs The ckpt. file size to check. @param checksum The file checksum to check In this case is should be NULL. @return integer 0 if file seems correct, 1 if not . This function checks whether a file exist or not and if its size is the expected one. **/ /*-------------------------------------------------------------------------*/ int FTI_CheckHDF5File(char* fn, long fs, char* checksum) { char str[FTI_BUFS]; if (access(fn, F_OK) == 0) { struct stat fileStatus; if (stat(fn, &fileStatus) == 0) { if (fileStatus.st_size == fs) { hid_t file_id = H5Fopen(fn, H5F_ACC_RDONLY, H5P_DEFAULT); if (file_id < 0) { sprintf(str, "Corrupted Checkpoint File: \"%s\"", fn); FTI_Print(str,FTI_WARN); return 1; } else{ H5Fclose(file_id); return 0; } } else { return 1; } } else { return 1; } } else { char str[FTI_BUFS]; sprintf(str, "Missing file: \"%s\"", fn); FTI_Print(str, FTI_WARN); return 1; } } /*-------------------------------------------------------------------------*/ /** @brief Calculates the number of bytes I need to fetch from the GPU. @param sizeOfElement Element size for the dataset @param maxBytes The maximum amount of bytes I can fetch from GPU. @param count Array storing the number of dimensions I can fetch each time @param numOfDimensions Number of dimensions of this dataset @param dimensions maximum index of each dimension. @param *sep Stores the maximum dimension I can fetch from the GPU @return integer number of bytes to fetch each time from the GPU. This function has a dual functionality. It computes the number of bytes I need to fetch from the GPU side. It also computes the "count" parameter. In other words it computes how many elements from each dimension I can compute from the total Bytes I fetched from the GPU **/ /*-------------------------------------------------------------------------*/ hsize_t FTI_calculateCountDim(size_t sizeOfElement, hsize_t maxBytes, hsize_t *count, int numOfDimensions, hsize_t *dimensions, hsize_t *sep) { int i; memset(count, 0, sizeof(hsize_t)*numOfDimensions); size_t maxElements = maxBytes/sizeOfElement; hsize_t bytesToFetch; if (maxElements == 0 ) maxElements = 1; hsize_t *dimensionSize = (hsize_t *) malloc (sizeof(hsize_t)*(numOfDimensions+1)); dimensionSize[numOfDimensions] =1; //Calculate how many elements does each whole dimension holds for ( i = numOfDimensions - 1; i >=0 ; i--){ dimensionSize[i] = dimensionSize[i+1] * dimensions[i]; } //Find which is the maximum dimension that I can fetch continuously. for ( i = numOfDimensions ; i >= 0; i--){ if ( maxElements < dimensionSize[i]){ break; } } // I is =-1 when I can fetch the whole buffer if ( i == -1 ){ *sep = 0; bytesToFetch = dimensionSize[*sep+1] * dimensions[*sep] * sizeOfElement; memcpy(count, dimensions, sizeof(hsize_t)*numOfDimensions); return bytesToFetch; } // Calculate the maxium elements of this dimension that I can get // This number should be a multiple of the total dimension lenght // of this dimension. *sep= i; int fetchElements = 0; for ( i = maxElements/(dimensionSize[*sep+1]) ; i >= 1; i--){ if ( dimensions[*sep]%i == 0){ fetchElements = i; break; } } //Fill in the count array and return. for ( i = 0 ; i < *sep ; i++ ) count[i] = 1; count[*sep] = fetchElements; for ( i = *sep+1; i < numOfDimensions ; i++) count[i] = dimensions[i]; bytesToFetch = dimensionSize[*sep+1] * count[*sep] * sizeOfElement; return bytesToFetch; } /*-------------------------------------------------------------------------*/ /** @brief Writes the elements to the HDF5 file. @param dataspace dataspace (shape) of the data to be stored. @param dataType data type of the data to be stored. @param dataset dataset of the data to be stored. @param count number of indexes for each dimension to be stored. @param offset describes the offset from the begining of the data to be stored @param ranks number of dimensions of this dataset @return integer FTI_SCES on succesfull write. This function uses hyperslabs to store a subset of the entire dataspace to the checkpoint file. **/ /*-------------------------------------------------------------------------*/ int FTI_WriteElements(hid_t dataspace, hid_t dataType, hid_t dataset, hsize_t *count, hsize_t *offset, hsize_t ranks, void *ptr) { char str[FTI_BUFS]; hid_t status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, offset, NULL,count, NULL); hsize_t *dims_in= (hsize_t*) malloc (sizeof(hsize_t)*ranks); memcpy(dims_in,count,ranks*sizeof(hsize_t)); hid_t memspace = H5Screate_simple(ranks,dims_in, NULL); hsize_t *offset_in = (hsize_t*) calloc (ranks,sizeof(ranks)); status = H5Sselect_hyperslab( memspace, H5S_SELECT_SET, offset_in, NULL, count, NULL); status = H5Dwrite(dataset, dataType, memspace, dataspace, H5P_DEFAULT, ptr); if (status < 0) { free(offset); free(count); sprintf(str, "Dataset could not be written"); FTI_Print(str, FTI_EROR); return FTI_NSCS; } free(offset_in); free(dims_in); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Read the elements from the checkpoint file. @param dataspace dataspace (shape) of the data to be stored. @param dataType data type of the data to be stored. @param dataset dataset of the data to be stored. @param count number of indexes for each dimension to be stored. @param offset describes the offset from the begining of the data to be stored @param ranks number of dimensions of this dataset @return integer FTI_SCES on succesfull write. This function uses hyperslabs to read a subset of the entire dataspace from the checkpoint file. **/ /*-------------------------------------------------------------------------*/ int FTI_ReadElements(hid_t dataspace, hid_t dimType, hid_t dataset, hsize_t *count, hsize_t *offset, hsize_t ranks, void *ptr) { char str[FTI_BUFS]; hid_t status = H5Sselect_hyperslab(dataspace, H5S_SELECT_SET, offset, NULL,count, NULL); hsize_t *dims_out= (hsize_t*) malloc (sizeof(hsize_t)*ranks); memcpy(dims_out,count,ranks*sizeof(hsize_t)); hid_t memspace = H5Screate_simple(ranks,dims_out, NULL); hsize_t *offset_out = (hsize_t*) calloc (ranks,sizeof(ranks)); status = H5Sselect_hyperslab( memspace, H5S_SELECT_SET, offset_out, NULL, count, NULL); status = H5Dread(dataset,dimType, memspace, dataspace, H5P_DEFAULT, ptr); if (status < 0) { free(offset); free(count); sprintf(str, "Dataset could not be written"); FTI_Print(str, FTI_EROR); return FTI_NSCS; } free(offset_out); free(dims_out); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief Advances the offset of an n-dimensional protected variable. @param sep The dimension index which is sliced. Dimension on the right side are transfered as a whole. Dimensions on the left side of sep are incrementally transfered. @param start coordinates of the n-dimensional space descirbing what I have processed up to now. @param add How many elements I have processed. @param dims The entire n-dimensional space @param ranks number of dimensions of this dataset @return integer Return 1 only when the entire data set is computed (This is not used in the current implementation). This function performs acutally a simle addition on a n-dimensional spase start = start+ offset. I am processing only dimensions lower than "sep" as the higher ones are ALWAYS completely tranfered from/to the host. **/ /*-------------------------------------------------------------------------*/ int FTI_AdvanceOffset(hsize_t sep, hsize_t *start, hsize_t *add, hsize_t *dims, hsize_t rank) { int i; hsize_t carryOut=0; hsize_t temp; temp = start[sep] + add[sep]; if ( temp >= dims[sep] ){ start[sep] = temp % dims[sep]; carryOut=1; } else{ start[sep] = temp; carryOut=0; } for ( i = sep-1; i >= 0 &&carryOut ; i--){ temp = start[i] + carryOut; if ( temp >= dims[i] ){ start[i] = temp % dims[i]; carryOut=1; } else{ start[i] = temp; carryOut=0; } } return carryOut; } /*-------------------------------------------------------------------------*/ /** @brief Writes a protected variable to the checkpoint file. @param FTI_DataVar The protected variable to be written. @return integer Return FTI_SCES when successfuly write the data to the file The function Write the data of a single FTI_Protect variable to the HDF5 file. If the data are on the HOST CPU side, all the data are tranfered with a single call. If the data are on the GPU side, we use hyperslabs to slice the data and asynchronously move data from the GPU side to the host side and then to the filesytem. **/ /*-------------------------------------------------------------------------*/ int FTI_WriteHDF5Var(FTIT_dataset *FTI_DataVar) { int j; hsize_t dimLength[32]; char str[FTI_BUFS]; int res; hid_t dcpl; for (j = 0; j < FTI_DataVar->rank; j++) { dimLength[j] = FTI_DataVar->dimLength[j]; } dcpl = H5Pcreate (H5P_DATASET_CREATE); res = H5Pset_fletcher32 (dcpl); res = H5Pset_chunk (dcpl, FTI_DataVar->rank, dimLength); hid_t dataspace = H5Screate_simple( FTI_DataVar->rank, dimLength, NULL); hid_t dataset = H5Dcreate2 ( FTI_DataVar->h5group->h5groupID, FTI_DataVar->name,FTI_DataVar->type->h5datatype, dataspace, H5P_DEFAULT, dcpl , H5P_DEFAULT); // If my data are stored in the CPU side // Just store the data to the file and return; #ifdef GPUSUPPORT if ( !FTI_DataVar->isDevicePtr ){ #endif res = H5Dwrite(dataset,FTI_DataVar->type->h5datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, FTI_DataVar->ptr); if (res < 0) { sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } res = H5Pclose (dcpl); if (res < 0) { sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } res = H5Dclose(dataset); if (res < 0) { sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } res = H5Sclose(dataspace); if (res < 0) { sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } return FTI_SCES; #ifdef GPUSUPPORT } // This code is only executed in the GPU case. hsize_t *count = (hsize_t*) malloc (sizeof(hsize_t)*FTI_DataVar->rank); hsize_t *offset= (hsize_t*) calloc (FTI_DataVar->rank,sizeof(hsize_t)); if ( !count|| !offset){ sprintf(str, "Could Not allocate count and offset regions"); FTI_Print(str, FTI_EROR); return FTI_NSCS; } hsize_t seperator; hsize_t fetchBytes = FTI_getHostBuffSize(); fetchBytes = FTI_calculateCountDim(FTI_DataVar->eleSize, fetchBytes ,count, FTI_DataVar->rank, dimLength, &seperator); sprintf(str,"GPU-Device Message: I Will Fetch %lld Bytes Per Stream Request", fetchBytes); FTI_Print(str,FTI_DBUG); FTIT_data_prefetch prefetcher; prefetcher.fetchSize = fetchBytes; prefetcher.totalBytesToFetch = FTI_DataVar->size; prefetcher.isDevice = FTI_DataVar->isDevicePtr; prefetcher.dptr = FTI_DataVar->devicePtr; size_t bytesToWrite; FTI_InitPrefetcher(&prefetcher); unsigned char *basePtr = NULL; if ( FTI_Try(FTI_getPrefetchedData(&prefetcher, &bytesToWrite, &basePtr), "Fetch next memory block from GPU to write to HDF5") != FTI_SCES){ return FTI_NSCS; } while( basePtr ){ res = FTI_WriteElements( dataspace, FTI_DataVar->type->h5datatype, dataset, count, offset, FTI_DataVar->rank , basePtr); if (res != FTI_SCES ) { free(offset); free(count); sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } FTI_AdvanceOffset(seperator, offset,count, dimLength, FTI_DataVar->rank); if ( FTI_Try(FTI_getPrefetchedData(&prefetcher, &bytesToWrite, &basePtr), "Fetch next memory block from GPU to write to HDF5") != FTI_SCES){ return FTI_NSCS; } } res = H5Dclose(dataset); if (res < 0) { free(offset); free(count); sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } res = H5Sclose(dataspace); if (res < 0) { free(offset); free(count); sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } free(offset); free(count); return FTI_SCES; #endif } /*-------------------------------------------------------------------------*/ /** @brief Reads a protected variable to the checkpoint file. @param FTI_DataVar The Var we will read from the to the Checkpoint file @return integer Return FTI_SCES when successfuly write the data to the file The function reads the data of a single FTI_Protect variable to the HDF5 file. If the data are on the HOST CPU side, all the data are tranfered with a single call. If the data should move to the GPU side, we use hyperslabs to slice the data and asynchronously move data from the File to the CPU and then to GPU side. **/ /*-------------------------------------------------------------------------*/ int FTI_ReadHDF5Var(FTIT_dataset *FTI_DataVar) { char str[FTI_BUFS]; int res; hid_t dataset = H5Dopen(FTI_DataVar->h5group->h5groupID, FTI_DataVar->name, H5P_DEFAULT); hid_t dataspace = H5Dget_space(dataset); // If my data are stored in the CPU side // Just store the data to the file and return; #ifdef GPUSUPPORT if ( !FTI_DataVar->isDevicePtr ){ #endif res = H5Dread(dataset,FTI_DataVar->type->h5datatype, H5S_ALL, H5S_ALL, H5P_DEFAULT, FTI_DataVar->ptr); if (res < 0) { sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } res = H5Dclose(dataset); if (res < 0) { sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } res = H5Sclose(dataspace); if (res < 0) { sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } return FTI_SCES; #ifdef GPUSUPPORT } hsize_t dimLength[32]; int j; for (j = 0; j < FTI_DataVar->rank; j++) { dimLength[j] = FTI_DataVar->dimLength[j]; } // This code is only executed in the GPU case. hsize_t *count = (hsize_t*) malloc (sizeof(hsize_t)*FTI_DataVar->rank); hsize_t *offset= (hsize_t*) calloc (FTI_DataVar->rank,sizeof(hsize_t)); if ( !count|| !offset){ sprintf(str, "Could Not allocate count and offset regions"); FTI_Print(str, FTI_EROR); return FTI_NSCS; } hsize_t seperator; size_t fetchBytes; size_t hostBufSize = FTI_getHostBuffSize(); //Calculate How many dimension I can compute each time //and how bug should the HOST-GPU communication buffer should be fetchBytes = FTI_calculateCountDim(FTI_DataVar->eleSize, hostBufSize ,count, FTI_DataVar->rank, dimLength, &seperator); //If the buffer is smaller than the minimum amount //then I need to allocate a bigger one. if (hostBufSize < fetchBytes){ if ( FTI_Try( FTI_DestroyDevices(), "Deleting host buffers" ) != FTI_SCES){ free(offset); free(count); sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } if ( FTI_Try (FTI_InitDevices( fetchBytes ), "Allocating host buffers")!= FTI_SCES) { free(offset); free(count); sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } } unsigned char *basePtr = NULL; int id = 0; int prevId = 1; hsize_t totalBytes = FTI_DataVar->size; cudaStream_t streams[2]; //Create the streams for the asynchronous data movement. CUDA_ERROR_CHECK(cudaStreamCreate(&(streams[0]))); CUDA_ERROR_CHECK(cudaStreamCreate(&(streams[1]))); unsigned char *dPtr = FTI_DataVar->devicePtr; // Perform the while loop until all data // are processed. while( totalBytes ){ basePtr = FTI_getHostBuffer(id); //Read file res = FTI_ReadElements( dataspace, FTI_DataVar->type->h5datatype, dataset, count, offset, FTI_DataVar->rank , basePtr); CUDA_ERROR_CHECK(cudaMemcpyAsync( dPtr , basePtr, fetchBytes, cudaMemcpyHostToDevice, streams[id])); if (res != FTI_SCES ) { free(offset); free(count); sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } //Increase accordingly the file offset FTI_AdvanceOffset(seperator, offset,count, dimLength, FTI_DataVar->rank); //Syncing the cuda stream. CUDA_ERROR_CHECK(cudaStreamSynchronize(streams[prevId])); prevId = id; id = (id + 1)%2; dPtr = dPtr + fetchBytes; totalBytes -= fetchBytes; } CUDA_ERROR_CHECK(cudaStreamSynchronize(streams[prevId])); CUDA_ERROR_CHECK(cudaStreamDestroy(streams[0])); CUDA_ERROR_CHECK(cudaStreamDestroy(streams[1])); res = H5Dclose(dataset); if (res < 0) { free(offset); free(count); sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } res = H5Sclose(dataspace); if (res < 0) { free(offset); free(count); sprintf(str, "Dataset #%d could not be written", FTI_DataVar->id); FTI_Print(str, FTI_EROR); return FTI_NSCS; } free(offset); free(count); return FTI_SCES; #endif } /*-------------------------------------------------------------------------*/ /** @brief Writes ckpt to using HDF5 file format. @param FTI_Conf Configuration metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ int FTI_WriteHDF5(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { FTI_Print("I/O mode: HDF5.", FTI_DBUG); char str[FTI_BUFS], fn[FTI_BUFS]; int level = FTI_Exec->ckptLvel; if (level == 4 && FTI_Ckpt[4].isInline) { //If inline L4 save directly to global directory snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->gTmpDir, FTI_Exec->meta[0].ckptFile); } else { snprintf(fn, FTI_BUFS, "%s/%s", FTI_Conf->lTmpDir, FTI_Exec->meta[0].ckptFile); } if( FTI_Exec->h5SingleFile ) { snprintf( fn, FTI_BUFS, "%s/%s-ID%08d.h5", FTI_Conf->h5SingleFileDir, FTI_Conf->h5SingleFilePrefix, FTI_Exec->ckptID ); } hid_t file_id; //Creating new hdf5 file if( FTI_Exec->h5SingleFile ) { hid_t plid = H5Pcreate( H5P_FILE_ACCESS ); H5Pset_fapl_mpio(plid, FTI_COMM_WORLD, MPI_INFO_NULL); file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, plid); H5Pclose( plid ); } else { file_id = H5Fcreate(fn, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); } if (file_id < 0) { sprintf(str, "FTI checkpoint file (%s) could not be opened.", fn); FTI_Print(str, FTI_EROR); return FTI_NSCS; } FTI_Exec->H5groups[0]->h5groupID = file_id; FTIT_H5Group* rootGroup = FTI_Exec->H5groups[0]; int i; for (i = 0; i < rootGroup->childrenNo; i++) { FTI_CreateGroup(FTI_Exec->H5groups[rootGroup->childrenID[i]], file_id, FTI_Exec->H5groups); } // write data into ckpt file // create datatypes for (i = 0; i < FTI_Exec->nbVar; i++) { int toCommit = 0; if (FTI_Data[i].type->h5datatype < 0) { toCommit = 1; } sprintf(str, "Calling CreateComplexType [%d] with hid_t %ld", FTI_Data[i].type->id, (long)FTI_Data[i].type->h5datatype); FTI_Print(str, FTI_DBUG); FTI_CreateComplexType(FTI_Data[i].type, FTI_Exec->FTI_Type); if (toCommit == 1) { char name[FTI_BUFS]; if (FTI_Data[i].type->structure == NULL) { //this is the array of bytes with no name sprintf(name, "Type%d", FTI_Data[i].type->id); } else { strncpy(name, FTI_Data[i].type->structure->name, FTI_BUFS); } herr_t res = H5Tcommit(FTI_Data[i].type->h5group->h5groupID, name, FTI_Data[i].type->h5datatype, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); if (res < 0) { sprintf(str, "Datatype #%d could not be commited", FTI_Data[i].id); FTI_Print(str, FTI_EROR); int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } H5Fclose(file_id); return FTI_NSCS; } } } if( FTI_Exec->h5SingleFile ) { FTI_CreateGlobalDatasets( FTI_Exec ); } // write data for (i = 0; i < FTI_Exec->nbVar; i++) { int res; if( FTI_Exec->h5SingleFile ) { res = FTI_WriteSharedFileData( FTI_Data[i] ); } else { res = FTI_WriteHDF5Var(&FTI_Data[i]); } if ( res != FTI_SCES ) { sprintf(str, "Dataset #%d could not be written", FTI_Data[i].id); FTI_Print(str, FTI_EROR); int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } H5Fclose(file_id); return FTI_NSCS; } } for (i = 0; i < FTI_Exec->nbVar; i++) { FTI_CloseComplexType(FTI_Data[i].type, FTI_Exec->FTI_Type); } int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } if( FTI_Exec->h5SingleFile ) { FTI_CloseGlobalDatasets( FTI_Exec ); } // close file FTI_Exec->H5groups[0]->h5groupID = -1; if (H5Fclose(file_id) < 0) { FTI_Print("FTI checkpoint file could not be closed.", FTI_EROR); return FTI_NSCS; } return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief It loads the HDF5 checkpoint data. @return integer FTI_SCES if successful. This function loads the checkpoint data from the checkpoint file and it updates checkpoint information. **/ /*-------------------------------------------------------------------------*/ int FTI_RecoverHDF5(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data) { char str[FTI_BUFS], fn[FTI_BUFS]; snprintf(fn, FTI_BUFS, "%s/%s", FTI_Ckpt[FTI_Exec->ckptLvel].dir, FTI_Exec->meta[FTI_Exec->ckptLvel].ckptFile); if( FTI_Exec->h5SingleFile ) { snprintf( fn, FTI_BUFS, "%s/%s-ID%08d.h5", FTI_Conf->h5SingleFileDir, FTI_Conf->h5SingleFilePrefix, FTI_Exec->ckptID ); } sprintf(str, "Trying to load FTI checkpoint file (%s)...", fn); FTI_Print(str, FTI_DBUG); hid_t file_id; //Open hdf5 file if( FTI_Exec->h5SingleFile ) { hid_t plid = H5Pcreate( H5P_FILE_ACCESS ); H5Pset_fapl_mpio( plid, FTI_COMM_WORLD, MPI_INFO_NULL ); file_id = H5Fopen( fn, H5F_ACC_RDONLY, plid ); H5Pclose( plid ); } else { file_id = H5Fopen(fn, H5F_ACC_RDONLY, H5P_DEFAULT); } if (file_id < 0) { FTI_Print("Could not open FTI checkpoint file.", FTI_EROR); return FTI_NREC; } FTI_Exec->H5groups[0]->h5groupID = file_id; FTIT_H5Group* rootGroup = FTI_Exec->H5groups[0]; int i; for (i = 0; i < FTI_Exec->H5groups[0]->childrenNo; i++) { FTI_OpenGroup(FTI_Exec->H5groups[rootGroup->childrenID[i]], file_id, FTI_Exec->H5groups); } for (i = 0; i < FTI_Exec->nbVar; i++) { FTI_CreateComplexType(FTI_Data[i].type, FTI_Exec->FTI_Type); } if( FTI_Exec->h5SingleFile ) { FTI_OpenGlobalDatasets( FTI_Exec ); } for (i = 0; i < FTI_Exec->nbVar; i++) { herr_t res; if( FTI_Exec->h5SingleFile ) { res = FTI_ReadSharedFileData( FTI_Data[i] ); } else { res = FTI_ReadHDF5Var(&FTI_Data[i]); } if (res < 0) { FTI_Print("Could not read FTI checkpoint file.", FTI_EROR); int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } H5Fclose(file_id); return FTI_NREC; } } for (i = 0; i < FTI_Exec->nbVar; i++) { FTI_CloseComplexType(FTI_Data[i].type, FTI_Exec->FTI_Type); } int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } if( FTI_Exec->h5SingleFile ) { FTI_CloseGlobalDatasets( FTI_Exec ); } FTI_Exec->H5groups[0]->h5groupID = -1; if (H5Fclose(file_id) < 0) { FTI_Print("Could not close FTI checkpoint file.", FTI_EROR); return FTI_NREC; } FTI_Exec->reco = 0; return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief During the restart, recovers the given variable @param id Variable to recover @return int FTI_SCES if successful. During a restart process, this function recovers the variable specified by the given id. **/ /*-------------------------------------------------------------------------*/ int FTI_RecoverVarHDF5(FTIT_execution* FTI_Exec, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data, int id) { char str[FTI_BUFS], fn[FTI_BUFS]; snprintf(fn, FTI_BUFS, "%s/%s", FTI_Ckpt[FTI_Exec->ckptLvel].dir, FTI_Exec->meta[FTI_Exec->ckptLvel].ckptFile); sprintf(str, "Trying to load FTI checkpoint file (%s)...", fn); FTI_Print(str, FTI_DBUG); hid_t file_id = H5Fopen(fn, H5F_ACC_RDONLY, H5P_DEFAULT); if (file_id < 0) { FTI_Print("Could not open FTI checkpoint file.", FTI_EROR); return FTI_NREC; } FTI_Exec->H5groups[0]->h5groupID = file_id; FTIT_H5Group* rootGroup = FTI_Exec->H5groups[0]; int i; for (i = 0; i < FTI_Exec->H5groups[0]->childrenNo; i++) { FTI_OpenGroup(FTI_Exec->H5groups[rootGroup->childrenID[i]], file_id, FTI_Exec->H5groups); } for (i = 0; i < FTI_Exec->nbVar; i++) { if (FTI_Data[i].id == id) { break; } } hid_t h5Type = FTI_Data[i].type->h5datatype; if (FTI_Data[i].type->id > 10 && FTI_Data[i].type->structure == NULL) { //if used FTI_InitType() save as binary h5Type = H5Tcopy(H5T_NATIVE_CHAR); H5Tset_size(h5Type, FTI_Data[i].size); } herr_t res = H5LTread_dataset(FTI_Data[i].h5group->h5groupID, FTI_Data[i].name, h5Type, FTI_Data[i].ptr); if (res < 0) { FTI_Print("Could not read FTI checkpoint file.", FTI_EROR); int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } H5Fclose(file_id); return FTI_NREC; } int j; for (j = 0; j < FTI_Exec->H5groups[0]->childrenNo; j++) { FTI_CloseGroup(FTI_Exec->H5groups[rootGroup->childrenID[j]], FTI_Exec->H5groups); } if (H5Fclose(file_id) < 0) { FTI_Print("Could not close FTI checkpoint file.", FTI_EROR); return FTI_NREC; } return FTI_SCES; } #endif <file_sep>/src/tools.c /** * Copyright (c) 2017 <NAME> * All rights reserved * * FTI - A multi-level checkpointing library for C/C++/Fortran applications * * Revision 1.0 : Fault Tolerance Interface (FTI) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file tools.c * @date October, 2017 * @brief Utility functions for the FTI library. */ #include "interface.h" #include <dirent.h> #include "api_cuda.h" int FTI_filemetastructsize; /**< size of FTIFF_db struct in file */ int FTI_dbstructsize; /**< size of FTIFF_db struct in file */ int FTI_dbvarstructsize; /**< size of FTIFF_db struct in file */ /*-------------------------------------------------------------------------*/ /** @brief Init of the static variables @return integer FTI_SCES if successful. This function initializes all static variables to zero. **/ /*-------------------------------------------------------------------------*/ int FTI_InitExecVars(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_injection* FTI_Inje) { // datablock size in file FTI_filemetastructsize = MD5_DIGEST_STRING_LENGTH + MD5_DIGEST_LENGTH + 7*sizeof(long); // TODO RS L3 only works for even file sizes. This accounts for many but clearly not all cases. // This is to fix. FTI_filemetastructsize += 2 - FTI_filemetastructsize%2; FTI_dbstructsize = sizeof(int) /* numvars */ + sizeof(long); /* dbsize */ FTI_dbvarstructsize = 3*sizeof(int) /* numvars */ + 2*sizeof(bool) + 2*sizeof(uintptr_t) + 2*sizeof(long) + MD5_DIGEST_LENGTH; // +--------- + // | FTI_Exec | // +--------- + /* char[BUFS] FTI_Exec->id */ memset(FTI_Exec->id,0x0,FTI_BUFS); /* int */ FTI_Exec->ckpt =0; /* int */ FTI_Exec->reco =0; /* int */ FTI_Exec->ckptLvel =0; /* int */ FTI_Exec->ckptIntv =0; /* int */ FTI_Exec->lastCkptLvel =0; /* int */ FTI_Exec->wasLastOffline =0; /* double */ FTI_Exec->iterTime =0; /* double */ FTI_Exec->lastIterTime =0; /* double */ FTI_Exec->meanIterTime =0; /* double */ FTI_Exec->globMeanIter =0; /* double */ FTI_Exec->totalIterTime =0; /* unsigned int */ FTI_Exec->syncIter =0; /* int */ FTI_Exec->syncIterMax =0; /* unsigned int */ FTI_Exec->minuteCnt =0; /* bool */ FTI_Exec->hasCkpt =false; /* unsigned int */ FTI_Exec->ckptCnt =0; /* unsigned int */ FTI_Exec->ckptIcnt =0; /* unsigned int */ FTI_Exec->ckptID =0; /* unsigned int */ FTI_Exec->ckptNext =0; /* unsigned int */ FTI_Exec->ckptLast =0; /* long */ FTI_Exec->ckptSize =0; /* unsigned int */ FTI_Exec->nbVar =0; /* unsigned int */ FTI_Exec->nbVarStored =0; /* unsigned int */ FTI_Exec->nbType =0; /* int */ FTI_Exec->metaAlloc =0; /* int */ FTI_Exec->initSCES =0; /* char[BUFS] FTI_Exec->h5SingleFileLast */ memset(FTI_Exec->h5SingleFileLast,0x0,FTI_BUFS); /* FTIT_iCPInfo FTI_Exec->iCPInfo */ memset(&(FTI_Exec->iCPInfo),0x0,sizeof(FTIT_iCPInfo)); /* FTIT_metadata[5] FTI_Exec->meta */ memset(FTI_Exec->meta,0x0,5*sizeof(FTIT_metadata)); /* FTIFF_db */ FTI_Exec->firstdb =NULL; /* FTIFF_db */ FTI_Exec->lastdb =NULL; /* FTIT_globalDataset */ FTI_Exec->globalDatasets =NULL; FTI_Exec->stageInfo =NULL; /* FTIFF_metaInfo FTI_Exec->FTIFFMeta */ memset(&(FTI_Exec->FTIFFMeta),0x0,sizeof(FTIFF_metaInfo)); FTI_Exec->FTIFFMeta.metaSize = FTI_filemetastructsize; /* MPI_Comm */ FTI_Exec->globalComm =0; /* MPI_Comm */ FTI_Exec->groupComm =0; // +--------- + // | FTI_Conf | // +--------- + /* char[BUFS] FTI_Conf->cfgFile */ memset(FTI_Conf->cfgFile,0x0,FTI_BUFS); /* int */ FTI_Conf->saveLastCkpt =0; /* int */ FTI_Conf->verbosity =0; /* int */ FTI_Conf->blockSize =0; /* int */ FTI_Conf->transferSize =0; #ifdef LUSTRE /* int */ FTI_Conf->stripeUnit =0; /* int */ FTI_Conf->stripeOffset =0; /* int */ FTI_Conf->stripeFactor =0; #endif /* bool */ FTI_Conf->keepL4Ckpt =0; /* bool */ FTI_Conf->h5SingleFileEnable =0; /* int */ FTI_Conf->ckptTag =0; /* int */ FTI_Conf->stageTag =0; /* int */ FTI_Conf->finalTag =0; /* int */ FTI_Conf->generalTag =0; /* int */ FTI_Conf->test =0; /* int */ FTI_Conf->l3WordSize =0; /* int */ FTI_Conf->ioMode =0; /* char[BUFS] FTI_Conf->localDir */ memset(FTI_Conf->localDir,0x0,FTI_BUFS); /* char[BUFS] FTI_Conf->glbalDir */ memset(FTI_Conf->glbalDir,0x0,FTI_BUFS); /* char[BUFS] FTI_Conf->metadDir */ memset(FTI_Conf->metadDir,0x0,FTI_BUFS); /* char[BUFS] FTI_Conf->lTmpDir */ memset(FTI_Conf->lTmpDir,0x0,FTI_BUFS); /* char[BUFS] FTI_Conf->gTmpDir */ memset(FTI_Conf->gTmpDir,0x0,FTI_BUFS); /* char[BUFS] FTI_Conf->mTmpDir */ memset(FTI_Conf->mTmpDir,0x0,FTI_BUFS); // +--------- + // | FTI_Topo | // +--------- + /* int */ FTI_Topo->nbProc =0; /* int */ FTI_Topo->nbNodes =0; /* int */ FTI_Topo->myRank =0; /* int */ FTI_Topo->splitRank =0; /* int */ FTI_Topo->nodeSize =0; /* int */ FTI_Topo->nbHeads =0; /* int */ FTI_Topo->nbApprocs =0; /* int */ FTI_Topo->groupSize =0; /* int */ FTI_Topo->sectorID =0; /* int */ FTI_Topo->nodeID =0; /* int */ FTI_Topo->groupID =0; /* int */ FTI_Topo->amIaHead =0; /* int */ FTI_Topo->headRank =0; /* int */ FTI_Topo->nodeRank =0; /* int */ FTI_Topo->groupRank =0; /* int */ FTI_Topo->right =0; /* int */ FTI_Topo->left =0; /* int[BUFS] FTI_Topo->body */ memset(FTI_Topo->body,0x0,FTI_BUFS*sizeof(int)); // +--------- + // | FTI_Ckpt | // +--------- + /* FTIT_Ckpt[5] FTI_Ckpt Array */ memset(FTI_Ckpt,0x0,sizeof(FTIT_checkpoint)*5); /* int */ FTI_Ckpt[4].isDcp =false; /* int */ FTI_Ckpt[4].hasDcp =false; // +--------- + // | FTI_Injc | // +--------- + //* int */ FTI_Injc->rank =0; //* int */ FTI_Injc->index =0; //* int */ FTI_Injc->position =0; //* int */ FTI_Injc->number =0; //* int */ FTI_Injc->frequency =0; //* int */ FTI_Injc->counter =0; //* double */ FTI_Injc->timer =0; return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief It calculates checksum of the checkpoint file. @param FTI_Exec Execution metadata. @param FTI_Data Dataset metadata. @param checksum Checksum that is calculated. @return integer FTI_SCES if successful. This function calculates checksum of the checkpoint file based on MD5 algorithm and saves it in checksum. **/ /*-------------------------------------------------------------------------*/ int FTI_Checksum(FTIT_execution* FTI_Exec, FTIT_dataset* FTI_Data, FTIT_configuration* FTI_Conf, char* checksum) { MD5_CTX mdContext; MD5_Init (&mdContext); int i; //iterate all variables for (i = 0; i < FTI_Exec->nbVar; i++) { #ifdef GPUSUPPORT if (FTI_Data[i].isDevicePtr) { if (FTI_Conf->ioMode != FTI_IO_FTIFF) FTI_Data[i].ptr = malloc(FTI_Data[i].count * FTI_Data[i].eleSize); if(FTI_Data[i].ptr == NULL){ FTI_Print("Failed to allocate FTI scratch buffer", FTI_EROR); return FTI_NSCS; } // TODO: Reuse GPU data on the host memory int result = FTI_Try(FTI_copy_from_device(FTI_Data[i].ptr, FTI_Data[i].devicePtr, FTI_Data[i].size, FTI_Exec), "copying data from GPU"); if(result == FTI_NSCS) { return FTI_NSCS; } } #endif MD5_Update (&mdContext, FTI_Data[i].ptr, FTI_Data[i].size); #ifdef GPUSUPPORT if (FTI_Data[i].isDevicePtr) { if (FTI_Conf->ioMode != FTI_IO_FTIFF){ free(FTI_Data[i].ptr); FTI_Data[i].ptr = NULL; } } #endif } unsigned char hash[MD5_DIGEST_LENGTH]; MD5_Final (hash, &mdContext); int ii = 0; for(i = 0; i < MD5_DIGEST_LENGTH; i++) { sprintf(&checksum[ii], "%02x", hash[i]); ii += 2; } return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief It compares checksum of the checkpoint file. @param fileName Filename of the checkpoint. @param checksumToCmp Checksum to compare. @return integer FTI_SCES if successful. This function calculates checksum of the checkpoint file based on MD5 algorithm. It compares calculated hash value with the one saved in the file. **/ /*-------------------------------------------------------------------------*/ int FTI_VerifyChecksum(char* fileName, char* checksumToCmp) { FILE *fd = fopen(fileName, "rb"); if (fd == NULL) { char str[FTI_BUFS]; sprintf(str, "FTI failed to open file %s to calculate checksum.", fileName); FTI_Print(str, FTI_WARN); return FTI_NSCS; } MD5_CTX mdContext; MD5_Init (&mdContext); int bytes; unsigned char data[CHUNK_SIZE]; while ((bytes = fread (data, 1, CHUNK_SIZE, fd)) != 0) { MD5_Update (&mdContext, data, bytes); } unsigned char hash[MD5_DIGEST_LENGTH]; MD5_Final (hash, &mdContext); int i; char checksum[MD5_DIGEST_STRING_LENGTH]; //calculated checksum int ii = 0; for(i = 0; i < MD5_DIGEST_LENGTH; i++) { sprintf(&checksum[ii], "%02x", hash[i]); ii += 2; } if (strcmp(checksum, checksumToCmp) != 0) { char str[FTI_BUFS]; sprintf(str, "TOOLS: Checksum do not match. \"%s\" file is corrupted. %s != %s", fileName, checksum, checksumToCmp); FTI_Print(str, FTI_WARN); fclose (fd); return FTI_NSCS; } fclose (fd); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief It receives the return code of a function and prints a message. @param result Result to check. @param message Message to print. @return integer The same result as passed in parameter. This function checks the result from a function and then decides to print the message either as a debug message or as a warning. **/ /*-------------------------------------------------------------------------*/ int FTI_Try(int result, char* message) { char str[FTI_BUFS]; if (result == FTI_SCES || result == FTI_DONE) { sprintf(str, "FTI succeeded to %s", message); FTI_Print(str, FTI_DBUG); } else { sprintf(str, "FTI failed to %s", message); FTI_Print(str, FTI_WARN); sprintf(str, "Error => %s", strerror(errno)); FTI_Print(str, FTI_WARN); } return result; } /*-------------------------------------------------------------------------*/ /** @brief It mallocs memory for the metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. This function mallocs the memory used for the metadata storage. **/ /*-------------------------------------------------------------------------*/ void FTI_MallocMeta(FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo) { int i; if (FTI_Topo->amIaHead) { for (i = 0; i < 5; i++) { FTI_Exec->meta[i].exists = calloc(FTI_Topo->nodeSize, sizeof(int)); FTI_Exec->meta[i].maxFs = calloc(FTI_Topo->nodeSize, sizeof(long)); FTI_Exec->meta[i].fs = calloc(FTI_Topo->nodeSize, sizeof(long)); FTI_Exec->meta[i].pfs = calloc(FTI_Topo->nodeSize, sizeof(long)); FTI_Exec->meta[i].ckptFile = calloc(FTI_BUFS * FTI_Topo->nodeSize, sizeof(char)); FTI_Exec->meta[i].currentL4CkptFile = calloc(FTI_BUFS * FTI_Topo->nodeSize, sizeof(char)); FTI_Exec->meta[i].nbVar = calloc(FTI_Topo->nodeSize, sizeof(int)); FTI_Exec->meta[i].varID = calloc(FTI_BUFS * FTI_Topo->nodeSize, sizeof(int)); FTI_Exec->meta[i].varSize = calloc(FTI_BUFS * FTI_Topo->nodeSize, sizeof(long)); } } else { for (i = 0; i < 5; i++) { FTI_Exec->meta[i].exists = calloc(1, sizeof(int)); FTI_Exec->meta[i].maxFs = calloc(1, sizeof(long)); FTI_Exec->meta[i].fs = calloc(1, sizeof(long)); FTI_Exec->meta[i].pfs = calloc(1, sizeof(long)); FTI_Exec->meta[i].ckptFile = calloc(FTI_BUFS, sizeof(char)); FTI_Exec->meta[i].currentL4CkptFile = calloc(FTI_BUFS, sizeof(char)); FTI_Exec->meta[i].nbVar = calloc(1, sizeof(int)); FTI_Exec->meta[i].varID = calloc(FTI_BUFS, sizeof(int)); FTI_Exec->meta[i].varSize = calloc(FTI_BUFS, sizeof(long)); } } FTI_Exec->metaAlloc = 1; } /*-------------------------------------------------------------------------*/ /** @brief It frees memory for the metadata. @param FTI_Exec Execution metadata. This function frees the memory used for the metadata storage. **/ /*-------------------------------------------------------------------------*/ void FTI_FreeMeta(FTIT_execution* FTI_Exec) { if (FTI_Exec->metaAlloc == 1) { int i; for (i = 0; i < 5; i++) { free(FTI_Exec->meta[i].exists); free(FTI_Exec->meta[i].maxFs); free(FTI_Exec->meta[i].fs); free(FTI_Exec->meta[i].pfs); free(FTI_Exec->meta[i].ckptFile); free(FTI_Exec->meta[i].nbVar); free(FTI_Exec->meta[i].varID); free(FTI_Exec->meta[i].varSize); } FTI_Exec->metaAlloc = 0; } } /*-------------------------------------------------------------------------*/ /** @brief It mallocs memory for the metadata. @param FTI_Exec Execution metadata. @param FTI_Topo Topology metadata. This function mallocs the memory used for the metadata storage. **/ /*-------------------------------------------------------------------------*/ int FTI_InitGroupsAndTypes(FTIT_execution* FTI_Exec) { FTI_Exec->FTI_Type = malloc(sizeof(FTIT_type*) * FTI_BUFS); if (FTI_Exec->FTI_Type == NULL) { return FTI_NSCS; } FTI_Exec->H5groups = malloc(sizeof(FTIT_H5Group*) * FTI_BUFS); if (FTI_Exec->H5groups == NULL) { return FTI_NSCS; } FTI_Exec->H5groups[0] = malloc(sizeof(FTIT_H5Group)); if (FTI_Exec->H5groups[0] == NULL) { return FTI_NSCS; } FTI_Exec->H5groups[0]->id = 0; FTI_Exec->H5groups[0]->childrenNo = 0; sprintf(FTI_Exec->H5groups[0]->name, "/"); FTI_Exec->nbGroup = 1; return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief It frees memory for the types. @param FTI_Exec Execution metadata. This function frees the memory used for the type storage. **/ /*-------------------------------------------------------------------------*/ void FTI_FreeTypesAndGroups(FTIT_execution* FTI_Exec) { int i; for (i = 0; i < FTI_Exec->nbType; i++) { if (FTI_Exec->FTI_Type[i]->structure != NULL) { //if complex type and have structure free(FTI_Exec->FTI_Type[i]->structure); } free(FTI_Exec->FTI_Type[i]); } free(FTI_Exec->FTI_Type); for (i = 0; i < FTI_Exec->nbGroup; i++) { free(FTI_Exec->H5groups[i]); } free(FTI_Exec->H5groups); } #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief It creates h5datatype (hid_t) from definitions in FTI_Types @param ftiType FTI_Type type This function creates (opens) hdf5 compound type. Should be called only before saving checkpoint in HDF5 format. Build-in FTI's types are always open. **/ /*-------------------------------------------------------------------------*/ void FTI_CreateComplexType(FTIT_type* ftiType, FTIT_type** FTI_Type) { char str[FTI_BUFS]; if (ftiType->h5datatype > -1) { //This type already created sprintf(str, "Type [%d] is already created.", ftiType->id); FTI_Print(str, FTI_DBUG); return; } if (ftiType->structure == NULL) { //Save as array of bytes sprintf(str, "Creating type [%d] as array of bytes.", ftiType->id); FTI_Print(str, FTI_DBUG); ftiType->h5datatype = H5Tcopy(H5T_NATIVE_CHAR); H5Tset_size(ftiType->h5datatype, ftiType->size); return; } hid_t partTypes[FTI_BUFS]; int i; //for each field create and rank-dimension array if needed for (i = 0; i < ftiType->structure->length; i++) { sprintf(str, "Type [%d] trying to create new type [%d].", ftiType->id, ftiType->structure->field[i].typeID); FTI_Print(str, FTI_DBUG); FTI_CreateComplexType(FTI_Type[ftiType->structure->field[i].typeID], FTI_Type); partTypes[i] = FTI_Type[ftiType->structure->field[i].typeID]->h5datatype; if (ftiType->structure->field[i].rank > 1) { //need to create rank-dimension array type hsize_t dims[FTI_BUFS]; int j; for (j = 0; j < ftiType->structure->field[i].rank; j++) { dims[j] = ftiType->structure->field[i].dimLength[j]; } sprintf(str, "Type [%d] trying to create %d-D array of type [%d].", ftiType->id, ftiType->structure->field[i].rank, ftiType->structure->field[i].typeID); FTI_Print(str, FTI_DBUG); partTypes[i] = H5Tarray_create(FTI_Type[ftiType->structure->field[i].typeID]->h5datatype, ftiType->structure->field[i].rank, dims); } else { if (ftiType->structure->field[i].dimLength[0] > 1) { //need to create 1-dimension array type sprintf(str, "Type [%d] trying to create 1-D [%d] array of type [%d].", ftiType->id, ftiType->structure->field[i].dimLength[0], ftiType->structure->field[i].typeID); FTI_Print(str, FTI_DBUG); hsize_t dim = ftiType->structure->field[i].dimLength[0]; partTypes[i] = H5Tarray_create(FTI_Type[ftiType->structure->field[i].typeID]->h5datatype, 1, &dim); } } } //create new HDF5 datatype sprintf(str, "Creating type [%d].", ftiType->id); FTI_Print(str, FTI_DBUG); ftiType->h5datatype = H5Tcreate(H5T_COMPOUND, ftiType->size); sprintf(str, "Type [%d] has hid_t %ld.", ftiType->id, (long)ftiType->h5datatype); FTI_Print(str, FTI_DBUG); if (ftiType->h5datatype < 0) { FTI_Print("FTI failed to create HDF5 type.", FTI_WARN); } //inserting fields into the new type for (i = 0; i < ftiType->structure->length; i++) { sprintf(str, "Insering type [%d] into new type [%d].", ftiType->structure->field[i].typeID, ftiType->id); FTI_Print(str, FTI_DBUG); herr_t res = H5Tinsert(ftiType->h5datatype, ftiType->structure->field[i].name, ftiType->structure->field[i].offset, partTypes[i]); if (res < 0) { FTI_Print("FTI faied to insert type in complex type.", FTI_WARN); } } } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief It closes h5datatype @param ftiType FTI_Type type This function destroys (closes) hdf5 compound type. Should be called after saving checkpoint in HDF5 format. **/ /*-------------------------------------------------------------------------*/ void FTI_CloseComplexType(FTIT_type* ftiType, FTIT_type** FTI_Type) { char str[FTI_BUFS]; if (ftiType->h5datatype == -1 || ftiType->id < 11) { //This type already closed or build-in type sprintf(str, "Cannot close type [%d]. Build in or already closed.", ftiType->id); FTI_Print(str, FTI_DBUG); return; } if (ftiType->structure != NULL) { //array of bytes don't have structure int i; //close each field for (i = 0; i < ftiType->structure->length; i++) { sprintf(str, "Closing type [%d] of compound type [%d].", ftiType->structure->field[i].typeID, ftiType->id); FTI_Print(str, FTI_DBUG); FTI_CloseComplexType(FTI_Type[ftiType->structure->field[i].typeID], FTI_Type); } } //close HDF5 datatype sprintf(str, "Closing type [%d].", ftiType->id); FTI_Print(str, FTI_DBUG); herr_t res = H5Tclose(ftiType->h5datatype); if (res < 0) { FTI_Print("FTI failed to close HDF5 type.", FTI_WARN); } ftiType->h5datatype = -1; } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief It creates a group and all it's children @param ftiGroup FTI_H5Group to be create @param parentGroup hid_t of the parent This function creates hdf5 group and all it's children. Should be called only before saving checkpoint in HDF5 format. **/ /*-------------------------------------------------------------------------*/ void FTI_CreateGroup(FTIT_H5Group* ftiGroup, hid_t parentGroup, FTIT_H5Group** FTI_Group) { ftiGroup->h5groupID = H5Gcreate2(parentGroup, ftiGroup->name, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); if (ftiGroup->h5groupID < 0) { FTI_Print("FTI failed to create HDF5 group.", FTI_WARN); return; } int i; for (i = 0; i < ftiGroup->childrenNo; i++) { FTI_CreateGroup(FTI_Group[ftiGroup->childrenID[i]], ftiGroup->h5groupID, FTI_Group); //Try to create the child } } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief It opens a group and all it's children @param ftiGroup FTI_H5Group to be opened @param parentGroup hid_t of the parent This function opens hdf5 group and all it's children. Should be called only before recovery in HDF5 format. **/ /*-------------------------------------------------------------------------*/ void FTI_OpenGroup(FTIT_H5Group* ftiGroup, hid_t parentGroup, FTIT_H5Group** FTI_Group) { ftiGroup->h5groupID = H5Gopen2(parentGroup, ftiGroup->name, H5P_DEFAULT); if (ftiGroup->h5groupID < 0) { FTI_Print("FTI failed to open HDF5 group.", FTI_WARN); return; } int i; for (i = 0; i < ftiGroup->childrenNo; i++) { FTI_OpenGroup(FTI_Group[ftiGroup->childrenID[i]], ftiGroup->h5groupID, FTI_Group); //Try to open the child } } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief It closes a group and all it's children @param ftiGroup FTI_H5Group to be closed This function closes (destoys) hdf5 group and all it's children. Should be called only after saving checkpoint in HDF5 format. **/ /*-------------------------------------------------------------------------*/ void FTI_CloseGroup(FTIT_H5Group* ftiGroup, FTIT_H5Group** FTI_Group) { char str[FTI_BUFS]; if (ftiGroup->h5groupID == -1) { //This group already closed, in tree this is error snprintf(str, FTI_BUFS, "Group %s is already closed?", ftiGroup->name); FTI_Print(str, FTI_WARN); return; } int i; for (i = 0; i < ftiGroup->childrenNo; i++) { FTI_CloseGroup(FTI_Group[ftiGroup->childrenID[i]], FTI_Group); //Try to close the child } herr_t res = H5Gclose(ftiGroup->h5groupID); if (res < 0) { FTI_Print("FTI failed to close HDF5 group.", FTI_WARN); } ftiGroup->h5groupID = -1; } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief It creates the global dataset in the VPR file. @param FTI_Exec Execution metadata. @return integer FTI_SCES if successful. Creates global dataset (shared among all ranks) in VPR file. The dataset position will be the group assigned to it by calling the FTI API function 'FTI_DefineGlobalDataset'. **/ /*-------------------------------------------------------------------------*/ int FTI_CreateGlobalDatasets( FTIT_execution* FTI_Exec ) { FTIT_globalDataset* dataset = FTI_Exec->globalDatasets; while( dataset ) { // create file space dataset->fileSpace = H5Screate_simple( dataset->rank, dataset->dimension, NULL ); if(dataset->fileSpace < 0) { char errstr[FTI_BUFS]; snprintf( errstr, FTI_BUFS, "Unable to create space for dataset #%d", dataset->id ); FTI_Print(errstr,FTI_EROR); return FTI_NSCS; } // create dataset hid_t loc = dataset->location->h5groupID; hid_t tid = FTI_Exec->FTI_Type[dataset->type.id]->h5datatype; dataset->hdf5TypeId = tid; hid_t fsid = dataset->fileSpace; // FLETCHER CHECKSUM NOT SUPPORTED FOR PARALLEL I/O IN HDF5 //hid_t dcpl = H5Pcreate (H5P_DATASET_CREATE); //H5Pset_fletcher32 (dcpl); // //hsize_t *chunk = malloc( sizeof(hsize_t) * dataset->rank ); //chunk[0] = chunk[1] = 4096; //H5Pset_chunk (dcpl, 2, chunk); dataset->hid = H5Dcreate( loc, dataset->name, tid, fsid, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT ); if(dataset->hid < 0) { char errstr[FTI_BUFS]; snprintf( errstr, FTI_BUFS, "Unable to create dataset #%d", dataset->id ); FTI_Print(errstr,FTI_EROR); return FTI_NSCS; } dataset->initialized = true; dataset = dataset->next; } return FTI_SCES; } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief Opens global dataset in VPR file. @param FTI_Exec Execution metadata. @return integer FTI_SCES if successful. This function is the analog to 'FTI_CreateGlobalDatasets' on recovery. **/ /*-------------------------------------------------------------------------*/ int FTI_OpenGlobalDatasets( FTIT_execution* FTI_Exec ) { hsize_t *dims = NULL; hsize_t *maxDims = NULL; char errstr[FTI_BUFS]; FTIT_globalDataset* dataset = FTI_Exec->globalDatasets; while( dataset ) { dims = (hsize_t*) realloc( dims, sizeof(hsize_t)*dataset->rank ); maxDims = (hsize_t*) realloc( maxDims, sizeof(hsize_t)*dataset->rank ); // open dataset hid_t loc = dataset->location->h5groupID; hid_t tid = FTI_Exec->FTI_Type[dataset->type.id]->h5datatype; dataset->hdf5TypeId = tid; dataset->hid = H5Dopen( loc, dataset->name, H5P_DEFAULT ); if(dataset->hid < 0) { snprintf( errstr, FTI_BUFS, "failed to open dataset '%s'", dataset->name ); FTI_Print( errstr, FTI_WARN ); return FTI_NSCS; } // get file space and check if rank and dimension coincide for file and execution hid_t fsid = H5Dget_space( dataset->hid ); if( fsid > 0 ) { int rank = H5Sget_simple_extent_ndims( fsid ); if( rank == dataset->rank ) { H5Sget_simple_extent_dims( fsid, dims, maxDims ); if( memcmp( dims, dataset->dimension, sizeof(hsize_t)*rank ) ) { snprintf( errstr, FTI_BUFS, "stored and requested dimensions of dataset '%s' differ!", dataset->name ); FTI_Print( errstr, FTI_WARN ); return FTI_NSCS; } } else { snprintf( errstr, FTI_BUFS, "stored and requested rank of dataset '%s' differ (stored:%d != requested:%d)!", dataset->name, rank, dataset->rank ); FTI_Print( errstr, FTI_WARN ); return FTI_NSCS; } } else { snprintf( errstr, FTI_BUFS, "failed to acquire data space information of dataset '%s'", dataset->name ); FTI_Print( errstr, FTI_WARN ); return FTI_NSCS; } dataset->fileSpace = fsid; dataset->initialized = true; dataset = dataset->next; } if( dims ) { free( dims ); } if( maxDims ) { free( maxDims ); } return FTI_SCES; } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief Closes global datasets in VPR file @param FTI_Exec Execution metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ int FTI_CloseGlobalDatasets( FTIT_execution* FTI_Exec ) { FTIT_globalDataset* dataset = FTI_Exec->globalDatasets; while( dataset ) { H5Sclose(dataset->fileSpace); H5Dclose(dataset->hid); dataset = dataset->next; } return FTI_SCES; } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief Writes global dataset subsets into VPR file. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ herr_t FTI_WriteSharedFileData( FTIT_dataset FTI_Data ) { if( FTI_Data.sharedData.dataset ) { // hdf5 datatype hid_t tid = FTI_Data.sharedData.dataset->hdf5TypeId; // dataset hdf5-id hid_t did = FTI_Data.sharedData.dataset->hid; // shared dataset file space hid_t fsid = FTI_Data.sharedData.dataset->fileSpace; // shared dataset rank int ndim = FTI_Data.sharedData.dataset->rank; // shared dataset array of nummber of elements in each dimension hsize_t *count = FTI_Data.sharedData.count; // shared dataset array of the offsets for each dimension hsize_t *offset = FTI_Data.sharedData.offset; // create dataspace for subset of shared dataset hid_t msid = H5Screate_simple( ndim, count, NULL ); if(msid < 0) { char errstr[FTI_BUFS]; snprintf( errstr, FTI_BUFS, "Unable to create space for var-id %d in dataset #%d", FTI_Data.id, FTI_Data.sharedData.dataset->id ); FTI_Print(errstr,FTI_EROR); return FTI_NSCS; } // select range in shared dataset in file if( H5Sselect_hyperslab(fsid, H5S_SELECT_SET, offset, NULL, count, NULL) < 0 ) { char errstr[FTI_BUFS]; snprintf( errstr, FTI_BUFS, "Unable to select sub-space for var-id %d in dataset #%d", FTI_Data.id, FTI_Data.sharedData.dataset->id ); FTI_Print(errstr,FTI_EROR); return FTI_NSCS; } // enable collective buffering hid_t plid = H5Pcreate( H5P_DATASET_XFER ); H5Pset_dxpl_mpio(plid, H5FD_MPIO_COLLECTIVE); // write data in file if( H5Dwrite(did, tid, msid, fsid, plid, FTI_Data.ptr) < 0 ) { char errstr[FTI_BUFS]; snprintf( errstr, FTI_BUFS, "Unable to write var-id %d of dataset #%d", FTI_Data.id, FTI_Data.sharedData.dataset->id ); FTI_Print(errstr,FTI_EROR); return FTI_NSCS; } H5Sclose( msid ); H5Pclose( plid ); } return FTI_SCES; } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief Checks for matching dimension sizes of sub-sets @param FTI_Data Dataset metadata. @param FTI_Exec Execution metadata. @return integer FTI_SCES if successful. This function counts the number of elements of all sub-sets contained in a particular global dataset and accumulates to a total value. If the accu- mulated value matches the number of elements defined for the global data- set, FTI_SCES is returned. This function is called before the checkpoint and before the recovery. @todo it would be great to check for region overlapping too. **/ /*-------------------------------------------------------------------------*/ int FTI_CheckDimensions( FTIT_dataset * FTI_Data, FTIT_execution * FTI_Exec ) { // NOTE checking for overlap is complicated and likely expensive // since it requires sorting within all contributing processes. // Thus, we check currently only the number of elements. FTIT_globalDataset* dataset = FTI_Exec->globalDatasets; while( dataset ) { int i,j; // sum of local elements hsize_t numElemLocal = 0, numElemGlobal; for( i=0; i<dataset->numSubSets; ++i ) { hsize_t numElemSubSet = 1; for( j=0; j<dataset->rank; j++ ) { numElemSubSet *= FTI_Data[dataset->varIdx[i]].sharedData.count[j]; } numElemLocal += numElemSubSet; } // number of elements in global dataset hsize_t numElem = 1; for( i=0; i<dataset->rank; ++i ) { numElem *= dataset->dimension[i]; } MPI_Allreduce( &numElemLocal, &numElemGlobal, 1, MPI_UNSIGNED_LONG_LONG, MPI_SUM, FTI_COMM_WORLD ); if( numElem != numElemGlobal ) { char errstr[FTI_BUFS]; snprintf( errstr, FTI_BUFS, "Number of elements of subsets (accumulated) do not match number of elements defined for global dataset #%d!", dataset->id ); FTI_Print( errstr, FTI_WARN); return FTI_NSCS; } dataset = dataset->next; } return FTI_SCES; } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief Checks if VPR file on restart @param FTI_Conf Configuration metadata. @param ckptID Checkpoint ID. @return integer FTI_SCES if successful. Checks if restart is possible for VPR file. 1) Checks if file exist for prefix and directory, defined in config file. 2) Checks if is regular file. 3) Checks if groups and datasets can be accessed and if datasets can be read If file found and sane, ckptID is set and FTI_SCES is returned. **/ /*-------------------------------------------------------------------------*/ int FTI_H5CheckSingleFile( FTIT_configuration* FTI_Conf, int *ckptID ) { char errstr[FTI_BUFS]; char fn[FTI_BUFS]; int res = FTI_SCES; struct stat st; struct dirent *entry; DIR *dir = opendir( FTI_Conf->h5SingleFileDir ); if ( dir == NULL ) { snprintf( errstr, FTI_BUFS, "VPR directory '%s' could not be accessed.", FTI_Conf->h5SingleFileDir ); FTI_Print(errstr, FTI_EROR); errno = 0; return FTI_NSCS; } *ckptID = -1; bool found = false; while((entry = readdir(dir)) != NULL) { if(strcmp(entry->d_name,".") && strcmp(entry->d_name,"..")) { int len = strlen( entry->d_name ); if( len > 14 ) { char fileRoot[FTI_BUFS]; bzero( fileRoot, FTI_BUFS ); memcpy( fileRoot, entry->d_name, len - 14 ); char fileRootExpected[FTI_BUFS]; snprintf( fileRootExpected, FTI_BUFS, "%s", FTI_Conf->h5SingleFilePrefix ); if( strncmp( fileRootExpected, fileRoot, FTI_BUFS ) == 0 ) { int id_tmp; sscanf( entry->d_name + len - 14 + 3, "%08d.h5", &id_tmp ); if( id_tmp > *ckptID ) { *ckptID = id_tmp; snprintf( fn, FTI_BUFS, "%s/%s-ID%08d.h5", FTI_Conf->h5SingleFileDir, FTI_Conf->h5SingleFilePrefix, *ckptID ); } found = true; } } } } if (!found) { snprintf( errstr, FTI_BUFS, "unable to find matching VPR file (filename pattern: '%s-ID########.h5')!", FTI_Conf->h5SingleFilePrefix ); FTI_Print( errstr, FTI_WARN ); return FTI_NSCS; } stat( fn, &st ); if( S_ISREG( st.st_mode ) ) { hid_t fid = H5Fopen( fn, H5F_ACC_RDONLY, H5P_DEFAULT ); if( fid > 0 ) { hid_t gid = H5Gopen1( fid, "/" ); if( gid > 0 ) { res += FTI_ScanGroup( gid, fn ); H5Gclose(gid); } else { snprintf( errstr, FTI_BUFS, "failed to access root group in file '%s'", fn ); FTI_Print( errstr, FTI_WARN ); res = FTI_NSCS; } H5Fclose(fid); } else { snprintf( errstr, FTI_BUFS, "failed to open file '%s'", fn ); FTI_Print( errstr, FTI_WARN ); res = FTI_NSCS; } } else { snprintf( errstr, FTI_BUFS, "'%s', is not a regular file!", fn ); FTI_Print( errstr, FTI_WARN ); res = FTI_NSCS; } return res; } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief Checks groups and datasets (callable recursively) @param gid Parent group ID. @param fn File name. @return integer FTI_SCES if successful. This function analyses the group structure recursivley starting at group 'gid'. It steps down in sub groups and checks datasets of consistency. The consistency check is performed if the dataset was created with the fletcher32 filter activated. A dataset read will return a negative value in that case if dataset corrupted. **/ /*-------------------------------------------------------------------------*/ int FTI_ScanGroup( hid_t gid, char* fn ) { int res = FTI_SCES; char errstr[FTI_BUFS]; hsize_t nobj; if( H5Gget_num_objs( gid, &nobj ) >= 0 ) { int i; for(i=0; i<nobj; i++) { int objtype; char dname[FTI_BUFS]; char gname[FTI_BUFS]; // determine if element is group or dataset objtype = H5Gget_objtype_by_idx(gid, (size_t)i ); if( objtype == H5G_DATASET ) { H5Gget_objname_by_idx(gid, (hsize_t)i, dname, (size_t) FTI_BUFS); // open dataset hid_t did = H5Dopen1( gid, dname ); if( did > 0 ) { hid_t sid = H5Dget_space(did); hid_t tid = H5Dget_type(did); int drank = H5Sget_simple_extent_ndims( sid ); size_t typeSize = H5Tget_size( tid ); hsize_t *count = (hsize_t*) calloc( drank, sizeof(hsize_t) ); hsize_t *offset = (hsize_t*) calloc( drank, sizeof(hsize_t) ); count[0] = 1; char* buffer = (char*) malloc( typeSize ); hid_t msid = H5Screate_simple( drank, count, NULL ); H5Sselect_hyperslab(sid, H5S_SELECT_SET, offset, NULL, count, NULL); // read element to trigger checksum comparison herr_t status = H5Dread(did, tid, msid, sid, H5P_DEFAULT, buffer); if( status < 0 ) { snprintf( errstr, FTI_BUFS, "unable to read from dataset '%s' in file '%s'!", dname, fn ); FTI_Print( errstr, FTI_WARN ); res += FTI_NSCS; } H5Dclose(did); H5Sclose(msid); H5Sclose(sid); H5Tclose(tid); free( count ); free( offset ); free( buffer ); } else { snprintf( errstr, FTI_BUFS, "failed to open dataset '%s' in file '%s'", dname, fn ); FTI_Print( errstr, FTI_WARN ); res += FTI_NSCS; } } // step down other group if( objtype == H5G_GROUP ) { H5Gget_objname_by_idx(gid, (hsize_t)i, gname, (size_t) FTI_BUFS); hid_t sgid = H5Gopen1( gid, gname ); if( sgid > 0 ) { res += FTI_ScanGroup( sgid, fn ); H5Gclose(sgid); } else { snprintf( errstr, FTI_BUFS, "failed to open group '%s' in file '%s'", gname, fn ); FTI_Print( errstr, FTI_WARN ); res += FTI_NSCS; } } } } else { snprintf( errstr, FTI_BUFS, "failed to get number of elements in file '%s'", fn ); FTI_Print( errstr, FTI_WARN ); res += FTI_NSCS; } return FTI_SCES; } #endif #ifdef ENABLE_HDF5 /*-------------------------------------------------------------------------*/ /** @brief Reads a sub-set of a global dataset on recovery. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. **/ /*-------------------------------------------------------------------------*/ herr_t FTI_ReadSharedFileData( FTIT_dataset FTI_Data ) { // hdf5 datatype hid_t tid = FTI_Data.sharedData.dataset->hdf5TypeId; // dataset hdf5-id hid_t did = FTI_Data.sharedData.dataset->hid; // shared dataset file space hid_t fsid = FTI_Data.sharedData.dataset->fileSpace; // shared dataset rank int ndim = FTI_Data.sharedData.dataset->rank; // shared dataset array of nummber of elements in each dimension hsize_t *count = FTI_Data.sharedData.count; // shared dataset array of the offsets for each dimension hsize_t *offset = FTI_Data.sharedData.offset; // create dataspace for subset of shared dataset hid_t msid = H5Screate_simple( ndim, count, NULL ); if(msid < 0) { char errstr[FTI_BUFS]; snprintf( errstr, FTI_BUFS, "Unable to create space for var-id %d in dataset #%d", FTI_Data.id, FTI_Data.sharedData.dataset->id ); FTI_Print(errstr,FTI_EROR); return FTI_NSCS; } // select range in shared dataset in file H5Sselect_hyperslab(fsid, H5S_SELECT_SET, offset, NULL, count, NULL); // enable collective buffering hid_t plid = H5Pcreate( H5P_DATASET_XFER ); H5Pset_dxpl_mpio(plid, H5FD_MPIO_COLLECTIVE); // write data in file herr_t status = H5Dread(did, tid, msid, fsid, plid, FTI_Data.ptr); if(status < 0) { char errstr[FTI_BUFS]; snprintf( errstr, FTI_BUFS, "Unable to read var-id %d from dataset #%d", FTI_Data.id, FTI_Data.sharedData.dataset->id ); FTI_Print(errstr,FTI_EROR); return FTI_NSCS; } H5Sclose( msid ); H5Pclose( plid ); return status; } #endif #ifdef ENABLE_HDF5 void FTI_FreeVPRMem( FTIT_execution* FTI_Exec, FTIT_dataset* FTI_Data ) { FTIT_globalDataset * dataset = FTI_Exec->globalDatasets; while( dataset ) { if( dataset->dimension ) { free( dataset->dimension ); } if( dataset->varIdx ) { free( dataset->varIdx ); } FTIT_globalDataset * curr = dataset; dataset = dataset->next; free( curr ); } int i=0; for( ; i<FTI_Exec->nbVar; i++ ) { if( FTI_Data[i].sharedData.offset ) { free( FTI_Data[i].sharedData.offset ); } if( FTI_Data[i].sharedData.count ) { free( FTI_Data[i].sharedData.count ); } } } #endif /*-------------------------------------------------------------------------*/ /** @brief It creates the basic datatypes and the dataset array. @param FTI_Data Dataset metadata. @return integer FTI_SCES if successful. This function creates the basic data types using FTIT_Type. **/ /*-------------------------------------------------------------------------*/ int FTI_InitBasicTypes(FTIT_dataset* FTI_Data) { int i; for (i = 0; i < FTI_BUFS; i++) { FTI_Data[i].id = -1; } FTI_InitType(&FTI_CHAR, sizeof(char)); FTI_InitType(&FTI_SHRT, sizeof(short)); FTI_InitType(&FTI_INTG, sizeof(int)); FTI_InitType(&FTI_LONG, sizeof(long)); FTI_InitType(&FTI_UCHR, sizeof(unsigned char)); FTI_InitType(&FTI_USHT, sizeof(unsigned short)); FTI_InitType(&FTI_UINT, sizeof(unsigned int)); FTI_InitType(&FTI_ULNG, sizeof(unsigned long)); FTI_InitType(&FTI_SFLT, sizeof(float)); FTI_InitType(&FTI_DBLE, sizeof(double)); FTI_InitType(&FTI_LDBE, sizeof(long double)); return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief It erases a directory and all its files. @param path Path to the directory we want to erase. @param flag Set to 1 to activate. @return integer FTI_SCES if successful. This function erases a directory and all its files. It focusses on the checkpoint directories created by FTI so it does NOT handle recursive erasing if the given directory includes other directories. **/ /*-------------------------------------------------------------------------*/ int FTI_RmDir(char path[FTI_BUFS], int flag) { if (flag) { char str[FTI_BUFS]; sprintf(str, "Removing directory %s and its files.", path); FTI_Print(str, FTI_DBUG); DIR* dp = opendir(path); if (dp != NULL) { struct dirent* ep = NULL; while ((ep = readdir(dp)) != NULL) { char fil[FTI_BUFS]; sprintf(fil, "%s", ep->d_name); FTI_Print(fil, FTI_DBUG); if ((strcmp(fil, ".") != 0) && (strcmp(fil, "..") != 0)) { char fn[FTI_BUFS]; sprintf(fn, "%s/%s", path, fil); sprintf(str, "File %s will be removed.", fn); FTI_Print(str, FTI_DBUG); if (remove(fn) == -1) { if (errno != ENOENT) { snprintf(str, FTI_BUFS, "Error removing target file (%s).", fn); FTI_Print(str, FTI_EROR); } } } } } else { if (errno != ENOENT) { FTI_Print("Error with opendir.", FTI_EROR); } } if (dp != NULL) { closedir(dp); } if (remove(path) == -1) { if (errno != ENOENT) { FTI_Print("Error removing target directory.", FTI_EROR); } } } return FTI_SCES; } /*-------------------------------------------------------------------------*/ /** @brief It erases the previous checkpoints and their metadata. @param FTI_Conf Configuration metadata. @param FTI_Topo Topology metadata. @param FTI_Ckpt Checkpoint metadata. @param level Level of cleaning. @return integer FTI_SCES if successful. This function erases previous checkpoint depending on the level of the current checkpoint. Level 5 means complete clean up. Level 6 means clean up local nodes but keep last checkpoint data and metadata in the PFS. **/ /*-------------------------------------------------------------------------*/ int FTI_Clean(FTIT_configuration* FTI_Conf, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int level) { int nodeFlag; //only one process in the node has set it to 1 int globalFlag = !FTI_Topo->splitRank; //only one process in the FTI_COMM_WORLD has set it to 1 globalFlag = (!FTI_Ckpt[4].isDcp && (globalFlag != 0)); nodeFlag = (((!FTI_Topo->amIaHead) && ((FTI_Topo->nodeRank - FTI_Topo->nbHeads) == 0)) || (FTI_Topo->amIaHead)) ? 1 : 0; nodeFlag = (!FTI_Ckpt[4].isDcp && (nodeFlag != 0)); if (level == 0) { FTI_RmDir(FTI_Conf->mTmpDir, globalFlag); FTI_RmDir(FTI_Conf->gTmpDir, globalFlag); FTI_RmDir(FTI_Conf->lTmpDir, nodeFlag); } // Clean last checkpoint level 1 if (level >= 1) { FTI_RmDir(FTI_Ckpt[1].metaDir, globalFlag); FTI_RmDir(FTI_Ckpt[1].dir, nodeFlag); } // Clean last checkpoint level 2 if (level >= 2) { FTI_RmDir(FTI_Ckpt[2].metaDir, globalFlag); FTI_RmDir(FTI_Ckpt[2].dir, nodeFlag); } // Clean last checkpoint level 3 if (level >= 3) { FTI_RmDir(FTI_Ckpt[3].metaDir, globalFlag); FTI_RmDir(FTI_Ckpt[3].dir, nodeFlag); } // Clean last checkpoint level 4 if ( level == 4 || level == 5 ) { FTI_RmDir(FTI_Ckpt[4].metaDir, globalFlag); FTI_RmDir(FTI_Ckpt[4].dir, globalFlag); rmdir(FTI_Conf->gTmpDir); } if ( FTI_Conf->dcpEnabled && level == 5 ) { FTI_RmDir(FTI_Ckpt[4].dcpDir, !FTI_Topo->splitRank); } // If it is the very last cleaning and we DO NOT keep the last checkpoint if (level == 5) { rmdir(FTI_Conf->lTmpDir); rmdir(FTI_Conf->localDir); rmdir(FTI_Conf->glbalDir); char buf[FTI_BUFS]; snprintf(buf, FTI_BUFS, "%s/Topology.fti", FTI_Conf->metadDir); if (remove(buf) == -1) { if (errno != ENOENT) { FTI_Print("Cannot remove Topology.fti", FTI_EROR); } } snprintf(buf, FTI_BUFS, "%s/Checkpoint.fti", FTI_Conf->metadDir); if (remove(buf) == -1) { if (errno != ENOENT) { FTI_Print("Cannot remove Checkpoint.fti", FTI_EROR); } } rmdir(FTI_Conf->metadDir); } // If it is the very last cleaning and we DO keep the last checkpoint if (level == 6) { rmdir(FTI_Conf->lTmpDir); rmdir(FTI_Conf->localDir); } return FTI_SCES; } <file_sep>/src/interface.h /** * Copyright (c) 2017 <NAME> * All rights reserved * * FTI - A multi-level checkpointing library for C/C++/Fortran applications * * Revision 1.0 : Fault Tolerance Interface (FTI) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file interface.h * @date October, 2017 * @brief Header file for the FTI library private functions. */ #ifndef _FTI_INTERFACE_H #define _FTI_INTERFACE_H #include "failure-injection.h" #include "fti.h" #include "ftiff.h" #include "../deps/iniparser/iniparser.h" #include "../deps/iniparser/dictionary.h" #include "../deps/jerasure/include/galois.h" #include "../deps/jerasure/include/jerasure.h" #ifdef ENABLE_SIONLIB // --> If SIONlib is installed # include <sion.h> #endif #ifdef ENABLE_HDF5 #include "hdf5.h" #include "hdf5_hl.h" #endif #include "stage.h" #include <stdint.h> #include "../deps/md5/md5.h" #define CHUNK_SIZE 131072 /**< MD5 algorithm chunk size. */ #include <fcntl.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <time.h> #include <errno.h> #include <math.h> #include <limits.h> #include <inttypes.h> #include <dirent.h> #include <stdbool.h> #include <stdint.h> #include <time.h> #include <libgen.h> #ifdef LUSTRE # include "lustreapi.h" #endif /*--------------------------------------------------------------------------- Defines ---------------------------------------------------------------------------*/ /** Malloc macro. */ #define talloc(type, num) (type *)malloc(sizeof(type) * (num)) extern int FTI_filemetastructsize; /**< size of FTIFF_metaInfo in file */ extern int FTI_dbstructsize; /**< size of FTIFF_db in file */ extern int FTI_dbvarstructsize; /**< size of FTIFF_dbvar in file */ /*--------------------------------------------------------------------------- FTI private functions ---------------------------------------------------------------------------*/ void FTI_PrintMeta(FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo); int FTI_FloatBitFlip(float *target, int bit); int FTI_DoubleBitFlip(double *target, int bit); void FTI_Print(char *msg, int priority); int FTI_UpdateIterTime(FTIT_execution* FTI_Exec); int FTI_WriteCkpt(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); #ifdef ENABLE_SIONLIB // --> If SIONlib is installed int FTI_WriteSionlib(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo,FTIT_dataset* FTI_Data); #endif int FTI_WriteMPI(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo,FTIT_dataset* FTI_Data); int FTI_WritePar(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo,FTIT_dataset* FTI_Data); int FTI_WritePosix(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_PostCkpt(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_Listen(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_HandleCkptRequest(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_HandleStageRequest(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int source); int FTI_UpdateConf(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, int restart); int FTI_ReadConf(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_injection *FTI_Inje); int FTI_TestConfig(FTIT_configuration* FTI_Conf, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_execution* FTI_Exec); int FTI_TestDirectories(FTIT_configuration* FTI_Conf, FTIT_topology* FTI_Topo); int FTI_CreateDirs(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_LoadConf(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_injection *FTI_Inje); #ifdef ENABLE_HDF5 int FTI_WriteHDF5(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_RecoverHDF5(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_RecoverVarHDF5(FTIT_execution* FTI_Exec, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data, int id); int FTI_WriteHDF5Var(FTIT_dataset* FTI_DataVar); int FTI_CheckHDF5File(char* fn, long fs, char* checksum); int FTI_OpenGlobalDatasets( FTIT_execution* FTI_Exec ); herr_t FTI_ReadSharedFileData( FTIT_dataset FTI_Data ); int FTI_H5CheckSingleFile( FTIT_configuration* FTI_Conf, int * ckptID ); int FTI_ScanGroup( hid_t gid, char* fn ); int FTI_CheckDimensions( FTIT_dataset * FTI_Data, FTIT_execution * FTI_Exec ); void FTI_FreeVPRMem( FTIT_execution* FTI_Exec, FTIT_dataset* FTI_Data ); #endif int FTI_GetChecksums(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, char* checksum, char* ptnerChecksum, char* rsChecksum); int FTI_WriteRSedChecksum(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int rank, char* checksum); int FTI_LoadTmpMeta(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_LoadMeta(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_WriteMetadata(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, long* fs, long mfs, char* fnl, char* checksums, int* allVarIDs, long* allVarSizes); int FTI_CreateMetadata(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_WriteCkptMetaData(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt ); int FTI_LoadCkptMetaData(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt ); int FTI_LoadL4CkptMetaData(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt ); int FTI_Local(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_Ptner(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_RSenc(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_Flush(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int level); int FTI_FlushPosix(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int level); int FTI_FlushMPI(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int level); #ifdef ENABLE_SIONLIB // --> If SIONlib is installed int FTI_FlushSionlib(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int level); #endif int FTI_Decode(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int *erased); int FTI_RecoverL1(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_RecoverL2(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_RecoverL3(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_RecoverL4(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_RecoverL4Posix(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_RecoverL4Mpi(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); #ifdef ENABLE_SIONLIB // --> If SIONlib is installed int FTI_RecoverL4Sionlib(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); #endif int FTI_CheckFile(char *fn, long fs, char* checksum); int FTI_CheckErasures(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int *erased); int FTI_RecoverFiles(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt); int FTI_Checksum(FTIT_execution* FTI_Exec, FTIT_dataset* FTI_Data, FTIT_configuration* FTI_Conf, char* checksum); int FTI_VerifyChecksum(char* fileName, char* checksumToCmp); int FTI_Try(int result, char* message); void FTI_MallocMeta(FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo); void FTI_FreeMeta(FTIT_execution* FTI_Exec); void FTI_FreeTypesAndGroups(FTIT_execution* FTI_Exec); #ifdef ENABLE_HDF5 herr_t FTI_WriteSharedFileData( FTIT_dataset FTI_Data ); void FTI_CreateComplexType(FTIT_type* ftiType, FTIT_type** FTI_Type); void FTI_CloseComplexType(FTIT_type* ftiType, FTIT_type** FTI_Type); void FTI_CreateGroup(FTIT_H5Group* ftiGroup, hid_t parentGroup, FTIT_H5Group** FTI_Group); void FTI_OpenGroup(FTIT_H5Group* ftiGroup, hid_t parentGroup, FTIT_H5Group** FTI_Group); void FTI_CloseGroup(FTIT_H5Group* ftiGroup, FTIT_H5Group** FTI_Group); int FTI_CreateGlobalDatasets( FTIT_execution* FTI_Exec ); int FTI_CloseGlobalDatasets( FTIT_execution* FTI_Exec ); #endif int FTI_InitGroupsAndTypes(FTIT_execution* FTI_Exec); int FTI_InitBasicTypes(FTIT_dataset* FTI_Data); int FTI_InitExecVars(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_injection* FTI_Inje); int FTI_RmDir(char path[FTI_BUFS], int flag); int FTI_Clean(FTIT_configuration* FTI_Conf, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, int level); int FTI_SaveTopo(FTIT_configuration* FTI_Conf, FTIT_topology* FTI_Topo, char *nameList); int FTI_ReorderNodes(FTIT_configuration* FTI_Conf, FTIT_topology* FTI_Topo, int *nodeList, char *nameList); int FTI_BuildNodeList(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, int *nodeList, char *nameList); int FTI_CreateComms(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, int *userProcList, int *distProcList, int* nodeList); int FTI_Topology(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo); int FTI_ArchiveL4Ckpt( FTIT_configuration* FTI_Conf, FTIT_execution *FTI_Exec, FTIT_checkpoint *FTI_Ckpt, FTIT_topology *FTI_Topo ); void FTI_PrintStatus( FTIT_execution *FTI_Exec, FTIT_topology *FTI_Topo, int ID, int source ); #endif // DIFFERENTIAL CHECKPOINTING #ifdef FTI_NOZLIB extern const uint32_t crc32_tab[]; static inline uint32_t crc32_raw(const void *buf, size_t size, uint32_t crc) { const uint8_t *p = (const uint8_t *)buf; while (size--) crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); return (crc); } static inline uint32_t crc32(const void *buf, size_t size) { uint32_t crc; crc = crc32_raw(buf, size, ~0U); return (crc ^ ~0U); } #endif typedef uintptr_t FTI_ADDRVAL; /**< for ptr manipulation */ typedef void* FTI_ADDRPTR; /**< void ptr type */ //INCREMENTAL CHECKPOINTING FOR FTIFF int FTI_ProcessDBVar(FTIT_execution *FTI_Exec, FTIT_configuration *FTI_Conf, FTIFF_dbvar *currentdbvar, FTIT_dataset *FTI_Data, unsigned char *hashchk, int fd, char *fn, long *dcpSize, unsigned char **dptr); int FTI_InitDcp(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_dataset* FTI_Data); int FTI_FinalizeDcp( FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec ); int FTI_InitNextHashData(FTIT_DataDiffHash *hashes); int FTI_FreeDataDiff( FTIT_DataDiffHash *dhash); dcpBLK_t FTI_GetDiffBlockSize(); int FTI_GetDcpMode(); int FTI_ReallocateDataDiff( FTIT_DataDiffHash *dhash, long nbHashes); int FTI_InitBlockHashArray( FTIFF_dbvar* dbvar ); int FTI_CollapseBlockHashArray( FTIT_DataDiffHash* hashes, long chunkSize); int FTI_ExpandBlockHashArray( FTIT_DataDiffHash* dataHash, long chunkSize ); long FTI_CalcNumHashes( long chunkSize ); int FTI_HashCmp( long hashIdx, FTIFF_dbvar* dbvar, unsigned char *ptr ); int FTI_UpdateDcpChanges(FTIT_dataset* FTI_Data, FTIT_execution* FTI_Exec); int FTI_ReceiveDataChunk(unsigned char** buffer_addr, size_t* buffer_size, FTIFF_dbvar* dbvar, FTIT_dataset* FTI_Data, unsigned char *startAddr, size_t *totalBytes ); // INCREMENTAL CHECKPOINTING int FTI_WritePosixVar(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_InitPosixICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_FinalizePosixICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_WriteFtiffVar(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_InitFtiffICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_FinalizeFtiffICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_WriteMpiVar(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_InitMpiICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_FinalizeMpiICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_WriteSionlibVar(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_InitSionlibICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_FinalizeSionlibICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_WriteHdf5Var(int varID, FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_InitHdf5ICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data); int FTI_FinalizeHdf5ICP(FTIT_configuration* FTI_Conf, FTIT_execution* FTI_Exec, FTIT_topology* FTI_Topo, FTIT_checkpoint* FTI_Ckpt, FTIT_dataset* FTI_Data);
39608fd331517ce00c577b2af68bcd269f320fb3
[ "C", "Shell" ]
8
Shell
vibhatha/fti
599e8b7decc4374f9c6c297aec28a6867f341d96
635271d15c5a9aef5376444485e18e2954959633
refs/heads/master
<file_sep>package com.feng.user.controller; import com.feng.user.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.ReactiveRedisTemplate; import org.springframework.data.redis.core.ReactiveValueOperations; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/redis") public class RedisController { /** * 注入响应式的ReactiveRedisTemplate */ private final ReactiveRedisTemplate redisTemplate; @Autowired public RedisController(ReactiveRedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } /** * 测试用 * @author liufeng * @date 2019年3月15日 * @return str */ @GetMapping("/hello/{msg}") public Mono<String> hello(@PathVariable String msg) { return Mono.just("hello: "+msg); } /** * 添加数据 * @author liufeng * @date 2019年3月15日 * @return str */ @PostMapping("/add") public Mono<User> add(@RequestBody User user) { final ReactiveValueOperations valueOperations = redisTemplate.opsForValue(); return valueOperations.getAndSet("user:"+user.getId(), user); } /** * 添加数据 * @author liufeng * @date 2019年3月15日 * @return str */ @PostMapping("/addUser") public Mono<User> addUser(@RequestBody User user) { final ReactiveValueOperations valueOperations = redisTemplate.opsForValue(); return valueOperations.getAndSet(user.getId(), user); } @GetMapping(value = "/user/{id}") public Mono<User> findCityById(@PathVariable("id") Long id) { String key = "user:" + id; ReactiveValueOperations<String, User> operations = redisTemplate.opsForValue(); return operations.get(key); } /** * 多个操作 * @return */ @PostMapping("/putAll") public Flux putAll() { Mono a = redisTemplate.opsForValue().set("a","aaa1"); Mono b = redisTemplate.opsForValue().set("b","bbb1"); Mono c = redisTemplate.opsForValue().set("c","ccc1"); return Flux.just(a, c); } /** * 根据id获取 * @param id * @return */ @GetMapping("/getById/{id}") public Mono getById(@PathVariable String id) { return redisTemplate.opsForValue().get(id); } /** * 获取多个数据 * @return */ @GetMapping("/getAll") public Flux getAll() { return Flux.just("a", "b", "c") .flatMap(s -> redisTemplate.opsForValue().get(s)); } }<file_sep>package com.feng.user; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class UserApplication { public static void main(String[] args) { // 解决redis 和 es 使用不同的netty版本问题 System.setProperty("es.set.netty.runtime.available.processors", "false"); SpringApplication.run(UserApplication.class, args); } } <file_sep>package com.feng.user.controller; import com.feng.common.entity.PageParam; import com.feng.common.result.Result; import com.feng.user.entity.User; import com.feng.user.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping("/add") public Result add(@RequestBody User user) { return Result.newSuccessInstance(userService.save(user)); } @GetMapping("/{id}") public Result byId(@PathVariable Long id) { return Result.newSuccessInstance(userService.findOne(id)); } @DeleteMapping("/{id}") public Result deleteById(@PathVariable Long id) { userService.deleteById(id); return Result.newSuccessInstance(); } @GetMapping("/byName/{username}") public Result byName(@PathVariable String username) { return Result.newSuccessInstance(userService.findByUsername(username)); } @GetMapping("/byNamePage/{username}") public Result byNamePage(@PathVariable String username,@ModelAttribute PageParam pageParam) { return Result.newSuccessInstance(userService.findByUsername(username,pageParam)); } @GetMapping("/all") public Result all() { return Result.newSuccessInstance(userService.findAll()); } @GetMapping("/count") public Result count() { return Result.newSuccessInstance(userService.count()); } } <file_sep># spring-cloud-gateway spring-cloud-gateway spring cloud 学习 # 端口 1 register 8761 2 gateway 80 3 user 8081 4 order 8082 5 msg 8888 6 admin 8080 <file_sep>package com.feng.user.dao; import com.feng.user.entity.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; public interface UserRepository extends ElasticsearchRepository<User, Long> { List<User> findByUsername(String username); Page<User> findByUsername(String username, Pageable pageable); }
d43cf4b309c51d447fc155cf092826449202fbcf
[ "Markdown", "Java" ]
5
Java
realmadred/spring-cloud-gateway
5f02bc4325e4131b8d781ef55c8fa059f3c79104
730060222abf61647f5051f160f4548c8678c6cc
refs/heads/master
<file_sep># Windows-11-Nightblood-update Update for Windows 11 0.1.05.2019 CR.cs configuration for Google Chrome added optimizer added emulator <file_sep>public class Videomemory; private class Videomemory; class Videomemory; //Videomemory type processor //Videomemory type graphics processor //Videomemory optimized //Videomemory hight performance //Videomemory upgrading graphics //Videomemory upgrade monitor RGB //Videomemory HDR contrast monitor RGB //Videomemory optimized performance //Videomemory repaired performance //Videomemory fixed graphics //Videomemory fixed DirectX graphics //Videomemory fixed Vulkan graphics //Videomemory HDR bridthness monitor RGB //Videomemory HDR histogram alignment //Videomemory HDR histogram //Videomemory detached //Videomemory attached //Videomemory detached performance //Videomemory attached performance //Videomemory use low power consumption //Videomemory use low heat //Videomemory use component integration //Videomemory use low load //Videomemory use hight performance //Videomemory use auto detect //Videomemory use AMD auto detect //Videomemory use Nvidia auto detect namespace Videomemory; { public int 2; public void Videomemory() public protected Videomemory() private int 3; private void Videomemory() private protected Videomemory() public set Videomemory; public add Videomemory; public get Videomemory; private set Videomemory; private get Videomemory; private add Videomemory; } namespace matrix; { matrix.add matrix; matrix.add videomemory; matrix.get videomemory; matrix.set videomemory; matrix[1][7] = 1.7; matrix[2][0] = -2.0; matrix[9][2] = 9.2; matrix[2][3] = -2.3 } <file_sep>public class ethernetplus; private class ethernetplus; class ethernetplus; //Ethernet optimized //Ethernet speed optimized //Ethernet connection optimized //Ethernet ping optimized //Ethernet use low heat //Ethernet use low power consumption //Ethernet use component integration //Ethernet use low load //Ethernet use hight performance namespace ethernet; { void ethernet; public void ethernet; private void ethernet; public int 2; private int 1 public set ethernet; private set ethernet; public get ethernet; private get ethernet; public add ethernet; private add ethernet; } <file_sep>public class skynet; private class skynet; class skynet; //Skynet type Net //Skynet type Network //Skynet type spynet //Skynet disabled botnet //Skynet use low heat //Skynet use component integration //Skynet use low power consumption //Skynet type Internet //Skynet use speed 100gbit //Skynet use speed 100gb/s //Skynet use ping 0ms //Skynet use performance hight //Skynet use bandwidth 6Ghz //Skynet use antispy //Skynet use antibotnet //Skynet use antivirus //Skynet use antitrojan //Skynet use antimalware //Skynet use proffesional version //Skynet use hight connection //Skynet use fast connection //Skynet use hyper hight connection //Skynet use Wi-Fi integration //Skynet use Ethernet intergration //Skynet use GPU integration //Skynet use CPU integration //Skynet use RAM integration //Skynet use hight signal //Skynet use signal integration //Skynet use ping integration //Skynet use bandwidth integration //Skynet use speed integration //Skynet use connection integration //Skynet use safe electrowaves namespace skynet; { public void skynet; public int 2; public protected skynet; public get skynet; public set skynet; public add skynet; private void skynet; private int 3; private protected skynet; private get skynet; private set skynet; private add skynet; } namespace matrix; { matrix.add matrix; matrix.add skynet; matrix.get skynet; matrix.set skynet; matrix[1][6] = 1.6; matrix[1][2] = -1.2; matrix[2][3] = 2.3; matrix[3][4] = -3.4 } <file_sep>public class skygame; private class skygame; class skygame; //Skygame type application optimized //Skygame type application //Skygame use optimized application //SKygame use optimized applications //Skygame use hight performance for applications //Skygame use optimized performance for applications //Skygame use fixed lags //Skygame use fixed freeze //Skygame use disabled lags //Skygame use disabled freeze //Skygame use disabled lags for applications //Skygame use disabled freeze for applications { public void skygame; public int 2; public protected skygame; public get skygame; public set skygame; public add skygame; private void skygame; private int 3; private protected skygame; private get skygame; private set skygame; private add skygame; } namespace matrix; { matrix.add matrix; matrix.add skygame; matrix.get skygame; matrix.set skygame; matrix[1][2] = 1.2; matrix[2][3] = -2.3; matrix[3][4] = 3.4; matrix[4][5] = 4.5; } <file_sep>class ram; public class ram; private class ram; //RAM optimized //RAM boosted //RAM type DDR3 //RAM type DDR4 //RAM optimized performance //RAM repaired performance //RAM hight performance //RAM optimized framerate //RAM optimized //RAM type physical memory //RAM detached //RAM attached //RAM detached performance //RAM attached performance //RAM use low power consumption //RAM use low heat //RAM use component integration //RAM use low load //RAM use hight performance //RAM use auto detect namespace ram; { void ram() public void ram() private void ram() int 2; private int 3; public int 4; protected ram() public protected ram() private protected ram() public set ram; public get ram; public add ram; set ram; get ram; add ram; private set ram; private add ram; private get ram; } namespace matrix; { matrix.add matrix; matrix.set ram; matrix.get ram; matrix.add ram; matrix[1][7] = 1.7; matrix[3][4] = -3.4; matrix[7][5] = 7.5; matrix[4][6] = -4.6; } <file_sep>public class rhhdrled; private class rhdrled; class rhdrled; //rthled type LED //rthled type Display //rthled type Display Screen //rthled optimized performance //rthled optimized colors //rthled optimized rgb //rthled HDR rgb //rthled HDR contrast rgb //rthled HDR bridthness rgb //rthled HDR gamma rgb //rthled ray traced rgb //rthled ray traced colors rgb //rthled ray traced bridthness rgb //rthled ray traced contrast rgb //rthled ray traced gamma rgb //rthled hdr colors rgb namespace rthled; { public void rthled() private void rthled() public int 2; private int 3; public protected rthled; private protected rthled; public get rthled; private get rthled; public set rthled; private set rthled; public add rthled; private add rthled; } <file_sep>class AngelScript; class AngelScript; Megatonscript Action; try { } catch (System.Exception) { throw; } catch Windows_shell; AngelScript Windows_shell; Windows_shell optimized; Windows_shell boosted; Windows_shell retailed; Windows_shell debugged; Windows_shell boosted(2); Windows_shell hight_perfomance; Windows_shell Ultra_hight_performance; Windows_shell HDR; Windows_shell fixed_bugs; Windows_shell fixed_glitched throw static int Main(string[] args) { return 0; } simulate Windows_shell; Windows_shell optimized; Windows_shell boosted; Windows_shell debug_mode; Windows_shell Ultra_hight_performance; Windows_shell unchecked; { #Windowshell } Windows_shell space_fix; Windows_shell toolbar_fixed; Windows_shell magic_performance; Windows_shell updated; Windows_shell autowrite; Windows_shell Ai; Windows_shell powershell; Windows_shell defrad_fixed; public System.Collections.Generic.IEnumerator<Windows_shell> GetEnumerator() { throw new System.NotImplementedException(); yield return default(Windows_shell); } Windows object this[int index] { get { } set { } } assembly Windows_shell; Windows_shell Torpedo_mode; Windows_shell Alternate_lags; Windows_shell Alternate_freeze; Windows_shell fixed_lags; Windows_shell fixed_freeze; Windows_shell fixed_applications_performance; Windows_shell Fixed_applications_handler; Generic Windows; Generic power; Generic Skynet; Generic Windows_shell; Core Windows; { #Windows_core [Fact] public void Windows_core() { //Given //When //Then } } AngelScript performance; AngelScript boost; AngelScript simulation; Simulate Shell; Simulate Windows; Simulate code_sctructuer; Simulate code_generic; Generic Windows_shell; Generic skynet; Generic Windows; Generic Ator; simulate Shell; simulate Windows; Simulate code_sctructuer; simulate code_generic; internet logic; internet logic; perforlogic internet; perfologic internet; train Windows_core; train Windows_plugins; train Windows_shell; train Windows_core; train Windows_plugins; train Windows_shell; Main Windows_core; Central Windows_core; Main Windows_core; Cental Windows_core; simulate World; simulate Life; simulate Lifecycle; simulate World; simulate Life; simulate Lifecycle; class Windows_core; class Windows_core; simulate Windows_generation; simulate Windows_generation; endcode Windows; endcode Windows; public WindowsIterator Windows { get { return new WindowsIterator(this); } } public class WindowsIterator { readonly ClassName outer; internal WindowsIterator(ClassName outer) { this.outer = outer; } // TODO: provide an appropriate implementation here public int Length { get { return 1; } } public ElementType this[int index] { get { // // TODO: implement indexer here // // you have full access to ClassName privates // throw new System.NotImplementedException(); return default(ElementType); } } public System.Collections.Generic.IEnumerator<ElementType> GetEnumerator() { for (int i = 0; i < this.Length; i++) { yield return this[i]; } } } public System.Collections.Generic.IEnumerator<Windows_shell> GetEnumerator() { throw new System.NotImplementedException(); yield return default(Windows_shell); } int 2; int 2; int 3; int 3; annex Windows_shell; annex Windows_shell; simulate Mandel_effect; simulate Space_effect; simulate Mandel_effect; simulate Space_effect; space Windows_core; space Windows_shell; space Windows_core; space Windows_shell; Action Windows_core; Action Windows_core; beeline Windows_core; beeline Windows_core; object Windows_core; array 20; object Windows_core; array 20; Windows_shell optimized; Windows_shell Acted; Windows_shell performance_fixed; Windows_shell vectorical_fixed; Windows_shell optimized; Windows_shell acted; Windows_shell performance_fixed; Windows_shell vectorical_fixed; Windows_shell toolbar_improved; Windows_shell internet_improved; Windows_shell startmenu_improved; Windows_shell toolbar_improved; Windows_shell internet_improved; Windows_shell startmenu_improved; Windows_shell HD_icons; Windows_shell HD_startmenu_icons; Windows_SHELL HD_icons; Windows_shell HD_startmenu_icons; Windows_Shell Hight_definition_fonts; Windows_shell Hight_definition_fonts; Windows_shell hight_quality_fonts; WIndows_shell hight_quality_fonts; Windows_shell annexer; Windows_shell annexer; Windows_shell audio_3d_mode; Windows_shell audio_3d_mode; Windows_shell Hight_volumed_display; Windows_shell Hight_quality_display; Windows_shell Hight_definition_display; Windows_shell Hight_volumed_display; Windows_shell Hight_quality_display; Windows_shell Hight_definition_display; Windows_shell Display_bridth_fixed; Windows_shell Display_contrast_fixed; Windows_shell Display_bridth_fixed; Windows_shell Display_contrast_fixed; Windows_shell Display_fade_fixed; Windows_shell Display_fade_fixed; Windows_shell Hight_definition_font; Windows_shell Hight_quality_font; Windows_shell Hight_volumed_font; Windows_shell Hight_definition_font; Windows_shell Hight_quality_font; Windows_shell Hight_volumed_font; annex BAN; annex BAX; annex BAN; annex BAX; using Display.Depth; using Display.Depth; Windows_shell depixelated_display; Windows_shell depixelated_display; Windows_shell volumed_display_pixels; Windows_shell volumed_display_pixels; Windows_shell hight_definition_display_gamma; Windows_shell hight_quality_display_gamma; Windows_shell Hight_volumed_display_gamma; Windows_shell hight_definition_display_gamma; Windows_shell hight_quality_display_gamma; Windows_shell Hight_volumed_display_gamma; Artex Joy; Artex Joy; Apex Windows_shell; Apex Windows_shell; Windows_shell Internet_fixed; Windows_shell Internet_speed_fixed; Windows_shell Internet_ping_fixed; Windows_shell Internet_connection_fixed; Windows_shell Internet_fixed; Windows_shell Internet_speed_fixed; Windows_shell Internet_ping_fixed; Windows_shell Internet_connection_fixed; <file_sep>public class optimizer; private class optimizer; class optimizer; //Windows NT 10.0 optimized //Windows NT 10.0 use registry optimized //Windows NT 10.0 use shell optimized //Windows NT 10.0 use core optimized //Windows NT 10.0 use services optimized //Windows NT 10.0 use toolbar optimized //Windows NT 10.0 use explorer optimized //Windows NT 10.0 use system applications optimized //Windows NT 10.0 use system dll optimized //Windows NT 10.0 use system optimized //Windows NT 10.0 use bios optimized //Windows NT 10.0 use desktop optimized //Windows NT 10.0 use DPI optimized //Windows NT 10.0 use screen resolution optimized //Windows NT 10.0 use DirectX 12.x optimized //Windows NT 10.0 use DirectX 11.x optimized //Windows NT 10.0 use DirectX 10.x optimized //Windows NT 10.0 use DirectX 9.x optimized //Windows NT 10.0 use Direct3D 12.x optimized //Windows NT 10.0 use Direct3D 11.x optimized //Windows NT 10.0 use Direct3D 10.x optimized //Windows NT 10.0 use Direct3D 9.x optimized //Windows NT 10.0 use Google Chrome optimized //Windows NT 10.0 use Opera optimized //Windows NT 10.0 use Microsoft Edge optimized namespace optimizer; { public void optimizer; private void optimizer; public int 2; private int 1; public protected optimizer; private protected optimizer; public get optimizer; private get optimizer; public add optimizer; private add optimizer; public set optimizer; private set optimizer; } namespace matrix; { matrix.add matrix; matrix.add optimizer; matrix.get optimizer; matrix.set optimizer; matrix[1][7] = 1.7; matrix[2][2] = -2.2; matrix[3][3] = 3.3; matrix[5][6] = -5.6 } <file_sep>class AngelScript; cli using; cli debug; namespace CLI; { CLI; } [Fact] public void o21() { //Given //When //Then } propertyName CPU; { propertyAdd CPU; andname CPU; } propertyName CPU; { add.block CPU; } windows.core actor; AngelScript actor; AngelScript Windows_core; cli using; AngelScript performance; AngelScript Windows_core; AngelScript ultra_hight_performance; Given A; fixed_error Windows_core; fixed_error performance; fixed_error colorize; fixed_error GPU; fixed_error core; using System.Core; using System.Windows; using Afterhope.System; sign Windows_core; sign Windows; sing Windows_system; { //Windows Core //Windows 10 core } using Windows.Core; using Windows.Fixer; using Windows.AI; fixed_error bugs; fixed_error glitches; fixed_error toolbar; fixed_error performance; fixed_error Windows_core; fixed_error crash; andhendler buog; endhandler debug; endhandler Windows_core; endhandler detected; detected Windows_core; detected Windows_core_x; simulate Windows_core; simulate Performance; simulate VoiceActor; simulate NoiseActor; simulate HDR; simulate RayTracing; simulate alternate_ray_tracing; simulate performance(0); simulate performance(1); simulate performance(2); simulate performance(3); simulate performance(4); simulate performance(5); simulate performance(6); databal rpug; dabsjf ei onetwothree script; #endregion onetwothree Script; struct Script { } simulate Windows_core; public System.Collections.Generic.IEnumerator<Windows_core> GetEnumerator() { throw new System.NotImplementedException(); yield return default(Windows_core); } interface IWindowscore { } public WindowscoreIterator Windowscore { get { return new WindowscoreIterator(this); } } public class WindowscoreIterator { readonly ClassName outer; internal WindowscoreIterator(ClassName outer) { this.outer = out er; } // TODO: provide an appropriate implementation here public int Length { get { return 1; } } public ElementType this[int index] { get { // // TODO: implement indexer here // // you have full access to ClassName privates // throw new System.NotImplementedException(); return default(ElementType); } } public System.Collections.Generic.IEnumerator<ElementType> GetEnumerator() { for (int i = 0; i < this.Length; i++) { yield return this[i]; } } } simulate Windows_core; public Windows_coreIterator Windows_core { get { return new Windows_coreIterator(this); } } public class Windows_coreIterator { readonly ClassName outer; internal Windows_coreIterator(ClassName outer) { this.outer = outer; } // TODO: provide an appropriate implementation here public int Length { get { return 1; } } public ElementType this[int index] { get { // // TODO: implement indexer here // // you have full access to ClassName privates // throw new System.NotImplementedException(); return default(ElementType); } } public System.Collections.Generic.IEnumerator<ElementType> GetEnumerator() { for (int i = 0; i < this.Length; i++) { yield return this[i]; } } } internal Windows; internal ghp; internal Windows_core; better Windows_core; better Windows_one_core; better Windows_debugger; afterscript Windows_core; Begin color; begin Windows_core; begin S; begic ABC; Action Windows_core; Macros Windows_core; Balanced Windows_core; AngelScript Windows_core; { #WindowsCore } AngelScript Windows; { #windows #delat } destruct Windows_core; { deloid Windows_core; end game; default Windows_core; den Windows_core; begic Windows_core; system.handler activated; system.voiceator activated; windows_core activated; windows_begin activated; } geomfx directx; geomfx vulkanapi; geomfx usi; geomfx windows_core; Windows_core started; Windows_core infinite_lifecycle; Windows_core fixed_bugs; Windows_core fixed_errors; Windows_core fixed_glitches; Windows_core fixed_performance; Windows_core unsign; Windows_core sign; Windows_core fixed_register_frame; Windows_core fixed_core; <file_sep>string Filename = @"GPU.cs" public class gpu; class gpu; { //Windows type os //Windows GPU optimized //Windows GPU repaired performance //Windows GPU repaired optimization //Windows GPU repaired load } <file_sep>public class cr; private class cr; class cr; //Google Chrome auto detected version //Google Chrome auto detected yer version //Google Chrome auto detected directory //Google Chrome fixed performance //Google Chrome use low heat //Google Chrome use optimized performance //Google Chrome optimized //Google Chrome use optimized tabs //Google Chrome use optimized clicks //Google Chrome use optimized settings //Google Chrome use optimized sites //Google Chrome use optimized web //Google Chrome use optimized configuration //Google Chrome use optimized flash player //Google Chrome use optimized webgl //Google Chrome use optimized extensions //Google Chrome use optimized api //Google Chrome use disabled lags //Google Chrome use disabled freeze namespace cr; { public void cr; public int 2; public protected cr; public get cr; public set cr; public add cr; private void cr; private int 1; private protected cr; private get cr; private set cr; private add cr; } namespace matrix; { matrix.add matrix; matrix.add chrome; matrix.set chrome; matrix.get chrome; matrix[0][1] = 0.1; matrix[1][2] = -1.2; matrix[2][3] = 2.3; matrix[3][4] = -3.4; } <file_sep>class windowsxi; public class windowsxi; private class windowsxi; //Windows 11 type os //Windows 11 type windows 10 //Windows 11 type windows operating system //Windows 11 optimized //Windows 11 optimized core //Windows 11 optimized shell //Windows 11 optimized CPU cores //Windows 11 optimized GPU cores //Windows 11 optimized subsurface //Windows 11 optimized desktop //Windows 11 optimized applications //Windows 11 optimized standalone applications //Windows 11 optimized CPU //Windows 11 optimized GPU //Windows 11 optimized RAM //Windows 11 optimized Wi-Fi //Windows 11 optimized Ethernet //Windows 11 boosted //Windows 11 Wi-Fi speed traced //Windows 11 Wi-Fi ping traced //Windows 11 Wi-Fi connection traced //Windows 11 Wi-Fi signal traced //Windows 11 Ethernet speed traced //Windows 11 Ethernet ping traced //Windows 11 Ethernet connection traced //Windows 11 Wi-Fi signal hight //Windows 11 Wi-Fi signal ultra //Windows 11 performance optimized //Windows 11 services optimized //Windows 11 start menu registry optimized //Windows 11 Wi-Fi registry optimized //Windows 11 Ethernet registry optimized //Windows 11 core registry optimized //Windows 11 shell registry optimized //Windows 11 Google Chrome registry optimized //Windows 11 Google Chrome optimized //Windows 11 applications registry optimized //Windows 11 bios registry optimized //Windows 11 drivers registry optimized //Windows 11 display driver registry optimized //Windows 11 boot registry optimized //Windows 11 reboot registery optimized //Windows 11 Turn Off registery optimized namespace windowsxi; { void windowsxi() void optimization() void windows11() void core() void shell() public void windowsxi() private void windowsxi() int 1; public int 2; private int 3; protected windowsxi() public protected windowsxi() private protected windowsxi() object array 20; public object array 21; private object array 22; float 1; public float 2; private float 3; bool 0; public bool 2; private bool 3; sbyte 59; public sbyte 58; private sbyte 53; byte 2048; public byte 4096; private byte 8192; object get 0x2; object get 0x3; object get 0x1; public object get 0x4; private object get 0x6 double 2; public double 3; private double 4; params windowsxi; public params windowsxi; private params windowsxi; value 2; public value 1; private value 0; abstract windowsxi; public abstract windowsxi; private abstract windowsxi; sealed windowsxi; public sealed windowsxi; private sealed windowsxi; async windows11; public async windows11; private async windowsxi; base windows11; public base windows11; private base windows11; break windows11; public break windows11; private break windows11; static windows11; public static windows11; private static windows11; while windows11; public while windows11; private while windows11; await windows11; public await windows11; private await windows11; var windowsxi; public var windowsxi; private var windowsxi; virtual windowsxi; public virtual windowsxi; private virtual windowsxi; struct windows11; public struct windows11; private struct windows11; operator windows11; public operator windows11; private operator windows11; this windows11; public this windows11; private this windows11; true windows11; private true windows11; public true windows11; false windows11; private false windows11; public false windows11; stackalloc windows11; private stackalloc windows11; public stackalloc windows11; public set windows11; public get windows11; public add windows11; private set windows11; private get windows11; private add windows11; } <file_sep>string Filename = @"CPU.cs" public class cpu; class cpu; { //Windows type os //Windows CPU optimized //Windows CPU repaired performance //Windows CPU repaired optimization //Windows CPU repaired load } <file_sep>public class rthled; private class rthled; class rthled; //RTHLED type LED //RTHLED type Display //RTHLED HDR histogram alignment //RTHLED HDR histogram //RTHLED Ray Traced histogram //RTHLED Ray Traced histogram alignment //RTHLED Ray Traced contrast //RTHLED Ray Traced bridthness namespace rthled; { void rthled; public void rthled; private void rthled; public int 2; int 3; private int 5; public protected rthled; private protected rthled; protected rthled; set rthled; public set rthled; private set rthled; public get rthled; get rthled; private get rthled; public add rthled; private add rthled; add rthled; } <file_sep>class AngelScript; static int Main(string[] args) { simulate AngelScript; return 0; } simulate ZPU; fixed.error CPU; fixed.error Central_processor; virtual simulate ZPU; simulator zero_processor; simulate zero_processor; simulate zero_processor(1); simualte zero_processor(2); simulate zero_processor(3); active ZPU(0); active ZPU(1); active zpu(2); active AngelScript; //ZPU virtual CPU //ZPU type processor //ZPU type Zero processor //ZPU type Graphics processor namespace ZPU; { public void ZPU(0); public public ZPU { get; set; } public region ZPU(0); } simulate zero_processor(0); simulate zero_processor(1); simulate zero_processor(2); simulate zero_processor(3); simulate ray_tracing(0); simulate ray_tracing(1); simulate ray_tracing(2); simulate ray_tracing(3); simulate GPU; simulate GPU(1); simulate GPU(0); simulate GPU(2); simulate performance; simulate performance(0); simulate performance(1); simulate performance(2); simulate performance(3); engine performance; engine zpu; engine cpu; engine gpu; engine public ZPU et { return new ZPU (this); } } public class ZPU { readonly ClassName outer; internal ZPU (ClassName outer) { this.outer = outer; } engine GPU2; engine ZPU(0); engine public ZPU0Iterator ZPU0 { get { return new ZPU0Iterator(this); } } public class ZPU0Iterator { readonly ClassName outer; internal ZPU0Iterator(ClassName outer) { this.outer = outer; } // TODO: provide an appropriate implementation here public int Length { get { return 1; } } public ElementType this[int index] { get { // // TODO: implement indexer here // // you have full access to ClassName privates // throw new System.NotImplementedException(); return default(ElementType); } } public System.Collections.Generic.IEnumerator<ElementType> GetEnumerator() { for (int i = 0; i < this.Length; i++) { yield return this[i]; } } } engine get_index(0); public System.Collections.Generic.IEnumerator<Get_index> GetEnumerator() { throw new System.NotImplementedException(); yield return default(Get_index); } get enginegl; get gpu; get cpu; get zpu; find zpu; find zpu(0); find zpu(1); find zpu(2); find zpu(3); active AngelScript; get AngelScript; IEnumerator AngelScript; simulate hight_Performance; simulate virtual_physics; simulate virtual_graphics; deusing System.IO deusing System.IO1 deusing core ClassName(Parameters) { public public System.Collections.Generic.IEnumerator<ZPU> GetEnumerator() { throw new System.NotImplementedException(); yield return default(ZPU); } } public using System.Rax public using System.engine annex ZPU; annex ZPU(0); annex ZPU(1); annex ZPU(2); annex System.Cryengine annex System.Validation annex System.processor annex System.Operator annex System.Orbital simulate DirectX_9_0; simulate DirectX_10_0; simulate DirectX_11_0; simulate DirectX_12_0; simulate DirectX_12_1; create DirectX_13_0; annex DirectX_13_0; active DirectX_13_0; annex DirectX.Validation annex DirectX.ray_tracing using Old.Techelogy using New.Techelogy using New.performance virtual graphics_card; virtual graphics_processor; virtual zero_processor; virtual Central_processor; using Graphics.Card using System.ABC fixed_error Validation; fixed_error load; fixed_error performance; fixed_error lags; fixed_error freeze; fixed_error bugs; fixed_error glitches; annex debug; annex dump; annex ray_tracing; annex performance; annex HDR; simulate HDR; active HDR; active ray_tracing; fixed_error internet_connection; fixed_error internet_speed; fixed_error internet_ping; fixed_error rostelecom_provider; fixed_error paynet; simulate internet; simulate life; simulate lifecycle; simulate peformance_halfbrick; simulate performance_enginegl; simulate vulkan_api; post_engine directx; post_engine ZPU; virtual messager; virtual validation; virtual anticritical; simulate bios; simulate anticritical; simulate fixer; simulate fixed_zpu; simulate fixator; IEnumerator ZPU; public System.Collections.Generic.IEnumerator<Engine> GetEnumerator() { throw new System.NotImplementedException(); yield return default(Engine); } simulate Wifi; simulate Ethernet; simulate ultra_hight_performance; simulate ZPU; simulate bios; simulate american_megatrends; fixed_error ZPU; fixed_error Validation; fixed_error american_megatrends; fixed_error performance; public System.Collections.Generic.IEnumerator<PastTracing> GetEnumerator() { throw new System.NotImplementedException(); yield return default(PastTracing); } cental orbital_script; cental angel_script; cental AngelScript; { oldGEN AngelScript; NewGen AngelScript; } { _newgen Geforce_videocard; _newgen ZPU; _newgen graphics; _newgen physics; } default csharp; { afterhope ZPU; before ZPU; after ZPU; actor ZPU; simulate physics; simulate graphics; simulate inversed_cinematics; simulate animations; } simulate KKK; get 0x99999999; megadump ZPU; ultradump ZPU; using System.Script using System.Xml deform Form; uniform Script; debug Console; debug ZPU; console.debug ZPU; console.Write ZPU; end ZPU; end GPU; end CPU; end ND; <file_sep>class AngelScript; class AngelScript; namespace GoogleChrome; { } namespace GoogleChrome; { } class GoogleChrome; class GoogleChrome; //Google Chrome optimized //Google Chrome type application //Google Chrome hight performance //Google Chrome performance fixed //Google Chrome performance optimized //Google Chrome optimized //Google Chrome type application //Google Chrome hight performance //Google Chrome performanced fixed //Google Chrome performanced optimized using Google.Chrome; using Google.Chrome; try { } catch (System.Exception) { throw; } simulate Google_chrome; simulate performance; simulate debug; simulate Google_chrome; simulate performance; simulate debug; simulate ajax; simulate ajax; simulate speed; simulate ping; simulate speed; simulate ping; Google_chrome freeze_fixed; Google_chrome lags_fixed; Google_chrome freeze_fixed; Google_chrome lags_fixed; Google_chrome lifecycle_ram; Google_chrome lifecycle_cpu; Google_chrome lifecycle_gpu; Google_chrome lifecycle_ram; Google_chrome lifecycle_cpu; Google_chrome lifecycle_gpu; #include "chrome.exe" #include "chrome.exe" Google_chrome timespeed_improved; Google_chrome timespeed_improved; Google_chrome fixed_falling_download_speed; Google_chrome fixed_falling_download_speed; Google_chrome fixed_down_download_speed; Google_chrome fixed_down_download_speed; Google_chrome fixed_falling_upload_speed; Google_chrome fixed_falling_download_speed; Google_chrome fixed_down_upload_speed; Google_chrome fixed_down_upload_speed; Google_chrome fixed_down_speed; Google_chrome fixed_down_speed; Google_chrome fixed_down_performance; Google_chrome fixed_down_performance; Google_chrome fixed_down_loading_speed; Google_chrome fixed_down_loading_speed; Google_chrome fixed_down_connection; Google_chrome fixed_down_connection; Google_chrome fixed_down_framerate; Google_chrome fixed_down_framerate; Google_chrome fixed_down_performance_cpu; Google_chrome fixed_down_performance_cpu; Google_chrome fixed_down_performance_ram; Google_chrome fixed_down_performance_ram; Google_chrome fixed_down_performance_gpu; Google_chrome fixed_down_performance_gpu; <file_sep>public class Videocard; private class Videocard; class Videocard; //Videocard type processor //Videocard type graphics processor //Videocard optimized //Videocard hight performance //Videocard upgrading graphics //Videocard upgrade monitor RGB //Videocard HDR contrast monitor RGB //Videocard optimized performance //Videocard repaired performance //Videocard fixed graphics //Videocard fixed DirectX graphics //Videocard fixed Vulkan graphics //Videocard HDR bridthness monitor RGB //Videocard HDR histogram alignment //Videocard HDR histogram //Videocard detached //Videocard attached //Videocard detached performance //Videocard attached performance //Videocard use low power consumption //Videocard use low heat //Videocard use component integration //Videocard use low load //Videocard use hight performance //Videocard use auto detect //Videocard use AMD auto detect //Videocard use Nvidia auto detect namespace Videocard; { public int 2; public void Videocard() public protected Videocard() private int 3; private void Videocard() private protected Videocard() public set Videocard; public add Videocard; public get Videocard; private set Videocard; private get Videocard; private add Videocard; } namespace matrix; { matrix.add matrix; matrix.get matrix; matrix.set matrix; matrix.add matrix; matrix[1][7] = 1.7; matrix[2][4] = -2.4; matrix[3][4] = 3.4; matrix[3][2] = -3.2; } <file_sep>public class font; private class font; class font; //Windows NT 10.0 fonts optimized //Windows NT 10.0 fonts quality 100% //Windows NT 11.0 fonts optimized //Windows NT 11.0 fonts quality 100% //Windows NT 11.0 fonts definition 100% //Windows NT 10.0 fonts definition 100% //Windows NT 10.0 fonts detached //Windows NT 10.0 fonts attached //Windows NT 11.0 fonts detached //Windows NT 11.0 fonts attached namespace fonts; { public void fonts; private void fonts; public int 2; private int 3; public protected fonts; private protected fonts; public add fonts; private add fonts; public get fonts; private get fonts; public set fonts; private set fonts; } <file_sep>private class cpu; public class cpu; class cpu; //CPU optimized //CPU cores optimized //CPU load optimized //CPU performance optimized //CPU repaired performance //CPU detached //CPU attached //CPU detached performance //CPU attached performance //CPU use low power consumption //CPU use low heat //CPU use component integration //CPU use low load //CPU use hight performance //CPU use auto detected namespace cpu; { void cpu() void cores() void load() void performance() private void cpu() public void cpu() int 3; private int 2; public int 1; protected cpu; private protected cpu; public protected cpu; byte 3; private byte 2; public byte 1; sbyte 3; private sbyte 2; public sbyte 3; default cpu; private default cpu; public default cpu; virtual cpu; private default cpu; public default cpu; public set cpu; public get cpu; public add cpu; private set cpu; private get cpu; private add cpu; } namespace matrix; { matrix.add matrix; matrix.add cpu; matrix.set cpu; matrix.get cpu; matrix[1][7] = 1.7; matrix[2][4] = 2.4; matrix[1][4] = -1.4; matrix[9][4] = 9.4; } <file_sep>public class gpu; private class gpu; class gpu; //GPU type processor //GPU type graphics processor //GPU optimized //GPU hight performance //GPU upgrading graphics //GPU upgrade monitor RGB //GPU HDR contrast monitor RGB //GPU optimized performance //GPU repaired performance //GPU fixed graphics //GPU fixed DirectX graphics //GPU fixed Vulkan graphics //GPU HDR bridthness monitor RGB //GPU HDR histogram alignment //GPU HDR histogram //GPU detached //GPU attached //GPU detached performance //GPU attached performance //GPU use low power consumption //GPU use low heat //GPU use component integration //GPU use low load //GPU use hight performance //GPU use auto detect namespace gpu; { public int 2; public void gpu() public protected gpu() private int 3; private void gpu() private protected gpu() public set gpu; public add gpu; public get gpu; private set gpu; private get gpu; private add gpu; } namespace matrix; { matrix.add matrix; matrix.add gpu; matrix.set gpu; matrix.get gpu; matrix[1][7] = 1.7; matrix[3][2] = -3.2; matrix[7][2] = 7.2; matrix[10][5] = 10.5; }
d6b6341e8160e96ea6320d9552dfbd7aab1296da
[ "Markdown", "C#" ]
21
Markdown
andraynada2002/Windows-11-Nightblood-update
3d6a43e21148a4f15381f56325eb2a45843a88ac
6c25efa35bd21f5b93ed9d5e94b6d52743a75724
refs/heads/master
<repo_name>shreyak28/helloworld<file_sep>/helloworld/helloworldapp/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def hello (request): return HttpResponse("hello welcome to the world of django framework")
a9179d7de8f88336ffc64c76e92f7db88a06750e
[ "Python" ]
1
Python
shreyak28/helloworld
0e96842234fa0b5551cbff82b2f9cecf23f9dd09
311bd7979ec390d7685359134c7a1a94bb5d5ad1
refs/heads/master
<file_sep>package base58 import ( "encoding/hex" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestBase58(t *testing.T) { rawHash := "00010966776006953D5567439E5E39F86A0D273BEED61967F6" hash, err := hex.DecodeString(rawHash) assert.Nil(t, err) encoded := Encode(hash) assert.Equal(t, "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", string(encoded)) assert.Equal(t, "16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM", EncodeToString(hash)) decoded := DecodeFromString("16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM") assert.Equal(t, strings.ToLower("00010966776006953D5567439E5E39F86A0D273BEED61967F6"), hex.EncodeToString(decoded)) } <file_sep># base58 Minimal, simplistic base58 encoder and decoder
8b562aa8d192f776b07b7fee59e5f18a27517a48
[ "Markdown", "Go" ]
2
Go
euforia/base58
7cb6301e9f7aa1ada59a077412e1f8dd91f23409
e585e169dd56a79348b3d3e8f8d6e3920bf84a45
refs/heads/master
<repo_name>Timurovic/AutoPartsServer<file_sep>/src/main/java/com/mobapplic/autoparts/server/controller/ChatController.java package com.mobapplic.autoparts.server.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/chat") public class ChatController { @RequestMapping(value = "/get", method = RequestMethod.GET) public String getChat() { return "message"; } } <file_sep>/README.md # AutoPartsServer Server Rest API for AutoParts apps
f0bfc9a13ff1f8cff44f1bf593a6c62f4c3b7821
[ "Markdown", "Java" ]
2
Java
Timurovic/AutoPartsServer
bca90560dbe979b9c6b309c78275c844f3054660
de6ffd9f7e5a400d140b6ced3b10f799099f4bbd
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> //-----------------------------------------------------------------------------------------------// //TP 2 Systeme d'exploitation : Minishell pour la gestion des fichiers et repertoire //---------------------------------les structeur de donnees--------------------------------------// typedef struct tm TEMPS; typedef struct inode{ /* Structure utilisee pour representer un inode*/ char type;//d ou f char mode[10]; int UID; int GID; unsigned int taille; char timeCreation[40]; char timeAcces[40]; char timeModification[40]; int premiersBlocs[10]; int inSimple;//stocke l'indice de blocDisque correspondant à indirection simple int inDouble;//stocke l'indice de blocDisque correspondant à un blocDisque de type //inSimpleindirection simple qui a dans chaque champs indice d'un blocDisque //de type inSimple }INODE; typedef struct ligneBloc{ /* Structure utilisee pour representer une ligne bloc, avec un nom de fichier et un numero d'inode*/ char nom[129]; int noInode ; }LIGNEBLOC; struct ligneBloc blocRep[15]; typedef union blocDisque{ struct inode i; struct ligneBloc blocRep[15]; int inSIMPLE[512]; int inDOUBLE[512]; char alignement[2048];//just pour fixer la taille d'un bloque à 2k }BLOCDISQUE; enum listeCMD {/*liste de commandes*/ CMD_MKDIR, CMD_RMDIR, CMD_CD, CMD_LS, CMD_CRF, CMD_CP, CMD_RM, CMD_MV, CMD_BLC, CMD_LOGOUT, CMD_NULLE, CMD_INVALIDE }; enum optCMD {/*liste d'options possible pour les commandes*/ OPT_OBL, OPT_OPT, OPT_NON, PAR_NON, PAR_INT }; struct syntaxeCmd {/*structure general d'un syntax*/ char * nom; enum listeCMD noCmd; char option; enum optCMD inode1; enum optCMD inode2; enum optCMD param; }; struct inodePNomE{/* pour stocker le path*/ char *nom; int inodeP; int inodeE; }; struct Cmd {/* structure general d'une commande*/ enum listeCMD noCmd; char option; struct inodePNomE path1; struct inodePNomE path2; int param; }; struct syntaxeCmd listeCmd[] = { // -----------------structure de commades--------------// {"mkdir", CMD_MKDIR, ' ', OPT_OBL, OPT_NON, PAR_NON }, {"rmdir", CMD_RMDIR, ' ', OPT_OBL, OPT_NON, PAR_NON }, {"cd", CMD_CD, ' ', OPT_OPT, OPT_NON, PAR_NON }, {"ls", CMD_LS, 'l', OPT_OPT, OPT_NON, PAR_NON }, {"crf", CMD_CRF, ' ', OPT_OBL, OPT_NON, PAR_INT }, {"cp", CMD_CP, ' ', OPT_OBL, OPT_OBL, PAR_NON }, {"mv", CMD_MV, ' ', OPT_OBL, OPT_OBL, PAR_NON }, {"rm", CMD_RM, ' ', OPT_OBL, OPT_NON, PAR_NON }, {"blc", CMD_BLC, ' ', OPT_OBL, OPT_NON, PAR_NON }, {"logout", CMD_LOGOUT, ' ', OPT_NON, OPT_NON, PAR_NON }, {"", CMD_NULLE, ' ', OPT_NON, OPT_NON, PAR_NON } }; const int NB_CMD = sizeof(listeCmd)/sizeof(struct syntaxeCmd);//Bruno //---------------------------LIMITS------------------------// /* nbMax de fichiers et reps = 103 */ /* Si il y a un reperoire avec un nom et on veut cree un fichier avec meme nom dans meme parent * il l'accept pas */ //-----------------------------------------------------------------------------------------------// //-------------------declaration des prototypes des fonction a utiliser--------------------------// #define NB_MAX_BLOC 52224 /* Constante pour le nombre de blocs de donnees maximum qu'on peut creer */ #define NB_MAX_INODE 9216 /* Nombre maximum de Inodes que on peut avoir */ #define NB_MAX_BLC 1920 /* Nombre maximum de BLOCDISQUE de taille 2k que on peut avoir */ int initializer(); int cmd_cd(struct Cmd *cmd); int cmd_rmDir(struct Cmd *cmd); void removeDir(int inode, int inodeP); int cmd_crf(struct Cmd *cmd); int cmd_Cp_Mv_Rm (struct Cmd *cmd); int cmd_rm(int inode); int cmd_blc(struct Cmd *cmd); int cmd_ls(struct Cmd *cmd); int cmd_mkdir(struct Cmd *cmd); int updateParent(int noInodeP, int inodeCourant, char nom[129], int inode , int checkUpdate); int returnInodeParent(int noInode); int retournNoInode(char *nom, int inodeP); int updateInode(int inodeDest, int inodeSource, int identifierInode); void recupererSousChaine(char * ptrBuffer, char * delimiteur, char ** tabSousChaine); struct inodePNomE validerPath(char *chaine); int nbElement(char ** tabSousChaine); int premierInodeLibre(); int allouerBlocLibres(); int allouerSpace(int nbBlocs, INODE *iInode); void libererSpace(int nbBlocs, INODE *iInode); void liberer(int b); void recupererTemps(char * timeString, int taille); int validerCmd(char *ligneCmd, struct Cmd * cmd, char **tabSousChaine); int afficherPrompt(); void initPremierBloc(int *tab) ; int avoirEnfant(INODE *iInode); int validerNom(char *nomDonne); //-----------------------------------------------------------------------------------------------// //--------------------------------------Les variables globals------------------------------------// union blocDisque * tableauBloc = NULL;// espce alooue dynamiquement pour les bolcs int nbBlocsAllouers = 0; int tabInode[NB_MAX_INODE] ;//tableu d'inodes contien les numeros de blocs unsigned int *blocLibres = NULL; //tableu blocLibre int repCourant = 0;//noInode courant initializé à zero pour la Racine const char sRep = '#'; const char * modeDir = "rwxr-xr-x"; //mode access pour un repertoir par defut const char * modeFic = "rw-r--r--"; //mode access pour un fichier par defut //-----------------------------------------------------------------------------------------------// //-----------------------------------------MAIN--------------------------------------------------// int main(int argc, char** argv){ char buffer[2000]; char * ptrBuffer; char * tabSousChaine[100] ;//pour stocker la chaine de commande entree par utilisateur struct Cmd cmd; size_t nbreBytes = 1000; int valeur = 0; pid_t pid; ptrBuffer = buffer; pid = fork(); if(pid < 0){ printf("Echec fork"); }else if(pid == 0){ execlp("clear", "clear", NULL); }else{ wait(NULL); initializer();// initializer la Racine do { afficherPrompt(); valeur = getline(&ptrBuffer, &nbreBytes, stdin); validerCmd(ptrBuffer, &cmd, tabSousChaine); switch (cmd.noCmd) { case CMD_MKDIR: cmd_mkdir(&cmd); break; case CMD_RMDIR: cmd_rmDir(&cmd); break; case CMD_CD: if(tabSousChaine[1]==NULL){ cmd.path1.inodeE = 0; cmd.path1.inodeP = 0; } cmd_cd(&cmd); break; case CMD_LS: if(tabSousChaine[1]!=NULL){ if(cmd.option!=' '){//si il y une option if(tabSousChaine[2]!=NULL){//si il y a une chemin donnée if(cmd.path1.inodeE==-1 || cmd.path1.inodeP==-1){// fprintf(stderr,"erreur: path inexistant\n"); break; } }else{ cmd.path1.inodeE = repCourant;//si il n'y a pas une chemin donnée } }else if(cmd.path1.inodeE==-1 || cmd.path1.inodeP==-1){ fprintf(stderr,"erreur: path inexistant\n"); break; } }else{ cmd.path1.inodeE = repCourant; } cmd_ls(&cmd); break; case CMD_CRF: cmd_crf(&cmd); break; case CMD_CP: cmd_Cp_Mv_Rm(&cmd); break; case CMD_RM: cmd_Cp_Mv_Rm(&cmd); break; case CMD_MV: cmd_Cp_Mv_Rm(&cmd); break; case CMD_BLC: cmd_blc(&cmd); break; case CMD_LOGOUT: printf("\n**************************Fin normale du programme**************************\n\n\n\n"); break; case CMD_NULLE: break; case CMD_INVALIDE: printf("commande invalide\n"); break; default: printf("Bug\n"); } }while(cmd.noCmd != CMD_LOGOUT); } return 0; } //les fonctions:--------------------------------------------------------// int validerCmd(char *ligneCmd, struct Cmd * cmd, char **tabSousChaine) {//Bruno /* Elle valide la commande donne et trouve inodes de path source et destination */ recupererSousChaine(ligneCmd," \n", tabSousChaine); int noArg=0; int nbArg = nbElement(tabSousChaine); int i; cmd->noCmd = CMD_NULLE; cmd->option = ' '; cmd->path1.inodeE = -1;/**/ cmd->path1.inodeP = -1;/**/ cmd->path2.inodeE = -1;/**/ cmd->path2.inodeP = -1;/**/ cmd->param = 0; if (nbArg == 0 ) return 0; for(i=0; i<NB_CMD; i++){ if(strcmp(tabSousChaine[noArg], listeCmd[i].nom)==0){ cmd->noCmd = listeCmd[i].noCmd; noArg++; if(listeCmd[i].option!=' ' && noArg < nbArg){// option optionelle /*ls if(tabSousChaine[noArg][0]=='-'){ if(strlen(tabSousChaine[noArg]) >1 && tabSousChaine[noArg][1]==listeCmd[i].option){ cmd->option = listeCmd[i].option; noArg++; }else { break; } } } if(listeCmd[i].inode1==OPT_OBL){// path 1 obligatoir/*mkdir rmdir rm cp mv blc crf if (noArg < nbArg) { cmd->path1 = validerPath(tabSousChaine[noArg]); noArg++; }else { break; } }else if(listeCmd[i].inode1==OPT_OPT && noArg < nbArg) {// path 1 optionelle/*ls cd cmd->path1 = validerPath(tabSousChaine[noArg]);/**/ noArg++; } if(listeCmd[i].inode2==OPT_OBL){// path 2 obligatoir/*cp mv if (noArg < nbArg) { cmd->path2 = validerPath(tabSousChaine[noArg]); noArg++; }else { break; } }else if(listeCmd[i].inode2==OPT_OPT && noArg < nbArg) { cmd->path2 = validerPath(tabSousChaine[noArg]); noArg++; } if(listeCmd[i].param == PAR_INT){//crf if (noArg < nbArg) { cmd->param = atoi(tabSousChaine[noArg]); noArg++; }else { break; } } if (noArg < nbArg) { // trop d'arguments break; } return 0; } } cmd->noCmd = CMD_INVALIDE; return 0; }; int initializer(){ /* Elle cree la Racine "/" */ blocLibres = (unsigned int *)realloc(blocLibres,120*sizeof(unsigned int)); int cnt; for(cnt = 0; cnt<120 ;cnt++){ blocLibres[cnt]=0; } //initialization du tabInode à -1; int j; for(j = 0; j<NB_MAX_INODE ;j++){ tabInode[j]=-1; } //numero de preomier blocDisque libre dans le tableauBloc int noBlocLibre1 = allouerBlocLibres(); tabInode[premierInodeLibre()] = noBlocLibre1; INODE *iInodeR = &tableauBloc[tabInode[0]].i; iInodeR->type = 'd'; strcpy(iInodeR->mode, modeDir); iInodeR->UID = 1; char timeString[40]; recupererTemps(timeString, 40); strcpy(iInodeR->timeCreation,timeString); strcpy(iInodeR->timeAcces,timeString); strcpy(iInodeR->timeModification,timeString); int k; for (k=0; k<10; k++){ tableauBloc[noBlocLibre1].i.premiersBlocs[k]=-1; } int noBlocLibre2 = allouerBlocLibres(); tableauBloc[noBlocLibre1].i.premiersBlocs[0] = noBlocLibre2; strcpy(tableauBloc[noBlocLibre2].blocRep[0].nom, "."); tableauBloc[noBlocLibre2].blocRep[0].noInode = 0; strcpy(tableauBloc[noBlocLibre2].blocRep[1].nom, ".."); tableauBloc[noBlocLibre2].blocRep[1].noInode = 0; repCourant = 0; int i; for (i=2; i<15; i++) { tableauBloc[noBlocLibre2].blocRep[i].noInode = -1; strcpy(tableauBloc[noBlocLibre2].blocRep[i].nom," "); } return 0; } int cmd_ls(struct Cmd *cmd){ /* Elle liste le contenu d'un repertoire dans differents mode: ls, ls [chemin], ls -l, ls -l [chemin] */ int cnt = 0;// un counteur pour ls pour ranger les noms de fichiers INODE *inodeLS = &tableauBloc[tabInode[cmd->path1.inodeE]].i; INODE *inodeLSP = &tableauBloc[tabInode[cmd->path1.inodeP]].i; if(inodeLS->type!='d' || inodeLSP->type!='d'){ fprintf(stderr,"erreur: path inexistant\n"); return 0; } int i = 0; while(i<10){ if(inodeLS->premiersBlocs[i]>0){ int j=0; while(j<15){ int inodeF = tableauBloc[inodeLS->premiersBlocs[i]].blocRep[j].noInode; if(inodeF>-1){ INODE *iInodeF = &tableauBloc[tabInode[inodeF]].i; char *nom = tableauBloc[inodeLS->premiersBlocs[i]].blocRep[j].nom; if(cmd->option == 'l'){ printf("%c%10s golrokh %4d %11s %s\n", iInodeF->type ,iInodeF->mode, iInodeF->taille, iInodeF->timeModification ,nom ); }else{ printf("%-15s", nom); cnt++; } } j++; } } i++; } if(cmd->option!='l'){ printf("\n"); }else{ if (cnt%6!=0) { printf("\n"); } } return 0; } int cmd_mkdir(struct Cmd *cmd){ /* Elle creer un repertoire */ if (cmd->path1.inodeE > 0) { /**/ fprintf(stderr,"erreur: le répertoire existe déjà\n"); return -1; } if(cmd->path1.inodeP<0){ fprintf(stderr,"erreur: path inexistant\n"); return -1; } if(validerNom(cmd->path1.nom)==-1){ fprintf(stderr,"erreur: nom\n"); return -1; } int noInode = premierInodeLibre(); if(noInode==NB_MAX_INODE){ fprintf(stderr,"erreur: la memoir est plein\n"); return -1; } int noBlocLibre1 = allouerBlocLibres(); if(noBlocLibre1==-1){ fprintf(stderr,"erreur: la memoir est plein\n"); tabInode[noInode] = -1; return -1; } tabInode[premierInodeLibre()] = noBlocLibre1; INODE *indRep = &tableauBloc[noBlocLibre1].i; indRep->type = 'd'; strcpy(indRep->mode, modeDir); indRep->UID = 1; char timeString[40]; recupererTemps(timeString, 40); strcpy(indRep->timeCreation,timeString); strcpy(indRep->timeAcces,timeString); strcpy(indRep->timeModification,timeString); int k; for (k=0; k<10; k++){ indRep->premiersBlocs[k]=-1; } indRep->inSimple = -1; indRep->inDouble = -1; int noBlocLibre2 = allouerBlocLibres(); if(noBlocLibre2==-1){ fprintf(stderr,"erreur: la memoir est plein\n"); tabInode[noInode] = -1; liberer(noBlocLibre1); return -1; } indRep->premiersBlocs[0] = noBlocLibre2; struct ligneBloc *rep = tableauBloc[noBlocLibre2].blocRep; strcpy(rep[0].nom, "."); rep[0].noInode = noInode; strcpy(rep[1].nom, ".."); rep[1].noInode = repCourant; int control = updateParent(cmd->path1.inodeP, noInode, cmd->path1.nom , -1, 1); if(control==-1){// si ajouter n'est pas effectue liberer(noBlocLibre1);//inode liberer(noBlocLibre2);//blocDisque tabInode[noInode] = -1; return 0; } int i; for(i = 2; i<15;i++){ tableauBloc[noBlocLibre2].blocRep[i].noInode = -1; strcpy(tableauBloc[noBlocLibre2].blocRep[i].nom," "); } return 0; } struct inodePNomE validerPath(char *chaine){ /* Elle valide un chemin par rapport a longueur de chemin donne et l'inode de premier rep dans le chemin et stocker le path dans un struc inodePNomE */ struct inodePNomE stInodePNomE; int tmpParent = -1; char *tab2[100]; int hauteur; stInodePNomE.inodeP = repCourant; stInodePNomE.inodeE = -1; if (*chaine == '/') {// si le path commence par "/" stInodePNomE.inodeP = 0; } if(strcmp(chaine,"/")==0 || strcmp(chaine,"\n")==0){//si le path est "/" stInodePNomE.inodeE = 0; stInodePNomE.inodeP = 0; stInodePNomE.nom = "/"; return stInodePNomE; } recupererSousChaine(chaine, "/", tab2); hauteur = nbElement(tab2); stInodePNomE.nom = tab2[hauteur-1]; int i = 0; for (i=0; i<hauteur; i++){ stInodePNomE.inodeE = retournNoInode(tab2[i], stInodePNomE.inodeP); tmpParent = stInodePNomE.inodeP; stInodePNomE.inodeP = stInodePNomE.inodeE; } stInodePNomE.inodeP = tmpParent; return stInodePNomE; } int cmd_cd(struct Cmd *cmd){ /* Elle change le repertoire courant vers celui specifie dans la commande cmd */ if(cmd->path1.inodeE==-1 || cmd->path1.inodeP==-1){ fprintf(stderr, "erreur: path inexistant\n"); return 0; } if(strcmp(cmd->path1.nom, "/")==0){ repCourant = 0; }else if(strcmp(cmd->path1.nom, "..")==0){ repCourant = returnInodeParent(repCourant); }else{ repCourant = cmd->path1.inodeE; } return 0; } int cmd_rmDir(struct Cmd *cmd){ /* Elle efface un repertoire avec tous ses fichiers*/ if(cmd->path1.inodeE<0||cmd->path1.inodeP<0){ fprintf(stderr,"path inexistant\n"); return 0; } int blocRepR; INODE *iInode = &tableauBloc[tabInode[cmd->path1.inodeE]].i; if(iInode->type=='d'){ if(avoirEnfant(iInode)==1){ printf("Suppression impossible : le répertoire contient des sous répertoires ou des fichiers\n"); }else{ updateParent(cmd->path1.inodeP, -1, " ", cmd->path1.inodeE,0); liberer(tabInode[cmd->path1.inodeE]); blocRepR = iInode->premiersBlocs[0]; liberer(blocRepR); liberer(tabInode[cmd->path1.inodeE]); tabInode[cmd->path1.inodeE] = -1; } }else{ fprintf(stderr,"path inexistant\n"); } return 0; } int avoirEnfant(INODE *iInode){ /* Elle efface un repertoire/fichier par son inode et inode de son parent */ int bool_avoirEnfant = 0; int i = 0; while(i<10 && bool_avoirEnfant == 0){ int j = 0; if(i==0){ j=2; } if (iInode->premiersBlocs[i]>-1) { while(j<15 && bool_avoirEnfant == 0){ int ind = tableauBloc[iInode->premiersBlocs[i]].blocRep[j].noInode; if(ind>-1){ bool_avoirEnfant = 1; } j++; } } i++; } return bool_avoirEnfant; } int cmd_crf(struct Cmd *cmd){ /* Elle cree un fichier de nom et taille donnes dans le command cmd */ char timeString[40]; int nbBlocs; int noInode; int noBlocLibre; recupererTemps(timeString, 40); if (cmd->path1.inodeP==-1) { fprintf(stderr,"path inexistant\n"); return 0; } if(validerNom(cmd->path1.nom)==-1){ fprintf(stderr,"erreur: nom\n"); return -1; } if(cmd->path1.inodeE==-1){ nbBlocs = (cmd->param/2); if(nbBlocs >= NB_MAX_BLOC){ fprintf(stderr,"impossible de creer un fichier avec la taille specifiee, espace disque insuffisant \n"); return -1; } if(cmd->param%2!=0) nbBlocs++; noInode = premierInodeLibre(); if(noInode==NB_MAX_INODE){ fprintf(stderr,"erreur: la memoir est plein\n"); return -1; } noBlocLibre = allouerBlocLibres(); if(noBlocLibre==-1){ fprintf(stderr,"erreur: la memoir est plein\n"); return -1; } tabInode[noInode] = noBlocLibre; INODE *indFic = &tableauBloc[noBlocLibre].i; int k; for (k=0; k<10; k++){ tableauBloc[noBlocLibre].i.premiersBlocs[k]=-1; } indFic->inSimple = -1; indFic->inDouble = -1; indFic->type = 'f'; strcpy(indFic->mode, modeFic); indFic->UID = 1; indFic->taille = cmd->param; strcpy(indFic->timeCreation,timeString); strcpy(indFic->timeAcces,timeString); strcpy(indFic->timeModification,timeString); int checkAlloue = allouerSpace(nbBlocs, indFic); if(checkAlloue!=0){// cas de espace memoire pleine libererSpace(checkAlloue, indFic); tabInode[noInode]=-1; liberer(noBlocLibre); return -1; } int control = updateParent(cmd->path1.inodeP, noInode, cmd->path1.nom, -1, 1); if(control==-1){// si ajouter n'est pas effectue liberer(noBlocLibre); tabInode[noInode] = -1; return 0; } }else{ fprintf(stderr,"ce fichier deja existe\n"); } return 0; } int cmd_Cp_Mv_Rm (struct Cmd *cmd){ /* Elle copie et deplacer un fichier source vers un fichier de destination et supprimer un fichier */ INODE *ind; INODE *indSource; int noInodeRDest; int noInodeDest; char *nom; int checkUpdate; if(cmd->path1.inodeE<0){ fprintf(stderr,"erreur path inexistant de Source\n"); return 0; } indSource = &tableauBloc[tabInode[cmd->path1.inodeE]].i; if(indSource->type=='d'){ fprintf(stderr,"erreur path le %s n'est pas un fichier\n",cmd->path1.nom); return 0; } if(cmd->noCmd!=6){ if(cmd->path2.inodeP<0){ fprintf(stderr,"erreur path inexistant de Destination\n"); return 0; }else{ nom = cmd->path1.nom; if(cmd->path2.inodeE>0){ ind = &tableauBloc[tabInode[cmd->path2.inodeE]].i; if(ind->type=='f'){ checkUpdate = updateInode(cmd->path2.inodeE, cmd->path1.inodeE,1);//1 ça veut dire inode deja existe if (checkUpdate==-1) { fprintf(stderr,"erreur d'espace memoire\n"); } return 0; }else{ noInodeRDest = cmd->path2.inodeE; } }else{ if(validerNom(cmd->path2.nom)==-1){ fprintf(stderr,"erreur: nom\n"); return -1; } nom = cmd->path2.nom; noInodeRDest = cmd->path2.inodeP; } noInodeDest = premierInodeLibre(); int noBlocLibre = allouerBlocLibres(); if(noBlocLibre==-1){ fprintf(stderr,"erreur: la memoir est plein\n"); return -1; } tabInode[noInodeDest] = noBlocLibre; checkUpdate = updateInode(noInodeDest, cmd->path1.inodeE,0);// inode nouveau if (checkUpdate==-1) { fprintf(stderr,"erreur d'espace memoire\n"); liberer(noBlocLibre); tabInode[noInodeDest] = -1; return 0; } if(cmd->noCmd!=6){ int control = updateParent(noInodeRDest, noInodeDest, nom, -1, 1);//here si la memoire est pleine if(control==-1){ tabInode[noInodeDest]=-1; liberer(noBlocLibre); return 0; } } } } if(cmd->noCmd==6){// si c'est la commande rm cmd_rm(cmd->path1.inodeE); } if(cmd->noCmd==7 || cmd->noCmd==6){ updateParent(cmd->path1.inodeP, -1, " ", cmd->path1.inodeE,0); } return 0; } int cmd_rm(int inode){ /* Elle efface un fichier en sepecifiant un numero d'inode.*/ INODE *iInode = &tableauBloc[tabInode[inode]].i; if(iInode->type == 'f'){ int nbBlocs; if(iInode->taille%2>0){ nbBlocs = iInode->taille/2+1; }else{ nbBlocs = iInode->taille/2; } libererSpace(nbBlocs, iInode); liberer(tabInode[inode]); tabInode[inode] = -1; }else{ fprintf(stderr,"c'est un repertoir pas un fichier\n"); } return 0; } int cmd_blc(struct Cmd *cmd){ /* Elle affiche les numeros de blocs utilisees par un fichier ou rep dont le nom est passe en parametre */ int cnt = 0;// un compteur pour nbBloc afficher pour les ranger dans les ligne et colons if(cmd->path1.inodeE<0){ fprintf(stderr,"le fichier %s n'existe pas\n", cmd->path1.nom); return 0; } INODE *inodeFichier = &tableauBloc[tabInode[cmd->path1.inodeE]].i; printf("%4d ",tabInode[cmd->path1.inodeE]); cnt++; int i = 0; while(i<10){ if(inodeFichier->premiersBlocs[i]>0){ printf("%4d ",inodeFichier->premiersBlocs[i] ); cnt++; } if(cnt%15==0){ printf("\n"); } i++; } if(inodeFichier->inSimple>0){ printf("%4d ", inodeFichier->inSimple); cnt++; int j = 0; while(tableauBloc[inodeFichier->inSimple].inSIMPLE[j]> 0 && j<512){ if (j != 511){ printf("%4d ", tableauBloc[inodeFichier->inSimple].inSIMPLE[j]); cnt++; } j++; if(cnt%15==0){ printf("\n"); } } } if(inodeFichier->inDouble>0){ printf("%4d ", inodeFichier->inDouble); cnt++; int i = 0; while(i<512 && tableauBloc[inodeFichier->inDouble].inSIMPLE[i]>0){ int j = 0; while(j<512 && tableauBloc [ tableauBloc[inodeFichier->inDouble].inSIMPLE[i]].inSIMPLE[j]>0){ printf("%4d ",tableauBloc [ tableauBloc[inodeFichier->inDouble].inSIMPLE[i]].inSIMPLE[j]); cnt++; if(cnt%15==0){ printf("\n"); } j++; } i++; } } if(cnt%15!=0){ printf("\n"); } return 0; } int updateParent(int noInodeP, int noInode, char nom[129], int inode, int checkUpdate){//check update est 1 pour mkdir et crf /* Elle ajoute l'noInode et le nom au parent ou noInode == inode dans l'inode de parent(noInodeP).*/ if(retournNoInode(nom, noInodeP)>0 && checkUpdate==1){ fprintf(stderr,"ce fichier deja existe dans le repertoir de destination\n"); return -1; }else{ INODE *inodeParent = &tableauBloc[tabInode[noInodeP]].i; int bool_ajoute = 0; int j = 0; while(bool_ajoute == 0 && j<10){ int i = 0; if (inodeParent->premiersBlocs[j]>-1) { while(bool_ajoute == 0 && i<15){ if(tableauBloc[inodeParent->premiersBlocs[j]].blocRep[i].noInode == inode){ //si le numero d'inode dans le parent est egal à inode donne (inode) //on le met a jour par noInode et nom donnes tableauBloc[inodeParent->premiersBlocs[j]].blocRep[i].noInode = noInode; strcpy(tableauBloc[inodeParent->premiersBlocs[j]].blocRep[i].nom , nom); bool_ajoute = 1; } i++; } }else{ int noBlocLibre = allouerBlocLibres(); if(noBlocLibre==-1){//Bruno fprintf(stderr,"erreur: la memoir est plein\n"); return -1; } inodeParent->premiersBlocs[j] = noBlocLibre; int l; for(l = 0; l<15; l++){/*elle initialize les restes d'inodes a -1*/ tableauBloc[inodeParent->premiersBlocs[j]].blocRep[l].noInode = -1; } tableauBloc[inodeParent->premiersBlocs[j]].blocRep[0].noInode = noInode; strcpy(tableauBloc[inodeParent->premiersBlocs[j]].blocRep[i].nom , nom); bool_ajoute = 1; } j++; } if(bool_ajoute==0){ printf("le repertoire est plein\n"); return -1; } } return 0; } int returnInodeParent(int noInode){ /* Elle retourne le numero d inode du parent *//* seulemnt pour les repertoirs */ INODE *iInode = &tableauBloc[tabInode[noInode]].i; return tableauBloc[iInode->premiersBlocs[0]].blocRep[1].noInode; } int retournNoInode(char *nom , int noInodeP){ /* Elle retourne numero d'inode d'un fichier a partir de son nom et le numero d'inode * de son parent et si il le trouve pas il retourne -1 */ int noInode = -1; INODE *ind = &tableauBloc[tabInode[noInodeP]].i; int bool_ind_trouve = 0; int j=0; while(j<10 && bool_ind_trouve==0){ if(ind->premiersBlocs[j]>-1){ int k = 0; while(k<15 && bool_ind_trouve==0){ if(strcmp(tableauBloc[ind->premiersBlocs[j]].blocRep[k].nom, nom)==0){ bool_ind_trouve = 1; noInode = tableauBloc[ind->premiersBlocs[j]].blocRep[k].noInode; } k++; } } j++; } return noInode; } int updateInode(int noInodeDest, int noInodeSource, int identifierInode){ /*Elle met a jour l'inode du fichier destination a partir de inodeSource*/ char timeString[40]; recupererTemps(timeString, 40); int nbBlocDest; int nbBlocSource; int alloue; INODE *iDest = &tableauBloc[tabInode[noInodeDest]].i; INODE *iSource = &tableauBloc[tabInode[noInodeSource]].i; strcpy(iDest->mode, iSource->mode); iDest->UID = iSource->UID; iDest->GID = iSource->GID; iDest->type = iSource->type; strcpy(iDest->timeCreation,timeString); strcpy(iDest->timeAcces,timeString); strcpy(iDest->timeModification,timeString); if(identifierInode==0){ int k; for (k=0; k<10; k++){ iDest->premiersBlocs[k]=-1; } iDest->inSimple = -1; iDest->inDouble = -1; iDest->taille = iSource->taille; nbBlocDest = iSource->taille/2; if(iDest->taille%2!=0) nbBlocDest++; alloue = allouerSpace(nbBlocDest, iDest); if(alloue!=0){ libererSpace(alloue, iDest); return -1; } } // Si fichier dest deja existe on va seulement mettre a jour la taille if(identifierInode==1){ nbBlocSource = iSource->taille/2; if(iSource->taille%2!=0) nbBlocSource++; nbBlocDest = iDest->taille/2; if(iDest->taille%2!=0) nbBlocDest++; int difNbBloc = nbBlocDest - nbBlocSource; /*Si la taille de deux fichier sont pas egales*/ if(difNbBloc>0){ libererSpace(difNbBloc, iDest); }else if(difNbBloc<0){ alloue = allouerSpace(difNbBloc*(-1), iDest); if(alloue!=0){ libererSpace(alloue, iDest); return -1; } } iDest->taille = iSource->taille; } return 0; } void recupererSousChaine(char * ptrBuffer, char * delimiteur, char ** tabSousChaine){ /* Elle reccoupere une chaine et la delimite par la chaine delimiteur et stocke le resultat * dans tabSousChaine.*/ int i; for(i=0; i<100; i++){ tabSousChaine[i]=NULL; } char * ptrChaine; int indice = 0; ptrChaine = strtok(ptrBuffer, delimiteur); if(ptrChaine != NULL){ tabSousChaine[indice] = ptrChaine; } while(ptrChaine != NULL){ ptrChaine = strtok(NULL, delimiteur); if(ptrChaine != NULL){ ++indice; tabSousChaine[indice] = ptrChaine; } } } int nbElement(char ** tabSousChaine){ /* Elle retourne le nombre d'elements contenu dans tabSousChaine*/ int i = 0; while(tabSousChaine[i]!=NULL){ i++; } return i; } int premierInodeLibre(){ /* Elle trouve premier inode libre(-1) dans le tabInode*/ int i = 0; int bool_prB_trouve = 0; while(i<NB_MAX_INODE && bool_prB_trouve==0){ if(tabInode[i]==-1){ bool_prB_trouve=1; } i++; } return i-1; } int allouerSpace(int nbBlocs, INODE *iInode){ /* Elle alloue space memoire à l'inode a partir de sa taille */ int blocAlloue; int j = 0; int cntBlocAlloue = 0; while(j<10 && cntBlocAlloue<nbBlocs){ if(iInode->premiersBlocs[j]<0){ blocAlloue = allouerBlocLibres(); if(blocAlloue!=-1){ iInode->premiersBlocs[j] = blocAlloue; cntBlocAlloue++; }else{ fprintf(stderr,"Impossible de creer un fichier avec la taille specifiee, espace disque insuffisant \n"); return cntBlocAlloue; } } j++; } if(cntBlocAlloue < nbBlocs){ if(iInode->inSimple<1){ blocAlloue = allouerBlocLibres(); if(blocAlloue!=-1){ iInode->inSimple = blocAlloue; int i; for (i=0; i<512; i++) { tableauBloc[iInode->inSimple].inSIMPLE[i]=-1; } tableauBloc[iInode->inSimple].inSIMPLE[2]=-1; tableauBloc[iInode->inSimple].inSIMPLE[3]=-1; }else{ fprintf(stderr,"Impossible de creer un fichier avec la taille specifiee, espace disque insuffisant \n"); return cntBlocAlloue; } } int k = 0; while(k<512 && cntBlocAlloue!=nbBlocs){ if(tableauBloc[iInode->inSimple].inSIMPLE[k]<1){ blocAlloue = allouerBlocLibres(); if(blocAlloue!=-1){ tableauBloc[iInode->inSimple].inSIMPLE[k] = blocAlloue; cntBlocAlloue++; }else{ fprintf(stderr,"Impossible de creer un fichier avec la taille specifiee, espace disque insuffisant \n"); return cntBlocAlloue; } } k++; } } if(cntBlocAlloue < nbBlocs){ if(iInode->inDouble<0){ if(blocAlloue!=-1){ iInode->inDouble = blocAlloue; int i; for (i=0; i<512; i++) { tableauBloc[blocAlloue].inDOUBLE[i]=-1; } }else{ fprintf(stderr,"Impossible de creer un fichier avec la taille specifiee, espace disque insuffisant \n"); return cntBlocAlloue; } } int k = 0; while(k<512 && cntBlocAlloue!=nbBlocs){ if (tableauBloc[iInode->inDouble].inDOUBLE[k]<0) { blocAlloue = allouerBlocLibres(); if(blocAlloue!=-1){ tableauBloc[iInode->inDouble].inDOUBLE[k] = blocAlloue; int i; for (i=0; i<512; i++) { tableauBloc[tableauBloc[iInode->inDouble].inDOUBLE[k]].inSIMPLE[i]=-1; } }else{ fprintf(stderr,"Impossible de creer un fichier avec la taille specifiee, espace disque insuffisant \n"); return cntBlocAlloue; } } int j = 0; while(j<512 && cntBlocAlloue!=nbBlocs && tableauBloc[tableauBloc[iInode->inDouble].inDOUBLE[k]].inSIMPLE[j]<0){ blocAlloue = allouerBlocLibres(); if(blocAlloue!=-1){ tableauBloc[tableauBloc[iInode->inDouble].inDOUBLE[k]].inSIMPLE[j] = blocAlloue; cntBlocAlloue++; }else{ fprintf(stderr,"Impossible de creer un fichier avec la taille specifiee, espace disque insuffisant \n"); return cntBlocAlloue; } j++; } k++; } } if (cntBlocAlloue < nbBlocs) { fprintf(stderr,"Impossible de creer un fichier avec la taille specifiee, espace disque insuffisant \n"); return cntBlocAlloue; } return 0; } void liberer(int b){ /*Elle met 0 pour le bit "b" dans la table blocLibres */ //b: numero de bit a liberer int indice = b/32;//indice correspond a champ de tableau que le "b" se trouve de dans int bits = b%32;// if((blocLibres[indice]& 1<<bits)){ blocLibres[indice] &= ~(1<<bits); // met le bit a 0 } } int allouerBlocLibres(){ /*Elle alloue premier bloc disque ou le bit dans la table de blocLibres qui est egal a 0 */ int cnt = 0; int i = 0; int bits = 0; int bool_bclLibre_trouve = 0; while((i+(120*cnt))<1920 && bool_bclLibre_trouve==0){ if(blocLibres[i]!=0xFFFFFFFF){ int b = 0; while(b<32 && bool_bclLibre_trouve==0){ if((blocLibres[i]& 1<<b)==0){ blocLibres[i]|=1<<b; bool_bclLibre_trouve=1; bits = b; } b++; } } if((i+1)%120==0 && cnt<16){ blocLibres = (unsigned int *)realloc(blocLibres,120*sizeof(unsigned int)); cnt++; i=-1; } i++; } if (bool_bclLibre_trouve==0) { return -1; } int blocLibre= ((i-1)*32+(120*cnt))+bits; if (blocLibre > 61439 ) return -1; if (blocLibre >= nbBlocsAllouers) { tableauBloc = (union blocDisque *) realloc(tableauBloc, sizeof (union blocDisque));//marche nbBlocsAllouers +=1; } return blocLibre; } void libererSpace(int nbBlocs, INODE *iInode){ /* Elle trouve tous les blocs occupes pour l'inode "iInode" */ int cntBlocLibrere = 0; if(iInode->inDouble>-1){ int k = 511; while(k>=0 && cntBlocLibrere<nbBlocs){ int j = 511; if(tableauBloc[iInode->inDouble].inDOUBLE[k]>-1){ while(j>=0 && cntBlocLibrere<nbBlocs){ if(tableauBloc[tableauBloc[iInode->inDouble].inDOUBLE[k]].inSIMPLE[j]>-1){ liberer(tableauBloc[tableauBloc[iInode->inDouble].inDOUBLE[k]].inSIMPLE[j]); cntBlocLibrere++; } j--; } } k--; } iInode->inDouble = -1; } if(iInode->inSimple>-1){ int i = 511; while(i>=0 && cntBlocLibrere<nbBlocs){ if(tableauBloc[iInode->inSimple].inSIMPLE[i]>-1){ liberer(tableauBloc[iInode->inSimple].inSIMPLE[i]); cntBlocLibrere++; } i--; } iInode->inSimple = -1; } int j = 9; while(j>=0 && cntBlocLibrere<nbBlocs){ if(iInode->premiersBlocs[j]>0){ liberer(iInode->premiersBlocs[j]); cntBlocLibrere++; iInode->premiersBlocs[j] = -1; } j--; } } int validerNom(char *nomDonne){ /* Elle valide si le nom commence pas par un signe ou .*/ int i = 0; int size = (int)strlen(nomDonne); while(i<size){ char ltr = nomDonne[i]; if((ltr>47 && ltr<91 ) || (ltr> 96 && ltr<123)) { i++; }else if((ltr == 46 && i!=0)){ i++; }else{ return -1; } } return 0; } void recupererTemps(char * timeString, int taille){ /* Elle obtient le temps actuel*/ TEMPS * ptrTemps; time_t t2; char * format = "%Y-%m-%d %H:%M"; time(&t2); ptrTemps = localtime ( &t2 ); strftime(timeString, taille, format, ptrTemps); } int afficherPrompt(){ /* Elle affiche le prompt selon le repertoire courant "repCourant"*/ char p = '#'; char tmpNom[129] = "/"; if(repCourant == 0){/* si le repertoire courant est la racine*/ printf("%s%c ", tmpNom, p); }else{/* si repCourant !=0 */ /* on cherche dans le parent de repertoir courant pour le nom de repertoire courant*/ int noInodeP = returnInodeParent(repCourant); INODE *inodeP = &tableauBloc[tabInode[noInodeP]].i; int bool_nom_trouve = 0;// 0 si le nom n'est pas trouve OU 1 si on le trouve dans le parent int i=0; while(i<10 && bool_nom_trouve == 0){ int j=0; if(i==0){ j=2; } if(inodeP->premiersBlocs[i]>-1){ while(j<15 && bool_nom_trouve == 0){ if(tableauBloc[inodeP->premiersBlocs[i]].blocRep[j].noInode == repCourant){ strcpy(tmpNom,tableauBloc[inodeP->premiersBlocs[i]].blocRep[j].nom); bool_nom_trouve = 1; } j++; } } i++; } if(noInodeP==0){/* si le parent est la racine on affiche le path au complet*/ printf("/%s%c ", tmpNom, p); }else{/* on affiche seulement le nom de repertoir courant avec ~ pour les restes */ printf("/~/%s%c ", tmpNom, p); } } return 0; }
5e44847784f361d4e3e9923bd54f2ce711223ed6
[ "C" ]
1
C
golrokh51/linuxMiniShell
d5b0608c115740dcbe85ed73c46dd746032c0da7
78114e63ac922b7452292b7148f5c961e2b9835a
refs/heads/master
<file_sep>//// //// hotReloading.swift //// LunchTime_iOS //// //// Created by Blaz on 15/08/2018. //// Copyright © 2018 Blaz. All rights reserved. //// // //import UIKit // //extension UIViewController { //5 // // #if DEBUG //1 // @objc func injected() { //2 // // print("I've been injected: \(self)") // viewDidLoad() //4 // } // #endif //} ////extension UIViewController { //// //// #if DEBUG //// @objc func injected() { //// //// for subview in self.view.subviews { //// subview.removeFromSuperview() //// } //// if let sublayers = self.view.layer.sublayers { //// for sublayer in sublayers { //// sublayer.removeFromSuperlayer() //// } //// } //// //// viewDidLoad() //// } //// #endif ////} <file_sep>// // MainCoordinator.swift // LunchTime_iOS // // Created by Blaz on 14/08/2018. // Copyright © 2018 Blaz. All rights reserved. // import UIKit class MainCoordinator: Coordinator { fileprivate var childCoordinators: [Coordinator] = [ FeedCoordinator(), MapViewCoordinator() ] @discardableResult func start()-> UIViewController { return startFeed() } // private func createLogin()-> UIViewController { // } @discardableResult func startFeed()-> UIViewController { let tabBarController = createTabBarController() tabBarController.showAsRoot() return tabBarController } } // MARK: - Main tab bar extension MainCoordinator { fileprivate func tabBarItem(for coordinator: Coordinator)-> UITabBarItem { switch coordinator { case is FeedCoordinator: return .feed case is MapViewCoordinator: return .map default: fatalError("No tab bar set for this coordinator!") } } fileprivate func createTabBarController()-> UITabBarController { let tabBarController = UITabBarController() let viewControllers = childCoordinators.map { coordinator-> UIViewController in let vc = coordinator.start() vc.tabBarItem = tabBarItem(for: coordinator) return vc } tabBarController.viewControllers = viewControllers return tabBarController } } extension UITabBarItem { static let feed = UITabBarItem(title: "searches", image: #imageLiteral(resourceName: "outline_dns_black_18dp"), selectedImage: nil) static let map = UITabBarItem(title: "find", image: #imageLiteral(resourceName: "baseline_my_location_black_18dp"), selectedImage: nil) } <file_sep>// // BaseViewController.swift // LunchTime_iOS // // Created by Blaz on 14/08/2018. // Copyright © 2018 Blaz. All rights reserved. // import UIKit class BaseViewController: UIViewController { enum NavigationBarDisplayMode { case always case never case automatic } var navigationBarDisplayMode: NavigationBarDisplayMode = .automatic { didSet { guard let navigationController = navigationController else { return } switch navigationBarDisplayMode { case .always: navigationController.isNavigationBarHidden = false case .automatic: let isFirstViewController = navigationController.viewControllers.count == 1 navigationController.isNavigationBarHidden = !isFirstViewController case .never: navigationController.isNavigationBarHidden = true } } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension BaseViewController { open class func instance() -> Self { if let vc = createFromStoryboard(type: self) { return vc } else { print("WARNING: can't create view controller from storybard:\(self)") return self.init() } } private class func createFromStoryboard<T: UIViewController>(type: T.Type) -> T? { let storyboardName = String(describing: type) let bundle = Bundle(for: T.self) guard bundle.path(forResource: storyboardName, ofType: "storyboardc") != nil else { return nil } let storyboard = UIStoryboard(name: storyboardName, bundle: bundle) guard let vc = storyboard.instantiateInitialViewController() else { print("no vc in storyboard(hint: check initial vc)") return nil } return vc as? T } } <file_sep>// // BaseNavigationController.swift // LunchTime_iOS // // Created by Blaz on 14/08/2018. // Copyright © 2018 Blaz. All rights reserved. // import UIKit class BaseNavigationController: UINavigationController { private func customizeNavigationBar() { removeShadowFromNavbar() navigationBar.barTintColor = .tulip navigationBar.tintColor = .white navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white, .font: UIFont.at_title] } private func removeShadowFromNavbar() { navigationBar.shadowImage = UIImage() } override func viewDidLoad() { super.viewDidLoad() customizeNavigationBar() } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension UIFont { @nonobjc static let at_profileTitle = UIFont.systemFont(ofSize: 23, weight: UIFont.Weight.light) @nonobjc static let at_title = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.light) @nonobjc static let at_placeholderLabel = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.light) @nonobjc static let at_details = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.light) @nonobjc static let at_subtitle = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.light) @nonobjc static let at_label = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.light) } extension UIColor { @nonobjc static let tulip = UIColor(red: 255/255.0, green: 146/255.0, blue: 139/255.0, alpha: 1) @nonobjc static let at_tintColor = UIColor(red: 0/255.0, green: 190/255.0, blue: 223/255.0, alpha: 1) @nonobjc static let at_error = UIColor(red: 255/255.0, green: 97/255.0, blue: 67/255.0, alpha: 1) @nonobjc static let at_disabledButton = UIColor(red: 220/255.0, green: 225/255.0, blue: 230/255.0, alpha: 1) @nonobjc static let at_defaultTextColor = UIColor(red: 46/255.0, green: 47/255.0, blue: 55/255.0, alpha: 1) @nonobjc static let at_lightTextColor = UIColor(red: 178/255.0, green: 184/255.0, blue: 194/255.0, alpha: 1) @nonobjc static let at_inactiveIcon = UIColor(red: 148/255.0, green: 157/255.0, blue: 165/255.0, alpha: 1) @nonobjc static let at_detailsTextColor = UIColor(red: 116/255.0, green: 117/255.0, blue: 130/255.0, alpha: 1) static let at_success = UIColor(red: 186/255.0, green: 204/255.0, blue: 32/255.0, alpha: 1) @nonobjc static let at_disabledButtonText = UIColor(red: 188/255.0, green: 195/255.0, blue: 202/255.0, alpha: 1) @nonobjc static let at_circleButton = UIColor(red: 231/255.0, green: 235/255.0, blue: 238/255.0, alpha: 1) @nonobjc static let at_separator = UIColor(red: 220/255.0, green: 227/255.0, blue: 233/255.0, alpha: 1) @nonobjc static let at_textView = UIColor(red: 116/255.0, green: 117/255.0, blue: 130/255.0, alpha: 1) } <file_sep>// // MapViewController.swift // LunchTime_iOS // // Created by Blaz on 17/08/2018. // Copyright © 2018 Blaz. All rights reserved. // import UIKit import GoogleMaps final class MapViewController: BaseViewController { // MARK: - Outlets @IBOutlet weak var mapView: GMSMapView! private var locationManager: CLLocationManager! private func reverseGeocodeCoordinate(_ coordinate: CLLocationCoordinate2D) { let geocoder = GMSGeocoder() geocoder.reverseGeocodeCoordinate(coordinate) { response, error in guard let address = response?.firstResult(), let lines = address.lines else { return } self.title = lines.joined(separator: "\n") UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() } } } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() locationManager.delegate = self mapView.delegate = self locationManager.requestWhenInUseAuthorization() } } // MARK: - GMSMapViewDelegate extension MapViewController: GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) { reverseGeocodeCoordinate(position.target) } } // MARK: - CLLocationManagerDelegate extension MapViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { guard status == .authorizedWhenInUse else { return } locationManager.startUpdatingLocation() mapView.isMyLocationEnabled = true mapView.settings.myLocationButton = true } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.first else { return } mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0) locationManager.stopUpdatingLocation() } } <file_sep>// // FeedViewController.swift // LunchTime_iOS // // Created by Blaz on 14/08/2018. // Copyright © 2018 Blaz. All rights reserved. // import UIKit class FeedViewController: BaseViewController { let mockDataSource = ["hblag", "kiwi", "apple", "mango", "patricia", "blaz", "beer"] // MARK: - Outlets @IBOutlet weak var tableView: UITableView! // MARK: - Navigation callbacks var onShouldGoToActionsList: (() -> Void)? var onShouldGoToCreateAction: (() -> Void)? @IBAction func goToActionsList(_ sender: UIButton) { self.onShouldGoToActionsList?() } @IBAction func goToCreateAction(_ sender: UIButton) { self.onShouldGoToCreateAction?() } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self //automaticallyAdjustsScrollViewInsets = false // MARK: - UserInteraction } } extension FeedViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 150.0 } } extension FeedViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FeedCell cell.titleLabel.text = mockDataSource[indexPath.row] return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mockDataSource.count } } <file_sep>// // Coordinator.swift // LunchTime_iOS // // Created by Blaz on 14/08/2018. // Copyright © 2018 Blaz. All rights reserved. // import UIKit public protocol Coordinator: class { @discardableResult func start() -> UIViewController } <file_sep>// // UIViewControllerExtensions.swift // LunchTime_iOS // // Created by Blaz on 14/08/2018. // Copyright © 2018 Blaz. All rights reserved. // import UIKit extension UIViewController { var window: UIWindow? { return self.view.window ?? (UIApplication.shared.delegate as! AppDelegate).window } var contentViewController: UIViewController? { if let navigationViewController = self as? UINavigationController { return navigationViewController.topViewController?.contentViewController } else { return self } } func showAsRoot() { guard let window = window else { return } window.rootViewController = self window.makeKeyAndVisible() } } <file_sep>// // MapViewCoordinator.swift // LunchTime_iOS // // Created by Blaz on 17/08/2018. // Copyright © 2018 Blaz. All rights reserved. // import UIKit class MapViewCoordinator: Coordinator { private var navigationController = BaseNavigationController() @discardableResult func start() -> UIViewController { let vc = MapViewController.instance() // vc.shouldNavigateToLobby = { [weak self] userType in // // self?.onComplete?(userType) // } navigationController.viewControllers = [vc] vc.navigationBarDisplayMode = .always return navigationController } }
6ed46b5558d7a0834135388f783e6c9b01adce74
[ "Swift" ]
9
Swift
BlazJurisic/LunchTime_iOS
c089daf11da20c8268a92f266e3a187dd707ccf5
005113aa45b1da5bac458033755d60fe5d0b90fd
refs/heads/master
<file_sep># What is this? # 2013/2/15のFluentd Casual Talks#2で発表した、"fluentd+Esperで動的ストリームクエリ"のデモプログラムです. スライドはこちら http://www.slideshare.net/Ogibayashi/20130215-fluentd-esper2 十分テストをしているわけではないので、環境などによっては動かないかも知れないです. その場合は教えてください. # Environment # 以下の環境で動作確認しています. * MacOSX 10.7.5 * fluentd 0.10.27 * Esper 4.6.0 # Setup # ## fluentd ## * ZMQ publish pluginのインストール ``` git clone https://github.com/ogibayashi/fluent-plugin-zmq-pub.git cd fluent-plugin-zmq-pub rake build fluent-gem install zmq fluent-gem install ./pkg/fluent-plugin-zmq-pub-0.0.1.gem --local ``` * fluentd.confの設定. 以下はapacheのaccesslogをin_tailで読み込み、ZeroMQにpublish, Esperの出力は"view.**"というtagでfluentdに飛ばされる場合の例です. <source> type forward </source> <source> type tail path /var/log/apache2/access_log tag apache.access format apache </source> <match apache.access> type zmq_pub pubkey <%tag%> bindaddr tcp://*:5556 flush_interval 1s </match> <match view.**> type stdout </match> ## Esper ## * jzmqのインストール https://github.com/zeromq/jzmq よりインストール. MacOS+Homebrewの場合の注意点は以下参照 http://stackoverflow.com/questions/3522248/how-do-i-compile-jzmq-for-zeromq-on-osx * デモプログラムのビルド ``` git clone https://github.com/ogibayashi/fluentd-esper-demo.git mvn package ``` # Running demo # * fluentdの起動 ``` $ fluentd ``` * デモプログラムの起動 * java.library.pathはjzmqのライブラリパスを指定 * コマンドライン引数(この場合はapache.access)は本プログラムがfluentdの出力をsubscribeする際のキー. 上記設定の場合、tagと合わせる. ``` cd fluentd-esper-demo java -Djava.library.path=/usr/local/lib -jar target/fluentd-esper-demo-1.0-SNAPSHOT-jar-with-dependencies.jar apache.access ``` * クエリの発行 src/main/scripts以下にサンプルのクライアントとEPLファイルがあります. クライアントからは、クエリの登録、参照、削除ができます. cd src/main/scripts # クエリの登録 ./testclient.rb count_by_code.epl # 登録されているクエリの一覧表示 ./testclient.rb -s # クエリの削除 ./testclient.rb -d count_by_code.epl 出力は、view.<eplファイル名>というタグでfluentdに送られ、上記設定の場合はfluentdの標準出力に出力されます. # 各javaクラス概要 # * EsperMain * mainメソッドを提供 * EsperSubscriber * 指定された文字列をキーにZeroMQからsubscribeし、Esperに投げるクラス * EPLServer * MessagePack-RPCでクライアントからのリクエストをlistenするクラス * EPLServerHandler * MessagePack-RPCにより呼び出されるメソッド(クエリの登録、一覧、削除)を提供するクラス # Copyright * Copyright (c) 2013- <NAME> * License * Apache License, Version 2.0 <file_sep>#!/usr/bin/env ruby require 'rubygems' require 'msgpack/rpc' require 'optparse' OPTS = {} ARGV.options {|opt| opt.on('-l', 'List events.'){|v| OPTS[:list] = v } opt.on('-s', 'List statements.'){|v| OPTS[:statement] = v } opt.on('-d VAL', 'List statements.'){|v| OPTS[:delete] = v } opt.on('-n VAL', 'Statment name' ){ |v| OPTS[:name] = v} opt.on('-c VAL', 'Create schema EPL filename' ){ |v| OPTS[:createschema] = v} opt.parse! } client = MessagePack::RPC::Client.new('127.0.0.1',1985) if OPTS[:list] puts client.call(:listschema) elsif OPTS[:statement] puts client.call(:liststatements) elsif OPTS[:delete] puts OPTS[:delete] client.call(:removestatement, OPTS[:delete]) elsif OPTS[:createschema] puts OPTS[:createschema] File.open(OPTS[:createschema]).readlines.each{|s| client.call(:createschema, s) } end ARGV.each{ |f| File.open(f).readlines.each{|q| puts client.call(:create, q, OPTS[:name] || f) } } <file_sep>package com.mayoya.realtime; import com.espertech.esper.client.EPAdministrator; import org.msgpack.rpc.Request; import com.espertech.esper.client.UpdateListener; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.EPStatement; import com.espertech.esper.client.EventType; import com.espertech.esper.client.StatementAwareUpdateListener; import com.espertech.esper.client.EPServiceProvider; import java.util.Properties; import org.fluentd.logger.FluentLogger; import java.util.Map; public class EPLServerHandler { private EPAdministrator cepAdm; private Properties conf; private final String FLUENT_DEFAULT_TAG="view"; private final String FLUENT_DEFAULT_HOST="localhost"; private final String FLUENT_DEFAULT_PORT="24224"; public class CEPListener implements StatementAwareUpdateListener { private FluentLogger LOG = null; public CEPListener() { String fluent_host = conf.getProperty("realtime.fluent.host",FLUENT_DEFAULT_HOST); String fluent_port = conf.getProperty("realtime.fluent.port",FLUENT_DEFAULT_PORT); String tag_prefix = conf.getProperty("realtime.fluent.tag_prefix", FLUENT_DEFAULT_TAG); if((fluent_host != null) && (fluent_port != null) && (LOG == null)){ LOG = FluentLogger.getLogger(tag_prefix,fluent_host, Integer.parseInt(fluent_port)); } } public void update(EventBean[] newData, EventBean[] oldData, EPStatement statement, EPServiceProvider epServiceProvider) { if(LOG == null){ System.out.println("------------" + statement.getName() + "-------"); for (EventBean e: newData){ System.out.println("Event received: " + e.getUnderlying()); } } else { for (EventBean e: newData){ LOG.log(statement.getName(), (Map<String,Object>)e.getUnderlying()); } } } } public EPLServerHandler(EPAdministrator cepAdm, Properties conf) { this.cepAdm = cepAdm; this.conf = conf; } public String getStatementList(){ String ret = ""; for(String st : cepAdm.getStatementNames()){ EPStatement statement = cepAdm.getStatement(st); ret = ret + statement.getName() + ":" + statement.getText() + "\n"; } return ret; } public void removestatement(Request request, String statementId){ EPStatement statement = cepAdm.getStatement(statementId); System.out.println("Remove statment " + statementId + ": " + statement.getText()); statement.destroy(); request.sendResult("Removed"); } public void liststatements(Request request){ request.sendResult(getStatementList()); } public void listschema (Request request) { String retStr = ""; for(EventType e : cepAdm.getConfiguration().getEventTypes()){ retStr = retStr + e.getName() + "\n"; } request.sendResult(retStr); } public void createschema(Request request, String eplString){ EPStatement statement = cepAdm.createEPL(eplString); request.sendResult("schema created: " + statement.getName()); } public void create(Request request, String query, String name){ EPStatement statement = cepAdm.createEPL(query,name); statement.addListener(new CEPListener()); request.sendResult("created EPL: " + statement.getName()); } }
92a05350f91d630d3988d16f9405c924ab7fa885
[ "Markdown", "Java", "Ruby" ]
3
Markdown
ogibayashi/fluentd-esper-demo
3c46b4cb20c0651d58ce36c87e2fac4e8001ea1f
a8be5589a177097386520ce7eefbce54da0b79fd
refs/heads/master
<file_sep>(()=>{ 'use strict'; let moduleForm = angular.module("uiRouterapp"); moduleForm.controller("formController", function (){ let vm = this; let defaultSettings=()=>{ loadData(); vm.inicializarCursos(); } let loadData = ()=>{ vm.encabezados = JSON.parse(localStorage.getItem("encabezados-cursos")); vm.cursos = JSON.parse(localStorage.getItem("cursos"))||[]; if(!vm.encabezados){ vm.encabezados=['ID','Nombre del curso','Duracion Meses','Fecha inicio', 'Fecha fin','Catedratico']; localStorage.setItem('encabezados-cursos', JSON.stringify(vm.encabezados)); } } vm.inicializarCursos = ()=>{ vm.curso = {}; } let getRandomId = () => { return Math.floor(Math.random() * (+100 - +1)) + +1; } let saveData = () => { localStorage.setItem("cursos", JSON.stringify(vm.cursos)); } vm.saveCurso = ()=>{ if(vm.curso.name && vm.curso.catedratico){ if(vm.curso.id){ vm.cursos.forEach(curso => { if (curso.id == vm.curso.id) student = vm.curso; }); }else{ vm.curso.id = getRandomId(); vm.cursos.push(vm.curso); } console.log(vm.curso); saveData(); vm.inicializarCursos(); } } vm.editCurso = (curso)=>{ curso.startDate = new Date (curso.startDate); curso.endDate = new Date(curso.endDate); vm.curso = curso; } vm.deleteCurso = (index)=>{ vm.cursos.splice(index,1); saveData(); } defaultSettings(); }); })();<file_sep>(()=>{ 'use strict'; let mainModule = angular.module("uiRouterapp",["ui.router"]); let mainModuleConfig = ($stateProvider, $locationProvider, $urlRouterProvider)=>{ $locationProvider.html5Mode(false); $urlRouterProvider.otherwise('app/form'); let states = [ { name: 'app', options: { url: '/app', abstract: true, templateUrl: 'app/app.html', controller: 'appController', controllerAs: 'vm' } }, { name: 'app.form', options: { tittle: 'Cursos', url: '/form', templateUrl: 'app/controller/form/form.html', controller: 'formController', controllerAs: 'vm' } }, { name: 'app.productos', options: { tittle: 'Productos', url:'/productos', templateUrl: 'app/controller/productos/productos.html', controller: 'productosController', controllerAs: 'vm' } }, { name: 'app.directivas', options: { tittle: 'Directivas', url: '/directivas', templateUrl: 'app/controller/directivas/directivas.html', controller: 'directivasController', controllerAs: 'vm' } }, { name: 'app.mart', options: { tittle: 'Market', url: '/market', templateUrl: 'app/controller/mart/mart.html', controller: 'martController', controllerAs: 'vm' } }, { name: 'app.filter', options: { tittle: 'Filter', url: '/filter', templateUrl: 'app/controller/filter/filter.html', controller: 'filterController', controllerAs: 'vm' } }, { name: 'app.pokeApi', options: { tittle: 'PokeApi', url: '/pokeApi', templateUrl: 'app/controller/pokeApi/pokeApi.html', controller: 'pokeApiController', controllerAs: 'vm' } } ]; states.forEach(state => $stateProvider.state(state.name, state.options)); }; mainModule.config(mainModuleConfig); mainModuleConfig.$inject = ['$stateProvider', '$locationProvider', '$urlRouterProvider']; mainModule.controller("appController", function($state){ let vm = this; vm.isNavCollapsed = true; vm.isCollapsed = false; vm.isCollapsedHorizontal = false; vm.navbarItems = $state.get(); }); })();<file_sep>(()=>{ 'use strict'; let moduleProducto = angular.module("uiRouterapp"); moduleProducto.controller("productosController", function (){ let vm = this; let defaultProductSettings = ()=>{ loadProductData(); vm.inicializarProductos(); } let loadProductData = ()=>{ vm.encabezadosProductos = JSON.parse(localStorage.getItem("encabezados-productos")); vm.encabezadosTabla = JSON.parse(localStorage.getItem("encabezados-tabla")); vm.productos = JSON.parse(localStorage.getItem("productos"))||[]; if(!vm.encabezadosProductos&&!vm.encabezadosTabla){ vm.encabezadosProductos=['ID','Nombre del producto','Costo','Proveedor', 'Lote', 'Descripcion Producto','Fecha de caducidad', 'URL1','URL2','URL3']; vm.encabezadosTabla=['ID','Nombre del producto','Costo','Proveedor', 'Lote', 'Descripcion Producto','Fecha de caducidad']; localStorage.setItem('encabezados-productos', JSON.stringify(vm.encabezadosProductos)); localStorage.setItem('encabezados-tabla', JSON.stringify(vm.encabezadosTabla)); } } vm.inicializarProductos = ()=>{ vm.producto = {}; } let randomIdProducto = () => { return Math.floor(Math.random() * (+100 - +1)) + +1; } let saveProductos = ()=>{ localStorage.setItem("productos", JSON.stringify(vm.productos)); } vm.saveProducto = ()=>{ vm.producto.caducidad = vm.producto.caducidad ? new Date(vm.producto.caducidad): new Date(); if(vm.producto.nombreProducto && vm.producto.proveedor && vm.producto.caducidad){ if(vm.producto.id){ vm.productos.forEach(producto => { if (producto.id == vm.producto.id) producto = vm.producto; }); }else{ vm.producto.id = randomIdProducto(); vm.producto.counter = 0; vm.productos.push(vm.producto); } saveProductos(); vm.inicializarProductos(); }else{ alert("Debe ingresar todos los datos"); } } vm.editProducto = (producto)=>{ producto.caducidad = new Date (producto.caducidad); vm.producto = producto; } vm.deleteProducto = (index)=>{ vm.productos.splice(index,1); saveProductos(); vm.inicializarProductos(); } defaultProductSettings(); }); })();<file_sep>(()=>{ 'use strict'; let modulePersona = angular.module("uiRouterapp"); modulePersona.controller('filterController', function (){ let vm = this; let defaultSettings = ()=>{ loadData(); vm.runInitialData(); } let loadData = ()=>{ vm.dataBase = JSON.parse(localStorage.getItem('Personas'))||[]; } vm.runInitialData = ()=>{ vm.data = {}; } let randomId = () => { return Math.floor(Math.random() * (+100 - +1)) + +1; } vm.save = (item)=>{ localStorage.setItem('Personas',JSON.stringify(vm.dataBase)); } vm.add = ()=>{ if(vm.data.nombre && vm.data.edad && vm.data.genero){ if(vm.data.id){ vm.dataBase.forEach(persona => { if (persona.id == vm.data.id) persona = vm.data; }); }else{ vm.data.id = randomId(); vm.dataBase.push(vm.data); } vm.save(); vm.runInitialData(); }else{ alert('Debe ingresar todos los datos'); } } vm.edit = (item)=>{ vm.data = item; } vm.delete = (index)=>{ vm.dataBase.splice(index,1); vm.save(); vm.runInitialData(); } defaultSettings(); }); })();<file_sep>(() => { 'use strict'; let module = angular.module("uiRouterapp"); module.filter('mayor', () => { return (array, opcion) => { let dataFiltrada = []; switch(opcion){ case "mayor": { array.forEach(element => { if(element.edad >=18) dataFiltrada.push(element); }); break; } case "menor":{ array.forEach(element => { if(element.edad <18) dataFiltrada.push(element); }); break; } case "hombre":{ array.forEach(element => { if(element.genero == "Hombre") dataFiltrada.push(element); }); break; } case "mujer":{ array.forEach(element => { if(element.genero == "Mujer") dataFiltrada.push(element); }); break; } default: { dataFiltrada = array; break; } } console.log(dataFiltrada); return dataFiltrada; } }); })();
fa287dd1a0b6c581493bcd8c26a87213a5f37430
[ "JavaScript" ]
5
JavaScript
mikeblue89/uiRouter
0b0af8cec2201bb9753c0a940170e2bf964c5def
93eadf037253d547d035dc30c30052337253e4d1
refs/heads/master
<repo_name>JPrasannanjaneyulu/MyExtentReportCode<file_sep>/src/test/java/com/qa/test/ExtentReportTest.java package com.qa.test; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ExtentReportTest { public static WebDriver driver; @BeforeMethod public void setUp() { System.setProperty("webdriver.chrome.driver", "D:\\batch229\\chromedriver.exe"); driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.google.com"); driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); } @Test(priority=1) public void googleTitleTest() { String title=driver.getTitle(); Assert.assertEquals(title, "Google"); } @Test(priority=2) public void googleLogoTest() { boolean googleLogo=driver.findElement(By.xpath("//img[@id='hplogo']")).isDisplayed(); //Assert.assertEquals(googleLogo, true); Assert.assertTrue(googleLogo, "Google logo is not matched"); } @AfterMethod public void tearDown() { driver.close(); } }
805813cbd1fd1adb4ba8dc3c2fb594c64babd404
[ "Java" ]
1
Java
JPrasannanjaneyulu/MyExtentReportCode
f4b19a05a33bb0a0745c802032a59d2c8a5aa36c
b42f5bd45f88be30eeec65cadfaf70cc341a6ed1
refs/heads/master
<repo_name>realsaraf/generator-editor-framework<file_sep>/test/test-app.js 'use strict'; var path = require('path'); var assert = require('yeoman-generator').assert; var helpers = require('yeoman-generator').test; describe('editor-framework:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({ projectName: 'Simple App', repo: 'simple/app', copyEntryFile: true, }) .on('end', done); }); it('creates files', function () { assert.file([ 'bower.json', 'package.json', 'gulpfile.js', 'app.js', 'index.html', // utils 'utils/gulp-tasks/electron-tasks.js', 'utils/gulp-tasks/minimize-tasks.js', 'utils/gulp-tasks/release-tasks.js', 'utils/gulp-tasks/setup-tasks.js', 'utils/libs/check-deps.js', 'utils/libs/git.js', 'utils/libs/setup-mirror.js', 'utils/res/atom.icns', 'utils/res/atom.ico', 'utils/git-commit.sh', 'utils/git-pull.sh', 'utils/git-push.sh', 'utils/git-status.sh', 'utils/rm-settings.sh', 'utils/run-tests.js', 'utils/run.js', // configs '.gitignore', '.editorconfig', '.jshintrc', // misc 'CONTRIBUTING.md', 'LICENSE.md', 'README.md', ]); }); it('should have the contents we expect', function () { assert.fileContent('package.json', '"name": "simple-app",'); assert.fileContent('bower.json', '"name": "simple-app",'); assert.fileContent('gulpfile.js', 'gulp.task(\'update-simple-app\''); assert.fileContent('utils/rm-settings.sh', 'rm -rf ~/.simple-app/*'); }); });
bb82cb454dc9c446ef85b691af3afd83bf6f4a74
[ "JavaScript" ]
1
JavaScript
realsaraf/generator-editor-framework
dfb5d0ea54154943d1590cd42b3fe833f7435b45
31f5e2019a76300f27ffeb16d2a59e61e84b15aa
refs/heads/master
<file_sep>import React, {Component} from 'react'; import axios from 'axios'; import { browserHistory } from 'react-router'; import {Link} from 'react-router'; import api from './Api'; export default class Product extends Component { constructor(props) { super(props); this.state = { products: [] } } componentDidMount() { this.getProduct() } getProduct() { axios.get(api() + '/api/products').then((response) => { console.log(response.data); let products = (response.data); this.setState({products}) }).catch((error) => { console.log(error); }); } addToCart() { axios.post(api() + '/api/add-product?id=' + this.state.products[this.props.params.productId].id).then((response)=>{ console.log(response.data); browserHistory.push('/products') }) } render() { let productsLoaded = false; let productNotFound = false; if (this.state.products.length > 0) { productsLoaded = true; } if (this.props.params.productId > 2 || this.props.params.productId < 0) { productNotFound = true; } return ( <div style={{ display:'flex', flexDirection:'column', }}> <header style={{ height: '7rem', backgroundColor: '#007BCD', display: 'flex', justifyContent: 'center', alignItems: 'center' }}> <Link to={'/'}> <h1 style={{ margin: 0 }}>Bimini</h1> </Link> <h3 style={{ margin: '0 0 0 .5rem' }}>{productsLoaded ? this.state.products[this.props.params.productId].name : null}</h3> <Link to={'/cart'}> <i className="fa fa-shopping-cart" aria-hidden="true" style={{ position: 'absolute', right: '5%', top: '2%', margin: 0 }}></i> </Link> </header> <content style={{ backgroundColor: '#369af8', display: 'block', height: '90vh' }}> <div className="main-section" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}> <div className='notFound' style={{marginTop: '5rem', textAlign: 'center', display: productNotFound ? 'block' : 'none'}}> <h3 style={{display: productNotFound ? 'inline' : 'none'}}>Product not found</h3> </div> <img style={{width:'5rem', marginTop:'2rem' }} src={productsLoaded ? this.state.products[this.props.params.productId].imageName : null} /> <description style={{marginTop:'2rem', width: '15rem', color:'white', fontFamily:'Rosario'}}>{productsLoaded ? this.state.products[this.props.params.productId].description : null} </description> <button style={{cursor: 'pointer', marginTop:'2rem', border: '2px solid white', backgroundColor:'white', borderRadius:'5px', display: productsLoaded ? 'inline-block' : 'none'}} onClick={this.addToCart.bind(this)}>Add to Cart</button> </div> </content> </div> ); } } <file_sep>package com.company; import jodd.json.JsonParser; import jodd.json.JsonSerializer; import spark.Session; import spark.Spark; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.net.URL; import java.net.URLConnection; import java.util.*; public class Main { public static ArrayList<Products> products = new ArrayList<>(); public static HashMap<Integer, Integer> cart = new HashMap(); public static void main(String[] args) throws IOException { File productData = new File("products.txt"); Scanner scanner = new Scanner(productData); while(scanner.hasNext()) { String read = scanner.nextLine(); String p [] = read.split(";"); Products prod = new Products(Integer.parseInt(p[0]), p[1], p[2], Double.parseDouble(p[3]), p[4]); products.add(prod); } Spark.port(getHerokuAssignedPort()); Spark.init(); Spark.get( "/api/hello", ((request, response) -> { return "hello world"; }) ); Spark.get( "/api/products", ((request, response) -> { JsonSerializer serializer = new JsonSerializer(); String json = serializer.include("*").serialize(products); /* is now a vehicle for what is in it*/ return json; }) ); Spark.get( "/api/get-cart", ((request, response) -> { //will be linked for all pages, will show the current attributes of the session //will have the remove, add, and change JsonSerializer serializer = new JsonSerializer(); String json = serializer.include("*").serialize(cart); /* is now a vehicle for what is in it*/ return json; //String quantity = id += request.queryParams("userSelection"); }) ); Spark.get( "/api/get-product", ((request, response) -> { JsonSerializer serializer = new JsonSerializer(); String json = serializer.include("*").serialize(products); /* is now a vehicle for what is in it*/ return json; //query parameter from url //switch or if statements?? on which product customer is inquiring upon (depends on session attribute?) }) ); Spark.get( "/api/tax", ((request, response) -> { String zip = request.queryParams("zipCode"); //String total = request.queryParams("subtotal"); //double subtotal = Double.parseDouble(total); double total = 0; for(Map.Entry<Integer, Integer> entry : cart.entrySet()) { Integer productId = entry.getKey(); Integer productQuantity = entry.getValue(); Products x = new Products(); //Integer.parseInt(id), "name", "description", Double.parseDouble("price"), "imageName"); for(Products temp : products) { if(temp.id == productId) { x = temp; } } total += x.getPrice() * productQuantity; } URL taxUrl = new URL("https://taxrates.api.avalara.com/postal?postal=" + zip + "&country=US&apikey=<KEY>); URLConnection uc = taxUrl.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); StringBuilder sb = new StringBuilder(); while(in.ready()) { sb.append(in.readLine()); } String inputLine = in.readLine(); //the url object that we created //System.out.println(inputLine); JsonParser parser = new JsonParser(); TaxListing listing = parser.parse(sb.toString(), TaxListing.class); listing.setTotal(total); JsonSerializer serializer = new JsonSerializer(); String json = serializer.include("*").serialize(listing); /* is now a vehicle for what is in it*/ return json; }) ); Spark.post( "/api/add-product", ((request, response) -> { //a button that allows the user to add as many to their cart as needed String id = request.queryParams("id"); if(id == null) { throw new Exception("No item selected"); } int idId = Integer.parseInt(id); cart.put(idId, 1); return ""; }) ); Spark.post( "/api/remove-product", ((request, response) -> { String id = request.queryParams("id"); if(id == null) { throw new Exception("No item selected"); } int idId = Integer.parseInt(id); cart.remove(idId); return ""; }) ); Spark.post( "/api/change-quantity", ((request, response) -> { String id = request.queryParams("id"); if(id == null) { throw new Exception("No item selected"); } int idId = Integer.parseInt(id); cart.get(idId); String newQuantity = request.queryParams("newQuantity"); int quantity = Integer.parseInt(newQuantity); cart.put(idId, quantity); // puts back the product with the idId # with an Integer(quantity) of z return ""; }) ); } private static int getHerokuAssignedPort() { ProcessBuilder processBuilder = new ProcessBuilder(); if (processBuilder.environment().get("PORT") != null) { return Integer.parseInt(processBuilder.environment().get("PORT")); } return 4567; //return default port if heroku-port isn't set (i.e. on localhost) } } <file_sep>import React, {Component} from 'react'; import {Link} from 'react-router'; import './ProductsPage.css'; import background from './ProductsPage.jpg'; import bottleOne from './bottleOne.svg'; import bottleOneHover from './bottleOneHover.svg'; import bottleTwo from './bottleTwo.svg'; import bottleTwoHover from './bottleTwoHover.svg'; import bottleThree from './bottleThree.svg'; import bottleThreeHover from './bottleThreeHover.svg'; import api from './Api'; const axios = require('axios'); export default class MyComponent extends Component { componentDidMount() { axios.get(api() + '/api/hello').then((response) => { console.log(response.data); }) } render() { return ( <div> <div className='productsHeader'> <div className='divCenter'> <h1> <Link to={'/'}>Bimini</Link> </h1> <h3>Products</h3> </div> <Link to={'/cart'}> <i className="fa fa-shopping-cart" aria-hidden="true"></i> </Link> </div> <div className='productsContent'> <img className='background' src={background}/> <div className='royale'> <Link to={"/products/" + 2}><img className='bottleOne' src={bottleOne}/> <img className='bottleOneHover' src={bottleOneHover}/> <p className='itemName royaleTop royale'>Agua</p> <p className='itemName royaleMiddle royale'>de</p> <p className='itemName royaleBottom royale'>Royale</p> </Link> <p className='itemPrice gray'>$1/bottle</p> </div> <hr className='hrOne'/> <div className='Serenity'> <Link to={"/products/" + 1}><img className='bottleTwo' src={bottleTwo}/> <img className='bottleTwoHover' src={bottleTwoHover}/> <p className='itemName serenityName'>Serenity</p> </Link> <p className='itemPrice white'>$2/bottle</p> </div> <hr className='hrTwo'/> <div className='vaticanPondWater'> <Link to={"/products/" + 0}><img className='bottleThree' src={bottleThree}/> <img className='bottleThreeHover' src={bottleThreeHover}/> <p className='itemName vaticanTop vatican'>Vatican</p> <p className='itemName vaticanMiddle vatican'>Pond</p> <p className='itemName vaticanBottom vatican'>Water</p> </Link> <p className='itemPrice blue'>$1000/bottle</p> </div> </div> </div> ); } } <file_sep>import React, {Component} from 'react'; import {Link} from 'react-router'; import './Cart.css'; import cart from './CartPage.jpg'; import axios from 'axios'; import api from './Api'; class Cart extends Component { constructor(props) { super(props); this.state = { cart: [], idNumber: '', total: 0 } } componentDidMount() { this.getCart() } getCart() { axios.get(api() + '/api/get-cart').then((responseCart) => { axios.get(api() + '/api/products').then((responseProducts) => { var cartItems = responseProducts.data.filter((v) => { return responseCart.data['' + v.id + ''] > 0; }); var cartItemQuantity = cartItems.map((v) => { var newItem = v; newItem.quantity = responseCart.data['' + v.id + '']; return newItem; }); this.setState({cart: cartItemQuantity}) this.getTotal() }) }).catch((error) => { console.log(error); }); } getTotal() { let totals = this.state.cart.map((product) => { return product.price * product.quantity }) let total = totals.reduce((a, v) => { return a + v; }, 0) this.setState({total}) } onRemoveClick(idNumber, e) { e.preventDefault(); console.log(idNumber); axios.post(api() + '/api/remove-product?id=' + idNumber).then((response) => { // console.log(cart.id); this.getCart(); }).catch((error) => { console.log(error); }); } onQuantityChange(idNumber, e) { e.preventDefault() axios.post(api() + '/api/change-quantity?id=' + idNumber + '&newQuantity=' + e.target.value).then(() => { this.getCart(); }) } render() { return ( <div className="cart-page-container"> <div className="cart-header"> <div className='center'> <h1 className="bimini-name-cart"> <Link to={'/'}>Bimini</Link> </h1> <h3 className="cart-name">Cart</h3> </div> </div> <div className="mid-section-cart"> <img className="cart-image" src={cart} alt='image'/> <div className="opaque-box-cart"> <ul className="product-cart"> {this.state.cart.map((product, index) => { // console.log(total); let idNumber = product.id return ( <li className="product-item-cart" key={product.id}> <controls> <i className="fa fa-times" aria-hidden="true" style={{ color: 'red', marginRight: '.5rem' }} onClick={this.onRemoveClick.bind(this, idNumber)}></i> <input onChange={this.onQuantityChange.bind(this, idNumber)} style={{ maxWidth: '2.75rem' }} type='number' min='1' placeholder={'qty: ' + product.quantity}/> </controls> {product.name}: ${product.price} </li> ) })} <hr style={{ width: '100%' }}/> <li className='product-item-cart' style={{ textAlign: 'center' }}> <span>Total:</span> <span>${this.state.total}</span> </li> </ul> <Link to='/checkout'> <button className="button-cart">Checkout</button> </Link> </div> </div> <footr> <p className="phone-number">555.555.5555</p> </footr> </div> ) } } export default Cart; <file_sep>import React, { Component } from 'react'; import axios from 'axios'; import './Checkout.css'; import { Link } from 'react-router'; require('round10').polyfill(); import api from './Api'; export default class Checkout extends Component { constructor(props) { super(props); this.state = {zip: 0, total: 0, tax: 0, zipSubmitted: false} } onZipChange(e) { console.log(e.target.value) this.setState({zip: e.target.value}) } calculateTax(e) { e.preventDefault(); console.log('asdasd') axios.get(api() + '/api/tax?zipCode=' + this.state.zip).then((response) => { this.setState({total: response.data.total, tax: response.data.totalRate, zipSubmitted: true}) }) } render() { return( <div className="checkout-container"> <div className="cart-header"> <div className='center'> <h1 className="bimini-name-cart"><Link to={'/'}>Bimini</Link></h1> <h3 className="cart-name">Checkout</h3> </div> </div> <div className="middle-section"> <div className="center-inputs"> <form onSubmit={this.calculateTax.bind(this)}> <input onChange={this.onZipChange.bind(this)} className='checkout-inputs' style={{maxWidth: '5.75rem'}} type='number' placeholder='Enter ZipCode' /> <button style={{cursor: 'pointer'}} className='checkout-inputs'>Enter</button> </form> </div> <div style={{display: 'flex', justifyContent: 'center', alignItems: 'center'}}> <div className='totals opaque-box' style={{marginTop: '2rem', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', textAlign: 'center', display: this.state.zipSubmitted ? 'flex' : 'none'}}> <h2 style={{color: 'white', fontFamily: 'Rosario', marginBottom: 0, textDecoration: 'underline'}}>Receipt</h2> <p style={{color: 'white', fontFamily: 'Rosario'}}>subtotal: {this.state.total}</p> <p style={{color: 'white', fontFamily: 'Rosario'}}>tax: {Math.round10((this.state.total * (this.state.tax/100)), -2)}</p> <hr style={{width: '25px'}}/> <p style={{color: 'white', fontFamily: 'Rosario', fontWeight: 'bold'}}>total: {Math.round10(this.state.total + (this.state.total * (this.state.tax/100)), -2)}</p> <h2 style={{color: 'white', fontFamily: 'Rosario'}}>Thank you!</h2> </div> </div> </div> </div> ) } } <file_sep># This is a crossover project between the Front End and Back End Engineering classes of The Iron Yard-Minneapolis ## Back End Contributors: [<NAME>](https://github.com/bounv), [<NAME>](https://github.com/Nellob01), and [<NAME>](https://github.com/michaelmernin) ## Front End Contributors: [<NAME>](https://github.com/AndrewSLentz) and [<NAME>](https://github.com/SPellegrene) ### Assignment description Create a simple storefront and e-commerce site. There will be at least 3 products that you have to load from an outside file. All routes must return JSON formatted data that the front-end can then use. You will also need to connect with the Avalara tax rate API to get tax rates for the location the user enters. ### Our concept We have created a designer water company called Bimini (named for the mythical home of the fountain of youth). The back end will be making an API with our three main products (all waters of various degrees of price and quality) and the front end will be making a clean and efficient site that accesses this API and allows people to order our products. <file_sep>import React, { Component } from 'react'; import {Link} from 'react-router'; import jpg from './HeaderNav.jpg'; import './App.css'; import pic from './LandingPage2.jpg'; import axios from 'axios'; import api from './Api'; class App extends Component { componentDidMount (){ axios.get(api() + '/api/hello').then((response)=> { console.log(response.data); }) } render() { return ( <div className="App"> <div className="App-header"> <h1 className="bimini-name">Bimini</h1> <ul className="nav-titles"> <li className="list-title"><Link to={"/products"}>Products</Link></li> <li className="list-title"><Link to={"/cart"}>Cart</Link></li> </ul> </div> <h2 className="slogan-main">"Water from the Heavens"</h2> <div className="mid-section"> {/* <img src={pic} className="land-photo" alt="image" /> */} <div className="opaque-box"> <span className="landing-page-desc">Bimini is your premiere source for artisinal waters imbued with all the finest minerals on earth. Browse our premium selection of products to find the perfect water for your needs and price range.</span> </div> </div> </div> ); } } export default App;
91accd053b43d2c7c8a2a2d5dd99d87cb169d01d
[ "JavaScript", "Java", "Markdown" ]
7
JavaScript
bounv/Bimini-App
fe8bc6974d36742d947946bbb0eab1cfa8f9944b
2c7320c78132ab3676d7d5afc4a837b0e9321a68
refs/heads/master
<file_sep>import React from 'react'; export class CCP extends React.Component { constructor(props){ super(props); this.containerDiv = React.createRef(); this.state = { initialized: false, agent: null, contacts: {} } } componentWillUnmount = () => { window.connect && window.connect.core.terminate(); }; componentDidMount() { window.connect.core.initCCP(this.containerDiv.current, { ccpUrl: this.props.ccpUrl, region: this.props.region, loginPopup: false, softphone: { allowFramedSoftphone: true, disableRingtone: false } }); } render() { return ( <div className="containerDiv" ref={this.containerDiv} /> ) } } <file_sep>import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import { CCP } from './CCP' import { withAuthenticator } from 'aws-amplify-react' import Amplify, { Auth } from 'aws-amplify'; import aws_exports from './aws-exports'; Amplify.configure(aws_exports); const ccpUrl = "https://angela-isengard.awsapps.com/connect/ccp-v2"; const region = "us-west-2"; class App extends Component { render() { console.log("window.ccp looks like 2"); console.log(window.ccp) return ( <CCP ccpUrl={ccpUrl} region={region}/> ); } } export default withAuthenticator(App, true);
161d2de84e08eebcf6908754d3e8e8ed02c95b05
[ "JavaScript" ]
2
JavaScript
angieyu/create-react-app-auth-amplify
bf9cc432bd0aeb71c3b5cbe2a8f846920398543e
72d884954c042723b65d0d0ab7a30b2a200300f2
refs/heads/main
<file_sep># This is the bash GUESSINGGAME project for The Unix Workbench course at Coursera. ## To find out more, visit [The Unix Workbench](https://www.coursera.org/learn/unix) 1. This README was generated : 12/12/2020 15:13:46 HST 2. The main program is guessinggame.sh and the number of lines of code is : 23 ### What this program does: #### guessinggame.sh program is a simple number guessing game: - Unlike other number guessing games, the initial value is derived from the number of files in folders the program is ran from. - The user running the program should have read permissions in the directory for the program to count the number of files and folders. - The program will check if a valid integer is entered and prompt the user if it is not valid and try again. - The program will tell the user if the number is too high and prompt the user to try again. - The program will tell the user if the number is too low and prompt the user to try again. - The program will tell the user if they have correctly guessed the number and end the program. ## Requirements of the assignment: ####GUESSINGGAME.SH 1. When the program starts the user should be asked how many files are in the current directory, and then the user should be prompted for a guess. 2. If the user's answer is incorrect the user should be advised that their guess was either too low or too high and then they should be prompted to try to guess again. 3. If the user's guess is correct then they should be congratulated and the program should end. 4. The program should not end until the user has entered the correct number of files in the current directory. 5. The program should be able to be run by entering bash guessinggame.sh into the console. 6. The program should contain at least one function, one loop, and one if statement. 7. The program should be more than 20 lines of code but less than 50 lines of code. ####makefile 1. The title of the project. 2. The date and time at which make was run. 3. The number of lines of code contained in guessinggame.sh. @DamagedDolphin <file_sep>#!/bin/bash function guess_game { echo "This is a number guessing game." load_number=$(ls | wc -l) while true do echo "How many files and directories do you think are in the current directory?" read user_value if ! [[ $user_value =~ [0-9] ]];then echo "That is not a valid number. Please try again." elif [[ $user_value -gt $load_number ]];then echo "Too high. Try again." elif [[ $user_value -lt $load_number ]];then echo "Too low. Try again." elif [[ $user_value -eq $load_number ]];then break fi done echo "Yes. The correct number of files and folders is " $load_number } guess_game <file_sep>all: README.md README.md: echo "# This is the bash GUESSINGGAME project for The Unix Workbench course at Coursera." > README.md echo "\n## To find out more, visit [The Unix Workbench](https://www.coursera.org/learn/unix)" >> README.md echo "\n1. This README was generated :" >> README.md date "+%m/%d/%Y %H:%M:%S %Z" >> README.md echo "\n2. The main program is guessinggame.sh and the number of lines of code is :" >> README.md wc -l guessinggame.sh | egrep -o "[0-9]+" >> README.md echo "\n### What this program does:" >> README.md echo "\n#### guessinggame.sh program is a simple number guessing game:" >> README.md echo "- Unlike other number guessing games, the initial value is derived from the number of files in folders the program is ran from." >> README.md echo "- The user running the program should have read permissions in the directory for the program to count the number of files and folders." >> README.md echo "- The program will check if a valid integer is entered and prompt the user if it is not valid and try again." >> README.md echo "- The program will tell the user if the number is too high and prompt the user to try again." >> README.md echo "- The program will tell the user if the number is too low and prompt the user to try again." >> README.md echo "- The program will tell the user if they have correctly guessed the number and end the program." >> README.md echo "\n" >> README.md echo "\n## Requirements of the assignment:" >> README.md echo "\n####GUESSINGGAME.SH" >> README.md echo "1. When the program starts the user should be asked how many files are in the current directory, and then the user should be prompted for a guess." >> README.md echo "2. If the user's answer is incorrect the user should be advised that their guess was either too low or too high and then they should be prompted to try to guess again." >> README.md echo "3. If the user's guess is correct then they should be congratulated and the program should end." >> README.md echo "4. The program should not end until the user has entered the correct number of files in the current directory." >> README.md echo "5. The program should be able to be run by entering bash guessinggame.sh into the console." >> README.md echo "6. The program should contain at least one function, one loop, and one if statement." >> README.md echo "7. The program should be more than 20 lines of code but less than 50 lines of code." >> README.md echo "\n####makefile" >> README.md echo "1. The title of the project." >> README.md echo "2. The date and time at which make was run." >> README.md echo "3. The number of lines of code contained in guessinggame.sh." >> README.md echo "\n@DamagedDolphin" >> README.md clean: rm README.md
c0653d599cda7261583dbb5892db15188c46a200
[ "Markdown", "Makefile", "Shell" ]
3
Markdown
damageddolphin/guessinggame
2c881d6fccfd239e0466837649a7ae79d54bd881
dea8b0f9b4850dc6dfe2a3f67639127ed5a04408
refs/heads/master
<repo_name>xiaohualaila/PEPlayer<file_sep>/app/src/main/cpp/PER/PERDecoder.h // // Created by tir on 2016/9/29. // #ifndef PANO_PERDECODER_H #define PANO_PERDECODER_H #include <media\NdkMediaCodec.h> #include <media\NdkMediaExtractor.h> #include <pthread.h> #include "../Common.h" #include "PERPackage.h" #include <queue> class PERDecoder { public: enum PERDecoderStatus { ReadyToPlay, Playing, Paused, Stoped, Closed, }; pthread_t thread; AMediaCodec *decoder; AMediaCodecBufferInfo *info; public: int decoderCode; bool isAvailableToDisplay; bool isNeedJump; bool isWaitingIFrame; uchar texData[MAX_ALPHA_IMAGE_SIZE]; int texWidth, texHeight; std::queue<PERPackage *> stepQueue; int newWidth, newHeight; float lastTS; PERDecoderStatus status; //只在runLoop里修改 PERDecoderStatus newStatus; pthread_cond_t cond; pthread_mutex_t condMutex; pthread_mutex_t queueMutex; PERDecoder(); ~PERDecoder(); bool setDecoder(int code, int width, int height); bool setDecoder(int width, int height); virtual void run(); //条件:ReadyToPlay void runLoop(); void pause(); //条件:Playing void resume(); //条件:Paused void stop(); //条件:ReadyToPlay, Playing, Paused virtual bool step(); void pushBuffer(PERPackage * package); void pushBuffer(PERPackage * package, bool isIFrame); bool popBuffer(); void clearQueue(); bool isIFrame(uchar *data); }; #endif //PANO_PERDECODER_H <file_sep>/app/src/main/cpp/Online/OnlinePano.cpp // // Created by tir on 2016/10/8. // #include "OnlinePano.h" #include "../MainController.h" static int writeFlag = true; static void RealDataCallBack(LONG lRealHandle, const char *szSerialNo, int nStreamID, LPPE_AVFRAME_DATA lpData, void *pUserData) { if (mc->onlinePano != NULL) { // if(writeFlag){ // LOGI("GLManager: cid %d:\n", lpData->byChannel); // if (lpData->lImageWidth!=0){ // char filename[100]; // sprintf(filename, "/storage/emulated/0/Pano/pgm/a_%d.pgm", lpData->byChannel); // LOGI("GLManager: 文件名 %s:\n", filename); // FILE *fp = fopen(filename, "wb+"); // if (fp){ // LOGI("GLManager: width %d,height %d:\n", lpData->lImageWidth,lpData->lImageHeight); // char buff[512]; // sprintf(buff, "P5\n%d %d\n%d\n", lpData->lImageWidth, lpData->lImageHeight, 255); // fwrite(buff, 1, strlen(buff), fp); // fwrite(lpData->pszData, 1, lpData->lImageWidth * lpData->lImageHeight, fp); // fclose(fp); // } // writeFlag = false; // } // } LOGI("OLPano:回调 数据长度 %d,通道:%d\n", lpData->lDataLength,lpData->byChannel); mc->onlinePano->realDataCallBack(lpData); } } OnlinePano::OnlinePano() { camIndex = -1; binFile = NULL; lLoginHandle = -1; lRealHandle = -1; lFileHandle = -1; pthread_mutex_init(&mutex,NULL);/* 互斥锁初始化 */ PE_Client_Init(); } OnlinePano::~OnlinePano() { unregistCam(); } bool OnlinePano::login(char *ip, int port, char *username, char *password) { lLoginHandle = PE_Client_Login(ip, port, username, password); if (lLoginHandle >= 0) { PE_Client_GetSadpInfoList(lLoginHandle, &SadpInfoList); LOGI("OLPano: Login success!"); return true; } else { int errorcode = PE_Client_GetLastError() - 0x8000F000; switch (errorcode) { case 11: mc->setErrorMessage("用户名或密码错误"); break; case 12: mc->setErrorMessage("网络错误"); break; case 13: mc->setErrorMessage("连接超时"); break; } LOGI("OLPano: Login failed %d", errorcode); return false; } } void OnlinePano::logout() { PE_Client_Logout(lLoginHandle); } int OnlinePano::getCamCount() { return SadpInfoList.wSadpNum; } char * OnlinePano::getCamNameWithIndex(int index) { return SadpInfoList.struSadpInfo[index].sDevName; } bool OnlinePano::registCamWithIndex(int index) { lastVideoTime = 0; if (index >= 0 && index < getCamCount()) { char * name = SadpInfoList.struSadpInfo[index].sSerialNo; char path[128] = "/storage/emulated/0/Pano/.online/"; char filename[128] = "/storage/emulated/0/Pano/.online/"; strcat(filename, name); strcat(filename, ".bin"); if (binFile != NULL) { delete binFile; } binFile = new PESBinFile(); if (binFile->openFile(filename) == false) { LOGI("OLPano: openFile failed: %s", filename); remove(filename); char url[128] = "BIN://"; strcat(url, name); strcat(url, ".bin"); lFileHandle = PE_Client_GetFileByName(lLoginHandle, url, path); if (lFileHandle >= 0){ LOGI("OLPano: Download file start url %s", url); int pos = 0; while (pos != 100 && pos >= 0){ pos = PE_Client_GetDownloadPos(lFileHandle); usleep(100000); } LOGI("OLPano: Download file done url %s", url); PE_Client_StopGetFile(lFileHandle); } lFileHandle = -1; if (binFile->openFile(filename) == false) { LOGI("OLPano: Open bin file faild in %s.", filename); return false; } } LOGI("OLPano: Open bin file success in %s.", filename); int camCount = binFile->camCount; if (camCount < MIN_CAMERA_COUNT && camCount > MAX_CAMERA_COUNT) { mc->setErrorMessage("不支持的视频分块数!"); LOGI("OLPano: Not avaliable camera count in %d.", camCount); return false; } int width = binFile->width; int height = binFile->height; for (int i = 0; i < binFile->camCount; i++) { int code = binFile->index[i]; OnlineDecoder * decoder = new OnlineDecoder(); if (decoder->setDecoder(code, width, height) == true) { decoder->run(); decoders[code] = decoder; } else { return false; } } LOGI("OLPano: Set %d decoders success!", camCount); mc->glm->onlinePano = this; mc->glm->panoType = PANO_TYPE_ONLINE; camIndex = index; setStreamType(STREAM_TYPE_MAIN); return true; } return false; } bool OnlinePano::setStreamType(int type) { if (lRealHandle != -1) { PE_Client_StopRealPlay(lRealHandle); lRealHandle = -1; } int width, height; switch (type) { case STREAM_TYPE_MAIN: width = binFile->width; height = binFile->height; break; case STREAM_TYPE_SUB: width = binFile->subWidth; height = binFile->subHeight; break; } for (int i = 0; i < binFile->camCount; i++) { int code = binFile->index[i]; decoders[code]->newWidth = width; decoders[code]->newHeight = height; } PE_CLIENT_PREVIEWINFO PreviewInfo; PreviewInfo.lChannel = camIndex; PreviewInfo.dwStreamType = type; PreviewInfo.dwLinkMode = 0; PreviewInfo.byProtoType = 0; LOGI("OLPano: camIndex:%d,dwStreamType:%d!", camIndex,type); lRealHandle = PE_Client_RealPlay(lLoginHandle, &PreviewInfo, RealDataCallBack, (void*)this); return true; } void OnlinePano::unregistCam() { PE_Client_StopRealPlay(lRealHandle); mc->glm->panoType = PANO_TYPE_NONE; mc->glm->onlinePano = NULL; mc->glm->glmDeinit(); if (binFile != NULL) { for (int i = 0; i < binFile->camCount; i++) { if (decoders[i] != NULL) { decoders[i]->stop(); delete decoders[i]; decoders[i] = NULL; } } delete binFile; binFile = NULL; } } void OnlinePano::realDataCallBack(LPPE_AVFRAME_DATA lpData) { LPPE_AVFRAME_DATA lpData2; PE_Client_Demux(lpData->pszData, lpData->lDataLength, &lpData2); int code = lpData2->byChannel; OnlineDecoder * decoder = decoders[code]; int len = lpData2->lDataLength; uchar * data = new uchar[len]; memcpy(data, lpData2->pszData, len); long long time = lpData2->lTimeStamp / 1000; int width = lpData2->lImageWidth; int height = lpData2->lImageHeight; unsigned int id = lpData2->lSequenceId; PERPackage * package = new PERPackage(len, data, time, width, height, id); LOGI("realDataCallBack"); // if(writeFlag){ // LOGI("OnlinePano: cid %d:\n", lpData->byChannel); //// LOGI("OnlinePano: sid %d",lpData->lSequenceId); // if (lpData->lImageWidth!=0){ // char filename[100]; // sprintf(filename, "/storage/emulated/0/Pano/pgm/a_%d.pgm", lpData->byChannel); // LOGI("OnlinePano: 文件名 %s:\n", filename); // FILE *fp = fopen(filename, "wb+"); // if (fp){ // LOGI("OnlinePano: width %d,height %d:\n", lpData->lImageWidth,lpData->lImageHeight); // char buff[512]; // sprintf(buff, "P5\n%d %d\n%d\n", lpData->lImageWidth, lpData->lImageHeight, 255); // fwrite(buff, 1, strlen(buff), fp); // fwrite(lpData->pszData, 1, lpData->lImageWidth * lpData->lImageHeight, fp); // fclose(fp); // } // writeFlag = false; // } // } decoder->pushBuffer(package,lpData->byFrameType == 1); } void OnlinePano::decodeFrameRateStep() { pthread_mutex_lock(&mutex); decodeFrameRate++; pthread_mutex_unlock(&mutex); } int OnlinePano::getDecodeFrameRate() { pthread_mutex_lock(&mutex); int fr = (int)((float)decodeFrameRate / (float)binFile->camCount + 0.5); decodeFrameRate = 0; pthread_mutex_unlock(&mutex); return fr; } int OnlinePano::getFileDownloadingPos() { if (lFileHandle >= 0) { return PE_Client_GetDownloadPos(lFileHandle); } else { return 0; } } long long OnlinePano::getCurrentVideoTime() { return lastVideoTime; } <file_sep>/app/src/main/cpp/PER/PERPano.h // // Created by tir on 2016/9/29. // #ifndef PANO_PERPANO_H #define PANO_PERPANO_H #include "../Common.h" #include "PERDecoder.h" #include "PERFile.h" class PERPano { public: bool stoped; bool isNeedJumpToTimeline; LONG jumpOffset; int decoderCount; float totalDuration; PERFile * file; PERDecoder * decoders[MAX_CAMERA_COUNT] = {0}; PERPano(); ~PERPano(); bool setPano(char * filename); void run(); float jumpToTimeline(); void awakeDecoders(); void awakeRunloop(); void resume(); void pause(); void stop(); bool setStreamType(int type); void decodeFrameRateStep(); int getDecodeFrameRate(); private: int decodeFrameRate; pthread_t thread; pthread_mutex_t mutex; pthread_cond_t cond; pthread_mutex_t condMutex; }; #endif //PANO_PERPANO_H <file_sep>/settings.gradle include ':app',':pelibrary' <file_sep>/app/src/main/cpp/timeb.h // // Created by tir on 2016/10/7. // #ifndef PANO_TIMEB_H #define PANO_TIMEB_H #include <sys/time.h> #include <chrono> struct timeb { time_t time; unsigned short millitm; short timezone; short dstflag; }; static int ftime(timeb* timebuf) { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::chrono::seconds sec = std::chrono::duration_cast<std::chrono::seconds>(now - std::chrono::system_clock::from_time_t(0)); std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - std::chrono::system_clock::from_time_t(sec.count())); timebuf->time = sec.count(); timebuf->millitm = ms.count(); timebuf->timezone = 0; timebuf->dstflag = 0; } #endif //PANO_TIMEB_H <file_sep>/app/src/main/cpp/PER/PERDecoder.cpp // // Created by tir on 2016/9/29. // #include "PERDecoder.h" #include "../MainController.h" static void runDecoderRunLoop(void *arg) { int code = *(int *)arg; mc->perPano->decoders[code]->runLoop(); } PERDecoder::PERDecoder() { newWidth = -1; newHeight = -1; isWaitingIFrame = true; decoder = NULL; info = NULL; lastTS = -1024; isAvailableToDisplay = false; isNeedJump = false; status = Closed; newStatus = Closed; pthread_cond_init(&cond, NULL); pthread_mutex_init(&condMutex,NULL); pthread_mutex_init(&queueMutex,NULL); } PERDecoder::~PERDecoder() { stop(); if (decoder != NULL) { AMediaCodec_stop(decoder); AMediaCodec_delete(decoder); } if (info != NULL) { delete info; } while (!stepQueue.empty()) { delete stepQueue.front(); stepQueue.pop(); } LOGI("PERDec:Decoder %d deinit.", decoderCode); } bool PERDecoder::setDecoder(int code, int width, int height) { decoderCode = code; return setDecoder(width, height); } bool PERDecoder::setDecoder(int width, int height) { if (info == NULL) { info = new AMediaCodecBufferInfo(); } if (decoder != NULL) { AMediaCodec_stop(decoder); AMediaCodec_delete(decoder); decoder = NULL; } decoder = AMediaCodec_createDecoderByType("video/avc"); AMediaFormat * format = AMediaFormat_new(); AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, "video/avc"); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_WIDTH, width); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_HEIGHT, height); //AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_COLOR_FORMAT, AIMAGE_FORMAT_YUV_420_888);//指定待解码的YUV格式 AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_COLOR_FORMAT, 19);//指定待解码的YUV格式 if (AMediaCodec_configure(decoder, format, NULL, NULL, 0) == 0) { AMediaCodec_start(decoder); if (newStatus == Closed) { newStatus = ReadyToPlay; } return true; } else { mc->setErrorMessage("注册解码器失败!\n播放器不支持此设备!"); LOGI("PERDec: Create mediacodec failed."); return false; } } void PERDecoder::pause() { if (newStatus == Playing) { newStatus = Paused; } } void PERDecoder::resume() { if (newStatus == Paused) { newStatus = Playing; } } void PERDecoder::stop() { newStatus = Stoped; pthread_cond_signal(&cond); } void PERDecoder::run() { if (newStatus == ReadyToPlay) { newStatus = Playing; } LOGI("PERDec:run %d runDecoderRunLoop", decoderCode); pthread_create(&thread, NULL, (void * (*)(void *))&runDecoderRunLoop, (void *)&decoderCode); } void PERDecoder::runLoop() { LOGI("PERDec:Decoder %d start runloop.", decoderCode); while (true) { status = newStatus; if (status == Paused || stepQueue.empty()) { LOGI("PERDec:Decoder %d wait runLoop!", decoderCode); pthread_cond_wait(&cond, &condMutex); //解码线程等待唤醒 } status = newStatus; if (status == Stoped) { LOGI("PERDec:Decoder %d status is Stoped then break runLoop!", decoderCode); break; } else if (status == Playing) { LOGI("PERDec:Decoder %d status is Playing in runLoop!", decoderCode); pthread_mutex_lock(&queueMutex); if (newWidth != -1 || newHeight != -1) { setDecoder(newWidth, newHeight); newWidth = -1; newHeight = -1; isNeedJump = true; LOGI("PERDec:Decoder %d newWidth is -1!", decoderCode); } if (isNeedJump) { isAvailableToDisplay = false; clearQueue(); isWaitingIFrame = true; isNeedJump = false; LOGI("PERDec:Decoder %d isNeedJump is true!", decoderCode); } if (step() == true) { popBuffer(); mc->decodeFrameRateStep(); } pthread_mutex_unlock(&queueMutex); } status = newStatus; if (status == Stoped) { break; LOGI("PERDec:Decoder %d break runLoop!", decoderCode); } } LOGI("PERDec:Decoder %d break runloop.", decoderCode); } static bool writeFlag = true; bool PERDecoder::step() { if (stepQueue.empty()) { LOGI("PERDec:Decoder %d stepQueue is empty!", decoderCode); return false; } PERPackage * package = stepQueue.front(); ssize_t inIndex = AMediaCodec_dequeueInputBuffer(decoder, 100000); if (inIndex >= 0) { size_t capacity; uint8_t *buffer = AMediaCodec_getInputBuffer(decoder, inIndex, &capacity); int size = package->len; memcpy(buffer, package->data, size); AMediaCodec_queueInputBuffer(decoder, inIndex, 0, size, 0, 0); } else { AMediaCodec_queueInputBuffer(decoder, inIndex, 0, 0, 0, 0); LOGI("PERDec:Decoder %d return false!", decoderCode); return false; } ssize_t outIndex = AMediaCodec_dequeueOutputBuffer(decoder, info, 100000); switch (outIndex) { case AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED: break; case AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED: AMediaCodec_getOutputFormat(decoder); break; case AMEDIACODEC_INFO_TRY_AGAIN_LATER: break; default: size_t capacity = 0; uchar * data = AMediaCodec_getOutputBuffer(decoder, outIndex, &capacity); // if(writeFlag){ //// LOGI("PERDecoder: cid :\n", decoderCode); // if (package->width!=0){ // char filename[100]; // sprintf(filename, "/storage/emulated/0/Pano/pgm/a_dec_out.pgm"); // LOGI("PERDecoder: 文件名 %s:\n", filename); // FILE *fp = fopen(filename, "wb+"); // if (fp){ // LOGI("PERDecoder: width %d,height %d:\n", package->width,package->height); // char buff[512]; // sprintf(buff, "P5\n%d %d\n%d\n", package->width, package->height, 255); // fwrite(buff, 1, strlen(buff), fp); // fwrite(data, 1, package->width * package->height, fp); // fclose(fp); // } // writeFlag = false; // } // } memcpy(texData, data, capacity); texWidth = package->width; texHeight = package->height; isAvailableToDisplay = true; AMediaCodec_releaseOutputBuffer(decoder, outIndex, true); LOGI("PERDec:Decoder %d end with return true!", decoderCode); return true; } LOGI("PERDec:Decoder %d end with return false!", decoderCode); return false; } void PERDecoder::pushBuffer(PERPackage *package) { pthread_mutex_lock(&queueMutex); if (isIFrame(package->data)) { LOGI("pushBuffer"); isWaitingIFrame = false; clearQueue(); stepQueue.push(package); LOGI("PERDec:pushBuffer唤醒解码线程:%d ", decoderCode); pthread_cond_signal(&cond); //唤醒解码线程 } else { if (isWaitingIFrame) { // LOGI("PERDec:pushBuffer:%d 等待i幀...", decoderCode); delete package; } else { stepQueue.push(package); // LOGI("PERDec:pushBuffer唤醒解码线程:%d ", decoderCode); pthread_cond_signal(&cond); //唤醒解码线程 } } pthread_mutex_unlock(&queueMutex); } void PERDecoder::pushBuffer(PERPackage * package, bool isIFrame) { pthread_mutex_lock(&queueMutex); if (isIFrame) { isWaitingIFrame = false; clearQueue(); stepQueue.push(package); pthread_cond_signal(&cond); //唤醒解码线程 } else { if (isWaitingIFrame) { delete package; } else { stepQueue.push(package); pthread_cond_signal(&cond); //唤醒解码线程 } } pthread_mutex_unlock(&queueMutex); } bool PERDecoder::popBuffer() { if (stepQueue.empty()) { return false; } else { delete stepQueue.front(); stepQueue.pop(); return true; } } void PERDecoder::clearQueue() { while (!stepQueue.empty()) { delete stepQueue.front(); stepQueue.pop(); } } bool PERDecoder::isIFrame(uchar *data) { if ((data[0] == 0x00) && (data[1] == 0x00) && (data[2] == 0x00) && (data[3] == 0x01) && ((data[4] & 0x1F) == 7)) { LOGI("PERDec:isIFrame return true:%d ", decoderCode); return true; } else { LOGI("PERDec:isIFrame return flase:%d ", decoderCode); return false; } }<file_sep>/app/src/main/cpp/MainController.h // // Created by tir on 2016/9/1. // #ifndef PANO_MAINCONTROLLER_H #define PANO_MAINCONTROLLER_H #include <unistd.h> #include "Common.h" #include "GLManager.h" #include "PES/PESPano.h" #include "PER/PERPano.h" #include "Online/OnlinePano.h" class MainController { public: int panoType; PESPano * pesPano; PERPano * perPano; OnlinePano * onlinePano; GLManager * glm; float timeline; char * lastErrorMessage; int surfaceIndex; void setErrorMessage(char * msg); static MainController * getInstance(); bool registPano(char * binFilename, int type); bool registPano(char *ip, int port, char *username, char *password); bool registPanoToGLM(); void unregistPano(); bool runPano(); float jumpPanoToTimeline(); bool awakeDecoders(); bool resumePano(); bool pausePano(); bool stopPano(); bool decodeFrameRateStep(); float getTotalDuration(); int getDecodeFrameRate(); private: static MainController * instance; MainController(); }; #endif //PANO_MAINCONTROLLER_H <file_sep>/app/src/main/cpp/PER/zip/ZipLibUtil.cpp /* Ziplib */ #include <zlib.h> #include <zconf.h> #include <string.h> #include <stdio.h> #include <assert.h> #define CHUNK 16384 #include "ZipLibUtil.h" #include <vector> int ExtracMemory2Memory(unsigned char *source_begin, size_t source_size, unsigned char **dest, size_t *dest_size){ int ret; unsigned have; z_stream strm; unsigned char *in = Z_NULL; unsigned char out[CHUNK]; unsigned char *source_iterator = source_begin; unsigned char *source_end = source_begin + source_size; std::vector<unsigned char> dest_vector; *dest = NULL; *dest_size = 0; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit(&strm); if (ret != Z_OK) return ret; /* decompress until deflate stream ends or end of file */ do { if (source_end >= source_iterator) { if (source_iterator + CHUNK<source_end){ strm.avail_in = CHUNK; in=source_iterator; source_iterator += CHUNK; } else{ strm.avail_in = source_end - source_iterator; in=source_iterator; source_iterator = source_end; } } if (strm.avail_in == 0) break; strm.next_in = in; /* run inflate() on input until output buffer not full */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = inflate(&strm, Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); /* state not clobbered */ switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strm); return ret; } have = CHUNK - strm.avail_out; dest_vector.insert(dest_vector.end(), &out[0], &out[have]); } while (strm.avail_out == 0); /* done when inflate() says it's done */ } while (ret != Z_STREAM_END); /* clean up and return */ (void)inflateEnd(&strm); *dest_size = dest_vector.size(); *dest = new unsigned char[dest_vector.size()]; std::copy(dest_vector.begin(), dest_vector.end(), *dest); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } int ComprssMemory2Memory(unsigned char *source_begin, size_t source_size, unsigned char **dest, size_t *dest_size){ int level = Z_DEFAULT_COMPRESSION; int ret, flush; unsigned have; z_stream strm; unsigned char *in = Z_NULL; unsigned char out[CHUNK]; unsigned char *source_iterator = source_begin; unsigned char *source_end = source_begin + source_size; std::vector<unsigned char> dest_vector; *dest = NULL; *dest_size = 0; /* allocate deflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; ret = deflateInit(&strm, level); if (ret != Z_OK) return ret; /* compress until end of file */ do { if (source_end >= source_iterator) { if (source_iterator + CHUNK<source_end){ strm.avail_in = CHUNK; in = source_iterator; source_iterator += CHUNK; } else{ strm.avail_in = source_end - source_iterator; in = source_iterator; source_iterator = source_end; } } flush = (strm.avail_in == 0) ? Z_FINISH : Z_NO_FLUSH; strm.next_in = in; /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = deflate(&strm, flush); /* no bad return value */ assert(ret != Z_STREAM_ERROR); /* state not clobbered */ have = CHUNK - strm.avail_out; dest_vector.insert(dest_vector.end(), &out[0], &out[have]); } while (strm.avail_out == 0); assert(strm.avail_in == 0); /* all input will be used */ /* done when last data in file processed */ } while (flush != Z_FINISH); assert(ret == Z_STREAM_END); /* stream will be complete */ /* clean up and return */ (void)deflateEnd(&strm); *dest_size = dest_vector.size(); *dest = new unsigned char[dest_vector.size()]; std::copy(dest_vector.begin(), dest_vector.end(), *dest); return Z_OK; } int ExtracFile2File(FILE *source, FILE *dest){ int ret; unsigned have; z_stream strm; unsigned char in[CHUNK]; unsigned char out[CHUNK]; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit(&strm); if (ret != Z_OK) return ret; /* decompress until deflate stream ends or end of file */ do { strm.avail_in = fread(in, 1, CHUNK, source); if (ferror(source)) { (void)inflateEnd(&strm); return Z_ERRNO; } if (strm.avail_in == 0) break; strm.next_in = in; /* run inflate() on input until output buffer not full */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = inflate(&strm, Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); /* state not clobbered */ switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strm); return ret; } have = CHUNK - strm.avail_out; if (fwrite(out, 1, have, dest) != have || ferror(dest)) { (void)inflateEnd(&strm); return Z_ERRNO; } } while (strm.avail_out == 0); /* done when inflate() says it's done */ } while (ret != Z_STREAM_END); /* clean up and return */ (void)inflateEnd(&strm); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } int ComprssFile2File(FILE *source, FILE *dest){ int level = Z_DEFAULT_COMPRESSION; int ret, flush; unsigned have; z_stream strm; unsigned char in[CHUNK]; unsigned char out[CHUNK]; /* allocate deflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; ret = deflateInit(&strm, level); if (ret != Z_OK) return ret; /* compress until end of file */ do { strm.avail_in = fread(in, 1, CHUNK, source); if (ferror(source)) { (void)deflateEnd(&strm); return Z_ERRNO; } flush = feof(source) ? Z_FINISH : Z_NO_FLUSH; strm.next_in = in; /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = deflate(&strm, flush); /* no bad return value */ assert(ret != Z_STREAM_ERROR); /* state not clobbered */ have = CHUNK - strm.avail_out; if (fwrite(out, 1, have, dest) != have || ferror(dest)) { (void)deflateEnd(&strm); return Z_ERRNO; } } while (strm.avail_out == 0); assert(strm.avail_in == 0); /* all input will be used */ /* done when last data in file processed */ } while (flush != Z_FINISH); assert(ret == Z_STREAM_END); /* stream will be complete */ /* clean up and return */ (void)deflateEnd(&strm); return Z_OK; } int ExtracMemory2File(unsigned char *source_begin, size_t source_size, FILE *dest){ int ret; unsigned have; z_stream strm; unsigned char *in = Z_NULL; unsigned char out[CHUNK]; unsigned char *source_iterator = source_begin; unsigned char *source_end = source_begin + source_size; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit(&strm); if (ret != Z_OK) return ret; /* decompress until deflate stream ends or end of file */ do { if (source_end >= source_iterator) { if (source_iterator + CHUNK<source_end){ strm.avail_in = CHUNK; in = source_iterator; source_iterator += CHUNK; } else{ strm.avail_in = source_end-source_iterator; in = source_iterator; source_iterator = source_end; } } if (strm.avail_in == 0) break; strm.next_in = in; /* run inflate() on input until output buffer not full */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = inflate(&strm, Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); /* state not clobbered */ switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strm); return ret; } have = CHUNK - strm.avail_out; if (fwrite(out, 1, have, dest) != have || ferror(dest)) { (void)inflateEnd(&strm); return Z_ERRNO; } } while (strm.avail_out == 0); /* done when inflate() says it's done */ } while (ret != Z_STREAM_END); /* clean up and return */ (void)inflateEnd(&strm); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } int ComprssFile2Memory(FILE *source, unsigned char **dest, size_t *dest_size){ int level = Z_DEFAULT_COMPRESSION; if (!source) return Z_ERRNO; int ret, flush; unsigned have; z_stream strm; unsigned char in[CHUNK]; unsigned char out[CHUNK]; std::vector<unsigned char> dest_vector; *dest = NULL; *dest_size = 0; /* allocate deflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; ret = deflateInit(&strm, level); if (ret != Z_OK) return ret; /* compress until end of file */ do { strm.avail_in = fread(in, 1, CHUNK, source); if (ferror(source)) { (void)deflateEnd(&strm); return Z_ERRNO; } flush = feof(source) ? Z_FINISH : Z_NO_FLUSH; strm.next_in = in; /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = deflate(&strm, flush); /* no bad return value */ assert(ret != Z_STREAM_ERROR); /* state not clobbered */ have = CHUNK - strm.avail_out; dest_vector.insert(dest_vector.end(), &out[0], &out[have]); } while (strm.avail_out == 0); assert(strm.avail_in == 0); /* all input will be used */ /* done when last data in file processed */ } while (flush != Z_FINISH); assert(ret == Z_STREAM_END); /* stream will be complete */ /* clean up and return */ (void)deflateEnd(&strm); *dest_size = dest_vector.size(); *dest = new unsigned char[dest_vector.size()]; std::copy(dest_vector.begin(), dest_vector.end(), *dest); return Z_OK; } <file_sep>/app/src/main/cpp/com_panoeye_pano_JNIServerLib.cpp // // Created by tir on 2016/9/1. // #include "com_panoeye_pano_JNIServerLib.h" #include "MainController.h" extern "C" { JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_glmInit(JNIEnv * env , jobject obj, jint width, jint height ) { mc->registPanoToGLM(); mc->glm->glmInit(width, height); } // JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_glmResize(JNIEnv * env, jobject obj, jint width, jint height, jfloat fovy) { // mc->glm->glmResize(width, height, fovy); // } JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_glmResize(JNIEnv * env, jobject obj, jint width, jint height) { mc->glm->glmResize(width, height); } JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_glmStep(JNIEnv * env, jobject obj, jfloat gldx, jfloat gldy, jfloat gldz, jfloat fovy) { mc->glm->glmStep(gldx, gldy, gldz, fovy); } JNIEXPORT jboolean JNICALL Java_com_panoeye_peplayer_JNIServerLib_registPano(JNIEnv * env, jobject obj, jstring filename, jint panoType) { char * _filename; _filename = (char*)env->GetStringUTFChars(filename,0); bool result; switch (panoType) { case PANO_TYPE_PES: result = mc->registPano(_filename, panoType); break; case PANO_TYPE_PER: result = mc->registPano(_filename, panoType); break; default: result = false; break; } env->ReleaseStringUTFChars(filename, _filename); return result; } JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_unregistPano(JNIEnv * env, jobject obj) { mc->unregistPano(); } JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_setTimeline(JNIEnv * env, jobject obj, jfloat timeline) { mc->timeline = timeline; } JNIEXPORT jfloat JNICALL Java_com_panoeye_peplayer_JNIServerLib_getTotalDuration(JNIEnv * env, jobject obj) { return mc->getTotalDuration(); } JNIEXPORT jint JNICALL Java_com_panoeye_peplayer_JNIServerLib_getDecodeFrameRate(JNIEnv * env, jobject obj) { return mc->getDecodeFrameRate(); } JNIEXPORT jboolean JNICALL Java_com_panoeye_peplayer_JNIServerLib_awakeDecoders(JNIEnv * env, jobject obj) { return mc->awakeDecoders(); } JNIEXPORT jboolean JNICALL Java_com_panoeye_peplayer_JNIServerLib_runPano(JNIEnv * env, jobject obj) { return mc->runPano(); } JNIEXPORT jfloat JNICALL Java_com_panoeye_peplayer_JNIServerLib_jumpPanoToTimeline(JNIEnv * env, jobject obj) { return mc->jumpPanoToTimeline(); } JNIEXPORT jboolean JNICALL Java_com_panoeye_peplayer_JNIServerLib_resumePano(JNIEnv * env, jclass obj) { return mc->resumePano(); } JNIEXPORT jboolean JNICALL Java_com_panoeye_peplayer_JNIServerLib_pausePano(JNIEnv * env, jobject obj) { return mc->pausePano(); } JNIEXPORT jstring JNICALL Java_com_panoeye_peplayer_JNIServerLib_getLastErrorMessage(JNIEnv * env, jobject obj) { return env->NewStringUTF(mc->lastErrorMessage); } JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_setMode(JNIEnv * env, jobject obj, jint mode) { switch (mode) { case PANO_TYPE_PES: mc->glm->isVRMode = false; break; case PANO_TYPE_PER: mc->glm->isVRMode = true; break; case PANO_TYPE_ONLINE: mc->glm->isVRMode = true; break; default: mc->glm->isVRMode = false; break; } mc->glm->glmResize(); } JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_flip(JNIEnv * env, jobject obj) { switch (mc->panoType) { case PANO_TYPE_PES: mc->pesPano->binFile->flip(); break; case PANO_TYPE_PER: mc->perPano->file->binFile->flip(); break; case PANO_TYPE_ONLINE: mc->onlinePano->binFile->flip(); break; default: return; } mc->glm->isNeedReloadBin = true; } JNIEXPORT jboolean JNICALL Java_com_panoeye_peplayer_JNIServerLib_setStreamType(JNIEnv * env, jobject obj, jint type) { switch (mc->panoType) { case PANO_TYPE_PES: return mc->pesPano->setStreamType(type); case PANO_TYPE_PER: return mc->perPano->setStreamType(type); case PANO_TYPE_ONLINE: return mc->onlinePano->setStreamType(type); default: return false; } } JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_setVideoMode(JNIEnv * env, jobject obj, jint mode) { switch (mode) { case 0: mc->glm->isGlobularMode = true; break; case 1: mc->glm->isGlobularMode = false; break; } } // JNIEXPORT jboolean JNICALL Java_com_panoeye_peplayer_JNIServerLib_registOnlinePano(JNIEnv * env, jobject obj, jstring ip, jint port, jstring username, jstring password) { char * _ip; _ip = (char*)env->GetStringUTFChars(ip,0); char * _username; _username = (char*)env->GetStringUTFChars(username,0); char * _password; _password = (char*)env->GetStringUTFChars(password,0); bool result = mc->registPano(_ip, port, _username, _password); env->ReleaseStringUTFChars(ip, _ip); env->ReleaseStringUTFChars(username, _username); env->ReleaseStringUTFChars(password, _password); return result; } //一键生成 //JNIEXPORT jboolean JNICALL //Java_com_panoeye_peplayer_JNIServerLib_registOnlinePano(JNIEnv *env, jclass type, jstring ip_, // jint port, jstring username_, // jstring password_) { // const char *ip = env->GetStringUTFChars(ip_, 0); // const char *username = env->GetStringUTFChars(username_, 0); // const char *password = env->GetStringUTFChars(password_, 0); // // // TODO // bool result = mc->registPano(const_cast<char *>(ip), port, (char*)username, (char*)password); // // env->ReleaseStringUTFChars(ip_, ip); // env->ReleaseStringUTFChars(username_, username); // env->ReleaseStringUTFChars(password_, password); // return result; //} JNIEXPORT jint JNICALL Java_com_panoeye_peplayer_JNIServerLib_getOnlinePanoCamCount(JNIEnv * env, jobject obj) { switch (mc->panoType) { case PANO_TYPE_ONLINE: return mc->onlinePano->getCamCount(); default: return 0; } } JNIEXPORT jbyteArray JNICALL Java_com_panoeye_peplayer_JNIServerLib_getOnlinePanoCamNameWithIndex(JNIEnv * env, jobject obj, jint index) { char str[128] = "unknow"; switch (mc->panoType) { case PANO_TYPE_ONLINE: { char * name = mc->onlinePano->getCamNameWithIndex(index); memcpy(str, name, strlen(name)); break; } default: break; } jbyte *by = (jbyte*)str; jbyteArray jarray = env->NewByteArray(strlen(str)); env->SetByteArrayRegion(jarray,0,strlen(str),by); return jarray; } JNIEXPORT jboolean JNICALL Java_com_panoeye_peplayer_JNIServerLib_registOnlinePanoCamWithIndex(JNIEnv * env, jobject obj, jint index) { switch (mc->panoType) { case PANO_TYPE_ONLINE: { bool result = mc->onlinePano->registCamWithIndex(index); if (result == false) { mc->onlinePano->unregistCam(); } return result; } default: return false; } } JNIEXPORT void JNICALL Java_com_panoeye_peplayer_JNIServerLib_unregistOnlinePanoCam(JNIEnv * env, jobject obj) { switch (mc->panoType) { case PANO_TYPE_ONLINE: return mc->onlinePano->unregistCam(); break; default: break; } } JNIEXPORT jlong JNICALL Java_com_panoeye_peplayer_JNIServerLib_getOnlinePanoCurrentTimeStamp(JNIEnv * env, jobject obj) { switch (mc->panoType) { case PANO_TYPE_ONLINE: //LOGI("time %ld", mc->onlinePano->getCurrentVideoTime()); return mc->onlinePano->getCurrentVideoTime(); default: return 0; } } JNIEXPORT jint JNICALL Java_com_panoeye_peplayer_JNIServerLib_getOnlinePanoFileDownloadingPos(JNIEnv * env, jobject obj) { switch (mc->panoType) { case PANO_TYPE_ONLINE: return mc->onlinePano->getFileDownloadingPos(); default: return 0; } } }<file_sep>/app/build.gradle apply plugin: 'com.android.application' android { compileSdkVersion 26 defaultConfig { applicationId "com.panoeye.peplayer" minSdkVersion 21 targetSdkVersion 26 versionCode 1 versionName "3.6" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" //.so库的默认目录为\app\src\main\jniLibs,若放到eclipse默认目录libs需修改如下 sourceSets { main { jni.srcDirs "src/main/cpp" jniLibs.srcDirs 'libs' } } externalNativeBuild { //cmake编译方式配置 cmake { // abiFilter:ABI 过滤器(application binary interface,应用二进制接口) //abiFilters 'armeabi' cppFlags "-std=c++11 -fexceptions -frtti" arguments "-DANDROID_STL=c++_static"//,"-DANDROID_TOOLCHAIN=clang" } //mk编译方式配置 ndk { // moduleName "JNIServerLib" abiFilters 'armeabi' //abiFilters 'armeabi-v7a,arm64-v8a,x86,x86_64' // stl "c++_static" // cFlags "-std=c++11 -fexceptions -frtti" // ldLibs "c", "stdc++", "atomic", "log", "android", "EGL", "GLESv1_CM", "GLESv2", "jnigraphics", "mediandk", "z" } } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } //关联CMake的程序清单文件,path 指向cmake文件路径,此处为项目工程根目录下。 externalNativeBuild { cmake { path 'CMakeLists.txt' } } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:26.1.0' implementation 'com.android.support:design:26.1.0' implementation 'com.android.support.constraint:constraint-layout:1.0.2' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' implementation project(':pelibrary') } <file_sep>/app/src/main/cpp/PER/PERBinFile.cpp // // Created by tir on 2016/9/29. // #include "PERBinFile.h" #include "../MainController.h" PERBinFile::PERBinFile() : PESBinFile() { } PERBinFile::~PERBinFile() { } bool PERBinFile::openData(uchar *data) { int dataIndex = 0; dataIndex += 264; memcpy(&radius, data + dataIndex, sizeof(int)); long off = 256 + sizeof(int)* 7 + 16 + sizeof(char)* 4 + 64; dataIndex = off; memcpy(&binName, data + dataIndex, 64); model_type = binName[0] - 'A'; sub_model_type = binName[1] - '0'; long off1 = off + 64 + 16 * sizeof(int)+16 * sizeof(char)+11 * sizeof(int)+10 * sizeof(float)+916; dataIndex = off1; dataIndex = off1; memcpy(&camCount, data + dataIndex, sizeof(int)); dataIndex += sizeof(int); if (camCount > MAX_CAMERA_COUNT || camCount < MIN_CAMERA_COUNT) { mc->setErrorMessage("不支持的Bin数据!"); LOGI("PERBinFile: Open data faild!"); return false; } for (int i = 0; i < camCount; i++) { PESBinMesh * mesh = new PESBinMesh(); memcpy(&mesh->cid, data + dataIndex, sizeof(int)); dataIndex += sizeof(int); memcpy(&mesh->lambda, data + dataIndex, sizeof(int)); dataIndex += sizeof(int); dataIndex += sizeof(int); int row, col; memcpy(&row, data + dataIndex, sizeof(int)); dataIndex += sizeof(int); memcpy(&col, data + dataIndex, sizeof(int)); dataIndex += sizeof(int); if (col * row >= MAX_ALPHA_IMAGE_SIZE) { mc->setErrorMessage("不支持的Bin数据!"); LOGI("PERBinFile: Alpha image is too large!"); return false; } width = col; height = row; dataIndex += 568; memcpy(mesh->imgData, data + dataIndex, col * row); dataIndex += col * row; int fullSize, subSize; memcpy(&fullSize, data + dataIndex, sizeof(int)); dataIndex += sizeof(int); memcpy(&subSize, data + dataIndex, sizeof(int)); dataIndex += sizeof(int); mesh->fullCoordCount = fullSize; mesh->subCoordCount = subSize; for (int j = 0; j < fullSize; j++) { PESTriCoord * tri = new PESTriCoord(); mesh->verMain[j] = tri; memcpy(tri, data + dataIndex, sizeof(PESTriCoord)); dataIndex += sizeof(PESTriCoord); } data += subSize * sizeof(PESTriCoord); //pes里的mesh是按照cid,per里是按照顺序。 meshes[i] = mesh; index[indexCount++] = i; } setCoord(); return true; } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PEDecodeBuffer.java package panoeye.pelibrary; import java.util.HashMap; import java.util.Map; /** * Created by tir on 2016/12/14. */ //解码缓存类 public class PEDecodeBuffer { private static final String TAG = "PEDecodeBuffer"; //解码缓存映射表 public MapThrowWrap bufferDict = new MapThrowWrap(new LockWrap<Map<Integer,PEFrameBuffer>>(new HashMap<Integer,PEFrameBuffer>())); //纹理数据映射表 public MapThrowWrap textureDict = new MapThrowWrap(new LockWrap<Map<Integer,PEVideoTexture>>(new HashMap<Integer,PEVideoTexture>())); // //构造函数:鱼眼相机解码缓存 // public PEDecodeBuffer(int cameraCount){ // Size size; // if (cameraCount == 1){ // size = new Size(960,960); // }else { // size = new Size(1280,960); // } // for (int cid=0;cid<cameraCount;cid++){ // PEFrameBuffer frameBuffer = new PEFrameBuffer(cid,size); // bufferDict.put(cid,frameBuffer);//添加帧数据缓存类对象到缓存映射表,以后可根据cid得到对应cid的frameBuffer配置 // } // } //构造函数:普通相机解码缓存 public PEDecodeBuffer(int cameraCount,Size size){ // Size size = new Size(1280,960); for (int cid=0;cid<cameraCount;cid++){ PEFrameBuffer frameBuffer = new PEFrameBuffer(cid,size); bufferDict.put(cid,frameBuffer);//添加帧数据缓存类对象到缓存映射表,以后可根据cid得到对应cid的frameBuffer配置 } } //构造函数:全景相机解码缓存 public PEDecodeBuffer(PEBinFile binFile)throws PEError{ for(Integer cid:binFile.cidList){ //binFile.camConfigs.get(cid)方法 返回PECameraConfig类对象 if(binFile.camConfigs.get(cid) == null){ throw PEError.gen(PEErrorType.fileReadFailed,String.format("未找到相机配置!cid:%02d",cid)); } //通过传入相机配置类对象构造帧数据缓存类 PEFrameBuffer frameBuffer = new PEFrameBuffer(binFile.camConfigs.get(cid)); bufferDict.put(cid,frameBuffer);//添加帧数据缓存类对象到缓存映射表,以后可根据cid得到对应cid的frameBuffer配置 } } //更新纹理数据映射表 public void undateIfNeed(Integer cid, int[] textures) throws PEError{ //根据cid从缓存映射表中取出缓存数据 PEFrameBuffer frameBuffer = (PEFrameBuffer)bufferDict.get(cid); if(frameBuffer.isNeedReload == true){//如果有解码好的数据就取出 到全景视频纹理类对象texture PEVideoTexture texture = new PEVideoTexture(frameBuffer,textures); textureDict.put(cid,texture); frameBuffer.isNeedReload = false;//取出完毕, // Log.d(TAG, "undateIfNeed取出完毕:"+cid); } } } <file_sep>/app/src/main/cpp/OnlineSDK/XML/XmlRpcTX2Util.h #ifndef CAM360_LIB_XMLRPCTX2UTIL_XMLRPCTX2UTIL_H_ #define CAM360_LIB_XMLRPCTX2UTIL_XMLRPCTX2UTIL_H_ #include <time.h> #include <map> #include <memory> #include <exception> #include <string> #include <vector> #include "tinyxml2.h" #include "../../timeb.h" namespace XmlRpcTX2Util{ //for server std::string generateResponse(); bool generateResponse(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** params); std::string generateResponse(int fault_code, const char *fault_string); std::string generateRespnseHeader(const char * server, timeb *time, const char * type, int length); std::string generateRespnseHeader(const char * server, timeb *time, const char * type, const char * session, int length); bool readRequestHeader(std::string header, int *header_size, std::string *type, int *length); bool readRequestHeader(std::string header, int *header_size, std::string *type, std::string * session, int *length); bool readRequest(tinyxml2::XMLDocument *doc, const char* buff, size_t len); bool parseRequest(tinyxml2::XMLDocument *doc, std::string *method_name, tinyxml2::XMLElement ** params); bool parseRequest(tinyxml2::XMLDocument *doc, std::string *method_name, tinyxml2::XMLElement ** value, int *value_num); //for client bool generateRequest(tinyxml2::XMLDocument *doc, std::string method_name, tinyxml2::XMLElement ** params); std::string generateRequestHeader(const char * client, const char* host, const char * type, int length); std::string generateRequestHeader(const char * client, const char* host, const char * type, const char * session, int length); bool readResponseHeader(std::string header, int *header_size, std::string *type, int *length); bool readResponseHeader(std::string header, int *header_size, std::string *type, std::string * session, int *length); bool readResponse(tinyxml2::XMLDocument *doc, const char* buff, size_t len); bool parseResponse(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** params); bool parseResponse(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value, int *value_num); bool parseResponse(tinyxml2::XMLDocument *doc, int *fault_code, std::string *fault_string); //util std::string to_string(const tinyxml2::XMLDocument *doc); std::string to_string(timeb time); std::string to_string(struct tm t); }; #endif //CAM360_LIB_XMLRPCTX2UTIL_XMLRPCTX2UTIL_H_<file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PEError.java package panoeye.pelibrary; /** * Created by tir on 2016/12/13. */ public class PEError extends Exception { public Integer code; public String name; public String msg; public PEError() { code = 0; name = "null"; msg = "null"; } public PEError(Integer code, String name, String msg) { this.code = code; this.name = name; this.msg = msg; } public static PEError gen(PEErrorType type, String msg) { switch (type) { case none: return new PEError(0000, "无错误", msg); case unknow:return new PEError(0001, "未知错误", msg); case notFound:return new PEError(0101, "未找到对象", msg); case fileOpenFailed:return new PEError(1101, "文件打开失败", msg); case fileSeekFailed:return new PEError(1102, "文件移动失败", msg); case fileReadFailed:return new PEError(1103, "文件读取失败", msg); case fileWriteFailed:return new PEError(1104, "文件写入失败", msg); case fileCloseFailed:return new PEError(1105, "文件关闭失败", msg); case fileEofFailed:return new PEError(1106, "文件结尾检查失败", msg); } return new PEError(); } } <file_sep>/app/src/main/cpp/OnlineSDK/SysComm.cpp #include "PanoDef.h" void PanoComm_Init(struct PanoComm *comm) { comm->keyword[0] = 'P'; comm->keyword[1] = 'E'; comm->keyword[2] = 'C'; comm->keyword[3] = 'M'; } bool PanoComm_Check(struct PanoComm *comm) { if (comm->keyword[0] == 'P' && comm->keyword[1] == 'E'&& comm->keyword[2] == 'C'&& comm->keyword[3] == 'M') return true; return false; } unsigned int PanoComm_Size() { return 12; } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/MapThrowWrap.java package panoeye.pelibrary; import java.util.Map; /** * Created by tir on 2016/12/14. */ //锁+Map封装类 public class MapThrowWrap<K, V> { private static final String TAG = "MapThrowWrap"; LockWrap<Map<K, V>> _obj;//锁封装类对象 public V get(K key) throws PEError { V value = _obj.get().get(key); if (value == null) { throw PEError.gen(PEErrorType.notFound, "textureDict中还未存在对应key:"+key+"的PEVideoTexture类对象"); } return value; } void put(K key, V value) { _obj.get().put(key, value); } //构造函数 MapThrowWrap(LockWrap<Map<K, V>> obj) { _obj = obj; } } <file_sep>/app/src/main/cpp/PES/PESBinFile.cpp // // Created by tir on 2016/8/30. // #include "PESBinFile.h" #include "../MainController.h" #define PE_B 1 //1: 8-ch, 标清:704x576; #define PE_M 12 //12: 8-ch, 标清车载:M0: 704-576;高清车载 MA:1280x720 PESBinFile::PESBinFile() { sub_video_size[0].height = QCIF_ROW; sub_video_size[0].width = QCIF_COL; sub_video_size[1].height = QVGA_ROW; sub_video_size[1].width = QVGA_COL; sub_video_size[2].height = CIF_ROW; sub_video_size[2].width = CIF_COL; sub_video_size[3].height = 480; sub_video_size[3].width = 640; sub_video_size[4].height = 320; sub_video_size[4].width = 560; sub_video_size[5].height = 576; sub_video_size[5].width = 720; sub_video_size[6].height = D1_ROW; sub_video_size[6].width = D1_COL; sub_video_size[7].height = 360; sub_video_size[7].width = 640; sub_video_size[8].height = 1080; sub_video_size[8].width = 1920; indexCount = 0; } PESBinFile::~PESBinFile() { for (int i = 0; i < MAX_CAMERA_COUNT; i++) { PESBinMesh * mesh = meshes[i]; if (mesh != NULL) { for (int j = 0; j < MAX_MESH_COORDINATE_COUNT; j++) { delete mesh->verMain[j]; } } delete mesh; } } bool PESBinFile::openFile(char *filename) { FILE * pBinFile; pBinFile = fopen(filename, "rb"); if (pBinFile == NULL) { mc->setErrorMessage("打开Bin文件失败!"); LOGI("PESBinFile: Open file faild in %s", filename); return false; } fseek(pBinFile, 264, SEEK_SET); fread(&radius, sizeof(int), 1, pBinFile); long off = 256 + sizeof(int)* 7 + 16 + sizeof(char)* 4 + 64; fseek(pBinFile, off, SEEK_SET); fread(binName, 1, 64, pBinFile); model_type = binName[0] - 'A'; sub_model_type = binName[1] - '0'; long off1 = off + 64 + 16 * sizeof(int)+16 * sizeof(char)+11 * sizeof(int)+10 * sizeof(float)+916; fseek(pBinFile, off1, SEEK_SET); fread(&camCount, sizeof(int), 1, pBinFile); if (camCount > MAX_CAMERA_COUNT || camCount < MIN_CAMERA_COUNT) { mc->setErrorMessage("不支持的Bin文件!"); LOGI("PESBinFile: Open file faild in %s", filename); return false; } for (int i = 0; i < camCount; i++) { PESBinMesh * mesh = new PESBinMesh(); fread(&mesh->cid, sizeof(int), 1, pBinFile); fread(&mesh->lambda, sizeof(float), 1, pBinFile); fseek(pBinFile, sizeof(int), SEEK_CUR); int row, col; fread(&row, sizeof(int), 1, pBinFile); fread(&col, sizeof(int), 1, pBinFile); width = col; height = row; if (col * row >= MAX_ALPHA_IMAGE_SIZE) { mc->setErrorMessage("不支持的Bin文件!"); LOGI("PESBinFile: Alpha image is too large in %s", filename); return false; } fseek(pBinFile, 568, SEEK_CUR); fread(mesh->imgData, 1, col * row, pBinFile); int fullSize, subSize; fread(&fullSize, sizeof(int), 1, pBinFile); fread(&subSize, sizeof(int), 1, pBinFile); if (fullSize >= MAX_MESH_COORDINATE_COUNT) { mc->setErrorMessage("不支持的Bin文件!"); LOGI("PESBinFile: Mesh is too much in %s", filename); return false; } mesh->fullCoordCount = fullSize; mesh->subCoordCount = subSize; for (int j = 0; j < fullSize; j++) { PESTriCoord * tri = new PESTriCoord(); mesh->verMain[j] = tri; fread(tri, sizeof(PESTriCoord), 1, pBinFile); } fseek(pBinFile, sizeof(PESTriCoord) * subSize, SEEK_CUR); meshes[mesh->cid] = mesh; index[indexCount++] = mesh->cid; } fclose(pBinFile); setCoord(); return true; } void PESBinFile::setCoord() { int coordCount = 0; int texCount = 0; for (int i = 0; i < camCount; i++) { int code = index[i]; PESBinMesh * mesh = meshes[code]; coordCount = 0; texCount = 0; for (int j = 0; j < mesh->fullCoordCount; j++) { for (int k = 0; k < 3; k++) { verCoord[code][coordCount++] = mesh->verMain[j]->sx[k]; verCoord[code][coordCount++] = mesh->verMain[j]->sy[k]; verCoord[code][coordCount++] = -mesh->verMain[j]->sz[k]; texCoord[code][texCount++] = mesh->verMain[j]->tx[k]; texCoord[code][texCount++] = mesh->verMain[j]->ty[k]; } } verCoordCount[code] = coordCount; texCoordCount[code] = texCount; if (coordCount > MAX_COORDINATE_COUNT) { LOGI("!!!stub!"); } } setColRow(); } void PESBinFile::setColRow() { subWidth = sub_video_size[2].width;// CIF_COL subHeight = sub_video_size[2].height;// CIF_ROW switch (model_type) { case PE_B: subWidth = sub_video_size[0].width;// QCIF_COL subHeight = sub_video_size[0].height;// QCIF_ROW break; case PE_M: switch (sub_model_type) { case 0: subWidth = sub_video_size[0].width;// QCIF_COL subHeight = sub_video_size[0].height;// QCIF_ROW break; } break; } } void PESBinFile::flip() { for (int i = 0; i < camCount; i++) { int code = index[i]; PESBinMesh * mesh = meshes[code]; for (int j = 0; j < MAX_COORDINATE_COUNT; j++) { if (j % 3 == 2) { verCoord[code][j] = -verCoord[code][j]; } } } }<file_sep>/app/src/main/cpp/PES/PESPano.h // // Created by tir on 2016/9/1. // #ifndef PANO_PESPANO_H #define PANO_PESPANO_H #include "../Common.h" #include "PESBinFile.h" #include "PESDecoder.h" class PESPano { public: int decoderCount; float totalDuration; PESDecoder *decoders[MAX_CAMERA_COUNT] = {0}; PESBinFile *binFile; PESPano(); ~PESPano(); bool setPano(char * filename); void run(); float jumpToTimeline(); void awakeDecoders(); void resume(); void pause(); void stop(); bool setStreamType(int type); void decodeFrameRateStep(); int getDecodeFrameRate(); void setPESTask(char * filename, int code,int * doneThreadCountPtr, int * successCountPtr); private: int decodeFrameRate; pthread_mutex_t mutex; pthread_mutex_t threadMutex; pthread_t thread[MAX_CAMERA_COUNT]; bool setPES(char * filename, int code); }; #endif //PANO_PESPANO_H <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/Pano.java package panoeye.pelibrary; /** * Created by Administrator on 2017/12/13. */ public class Pano { PEBinFile binFile ;//bin文件 // int camCount;//镜头模组个数 Float minDuration = 0f;//pes文件第一个I帧到最后一帧之间的最小时间间隔,单位为秒。 // Pano(String name)throws PEError { //// PERPano pano = new PERPano(name); //// PESPano pano = new PESPano(name); // } } <file_sep>/app/src/main/cpp/include/xrapi/XrApiHelpers.h // // Created by SVR00003 on 2017/9/19. // #ifndef XRSDK_XRAPIHELPERS_H #define XRSDK_XRAPIHELPERS_H #include "math.h" // for cosf(), sinf(), tanf() #include "string.h" // for memset() #include "XrApiConfig.h" #include "XrApiVersion.h" #include "XrApiTypes.h" #include <XrLogUtils.h> #define XRAPI_PI 3.14159265358979323846f #define XRAPI_ZNEAR 0.1f #if defined( __GNUC__ ) # define XRAPI_UNUSED(a) do {__typeof__ (&a) __attribute__ ((unused)) __tmp = &a; } while(0) #else # define XRAPI_UNUSED(a) (a) #endif //----------------------------------------------------------------- // Matrix helper functions. //----------------------------------------------------------------- // Use left-multiplication to accumulate transformations. static inline xrMatrix4f xrMatrix4f_Multiply( const xrMatrix4f * a, const xrMatrix4f * b ) { xrMatrix4f out; out.M[0][0] = a->M[0][0] * b->M[0][0] + a->M[0][1] * b->M[1][0] + a->M[0][2] * b->M[2][0] + a->M[0][3] * b->M[3][0]; out.M[1][0] = a->M[1][0] * b->M[0][0] + a->M[1][1] * b->M[1][0] + a->M[1][2] * b->M[2][0] + a->M[1][3] * b->M[3][0]; out.M[2][0] = a->M[2][0] * b->M[0][0] + a->M[2][1] * b->M[1][0] + a->M[2][2] * b->M[2][0] + a->M[2][3] * b->M[3][0]; out.M[3][0] = a->M[3][0] * b->M[0][0] + a->M[3][1] * b->M[1][0] + a->M[3][2] * b->M[2][0] + a->M[3][3] * b->M[3][0]; out.M[0][1] = a->M[0][0] * b->M[0][1] + a->M[0][1] * b->M[1][1] + a->M[0][2] * b->M[2][1] + a->M[0][3] * b->M[3][1]; out.M[1][1] = a->M[1][0] * b->M[0][1] + a->M[1][1] * b->M[1][1] + a->M[1][2] * b->M[2][1] + a->M[1][3] * b->M[3][1]; out.M[2][1] = a->M[2][0] * b->M[0][1] + a->M[2][1] * b->M[1][1] + a->M[2][2] * b->M[2][1] + a->M[2][3] * b->M[3][1]; out.M[3][1] = a->M[3][0] * b->M[0][1] + a->M[3][1] * b->M[1][1] + a->M[3][2] * b->M[2][1] + a->M[3][3] * b->M[3][1]; out.M[0][2] = a->M[0][0] * b->M[0][2] + a->M[0][1] * b->M[1][2] + a->M[0][2] * b->M[2][2] + a->M[0][3] * b->M[3][2]; out.M[1][2] = a->M[1][0] * b->M[0][2] + a->M[1][1] * b->M[1][2] + a->M[1][2] * b->M[2][2] + a->M[1][3] * b->M[3][2]; out.M[2][2] = a->M[2][0] * b->M[0][2] + a->M[2][1] * b->M[1][2] + a->M[2][2] * b->M[2][2] + a->M[2][3] * b->M[3][2]; out.M[3][2] = a->M[3][0] * b->M[0][2] + a->M[3][1] * b->M[1][2] + a->M[3][2] * b->M[2][2] + a->M[3][3] * b->M[3][2]; out.M[0][3] = a->M[0][0] * b->M[0][3] + a->M[0][1] * b->M[1][3] + a->M[0][2] * b->M[2][3] + a->M[0][3] * b->M[3][3]; out.M[1][3] = a->M[1][0] * b->M[0][3] + a->M[1][1] * b->M[1][3] + a->M[1][2] * b->M[2][3] + a->M[1][3] * b->M[3][3]; out.M[2][3] = a->M[2][0] * b->M[0][3] + a->M[2][1] * b->M[1][3] + a->M[2][2] * b->M[2][3] + a->M[2][3] * b->M[3][3]; out.M[3][3] = a->M[3][0] * b->M[0][3] + a->M[3][1] * b->M[1][3] + a->M[3][2] * b->M[2][3] + a->M[3][3] * b->M[3][3]; return out; } // Returns the transpose of a 4x4 matrix. static inline xrMatrix4f xrMatrix4f_Transpose( const xrMatrix4f * a ) { xrMatrix4f out; out.M[0][0] = a->M[0][0]; out.M[0][1] = a->M[1][0]; out.M[0][2] = a->M[2][0]; out.M[0][3] = a->M[3][0]; out.M[1][0] = a->M[0][1]; out.M[1][1] = a->M[1][1]; out.M[1][2] = a->M[2][1]; out.M[1][3] = a->M[3][1]; out.M[2][0] = a->M[0][2]; out.M[2][1] = a->M[1][2]; out.M[2][2] = a->M[2][2]; out.M[2][3] = a->M[3][2]; out.M[3][0] = a->M[0][3]; out.M[3][1] = a->M[1][3]; out.M[3][2] = a->M[2][3]; out.M[3][3] = a->M[3][3]; return out; } // Returns a 3x3 minor of a 4x4 matrix. static inline float xrMatrix4f_Minor( const xrMatrix4f * m, int r0, int r1, int r2, int c0, int c1, int c2 ) { return m->M[r0][c0] * ( m->M[r1][c1] * m->M[r2][c2] - m->M[r2][c1] * m->M[r1][c2] ) - m->M[r0][c1] * ( m->M[r1][c0] * m->M[r2][c2] - m->M[r2][c0] * m->M[r1][c2] ) + m->M[r0][c2] * ( m->M[r1][c0] * m->M[r2][c1] - m->M[r2][c0] * m->M[r1][c1] ); } // Returns the inverse of a 4x4 matrix. static inline xrMatrix4f xrMatrix4f_Inverse( const xrMatrix4f * m ) { const float rcpDet = 1.0f / ( m->M[0][0] * xrMatrix4f_Minor( m, 1, 2, 3, 1, 2, 3 ) - m->M[0][1] * xrMatrix4f_Minor( m, 1, 2, 3, 0, 2, 3 ) + m->M[0][2] * xrMatrix4f_Minor( m, 1, 2, 3, 0, 1, 3 ) - m->M[0][3] * xrMatrix4f_Minor( m, 1, 2, 3, 0, 1, 2 ) ); xrMatrix4f out; out.M[0][0] = xrMatrix4f_Minor( m, 1, 2, 3, 1, 2, 3 ) * rcpDet; out.M[0][1] = -xrMatrix4f_Minor( m, 0, 2, 3, 1, 2, 3 ) * rcpDet; out.M[0][2] = xrMatrix4f_Minor( m, 0, 1, 3, 1, 2, 3 ) * rcpDet; out.M[0][3] = -xrMatrix4f_Minor( m, 0, 1, 2, 1, 2, 3 ) * rcpDet; out.M[1][0] = -xrMatrix4f_Minor( m, 1, 2, 3, 0, 2, 3 ) * rcpDet; out.M[1][1] = xrMatrix4f_Minor( m, 0, 2, 3, 0, 2, 3 ) * rcpDet; out.M[1][2] = -xrMatrix4f_Minor( m, 0, 1, 3, 0, 2, 3 ) * rcpDet; out.M[1][3] = xrMatrix4f_Minor( m, 0, 1, 2, 0, 2, 3 ) * rcpDet; out.M[2][0] = xrMatrix4f_Minor( m, 1, 2, 3, 0, 1, 3 ) * rcpDet; out.M[2][1] = -xrMatrix4f_Minor( m, 0, 2, 3, 0, 1, 3 ) * rcpDet; out.M[2][2] = xrMatrix4f_Minor( m, 0, 1, 3, 0, 1, 3 ) * rcpDet; out.M[2][3] = -xrMatrix4f_Minor( m, 0, 1, 2, 0, 1, 3 ) * rcpDet; out.M[3][0] = -xrMatrix4f_Minor( m, 1, 2, 3, 0, 1, 2 ) * rcpDet; out.M[3][1] = xrMatrix4f_Minor( m, 0, 2, 3, 0, 1, 2 ) * rcpDet; out.M[3][2] = -xrMatrix4f_Minor( m, 0, 1, 3, 0, 1, 2 ) * rcpDet; out.M[3][3] = xrMatrix4f_Minor( m, 0, 1, 2, 0, 1, 2 ) * rcpDet; return out; } // Returns a 4x4 identity matrix. static inline xrMatrix4f xrMatrix4f_CreateIdentity() { xrMatrix4f out; out.M[0][0] = 1.0f; out.M[0][1] = 0.0f; out.M[0][2] = 0.0f; out.M[0][3] = 0.0f; out.M[1][0] = 0.0f; out.M[1][1] = 1.0f; out.M[1][2] = 0.0f; out.M[1][3] = 0.0f; out.M[2][0] = 0.0f; out.M[2][1] = 0.0f; out.M[2][2] = 1.0f; out.M[2][3] = 0.0f; out.M[3][0] = 0.0f; out.M[3][1] = 0.0f; out.M[3][2] = 0.0f; out.M[3][3] = 1.0f; return out; } // Returns a 4x4 homogeneous translation matrix. static inline xrMatrix4f xrMatrix4f_CreateTranslation( const float x, const float y, const float z ) { xrMatrix4f out; out.M[0][0] = 1.0f; out.M[0][1] = 0.0f; out.M[0][2] = 0.0f; out.M[0][3] = x; out.M[1][0] = 0.0f; out.M[1][1] = 1.0f; out.M[1][2] = 0.0f; out.M[1][3] = y; out.M[2][0] = 0.0f; out.M[2][1] = 0.0f; out.M[2][2] = 1.0f; out.M[2][3] = z; out.M[3][0] = 0.0f; out.M[3][1] = 0.0f; out.M[3][2] = 0.0f; out.M[3][3] = 1.0f; return out; } // Returns a 4x4 homogeneous rotation matrix. static inline xrMatrix4f xrMatrix4f_CreateRotation( const float radiansX, const float radiansY, const float radiansZ ) { const float sinX = sinf( radiansX ); const float cosX = cosf( radiansX ); const xrMatrix4f rotationX = { { { 1, 0, 0, 0 }, { 0, cosX, -sinX, 0 }, { 0, sinX, cosX, 0 }, { 0, 0, 0, 1 } } }; const float sinY = sinf( radiansY ); const float cosY = cosf( radiansY ); const xrMatrix4f rotationY = { { { cosY, 0, sinY, 0 }, { 0, 1, 0, 0 }, { -sinY, 0, cosY, 0 }, { 0, 0, 0, 1 } } }; const float sinZ = sinf( radiansZ ); const float cosZ = cosf( radiansZ ); const xrMatrix4f rotationZ = { { { cosZ, -sinZ, 0, 0 }, { sinZ, cosZ, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } } }; const xrMatrix4f rotationXY = xrMatrix4f_Multiply( &rotationY, &rotationX ); return xrMatrix4f_Multiply( &rotationZ, &rotationXY ); } // Returns a projection matrix based on the specified dimensions. // The projection matrix transforms -Z=forward, +Y=up, +X=right to the appropriate clip space for the graphics API. // The far plane is placed at infinity if farZ <= nearZ. // An infinite projection matrix is preferred for rasterization because, except for // things *right* up against the near plane, it always provides better precision: // "Tightening the Precision of Perspective Rendering" // <NAME>, <NAME> // Journal of Graphics Tools, Volume 16, Issue 1, 2012 static inline xrMatrix4f xrMatrix4f_CreateProjection( const float minX, const float maxX, float const minY, const float maxY, const float nearZ, const float farZ ) { const float width = maxX - minX; const float height = maxY - minY; const float offsetZ = nearZ; // set to zero for a [0,1] clip space xrMatrix4f out; if ( farZ <= nearZ ) { // place the far plane at infinity out.M[0][0] = 2 * nearZ / width; out.M[0][1] = 0; out.M[0][2] = ( maxX + minX ) / width; out.M[0][3] = 0; out.M[1][0] = 0; out.M[1][1] = 2 * nearZ / height; out.M[1][2] = ( maxY + minY ) / height; out.M[1][3] = 0; out.M[2][0] = 0; out.M[2][1] = 0; out.M[2][2] = -1; out.M[2][3] = -( nearZ + offsetZ ); out.M[3][0] = 0; out.M[3][1] = 0; out.M[3][2] = -1; out.M[3][3] = 0; } else { // normal projection out.M[0][0] = 2 * nearZ / width; out.M[0][1] = 0; out.M[0][2] = ( maxX + minX ) / width; out.M[0][3] = 0; out.M[1][0] = 0; out.M[1][1] = 2 * nearZ / height; out.M[1][2] = ( maxY + minY ) / height; out.M[1][3] = 0; out.M[2][0] = 0; out.M[2][1] = 0; out.M[2][2] = -( farZ + offsetZ ) / ( farZ - nearZ ); out.M[2][3] = -( farZ * ( nearZ + offsetZ ) ) / ( farZ - nearZ ); out.M[3][0] = 0; out.M[3][1] = 0; out.M[3][2] = -1; out.M[3][3] = 0; } return out; } // Returns a projection matrix based on the given FOV. static inline xrMatrix4f xrMatrix4f_CreateProjectionFov( const float fovDegreesX, const float fovDegreesY, const float offsetX, const float offsetY, const float nearZ, const float farZ ) { const float halfWidth = nearZ * tanf( fovDegreesX * ( XRAPI_PI / 180.0f * 0.5f ) ); const float halfHeight = nearZ * tanf( fovDegreesY * ( XRAPI_PI / 180.0f * 0.5f ) ); const float minX = offsetX - halfWidth; const float maxX = offsetX + halfWidth; const float minY = offsetY - halfHeight; const float maxY = offsetY + halfHeight; return xrMatrix4f_CreateProjection( minX, maxX, minY, maxY, nearZ, farZ ); } // Returns the 4x4 rotation matrix for the given quaternion. static inline xrMatrix4f xrMatrix4f_CreateFromQuaternion( const xrQuatf * q ) { const float ww = q->w * q->w; const float xx = q->x * q->x; const float yy = q->y * q->y; const float zz = q->z * q->z; xrMatrix4f out; out.M[0][0] = ww + xx - yy - zz; out.M[0][1] = 2 * ( q->x * q->y - q->w * q->z ); out.M[0][2] = 2 * ( q->x * q->z + q->w * q->y ); out.M[0][3] = 0; out.M[1][0] = 2 * ( q->x * q->y + q->w * q->z ); out.M[1][1] = ww - xx + yy - zz; out.M[1][2] = 2 * ( q->y * q->z - q->w * q->x ); out.M[1][3] = 0; out.M[2][0] = 2 * ( q->x * q->z - q->w * q->y ); out.M[2][1] = 2 * ( q->y * q->z + q->w * q->x ); out.M[2][2] = ww - xx - yy + zz; out.M[2][3] = 0; out.M[3][0] = 0; out.M[3][1] = 0; out.M[3][2] = 0; out.M[3][3] = 1; return out; } // Convert a standard projection matrix into a TexCoordsFromTanAngles matrix for // the primary time warp surface. static inline xrMatrix4f xrMatrix4f_TanAngleMatrixFromProjection( const xrMatrix4f * projection ) { /* A projection matrix goes from a view point to NDC, or -1 to 1 space. Scale and bias to convert that to a 0 to 1 space. const xrMatrix3f m = { { { projection->M[0][0], 0.0f, projection->M[0][2] }, { 0.0f, projection->M[1][1], projection->M[1][2] }, { 0.0f, 0.0f, -1.0f } } }; // Note that there is no Y-flip because eye buffers have 0,0 = left-bottom. const xrMatrix3f s = xrMatrix3f_CreateScaling( 0.5f, 0.5f ); const xrMatrix3f t = xrMatrix3f_CreateTranslation( 0.5f, 0.5f ); const xrMatrix3f r0 = xrMatrix3f_Multiply( &s, &m ); const xrMatrix3f r1 = xrMatrix3f_Multiply( &t, &r0 ); return r1; clipZ = ( z * projection[2][2] + projection[2][3] ) / ( projection[3][2] * z ) z = projection[2][3] / ( clipZ * projection[3][2] - projection[2][2] ) z = ( projection[2][3] / projection[3][2] ) / ( clipZ - projection[2][2] / projection[3][2] ) */ const xrMatrix4f tanAngleMatrix = { { { 0.5f * projection->M[0][0], 0.0f, 0.5f * projection->M[0][2] - 0.5f, 0.0f }, { 0.0f, 0.5f * projection->M[1][1], 0.5f * projection->M[1][2] - 0.5f, 0.0f }, { 0.0f, 0.0f, -1.0f, 0.0f }, // Store the values to convert a clip-Z to a linear depth in the unused matrix elements. { projection->M[2][2], projection->M[2][3], projection->M[3][2], 1.0f } } }; return tanAngleMatrix; } // If a simple quad defined as a -1 to 1 XY unit square is transformed to // the camera view with the given modelView matrix, it can alternately be // drawn as a time warp overlay image to take advantage of the full window // resolution, which is usually higher than the eye buffer textures, and // avoids resampling both into the eye buffer, and again to the screen. // This is used for high quality movie screens and user interface planes. // // Note that this is NOT an MVP matrix -- the "projection" is handled // by the distortion process. // // This utility functions converts a model-view matrix that would normally // draw a -1 to 1 unit square to the view into a TexCoordsFromTanAngles matrix // for an overlay surface. // // The resulting z value should be straight ahead distance to the plane. // The x and y values will be pre-multiplied by z for projective texturing. static inline xrMatrix4f xrMatrix4f_TanAngleMatrixFromUnitSquare( const xrMatrix4f * modelView ) { /* // Take the inverse of the view matrix because the view matrix transforms the unit square // from world space into view space, while the matrix needed here is the one that transforms // the unit square from view space to world space. const xrMatrix4f inv = xrMatrix4f_Inverse( modelView ); // This matrix calculates the projection onto the (-1, 1) X and Y axes of the unit square, // of the intersection of the vector (tanX, tanY, -1) with the plane described by the matrix // that transforms the unit square into world space. const xrMatrix3f m = { { { inv.M[0][0] * inv.M[2][3] - inv.M[0][3] * inv.M[2][0], inv.M[0][1] * inv.M[2][3] - inv.M[0][3] * inv.M[2][1], inv.M[0][2] * inv.M[2][3] - inv.M[0][3] * inv.M[2][2] }, { inv.M[1][0] * inv.M[2][3] - inv.M[1][3] * inv.M[2][0], inv.M[1][1] * inv.M[2][3] - inv.M[1][3] * inv.M[2][1], inv.M[1][2] * inv.M[2][3] - inv.M[1][3] * inv.M[2][2] }, { - inv.M[2][0], - inv.M[2][1], - inv.M[2][2] } } }; // Flip the Y because textures have 0,0 = left-top as opposed to left-bottom. const xrMatrix3f f = xrMatrix3f_CreateScaling( 1.0f, -1.0f ); const xrMatrix3f s = xrMatrix3f_CreateScaling( 0.5f, 0.5f ); const xrMatrix3f t = xrMatrix3f_CreateTranslation( 0.5f, 0.5f ); const xrMatrix3f r0 = xrMatrix3f_Multiply( &f, &m ); const xrMatrix3f r1 = xrMatrix3f_Multiply( &s, &r0 ); const xrMatrix3f r2 = xrMatrix3f_Multiply( &t, &r1 ); return r2; */ const xrMatrix4f inv = xrMatrix4f_Inverse( modelView ); const float coef = ( inv.M[2][3] > 0.0f ) ? 1.0f : -1.0f; xrMatrix4f m; m.M[0][0] = ( +0.5f * ( inv.M[0][0] * inv.M[2][3] - inv.M[0][3] * inv.M[2][0] ) - 0.5f * inv.M[2][0] ) * coef; m.M[0][1] = ( +0.5f * ( inv.M[0][1] * inv.M[2][3] - inv.M[0][3] * inv.M[2][1] ) - 0.5f * inv.M[2][1] ) * coef; m.M[0][2] = ( +0.5f * ( inv.M[0][2] * inv.M[2][3] - inv.M[0][3] * inv.M[2][2] ) - 0.5f * inv.M[2][2] ) * coef; m.M[0][3] = 0.0f; m.M[1][0] = ( -0.5f * ( inv.M[1][0] * inv.M[2][3] - inv.M[1][3] * inv.M[2][0] ) - 0.5f * inv.M[2][0] ) * coef; m.M[1][1] = ( -0.5f * ( inv.M[1][1] * inv.M[2][3] - inv.M[1][3] * inv.M[2][1] ) - 0.5f * inv.M[2][1] ) * coef; m.M[1][2] = ( -0.5f * ( inv.M[1][2] * inv.M[2][3] - inv.M[1][3] * inv.M[2][2] ) - 0.5f * inv.M[2][2] ) * coef; m.M[1][3] = 0.0f; m.M[2][0] = ( -inv.M[2][0] ) * coef; m.M[2][1] = ( -inv.M[2][1] ) * coef; m.M[2][2] = ( -inv.M[2][2] ) * coef; m.M[2][3] = 0.0f; m.M[3][0] = 0.0f; m.M[3][1] = 0.0f; m.M[3][2] = 0.0f; m.M[3][3] = 1.0f; return m; } // Convert a standard view matrix into a TexCoordsFromTanAngles matrix for // the looking into a cube map. static inline xrMatrix4f xrMatrix4f_TanAngleMatrixForCubeMap( const xrMatrix4f * viewMatrix ) { xrMatrix4f m = *viewMatrix; // clear translation for ( int i = 0; i < 3; i++ ) { m.M[ i ][ 3 ] = 0.0f; } return xrMatrix4f_Inverse( &m ); } // Utility function to calculate external velocity for smooth stick yaw turning. // To reduce judder in FPS style experiences when the application framerate is // lower than the vsync rate, the rotation from a joypad can be applied to the // view space distorted eye vectors before applying the time warp. static inline xrMatrix4f xrMatrix4f_CalculateExternalVelocity( const xrMatrix4f * viewMatrix, const float yawRadiansPerSecond ) { const float angle = yawRadiansPerSecond * ( -1.0f / 60.0f ); const float sinHalfAngle = sinf( angle * 0.5f ); const float cosHalfAngle = cosf( angle * 0.5f ); // Yaw is always going to be around the world Y axis xrQuatf quat; quat.x = viewMatrix->M[0][1] * sinHalfAngle; quat.y = viewMatrix->M[1][1] * sinHalfAngle; quat.z = viewMatrix->M[2][1] * sinHalfAngle; quat.w = cosHalfAngle; return xrMatrix4f_CreateFromQuaternion( &quat ); } //----------------------------------------------------------------- // Default initialization helper functions. //----------------------------------------------------------------- // Utility function to default initialize the xrInitParms. static inline xrInitParms xrapiDefaultInitParms( const xrJava * java ) { xrInitParms parms; memset( &parms, 0, sizeof( parms ) ); parms.Type = XRAPI_STRUCTURE_TYPE_INIT_PARMS; parms.ProductVersion = XRAPI_PRODUCT_VERSION; parms.MajorVersion = XRAPI_MAJOR_VERSION; parms.MinorVersion = XRAPI_MINOR_VERSION; parms.PatchVersion = XRAPI_PATCH_VERSION; parms.GraphicsAPI = XRAPI_GRAPHICS_API_OPENGL_ES_2; parms.Java = *java; return parms; } // Utility function to default initialize the xrModeParms. static inline xrModeParms xrapiDefaultModeParms( const xrJava * java ) { xrModeParms parms; memset( &parms, 0, sizeof( parms ) ); parms.Type = XRAPI_STRUCTURE_TYPE_MODE_PARMS; parms.Flags |= XRAPI_MODE_FLAG_ALLOW_POWER_SAVE; parms.Flags |= XRAPI_MODE_FLAG_RESET_WINDOW_FULLSCREEN; parms.Java = *java; return parms; } // Utility function to default initialize the xrPerformanceParms. static inline xrPerformanceParms xrapiDefaultPerformanceParms() { xrPerformanceParms parms; parms.CpuLevel = 2; parms.GpuLevel = 2; parms.MainThreadTid = 0; parms.RenderThreadTid = 0; return parms; } typedef enum { XRAPI_FRAME_INIT_DEFAULT, XRAPI_FRAME_INIT_BLACK, XRAPI_FRAME_INIT_BLACK_FLUSH, XRAPI_FRAME_INIT_BLACK_FINAL, XRAPI_FRAME_INIT_LOADING_ICON, XRAPI_FRAME_INIT_LOADING_ICON_FLUSH, XRAPI_FRAME_INIT_MESSAGE, XRAPI_FRAME_INIT_MESSAGE_FLUSH } xrFrameInit; // Utility function to default initialize the xrFrameParms. static inline xrFrameParms xrapiDefaultFrameParms( const xrJava * java, const xrFrameInit init, const double currentTime, xrTextureSwapChain * textureSwapChain ) { const xrMatrix4f projectionMatrix = xrMatrix4f_CreateProjectionFov( 90.0f, 90.0f, 0.0f, 0.0f, 0.1f, 0.0f ); const xrMatrix4f texCoordsFromTanAngles = xrMatrix4f_TanAngleMatrixFromProjection( &projectionMatrix ); xrFrameParms parms; memset( &parms, 0, sizeof( parms ) ); parms.Type = XRAPI_STRUCTURE_TYPE_FRAME_PARMS; for ( int layer = 0; layer < XRAPI_FRAME_LAYER_TYPE_MAX; layer++ ) { parms.Layers[layer].ColorScale = 1.0f; for ( int eye = 0; eye < XRAPI_FRAME_LAYER_EYE_MAX; eye++ ) { parms.Layers[layer].Textures[eye].TexCoordsFromTanAngles = texCoordsFromTanAngles; parms.Layers[layer].Textures[eye].TextureRect.width = 1.0f; parms.Layers[layer].Textures[eye].TextureRect.height = 1.0f; parms.Layers[layer].Textures[eye].HeadPose.Pose.Orientation.w = 1.0f; parms.Layers[layer].Textures[eye].HeadPose.TimeInSeconds = currentTime; } } parms.LayerCount = 1; parms.MinimumVsyncs = 1; parms.ExtraLatencyMode = XRAPI_EXTRA_LATENCY_MODE_OFF; parms.ExternalVelocity.M[0][0] = 1.0f; parms.ExternalVelocity.M[1][1] = 1.0f; parms.ExternalVelocity.M[2][2] = 1.0f; parms.ExternalVelocity.M[3][3] = 1.0f; parms.PerformanceParms = xrapiDefaultPerformanceParms(); parms.Java = *java; parms.Layers[0].SrcBlend = XRAPI_FRAME_LAYER_BLEND_ONE; parms.Layers[0].DstBlend = XRAPI_FRAME_LAYER_BLEND_ZERO; parms.Layers[0].Flags = 0; parms.Layers[1].SrcBlend = XRAPI_FRAME_LAYER_BLEND_SRC_ALPHA; parms.Layers[1].DstBlend = XRAPI_FRAME_LAYER_BLEND_ONE_MINUS_SRC_ALPHA; parms.Layers[1].Flags = 0; switch ( init ) { case XRAPI_FRAME_INIT_DEFAULT: { break; } case XRAPI_FRAME_INIT_BLACK: case XRAPI_FRAME_INIT_BLACK_FLUSH: case XRAPI_FRAME_INIT_BLACK_FINAL: { parms.Flags = XRAPI_FRAME_FLAG_INHIBIT_SRGB_FRAMEBUFFER; for ( int eye = 0; eye < XRAPI_FRAME_LAYER_EYE_MAX; eye++ ) { parms.Layers[0].Textures[eye].ColorTextureSwapChain = (xrTextureSwapChain *)XRAPI_DEFAULT_TEXTURE_SWAPCHAIN_BLACK; } break; } case XRAPI_FRAME_INIT_LOADING_ICON: case XRAPI_FRAME_INIT_LOADING_ICON_FLUSH: { parms.LayerCount = 2; parms.Flags = XRAPI_FRAME_FLAG_INHIBIT_SRGB_FRAMEBUFFER; parms.Layers[1].Flags = XRAPI_FRAME_LAYER_FLAG_SPIN; parms.Layers[1].SpinSpeed = 1.0f; // rotation in radians per second parms.Layers[1].SpinScale = 16.0f; // icon size factor smaller than fullscreen for ( int eye = 0; eye < XRAPI_FRAME_LAYER_EYE_MAX; eye++ ) { parms.Layers[0].Textures[eye].ColorTextureSwapChain = (xrTextureSwapChain *)XRAPI_DEFAULT_TEXTURE_SWAPCHAIN_BLACK; parms.Layers[1].Textures[eye].ColorTextureSwapChain = ( textureSwapChain != NULL ) ? textureSwapChain : (xrTextureSwapChain *)XRAPI_DEFAULT_TEXTURE_SWAPCHAIN_LOADING_ICON; } break; } case XRAPI_FRAME_INIT_MESSAGE: case XRAPI_FRAME_INIT_MESSAGE_FLUSH: { parms.LayerCount = 2; parms.Flags = XRAPI_FRAME_FLAG_INHIBIT_SRGB_FRAMEBUFFER; parms.Layers[1].SpinSpeed = 0.0f; // rotation in radians per second parms.Layers[1].SpinScale = 2.0f; // message size factor smaller than fullscreen for ( int eye = 0; eye < XRAPI_FRAME_LAYER_EYE_MAX; eye++ ) { parms.Layers[0].Textures[eye].ColorTextureSwapChain = (xrTextureSwapChain *)XRAPI_DEFAULT_TEXTURE_SWAPCHAIN_BLACK; parms.Layers[1].Textures[eye].ColorTextureSwapChain = ( textureSwapChain != NULL ) ? textureSwapChain : (xrTextureSwapChain *)XRAPI_DEFAULT_TEXTURE_SWAPCHAIN_LOADING_ICON; } break; } } if ( init == XRAPI_FRAME_INIT_BLACK_FLUSH || init == XRAPI_FRAME_INIT_LOADING_ICON_FLUSH || init == XRAPI_FRAME_INIT_MESSAGE_FLUSH ) { parms.Flags |= XRAPI_FRAME_FLAG_FLUSH; } if ( init == XRAPI_FRAME_INIT_BLACK_FINAL ) { parms.Flags |= XRAPI_FRAME_FLAG_FLUSH | XRAPI_FRAME_FLAG_FINAL; } return parms; } //----------------------------------------------------------------- // Head Model //----------------------------------------------------------------- // Utility function to default initialize the xrHeadModelParms. static inline xrHeadModelParms xrapiDefaultHeadModelParms() { xrHeadModelParms parms; memset( &parms, 0, sizeof( parms ) ); parms.InterpupillaryDistance = 0.0640f; // average interpupillary distance parms.EyeHeight = 1.6750f; // average eye height above the ground when standing parms.HeadModelDepth = 0.0805f; parms.HeadModelHeight = 0.0750f; return parms; } //----------------------------------------------------------------- // Eye view matrix helper functions. //----------------------------------------------------------------- // Apply the head-on-a-stick model if head tracking is not available. static inline xrTracking xrapiApplyHeadModel( const xrHeadModelParms * headModelParms, const xrTracking * tracking ) { if ( ( tracking->Status & XRAPI_TRACKING_STATUS_POSITION_TRACKED ) == 0 ) { // Calculate the head position based on the head orientation using a head-on-a-stick model. const xrHeadModelParms * p = headModelParms; const xrMatrix4f m = xrMatrix4f_CreateFromQuaternion( &tracking->HeadPose.Pose.Orientation ); xrTracking newTracking = *tracking; newTracking.HeadPose.Pose.Position.x = m.M[0][1] * p->HeadModelHeight - m.M[0][2] * p->HeadModelDepth; newTracking.HeadPose.Pose.Position.y = m.M[1][1] * p->HeadModelHeight - m.M[1][2] * p->HeadModelDepth - p->HeadModelHeight;// + p->EyeHeight; newTracking.HeadPose.Pose.Position.z = m.M[2][1] * p->HeadModelHeight - m.M[2][2] * p->HeadModelDepth; return newTracking; } return *tracking; } static inline xrMatrix4f xrapiGetTransformFromPose( const xrPosef * pose ) { const xrMatrix4f rotation = xrMatrix4f_CreateFromQuaternion( &pose->Orientation ); const xrMatrix4f translation = xrMatrix4f_CreateTranslation( pose->Position.x, pose->Position.y, pose->Position.z ); return xrMatrix4f_Multiply( &translation, &rotation ); } static inline xrMatrix4f xrapiGetViewMatrixFromPose( const xrPosef * pose ) { const xrMatrix4f transform = xrapiGetTransformFromPose( pose ); return xrMatrix4f_Inverse( &transform ); } // Utility function to get the eye view matrix based on the center eye view matrix and the IPD. static inline xrMatrix4f xrapiGetEyeViewMatrix( const xrHeadModelParms * headModelParms, const xrMatrix4f * centerEyeViewMatrix, const int eye ) { const float eyeOffset = ( eye ? -0.5f : 0.5f ) * headModelParms->InterpupillaryDistance; const xrMatrix4f eyeOffsetMatrix = xrMatrix4f_CreateTranslation( eyeOffset, 0.0f, 0.0f ); return xrMatrix4f_Multiply( &eyeOffsetMatrix, centerEyeViewMatrix ); } static inline void xrMatrix4f_Log(const char* prefix, const xrMatrix4f mat) { #if defined(LOG_MAT) LOGD("%s:%f %f %f %f,%f %f %f %f,%f %f %f %f,%f %f %f %f,",prefix, mat.M[0][0], mat.M[0][1], mat.M[0][2], mat.M[0][3], mat.M[1][0], mat.M[1][1], mat.M[1][2], mat.M[1][3], mat.M[2][0], mat.M[2][1], mat.M[2][2], mat.M[2][3], mat.M[3][0], mat.M[3][1], mat.M[3][2], mat.M[3][3]); #endif } #endif //XRSDK_XRAPIHELPERS_H <file_sep>/app/CMakeLists.txt cmake_minimum_required(VERSION 3.4.1) add_library( # Sets the name of the library. native-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). src/main/cpp/native-lib.cpp ) find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log ) # TODO ${CMAKE_SOURCE_DIR}:表示 CMakeLists.txt的当前文件夹路径 # TODO ${ANDROID_ABI}:编译时会自动根据 CPU架构去选择相应的库 set(distribution_DIR ${CMAKE_SOURCE_DIR}/src/main/jniLibs) add_library( avcodec-57 SHARED IMPORTED) set_target_properties( avcodec-57 PROPERTIES IMPORTED_LOCATION ${distribution_DIR}/armeabi/libavcodec-57.so ) add_library( avfilter-6 SHARED IMPORTED) set_target_properties( avfilter-6 PROPERTIES IMPORTED_LOCATION ${distribution_DIR}/armeabi/libavfilter-6.so) add_library( avformat-57 SHARED IMPORTED) set_target_properties( avformat-57 PROPERTIES IMPORTED_LOCATION ${distribution_DIR}/armeabi/libavformat-57.so) add_library( avutil-55 SHARED IMPORTED) set_target_properties( avutil-55 PROPERTIES IMPORTED_LOCATION ${distribution_DIR}/armeabi/libavutil-55.so) add_library( swresample-2 SHARED IMPORTED) set_target_properties( swresample-2 PROPERTIES IMPORTED_LOCATION ${distribution_DIR}/armeabi/libswresample-2.so) add_library( swscale-4 SHARED IMPORTED) set_target_properties( swscale-4 PROPERTIES IMPORTED_LOCATION ${distribution_DIR}/armeabi/libswscale-4.so) #add_library( xrapi # SHARED # IMPORTED) #set_target_properties( xrapi # PROPERTIES IMPORTED_LOCATION # ${distribution_DIR}/armeabi/libxrapi.so) # TODO 引入第三方 .h 文件夹 include_directories(src/main/cpp/include/) # TODO 将自己编写的 C/C++源文件与第三方库进行连接 target_link_libraries( native-lib avcodec-57 avfilter-6 avformat-57 avutil-55 swresample-2 swscale-4 # xrapi ${log-lib} ) # TODO 引入连接服务器的c++端源文件 add_library( # 设置库名. JNIServerLib # 设置库类型为动态库. SHARED # 列出所有需要编译的c源文件. src/main/cpp/com_panoeye_pano_JNIServerLib.cpp src/main/cpp/GLManager.cpp src/main/cpp/GLMatrix.cpp src/main/cpp/MainController.cpp src/main/cpp/Online/OnlineDecoder.cpp src/main/cpp/Online/OnlinePano.cpp src/main/cpp/OnlineSDK/CClient/CClient.cpp src/main/cpp/OnlineSDK/CClient/MemoryPool.cpp src/main/cpp/OnlineSDK/CClient/NBSocketClient.cpp src/main/cpp/OnlineSDK/md5/md5.cpp src/main/cpp/OnlineSDK/PEClientSDK/PEClient.cpp src/main/cpp/OnlineSDK/PEClientSDK/PEClientSDK.cpp src/main/cpp/OnlineSDK/SysComm.cpp src/main/cpp/OnlineSDK/XML/tinyxml2.cpp src/main/cpp/OnlineSDK/XML/XmlRpcTX2Util.cpp src/main/cpp/OnlineSDK/XML/XmlRpcTX2Value.cpp src/main/cpp/PER/PERBinFile.cpp src/main/cpp/PER/PERDecoder.cpp src/main/cpp/PER/PERFile.cpp src/main/cpp/PER/PERPackage.cpp src/main/cpp/PER/PERPano.cpp src/main/cpp/PER/zip/ZipLibUtil.cpp src/main/cpp/PES/PESBinFile.cpp src/main/cpp/PES/PESDecoder.cpp src/main/cpp/PES/PESFile.cpp src/main/cpp/PES/PESPano.cpp ) target_link_libraries( # 指定需要链接的目标库. JNIServerLib # 将目标库与log库链接起来 ${log-lib} # 源文件中用到的其他库(以下4个必需). GLESv1_CM GLESv2 mediandk z # 源文件中用到的其他库(以下可选). #c #stdc++ #atomic #log #android #EGL #jnigraphics )<file_sep>/app/src/main/cpp/PER/PERPano.cpp // // Created by tir on 2016/9/29. // #include "PERPano.h" #include "../MainController.h" static void runPerAwakeRunloop(void *arg) { mc->perPano->awakeRunloop(); } PERPano::PERPano() { stoped = false; file = NULL; decoderCount = 0; pthread_mutex_init(&mutex,NULL); pthread_cond_init(&cond, NULL); pthread_mutex_init(&condMutex,NULL); for (int i = 0; i < MAX_CAMERA_COUNT; i++) { decoders[i] = NULL; } } PERPano::~PERPano() { for (int i = 0; i < MAX_CAMERA_COUNT; i++) { if (decoders[i] != NULL) { delete decoders[i]; } } if (file != NULL) { delete file; } } bool PERPano::setPano(char * filename) { file = new PERFile(); char * path = "/storage/emulated/0/Pano/"; char pathname[512] = {0}; strcat(pathname, path); strcat(pathname, filename); if (file->openFile(pathname) == false) { LOGI("PANO: Open PER file faild in %s.", pathname); return false; } LOGI("PANO: Open PER file success in %s.", pathname); int camCount = file->binFile->camCount; if (camCount < MIN_CAMERA_COUNT && camCount > MAX_CAMERA_COUNT) { mc->setErrorMessage("不支持的视频分块数!"); LOGI("PANO: Not avaliable camera count in %d.", camCount); return false; } int width = file->binFile->width; int height = file->binFile->height; for (int i = 0; i < file->binFile->camCount; i++) { int code = file->binFile->index[i]; PERDecoder * decoder = new PERDecoder(); if (decoder->setDecoder(code, width, height) == false) { return false; } decoders[code] = decoder; decoderCount++; } totalDuration = file->recordHead.endTime.time - file->recordHead.startTime.time; return true; } void PERPano::run() { jumpToTimeline(); for (int i = 0; i < decoderCount; i++) { decoders[i]->run(); } pthread_create(&thread, NULL, (void * (*)(void *))&runPerAwakeRunloop, NULL); } float PERPano::jumpToTimeline() { float tl = mc->timeline; float minTS = 1024; LONG minOffset; long dataOffset; for (int i = 0; i < decoderCount; i++) { int code = file->binFile->index[i]; int index = -1; float ts = -1024; for (int j = 1; j < file->indexIndex[code]; j++) { if (file->indexList[code][j].cPDt >= tl) { index = j - 1; ts = file->indexList[code][index].cPDt; dataOffset = file->indexList[code][index].streamPackageOffset; break; } } if (index == -1) { index = file->indexIndex[code] - 1; ts = file->indexList[code][index].cPDt; dataOffset = file->indexList[code][index].streamPackageOffset; } decoders[code]->lastTS = ts; if (ts < minTS) { minTS = ts; minOffset = dataOffset; } } LONG playDataOffset = file->head.streamOffset + minOffset; file->seekTo(playDataOffset); for (int i = 0; i < decoderCount; i++) { decoders[i]->isNeedJump = true; } return minTS; } void PERPano::awakeDecoders() { pthread_cond_signal(&cond); } void PERPano::awakeRunloop() { while (true) { pthread_cond_wait(&cond, &condMutex); //自身等待唤醒 if (stoped) { LOGI("PERPano:awakeRunloop stoped"); break; } for (int i = 0; i < decoderCount; i++) { int code; if (file->setVideoData(&code) == true) { LOGI("PERPano:awakeRunloop唤醒解码线程:%d ", i); pthread_cond_signal(&decoders[code]->cond); //唤醒解码线程 } } if (stoped) { LOGI("PERPano:awakeRunloop break"); break; } } } void PERPano::resume() { for (int i = 0; i < decoderCount; i++) { decoders[i]->resume(); } } void PERPano::pause() { for (int i = 0; i < decoderCount; i++) { decoders[i]->pause(); } } void PERPano::stop() { for (int i = 0; i < decoderCount; i++) { decoders[i]->stop(); } stoped = true; pthread_cond_signal(&cond); } bool PERPano::setStreamType(int type) { int width, height; switch (type) { case STREAM_TYPE_MAIN: width = file->binFile->width; height = file->binFile->height; break; case STREAM_TYPE_SUB: width = file->binFile->subWidth; height = file->binFile->subHeight; break; } for (int i = 0; i < decoderCount; i++) { int code = file->binFile->index[i]; decoders[code]->newWidth = width; decoders[code]->newHeight = height; } file->streamType = type; return true; } void PERPano::decodeFrameRateStep() { pthread_mutex_lock(&mutex); decodeFrameRate++; pthread_mutex_unlock(&mutex); } int PERPano::getDecodeFrameRate() { pthread_mutex_lock(&mutex); int fr = (int)((float)decodeFrameRate / (float)file->binFile->camCount + 0.5); decodeFrameRate = 0; pthread_mutex_unlock(&mutex); return fr; } <file_sep>/app/src/main/cpp/OnlineSDK/XML/XmlRpcTX2Value.cpp #include "XmlRpcTX2Value.h" #include "base64.h" #include <iostream> #include <exception> namespace XmlRpcTX2Value { static const char VALUE_TAG[] = "value"; static const char BOOLEAN_TAG[] = "boolean"; static const char DOUBLE_TAG[] = "double"; static const char INT_TAG[] = "int"; static const char I4_TAG[] = "i4"; static const char STRING_TAG[] = "string"; static const char DATETIME_TAG[] = "dateTime.iso8601"; static const char BASE64_TAG[] = "base64"; static const char ARRAY_TAG[] = "array"; static const char DATA_TAG[] = "data"; static const char STRUCT_TAG[] = "struct"; static const char MEMBER_TAG[] = "member"; static const char NAME_TAG[] = "name"; // Format strings std::string XmlRpcValue::_doubleFormat("%f"); // Clean up void XmlRpcValue::invalidate() { switch (_type) { case TypeString: delete _value.asString; break; case TypeDateTime: delete _value.asTime; break; case TypeBase64: delete _value.asBinary; break; case TypeArray: delete _value.asArray; break; case TypeStruct: delete _value.asStruct; break; default: break; } _type = TypeInvalid; _value.asBinary = 0; } // Type checking void XmlRpcValue::assertTypeOrInvalid(Type t) { if (_type == TypeInvalid) { _type = t; switch (_type) { // Ensure there is a valid value for the type case TypeString: _value.asString = new std::string(); break; case TypeDateTime: _value.asTime = new struct tm(); break; case TypeBase64: _value.asBinary = new BinaryData(); break; case TypeArray: _value.asArray = new ValueArray(); break; case TypeStruct: _value.asStruct = new ValueStruct(); break; default: _value.asBinary = 0; break; } } else if (_type != t) throw std::exception();//"type error" } void XmlRpcValue::assertArray(int size) const { if (_type != TypeArray) throw std::exception();//"type error: expected an array" else if (int(_value.asArray->size()) < size) throw std::exception();//"range error: array index too large" } void XmlRpcValue::assertArray(int size) { if (_type == TypeInvalid) { _type = TypeArray; _value.asArray = new ValueArray(size); } else if (_type == TypeArray) { if (int(_value.asArray->size()) < size) _value.asArray->resize(size); } else throw std::exception();//"type error: expected an array" } void XmlRpcValue::assertStruct() { if (_type == TypeInvalid) { _type = TypeStruct; _value.asStruct = new ValueStruct(); } else if (_type != TypeStruct) throw std::exception();//"type error: expected a struct" } // Operators XmlRpcValue& XmlRpcValue::operator=(XmlRpcValue const& rhs) { if (this != &rhs) { invalidate(); _type = rhs._type; switch (_type) { case TypeBoolean: _value.asBool = rhs._value.asBool; break; case TypeInt: _value.asInt = rhs._value.asInt; break; case TypeDouble: _value.asDouble = rhs._value.asDouble; break; case TypeDateTime: _value.asTime = new struct tm(*rhs._value.asTime); break; case TypeString: _value.asString = new std::string(*rhs._value.asString); break; case TypeBase64: _value.asBinary = new BinaryData(*rhs._value.asBinary); break; case TypeArray: _value.asArray = new ValueArray(*rhs._value.asArray); break; case TypeStruct: _value.asStruct = new ValueStruct(*rhs._value.asStruct); break; default: _value.asBinary = 0; break; } } return *this; } // Predicate for tm equality static bool tmEq(struct tm const& t1, struct tm const& t2) { return t1.tm_sec == t2.tm_sec && t1.tm_min == t2.tm_min && t1.tm_hour == t2.tm_hour && t1.tm_mday == t1.tm_mday && t1.tm_mon == t2.tm_mon && t1.tm_year == t2.tm_year; } bool XmlRpcValue::operator==(XmlRpcValue const& other) const { if (_type != other._type) return false; switch (_type) { case TypeBoolean: return (!_value.asBool && !other._value.asBool) || (_value.asBool && other._value.asBool); case TypeInt: return _value.asInt == other._value.asInt; case TypeDouble: return _value.asDouble == other._value.asDouble; case TypeDateTime: return tmEq(*_value.asTime, *other._value.asTime); case TypeString: return *_value.asString == *other._value.asString; case TypeBase64: return *_value.asBinary == *other._value.asBinary; case TypeArray: return *_value.asArray == *other._value.asArray; // The map<>::operator== requires the definition of value< for kcc case TypeStruct: //return *_value.asStruct == *other._value.asStruct; { if (_value.asStruct->size() != other._value.asStruct->size()) return false; ValueStruct::const_iterator it1 = _value.asStruct->begin(); ValueStruct::const_iterator it2 = other._value.asStruct->begin(); while (it1 != _value.asStruct->end()) { const XmlRpcValue& v1 = it1->second; const XmlRpcValue& v2 = it2->second; if (!(v1 == v2)) return false; it1++; it2++; } return true; } default: break; } return true; // Both invalid values ... } bool XmlRpcValue::operator!=(XmlRpcValue const& other) const { return !(*this == other); } // Works for strings, binary data, arrays, and structs. int XmlRpcValue::size() const { switch (_type) { case TypeString: return int(_value.asString->size()); case TypeBase64: return int(_value.asBinary->size()); case TypeArray: return int(_value.asArray->size()); case TypeStruct: return int(_value.asStruct->size()); default: break; } throw std::exception();//"type error" } // Checks for existence of struct member bool XmlRpcValue::hasMember(const std::string& name) const { return _type == TypeStruct && _value.asStruct->find(name) != _value.asStruct->end(); } // Set the value from xml. The chars at *offset into valueXml // should be the start of a <value> tag. Destroys any existing value. bool XmlRpcValue::fromXml(tinyxml2::XMLElement * value){ invalidate(); try{ typeid(*value); if (std::string(value->Value()) != VALUE_TAG) return false; tinyxml2::XMLElement * type = value->FirstChildElement(); std::string typeTag = type?type->Value():""; bool result = false; if (typeTag == BOOLEAN_TAG) result = boolFromXml(type); else if (typeTag == I4_TAG || typeTag == INT_TAG) result = intFromXml(type); else if (typeTag == DOUBLE_TAG) result = doubleFromXml(type); else if (typeTag.empty() || typeTag == STRING_TAG) result = stringFromXml(type); else if (typeTag == DATETIME_TAG) result = timeFromXml(type); else if (typeTag == BASE64_TAG) result = binaryFromXml(type); else if (typeTag == ARRAY_TAG) result = arrayFromXml(type); else if (typeTag == STRUCT_TAG) result = structFromXml(type); // Watch for empty/blank strings with no <string>tag else { result = stringFromXml(value); } return result; } catch (std::bad_typeid){ return false; } //return true; } // Encode the Value in xml bool XmlRpcValue::toXml(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value){ switch (_type) { case TypeBoolean: return boolToXml(doc, value); case TypeInt: return intToXml(doc, value); case TypeDouble: return doubleToXml(doc, value); case TypeString: return stringToXml(doc, value); case TypeDateTime: return timeToXml(doc, value); case TypeBase64: return binaryToXml(doc, value); case TypeArray: return arrayToXml(doc, value); case TypeStruct: return structToXml(doc, value); default: break; } return false; // Invalid value } // Boolean bool XmlRpcValue::boolFromXml(tinyxml2::XMLElement * value_type) { try{ typeid(*value_type); typeid(*value_type->FirstChild()); std::string ValueStr = value_type->FirstChild()->Value(); _type = TypeBoolean; _value.asBool = (stoi(ValueStr) == 1); } catch (std::bad_typeid){ return false; } return true; } bool XmlRpcValue::boolToXml(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value){ *value = doc->NewElement(VALUE_TAG); tinyxml2::XMLElement * value_type = doc->NewElement(BOOLEAN_TAG); value_type->LinkEndChild(doc->NewText(_value.asBool ? "1" : "0")); (*value)->LinkEndChild(value_type); return true; } // Int bool XmlRpcValue::intFromXml(tinyxml2::XMLElement * value_type) { try{ typeid(*value_type); typeid(*value_type->FirstChild()); std::string ValueStr = value_type->FirstChild()->Value(); _type = TypeInt; _value.asInt = stoi(ValueStr); } catch (std::bad_typeid){ return false; } return true; } bool XmlRpcValue::intToXml(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value){ *value = doc->NewElement(VALUE_TAG); tinyxml2::XMLElement * value_type = doc->NewElement(I4_TAG); value_type->LinkEndChild(doc->NewText(std::to_string(_value.asInt).c_str())); (*value)->LinkEndChild(value_type); return true; } // Double bool XmlRpcValue::doubleFromXml(tinyxml2::XMLElement * value_type) { try{ typeid(*value_type); typeid(*value_type->FirstChild()); std::string ValueStr = value_type->FirstChild()->Value(); _type = TypeDouble; _value.asDouble = stod(ValueStr); } catch (std::bad_typeid){ return false; } return true; } bool XmlRpcValue::doubleToXml(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value){ *value = doc->NewElement(VALUE_TAG); tinyxml2::XMLElement * value_type = doc->NewElement(DOUBLE_TAG); value_type->LinkEndChild(doc->NewText(std::to_string(_value.asDouble).c_str())); (*value)->LinkEndChild(value_type); return true; } // String bool XmlRpcValue::stringFromXml(tinyxml2::XMLElement * value_type) { try{ typeid(*value_type); typeid(*value_type->FirstChild()); std::string ValueStr = value_type->FirstChild()->Value(); _type = TypeString; _value.asString = new std::string(ValueStr); } catch (std::bad_typeid){ _type = TypeString; _value.asString = new std::string(""); return true; } return true; } bool XmlRpcValue::stringToXml(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value){ *value = doc->NewElement(VALUE_TAG); tinyxml2::XMLElement * value_type = doc->NewElement(STRING_TAG); value_type->LinkEndChild(doc->NewText(_value.asString->c_str())); (*value)->LinkEndChild(value_type); return true; } // DateTime (stored as a struct tm) bool XmlRpcValue::timeFromXml(tinyxml2::XMLElement * value_type) { try{ typeid(*value_type); typeid(*value_type->FirstChild()); std::string ValueStr = value_type->FirstChild()->Value(); struct tm t; if (sscanf(ValueStr.c_str(), "%4d%2d%2dT%2d:%2d:%2d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return false; t.tm_isdst = -1; _type = TypeDateTime; _value.asTime = new struct tm(t); } catch (std::bad_typeid){ return false; } return true; } inline std::string to_string(struct tm *t){ char buf[20]; sprintf(buf, "%4d%02d%02dT%02d:%02d:%02d", t->tm_year, t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); buf[sizeof(buf)-1] = 0; return std::string(buf); } bool XmlRpcValue::timeToXml(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value){ *value = doc->NewElement(VALUE_TAG); tinyxml2::XMLElement * value_type = doc->NewElement(DATETIME_TAG); value_type->LinkEndChild(doc->NewText(to_string(_value.asTime).c_str())); (*value)->LinkEndChild(value_type); return true; } // Base64 bool XmlRpcValue::binaryFromXml(tinyxml2::XMLElement * value_type) { try{ typeid(*value_type); typeid(*value_type->FirstChild()); std::string ValueStr = value_type->FirstChild()->Value(); _type = TypeBase64; std::string asString = ValueStr; _value.asBinary = new BinaryData(); // check whether base64 encodings can contain chars xml encodes... // convert from base64 to binary int iostatus = 0; base64<char> decoder; std::back_insert_iterator<BinaryData> ins = std::back_inserter(*(_value.asBinary)); decoder.get(asString.begin(), asString.end(), ins, iostatus); } catch (std::bad_typeid){ return false; } return true; } bool XmlRpcValue::binaryToXml(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value){ // convert to base64 std::vector<char> base64data; int iostatus = 0; base64<char> encoder; std::back_insert_iterator<std::vector<char> > ins = std::back_inserter(base64data); encoder.put(_value.asBinary->begin(), _value.asBinary->end(), ins, iostatus, base64<>::crlf()); // Wrap with xml *value = doc->NewElement(VALUE_TAG); tinyxml2::XMLElement * value_type = doc->NewElement(BASE64_TAG); value_type->LinkEndChild(doc->NewText(base64data.data())); (*value)->LinkEndChild(value_type); return true; } // Array bool XmlRpcValue::arrayFromXml(tinyxml2::XMLElement * value_type) { try{ typeid(*value_type); typeid(*value_type->FirstChildElement(DATA_TAG)); tinyxml2::XMLElement * data = value_type->FirstChildElement(DATA_TAG); _type = TypeArray; _value.asArray = new ValueArray; XmlRpcValue v; tinyxml2::XMLElement * value = data->FirstChildElement(VALUE_TAG); while (value){ if (v.fromXml(value)){ _value.asArray->push_back(v); // copy... }else break; value = value->NextSiblingElement(VALUE_TAG); } } catch (std::bad_typeid){ return false; } return true; } // In general, its preferable to generate the xml of each element of the // array as it is needed rather than glomming up one big string. bool XmlRpcValue::arrayToXml(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value){ *value = doc->NewElement(VALUE_TAG); tinyxml2::XMLElement * array = doc->NewElement(ARRAY_TAG); (*value)->LinkEndChild(array); tinyxml2::XMLElement * data = doc->NewElement(DATA_TAG); array->LinkEndChild(data); int s = int(_value.asArray->size()); for (int i = 0; i < s; ++i){ tinyxml2::XMLElement * value0; if (_value.asArray->at(i).toXml(doc, &value0)){ data->LinkEndChild(value0); } } return true; } bool XmlRpcValue::structFromXml(tinyxml2::XMLElement * value_type) { try{ _type = TypeStruct; _value.asStruct = new ValueStruct; typeid(*value_type); tinyxml2::XMLElement * member = value_type->FirstChildElement(MEMBER_TAG); while (member){ tinyxml2::XMLElement * name = member->FirstChildElement(NAME_TAG); tinyxml2::XMLElement * value = name->NextSiblingElement(VALUE_TAG); typeid(*name); typeid(*name->FirstChild()); std::string asString = name->FirstChild()->Value(); XmlRpcValue val(value); if (!val.valid()) { invalidate(); return false; } const std::pair<const std::string, XmlRpcValue> p(asString, val); _value.asStruct->insert(p); member = member->NextSiblingElement(MEMBER_TAG); } } catch (std::bad_typeid){ invalidate(); return true; } return true; } // In general, its preferable to generate the xml of each element // as it is needed rather than glomming up one big string. bool XmlRpcValue::structToXml(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value){ *value = doc->NewElement(VALUE_TAG); tinyxml2::XMLElement * struct_tag = doc->NewElement(STRUCT_TAG); (*value)->LinkEndChild(struct_tag); ValueStruct::iterator it; for (it = _value.asStruct->begin(); it != _value.asStruct->end(); ++it) { tinyxml2::XMLElement * member = doc->NewElement(MEMBER_TAG); tinyxml2::XMLElement * name = doc->NewElement(NAME_TAG); name->LinkEndChild(doc->NewText(it->first.c_str())); tinyxml2::XMLElement * value0; if (it->second.toXml(doc, &value0)){ member->LinkEndChild(name); member->LinkEndChild(value0); struct_tag->LinkEndChild(member); } } return true; } // Write the value without xml encoding it std::ostream& XmlRpcValue::write(std::ostream& os) const { switch (_type) { default: break; case TypeBoolean: os << _value.asBool; break; case TypeInt: os << _value.asInt; break; case TypeDouble: os << _value.asDouble; break; case TypeString: os << *_value.asString; break; case TypeDateTime: { struct tm* t = _value.asTime; char buf[20]; //sprintf_s(buf, sizeof(buf)-1, "%4d%02d%02dT%02d:%02d:%02d", // t->tm_year, t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); sprintf(buf, "%4d%02d%02dT%02d:%02d:%02d", t->tm_year, t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); buf[sizeof(buf)-1] = 0; os << buf; break; } case TypeBase64: { int iostatus = 0; std::ostreambuf_iterator<char> out(os); base64<char> encoder; encoder.put(_value.asBinary->begin(), _value.asBinary->end(), out, iostatus, base64<>::crlf()); break; } case TypeArray: { int s = int(_value.asArray->size()); os << '{'; for (int i = 0; i<s; ++i) { if (i > 0) os << ','; _value.asArray->at(i).write(os); } os << '}'; break; } case TypeStruct: { os << '['; ValueStruct::const_iterator it; for (it = _value.asStruct->begin(); it != _value.asStruct->end(); ++it) { if (it != _value.asStruct->begin()) os << ','; os << it->first << ':'; it->second.write(os); } os << ']'; break; } } return os; } } // namespace XmlRpc // ostream std::ostream& operator<<(std::ostream& os, XmlRpcTX2Value::XmlRpcValue& v) { // If you want to output in xml format: //return os << v.toXml(); return v.write(os); } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PERModule.java package panoeye.pelibrary; /** * Created by tir on 2016/12/9. * pes文件类 */ class PERModule { // List<Float> timestampList = new ArrayList<>();//时间戳列表 // HashMap<Float, Integer> timestampDict = new HashMap<>();//时间戳-文件指针位置对照表 // List<Float> iFrameList = new ArrayList<>();//I帧列表 // HashMap<Float, Integer> IFrameDict = new HashMap<>();//时间戳-文件指针位置对照表 private Float firstIFrameTimestamp = 0.0f;//第一个I帧时间戳 //设置第一个I帧时间戳 boolean setFirstIFrameTimestamp(Float timestamp) { if (this.firstIFrameTimestamp == 0.0f) { this.firstIFrameTimestamp = timestamp; return true; } else return false; } //取出第一个I帧时间戳 Float getFirstIFrameTimestamp() { return firstIFrameTimestamp; } } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PESFile.java package panoeye.pelibrary; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by tir on 2016/12/9. */ //pes文件类 class PESFile { Float duration = 0.0f;//第一个I帧到最后一帧之间的时间间隔,单位为秒。 private byte x;//帧类型,103代表I帧,97代表P帧。 private Float timestamp;//时间戳 List<ByteBuffer> oneFrameDataList = new ArrayList<>();//数据帧列表 List<Float> timestampList = new ArrayList<>();//时间戳列表 HashMap<Float,Integer> timestampDict = new HashMap<>();//时间戳-文件指针位置对照表 List<Float> IFrame = new ArrayList<>();//I帧列表 Float firstPacketTimestampOffset = 0.0f;//第一个I帧时间戳 // PERFileStatus status = PERFileStatus.closed;//pes文件状态 RandomAccessFile fp;//文件指针 int id; //构造函数 PESFile(String path,int id) throws PEError{ try { //打开视频文件读取到fp中 fp = PEFile.fopen(path); this.id = id; // status = PERFileStatus.opened; PEFile.fseek(fp, Define.SIZE_PES_HEAD, FileSeekFlag.SET);//跳过2000个字节,即从第2001个字节开始读取 buildData(fp);//取出视频数据 }catch (PEError e){ e.gen(PEErrorType.fileReadFailed,"PESFile读取失败"); } } //根据帧编号获取视频包的该帧数据 PESVideoPacket getPESVideoPacket(Integer frameNum){//frameNum==0 timestamp = timestampList.get(frameNum);//5.451 Integer point = timestampDict.get(timestamp);//872824 return new PESVideoPacket(fp,point);//返回一帧数据 } // // 帧编号获取视频包的该帧数据 // ByteBuffer getPEVideoPacket(Integer frameNum){ // return oneFrameDataList.get(frameNum);//返回一帧数据 // } //建立时间戳-帧数据指针位置对照表 void buildData(RandomAccessFile fp)throws PEError { Integer fLength = PEFile.flength(fp); findIFrame(fp);//找到第一个I帧的位置 findFrame(fp);//找到余下所有帧的位置 } //找到第一个I帧的位置 void findIFrame(RandomAccessFile fp)throws PEError{ Integer length; int icount = 0,ecount=0; while (true) { if (PEFile.headEquals(fp)) {//若Head正确 icount++; Integer pointtemp = PEFile.ftell(fp);//读取当前文件指针位置到临时变量//2005//10109 Float timeStamp = PEFile.freadFloat(fp);//读取4个字节到临时变量timeStamp length = PEFile.freadInteger(fp);//读取4个字节到length//8091 PEFile.fseek(fp,4, FileSeekFlag.CUR);//跳4个字节,判断I帧 x = PEFile.freadByte(fp);//读取1个字节到x//0x61(即97)//...//0x67(即103) if( (x & 0x1f)==0x07){//当x=103找到I帧,第一个 timestampList.add(timeStamp);//存储时间戳 timestampDict.put(timeStamp,pointtemp);//时间戳和指针位置 IFrame.add(timeStamp); firstPacketTimestampOffset = timeStamp; PEFile.fseek(fp,-5,FileSeekFlag.CUR);//返回5个字节,回到读取完length的位置 PEFile.fseek(fp,length,FileSeekFlag.CUR);//跳过一帧 // ByteBuffer oneFrameData = PEFile.freadByteBuffer(fp,length);//读取一帧数据到临时变量 // oneFrameDataList.add(oneFrameData);//添加到帧数据列表 break;//跳出循环 } else{//没找到 PEFile.fseek(fp,-5,FileSeekFlag.CUR);//返回5个字节,回到读取完length的位置 PEFile.fseek(fp,length,FileSeekFlag.CUR);//跳过一帧,继续找 } } else ecount++; } } //找到余下所有帧的位置 void findFrame(RandomAccessFile fp)throws PEError{ Integer length; int icount2 = 0,ecount2=0; while (true){ if(PEFile.headEquals(fp)){ icount2++; Integer pointtemp = PEFile.ftell(fp);//读取当前文件指针位置到临时变量 Float timeStamp = PEFile.freadFloat(fp);//保存时间戳到临时变量 length = PEFile.freadInteger(fp);//读取length //如果文件读到了结尾执行if语句体。其中flength()获取文件长度 if(PEFile.flength(fp)<=(PEFile.ftell(fp)+length)){ int ffLength = PEFile.flength(fp); int tell = (PEFile.ftell(fp)); //获取第一个I帧到最后一帧之间的时间间隔 duration = timestampList.get(timestampList.size()-1) - firstPacketTimestampOffset; return; } timestampList.add(timeStamp); timestampDict.put(timeStamp,pointtemp); PEFile.fseek(fp,4, FileSeekFlag.CUR);//跳4个字节,判断I帧 x = PEFile.freadByte(fp); if ((x & 0x1f)==0x07){ IFrame.add(timeStamp); } PEFile.fseek(fp,-5,FileSeekFlag.CUR);//返回5个字节,回到读取完length的位置 PEFile.fseek(fp,length,FileSeekFlag.CUR);//跳过一帧,继续读取 // ByteBuffer oneFrameData = PEFile.freadByteBuffer(fp,length);//读取一帧数据到临时变量 //// oneFrameDataList.add(oneFrameData);//添加到帧数据列表 // RandomAccessFile fpH264 = PEFile.fopenMode(Define.ROOT_PATH+"/h264/"+id+".h264","rw");//打开文件 // // 文件长度,字节数 // long fileLength = 0; // try { // fileLength = fpH264.length(); // // 将写文件指针移到文件尾。 // fpH264.seek(fileLength); // } catch (IOException e) { // e.printStackTrace(); // } // PEFile.fwriteArray(fpH264,oneFrameData); // PEFile.fclose(fpH264);//释放文件 }else ecount2++; } } } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/LockWrap.java package panoeye.pelibrary; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Created by tir on 2016/12/13. */ //锁封装类 class LockWrap<T>{ Lock _lock = new ReentrantLock();//ReentrantLock 重入锁 private T _obj;//模板类对象 //获取T类对象 T get(){ return _obj; } //设置T类对象 void set(T obj){ _obj = obj; } //T类对象上锁 void lock(){ _lock.lock(); } //T类对象上锁:只有当它在调用时是空闲的,才获得锁 boolean tryLock(){ return _lock.tryLock(); } //T类对象解锁 void unlock(){ _lock.unlock(); } //构造函数 LockWrap(T obj){ _obj = obj; } } <file_sep>/app/src/main/cpp/OnlineSDK/PEClientSDK/PEClientSDK.h ////////////////////////////////////////////////////////////////////////// /// COPYRIGHT NOTICE /// Copyright (c) 2013-2020, ����������Ϣ�Ƽ����޹�˾ /// All rights reserved. /// /// @file PEClientSDK.h /// @brief PanoEye PEClientSDK /// /// @version 0.0.1 /// @author <NAME> /// @created 2016/08/16 /// ////////////////////////////////////////////////////////////////////////// #ifndef PECLIENTSDK_PECLIENTSDK_H_ #define PECLIENTSDK_PECLIENTSDK_H_ #include "../type.h" #if (defined(WIN32) || defined(_WIN32_WCE)) #include <Windows.h> #ifdef PECLIENTSDKDLL_EXPORTS #define PE_API __declspec(dllexport) #else #define PE_API __declspec(dllimport) #endif #ifndef WINAPI #define WINAPI __stdcall #endif typedef unsigned __int64 UINT64; typedef __int64 INT64; #elif defined(__linux__) || defined(__APPLE__) //linux #ifdef PECLIENTSDKDLL_EXPORTS #define PE_API __attribute__((visibility("default"))) #else #define PE_API #endif #define WINAPI __stdcall #define IN #define OUT #endif //#define PECLIENTSDKDLL_API PE_API #include "../type.h" #include <time.h> //#ifndef _TM_DEFINED //struct tm { // int tm_sec; /* seconds after the minute - [0,59] */ // int tm_min; /* minutes after the hour - [0,59] */ // int tm_hour; /* hours since midnight - [0,23] */ // int tm_mday; /* day of the month - [1,31] */ // int tm_mon; /* months since January - [0,11] */ // int tm_year; /* years since 1900 */ // int tm_wday; /* days since Sunday - [0,6] */ // int tm_yday; /* days since January 1 - [0,365] */ // int tm_isdst; /* daylight savings time flag */ //}; //#define _TM_DEFINED //#endif /* _TM_DEFINED */ ////////////////////////////////////////////////////////////////////////// // ������� ////////////////////////////////////////////////////////////////////////// #define PE_ERRCODE_BEGIN 0x8000F000 #define PE_ERRCODE_SUCCESS ( 0) //δ֪�¼� #define PE_ERRCODE_FAIL (PE_ERRCODE_BEGIN + 1) //ִ��ʧ�� #define PE_ERRCODE_NOSUPPORT (PE_ERRCODE_BEGIN + 3) //��֧�ָù��� #define PE_ERRCODE_VERIFY (PE_ERRCODE_BEGIN + 4) //��֤���� #define PE_ERRCODE_OUTOFMEM (PE_ERRCODE_BEGIN + 5) //�ڴ���� #define PE_ERRCODE_NOT_FIND (PE_ERRCODE_BEGIN + 7) //δ�ҵ� #define PE_ERRCODE_NULLPOINT (PE_ERRCODE_BEGIN + 9) //��ָ�� #define PE_ERRCODE_PARAM (PE_ERRCODE_BEGIN + 10) //�������� #define PE_ERRCODE_USER_PWD (PE_ERRCODE_BEGIN + 11) //�û������������ #define PE_ERRCODE_NETWORK (PE_ERRCODE_BEGIN + 12) //�豸�����߻�������� #define PE_ERRCODE_TIMEOUT (PE_ERRCODE_BEGIN + 13) ////////////////////////////////////////////////////////////////////////// // �¼�ID ////////////////////////////////////////////////////////////////////////// #define PE_EVENT_BEGIN 100 #define PE_EVENT_UNKNOWN ( -1) //δ֪�¼� #define PE_EVENT_LOGIN_CLOSE (PE_EVENT_BEGIN + 1) //��¼���ӱ��Ͽ� #define PE_EVENT_PREVIEW_CLOSE (PE_EVENT_BEGIN + 2) //Ԥ�����ӱ��Ͽ� #ifndef STRUCT_PE_ENCODER_TYPE_DEFINED #define STRUCT_PE_ENCODER_TYPE_DEFINED 1 typedef enum tag_PE_ENCODER_TYPE { PE_ENCODER_TYPE_UNKNOWN = 0, //δ֪���� PE_ENCODER_TYPE_H264 = 1, //H264���� PE_ENCODER_TYPE_MJPEG = 2, //MJPEG���� PE_ENCODER_TYPE_H264_MAIN = 3, //H264 main profile PE_ENCODER_TYPE_H264_HIGH = 4, //H264 high profile PE_ENCODER_TYPE_G711_ALAW = 5, //G711A�ɱ��� PE_ENCODER_TYPE_G711_ULAW = 6, //G711U�ɱ��� PE_ENCODER_TYPE_RAW_PCM = 7, //PCM���룬�������� }PE_ENCODER_TYPE; #endif #ifndef STRUCT_PE_AVFRAME_DATA_DEFINED #define STRUCT_PE_AVFRAME_DATA_DEFINED 1 //����Ƶ֡ typedef struct tag_PE_AVFRAME_DATA { BYTE byStreamFormat; //1��ʾԭʼ����2��ʾ����� BYTE byESStreamType; //ԭʼ�����ͣ�1��ʾ��Ƶ��2��ʾ��Ƶ BYTE byEncoderType; //�����ʽ,��ֵ��ο�PE_ENCODER_TYPEö�ٶ��� BYTE byFrameType; //����֡����,1��ʾI֡, 2��ʾP֡, 0��ʾδ֪���� WORD wFrameRate; //֡�� WORD wBitRate; //��ǰ���� BYTE byChannel; //ͨ�� DWORD lSequenceId; //����֡��� CHAR *pszData; //���� DWORD lDataLength; //������Ч���� DWORD lImageWidth; //��Ƶ��� DWORD lImageHeight; //��Ƶ�߶� INT64 lTimeStamp; //���ݲɼ�ʱ�������λΪ΢�� }PE_AVFRAME_DATA, *LPPE_AVFRAME_DATA; #endif #ifndef STRUCT_PE_CLIENT_DEFINED #define STRUCT_PE_CLIENT_DEFINED 1 //Ԥ���ӿ� typedef struct tagPE_CLIENT_PREVIEWINFO { LONG lChannel; //ͨ���� DWORD dwStreamType; // �������ͣ�0-��������1-������ DWORD dwLinkMode; // 0��TCP��ʽ BYTE byProtoType; //Ӧ�ò�ȡ��Э�飬0-˽��Э�� BYTE byRes[171]; //���� }PE_CLIENT_PREVIEWINFO, *LPPE_CLIENT_PREVIEWINFO; typedef struct tagPE_CLIENT_FILECOND { LONG lChannel; DWORD dwIsLocked; struct tm struStartTime; struct tm struStopTime; BYTE byRes2[104]; //���� }PE_CLIENT_FILECOND, *LPPE_CLIENT_FILECOND; //¼���ļ����� typedef struct tagPE_CLIENT_FINDDATA { CHAR sFileName[250]; //�ļ��� struct tm struStartTime; //�ļ��Ŀ�ʼʱ�� struct tm struStopTime; //�ļ��Ľ���ʱ�� DWORD dwFileSize; //�ļ��Ĵ�С BYTE byLocked; //1��ʾ���ļ��Ѿ�������,0��ʾ�������ļ� BYTE byRes[41]; //���� }PE_CLIENT_FINDDATA, *LPPE_CLIENT_FINDDATA; typedef struct tagPE_CLIENT_SADPINFO { CHAR sIP[64]; CHAR sUUID[64]; CHAR sDevName[256]; CHAR sSerialNo[64]; BYTE byRes[104]; //���� }PE_CLIENT_SADPINFO, *LPPE_CLIENT_SADPINFO; typedef struct tagPE_CLIENT_SADPINFO_LIST { WORD wSadpNum; // �������豸��Ŀ BYTE byRes[182]; // �����ֽ� PE_CLIENT_SADPINFO struSadpInfo[256]; // ���� }PE_CLIENT_SADPINFO_LIST, *LPPE_CLIENT_SADPINFO_LIST; #endif #ifndef _PE_PTZ_POS_CFG_DEFINED typedef struct tagPE_PTZ_POS_CFG { float fPanPos;//ˮƽ���� float fTiltPos;//��ֱ���� float fZoomPos;//�䱶���� BYTE byRes[172]; }PE_PTZ_POS_CFG, *LPPE_PTZ_POS_CFG; #define _PE_PTZ_POS_CFG_DEFINED #endif #ifndef _PE_PTZ_CMD_DEFINED /**********************��̨�������� begin***********************/ #define PE_IRISCLOSE 0x0102 /**< ��Ȧ�� */ #define PE_IRISOPEN 0x0104 /**< ��Ȧ�� */ #define PE_FOCUSNEAR 0x0202 /**< ���ۼ� */ #define PE_FOCUSFAR 0x0204 /**< Զ�ۼ� */ #define PE_ZOOMTELE 0x0302 /**< ��С */ #define PE_ZOOMWIDE 0x0304 /**< �Ŵ� */ #define PE_TILTUP 0x0402 /**< ���� */ #define PE_TILTDOWN 0x0404 /**< ���� */ #define PE_PANRIGHT 0x0502 /**< ���� */ #define PE_PANLEFT 0x0504 /**< ���� */ #define PE_LEFTUP 0x0702 /**< ���� */ #define PE_LEFTDOWN 0x0704 /**< ���� */ #define PE_RIGHTUP 0x0802 /**< ���� */ #define PE_RIGHTDOWN 0x0804 /**< ���� */ #define PE_BRUSHON 0x0A01 /**< ��ˢ�� */ #define PE_BRUSHOFF 0x0A02 /**< ��ˢ�� */ #define PE_LIGHTON 0x0B01 /**< �ƿ� */ #define PE_LIGHTOFF 0x0B02 /**< �ƹ� */ #define PE_INFRAREDON 0x0C01 /**< ���⿪ */ #define PE_INFRAREDOFF 0x0C02 /**< ����� */ #define PE_HEATON 0x0D01 /**< ���ȿ� */ #define PE_HEATOFF 0x0D02 /**< ���ȹ� */ /**********************��̨�������� end*************************/ #define _PE_PTZ_CMD_DEFINED #endif #ifndef _PE_PLAY_CMD_DEFINED /**********************���ſ������� begin***********************/ #define PE_PLAYPAUSE 0x001 /**< ��ͣ���� */ #define PE_PLAYRESTART 0x002 /**< �ָ����ţ����ָ���ͣǰ���ٶȲ��ţ� */ #define PE_PLAYFAST 0x003 /**< ��� */ #define PE_PLAYSLOW 0x004 /**< ���� */ #define PE_PLAYNORMAL 0x005 /**< �����ٶȲ���*/ #define PE_PLAYSETPOS 0x011 /**< �ı��ļ��طŵĽ��� */ #define PE_PLAYGETPOS 0x012 /**< ��ȡ���ļ��طŵĽ��� */ #define PE_PLAYGETTIME 0x013 /**< ��ȡ��ǰ�Ѿ����ŵ�ʱ��*/ #define PE_PLAYSETTIME 0x014 /**< ������ʱ�䶨λ */ /**********************���ſ������� end*************************/ #define _PE_PLAY_CMD_DEFINED #endif #ifndef _PE_SERVER_CONFIG_CMD_DEFINED /**********************�������������� begin*********************/ #define PE_SET_PTZ_POS 14 #define PE_GET_PTZ_POS 15 /**********************�������������� end***********************/ #define _PE_SERVER_CONFIG_CMD_DEFINED #endif #ifdef __cplusplus extern "C" { #endif #define CONST const #define CALLBACK __stdcall typedef void (CALLBACK *fPERealDataCallBack)(LONG lRealHandle, CONST CHAR * szSerialNo, int nStreamID, LPPE_AVFRAME_DATA lpData, void * pUserData); typedef void (CALLBACK *fPEPlayDataCallBack)(LONG lPlayHandle, CONST CHAR *sServerFileName, int nStreamID, LPPE_AVFRAME_DATA lpData, void * pUserData); typedef void (CALLBACK *fPEExceptionCallBack)(DWORD dwType, LONG lHandle, void *pUserData); PE_API BOOL WINAPI PE_Client_Init(); PE_API BOOL WINAPI PE_Client_Cleanup(); PE_API BOOL WINAPI PE_Client_SetExceptionCallBack(fPEExceptionCallBack cbExceptionCallBack, void* pUserData); PE_API LONG WINAPI PE_Client_Login(CONST CHAR *sDVRIP, WORD wDVRPort, CONST CHAR *sUserName, CONST CHAR *sPassword); PE_API BOOL WINAPI PE_Client_Logout(LONG lUserID); PE_API LONG WINAPI PE_Client_RealPlay(LONG lUserID, LPPE_CLIENT_PREVIEWINFO lpPreviewInfo, fPERealDataCallBack cbRealDataCallBack, void* pUserData); PE_API BOOL WINAPI PE_Client_StopRealPlay(LONG lRealHandle); PE_API LONG WINAPI PE_Client_FindFile(LONG lUserID, LPPE_CLIENT_FILECOND pFindCond); PE_API BOOL WINAPI PE_Client_FindNextFile(LONG lFindHandle, LPPE_CLIENT_FINDDATA lpFindData); PE_API BOOL WINAPI PE_Client_FindClose(LONG lFindHandle); PE_API LONG WINAPI PE_Client_PlayBackByName(LONG lUserID, CONST CHAR *sPlayBackFileName, fPEPlayDataCallBack cbPlayDataCallBack, void* pUserData); PE_API BOOL WINAPI PE_Client_PlayBackControl(LONG lPlayHandle, DWORD dwControlCode, LPVOID lpInBuffer = NULL, DWORD dwInLen = 0, LPVOID lpOutBuffer = NULL, DWORD *lpOutLen = NULL); PE_API BOOL WINAPI PE_Client_StopPlayBack(LONG lPlayHandle); PE_API BOOL WINAPI PE_Client_SetServerConfig(LONG lUserID, DWORD dwCommand, LONG lChannel, LPVOID lpInBuffer, DWORD dwInBufferSize); PE_API BOOL WINAPI PE_Client_GetServerConfig(LONG lUserID, DWORD dwCommand, LONG lChannel, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned); PE_API BOOL WINAPI PE_Client_PTZControl(LONG lRealHandle, DWORD dwPTZCommand, BOOL dwStop, DWORD dwSpeed); PE_API BOOL WINAPI PE_Client_GetSadpInfoList(LONG lUserID, LPPE_CLIENT_SADPINFO_LIST lpSadpInfoList); PE_API LONG WINAPI PE_Client_GetFileByName(LONG lUserID, CONST CHAR *sServerFileName, CONST CHAR *sSavedFileDirectory); PE_API int WINAPI PE_Client_GetDownloadPos(LONG lFileHandle); PE_API BOOL WINAPI PE_Client_StopGetFile(LONG lFileHandle); PE_API LONG WINAPI PE_Client_GetLastError(); PE_API BOOL WINAPI PE_Client_Demux(char *pszData, long lDataLength, LPPE_AVFRAME_DATA *lpData); #ifdef __cplusplus } #endif #endif <file_sep>/app/src/main/cpp/OnlineSDK/md5/md5.h #ifndef MD5_H_ #define MD5_H_ typedef struct tag_MD5_CTX { unsigned int count[2]; unsigned int state[4]; unsigned char buffer[64]; }MD5_CTX; static void MD5Init(MD5_CTX *context); static void MD5Update(MD5_CTX *context,unsigned char *input,unsigned int inputlen); static void MD5Final(MD5_CTX *context,unsigned char digest[16]); static void MD5Transform(unsigned int state[4],unsigned char block[64]); static void MD5Encode(unsigned char *output,unsigned int *input,unsigned int len); static void MD5Decode(unsigned int *output,unsigned char *input,unsigned int len); #endif <file_sep>/app/src/main/java/com/panoeye/peplayer/peonline/RawRenderer.java package com.panoeye.peplayer.peonline; import android.content.Context; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.util.Log; import com.panoeye.peplayer.R; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import panoeye.pelibrary.Define; import panoeye.pelibrary.PEDecodeBuffer; import panoeye.pelibrary.PEError; import panoeye.pelibrary.PEMatrix; import panoeye.pelibrary.PESquare; import panoeye.pelibrary.PEVideoTexture; import panoeye.pelibrary.Shader; /** * Created by Administrator on 2017/11/13. * 渲染器类-->完成实际的绘图动作 * 1-->建立一个OpenGL ES环境 * 2-->定义形状 * 3-->绘图形状 * 4-->应用投影和相机视图 * 5-->添加运动 * 6-->触摸事件响应 */ public class RawRenderer implements GLSurfaceView.Renderer { float[] mModelMatrix = new float[16]; //模型矩阵 float[] mViewMatrix = new float[16]; //视图矩阵 float[] mProjectionMatrix = new float[16];//投影矩阵 private final float[] mMVPMatrix = new float[16];//模型视图投影矩阵 private float[] mRotationMatrix = new float[16];//旋转矩阵 final Float PI = 3.141592f; private int width = 1; private int height = 1; private float fovy;//fovy 是 y 轴的 field of view 值,也就是视角大小。 float[] glRotateXAixs = new float[3]; float[] glRotateYAixs = new float[3]; float[] glRotateZAixs = new float[3]; float[] glTranslate = new float[3]; private static final String TAG = "RawRenderer"; String mVertexShader; // 顶点着色器 String mFragmentShader;// 片段着色器 int mProgram;// 自定义渲染管线着色器程序id PESquare[] squares; int[][] textures; PEDecodeBuffer decodeBuffer; // 既然renderer的代码运行于主界面之外的单独线程中,你必须声明这个公开变量为volatile(挥发物;不稳定的), // 事实上不声明为volatile也可以。 public volatile float mAngle; static final int COORDS_PER_VERTEX = 3; // 设置颜色(海蓝色),分别为red, green, blue 和alpha(透明度)的值 float color[] = { 0.33371875f, 0.76953125f, 0.66665625f, 1.0f }; private int mColorHandle; //指向fragment shader的成员vColor的handle private int mPositionHandle; // 顶点位置属性引用 private int mTexCoordHandle; private int mMVPMatrixHandle;// 总变换矩阵引用 private int tex_y; private int tex_u; private int tex_v; private final int vertexCount = 6; // 顶点数量为4(=12/3) private final int vertexStride = COORDS_PER_VERTEX * 4; // 顶点之间的间距(步幅),其中每个顶点占12(=3*4)bytes public RawRenderer(PEDecodeBuffer decodeBuffer, Context context){ mVertexShader = Shader.readTextFileFromResource(context, R.raw.vertex); mFragmentShader = Shader.readTextFileFromResource(context,R.raw.frag); this.decodeBuffer = decodeBuffer; squares = new PESquare[Define.cameraCount]; textures = new int[Define.cameraCount][3]; for (int i = 0;i<Define.cameraCount;i++){ squares[i]=new PESquare(); } } /** * onSurfaceCreated()方法 * Called once to set up the view's OpenGL ES environment. * 仅调用一次,用于设置view的OpenGLES环境。 */ public void onSurfaceCreated(GL10 unused, EGLConfig config) { initTexture(); useProgram(); // GLES20.glEnable(GLES20.GL_DEPTH_TEST); // GLES20.glDepthFunc(GLES20.GL_LEQUAL); // //GLES20.glEnable(GLES20.GL_BLEND); // GLES20.glEnable(GLES20.GL_TEXTURE_2D); // //GLES20.glEnable(GLES20.GL_CULL_FACE); } /** * onDrawFrame()方法 * Called for each redraw of the view. * 每次View被重绘时被调用。 */ public void onDrawFrame(GL10 unused) { Define.openglFrameRate +=1; glResize(); glDraw(Define.x,Define.y,Define.z); } /** * onSurfaceChanged()方法 * Called if the geometry of the view changes, for example when the device's screen orientation changes. * 如果view的几何形状发生变化了就调用,例如当竖屏变为横屏时。 */ public void onSurfaceChanged(GL10 unused, int width, int height) { //设置视口大小 GLES20.glViewport(0, 0, width, height); //竖屏启动:竖屏:1080*1752;横屏:1920*912; //横屏启动:竖屏:1080*1776;横屏:1920*936。 Log.d(TAG, "onSurfaceChanged: width:"+width+",height:"+height); this.width = width; this.height = height; // float ratio = (float) width / height;//缩小、放大比例 // // 此投影矩阵在onDrawFrame()中将应用到对象的坐标 // // frustumM()函数,对矩阵进行ratio倍投影变换;frustum(截头锥体,视锥)。 // PEMatrix.frustumM(mProjectionMatrix, 0, ratio, -ratio, -1, 1, 3, 7); // //注: 只对你的对象应用一个投影变换一般会导制什么也看不到。通常,你必须也对其应用一个视口变换才能看到东西。 } public void initTexture(){ for (int j = 0;j<Define.cameraCount;j++){ GLES20.glGenTextures(3,textures[j],0); for (int i = 0;i<3;i++){ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,textures[j][i]); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,0); } } } public void useProgram() { mProgram = Shader.buildProgram(mVertexShader, mFragmentShader); GLES20.glUseProgram(mProgram); //获取程序中顶点位置、纹理位置的属性引用 mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition"); mTexCoordHandle = GLES20.glGetAttribLocation(mProgram,"a_texCoord"); //获取程序中总变换矩阵引用 mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); tex_y = GLES20.glGetUniformLocation(mProgram,"SamplerY"); tex_u = GLES20.glGetUniformLocation(mProgram,"SamplerU"); tex_v = GLES20.glGetUniformLocation(mProgram,"SamplerV"); } public void glResize(){ this.fovy = Define.fovy; Float aspect = (new Float(width))/(new Float(height)); Float zNear = 0.1f; Float zFar = 2000.0f; Float top = zNear*(new Float(Math.tan(fovy*PI/180.0))); Float bottom = -top; Float left = bottom * aspect; Float right = top * aspect; // Log.d(TAG, "glResize: top:"+top+",bottom:"+bottom+";left:"+left+",right:"+right); PEMatrix.frustum(mProjectionMatrix,left,right,bottom,top,zNear,zFar);//缩放 // // PEMatrix.setLookAtM()函数,设置相机(即观测点)的位置(视图矩阵) // PEMatrix.setLookAtM(mViewMatrix, 0, 0, 0, -3, 0f, 0f, 0f, 0f, 1.0f, 0.0f); // // 计算投影和视图变换 // // PEMatrix.multiplyMM()函数,对矩阵进行乘法运算(mMVPMatrix = mProjectionMatrix * mViewMatrix)。 // PEMatrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0); // //PEMatrix.setRotateM()函数,设置旋转矩阵。 // PEMatrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f); // // // 合并旋转矩阵到投影和相机视图矩阵 // PEMatrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix, 0, mMVPMatrix, 0); } public void glDraw(float x,float y,float z) { // 传入计算出的变换矩阵 //清除深度缓冲与颜色缓冲 GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); GLES20.glClearColor(0.8f,0.8f,0.8f,1.0f); // if (Define.isStretch == false){ float dx =x/150; float dy =y/120; // float zd =(float)(z/180*PI); // float zp = 0; // if (Define.isInBall == true){ // zp = 0; // }else { // zp = -450; // } PEMatrix.makeVec3(glTranslate, dx, -dy,0); PEMatrix.makeUnit(mModelMatrix); PEMatrix.translate(mModelMatrix, glTranslate);//平移 // PEMatrix.rotate(mModelMatrix,yd,glRotateXAxis); // PEMatrix.rotate(mModelMatrix,-xd,glRotateZAxis); // float[] rollAxis = {(float)Math.sin(-xd),(float)Math.cos(-xd),0}; // PEMatrix.rotate(mModelMatrix,-zd,rollAxis); // }else { // PEMatrix.makeVec3(glTranslate, x, -y,-400); // PEMatrix.makeUnit(mModelMatrix); // PEMatrix.translate(mModelMatrix, glTranslate); // } PEMatrix.calMulti(mMVPMatrix, mProjectionMatrix, mModelMatrix); // // 获取指向fragment shader的成员vColor的handle // mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor"); // // 设置三角形的颜色 // GLES20.glUniform4fv(mColorHandle, 1, color, 0); // 将投影和视口变换传递给着色器shader GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0); // int count = 2; // if (Define.isHalfBall == false){ // count = 2; // } for (int i = 0 ;i<Define.cameraCount;i++){ if (Define.cameraCount == 5){ squares[i].mVertexBuffer5.position(18*i); }else if (Define.cameraCount == 8){ squares[i].mVertexBuffer8.position(18*i); }else { squares[i].mVertexBuffer.position(18*i); } do { if (textures[i] == null){ Log.e(TAG, "glDraw:textures[i]: == null "); } if (decodeBuffer == null){ Log.e(TAG, "glDraw:decodeBuffer: == null "); } try { decodeBuffer.undateIfNeed(i,textures[i]); } catch (PEError peError) { peError.printStackTrace(); } // FEVideoTexture videoTexture = decodeBuffer[i].texture; PEVideoTexture videoTexture = null;//得到PEVideoTexture类对象 try { videoTexture = (PEVideoTexture)decodeBuffer.textureDict.get(i); } catch (PEError peError) { peError.printStackTrace(); } if (videoTexture == null){ break; } GLES20.glActiveTexture(GLES20.GL_TEXTURE0); videoTexture.bindTextureY(); GLES20.glUniform1i(tex_y, 0); GLES20.glActiveTexture(GLES20.GL_TEXTURE1); videoTexture.bindTextureU(); GLES20.glUniform1i(tex_u, 1); GLES20.glActiveTexture(GLES20.GL_TEXTURE2); videoTexture.bindTextureV(); GLES20.glUniform1i(tex_v, 2); // 允许顶点位置数据数组 GLES20.glEnableVertexAttribArray(mPositionHandle); GLES20.glEnableVertexAttribArray(mTexCoordHandle); // 指定顶点位置数据 // if (Define.isStretch ==false){ //// GLES20.glVertexAttribPointer(mPositionHandle, 3, GLES20.GL_FLOAT, false, 0, ball[i].mVertexBuffer); // }else { // if (Define.isFlip == false){ //// GLES20.glVertexAttribPointer(maPositionHandle, 2, GLES20.GL_FLOAT, false, 0, ball[i].vertexStretch); // }else { //// GLES20.glVertexAttribPointer(maPositionHandle, 2, GLES20.GL_FLOAT, false, 0, ball[i].vertexStretchFlip); // } // } //GLES20.glVertexAttribPointer(mTexCoordHandle,2,GLES20.GL_FLOAT,false,0,ball[i].mTextureBuffer); if (Define.cameraCount == 5){ GLES20.glVertexAttribPointer(mPositionHandle, 3, GLES20.GL_FLOAT, false, vertexStride, squares[i].mVertexBuffer5); GLES20.glVertexAttribPointer(mTexCoordHandle,2,GLES20.GL_FLOAT,false,0,squares[i].mTextureFlipBuffer5); }else if (Define.cameraCount == 8){ GLES20.glVertexAttribPointer(mPositionHandle, 3, GLES20.GL_FLOAT, false, vertexStride, squares[i].mVertexBuffer8); GLES20.glVertexAttribPointer(mTexCoordHandle,2,GLES20.GL_FLOAT,false,0,squares[i].mTextureFlipBuffer8); }else { GLES20.glVertexAttribPointer(mPositionHandle, 3, GLES20.GL_FLOAT, false, vertexStride, squares[i].mVertexBuffer); GLES20.glVertexAttribPointer(mTexCoordHandle,2,GLES20.GL_FLOAT,false,0,squares[i].mTextureBuffer); // GLES20.glVertexAttribPointer(mTexCoordHandle,2,GLES20.GL_FLOAT,false,0,squares[i].mTextureFlipBuffer); } // 绘制球 //GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, ball[i].vCount); // 绘制三角形// 用 glDrawElements 来绘制矩形,mVertexIndexBuffer 指定了顶点绘制顺序 GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, vertexCount); // GLES20.glDrawElements(GLES20.GL_TRIANGLES, squares[i].drawOrder.length,GLES20.GL_UNSIGNED_SHORT, squares[i].drawListBuffer); // 禁用这个指向三角形的顶点数组(注释无异) // GLES20.glDisableVertexAttribArray(mPositionHandle); // GLES20.glDisableVertexAttribArray(mTexCoordHandle); }while (false); } } public float getAngle() { return mAngle; } public void setAngle(float angle) { mAngle = angle; } } <file_sep>/app/src/main/cpp/OnlineSDK/CClient/NBSocketClient.cpp #if defined(_WINDOWS) # include <stdio.h> //#define FD_SETSIZE 1024 # include <winsock2.h> # pragma comment( lib, "ws2_32.lib" ) #else extern "C" { # include <unistd.h> # include <stdio.h> # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # include <netdb.h> # include <errno.h> # include <fcntl.h> } #endif // _WINDOWS #include "NBSocketClient.h" #include <bitset> #include <iostream> #include <vector> CNBSocketClient::CNBSocketClient() { m_socket = -1; m_isConnected = false; m_send_buff = m_bufferpool.Construct(); m_worker_send_buff = m_bufferpool.Construct(); m_worker_recv_buff = m_bufferpool.Construct(); } CNBSocketClient::~CNBSocketClient() { delete m_send_buff; delete m_worker_send_buff; delete m_worker_recv_buff; } bool CNBSocketClient::Connect(const char *host, USHORT port) { if (m_socket == -1) return false; if (m_isConnected) return true; struct sockaddr_in saddr; memset(&saddr, 0, sizeof(saddr)); saddr.sin_family = AF_INET; struct hostent *hp = gethostbyname(host); if (hp == 0) return false; saddr.sin_family = hp->h_addrtype; memcpy(&saddr.sin_addr, hp->h_addr, hp->h_length); saddr.sin_port = htons((u_short)port); // For asynch operation, this will return EWOULDBLOCK (windows) or // EINPROGRESS (linux) and we just need to wait for the socket to be writable... int result = ::connect(m_socket, (struct sockaddr *)&saddr, sizeof(saddr)); m_isConnected = result == 0 || nonFatalError(); if (m_isConnected){ m_WorkerThread = std::move(std::thread(std::bind(&CNBSocketClient::WorkerThread, this))); } return m_isConnected; } bool CNBSocketClient::Disconnect() { if (m_isConnected){ m_isConnected = false; if (m_WorkerThread.joinable()) m_WorkerThread.join(); } ClientRelease(); ClientAlloc(); return true; } std::string CNBSocketClient::GetHost(){ // std::string HostStream; // struct sockaddr_in saddr; // memset(&saddr, 0, sizeof(saddr)); // int sizeof_saddr = sizeof(saddr); // if (0 == ::getsockname(m_socket, (struct sockaddr *)&saddr, &sizeof_saddr)) // { // char chIP[100]; // char * tmp = inet_ntoa(saddr.sin_addr); // memcpy(chIP, tmp, 100); // HostStream = chIP; // } // // return HostStream; return "127.0.0.1:8080"; } #if defined(_WINDOWS) static void initWinSock() { static bool wsInit = false; if (!wsInit) { WORD wVersionRequested = MAKEWORD(2, 0); WSADATA wsaData; WSAStartup(wVersionRequested, &wsaData); wsInit = true; } } #else #define initWinSock() #endif // _WINDOWS void CNBSocketClient::ClientAlloc() { initWinSock(); m_socket = (int) ::socket(AF_INET, SOCK_STREAM, 0); if (m_socket == -1) return; #if defined(_WINDOWS) unsigned long flag = 1; bool ret = ioctlsocket((SOCKET)m_socket, FIONBIO, &flag) == 0; #else bool ret = fcntl(m_socket, F_SETFL, O_NONBLOCK) == 0; #endif // _WINDOWS } void CNBSocketClient::ClientRelease() { if (m_socket == -1) return; #if defined(_WINDOWS) closesocket(m_socket); #else ::close(m_socket); #endif // _WINDOWS m_socket = -1; } bool CNBSocketClient::Send(const BYTE* pBuffer, int iLength, int iOffset) { if (!m_isConnected) return false; std::lock_guard<std::mutex> lck(m_send_deque_mutex); return iLength == m_send_buff->Cat((LPBYTE)(pBuffer + iOffset), iLength); } bool CNBSocketClient::SendPackets(const WSABUF pBuffers[], int iCount) { if (!m_isConnected) return false; bool ret = true; std::lock_guard<std::mutex> lck(m_send_deque_mutex); for (int i = 0; i < iCount; ++i){ ret &= pBuffers[i].len == m_send_buff->Cat((LPBYTE)(pBuffers[i].buf), pBuffers[i].len); } return ret; } void CNBSocketClient::WorkerThread() { enum EnNBSocketError { NBSE_UNKNOWN, // Unknown NBSE_CONNECT, // Connect NBSE_SEND, // Send NBSE_RECEIVE, // Receive numEnNBSocketError }; std::bitset<numEnNBSocketError> NBSocketError; m_worker_send_buff->Reset(); m_worker_recv_buff->Reset(); while (m_isConnected){ std::unique_lock<std::mutex> lck(m_send_deque_mutex); m_worker_send_buff->Cat(m_send_buff); lck.unlock(); bool eof=false; if (!nbRead(&eof)) NBSocketError.set(NBSE_RECEIVE); if (eof) NBSocketError.set(NBSE_CONNECT); if (!nbWrite()) NBSocketError.set(NBSE_SEND); if (NBSocketError.any()){ OnError(); break; } else{ if (!OnReceive()) break; } //std::this_thread::sleep_for(std::chrono::milliseconds(20)); std::this_thread::yield(); } while (m_isConnected){ std::unique_lock<std::mutex> lck(m_send_deque_mutex); m_worker_send_buff->Reset(); lck.unlock(); } } // Read available text from the specified socket. Returns false on error. bool CNBSocketClient::nbRead(bool *eof) { const int READ_SIZE = 4096; // Number of bytes to attempt to read at a time char readBuf[READ_SIZE]; bool wouldBlock = false; *eof = false; while (!wouldBlock && !*eof) { #if defined(_WINDOWS) int n = recv(m_socket, readBuf, READ_SIZE, 0); #else int n = read(m_socket, readBuf, READ_SIZE); #endif if (n > 0) { m_worker_recv_buff->Cat((LPBYTE)(readBuf), n); } else if (n == 0) { *eof = true; } else if (nonFatalError()) { wouldBlock = true; } else { return false; // Error } } return true; } // Write text to the specified socket. Returns false on error. bool CNBSocketClient::nbWrite() { int nToWrite = m_worker_send_buff->Size(); const int WRITE_SIZE = 4096; // Number of bytes to attempt to read at a time char writeBuf[WRITE_SIZE]; bool wouldBlock = false; while (nToWrite > 0 && !wouldBlock) { int n = m_worker_send_buff->Peek((LPBYTE)(writeBuf), WRITE_SIZE); #if defined(_WINDOWS) n = send(m_socket, writeBuf, n, 0); #else n = write(m_socket, writeBuf, n); #endif if (n > 0) { m_worker_send_buff->Reset(n,nToWrite); nToWrite -= n; } else if (nonFatalError()) { wouldBlock = true; } else { return false; // Error } } return true; } // These errors are not considered fatal for an IO operation; the operation will be re-tried. bool CNBSocketClient::nonFatalError() { int err = CNBSocketClient::getError(); return (err == EINPROGRESS || err == EWOULDBLOCK);//|| err == EAGAIN || err == EINTR } // Returns last errno int CNBSocketClient::getError() { #if defined(_WINDOWS) int ret = WSAGetLastError(); switch (ret) { case WSAEINPROGRESS: return EINPROGRESS; break; case WSAEWOULDBLOCK: return EWOULDBLOCK; break; case WSAETIMEDOUT: return ETIMEDOUT; break; default: return ret; break; } #else return errno; #endif } bool CNBSocketClient::OnReceive() { try { int iLength = m_worker_recv_buff->Size(); const size_t pc_size = PanoComm_Size(); const size_t data_size = sizeof(PE_StreamZeroChanData); PanoComm pc; memset(&pc, 0, sizeof(pc)); while (pc_size == m_worker_recv_buff->Peek((BYTE *)&pc, pc_size)) { if (PanoComm_Check(&pc)) { if (pc.pkgSize > iLength) return true; int msg_type = pc.command; BYTE *msg_buff = new BYTE[pc.pkgSize]; size_t msg_buff_size = pc.pkgSize; BYTE *msg_body = msg_buff + pc_size; size_t msg_body_size = msg_buff_size - pc_size; int ret = m_worker_recv_buff->Fetch(msg_buff, msg_buff_size); if (ret == msg_buff_size) { OnClientReceive(pc, msg_body, msg_body_size); iLength -= msg_buff_size; } else{ //TRACE2("CClient::OnReceive(), FR_LENGTH_TOO_LONG, file: %s, line: %d\n", __FILE__, __LINE__); delete[] msg_buff; return true; } delete[] msg_buff; memset(&pc, 0, sizeof(pc)); } else { BYTE pData; m_worker_recv_buff->Fetch(&pData, 1); } } } catch (std::bad_alloc) { } return true; } void CNBSocketClient::OnError() { OnClientClose(); } <file_sep>/app/src/main/java/com/panoeye/peplayer/peonline/FEDraw.java package com.panoeye.peplayer.peonline; import android.content.Context; import android.opengl.GLSurfaceView; import panoeye.pelibrary.PEBinFile; import panoeye.pelibrary.PEDecodeBuffer; import panoeye.pelibrary.PEError; import panoeye.pelibrary.PERendererOnline; /** * Created by tir on 2017/4/17. */ public class FEDraw { GLSurfaceView view; PEDecodeBuffer decodeBuffer; Context context; PEBinFile binFile; public FEDraw(GLSurfaceView view,PEDecodeBuffer decodeBuffer,Context context){ this.view = view; this.decodeBuffer = decodeBuffer; this.context = context; } public FEDraw(GLSurfaceView view,PEDecodeBuffer decodeBuffer,PEBinFile binFile){ this.view = view; this.decodeBuffer = decodeBuffer; this.binFile = binFile; } public void drawRaw(){ // FERender render = new FERender(decodeBuffer,context); RawRenderer render = new RawRenderer(decodeBuffer,context); view.setEGLContextClientVersion(2); view.setRenderer(render); } public void drawFishEye(){ FERender render = new FERender(decodeBuffer,context); view.setEGLContextClientVersion(2); view.setRenderer(render); } public void drawPano(){ PERendererOnline render = null;//构造渲染器myRenderer // PERendererGain render = null;//构造渲染器myRenderer try { render = new PERendererOnline(binFile,decodeBuffer); // render = new PERendererGain(binFile,decodeBuffer); } catch (PEError peError) { peError.printStackTrace(); } view.setEGLContextClientVersion(2); view.setRenderer(render); } } <file_sep>/app/src/main/cpp/MainController.cpp // // Created by tir on 2016/9/1. // #include "MainController.h" MainController * MainController::instance; MainController* MainController::getInstance() { if (instance == NULL ) instance = new MainController(); return instance; } MainController::MainController() { pesPano = NULL; perPano = NULL; onlinePano = NULL; glm = new GLManager(); panoType = PANO_TYPE_NONE; timeline = 0; surfaceIndex = 0; lastErrorMessage = "No Error."; LOGI("MC: Init."); } void MainController::setErrorMessage(char *msg) { lastErrorMessage = msg; } bool MainController::registPano(char * binFilename, int type) { if (panoType != PANO_TYPE_NONE) { unregistPano(); } panoType = type; timeline = 0; switch (type) { case PANO_TYPE_PES: pesPano = new PESPano(); if (pesPano->setPano(binFilename) == true) { LOGI("MC: Regist PES pano success."); return true; } else { delete pesPano; pesPano = NULL; panoType = -1; LOGI("MC: Regist PES pano failed."); return false; } case PANO_TYPE_PER: perPano = new PERPano(); if (perPano->setPano(binFilename) == true) { LOGI("MC: Regist PER pano success."); return true; } else { delete perPano; perPano = NULL; panoType = -1; LOGI("MC: Regist PER pano failed."); return false; } default: panoType = -1; return false; } } bool MainController::registPano(char *ip, int port, char *username, char *password) { onlinePano = new OnlinePano(); if (onlinePano->login(ip, port, username, password) == true) { panoType = PANO_TYPE_ONLINE; return true; } else { panoType = PANO_TYPE_NONE; delete onlinePano; return false; } } bool MainController::registPanoToGLM() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return false; } else { glm->panoType = panoType; glm->pesPano = pesPano; return true; } case PANO_TYPE_PER: if (perPano == NULL) { return false; } else { glm->panoType = panoType; glm->perPano = perPano; return true; } default: return false; } } void MainController::unregistPano() { switch (panoType) { case PANO_TYPE_PES: if (pesPano != NULL) { pesPano->stop(); glm->glmDeinit(); delete pesPano; } break; case PANO_TYPE_PER: if (perPano != NULL) { perPano->stop(); glm->glmDeinit(); delete perPano; } break; case PANO_TYPE_ONLINE: if (onlinePano != NULL) { onlinePano->logout(); glm->glmDeinit(); delete onlinePano; } break; default: break; } glm->panoType = PANO_TYPE_NONE; glm->pesPano = NULL; glm->perPano = NULL; panoType = PANO_TYPE_NONE; timeline = 0; perPano = NULL; pesPano = NULL; } bool MainController::runPano() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return false; } else { pesPano->run(); return true; } case PANO_TYPE_PER: if (perPano == NULL) { return false; } else { perPano->run(); return true; } default: return false; } } float MainController::jumpPanoToTimeline() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return 0; } else { return pesPano->jumpToTimeline(); } case PANO_TYPE_PER: if (perPano == NULL) { return 0; } else { return perPano->jumpToTimeline(); } default: return 0; } } bool MainController::awakeDecoders() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return false; } else { pesPano->awakeDecoders(); return true; } case PANO_TYPE_PER: if (perPano == NULL) { return false; } else { perPano->awakeDecoders(); return true; } default: return false; } } bool MainController::resumePano() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return false; } else { pesPano->resume(); return true; } case PANO_TYPE_PER: if (perPano == NULL) { return false; } else { perPano->resume(); return true; } default: return false; } } bool MainController::pausePano() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return false; } else { pesPano->pause(); return true; } case PANO_TYPE_PER: if (perPano == NULL) { return false; } else { perPano->pause(); return true; } default: return false; } } bool MainController::stopPano() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return false; } else { pesPano->stop(); return true; } case PANO_TYPE_PER: if (perPano == NULL) { return false; } else { perPano->stop(); return true; } default: return false; } } bool MainController::decodeFrameRateStep() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return false; } else { pesPano->decodeFrameRateStep(); return true; } case PANO_TYPE_PER: if (perPano == NULL) { return false; } else { perPano->decodeFrameRateStep(); return true; } case PANO_TYPE_ONLINE: if (onlinePano == NULL) { return false; } else { onlinePano->decodeFrameRateStep(); return true; } default: return false; } } float MainController::getTotalDuration() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return -1; } else { return pesPano->totalDuration; } case PANO_TYPE_PER: if (perPano == NULL) { return -1; } else { return perPano->totalDuration; } default: return 0; } } int MainController::getDecodeFrameRate() { switch (panoType) { case PANO_TYPE_PES: if (pesPano == NULL) { return 0; } else { return pesPano->getDecodeFrameRate(); } case PANO_TYPE_PER: if (perPano == NULL) { return 0; } else { return perPano->getDecodeFrameRate(); } case PANO_TYPE_ONLINE: if (onlinePano == NULL) { return 0; } else { return onlinePano->getDecodeFrameRate(); } default: return 0; } }<file_sep>/app/src/main/cpp/PES/PESBinFile.h // // Created by tir on 2016/8/30. // #ifndef MEDIACODEC_PESBINFILE_H #define MEDIACODEC_PESBINFILE_H #include "../Common.h" #include <iostream> #define CIF_ROW 288 #define CIF_COL 352 #define D1_ROW 576 #define D1_COL 704 #define QCIF_ROW 144 #define QCIF_COL 176 #define QVGA_ROW 240 #define QVGA_COL 320 struct PESTriCoord { float x[3], y[3]; //cylinder position float tx[3], ty[3]; //texture position float sx[3], sy[3], sz[3]; //sphere position }; struct PESBinMesh { int cid; float lambda; uchar imgData[MAX_ALPHA_IMAGE_SIZE]; int fullCoordCount, subCoordCount; PESTriCoord * verMain[MAX_MESH_COORDINATE_COUNT] = {0}; }; struct PESBinVideoSize { int width; int height; }; class PESBinFile { public: int radius; char binName[64]; int model_type, sub_model_type; PESBinVideoSize sub_video_size[9]; int subWidth, subHeight; int camCount; int width, height; float verCoord[MAX_CAMERA_COUNT][MAX_COORDINATE_COUNT]; float texCoord[MAX_CAMERA_COUNT][MAX_COORDINATE_COUNT]; int verCoordCount[MAX_CAMERA_COUNT] = {0}; int texCoordCount[MAX_CAMERA_COUNT] = {0}; PESBinMesh * meshes[MAX_CAMERA_COUNT] = {0}; int index[MAX_CAMERA_COUNT]; int indexCount; PESBinFile(); ~PESBinFile(); bool openFile(char * filename); void setCoord(); void setColRow(); void flip(); }; #endif //MEDIACODEC_PESBINFILE_H <file_sep>/app/src/main/cpp/PES/PESFile.cpp // // Created by tir on 2016/8/15. // #include "PESFile.h" #include "../MainController.h" PESFile::PESFile() { fp = NULL; status = Closed; timestampIndex = 0; timestampCount = 0; timestampMap.clear(); } PESFile::~PESFile() { closeFile(); } int PESFile::readLength() { int len; fread(&len, SIZE_OF_LENGTH, 1, fp); return len; } float PESFile::readTimeStamp() { float ts; fread(&ts, SIZE_OF_TIME_STAMP, 1, fp); return ts; } bool PESFile::openFile(char *filename) { closeFile(); fp = fopen(filename, "rb"); if (fp == NULL) { mc->setErrorMessage("打开Pes文件失败!"); LOGI("PESFile: Open file faild in %s", filename); status = Closed; return false; } else { status = Opened; if (fseek(fp, SIZE_OF_HEAD, SEEK_SET) != 0) { mc->setErrorMessage("解析Pes文件失败!"); LOGI("PESFile: Pes file seek head faild in %s", filename); } if (findIFrame()) { while(checkData() > 0) ; timestampCount = timestampIndex; timestampIndex = 0; return true; } else { fclose(fp); mc->setErrorMessage("解析Pes文件失败!"); LOGI("PESFile: Can not find I Frame in %s", filename); return false; } } } bool PESFile::findIFrame() { while (true) { if (checkFrameHead()) { if (isIFrame()) { return true; } nextFrame(); } else { return false; } } } bool PESFile::checkFrameHead() { uchar buffer[5]={0}; int len = fread(buffer, 1, SIZE_OF_FRAME_HEAD, fp); if (len != SIZE_OF_FRAME_HEAD) { return false; } if ((buffer[0] == 0x00) && (buffer[1] == 0x00) && (buffer[2] == 0x00) && (buffer[3] == 0x01) && (buffer[4] == 0xFF)) { return true; } else { return false; } } bool PESFile::isIFrame() { bool result; uchar buffer[5] = {0}; readTimeStamp(); readLength(); int len = fread(buffer, 1, SIZE_OF_FRAME_HEAD, fp); if (len == SIZE_OF_FRAME_HEAD) { if ((buffer[0] == 0x00) && (buffer[1] == 0x00) && (buffer[2] == 0x00) && (buffer[3] == 0x01)) { if (((buffer[4] & 0x1F) == 7)) { result = true; } else { result = false; } } else { result = false; } } else { result = false; } //跳回帧头 fseek(fp, -SIZE_OF_FRAME_HEAD, SEEK_CUR); fseek(fp, -SIZE_OF_LENGTH, SEEK_CUR); fseek(fp, -SIZE_OF_TIME_STAMP, SEEK_CUR); fseek(fp, -SIZE_OF_FRAME_HEAD, SEEK_CUR); return result; } void PESFile::nextFrame() { int len; checkFrameHead(); readTimeStamp(); len = readLength(); fseek(fp, len, SEEK_CUR); } void PESFile::closeFile() { if (fp != NULL) { fclose(fp); } status = Closed; timestampMap.clear(); timestampIndex = 0; timestampCount = 0; } int PESFile::checkData() { int fpPos = ftell(fp); if (checkFrameHead()) { float ts = readTimeStamp(); int len = readLength(); tsList[timestampIndex++] = ts; timestampMap[ts] = fpPos; fseek(fp, len, SEEK_CUR); if (feof(fp)) { return -1; } else { return len; } } else { return -1; } } int PESFile::setData(uchar * buffer, int size) { if (status == Opened) { fseek(fp, timestampMap[tsList[timestampIndex++]], SEEK_SET); if (checkFrameHead()) { readTimeStamp(); int len = readLength(); fread(dataBuffer, len, 1, fp); memcpy(buffer, dataBuffer, len); if (feof(fp)) { closeFile(); return -1; } else { return len; } } } return -1; } float PESFile::jumpTo(float ts) { int index = -1; if (tsList[0] > ts) { index = 0; } else { for (int i = 0; i < timestampCount - 1 - 1; i++) { if ((tsList[i] <= ts) && tsList[i + 1] > ts) { index = i; } } if (index == -1) { index = timestampCount - 1; } } while (true) { if (index <= 0) { break; } else { index--; } fseek(fp, timestampMap[tsList[index]], SEEK_SET); fseek(fp, SIZE_OF_FRAME_HEAD, SEEK_CUR); if (isIFrame()) { break; } } timestampIndex = index; return tsList[index]; } <file_sep>/app/src/main/cpp/GLMatrix.h // // Created by tir on 2016/8/26. // #ifndef MEDIACODEC_GLMATRIX_H #define MEDIACODEC_GLMATRIX_H #include <math.h> #include "Common.h" class GLMatrix { public: GLMatrix(); static void mCalMulti(float * result, float * m1, float * m2); static void mMakeVec3(float * result, float x, float y, float z); static void mMakeCopy(float * result, float * source); static void mLogi(float * matrix); static void mMakeUnit(float * matrix); static void mMakeEmpty(float * matrix); static void mTranslate(float * matrix, float * vec3); static void mRotate(float * matrix, float angle, float * vec3); static void mFrustum(float * matrix, float left, float right, float bottom, float top, float zNear, float zFar); private: static int getIndex(int row, int col); }; #endif //MEDIACODEC_GLMATRIX_H <file_sep>/app/src/main/cpp/OnlineSDK/CClient/MemoryPool.h #ifndef CAM360_LIBCAM_CLIENT_MEMORYPOOL_H_ #define CAM360_LIBCAM_CLIENT_MEMORYPOOL_H_ #include <atomic> #include <list> #include <mutex> #include "../type.h" #if defined(_WINDOWS) #include <Windows.h> #else #endif // _WINDOWS typedef struct tag_MEMORY_BLOCK{ DWORD dwBufferSize; LPBYTE lpbyBuffer; int iDataLength; int iDataOffset; }MEMORY_BLOCK, *LPMEMORY_BLOCK; bool MemoryBlock_Construct(DWORD dwBufferSize, LPMEMORY_BLOCK *ppBlock); void MemoryBlock_Destruct(LPMEMORY_BLOCK pBlock); int MemoryBlock_Cat(LPMEMORY_BLOCK pBlock, const LPBYTE pData, int length); int MemoryBlock_Fetch(LPMEMORY_BLOCK pBlock, LPBYTE pData, int length); int MemoryBlock_Peek(LPMEMORY_BLOCK pBlock, LPBYTE pData, int length); class CMemoryPool; class CMemoryItem; class CMemoryPool{ public: CMemoryPool(int buff_size = 4096, int buff_num = 10); ~CMemoryPool(); CMemoryItem* Construct(); private: const int kBufferSize; std::recursive_mutex m_MemoryBlock_list_mutex; std::list<LPMEMORY_BLOCK> m_MemoryBlock_list; std::atomic_llong m_Item_Count; void Destruct(CMemoryItem* pItem); bool GetMemoryBlock(LPMEMORY_BLOCK *block); bool FreeMemoryBlock(LPMEMORY_BLOCK block); friend class CMemoryItem; }; class CMemoryItem{ public: ~CMemoryItem(); int Cat(const LPBYTE pData, int length); int Cat(CMemoryItem* other); int Fetch(LPBYTE pData, int length); int Peek(LPBYTE pData, int length); int Reduce(int length); void Reset(int begin = 0, int end = 0); int Size(); private: CMemoryItem(CMemoryPool* pool) :kMemoryPool(pool){ ; }; std::recursive_mutex m_MemoryBlock_list_mutex; std::list<LPMEMORY_BLOCK> m_MemoryBlock_list; CMemoryPool * kMemoryPool; friend class CMemoryPool; }; #endif <file_sep>/app/src/main/cpp/OnlineSDK/CClient/ClientListener.h #ifndef CAM360_LIBCAM_CLIENT_CLIENTLISTENER_H_ #define CAM360_LIBCAM_CLIENT_CLIENTLISTENER_H_ #include "../PanoDef.h" #include "../type.h" #include <string> struct WSABUF { ULONG len; /* the length of the buffer */ char * buf; /* the pointer to the buffer */ }; class CClientListener { protected: virtual bool OnClientReceive(PanoComm pc, BYTE *msg_body, size_t msg_body_size) = 0; virtual bool OnClientClose() = 0; virtual bool Connect(const char *ipaddr, USHORT port) = 0; virtual bool Disconnect() = 0; virtual std::string GetHost() = 0; virtual void ClientAlloc() = 0; virtual void ClientRelease() = 0; virtual bool Send(const BYTE* pBuffer, int iLength, int iOffset) = 0; virtual bool SendPackets(const WSABUF pBuffers[], int iCount) = 0; }; #endif <file_sep>/app/src/main/cpp/PER/zip/ZipLibUtil.h #ifndef CAM360_LIB_ZIPLIBUTIL_H_ #define CAM360_LIB_ZIPLIBUTIL_H_ //#include <io.h> #include <iostream> #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) # include <fcntl.h> # include <io.h> # define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) #else # define SET_BINARY_MODE(file) #endif #ifndef ZLIB_H /* constants */ #define Z_NO_FLUSH 0 #define Z_PARTIAL_FLUSH 1 #define Z_SYNC_FLUSH 2 #define Z_FULL_FLUSH 3 #define Z_FINISH 4 #define Z_BLOCK 5 #define Z_TREES 6 /* Allowed flush values; see deflate() and inflate() below for details */ #define Z_OK 0 #define Z_STREAM_END 1 #define Z_NEED_DICT 2 #define Z_ERRNO (-1) #define Z_STREAM_ERROR (-2) #define Z_DATA_ERROR (-3) #define Z_MEM_ERROR (-4) #define Z_BUF_ERROR (-5) #define Z_VERSION_ERROR (-6) /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ #define Z_NO_COMPRESSION 0 #define Z_BEST_SPEED 1 #define Z_BEST_COMPRESSION 9 #define Z_DEFAULT_COMPRESSION (-1) /* compression levels */ #define Z_FILTERED 1 #define Z_HUFFMAN_ONLY 2 #define Z_RLE 3 #define Z_FIXED 4 #define Z_DEFAULT_STRATEGY 0 /* compression strategy; see deflateInit2() below for details */ #define Z_BINARY 0 #define Z_TEXT 1 #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ #define Z_UNKNOWN 2 /* Possible values of the data_type field (though see inflate()) */ #define Z_DEFLATED 8 /* The deflate compression method (the only one supported in this version) */ #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ #endif int ExtracMemory2Memory(unsigned char *source, size_t source_size, unsigned char **dest, size_t *dest_size); int ComprssMemory2Memory(unsigned char *source, size_t source_size, unsigned char **dest, size_t *dest_size); int ExtracFile2File(FILE *source, FILE *dest); int ComprssFile2File(FILE *source, FILE *dest); int ExtracMemory2File(unsigned char *source, size_t source_size, FILE *dest); int ComprssFile2Memory(FILE *source, unsigned char **dest, size_t *dest_size); #endif <file_sep>/app/src/main/java/com/panoeye/peplayer/OnlineServiceSettingActivity.java package com.panoeye.peplayer; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Created by tir on 2016/10/5. */ public class OnlineServiceSettingActivity extends AppCompatActivity { TextView ipField, portField; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_onlineservicesetting); ipField = findViewById(R.id.ipField); portField = findViewById(R.id.portField); SharedPreferences sPerfs= PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); ipField.setText(sPerfs.getString("IP", "")); portField.setText(sPerfs.getString("PORT", "")); // ipField.setText("192.168.20.99"); // portField.setText("5555"); // next(null); } public void back(View btn) { this.finish(); } public void next(View btn) { int port = Integer.parseInt(portField.getText().toString()); Intent intent = new Intent(this, OnlineUserSettingActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("IP", ipField.getText().toString()); bundle.putSerializable("PORT", port); intent.putExtras(bundle); SharedPreferences sPerfs= PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = sPerfs.edit(); editor.putString("IP", ipField.getText().toString()); editor.putString("PORT", portField.getText().toString()); editor.commit(); startActivity(intent); } } <file_sep>/app/src/main/java/com/panoeye/peplayer/OnlineListActivity.java package com.panoeye.peplayer; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Timer; import java.util.TimerTask; /** * Created by tir on 2016/10/9. */ public class OnlineListActivity extends AppCompatActivity { private static final String TAG = "OnlineListActivity"; final WeakReference<OnlineListActivity> self = new WeakReference<>(this); private ArrayList<String> fileList = new ArrayList<>(); private ListView listView; ArrayAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate: ~~~"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_onlinelist); listView = findViewById(R.id.listView2); int count = JNIServerLib.getOnlinePanoCamCount(); for (int i = 0; i < count; i++) { String name = "unknow"; try { name = new String(JNIServerLib.getOnlinePanoCamNameWithIndex(i),"GB2312"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } fileList.add(name); } adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, fileList); listView.setAdapter(adapter); listView.setOnItemClickListener(adapterListener); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ disconnect(null); } return false; } public void disconnect(View btn) { new AlertDialog.Builder(this) .setTitle("断开连接") .setMessage("确定要断开连接吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // JNIServerLib.unregistPano(); self.get().finish(); } }) .setNegativeButton("取消", null) .setCancelable(false) .show(); } final private AdapterView.OnItemClickListener adapterListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { final int row = (int) l; Intent intent = new Intent(self.get(), LoadingActivity.class); startActivity(intent); new Thread(new Runnable() { @Override public void run() { while (LoadingActivity.loadingActivity == null) ; LoadingActivity.loadingActivity.startPos(); if (JNIServerLib.registOnlinePanoCamWithIndex(row) == true) { Intent intent = new Intent(self.get(), OnlinePlayActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("NAME", fileList.get(row)); intent.putExtras(bundle); mHandler.sendEmptyMessage(1); startActivity(intent); finish(); } else { mHandler.sendEmptyMessage(2); } } }).start(); } }; final private Handler mHandler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 0 : break; case 1 : LoadingActivity.loadingActivity.close(); break; case 2: LoadingActivity.loadingActivity.close(); new AlertDialog.Builder(self.get()) .setTitle("错误") .setMessage("操作失败!\n不支持的相机或访问存储设备失败。\n可能是由于安全软件禁止访问权限。") .setPositiveButton("确定", null) .setCancelable(false) .show(); default : break; } } }; } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PEVideoTexture.java package panoeye.pelibrary; import android.opengl.GLES20; import java.nio.ByteBuffer; /** * Created by tir on 2016/12/14. * 全景视频纹理类 */ public class PEVideoTexture { private int[] textures; PEVideoTexture(PEFrameBuffer frameBuffer,int[] textures ) { ByteBuffer buffer; ByteBuffer Ybuffer; ByteBuffer Ubuffer; ByteBuffer Vbuffer; Size size; size = frameBuffer.size; buffer = frameBuffer.get();//获取PEFrameBuffer类对象frameBuffer的成员_imgBuffer到ByteBuffer类对象buffer this.textures = textures; Ybuffer = ByteBuffer.allocateDirect(size.height * size.width); Ubuffer = ByteBuffer.allocateDirect(size.height * size.width/4); Vbuffer = ByteBuffer.allocateDirect(size.height * size.width/4); frameBuffer.lock(); buffer.position(0); buffer.limit(size.height * size.width);//1228800 Ybuffer.clear(); Ybuffer.put(buffer); Ybuffer.clear(); buffer.limit(size.height * size.width + size.height * size.width / 4);//1536000 Ubuffer.clear(); Ubuffer.put(buffer); Ubuffer.clear(); buffer.limit(size.height * size.width + size.height * size.width / 2);//1843200 Vbuffer.clear(); Vbuffer.put(buffer); Vbuffer.clear(); frameBuffer.unlock(); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, size.width, size.height, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, Ybuffer); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[1]); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, size.width/2, size.height/2, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, Ubuffer); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[2]); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, size.width/2, size.height/2, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, Vbuffer); } public void bindTextureY() { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]); } public void bindTextureU() { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[1]); } public void bindTextureV() { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[2]); } public void bindTextureA() { GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[3]); } } <file_sep>/app/src/main/cpp/OnlineSDK/PEClientSDK/PEClient.h #ifndef CAM360_PANOCAM_NETCLIENT_HPSOCKET_H_ #define CAM360_PANOCAM_NETCLIENT_HPSOCKET_H_ #include "../CClient/CClient.h" #include "PEClientSDK.h" #include <memory> #include <exception> #include <thread> #include <mutex> #include <functional> class CPEClient : public CClient { public: CPEClient(); virtual ~CPEClient(); int Login(const char *ipaddr, WORD port, const char* username, const char* password); int Logout(); int GetSadpInfoList(LPPE_CLIENT_SADPINFO_LIST lpSadpInfoList); bool StopRealPlay(int); int GetPEStreamPort(const char* uuid); }; #endif //CAM360_PANOCAM_NETCLIENT_HPSOCKET_H_<file_sep>/app/src/main/cpp/Online/OnlineDecoder.h // // Created by tir on 2016/10/9. // #ifndef PANO_ONLINEDECODER_H #define PANO_ONLINEDECODER_H #include "../Common.h" #include "../PER/PERDecoder.h" #include "../OnlineSDK/PEClientSDK/PEClientSDK.h" #include <media\NdkMediaCodec.h> #include <media\NdkMediaExtractor.h> #include <queue> #include <pthread.h> class OnlineDecoder: public PERDecoder { public: OnlineDecoder(); ~OnlineDecoder(); void run(); bool step(); private: }; #endif //PANO_ONLINEDECODER_H <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PECmbFile.java package panoeye.pelibrary; import android.util.Log; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.FloatBuffer; /** * Created by Administrator on 2018/3/23. */ public class PECmbFile { private static final String TAG = "PECmbFile"; int num,col,row; ByteBuffer cmb_mask[]; FloatBuffer map_x[]; FloatBuffer map_y[]; public PECmbFile(String cmbPath)throws PEError{ // java.io.PEFile cmbFile = new java.io.PEFile(cmbPath); // if (cmbFile.exists()) { RandomAccessFile pCmbFile = PEFile.fopen(cmbPath);//打开bin文件 readPECmbFileInfo(pCmbFile); // }else { // Log.e(TAG, "PECmbFile: 找不到cmb调色文件!"); // } } void readPECmbFileInfo(RandomAccessFile fp)throws PEError{ num = PEFile.freadInteger(fp); //8 col = PEFile.freadInteger(fp); //320 row = PEFile.freadInteger(fp); //240 cmb_mask = new ByteBuffer[num]; map_x = new FloatBuffer[num]; map_y = new FloatBuffer[num]; for (int i = 0; i < num; i++){ Log.e(TAG, "readPECmbFileInfo: i:"+i); cmb_mask[i] = PEFile.freadByteBuffer(fp,col*row);//读取row*col个字节//76800 map_x[i] = PEFile.freadFloatBuffer(fp,col*row);//读取row*col个Float类型数据//76800*4 map_y[i] = PEFile.freadFloatBuffer(fp,col*row);//读取row*col个Float类型数据//76800*4 } } } <file_sep>/app/src/main/cpp/include/xrapi/XrApiTypes.h // // Created by SVR00003 on 2017/9/15. // #ifndef XRSDK_XRAPITYPES_H #define XRSDK_XRAPITYPES_H #include <stdbool.h> #include "XrApiConfig.h" // needed for XRAPI_EXPORT //----------------------------------------------------------------- // Java //----------------------------------------------------------------- #if defined( ANDROID ) #include <jni.h> #elif defined( __cplusplus ) typedef struct _JNIEnv JNIEnv; typedef struct _JavaVM JavaVM; typedef class _jobject * jobject; #else typedef const struct JNINativeInterface * JNIEnv; typedef const struct JNIInvokeInterface * JavaVM; typedef void * jobject; #endif typedef struct { JavaVM * Vm; // Java Virtual Machine JNIEnv * Env; // Thread specific environment jobject ActivityObject; // Java activity object } xrJava; XRAPI_ASSERT_TYPE_SIZE_32_BIT( xrJava, 12 ); XRAPI_ASSERT_TYPE_SIZE_64_BIT( xrJava, 24 ); //----------------------------------------------------------------- // Basic Types //----------------------------------------------------------------- typedef signed int xrResult; // xrResult isn't actually an enum type and the the success / failure types are not // defined anywhere for GearVR XrApi. This needs to be remedied. For now, I'm defining // these here and will try to address this larger issue in a follow-on changeset. // errors are < 0, successes are >= 0 // Except where noted, these match error codes from PC CAPI. typedef enum xrSuccessResult_ { xrSuccess = 0, } xrSuccessResult; typedef enum xrErrorResult_ { xrError_MemoryAllocationFailure = -1000, xrError_NotInitialized = -1004, xrError_InvalidParameter = -1005, xrError_DeviceUnavailable = -1010, // device is not connected, or not connected as input device xrError_InvalidOperation = -1015, // enums not in CAPI xrError_UnsupportedDeviceType = -1050, // specified device type isn't supported on GearVR xrError_NoDevice = -1051, // specified device ID does not map to any current device xrError_NotImplemented = -1052, // executed an incomplete code path - this should not be possible in public releases. xrResult_EnumSize = 0x7fffffff } xrErrorResult; typedef struct xrVector2f_ { float x, y; } xrVector2f; XRAPI_ASSERT_TYPE_SIZE( xrVector2f, 8 ); typedef struct xrVector3f_ { float x, y, z; } xrVector3f; XRAPI_ASSERT_TYPE_SIZE( xrVector3f, 12 ); typedef struct xrVector4f_ { float x, y, z, w; } xrVector4f; XRAPI_ASSERT_TYPE_SIZE( xrVector4f, 16 ); // Quaternion. typedef struct xrQuatf_ { float x, y, z, w; } xrQuatf; XRAPI_ASSERT_TYPE_SIZE( xrQuatf, 16 ); // Row-major 4x4 matrix. typedef struct xrMatrix4f_ { float M[4][4]; } xrMatrix4f; XRAPI_ASSERT_TYPE_SIZE( xrMatrix4f, 64 ); // Position and orientation together. typedef struct xrPosef_ { xrQuatf Orientation; xrVector3f Position; } xrPosef; XRAPI_ASSERT_TYPE_SIZE( xrPosef, 28 ); typedef struct xrRectf_ { float x; float y; float width; float height; } xrRectf; XRAPI_ASSERT_TYPE_SIZE( xrRectf, 16 ); typedef enum { XRAPI_FALSE = 0, XRAPI_TRUE } xrBooleanResult; typedef enum { XRAPI_EYE_LEFT, XRAPI_EYE_RIGHT, XRAPI_EYE_COUNT } xrEye; //----------------------------------------------------------------- // Structure Types //----------------------------------------------------------------- typedef enum { XRAPI_STRUCTURE_TYPE_INIT_PARMS = 1, XRAPI_STRUCTURE_TYPE_MODE_PARMS = 2, XRAPI_STRUCTURE_TYPE_FRAME_PARMS = 3, } xrStructureType; //----------------------------------------------------------------- // System Properties and Status //----------------------------------------------------------------- typedef enum { XRAPI_DEVICE_TYPE_GEARVR_START = 0, XRAPI_DEVICE_TYPE_NOTE4 = XRAPI_DEVICE_TYPE_GEARVR_START, XRAPI_DEVICE_TYPE_NOTE5 = 1, XRAPI_DEVICE_TYPE_S6 = 2, XRAPI_DEVICE_TYPE_S7 = 3, XRAPI_DEVICE_TYPE_NOTE7 = 4, // No longer supported. XRAPI_DEVICE_TYPE_S8 = 5, XRAPI_DEVICE_GEARVR_END = 63, XRAPI_DEVICE_TYPE_UNKNOWN = -1, } xrDeviceType; typedef enum { XRAPI_HEADSET_TYPE_R320 = 0, // Note4 Innovator XRAPI_HEADSET_TYPE_R321 = 1, // S6 Innovator XRAPI_HEADSET_TYPE_R322 = 2, // Commercial 1 XRAPI_HEADSET_TYPE_R323 = 3, // Commercial 2 (USB Type C) XRAPI_HEADSET_TYPE_R324 = 4, // Commercial 3 (USB Type C) XRAPI_HEADSET_TYPE_UNKNOWN = -1, } xrHeadsetType; typedef enum { XRAPI_DEVICE_REGION_UNSPECIFIED, XRAPI_DEVICE_REGION_JAPAN, XRAPI_DEVICE_REGION_CHINA, } xrDeviceRegion; typedef enum { XRAPI_VIDEO_DECODER_LIMIT_4K_30FPS, XRAPI_VIDEO_DECODER_LIMIT_4K_60FPS, } xrVideoDecoderLimit; typedef enum { XRAPI_SYS_PROP_DEVICE_TYPE, XRAPI_SYS_PROP_MAX_FULLSPEED_FRAMEBUFFER_SAMPLES, // Physical width and height of the display in pixels. XRAPI_SYS_PROP_DISPLAY_PIXELS_WIDE, XRAPI_SYS_PROP_DISPLAY_PIXELS_HIGH, // Refresh rate of the display in cycles per second. // Currently 60Hz. XRAPI_SYS_PROP_DISPLAY_REFRESH_RATE, // With a display resolution of 2560x1440, the pixels at the center // of each eye cover about 0.06 degrees of visual arc. To wrap a // full 360 degrees, about 6000 pixels would be needed and about one // quarter of that would be needed for ~90 degrees FOV. As such, Eye // images with a resolution of 1536x1536 result in a good 1:1 mapping // in the center, but they need mip-maps for off center pixels. To // avoid the need for mip-maps and for significantly improved rendering // performance this currently returns a conservative 1024x1024. XRAPI_SYS_PROP_SUGGESTED_EYE_TEXTURE_WIDTH, XRAPI_SYS_PROP_SUGGESTED_EYE_TEXTURE_HEIGHT, // This is a product of the lens distortion and the screen size, // but there is no truly correct answer. // There is a tradeoff in resolution and coverage. // Too small of an FOV will leave unrendered pixels visible, but too // large wastes resolution or fill rate. It is unreasonable to // increase it until the corners are completely covered, but we do // want most of the outside edges completely covered. // Applications might choose to render a larger FOV when angular // acceleration is high to reduce black pull in at the edges by // the time warp. // Currently symmetric 90.0 degrees. XRAPI_SYS_PROP_SUGGESTED_EYE_FOV_DEGREES_X, // Horizontal field of view in degrees XRAPI_SYS_PROP_SUGGESTED_EYE_FOV_DEGREES_Y, // Vertical field of view in degrees // Path to the external SD card. On Android-M, this path is dynamic and can // only be determined once the SD card is mounted. Returns an empty string if // device does not support an ext sdcard or if running Android-M and the SD card // is not mounted. XRAPI_SYS_PROP_EXT_SDCARD_PATH, XRAPI_SYS_PROP_DEVICE_REGION, // Video decoder limit for the device. XRAPI_SYS_PROP_VIDEO_DECODER_LIMIT, XRAPI_SYS_PROP_HEADSET_TYPE, // A single press and release of the back button in less than this time is considered // a 'short press'. XRAPI_SYS_PROP_BACK_BUTTON_SHORTPRESS_TIME, // in seconds // Pressing the back button twice within this time is considered a 'double tap'. XRAPI_SYS_PROP_BACK_BUTTON_DOUBLETAP_TIME, // in seconds XRAPI_SYS_PROP_DOMINANT_HAND, // returns an xrHandedness enum for left or right hand // Returns XRAPI_TRUE if Multiview rendering support is available for this system, // otherwise XRAPI_FALSE. XRAPI_SYS_PROP_MULTIVIEW_AVAILABLE = 128, // Returns XRAPI_TRUE if submission of SRGB Layers is supported for this system, // otherwise XRAPI_FALSE. XRAPI_SYS_PROP_SRGB_LAYER_SOURCE_AVAILABLE, XRAPI_SYS_PROP_BUILD_PRODUCT, // Lens seperation XRAPI_SYS_PROP_LENS_SEPERATION = 1024, XRAPI_SYS_PROP_WIDTH_METERS, XRAPI_SYS_PROP_HEIGHT_METERS, XRAPI_SYS_PROP_UNITY_VSYNC_CNT, XRAPI_SYS_PROP_WFD_TYPE, XRAPI_SYS_PROP_WFD_WHRATIO, XRAPI_SYS_PROP_SCREEN_TYPE, XRAPI_SYS_PROP_CHROMATIC_CORRECTION_STATE, XRAPI_SYS_PROP_CHROMATIC_ABERRATION_0, XRAPI_SYS_PROP_CHROMATIC_ABERRATION_1, XRAPI_SYS_PROP_CHROMATIC_ABERRATION_2, XRAPI_SYS_PROP_CHROMATIC_ABERRATION_3, } xrSystemProperty; typedef enum { XRAPI_HAND_UNKNOWN = 0, XRAPI_HAND_LEFT = 1, XRAPI_HAND_RIGHT = 2 } xrHandedness; typedef enum { XRAPI_SYS_STATUS_DOCKED, // Device is docked. XRAPI_SYS_STATUS_MOUNTED, // Device is mounted. XRAPI_SYS_STATUS_THROTTLED, // Device is in powersave mode. XRAPI_SYS_STATUS_THROTTLED2, // Device is in extreme powersave mode. // enum 4 used to be XRAPI_SYS_STATUS_THROTTLED_WARNING_LEVEL. XRAPI_SYS_STATUS_RENDER_LATENCY_MILLISECONDS = 5,// Average time between render tracking sample and scanout. XRAPI_SYS_STATUS_TIMEWARP_LATENCY_MILLISECONDS, // Average time between timewarp tracking sample and scanout. XRAPI_SYS_STATUS_SCANOUT_LATENCY_MILLISECONDS, // Average time between Vsync and scanout. XRAPI_SYS_STATUS_APP_FRAMES_PER_SECOND, // Number of frames per second delivered through Xrapi_SubmitFrame. XRAPI_SYS_STATUS_SCREEN_TEARS_PER_SECOND, // Number of screen tears per second (per eye). XRAPI_SYS_STATUS_EARLY_FRAMES_PER_SECOND, // Number of frames per second delivered a whole display refresh early. XRAPI_SYS_STATUS_STALE_FRAMES_PER_SECOND, // Number of frames per second delivered late. XRAPI_SYS_STATUS_HEADPHONES_PLUGGED_IN, // Returns XRAPI_TRUE if headphones are plugged into the device. XRAPI_SYS_STATUS_RECENTER_COUNT, // Returns the current HMD recenter count. Defaults to 0. XRAPI_SYS_STATUS_SYSTEM_UX_ACTIVE, // Returns XRAPI_TRUE if a system UX layer is active XRAPI_SYS_STATUS_FRONT_BUFFER_PROTECTED = 128, // True if the front buffer is allocated in TrustZone memory. XRAPI_SYS_STATUS_FRONT_BUFFER_565, // True if the front buffer is 16-bit 5:6:5 XRAPI_SYS_STATUS_FRONT_BUFFER_SRGB, // True if the front buffer uses the sRGB color space. } xrSystemStatus; //----------------------------------------------------------------- // Initialization //----------------------------------------------------------------- typedef enum { XRAPI_INITIALIZE_SUCCESS = 0, XRAPI_INITIALIZE_UNKNOWN_ERROR = -1, XRAPI_INITIALIZE_PERMISSIONS_ERROR = -2, } xrInitializeStatus; typedef enum { XRAPI_GRAPHICS_API_OPENGL_ES_2 = ( 0x10000 | 0x0200 ), // OpenGL ES 2.x context XRAPI_GRAPHICS_API_OPENGL_ES_3 = ( 0x10000 | 0x0300 ), // OpenGL ES 3.x context XRAPI_GRAPHICS_API_OPENGL_COMPAT = ( 0x20000 | 0x0100 ), // OpenGL Compatibility Profile XRAPI_GRAPHICS_API_OPENGL_CORE_3 = ( 0x20000 | 0x0300 ), // OpenGL Core Profile 3.x XRAPI_GRAPHICS_API_OPENGL_CORE_4 = ( 0x20000 | 0x0400 ), // OpenGL Core Profile 4.x } xrGraphicsAPI; typedef enum { XRAPI_SCREEN_MODE_DEFAULT = 0x0, XRAPI_SCREEN_MODE_DUAL = XRAPI_SCREEN_MODE_DEFAULT, XRAPI_SCREEN_MODE_SPLIT = 0x1, XRAPI_SCREEN_MODE_MULTIVIEW = 0x2, XRAPI_IVR_SDK_COMPATIBLE = 0x00200000, } xrInitFlags; typedef struct { xrStructureType Type; int ProductVersion; int MajorVersion; int MinorVersion; int PatchVersion; xrGraphicsAPI GraphicsAPI; xrJava Java; //values contain in xrInitFlags unsigned int Flags; } xrInitParms; XRAPI_ASSERT_TYPE_SIZE_32_BIT( xrInitParms, 40 ); XRAPI_ASSERT_TYPE_SIZE_64_BIT( xrInitParms, 56 ); //----------------------------------------------------------------- // VR Mode //----------------------------------------------------------------- // NOTE: the first two flags use the first two bytes for backwards compatibility on little endian systems. typedef enum { // If set, warn and allow the app to continue at 30 FPS when throttling occurs. // If not set, display the level 2 error message which requires the user to undock. XRAPI_MODE_FLAG_ALLOW_POWER_SAVE = 0x000000FF, // When an application moves backwards on the activity stack, // the activity window it returns to is no longer flagged as fullscreen. // As a result, Android will also render the decor view, which wastes a // significant amount of bandwidth. // By setting this flag, the fullscreen flag is reset on the window. // Unfortunately, this causes Android life cycle events that mess up // several NativeActivity codebases like Stratum and UE4, so this // flag should only be set for specific applications. // Use "adb shell dumpsys SurfaceFlinger" to verify // that there is only one HWC next to the FB_TARGET. XRAPI_MODE_FLAG_RESET_WINDOW_FULLSCREEN = 0x0000FF00, // The WindowSurface passed in is an ANativeWindow. XRAPI_MODE_FLAG_NATIVE_WINDOW = 0x00010000, // Create the front buffer in TrustZone memory to allow protected DRM // content to be rendered to the front buffer. This functionality // requires the WindowSurface to be allocated from TimeWarp, via // specifying the nativeWindow via XRAPI_MODE_FLAG_NATIVE_WINDOW. XRAPI_MODE_FLAG_FRONT_BUFFER_PROTECTED = 0x00020000, // Create a 16-bit 5:6:5 front buffer. XRAPI_MODE_FLAG_FRONT_BUFFER_565 = 0x00040000, // Create a front buffer using the sRGB color space. XRAPI_MODE_FLAG_FRONT_BUFFER_SRGB = 0x00080000, } xrModeFlags; typedef struct { xrStructureType Type; // Combination of xrModeFlags flags. unsigned int Flags; // The Java VM is needed for the time warp thread to create a Java environment. // A Java environment is needed to access various system services. The thread // that enters VR mode is responsible for attaching and detaching the Java // environment. The Java Activity object is needed to get the windowManager, // packageName, systemService, etc. xrJava Java; XRAPI_PADDING_32_BIT( 4 ); // If not zero, then use this display for asynchronous time warp rendering. // Using EGL this is an EGLDisplay. unsigned long long Display; // If not zero, then use this window surface for asynchronous time warp rendering. // Using EGL this can be the EGLSurface created by the application for the ANativeWindow. // Preferrably this is the ANativeWIndow itself (requires XRAPI_MODE_FLAG_NATIVE_WINDOW). unsigned long long WindowSurface; // If not zero, then resources from this context will be shared with the asynchronous time warp. // Using EGL this is an EGLContext. unsigned long long ShareContext; } xrModeParms; XRAPI_ASSERT_TYPE_SIZE_32_BIT( xrModeParms, 48 ); XRAPI_ASSERT_TYPE_SIZE_64_BIT( xrModeParms, 56 ); // VR context // To allow multiple Android activities that live in the same address space // to cooperatively use the XrApi, each activity needs to maintain its own // separate contexts for a lot of the video related systems. typedef struct xrMobile xrMobile; //----------------------------------------------------------------- // Tracking //----------------------------------------------------------------- // Full rigid body pose with first and second derivatives. typedef struct xrRigidBodyPosef_ { xrPosef Pose; xrVector3f AngularVelocity; xrVector3f LinearVelocity; xrVector3f AngularAcceleration; xrVector3f LinearAcceleration; XRAPI_PADDING( 4 ); double TimeInSeconds; // Absolute time of this pose. double PredictionInSeconds; // Seconds this pose was predicted ahead. } xrRigidBodyPosef; XRAPI_ASSERT_TYPE_SIZE( xrRigidBodyPosef, 96 ); // Bit flags describing the current status of sensor tracking. typedef enum { XRAPI_TRACKING_STATUS_ORIENTATION_TRACKED = 0x0001, // Orientation is currently tracked. XRAPI_TRACKING_STATUS_POSITION_TRACKED = 0x0002, // Position is currently tracked. XRAPI_TRACKING_STATUS_HMD_CONNECTED = 0x0080 // HMD is available & connected. } xrTrackingStatus; // Tracking state at a given absolute time. typedef struct xrTracking2_ { // Sensor status described by xrTrackingStatus flags. unsigned int Status; XRAPI_PADDING( 4 ); // Predicted head configuration at the requested absolute time. // The pose describes the head orientation and center eye position. xrRigidBodyPosef HeadPose; struct { xrMatrix4f ProjectionMatrix; xrMatrix4f ViewMatrix; } Eye[ XRAPI_EYE_COUNT ]; } xrTracking2; XRAPI_ASSERT_TYPE_SIZE( xrTracking2, 360 ); typedef struct xrTracking_ { // Sensor status described by xrTrackingStatus flags. unsigned int Status; XRAPI_PADDING( 4 ); // Predicted head configuration at the requested absolute time. // The pose describes the head orientation and center eye position. xrRigidBodyPosef HeadPose; } xrTracking; XRAPI_ASSERT_TYPE_SIZE( xrTracking, 104 ); //----------------------------------------------------------------- // Texture Swap Chain //----------------------------------------------------------------- typedef enum { XRAPI_TEXTURE_TYPE_2D, // 2D textures. XRAPI_TEXTURE_TYPE_2D_EXTERNAL, // External 2D texture. XRAPI_TEXTURE_TYPE_2D_ARRAY, // Texture array. XRAPI_TEXTURE_TYPE_CUBE, // Cube maps. XRAPI_TEXTURE_TYPE_MAX, } xrTextureType; typedef enum { XRAPI_TEXTURE_FORMAT_NONE, XRAPI_TEXTURE_FORMAT_565, XRAPI_TEXTURE_FORMAT_5551, XRAPI_TEXTURE_FORMAT_4444, XRAPI_TEXTURE_FORMAT_8888, XRAPI_TEXTURE_FORMAT_8888_sRGB, XRAPI_TEXTURE_FORMAT_RGBA16F, XRAPI_TEXTURE_FORMAT_DEPTH_16, XRAPI_TEXTURE_FORMAT_DEPTH_24, XRAPI_TEXTURE_FORMAT_DEPTH_24_STENCIL_8, } xrTextureFormat; typedef enum { XRAPI_DEFAULT_TEXTURE_SWAPCHAIN_BLACK = 0x1, XRAPI_DEFAULT_TEXTURE_SWAPCHAIN_LOADING_ICON = 0x2, XRAPI_TEXTURE_SWAPCHAIN_EXTERNAL_TEXTRUEID = 0x3 } xrDefaultTextureSwapChain; typedef enum { XRAPI_TEXTURE_SWAPCHAIN_FULL_MIP_CHAIN = -1 } xrTextureSwapChainSettings; typedef struct xrTextureSwapChain xrTextureSwapChain; //----------------------------------------------------------------- // Frame Submission //----------------------------------------------------------------- typedef enum { // To get gamma correct sRGB filtering of the eye textures, the textures must be // allocated with GL_SRGB8_ALPHA8 format and the window surface must be allocated // with these attributes: // EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_SRGB_KHR // // While we can reallocate textures easily enough, we can't change the window // colorspace without relaunching the entire application, so if you want to // be able to toggle between gamma correct and incorrect, you must allocate // the framebuffer as sRGB, then inhibit that processing when using normal // textures. XRAPI_FRAME_FLAG_INHIBIT_SRGB_FRAMEBUFFER = 1, // Flush the warp swap pipeline so the images show up immediately. // This is expensive and should only be used when an immediate transition // is needed like displaying black when resetting the HMD orientation. XRAPI_FRAME_FLAG_FLUSH = 2, // This is the final frame. Do not accept any more frames after this. XRAPI_FRAME_FLAG_FINAL = 4, // enum 8 used to be XRAPI_FRAME_FLAG_TIMEWARP_DEBUG_GRAPH_SHOW. // enum 16 used to be XRAPI_FRAME_FLAG_TIMEWARP_DEBUG_GRAPH_FREEZE. // enum 32 used to be XRAPI_FRAME_FLAG_TIMEWARP_DEBUG_GRAPH_LATENCY_MODE. // Don't show the volume layer whent set. XRAPI_FRAME_FLAG_INHIBIT_VOLUME_LAYER = 64, // enum 128 used to be XRAPI_FRAME_FLAG_SHOW_LAYER_COMPLEXITY. // enum 256 used to be XRAPI_FRAME_FLAG_SHOW_TEXTURE_DENSITY. } xrFrameFlags; typedef enum { // Enable writing to the alpha channel // NOTE: *_WRITE_ALPHA is DEPRECATED. Please do not write any new code which // relies on it's use. XRAPI_FRAME_LAYER_FLAG_WRITE_ALPHA = 1, // Correct for chromatic aberration. Quality/perf trade-off. XRAPI_FRAME_LAYER_FLAG_CHROMATIC_ABERRATION_CORRECTION = 2, // Used for some HUDs, but generally considered bad practice. XRAPI_FRAME_LAYER_FLAG_FIXED_TO_VIEW = 4, // Spin the layer - for loading icons XRAPI_FRAME_LAYER_FLAG_SPIN = 8, // Clip fragments outside the layer's TextureRect XRAPI_FRAME_LAYER_FLAG_CLIP_TO_TEXTURE_RECT = 16, } xrFrameLayerFlags; typedef enum { XRAPI_FRAME_LAYER_EYE_LEFT, XRAPI_FRAME_LAYER_EYE_RIGHT, XRAPI_FRAME_LAYER_EYE_MAX } xrFrameLayerEye; typedef enum { XRAPI_FRAME_LAYER_BLEND_ZERO, XRAPI_FRAME_LAYER_BLEND_ONE, XRAPI_FRAME_LAYER_BLEND_SRC_ALPHA, // NOTE: *_DST_ALPHA blend modes are DEPRECATED. Please do not // write any new code which relies on it's use. XRAPI_FRAME_LAYER_BLEND_DST_ALPHA, XRAPI_FRAME_LAYER_BLEND_ONE_MINUS_DST_ALPHA, XRAPI_FRAME_LAYER_BLEND_ONE_MINUS_SRC_ALPHA } xrFrameLayerBlend; typedef enum { // enum 0-3 have been deprecated. Explicit indices // for frame layers should be used instead. XRAPI_FRAME_LAYER_TYPE_MAX = 4 } xrFrameLayerType; typedef enum { XRAPI_EXTRA_LATENCY_MODE_OFF, XRAPI_EXTRA_LATENCY_MODE_ON, XRAPI_EXTRA_LATENCY_MODE_DYNAMIC } xrExtraLatencyMode; // Note that any layer textures that are dynamic must be triple buffered. typedef struct { // Because OpenGL ES does not support clampToBorder, it is the // application's responsibility to make sure that all mip levels // of the primary eye texture have a black border that will show // up when time warp pushes the texture partially off screen. xrTextureSwapChain * ColorTextureSwapChain; // DEPRECATED: Please do not write any new code which relies on DepthTextureSwapChain. // The depth texture is optional for positional time warp. xrTextureSwapChain * DepthTextureSwapChain; // Index to the texture from the set that should be displayed. int TextureSwapChainIndex; // Points on the screen are mapped by a distortion correction // function into ( TanX, TanY, -1, 1 ) vectors that are transformed // by this matrix to get ( S, T, Q, _ ) vectors that are looked // up with texture2dproj() to get texels. xrMatrix4f TexCoordsFromTanAngles; // Only texels within this range should be drawn. // This is a sub-rectangle of the [(0,0)-(1,1)] texture coordinate range. xrRectf TextureRect; XRAPI_PADDING( 4 ); // The tracking state for which ModelViewMatrix is correct. // It is ok to update the orientation for each eye, which // can help minimize black edge pull-in, but the position // must remain the same for both eyes, or the position would // seem to judder "backwards in time" if a frame is dropped. xrRigidBodyPosef HeadPose; // If not zero, this fence will be used to determine whether or not // rendering to the color and depth texture swap chains has completed. unsigned long long CompletionFence; } xrFrameLayerTexture; XRAPI_ASSERT_TYPE_SIZE_32_BIT( xrFrameLayerTexture, 200 ); XRAPI_ASSERT_TYPE_SIZE_64_BIT( xrFrameLayerTexture, 208 ); typedef struct { // Image used for each eye. xrFrameLayerTexture Textures[XRAPI_FRAME_LAYER_EYE_MAX]; // Speed and scale of rotation when XRAPI_FRAME_LAYER_FLAG_SPIN is set in xrFrameLayer::Flags float SpinSpeed; // Radians/Second float SpinScale; // Color scale for this layer (including alpha) float ColorScale; // padding for deprecated variable. XRAPI_PADDING( 4 ); // Layer blend function. xrFrameLayerBlend SrcBlend; xrFrameLayerBlend DstBlend; // Combination of xrFrameLayerFlags flags. int Flags; } xrFrameLayer; XRAPI_ASSERT_TYPE_SIZE_32_BIT( xrFrameLayer, 432 ); XRAPI_ASSERT_TYPE_SIZE_64_BIT( xrFrameLayer, 448 ); typedef struct { // These are fixed clock levels in the range [0, 3]. int CpuLevel; int GpuLevel; // These threads will get SCHED_FIFO. int MainThreadTid; int RenderThreadTid; } xrPerformanceParms; XRAPI_ASSERT_TYPE_SIZE( xrPerformanceParms, 16 ); typedef struct { xrStructureType Type; XRAPI_PADDING( 4 ); // Layers composited in the time warp. xrFrameLayer Layers[XRAPI_FRAME_LAYER_TYPE_MAX]; int LayerCount; // Combination of xrFrameFlags flags. int Flags; // Application controlled frame index that uniquely identifies this particular frame. // This must be the same frame index that was passed to Xrapi_GetPredictedDisplayTime() // when synthesis of this frame started. long long FrameIndex; // WarpSwap will not return until at least this many V-syncs have // passed since the previous WarpSwap returned. // Setting to 2 will reduce power consumption and may make animation // more regular for applications that can't hold full frame rate. int MinimumVsyncs; // Latency Mode. xrExtraLatencyMode ExtraLatencyMode; // DEPRECATED: Please do not write any code which relies on ExternalVelocity. // Rotation from a joypad can be added on generated frames to reduce // judder in FPS style experiences when the application framerate is // lower than the V-sync rate. // This will be applied to the view space distorted // eye vectors before applying the rest of the time warp. // This will only be added when the same xrFrameParms is used for // more than one V-sync. xrMatrix4f ExternalVelocity; // DEPRECATED: Please do not write any code which relies on SurfaceTextureObject. // jobject that will be updated before each eye for minimal // latency. // IMPORTANT: This should be a JNI weak reference to the object. // The system will try to convert it into a global reference before // calling SurfaceTexture->Update, which allows it to be safely // freed by the application. jobject SurfaceTextureObject; // CPU/GPU performance parameters. xrPerformanceParms PerformanceParms; // For handling HMD events and power level state changes. xrJava Java; } xrFrameParms; XRAPI_ASSERT_TYPE_SIZE_32_BIT( xrFrameParms, 1856 ); XRAPI_ASSERT_TYPE_SIZE_64_BIT( xrFrameParms, 1936 ); //----------------------------------------------------------------- // Head Model //----------------------------------------------------------------- typedef struct { float InterpupillaryDistance; // Distance between eyes. float EyeHeight; // Eye height relative to the ground. float HeadModelDepth; // Eye offset forward from the head center at EyeHeight. float HeadModelHeight; // Neck joint offset down from the head center at EyeHeight. } xrHeadModelParms; XRAPI_ASSERT_TYPE_SIZE( xrHeadModelParms, 16 ); #endif //XRSDK_XRAPITYPES_H <file_sep>/app/src/main/cpp/PER/PERFile.h // // Created by tir on 2016/9/28. // #ifndef PANO_PERFILE_H #define PANO_PERFILE_H #include "../timeb.h" #include "zip/ZipLibUtil.h" #include "PERBinFile.h" #pragma pack(push,1) struct PERFileHead { char head[20]; uchar version; LONG streamOffset; LONG streamSize; char packetType; LONG devInfoOffset; LONG recordInfoOffset; }; struct PERDevHead { unsigned char head; //0x40 char devName[256]; char serialNum[64]; LONG binZipOffset; LONG binZipSize; int streamMode; }; struct PERRecordHead { uchar head; //0x41 timeb createTime; timeb startTime; timeb endTime; LONG listOffset;//绝对偏移量 LONG listSize; LONG listCellSize; }; struct PERIndexCell{ uchar head; LONG preCellOffset; //相对于index_list_order,负数为无效 LONG nextCellOffset; //相对于index_list_order,负数为无效 LONG streamPackageOffset; //相对于stream_load_order,负数为无效 timeb currentTime; float cPDt; unsigned isIFrame: 8; unsigned streamID: 8; ulong frameID; //当前帧ID ulong keyframeID; //当前帧依赖的关键帧ID }; struct PERPackageHead { unsigned head; LONG pesHeadOffset; }; struct PERPackagePESHead { unsigned head : 24; unsigned streamID : 8; LONG videoHeadOffset; }; struct PERPackageVideoHead { unsigned head; //0x000001B3 timeb tPTS; //UTS绝对时间 float fPTS; //相对于文件开始时间 timeb tDTS; //UTS绝对时间 float fDTS; //相对于文件开始时间 LONG videoDataOffset; //距离这个头的偏移 LONG videoDataSize; //扩展区 unsigned isIFrame; //关键帧 ulong frameID; //当前帧ID ulong IFrameID; //当前帧依赖的关键帧ID }; struct PERVideoPackage { PERPackageHead head; PERPackagePESHead pesHead; PERPackageVideoHead videoHead; }; #pragma pack(pop) class PERFile { public: int streamType; FILE * file; PERFileHead head; PERDevHead devHead; PERRecordHead recordHead; PERIndexCell indexList[MAX_CAMERA_COUNT][MAX_PER_CELL_COUNT]; int indexIndex[MAX_CAMERA_COUNT] = {0}; PERBinFile * binFile; PERFile(); ~PERFile(); bool openFile(char * filename); void seekTo(int offset); bool setVideoData(int * code); }; #endif //PANO_PERFILE_H <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PERendererGain.java package panoeye.pelibrary; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.util.Log; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Created by Administrator on 2018/1/9. */ public class PERendererGain implements GLSurfaceView.Renderer { private static final String TAG = "PERendererOnline"; int cameraNum; final Float PI = 3.141592f; FloatBuffer verCoordbuffer ;//顶点坐标 FloatBuffer texCoordbuffer; //纹理坐标 FloatBuffer VR_VERTEX_COORD;//VR模式顶点坐标 FloatBuffer VR_TEXTURE_COORD; //VR模式纹理坐标 private int vboVer[][] ;//vbo 顶点缓冲区对象 private int vboTex[][] ; float[] mProjMatrix = new float[16]; float[] mModeViewMatrix = new float[16]; float[] mMatrix = new float[16]; float[] glTranslate = new float[3]; float[] glRotateXAxis = new float[3]; float[] glRotateZAxis = new float[3]; private int shaderVertex; private int shaderTexture; private int shaderMatrix; private int tex_type; private int tex_y; private int tex_u; private int tex_v; private int tex_a; private int program; private int turn_y; private int turn_u; private int turn_v; int[][] textures ; int[][] texturesTurn; IntBuffer textureId, rboId, fboId; private int width = 1; private int height = 1; private float fovy =45f; private boolean changeFlag = false ; PEBinFile binFile ;//bin文件 PEDecodeBuffer decodeBuffer; Integer radius ; //构造函数 public PERendererGain(PEBinFile binFile, PEDecodeBuffer decodeBuffer)throws PEError { this.binFile = binFile; this.decodeBuffer = decodeBuffer; this.cameraNum = binFile.info.camCount; textures = new int[binFile.info.camCount][7];//int textures[8][4] texturesTurn = new int[binFile.info.camCount][3];//int textures[8][3] vboVer = new int[binFile.info.camCount][1]; vboTex = new int[binFile.info.camCount][1]; textureId = IntBuffer.allocate(1); fboId = IntBuffer.allocate(1); rboId = IntBuffer.allocate(1); //VR模式顶点坐标 VR_VERTEX_COORD = FloatBufferInit.bufferUtilInit(PESquare.VR_VERTEX_COORD.length); VR_VERTEX_COORD.put(PESquare.VR_VERTEX_COORD).position(0); //VR模式纹理坐标 VR_TEXTURE_COORD = FloatBufferInit.bufferUtilInit(PESquare.VR_TEXTURE_COORD.length); VR_TEXTURE_COORD.put(PESquare.VR_TEXTURE_COORD).position(0); } //仅调用一次,用于设置view的OpenGLES环境。 public void onSurfaceCreated(GL10 gl, EGLConfig config){ Log.d(TAG, "onSurfaceCreated: "); // GLES20.glClearColor(0.3f, 0.5f, 0.7f, 1.0f); GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); initVBO(); // initTexture(); // initVR(); useProgram(); // float[] dst = new float[3]; // int offset = 0; // for (int pointCount = 1;pointCount<10;pointCount++){ // verCoordbuffer.get(dst,0,3); // offset = offset+3; // Log.d(TAG, "onSurfaceChanged: "+dst[0]+","+dst[1]+","+dst[2]); // } } //每次View被重绘时被调用。 public void onDrawFrame(GL10 gl) { // GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT|GLES20.GL_DEPTH_BUFFER_BIT); Define.openglFrameRate++; glResize(); try { glDraw();//opengl绘制 }catch (PEError e){ Log.d("onDrawFrame", e.name+e.msg); } } //如果view的几和形状发生变化了就调用,例如当竖屏变为横屏时。 public void onSurfaceChanged(GL10 gl,int width,int height){ Log.d(TAG, "onSurfaceChanged: "); GLES20.glViewport(0,0,width,height); this.width = width; this.height = height; // glResize(); if (changeFlag == false) { initTexture(); initVR(); // changeFlag = true; } } //初始化顶点缓冲对象 void initVBO(){ for (Integer cid:binFile.cidList){ // for (int cid=0;cid<cameraNum;cid++){ int channel; switch (binFile.info.camCount){ case 5: if (cid==1) channel = 3; else if (cid==3) channel = 1; else channel = cid; break; case 8: if (cid>0 && cid<7) channel = 7-cid; else channel = cid; break; default: channel = cid; break; } //从bin文件获取顶点坐标 if (Define.flip == false){ verCoordbuffer = binFile.camConfigs.get(channel).verCoordbuffer; }else { verCoordbuffer = binFile.camConfigs.get(channel).verCoordbufferFlip; } //从bin文件获取纹理坐标 texCoordbuffer = binFile.camConfigs.get(channel).texCoordbuffer; /** * 函数:void glGenBuffers(int n, int[] buffers, int offset) * 作用:向OpenGL ES申请开辟新的VBO,并通过buffers数组获取VBO handle,handle的类型为整型。 * @param int n      申请的VBO个数 * @param int[] buffers  用于存储VBO handle的数组 * @param int offset    buffers数组的偏移量,即从buffers的第offset个位置开始存储handle * 注意:需要满足 n + offset <= buffers.length */ GLES20.glGenBuffers(1,vboVer[cid],0); /** * 函数:void glBindBuffer(int target, int buffer) * 作用:通过handle绑定指定的VBO,同一时间只能绑定一个同类型的VBO,只有当前被绑定的VBO才会被用户操作。通过绑定handle为0的VBO,可以取消对所有同类型VBO的绑定。 * @param int target    指定绑定的VBO类型,具体类型有GL_ARRAY_BUFFER(用于为顶点数组传值)和GL_ELEMENT_ARRAY_BUFFER(用于为索引数组传值) * @param int buffer    指定绑定的VBO handle */ GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER,vboVer[cid][0]); /** * 函数:void glBufferData(int target, int size, Buffer data, int usage) * 作用:将数据传递给当前绑定的VBO。 * @param int target    指定VBO类型,同上 * @param int size     指定VBO的大小,单位为byte * @param Buffer data   指定需要传递的数据 * @param int usage    指定VBO的存储方式,例如GL_STATIC_DRAW或GL_DYNAMIC_DRAW */ GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER,binFile.camConfigs.get(channel).verCoordLength*4,verCoordbuffer,GLES20.GL_STATIC_DRAW); GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER,0); GLES20.glGenBuffers(1,vboTex[cid],0); GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER,vboTex[cid][0]); GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER,binFile.camConfigs.get(channel).texCoordLength*4,texCoordbuffer,GLES20.GL_STATIC_DRAW); GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER,0); } } void initTexture(){ PEMatrix.makeVec3(glRotateXAxis, 1, 0, 0); PEMatrix.makeVec3(glRotateZAxis, 0, 0, 1); // GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);//设置图像融合参数 // GLES20.glEnable(GLES20.GL_BLEND);//启用图像融合 // GLES20.glEnable(GLES20.GL_TEXTURE_2D); for (Integer cid : binFile.cidList) { // for (int cid=0;cid<cameraNum;cid++){ GLES20.glGenTextures(7, textures[cid], 0); GLES20.glGenTextures(3, texturesTurn[cid], 0); Size size = binFile.camConfigs.get(cid).fullSize; for (int i = 0; i < 7; i++) { Log.d(TAG, "initTexture: textures:"+textures[cid][i]); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[cid][i]); //set filtering GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);//GL_CLAMP_TO_EDGE GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); } int channel; switch (binFile.info.camCount){ case 5: if (cid==1) channel = 3; else if (cid==3) channel = 1; else channel = cid; break; case 8: if (cid>0 && cid<7) channel = 7-cid; else channel = cid; break; default: channel = cid; break; } GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[cid][3]); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_LUMINANCE, size.width, size.height, 0, GLES20.GL_LUMINANCE, GLES20.GL_UNSIGNED_BYTE, binFile.camConfigs.get(channel).alphaData); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); if (Define.isCmbExist){ // PEColorTune.undateIfNeedTurn7(cid,textures[cid]);//绑定调色数据 PEColorTune.undateIfNeedTurn(cid,texturesTurn[cid]);//绑定调色数据 for (int i = 0; i < 3; i++) { Log.e(TAG, "initTexture: texturesTurn:"+texturesTurn[cid][i]); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texturesTurn[cid][i]); //glTexParameteri():纹理过滤函数 GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT);//GL_CLAMP_TO_EDGE GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT);//GL_NONE GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); } } } // PEMatrix.makeUnit(mModeViewMatrix); // PEMatrix.makeUnit(mProjMatrix); // PEMatrix.makeUnit(mMatrix); } void initVR(){ //创建纹理 GLES20.glGenTextures(1, textureId); int a= textureId.get(0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId.get(0)); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_GENERATE_MIPMAP_HINT, GLES20.GL_TRUE); GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGB, width, height, 0, GLES20.GL_RGB, GLES20.GL_UNSIGNED_BYTE, null); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0); //创建renderBuffer GLES20.glGenRenderbuffers(1, rboId); int b=rboId.get(0); GLES20.glBindRenderbuffer(GLES20.GL_RENDERBUFFER, rboId.get(0)); GLES20.glRenderbufferStorage(GLES20.GL_RENDERBUFFER, GLES20.GL_DEPTH_COMPONENT, width, height);//allocate a memory space for rboId GLES20.glBindRenderbuffer(GLES20.GL_RENDERBUFFER, 0); //创建Frame Buffer Object (FBO) GLES20.glGenFramebuffers(1, fboId); int c=fboId.get(0); GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboId.get(0)); GLES20.glFramebufferTexture2D(GLES20.GL_FRAMEBUFFER, GLES20.GL_COLOR_ATTACHMENT0, GLES20.GL_TEXTURE_2D, textureId.get(0), 0);//switch 2D texture objects GLES20.glFramebufferRenderbuffer(GLES20.GL_FRAMEBUFFER, GLES20.GL_DEPTH_ATTACHMENT, GLES20.GL_RENDERBUFFER, rboId.get(0)); //switch rboId objects. GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); // GLES20.glFinish(); } void useProgram(){ program = Shader.buildProgram(); GLES20.glUseProgram(program); shaderVertex = GLES20.glGetAttribLocation(program,"vPosition"); shaderTexture = GLES20.glGetAttribLocation(program,"a_texCoord"); shaderMatrix = GLES20.glGetUniformLocation(program,"glMatrix"); tex_type = GLES20.glGetUniformLocation(program,"SampleType"); tex_y = GLES20.glGetUniformLocation(program,"SamplerY"); tex_u = GLES20.glGetUniformLocation(program,"SamplerU"); tex_v = GLES20.glGetUniformLocation(program,"SamplerV"); tex_a = GLES20.glGetUniformLocation(program,"SamplerA"); turn_y = GLES20.glGetUniformLocation(program,"TurnY"); turn_u = GLES20.glGetUniformLocation(program,"TurnU"); turn_v = GLES20.glGetUniformLocation(program,"TurnV"); } public void glDraw() throws PEError { if (Define.isNeedFilp == true){ initVBO(); Define.isNeedFilp = false; } if (Define.showVR == true){ GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, fboId.get(0)); }else { GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,0); } GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // GLES20.glClearColor(0.8f,0.8f,0.8f,1.0f); float xd = (Define.x/180*PI); float yd = (Define.y/180*PI); float zd = (Define.z/180*PI); PEMatrix.makeUnit(mModeViewMatrix); if (Define.mode == Define.MODE_GLOBULAR){ radius = binFile.info.radius; radius = 450; PEMatrix.makeVec3(glTranslate, 0, 0, -(radius * 7 / 8));//-(radius * 7 / 8) PEMatrix.translate(mModeViewMatrix, glTranslate); //平移 PEMatrix.rotate(mModeViewMatrix,-yd, glRotateXAxis);//旋转 PEMatrix.rotate(mModeViewMatrix,-xd, glRotateZAxis); float[] rollAxis = {(float)Math.sin(-xd),(float)Math.cos(-xd),0}; PEMatrix.rotate(mModeViewMatrix,-zd,rollAxis); GLES20.glEnable(GLES20.GL_BLEND);//启用图像融合 } if (Define.mode == Define.MODE_ORIGINAL){ PEMatrix.makeVec3(glTranslate, xd, -yd, 0); PEMatrix.translate(mModeViewMatrix, glTranslate); GLES20.glDisable(GLES20.GL_BLEND);//禁用图像融合 } PEMatrix.calMulti(mMatrix, mProjMatrix, mModeViewMatrix);//矩阵乘运算 PESquare[] squares; squares = new PESquare[cameraNum]; for (int i = 0;i<cameraNum;i++){ squares[i]=new PESquare(); } if (Define.mode == Define.MODE_ORIGINAL){ GLES20.glUniform1i(tex_type, 2); // 将投影和视口变换传递给着色器shader GLES20.glUniformMatrix4fv(shaderMatrix, 1, false, mMatrix, 0); } for (int cid : binFile.cidList){ decodeBuffer.undateIfNeed(cid, textures[cid]);//更新解码好的缓存数据 // PEVideoTexture videoTexture; // try { // videoTexture =(PEVideoTexture)decodeBuffer.textureDict.get(cid);//得到PEVideoTexture类对象 // }catch (PEError e){ // Log.d(TAG, "glDraw: videoTexture为空"); // } //选择由纹理函数进行修改的当前纹理单位 GLES20.glActiveTexture(GLES20.GL_TEXTURE0); // videoTexture.bindTextureY(); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[cid][0]); GLES20.glUniform1i(tex_y, 0); GLES20.glActiveTexture(GLES20.GL_TEXTURE1); // videoTexture.bindTextureU(); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[cid][1]); GLES20.glUniform1i(tex_u, 1); GLES20.glActiveTexture(GLES20.GL_TEXTURE2); // videoTexture.bindTextureV(); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[cid][2]); GLES20.glUniform1i(tex_v, 2); GLES20.glActiveTexture(GLES20.GL_TEXTURE3); // videoTexture.bindTextureA(); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[cid][3]); GLES20.glUniform1i(tex_a, 3); if (Define.isCmbExist){ if (PEColorTune.updateGainList[cid] == 0){ // PEColorTune.undateIfNeedTurn7(cid,textures[cid]);//更新调色数据 PEColorTune.undateIfNeedTurn(cid,texturesTurn[cid]);//更新调色数据 PEColorTune.updateGainList[cid] = cid+1; } // if (PEColorTune.colorTurnFlag){ // PEColorTune.undateIfNeedTurn(cid,textures[cid]); // } GLES20.glActiveTexture(GLES20.GL_TEXTURE4); // GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[cid][4]); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texturesTurn[cid][0]); GLES20.glUniform1i(turn_y, 4); GLES20.glActiveTexture(GLES20.GL_TEXTURE5); // GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[cid][5]); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texturesTurn[cid][1]); GLES20.glUniform1i(turn_u, 5); GLES20.glActiveTexture(GLES20.GL_TEXTURE6); // GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[cid][6]); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texturesTurn[cid][2]); GLES20.glUniform1i(turn_v, 6); } if (Define.mode == Define.MODE_GLOBULAR){ drawGlobular(cid); } if (Define.mode == Define.MODE_ORIGINAL){ drawOriginal(cid,squares); } } if (Define.showVR == true){ GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId.get(0)); GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,0); GLES20.glUniform1i(tex_type,0); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureId.get(0)); GLES20.glUniform1i(tex_y,0); PEMatrix.makeUnit(mMatrix); GLES20.glUniformMatrix4fv(shaderMatrix,1,false,mMatrix,0); GLES20.glVertexAttribPointer(shaderVertex,2,GLES20.GL_FLOAT,false,0,VR_VERTEX_COORD); GLES20.glEnableVertexAttribArray(shaderVertex); GLES20.glVertexAttribPointer(shaderTexture,2,GLES20.GL_FLOAT,false,0,VR_TEXTURE_COORD); GLES20.glEnableVertexAttribArray(shaderTexture); GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,12); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D,0); } } private void drawOriginal(int i,PESquare squares[]) { // GLES20.glUniform1i(tex_type, 2); do { switch (cameraNum){ case 5: squares[i].mVertexBuffer5.position(18*i); GLES20.glVertexAttribPointer(shaderVertex, 3,GLES20.GL_FLOAT,false, 12,squares[i].mVertexBuffer5); GLES20.glVertexAttribPointer(shaderTexture,2,GLES20.GL_FLOAT,false,0,squares[i].mTextureFlipBuffer5); break; case 8: squares[i].mVertexBuffer8.position(18*i); GLES20.glVertexAttribPointer(shaderVertex, 3,GLES20.GL_FLOAT,false,12,squares[i].mVertexBuffer8); GLES20.glVertexAttribPointer(shaderTexture,2,GLES20.GL_FLOAT,false,0,squares[i].mTextureFlipBuffer8); break; default: squares[i].mVertexBuffer.position(18*i); GLES20.glVertexAttribPointer(shaderVertex, 3,GLES20.GL_FLOAT,false,12,squares[i].mVertexBuffer); GLES20.glVertexAttribPointer(shaderTexture,2,GLES20.GL_FLOAT,false,0,squares[i].mTextureBuffer); break; } // // 允许顶点位置数据数组 GLES20.glEnableVertexAttribArray(shaderVertex); GLES20.glEnableVertexAttribArray(shaderTexture); GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 6); // 禁用这个指向三角形的顶点数组(注释无异) GLES20.glDisableVertexAttribArray(shaderVertex); GLES20.glDisableVertexAttribArray(shaderTexture); }while (false); } private void drawGlobular(int cid) { //给uniform变量传值,变量的值应该由getUniformLocation函数返回, GLES20.glUniform1i(tex_type, 1); //给uniform变量传矩阵:参数依次为:更改的变量,矩阵个数,是否要转置矩阵,矩阵的指针,偏移。 GLES20.glUniformMatrix4fv(shaderMatrix, 1, false, mMatrix, 0);//更改矩阵或矩阵数组 //绑定vboVer,顶点位置坐标 GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER,vboVer[cid][0]); GLES20.glVertexAttribPointer(shaderVertex, 3, GLES20.GL_FLOAT, false, 0, 0); GLES20.glEnableVertexAttribArray(shaderVertex); //绑定vboTex,纹理位置坐标 GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER,vboTex[cid][0]); GLES20.glVertexAttribPointer(shaderTexture, 2, GLES20.GL_FLOAT, false, 0, 0); GLES20.glEnableVertexAttribArray(shaderTexture); GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0); GLES20.glViewport(0,0,width,height); GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, verCoordbuffer.capacity() / 3); GLES20.glDisableVertexAttribArray(shaderVertex); GLES20.glDisableVertexAttribArray(shaderTexture); } public void glResize(){ // GLES20.glViewport(0,0,width,height); this.fovy = Define.fovy; Float aspect ; if (Define.showVR == true){ aspect = (new Float(width/2))/(new Float(height)); }else { aspect = (new Float(width))/(new Float(height)); } Float zNear = 0.1f; Float zFar = 2000.0f; Float top = zNear*(new Float(Math.tan(fovy*PI/360.0))); Float bottom = -top; Float left = bottom * aspect; Float right = top * aspect; PEMatrix.frustum(mProjMatrix,left,right,bottom,top,zNear,zFar); } } <file_sep>/app/src/main/cpp/PES/PESDecoder.cpp // // Created by tir on 2016/7/29. // #include "PESDecoder.h" #include "../MainController.h" static void runDecoderRunLoop(void *arg) { int code = *(int *)arg; mc->pesPano->decoders[code]->runLoop(); } PESDecoder::PESDecoder() { decoder = NULL; info = NULL; isAvailableToDisplay = false; status = Closed; newStatus = Closed; pthread_cond_init(&cond, NULL); pthread_mutex_init(&condMutex,NULL); } PESDecoder::~PESDecoder() { if (decoder != NULL) { AMediaCodec_stop(decoder); AMediaCodec_delete(decoder); } if (info != NULL) { delete info; } if (pesFile != NULL) { delete pesFile; } LOGI("PESDec:Decoder %d deinit.", decoderCode); } bool PESDecoder::setFile(char *sample, int code, int width, int height) { decoderCode = code; pesFile = new PESFile(); if (pesFile->openFile(sample) == true) { info = new AMediaCodecBufferInfo(); decoder = AMediaCodec_createDecoderByType("video/avc"); AMediaFormat * format = AMediaFormat_new(); AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, "video/avc"); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_WIDTH, width); AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_HEIGHT, height); if (AMediaCodec_configure(decoder, format, NULL, NULL, 0) == 0) { AMediaCodec_start(decoder); newStatus = ReadyToPlay; return true; } else { mc->setErrorMessage("注册解码器失败!\n播放器不支持此设备!"); LOGI("PESDec: Create mediacodec failed."); return false; } } else { LOGI("PESDec: Open pes file failed in code %d file %s.", decoderCode, sample); return false; } } void PESDecoder::pause() { if (newStatus == Playing) { newStatus = Paused; } } void PESDecoder::resume() { if (newStatus == Paused) { newStatus = Playing; } } void PESDecoder::stop() { newStatus = Stoped; pthread_cond_signal(&cond); pesFile->closeFile(); } void PESDecoder::run() { jumpTo(0); if (newStatus == ReadyToPlay) { newStatus = Playing; } pthread_create(&thread, NULL, (void * (*)(void *))&runDecoderRunLoop, (void *)&decoderCode); } void PESDecoder::runLoop() { LOGI("PESDec:Decoder %d start runloop.", decoderCode); jumpTo(0); while (true) { status = newStatus; if (status == Playing) { if (pesFile->timestampIndex < pesFile->timestampCount - 1 - 1) { if (mc->timeline >= pesFile->tsList[pesFile->timestampIndex]) { step(); mc->decodeFrameRateStep(); } } } pthread_cond_wait(&cond, &condMutex); //解码线程等待唤醒 if (status == Stoped) { break; } } LOGI("PESDec:Decoder %d break runloop.", decoderCode); } float PESDecoder::jumpTo(float ts) { return pesFile->jumpTo(ts); } void PESDecoder::step() { LOGI("PECLIENT:step"); ssize_t inIndex = AMediaCodec_dequeueInputBuffer(decoder, 100000); if (inIndex >= 0) { size_t capacity; uint8_t *buffer = AMediaCodec_getInputBuffer(decoder, inIndex, &capacity); int length = setData(buffer, capacity); if (length >= 0) { AMediaCodec_queueInputBuffer(decoder, inIndex, 0, length, 0, 0); } else { AMediaCodec_queueInputBuffer(decoder, inIndex, 0, 0, 0, 0); return; } } else { AMediaCodec_queueInputBuffer(decoder, inIndex, 0, 0, 0, 0); return; } ssize_t outIndex = AMediaCodec_dequeueOutputBuffer(decoder, info, 100000); switch (outIndex) { case AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED: break; case AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED: AMediaCodec_getOutputFormat(decoder); break; case AMEDIACODEC_INFO_TRY_AGAIN_LATER: break; default: size_t capacity = 0; uchar * data = AMediaCodec_getOutputBuffer(decoder, outIndex, &capacity); memcpy(texData, data, capacity); isAvailableToDisplay = true; AMediaCodec_releaseOutputBuffer(decoder, outIndex, true); break; } if ((info->flags && AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) != 0) { newStatus = Stoped; LOGI("Decoder %d decode done", decoderCode); } } int PESDecoder::setData(uint8_t * buffer, size_t size) { return pesFile->setData(buffer, size); } <file_sep>/app/src/main/cpp/PER/PERBinFile.h // // Created by tir on 2016/9/29. // #ifndef PANO_PERBINFILE_H #define PANO_PERBINFILE_H #include "../Common.h" #include "../PES/PESBinFile.h" class PERBinFile: public PESBinFile { public: PERBinFile(); ~PERBinFile(); bool openData(uchar * data); private: }; #endif //PANO_PERBINFILE_H <file_sep>/app/src/main/cpp/OnlineSDK/CClient/NBSocketClient.h #ifndef CAM360_LIBCAM_CLIENT_NBSOCKETCLIENT_H_ #define CAM360_LIBCAM_CLIENT_NBSOCKETCLIENT_H_ #include "ClientListener.h" #include "MemoryPool.h" #include <atomic> #include <thread> #include <deque> #include <mutex> class CNBSocketClient : public CClientListener { public: CNBSocketClient(); ~CNBSocketClient(); protected: virtual bool Connect(const char *ipaddr, USHORT port) override; virtual bool Disconnect() override; virtual std::string GetHost() override; virtual void ClientAlloc() override; virtual void ClientRelease() override; virtual bool Send(const BYTE* pBuffer, int iLength, int iOffset) override; virtual bool SendPackets(const WSABUF pBuffers[], int iCount) override; private: int m_socket; bool m_isConnected; std::thread m_WorkerThread; std::mutex m_send_deque_mutex; CMemoryItem *m_send_buff; CMemoryItem *m_worker_send_buff; CMemoryItem *m_worker_recv_buff; CMemoryPool m_bufferpool; void WorkerThread(); bool nbRead(bool *eof); bool nbWrite(); bool nonFatalError(); int getError(); bool OnReceive(); void OnError(); }; #endif <file_sep>/app/src/main/cpp/include/xrapi/XrApiSystemUtils.h // // Created by SVR00003 on 2017/9/26. // #ifndef XRSDK_XRAPISYSTEMUTILS_H #define XRSDK_XRAPISYSTEMUTILS_H #include "XrApiConfig.h" #include "XrApiTypes.h" #if defined( __cplusplus ) extern "C" { #endif typedef enum { XRAPI_SYS_UI_GLOBAL_MENU, // Display the Universal Menu. XRAPI_SYS_UI_CONFIRM_QUIT_MENU, // Display the 'Confirm Quit' Menu. XRAPI_SYS_UI_KEYBOARD_MENU, // Display a Keyboard Menu for editing a single string. XRAPI_SYS_UI_FILE_DIALOG_MENU, // Display a Folder Browser Menu for selecting the path to a file or folder. } xrSystemUIType; // Display a specific System UI. XRAPI_EXPORT bool xrapiShowSystemUI( const xrJava * java, const xrSystemUIType type ); //set performance level XRAPI_EXPORT void xrapiSetVrSystemPerformance(const int gpuLevel, const int cpuLevel); //release performance to lower XRAPI_EXPORT void xrapiReleaseVrSystemPerformance(); //set sched fifo XRAPI_EXPORT void xrapiSetSchedFifo(const int tid, const int cpu, const int priority, const int schedPolicy); // ----DEPRECATED // This function is DEPRECATED. Please do not write any new code which // relies on it's use. // Display a specific System UI and pass extra JSON text data. XRAPI_EXPORT bool xrapiShowSystemUIWithExtra( const xrJava * java, const xrSystemUIType type, const char * extraJsonText ); // Launch the Oculus Home application. // NOTE: This exits the current application by executing a finishAffinity. XRAPI_EXPORT void xrapiReturnToHome( const xrJava * java ); // Display a Fatal Error Message using the System UI. XRAPI_EXPORT void xrapiShowFatalError( const xrJava * java, const char * title, const char * message, const char * fileName, const unsigned int lineNumber ); #if defined( __cplusplus ) } // extern "C" #endif #endif //XRSDK_XRAPISYSTEMUTILS_H <file_sep>/app/src/main/assets/frag.sh precision mediump float; varying lowp vec2 tc; uniform sampler2D SamplerY; uniform sampler2D SamplerU; uniform sampler2D SamplerV; void main(void){ mediump vec3 yuv; lowp vec3 rgb; yuv.x = texture2D(SamplerY, tc).r; yuv.y = texture2D(SamplerU, tc).r - 0.5; yuv.z = texture2D(SamplerV, tc).r - 0.5; rgb = mat3( 1, 1, 1, 0, -0.39465, 2.03211, 1.13983, -0.58060, 0 ) * yuv; gl_FragColor = vec4(rgb,0); } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PEBinFile.java package panoeye.pelibrary; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by tir on 2016/12/8. */ /*调用了PEBinFileInfo和PECameraConfig*/ public class PEBinFile { private static final String TAG = "PEBinFile"; public PEBinFileInfo info = new PEBinFileInfo();//bin文件信息 public Map<Integer,PECameraConfig> camConfigs = new HashMap<>();//镜头id跟相机配置对照表 public List<Integer> cidList = new ArrayList<>();//镜头id列表 PEBinFile(){} //构造函数 public PEBinFile(String path) throws PEError{ RandomAccessFile pBinFile = PEFile.fopen(path);//打开bin文件 //获取bin文件信息到info info = new PEBinFileInfo(pBinFile); Size subSize = getSubSize();//获取子码流尺寸大小 //依次读取每个模组配置 for (Integer i = 0; i < info.camCount; i++) { PECameraConfig camConfig = PECameraConfig.read(pBinFile);//获取相机配置到camConfig camConfig.subSize = subSize; camConfigs.put(camConfig.cid,camConfig);//bin文件中一个cid对应一个相机配置,存放次序不同 cidList.add(camConfig.cid);//例如首先读取出来的可能是2号相机及配置,到时候根据cid找到相应的配置 // Log.d(TAG, "PEBinFile: cid:"+camConfig.cid);//0,6,5,4,3,2,1,7 } PEFile.fclose(pBinFile);//释放bin文件 } //根据相机型号设置子码流尺寸的大小 private Size getSubSize(){ //默认大小为352*288 Size ret = new Size(Define.CIF_COL,Define.CIF_ROW); if (info.model_type == Define.PE_B) { ret = new Size(Define.QCIF_COL, Define.QCIF_ROW); } if(info.model_type == Define.PE_M && info.sub_model_type == 0){ ret = new Size(Define.QCIF_COL, Define.QCIF_ROW); } return ret; } } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/Size.java package panoeye.pelibrary; /** * Created by tir on 2016/12/8. */ public class Size { public Integer width = 0; public Integer height = 0; public Size(Integer width, Integer height){ this.width=width; this.height=height; } } <file_sep>/app/src/main/cpp/PER/PERPackage.cpp // // Created by tir on 2016/10/10. // #include "PERPackage.h" PERPackage::PERPackage(int _len, uchar *_data, long long _timestamp, int _width, int _height, int _id) { len = _len; data = _data; timestamp = _timestamp; width = _width; height = _height; id = _id; } PERPackage::~PERPackage() { delete[] data; }<file_sep>/app/src/main/cpp/include/xrapi/XrApiConfig.h // // Created by SVR00003 on 2017/9/16. // #ifndef XRSDK_XRAPICONFIG_H #define XRSDK_XRAPICONFIG_H #if defined( XRAPI_ENABLE_EXPORT ) #define XRAPI_EXPORT __attribute__( ( __visibility__( "default" ) ) ) #else #define XRAPI_EXPORT #endif #define XRAPI_DEPRECATED __attribute__( ( deprecated ) ) #if defined( __x86_64__ ) || defined( __aarch64__ ) || defined( _WIN64 ) #define XRAPI_64_BIT #else #define XRAPI_32_BIT #endif #if defined( __cplusplus ) && __cplusplus >= 201103L #define XRAPI_STATIC_ASSERT( exp ) static_assert( exp, #exp ) #endif #if !defined( XRAPI_STATIC_ASSERT ) && defined( __clang__ ) #if __has_feature( cxx_static_assert ) || __has_extension( cxx_static_assert ) #define XRAPI_STATIC_ASSERT( exp ) static_assert( exp ) #endif #endif #if !defined( XRAPI_STATIC_ASSERT ) #if defined( __COUNTER__ ) #define XRAPI_STATIC_ASSERT( exp ) XRAPI_STATIC_ASSERT_ID( exp, __COUNTER__ ) #else #define XRAPI_STATIC_ASSERT( exp ) XRAPI_STATIC_ASSERT_ID( exp, __LINE__ ) #endif #define XRAPI_STATIC_ASSERT_ID( exp, id ) XRAPI_STATIC_ASSERT_ID_EXPANDED( exp, id ) #define XRAPI_STATIC_ASSERT_ID_EXPANDED( exp, id ) typedef char assert_failed_##id[(exp) ? 1 : -1] #endif #if defined( __COUNTER__ ) #define XRAPI_PADDING( bytes ) XRAPI_PADDING_ID( bytes, __COUNTER__ ) #else #define XRAPI_PADDING( bytes ) XRAPI_PADDING_ID( bytes, __LINE__ ) #endif #define XRAPI_PADDING_ID( bytes, id ) XRAPI_PADDING_ID_EXPANDED( bytes, id ) #define XRAPI_PADDING_ID_EXPANDED( bytes, id ) unsigned char dead##id[(bytes)] #define XRAPI_ASSERT_TYPE_SIZE( type, bytes ) XRAPI_STATIC_ASSERT( sizeof( type ) == (bytes) ) #if defined( XRAPI_64_BIT ) #define XRAPI_PADDING_32_BIT( bytes ) #if defined( __COUNTER__ ) #define XRAPI_PADDING_64_BIT( bytes ) XRAPI_PADDING_ID( bytes, __COUNTER__ ) #else #define XRAPI_PADDING_64_BIT( bytes ) XRAPI_PADDING_ID( bytes, __LINE__ ) #endif #define XRAPI_ASSERT_TYPE_SIZE_32_BIT( type, bytes ) #define XRAPI_ASSERT_TYPE_SIZE_64_BIT( type, bytes ) XRAPI_STATIC_ASSERT( sizeof( type ) == (bytes) ) #else #define XRAPI_ASSERT_TYPE_SIZE( type, bytes ) XRAPI_STATIC_ASSERT( sizeof( type ) == (bytes) ) #if defined( __COUNTER__ ) #define XRAPI_PADDING_32_BIT( bytes ) XRAPI_PADDING_ID( bytes, __COUNTER__ ) #else #define XRAPI_PADDING_32_BIT( bytes ) XRAPI_PADDING_ID( bytes, __LINE__ ) #endif #define XRAPI_PADDING_64_BIT( bytes ) #define XRAPI_ASSERT_TYPE_SIZE_32_BIT( type, bytes ) XRAPI_STATIC_ASSERT( sizeof( type ) == (bytes) ) #define XRAPI_ASSERT_TYPE_SIZE_64_BIT( type, bytes ) #endif #endif //XRSDK_XRAPICONFIG_H <file_sep>/app/src/main/java/com/panoeye/peplayer/map/PanoMap.java package com.panoeye.peplayer.map; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.map.BitmapDescriptorFactory; import com.baidu.mapapi.map.CircleOptions; import com.baidu.mapapi.map.InfoWindow; import com.baidu.mapapi.map.MapPoi; import com.baidu.mapapi.map.MapStatus; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.Marker; import com.baidu.mapapi.map.MarkerOptions; import com.baidu.mapapi.map.MyLocationConfiguration; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; import com.panoeye.peplayer.peonline.ConnectManager; import com.panoeye.peplayer.PlayOnline; import com.panoeye.peplayer.R; import java.io.File; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Collections; import panoeye.pelibrary.Define; import static com.panoeye.peplayer.ConnectPage.Init; import static com.panoeye.peplayer.ConnectPage.connectManager; import static com.panoeye.peplayer.map.ParseXML.createXMLByDOM; import static com.panoeye.peplayer.map.ParseXML.parseXMLByDOM; import static com.panoeye.peplayer.map.ParseXML.editXMLByDOM; /** * Created by Administrator on 2018/3/14. */ public class PanoMap extends AppCompatActivity implements SensorEventListener { private static final String TAG = "PanoMap"; // 定位相关 LocationClient mLocClient; public PanoMap.MyLocationListenner myListener = new PanoMap.MyLocationListenner(); private MyLocationConfiguration.LocationMode mCurrentMode; BitmapDescriptor mCurrentMarker; private static final int accuracyCircleFillColor = 0xAAFFFF88; private static final int accuracyCircleStrokeColor = 0xAA00FF00; private SensorManager mSensorManager; private Double lastX = 0.0; private int mCurrentDirection = 0; private double mCurrentLat = 0.0; private double mCurrentLon = 0.0; private float mCurrentAccracy; MapView mMapView; BaiduMap mBaiduMap; // UI相关 RadioGroup.OnCheckedChangeListener radioButtonListener; Button requestLocButton; boolean isFirstLoc = true; // 是否首次定位 private MyLocationData locData; private float direction; // 初始化全局 bitmap 信息,不用时及时 recycle BitmapDescriptor bdA = BitmapDescriptorFactory .fromResource(R.drawable.icon_marka); BitmapDescriptor bdB = BitmapDescriptorFactory .fromResource(R.drawable.icon_markb); BitmapDescriptor bdC = BitmapDescriptorFactory .fromResource(R.drawable.icon_markc); BitmapDescriptor bdD = BitmapDescriptorFactory .fromResource(R.drawable.icon_markd); BitmapDescriptor bd = BitmapDescriptorFactory .fromResource(R.drawable.icon_gcoding); BitmapDescriptor bdGround = BitmapDescriptorFactory .fromResource(R.drawable.ground_overlay); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_location); requestLocButton = (Button) findViewById(R.id.button1); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);//获取传感器管理服务 //设置定位模式 mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL; requestLocButton.setText("普通"); View.OnClickListener btnClickListener = new View.OnClickListener() { public void onClick(View v) { switch (mCurrentMode) { case NORMAL: requestLocButton.setText("跟随"); mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING; mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration( mCurrentMode, true, mCurrentMarker)); MapStatus.Builder builder = new MapStatus.Builder(); builder.overlook(0); mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); break; case COMPASS: requestLocButton.setText("普通"); mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL; mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration( mCurrentMode, true, mCurrentMarker)); MapStatus.Builder builder1 = new MapStatus.Builder(); builder1.overlook(0); mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder1.build())); break; case FOLLOWING: requestLocButton.setText("罗盘"); mCurrentMode = MyLocationConfiguration.LocationMode.COMPASS; mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration( mCurrentMode, true, mCurrentMarker)); break; default: break; } int ret = mLocClient.requestLocation(); Log.e("log", "onClick: "+ret+mLocClient.isStarted());//false if (!mLocClient.isStarted()) { // mLocClient.stop(); // mLocClient.start(); // mLocClient.restart(); Log.d("log", "onClick: "+mLocClient.isStarted());//false } } }; requestLocButton.setOnClickListener(btnClickListener); RadioGroup group = (RadioGroup) this.findViewById(R.id.radioGroup); radioButtonListener = new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.defaulticon) { // 传入null则,恢复默认图标 mCurrentMarker = null; mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration( mCurrentMode, true, null)); } if (checkedId == R.id.customicon) { // 修改为自定义marker(定位图标) mCurrentMarker = BitmapDescriptorFactory .fromResource(R.drawable.arrow);//icon_geo //设置自定义样式(定位模式,是否开启方向,自定义图标样式,自定义精度圈填充颜色,自定义精度圈边框颜色) mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration( mCurrentMode, true, mCurrentMarker, accuracyCircleFillColor, accuracyCircleStrokeColor)); } } }; group.setOnCheckedChangeListener(radioButtonListener); // 地图初始化 mMapView = (MapView) findViewById(R.id.bmapView); mBaiduMap = mMapView.getMap(); // 开启定位图层 mBaiduMap.setMyLocationEnabled(true); // 定位初始化 mLocClient = new LocationClient(this); mLocClient.registerLocationListener(myListener); // mLocClient.registerNotifyLocationListener(myListener); LocationClientOption option = new LocationClientOption(); // option.setOpenGps(true); // 打开gps option.setCoorType("bd09ll"); // 设置坐标类型 option.setScanSpan(0);// 可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 option.setLocationMode(LocationClientOption.LocationMode.Battery_Saving); // option.setServiceName("com.baidu.location.service_v2.9"); option.setIgnoreKillProcess(true);// 可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 //可选,定位SDK内部是一个service,并放到了独立进程。 //设置是否在stop的时候杀死这个进程,默认(建议)不杀死,即setIgnoreKillProcess(true) mLocClient.setLocOption(option); mLocClient.start(); if (isWiFiActive(this)){ LatLng llnb = new LatLng(29.925738,121.637416); MapStatus.Builder builder = new MapStatus.Builder(); builder.target(llnb).zoom(17.0f); mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); } /* if (!isNetworkActive()){ LatLng llnb = new LatLng(29.925738,121.637416); MapStatus.Builder builder = new MapStatus.Builder(); builder.target(llnb).zoom(17.0f); mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); }*/ // Intent startIntent = new Intent(this,com.baidu.location.f.class); // startService(startIntent); Log.e("log", "onCreate: "+mLocClient.isStarted());//false Log.e("log", "onCreate: "+mLocClient.getVersion());//7.2.1 initOverlay(); initListener(); } public void initOverlay() { // add marker overlay LatLng llA = new LatLng(29.92235, 121.633338); LatLng llB = new LatLng(29.927743, 121.641416); LatLng llC = new LatLng(29.92335, 121.641416); LatLng llD = new LatLng(29.925743, 121.637416); File sd_path = Environment.getExternalStorageDirectory(); File file_cfg_dir = new File(sd_path.getPath() + "//pano//param"); File file_cfg = new File(file_cfg_dir.getPath(),"cameramap.xml"); String IP = null; String bin = null; int cameraType = 0; ArrayList<Camera>cameras = (ArrayList<Camera>)parseXMLByDOM(file_cfg); for (Camera camera:cameras){ Log.d(TAG, "initOverlay: id:"+camera.getId()); if (camera.getId() != -1){ IP = camera.getIP(); bin = camera.getBin(); cameraType = camera.getCameraType(); } } Bundle bundle = new Bundle(); bundle.putString("IP",IP); bundle.putString("bin",bin); bundle.putInt("cameraType",cameraType); MarkerOptions ooA = new MarkerOptions().position(llA).icon(bdA) .zIndex(9).draggable(true).extraInfo(bundle); // if (animationBox.isChecked()) { // 掉下动画 ooA.animateType(MarkerOptions.MarkerAnimateType.drop); // } mMarkerA = (Marker) (mBaiduMap.addOverlay(ooA)); MarkerOptions ooB = new MarkerOptions().position(llB).icon(bdB) .zIndex(5); // if (animationBox.isChecked()) { // 掉下动画 ooB.animateType(MarkerOptions.MarkerAnimateType.drop); // } mMarkerB = (Marker) (mBaiduMap.addOverlay(ooB)); MarkerOptions ooC = new MarkerOptions().position(llC).icon(bdC) .zIndex(9).draggable(true).extraInfo(bundle); // if (animationBox.isChecked()) { // 掉下动画 ooC.animateType(MarkerOptions.MarkerAnimateType.drop); // } mMarkerC = (Marker) (mBaiduMap.addOverlay(ooC)); } private Marker mMarkerA; private Marker mMarkerB; private Marker mMarkerC; private Marker mMarkerD; private InfoWindow mInfoWindow; private void initListener() { mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() { @Override public void onTouch(MotionEvent event) { } }); mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() { /** * 单击地图 */ public void onMapClick(LatLng point) { // touchType = "单击地图"; // currentPt = point; // updateMapState(); Toast.makeText(PanoMap.this,"点击位置:" + point.latitude + ", " + point.longitude,Toast.LENGTH_LONG).show(); } /** * 单击地图中的POI点 */ public boolean onMapPoiClick(MapPoi poi) { // touchType = "单击POI点"; // currentPt = poi.getPosition(); // updateMapState(); return false; } }); mBaiduMap.setOnMapLongClickListener(new BaiduMap.OnMapLongClickListener() { /** * 长按地图 */ public void onMapLongClick(LatLng point) { // touchType = "长按"; // currentPt = point; // updateMapState(); MarkerOptions ooD = new MarkerOptions().position(point).icon(bd) .zIndex(9).draggable(true); // if (animationBox.isChecked()) { // 掉下动画 //ooD.animateType(MarkerOptions.MarkerAnimateType.drop); // } mMarkerD = (Marker) (mBaiduMap.addOverlay(ooD)); //从xml创建要显示的View,并设置相应的值 LayoutInflater inflater = LayoutInflater.from(getApplicationContext()); View view = inflater.inflate(R.layout.layout_map_item, null); TextView txtLatLng = (TextView)view.findViewById(R.id.text_item_latlng); final EditText background = (EditText) view.findViewById(R.id.ed_item_background); final EditText keyWord = (EditText) view.findViewById(R.id.ed_item_keyword); Button btnSearch = (Button) view.findViewById(R.id.btn_search); Button btnCancel = (Button) view.findViewById(R.id.btn_cancel); txtLatLng.setText("纬度:"+point.latitude+",经度:"+point.longitude); final LatLng lngFinal = point; //点击view上面的检索按钮调用方法 btnSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Log.d("WorkMainActivity","搜索附近500米"); mBaiduMap.clear();//清空地图上的标记 String circumBackground = background.getText().toString(); if(null==circumBackground||"".equals(circumBackground)){ return; }else { String keyWordString = keyWord.getText().toString(); if(null==keyWordString||"".equals(keyWordString)){ return; }else { int circum = Integer.parseInt(circumBackground); // PoiNearbySearchOption poiNearbySearchOption = new PoiNearbySearchOption(); // poiNearbySearchOption.location(lngFinal); //以长按坐标点为中心,画指定半径的圆,并制定透明度为100,作为搜索范围 CircleOptions circleOptions = new CircleOptions(); circleOptions.center(lngFinal); circleOptions.radius(circum); circleOptions.fillColor(Color.argb(100,28,95,167)); mBaiduMap.addOverlay(circleOptions); // poiNearbySearchOption.keyword(keyWordString); // poiNearbySearchOption.radius(circum); // PoiSearch poiSearch = PoiSearch.newInstance(); // poiSearch.searchNearby(poiNearbySearchOption); // poiSearch.setOnGetPoiSearchResultListener(WorkMainActivity.this); } } } }); //点击取消按钮 btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Log.d("WorkMainActivity","取消搜索"); mBaiduMap.hideInfoWindow(); } }); InfoWindow infoWindow = new InfoWindow(view, lngFinal, -47); mBaiduMap.showInfoWindow(infoWindow); } }); mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() { public boolean onMarkerClick(final Marker marker) { Button button = new Button(getApplicationContext()); button.setBackgroundResource(R.drawable.popup); InfoWindow.OnInfoWindowClickListener listener = null; if (marker == mMarkerA) { button.setText("播放全景"); button.setTextColor(Color.BLACK); button.setWidth(300); listener = new InfoWindow.OnInfoWindowClickListener() { public void onInfoWindowClick() { // LatLng ll = marker.getPosition(); // LatLng llNew = new LatLng(ll.latitude + 0.005, // ll.longitude + 0.005); // marker.setPosition(llNew); mBaiduMap.hideInfoWindow(); playPano(mMarkerA.getExtraInfo().getString("IP"),mMarkerA.getExtraInfo().getString("bin"),mMarkerA.getExtraInfo().getInt("cameraType")); } }; LatLng ll = marker.getPosition(); mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), ll, -47, listener); mBaiduMap.showInfoWindow(mInfoWindow); }else if (marker == mMarkerB) { button.setText("写入xml"); button.setTextColor(Color.BLACK); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // marker.setIcon(bd); File sd_path; File file_cfg_dir; File file_cfg; //获取SD卡根目录 sd_path = Environment.getExternalStorageDirectory(); //判断文件夹是否存在 file_cfg_dir = new File(sd_path.getPath() + "//pano//param"); //判断配置文件是否存在 file_cfg = new File(file_cfg_dir.getPath(),"cameramap.xml"); createXMLByDOM(file_cfg); mBaiduMap.hideInfoWindow(); } }); LatLng ll = marker.getPosition(); mInfoWindow = new InfoWindow(button, ll, -47); mBaiduMap.showInfoWindow(mInfoWindow); }else if (marker == mMarkerC) { button.setText("修改xml"); button.setTextColor(Color.BLACK); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // marker.remove(); File sd_path; File file_cfg_dir; File file_cfg; //获取SD卡根目录 sd_path = Environment.getExternalStorageDirectory(); //判断文件夹是否存在 file_cfg_dir = new File(sd_path.getPath() + "//pano//param"); //判断配置文件是否存在 file_cfg = new File(file_cfg_dir.getPath(),"cameramap.xml"); editXMLByDOM(file_cfg,"2","192.168.20.168","D00010368","5","D168"); mBaiduMap.hideInfoWindow(); } }); LatLng ll = marker.getPosition(); mInfoWindow = new InfoWindow(button, ll, -47); mBaiduMap.showInfoWindow(mInfoWindow); } else if (marker == mMarkerD) { button.setText("删除"); button.setTextColor(Color.BLACK); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { marker.remove(); mBaiduMap.hideInfoWindow(); } }); LatLng ll = marker.getPosition(); mInfoWindow = new InfoWindow(button, ll, -47); mBaiduMap.showInfoWindow(mInfoWindow); } return true; } }); } final private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case 0: pd.dismiss(); Toast.makeText(PanoMap.this," 相机连接成功!",Toast.LENGTH_SHORT).show(); break; case 1: pd.dismiss(); AlertDialog.Builder builder = new AlertDialog.Builder(PanoMap.this); //先得到构造器 builder.setTitle("错误提示"); //设置标题 builder.setMessage("网络连接错误,请检查网络连接!"); //设置内容 //builder.setIcon(R.mipmap.ic_launcher);//设置图标,图片id即可 builder.create(); builder.create().show(); break; case 2: pd.dismiss(); connectManager.closeRTSP(); builder = new AlertDialog.Builder(PanoMap.this); //先得到构造器 builder.setTitle("超時提示"); //设置标题 builder.setMessage("网络连接超时,请重试!"); //设置内容 //builder.setIcon(R.mipmap.ic_launcher);//设置图标,图片id即可 builder.create(); builder.create().show(); break; } } }; private ProgressDialog pd; private void playPano(String IP, final String serialNo,int cameraCnt) { Log.d(TAG, "playPano: IP:"+IP); Log.d(TAG, "playPano: serialNo:"+serialNo); Define.cameraCount = cameraCnt; pd = ProgressDialog.show(this,"loading...","please wait..."); final String head = "rtsp://admin:123456@"; // final String IP = IPAddr.getText().toString(); // final String IP = "192.168.20.178"; int port = 12341; int[] port5 = {12341,12344,12343,12342,12345}; int[] port8 = {12341,12347,12346,12345,12344,12343,12342,12348}; final String end = "/mpeg4"; int fishPort = 554; String fishEnd = "/profile2"; final String[] rtspAddr =new String[Define.cameraCount]; for (int cid=0;cid<Define.cameraCount;cid++){ switch (Define.cameraCount){ case 8: rtspAddr[cid] = head+IP+":"+ port8[cid] +end; break; case 5: rtspAddr[cid] = head+IP+":"+ port5[cid] +end; break; case 1: rtspAddr[cid] = head+IP+":"+ fishPort +fishEnd; break; default: rtspAddr[cid] = head+IP+":"+ port +end; Log.d(TAG, "port: "+port); port++; break; } } final Thread connThread = new Thread(new Runnable() { @Override public void run() { // android.os.Process.setThreadPriority (android.os.Process.THREAD_PRIORITY_LOWEST); // android.os.Process.setThreadPriority (android.os.Process.THREAD_PRIORITY_BACKGROUND); // Thread.currentThread().setPriority(4); // Log.e(TAG, "run:getPriority(): "+Thread.currentThread().getPriority()); Init(Define.cameraCount); connectManager = new ConnectManager(); for (int cid=0;cid<Define.cameraCount;cid++){ final int finalHandle = cid; new Thread(new Runnable(){ @Override public void run() { // android.os.Process.setThreadPriority (android.os.Process.THREAD_PRIORITY_BACKGROUND); // Thread.currentThread().setPriority(6); // Log.d(TAG, "run: getPriority(): "+Thread.currentThread().getPriority()+";cid:"+finalHandle); int ret = connectManager.InitRTSP(rtspAddr[finalHandle],finalHandle); Log.d(TAG, "run: cid:"+finalHandle+";ret-->"+ret); if (ret == 0){ connectManager.flagsDict.put(finalHandle,"Succeed"); Log.d(TAG,"模组"+ finalHandle +"-->RTSPConnect()成功!"); }else { connectManager.flagsDict.put(finalHandle,"Failed"); Log.e(TAG,"模组"+ finalHandle +"-->RTSPConnect()失败!"); connectManager.connErrCnt++; } } }).start(); } int sleepCount = 0; while (true){ Log.d(TAG, "onCreate: true循环,连接相机中..."); Log.d(TAG, "RTSPConnect(): flags.size()-->:"+connectManager.flagsDict.size()); if (connectManager.flagsDict.size() == Define.cameraCount){ if (connectManager.connErrCnt != Define.cameraCount){ Intent intent = new Intent(PanoMap.this,PlayOnline.class); Bundle bundle = new Bundle(); // bundle.putSerializable("serialNo",serialNo.getText().toString()); // bundle.putSerializable("serialNo","E10010078"); bundle.putSerializable("serialNo",serialNo); intent.putExtras(bundle); startActivity(intent); handler.sendEmptyMessage(0); }else { handler.sendEmptyMessage(1); } break; } try { sleepCount++; Log.d(TAG, "onCreate: sleepCount:"+sleepCount); if (sleepCount>=5){ handler.sendEmptyMessage(2); break; } // Thread.yield(); Thread.sleep(2000);//线程休眠2s } catch (InterruptedException e) { e.printStackTrace(); } } } }); // connThread.setPriority(4); connThread.start(); } @Override public void onSensorChanged(SensorEvent sensorEvent) { double x = sensorEvent.values[SensorManager.DATA_X]; if (Math.abs(x - lastX) > 1.0) { mCurrentDirection = (int) x; // Log.d(TAG, "onSensorChanged:方向:"+mCurrentDirection); locData = new MyLocationData.Builder() .accuracy(mCurrentAccracy) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(mCurrentDirection) .latitude(mCurrentLat) .longitude(mCurrentLon) .build(); mBaiduMap.setMyLocationData(locData); } lastX = x; } @Override public void onAccuracyChanged(Sensor sensor, int i) { } /** * 定位SDK监听函数 */ public class MyLocationListenner implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { Log.e("log", "onReceiveLocation: "); // map view 销毁后不在处理新接收的位置 if (location == null || mMapView == null) { return; } mCurrentLat = location.getLatitude(); mCurrentLon = location.getLongitude(); mCurrentAccracy = location.getRadius(); Log.d("log", "onReceiveLocation:纬度:"+mCurrentLat+",经度:"+mCurrentLon+",精度:"+mCurrentAccracy); locData = new MyLocationData.Builder() .latitude(mCurrentLat) .longitude(mCurrentLon) .accuracy(mCurrentAccracy) // 此处设置开发者获取到的方向信息,顺时针0-360 .direction(mCurrentDirection) .build(); mBaiduMap.setMyLocationData(locData); if (isFirstLoc) { isFirstLoc = false; LatLng ll = new LatLng(location.getLatitude(),location.getLongitude()); // LatLng llnb = new LatLng(29.925738,121.637416); MapStatus.Builder builder = new MapStatus.Builder(); builder.target(ll).zoom(18.0f); mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build())); } if (location.getLocType() == BDLocation.TypeGpsLocation) { // GPS类型定位结果 location.getSpeed(); // 速度 单位:km/h,注意:网络定位结果是没有速度的 location.getSatelliteNumber(); // 卫星数目,gps定位成功最少需要4颗卫星 location.getAltitude(); //海拔高度 单位:米 location.getGpsAccuracyStatus(); // gps质量判断 } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) { // 网络类型定位结果 if (location.hasAltitude()) { //如果有海拔高度 location.getAltitude();//单位:米// } location.getOperators();//运营商信息 } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果 // 离线定位成功,离线定位结果也是有效的; Log.d("log", "onReceiveLocation: 离线定位成功"); } else if (location.getLocType() == BDLocation.TypeServerError) { //服务端网络定位失败,可以反馈IMEI号和大体定位时间到<EMAIL>; } else if (location.getLocType() == BDLocation.TypeNetWorkException) { //网络不同导致定位失败,请检查网络是否通畅; } else if (location.getLocType() == BDLocation.TypeCriteriaException) { //无法获取有效定位依据导致定位失败,一般是由于手机的原因,处于飞行模式下一般会造成这种结果,可以试着重启手机; } } // public void onReceivePoi(BDLocation poiLocation) { // } } @Override protected void onPause() { mMapView.onPause(); super.onPause(); } @Override protected void onResume() { mMapView.onResume(); super.onResume(); //为系统的方向传感器注册监听器 mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI); } @Override protected void onStop() { //取消注册传感器监听 mSensorManager.unregisterListener(this); super.onStop(); } @Override protected void onDestroy() { // 退出时销毁定位 mLocClient.stop(); // 关闭定位图层 mBaiduMap.setMyLocationEnabled(false); mMapView.onDestroy(); mMapView = null; super.onDestroy(); } public static boolean isWiFiActive(Context context) { WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); int ipAddress = wifiInfo == null ? 0 : wifiInfo.getIpAddress(); String ip = intToIp(ipAddress); Log.e(TAG, "isWiFiActive: ip-->" + ip ); if (mWifiManager.isWifiEnabled() && ipAddress != 0) { System.out.println("**** WIFI is on"); return true; } else { System.out.println("**** WIFI is off"); return false; } } public static String intToIp(int ipInt) { StringBuilder sb = new StringBuilder(); sb.append(ipInt & 0xFF).append("."); sb.append((ipInt >> 8) & 0xFF).append("."); sb.append((ipInt >> 16) & 0xFF).append("."); sb.append((ipInt >> 24) & 0xFF); return sb.toString(); } public static boolean isNetworkActive(Context context) { String ip; ConnectivityManager conMann = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (mobileNetworkInfo.isConnected()) { ip = getLocalIpAddress(); System.out.println("本地ip-----"+ip); return true; }else if(wifiNetworkInfo.isConnected()) { WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); ip = intToIp(ipAddress); System.out.println("wifi_ip地址为------"+ip); return true; } return false; } private static String getLocalIpAddress() { try { String ipv4; ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface ni: nilist) { ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses()); for (InetAddress address: ialist){ if (!address.isLoopbackAddress()) { ipv4=address.getHostAddress(); return ipv4; } } } } catch (SocketException ex) { Log.e("localip", ex.toString()); } return null; } } <file_sep>/app/src/main/cpp/OnlineSDK/PEClientSDK/PEClientSDK.cpp #if (defined(WIN32) || defined(_WIN32_WCE)) #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <WinSock2.h> #elif defined(__linux__) || defined(__APPLE__) //linux //#include "../CrossPlatformCDefine/CrossPlatformCDefine.h" #endif #include "PEClientSDK.h" #include "PEClient.h" //#include "../../Common.h" #include <android/log.h> #define LOG_TAG "JNI_LOG" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #include <algorithm> #include <atomic> #include <cassert> #include <climits> #include <cmath> #include <cstdio> #include <cstddef> #include <exception> #include <fstream> #include <iostream> #include <map> #include <mutex> #include <numeric> #include <string> #define PE_MAX_CLIENT 200 #define PE_MAX_PREVIEW 2000 #define PE_MAX_FIND 2000 #define PE_MAX_PLAYBACK 2000 #define PE_MAX_DOWNLOAD 2000 typedef struct tag_PE_CLIENT PE_CLIENT; typedef struct tag_PE_CLIENT *LPPE_CLIENT; typedef struct tag_PE_CLIENT_PREVIEW PE_CLIENT_PREVIEW; typedef struct tag_PE_CLIENT_PREVIEW *LPPE_CLIENT_PREVIEW; typedef struct tag_PE_CLIENT_FIND PE_CLIENT_FIND; typedef struct tag_PE_CLIENT_FIND *LPPE_CLIENT_FIND; typedef struct tag_PE_CLIENT_PLAYBACK PE_CLIENT_PLAYBACK; typedef struct tag_PE_CLIENT_PLAYBACK *LPPE_CLIENT_PLAYBACK; typedef struct tag_PE_CLIENT_DOWNLOAD PE_CLIENT_DOWNLOAD; typedef struct tag_PE_CLIENT_DOWNLOAD *LPPE_CLIENT_DOWNLOAD; struct tag_PE_CLIENT{ bool unused; char sDVRIP[200]; WORD wDVRPort; char sUserName[200]; char sPassword[200]; LONG lUserID; CPEClient *lpclient; }; struct tag_PE_CLIENT_PREVIEW{ bool unused; PE_CLIENT_PREVIEWINFO preview_info; PE_CLIENT_SADPINFO sadp_info; LONG lUserID; LONG lRealHandle; INT nHandle; fPERealDataCallBack cbRealDataCallBack; void* pUserData; DWORD lSequenceId[256]; }; struct tag_PE_CLIENT_FIND{ bool unused; LONG lUserID; LONG lFindHandle; long lIndex; long lDataNum; LPPE_CLIENT_FINDDATA lpData; }; struct tag_PE_CLIENT_PLAYBACK{ bool unused; CHAR sFileName[250]; PE_CLIENT_PREVIEWINFO preview_info; PE_CLIENT_SADPINFO sadp_info; PE_CLIENT_FINDDATA find_data; LONG lUserID; LONG lPlayHandle; INT nHandle; fPEPlayDataCallBack cbPlayDataCallBack; void* pUserData; int play_speed; FLOAT total_time; struct tm start_time; DWORD lSequenceId[256]; }; struct tag_PE_CLIENT_DOWNLOAD{ bool unused; LONG lUserID; LONG lFileHandle; INT nHandle; FILE *fp; DWORD dwFileSize; DWORD dwRecvLength; std::string sFileName; }; static volatile long long g_sdk_inited; static volatile long g_api_last_error_code; static std::recursive_mutex g_api_recursive_mutex; // recursive_mutex 是一种递归互斥锁类 static fPEExceptionCallBack g_exception_callback = NULL; static void* g_exception_userdata = NULL; PE_CLIENT g_pe_client[PE_MAX_CLIENT]; PE_CLIENT_PREVIEW g_pe_preview[PE_MAX_PREVIEW]; PE_CLIENT_FIND g_pe_find[PE_MAX_FIND]; PE_CLIENT_PLAYBACK g_pe_playback[PE_MAX_PLAYBACK]; PE_CLIENT_DOWNLOAD g_pe_download[PE_MAX_DOWNLOAD]; inline bool SelectLPPE_CLIENTByUserID(LONG lUserID, LPPE_CLIENT *client){ if (lUserID < 0 || lUserID >= PE_MAX_CLIENT) { g_api_last_error_code = PE_ERRCODE_OUTOFMEM; return false; } std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); if (g_pe_client[lUserID].unused || NULL == g_pe_client[lUserID].lpclient) { g_api_last_error_code = PE_ERRCODE_NULLPOINT; return false; } else{ *client = g_pe_client + lUserID; return true; } } inline bool SelectLPPE_CLIENT_PREVIEWByRealHandle(LONG lRealHandle, LPPE_CLIENT_PREVIEW *preview){ if (lRealHandle < 0 || lRealHandle >= PE_MAX_PREVIEW) { g_api_last_error_code = PE_ERRCODE_NOT_FIND; return false; } std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); if (g_pe_preview[lRealHandle].unused) { g_api_last_error_code = PE_ERRCODE_NULLPOINT; return false; } else{ *preview = g_pe_preview + lRealHandle; return true; } } inline bool SelectLPPE_CLIENT_FILE_LISTByFindHandle(LONG lFindHandle, LPPE_CLIENT_FIND *lplppe_find) { if (lFindHandle < 0 || lFindHandle >= PE_MAX_FIND) { g_api_last_error_code = PE_ERRCODE_NOT_FIND; return false; } std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); if (g_pe_find[lFindHandle].unused){ g_api_last_error_code = PE_ERRCODE_NULLPOINT; return false; } *lplppe_find = g_pe_find + lFindHandle; return true; } inline bool SelectLPPE_CLIENT_PLAYBACKByPlayHandle(LONG lPlayHandle, LPPE_CLIENT_PLAYBACK *playback){ if (lPlayHandle < 0 || lPlayHandle >= PE_MAX_PLAYBACK) { g_api_last_error_code = PE_ERRCODE_OUTOFMEM; return false; } std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_PLAYBACK lppe_playback = g_pe_playback + lPlayHandle; if (g_pe_playback[lPlayHandle].unused) { g_api_last_error_code = PE_ERRCODE_NULLPOINT; return false; } else{ *playback = g_pe_playback + lPlayHandle; return true; } } inline bool SelectLPPE_CLIENT_DOWNLOADByFileHandle(LONG lFileHandle, LPPE_CLIENT_DOWNLOAD *download){ if (lFileHandle < 0 || lFileHandle >= PE_MAX_DOWNLOAD) { g_api_last_error_code = PE_ERRCODE_NOT_FIND; return false; } std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); if (g_pe_download[lFileHandle].unused) { g_api_last_error_code = PE_ERRCODE_NULLPOINT; return false; } else{ *download = g_pe_download + lFileHandle; return true; } } inline bool SelectLPPE_CLIENTByRealHandle(LONG lRealHandle, LPPE_CLIENT *client){ std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_PREVIEW lppe_preview = NULL; if (!SelectLPPE_CLIENT_PREVIEWByRealHandle(lRealHandle, &lppe_preview)) return false; return SelectLPPE_CLIENTByUserID(lppe_preview->lUserID, client); } inline bool SelectLPPE_CLIENT_SADPINFOByUserIDAndChannel(LONG lUserID, LONG lChannel, LPPE_CLIENT_SADPINFO sadp_info) { PE_CLIENT_SADPINFO_LIST sadp_info_list; std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); if (TRUE == PE_Client_GetSadpInfoList(lUserID, &sadp_info_list)){ if (lChannel < 0 || lChannel >= sadp_info_list.wSadpNum) { g_api_last_error_code = PE_ERRCODE_PARAM; return false; } memcpy(sadp_info, sadp_info_list.struSadpInfo + lChannel, sizeof(PE_CLIENT_SADPINFO)); return true; } return false; } void PEThrowException(DWORD dwType, LONG lHandle) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); if (g_exception_callback) g_exception_callback(dwType, lHandle, g_exception_userdata); } inline void Struct_PE_AVFRAME_DATA_Init(CONST LPPE_STREAM_DATA lpInfo, CONST BYTE* pData, CONST int iLength, LPPE_AVFRAME_DATA data) { data->byStreamFormat = 1; //1表示原始流,2表示混合流 data->byESStreamType = 1; //原始流类型,1表示视频,2表示音频 data->byEncoderType = PE_ENCODER_TYPE_H264; //编码格式,其值请参看PE_ENCODER_TYPE枚举定义 data->byFrameType = lpInfo->byFrameType; //数据帧类型,1表示I帧, 2表示P帧, 0表示未知类型 data->wFrameRate = 0; //帧率 data->wBitRate = 0; //当前码率 data->byChannel = lpInfo->byPID; //通道 //data->lSequenceId; //数据帧序号 data->pszData = (CHAR*)pData; //数据 data->lDataLength = iLength; //数据有效长度 data->lImageWidth = lpInfo->lImageWidth; //视频宽度 data->lImageHeight = lpInfo->lImageHeight; //视频高度 data->lTimeStamp = lpInfo->llTimeStamp * 1000; //数据采集时间戳,单位为微秒 } inline void Struct_PE_AVFRAME_DATA_InitMux(CONST LPPE_STREAM_DATA lpInfo, CONST BYTE* pData, CONST int iLength, LPPE_AVFRAME_DATA data) { const size_t head_size = sizeof(PE_AVFRAME_DATA); size_t buff_size = head_size + iLength; char *buff = new char[buff_size]; Struct_PE_AVFRAME_DATA_Init(lpInfo, pData, iLength, LPPE_AVFRAME_DATA(buff)); memcpy(buff + head_size, pData, iLength); memcpy(data, buff, head_size); data->byStreamFormat = 2; data->byChannel = 0; data->lSequenceId = 0; data->pszData = buff; data->lDataLength = buff_size; } bool PEPushRealStreamData(LONG lUserID, LPPE_STREAM_DATA lpInfo, BYTE* pData, int iLength){ LONG lRealHandle = -1; LPPE_CLIENT_PREVIEW lppe_preview = NULL; for (LONG handle = 0; handle < PE_MAX_PREVIEW; ++handle){ lppe_preview = g_pe_preview + handle; if (!lppe_preview->unused && lppe_preview->lUserID == lUserID && lppe_preview->nHandle == lpInfo->byPreviewID){ lRealHandle = lppe_preview->lRealHandle; break; } } if (-1 == lRealHandle) return false; fPERealDataCallBack cbRealDataCallBack = lppe_preview->cbRealDataCallBack; if (NULL == cbRealDataCallBack) return true; PE_AVFRAME_DATA data; //Struct_PE_AVFRAME_DATA_Init(lpInfo, pData, iLength, &data); //data.lSequenceId = lppe_preview->lSequenceId++; Struct_PE_AVFRAME_DATA_InitMux(lpInfo, pData, iLength, &data); LPPE_AVFRAME_DATA(data.pszData)->lSequenceId = lppe_preview->lSequenceId[lpInfo->byPID]++; cbRealDataCallBack(lRealHandle, lppe_preview->sadp_info.sSerialNo, lppe_preview->preview_info.dwStreamType, &data, lppe_preview->pUserData); delete[] data.pszData; return true; } bool PEPushPlaybackStreamData(LONG lUserID, LPPE_STREAM_DATA lpInfo, BYTE* pData, int iLength){ LONG lPlayHandle = -1; LPPE_CLIENT_PLAYBACK lppe_playback = NULL; for (LONG handle = 0; handle < PE_MAX_PLAYBACK; ++handle){ lppe_playback = g_pe_playback + handle; if (!lppe_playback->unused && lppe_playback->lUserID == lUserID && lppe_playback->nHandle == lpInfo->byPreviewID){ lPlayHandle = lppe_playback->lPlayHandle; break; } } if (-1 == lPlayHandle) return false; fPEPlayDataCallBack cbPlayDataCallBack = lppe_playback->cbPlayDataCallBack; if (NULL == cbPlayDataCallBack) return true; PE_AVFRAME_DATA data; //Struct_PE_AVFRAME_DATA_Init(lpInfo, pData, iLength, &data); //data.lSequenceId = lppe_preview->lSequenceId++; Struct_PE_AVFRAME_DATA_InitMux(lpInfo, pData, iLength, &data); LPPE_AVFRAME_DATA(data.pszData)->lSequenceId = lppe_playback->lSequenceId[lpInfo->byPID]++; cbPlayDataCallBack(lPlayHandle, lppe_playback->sFileName, lppe_playback->preview_info.dwStreamType, &data, lppe_playback->pUserData); delete[] data.pszData; return true; } void PEPushStreamData(CONST CPEClient *client, LPPE_STREAM_DATA lpInfo, BYTE* pData, int iLength){ LONG lUserID = -1; for (LONG handle = 0; handle < PE_MAX_CLIENT; ++handle){ if (!g_pe_client[handle].unused && client == g_pe_client[handle].lpclient){ lUserID = handle; break; } } if (-1 == lUserID) return; if (!PEPushRealStreamData(lUserID, lpInfo, pData, iLength)) PEPushPlaybackStreamData(lUserID, lpInfo, pData, iLength); } void PEPushFileData(CONST CPEClient *client, LPPE_FILE_DATA lpInfo, BYTE* pData, int iLength) { LONG lUserID = -1; for (LONG handle = 0; handle < PE_MAX_CLIENT; ++handle){ if (!g_pe_client[handle].unused && client == g_pe_client[handle].lpclient){ lUserID = handle; break; } } if (-1 == lUserID) return; LONG lFileHandle = -1; LPPE_CLIENT_DOWNLOAD lppe_download = NULL; for (LONG handle = 0; handle < PE_MAX_PREVIEW; ++handle){ lppe_download = g_pe_download + handle; if (!lppe_download->unused && lppe_download->lUserID == lUserID && lppe_download->nHandle == lpInfo->byPreviewID){ lFileHandle = lppe_download->lFileHandle; break; } } if (-1 == lFileHandle) return; lppe_download->dwRecvLength += iLength; //fseek(lppe_download->fp, lpInfo->dwOffset,SEEK_SET); fwrite(pData, 1, iLength, lppe_download->fp); } BOOL WINAPI PE_Client_Init() { // lock_guard 是一种锁类的类模板 这里使用类模板定义了模板类对象lck, // 会调用lock_guard类的默认构造函数,对递归互斥锁对象g_api_recursive_mutex进行上锁。 std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); g_sdk_inited++; if (1 == g_sdk_inited) { //////////////////////////////////////////////// for (int i = 0; i < PE_MAX_CLIENT; ++i){ g_pe_client[i].unused = true; g_pe_client[i].lUserID = i; g_pe_client[i].lpclient = NULL; } for (int i = 0; i < PE_MAX_PREVIEW; ++i){ g_pe_preview[i].unused = true; g_pe_preview[i].lRealHandle = i; } for (int i = 0; i < PE_MAX_FIND; ++i){ g_pe_find[i].unused = true; g_pe_find[i].lFindHandle = i; g_pe_find[i].lIndex = 0; g_pe_find[i].lDataNum = 0; g_pe_find[i].lpData = NULL; } for (int i = 0; i < PE_MAX_PLAYBACK; ++i){ g_pe_playback[i].unused = true; g_pe_playback[i].lPlayHandle = i; } for (int i = 0; i < PE_MAX_DOWNLOAD; ++i){ g_pe_download[i].unused = true; g_pe_download[i].lFileHandle = i; } } return TRUE; } BOOL WINAPI PE_Client_Cleanup() { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); g_sdk_inited--; if (0 == g_sdk_inited) { //////////////////////////////////////////////// g_sdk_inited = 1; g_sdk_inited = 0; } else if (g_sdk_inited < 0){ g_sdk_inited = 0; return FALSE; } return TRUE; } BOOL WINAPI PE_Client_SetExceptionCallBack(fPEExceptionCallBack cbExceptionCallBack, void* pUserData) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); g_exception_callback = cbExceptionCallBack; g_exception_userdata = pUserData; return TRUE; } LONG WINAPI PE_Client_Login(CONST CHAR *sDVRIP, WORD wDVRPort, CONST CHAR *sUserName, CONST CHAR *sPassword) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT lppe_client = NULL; for (LONG handle = 0; handle < PE_MAX_CLIENT; ++handle){ if (g_pe_client[handle].unused){ lppe_client = g_pe_client + handle; break; } } if (NULL == lppe_client){ g_api_last_error_code = PE_ERRCODE_OUTOFMEM; return -1; } CPEClient * lpclient = new CPEClient; int error_code = lpclient->Login(sDVRIP, wDVRPort, sUserName, sPassword); if (error_code != PE_ERRCODE_SUCCESS){ delete lpclient; g_api_last_error_code = error_code; return -1; } else{ lppe_client->lpclient = lpclient; strcpy(lppe_client->sDVRIP, sDVRIP); lppe_client->wDVRPort = wDVRPort; strcpy(lppe_client->sUserName, sUserName); strcpy(lppe_client->sPassword, <PASSWORD>); lppe_client->unused = false; return lppe_client->lUserID; } } BOOL WINAPI PE_Client_Logout(LONG lUserID) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lUserID, &lppe_client)) return FALSE; delete lppe_client->lpclient; lppe_client->lpclient = NULL; lppe_client->unused = true; return TRUE; } LONG WINAPI PE_Client_RealPlay(LONG lUserID, LPPE_CLIENT_PREVIEWINFO lpPreviewInfo, fPERealDataCallBack cbRealDataCallBack, void* pUserData) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LOGI("OLPano:NUM:%ld",lpPreviewInfo->lChannel); LPPE_CLIENT_PREVIEW lppe_preview = NULL; for (int i = 0; i < PE_MAX_PREVIEW; ++i){ if (g_pe_preview[i].unused){ lppe_preview = g_pe_preview + i; break; } } if (NULL == lppe_preview){ g_api_last_error_code = PE_ERRCODE_OUTOFMEM; return -1; } LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lUserID, &lppe_client)) return -1; PE_CLIENT_SADPINFO sadp_info; if (!SelectLPPE_CLIENT_SADPINFOByUserIDAndChannel(lUserID, lpPreviewInfo->lChannel, &sadp_info)) return -1; LOGI("PECLIENT:port:%d",lppe_client->wDVRPort); /////////////////////////////////////////////////////////////////// int port = lppe_client->lpclient->GetPEStreamPort((char*)sadp_info.sUUID); LOGI("PECLIENT:wDVRPort:%d",port); lppe_client->lpclient->Logout(); int error_code = lppe_client->lpclient->Login(lppe_client->sDVRIP, port, lppe_client->sUserName, lppe_client->sPassword); if (error_code != PE_ERRCODE_SUCCESS){ delete lppe_client->lpclient; lppe_client->lpclient = NULL; lppe_client->unused = true; g_api_last_error_code = error_code; return -1; } LOGI("PECLIENT:登陆成功:%d",port); lppe_client->wDVRPort = port; //////////////////////////////////////////////////////////////////////////// if (lpPreviewInfo->byProtoType == 0 && lpPreviewInfo->dwLinkMode == 0) { lppe_preview->lUserID = lUserID; memcpy(&(lppe_preview->preview_info), lpPreviewInfo, sizeof(*lpPreviewInfo)); memcpy(&(lppe_preview->sadp_info), &sadp_info, sizeof(sadp_info)); lppe_preview->cbRealDataCallBack = cbRealDataCallBack; lppe_preview->pUserData = pUserData; for (int j = 0; j < 256; ++j) lppe_preview->lSequenceId[j] = 0; LOGI("码流:%d",lpPreviewInfo->dwStreamType); int handle; if (lppe_client->lpclient->RequestStreamData(sadp_info.sUUID, lpPreviewInfo->dwStreamType, &handle)){ lppe_preview->nHandle = handle; lppe_preview->unused = false; return lppe_preview->lRealHandle; } else { g_api_last_error_code = PE_ERRCODE_FAIL; } } return -1; } BOOL WINAPI PE_Client_StopRealPlay(LONG lRealHandle) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_PREVIEW lppe_preview = NULL; if (!SelectLPPE_CLIENT_PREVIEWByRealHandle(lRealHandle, &lppe_preview)) return FALSE; LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lppe_preview->lUserID, &lppe_client)) return FALSE; int nHandle = lppe_preview->nHandle; lppe_preview->unused = true; lppe_client->lpclient->StopStreamData(nHandle); return TRUE; } inline void ConvertStructTmToString(const struct tm* tmp, char* buff, int buff_size) { sprintf(buff, "%0.4d-%0.2d-%0.2d %0.2d:%0.2d:%0.2d.%04u", tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, 0); } template<size_t N> inline void ConvertStructTmToString(const struct tm* ct, char(&buff)[N]){ ConvertStructTmToString(ct, buff, N); } inline void ConvertStringToStructTm(const char* str, struct tm* tmp) { time_t t = time(NULL); *tmp = *localtime(&t); sscanf(str, "%d-%d-%d %d:%d:%d", &tmp->tm_year, &tmp->tm_mon, &tmp->tm_mday, &tmp->tm_hour, &tmp->tm_min, &tmp->tm_sec); tmp->tm_year -= 1900; tmp->tm_mon -= 1; } LONG WINAPI PE_Client_FindFile(LONG lUserID, LPPE_CLIENT_FILECOND pFindCond) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_FIND lppe_find = NULL; for (int i = 0; i < PE_MAX_FIND; ++i){ if (g_pe_find[i].unused){ lppe_find = g_pe_find + i; break; } } if (NULL == lppe_find){ g_api_last_error_code = PE_ERRCODE_OUTOFMEM; return -1; } LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lUserID, &lppe_client)) return -1; PE_CLIENT_SADPINFO sadp_info; if (!SelectLPPE_CLIENT_SADPINFOByUserIDAndChannel(lUserID, pFindCond->lChannel, &sadp_info)) return -1; char begTime[256]; ConvertStructTmToString(&pFindCond->struStartTime, begTime); char endTime[256]; ConvertStructTmToString(&pFindCond->struStopTime, endTime); CClient::RemoteRecordExtInfos info; if (!lppe_client->lpclient->GetRecordFileList(sadp_info.sUUID, begTime, endTime, &info)){ g_api_last_error_code = PE_ERRCODE_FAIL; return -1; } lppe_find->unused = false; lppe_find->lUserID = lUserID; lppe_find->lIndex = 0; long lFileDataNum = info.size(); lppe_find->lDataNum = lFileDataNum; if (lFileDataNum > 0){ lppe_find->lpData = new PE_CLIENT_FINDDATA[lFileDataNum]; for (int i = 0; i < lFileDataNum; ++i) { LPPE_CLIENT_FINDDATA find_data = lppe_find->lpData + i; strcpy(find_data->sFileName, info[i].full_dir.c_str()); //文件名 ConvertStringToStructTm(info[i].record_time.c_str(), &find_data->struStartTime);//文件的开始时间 ConvertStringToStructTm(info[i].end_time.c_str(), &find_data->struStopTime); //文件的结束时间 find_data->dwFileSize=0; //文件的大小 find_data->byLocked=0; //1表示此文件已经被锁定,0表示正常的文件 } } return lppe_find->lFindHandle; } BOOL WINAPI PE_Client_FindNextFile(LONG lFindHandle, LPPE_CLIENT_FINDDATA lpFindData) { LPPE_CLIENT_FIND lppe_find = NULL; if (!SelectLPPE_CLIENT_FILE_LISTByFindHandle(lFindHandle, &lppe_find)) return FALSE; if (lppe_find->lIndex >= lppe_find->lDataNum){ g_api_last_error_code = PE_ERRCODE_NOT_FIND; return FALSE; } memcpy(lpFindData, lppe_find->lpData + lppe_find->lIndex, sizeof(PE_CLIENT_FINDDATA)); lppe_find->lIndex++; return TRUE; } BOOL WINAPI PE_Client_FindClose(LONG lFindHandle) { LPPE_CLIENT_FIND lppe_find = NULL; if (!SelectLPPE_CLIENT_FILE_LISTByFindHandle(lFindHandle, &lppe_find)) return FALSE; if (lppe_find->lDataNum > 0){ delete[] lppe_find->lpData; } lppe_find->lIndex = 0; lppe_find->lDataNum = 0; lppe_find->lpData = NULL; lppe_find->unused = true; return TRUE; } inline bool FindPlayBackInfoByName(LONG lUserID, const char *sPlayBackFileName, LPPE_CLIENT_PREVIEWINFO lppreview_info, LPPE_CLIENT_SADPINFO lpsadp_info, LPPE_CLIENT_FINDDATA lpfind_data) { PE_CLIENT_FILECOND find_cond; memset(&find_cond, 0, sizeof(find_cond)); find_cond.struStopTime.tm_year = 9000 - 1900; std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); PE_CLIENT_SADPINFO_LIST sadp_info_list; if (TRUE == PE_Client_GetSadpInfoList(lUserID, &sadp_info_list)){ for (int i = 0; i < sadp_info_list.wSadpNum; ++i){ find_cond.lChannel = i; LONG lFindHandle = PE_Client_FindFile(lUserID, &find_cond); if (lFindHandle >= 0){ PE_CLIENT_FINDDATA find_data; while (TRUE == PE_Client_FindNextFile(lFindHandle, &find_data)) { if (0 == strcmp(find_data.sFileName, sPlayBackFileName)){ memset(lppreview_info, 0, sizeof(*lppreview_info)); lppreview_info->lChannel = i; lppreview_info->dwStreamType=0; lppreview_info->dwLinkMode=0; lppreview_info->byProtoType=0; memcpy(lpsadp_info, sadp_info_list.struSadpInfo + i, sizeof(*lpsadp_info)); memcpy(lpfind_data, &find_data, sizeof(*lpfind_data)); PE_Client_FindClose(lFindHandle); return true; } } PE_Client_FindClose(lFindHandle); } } } g_api_last_error_code = PE_ERRCODE_NOT_FIND; return false; } LONG WINAPI PE_Client_PlayBackByName(LONG lUserID, CONST CHAR *sPlayBackFileName, fPEPlayDataCallBack cbPlayDataCallBack, void* pUserData) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_PLAYBACK lppe_playback = NULL; for (int i = 0; i < PE_MAX_PLAYBACK; ++i){ if (g_pe_playback[i].unused){ lppe_playback = g_pe_playback + i; break; } } if (NULL == lppe_playback){ g_api_last_error_code = PE_ERRCODE_OUTOFMEM; return FALSE; } LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lUserID, &lppe_client)) return -1; PE_CLIENT_PREVIEWINFO preview_info; PE_CLIENT_SADPINFO sadp_info; PE_CLIENT_FINDDATA find_data; if (!FindPlayBackInfoByName(lUserID, sPlayBackFileName, &preview_info, &sadp_info, &find_data)) return -1; strcpy(lppe_playback->sFileName, sPlayBackFileName); memcpy(&lppe_playback->preview_info, &preview_info, sizeof(preview_info)); memcpy(&lppe_playback->sadp_info, &sadp_info, sizeof(sadp_info)); memcpy(&lppe_playback->find_data, &find_data, sizeof(find_data)); lppe_playback->lUserID = lUserID; lppe_playback->cbPlayDataCallBack = cbPlayDataCallBack; lppe_playback->pUserData = pUserData; for (int j = 0; j < 256; ++j) lppe_playback->lSequenceId[j] = 0; float total_time; struct tm recTime; int handle; if (!lppe_client->lpclient->PlayRecordFile(sadp_info.sUUID, sPlayBackFileName, &total_time, &recTime, &handle)){ g_api_last_error_code = PE_ERRCODE_FAIL; return -1; } lppe_playback->total_time = total_time; memcpy(&lppe_playback->start_time, &recTime, sizeof(recTime)); lppe_playback->nHandle = handle; lppe_playback->unused = false; return lppe_playback->lPlayHandle; } BOOL WINAPI PE_Client_PlayBackControl(LONG lPlayHandle, DWORD dwControlCode, LPVOID lpInBuffer, DWORD dwInLen, LPVOID lpOutBuffer, DWORD *lpOutLen) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_PLAYBACK lppe_playback = NULL; if (!SelectLPPE_CLIENT_PLAYBACKByPlayHandle(lPlayHandle, &lppe_playback)) return FALSE; LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lppe_playback->lUserID, &lppe_client)) return FALSE; bool ret = false; switch (dwControlCode){ case PE_PLAYPAUSE: lppe_client->lpclient->PausePlayRecord(lppe_playback->nHandle,true); break; case PE_PLAYRESTART: lppe_client->lpclient->PausePlayRecord(lppe_playback->nHandle, false); break; case PE_PLAYFAST: ++lppe_playback->play_speed; lppe_playback->play_speed = fmin(lppe_playback->play_speed, 4); ret = lppe_client->lpclient->SetPlayRecordSpeed(lppe_playback->nHandle, lppe_playback->play_speed); break; case PE_PLAYSLOW: --lppe_playback->play_speed; lppe_playback->play_speed = fmax(lppe_playback->play_speed, -4); ret = lppe_client->lpclient->SetPlayRecordSpeed(lppe_playback->nHandle, lppe_playback->play_speed); break; case PE_PLAYNORMAL: lppe_playback->play_speed = 0; ret = lppe_client->lpclient->SetPlayRecordSpeed(lppe_playback->nHandle, lppe_playback->play_speed); break; case PE_PLAYSETPOS: { float cur_tm = *(float*)lpInBuffer * lppe_playback->total_time; cur_tm = fmin(cur_tm, lppe_playback->total_time); cur_tm = fmax(cur_tm, 0.0f); ret = lppe_client->lpclient->SetPlayRecordCurrentTime(lppe_playback->nHandle, cur_tm); } break; case PE_PLAYGETPOS: { float cur_tm = 0.0f; if (lppe_client->lpclient->GetPlayRecordState(lppe_playback->nHandle, &cur_tm)){ *(float *)lpOutBuffer = cur_tm / lppe_playback->total_time; *lpOutLen = 4; ret = true; } } break; case PE_PLAYGETTIME: { float cur_tm = 0.0f; if (lppe_client->lpclient->GetPlayRecordState(lppe_playback->nHandle, &cur_tm)){ time_t ctt = mktime(&lppe_playback->start_time) + static_cast<time_t>(cur_tm); struct tm ct; ct = *localtime(&ctt); memcpy(lpOutBuffer, &ct, sizeof(ct)); *lpOutLen = sizeof(ct); ret = true; } } break; case PE_PLAYSETTIME: { struct tm *ct = (struct tm*)lpInBuffer; time_t ct1 = mktime(ct); time_t ct0 = mktime(&lppe_playback->start_time); float cur_tm = ct1 - ct0; cur_tm = fmin(cur_tm, lppe_playback->total_time); cur_tm = fmax(cur_tm, 0.0f); ret = lppe_client->lpclient->SetPlayRecordCurrentTime(lppe_playback->nHandle, cur_tm); } break; } if (!ret){ g_api_last_error_code = PE_ERRCODE_FAIL; return FALSE; } return TRUE; } BOOL WINAPI PE_Client_StopPlayBack(LONG lPlayHandle) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_PLAYBACK lppe_playback = NULL; if (!SelectLPPE_CLIENT_PLAYBACKByPlayHandle(lPlayHandle, &lppe_playback)) return FALSE; LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lppe_playback->lUserID, &lppe_client)) return FALSE; int nHandle = lppe_playback->nHandle; lppe_playback->unused = true; lppe_client->lpclient->StopPlayRecord(nHandle); return TRUE; } BOOL WINAPI PE_Client_SetServerConfig(LONG lUserID, DWORD dwCommand, LONG lChannel, LPVOID lpInBuffer, DWORD dwInBufferSize) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lUserID, &lppe_client)) return FALSE; PE_CLIENT_SADPINFO sadp_info; if (!SelectLPPE_CLIENT_SADPINFOByUserIDAndChannel(lUserID, lChannel, &sadp_info)) return FALSE; return lppe_client->lpclient->SetServerConfig(sadp_info.sUUID, dwCommand, lpInBuffer, dwInBufferSize) ? TRUE : FALSE; } BOOL WINAPI PE_Client_GetServerConfig(LONG lUserID, DWORD dwCommand, LONG lChannel, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lUserID, &lppe_client)) return FALSE; PE_CLIENT_SADPINFO sadp_info; if (!SelectLPPE_CLIENT_SADPINFOByUserIDAndChannel(lUserID, lChannel, &sadp_info)) return FALSE; return lppe_client->lpclient->GetServerConfig(sadp_info.sUUID, dwCommand, lpOutBuffer, dwOutBufferSize, lpBytesReturned) ? TRUE : FALSE; } BOOL WINAPI PE_Client_PTZControl(LONG lRealHandle, DWORD dwPTZCommand, BOOL dwStop, DWORD dwSpeed) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByRealHandle(lRealHandle, &lppe_client)) return FALSE; LPPE_CLIENT_PREVIEW lppe_preview = NULL; if (!SelectLPPE_CLIENT_PREVIEWByRealHandle(lRealHandle, &lppe_preview)) return FALSE; return lppe_client->lpclient->ControlPtzWithSpeed(lppe_preview->sadp_info.sUUID, FALSE == dwStop ? dwPTZCommand : PE_PTZ_ALLSTOP, dwSpeed)?TRUE:FALSE; } BOOL WINAPI PE_Client_GetSadpInfoList(LONG lUserID, LPPE_CLIENT_SADPINFO_LIST lpSadpInfoList) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lUserID, &lppe_client)) return FALSE; int error_code = lppe_client->lpclient->GetSadpInfoList(lpSadpInfoList); if (error_code == PE_ERRCODE_SUCCESS){ return TRUE; } else{ g_api_last_error_code = error_code; return FALSE; } } LONG WINAPI PE_Client_GetFileByName(LONG lUserID, CONST CHAR *sServerFileName, CONST CHAR *sSavedFileDirectory) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_DOWNLOAD lppe_download = NULL; for (int i = 0; i < PE_MAX_DOWNLOAD; ++i){ if (g_pe_download[i].unused){ lppe_download = g_pe_download + i; break; } } if (NULL == lppe_download){ g_api_last_error_code = PE_ERRCODE_OUTOFMEM; return -1; } LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lUserID, &lppe_client)) return -1; std::string filename(sServerFileName); std::string serverfilename; std::string outfilename; const std::string protocol_bin("BIN://"); if (0 == filename.find(protocol_bin)) { serverfilename = "C:\\Program Files\\PanoEye\\param\\"; serverfilename += filename.substr(protocol_bin.length()); outfilename = std::string(sSavedFileDirectory) + filename.substr(protocol_bin.length()); } else { serverfilename = filename; auto pos = filename.find_last_of('\\'); outfilename = std::string(sSavedFileDirectory) + (pos == std::string::npos ? filename : filename.substr(pos+1)); } lppe_download->dwRecvLength = 0; lppe_download->lUserID = lUserID; lppe_download->sFileName = outfilename; outfilename +=".tmp"; FILE *fp=NULL; fp = fopen(outfilename.c_str(), "wb+"); if (fp == NULL){ g_api_last_error_code = PE_ERRCODE_FAIL; return -1; } lppe_download->fp = fp; DWORD dwFileSize; int handle; if (!lppe_client->lpclient->GetFileByName(serverfilename.c_str(), 0, &dwFileSize, &handle)){ fclose(fp); g_api_last_error_code = PE_ERRCODE_FAIL; return -1; } lppe_download->dwFileSize = dwFileSize; lppe_download->nHandle = handle; lppe_download->unused = false; return lppe_download->lFileHandle; } int WINAPI PE_Client_GetDownloadPos(LONG lFileHandle) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_DOWNLOAD lppe_download = NULL; if (!SelectLPPE_CLIENT_DOWNLOADByFileHandle(lFileHandle, &lppe_download)) return -1; if (lppe_download->dwRecvLength == lppe_download->dwFileSize) return 100; float fpos = lppe_download->dwRecvLength * 100.0 / lppe_download->dwFileSize; int ipos = fpos; if (ipos >= 100) return 99; return ipos; } BOOL WINAPI PE_Client_StopGetFile(LONG lFileHandle) { std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); LPPE_CLIENT_DOWNLOAD lppe_download = NULL; if (!SelectLPPE_CLIENT_DOWNLOADByFileHandle(lFileHandle, &lppe_download)) return FALSE; LPPE_CLIENT lppe_client = NULL; if (!SelectLPPE_CLIENTByUserID(lppe_download->lUserID, &lppe_client)) return FALSE; int nHandle = lppe_download->nHandle; lppe_download->unused = true; lppe_client->lpclient->StopGetFile(nHandle); fclose(lppe_download->fp); rename((lppe_download->sFileName + ".tmp").c_str(), (lppe_download->sFileName).c_str()); return TRUE; } LONG WINAPI PE_Client_GetLastError(){ std::lock_guard<std::recursive_mutex> lck(g_api_recursive_mutex); long tmp = g_api_last_error_code; g_api_last_error_code = PE_ERRCODE_SUCCESS; return tmp; } BOOL WINAPI PE_Client_Demux(char *pszData, long lDataLength, LPPE_AVFRAME_DATA *lpData){ const size_t head_size = sizeof(PE_AVFRAME_DATA); if (NULL != pszData && lDataLength > head_size){ LPPE_AVFRAME_DATA lpAVFrameData = LPPE_AVFRAME_DATA(pszData); lpAVFrameData->pszData = pszData + head_size; if (lpAVFrameData->lDataLength + head_size == lDataLength){ *lpData = lpAVFrameData; return TRUE; } } return FALSE; } #if (defined(WIN32) || defined(_WIN32_WCE)) BOOL WINAPI DllMain( HINSTANCE hinstDLL, // handle to DLL module DWORD fdwReason, // reason for calling function LPVOID lpReserved) // reserved { // Perform actions based on the reason for calling. switch (fdwReason) { case DLL_PROCESS_ATTACH: // Initialize once for each new process. // Return FALSE to fail DLL load. OutputDebugStringA("PEClientSDK V0.0.1 (201609091345)\n"); break; case DLL_THREAD_ATTACH: // Do thread-specific initialization. break; case DLL_THREAD_DETACH: // Do thread-specific cleanup. break; case DLL_PROCESS_DETACH: // Perform any necessary cleanup. break; } return TRUE; // Successful DLL_PROCESS_ATTACH. } #elif defined(__linux__) || defined(__APPLE__) //linux #endif <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/Define.java package panoeye.pelibrary; import java.util.Date; /** * Created by tir on 2016/12/8. */ public class Define { public static int cameraCount = 8; static int CUR_WIDTH = 1280; static int CUR_HEIGHT = 960; static Integer GAIN_WIDTH = 320; static Integer GAIN_HEIGHT = 240; public static boolean isCmbExist = false; public static int pointCount = 1; static Integer CIF_ROW = 288; static Integer CIF_COL = 352; static Integer D1_ROW = 576; static Integer D1_COL = 704; static Integer QCIF_ROW = 144; static Integer QCIF_COL = 176; static Integer QVGA_ROW = 240; static Integer QVGA_COL = 320; static Integer PE_B = 1; static Integer PE_M = 12; static Integer SIZE_INT = 4; static Integer SIZE_CHAR = 1; static Integer SIZE_FLOAT =4; static Integer SIZE_CAMERA = 84; static Integer SIZE_PES_HEAD = 2000; static Integer SIZE_PER_HEAD = 432; static Integer order_PER_serial_no = 295; static Integer order_PER_bin_zip_order = 359; static Integer order_PER_bin_zip_size = 363; static Integer order_PER_index_list_order = 420; static Integer CAMCOUNT_MIN = 2; static Integer CAMCOUNT_MAX = 8; public static float x = 0; public static float y = 0; public static float z = 0; public static float fovy = 45; public static int openglFrameRate = 0; public static int videoFrameRate = 0; public static boolean flip = false; public static boolean isNeedFilp = false; public static int mode = 0; //0 全景 1 vr 2 原始 public static final int MODE_GLOBULAR = 0; public static final int MODE_VR = 1; public static final int MODE_ORIGINAL = 2; public static boolean showVR = false; public static String ROOT_PATH = "/storage/emulated/0/Pano/"; public static String PARAM_PATH = "/storage/emulated/0/Pano/param/"; public static boolean isStretch = false; public static boolean isHalfBall = true; public static boolean isInBall = false; public static boolean isFlip = false; public static float xRatio = 1.0f;//1.0f public static float yRatio = 1.0f;//1.0f public static float xCircle = 0.5f;//0.5f public static float yCircle = 0.5f;//0.5f } //java没有结构体,故class当struct用 class PER_FILE_Head{ // byte magic_head[20];//"PanoEye Record PEFile\0" byte file_format_version;//0x01,第一版 int stream_payload_order;//有效载荷,有效负荷,(有效信息起始位)的绝对偏移量(起点) int stream_payload_size; //有效负载大小(单位为字节数) byte packet_type; //保留,'P':=媒体格式(动态负载大小),'T':=传输格式(还未制定,固定188个字节传输包) int dev_info_order; //配置信息的绝对偏移量 int record_info_order; //录像信息的绝对偏移量 PER_FILE_Head_DevInfo dev_info;//配置结构体 PER_FILE_Head_RecordInfo record_info;//录像结构体 } class PER_FILE_Head_DevInfo{ byte magic_number; //0x40 // byte dev_name[256];//相机名称//E1078 // byte serial_no[64];//相机序列号//E10010078 int bin_zip_order; //bin压缩文件的绝对偏移量(起点) int bin_zip_size; //bin压缩文件大小 int stream_mode; //保留,不用//0 } class PER_FILE_Head_RecordInfo{ byte magic_number; //0x41 Date create_time; //录像创建时间 Date record_start_time;//录像开始时间 Date record_end_time; //录像结束时间 int index_list_order; //PER_IndexIter结构体列表的绝对偏移量(起点) int index_list_size; //PER_IndexIter结构体列表的数量 int index_list_iter_size; //PER_IndexIter结构体的尺寸 } class PER_PS_PacketHead { int sync_byte; //同步字节,总是0x000001BB,表示这个包是正确的 int PES_Packet_Order; //距离这个头的偏移( 起点) } class PER_PES_PacketHead { byte[] sync_byte = new byte[3]; //0x000001 byte stream_id; //数据来源,相机ID和类型,Examples: Audio streams (0xD0-0xDE), Video Main Streams (0xE0-0xEE), Video Sub Streams (0xB0-0xBE), 视频编辑数据 (0xC0-0xCE),最多15个通道。 0xXF,作为使用扩展通道 int PE_Packet_Order; //距离这个头的偏移( 起点) } class PER_PE_Video_PacketHead { int sync_byte; //0x000001B3 Date tPTS; //UTS绝对时间,显示时间 float fPTS; //相对于文件开始时间(秒为单位) Date tDTS; //UTS绝对时间,解码I-Frame时间 float fDTS; //相对于文件开始时间 int RAW_Data_Order; //距离这个头的偏移( 起点) int RAW_Data_Size; //扩展区 byte is_key; //关键帧 int frame_index; //当前帧ID int keyframe_index; //当前帧依赖的关键帧ID } class PER_IndexIter{ byte magic_number; int pre_index_order; int next_index_order; int stream_packet_order; Date cur_time; float cPDt; byte is_key; byte stream_id; int frame_index; int keyframe_index; } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PEErrorType.java package panoeye.pelibrary; /** * Created by tir on 2016/12/13. */ enum PEErrorType { none, unknow, notFound, fileOpenFailed, fileSeekFailed, fileReadFailed, fileWriteFailed, fileCloseFailed, fileEofFailed, } <file_sep>/app/src/main/cpp/OnlineSDK/PEClientSDK/PEClient.cpp #include "PEClient.h" #include "../MainController.h" extern void PEThrowException(DWORD dwType, LONG lHandle); extern void PEPushStreamData(CONST CPEClient* client, LPPE_STREAM_DATA lpInfo, BYTE* pData, int iLength); extern void PEPushFileData(CONST CPEClient *client, LPPE_FILE_DATA lpInfo, BYTE* pData, int iLength); ///////////////////////////////////////////// void Common_StreamDataCallBack(LPPE_STREAM_DATA lpInfo, BYTE* pData, int iLength, void *UserData) { CPEClient *client = (CPEClient*)UserData; uchar *pData_RAW = pData; int length_RAW = iLength; PEPushStreamData(client, lpInfo, pData, iLength); } void Common_FileDataCallBack(LPPE_FILE_DATA lpInfo, BYTE* pData, int iLength, void *UserData) { CPEClient *client = (CPEClient*)UserData; uchar *pData_RAW = pData; int length_RAW = iLength; PEPushFileData(client, lpInfo, pData, iLength); } CPEClient::CPEClient() { CClient::SetStreamDataCallBack(Common_StreamDataCallBack,this); CClient::SetFileDataCallBack(Common_FileDataCallBack, this); ClientAlloc(); } CPEClient::~CPEClient() { Logout(); ClientRelease(); } #define LOGIN_SUCCESS 0 #define LOGIN_FAILED_TIMEOUT 1 #define LOGIN_FAILED_USERERROR 2 int CPEClient::Login(const char *ipaddr, WORD port, const char* username, const char* password) { if (!Connect(ipaddr, port)) return PE_ERRCODE_NETWORK; int loginStatus = CClient::Login(username, password); if (loginStatus != LOGIN_SUCCESS) { if (loginStatus == LOGIN_FAILED_USERERROR) { return PE_ERRCODE_USER_PWD; } else if (loginStatus == LOGIN_FAILED_TIMEOUT) { return PE_ERRCODE_TIMEOUT; } } return loginStatus; return PE_ERRCODE_SUCCESS; } int CPEClient::Logout() { CClient::Logout(); Disconnect(); return PE_ERRCODE_SUCCESS; } bool CPEClient::StopRealPlay(int nHandle) { return StopStreamData(nHandle); } int CPEClient::GetPEStreamPort(const char* uuid) { return CClient::GetStreamPort(uuid); } int CPEClient::GetSadpInfoList(LPPE_CLIENT_SADPINFO_LIST lpSadpInfoList) { RemotePanoSetup *lps; size_t ps_num=0; if (CClient::GetCamList(&lps,&ps_num)) { lpSadpInfoList->wSadpNum = ps_num; LOGI("NUM:%d",ps_num); for (size_t i = 0; i < ps_num; ++i) { LPPE_CLIENT_SADPINFO lpSadpInfo = lpSadpInfoList->struSadpInfo + i; LPRemotePanoSetup ps = lps + i; strcpy(lpSadpInfo->sIP, ps->ip); strcpy(lpSadpInfo->sUUID, ps->uuid); strcpy(lpSadpInfo->sDevName, ps->devName); strcpy(lpSadpInfo->sSerialNo, ps->serial_no); } CClient::FreeCamList(lps); return PE_ERRCODE_SUCCESS; } return PE_ERRCODE_FAIL; } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PEDecodeManager.java package panoeye.pelibrary; import android.util.Log; import java.util.HashMap; /** * Created by jun on 2017/12/13. */ public class PEDecodeManager { private static final String TAG = "PEDecodeManager"; private Float TIMELINE_STEP = 0.07f;//时间轴每次增长的时间 boolean pauseFlag = true;//暂停标志 Thread thread;//线程 HashMap<Integer,PEDecodeThread> threads = new HashMap<>();//镜头与解码线程对照表 LockWrap<Float> timeline = new LockWrap<Float>(0.0f);//时间轴 //public LockWrap<HashMap<Integer,Integer>> frameCounter = new LockWrap<>(new HashMap<Integer,Integer>()); LockWrap<PEDecodeManagerStatus> status = new LockWrap<>(PEDecodeManagerStatus.over);//解码管理状态 PERPano pano; PEDecodeBuffer decodeBuffer; //构造函数 PEDecodeManager(PERPano pano,PEDecodeBuffer decodeBuffer){ this.pano = pano; this.decodeBuffer = decodeBuffer; } //初始化解码器 void initDecoders(){ try { threads = pano.initDecoders(decodeBuffer); }catch (PEError e){ e.printStackTrace(); } } //结束播放 void invalidate() throws PEError{ status.set(PEDecodeManagerStatus.stop); } //开始解码绘制 void start() throws PEError{ initDecoders();//解码初始化器 pauseFlag = false; timeline.set(0f);//设置时间轴初始值//97f //创建线程 thread = new Thread(new Runnable() { @Override public void run() { try { runloop();//run()的循环体 } catch (InterruptedException E) { PEError.gen(PEErrorType.none, "休眠失败!"); }catch (PEError error){ } Log.i("runloop","结束"); } }); thread.start();//启动线程 status.set(PEDecodeManagerStatus.play); } void reView(){ pauseFlag = false; status.set(PEDecodeManagerStatus.play); } void pause() { pauseFlag = true; status.set(PEDecodeManagerStatus.pause); } void restart(){ timeline.set(0f); setJumpToTime(0f); status.set(PEDecodeManagerStatus.play); } boolean setJumpToTime(float jumpToTime){ if (jumpToTime>pano.minDuration){ Log.d(TAG,"setJumpToTime:"+jumpToTime); return false; } float timeStamp = 0.0f; int timeStampIndex = 0; int fpPosition; if (jumpToTime>0) { timeStampIndex = (int)((jumpToTime/pano.minDuration)*pano.perFile.mainStreamIndexCount); } if (timeStampIndex<pano.perFile.mainStreamIndexCount){ timeStamp = pano.perFile.iFrameTimestampList.get(timeStampIndex); fpPosition = pano.perFile.iFrameTimestampDict.get(timeStamp); pano.perFile.currentFramePosition = fpPosition; timeline.set(timeStamp); return true; } return false; } //run()的循环体 void runloop() throws InterruptedException,PEError{ int camCount = pano.binFile.info.camCount; while (true){ if(pauseFlag == true){//如果播放状态暂停 Thread.sleep(200);//线程休眠200ms continue;//跳过下面的语句,重新执行runloop()函数 } if (status.get()==PEDecodeManagerStatus.stop){//如果播放状态停止 break; } if (timeline.get()>pano.minDuration){//播放到了文件末尾 status.set(PEDecodeManagerStatus.over);//设置播放状态结束 Thread.sleep(200);//线程休眠200ms continue; }else { timeline.set(timeline.get()+TIMELINE_STEP);//设置时间轴增长步长 } //Log.d("runloop: ",timeline.get().toString() ); for (int i=0;i<camCount;i++) { int cid = pano.perFile.findOneFrame(pano.perFile.fp); if (cid!=-1) { // Log.d(TAG, "runloop: cid:"+cid); threads.get(cid).step(timeline.get(), pano.perFile.oneFrameData);//执行step()函数 } } Thread.sleep(40);//线程休眠20ms } } } <file_sep>/app/src/main/cpp/OnlineSDK/CClient/CClient.cpp #include "CClient.h" #include "../PanoDef.h" //#include "../ZipLibUtil/ZipLibUtil.h" extern "C" { #include "../md5/md5.cpp" } #include <iostream> //#include <Windows.h> CClient::CClient() { logined_ = false; begin_time_point_ = std::chrono::steady_clock::now(); } CClient::~CClient() { Logout(); } void CClient::ClientAlloc() { try { #if defined(USING_HPSOCKET) CHpSocketClient::ClientAlloc(); #else CNBSocketClient::ClientAlloc(); #endif } catch (std::bad_alloc){ //HandleException(__FILE__, __LINE__); } catch (...) { //HandleException(__FILE__, __LINE__); } } void CClient::ClientRelease() { try { #if defined(USING_HPSOCKET) CHpSocketClient::ClientRelease(); #else CNBSocketClient::ClientRelease(); #endif } catch (...) { //HandleException(__FILE__, __LINE__); } } void CClient::SetStreamDataCallBack(void(*DataCallBack)(LPPE_STREAM_DATA lpInfo, BYTE* pData, int iLength, void *UserData), void *UserData) { try { std::lock_guard<std::mutex> lck(stream_data_callback_mtx_); stream_data_callback_ = std::bind(DataCallBack, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, UserData); } catch (...) { //HandleException(__FILE__, __LINE__); } } void CClient::SetFileDataCallBack(void(*DataCallBack)(LPPE_FILE_DATA lpInfo, BYTE* pData, int iLength, void *UserData), void *UserData) { try { std::lock_guard<std::mutex> lck(file_data_callback_mtx_); file_data_callback_ = std::bind(DataCallBack, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, UserData); } catch (...) { //HandleException(__FILE__, __LINE__); } } void CClient::MakeHash(char* hash, char *input, size_t inputlen) { try { auto now_time_point = std::chrono::steady_clock::now(); auto t = std::chrono::duration_cast<std::chrono::microseconds>(now_time_point - begin_time_point_); auto count = t.count(); unsigned char decrypt[16]; MD5_CTX md5; MD5Init(&md5); MD5Update(&md5, (unsigned char*)input, inputlen); MD5Update(&md5, (unsigned char*)&count, sizeof(count)); MD5Final(&md5, decrypt); for (int i = 0; i < 16; i++) { sprintf(&hash[2 * i], "%02x", decrypt[i]); } } catch (...) { //HandleException(__FILE__, __LINE__); } } bool CClient::SendEmptyMsg(size_t s) { #if defined(USING_HPSOCKET) WSABUF buffers[2]; try { char buff[4096]; PanoComm pc; std::fill(std::begin(buff), std::end(buff), 0); PanoComm_Init(&pc); pc.command = CT_EMPTY; pc.pkgSize = PanoComm_Size() + s; buffers[0].buf = (CHAR*)&pc; buffers[0].len = PanoComm_Size(); buffers[1].buf = (CHAR*)buff; buffers[1].len = s; } catch (...) { //HandleException(__FILE__, __LINE__); } return SendPackets(buffers, s == 0 ? 1 : 2); #else return true; #endif } bool CClient::Execute(const char* method, XmlRpcTX2Value::XmlRpcValue& val, XmlRpcTX2Value::XmlRpcValue& result, long msTime /*= 1000l*/) { try { tinyxml2::XMLDocument doc; tinyxml2::XMLElement * params; XmlRpcTX2Util::generateRequest(&doc, method, &params); tinyxml2::XMLElement * param = doc.NewElement("param"); tinyxml2::XMLElement * value = nullptr; if (val.toXml(&doc, &value)) { param->LinkEndChild(value); params->LinkEndChild(param); } std::string xml = XmlRpcTX2Util::to_string(&doc); char hash[33]; MakeHash(hash, (char*)xml.c_str(), xml.length()); std::string header = XmlRpcTX2Util::generateRequestHeader("CClient1.0", GetHost().c_str(), "text/xml", hash, xml.length()); WSABUF buffers[3]; PanoComm pc; PanoComm_Init(&pc); pc.command = CT_XMLRPC_OVER_PES_REQUEST; pc.pkgSize = PanoComm_Size() + header.length() + xml.length(); buffers[0].buf = (CHAR*)&pc; buffers[0].len = PanoComm_Size(); buffers[1].buf = (CHAR*)header.data(); buffers[1].len = header.length(); buffers[2].buf = (CHAR*)xml.data(); buffers[2].len = xml.length(); if (pc.pkgSize < 4096) { SendEmptyMsg(4096 - pc.pkgSize); } if (SendPackets(buffers, 3)) { msTime = 5000; auto end_time_point = std::chrono::steady_clock::now() + \ std::chrono::milliseconds(msTime < 0 ? 60 * 1000 : msTime); while (true) { { std::unique_lock<std::mutex> lck(ReceiveMsgResponseMutex); if (std::cv_status::timeout == ReceiveMsgResponseConditionVariable.wait_until(lck, end_time_point)) return false; } std::lock_guard<std::mutex> lck(msg_response_list_mtx_); for (auto msg_response = std::begin(msg_response_list_); msg_response != std::end(msg_response_list_);){ if (*msg_response == std::string(hash)) { result = msg_response->result; msg_response = msg_response_list_.erase(msg_response); return true; } else { ++msg_response; } } } return true; } } catch (...)//bad_alloc) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::ProcessMsg(std::string msg) { try { int header_size = 0; std::string strType; std::string hash; int data_size = -1; if (XmlRpcTX2Util::readResponseHeader(msg, &header_size, &strType, &hash, &data_size)) { std::string msg_body; std::copy(std::begin(msg), std::end(msg), std::back_inserter(msg_body)); tinyxml2::XMLDocument doc; tinyxml2::XMLElement * params = nullptr; XmlRpcTX2Util::readResponse(&doc, msg_body.c_str(), msg_body.length()); int value_num = 0; if (XmlRpcTX2Util::parseResponse(&doc, nullptr, &value_num)) { XmlRpcTX2Value::XmlRpcValue result; if (value_num > 0) { tinyxml2::XMLElement ** value = new tinyxml2::XMLElement *[value_num]; if (XmlRpcTX2Util::parseResponse(&doc, value, &value_num)) { if (value_num > 1) { for (int id = 0; id < value_num; ++id) { result[id] = XmlRpcTX2Value::XmlRpcValue(value[id]); } } else if (value_num == 1) { result = XmlRpcTX2Value::XmlRpcValue(value[0]); } } delete[] value; } std::unique_lock<std::mutex> lck(msg_response_list_mtx_); MsgResponse msg_response; std::copy(std::begin(hash), std::end(hash), std::begin(msg_response.md5)); msg_response.result = result; msg_response_list_.push_back(msg_response); lck.unlock(); ReceiveMsgResponseConditionVariable.notify_all(); lck.lock(); auto time_point = std::chrono::steady_clock::now(); for (auto msg_response = std::begin(msg_response_list_); msg_response != std::end(msg_response_list_);) { auto dt = std::chrono::duration_cast<std::chrono::minutes>(time_point - msg_response->time); if (dt > std::chrono::minutes(2)) { msg_response = msg_response_list_.erase(msg_response); } else { ++msg_response; } } lck.unlock(); return true; } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::Connect(const char *ipaddr, USHORT port) { try { #if defined(USING_HPSOCKET) if (CHpSocketClient::Connect(ipaddr, port)) { SendEmptyMsg(4096); SendEmptyMsg(4096); SendEmptyMsg(4096); SendEmptyMsg(4096); } else { return false; } #else return CNBSocketClient::Connect(ipaddr, port); #endif } catch (...) { //HandleException(__FILE__, __LINE__); } return true; } bool CClient::Disconnect() { try { #if defined(USING_HPSOCKET) return CHpSocketClient::Disconnect(); #else return CNBSocketClient::Disconnect(); #endif } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } #define LOGIN_SUCCESS 0 #define LOGIN_FAILED_TIMEOUT 1 #define LOGIN_FAILED_USERERROR 2 bool CClient::Login(const char* username, const char* password) { try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = username; params[1] = password; if (Execute("CT_LOGIN", params, result)) { if (bool(result[0])) { //const XmlRpcTX2Value::XmlRpcValue::BinaryData& data = result[1]; //memcpy(&RemoteConnID, data.data(), sizeof(RemoteConnID)); logined_ = true; return LOGIN_SUCCESS; } else { return LOGIN_FAILED_USERERROR; } } else { return LOGIN_FAILED_TIMEOUT; } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::Logout() { logined_ = false; return true; } bool CClient::GetCamList(RemotePanoSetup **lps, size_t *num) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; if (Execute("CT_CAM_LIST_V2", params, result)) { if (bool(result[0])) { if (result.size() > 1) { *num = result[1].size(); if (*num > 0){ RemotePanoSetup *ps = new RemotePanoSetup[*num]; for (size_t id = 0; id < *num; ++id) { strcpy(ps[id].ip, std::string(result[1][id]["ip"]).c_str()); strcpy(ps[id].serial_no, std::string(result[1][id]["serial_no"]).c_str()); strcpy(ps[id].devName, std::string(result[1][id]["devName"]).c_str()); strcpy(ps[id].uuid, std::string(result[1][id]["uuid"]).c_str()); ps[id].capture_type = int(result[1][id]["capture_type"]); ps[id].model_type = int(result[1][id]["model_type"]); ps[id].sub_model_type = int(result[1][id]["sub_model_type"]); ps[id].ptz_type = int(result[1][id]["ptz_type"]); } *lps = ps; } else { *lps = nullptr; } } return true; } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::FreeCamList(RemotePanoSetup *ps) { delete[] ps; return true; } int CClient::DownloadPraram(const char *serial_no, const char * filename) { try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = serial_no; if (Execute("CT_DOWNLOAD_PRARAM", params, result, -1)) { if (bool(result[0])){ const XmlRpcTX2Value::XmlRpcValue::BinaryData& data = result[1]; FILE * fp = nullptr; fp = fopen(filename, "wb+"); if (0 == fp) { //ExtracMemory2File((unsigned char*)&data[0], data.size(), fp); fclose(fp); return true; } } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } int CClient::GetStreamPort(const char* uuid) { if (!logined_) return -1; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = uuid; //printf("CClient::GetPort()................\n"); if (Execute("CT_REQUEST_PORT_BY_UUID", params, result)) { return int(result[1]); } } catch (...) { //ClientHandleException(__FILE__, __LINE__); } return -1; } bool CClient::GetStreamSysHead(const char* uuid, int stream_format, BYTE **buff, size_t *buff_size) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = uuid; params[1] = stream_format; if (Execute("CT_GET_STREAM_SYS_HEAD_BY_UUID", params, result)) { if (bool(result[0])) { XmlRpcTX2Value::XmlRpcValue::BinaryData& data = result[1]; *buff_size = data.size(); *buff = new BYTE[*buff_size]; std::copy(std::begin(data), std::end(data), *buff); return true; } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::FreeSysHead(BYTE *buff) { delete[] buff; return true; } bool CClient::SetCamAction(const char* uuid, int action) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = std::string(uuid); params[1] = action; if (Execute("CT_SET_CAM_ACTION", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::RequestStreamData(const char* uuid, int stream_format, int *handle) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = uuid; params[1] = stream_format; if (Execute("CT_REQUEST_REALPLAY_BY_UUID", params, result)) { if (bool(result[0])){ *handle = result[1]; return true; } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::SwitchStreamDataFormat(int handle, int stream_format){ if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = handle; params[1] = stream_format; if (Execute("CT_SWITCH_STREAM_FORMAT", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::StopStreamData(int handle) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = handle; if (Execute("CT_STOP_REALPLAY_BY_HANDLE", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::GetRecordFileList(const char* uuid, const char* begTime, const char* endTime, RemoteRecordExtInfos *info){ if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = uuid; params[1] = begTime; params[2] = endTime; if (Execute("CT_GET_RECORD_FILE_LIST_BY_UUID", params, result)) { if (bool(result[0])) { if (result.size() > 1) { for (int id = 0; id < result[1].size(); ++id) { std::string record_time = result[1][id][0]; std::string full_dir = result[1][id][1]; std::string end_time = result[1][id][2]; bool continuity = result[1][id][3]; info->push_back({ record_time, end_time, full_dir, continuity }); } } return true; } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::PlayRecordFile(const char *uuid, const char *file_dir, float *total_time, struct tm *recTime, int *handle) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = uuid; params[1] = file_dir; if (Execute("CT_PLAY_RECORD_FILE_BY_UUID", params, result)) { if (bool(result[0])) { *total_time = (float)double(result[1]); XmlRpcTX2Value::XmlRpcValue::BinaryData& data = result[2]; std::copy(std::begin(data), std::end(data), (char*)recTime); *handle = int(result[3]); return true; } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::StopPlayRecord(int handle) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = handle; if (Execute("CT_STOP_PLAY_RECORD_BY_HANDLE", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::PausePlayRecord(int handle, bool bPause) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = handle; params[1] = bPause; if (Execute("CT_PAUSE_PLAY_RECORD_BY_HANDLE", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::GetPlayRecordState(int handle, float *cur_time) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = handle; if (Execute("CT_GET_PLAY_RECORD_STATE_BY_HANDLE", params, result)) { if (bool(result[0])) { *cur_time = (float)double(result[1]); return bool(result[2]); } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::SetPlayRecordSpeed(int handle, int speed) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = handle; params[1] = speed; if (Execute("CT_SET_PLAY_RECORD_SPEED_BY_HANDLE", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::SetPlayRecordCurrentTime(int handle, float cur_tm) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = handle; params[1] = (float)double(cur_tm); if (Execute("CT_SET_PLAY_RECORD_CURRENT_TIME_BY_HANDLE", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::ControlPtzWithSpeed(const char* uuid, int cmd, int ptz_speed) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = uuid; params[1] = cmd; params[2] = ptz_speed; if (Execute("CT_CONTROL_PTZ_WITH_SPEED_BY_UUID", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::SetServerConfig(const char* uuid, DWORD dwCommand, LPVOID lpInBuffer, DWORD dwInBufferSize) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = std::string(uuid); params[1] = int(dwCommand); if (dwCommand == CT_SET_ZERO_CHAN_CFG) { } else if (dwCommand == CT_SET_CONNECT_CFG) { int *action = (int*)lpInBuffer; params[2] = *action; } else if (dwCommand == CT_SET_PTZ_POS) { LPPE_PTZ_POS_CFG cfg = (LPPE_PTZ_POS_CFG)lpInBuffer; params[2] = double(cfg->fTiltPos); params[3] = double(cfg->fPanPos); params[4] = int(cfg->fZoomPos); } else { return false; } if (Execute("CT_SET_SERVER_CONFIG", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::GetServerConfig(const char* uuid, DWORD dwCommand, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = std::string(uuid); params[1] = int(dwCommand); if (Execute("CT_GET_SERVER_CONFIG", params, result, 10000)) { if (bool(result[0])){ if (dwCommand == CT_GET_CONNECT_CFG) { LPPE_CONNECT_CFG cfg = (LPPE_CONNECT_CFG)lpOutBuffer; *lpBytesReturned = sizeof(PE_CONNECT_CFG); cfg->byNetState = int(result[1]); cfg->byStopConnect = int(result[2]); cfg->byAutoConnect = int(result[3]); cfg->bySubStreamOnly = int(result[4]); return true; } else if (dwCommand == CT_GET_PTZ_POS) { LPPE_PTZ_POS_CFG cfg = (LPPE_PTZ_POS_CFG)lpOutBuffer; *lpBytesReturned = sizeof(PE_PTZ_POS_CFG); cfg->fTiltPos = double(result[1]); cfg->fPanPos = double(result[2]); cfg->fZoomPos = int(result[3]); return true; } } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::GetFileByName(const char *file_dir, DWORD dwOffset, LPDWORD dwFileSize, int *handle) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = std::string(file_dir); params[1] = int(dwOffset); if (Execute("CT_GET_FILE_BY_NAME", params, result)) { if (bool(result[0])){ *handle = int(result[1]); *dwFileSize = int(result[2]); return true; } } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } bool CClient::StopGetFile(int handle) { if (!logined_) return false; try { XmlRpcTX2Value::XmlRpcValue params, result; params[0] = int(handle); if (Execute("CT_STOP_GET_FILE_BY_HANDLE", params, result)) { return bool(result[0]); } } catch (...) { //HandleException(__FILE__, __LINE__); } return false; } std::chrono::system_clock::time_point CClient::GetSyncTimePoint(){ return sync_time_; } bool CClient::OnClientReceive(PanoComm pc, BYTE *msg_body, size_t msg_body_size) { int msg_type = pc.command; switch (msg_type) { case CT_STREAM_ZERO_CHAN_DATA: break; case CT_XMLRPC_OVER_PES_RESPONSE: { std::string msg; std::copy_n(msg_body, msg_body_size, std::back_inserter(msg)); std::thread(std::bind(&CClient::ProcessMsg, this, msg)).detach(); } break; case CT_SERVER_VERSION_SEND: break; case CT_STREAM_ZERO_CHAN_TIME_SYNC: { int data_size = sizeof(PE_StreamZeroChanData); PE_StreamZeroChanData *sd = (PE_StreamZeroChanData *)(msg_body); uchar *raw_data = msg_body + data_size; int raw_data_length = msg_body_size - data_size; long long dt; memcpy(&dt, raw_data, sizeof(dt)); sync_time_ = std::chrono::system_clock::time_point(std::chrono::milliseconds(dt)); } break; case CT_STREAM_DATA: { PE_STREAM_DATA struStreamInfo; memset(&struStreamInfo, 0, sizeof(struStreamInfo)); struStreamInfo.dwSize = sizeof(struStreamInfo); LPPE_STREAM_DATA lpInfo = (LPPE_STREAM_DATA)(msg_body); uchar *raw_data = msg_body + lpInfo->dwSize; int raw_data_length = msg_body_size - lpInfo->dwSize; DWORD dwSize = std::min(struStreamInfo.dwSize, lpInfo->dwSize); memcpy(&struStreamInfo, lpInfo, dwSize); std::lock_guard<std::mutex> lck(stream_data_callback_mtx_); if (stream_data_callback_) stream_data_callback_(&struStreamInfo, raw_data, raw_data_length); } break; case CT_FILE_TRANSLATE: { PE_FILE_DATA struFileInfo; memset(&struFileInfo, 0, sizeof(struFileInfo)); struFileInfo.dwSize = sizeof(struFileInfo); LPPE_FILE_DATA lpInfo = (LPPE_FILE_DATA)(msg_body); uchar *raw_data = msg_body + lpInfo->dwSize; int raw_data_length = msg_body_size - lpInfo->dwSize; DWORD dwSize = std::min(struFileInfo.dwSize, lpInfo->dwSize); memcpy(&struFileInfo, lpInfo, dwSize); std::lock_guard<std::mutex> lck(file_data_callback_mtx_); if (file_data_callback_) file_data_callback_(&struFileInfo, raw_data, raw_data_length); } break; default: break; } return true; } bool CClient::OnClientClose() { Logout(); return true; } <file_sep>/app/src/main/assets/vertex.sh uniform mat4 uMVPMatrix; //总变换矩阵 attribute vec2 a_texCoord; attribute vec4 vPosition; varying vec2 tc; void main() { //根据总变换矩阵计算此次绘制此顶点位置 gl_Position = uMVPMatrix * vPosition; //将顶点的位置传给片元着色器 tc = a_texCoord; } <file_sep>/app/src/main/cpp/Online/OnlinePano.h // // Created by tir on 2016/10/8. // #ifndef PANO_ONLINEPANO_H #define PANO_ONLINEPANO_H #include "../Common.h" #include "../OnlineSDK/PEClientSDK/PEClientSDK.h" #include "OnlineDecoder.h" #include "../PES/PESBinFile.h" class OnlinePano { public: int camIndex; OnlineDecoder *decoders[MAX_CAMERA_COUNT] = {0}; PESBinFile * binFile = NULL; long long lastVideoTime; long lLoginHandle; long lRealHandle; int lFileHandle; PE_CLIENT_SADPINFO_LIST SadpInfoList; OnlinePano(); ~OnlinePano(); bool login(char * ip, int port, char * username, char * password); void logout(); int getCamCount(); char * getCamNameWithIndex(int index); bool registCamWithIndex(int index); bool setStreamType(int type); void unregistCam(); void realDataCallBack(LPPE_AVFRAME_DATA lpData); void decodeFrameRateStep(); int getDecodeFrameRate(); int getFileDownloadingPos(); long long getCurrentVideoTime(); private: int decodeFrameRate; pthread_mutex_t mutex;// pthread_mutex_t 是Linux下的互斥锁 }; #endif //PANO_ONLINEPANO_H <file_sep>/app/src/main/cpp/PER/PERPackage.h // // Created by tir on 2016/10/10. // #ifndef PANO_PERPACKAGE_H #define PANO_PERPACKAGE_H #include "../Common.h" class PERPackage { public: int len; uchar * data; long long timestamp; int width, height; unsigned int id; PERPackage(int _len, uchar * _data, long long _timestamp, int _width, int _height, int _id); ~PERPackage(); }; #endif //PANO_PERPACKAGE_H <file_sep>/app/src/main/cpp/OnlineSDK/CClient/MemoryPool.cpp #include "MemoryPool.h" #include <algorithm> #include <numeric> //////////////////////////////////////////////////////////////////////////////// bool MemoryBlock_Construct(DWORD dwBufferSize, LPMEMORY_BLOCK *ppBlock) { LPMEMORY_BLOCK tmp = NULL; try{ tmp = new MEMORY_BLOCK; tmp->dwBufferSize = dwBufferSize; tmp->lpbyBuffer = NULL; tmp->lpbyBuffer = new BYTE[dwBufferSize]; tmp->iDataOffset = 0; tmp->iDataLength = 0; } catch (std::bad_alloc){ if (tmp){ delete tmp; } return false; } *ppBlock = tmp; return true; } void MemoryBlock_Destruct(LPMEMORY_BLOCK pBlock) { delete[] pBlock->lpbyBuffer; delete pBlock; } int MemoryBlock_Cat(LPMEMORY_BLOCK pBlock, const LPBYTE pData, int length) { if (pBlock->iDataOffset > 0){ if (pBlock->iDataLength > 0){ LPBYTE tmp = new BYTE[pBlock->iDataLength]; memcpy(tmp, pBlock->lpbyBuffer + pBlock->iDataOffset, pBlock->iDataLength); memcpy(pBlock->lpbyBuffer, tmp, pBlock->iDataLength); delete[] tmp; } pBlock->iDataOffset = 0; } int write_size = std::min((int)pBlock->dwBufferSize - pBlock->iDataLength, length); if (write_size > 0){ memcpy(pBlock->lpbyBuffer + pBlock->iDataLength, pData, write_size); pBlock->iDataLength += write_size; } return write_size; } int MemoryBlock_Fetch(LPMEMORY_BLOCK pBlock, LPBYTE pData, int length) { int read_size = std::min(pBlock->iDataLength, length); if (read_size > 0){ memcpy(pData, pBlock->lpbyBuffer + pBlock->iDataOffset, read_size); pBlock->iDataOffset += read_size; pBlock->iDataLength -= read_size; } return read_size; } int MemoryBlock_Peek(LPMEMORY_BLOCK pBlock, LPBYTE pData, int length) { int read_size = std::min(pBlock->iDataLength, length); if (read_size > 0){ memcpy(pData, pBlock->lpbyBuffer + pBlock->iDataOffset, read_size); } return read_size; } //////////////////////////////////////////////////////////////////////////////// CMemoryPool::CMemoryPool(int buff_size /*= 4096*/, int buff_num /*= 10*/) :kBufferSize(buff_size) { for (int i = 0; i < buff_num; ++i){ LPMEMORY_BLOCK block = NULL; if (MemoryBlock_Construct(buff_size, &block)) m_MemoryBlock_list.push_back(block); } m_Item_Count = 0; } CMemoryPool::~CMemoryPool() { if (0 != m_Item_Count){ printf("�ڴ�й¶\n"); } std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); std::for_each(std::begin(m_MemoryBlock_list), std::end(m_MemoryBlock_list), [](LPMEMORY_BLOCK block){ MemoryBlock_Destruct(block); }); m_MemoryBlock_list.clear(); } CMemoryItem* CMemoryPool::Construct() { CMemoryItem *pItem = nullptr; try{ pItem = new CMemoryItem(this); m_Item_Count++; } catch (std::bad_alloc){ return nullptr; } return pItem; } void CMemoryPool::Destruct(CMemoryItem* pItem) { std::lock_guard<std::recursive_mutex> lck(pItem->m_MemoryBlock_list_mutex); std::for_each(std::begin(pItem->m_MemoryBlock_list), std::end(pItem->m_MemoryBlock_list), [this](LPMEMORY_BLOCK block){ FreeMemoryBlock(block); }); pItem->m_MemoryBlock_list.clear(); m_Item_Count--; } bool CMemoryPool::GetMemoryBlock(LPMEMORY_BLOCK *block){ std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); if (m_MemoryBlock_list.empty()) { if (!MemoryBlock_Construct(kBufferSize, block)) return false; } else { *block = m_MemoryBlock_list.front(); m_MemoryBlock_list.pop_front(); } return true; } bool CMemoryPool::FreeMemoryBlock(LPMEMORY_BLOCK block){ std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); block->iDataLength = 0; block->iDataOffset = 0; m_MemoryBlock_list.push_back(block); return true; } //////////////////////////////////////////////////////////////////////////////// CMemoryItem::~CMemoryItem() { kMemoryPool->Destruct(this); } int CMemoryItem::Cat(const LPBYTE pBuffer, int iLength) { int cat = 0; LPBYTE pData = (LPBYTE)pBuffer; int iDataLength = iLength; std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); if (m_MemoryBlock_list.size() > 0){ LPMEMORY_BLOCK tmp = m_MemoryBlock_list.back(); if (tmp->iDataLength < tmp->dwBufferSize){ int write_size = MemoryBlock_Cat(tmp, pData, iDataLength); cat += write_size; pData += write_size; iDataLength -= write_size; } } if (iDataLength > 0){ int count = (iDataLength + kMemoryPool->kBufferSize - 1) / kMemoryPool->kBufferSize; for (int i = 0; i < count; ++i){ LPMEMORY_BLOCK block; if (!kMemoryPool->GetMemoryBlock(&block)) break; int write_size = MemoryBlock_Cat(block, pData, iDataLength); cat += write_size; pData += write_size; iDataLength -= write_size; m_MemoryBlock_list.push_back(block); } } return cat; } int CMemoryItem::Cat(CMemoryItem* other) { int cat = other->Size(); std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); std::lock_guard<std::recursive_mutex> other_lck(other->m_MemoryBlock_list_mutex); if (other->m_MemoryBlock_list.size() == 1 && m_MemoryBlock_list.size() > 0){ LPMEMORY_BLOCK tmp = m_MemoryBlock_list.back(); LPMEMORY_BLOCK other_tmp = other->m_MemoryBlock_list.front(); if (tmp->iDataLength + other_tmp->iDataLength <= tmp->dwBufferSize){ MemoryBlock_Cat(tmp, other_tmp->lpbyBuffer + other_tmp->iDataOffset, other_tmp->iDataLength); other->Reset(); } } for (auto memory_block = std::begin(other->m_MemoryBlock_list); memory_block != std::end(other->m_MemoryBlock_list);) { m_MemoryBlock_list.push_back(*memory_block); memory_block = other->m_MemoryBlock_list.erase(memory_block); } return cat; } int CMemoryItem::Fetch(BYTE* pData, int length) { LPMEMORY_BLOCK tmp = nullptr; int iDataLength = 0; std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); for (auto black = std::begin(m_MemoryBlock_list); black != std::end(m_MemoryBlock_list);) { tmp = *black; if (length <= 0) break; int read_size = MemoryBlock_Fetch(tmp, pData, length); pData += read_size; length -= read_size; iDataLength += read_size; if (tmp->iDataLength == 0){ black = m_MemoryBlock_list.erase(black); kMemoryPool->FreeMemoryBlock(tmp); } else break; } return iDataLength; } int CMemoryItem::Peek(BYTE* pData, int length) { int iDataLength = 0; std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); for (auto black = std::begin(m_MemoryBlock_list); black != std::end(m_MemoryBlock_list); ++black) { LPMEMORY_BLOCK tmp = *black; if (length <= 0) break; int read_size = MemoryBlock_Peek(tmp, pData, length); pData += read_size; length -= read_size; iDataLength += read_size; } return iDataLength; } int CMemoryItem::Reduce(int length) { std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); if (length <= 0) return Size(); int last = Size() - length; Reset(0, last); return last; } void CMemoryItem::Reset(int begin /*= 0*/, int end /*= 0*/) { std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); LPMEMORY_BLOCK tmp = nullptr; int pos = 0; for (auto black = std::begin(m_MemoryBlock_list); black != std::end(m_MemoryBlock_list); ++black) { tmp = *black; int iDataLength = tmp->iDataLength; int black_begin = pos; int black_end = pos + iDataLength; if (black_end <= begin){ tmp->iDataLength = 0; printf("CMemoryItem::Reset Remove0 [%d,%d)\n", black_begin, black_end); } else if (black_begin < begin && black_end > begin){ int reduce = begin - pos; tmp->iDataOffset += reduce; tmp->iDataLength -= reduce; printf("CMemoryItem::Reset Remove1 [%d,%d)\n", black_begin, black_begin + tmp->iDataLength); } else if (black_begin >= end){ tmp->iDataLength = 0; printf("CMemoryItem::Reset Remove2 [%d,%d)\n", black_begin, black_end); } else if (black_begin < end && black_end > end){ tmp->iDataLength = end - pos; printf("CMemoryItem::Reset Remove3 [%d,%d)\n", end, black_end); } pos += iDataLength; } for (auto black = std::begin(m_MemoryBlock_list); black != std::end(m_MemoryBlock_list);) { tmp = *black; if (tmp->iDataLength == 0){ black = m_MemoryBlock_list.erase(black); kMemoryPool->FreeMemoryBlock(tmp); } else ++black; } printf("CMemoryItem::Reset [%d,%d)\n", begin, end); } int CMemoryItem::Size(){ std::lock_guard<std::recursive_mutex> lck(m_MemoryBlock_list_mutex); return std::accumulate(std::begin(m_MemoryBlock_list), std::end(m_MemoryBlock_list), 0, [](int init, LPMEMORY_BLOCK block){return init + block->iDataLength; }); } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PanoType.java //package panoeye.pelibrary; // //public enum PanoType{ // PER, // PES, //} <file_sep>/app/src/main/java/com/panoeye/peplayer/peonline/FishEyeDrawActivity.java //package com.panoeye.peplayer.peonline; // //import android.opengl.GLSurfaceView; //import android.os.Handler; //import android.os.Message; //import android.support.v7.app.AppCompatActivity; //import android.os.Bundle; //import android.util.Log; //import android.view.KeyEvent; //import android.view.MotionEvent; //import android.view.View; //import android.view.WindowManager; //import android.widget.Button; //import android.widget.TextView; //import android.widget.Toast; // //import com.panoeye.peplayer.R; // //import java.io.BufferedReader; //import java.io.FileInputStream; //import java.io.IOException; //import java.io.InputStreamReader; //import java.net.InetSocketAddress; //import java.net.Socket; //import java.net.SocketAddress; //import java.sql.Time; //import java.util.Date; //import java.util.Timer; //import java.util.TimerTask; // //public class FishEyeDrawActivity extends AppCompatActivity { // GLSurfaceView view = null; // FEDrawManager drawManager1,drawManager2; // Timer time; // Socket socket = null; // FEFrameBuffer []frameBuffer; // FEDecodeBuffer []decodeBuffer; // static { // System.loadLibrary("avcodec-57"); // System.loadLibrary("native-lib"); // System.loadLibrary("avfilter-6"); // System.loadLibrary("avformat-57"); // System.loadLibrary("avutil-55"); // System.loadLibrary("swresample-2"); // System.loadLibrary("swscale-4"); // } // public native static int Init(); // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN); // setContentView(R.layout.activity_draw_fisheye); // // view = (GLSurfaceView)findViewById(R.id.surfaceView); // // String RTSPAddr1 = (String)getIntent().getSerializableExtra("RTSPAddr1"); // String RTSPAddr2 = (String)getIntent().getSerializableExtra("RTSPAddr2"); // // frameBuffer = new FEFrameBuffer[2]; // decodeBuffer = new FEDecodeBuffer[2]; // // new Thread(new Runnable() { // @Override // public void run() { // Log.i("cj", "linkBtn: "); // String ip = (String) getIntent().getSerializableExtra("ip"); // String port = (String) getIntent().getSerializableExtra("port"); // try { // socket = new Socket(); // String portstr = port; // int portNum = Integer.parseInt(portstr); // SocketAddress add = new InetSocketAddress(ip.toString(),portNum); // socket.connect(add,5000); // //socket = new Socket("192.168.111.199",5000); // BufferedReader buff = new BufferedReader(new InputStreamReader( // socket.getInputStream() // )); // String line = null; // while ((line = buff.readLine())!=null){ // Message msg = new Message(); // msg.what = 0x11; // Bundle bundle = new Bundle(); // bundle.clear(); // // int headCH = line.indexOf('X'); // if (headCH>=0) // { // line = line.substring(headCH); // char ch = line.charAt(8); // if (ch=='Y'){ // //Log.e(String.valueOf(line.length()),line+"\n"); // bundle.putString("msg",line); // msg.setData(bundle); // handler.sendMessage(msg); // } // } // } // // buff.close(); // socket.close(); // }catch (IOException e){ // e.printStackTrace(); // Bundle bundle = new Bundle(); // bundle.clear(); // Message msg = new Message(); // msg.what = 0x11; // bundle.putString("msg","陀螺仪获取错误"); // msg.setData(bundle); // handler.sendMessage(msg); // } // } // }).start(); // // Init(); // if (RTSPAddr1.equals("") == false&&RTSPAddr2.equals("")==true){ // frameBuffer[0] = new FEFrameBuffer(); // drawManager1 = new FEDrawManager(RTSPAddr1,frameBuffer[0]); // // boolean ret = drawManager1.Init(); // if (ret == false){ // // }else { // // } // drawManager1.start(); // decodeBuffer[0] = new FEDecodeBuffer(frameBuffer[0]); // Define.isHalfBall = true; // } // if (RTSPAddr1.equals("") == true &&RTSPAddr2.equals("")==false){ // frameBuffer[0] = new FEFrameBuffer(); // drawManager2 = new FEDrawManager(RTSPAddr2,frameBuffer[0]); // boolean ret = drawManager2.Init(); // if (ret == false){ // // }else { // // } // // drawManager2.start(); // decodeBuffer[0] = new FEDecodeBuffer(frameBuffer[0]); // Define.isHalfBall = true; // } // if (RTSPAddr1.equals("") == true&&RTSPAddr2.equals("") == true){ // // } // if (RTSPAddr1.equals("") == false&&RTSPAddr2.equals("") == false){ // Define.isHalfBall = false; // // frameBuffer[0] = new FEFrameBuffer(); // drawManager1 = new FEDrawManager(RTSPAddr1,frameBuffer[0]); // boolean ret = drawManager1.Init(); // if (ret == false){ // // } // else { // // } // // // frameBuffer[1] = new FEFrameBuffer(); // drawManager2 = new FEDrawManager(RTSPAddr2,frameBuffer[1]); // ret = drawManager2.Init(); // if (ret == false){ // // }else { // // } // // decodeBuffer[0] = new FEDecodeBuffer(frameBuffer[0]); // decodeBuffer[1] = new FEDecodeBuffer(frameBuffer[1]); // // drawManager2.start(); // drawManager1.start(); // // } // // FEDraw draw = new FEDraw(view,decodeBuffer,getApplicationContext()); // draw.draw(); // // TimerTask task = new TimerTask() { // @Override // public void run() { // handler.sendEmptyMessage(0); // } // }; // time = new Timer(); // time.schedule(task,0,1000); // setView(); // } // // TextView fps1,video1,video2,cpu,gyro; // void setView(){ // fps1 = (TextView)findViewById(R.id.fps1); // video2 = (TextView)findViewById(R.id.video2); // video1 = (TextView)findViewById(R.id.video1); // cpu = (TextView)findViewById(R.id.cpu); // proBtn = (Button)findViewById(R.id.proBtn); // posBtn = (Button)findViewById(R.id.posBtn); // Flip = (Button)findViewById(R.id.Flip); // Flip.setEnabled(false); // gyro = (TextView)findViewById(R.id.gyro); // } // Handler handler = new Handler(){ // @Override // public void handleMessage(Message msg) { // switch (msg.what){ // case 0: // fps1.setText("fps1:"+Define.fps1); // video2.setText("video2:"+Define.video2); // video1.setText("video1:"+Define.video1); // cpu.setText("CPU: " + String.valueOf(((int)(getAppCpuRate() * 100)) / 100.0) + " %"); // Define.fps1 = 0; // Define.video2 = 0; // Define.video1 = 0; // case 0x11: // Bundle bundle = msg.getData(); // if (bundle.getString("msg")!=null){ // gyro.setText(bundle.getString("msg")); // } // break; // default: // break; // } // // // } // }; // // float lastTotalCpuTime = -1; // float lastAppCpuTime = -1; // public float getAppCpuRate() { // // float totalCpuTime = getTotalCpuTime(); // float appCpuTime = getAppCpuTime(); // float cpuRate; // if (lastTotalCpuTime != -1 && lastAppCpuTime != -1) { // cpuRate = 100 * (appCpuTime - lastAppCpuTime) // / (totalCpuTime - lastTotalCpuTime); // } else { // cpuRate = 0; // } // lastTotalCpuTime = totalCpuTime; // lastAppCpuTime = appCpuTime; // return cpuRate; // } // // public long getTotalCpuTime() { // 获取系统总CPU使用时间 // String[] cpuInfos = null; // try // { // BufferedReader reader = new BufferedReader(new InputStreamReader( // new FileInputStream("/proc/stat")), 1000); // String load = reader.readLine(); // reader.close(); // cpuInfos = load.split(" "); // } // catch (IOException ex) // { // ex.printStackTrace(); // } // long totalCpu = Long.parseLong(cpuInfos[2]) // + Long.parseLong(cpuInfos[3]) + Long.parseLong(cpuInfos[4]) // + Long.parseLong(cpuInfos[6]) + Long.parseLong(cpuInfos[5]) // + Long.parseLong(cpuInfos[7]) + Long.parseLong(cpuInfos[8]); // return totalCpu; // } // // public long getAppCpuTime() { // 获取应用占用的CPU时间 // String[] cpuInfos = null; // try // { // int pid = android.os.Process.myPid(); // BufferedReader reader = new BufferedReader(new InputStreamReader( // new FileInputStream("/proc/" + pid + "/stat")), 1000); // String load = reader.readLine(); // reader.close(); // cpuInfos = load.split(" "); // } // catch (IOException ex) // { // ex.printStackTrace(); // } // long appCpuTime = Long.parseLong(cpuInfos[13]) // + Long.parseLong(cpuInfos[14]) + Long.parseLong(cpuInfos[15]) // + Long.parseLong(cpuInfos[16]); // return appCpuTime; // } // // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // if(keyCode == KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0){ // drawManager1.stop(); // drawManager2.stop(); // view = null; // drawManager1 = null; // drawManager2 = null; // time.cancel(); // decodeBuffer = null; // frameBuffer = null; // finish(); // } // return true; // } // // Button proBtn,posBtn,Flip; // public void stretch(View btn){ // if (Define.isStretch == true){ // Define.x = 0; // Define.y = 0; // Define.fovy = 45; // proBtn.setText("柱面投影"); // posBtn.setEnabled(true); // Flip.setEnabled(false); // Define.isStretch = false; // }else { // Define.x = -200; // Define.y = -40; // Define.fovy = 65; // Flip.setEnabled(true); // posBtn.setEnabled(false); // proBtn.setText("球状投影"); // Define.isStretch = true; // } // } // public void posBall(View btn){ // if (Define.isInBall == false){ // posBtn.setText("球外"); // Define.isInBall = true; // }else { // posBtn.setText("球内"); // Define.isInBall = false; // } // } // public void Flip(View btn){ // if (Define.isFlip == false){ // Define.isFlip = true; // }else { // Define.isFlip = false; // } // } // // private float spacing(MotionEvent event){ // float x = event.getX(0) - event.getX(1); // float y = event.getY(0) - event.getY(1); // return (float) (Math.sqrt(x*x+y*y)); // } // // float mPreviousX,mPreviousY; // float mPreviousDir; // boolean isDragging = false; // boolean isZoomming = false; // float newDir; // static final float FOVY_MIN = 5.0f; // static final float FOVY_MAX = 180.0f; // Date touchDownTime; // public boolean onTouchEvent(MotionEvent event){ // float x = event.getX(); // float y = event.getY(); // switch (event.getAction()&MotionEvent.ACTION_MASK){ // case MotionEvent.ACTION_MOVE: // if (isZoomming){ // newDir = spacing(event); // float tScale = (float)(Define.fovy - (Math.min(Math.max(newDir / mPreviousDir, 0.6), 1.4) - 1) * 10 * 2); // Define.fovy = Math.min(Math.max((tScale), FOVY_MIN), FOVY_MAX); // Log.d("mPreviousDir", String.valueOf(newDir / mPreviousDir)); // mPreviousDir = newDir; // break; // } // // if (isDragging){ // float dx = (x - mPreviousX)/10; // float dy = (y - mPreviousY)/10; // Define.x += dx; // Define.y += dy; // mPreviousY = y; // mPreviousX = x; // break; // } // // case MotionEvent.ACTION_DOWN: // mPreviousX = x; // mPreviousY = y; // touchDownTime = new Date(); // isDragging = true; // break; // case MotionEvent.ACTION_UP: // isDragging = false; // isZoomming = false; // // break; // case MotionEvent.ACTION_POINTER_UP: // isDragging = false; // isZoomming = false; // touchDownTime= null; // break; // case MotionEvent.ACTION_POINTER_DOWN: // touchDownTime= null; // if (event.getPointerCount() == 2) { // isZoomming = true; // mPreviousDir = spacing(event); // } // break; // } // // return true; // } //} <file_sep>/app/src/main/cpp/GLManager.h // // Created by tir on 2016/9/1. // #ifndef PANO_GLMANAGER_H #define PANO_GLMANAGER_H #include <math.h> #include <cstring> #include <GLES/gl.h> #include <GLES/glext.h> #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include "Common.h" #include "GLMatrix.h" #include "PES/PESPano.h" #include "PER/PERPano.h" #include "Online/OnlinePano.h" #define GL_BACKGROUND_COLOR 0.8f, 0.8f, 0.8f, 1.0f class GLManager { public: GLManager(); int panoType; PESPano * pesPano; PERPano * perPano; OnlinePano * onlinePano; float radius; bool isVRMode = false; bool isGlobularMode = true; bool isNeedReloadBin = false; bool glmInit(int width, int height); void glmReloadBin(); void glmDeinit(); void glmResize(); // void glmResize(int width, int height, float fovy); void glmResize(int width, int height); void glmStep(float x, float y, float z, float fovy); private: float width, height, fovy; GLuint vertexShader, fragmentShader; GLuint shaderProgram; GLuint shaderVertex, shaderTexture, shaderMatrix; GLuint tex_y, tex_u, tex_v, tex_a, tex_type; GLuint vboVer[MAX_CAMERA_COUNT] = {0}, vboTex[MAX_CAMERA_COUNT] = {0}; float glRotateXAxis[3], glRotateYAxis[3], glRotateZAxis[3]; float glProjectionMatrix[16]; GLuint textures[MAX_CAMERA_COUNT][4]; GLuint renderBuffer, frameBuffer, displayTexture; GLfloat originalVerCoord[8][18]; void setOriginalVerCoord(int w, int h); GLuint buildProgram(const char* vertexShaderSource, const char* fragmentShaderSource); GLuint buildShader(const char* source, GLenum shaderType); }; static const char* VERTEX_SHADER = "attribute vec4 vPosition; \n" "attribute vec2 a_texCoord; \n" "uniform mat4 glMatrix; \n" "varying vec2 tc; \n" "void main() \n" "{ \n" " gl_Position = glMatrix * vPosition; \n" " tc = a_texCoord; \n" "} \n"; static const char* FRAG_SHADER = "varying lowp vec2 tc; \n" "uniform int SampleType; \n"//0 = rgb, 1 = yuv球面, 2 = yuv平面 "uniform sampler2D SamplerY; \n" "uniform sampler2D SamplerU; \n" "uniform sampler2D SamplerV; \n" "uniform sampler2D SamplerA; \n" "void main(void) \n" "{ \n" " if (SampleType == 0) { \n" " gl_FragColor = vec4(texture2D(SamplerY, tc).r,\n" " texture2D(SamplerY, tc).g,\n" " texture2D(SamplerY, tc).b, 1);\n" " } else { \n" " mediump vec3 yuv; \n" " lowp vec3 rgb; \n" " yuv.x = texture2D(SamplerY, tc).r; \n" " yuv.y = texture2D(SamplerU, tc).r - 0.5; \n" " yuv.z = texture2D(SamplerV, tc).r - 0.5; \n" " rgb = mat3( 1, 1, 1, \n" " 0, -0.39465, 2.03211, \n" " 1.13983, -0.58060, 0 ) * yuv; \n" " if (SampleType == 1) { \n" " gl_FragColor = vec4(rgb, texture2D(SamplerA, tc).r);\n" " } else { \n" " gl_FragColor = vec4(rgb, 1); \n" " } \n" " } \n" "} \n"; static GLfloat VR_VERTEX_COORD[] = { -1, -1, 0, -1, 0, 1, -1, -1, 0, 1, -1, 1, 0, -1, 1, -1, 1, 1, 0, -1, 1, 1, 0, 1, }; static GLfloat TEXTURE_COORD[] = { 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, }; #endif //PANO_GLMANAGER_H <file_sep>/app/src/main/cpp/PER/PERFile.cpp // // Created by tir on 2016/9/28. // #include "PERFile.h" #include "../MainController.h" PERFile::PERFile() { streamType = STREAM_TYPE_MAIN; file = NULL; } PERFile::~PERFile() { if (file != NULL) { fclose(file); } delete binFile; } bool PERFile::openFile(char *filename) { file = fopen(filename, "rb"); fread(&head, sizeof(PERFileHead), 1, file); fseek(file, head.devInfoOffset, SEEK_SET); fread(&devHead, sizeof(PERDevHead), 1, file); fseek(file, head.recordInfoOffset, SEEK_SET); fread(&recordHead, sizeof(PERRecordHead), 1, file); fseek(file, recordHead.listOffset, SEEK_SET); for (int i = 0; i < recordHead.listSize; i++) { PERIndexCell cell; fread(&cell, recordHead.listCellSize, 1, file); int index = cell.streamID - 0xE0; if ((index >= 0) && (index < MAX_CAMERA_COUNT)) { indexList[index][indexIndex[index]++] = cell; } } fseek(file, devHead.binZipOffset, SEEK_SET); size_t binZipSize = devHead.binZipSize; uchar * binZipData = new uchar[binZipSize]; fread(binZipData, binZipSize, 1, file); uchar * binData; size_t binSize; int result = ExtracMemory2Memory(binZipData, binZipSize, &binData, &binSize); binFile = new PERBinFile(); binFile->openData(binData); delete[] binZipData; return true; } void PERFile::seekTo(int offset) { if (file == NULL) { return; } fseek(file, offset, SEEK_SET); } bool PERFile::setVideoData(int * code) { if (file == NULL) { return false; } int sizeOfHead = sizeof(PERPackageHead) + sizeof(PERPackagePESHead) + sizeof(PERPackageVideoHead); while (true) { PERVideoPackage package; fread(&package.head, sizeof(PERPackageHead), 1, file); fread(&package.pesHead, sizeof(PERPackagePESHead), 1, file); fread(&package.videoHead, sizeof(PERPackageVideoHead), 1, file); int id = -1; int width, height; switch (streamType) { case STREAM_TYPE_MAIN: id = package.pesHead.streamID - 0xE0; width = binFile->width; height = binFile->height; break; case STREAM_TYPE_SUB: id = package.pesHead.streamID - 0xB0; width = binFile->subWidth; height = binFile->subHeight; break; } int size = package.videoHead.videoDataSize; float ts = package.videoHead.fPTS; if ((id >= 0) && (id < MAX_CAMERA_COUNT)) { PERDecoder * decoder = mc->perPano->decoders[id]; if ((ts <= mc->timeline) && (ts >= decoder->lastTS)) { uchar * data = new uchar[size]; fread(data, size, 1, file); PERPackage * package = new PERPackage(size, data, ts, width, height, 0); decoder->pushBuffer(package); *code = id; return true; } else if ((ts <= mc->timeline) && (ts < decoder->lastTS)) { fseek(file, size, SEEK_CUR); //跳过 } else if ((ts > mc->timeline) && (ts >= decoder->lastTS)) { fseek(file, -sizeOfHead, SEEK_CUR); //跳回去 } else if ((ts > mc->timeline) && (ts < decoder->lastTS)) { fseek(file, size, SEEK_CUR); //跳过 } return false; } else { fseek(file, size, SEEK_CUR); } if (feof(file)) { return false; } } }<file_sep>/app/src/main/cpp/GLManager.cpp // // Created by tir on 2016/9/1. // #include "GLManager.h" #include "MainController.h" GLManager::GLManager() { GLMatrix::mMakeUnit(glProjectionMatrix); GLMatrix::mMakeVec3(glRotateXAxis, 1, 0, 0); GLMatrix::mMakeVec3(glRotateYAxis, 0, 1, 0); GLMatrix::mMakeVec3(glRotateZAxis, 0, 0, 1); width = 1; height = 1; panoType = PANO_TYPE_NONE; pesPano = NULL; perPano = NULL; onlinePano = NULL; } bool GLManager::glmInit(int width, int height) { isVRMode = false; isGlobularMode = true; isNeedReloadBin = false; radius = 0; glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); for (int i = 0; i < MAX_CAMERA_COUNT; i++) { for (int j = 0; j < 4; j++) { glGenTextures(1, &textures[i][j]); glBindTexture(GL_TEXTURE_2D, textures[i][j]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D, 0); } } glmReloadBin(); //创建纹理 glGenTextures(1, &displayTexture); glBindTexture(GL_TEXTURE_2D, displayTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); glBindTexture(GL_TEXTURE_2D, 0); //创建renderbuffer glGenRenderbuffers(1, &renderBuffer); glBindRenderbuffer(GL_RENDERBUFFER, renderBuffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height); glBindRenderbuffer(GL_RENDERBUFFER, 0); //创建framebuffer glGenFramebuffers(1, &frameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, displayTexture, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, renderBuffer); glBindFramebuffer(GL_FRAMEBUFFER, 0); glFinish(); //glCheckFramebufferStatus(GL_FRAMEBUFFER); shaderProgram = buildProgram(VERTEX_SHADER, FRAG_SHADER); glUseProgram(shaderProgram); shaderVertex = glGetAttribLocation(shaderProgram, "vPosition"); shaderTexture = glGetAttribLocation(shaderProgram, "a_texCoord"); shaderMatrix = glGetUniformLocation(shaderProgram, "glMatrix"); tex_type = glGetUniformLocation(shaderProgram, "SampleType"); tex_y = glGetUniformLocation(shaderProgram, "SamplerY"); tex_u = glGetUniformLocation(shaderProgram, "SamplerU"); tex_v = glGetUniformLocation(shaderProgram, "SamplerV"); tex_a = glGetUniformLocation(shaderProgram, "SamplerA"); return true; } void GLManager::glmReloadBin() { PESBinFile * binFile; switch (panoType) { case PANO_TYPE_PES: binFile = pesPano->binFile; break; case PANO_TYPE_PER: binFile = perPano->file->binFile; break; case PANO_TYPE_ONLINE: binFile = onlinePano->binFile; break; default: break; } for (int i = 0; i < binFile->camCount; i++) { int code = binFile->index[i]; if (vboVer[code] == 0) { glGenBuffers(1, &vboVer[code]); } glBindBuffer(GL_ARRAY_BUFFER, vboVer[code]); glBufferData(GL_ARRAY_BUFFER, binFile->verCoordCount[code] * sizeof(GLfloat), binFile->verCoord[code], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); if (vboTex[code] == 0) { glGenBuffers(1, &vboTex[code]); } glBindBuffer(GL_ARRAY_BUFFER, vboTex[code]); glBufferData(GL_ARRAY_BUFFER, binFile->texCoordCount[code] * sizeof(GLfloat), binFile->texCoord[code], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindTexture(GL_TEXTURE_2D, textures[code][3]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, binFile->width, binFile->height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, binFile->meshes[code]->imgData); glBindTexture(GL_TEXTURE_2D, 0); } radius = binFile->radius; radius = 450; // setOriginalVerCoord(binFile->width, binFile->height); // if (radius == 0) { // radius = binFile->radius; // } else { // radius = -radius; // } isNeedReloadBin = false; } void GLManager::glmDeinit() { glDeleteProgram(shaderProgram); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); for (int i = 0; i < MAX_CAMERA_COUNT; i++) { for (int j = 0; j < 4; j++) { glDeleteTextures(1, &textures[i][j]); } glDeleteBuffers(1,&vboVer[i]); glDeleteBuffers(1,&vboTex[i]); } glDeleteFramebuffers(1, &frameBuffer); glDeleteRenderbuffers(1, &renderBuffer); glDeleteTextures(1, &displayTexture); } void GLManager::glmResize() { // glmResize(width, height, fovy); glmResize(width, height); } //void GLManager::glmResize(int width, int height, float fovy) { // this->width = width; // this->height = height; // this->fovy = fovy; // GLfloat aspect; // if (isVRMode) { // aspect = (GLfloat)(width / 2)/(GLfloat)height; // } else { // aspect = (GLfloat)width/(GLfloat)height; // } // GLfloat zNear = 0.1f; // GLfloat zFar = 2000.0f; // // GLfloat top = zNear * ((GLfloat) tan(fovy * PI / 360.0)); // GLfloat bottom = -top; // GLfloat left = bottom * aspect; // GLfloat right = top * aspect; // // GLMatrix::mFrustum(glProjectionMatrix, left, right, bottom, top, zNear, zFar); // glViewport(0, 0, width, height); //} void GLManager::glmResize(int width, int height) { this->width = width; this->height = height; GLfloat aspect; if (isVRMode) { aspect = (GLfloat)(width / 2)/(GLfloat)height; } else { aspect = (GLfloat)width/(GLfloat)height; } GLfloat zNear = 0.1f; GLfloat zFar = 2000.0f; GLfloat top = zNear * ((GLfloat) tan(fovy * PI / 360.0)); GLfloat bottom = -top; GLfloat left = bottom * aspect; GLfloat right = top * aspect; GLMatrix::mFrustum(glProjectionMatrix, left, right, bottom, top, zNear, zFar); glViewport(0, 0, width, height); } int writeFlag = true; void GLManager::glmStep(float x, float y, float z, float fovy) { if (panoType == PANO_TYPE_NONE) { return; } if ((panoType == PANO_TYPE_PES) && (pesPano == NULL)) { return; } if ((panoType == PANO_TYPE_PER) && (perPano == NULL)) { return; } if ((panoType == PANO_TYPE_ONLINE) && (onlinePano == NULL)) { return; } if (isNeedReloadBin) { glmReloadBin(); } bool isVRMode = this->isVRMode; bool isGlobularMode = this->isGlobularMode; // if (isVRMode) { // glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer); // } glClear(GL_COLOR_BUFFER_BIT); glClearColor(GL_BACKGROUND_COLOR); float yd = (float)(y / 180 * PI); float xd = (float)(x / 180 * PI); float zd = (float)(z / 180 * PI); this->fovy = fovy; glmResize(); float glModelViewMatrix[16]; float glMatrix[16]; GLMatrix::mMakeUnit(glModelViewMatrix); GLMatrix::mMakeUnit(glMatrix); if (isGlobularMode) { float glTranslate[3]; GLMatrix::mMakeVec3(glTranslate, 0, 0, -(radius * 7 / 8)); GLMatrix::mTranslate(glModelViewMatrix, glTranslate); GLMatrix::mRotate(glModelViewMatrix, -yd, glRotateXAxis); GLMatrix::mRotate(glModelViewMatrix, -xd, glRotateZAxis); float rollAxis[3] = {(float) sin(-xd), (float) cos(-xd), 0}; GLMatrix::mRotate(glModelViewMatrix, -zd, rollAxis); GLMatrix::mCalMulti(glMatrix, glProjectionMatrix, glModelViewMatrix); } else { float glTranslate[3]; GLMatrix::mMakeVec3(glTranslate, xd * 500, -yd * 500, 0); GLMatrix::mTranslate(glModelViewMatrix, glTranslate); GLMatrix::mCalMulti(glMatrix, glProjectionMatrix, glModelViewMatrix); } int width; int height; int camCount; PESBinFile * binFile; switch (panoType) { case PANO_TYPE_PES: binFile = pesPano->binFile; break; case PANO_TYPE_PER: binFile = perPano->file->binFile; break; case PANO_TYPE_ONLINE: binFile = onlinePano->binFile; break; } camCount = binFile->camCount; for (int i = 0; i < camCount; i++) { int code; bool isAvailableToDisplay = false; uchar *data = NULL; switch (panoType) { case PANO_TYPE_PES: code = pesPano->binFile->index[i]; isAvailableToDisplay = pesPano->decoders[code]->isAvailableToDisplay; data = pesPano->decoders[code]->texData; width = pesPano->binFile->width; height = pesPano->binFile->height; break; case PANO_TYPE_PER: code = perPano->file->binFile->index[i]; isAvailableToDisplay = perPano->decoders[code]->isAvailableToDisplay; data = perPano->decoders[code]->texData; width = perPano->decoders[code]->texWidth; height = perPano->decoders[code]->texHeight; break; case PANO_TYPE_ONLINE: code = onlinePano->binFile->index[i]; isAvailableToDisplay = onlinePano->decoders[code]->isAvailableToDisplay; data = onlinePano->decoders[code]->texData; width = onlinePano->decoders[code]->texWidth; height = onlinePano->decoders[code]->texHeight; break; default: return; } // if(writeFlag){ // LOGI("GLManager: cid %d:\n", code); // if (width!=0){ // char filename[100]; // sprintf(filename, "/storage/emulated/0/Pano/pgm/a_%d.pgm", code); // LOGI("GLManager: 文件名 %s:\n", filename); // FILE *fp = fopen(filename, "wb+"); // if (fp){ // LOGI("GLManager: width %d,height %d:\n", width,height); // char buff[512]; // sprintf(buff, "P5\n%d %d\n%d\n", width, height, 255); // fwrite(buff, 1, strlen(buff), fp); // fwrite(data, 1, width * height, fp); // fclose(fp); // } // writeFlag = false; // } // } if (isAvailableToDisplay) { glBindTexture(GL_TEXTURE_2D, textures[code][0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width, height, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, textures[code][1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, data + width * height); glBindTexture(GL_TEXTURE_2D, textures[code][2]); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, width / 2, height / 2, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, data + width * height * 5 / 4); } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, textures[code][0]); glUniform1i(tex_y, 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, textures[code][1]); glUniform1i(tex_u, 1); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, textures[code][2]); glUniform1i(tex_v, 2); glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, textures[code][3]); glUniform1i(tex_a, 3); if (isGlobularMode) { glUniform1i(tex_type, 1); glUniformMatrix4fv(shaderMatrix, 1, GL_FALSE, glMatrix); glBindBuffer(GL_ARRAY_BUFFER, vboVer[code]); glVertexAttribPointer(shaderVertex, 3, GL_FLOAT, 0, 0, 0); glEnableVertexAttribArray(shaderVertex); glBindBuffer(GL_ARRAY_BUFFER, vboTex[code]); glVertexAttribPointer(shaderTexture, 2, GL_FLOAT, 0, 0, 0); glEnableVertexAttribArray(shaderTexture); glBindBuffer(GL_ARRAY_BUFFER, 0); switch (panoType) { case PANO_TYPE_PES: glDrawArrays(GL_TRIANGLES, 0, pesPano->binFile->verCoordCount[code]); break; case PANO_TYPE_PER: glDrawArrays(GL_TRIANGLES, 0, perPano->file->binFile->verCoordCount[code]); break; case PANO_TYPE_ONLINE: if(isVRMode) { //width = 2880; //height = 1600; LOGI("ttttt:width:%d,height:%d",this->width,this->height); glViewport(0,0,this->width/2,this->height); glDrawArrays(GL_TRIANGLES, 0, onlinePano->binFile->verCoordCount[code]); glViewport(this->width/2,0,this->width/2,this->height); glDrawArrays(GL_TRIANGLES, 0, onlinePano->binFile->verCoordCount[code]); } else { glDrawArrays(GL_TRIANGLES, 0, onlinePano->binFile->verCoordCount[code]); } break; default: return; } } else { glUniform1i(tex_type, 2); glUniformMatrix4fv(shaderMatrix, 1, GL_FALSE, glMatrix); glVertexAttribPointer(shaderVertex, 3, GL_FLOAT, 0, 0, originalVerCoord[i]); glEnableVertexAttribArray(shaderVertex); glVertexAttribPointer(shaderTexture, 2, GL_FLOAT, 0, 0, TEXTURE_COORD); glEnableVertexAttribArray(shaderTexture); switch (panoType) { case PANO_TYPE_PES: glDrawArrays(GL_TRIANGLES, 0, 6); break; case PANO_TYPE_PER: glDrawArrays(GL_TRIANGLES, 0, 6); break; case PANO_TYPE_ONLINE: glDrawArrays(GL_TRIANGLES, 0, 6); break; default: return; } } } // if (isVRMode) { // glBindFramebuffer(GL_FRAMEBUFFER, 0); // // glBindTexture(GL_TEXTURE_2D, displayTexture); // glGenerateMipmap(GL_TEXTURE_2D); // glBindTexture(GL_TEXTURE_2D, 0); // // glClear(GL_COLOR_BUFFER_BIT); // glClearColor(GL_BACKGROUND_COLOR); // // glUniform1i(tex_type, 0); // glActiveTexture(GL_TEXTURE0); // glBindTexture(GL_TEXTURE_2D, displayTexture); // glUniform1i(tex_y, 0); // GLMatrix::mMakeUnit(glMatrix); // glUniformMatrix4fv(shaderMatrix, 1, GL_FALSE, glMatrix); // glVertexAttribPointer(shaderVertex, 2, GL_FLOAT, 0, 0, VR_VERTEX_COORD); // glEnableVertexAttribArray(shaderVertex); // glVertexAttribPointer(shaderTexture, 2, GL_FLOAT, 0, 0, TEXTURE_COORD); // glEnableVertexAttribArray(shaderTexture); // glDrawArrays(GL_TRIANGLES, 0, 12); // // glBindTexture(GL_TEXTURE_2D, 0); // // } } GLuint GLManager::buildShader(const char* source, GLenum shaderType) { GLuint shaderHandle = glCreateShader(shaderType); if (shaderHandle) { glShaderSource(shaderHandle, 1, &source, 0); glCompileShader(shaderHandle); GLint compiled = 0; glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &compiled); if (!compiled) { GLint infoLen = 0; glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &infoLen); if (infoLen) { char* buf = (char*)malloc(infoLen); if (buf) { glGetShaderInfoLog(shaderHandle, infoLen, NULL, buf); mc->setErrorMessage("编译Shader失败!"); LOGI("GLM: Could not compile shader %d:\n%s\n", shaderType, buf); free(buf); } glDeleteShader(shaderHandle); shaderHandle = 0; } } } return shaderHandle; } GLuint GLManager::buildProgram(const char* vertexShaderSource, const char* fragmentShaderSource) { vertexShader = buildShader(vertexShaderSource, GL_VERTEX_SHADER); fragmentShader = buildShader(fragmentShaderSource, GL_FRAGMENT_SHADER); GLuint programHandle = glCreateProgram(); if (programHandle) { glAttachShader(programHandle, vertexShader); glAttachShader(programHandle, fragmentShader); glLinkProgram(programHandle); GLint linkStatus = GL_FALSE; glGetProgramiv(programHandle, GL_LINK_STATUS, &linkStatus); if (linkStatus != GL_TRUE) { GLint bufLength = 0; glGetProgramiv(programHandle, GL_INFO_LOG_LENGTH, &bufLength); if (bufLength) { char* buf = (char*) malloc(bufLength); if (buf) { glGetProgramInfoLog(programHandle, bufLength, NULL, buf); mc->setErrorMessage("链接Shader失败!"); LOGI("GLM: Could not link program:\n%s\n", buf); free(buf); } } glDeleteProgram(programHandle); programHandle = 0; } } return programHandle; } void GLManager::setOriginalVerCoord(int w, int h) { float z = -500; float fh = 250 * w / h / 2; for (int i = 0; i < 8; i++) { float pointA[3] = {500.0f * (i - 1), fh, z}; float pointB[3] = {500.0f * i, fh, z}; float pointC[3] = {500.0f * (i - 1), -fh, z}; float pointD[3] = {500.0f * i, -fh, z}; int c = 0; float * index[6] = {pointA, pointB, pointD, pointA, pointD, pointC}; for (int j = 0; j < 6; j++) { for (int k = 0; k < 3; k++) { originalVerCoord[i][c++] = index[j][k]; } } } }<file_sep>/app/src/main/cpp/OnlineSDK/PEClientSDK/非项目文件/PEClientSDK0.h ////////////////////////////////////////////////////////////////////////// /// COPYRIGHT NOTICE /// Copyright (c) 2013-2020, 宁波环视信息科技有限公司 /// All rights reserved. /// /// @file PEClientSDK.h /// @brief PanoEye PEClientSDK /// /// @version 0.0.1 /// @author <NAME> /// @created 2016/08/16 /// ////////////////////////////////////////////////////////////////////////// #ifndef PECLIENTSDK_PECLIENTSDK_H_ #define PECLIENTSDK_PECLIENTSDK_H_ #include "../type.h" #if (defined(WIN32) || defined(_WIN32_WCE)) #include <Windows.h> #ifdef PECLIENTSDKDLL_EXPORTS #define PE_API __declspec(dllexport) #else #define PE_API __declspec(dllimport) #endif #ifndef WINAPI #define WINAPI __stdcall #endif typedef unsigned __int64 UINT64; typedef __int64 INT64; #ifndef _TM_DEFINED struct tm { int tm_sec; /* seconds after the minute - [0,59] */ int tm_min; /* minutes after the hour - [0,59] */ int tm_hour; /* hours since midnight - [0,23] */ int tm_mday; /* day of the month - [1,31] */ int tm_mon; /* months since January - [0,11] */ int tm_year; /* years since 1900 */ int tm_wday; /* days since Sunday - [0,6] */ int tm_yday; /* days since January 1 - [0,365] */ int tm_isdst; /* daylight savings time flag */ }; #define _TM_DEFINED #endif /* _TM_DEFINED */ #elif defined(ANDROID_NDK) #include "basetsd.h" #include <time.h> #define PE_API #define CONST const #define CALLBACK #define WINAPI #define IN #define OUT #elif defined(__linux__) || defined(__APPLE__) //linux #ifdef PECLIENTSDKDLL_EXPORTS #define PE_API __attribute__((visibility("default"))) #else #define PE_API #endif #define CONST const #define CALLBACK __stdcall #define WINAPI __stdcall #define IN #define OUT //typedef unsigned long long UINT64; //typedef long long INT64; #endif //#define PECLIENTSDKDLL_API PE_API //#include "../type.h" #include <time.h> ////////////////////////////////////////////////////////////////////////// // 错误代码 ////////////////////////////////////////////////////////////////////////// #define PE_ERRCODE_BEGIN 0x8000F000 #define PE_ERRCODE_SUCCESS ( 0) //未知事件 #define PE_ERRCODE_FAIL (PE_ERRCODE_BEGIN + 1) //执行失败 #define PE_ERRCODE_NOSUPPORT (PE_ERRCODE_BEGIN + 3) //不支持该功能 #define PE_ERRCODE_VERIFY (PE_ERRCODE_BEGIN + 4) //验证错误 #define PE_ERRCODE_OUTOFMEM (PE_ERRCODE_BEGIN + 5) //内存溢出 #define PE_ERRCODE_NOT_FIND (PE_ERRCODE_BEGIN + 7) //未找到 #define PE_ERRCODE_NULLPOINT (PE_ERRCODE_BEGIN + 9) //空指针 #define PE_ERRCODE_PARAM (PE_ERRCODE_BEGIN + 10) //参数错误 #define PE_ERRCODE_USER_PWD (PE_ERRCODE_BEGIN + 11) //用户名或密码错误 #define PE_ERRCODE_NETWORK (PE_ERRCODE_BEGIN + 12) //设备不在线或网络错误 #define PE_ERRCODE_TIMEOUT (PE_ERRCODE_BEGIN + 13) //网络超时 ////////////////////////////////////////////////////////////////////////// // 事件ID ////////////////////////////////////////////////////////////////////////// #define PE_EVENT_BEGIN 100 #define PE_EVENT_UNKNOWN ( -1) //未知事件 #define PE_EVENT_LOGIN_CLOSE (PE_EVENT_BEGIN + 1) //登录连接被断开 #define PE_EVENT_PREVIEW_CLOSE (PE_EVENT_BEGIN + 2) //预览连接被断开 #ifndef STRUCT_PE_ENCODER_TYPE_DEFINED #define STRUCT_PE_ENCODER_TYPE_DEFINED 1 typedef enum tag_PE_ENCODER_TYPE { PE_ENCODER_TYPE_UNKNOWN = 0, //未知编码 PE_ENCODER_TYPE_H264 = 1, //H264编码 PE_ENCODER_TYPE_MJPEG = 2, //MJPEG编码 PE_ENCODER_TYPE_H264_MAIN = 3, //H264 main profile PE_ENCODER_TYPE_H264_HIGH = 4, //H264 high profile PE_ENCODER_TYPE_G711_ALAW = 5, //G711A律编码 PE_ENCODER_TYPE_G711_ULAW = 6, //G711U律编码 PE_ENCODER_TYPE_RAW_PCM = 7, //PCM编码,即不编码 }PE_ENCODER_TYPE; #endif #ifndef STRUCT_PE_AVFRAME_DATA_DEFINED #define STRUCT_PE_AVFRAME_DATA_DEFINED 1 //音视频帧 typedef struct tag_PE_AVFRAME_DATA { BYTE byStreamFormat; //1表示原始流,2表示混合流 BYTE byESStreamType; //原始流类型,1表示视频,2表示音频 BYTE byEncoderType; //编码格式,其值请参看PE_ENCODER_TYPE枚举定义 BYTE byFrameType; //数据帧类型,1表示I帧, 2表示P帧, 0表示未知类型 WORD wFrameRate; //帧率 WORD wBitRate; //当前码率 BYTE byChannel; //通道 DWORD lSequenceId; //数据帧序号 CHAR *pszData; //数据 DWORD lDataLength; //数据有效长度 DWORD lImageWidth; //视频宽度 DWORD lImageHeight; //视频高度 INT64 lTimeStamp; //数据采集时间戳,单位为微秒 }PE_AVFRAME_DATA, *LPPE_AVFRAME_DATA; #endif #ifndef STRUCT_PE_CLIENT_DEFINED #define STRUCT_PE_CLIENT_DEFINED 1 //预览接口 typedef struct tagPE_CLIENT_PREVIEWINFO { LONG lChannel; //通道号 DWORD dwStreamType; // 码流类型,0-主码流,1-子码流 DWORD dwLinkMode; // 0:TCP方式 BYTE byProtoType; //应用层取流协议,0-私有协议 BYTE byRes[171]; //保留 }PE_CLIENT_PREVIEWINFO, *LPPE_CLIENT_PREVIEWINFO; typedef struct tagPE_CLIENT_FILECOND { LONG lChannel; DWORD dwIsLocked; struct tm struStartTime; struct tm struStopTime; BYTE byRes2[104]; //保留 }PE_CLIENT_FILECOND, *LPPE_CLIENT_FILECOND; //录象文件参数 typedef struct tagPE_CLIENT_FINDDATA { CHAR sFileName[250]; //文件名 struct tm struStartTime; //文件的开始时间 struct tm struStopTime; //文件的结束时间 DWORD dwFileSize; //文件的大小 BYTE byLocked; //1表示此文件已经被锁定,0表示正常的文件 BYTE byRes[41]; //保留 }PE_CLIENT_FINDDATA, *LPPE_CLIENT_FINDDATA; // 按ID+时间回放结构体 typedef struct tagPE_CLIENT_PLAYBACKINFO { LONG lChannel; //通道号 DWORD dwStreamType; // 码流类型,0-主码流,1-子码流 struct tm struBeginTime; struct tm struEndTime; BYTE byRes[104]; }PE_CLIENT_PLAYBACKINFO, *LPPE_CLIENT_PLAYBACKINFO; typedef struct tagPE_CLIENT_SADPINFO { CHAR sIP[64]; CHAR sUUID[64]; CHAR sDevName[256]; CHAR sSerialNo[64]; BYTE byRes[104]; //保留 }PE_CLIENT_SADPINFO, *LPPE_CLIENT_SADPINFO; typedef struct tagPE_CLIENT_SADPINFO_LIST { WORD wSadpNum; // 搜索到设备数目 BYTE byRes[182]; // 保留字节 PE_CLIENT_SADPINFO struSadpInfo[256]; // 搜索 }PE_CLIENT_SADPINFO_LIST, *LPPE_CLIENT_SADPINFO_LIST; #endif #ifndef _PE_PTZ_POS_CFG_DEFINED typedef struct tagPE_PTZ_POS_CFG { float fPanPos;//水平参数 float fTiltPos;//垂直参数 float fZoomPos;//变倍参数 BYTE byRes[172]; }PE_PTZ_POS_CFG, *LPPE_PTZ_POS_CFG; #define _PE_PTZ_POS_CFG_DEFINED #endif #ifndef _PE_PTZ_CMD_DEFINED /**********************云台控制命令 begin***********************/ #define PE_IRISCLOSE 0x0102 /**< 光圈关 */ #define PE_IRISOPEN 0x0104 /**< 光圈开 */ #define PE_FOCUSNEAR 0x0202 /**< 近聚集 */ #define PE_FOCUSFAR 0x0204 /**< 远聚集 */ #define PE_ZOOMTELE 0x0302 /**< 缩小 */ #define PE_ZOOMWIDE 0x0304 /**< 放大 */ #define PE_TILTUP 0x0402 /**< 向上 */ #define PE_TILTDOWN 0x0404 /**< 向下 */ #define PE_PANRIGHT 0x0502 /**< 向右 */ #define PE_PANLEFT 0x0504 /**< 向左 */ #define PE_LEFTUP 0x0702 /**< 左上 */ #define PE_LEFTDOWN 0x0704 /**< 左下 */ #define PE_RIGHTUP 0x0802 /**< 右上 */ #define PE_RIGHTDOWN 0x0804 /**< 右下 */ #define PE_BRUSHON 0x0A01 /**< 雨刷开 */ #define PE_BRUSHOFF 0x0A02 /**< 雨刷关 */ #define PE_BRUSHONCE 0x0A03 /**< 雨刷单次 */ #define PE_LIGHTON 0x0B01 /**< 灯开 */ #define PE_LIGHTOFF 0x0B02 /**< 灯关 */ #define PE_INFRAREDON 0x0C01 /**< 红外开 */ #define PE_INFRAREDOFF 0x0C02 /**< 红外关 */ #define PE_HEATON 0x0D01 /**< 加热开 */ #define PE_HEATOFF 0x0D02 /**< 加热关 */ /**********************云台控制命令 end*************************/ #define _PE_PTZ_CMD_DEFINED #endif #ifndef _PE_PLAY_CMD_DEFINED /**********************播放控制命令 begin***********************/ #define PE_PLAYPAUSE 0x001 /**< 暂停播放 */ #define PE_PLAYRESTART 0x002 /**< 恢复播放(将恢复暂停前的速度播放) */ #define PE_PLAYFAST 0x003 /**< 快放 */ #define PE_PLAYSLOW 0x004 /**< 慢放 */ #define PE_PLAYNORMAL 0x005 /**< 正常速度播放*/ #define PE_PLAYSETPOS 0x011 /**< 改变文件回放的进度 */ #define PE_PLAYGETPOS 0x012 /**< 获取按文件回放的进度 */ #define PE_PLAYSETTIME 0x014 /**< 按绝对时间定位 */ #define PE_PLAYGETTIME 0x013 /**< 获取当前已经播放的时间*/ /**********************播放控制命令 end*************************/ #define _PE_PLAY_CMD_DEFINED #endif #ifndef _PE_SERVER_CONFIG_CMD_DEFINED /**********************服务器配置命令 begin*********************/ #define PE_SET_PTZ_POS 14 #define PE_GET_PTZ_POS 15 /**********************服务器配置命令 end***********************/ #define _PE_SERVER_CONFIG_CMD_DEFINED #endif #ifdef __cplusplus extern "C" { #endif typedef void (CALLBACK *fPERealDataCallBack)(LONG lRealHandle, CONST CHAR * szSerialNo, int nStreamID, LPPE_AVFRAME_DATA lpData, void * pUserData); typedef void (CALLBACK *fPEPlayDataCallBack)(LONG lPlayHandle, CONST CHAR *sServerFileName, int nStreamID, LPPE_AVFRAME_DATA lpData, void * pUserData); typedef void (CALLBACK *fPEExceptionCallBack)(DWORD dwType, LONG lHandle, void *pUserData); PE_API BOOL WINAPI PE_Client_Init(); PE_API BOOL WINAPI PE_Client_Cleanup(); PE_API BOOL WINAPI PE_Client_SetExceptionCallBack(fPEExceptionCallBack cbExceptionCallBack, void* pUserData); PE_API LONG WINAPI PE_Client_Login(CONST CHAR *sDVRIP, WORD wDVRPort, CONST CHAR *sUserName, CONST CHAR *sPassword); PE_API BOOL WINAPI PE_Client_Logout(LONG lUserID); PE_API LONG WINAPI PE_Client_RealPlay(LONG lUserID, LPPE_CLIENT_PREVIEWINFO lpPreviewInfo, fPERealDataCallBack cbRealDataCallBack, void* pUserData); PE_API BOOL WINAPI PE_Client_StopRealPlay(LONG lRealHandle); PE_API LONG WINAPI PE_Client_FindFile(LONG lUserID, LPPE_CLIENT_FILECOND pFindCond); PE_API BOOL WINAPI PE_Client_FindNextFile(LONG lFindHandle, LPPE_CLIENT_FINDDATA lpFindData); PE_API BOOL WINAPI PE_Client_FindClose(LONG lFindHandle); PE_API LONG WINAPI PE_Client_PlayBackByName(LONG lUserID, CONST CHAR *sPlayBackFileName, fPEPlayDataCallBack cbPlayDataCallBack, void* pUserData); PE_API LONG WINAPI PE_Client_PlayBackByTime(LONG lUserID, CONST LPPE_CLIENT_PLAYBACKINFO para, fPEPlayDataCallBack cbPlayDataCallBack, void* pUserData); PE_API BOOL WINAPI PE_Client_PlayBackControl(LONG lPlayHandle, DWORD dwControlCode, LPVOID lpInBuffer = NULL, DWORD dwInLen = 0, LPVOID lpOutBuffer = NULL, DWORD *lpOutLen = NULL); PE_API BOOL WINAPI PE_Client_StopPlayBack(LONG lPlayHandle); PE_API BOOL WINAPI PE_Client_SetServerConfig(LONG lUserID, DWORD dwCommand, LONG lChannel, LPVOID lpInBuffer, DWORD dwInBufferSize); PE_API BOOL WINAPI PE_Client_GetServerConfig(LONG lUserID, DWORD dwCommand, LONG lChannel, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned); PE_API BOOL WINAPI PE_Client_PTZControl(LONG lRealHandle, DWORD dwPTZCommand, BOOL dwStop, DWORD dwSpeed); PE_API BOOL WINAPI PE_Client_GetSadpInfoList(LONG lUserID, LPPE_CLIENT_SADPINFO_LIST lpSadpInfoList); PE_API LONG WINAPI PE_Client_GetFileByName(LONG lUserID, CONST CHAR *sServerFileName, CONST CHAR *sSavedFileDirectory); PE_API int WINAPI PE_Client_GetDownloadPos(LONG lFileHandle); PE_API BOOL WINAPI PE_Client_StopGetFile(LONG lFileHandle); PE_API LONG WINAPI PE_Client_GetLastError(); PE_API BOOL WINAPI PE_Client_Demux(char *pszData, long lDataLength, LPPE_AVFRAME_DATA *lpData); #ifdef __cplusplus } #endif #endif <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PESDecodeThread.java package panoeye.pelibrary; import android.util.Log; /** * Created by tir on 2016/12/15. */ //解码线程类 class PESDecodeThread extends Thread{ private PEDecoder decoder;//解码器 private PESFile pesFile;//pes文件 private Integer index = 0;// private Thread thread;//线程 private Integer cid;//镜头id private boolean needDecode;// private boolean stopFlag = true;// boolean threadStop = false;// float tmp = 0f;// //构造函数 PESDecodeThread(PEDecoder decoder, PESFile pesFile,Integer cid ){ this.decoder = decoder; this.pesFile = pesFile; this.cid = cid; } //重写了父类的run方法 public void run() { /* while (true){ try { if(needDecode){ needDecode = false; decoder.decode(pesFile.getPEVideoPacket(index)); //Log.e(String.format("线程%d",cid),String.format("%d",index)); }else{ Thread.sleep(20); } }catch (InterruptedException e){ e.printStackTrace(); } }*/ synchronized (cid){ try { while (true){ if (stopFlag==false){ break; } if(needDecode == true) { if (index<pesFile.timestampList.size()-1){ decoder.decode(pesFile.getPESVideoPacket(index -1).oneFrameData,cid,1);//解码 } needDecode = false; cid.wait(); } } Log.i("线程已经结束!","msg"); threadStop = true; }catch (InterruptedException e){ Log.e("线程","报错"); }catch (PEError e){ Log.e("线程","报错了"); } } } void threadStop(){ stopFlag = false; } void jumpToTime(Float jumpToTime) { if (jumpToTime == 0){ index = 0; return; } if (jumpToTime >= 0f && jumpToTime+pesFile.firstPacketTimestampOffset <= pesFile.IFrame.get(pesFile.IFrame.size()-1)) { int i = 0; while (true){ if ((jumpToTime+pesFile.firstPacketTimestampOffset)<=pesFile.IFrame.get(i)){ tmp = pesFile.IFrame.get(i-1); break; } i++; } i = 0; while (true){ if (tmp == pesFile.timestampList.get(i)){ index = i; if (index == 0){ index =1; } tmp =pesFile.timestampList.get(i)-pesFile.firstPacketTimestampOffset; break; } i++; } } } //时间轴控制 void step(Float timeLine ){ /* if(thread == null){ thread = new Thread(this); thread.start(); } if(timeLine>=(pesFile.timestampList.get(index))-pesFile.firstPacketTimestampOffset){ index+=1; needDecode = true; }*/ if(thread == null){ thread = new Thread(this); thread.start(); } synchronized (cid){//synchronized() 创建了一个互斥锁,防止{}里的内容在同一时间内被其他线程访问,起到了线程保护的作用 if (index<pesFile.timestampList.size()-1) { if (timeLine >= (pesFile.timestampList.get(index)) - pesFile.firstPacketTimestampOffset) { index += 1;//index自增1 needDecode = true;//需要解码 cid.notify();//唤醒线程 //Log.d("index", index.toString()); //Log.e(String.format("线程%d",cid),String.format("%d",index-1)); } } } } } <file_sep>/app/src/main/cpp/OnlineSDK/CClient/CClient.h #ifndef CAM360_LIBCAM_CLIENT_CLIENT_H_ #define CAM360_LIBCAM_CLIENT_CLIENT_H_ #include "../PanoDef.h" #if defined(USING_HPSOCKET) #include "HpSocketClient.h" #else #include "NBSocketClient.h" #endif #include "../XML/XmlRpcTX2Util.h" #include "../XML/XmlRpcTX2Value.h" #include <memory> #include <chrono> #include <condition_variable> #include <exception> #include <thread> #include <mutex> #include <functional> #include <vector> //#include <Windows.h> #if defined(USING_HPSOCKET) class CClient : public CHpSocketClient #else class CClient : public CNBSocketClient #endif { private: std::mutex stream_data_callback_mtx_; std::function<void(LPPE_STREAM_DATA, BYTE*, int)> stream_data_callback_; std::mutex file_data_callback_mtx_; std::function<void(LPPE_FILE_DATA, BYTE*, int)> file_data_callback_; bool logined_; std::mutex ReceiveMsgResponseMutex; std::condition_variable ReceiveMsgResponseConditionVariable; struct MsgResponse { char md5[33]; XmlRpcTX2Value::XmlRpcValue result; std::chrono::steady_clock::time_point time; MsgResponse(){ std::fill(std::begin(md5), std::end(md5), ' '); md5[32] = '\0'; time = std::chrono::steady_clock::now(); } MsgResponse(const MsgResponse & rhs){ std::copy(std::begin(rhs.md5), std::end(rhs.md5), md5); result = rhs.result; time = rhs.time; } bool operator==(const MsgResponse & rhs){ return std::string(md5) == std::string(rhs.md5); } bool operator==(std::string hash){ return std::string(md5) == hash; } }; std::list<MsgResponse> msg_response_list_; std::mutex msg_response_list_mtx_; std::chrono::steady_clock::time_point begin_time_point_; std::chrono::system_clock::time_point sync_time_; void MakeHash(char* hash, char *input, size_t inputlen); bool SendEmptyMsg(size_t s); public: CClient(); virtual ~CClient(); void SetStreamDataCallBack(void(*DataCallBack)(LPPE_STREAM_DATA lpInfo, BYTE* pData, int iLength, void *UserData), void *UserData); void SetFileDataCallBack(void(*DataCallBack)(LPPE_FILE_DATA lpInfo, BYTE* pData, int iLength, void *UserData), void *UserData); virtual void ClientAlloc() override; virtual void ClientRelease() override; bool Execute(const char* method, XmlRpcTX2Value::XmlRpcValue& params, XmlRpcTX2Value::XmlRpcValue& result, long msTime = 1000l); bool ProcessMsg(std::string msg); virtual bool Connect(const char *ipaddr, USHORT port) override; virtual bool Disconnect() override; bool Login(const char* username, const char* password); bool Logout(); // int AddNewCam(const char* ipaddr, const char* dev_name, const char *serial_no); // int DeleteOneCam(const char* uuid); typedef struct tag_RemotePanoSetup{ char ip[64]; char uuid[64]; char devName[256]; char serial_no[64]; uchar capture_type; uchar ptz_type; int model_type; int sub_model_type; }RemotePanoSetup, *LPRemotePanoSetup; bool GetCamList(RemotePanoSetup **ps, size_t *num); bool FreeCamList(RemotePanoSetup *ps); int DownloadPraram(const char *serial_no, const char * filename); // int UpdatePraram(const char *serial_no, const char * filename); bool FreeSysHead(BYTE *buff); public: int GetStreamPort(const char* uuid); bool GetStreamSysHead(const char* uuid, int stream_format, BYTE **buff, size_t *buff_size); // int GetCamState(); bool SetCamAction(const char* uuid,int action); bool RequestStreamData(const char* uuid, int stream_format, int *handle); bool SwitchStreamDataFormat(int handle, int stream_format); bool StopStreamData(int handle); struct RemoteRecordExtInfo { std::string record_time; std::string end_time; std::string full_dir; bool continuity; }; typedef std::vector<RemoteRecordExtInfo> RemoteRecordExtInfos; bool GetRecordFileList(const char* uuid, const char* begTime, const char* endTime, RemoteRecordExtInfos *info); bool PlayRecordFile(const char *uuid, const char *file_dir, float * total_time, struct tm *recTime, int *handle); bool StopPlayRecord(int handle); bool PausePlayRecord(int handle, bool bPause); bool GetPlayRecordState(int handle, float *cur_time); bool SetPlayRecordSpeed(int handle, int speed); bool SetPlayRecordCurrentTime(int handle, float cur_tm); bool SetServerConfig(const char* uuid, DWORD dwCommand, LPVOID lpInBuffer, DWORD dwInBufferSize); bool GetServerConfig(const char* uuid, DWORD dwCommand, LPVOID lpOutBuffer, DWORD dwOutBufferSize, LPDWORD lpBytesReturned); bool ControlPtzWithSpeed(const char* uuid, int cmd, int ptz_speed); bool GetFileByName(const char *file_dir, DWORD dwOffset, LPDWORD dwFileSize, int *handle); bool StopGetFile(int handle); std::chrono::system_clock::time_point GetSyncTimePoint(); private: virtual bool OnClientReceive(PanoComm pc, BYTE *msg_body, size_t msg_body_size) override; virtual bool OnClientClose() override; }; #endif //#define LOG "JavaCallCDemoLog" // 这个是自定义的LOG的标识 //#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG,__VA_ARGS__) // 定义LOGD类型 //#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG,__VA_ARGS__) // 定义LOGI类型 //#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG,__VA_ARGS__) // 定义LOGW类型 //#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG,__VA_ARGS__) // 定义LOGE类型 //#define LOGF(...) __android_log_print(ANDROID_LOG_FATAL,LOG,__VA_ARGS__) // 定义LOGF类型<file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PesHandle.java package panoeye.pelibrary; import android.opengl.GLSurfaceView; /** * Created by tir on 2017/3/20. */ public class PesHandle{ PESPano pano; PEDecodeBuffer decodeBuffer; PESDecodeManager decodeManager;//解码管理类 public Float duration;//pse文件第一个I帧到最后一帧之间的最小时间间隔,单位为秒。 public int camCount;//镜头模组个数 private static final String TAG = "PesHandle"; //构造函数 PesHandle(String name) throws PEError { pano = new PESPano(name); decodeBuffer = new PEDecodeBuffer(pano.binFile); decodeManager = new PESDecodeManager(pano,decodeBuffer); duration = pano.minDuration;//接收pse文件第一个I帧到最后一帧之间的最小时间间隔,单位为秒。 camCount = pano.binFile.info.camCount;//接收镜头模组个数 } //设置视图 void setView(GLSurfaceView view)throws PEError{ PERenderer myRenderer = new PERenderer(pano.binFile,decodeBuffer);//构造渲染器myRenderer view.setEGLContextClientVersion(2);//选择OpenGL ES 2.0的环境 view.setRenderer(myRenderer);//给view设置渲染器 } } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PESquare.java package panoeye.pelibrary; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; /** * Created by Administrator on 2018/1/22. * 此类定义全景的矩形显示模式 */ public class PESquare { public FloatBuffer mVertexBuffer; // 顶点缓冲 public FloatBuffer mVertexBuffer5; // 顶点缓冲 public FloatBuffer mVertexBuffer8; // 顶点缓冲 public FloatBuffer mTextureBuffer; // 纹理缓冲 public FloatBuffer mTextureFlipBuffer5; // 纹理缓冲 public FloatBuffer mTextureFlipBuffer8; // 纹理缓冲 static final float[] VERTEX = { // in counterclockwise order: -1, 0.4f, 0, // 左上 -1, -0.4f, 0, // 左下 -0.4f, -0.4f, 0, // 右下 -1, 0.4f, 0, // 左上 -0.4f, -0.4f, 0, // 右下 -0.4f, 0.4f, 0, // 右上 -0.4f, 0.4f, 0, // 左上 -0.4f, -0.4f, 0, // 左下 0.2f, -0.4f, 0, // 右下 -0.4f, 0.4f, 0, // 左上 0.2f, -0.4f, 0, // 右下 0.2f, 0.4f, 0, // 右上 }; static final float[] VERTEX_5 = { // in counterclockwise order: -1, 1, 0, // 左上 -1, 0, 0, // 左下 -0.2f, 0, 0, // 右下 -1, 1, 0, // 左上 -0.2f, 0, 0, // 右下 -0.2f, 1, 0, // 右上 -0.2f, 1, 0, // 左上 -0.2f, 0, 0, // 左下 0.6f, 0, 0, // 右下 -0.2f, 1, 0, // 左上 0.6f, 0, 0, // 右下 0.6f, 1, 0, // 右上 0.6f, 1, 0, // 左上 0.6f, 0, 0, // 左下 1.4f, 0, 0, // 右下 0.6f, 1, 0, // 左上 1.4f, 0, 0, // 右下 1.4f, 1, 0, // 右上 -1, 0, 0, // 左上 -1, -1, 0, // 左下 0.2f, -1, 0, // 右下 -1, 0, 0, // 左上 0.2f, -1, 0, // 右下 0.2f, 0, 0, // 右上 0.2f, 0, 0, // 左上 0.2f, -1, 0, // 左下 1.4f, -1, 0, // 右下 0.2f, 0, 0, // 左上 1.4f, -1, 0, // 右下 1.4f, 0, 0, // 右上 }; static final float[] VERTEX_8 = { -1, 0.8f, 0, // 左上 -1, 0, 0, // 左下 -0.4f, 0, 0, // 右下 -1, 0.8f, 0, // 左上 -0.4f, 0, 0, // 右下 -0.4f, 0.8f, 0, // 右上 -0.4f, 0.8f, 0, // 左上 -0.4f, 0, 0, // 左下 0.2f, 0, 0, // 右下 -0.4f, 0.8f, 0, // 左上 0.2f, 0, 0, // 右下 0.2f, 0.8f, 0, // 右上 0.2f, 0.8f, 0, // 左上 0.2f, 0, 0, // 左下 0.8f, 0, 0, // 右下 0.2f, 0.8f, 0, // 左上 0.8f, 0, 0, // 右下 0.8f, 0.8f, 0, // 右上 0.8f, 0.8f, 0, // 左上 0.8f, 0, 0, // 左下 1.4f, 0, 0, // 右下 0.8f, 0.8f, 0, // 左上 1.4f, 0, 0, // 右下 1.4f, 0.8f, 0, // 右上 -1, 0, 0, // 左上 -1, -0.8f, 0, // 左下 -0.4f, -0.8f, 0, // 右下 -1, 0, 0, // 左上 -0.4f, -0.8f, 0, // 右下 -0.4f, 0, 0, // 右上 -0.4f, 0, 0, // 左上 -0.4f, -0.8f, 0, // 左下 0.2f, -0.8f, 0, // 右下 -0.4f, 0, 0, // 左上 0.2f, -0.8f, 0, // 右下 0.2f, 0, 0, // 右上 0.2f, 0, 0, // 左上 0.2f, -0.8f, 0, // 左下 0.8f, -0.8f, 0, // 右下 0.2f, 0, 0, // 左上 0.8f, -0.8f, 0, // 右下 0.8f, 0, 0, // 右上 0.8f, 0, 0, // 左上 0.8f, -0.8f, 0, // 左下 1.4f, -0.8f, 0, // 右下 0.8f, 0, 0, // 左上 1.4f, -0.8f, 0, // 右下 1.4f, 0, 0, // 右上 }; private static final float[] TEX_VERTEX = { // in clockwise order: // 原始图像贴图(按顶点绘制顺序贴图),5路倒着,8路向右。 0, 1f, // 左上 0, 0, // 左下 1f, 0, // 右下 0, 1f, // 左上 1f, 0, // 右下 1f, 1f, // 右上 }; private static final float[] TEX_VERTEX_FLIP_5 = { //5路站着(对角线45°) 0, 0, // 左下 0, 1f, // 左上 1f, 1f, // 右上 0, 0, // 左下 1f, 1f, // 右上 1f, 0, // 右下 //5路站着(对角线-45°) // 1f, 0, // 右下 // 1f, 1f, // 右上 // 0, 1f, // 左上 // 1f, 0, // 右下 // 0, 1f, // 左上 // 0, 0, // 左下 }; private static final float[] TEX_VERTEX_FLIP_8 = { // //8路站着(对角线45°) // 0, 0, // 左下 // 1f, 0, // 右下 // 1f, 1f, // 右上 // 0, 0, // 左下 // 1f, 1f, // 右上 // 0, 1f, // 左上 //8路站着(对角线-45°) 0, 1f, // 左上 1f, 1f, // 右上 1f, 0, // 右下 0, 1f, // 左上 1f, 0, // 右下 0, 0, // 左下 //8路倒着(对角线-45°) // 1f, 0, // 右下 // 0, 0, // 左下 // 0, 1f, // 左上 // 1f, 0, // 右下 // 0, 1f, // 左上 // 1f, 1f, // 右上 }; public static float[] VR_VERTEX_COORD = { -1, -1, 0, -1, 0, 1, -1, -1, 0, 1, -1, 1, 0, -1, 1, -1, 1, 1, 0, -1, 1, 1, 0, 1, }; public static float[] VR_TEXTURE_COORD = { 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, }; //构造函数 public PESquare() { mVertexBuffer = ByteBuffer.allocateDirect(VERTEX.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer() .put(VERTEX); mVertexBuffer.position(0); mVertexBuffer5 = ByteBuffer.allocateDirect(VERTEX_5.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer() .put(VERTEX_5); mVertexBuffer5.position(0); mVertexBuffer8 = ByteBuffer.allocateDirect(VERTEX_8.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer() .put(VERTEX_8); mVertexBuffer8.position(0); mTextureBuffer = ByteBuffer.allocateDirect(TEX_VERTEX.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer() .put(TEX_VERTEX); mTextureBuffer.position(0); mTextureFlipBuffer5 = ByteBuffer.allocateDirect(TEX_VERTEX_FLIP_5.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer() .put(TEX_VERTEX_FLIP_5); mTextureFlipBuffer5.position(0); mTextureFlipBuffer8 = ByteBuffer.allocateDirect(TEX_VERTEX_FLIP_8.length * 4) .order(ByteOrder.nativeOrder()) .asFloatBuffer() .put(TEX_VERTEX_FLIP_8); mTextureFlipBuffer8.position(0); } } <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/PEFrameBuffer.java package panoeye.pelibrary; import android.util.Log; import java.nio.ByteBuffer; /** * Created by tir on 2016/12/14. * 帧数据缓存类 */ public class PEFrameBuffer { private static final String TAG = "PEFrameBuffer"; Integer cid;//镜头id private LockWrap<ByteBuffer> _imgBuffer = new LockWrap<>(ByteBuffer.allocate(0)) ;//图像缓存 public Size size;//主码流尺寸 Integer bufferSize = 0;//一帧画面的缓存大小 public boolean isNeedReload = false;//标志是否有解码好的数据 //设置ByteBuffer类对象 public void set(ByteBuffer byteBuffer){ _imgBuffer.set(byteBuffer);//将byteBuffer设置为_imgBuffer的内容 } //获取ByteBuffer类对象 ByteBuffer get(){ return _imgBuffer.get();//通过_imgBuffer获取到byteBuffer } boolean tryLock(){ return _imgBuffer.tryLock(); } //ByteBuffer类对象上锁 void lock(){ _imgBuffer.lock(); } //ByteBuffer类对象解锁 void unlock(){ _imgBuffer.unlock(); } PEFrameBuffer(int cameraId,Size size){ this.cid = cameraId; bufferSize = size.width*size.height*3;//3686400=1280*960*3 this.size = size; Log.d(TAG, "PEFrameBuffer1: cid:"+cid); Log.d(TAG, "PEFrameBuffer1: width:"+size.width+",height:"+size.height); } //构造函数 public PEFrameBuffer(PECameraConfig config){ this.cid = config.cid; bufferSize = config.fullSize.height*config.fullSize.width*3;//获取一帧画面的缓存大小//9437184=2048*1536*3 this.size = config.fullSize; Log.d(TAG, "PEFrameBuffer2: cid:"+cid+",bufferSize"+bufferSize); Log.d(TAG, "PEFrameBuffer2: size:"+size.width+","+size.height); } } <file_sep>/app/src/main/cpp/native-lib.cpp #include <jni.h> #include <string> #include <android/log.h> extern "C"{ //编码 #include "libavcodec/avcodec.h" //封装格式处理 #include "libavformat/avformat.h" //像素处理 #include "libswscale/swscale.h" //#include "xrapi/XrApi.h" }; #define FFLOGI(FORMAT,...) __android_log_print(ANDROID_LOG_INFO,"ffmpeg",FORMAT,##__VA_ARGS__); #define FFLOGE(FORMAT,...) __android_log_print(ANDROID_LOG_ERROR,"ffmpeg",FORMAT,##__VA_ARGS__); typedef struct ffmpeg{ AVPacket *packet; //包 AVFormatContext *pFormatCtx;//格式上下文 AVCodecContext *pCodecCtx; //编解码上下文 int width; //帧宽度 int height ; //帧高度 int frame_count; //帧数量 // bool isUsed; //使用标志 const char *input; //输入 int v_stream_idx; //流的类型 }ffmpegClient,*LpFfmpeg; //int cameraCount = 0; LpFfmpeg FFC[8]; extern "C" JNIEXPORT jstring JNICALL Java_com_panoeye_peplayer_PlayOnline_stringFromJNI( JNIEnv *env, jobject /* this */) { std::string hello = "Hello from C++"; return env->NewStringUTF(hello.c_str()); // char info[10000] = { 0 }; // avcodec_register_all(); // sprintf(info, "%s\n", avcodec_configuration()); // return env->NewStringUTF(info); } //extern "C" //JNIEXPORT jint JNICALL //Java_com_panoeye_peplayer_OnlinePlayActivity_XrInit( // JNIEnv *env, jobject thiz) { // FFLOGI("%s","xrapiSensorInit"); // xrapiSensorInit(); // // return 1; //} void QuaternionToEulerAngles(double qw, double qx, double qy, double qz , double&roll,double&yaw,double&pitch) { roll = atan2f(2.f * (qw*qz + qx*qy), 1-2*(qz*qz+qx*qx)); //Z yaw = asinf(2.f * (qw*qx - qy*qz)); //Y pitch =atan2f(2.f * (qw*qy + qz*qx), 1-2*(qy*qy+qx*qx));//X } // //extern "C" //JNIEXPORT jdoubleArray JNICALL //Java_com_panoeye_peplayer_OnlinePlayActivity_GetData( // JNIEnv *env, jobject thiz) { // // xrTracking tt = xrapiGetPredictedTrackingForServer(nullptr,-1); // // double roll, yaw, pitch; // QuaternionToEulerAngles(tt.HeadPose.Pose.Orientation.w,tt.HeadPose.Pose.Orientation.x, // tt.HeadPose.Pose.Orientation.y,tt.HeadPose.Pose.Orientation.z, // roll, yaw, pitch); // jdoubleArray data= (*env).NewDoubleArray(10); // jdouble tmp[3]; // tmp[0] = yaw; // tmp[1] = pitch; // tmp[2] = roll; // (*env).SetDoubleArrayRegion(data,0,3,tmp); // // return data; //} extern "C" JNIEXPORT jint JNICALL Java_com_panoeye_peplayer_ConnectPage_Init( JNIEnv *env, jobject, /* this */ jint cCount) { //1.注册所有组件 av_register_all(); avformat_network_init(); for (int i = 0; i < cCount; i++) { // cameraCount = cCount; FFC[i] = new ffmpegClient; FFC[i]->packet = (AVPacket*)av_malloc(sizeof(AVPacket)); FFC[i]->pFormatCtx = avformat_alloc_context(); FFC[i]->frame_count =0; // FFC[i]->isUsed = false; FFC[i]->input = NULL; FFC[i]->v_stream_idx = -1; } return 0; } extern "C" JNIEXPORT jint JNICALL Java_com_panoeye_peplayer_peonline_ConnectManager_RTSPConnect( JNIEnv *env, jclass type, jstring input_, jint handle) { //获取输入输出文件名 FFC[handle]->input = env->GetStringUTFChars(input_, 0); FFLOGE("%s","正在连接"); //2.打开输入视频文件 if (avformat_open_input(&FFC[handle]->pFormatCtx, FFC[handle]->input, NULL, NULL) != 0) { FFLOGE("%s","无法打开输入视频文件"); return -1; }FFLOGI("%s","成功打开输入视频文件"); //3.获取视频文件信息 int ret = avformat_find_stream_info(FFC[handle]->pFormatCtx,NULL); FFLOGE("avformat_find_stream_info()返回值为:%d",ret); if (ret < 0) { FFLOGE("%s","无法获取视频文件信息"); return -2; }FFLOGI("%s","成功获取视频文件信息"); //获取视频流的索引位置 //遍历所有类型的流(音频流、视频流、字幕流),找到视频流 int i = 0; //number of streams for (; i < FFC[handle]->pFormatCtx->nb_streams; i++) { //流的类型 if (FFC[handle]->pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { FFC[handle]->v_stream_idx = i; break; } } if (FFC[handle]->v_stream_idx == -1) { FFLOGE("%s","找不到视频流\n"); return -3; }FFLOGI("%s","成功找到视频流"); //只有知道视频的编码方式,才能够根据编码方式去找到解码器 //获取视频流中的编解码上下文 FFC[handle]->pCodecCtx = FFC[handle]->pFormatCtx->streams[FFC[handle]->v_stream_idx]->codec; // //4.根据编解码上下文中的编码id查找对应的解码 // AVCodec *pCodec = avcodec_find_decoder(FFC[handle]->pCodecCtx->codec_id); // if (pCodec == NULL) // { // FFLOGE("%s","找不到解码器\n"); // return -1; // }FFLOGI("%s","成功找到解码器"); // // //5.打开解码器 // if (avcodec_open2(FFC[handle]->pCodecCtx,pCodec,NULL)<0) // { // FFLOGE("%s","解码器无法打开\n"); // return -1; // }FFLOGI("%s","成功打开解码器"); //输出视频信息 FFLOGI("handle:%d",handle); FFLOGI("视频的文件格式:%s",FFC[handle]->pFormatCtx->iformat->name); FFLOGI("视频时长:%l", (FFC[handle]->pFormatCtx->duration)/1000000); FFLOGI("视频的宽高:%d,%d",FFC[handle]->pCodecCtx->width,FFC[handle]->pCodecCtx->height); // FFLOGI("解码器的名称:%s",pCodec->name); FFC[handle]->width = FFC[handle]->pCodecCtx->width; FFC[handle]->height = FFC[handle]->pCodecCtx->height; FFLOGI("连接成功:第%d路相机\n",handle); env->ReleaseStringUTFChars(input_, FFC[handle]->input); return 0; } extern "C" JNIEXPORT jint JNICALL Java_com_panoeye_peplayer_peonline_ConnectManager_getWidth( JNIEnv *env, jobject /* this */,jint handle) { return FFC[handle]->width; } extern "C" JNIEXPORT jint JNICALL Java_com_panoeye_peplayer_peonline_ConnectManager_getHeight( JNIEnv *env, jobject /* this */,jint handle) { return FFC[handle]->height; } extern "C" JNIEXPORT jobject JNICALL Java_com_panoeye_peplayer_peonline_ConnectManager_getPacket( JNIEnv *env, jobject /* this */,jint handle) { //6.一帧一帧的读取压缩数据 if (av_read_frame(FFC[handle]->pFormatCtx,FFC[handle]-> packet) >= 0) { if (FFC[handle]-> packet->stream_index == FFC[handle]->v_stream_idx){ FFC[handle]->frame_count++; FFLOGI("获取模组:%d的第%d帧,size:%d\n",handle,FFC[handle]->frame_count, FFC[handle]->packet->size); //FFLOGI("获取AVPacket结构体的成员data的pointer(地址):%p\n",FFC[handle]->packet->data); return env->NewDirectByteBuffer(FFC[handle]->packet->data,FFC[handle]->packet->size); }else{ FFLOGE("%d:不是视频数据\n",handle); } } return NULL; } extern "C" JNIEXPORT void JNICALL Java_com_panoeye_peplayer_peonline_ConnectManager_clearPacket( JNIEnv *env, jobject /* this */,jint handle) { //释放资源 av_free_packet(FFC[handle]->packet); } extern "C" JNIEXPORT void JNICALL Java_com_panoeye_peplayer_peonline_ConnectManager_clear( JNIEnv *env, jobject /* this */,jint handle) { //释放资源 avformat_close_input(&FFC[handle]->pFormatCtx); avcodec_close(FFC[handle]->pCodecCtx); av_free_packet(FFC[handle]->packet); } extern "C" JNIEXPORT void JNICALL Java_com_panoeye_peplayer_peonline_ConnectManager_closeRTSP( JNIEnv *env, jobject /* this */,jint handle) { //释放资源 avformat_close_input(&FFC[handle]->pFormatCtx); avcodec_close(FFC[handle]->pCodecCtx); } <file_sep>/app/src/main/cpp/OnlineSDK/PanoDef.h #ifndef _PANO_DEF_H_ #define _PANO_DEF_H_ #include <limits.h> #include "type.h" #ifdef WIN32 #ifndef WINVER // Specifies that the minimum required platform is Windows Vista. #define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows. #endif #ifndef WINVER #define _WIN32_WINNT _WIN32_WINNT_MAXVER #endif #endif //#define USE_ENG_UI #ifndef USE_ENG_UI #define USE_CHN_UI #endif //for SDK export //#define PANOEYE_SDK #define USE_OCULUS #ifndef PANOEYE_SDK //define if using H3C camera��������� //#define USE_H3C_CAM #ifdef USE_H3C_CAM //#define USE_H3C_IPC_OLD #define USE_H3C_IPC_NEW #endif //���������������/ 2013/11/28 songkk #define USE_HK_CAM #ifdef USE_HK_CAM #define USE_SR_CAM // ������� #define USE_CY_CAM // ������� #endif //#define USE_KD_CAM //#define USE_HT_DECODE //�󻪸����������/ 2013/11/28 songkk #define USE_DH_CAM //�ǰ������������/ 2014/4/23 jianglj #define USE_YA_CAM #ifdef USE_YA_CAM //#define USE_YA_CAM_INTERFACE #endif #endif //define if Box projection #define USE_BOX_PROJECTION #define PANO_MAX_CHANNEL_NUM 8 #define PANO_MAX_NET_IMG_NUM 100 #define PANO_CLIENT_PROC_NUM 4 #define PANO_CLIENT_CNUM_PER_PROC 8 #define PANO_SERVER_PROC_NUM 1 #define PANO_SERVER_CNUM_PER_PROC 32 //#define PANO_LINK_PROC_NUM 3 //#define PANO_LINK_CNUM_PER_PROC 10 #define RestartTimeGap 1.5 //////////////////////////////////// #define CIF_ROW 288 #define CIF_COL 352 #define D1_ROW 576 #define D1_COL 704 #define QCIF_ROW 144 #define QCIF_COL 176 #define QVGA_ROW 240 #define QVGA_COL 320 //#define COLOR_GAIN_ROW 288 //240 //#define COLOR_GAIN_COL 352 //320 #define COLOR_GAIN_ROW 240 //240 #define COLOR_GAIN_COL 320 //320 #define STD_Radius 450.0f //for Sphere radius #define ZipBinfileSize (5*1024*1024) /////////////////////////////////////////////////////// enum Disp_List { List_None, //0 List_Inited, //1 List_ReInit, //2 }; enum Display_Mode { Cam360_PTZ, //0 Cam360_Plane, //1 Cam360_Cylinder, //2 Cam360_Origin, //3 Cam360_Fusion, //4 }; enum Cam360_Resolution { Cam360_D1, //0 Cam360_CIF, //1 }; enum RecordMode { Record_D1, //0 Record_CIF, //1 Record_DVR //2 }; enum System_Modes { Sys_None, Sys_Image, Sys_Net_Data, }; enum Replay_Types { Replay_None, Replay_PES, Replay_AVI, Replay_PER, }; enum Net_Modes { Net_No_Connect, Net_Connecting, Net_Connected, }; enum Sensor_Model { PS_XM =0, // ���� PS_TST =1, // ����ͨ PS_H3C =2, // ���� PS_HK =3, // ����������� PS_DH =4, // ����� PS_YA =5, // �ǰ���� PS_HT =6, // ��;���� PS_NXP =7, // NXP����(����ʱ��) PS_SR =8, // ������� PS_CY =9, // ������� PS_KD = 10, // �ƴ���� }; enum Stream_Format { PS_MAIN, PS_EXTRA, }; enum PE_Model { PE_A=0, //0: 4-ch, ���壺A0: 1280x960; A1:2048x1536(3M) PE_B, //1: 8-ch, ���壺704x576; PE_C, //2: 2-ch, ���壺C0: 1280x960; PE_D, //3: 5-ch, ���壺D0: 1280x960; PE_E, //4: 8-ch, ���壺E0,E1: 1280x960; E3,E4:2048x1536(3M) PE_F, //5: 7-ch, ���壺F0: 1280x960; PE_G, //6: 3-ch, ���壺G0: 1280x960, ˮƽ; G1��1280x960,��ֱ PE_H, //7: 6-ch, ���壺H0: 1920x1280(2M, TST); H1: (3M, NXP) PE_L = 11, //11: 7-ch, ���峵�� LA��1280x720 PE_M = 12, //12: 8-ch, ���峵�أ�M0: 704-576;���峵�� MA��1280x720 PE_N, //13: 6-ch, ���峵�أ�N0: 1280x960; PE_O, //14: No use PE_P, //15: 4-ch, �������˲t����P0: 1280x960; PE_Q, //16: 6-ch, �������˲t����P0: 2048x1536; PE_R, //17: 4-ch, ��·ˮƽ��R0: 1280x720; PE_S, //17: 6-ch, 6·ˮƽ��S0: 2048x1536; PE_Z=25, //��������룺1-ch; // Z0��������Z1������ͨ��Z2������ // Z3��������Z4���󻪣�Z5:�ǰ��� // Z6:��;��Z7:������� }; enum Video_Type { VT_AVI, VT_H264, VT_PES, VT_PER, }; enum Play_Mode { Video_Play =0, //0 Video_Pause =1, //1 Video_Stop =2, //2 Video_Finish =3, //3 Video_Close =4, //4 Video_Open =5, //5 }; enum Play_DVRMode { ByName, //0 ByTime, //1 }; enum Comm_Type { CT_STREAM_ZERO_CHAN_DATA = 1, CT_STREAM_ZERO_CHAN_AUDIO_DATA = 2, CT_STREAM_ZERO_CHAN_SYS_HEAD = 3, CT_STREAM_ZERO_CHAN_TIME_SYNC = 4, CT_XMLRPC_OVER_PES_REQUEST = 5, CT_XMLRPC_OVER_PES_RESPONSE = 6, CT_SERVER_VERSION_REQ = 7, CT_SERVER_VERSION_SEND = 8, CT_EMPTY = 9, CT_FILE_TRANSLATE = 10, CT_SET_ZERO_CHAN_CFG = 11, CT_SET_CONNECT_CFG = 12, CT_GET_CONNECT_CFG = 13, CT_SET_PTZ_POS = 14, CT_GET_PTZ_POS = 15, CT_SET_PTZ_SEL_ZOOM_IN = 16, CT_STREAM_DATA = 17, CT_STREAM_AUDIO_DATA = 18, CT_STREAM_SYS_HEAD = 19, }; enum Server_State { SERVER_START, SERVER_STOP, CLIENT_START, CLIENT_STOP, }; enum PE_PTZ_MOUSE_MODE { PE_PTZ_MOUSE_STOP = -1, PE_PTZ_MOUSE_DOWN = 0, PE_PTZ_MOUSE_UP = 1, PE_PTZ_MOUSE_RIGHT = 2, PE_PTZ_MOUSE_LEFT = 3, PE_PTZ_MOUSE_ZOOM_IN = 4, PE_PTZ_MOUSE_ZOOM_OUT = 5, PE_PTZ_MOUSE_FOLLOW = 6, }; enum PE_PTZ_CMD { PE_PTZ_CMD_MOUSE = 0, PE_PTZ_CMD_BUTTON = 1, PE_PTZ_CMD_MOVE = 2, PE_PTZ_CMD_3D_MOVE = 3, PE_PTZ_CMD_STOP = 4, PE_PTZ_CMD_GET_INFO = 5, PE_PTZ_CMD_SET_SPEED = 6, PE_PTZ_IRISCLOSESTOP = 0x0101, /**< ��Ȧ��ֹͣ */ PE_PTZ_IRISCLOSE = 0x0102, /**< ��Ȧ�� */ PE_PTZ_IRISOPENSTOP = 0x0103, /**< ��Ȧ��ֹͣ */ PE_PTZ_IRISOPEN = 0x0104, /**< ��Ȧ�� */ PE_PTZ_FOCUSNEARSTOP = 0x0201, /**< ���ۼ�ֹͣ */ PE_PTZ_FOCUSNEAR = 0x0202, /**< ���ۼ� */ PE_PTZ_FOCUSFARSTOP = 0x0203, /**< Զ�ۼ� ֹͣ*/ PE_PTZ_FOCUSFAR = 0x0204, /**< Զ�ۼ� */ PE_PTZ_ZOOMTELESTOP = 0x0301, /**< ��Сֹͣ */ PE_PTZ_ZOOMTELE = 0x0302, /**< ��С */ PE_PTZ_ZOOMWIDESTOP = 0x0303, /**< �Ŵ�ֹͣ */ PE_PTZ_ZOOMWIDE = 0x0304, /**< �Ŵ� */ PE_PTZ_TILTUPSTOP = 0x0401, /**< ����ֹͣ */ PE_PTZ_TILTUP = 0x0402, /**< ���� */ PE_PTZ_TILTDOWNSTOP = 0x0403, /**< ����ֹͣ */ PE_PTZ_TILTDOWN = 0x0404, /**< ���� */ PE_PTZ_PANRIGHTSTOP = 0x0501, /**< ����ֹͣ */ PE_PTZ_PANRIGHT = 0x0502, /**< ���� */ PE_PTZ_PANLEFTSTOP = 0x0503, /**< ����ֹͣ */ PE_PTZ_PANLEFT = 0x0504, /**< ���� */ PE_PTZ_PRESAVE = 0x0601, /**< Ԥ��λ���� */ PE_PTZ_PRECALL = 0x0602, /**< Ԥ��λ���� */ PE_PTZ_PREDEL = 0x0603, /**< Ԥ��λɾ�� */ PE_PTZ_LEFTUPSTOP = 0x0701, /**< ����ֹͣ */ PE_PTZ_LEFTUP = 0x0702, /**< ���� */ PE_PTZ_LEFTDOWNSTOP = 0x0703, /**< ����ֹͣ */ PE_PTZ_LEFTDOWN = 0x0704, /**< ���� */ PE_PTZ_RIGHTUPSTOP = 0x0801, /**< ����ֹͣ */ PE_PTZ_RIGHTUP = 0x0802, /**< ���� */ PE_PTZ_RIGHTDOWNSTOP = 0x0803, /**< ����ֹͣ */ PE_PTZ_RIGHTDOWN = 0x0804, /**< ���� */ PE_PTZ_ALLSTOP = 0x0901, /**< ȫͣ������ */ PE_PTZ_BRUSHON = 0x0A01, /**< ��ˢ�� */ PE_PTZ_BRUSHOFF = 0x0A02, /**< ��ˢ�� */ PE_PTZ_LIGHTON = 0x0B01, /**< �ƿ� */ PE_PTZ_LIGHTOFF = 0x0B02, /**< �ƹ� */ PE_PTZ_INFRAREDON = 0x0C01, /**< ���⿪ */ PE_PTZ_INFRAREDOFF = 0x0C02, /**< ����� */ PE_PTZ_HEATON = 0x0D01, /**< ���ȿ� */ PE_PTZ_HEATOFF = 0x0D02, /**< ���ȹ� */ PE_PTZ_SCANCRUISE = 0x0E01, /**< ��̨����ɨè */ PE_PTZ_SCANCRUISESTOP = 0x0E02, /**< ��̨����ɨè */ PE_PTZ_TRACKCRUISE = 0x0F01, /**< ��̨�켣Ѳ�� */ PE_PTZ_TRACKCRUISESTOP = 0x0F02, /**< ��̨�켣Ѳ�� */ PE_PTZ_PRESETCRUISE = 0x1001, /**< ��̨��Ԥ��λѲ�� ���������ֲ�����̨ģ������ */ PE_PTZ_PRESETCRUISESTOP = 0x1002, /**< ��̨��Ԥ��λѲ�� ֹͣ���������ֲ�����̨ģ������ */ }; //////////////////////////////////////////////// struct PanoTri { float x[3], y[3]; //cylinder position float tx[3],ty[3]; //texture position float sx[3],sy[3],sz[3]; //sphere position }; struct PanoTriTexture { float tx[3], ty[3]; //texture position }; struct PanoBoxLine { float bx[2],by[2],bz[2]; //box position float sx[2],sy[2],sz[2]; //sphere position }; struct PanoBoxTri { //float x[3], y[3]; float tx[3],ty[3]; float bx[3],by[3],bz[3]; //box position float sx[3],sy[3],sz[3]; //sphere position unsigned char on; }; typedef unsigned long ULONG; typedef unsigned char uchar; /////////////////////////////////////////////////////////// struct PanoComm { char keyword[4]; //"PECM" UINT command; //see struct Comm_Type int pkgSize; //total packet size including data part }; void PanoComm_Init(struct PanoComm *); bool PanoComm_Check(struct PanoComm *); unsigned int PanoComm_Size(); struct PE_StreamZeroChanData { int camId; //camera id int stream_format; //stream format }; //#include <winsock2.h> //to prevent <winsock.h> in <windows.h> //#include <windows.h> #ifndef _PE_CONNECT_CFG_DEFINED typedef struct tagPE_CONNECT_CFG { BYTE byNetState; BYTE byStopConnect; BYTE byAutoConnect; BYTE bySubStreamOnly; BYTE byRes[180]; }PE_CONNECT_CFG, *LPPE_CONNECT_CFG; #define _PE_CONNECT_CFG_DEFINED #endif #ifndef _PE_PTZ_POS_CFG_DEFINED typedef struct tagPE_PTZ_POS_CFG { float fPanPos; //水平参数 float fTiltPos;//垂直参数 float fZoomPos;//变倍参数 BYTE byRes[172]; }PE_PTZ_POS_CFG, *LPPE_PTZ_POS_CFG; #define _PE_PTZ_POS_CFG_DEFINED #endif #ifndef _PE_POINT_FRAME_DEFINED typedef struct tagPE_POINT_FRAME { float xTop; //������ʼ���x���� float yTop; //����������y���� float xBottom; //����������x���� float yBottom; //����������y���� float bCounter; //���� BYTE byRes[164]; }PE_POINT_FRAME, *LPPE_POINT_FRAME; #define _PE_POINT_FRAME_DEFINED #endif #ifndef _PE_STREAM_DATA_DEFINED typedef struct tagPE_STREAM_DATA { DWORD dwSize; BYTE byPreviewID; BYTE byNID; //netimg ID BYTE byPID; //camera id BYTE byStreamFormat; //stream format INT64 llTimeStamp; FLOAT fTimeInterval; BYTE byFrameType; DWORD lImageWidth; DWORD lImageHeight; }PE_STREAM_DATA, *LPPE_STREAM_DATA; #define _PE_STREAM_DATA_DEFINED #endif #ifndef _PE_FILE_DATA_DEFINED typedef struct tagPE_FILE_DATA { DWORD dwSize; BYTE byPreviewID; DWORD dwFileSize; DWORD dwOffset; DWORD dwDataLength; }PE_FILE_DATA, *LPPE_FILE_DATA; #define _PE_FILE_DATA_DEFINED #endif //#if !defined(USING_HPSOCKET) //#define USING_HPSOCKET //#endif #endif <file_sep>/app/src/main/cpp/GLMatrix.cpp // // Created by tir on 2016/8/26. // #include "GLMatrix.h" GLMatrix::GLMatrix() { } int GLMatrix::getIndex(int row, int col) { return row * 4 + col; } void GLMatrix::mMakeVec3(float *result, float x, float y, float z) { result[0] = x; result[1] = y; result[2] = z; } void GLMatrix::mLogi(float *matrix) { LOGI("{"); LOGI("%f, %f, %f, %f", matrix[0], matrix[1], matrix[2], matrix[3]); LOGI("%f, %f, %f, %f", matrix[4], matrix[5], matrix[6], matrix[7]); LOGI("%f, %f, %f, %f", matrix[8], matrix[9], matrix[10], matrix[11]); LOGI("%f, %f, %f, %f", matrix[12], matrix[13], matrix[14], matrix[15]); LOGI("}"); } void GLMatrix::mMakeUnit(float *matrix) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i == j) { matrix[getIndex(i, j)] = 1; } else { matrix[getIndex(i, j)] = 0; } } } } void GLMatrix::mMakeEmpty(float *matrix) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { matrix[getIndex(i, j)] = 0; } } } void GLMatrix::mMakeCopy(float *result, float *source) { for (int row = 0; row < 4; row++) { for (int col = 0; col < 4; col++) { result[getIndex(row, col)] = source[getIndex(row, col)]; } } } void GLMatrix::mCalMulti(float *result, float *m1, float *m2) { mMakeEmpty(result); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { for (int k = 0; k < 4; k++) { result[getIndex(j, i)] += m1[getIndex(k, i)] * m2[getIndex(j, k)]; } } } } void GLMatrix::mTranslate(float *matrix, float * vec3) { for (int col = 0; col < 3; col ++) { matrix[getIndex(3, col)] = matrix[getIndex(0, col)] * vec3[col] + matrix[getIndex(1, col)] * vec3[col] + matrix[getIndex(2, col)] * vec3[col] + matrix[getIndex(3, col)]; } } void GLMatrix::mRotate(float *matrix, float angle, float * vec3) { float rotate[16]; float axis[3]; float temp[3]; float c = cos(angle); float s = sin(angle); for (int col = 0; col < 3; col++) { axis[col] = vec3[col]; } for (int col = 0; col < 3; col++) { temp[col] = (1 - c) * axis[col]; } rotate[getIndex(0, 0)] = c + temp[0] * axis[0]; rotate[getIndex(0, 1)] = 0 + temp[0] * axis[1] + s * axis[2]; rotate[getIndex(0, 2)] = 0 + temp[0] * axis[2] - s * axis[1]; rotate[getIndex(1, 0)] = 0 + temp[1] * axis[0] - s * axis[2]; rotate[getIndex(1, 1)] = c + temp[1] * axis[1]; rotate[getIndex(1, 2)] = 0 + temp[1] * axis[2] + s * axis[0]; rotate[getIndex(2, 0)] = 0 + temp[2] * axis[0] + s * axis[1]; rotate[getIndex(2, 1)] = 0 + temp[2] * axis[1] - s * axis[0]; rotate[getIndex(2, 2)] = c + temp[2] * axis[2]; float mCopy[16]; mMakeCopy(mCopy, matrix); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { matrix[getIndex(row, col)] = mCopy[getIndex(0, col)] * rotate[getIndex(row, 0)] + mCopy[getIndex(1, col)] * rotate[getIndex(row, 1)] + mCopy[getIndex(2, col)] * rotate[getIndex(row, 2)]; } } } void GLMatrix::mFrustum(float * matrix, float left, float right, float bottom, float top, float zNear, float zFar) { mMakeUnit(matrix); matrix[getIndex(0, 0)] = (2 * zNear) / (right - left); matrix[getIndex(1, 1)] = (2 * zNear) / (top - bottom); matrix[getIndex(2, 0)] = (right + left) / (right - left); matrix[getIndex(2, 1)] = (top + bottom) / (top - bottom); matrix[getIndex(2, 2)] = -(zFar + zNear) / (zFar - zNear); matrix[getIndex(2, 3)] = -1; matrix[getIndex(3, 2)] = -(2 * zFar * zNear) / (zFar - zNear); } <file_sep>/app/src/main/java/com/panoeye/peplayer/OnlinePlayActivity.java package com.panoeye.peplayer; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.net.TrafficStats; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.DisplayMetrics; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.Button; import android.widget.TextView; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; /** * Created by tir on 2016/10/9. */ public class OnlinePlayActivity extends AppCompatActivity implements GLSurfaceView.Renderer, SensorEventListener { final WeakReference<OnlinePlayActivity> self = new WeakReference<OnlinePlayActivity>(this); //主子码流 static final int STREAM_TYPE_MAIN = 0; static final int STREAM_TYPE_SUB = 1; static int PITCH_MAX = 175; static int PITCH_MIN = 5; static final float FOVY_MIN = 5.0f; static final float FOVY_MAX = 90.0f; static final int MODE_NORMAL = 0; static final int MODE_VR = 1; static final int MODE_EXITING = 2; static final int VIDEO_GLOBULAR = 0; static final int VIDEO_ORIGINAL = 1; boolean isFinish = false; boolean isFullScreen = false; private SensorManager sensorManager; private Sensor gyroscopeSensor; //陀螺仪 private Sensor accelerometerSensor; //加速度 private Sensor linearAccelerometerSensor; //线加速度 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_onlineplay); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setViews(); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); gyroscopeSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); linearAccelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION); hideCtrlViews(); } float angleYaw = 0, anglePitch = 0, angleRoll = 0; float angleYawVROffset = 0; float radiansYaw = 0, radiansPitch = 0; long sensorTS = 0; float speedY = 0; @Override public void onSensorChanged(SensorEvent event) { float dx = event.values[0]; float dy = event.values[1]; float dz = event.values[2]; if (mode == MODE_VR) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { float pitch = (float) Math.toDegrees(Math.atan(dx / dz)); if (pitch < 0) { pitch += 180; } pitch = Math.min(Math.max(pitch, PITCH_MIN), PITCH_MAX); float roll = (float) Math.toDegrees(Math.atan((dy - speedY) / dx)); roll = Math.min(Math.max(roll, -85), 85); //非极端俯仰和横滚下 if ((pitch != PITCH_MIN && pitch != PITCH_MAX) && (roll != -85 && roll != 85)) { //参与辅助校准 radiansPitch = (radiansPitch * 3 + (float) Math.toRadians(pitch)) / 4; //直接计算角度 angleRoll = (angleRoll * 3 + roll) / 4; } } else if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) { speedY = dy; }else if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) { if (sensorTS != 0) { double dT = (event.timestamp - sensorTS) / 1000000000.0f; float radiansYawDifference = (float)(dx * dT); float radiansPitchDifference = (float)(dy * dT); radiansYaw += radiansYawDifference; float angleXAim = (float) Math.toDegrees(radiansYaw); radiansPitch -= radiansPitchDifference; float angleYAim = (float) Math.toDegrees(radiansPitch); angleYAim = Math.min(Math.max(angleYAim, PITCH_MIN), PITCH_MAX); //滤波 angleYaw = (angleYaw * 3 + angleXAim) / 4; anglePitch = (anglePitch * 3 + angleYAim) / 4; } sensorTS = event.timestamp; } } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } @Override public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) { DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); //长的是长,短的是宽 int width = Math.max(metric.heightPixels, metric.widthPixels); int height = Math.min(metric.heightPixels, metric.widthPixels); JNIServerLib.glmInit(width, height); } @Override public void onSurfaceChanged(GL10 gl10, int i, int i1) { JNIServerLib.glmResize(i, i1); } int openglFrameRate = 0; @Override public void onDrawFrame(GL10 gl10) { if (mode == MODE_VR) { float x = angleYaw + angleYawVROffset; //陀螺仪 JNIServerLib.glmStep(x, anglePitch, angleRoll, fovy); openglFrameRate++; } else if (mode == MODE_NORMAL) { JNIServerLib.glmStep(angleYaw, anglePitch, angleRoll, fovy); openglFrameRate++; } else { gl10.glClear(GL10.GL_COLOR_BUFFER_BIT); } if (isFinish && mode != MODE_EXITING) { mode = MODE_EXITING; sensorManager.unregisterListener(self.get()); Intent intent = new Intent(self.get(), LoadingActivity.class); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); startActivity(intent); new Thread(new Runnable() { @Override public void run() { while (LoadingActivity.loadingActivity == null) ; JNIServerLib.unregistOnlinePanoCam(); mHandler.sendEmptyMessage(0); } }).start(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ back(null); } return false; } float fovy = 45.0f; float mPreviousX, mPreviousY; float mPreviousDis; boolean isDragging = false; boolean isZoomming = false; Date touchDownTime; @Override public boolean onTouchEvent(MotionEvent event) { float x = event.getX(); float y = event.getY(); switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_MOVE: if (isDragging) { float dx = (x - mPreviousX) / 10; float dy = (y - mPreviousY) / 10; if (mode == MODE_VR) { angleYawVROffset += dx; } else { angleYaw += dx; anglePitch += dy; anglePitch = Math.min(Math.max(anglePitch, PITCH_MIN), PITCH_MAX); } mPreviousX = x; mPreviousY = y; } if (isZoomming) { float distance = getDistance(event); float tScale = (float)(fovy - (Math.min(Math.max(distance / mPreviousDis, 0.6), 1.4) - 1) * 10 * 2); fovy = Math.min(Math.max(tScale, FOVY_MIN), FOVY_MAX); mPreviousDis = distance; } break; case MotionEvent.ACTION_DOWN: mPreviousX = x; mPreviousY = y; isDragging = true; touchDownTime = new Date(); break; case MotionEvent.ACTION_POINTER_DOWN: if (event.getPointerCount() == 2) { isZoomming = true; mPreviousDis = getDistance(event); } touchDownTime = null; isDragging = false; break; case MotionEvent.ACTION_UP: isDragging = false; isZoomming = false; if (touchDownTime != null) { Date nowTime = new Date(); if (nowTime.getTime() - touchDownTime.getTime() <= 100) { if (isFullScreen == true) { showCrtlViews(); } else { hideCtrlViews(); } } } break; case MotionEvent.ACTION_POINTER_UP: isDragging = false; isZoomming = false; touchDownTime = null; break; case MotionEvent.ACTION_CANCEL: isDragging = false; isZoomming = false; touchDownTime = null; break; } return true; } public void back(View btn) { new AlertDialog.Builder(this) .setTitle("退出播放") .setMessage("确定要退出播放吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { frameRateTimer.cancel(); isFinish = true; getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } }) .setNegativeButton("取消", null) .setCancelable(false) .show(); } int mode = MODE_NORMAL; public void mode(View btn) { if (videoMode == VIDEO_ORIGINAL) { new AlertDialog.Builder(this) .setTitle("提示") .setMessage("播放原始图像时VR模式不可用!") .setPositiveButton("确定", null) .setCancelable(false) .show(); return; } Log.d("SHOWVR", ""+mode); if (mode == MODE_NORMAL) { mode = MODE_VR; modeBtn.setText("正常"); angleYawVROffset = 0; angleYaw = 0; radiansYaw = 0; sensorTS = 0; sensorManager.registerListener(this, gyroscopeSensor, SensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_GAME); sensorManager.registerListener(this, linearAccelerometerSensor, SensorManager.SENSOR_DELAY_GAME); } else if (mode == MODE_VR) { mode = MODE_NORMAL; modeBtn.setText("VR"); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); sensorManager.unregisterListener(this, gyroscopeSensor); sensorManager.unregisterListener(this, accelerometerSensor); sensorManager.unregisterListener(this, linearAccelerometerSensor); angleRoll = 0; } JNIServerLib.setMode(mode); } public void flip(View btn) { if (videoMode == VIDEO_ORIGINAL) { new AlertDialog.Builder(this) .setTitle("提示") .setMessage("播放原始图像时上下翻转不可用!") .setPositiveButton("确定", null) .setCancelable(false) .show(); return; } JNIServerLib.flip(); } int streamType = STREAM_TYPE_MAIN; public void streamType(View btn) { Intent intent = new Intent(self.get(), LoadingActivity.class); startActivity(intent); new Thread(new Runnable() { @Override public void run() { while (LoadingActivity.loadingActivity == null) ; if (streamType == STREAM_TYPE_MAIN) { streamType = STREAM_TYPE_SUB; } else if (streamType == STREAM_TYPE_SUB) { streamType = STREAM_TYPE_MAIN; } if (JNIServerLib.setStreamType(streamType) == false) { mHandler.sendEmptyMessage(3); } else { mHandler.sendEmptyMessage(4); } } }).start(); } int videoMode = VIDEO_GLOBULAR; public void videoMode(View btn) { if (mode == MODE_VR) { mode(null); } if (videoMode == VIDEO_GLOBULAR) { videoMode = VIDEO_ORIGINAL; videoModeBtn.setText("全景图像"); PITCH_MAX = 90; PITCH_MIN = -90; angleYaw = 0; anglePitch = 0; angleRoll = 0; } else { videoMode = VIDEO_GLOBULAR; videoModeBtn.setText("原始图像"); PITCH_MAX = 175; PITCH_MIN = 5; angleYaw = 0; anglePitch = PITCH_MIN; angleRoll = 0; } JNIServerLib.setVideoMode(videoMode); } private void showCrtlViews() { AlphaAnimation animation = new AlphaAnimation(0.0f, 0.8f); animation.setDuration(200); animation.setFillAfter(true); animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { topView.setAlpha(0.8f); btnView.setAlpha(0.8f); videoFrameRateLabel.setAlpha(0.8f); glFrameRateLabel.setAlpha(0.8f); netLabel.setAlpha(0.8f); cpuLabel.setAlpha(0.8f); timeLabel.setAlpha(0.8f); } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } }); topView.startAnimation(animation); btnView.startAnimation(animation); videoFrameRateLabel.startAnimation(animation); glFrameRateLabel.startAnimation(animation); netLabel.startAnimation(animation); cpuLabel.startAnimation(animation); timeLabel.startAnimation(animation); findViewById(R.id.backBtn).setVisibility(View.VISIBLE); findViewById(R.id.modeBtn).setVisibility(View.VISIBLE); findViewById(R.id.flipBtn).setVisibility(View.VISIBLE); findViewById(R.id.streamTypeBtn).setVisibility(View.VISIBLE); findViewById(R.id.videoModeBtn).setVisibility(View.VISIBLE); isFullScreen = false; } private void hideCtrlViews() { AlphaAnimation animation = new AlphaAnimation(0.8f, 0.0f); animation.setDuration(200); animation.setFillAfter(true); animation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { topView.setAlpha(0.0f); btnView.setAlpha(0.0f); videoFrameRateLabel.setAlpha(0.0f); glFrameRateLabel.setAlpha(0.0f); netLabel.setAlpha(0.0f); cpuLabel.setAlpha(0.0f); timeLabel.setAlpha(0.0f); } @Override public void onAnimationRepeat(Animation animation) { } }); topView.startAnimation(animation); btnView.startAnimation(animation); videoFrameRateLabel.startAnimation(animation); glFrameRateLabel.startAnimation(animation); netLabel.startAnimation(animation); cpuLabel.startAnimation(animation); timeLabel.startAnimation(animation); findViewById(R.id.backBtn).setVisibility(View.GONE); findViewById(R.id.modeBtn).setVisibility(View.GONE); findViewById(R.id.flipBtn).setVisibility(View.GONE); findViewById(R.id.streamTypeBtn).setVisibility(View.GONE); findViewById(R.id.videoModeBtn).setVisibility(View.GONE); isFullScreen = true; } public float getDistance(MotionEvent Event) { float deltalX = Event.getX(0) - Event.getX(1); float deltalY = Event.getY(0) - Event.getY(1); return (float) Math.sqrt(deltalX * deltalX + deltalY * deltalY); } Timer frameRateTimer; GLSurfaceView mView; Button modeBtn, streamTypeBtn, videoModeBtn; View topView, btnView; TextView textView; TextView videoFrameRateLabel, glFrameRateLabel, netLabel, cpuLabel, timeLabel; private void setViews() { topView = (View) findViewById(R.id.topView); btnView = (View) findViewById(R.id.btnView); modeBtn = (Button)findViewById(R.id.modeBtn); streamTypeBtn = (Button)findViewById(R.id.streamTypeBtn); videoModeBtn = (Button)findViewById(R.id.videoModeBtn); textView = (TextView)findViewById(R.id.titleTextView); mView = (GLSurfaceView) findViewById(R.id.surfaceView); videoFrameRateLabel = (TextView) findViewById(R.id.videoFrameRateLabel); glFrameRateLabel = (TextView) findViewById(R.id.glFrameRateLabel); netLabel = (TextView) findViewById(R.id.netLabel); cpuLabel = (TextView) findViewById(R.id.cpuLabel); timeLabel = (TextView) findViewById(R.id.timeLabel); String name = (String)getIntent().getSerializableExtra("NAME"); textView.setText(name); mView.setEGLContextClientVersion(2); mView.setRenderer(this); // frameRateTimer = new Timer(); // TimerTask task = new TimerTask(){ // public void run() { // mHandler.sendEmptyMessage(2); // } // }; // frameRateTimer.schedule(task, 0, 1000); } final private Handler mHandler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 0: LoadingActivity.loadingActivity.close(); self.get().finish(); break; case 1: break; case 2://每秒刷新帧率 glFrameRateLabel.setText("OpenGL: " + String.valueOf(openglFrameRate) + " fps"); videoFrameRateLabel.setText("Videos: " + String.valueOf(JNIServerLib.getDecodeFrameRate()) + " fps"); openglFrameRate = 0; netLabel.setText("Network: " + String.valueOf(getAppNetworkSpeed()) + " kBps"); cpuLabel.setText("CPU: " + String.valueOf(((int)(getAppCpuRate() * 100)) / 100.0) + " %"); long ts = JNIServerLib.getOnlinePanoCurrentTimeStamp(); Date date = new Date(ts); SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); timeLabel.setText(sf.format(date)); break; case 3: LoadingActivity.loadingActivity.close(); new AlertDialog.Builder(self.get()) .setTitle("提示") .setMessage(JNIServerLib.getLastErrorMessage()) .setPositiveButton("确定", null) .setCancelable(false) .show(); break; case 4: LoadingActivity.loadingActivity.close(); if (streamType == STREAM_TYPE_MAIN) { streamTypeBtn.setText("子码流"); } else if (streamType == STREAM_TYPE_SUB) { streamTypeBtn.setText("主码流"); } break; case 5: mode(null); default : break; } } }; private long lastTotalRxBytes = 0; private long lastTimeStamp = 0; private int getAppNetworkSpeed() { long nowTotalRxBytes = getTotalRxBytes(); long nowTimeStamp = System.currentTimeMillis(); long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));//毫秒转换 lastTimeStamp = nowTimeStamp; lastTotalRxBytes = nowTotalRxBytes; return (int)speed; } private long getTotalRxBytes() { return TrafficStats.getUidRxBytes(getApplicationInfo().uid)==TrafficStats.UNSUPPORTED ? 0 :(TrafficStats.getTotalRxBytes()/1024);//转为KB } float lastTotalCpuTime = -1; float lastAppCpuTime = -1; public float getAppCpuRate() { float totalCpuTime = getTotalCpuTime(); float appCpuTime = getAppCpuTime(); float cpuRate; if (lastTotalCpuTime != -1 && lastAppCpuTime != -1) { cpuRate = 100 * (appCpuTime - lastAppCpuTime) / (totalCpuTime - lastTotalCpuTime); } else { cpuRate = 0; } lastTotalCpuTime = totalCpuTime; lastAppCpuTime = appCpuTime; return cpuRate; } public long getTotalCpuTime() { // 获取系统总CPU使用时间 String[] cpuInfos = null; try { BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream("/proc/stat")), 1000); String load = reader.readLine(); reader.close(); cpuInfos = load.split(" "); } catch (IOException ex) { ex.printStackTrace(); } long totalCpu = Long.parseLong(cpuInfos[2]) + Long.parseLong(cpuInfos[3]) + Long.parseLong(cpuInfos[4]) + Long.parseLong(cpuInfos[6]) + Long.parseLong(cpuInfos[5]) + Long.parseLong(cpuInfos[7]) + Long.parseLong(cpuInfos[8]); return totalCpu; } public long getAppCpuTime() { // 获取应用占用的CPU时间 String[] cpuInfos = null; try { int pid = android.os.Process.myPid(); BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream("/proc/" + pid + "/stat")), 1000); String load = reader.readLine(); reader.close(); cpuInfos = load.split(" "); } catch (IOException ex) { ex.printStackTrace(); } long appCpuTime = Long.parseLong(cpuInfos[13]) + Long.parseLong(cpuInfos[14]) + Long.parseLong(cpuInfos[15]) + Long.parseLong(cpuInfos[16]); return appCpuTime; } } <file_sep>/app/src/main/java/com/panoeye/peplayer/OnlineUserSettingActivity.java package com.panoeye.peplayer; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.TextView; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.WeakReference; /** * Created by tir on 2016/10/5. */ public class OnlineUserSettingActivity extends AppCompatActivity { private static final String TAG = "OnlineUserSetting"; final WeakReference<OnlineUserSettingActivity> self = new WeakReference<OnlineUserSettingActivity>(this); TextView usernameField, passwordField; String ip; int port; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_onlineusersetting); usernameField = findViewById(R.id.usernameField); passwordField = findViewById(R.id.passwordField); ip = (String)getIntent().getSerializableExtra("IP"); port = (int)getIntent().getSerializableExtra("PORT"); SharedPreferences sPerfs= PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); usernameField.setText(sPerfs.getString("USERNAME", "")); passwordField.setText(sPerfs.getString("PASSWORD", "")); // usernameField.setText("admin"); // passwordField.setText("<PASSWORD>"); // next(null); } public void back(View btn) { this.finish(); } public void next(View btn) { Intent intent = new Intent(self.get(), LoadingActivity.class); startActivity(intent); Thread subThread = new Thread(new Runnable() { @Override public void run() { // int c = 0; // Log.d(TAG, "run: "+LoadingActivity.loadingActivity); while (LoadingActivity.loadingActivity == null){ // c++; // Log.d(TAG, "run~线程等待次数:"+c); try { Thread.sleep(10);//等待10ms } catch (InterruptedException e) { e.printStackTrace(); } } String username = usernameField.getText().toString(); String password = <PASSWORD>Field.getText().toString(); if (JNIServerLib.registOnlinePano(ip, port, username, password) == true) { Log.i("sss","ip "+ip); Log.i("sss","port "+port); Intent intent = new Intent(self.get(), OnlineListActivity.class); SharedPreferences sPerfs= PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = sPerfs.edit(); editor.putString("USERNAME", username); editor.putString("PASSWORD", <PASSWORD>); editor.commit(); Log.d(TAG, "run: ~~~"); mHandler.sendEmptyMessage(1); startActivity(intent); } else { mHandler.sendEmptyMessage(2); } } }); subThread.start(); // Log.d(TAG, "next: "+Thread.currentThread().getName()); // Log.d(TAG, "next: "+Thread.currentThread().getPriority()); // Log.d(TAG, "next~: "+subThread.getName()); // Log.d(TAG, "next~: "+subThread.getId()); // Log.d(TAG, "next~: "+subThread.getState()); // Log.d(TAG, "next~: "+subThread.getPriority()); // Log.d(TAG, "next~: "+subThread.isAlive()); } final private Handler mHandler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 0 : break; case 1 : LoadingActivity.loadingActivity.close(); break; case 2: LoadingActivity.loadingActivity.close(); new AlertDialog.Builder(self.get()) .setTitle("错误") .setMessage(JNIServerLib.getLastErrorMessage()) .setPositiveButton("确定", null) .setCancelable(false) .show(); default : break; } } }; } <file_sep>/app/src/main/cpp/OnlineSDK/XML/XmlRpcTX2Util.cpp #include "XmlRpcTX2Util.h" #include <typeinfo> #include <iostream> #include <string> #include "XmlRpcTX2Value.h" using namespace tinyxml2; namespace XmlRpcTX2Util{ std::string generateResponse(){ tinyxml2::XMLDocument doc; XMLDeclaration* decl = doc.NewDeclaration(); doc.LinkEndChild(decl); XMLElement *method_response = doc.NewElement("methodResponse"); doc.LinkEndChild(method_response); tinyxml2::XMLElement *params = doc.NewElement("params"); method_response->LinkEndChild(params); XMLElement * param = doc.NewElement("param"); params->LinkEndChild(param); XMLElement * value = doc.NewElement("value"); param->LinkEndChild(value); return to_string(&doc); } bool generateResponse(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** params){ XMLDeclaration* decl = doc->NewDeclaration(); doc->LinkEndChild(decl); XMLElement *method_response = doc->NewElement("methodResponse"); doc->LinkEndChild(method_response); *params = doc->NewElement("params"); method_response->LinkEndChild(*params); return true; } std::string generateResponse(int fault_code, const char *fault_string){ tinyxml2::XMLDocument doc; XMLDeclaration* decl = doc.NewDeclaration(); doc.LinkEndChild(decl); XMLElement *method_response = doc.NewElement("methodResponse"); doc.LinkEndChild(method_response); XMLElement * fault = doc.NewElement("fault"); method_response->LinkEndChild(fault); XmlRpcTX2Value::XmlRpcValue fault_struct; fault_struct["faultCode"] = fault_code; fault_struct["faultString"] = fault_string; XMLElement * fault_value=nullptr; fault_struct.toXml(&doc, &fault_value); fault->LinkEndChild(fault_value); return to_string(&doc); } std::string generateRespnseHeader(const char * version, timeb *tbTime, const char * content_type, int content_length){ timeb tmp; if (!tbTime){ ftime(&tmp); } else{ memcpy(&tmp, tbTime, sizeof(timeb)); } std::string header; header += "HTTP/1.1 200 OK\r\n"; header += "Connection: Keep-Alive\r\n"; header += "Content-Length: " + std::to_string(content_length) + "\r\n"; header += "Content-Type: " + std::string(content_type) + "\r\n"; header += "Date: " + to_string(tmp) + "\r\n"; header += "Server: " + std::string(version) + "\r\n\r\n"; return header; } std::string generateRespnseHeader(const char * version, timeb *tbTime, const char * content_type, const char * hash, int content_length){ timeb tmp; if (!tbTime){ ftime(&tmp); } else{ memcpy(&tmp, tbTime, sizeof(timeb)); } std::string header; header += "HTTP/1.1 200 OK\r\n"; header += "Connection: Keep-Alive\r\n"; header += "Content-Length: " + std::to_string(content_length) + "\r\n"; header += "Content-Type: " + std::string(content_type) + "\r\n"; header += "Date: " + to_string(tmp) + "\r\n"; header += "Server: " + std::string(version) + "\r\n"; header += "Cookie: " + std::string(hash) + "\r\n\r\n"; return header; } bool readRequest(tinyxml2::XMLDocument *doc, const char* buff, size_t len){ return XML_NO_ERROR == doc->Parse(buff, len); } bool parseRequest(tinyxml2::XMLDocument *doc, std::string *method_name, tinyxml2::XMLElement ** params){ try{ XMLElement * methodCall = doc->FirstChildElement("methodCall"); typeid(*methodCall); XMLElement * methodName = methodCall->FirstChildElement("methodName"); typeid(*methodName); *method_name = methodName->FirstChild()->Value(); *params = methodName->NextSiblingElement("params"); typeid(**params); return true; } catch (std::bad_typeid){ return false; } return false; } bool parseRequest(tinyxml2::XMLDocument *doc, std::string *method_name, tinyxml2::XMLElement ** value, int *value_num){ try{ XMLElement * methodCall = doc->FirstChildElement("methodCall"); typeid(*methodCall); XMLElement * methodName = methodCall->FirstChildElement("methodName"); typeid(*methodName); *method_name = methodName->FirstChild()->Value(); tinyxml2::XMLElement *params = methodName->NextSiblingElement("params"); typeid(*params); XMLElement *param = params->FirstChildElement("param"); std::vector<XMLElement *> value_vector; while (param){ XMLElement *value_iter = param->FirstChildElement("value"); if (value_iter) value_vector.push_back(value_iter); param = param->NextSiblingElement("param"); } if (!value_num){ return false; } else if (*value_num < 0){ *value_num = value_vector.size(); return true; } else if (*value_num > (int)value_vector.size()){ *value_num = value_vector.size(); } if (value){ for (int i = 0; i < (int)value_vector.size() && i < *value_num; ++i) { value[i] = value_vector.at(i); } } return true; } catch (std::bad_typeid) { return false; } return false; } bool readRequestHeader(std::string header, int *header_size, std::string *type, int *length){ bool ret = false; auto lp = header.find("Content-Length: "); // Start of content-length value auto tp = header.find("Content-Type: "); // Start of content-type value auto bp = header.rfind("\r\n\r\n"); // Start of body if (lp == header.npos || tp == header.npos || bp == header.npos){ return false; } auto lep = header.find("\r\n", lp); std::string Content_LengthValueStr(header, lp + 16, lep - (lp + 16)); auto tep = header.find("\r\n", tp); std::string Content_TypeValueStr(header, tp + 14, tep - (tp + 14)); *header_size = bp + 4; if (Content_TypeValueStr.size() > 0){ if ("binary/h264" == Content_TypeValueStr){ *type = "H264"; ret = true; } else if ("text/xml" == Content_TypeValueStr){ *type = "xml"; ret = true; } } *length = std::stoi(Content_LengthValueStr); if (*length > 0){ ret &= true; } else{ ret &= false; } return ret; } bool readRequestHeader(std::string header, int *header_size, std::string *type, std::string * session, int *length){ bool ret = false; auto lp = header.find("Content-Length: "); // Start of content-length value auto tp = header.find("Content-Type: "); // Start of content-type value auto cp = header.find("Cookie: "); // Start of content-type value auto bp = header.rfind("\r\n\r\n"); // Start of body if (lp == header.npos || tp == header.npos || cp == header.npos || bp == header.npos){ return false; } auto lep = header.find("\r\n", lp); std::string Content_LengthValueStr(header, lp + 16, lep - (lp + 16)); auto tep = header.find("\r\n", tp); std::string Content_TypeValueStr(header, tp + 14, tep - (tp + 14)); auto cep = header.find("\r\n", cp); *session = std::string(header, cp + 8, cep - (cp + 8)); *header_size = bp + 4; if (Content_TypeValueStr.size() > 0){ if ("binary/h264" == Content_TypeValueStr){ *type = "H264"; ret = true; } else if ("text/xml" == Content_TypeValueStr){ *type = "xml"; ret = true; } } *length = std::stoi(Content_LengthValueStr); if (*length > 0){ ret &= true; } else{ ret &= false; } return ret; } bool generateRequest(tinyxml2::XMLDocument *doc, std::string method_name, tinyxml2::XMLElement ** params){ XMLDeclaration* decl = doc->NewDeclaration(); doc->LinkEndChild(decl); XMLElement * methodCall = doc->NewElement("methodCall"); doc->LinkEndChild(methodCall); XMLElement * methodName = doc->NewElement("methodName"); methodName->LinkEndChild(doc->NewText(method_name.c_str())); methodCall->LinkEndChild(methodName); *params = doc->NewElement("params"); methodCall->LinkEndChild(*params); return true; } std::string generateRequestHeader(const char * client, const char* host, const char * type, int length){ std::string header; header += "POST /RPC2 HTTP/1.1\r\n"; header += "User-Agent: " + std::string(client) + "\r\n"; header += "Host: " + std::string(host) + "\r\n"; header += "Content-Type: " + std::string(type) + "\r\n"; header += "Content-Length: " + std::to_string(length) + "\r\n\r\n"; return header; } std::string generateRequestHeader(const char * client, const char* host, const char * type, const char * hash, int length){ std::string header; header += "POST /RPC2 HTTP/1.1\r\n"; header += "User-Agent: " + std::string(client) + "\r\n"; header += "Host: " + std::string(host) + "\r\n"; header += "Content-Type: " + std::string(type) + "\r\n"; header += "Content-Length: " + std::to_string(length) + "\r\n"; header += "Cookie: " + std::string(hash) + "\r\n\r\n"; return header; } bool readResponseHeader(std::string header, int *header_size, std::string *type, int *length){ bool ret = false; auto lp = header.find("Content-Length: "); // Start of content-length value auto tp = header.find("Content-Type: "); // Start of content-type value auto bp = header.rfind("\r\n\r\n"); // Start of body if (lp == header.npos || tp == header.npos || bp == header.npos){ return false; } auto lep = header.find("\r\n", lp); std::string Content_LengthValueStr(header, lp + 16, lep - (lp + 16)); auto tep = header.find("\r\n", tp); std::string Content_TypeValueStr(header, tp + 14, tep - (tp + 14)); *header_size = bp + 4; if (Content_TypeValueStr.size() > 0){ ret = true; if ("binary/h264" == Content_TypeValueStr){ *type = "H264"; } else if ("text/xml" == Content_TypeValueStr){ *type = "xml"; } else{ auto lp = Content_TypeValueStr.find("/"); if (lp != Content_TypeValueStr.npos){ *type = std::string(Content_TypeValueStr, lp+1, Content_TypeValueStr.npos); } else{ *type = Content_TypeValueStr; } } } else{ ret = false; } *length = std::stoi(Content_LengthValueStr); if (*length > 0){ ret &= true; } else{ ret &= false; } return ret; } bool readResponseHeader(std::string header, int *header_size, std::string *type, std::string * session, int *length){ bool ret = false; auto lp = header.find("Content-Length: "); // Start of content-length value auto tp = header.find("Content-Type: "); // Start of content-type value auto cp = header.find("Cookie: "); // Start of content-type value auto bp = header.rfind("\r\n\r\n"); // Start of body if (lp == header.npos || tp == header.npos || cp == header.npos || bp == header.npos){ return false; } auto lep = header.find("\r\n", lp); std::string Content_LengthValueStr(header, lp + 16, lep - (lp + 16)); auto tep = header.find("\r\n", tp); std::string Content_TypeValueStr(header, tp + 14, tep - (tp + 14)); auto cep = header.find("\r\n", cp); *session = std::string(header, cp + 8, cep - (cp + 8)); *header_size = bp + 4; if (Content_TypeValueStr.size() > 0){ ret = true; if ("binary/h264" == Content_TypeValueStr){ *type = "H264"; } else if ("text/xml" == Content_TypeValueStr){ *type = "xml"; } else{ auto lp = Content_TypeValueStr.find("/"); if (lp != Content_TypeValueStr.npos){ *type = std::string(Content_TypeValueStr, lp + 1, Content_TypeValueStr.npos); } else{ *type = Content_TypeValueStr; } } } else{ ret = false; } *length = std::stoi(Content_LengthValueStr); if (*length > 0){ ret &= true; } else{ ret &= false; } return ret; } bool readResponse(tinyxml2::XMLDocument *doc, const char* buff, size_t len){ return XML_NO_ERROR == doc->Parse(buff, len); } bool parseResponse(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** params){ try{ XMLElement * methodResponse = doc->FirstChildElement("methodResponse"); typeid(*methodResponse); *params = methodResponse->FirstChildElement("params"); typeid(**params); return true; } catch (std::bad_typeid){ return false; } return false; } bool parseResponse(tinyxml2::XMLDocument *doc, tinyxml2::XMLElement ** value, int *value_num){ try{ XMLElement * methodResponse = doc->FirstChildElement("methodResponse"); typeid(*methodResponse); XMLElement *params = methodResponse->FirstChildElement("params"); typeid(*params); XMLElement *param = params->FirstChildElement("param"); std::vector<XMLElement *> value_vector; while (param){ XMLElement *value_iter = param->FirstChildElement("value"); if (value_iter) value_vector.push_back(value_iter); param = param->NextSiblingElement("param"); } if (!value_num){ return false; } else if (*value_num <= 0){ *value_num = value_vector.size(); return true; } else if (*value_num > (int) value_vector.size()){ *value_num = value_vector.size(); } if (value){ for (int i = 0; i < (int) value_vector.size() && i < *value_num; ++i){ value[i] = value_vector.at(i); } } return true; } catch (std::bad_typeid){ return false; } return false; } bool parseResponse(tinyxml2::XMLDocument *doc, int *fault_code, std::string *fault_string){ try{ XMLElement * methodResponse = doc->FirstChildElement("methodResponse"); typeid(*methodResponse); XMLElement * fault = methodResponse->FirstChildElement("fault"); typeid(*fault); XMLElement * fault_value = fault->FirstChildElement("value"); typeid(*fault_value); XmlRpcTX2Value::XmlRpcValue fault_struct(fault_value); *fault_code = fault_struct["faultCode"]; *fault_string = std::string(fault_struct["faultString"]); return true; } catch (std::bad_typeid){ return false; } catch (std::exception){ return false; } return false; } std::string to_string(const tinyxml2::XMLDocument *doc){ XMLPrinter printer; doc->Accept(&printer); return std::string(printer.CStr()); } std::string to_string(timeb tbTime){ struct tm *p; p=gmtime(&tbTime.time); char buf[512]; strftime(buf, 512, "%a, %d %b %Y %X GMT", p); return std::string(buf); } std::string to_string(struct tm t){ char buf[20]; sprintf(buf, "%4d%02d%02dT%02d:%02d:%02d", t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec); buf[sizeof(buf)-1] = 0; return std::string(buf); } } <file_sep>/app/src/main/cpp/PES/PESDecoder.h // // Created by tir on 2016/7/29. // #ifndef MEDIACODEC_JNIPLAYTHREAD_H #define MEDIACODEC_JNIPLAYTHREAD_H #include "../Common.h" #include "PESFile.h" #include <media\NdkMediaCodec.h> #include <media\NdkMediaExtractor.h> #include <pthread.h> class PESDecoder { enum PESDecoderStatus { ReadyToPlay, Playing, Paused, Stoped, Closed, }; public: int decoderCode; PESFile * pesFile; bool isAvailableToDisplay; uchar texData[MAX_ALPHA_IMAGE_SIZE]; PESDecoderStatus status; //只在runLoop里修改 PESDecoderStatus newStatus; pthread_cond_t cond; pthread_mutex_t condMutex; PESDecoder(); ~PESDecoder(); bool setFile(char * sample, int code, int width, int height); void run(); //条件:ReadyToPlay void runLoop(); float jumpTo(float ts); void pause(); //条件:Playing void resume(); //条件:Paused void stop(); //条件:ReadyToPlay, Playing, Paused private: pthread_t thread; AMediaCodec *decoder; AMediaCodecBufferInfo *info; int setData(uint8_t * buffer, size_t size); void step(); }; #endif //MEDIACODEC_JNIPLAYTHREAD_H <file_sep>/pelibrary/src/main/java/panoeye/pelibrary/Shader.java package panoeye.pelibrary; import android.content.Context; import android.content.res.Resources; import android.opengl.GLES20; import android.util.Log; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.InputStreamReader; /** * Created by tir on 2017/4/17. * 着色器类 * OpenGL超级宝典笔记——GLSL语言基础:https://my.oschina.net/sweetdark/blog/208024#OSC_h3_12 */ //attribute属性,使用顶点数组封装每个顶点的数据,一般用于每个顶点都不相同的变量,如顶点位置,颜色。 //uniform 顶点着色器使用的常量数据,不能被着色器修改,一般用于对所有顶点都相同的变量 //sampler 这个是可选的,特殊的uniform 表示顶点着色器使用的纹理 //mat4 4*4 浮点数矩阵 public class Shader { private static final String TAG = "Shader"; private static final String vertexShaderCode = "attribute vec4 vPosition; \n"+ "attribute vec2 a_texCoord; \n"+ "uniform mat4 glMatrix; \n"+ "varying vec2 tc; \n"+ "void main() \n"+ "{ \n"+ "gl_Position = glMatrix * vPosition; \n"+ "tc = a_texCoord; \n"+ "} \n"; private static final String fragmentShaderCode = "varying lowp vec2 tc; \n"+ "uniform int SampleType; \n"+//0 = rgb, 1 = yuv球面, 2 = yuv平面 "uniform sampler2D SamplerY; \n"+ "uniform sampler2D SamplerU; \n"+ "uniform sampler2D SamplerV; \n"+ "uniform sampler2D SamplerA; \n"+ "uniform sampler2D TurnY; \n"+ "uniform sampler2D TurnU; \n"+ "uniform sampler2D TurnV; \n"+ "void main(void) \n"+ "{ \n"+ " if (SampleType == 0) { \n"+ " gl_FragColor = vec4(texture2D(SamplerY, tc).r,\n"+ " texture2D(SamplerY, tc).g,\n"+ " texture2D(SamplerY, tc).b, 1);\n"+ " } else { \n"+ " mediump vec3 yuv; \n"+ " lowp vec3 rgb; \n"+ " yuv.x = texture2D(SamplerY, tc).r; \n"+ " yuv.y = texture2D(SamplerU, tc).r - 0.5; \n"+ " yuv.z = texture2D(SamplerV, tc).r - 0.5; \n"+ " rgb = mat3( 1, 1, 1, \n"+ " 0, -0.39465, 2.03211, \n"+ " 1.13983, -0.58060, 0 ) * yuv; \n"+ // " rgb = mat3( 1, 0, 1.13983,\n"+ // " 1, -0.39465, -0.58060,\n"+ // " 1, 2.03211, 0 ) * yuv; \n"+ " if (SampleType == 1) { \n"+ " gl_FragColor = vec4(rgb, texture2D(SamplerA, tc).r);\n"+ // "gl_FragColor = vec4(0.0,1.0,0.0,1.0);\n"+ " } else { \n"+ " gl_FragColor = vec4(rgb, 1); \n"+ // "gl_FragColor = vec4(0.0,1.0,0.0,1);\n"+ " } \n"+ " } \n"+ "} \n"; private static final String YUV420toRGB444JustGainFSPCode = "varying lowp vec2 tc; \n"+ "uniform int SampleType; \n"+//0 = rgb, 1 = yuv球面, 2 = yuv平面 // "uniform sampler2D SamplerY; \n"+ // "uniform sampler2D SamplerU; \n"+ // "uniform sampler2D SamplerV; \n"+ "uniform sampler2D SamplerA; \n"+ "uniform sampler2D TurnY; \n"+ "uniform sampler2D TurnU; \n"+ "uniform sampler2D TurnV; \n"+ "void main(void) \n"+ "{ \n"+ // " if (SampleType == 0) { \n"+ // " gl_FragColor = vec4(texture2D(SamplerY, tc).r,\n"+ // " texture2D(SamplerY, tc).g,\n"+ // " texture2D(SamplerY, tc).b, 1);\n"+ // " } else { \n"+ " mediump vec3 yuv; \n"+ " lowp vec3 rgb; \n"+ " vec4 gain_Y = texture2D(TurnY,tc); \n"+ " vec4 gain_U = texture2D(TurnU,tc); \n"+ " vec4 gain_V = texture2D(TurnV,tc); \n"+ " yuv.x = (gain_Y.r); \n"+ " yuv.y = (gain_U.r-0.5); \n"+ " yuv.z = (gain_V.r-0.5); \n"+ // " rgb = mat3( 1, 1, 1, \n"+ // " 0, -0.39465, 2.03211, \n"+ // " 1.13983, -0.58060, 0 ) * yuv; \n"+ " rgb.r=yuv.x +1.1403*yuv.z; \n"+ " rgb.g=yuv.x-0.3939*yuv.y-0.5808*yuv.z; \n"+ " rgb.b=yuv.x+2.0284*yuv.y; \n"+ " rgb.r = (rgb.r<0.0)?0.0:((rgb.r>1.0)?1.0:rgb.r); \n"+ " rgb.g = (rgb.g<0.0)?0.0:((rgb.g>1.0)?1.0:rgb.g); \n"+ " rgb.b = (rgb.b<0.0)?0.0:((rgb.b>1.0)?1.0:rgb.b); \n"+ // " rgb = yuv * mat3( 1, 0, 1.13983,\n"+ // " 1, -0.39465, -0.58060,\n"+ // " 1, 2.03211, 0 ); \n"+ " if (SampleType == 1) { \n"+ " gl_FragColor = vec4(rgb, texture2D(SamplerA, tc).r);\n"+ // " gl_FragColor = vec4(rgb, 1); \n"+ // "gl_FragColor = vec4(1.0,0.0,0.0,texture2D(SamplerA, tc).r);\n"+ " } else { \n"+ " gl_FragColor = vec4(rgb, 1); \n"+ // "gl_FragColor = vec4(0.0,0.0,1.0,1);\n"+ " } \n"+ // " } \n"+ "} \n"; private static final String YUV420toRGB444PlusGainFSPCode = "varying lowp vec2 tc; \n"+ "uniform int SampleType; \n"+//0 = rgb, 1 = yuv球面, 2 = yuv平面 "uniform sampler2D SamplerY; \n"+ "uniform sampler2D SamplerU; \n"+ "uniform sampler2D SamplerV; \n"+ "uniform sampler2D SamplerA; \n"+ "uniform sampler2D TurnY; \n"+ "uniform sampler2D TurnU; \n"+ "uniform sampler2D TurnV; \n"+ "void main(void) \n"+ "{ \n"+ " if (SampleType == 0) { \n"+ " gl_FragColor = vec4(texture2D(SamplerY, tc).r,\n"+ " texture2D(SamplerY, tc).g,\n"+ " texture2D(SamplerY, tc).b, 1);\n"+ " } else { \n"+ " mediump vec3 yuv; \n"+ " lowp vec3 rgb; \n"+ " vec4 gain_Y = texture2D(TurnY,tc); \n"+ " vec4 gain_U = texture2D(TurnU,tc); \n"+ " vec4 gain_V = texture2D(TurnV,tc); \n"+ " yuv.x = texture2D(SamplerY, tc).r + (gain_Y.r-0.5)*0.75; \n"+ " yuv.y = texture2D(SamplerU, tc).r - 0.5 + (gain_U.r-0.5)*0.75; \n"+ " yuv.z = texture2D(SamplerV, tc).r - 0.5 + (gain_V.r-0.5)*0.75; \n"+ // " rgb = mat3( 1, 1, 1, \n"+ // " 0, -0.39465, 2.03211, \n"+ // " 1.13983, -0.58060, 0 ) * yuv; \n"+ " rgb.r=yuv.x +1.1403*yuv.z; \n"+ " rgb.g=yuv.x-0.3939*yuv.y-0.5808*yuv.z; \n"+ " rgb.b=yuv.x+2.0284*yuv.y; \n"+ " rgb.r = (rgb.r<0.0)?0.0:((rgb.r>1.0)?1.0:rgb.r); \n"+ " rgb.g = (rgb.g<0.0)?0.0:((rgb.g>1.0)?1.0:rgb.g); \n"+ " rgb.b = (rgb.b<0.0)?0.0:((rgb.b>1.0)?1.0:rgb.b); \n"+ // " rgb = yuv * mat3( 1, 0, 1.13983,\n"+ // " 1, -0.39465, -0.58060,\n"+ // " 1, 2.03211, 0 ); \n"+ " if (SampleType == 1) { \n"+ " gl_FragColor = vec4(rgb, texture2D(SamplerA, tc).r);\n"+ // "gl_FragColor = vec4(0.0,1.0,0.0,1.0);\n"+ " } else { \n"+ " gl_FragColor = vec4(rgb, 1); \n"+ // "gl_FragColor = vec4(0.0,1.0,0.0,1);\n"+ " } \n"+ " } \n"+ "} \n"; private static final String YUV420toRGB444PlusGain_VR_FSPCode = "varying lowp vec2 tc; \n"+ "uniform int SampleType; \n"+//0 = rgb, 1 = yuv球面, 2 = yuv平面 "uniform sampler2D SamplerY,SamplerU,SamplerV,SamplerA,TurnY,TurnU,TurnV; \n"+ "void main() \n"+ "{ \n"+ " float y,u,v,r,g,b; \n"+ " vec4 colorO; \n"+ " if (SampleType == 0) { \n"+ " gl_FragColor = vec4(texture2D(SamplerY, tc).r, \n"+ " texture2D(SamplerY, tc).g, \n"+ " texture2D(SamplerY, tc).b, 1); \n"+ " } else { \n"+ " vec4 colorY = texture2D(SamplerY,tc); \n"+ " vec4 colorU = texture2D(SamplerU,tc); \n"+ " vec4 colorV = texture2D(SamplerV,tc); \n"+ " vec4 colorA = texture2D(SamplerA,tc); \n"+ " vec4 gain_Y = texture2D(TurnY,tc); \n"+ " vec4 gain_U = texture2D(TurnU,tc); \n"+ " vec4 gain_V = texture2D(TurnV,tc); \n"+ " y=colorY.r+(gain_Y.r-0.5)*0.75; \n"+ " u=colorU.r-0.5+(gain_U.r-0.5)*0.75; \n"+ " v=colorV.r-0.5+(gain_V.r-0.5)*0.75; \n"+ // " y = texture2D(SamplerY,tc).r + texture2D(TurnY,tc).r-0.5; \n"+ // " u = texture2D(SamplerU,tc).r-0.5 + texture2D(TurnU,tc).r-0.5;\n"+ // " v = texture2D(SamplerV,tc).r-0.5 + texture2D(TurnV,tc).r-0.5;\n"+ " r=y +1.1403*v; \n"+ " g=y-0.3939*u-0.5808*v; \n"+ " b=y+2.0284*u; \n"+ " colorO.r = (r<0.0)?0.0:((r>1.0)?1.0:r); \n"+ " colorO.g = (g<0.0)?0.0:((g>1.0)?1.0:g); \n"+ " colorO.b = (b<0.0)?0.0:((b>1.0)?1.0:b); \n"+ " colorO.a = texture2D(SamplerA,tc).r; \n"+ " gl_FragColor = colorO; \n"+ " } \n"+ "} \n"; //创建shader程序的方法:调用时不需传参 public static int buildProgram(){ //加载顶点着色器 int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER,vertexShaderCode); //加载片源着色器fragment int fragmentShader; if (Define.isCmbExist){ // fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER,YUV420toRGB444JustGainFSPCode); fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, YUV420toRGB444PlusGain_VR_FSPCode);//支持调色 }else { fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER,fragmentShaderCode);//不支持调色 } //创建着色器程序 int programHandle = GLES20.glCreateProgram(); //若成功 if(programHandle !=0){ //向程序中加入顶点着色器 GLES20.glAttachShader(programHandle,vertexShader); //向程序中加入片元着色器 GLES20.glAttachShader(programHandle,fragmentShader); //链接程序 GLES20.glLinkProgram(programHandle); int[] linkStatus = new int[1]; //获取program的链接情况 GLES20.glGetProgramiv(programHandle,GLES20.GL_LINK_STATUS,linkStatus,0); //若链接失败则报错并删除程序 if (linkStatus[0] != GLES20.GL_TRUE) { //GLES20.GL_TRUE == 1 Log.e("TGA","could not link program:"); Log.e("TGA",GLES20.glGetProgramInfoLog(programHandle)); GLES20.glDeleteProgram(programHandle); programHandle = 0; } } //释放资源 GLES20.glDeleteShader(vertexShader); GLES20.glDeleteShader(fragmentShader); return programHandle; } //加载自定义shader的方法 public static int loadShader(int shaderType,String shaderCode){ //shader类型,自定义管线有vertexShader和fragmentShader两种 // GLES20.GL_VERTEX_SHADER GLES20.GL_FRAGMENT_SHADER; //shader的脚本字符串,管线的处理程序,GLSL语言 //创建一个新shader int shader = GLES20.glCreateShader(shaderType); //若创建成功则加载shader if (shader!=0){ //加载shader的源代码 GLES20.glShaderSource(shader,shaderCode); //编译shader GLES20.glCompileShader(shader); //存放编译成功的shader数量的数组 int[] compiled = new int[1]; //获取shader的编译情况 GLES20.glGetShaderiv(shader,GLES20.GL_COMPILE_STATUS,compiled,0); if (compiled[0]==0){ //若编译失败则显示日志并删除shader Log.e("ES20_ERROR", "Could not compile shader: " + shaderType); Log.e("ES20_ERROR",shaderCode); Log.e("ES20_ERROR",GLES20.glGetShaderInfoLog(shader)); GLES20.glDeleteShader(shader); shader = 0; } } return shader; } //创建shader程序的方法:调用需传入参数 public static int buildProgram(String vertexSource,String fragmentSource){ //加载顶点着色器 int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER,vertexSource); if (vertexShader == 0){ return 0; } //加载片元着色器 int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER,fragmentSource); if (pixelShader == 0){ return 0; } //创建程序 int program = GLES20.glCreateProgram(); //若创建成功,则向程序中加入顶点着色器和片元着色器 if (program!=0){ //向程序中加入顶点着色器 GLES20.glAttachShader(program,vertexShader); //checkGlError("glAttachShader"); //向程序中加入片元着色器 GLES20.glAttachShader(program,pixelShader); //checkGlError("glAttachShader"); //链接程序 GLES20.glLinkProgram(program); //存放链接成功program数量的数组 int[] linkStatus = new int[1]; //获取链接情况 GLES20.glGetProgramiv(program,GLES20.GL_LINK_STATUS,linkStatus,0); if (linkStatus[0]!=GLES20.GL_TRUE){ Log.e("ES20_ERROR", "Could not link program: "); Log.e("ES20_ERROR", GLES20.glGetProgramInfoLog(program)); GLES20.glDeleteProgram(program); program = 0; } } GLES20.glDeleteShader(vertexShader); GLES20.glDeleteShader(pixelShader); return program; } public static void checkGlError(String op){ int error; while ((error = GLES20.glGetError())!=GLES20.GL_NO_ERROR){ Log.e("ES20_ERROR", op + ": glError " + error); throw new RuntimeException(op + ": glError " + error); } } //从sh脚本中加载shader内容的方法 public static String loadFromAssetsFile(String fname, Resources r){ String result = null; try{ InputStream in = r.getAssets().open(fname); int ch =0 ; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((ch = in.read())!=-1){ baos.write(ch); } byte[] buff = baos.toByteArray(); baos.close(); in.close(); result = new String(buff,"UTF-8"); result = result.replaceAll("\\r\\n","\n"); }catch (Exception e){ e.printStackTrace(); } return result; } //从安卓Resource的raw文件夹根据资源Id读取文本文件 public static String readTextFileFromResource(Context context , int resourceId){ StringBuilder body = new StringBuilder(); InputStream inputStream = null; InputStreamReader reader = null; BufferedReader bufferedReader = null; try { inputStream = context.getResources().openRawResource(resourceId); reader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(reader); String line = null; while ((line = bufferedReader.readLine()) != null){ body.append(line + "\n"); } }catch (Exception e){ Log.d(TAG, "readTextFileFromResource: read ResourceFile has error"); }finally { try { if (bufferedReader != null){ bufferedReader.close(); } if (reader != null){ reader.close(); } if (inputStream != null){ inputStream.close(); } }catch (Exception e){} } return body.toString(); } } <file_sep>/app/src/main/cpp/Common.h // // Created by tir on 2016/9/1. // #ifndef PANO_COMMON_H #define PANO_COMMON_H #include <android/log.h> #define LOG_TAG "JNI_LOG" #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) #define _FILE_OFFSET_BITS 64 #define PI 3.1415926 #define LONG int #define uchar unsigned char #define ulong unsigned LONG #define mc MainController::getInstance() #define SEEK_SET 0 //文件开头 #define SEEK_CUR 1 //当前位置 #define SEEK_END 2 //文件末尾 #define MAX_BUFFER_SIZE 128 * 1024 #define MAX_TIME_STAMP_SIZE 1 * 1024 * 1024 #define SIZE_OF_HEAD 2000 #define SIZE_OF_FRAME_HEAD 5 #define SIZE_OF_TIME_STAMP 4 #define SIZE_OF_LENGTH 4 #define MAX_CAMERA_COUNT 8 #define MIN_CAMERA_COUNT 2 #define MAX_ALPHA_IMAGE_SIZE 6 * 1024 * 1024 #define MAX_MESH_COORDINATE_COUNT 4 * 1024 #define MAX_COORDINATE_COUNT 16 * 1024 *10 #define MAX_PER_CELL_COUNT 1 *1024 * 1024 #define PANO_TYPE_NONE -1 #define PANO_TYPE_PES 0 #define PANO_TYPE_PER 1 #define PANO_TYPE_ONLINE 2 //主子码流 #define STREAM_TYPE_MAIN 0 #define STREAM_TYPE_SUB 1 #endif //PANO_COMMON_H <file_sep>/app/src/main/cpp/OnlineSDK/type.h // // Created by tir on 2016/10/7. // #ifndef PANO_TYPE_H #define PANO_TYPE_H #define BYTE unsigned char #define FLOAT float #define INT64 long long #define UINT64 unsigned long long #define DWORD unsigned int #define USHORT unsigned short #define ULONG unsigned long #define UINT unsigned int #define LPBYTE unsigned char * #define LPVOID void * #define LPDWORD unsigned int * #define CHAR char #define LONG long #define WORD short #define BOOL bool #define INT int #define TRUE true #define FALSE false #endif //PANO_TYPE_H <file_sep>/app/src/main/cpp/include/xrapi/XrApiVersion.h // // Created by SVR00003 on 2017/9/21. // #ifndef XRSDK_XRAPIVERSION_H #define XRSDK_XRAPIVERSION_H // Master version numbers #define XRAPI_PRODUCT_VERSION 1 #define XRAPI_MAJOR_VERSION 1 #define XRAPI_MINOR_VERSION 7 #define XRAPI_PATCH_VERSION 0 // Internal build identifier #define XRAPI_BUILD_VERSION 425935 // Internal build description #define XRAPI_BUILD_DESCRIPTION "Development" // Minimum version of the driver required for this API #define XRAPI_DRIVER_VERSION 66982225 #endif //XRSDK_XRAPIVERSION_H <file_sep>/app/src/main/cpp/Online/OnlineDecoder.cpp // // Created by tir on 2016/10/9. // #include "OnlineDecoder.h" #include "../MainController.h" static void runDecoderRunLoop(void *arg) { int code = *(int *)arg; mc->onlinePano->decoders[code]->runLoop(); } OnlineDecoder::OnlineDecoder() { } OnlineDecoder::~OnlineDecoder() { } void OnlineDecoder::run() { if (newStatus == ReadyToPlay) { newStatus = Playing; } pthread_create(&thread, NULL, (void * (*)(void *))&runDecoderRunLoop, (void *)&decoderCode); } bool OnlineDecoder::step() { bool result = PERDecoder::step(); if (result == true) { PERPackage * package = stepQueue.front(); mc->onlinePano->lastVideoTime = package->timestamp; } return result; } <file_sep>/app/src/main/cpp/PES/PESFile.h // // Created by tir on 2016/8/15. // #ifndef MEDIACODEC_PESFILE_H #define MEDIACODEC_PESFILE_H #include <iostream> #include <string> #include <map> #include "../Common.h" class PESFile { enum PESFileStatus { Opened, Closed, }; public: PESFileStatus status; float tsList[MAX_TIME_STAMP_SIZE]; std::map<float ,int> timestampMap; //时间戳:数据在文件中的位置 int timestampIndex; //扫描时用作数组填充,播放时用作帧数据索引 int timestampCount; PESFile(); ~PESFile(); bool openFile(char * filename); void closeFile(); int checkData(); float jumpTo(float TS); int setData(uchar * buffer, int size); private: FILE * fp; uchar * dataBuffer[MAX_BUFFER_SIZE] = {0}; bool checkFrameHead(); float readTimeStamp(); int readLength(); bool isIFrame(); bool findIFrame(); void nextFrame(); }; #endif //MEDIACODEC_PESFILE_H <file_sep>/app/src/main/cpp/PES/PESPano.cpp // // Created by tir on 2016/9/1. // #include "PESPano.h" #include "../MainController.h" static void sendSetPESTask(void ** objs) { PESPano * pano = (PESPano *)objs[0]; char * filename = (char *)objs[1]; int code = *(int *)objs[2]; int * successCountPtr = (int *)objs[3]; int * doneThreadCountPtr = (int *)objs[4]; pano->setPESTask(filename, code,doneThreadCountPtr, successCountPtr); } void PESPano::setPESTask(char *filename, int code,int * doneThreadCountPtr, int *successCountPtr) { if (setPES(filename, code) == true) { LOGI("PANO: Set pes decoder success in %s", filename); pthread_mutex_lock(&threadMutex); (*successCountPtr) = (*successCountPtr) + 1; pthread_mutex_unlock(&threadMutex); } else { LOGI("PANO: Set pes decoder failed in %s.", filename); } pthread_mutex_lock(&threadMutex); (*doneThreadCountPtr) = (*doneThreadCountPtr) + 1; pthread_mutex_unlock(&threadMutex); } PESPano::PESPano() { binFile = NULL; for (int i = 0; i < MAX_CAMERA_COUNT; i++) { decoders[i] = NULL; } decoderCount = 0; totalDuration = 0; decodeFrameRate = 0; pthread_mutex_init(&mutex,NULL); pthread_mutex_init(&threadMutex,NULL); } PESPano::~PESPano() { if (binFile != NULL) { delete binFile; } for (int i = 0; i < MAX_CAMERA_COUNT; i++) { if (decoders[i] != NULL) { delete decoders[i]; } } } bool PESPano::setPano(char * filename){ binFile = new PESBinFile(); char * tPath = "/storage/emulated/0/Pano/"; char path[64] = {0}; strcat(path, tPath); strcat(path, filename); strcat(path, "/"); char binPathFilename[128] = {0}; strcat(binPathFilename, path); strcat(binPathFilename, filename); strcat(binPathFilename, ".bin"); if (binFile->openFile(binPathFilename) == false) { LOGI("PANO: Open bin file faild in %s.", binPathFilename); return false; } LOGI("PANO: Open bin file success in %s.", binPathFilename); int camCount = binFile->camCount; if (camCount < MIN_CAMERA_COUNT && camCount > MAX_CAMERA_COUNT) { mc->setErrorMessage("不支持的视频分块数!"); LOGI("PANO: Not avaliable camera count in %d.", camCount); return false; } int codeList[MAX_CAMERA_COUNT]; //读取PES文件 char pesPathFilename[MAX_CAMERA_COUNT][128]; void * objs[MAX_CAMERA_COUNT][5]; int doneThreadCount = 0; int successCount = 0; for (int i = 0; i < camCount; i++) { int code = binFile->index[i]; char codeChar[3] = { 0 }; codeChar[0] = '0'; codeChar[1] = code + '0'; pesPathFilename[i][0] = 0; strcat(pesPathFilename[i], path); strcat(pesPathFilename[i], codeChar); strcat(pesPathFilename[i], ".pes"); objs[i][0] = this; objs[i][1] = pesPathFilename[i]; codeList[i] = code; objs[i][2] = &codeList[i]; objs[i][3] = &successCount; objs[i][4] = &doneThreadCount; } //创建线程 for (int i = 0; i <camCount; i++) { pthread_create(&thread[i], NULL, (void * (*)(void *))&sendSetPESTask, (void *)&objs[i]); } //等待回归 while (doneThreadCount < camCount) { usleep(100000); } if (successCount < camCount) { return false; } //统一时间0点,把开头的时间减掉 float maxStartTS = -1; for (int i = 0; i < camCount; i++) { int code = binFile->index[i]; PESFile * pesFile = decoders[code]->pesFile; float startTS = pesFile->tsList[0]; if (startTS > maxStartTS) { maxStartTS = startTS; } } //扫描时间戳 for (int i = 0; i < camCount; i++) { int code = binFile->index[i]; PESFile * pesFile = decoders[code]->pesFile; for (int j = 0; j < pesFile->timestampCount; j++) { int mapValue = pesFile->timestampMap[pesFile->tsList[j]]; pesFile->timestampMap.erase(pesFile->tsList[j]); pesFile->tsList[j] -= maxStartTS; pesFile->timestampMap[pesFile->tsList[j]] = mapValue; } } //找到总时间 float minTotalTS = 1.0e+10; //取个足够大的数 for (int i = 0; i < camCount; i++) { int code = binFile->index[i]; PESFile * pesFile = decoders[code]->pesFile; float totalTS = pesFile->tsList[pesFile->timestampCount - 1]; if (totalTS < minTotalTS) { minTotalTS = totalTS; } } totalDuration = minTotalTS; return true; } bool PESPano::setPES(char * filename, int code){ PESDecoder * decoder = new PESDecoder(); if (decoder->setFile(filename, code, binFile->width, binFile->height) == false) { delete decoder; decoder = NULL; return false; } else { decoders[code] = decoder; decoderCount++; return true; } } void PESPano::run(){ for (int i = 0; i < decoderCount; i++) { decoders[binFile->index[i]]->run(); } } float PESPano::jumpToTimeline() { float minTimestamp = 1e+10; for (int i = 0; i < decoderCount; i++) { int code = binFile->index[i]; float timestamp = decoders[code]->jumpTo(mc->timeline); if (timestamp < minTimestamp) { minTimestamp = timestamp; } } return minTimestamp; } void PESPano::awakeDecoders() { for (int i = 0; i < decoderCount; i++) { pthread_cond_signal(&decoders[binFile->index[i]]->cond); //唤醒解码线程 } } void PESPano::resume(){ for (int i = 0; i < decoderCount; i++) { decoders[binFile->index[i]]->resume(); } } void PESPano::pause(){ for (int i = 0; i < decoderCount; i++) { decoders[binFile->index[i]]->pause(); } } void PESPano::stop(){ for (int i = 0; i < decoderCount; i++) { decoders[binFile->index[i]]->stop(); } } bool PESPano::setStreamType(int type) { mc->setErrorMessage("PES视频中不包含子码流数据!"); return false; } void PESPano::decodeFrameRateStep() { pthread_mutex_lock(&mutex); decodeFrameRate++; pthread_mutex_unlock(&mutex); } int PESPano::getDecodeFrameRate() { pthread_mutex_lock(&mutex); int fr = (int)((float)decodeFrameRate / (float)binFile->camCount + 0.5); decodeFrameRate = 0; pthread_mutex_unlock(&mutex); return fr; }
b1645f38498dbf23a1b5e662d497e476712ab9d3
[ "CMake", "Gradle", "Java", "C", "C++", "Shell" ]
92
C++
xiaohualaila/PEPlayer
aba6a47200971e417a6aa6a9f05494665821eaa9
798ca298ce9d785ffcb0e229a3e1a5123a2efdca
refs/heads/master
<repo_name>Misjly/RestaurantMenu<file_sep>/Business layer/User.cs using System; using System.Xml.Serialization; namespace Object_2.Business_layer { [Serializable] public class User { [XmlAttribute] public string Name { get; set; } [XmlElement] public double Weight { get; set; } [XmlElement] public double Height { get; set; } [XmlElement] public int Age { get; set; } [XmlElement] public Activity DailyActivity { get; set; } public User() { } } } <file_sep>/Data access layer/Serializer.cs using Object_2.Business_layer; using System.Configuration; using System.IO; using System.Text; using System.Xml.Serialization; namespace Object_2.Data_access_layer { public class Serializer<T> where T : class { public Serializer() { } public void Serialize(T items) { using (var fs = new FileStream(ConfigurationManager.AppSettings[typeof(T).Name], FileMode.Create)) { using (var sw = new StreamWriter(fs, Encoding.UTF8)) { XmlSerializer formatter = new XmlSerializer(typeof(T)); formatter.Serialize(sw, items); } } } public T Deserialize() { using (var fs = new FileStream(ConfigurationManager.AppSettings[typeof(T).Name], FileMode.OpenOrCreate)) { using (var sr = new StreamReader(fs, Encoding.UTF8)) { XmlSerializer formatter = new XmlSerializer(typeof(T)); return (T)formatter.Deserialize(sr); } } } } } <file_sep>/Business layer/Category.cs using System; using System.Collections.Generic; using System.Xml.Serialization; namespace Object_2.Business_layer { [Serializable] public class Category { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("description")] public string Description { get; set; } [XmlElement("Product", Type = typeof(Product))] public List<Product> Products { get; set; } = new List<Product>(); public Category() { } } } <file_sep>/Presentation layer/UserForm.cs using Object_2.Business_layer; using Object_2.Data_access_layer; using System; using System.Linq; using System.Windows.Forms; namespace Object_2.Presentation_layer { public partial class UserForm : Form { private UserList _users; private string _name; public UserForm(string name) { _name = name; InitializeComponent(); Serializer<UserList> serializer = new Serializer<UserList>(); _users = serializer.Deserialize(); if (_users.Users.Select(x => x.Name).Contains(name)) { var user = _users.Users.Where(x => x.Name == name).First(); AgeBox.Value = user.Age; WeightBox.Value = (decimal)user.Weight; HeightBox.Value = (decimal)user.Height; ActivityBox.SelectedItem = user.DailyActivity.ToString(); } } private void EnterButton_Click(object sender, EventArgs e) { if(ActivityBox.SelectedItem == null) { MessageBox.Show("Select your daily activity"); return; } User user = new User { Name = _name, Age = (int)AgeBox.Value, Weight = (double)WeightBox.Value, Height = (double)HeightBox.Value, DailyActivity = (Activity)Enum.Parse(typeof(Activity), ActivityBox.SelectedItem.ToString()), }; if (!_users.Users.Select(x => x.Name).Contains(user.Name)) _users.Users.Add(user); Serializer<UserList> serializer = new Serializer<UserList>(); serializer.Serialize(_users); Hide(); ProductForm form = new ProductForm(user); form.Show(); } private void UserForm_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } } } <file_sep>/Business layer/Catalog.cs using System.Collections; using System.Collections.Generic; using System.Xml.Serialization; namespace Object_2.Business_layer { [XmlRoot("Db")] public class Catalog : IList<Category> { [XmlElement] private IList<Category> _categories { get; set; } = new List<Category>(); public int Count => _categories.Count; public bool IsReadOnly => false; public Category this[int index] { get { return _categories[index]; } set { _categories[index] = value; } } public Catalog() { } public int IndexOf(Category item) { return _categories.IndexOf(item); } public void Insert(int index, Category item) { _categories.Insert(index, item); } public void RemoveAt(int index) { _categories.RemoveAt(index); } public void Add(Category item) { _categories.Add(item); } public void Clear() { _categories.Clear(); } public bool Contains(Category item) { return _categories.Contains(item); } public void CopyTo(Category[] array, int arrayIndex) { _categories.CopyTo(array, arrayIndex); } public bool Remove(Category item) { return _categories.Remove(item); } public IEnumerator<Category> GetEnumerator() { return _categories.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <file_sep>/Presentation layer/MainForm.cs using Object_2.Presentation_layer; using System.Windows.Forms; namespace Object_2 { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private void NameButton_Click(object sender, System.EventArgs e) { if(NameBox.Text == "") { MessageBox.Show("Fill the info"); return; } Hide(); UserForm form = new UserForm(NameBox.Text); form.Show(); } } } <file_sep>/Business layer/Menu.cs using System; using System.Xml.Serialization; namespace Object_2.Business_layer { [Serializable] public class Menu { [XmlElement("Breakfast")] public Category Breakfast { get; set; } [XmlElement("Lunch")] public Category Lunch { get; set; } [XmlElement("Dinner")] public Category Dinner { get; set; } public Menu() { Breakfast = new Category(); Breakfast.Name = "Breakfast"; Lunch = new Category(); Lunch.Name = "Lunch"; Dinner = new Category(); Dinner.Name = "Dinner"; } } } <file_sep>/Presentation layer/ProductForm.cs using Object_2.Business_layer; using Object_2.Data_access_layer; using System; using System.Windows.Forms; using System.Globalization; using System.Drawing; namespace Object_2.Presentation_layer { public partial class ProductForm : Form { private Catalog _catalog; private Business_layer.Menu _menu = new Business_layer.Menu(); private NumberFormatInfo _setPrecision = new NumberFormatInfo { NumberDecimalDigits = 2, NumberDecimalSeparator = "," }; public ProductForm(User user) { InitializeComponent(); UserNameLabel.Text = user.Name; AgeInfoLabel.Text = user.Age.ToString(); WeightInfoLabel.Text = user.Weight.ToString(); HeightInfoLabel.Text = user.Height.ToString(); ActivityInfoLabel.Text = user.DailyActivity.ToString(); double ARM = 0; switch (user.DailyActivity) { case Activity.Low: { ARM = 1.2; break; } case Activity.Normal: { ARM = 1.375; break; } case Activity.Average: { ARM = 1.55; break; } case Activity.High: { ARM = 1.725; break; } } CaloriesRateInfoLabel.Text = (ARM + (447.593 + 9.247 * user.Weight + 3.098 * user.Height - 4.330 * user.Age)).ToString(); Serializer<Catalog> serializer = new Serializer<Catalog>(); _catalog = serializer.Deserialize(); CatalogListView.View = View.Details; CatalogListView.Columns.Add("Name", 250); CatalogListView.Columns.Add("Gramms", 50); CatalogListView.Columns.Add("Protein", 50); CatalogListView.Columns.Add("Fats", 50); CatalogListView.Columns.Add("Carbs", 50); CatalogListView.Columns.Add("Calories", 50); foreach (var category in _catalog) { var group = new ListViewGroup(category.Name, HorizontalAlignment.Left); foreach (var product in category.Products) { var item = new ListViewItem(product.Name, group); item.SubItems.Add(product.Gramms.ToString()); item.SubItems.Add(product.StringProtein); item.SubItems.Add(product.StringFats); item.SubItems.Add(product.StringCarbs); item.SubItems.Add(product.StringCalories); item.Tag = product; CatalogListView.Items.Add(item); } CatalogListView.Groups.Add(group); } MenuListView.View = View.Details; MenuListView.Columns.Add("Name", 250); MenuListView.Columns.Add("Gramms", 50); MenuListView.Columns.Add("Protein", 50); MenuListView.Columns.Add("Fats", 50); MenuListView.Columns.Add("Carbs", 50); MenuListView.Columns.Add("Calories", 50); ListViewGroup menuGroup = new ListViewGroup("Breakfast", HorizontalAlignment.Center); MenuListView.Groups.Add(menuGroup); var menuItem = new ListViewItem("", menuGroup); menuItem.SubItems.Add(""); menuItem.SubItems.Add(""); menuItem.SubItems.Add(""); menuItem.SubItems.Add(""); menuItem.SubItems.Add(""); MenuListView.Items.Add(menuItem); MenuListView.View = View.Details; menuGroup = new ListViewGroup("Lunch", HorizontalAlignment.Center); MenuListView.Groups.Add(menuGroup); var menuItem1 = new ListViewItem("", menuGroup); menuItem1.SubItems.Add(""); menuItem1.SubItems.Add(""); menuItem1.SubItems.Add(""); menuItem1.SubItems.Add(""); menuItem1.SubItems.Add(""); MenuListView.Items.Add(menuItem1); menuGroup = new ListViewGroup("Dinner", HorizontalAlignment.Center); MenuListView.Groups.Add(menuGroup); var menuItem2 = new ListViewItem("", menuGroup); menuItem2.SubItems.Add(""); menuItem2.SubItems.Add(""); menuItem2.SubItems.Add(""); menuItem2.SubItems.Add(""); menuItem2.SubItems.Add(""); MenuListView.Items.Add(menuItem2); } private void SaveButton_Click(object sender, EventArgs e) { Serializer<Catalog> serializer = new Serializer<Catalog>(); serializer.Serialize(_catalog); MessageBox.Show("Catalog was successfully saved"); } private void ProductForm_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void DeleteButton_Click(object sender, EventArgs e) { try { CatalogListView.Items.Remove(CatalogListView.SelectedItems[0]); } catch (Exception) { MessageBox.Show("Select item"); } } private void AddButton_Click(object sender, EventArgs e) { if (NameTextBox.Text == "" || CategoryTextBox.Text == "" || GrammsTextBox.Text == "" || ProteinTextBox.Text == "" || FatsTextBox.Text == "" || CarbsTextBox.Text == "" || CaloriesTextBox.Text == "") { MessageBox.Show("Fill the info"); return; } try { double temp = double.Parse(GrammsTextBox.Text, _setPrecision); GrammsTextBox.Text = temp.ToString("F", _setPrecision); temp = double.Parse(ProteinTextBox.Text, _setPrecision); ProteinTextBox.Text = temp.ToString("F", _setPrecision); temp = double.Parse(FatsTextBox.Text, _setPrecision); FatsTextBox.Text = temp.ToString("F", _setPrecision); temp = double.Parse(CarbsTextBox.Text, _setPrecision); CarbsTextBox.Text = temp.ToString("F", _setPrecision); int.Parse(CaloriesTextBox.Text); } catch (FormatException) { MessageBox.Show($"Info was in wrong form:{Environment.NewLine}" + $"Protein, Fats and Carbs are fractional numbers with comma{Environment.NewLine}" + "Gramms and Calories are integers"); return; } var item = new ListViewItem(NameTextBox.Text); item.SubItems.Add(GrammsTextBox.Text); item.SubItems.Add(ProteinTextBox.Text); item.SubItems.Add(FatsTextBox.Text); item.SubItems.Add(CarbsTextBox.Text); item.SubItems.Add(CaloriesTextBox.Text); bool group_exists = false; foreach (ListViewGroup group in CatalogListView.Groups) { if (group.Header == CategoryTextBox.Text) { item.Group = group; group_exists = true; break; } } if (!group_exists) { ListViewGroup group = new ListViewGroup(CategoryTextBox.Text); CatalogListView.Groups.Add(group); item.Group = group; } CatalogListView.Items.Add(item); } private void EditButton_Click(object sender, EventArgs e) { int gramms; try { gramms = int.Parse(GrammsTextBox2.Text); } catch (FormatException) { MessageBox.Show($"Info was in wrong form:{Environment.NewLine}Gramms is integer"); return; } try { if (MenuListView.SelectedItems[0].SubItems[0].Text == "") { MessageBox.Show("Select the item"); return; } } catch (Exception) { MessageBox.Show("Select the item"); return; } double oldGramms = double.Parse(MenuListView.SelectedItems[0].SubItems[1].Text, _setPrecision); double total = double.Parse(TotalInfoLabel.Text, _setPrecision); total -= ((Product)MenuListView.SelectedItems[0].Tag).Calories; double ratio = gramms / oldGramms; var product = new Product() { Name = ((Product)MenuListView.SelectedItems[0].Tag).Name, Gramms = gramms, Protein = ((Product)MenuListView.SelectedItems[0].Tag).Protein * ratio, Fats = ((Product)MenuListView.SelectedItems[0].Tag).Fats * ratio, Carbs = ((Product)MenuListView.SelectedItems[0].Tag).Carbs * ratio, Calories = ((Product)MenuListView.SelectedItems[0].Tag).Calories * ratio, }; MenuListView.SelectedItems[0].Tag = product; switch(MenuListView.SelectedItems[0].Group.Header) { case "Breakfast": { for (int i = 0; i < _menu.Breakfast.Products.Count; i++) { if (_menu.Breakfast.Products[i].Name == product.Name) { _menu.Breakfast.Products[i] = product; break; } } break; } case "Lunch": { for (int i = 0; i < _menu.Lunch.Products.Count; i++) { if (_menu.Lunch.Products[i].Name == product.Name) { _menu.Lunch.Products[i] = product; break; } } break; } case "Dinner": { for (int i = 0; i < _menu.Dinner.Products.Count; i++) { if (_menu.Dinner.Products[i].Name == product.Name) { _menu.Dinner.Products[i] = product; break; } } break; } } MenuListView.SelectedItems[0].SubItems[1].Text = gramms.ToString(); MenuListView.SelectedItems[0].SubItems[2].Text = product.StringProtein; MenuListView.SelectedItems[0].SubItems[3].Text = product.StringFats; MenuListView.SelectedItems[0].SubItems[4].Text = product.StringCarbs; MenuListView.SelectedItems[0].SubItems[5].Text = product.StringCalories; total += ((Product)MenuListView.SelectedItems[0].Tag).Calories; TotalInfoLabel.Text = total.ToString("F", _setPrecision); } private void DeleteButton2_Click(object sender, EventArgs e) { try { if (MenuListView.SelectedItems[0].SubItems[0].Text == "") { MessageBox.Show("Select the item"); return; } switch(MenuListView.SelectedItems[0].Group.Header) { case "Breakfast": { _menu.Breakfast.Products.Remove((Product)MenuListView.SelectedItems[0].Tag); break; } case "Lunch": { _menu.Lunch.Products.Remove((Product)MenuListView.SelectedItems[0].Tag); break; } case "Dinner": { _menu.Dinner.Products.Remove((Product)MenuListView.SelectedItems[0].Tag); break; } } double total = double.Parse(TotalInfoLabel.Text, _setPrecision); total -= ((Product)MenuListView.SelectedItems[0].Tag).Calories; TotalInfoLabel.Text = total.ToString("F", _setPrecision); MenuListView.SelectedItems[0].Remove(); } catch (Exception) { MessageBox.Show("Select the item"); } } private void SaveButton2_Click(object sender, EventArgs e) { Serializer<Business_layer.Menu> serializer = new Serializer<Business_layer.Menu>(); serializer.Serialize(_menu); MessageBox.Show("Menu was successfully saved"); } private void MenuButton_Click(object sender, EventArgs e) { ListViewItem item = (ListViewItem)CatalogListView.SelectedItems[0].Clone(); item.BackColor = Color.White; switch (MenuListBox.SelectedItem) { case "Breakfast": { item.Group = MenuListView.Groups[0]; break; } case "Lunch": { item.Group = MenuListView.Groups[1]; break; } case "Dinner": { item.Group = MenuListView.Groups[2]; break; } } foreach (ListViewItem lvi in MenuListView.Items) { if (lvi.Text == item.Text && item.Group == lvi.Group) return; } switch (MenuListBox.SelectedItem) { case "Breakfast": { _menu.Breakfast.Products.Add((Product)CatalogListView.SelectedItems[0].Tag); break; } case "Lunch": { _menu.Lunch.Products.Add((Product)CatalogListView.SelectedItems[0].Tag); break; } case "Dinner": { _menu.Dinner.Products.Add((Product)CatalogListView.SelectedItems[0].Tag); break; } } MenuListView.Items.Add(item); double total = double.Parse(TotalInfoLabel.Text, _setPrecision); total += ((Product)item.Tag).Calories; TotalInfoLabel.Text = total.ToString("F", _setPrecision); } private void SearchButton_Click(object sender, EventArgs e) { foreach(ListViewItem viewItem in CatalogListView.Items) { viewItem.BackColor = Color.White; } foreach (ListViewItem viewItem in CatalogListView.Items) { if (viewItem.Text.Contains(SearchTextBox.Text)) viewItem.BackColor = Color.Green; } } private void ClearButton_Click(object sender, EventArgs e) { foreach (ListViewItem viewItem in CatalogListView.Items) { viewItem.BackColor = Color.White; } } } } <file_sep>/Business layer/UserList.cs using System.Collections; using System.Collections.Generic; using System.Xml.Serialization; namespace Object_2.Business_layer { [XmlRoot("Users")] public class UserList : IList<User> { [XmlArrayItem] public IList<User> Users { get; set; } = new List<User>(); public int Count => Users.Count; public bool IsReadOnly => false; public User this[int index] { get { return Users[index]; } set { Users[index] = value; } } public UserList() { } public int IndexOf(User item) { return Users.IndexOf(item); } public void Insert(int index, User item) { Users.Insert(index, item); } public void RemoveAt(int index) { Users.RemoveAt(index); } public void Add(User item) { Users.Add(item); } public void Clear() { Users.Clear(); } public bool Contains(User item) { return Users.Contains(item); } public void CopyTo(User[] array, int arrayIndex) { Users.CopyTo(array, arrayIndex); } public bool Remove(User item) { return Users.Remove(item); } public IEnumerator<User> GetEnumerator() { return Users.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } <file_sep>/Business layer/Product.cs using System; using System.Globalization; using System.Xml.Serialization; namespace Object_2.Business_layer { [Serializable] public class Product { private NumberFormatInfo _setPrecision = new NumberFormatInfo { NumberDecimalDigits = 2, NumberDecimalSeparator = "," }; [XmlElement("Name", Type = typeof(string))] public string Name { get; set; } [XmlElement("Gramms", Type = typeof(int))] public int Gramms { get; set; } [XmlElement("Protein", Type = typeof(string))] public string StringProtein { get { return Protein.ToString("F", _setPrecision); } set { Protein = double.Parse(value, _setPrecision); } } [XmlIgnore] public double Protein { get; set; } [XmlElement("Fats", Type = typeof(string))] public string StringFats { get { return Fats.ToString("F", _setPrecision); } set { Fats = double.Parse(value, _setPrecision); } } [XmlIgnore] public double Fats { get; set; } [XmlElement("Carbs", Type = typeof(string))] public string StringCarbs { get { return Carbs.ToString("F", _setPrecision); } set { Carbs = double.Parse(value, _setPrecision); } } [XmlIgnore] public double Carbs { get; set; } [XmlElement("Calories", Type = typeof(string))] public string StringCalories { get { return Calories.ToString("F", _setPrecision); } set { Calories = double.Parse(value, _setPrecision); } } [XmlIgnore] public double Calories { get; set; } public Product() { } } } <file_sep>/Business layer/Activity.cs namespace Object_2.Business_layer { public enum Activity { Low, Normal, Average, High } }
dc2261d69b0d6ac4ce5c37ba01b82eb9fe7c1353
[ "C#" ]
11
C#
Misjly/RestaurantMenu
c4ee74a43eee25e450678cf42be6a631d4dc8628
4b28c006436454b620699d065f0f111cf6843233
refs/heads/master
<repo_name>zeqinjie/ZQLineChartView<file_sep>/ZQLineChartView/TWColor.h // // TWColor.h // ZQLineChartView // // Created by zhengzqin on 16/8/26. // Copyright © 2016年 zhengzqin. All rights reserved. // #ifndef TWColor_h #define TWColor_h #define TWColor_282828 [UIColor colorWithHexString:@"282828"] #define TWColor_f5f5f5 [UIColor colorWithHexString:@"f5f5f5"] #define TWColor_868686 [UIColor colorWithHexString:@"868686"] #define TWColor_969696 [UIColor colorWithHexString:@"969696"] #define TWColor_ff6600 [UIColor colorWithHexString:@"ff6600"] #define TWColor_0d74c6 [UIColor colorWithHexString:@"0d74c6"] #define TWColor_868686 [UIColor colorWithHexString:@"868686"] #define TWColor_eaeaea [UIColor colorWithHexString:@"eaeaea"] #define TWColor_999999 [UIColor colorWithHexString:@"999999"] #define TWColor_a6a6a6 [UIColor colorWithHexString:@"a6a6a6"] #define TWColor_efefef [UIColor colorWithHexString:@"efefef"] #define TWColor_f8f8f8 [UIColor colorWithHexString:@"f8f8f8"] #define TWColor_ffffff [UIColor colorWithHexString:@"ffffff"] #define TWColor_e5e5e5 [UIColor colorWithHexString:@"e5e5e5"] #define TWColor_e7e7e7 [UIColor colorWithHexString:@"e7e7e7"] #define TWColor_dcdcdc [UIColor colorWithHexString:@"dcdcdc"] #define TWColor_868686 [UIColor colorWithHexString:@"868686"] #define TWColor_ff8000 [UIColor colorWithHexString:@"ff8000"] #define TWColor_646464 [UIColor colorWithHexString:@"646464"] #define TWColor_04844d [UIColor colorWithHexString:@"04844d"] #define TWColor_f1f1f1 [UIColor colorWithHexString:@"f1f1f1"] #define TWColor_1f1f1f [UIColor colorWithHexString:@"1f1f1f"] #define TWColor_f74c30 [UIColor colorWithHexString:@"f74c30"] #define TWColor_ff4200 [UIColor colorWithHexString:@"ff4200"] #define TWColor_ff4000 [UIColor colorWithHexString:@"ff4000"] #define TWColor_ff0000 [UIColor colorWithHexString:@"ff0000"] //导航栏 带透明度 #define TWColor_fe8813 [UIColor colorWithHexString:@"FE8813" alpha:0.9] #define TWColor_ff8000 [UIColor colorWithHexString:@"ff8000"] #define TWColor_fe9956 [UIColor colorWithHexString:@"fe9956"] #define TWColor_29b75b [UIColor colorWithHexString:@"29b75b"] #define TWColor_c4c4c4 [UIColor colorWithHexString:@"c4c4c4"] #define TWColor_f4f4f4 [UIColor colorWithHexString:@"f4f4f4"] #define TWColor_d8d8d8 [UIColor colorWithHexString:@"d8d8d8"] #define TWColor_bbbbbb [UIColor colorWithHexString:@"bbbbbb"]// #define TWColor_ffb56c [UIColor colorWithHexString:@"ffb56c"] #define TWColor_4c4c4c [UIColor colorWithHexString:@"4c4c4c"] #define TWColor_2479d1 [UIColor colorWithHexString:@"2479d1"] #define TWColor_f2f2f2 [UIColor colorWithHexString:@"f2f2f2"] #define TWColor_2478d2 [UIColor colorWithHexString:@"2478d2"] #define TWColor_c7d0d9 [UIColor colorWithHexString:@"c7d0d9"] #define TWColor_ccd7e2 [UIColor colorWithHexString:@"ccd7e2"] #define TWColor_2c81cd [UIColor colorWithHexString:@"2c81cd"] #define TWColor_1d60af [UIColor colorWithHexString:@"1d60af"] #define TWColor_ff8b08 [UIColor colorWithHexString:@"ff8b08"] #define TWColor_e46824 [UIColor colorWithHexString:@"e46824"] #define TWColor_085ec1 [UIColor colorWithHexString:@"085ec1"] #define TWColor_ababab [UIColor colorWithHexString:@"ababab"] #define TWColor_660000 [UIColor colorWithHexString:@"660000"] #define TWColor_dbdbdb [UIColor colorWithHexString:@"dbdbdb"] #define TWColor_000000 [UIColor colorWithHexString:@"000000"] #define TWColor_666666 [UIColor colorWithHexString:@"666666"] #define TWColor_e4e4e6 [UIColor colorWithHexString:@"e4e4e6" alpha:0.9] #define TWColor_6b7072 [UIColor colorWithHexString:@"6b7072"] #define TWColor_394043 [UIColor colorWithHexString:@"394043"] #define TWColor_8b8b8b [UIColor colorWithHexString:@"8b8b8b"] #define TWColor_b1b1b1 [UIColor colorWithHexString:@"b1b1b1"] #define TWColor_8c8c8c [UIColor colorWithHexString:@"8c8c8c"] #define TWColor_ebebeb [UIColor colorWithHexString:@"ebebeb"] #define TWColor_bfbfbf [UIColor colorWithHexString:@"bfbfbf"] #define TWColor_333333 [UIColor colorWithHexString:@"333333"] #define TWColor_e0e0e0 [UIColor colorWithHexString:@"e0e0e0"] #define TWColor_888888 [UIColor colorWithHexString:@"888888"] #define TWColor_ff4400 [UIColor colorWithHexString:@"ff4400"] #define TWColor_b2b2b2 [UIColor colorWithHexString:@"b2b2b2"] #define TWColor_b3b3b3 [UIColor colorWithHexString:@"b3b3b3"] #define TWColor_2b65e7 [UIColor colorWithHexString:@"2b65e7"] #define TWColor_4990fe [UIColor colorWithHexString:@"4990fe"] #define TWColor_4d8dd9 [UIColor colorWithHexString:@"4d8dd9"] #define TWColor_58e672 [UIColor colorWithHexString:@"58e672"] #define TWColor_43c15b [UIColor colorWithHexString:@"43c15b"] #define TWColor_fb9999 [UIColor colorWithHexString:@"fb9999"] #define TWColor_f66b6b [UIColor colorWithHexString:@"f66b6b"] #define TWColor_fdb179 [UIColor colorWithHexString:@"fdb179"] #define TWColor_f0f0f0 [UIColor colorWithHexString:@"f0f0f0"] #define TWColor_ff9446 [UIColor colorWithHexString:@"ff9446"]//TWColor_d4d4d4 #define TWColor_4d4d4d [UIColor colorWithHexString:@"4d4d4d"]//f7f4cd #define TWColor_808080 [UIColor colorWithHexString:@"808080"] #define TWColor_f7f4cd [UIColor colorWithHexString:@"f7f4cd"] #define TWColor_122a44 [UIColor colorWithHexString:@"122a44" alpha:0.6] #define TWColor_333333 [UIColor colorWithHexString:@"333333"] #define TWColor_3c3c3c [UIColor colorWithHexString:@"3c3c3c"] #define TWColor_e6e6e6 [UIColor colorWithHexString:@"e6e6e6"] #define TWColor_95abc2 [UIColor colorWithHexString:@"95abc2"] #define TWColor_f2f6fa [UIColor colorWithHexString:@"f2f6fa"] #define TWColor_bfbfbf [UIColor colorWithHexString:@"bfbfbf"] #define TWColor_cccccc [UIColor colorWithHexString:@"cccccc"] #define TWColor_d9d9d9 [UIColor colorWithHexString:@"d9d9d9"] #define TWColor_e27000 [UIColor colorWithHexString:@"e27000"] #define TWColor_fff7f0 [UIColor colorWithHexString:@"fff7f0"] #define TWColor_1e66b3 [UIColor colorWithHexString:@"1e66b3"] #define TWColor_c6daf0 [UIColor colorWithHexString:@"c6daf0"] #define TWColor_fafafa [UIColor colorWithHexString:@"fafafa"] #define TWColor_ff7f00 [UIColor colorWithHexString:@"ff7f00"]//导航栏颜色 #define TWColor_f6f6f6 [UIColor colorWithHexString:@"f6f6f6"] #define TWColor_fd9228 [UIColor colorWithHexString:@"fd9228"] #define TWColor_dddddd [UIColor colorWithHexString:@"dddddd"] #define TWColor_1e61c8 [UIColor colorWithHexString:@"1e61c8"] #define TWColor_eeeeee [UIColor colorWithHexString:@"eeeeee"] #define TWColor_f1f5fa [UIColor colorWithHexString:@"f1f5fa"] #define TWColor_dce1e7 [UIColor colorWithHexString:@"dce1e7"] #define TWColor_dce8f4 [UIColor colorWithHexString:@"dce8f4"] #define TWColor_fb2f38 [UIColor colorWithHexString:@"fb2f38"]// #define TWColor_447dd8 [UIColor colorWithHexString:@"447DD8"] #define TWColor_adadad [UIColor colorWithHexString:@"adadad"] #define TWColor_e6e8eb [UIColor colorWithHexString:@"e6e8eb"] #define TWColor_616161 [UIColor colorWithHexString:@"616161"] #define TWColor_228d5a [UIColor colorWithHexString:@"228d5a"]//E99232 #define TWColor_e99232 [UIColor colorWithHexString:@"E99232"]// #define TWColor_d83a40 [UIColor colorWithHexString:@"D83A40"] #define TWColor_ff3327 [UIColor colorWithHexString:@"ff3327"] #define TWColor_339d31 [UIColor colorWithHexString:@"339d31"] #define TWColor_00b0f0 [UIColor colorWithHexString:@"00b0f0"] #define TWColor_ffc000 [UIColor colorWithHexString:@"ffc000"] #define TWColor_ed7d31 [UIColor colorWithHexString:@"ed7d31"] #define TWColor_436bff [UIColor colorWithHexString:@"436bff"] #define TWColor_1a1a1a [UIColor colorWithHexString:@"1a1a1a"] #define TWColor_4e7dff [UIColor colorWithHexString:@"4e7dff"]//藍色 #define TWColor_ff9c40 [UIColor colorWithHexString:@"ff9c40"]//橙色 #define TWColor_40c598 [UIColor colorWithHexString:@"40c598"]//綠色 #endif /* TWColor_h */ <file_sep>/README.md # ZQLineChartView # How To Use ```ruby 折线图,参考 WSLineChartView 做了修改 支持 刷新数据 自定义 多种属性 喜欢的点个星。 (*^__^*) ```
ea230655df29fc541f31a2d1ebcf9a2a5878dd79
[ "Markdown", "C" ]
2
C
zeqinjie/ZQLineChartView
ce953586181ced5137177b9bed20ee8323c5d8f3
58b4cec6f1c92b2d0a125c08161fbccbeded0f38
refs/heads/master
<file_sep>// Source : https://oj.leetcode.com/problems/two-sum/ // Author : <NAME> // Date : 2015-05-30 /********************************************************************************** * * Given an array of integers, find two numbers such that they add up to a specific target number. * * The function twoSum should return indices of the two numbers such that they add up to the target, * where index1 must be less than index2. Please note that your returned answers (both index1 and index2) * are not zero-based. * * You may assume that each input would have exactly one solution. * * Input: numbers={2, 7, 11, 15}, target=9 * Output: index1=1, index2=2 * * **********************************************************************************/ /** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { var hash = {}; var result = []; for (var i = 0, l = nums.length; i < l; ++i) { var n = nums[i]; // find the second one if (hash[n] > 0) { result.push(hash[n], i + 1); break; } else { // store the index hash[target - n] = i + 1; } } return result; }; var testCase = [2, 7, 11, 15]; var result = twoSum(testCase, 9); console.log(result.toString() === '1,2'); // true <file_sep>// Source : https://oj.leetcode.com/problems/merge-sorted-array/ // Author : <NAME> // Date : 2015-05-29 /********************************************************************************** * * Given two sorted integer arrays A and B, merge B into A as one sorted array. * * Note: * You may assume that A has enough space (size that is greater or equal to m + n) * to hold additional elements from B. The number of elements initialized in A and B * are m and n respectively. * **********************************************************************************/ /** * @param {number[]} nums1 * @param {number} m * @param {number[]} nums2 * @param {number} n * @return {void} Do not return anything, modify nums1 in-place instead. */ var merge = function(nums1, m, nums2, n) { var n1Index = 0; // Trim trailing 0s on nums1 // Runtime: 152 ms nums1.splice(m); // Runtime: 141 ms // while (m != nums1.length) { // nums1.pop(); // } for (var n2Index = 0; n2Index < n; n2Index++) { while (nums2[n2Index] > nums1[n1Index]) { n1Index++; } nums1.splice(n1Index, 0, nums2[n2Index]); } }; // Test case var m = [4, 5, 6, 0, 0, 0]; var n = [1, 2, 3]; merge(m, 3, n, 3); console.log(m.toString() === '1,2,3,4,5,6'); // true <file_sep>// Source : https://oj.leetcode.com/problems/reverse-words-in-a-string/ // Author : <NAME> // Date : 2015-06-13 /********************************************************************************** * * Given an input string, reverse the string word by word. * * For example, * Given s = "the sky is blue", * return "blue is sky the". * * * Clarification: * * What constitutes a word? * A sequence of non-space characters constitutes a word. * Could the input string contain leading or trailing spaces? * Yes. However, your reversed string should not contain leading or trailing spaces. * How about multiple spaces between two words? * Reduce them to a single space in the reversed string. * * **********************************************************************************/ /** * Manually get all words * * @param {string} str * @returns {string} */ var reverseWords = function(str) { var strArr = []; var word = ''; for (var i = str.length - 1; i >= 0; --i) { if (str[i] !== ' ') { word = str[i] + word; } else if (word) { strArr.push(word); word = ''; } } if (str[0] !== ' ') { strArr.push(word); } return strArr.join(' '); }; /** * Using Regex to get all words * * @param {string} str * @returns {string} */ var reverseWords_regex = function(str) { var strArr = str.match(/\S+/g); return strArr ? strArr.reverse().join(' ') : ''; }; // Test case console.log(reverseWords('the sky is blue') === 'blue is sky the'); // true <file_sep>// Source : https://oj.leetcode.com/problems/letter-combinations-of-a-phone-number/ // Author : <NAME> // Date : 2015-06-11 /********************************************************************************** * * Given a digit string, return all possible letter combinations that the number could represent. * * A mapping of digit to letters (just like on the telephone buttons) is given below. * * Input:Digit string "23" * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. * * Note: * Although the above answer is in lexicographical order, your answer could be in any order you want. * * **********************************************************************************/ /** * @param {string} digits * @return {string[]} */ var letterCombinations = function(digits) { return f([], digits); }; var map = { 2: ['a', 'b', 'c'], 3: ['d', 'e', 'f'], 4: ['g', 'h', 'i'], 5: ['j', 'k', 'l'], 6: ['m', 'n', 'o'], 7: ['p', 'q', 'r', 's'], 8: ['t', 'u', 'v'], 9: ['w', 'x', 'y', 'z'] }; function f(arr, digits) { if (!digits.length) { return arr; } var num = digits[0]; // first char var tmp = arr.length ? [] : map[num]; arr.forEach(function(v) { map[num].forEach(function(m) { tmp.push(v + m); }); }); return f(tmp, digits.substring(1)); } // Test case console.log(letterCombinations('23').toString() === 'ad,ae,af,bd,be,bf,cd,ce,cf'); // true
111fc51e19881b58876f31054579f75b599ba5c3
[ "JavaScript" ]
4
JavaScript
jinwyp/Leetcode
9454ceb33a61d86cce34dca81133b4abed1776f4
88bc9124b1c98ca0ae0dcb2fe7f708fe6ffb9bcc
refs/heads/master
<file_sep>#!/usr/bin/env python from pyzotero import zotero import click import ConfigParser import os import shelve APP_NAME = 'majorzoot' def read_config(): cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini') parser = ConfigParser.RawConfigParser() parser.read([cfg]) rv = {} for section in parser.sections(): for key, value in parser.items(section): rv['%s.%s' % (section, key)] = value return rv def get_items(library): config = read_config() zot = zotero.Zotero(config['%s.library_id' % library], config['%s.library_type' % library], config['%s.api_key' % library]) version = zot.last_modified_version() store = shelve.open( os.path.join(click.get_app_dir(APP_NAME), '%s.cache' % library)) if str(version) in store: return store[str(version)] else: click.echo('Refreshing cache') num_items = zot.num_items() limit = 100 all_items = [] for start in range(1, num_items, limit): if start + limit > num_items: limit = num_items - start + 1 items = zot.items(start=start, limit=limit) all_items.extend(items) store[str(version)] = all_items store.close() # TODO: clear old version? return all_items @click.group() def cli(): pass @click.command() @click.option('--library', # default to first library in config default=read_config().items()[0][0].split('.')[0], help='Name of Zotero library') def listauthors(library): click.echo('Listing authors for %s' % library) items = get_items(library) creators = [] for item in items: # not all items seem to have creators if 'creators' in item['data']: creators.extend(item['data']['creators']) author_names = {} for creator in creators: if 'name' in creator: name = creator['name'] else: name = '%s, %s' % (creator['lastName'], creator['firstName']) if name in author_names: author_names[name] += 1 else: author_names[name] = 1 click.echo_via_pager( '\n'.join(sorted(author_names.keys(), key=unicode.lower))) click.echo('Total number of authors: %s' % len(author_names.keys())) cli.add_command(listauthors) <file_sep>[userlibrary] library_id= library_type=user api_key= [grouplibrary] library_id= library_type=group api_key= <file_sep>#!/usr/bin/env python from setuptools import setup setup(name='majorzoot', version='0.1', author='<NAME>', author_email='<EMAIL>', py_modules=['repo'], include_package_data=True, install_requires=[ 'click', 'pyzotero'], entry_points=''' [console_scripts] majorzoot=majorzoot:cli ''', )
c552cdf32295a35ac1bdc693e6908052b9904693
[ "Python", "INI" ]
3
Python
majorgreys/majorzoot
21514910c2c284d36b58033feae8ec59ea52eb12
d42b216fbd34aafbbbd57cf664316f0c14572c79
refs/heads/master
<repo_name>laurazhukas/vuecalc<file_sep>/app/js/components/calculator.js import Buttons from './button.js' const Calculator= { name: 'Component', props: [], template: require('../../templates/calculator.html'), mixins: [], components: { Buttons, }, data() { return { displayNum: 0, x: 0, y: 0, switchVariable: false, operator: null, isNotNumber: false, runningSum: 0, numPrecision : 3 } }, methods : { getResult: function (x,y, operator) { switch (operator) { case 'add': return parseFloat(x) + parseFloat(y) case 'subtract': return parseFloat(x) - parseFloat(y) case 'multiply': return parseFloat(x) * parseFloat(y) case 'divide': return parseFloat(x) / parseFloat(y) default: return 'error' } }, clear() { this.x =0 this.y=0 this.switchVariable = false this.operator = null this.displayNum = 0 }, calculate() { this.x = this.getResult(this.x,this.y, this.operator) this.displayNum = this.x this.operator = null this.isNotNumber = true this.y=0 }, isOperator(value) { if (value === 'add' || value ==='subtract'|| value ==='multiply'||value ==='divide') { return true } }, updateVariables(value) { if (this.switchVariable && !this.isNotNumber) { this.y += value this.displayNum = parseFloat(this.y) } else if (!this.switchVariable && !this.isNotNumber) { this.x += value this.displayNum = parseFloat(this.x) } }, operatorButtonPressed() { this.runningSum = this.getResult(this.x,this.y,this.operator) this.x= this.runningSum this.displayNum = parseFloat(this.x) this.y=0 }, calculateNum: function (value) { this.isNotNumber = false if (value === 'clear') { this.clear() this.isNotNumber = true } if (value === 'calculate') { this.calculate() } if (this.isOperator(value)) { if (this.switchVariable) { this.operatorButtonPressed() } this.switchVariable = true this.operator = value this.isNotNumber = true } this.updateVariables(value) } }, computed: { display() { return `${this.displayNum.toPrecision(this.numPrecision)}` } }, } export default Calculator<file_sep>/app/js/components/button.js const Button= { name: 'Component', props: [], template: require('../../templates/buttons.html'), mixins: [], components: {}, data() { return { buttonName: 'v-on:calculate-num="calculateNum"', randVal : 2, value: 0, buttonArray :[ {toSend: '7', objClass: 'numberKeys', display:7}, {toSend: '8', objClass: 'numberKeys', display:8}, {toSend: '9', objClass: 'numberKeys', display:9}, {toSend: 'add', objClass: 'operator', display:'+'}, {toSend: '4', objClass: 'numberKeys', display:4}, {toSend: '5', objClass: 'numberKeys', display:5}, {toSend: '6', objClass: 'numberKeys', display:6}, {toSend: 'subtract', objClass: 'operator', display:'-'}, {toSend: '3', objClass: 'numberKeys', display:3}, {toSend: '2', objClass: 'numberKeys', display:2}, {toSend: '1', objClass: 'numberKeys', display:1}, {toSend: 'multiply', objClass: 'operator', display:'x'}, {toSend: '0', objClass: 'numberKeys', display:0}, {toSend: '.', objClass: 'numberKeys', display:'.'}, {toSend: 'calculate', objClass: 'importantOperator', display:'='}, {toSend: 'divide', objClass: 'operator', display:'÷'} ] } }, methods: { calculateNum : function (value) { console.log ('In buttons.js and value is: ' + value), this.value = value + this.randVal }, buttonClicked : function (val) { this.$emit('button-clicked', val) } }, created() { }, computed: { message() { console.log('this random value: '+ this.value) } }, } export default Button<file_sep>/app/js/index.js // External Libs import Vue from 'vue' require('bootstrapJs') // Import Styles require('!style-loader!css-loader!bootstrap/dist/css/bootstrap.min.css') require('css/main.scss') // Mixins // Components import Calculator from './components/calculator.js' // Interfaces new Vue({ name: 'Vue Typescript Boilerplate', mixins: [], el: '#vue-main', components: { Calculator, }, data() { return { name: 'Derp' } }, methods: { }, mounted() { console.log('Mounted Main') this.name = 'Bob' }, }) <file_sep>/README.md # vueCalc <file_sep>/app/js/components/display.js const Display= { name: 'Component', props: [], template: require('../../templates/display.html'), mixins: [], components: {}, data() { return { } }, created() { }, computed: { }, } export default Display
5f3b89d66f36a990c92d93a67b9d818668339477
[ "JavaScript", "Markdown" ]
5
JavaScript
laurazhukas/vuecalc
4e1f87c588d35c7d14dc214b617c5578a09b5d89
dd6e13ea9c660f50fa89631117b3baf4dacad2d2
refs/heads/master
<file_sep>// Creates a new class called Ship class Ship { // Defines all the functions and is called by using new Ship(x, y, min velocity, max velocity) constructor(x, y, minv, maxv) { // Sets the x and y position to the given position this.position = { x: x, y: y } // Defines acceleration as 0 this.acceleration = { x: 0, y: 0 } // Defines velocity as 0 this.velocity = { x: 0, y: 0 } this.protectionTime = 100; this.protection = 0; this.canShoot = true; this.shootDelay = 0; this.maxShootDelay = 6; this.thrusting = false this.size = 20 this.r = this.size / 2; this.drag = 0.95 this.rotation = 0; this.minVel = minv this.maxVel = maxv; this.speed = 2; this.multiplier = 3; } checkVelocity() { // Gets the rotation of the ship in pixels and multiplies them by 0.2 and speed (If 0.2 wasn't there it would make the ship too fast) // Lets say speed is 2, it would multiply by 2 but if you multiply 2 by 0.2 you get 0.4 which means it multiplies everything by 0.4 this.acceleration = { x: this.speed * 0.2 * Math.cos((this.rotation - 90) * (Math.PI / 180)), y: this.speed * 0.2 * Math.sin((this.rotation - 90) * (Math.PI / 180)) } // If the ship isn't trusting apply drag if (!this.thrusting) { // drag is 0.95 so if the velocity is 5 and you multiply it with 0.95 you get 4.75 this.velocity.x *= this.drag; this.velocity.y *= this.drag; } // if the velocity is higher than the max velocity just set it to max and vise versa if (this.velocity.x > this.maxVel) this.velocity.x = this.maxVel if (this.velocity.x < this.minVel) this.velocity.x = this.minVel if (this.velocity.y > this.maxVel) this.velocity.y = this.maxVel if (this.velocity.y < this.minVel) this.velocity.y = this.minVel // If the rotation is bigger than 360 set it to 0 if (this.rotation > 360) this.rotation = this.rotation - 360; // If the rotation is lower than 0 set it to 360 else if (this.rotation < 0) this.rotation = 360 + this.rotation; // Apply velocity to the position this.position.x += this.velocity.x this.position.y += this.velocity.y } shoot() { // Create the laser on the ships position // Give it the ships rotation // Make it half of the ships size aka give it the ships radius createLaser(this.position.x, this.position.y, this.r, this.rotation, this.r) // Disable the ship from shooting this.canShoot = false; } // Check keys if you need to execute a function checkKeys() { // If W is pressed if (pressedKeys.up) { // Increase velocity by acceleration this.velocity.x += this.acceleration.x; this.velocity.y += this.acceleration.y; // Set thrusting to true this.thrusting = true; } else if (pressedKeys.down) { // Else id S is pressed // decrease velocity by acceleration this.velocity.x -= this.acceleration.x; this.velocity.y -= this.acceleration.y; // Set thrusting to false this.thrusting = false; } else { // Else if none of those match // Set thrusting to false this.thrusting = false; } // If A is pressed if (pressedKeys.left) { // Decrease the rotation by speed times the multiplier this.rotation -= this.speed * this.multiplier; } else if (pressedKeys.right) { // Else if D is pressed // Increase the rotation by speed times the multiplier this.rotation += this.speed * this.multiplier; } // If space is pressed and the ship can shoot if (pressedKeys.space && (this.canShoot || game.superman)) { // Shoot this.shoot(); if (this.protected()) this.protection = this.protectionTime; } } blink() { var rem = this.protection % 20 if (rem >= 0 && rem <= 10) ctx.strokeStyle = 'black'; else ctx.strokeStyle = 'white'; } // Draw event draw() { // Sets the canvas line width devided by 5 so the lines wouldn't be too thick or too thin ctx.lineWidth = this.r / 5; // Sets the color of the stroke to white if (this.protected()) this.blink(); else ctx.strokeStyle = 'white'; // Creates particles if (this.thrusting) { var randRot = (this.rotation + Math.random() * 35 + 165) % 360 var thrustParticles = new Shapes(this.r/2).asteroid createParticle(this.position.x, this.position.y, 5, randRot, 15, 50, thrustParticles, true) } // Draw the ship on the ships coordinates and rotated drawShape(new Shapes(this.size).ship, true, this.position.x, this.position.y, 1, (Math.PI / 180) * this.rotation); } // Check if the ship can shoot shootCheck() { // If the ship can shoot then return true if (this.canShoot) return true; // If the shootDelaay is smaller than maxShootDelay if (this.shootDelay < this.maxShootDelay) { // Icrease shootDelay by 1 this.shootDelay++ } else { // Else if it's bigger than maxShootDelay // Set the shootDelay to 0 this.shootDelay = 0; // Allow the ship to shoot this.canShoot = true; } } protected(add = false) { if (this.protection < this.protectionTime) { if (add) this.protection++; return true; } return false; } deathParticles(){ for (i = 0; i < 360; i++) { if (i % 15 == 0) { createParticle(this.position.x, this.position.y, 5, i, 20, 5) } } } die() { if (!this.protected()) { this.deathParticles(); createShip(c.width / 2, c.height / 2, -10, 10) if (--lives == 0) game.lose(); return } } // Main update function for the ship update() { // Check if the ship is protected this.protected(true); // Draw the ship this.draw() // Check if the ship can shoot this.shootCheck(); // Check the keys this.checkKeys(); // Check the velocity this.checkVelocity(); // If it's off screen then warp to the other side if (offScreen(this)) warp(this); } }; function createShip(x, y, minv, maxv){ ship = new Ship(x, y, minv, maxv, game.superman); }<file_sep>// Ships drawing coordinates based from 0 class Shapes { constructor(s, points = (Math.random() * 14) + 5, distortion = 1.5) { this.size = s; this.r = s/2; this.points = points; this.distortion = distortion; this.ship = [ 0, 0, -this.r / 2, this.r, -this.r, this.r, 0, -this.r, this.r, this.r, this.r / 2, this.r ] this.laser = [ 0, this.r, -this.r / 2, this.r, -this.r / 2, -this.r, this.r / 2, -this.r, this.r / 2, this.r ] this.asteroid = this.drawAsteroid(); } drawAsteroid() { // New asteroid array that we'll temporarely save the array of the asteroid to var asteroid = []; // For every point get the x and y coordinates and save them in the temporary array for (var i = 1; i <= this.points; i += 1) { // Random offset for the points which moves them closer or further away from the center var offset = Math.random() *this.distortion * 2 + 1 -this.distortion; // Push the x and y to the temporary array asteroid.push((this.size * offset) * Math.cos(i * 2 * Math.PI / this.points)); //x asteroid.push((this.size * offset) * Math.sin(i * 2 * Math.PI / this.points)); //y } // Return the temporary array to the caller return asteroid; } }<file_sep>class Particle { constructor(x, y, s, rot, speed, lifeSpan, shape, redraw, id) { this.id = id; this.shape = shape; this.redraw = redraw; this.x = x; this.y = y; this.size = s; this.r = s / 2; this.lifeTime = 0; this.lifeSpan = lifeSpan; this.speed = speed this.rot = rot; } applyVelocity() { this.velocity = { x: this.speed * 0.2 * Math.cos((this.rot - 90) * (Math.PI / 180)), y: this.speed * 0.2 * Math.sin((this.rot - 90) * (Math.PI / 180)) } this.x += this.velocity.x this.y += this.velocity.y } destroy() { particleIDs.push(this.id); // Gets the index of this asteroid using it's id var id = particles.findIndex(e => (e.id == this.id)) destroyParticles.push(id); }; draw() { ctx.lineWidth = this.r / 10; ctx.strokeStyle = 'white'; if(this.shape){ if(this.redraw){ drawShape(new Shapes(this.r).asteroid, true, this.x, this.y, 1, (Math.PI / 180) * this.rot); }else{ drawShape(this.shape, true, this.x, this.y, 1, (Math.PI / 180) * this.rot); } }else{ ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI); ctx.stroke(); } }; update() { this.applyVelocity(); this.draw(); if (this.lifeTime < this.lifeSpan) this.lifeTime++; else this.destroy(); }; } particles = []; particleIDs = []; destroyParticles = []; function createParticle(x, y, s, rot, speed, lifeSpan, shape, redraw) { var id; if (!particleIDs.length) { id = particles.length + 1 } else { id = particleIDs.shift(); } particles.push(new Particle(x, y, s, rot, speed, lifeSpan, shape, redraw, id)) } function drawParticles() { for (p in particles) { if (particles.hasOwnProperty(p)) { particles[p].update(); } } while (destroyParticles.length) { // Removes all the particles var id = destroyParticles.pop() // Remove this particle from the array particles.splice(id, 1); } }<file_sep># asteroidShooter Doggos class project :3 mine is better ### How to play - Use W|A|S|D to move - Use space to shoot Going in the console and writing "game." gives you some options <file_sep>// Creates a new class Called Asteroid class Laser { // Defines all the functions and is called by using new Ship(x, y, size, rotation, id) constructor(x, y, s, rot, id, or) { this.id = id; this.rotation = rot this.size = s; this.r = this.size / 2; // Sets the poition of the bullet outside of the radius of the object calling it this.position = { x: x + Math.cos((this.rotation - 90) * (Math.PI / 180)) * or, y: y + Math.sin((this.rotation - 90) * (Math.PI / 180)) * or } this.age = 0; this.maxAge = 80//Math.random() * 60 + 40 this.speed = 50; } checkVelocity() { this.velocity = { x: this.speed * 0.2 * Math.cos((this.rotation - 90) * (Math.PI / 180)), y: this.speed * 0.2 * Math.sin((this.rotation - 90) * (Math.PI / 180)) } this.position.x += this.velocity.x this.position.y += this.velocity.y } draw() { ctx.lineWidth = this.r / 10; ctx.strokeStyle = 'white'; drawShape(new Shapes(this.size).laser, true, this.position.x, this.position.y, 1, (Math.PI / 180) * this.rotation); } destroy() { laserIDs.push(this.id); var id = lasers.findIndex(e => (e.id == this.id)) lasersidsToDestroy.push(id); } async update() { this.checkVelocity(); this.draw(); //if (offScreen(this)) warp(this); if (offScreen(this)) game.warp ? warp(this) : this.destroy(); if(++this.age == this.maxAge && !game.superman) this.destroy(); } };<file_sep>class Heart { display(x, y, s) { this.x = x; this.y = y; this.s = s; this.r = s / 2; this.draw(); } draw() { ctx.lineWidth = this.r / 10; ctx.strokeStyle = 'white'; var heart = [ 0, this.r, -this.r, -this.r/2.5, -this.r/2, -this.r, 0, -this.r/2, this.r/2, -this.r, this.r, -this.r/2.5, ] drawShape(heart, true, this.x, this.y, 1, 0); // ctx.fillStyle = "white"; // ctx.fill(); } }
b7dece5e0f7ca886133efad1d1d31e9963b8d4dd
[ "JavaScript", "Markdown" ]
6
JavaScript
dcrime/asteroidShooter
fb3396ee42ac1ce7bebb679b525ff6338ac4be2f
07005ae5f0da94a16dd7fe1a383f087744c5dfa2
refs/heads/main
<repo_name>IzabelaLage/C<file_sep>/ex01.c //Exemplo: Abrindo, gravando e fechando arquivo #include <stdio.h> #include <stdlib.h> int main(void) { FILE *pont_arq; char palavra[20]; pont_arq = fopen("arquivo.txt", "w"); if(pont_arq == NULL) { printf("Erro na abertura do arquivo!"); return 1; } printf("Escreva uma palavra para testar gravacao de arquivo: "); scanf("%s", palavra); fprintf(pont_arq, "%s", palavra); fclose(pont_arq); printf("Dados gravados com sucesso!"); return(0); }
1f9b7996afea59f75140bb82dfd91cafb4440921
[ "C" ]
1
C
IzabelaLage/C
0e260db7886f06884666af4627e7c9c73412f270
64f844a2fa85d6fc4752f0caf093dae9faca4e6e
refs/heads/main
<repo_name>alexarmstrongvi/AmesHouseRegression<file_sep>/README.md # Overview This collection of notebooks shows the building of a regression model to predict the sale price of houses in Ames, Iowa. The goal of this project has been to deepen my experience with the python tools used in * Handling continuous, discrete, ordinal, and categorical data types * Correlation measures between all data type combinations * Imputation of missing values * Encoding categorical data types (e.g. one-hot, contrast, binary, target) * Building regression models with SciKit-Learn : Linear regreesion, GLM, Decision Tree, BDT, kNN, and multi-layer perceptron NN * Statistical analysis with SciKit-Learn, SciPy, Statsmodels, and Pingouin * Automated approaches to feature selection and model building (e.g. forward stepwise selection, recursive feature elimination) * Outlier detection # Current model evaluation Training data 5-fold CV results of OLS linear regression model using 14 features (8 Categorical, 6 Numerical): * RMSE : $23000 +/- 2000 * MSLE : 0.017 +/- 0.002 * RMSLE : 0.131 +/- 0.009 * MAPE : 9.4% +/- 0.4% ![FinalLinearFit](./images/FinalLinearFit.png) # Project files * [AmesHousingEDA](AmesHousingEDA.ipynb) - Exploratory data analysis and tuning of the final model * [AmesHousingPriceRegression](AmesHousingPriceRegression.ipynb) - The final self-contained pipeline (_forthcoming_) * [utilities](utilities.py) - Utility functions for EDA and other data analysis tasks * [test_utilities](test_utilities.ipynb) - Unit tests and examples of the utility functions # The Data This is the [Kaggle release](https://www.kaggle.com/c/house-prices-advanced-regression-techniques) of the 2011 dataset published by <NAME> in the _Journal of Statistics Education_ ([De Cock 2011](http://jse.amstat.org/v19n3/decock.pdf)). It describes "the sale of individual residential property in Ames, Iowa from 2006 to 2010. The data set contains 2930 observations and a large number of explanatory variables (23 nominal, 23 ordinal, 14 discrete, and 20 continuous) involved in assessing home values" ## Feature Breakdown * **SalePrice** - the property's sale price in dollars. This is the target variable that you're trying to predict. * **Building classification** * MSSubClass: The building class * BldgType: Type of dwelling * HouseStyle: Style of dwelling * OverallQual: Overall material and finish quality * OverallCond: Overall condition rating * YearBuilt: Original construction date * YearRemodAdd: Remodel date * Functional: Home functionality rating * **Land/Lot** * LotFrontage: Linear feet of street connected to property * LotArea: Lot size in square feet * LotShape: General shape of property * LandContour: Flatness of the property * LotConfig: Lot configuration * LandSlope: Slope of property * Foundation: Type of foundation * **Surroundings** * MSZoning: The general zoning classification * Street: Type of road access * Alley: Type of alley access * Neighborhood: Physical locations within Ames city limits * Condition1: Proximity to main road or railroad * Condition2: Proximity to main road or railroad (if a second is present) * **Exterior** * General * Exterior1st: Exterior covering on house * Exterior2nd: Exterior covering on house (if more than one material) * MasVnrType: Masonry veneer type * MasVnrArea: Masonry veneer area in square feet * ExterQual: Exterior material quality * ExterCond: Present condition of the material on the exterior * Roof * RoofStyle: Type of roof * RoofMatl: Roof material * Deck/Porch * WoodDeckSF: Wood deck area in square feet * OpenPorchSF: Open porch area in square feet * EnclosedPorch: Enclosed porch area in square feet * 3SsnPorch: Three season porch area in square feet * ScreenPorch: Screen porch area in square feet * Pool * PoolArea: Pool area in square feet * PoolQC: Pool quality * Fence: Fence quality * **Basement** * BsmtQual: Height of the basement * BsmtCond: General condition of the basement * BsmtExposure: Walkout or garden level basement walls * BsmtFinType1: Quality of basement finished area * BsmtFinSF1: Type 1 finished square feet * BsmtFinType2: Quality of second finished area (if present) * BsmtFinSF2: Type 2 finished square feet * BsmtUnfSF: Unfinished square feet of basement area * TotalBsmtSF: Total square feet of basement area * BsmtFullBath: Basement full bathrooms * BsmtHalfBath: Basement half bathrooms * **Above grade (i.e. above ground) interior** * 1stFlrSF: First Floor square feet * 2ndFlrSF: Second floor square feet * LowQualFinSF: Low quality finished square feet (all floors) * GrLivArea: Above grade (ground) living area square feet * FullBath: Full bathrooms above grade * HalfBath: Half baths above grade * BedroomAbvGr: Number of bedrooms above basement level * KitchenAbvGr: Number of kitchens * KitchenQual: Kitchen quality * TotRmsAbvGrd: Total rooms above grade (does not include bathrooms) * Fireplaces: Number of fireplaces * FireplaceQu: Fireplace quality * **Garage** * GarageType: Garage location * GarageYrBlt: Year garage was built * GarageFinish: Interior finish of the garage * GarageCars: Size of garage in car capacity * GarageArea: Size of garage in square feet * GarageQual: Garage quality * GarageCond: Garage condition * PavedDrive: Paved driveway * **Utilities** * Utilities: Type of utilities available * Heating: Type of heating * HeatingQC: Heating quality and condition * CentralAir: Central air conditioning * Electrical: Electrical system * **Sale** * MoSold: Month Sold * YrSold: Year Sold * SaleType: Type of sale * SaleCondition: Condition of sale * MiscFeature: Miscellaneous feature not covered in other categories * MiscVal: Value of miscellaneous feature For more detail on the data features, such as possible values for categorical features, see [data description](data/data_description.txt) file <file_sep>/utilities.py #!/usr/bin/env python3 """ Useful functions for exploratory data analysis Author: <NAME> <<EMAIL>> March 2020 Example: import utilities as utils """ import phik from sklearn.preprocessing import KBinsDiscretizer from sklearn.feature_selection import mutual_info_classif, mutual_info_regression import pingouin as pg import statsmodels.api as sm import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from scipy import stats, optimize import numpy as np from collections import defaultdict from typing import Mapping, List, Callable, Any def categorize_data_type( df : pd.DataFrame, continuous_thr : int = 50, override : Mapping = None ) -> pd.DataFrame: """ Attempt to categorize the data types of DataFrame columns into nominal, ordinal, or continuous. No attempt to determine discrete data types. Arguments: df : DataFrame to be categorized continuous_thr : Minimum threshold on the number of unique values to be considered continuous override : dict[feature name] = data type Override automatically determined data type Returns: Data type of each feature in a Series """ if not override: override = {} data_types = [] for feature in df: if feature in override: data_types.append(override[feature]) continue data = df[feature].dropna() n_unique = len(data.unique()) if data.dtype == 'object': data_type = 'Nominal' elif data.dtype == 'float64' and not np.allclose(data%1, 0): data_type = 'Continuous' elif data.dtype in ['int64', 'float64'] and n_unique >= continuous_thr: data_type = 'Continuous' elif data.dtype == 'int64': data_type = 'Ordinal' else: data_type = 'Unknown' data_types.append(data_type) rv = pd.Series(data_types, index=df.columns, name='Data type') return rv def nearest_neighbor_value(vals, val): ''' Return array entry with value closest to target entry Arguments : vals : array of comparable values (e.g. float, string) val : target value Returns: nearest neighbor value >>> nearest_neighbor_value([2,3,5],2) 3 >>> nearest_neighbor_value([2,5,3],2) 3 ''' vals = np.sort(vals) index = np.where(vals == val)[0][0] if index == len(vals)-1: # target entry in back nneighbor = vals[index-1] elif index == 0: # target entry in front nneighbor = vals[1] else: # Target entry in middle diff_lo = abs(val - vals[index-1]) diff_hi = abs(val - vals[index+1]) nneighbor = vals[index-1] if diff_lo < diff_hi else vals[index+1] return nneighbor def outlier_check(df, index, num_features, discrete_thr=10, print_result=False): """ Calculate outlier statistics for each feature of a given entry Arguments: df : Input DataFrame index : Index of entry num_features : Numerical features in df discrete_thr : Threshold on number of unique values for calculating numerical outlier statistics print_result : print results instead of returning them Returns: (df_numerical, df_categorical) : Outlier statatistis for numerical and categorical variables """ num_scores = defaultdict(dict) cat_scores = defaultdict(dict) for f in df.columns: vals = df[f] val = vals[index] vc = vals.value_counts() mode = vc.index[0] if f in num_features and len(vc) > discrete_thr: num_scores['Value'][f] = val if pd.isnull(val): continue num_scores['Mean'][f] = vals.mean() num_scores['Median'][f] = vals.median() num_scores['NN value'][f] = nearest_neighbor_value(vals, val) num_scores['|Z-score|'][f] = abs(stats.zscore(vals)[index]) #num_scores['percentile-score'][f] = stats.percentileofscore(vals, val) median_resids = np.abs(vals - vals.median()) median_resid = np.abs(val - vals.median()) num_scores['percentile-score'][f] = stats.percentileofscore(median_resids, median_resid) # MAD score # must account for cases where >50% of values are the same mad = stats.median_abs_deviation(vals) if mad > 0: mad_score = median_resid/mad elif val == mode: mad_score = 0 else: # val != mode mad_score = float('inf') num_scores['|MAD-score|'][f] = mad_score else : # Categorical cat_scores['Value'][f] = val if pd.isnull(val): continue ival = vc.index.get_loc(val) inn = ival-1 if ival > 0 else 0 cat_scores['Mode'][f] = mode cat_scores['freq'][f] = vc[val] cat_scores['freq rank'][f] = ival + 1 cat_scores['# unique'][f] = len(vc) cat_scores['rel freq'][f] = vc[val]/len(df) cat_scores['cum freq'][f] = vc.iloc[ival:].sum()/len(df) cat_scores['max freq ratio'][f] = vc[val]/vc[mode] cat_scores['NN freq ratio'][f] = vc.iloc[ival]/vc.iloc[ival-1] if ival>0 else 1 df_num_scores = pd.DataFrame(num_scores) df_cat_scores = pd.DataFrame(cat_scores) if print_result: print('Outlier test for entry', index) with pd.option_context('display.max_rows', None, 'display.max_columns', None): # Show two tables: one for continuous and another for categorical print("Numerical Outliers") display(df_num_scores.sort_values(['|Z-score|'], ascending=False)) print("Categorical Outliers") display(df_cat_scores.sort_values(['cum freq'])) else: return df_num_scores, df_cat_scores def r2_adjusted(r2, n, k): return 1 - ((1-r2)*(n-1))/(n-k-1) def corr_to_target( df : pd.DataFrame, target : Any, cat_features : Any, ) -> pd.DataFrame: """ Determine correlation of target feature to all other features with an effect size that is comparable between categorical and numerical features. Arguments: df : Data target : Target feature key in DataFrame with respect to which correlations are determined cat_features : Keys for categorical features in DataFrame Returns: DataFrame with correlations measures """ result = defaultdict(dict) cat_target = target in cat_features num_target = not cat_target for f in df.columns.drop(target): data = df[[f, target]].dropna() cat_feature = f in cat_features num_feature = not cat_feature result['Categorical'][f] = int(cat_feature) if cat_target and cat_feature: pass elif cat_target and num_feature: pass elif num_target and cat_feature: vc = data[f].value_counts() if vc.min() > 1: n2, pval = pg.welch_anova(data=data, dv=target, between=f).loc[0,['np2','p-unc']].values result['R2'][f] = n2 result['R2_adj'][f] = r2_adjusted(n2,len(data),len(vc)) result['pval'][f] = pval #mi = mutual_info_classif(data[[target]], data[f])[0] #result['MI'][f] = mi elif num_target and num_feature: r, pval = stats.pearsonr(data[f], data[target]) result['R2'][f] = r**2 result['R2_adj'][f] = r2_adjusted(r**2, len(data), 1) result['pval'][f] = pval #mi = mutual_info_regression(data[[f]], data[target])[0] #result['MI'][f] = mi return pd.DataFrame(result) def local_sigma_bands( x : np.ndarray, y : np.ndarray, n_regions : int = 100, window_scale : float = 0.3, percentiles : bool = False, zero : bool = False ) -> (np.ndarray, np.ndarray, np.ndarray, np.ndarray): """ Estimate local mean and standard deviation Arguments: x : Predictor variable y : Response variable n_regions : Number of localized regions in x to process window_scale : Relative window size defining each local x region. Scale ranges from 0 to 1. Default behavior calculates window width relative to the range of x values; value in [0,1] For `percentiles=True`, window scale is in units of percentiles; value in [0,100] percentiles : Window includes a percentile range of data points instead of a fixed width range zero : Center the sigma bands around zero Returns: x_local : Central x values for regions used in calculating local mean and std y_mid : Mean for each local region y_lo, y_hi : One standard deviation below and above the mean at each local x """ # Sort data points by x values idx_sort = np.argsort(x) x, y = x[idx_sort], y[idx_sort] # Configure parameters if percentiles: x_scan = np.linspace(0,100, n_regions) window_width = window_scale else: x_scan = np.linspace(min(x), max(x), n_regions) window_width = window_scale * (max(x) - min(x)) # Calculate bands x_local, y_lo, y_mid, y_hi = [],[],[],[] for i, xi in enumerate(x_scan): if percentiles: p_lo = max(0, xi - window_width/2) p_hi = min(100, xi + window_width/2) x_mid, x_lo, x_hi = np.percentile(x, [xi, p_lo, p_hi]) x_local.append(x_mid) else: x_local.append(xi) x_lo, x_hi = xi - window_width/2, xi + window_width/2 vals = y[(x_lo <= x) & (x <= x_hi)] if len(vals) > 2: y_mid.append(vals.mean()) y_lo.append(vals.mean() - vals.std(ddof=1)) y_hi.append(vals.mean() + vals.std(ddof=1)) else: # Not enough values to calculate std. Skip region x_local.pop() # Format output x_local = np.array(x_local) y_lo = np.array(y_lo) y_mid = np.array(y_mid) y_hi = np.array(y_hi) if zero: offset = (y_hi + y_lo)/2 y_lo -= offset y_hi -= offset return (x_local, y_mid, y_lo, y_hi) def truncated_hist( x : pd.Series, val : Any = 'mode', ax : plt.Axes = None ) -> plt.Axes: """ Truncated histogram to visualize more values when one dominates Arguments: x : Data Series val : Value to truncate in histogram. 'mode' will truncate the data mode. ax : matplotlib Axes object to draw plot onto Returns: ax : Returns the Axes object with the plot drawn onto it """ # Setup Axes if not ax: fig, ax = plt.subplots() ax.set_xlabel(x.name) ax.set_ylabel('Counts') if val is None: ax.hist(x, bins='auto') return if val == 'mode': val = x.mode().iloc[0] # Plot without selected value sel_vals = x[x != val] bin_vals, bin_edges, _ = ax.hist(sel_vals, bins='auto') ax_min, ax_max = ax.get_ylim() ax.set_ylim(ax_min, ax_max*1.1) # Expand x-axis to include removed value and then annotate with the value's count ax_min, ax_max = ax.get_xlim() if val < min(sel_vals): # Lower xmin buff = abs(ax_max - max(sel_vals)) ax.set_xlim(val - buff, ax_max) horiztonal_alignment = 'left' arrow_relpos = (0, 0) elif val > max(sel_vals): # Increase xmax buff = abs(ax_min - min(sel_vals)) ax.set_xlim(ax_min, val + buff) horiztonal_alignment = 'right' arrow_relpos = (1, 1) else: # No change to x range horiztonal_alignment = 'center' arrow_relpos = (0.5, 0.5) val_count = (x == val).sum() val_perc = val_count/len(x) ax.annotate(f'{val} (count={val_count}; {val_perc:.0%} of total)', xy=(val, 0), xytext=(val, max(bin_vals)*1.1), xycoords='data', ha=horiztonal_alignment, arrowprops=dict(arrowstyle = '<-', color = 'black', lw = '4', relpos=arrow_relpos) ) return ax def truncated_countplot( x : pd.Series, val : Any = 'mode', ax : plt.Axes = None ) -> plt.Axes: """ Truncated count plot to visualize more values when one dominates Arguments: x : Data Series val : Value to truncate in count plot. 'mode' will truncate the data mode. ax : matplotlib Axes object to draw plot onto Returns: ax : Returns the Axes object with the plot drawn onto it """ # Setup Axes if not ax: fig, ax = plt.subplots() ax.set_xlabel(x.name) ax.set_ylabel('Counts') if val is None: sns.countplot(x=x, ax=ax) return if val == 'mode': val = x.mode().iloc[0] # Plot and truncate splot = sns.countplot(x=x, ax=ax) ymax = x[x != val].value_counts().iloc[0]*1.4 ax.set_ylim(0, ymax) # Annotate truncated bin xticklabels = [x.get_text() for x in ax.get_xticklabels()] val_ibin = xticklabels.index(str(val)) val_bin = splot.patches[val_ibin] xloc = val_bin.get_x() + 0.5*val_bin.get_width() yloc = ymax ax.annotate('', xy=(xloc, 0), xytext=(xloc, yloc), xycoords='data', arrowprops=dict(arrowstyle = '<-', color = 'black', lw = '4') ) val_count = (x == val).sum() val_perc = val_count / len(x) ax.annotate(f'{val} (count={val_count}; {val_perc:.0%} of total)', xy=(0.5, 0), xytext=(0.5, 0.9), xycoords='axes fraction', ha='center' ) return ax def plot_grid( df : pd.DataFrame, features : List, plottype : str = None, plot_func : Callable[[pd.DataFrame, Any, plt.Axes], Any] = None, ncols : int = 4, vscale : float = 5, hscale : float = 5 ) -> plt.Axes: """ Draw several univariate plots in a grid Arguments: df : Dataframe with data to plot features : Dataframe features to plot plottype : Type of plot * 'histplot' * 'histplot_trunc' * 'histplot_discrete' * 'countplot_trunc' * 'countplot_few' * 'countplot_many' * None -> must provide `plot_func` plot_func : Arbitrary plot function (`plot_func(DataFrame, feature, Axes)`) ncols : Number of columns in grid vscale, hscale : Vertical and horizonital scale of each plot in the grid (i.e. `figsize`) Returns: fig : Figure ax : array of Axes objects. """ # Initialize figure nrows = len(features)//ncols + (len(features)%ncols > 0) fig, axs = plt.subplots(nrows, ncols, figsize=(ncols*hscale,nrows*vscale)) # Draw plots from left -> right and top -> bottom for i, c in enumerate(features): ax = axs[i//ncols, i%ncols] if nrows > 1 else axs[i] if plottype == 'histplot': sns.histplot(df, x=c, ax=ax) elif plottype == 'histplot_crop': truncated_hist(df[c], val='mode', ax=ax) elif plottype == 'histplot_discrete': sns.histplot(df, x=c, discrete=True, shrink=0.9, ax=ax) elif plottype == 'countplot_crop': truncated_countplot(df[c], val='mode', ax=ax) elif plottype == 'countplot_few': sns.countplot(data=df, x=c, ax=ax) elif plottype == 'countplot_many': sns.countplot(data=df, y=c, ax=ax) elif plot_func: plot_func(df, c, ax) else: print('Plot type no recognized:', plottype) break # Remove any axes not filled if len(features)%ncols: for i in range(len(features)%ncols, ncols): ax = axs[nrows-1, i%ncols] if nrows > 1 else axs[i] ax.axis('off') return fig, axs def power_fit( x : np.ndarray, y : np.ndarray, neg_p : bool = False, maxfev : int = None, use_jac : bool = False ) -> (float, float, float, float): """ Fit quasi-polynomial a*(x-s)^p + b to inputs. Useful for checking linearity Arguments: x, y : Data for fit neg_p : Initialize fit with p = -1. Improves convergence if true p < 0 maxfev : Manually set max function evaluations use_jac : Use Jacobian in curve fit Returns: (a, s, p, b) : fit parameters """ def f(x, a, s, p, b): return a*((x-s)**p) + b def jac(x, a, s, p, b): return np.array([ (x-s)**p, # df/da -p*((x-s)**(p-1)), # df/ds np.log(x-s) * ((x-s)**p), # df/dp np.ones(len(x)) # df/db ]).T if not use_jac: jac = None # Constraints : x-s > 0 or else discontinuous behavior since df/fp undefined s_max = x.min()-1e-3*np.ptp(x) # Initialize fit parameters to give OLS fit line X = sm.add_constant(x.reshape(-1,1)) result = sm.OLS(y, X).fit() a0 = result.params[1] # OLS Slope s0 = s_max p0 = -1 if neg_p else 1 b0 = result.predict([[1, s_max]])[0] param0 = (a0, s0, p0, b0) # Define bounds #p_min, p_max = (-3, -1/3) if neg_p else (1/3, 3) p_min, p_max = (-2, -1/2) if neg_p else (1/2, 2) bounds = [ # a, s, p, b [-np.inf, -np.inf, p_min, -np.inf], # lower [np.inf, s_max, p_max, np.inf] # upper ] # Fit try: popt, _ = optimize.curve_fit(f, x, y, p0=param0, bounds=bounds, method='trf', jac=jac, maxfev=maxfev) except RuntimeError as e: print('Power fit failed:',e) return param0 return popt def inverse_crosstab(table): n = table.sum().sum() x = [] y = [] for i, row in enumerate(table.index): for j, col in enumerate(table.columns): count = table.at[row,col] x += [j]*count y += [i]*count return np.array(x), np.array(y) # Cochran’s rule of thumb is that at least 80% of the expected cell frequencies is 5 counts or more, # and that no expected cell frequency is less than 1 count. For a 2x2 contingency table, Cochran # recommends that the test should be used only if the expected frequency in each cell is at # least 5 counts. def phi_coef(cont_table): """ - a measure of association for two binary variables - the Pearson correlation coefficient reduces to the phi coefficient in the 2×2 case """ chi2 = stats.chi2_contingency(cont_table, correction=False)[0] N = cont_table.sum().sum() return np.sqrt(chi2/N) def tschuprows_t(cont_table): """ - Tschuprow, 1925, 1939 - Symmetric, order independent measure of correlation between discrete variables with >=2 levels - varies from 0 (no association) to 1 (complete association) - Reduces to the phi coefficient in the 2×2 case """ phi = phi_coef(cont_table) c, r = cont_table.shape correction = ((r-1)*(c-1))**(-1/4) return correction * phi def contingency_coef(cont_table, adjust=True): """ - An adjustment to phi coefficient, intended to adapt it to tables larger than 2-by-2. - The larger the table your chi-squared coefficient is calculated from, the closer to 1 a perfect association will approach. That’s why some statisticians suggest using the contingency coefficient only if you’re working with a 5 by 5 table or larger. (https://www.statisticshowto.com/contingency-coefficient/) """ phi = phi_coef(cont_table) correction = 1 / np.sqrt(1 + phi**2) if adjust: # normalize across different contingency table dimensions r, c = cont_table.shape theoretical_max = ((r-1)/r * (c-1)/c)**(1/4) else: theoretical_max = 1 return (correction * phi) / theoretical_max # return 1/np.sqrt(1 + N/chi2) / theoretical_max def cramers_v(cont_table): """ - Cramer, 1946 - Symmetric, order independent measure of correlation between discrete variables with >=2 levels - Varies from 0 (no association) to 1 (complete association) - Reduces to the phi coefficient in the 2×2 case """ phi = phi_coef(cont_table) min_dim = min(cont_table.shape) correction = 1 / np.sqrt(min_dim-1) return correction * phi def conditional_entropy(p_xy): if not np.allclose(p_xy.sum(), 1): # not normalized p_xy = p_xy/p_xy.sum() p_y = p_xy.sum(axis=1, keepdims=True) return -np.sum(p_xy * np.log(p_xy/p_y)) def uncertainty_coef(cont_table, sym=False): """ - Asymmetric (Y|X) - Varies from 0 (no association) to 1 (complete association) - Theil (1970) derived a large part of the uncertainty coefficient, so it’s occasionally referred to as “Theil’s U”. This is a little misleading, because the term Theil’s U usually refers to a completely different U used in finance. """ if sym: sx = stats.entropy(cont_table.sum(axis=0)) sy = stats.entropy(cont_table.sum(axis=1)) ux = uncertainty_coef(cont_table) uy = uncertainty_coef(cont_table.T) return (sx*ux + sy*uy)/(sx+sy) # Entropy weighted average sx = stats.entropy(cont_table.sum(axis=0)) x, y = inverse_crosstab(cont_table) mi = mutual_info_classif(x.reshape(-1,1), y, discrete_features=True)[0] #mi = hx - conditional_entropy(cont_table.to_numpy()) return mi/sx def goodman_kruskals_lambda(cont_table, sym=False): """ - <NAME>., <NAME>. (1954) "Measures of association for cross classifications" - default asymmetric (Y|X) but can symmetric version available """ n = cont_table.sum().sum() # Total entries s = cont_table.max(axis=0).sum() # Sum of col max r = cont_table.sum(axis=1).max() # Max of row sum if sym: sx = cont_table.max(axis=1).sum() rx = cont_table.sum(axis=0).max() s = (sx+s)/2 r = (rx+r)/2 e1 = 1 - r/n # P(error) from always guessing Y from max P(Y) e2 = 1 - s/n # P(error) from always guessing Y from max P(X=x,Y) return (e1 - e2) / e1 # = (s-r)/(n-r) def phik_coef(cont_table): pk = phik.phik.phik_from_hist2d(cont_table.to_numpy()) pk_pval, pk_z = phik.significance.significance_from_hist2d(cont_table.to_numpy()) return (pk, pk_pval, pk_z)
c8da2cc9ac1cd646be6945612ad042365b927281
[ "Markdown", "Python" ]
2
Markdown
alexarmstrongvi/AmesHouseRegression
39898d7a950ea02abc2d2b363ac98470de94d63e
a3872c2431f35e0fffea5c7e8181bfab269c2857
refs/heads/master
<file_sep>/* * 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 GUI.Consultas.Opciones; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ComboBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; /** * * @author Asus */ public class OpcionesC { private Scene escena; private VBox vbox; private HBox menu; private ComboBox<String> opciones; private Button seleccionar; private Button regresar; private HBox fondo; private Image logo; private Text nombreE; private StackPane fondos; public OpcionesC() throws FileNotFoundException { this.opciones = new ComboBox<>(); opciones.getItems().addAll("Informacion personal","Programas Colombia", "Programas voluntariado","Programas ICCP", "Asignacion programas Colombia" ,"Asignacion programas voluntariado","Asignacion programas ICCP"); this.seleccionar = new Button("Seleccionar tabla"); this.regresar = new Button("Atras"); this.menu = new HBox(); this.vbox = new VBox(); vbox.setPadding(new Insets(100, 0, 0, 20)); menu.setSpacing(100); Label label = new Label("Ingrese la tabla en la cual quiere hacer la consulta: ", opciones); label.setContentDisplay(ContentDisplay.RIGHT); menu.getChildren().addAll(label, seleccionar, regresar); vbox.getChildren().add(menu); this.fondo = new HBox(); this.logo = new Image(new FileInputStream("src/GUI/Logo.png")); this.nombreE = new Text("Base de datos YMCA"); nombreE.setFont(Font.font(50)); fondo.getChildren().addAll(nombreE, new ImageView(logo)); fondo.setPadding(new Insets(5, 10, 0, 10)); fondo.setSpacing(600); this.fondos = new StackPane(); Image pp = new Image(new FileInputStream("src/GUI/Fondo.png")); ImageView imagen = new ImageView(pp); fondos.getChildren().addAll(imagen, fondo, vbox); escena = new Scene(fondos, 1200, 670); } public void mostrar(Stage stage) { stage.setTitle("Consulta"); stage.setScene(this.escena); stage.show(); } public Button getSeleccionar() { return seleccionar; } public ComboBox<String> getOpciones() { return opciones; } public Button getRegresar() { return regresar; } } <file_sep>package Proceso; /* * 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. */ /** * * @author Estudiante */ public class Producto { protected String nombre; protected String destino; protected Fecha fechaLlegada; protected Fecha fechaSalida; public Producto(String nombre, String destino, Fecha fechaLlegada, Fecha fechaSalida) { this.nombre = nombre; this.destino = destino; this.fechaLlegada = fechaLlegada; this.fechaSalida = fechaSalida; } public String getNombre() { return nombre; } public String getDestino() { return destino; } public Fecha getFechaLlegada() { return fechaLlegada; } public Fecha getFechaSalida() { return fechaSalida; } } <file_sep>/* * 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 GUI.Formularios.FormulariosOpc3; import GUI.Formularios.FormularioICCPAssign.FormICCPAssignVC; import GUI.Formularios.FormularioLocalVolunProg.FormLocalVolProgVC; import GUI.Formularios.FormulariosOpc.*; import GUI.Formularios.FormularioProgAssign.FormProgAssignVC; import GUI.Singleton; import ModeloNegocio.GestorPlataforma; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.Event; import javafx.event.EventHandler; /** * * @author Asus */ public class Opciones3VC { private Opciones3 vista; private GestorPlataforma gestor; public Opciones3VC(GestorPlataforma gestor) throws FileNotFoundException { this.gestor = gestor; this.vista = new Opciones3(); vista.getB1().setOnMousePressed(new b1Pressed()); vista.getB2().setOnMousePressed(new b2Pressed()); vista.getB3().setOnMousePressed(new b3Pressed()); vista.getRegresar().setOnMousePressed(new regresar()); } public void mostrarVista(){ Singleton singleton = Singleton.getSingleton(); vista.mostrar(singleton.getStage()); } class b1Pressed implements EventHandler<Event>{ @Override public void handle(Event event) { FormProgAssignVC vista1 = null; try { vista1 = new FormProgAssignVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(Opciones3VC.class.getName()).log(Level.SEVERE, null, ex); } vista1.mostrarVista(); } } class b2Pressed implements EventHandler<Event>{ @Override public void handle(Event event) { FormLocalVolProgVC vista1 = null; try { vista1 = new FormLocalVolProgVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(Opciones3VC.class.getName()).log(Level.SEVERE, null, ex); } vista1.mostrarVista(); } } class b3Pressed implements EventHandler<Event>{ @Override public void handle(Event event) { FormICCPAssignVC vista1 = null; try { vista1 = new FormICCPAssignVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(Opciones3VC.class.getName()).log(Level.SEVERE, null, ex); } vista1.mostrarVista(); } } class regresar implements EventHandler<Event>{ @Override public void handle(Event event) { OpcionesVC vista = null; try { vista = new OpcionesVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(Opciones3VC.class.getName()).log(Level.SEVERE, null, ex); } vista.mostrarVista();; } } } <file_sep>import java.util.ArrayList; /* * 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. */ /** * * @author Asus */ public class Estanteria { private String categoriaOrigen; private String origen; private boolean estaLlena; private int numEstanteria; private ArrayList<Libro> libros; public Estanteria(String categoriaOrigen, String origen, boolean estaLlena, int numEstanteria, ArrayList<Libro> libros) { this.categoriaOrigen = categoriaOrigen; this.origen = origen; this.estaLlena = estaLlena; this.numEstanteria = numEstanteria; this.libros = libros; } public String getCategoriaOrigen() { return categoriaOrigen; } public void setCategoriaOrigen(String categoriaOrigen) { this.categoriaOrigen = categoriaOrigen; } public String getOrigen() { return origen; } public void setOrigen(String origen) { this.origen = origen; } public boolean isEstaLlena() { return estaLlena; } public void setEstaLlena(boolean estaLlena) { this.estaLlena = estaLlena; } public ArrayList<Libro> getLibros() { return libros; } public void addLibros(Libro libro){ libros.add(libro); } public int getNumEstanteria() { return numEstanteria; } public void setNumEstanteria(int numEstanteria) { this.numEstanteria = numEstanteria; } } <file_sep>/* * 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 GUI.Formularios.FormularioLocalVolunProg; import GUI.Formularios.FormularioLocalVolunProg.*; import GUI.Formularios.FormulariosOpc.OpcionesVC; import GUI.Formularios.FormulariosOpc3.Opciones3VC; import GUI.Singleton; import ModeloNegocio.GestorPlataforma; import ModeloNegocio.LocalVolunteerAssignment; import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.control.Alert; /** * * @author Asus */ public class FormLocalVolProgVC { private FormLocalVolProg vista; private GestorPlataforma gestor; public FormLocalVolProgVC(GestorPlataforma gestor) throws FileNotFoundException { this.gestor = gestor; this.vista= new FormLocalVolProg(); vista.getBoton().setOnMousePressed(new siguiente()); vista.getRegresar().setOnMousePressed(new regresar()); } public void mostrarVista(){ Singleton singleton = Singleton.getSingleton(); vista.mostrar(singleton.getStage()); } class siguiente implements EventHandler<Event>{ @Override public void handle(Event event) { String idPersona = vista.getIdParticipanteTF().getText(); String nombrePersona = vista.getNombreParticipanteTF().getText(); String nombreCampamento = vista.getNombreCampamentoTF().getText(); String calificacion = vista.getCalificacionTF().getText(); String nota = vista.getNotaTF().getText(); boolean t = true; if (idPersona.equals("") || nombrePersona.equals("") || nombrePersona.equals("") || calificacion.equals("")) { t = false; Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Debe llenar todos los campos que se encuentran como obligatorios"); alert.show(); FormLocalVolProgVC pantalla = null; try { pantalla = new FormLocalVolProgVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormLocalVolProgVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } boolean l = false; for(int i=0;i<gestor.getPersonas().size() && !l;i++){ if(gestor.getPersonas().get(i).getId().equals(idPersona) && gestor.getPersonas().get(i).getFullName().equals(nombrePersona)){ t = true; } } boolean q = false; for(int j=0;j<gestor.getProgramasVoluntariado().size() && !q;j++){ if(gestor.getProgramasVoluntariado().get(j).getNombre().equals(nombreCampamento) ){ q = true; } } if(l==false || q==false){ t = false; Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Puede que la persona o el campamento que ingreso no existan"); alert.show(); FormLocalVolProgVC pantalla = null; try { pantalla = new FormLocalVolProgVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormLocalVolProgVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } if (t) { try { String rol = vista.getRolTF().getValue().toString(); LocalVolunteerAssignment asignacion = new LocalVolunteerAssignment(idPersona, nombrePersona, nombreCampamento, rol, calificacion, nota); try { gestor.addVoluntariadoAssignment(asignacion); } catch (IOException ex) { Logger.getLogger(FormLocalVolProgVC.class.getName()).log(Level.SEVERE, null, ex); } Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmacion"); alert.setHeaderText("La informacion ha sido registrada"); alert.show(); OpcionesVC pantalla = null; try { pantalla = new OpcionesVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormLocalVolProgVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } catch (NullPointerException e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Debe llenar todos los campos que se encuentran como obligatorios"); alert.show(); FormLocalVolProgVC pantalla = null; try { pantalla = new FormLocalVolProgVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormLocalVolProgVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } } } } class regresar implements EventHandler<Event>{ @Override public void handle(Event event) { Opciones3VC pantalla = null; try { pantalla = new Opciones3VC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormLocalVolProgVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } } } <file_sep>package ModeloNegocio; /* * 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. */ /** * * @author Asus */ public class VolunteerPrograms extends Programas{ private String company; private String fechaGrado; private String duration; private String tipoVoluntariado; public VolunteerPrograms(String company, String fechaGrado, String duration, String tipoVoluntariado, String ID) { super(ID, tipoVoluntariado + "-" + company + "-" + fechaGrado); this.company = company; this.fechaGrado = fechaGrado; this.duration = duration; this.tipoVoluntariado = tipoVoluntariado; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getFechaGrado() { return fechaGrado; } public void setFechaGrado(String fechaGrado) { this.fechaGrado = fechaGrado; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getTipoVoluntariado() { return tipoVoluntariado; } public void setTipoVoluntariado(String tipoVoluntariado) { this.tipoVoluntariado = tipoVoluntariado; } } <file_sep>/* * 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. */ /** * * @author Asus */ public class TravelAgency { private String name; private Hotel[] knownHotels; private Travel[] offeredTravels; private Airport[] airports; public TravelAgency(String name) { this.name = name; this.knownHotels = new Hotel[5]; this.offeredTravels = new Travel[10]; this.airports = new Airport[4]; } } <file_sep>/* * 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 GUI.Formularios.FormularioPersInfo; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; /** * * @author Asus */ public class FormPersona { private Scene escena; private VBox vbox; private HBox hbox; private HBox hbox2; private HBox hbox3; private Label informacion; private Label fullName; private TextField fullNameTF; private Label typeDocument; private ChoiceBox typeDocumentTF; private Label Id; private TextField IdTF; private Label gender; private ChoiceBox genderTF; private Label dateBirth; private DatePicker dateBirthTF; private Label mobile; private TextField mobileTF; private Label phone; private TextField phoneTF; private Label citizen; private TextField citizenTF; private Label email; private TextField emailTF; private Label passport; private TextField passportTF; private Label sizeShirt; private ChoiceBox sizeShirtTF; private Label currentOcupation; private TextField currentOcupationTF; private HBox hbox4; private Label info2; private Label fieldsStudy; private TextField fieldsStudyTF; private Label university; private TextField universityTF; private Label graduado; private ChoiceBox graduadoTF; private Label currentAdress; private HBox hbox5; private Label info3; private TextField currentAdressTF; private Label currentCity; private TextField currentCityTF; private HBox hbox6; private Label info4; private Label fullNameEmergencyContact; private TextField fullNameEmergencyContactTF; private Label numberEmergencyContact; private TextField numberEmergencyContactTF; private Label emailEmergencyContact; private TextField emailEmergencyContactTF; private Label relationship; private ChoiceBox relationshipTF; private Button boton; private HBox fondo; private Image logo; private Text nombreE; private StackPane fondos; private ObservableList names; private ObservableList names2; private ObservableList names3; private ObservableList names4; private ObservableList names5; private Button regresar; private HBox botones; public FormPersona() throws FileNotFoundException { this.vbox = new VBox(); vbox.setSpacing(20); vbox.setPadding(new Insets(100, 25, 25, 25)); Label info = new Label("Nota: Los campos con \"*\" son obligatorios"); info.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 15)); this.informacion = new Label("Informacion personal: ", info); informacion.setContentDisplay(ContentDisplay.RIGHT); informacion.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 20)); vbox.getChildren().add(informacion); this.hbox = new HBox(); this.fullNameTF = new TextField(); this.fullName = new Label("Nombre completo: *" , fullNameTF); fullName.setContentDisplay(ContentDisplay.RIGHT); names = FXCollections.observableArrayList(); names.add("Tarjeta de identidad"); names.add("Cedula de ciudadania"); names.add("<NAME>"); names.add("Pasaporte"); names.add("Registro civil"); this.typeDocumentTF = new ChoiceBox(names); this.typeDocument = new Label("Tipo de documento: *", typeDocumentTF); typeDocument.setContentDisplay(ContentDisplay.RIGHT); this.IdTF = new TextField(); this.Id = new Label("Identificacion: *" , IdTF); Id.setContentDisplay(ContentDisplay.RIGHT); names2 = FXCollections.observableArrayList(); names2.add("Masculino"); names2.add("Femenino"); this.genderTF = new ChoiceBox(names2); this.gender = new Label("Genero: *", genderTF); gender.setContentDisplay(ContentDisplay.RIGHT); hbox.getChildren().addAll(fullName,typeDocument,Id,gender); hbox.setSpacing(20); vbox.getChildren().add(hbox); this.hbox2 = new HBox(); this.dateBirthTF = new DatePicker(); this.dateBirth = new Label("Fecha nacimiento: *", dateBirthTF); dateBirth.setContentDisplay(ContentDisplay.RIGHT); this.mobileTF = new TextField(); this.mobile = new Label("Celular: *", mobileTF); mobile.setContentDisplay(ContentDisplay.RIGHT); this.phoneTF = new TextField(); this.phone = new Label("Telefono:", phoneTF); phone.setContentDisplay(ContentDisplay.RIGHT); names3 = FXCollections.observableArrayList(); names3.add("S"); names3.add("M"); names3.add("L"); names3.add("XXL"); names3.add("XL"); names3.add("10"); names3.add("12"); names3.add("14"); names3.add("16"); this.sizeShirtTF = new ChoiceBox(names3); this.sizeShirt = new Label("Tamaño de camisa: *", sizeShirtTF); sizeShirt.setContentDisplay(ContentDisplay.RIGHT); hbox2.getChildren().addAll(dateBirth,mobile,phone, sizeShirt); hbox2.setSpacing(60); vbox.getChildren().add(hbox2); this.hbox3 = new HBox(); this.emailTF = new TextField(); this.email = new Label("Email: *", emailTF); email.setContentDisplay(ContentDisplay.RIGHT); this.citizenTF = new TextField(); this.citizen = new Label("Nacionalidad:", citizenTF); citizen.setContentDisplay(ContentDisplay.RIGHT); this.passportTF = new TextField(); this.passport = new Label("Pasaporte:", passportTF); passport.setContentDisplay(ContentDisplay.RIGHT); hbox3.getChildren().addAll(email,citizen, passport); hbox3.setSpacing(100); vbox.getChildren().add(hbox3); this.info2 = new Label("Informacion academica:"); info2.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 20)); vbox.getChildren().add(info2); this.hbox4 = new HBox(); this.fieldsStudyTF = new TextField(); this.fieldsStudy = new Label("Carrera: *", fieldsStudyTF); fieldsStudy.setContentDisplay(ContentDisplay.RIGHT); this.universityTF = new TextField(); this.university = new Label("Universidad: *", universityTF); university.setContentDisplay(ContentDisplay.RIGHT); names5 = FXCollections.observableArrayList(); names5.add("Si"); names5.add("No"); this.graduadoTF = new ChoiceBox(names5); this.graduado = new Label("Graduado: *", graduadoTF); graduado.setContentDisplay(ContentDisplay.RIGHT); hbox4.getChildren().addAll(fieldsStudy,university,graduado); hbox4.setSpacing(100); vbox.getChildren().add(hbox4); this.info3 = new Label("Informacion actual: "); info3.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 20)); vbox.getChildren().add(info3); this.hbox5 = new HBox(); this.currentOcupationTF = new TextField(); this.currentOcupation = new Label("Ocupacion: *", currentOcupationTF); currentOcupation.setContentDisplay(ContentDisplay.RIGHT); this.currentAdressTF = new TextField(); this.currentAdress = new Label("Direccion actual: *", currentAdressTF); currentAdress.setContentDisplay(ContentDisplay.RIGHT); this.currentCityTF = new TextField(); this.currentCity = new Label("Ciudad actual: *", currentCityTF); currentCity.setContentDisplay(ContentDisplay.RIGHT); hbox5.getChildren().addAll(currentOcupation,currentAdress,currentCity); hbox5.setSpacing(100); vbox.getChildren().add(hbox5); this.info4 = new Label("Informacion contacto de emergencia: "); info4.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 20)); vbox.getChildren().add(info4); this.hbox6 = new HBox(); this.fullNameEmergencyContactTF = new TextField(); this.fullNameEmergencyContact = new Label("Nombre: *", fullNameEmergencyContactTF); fullNameEmergencyContact.setContentDisplay(ContentDisplay.RIGHT); this.numberEmergencyContactTF = new TextField(); this.numberEmergencyContact = new Label("Numero: *", numberEmergencyContactTF); numberEmergencyContact.setContentDisplay(ContentDisplay.RIGHT); this.emailEmergencyContactTF = new TextField(); this.emailEmergencyContact = new Label("Email: *",emailEmergencyContactTF); emailEmergencyContact.setContentDisplay(ContentDisplay.RIGHT); names4 = FXCollections.observableArrayList(); names4.add("Papá"); names4.add("Mamá"); names4.add("Primo"); names4.add("Prima"); names4.add("Abuelo"); names4.add("Abuela"); names4.add("Madrina"); names4.add("Padrino"); names4.add("Tio"); names4.add("Tia"); names4.add("Amigo"); names4.add("N/A"); this.relationshipTF = new ChoiceBox(names4); this.relationship = new Label("Relacion: *", relationshipTF); relationship.setContentDisplay(ContentDisplay.RIGHT); hbox6.getChildren().addAll(fullNameEmergencyContact,numberEmergencyContact,emailEmergencyContact,relationship); hbox6.setSpacing(70); vbox.getChildren().add(hbox6); this.botones = new HBox(); botones.setAlignment(Pos.CENTER); botones.setSpacing(100); this.boton = new Button("Agregar"); this.regresar = new Button("Regresar"); botones.getChildren().addAll(regresar, boton); vbox.getChildren().add(botones); this.fondo = new HBox(); this.logo = new Image(new FileInputStream("src/GUI/Logo.png")); this.nombreE = new Text("Base de datos YMCA"); nombreE.setFont(Font.font(50)); fondo.getChildren().addAll(nombreE, new ImageView(logo)); fondo.setPadding(new Insets(5, 10, 0, 10)); fondo.setSpacing(600); this.fondos = new StackPane(); Image pp = new Image(new FileInputStream("src/GUI/Fondo.png")); ImageView imagen = new ImageView(pp); fondos.getChildren().addAll(imagen, fondo, vbox); this.escena = new Scene(fondos, 1200, 670, Color.BLACK); } public void mostrar(Stage stage){ stage.setTitle("Formulario Informacion personal"); stage.setScene(this.escena); stage.show(); } public TextField getFullNameTF() { return fullNameTF; } public ChoiceBox getTypeDocumentTF() { return typeDocumentTF; } public TextField getIdTF() { return IdTF; } public ChoiceBox getGenderTF() { return genderTF; } public DatePicker getDateBirthTF() { return dateBirthTF; } public TextField getMobileTF() { return mobileTF; } public TextField getPhoneTF() { return phoneTF; } public TextField getCitizenTF() { return citizenTF; } public TextField getEmailTF() { return emailTF; } public TextField getPassportTF() { return passportTF; } public ChoiceBox getSizeShirtTF() { return sizeShirtTF; } public TextField getCurrentOcupationTF() { return currentOcupationTF; } public TextField getFieldsStudyTF() { return fieldsStudyTF; } public TextField getUniversityTF() { return universityTF; } public ChoiceBox getGraduadoTF() { return graduadoTF; } public TextField getCurrentAdressTF() { return currentAdressTF; } public TextField getCurrentCityTF() { return currentCityTF; } public TextField getFullNameEmergencyContactTF() { return fullNameEmergencyContactTF; } public TextField getNumberEmergencyContactTF() { return numberEmergencyContactTF; } public TextField getEmailEmergencyContactTF() { return emailEmergencyContactTF; } public ChoiceBox getRelationshipTF() { return relationshipTF; } public Button getBoton() { return boton; } public Button getRegresar() { return regresar; } } <file_sep> import java.io.Serializable; import java.util.ArrayList; /* * 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. */ /** * * @author Asus */ public class EducacionContinuada extends Sede implements Serializable{ private String claseMasPopular; public EducacionContinuada(String claseMasPopular, String nombre, String direccion, int telefono, double areaConstruida, String tipoPrograma, String nombrePrograma, String descripcion) { super(nombre, direccion, telefono, areaConstruida, tipoPrograma, nombrePrograma, descripcion); this.claseMasPopular = claseMasPopular; } public String getClaseMasPopular() { return claseMasPopular; } public void setClaseMasPopular(String claseMasPopular) { this.claseMasPopular = claseMasPopular; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public int getTelefono() { return telefono; } public void setTelefono(int telefono) { this.telefono = telefono; } public double getAreaConstruida() { return areaConstruida; } public void setAreaConstruida(double areaConstruida) { this.areaConstruida = areaConstruida; } public ArrayList<ProgramaFormacion> getProgramas() { return programas; } public void setProgramas(ArrayList<ProgramaFormacion> programas) { this.programas = programas; } @Override public ArrayList darInformacion() { ArrayList informacion = super.darInformacion(); informacion.add(claseMasPopular); return informacion; } } <file_sep>package ModeloNegocio; /* * 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. */ /** * * @author Asus */ public class PersonalInformation { private String fullName; private String typeDocument; private String Id; private String gender; private String dateBirth; private String mobile; private String phone; private String citizen; private String email; private String passport; private String sizeShirt; private String currentOcupation; private String fieldsStudy; private String university; private boolean graduate; private String currentAdress; private String currentCity; private String fullNameEmergencyContact; private String numberEmergencyContact; private String emailEmergencyContact; private String relationship; public PersonalInformation(String fullName, String typeDocument, String Id, String gender, String dateBirth, String mobile, String email, String sizeShirt, String currentOcupation, String fieldsStudy, String university, boolean graduate, String currentAdress, String currentCity, String fullNameEmergencyContact, String numberEmergencyContact, String emailEmergencyContact, String relationship) { this.fullName = fullName; this.typeDocument = typeDocument; this.Id = Id; this.gender = gender; this.dateBirth = dateBirth; this.mobile = mobile; this.email = email; this.sizeShirt = sizeShirt; this.currentOcupation = currentOcupation; this.fieldsStudy = fieldsStudy; this.university = university; this.graduate = graduate; this.currentAdress = currentAdress; this.currentCity = currentCity; this.fullNameEmergencyContact = fullNameEmergencyContact; this.numberEmergencyContact = numberEmergencyContact; this.emailEmergencyContact = emailEmergencyContact; this.relationship = relationship; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getTypeDocument() { return typeDocument; } public void setTypeDocument(String typeDocument) { this.typeDocument = typeDocument; } public String getId() { return Id; } public void setId(String Id) { this.Id = Id; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getDateBirth() { return dateBirth; } public void setDateBirth(String dateBirth) { this.dateBirth = dateBirth; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCitizen() { return citizen; } public void setCitizen(String citizen) { this.citizen = citizen; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassport() { return passport; } public void setPassport(String passport) { this.passport = passport; } public String getSizeShirt() { return sizeShirt; } public void setSizeShirt(String sizeShirt) { this.sizeShirt = sizeShirt; } public String getCurrentOcupation() { return currentOcupation; } public void setCurrentOcupation(String currentOcupation) { this.currentOcupation = currentOcupation; } public String getFieldsStudy() { return fieldsStudy; } public void setFieldsStudy(String fieldsStudy) { this.fieldsStudy = fieldsStudy; } public String getUniversity() { return university; } public void setUniversity(String university) { this.university = university; } public boolean isGraduate() { return graduate; } public void setGraduate(boolean graduate) { this.graduate = graduate; } public String getCurrentAdress() { return currentAdress; } public void setCurrentAdress(String currentAdress) { this.currentAdress = currentAdress; } public String getCurrentCity() { return currentCity; } public void setCurrentCity(String currentCity) { this.currentCity = currentCity; } public String getFullNameEmergencyContact() { return fullNameEmergencyContact; } public void setFullNameEmergencyContact(String fullNameEmergencyContact) { this.fullNameEmergencyContact = fullNameEmergencyContact; } public String getNumberEmergencyContact() { return numberEmergencyContact; } public void setNumberEmergencyContact(String numberEmergencyContact) { this.numberEmergencyContact = numberEmergencyContact; } public String getEmailEmergencyContact() { return emailEmergencyContact; } public void setEmailEmergencyContact(String emailEmergencyContact) { this.emailEmergencyContact = emailEmergencyContact; } public String getRelationship() { return relationship; } public void setRelationship(String relationship) { this.relationship = relationship; } } <file_sep>/* * 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 GestionArchivos; import Proceso.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.util.*; /** * * @author Estudiante */ public class Gestion { private String ruta; public Gestion(String ruta) { this.ruta = ruta; } public String fechaToString(Fecha fecha){ String Fecha1 = (fecha.getDia()+" "+fecha.getMes()+" "+fecha.getAnnio()); return Fecha1; } public ArrayList<String> trazaProducto(Venta producto){ ArrayList<String> traza = new ArrayList<>(); String nomProdu = producto.getProductoDistribuido().getNombre(); traza.add(nomProdu); String retail = producto.getProductoDistribuido().getDestino(); traza.add(retail); String codVenta = String.valueOf(producto.getCodVenta()); traza.add(codVenta); String precio = String.valueOf(producto.getPrecio()); traza.add(precio); String DistributionCen = producto.getProductoDistribuido().getProductoProducido().getDestino(); traza.add(DistributionCen); String fechaLLega = fechaToString(producto.getProductoDistribuido().getFechaLlegada()); traza.add(fechaLLega); String fechaSali = fechaToString(producto.getProductoDistribuido().getFechaSalida()); traza.add(fechaSali); String Manufacturer = producto.getProductoDistribuido().getProductoProducido().getMateriaPrima().get(0).getDestino(); traza.add(Manufacturer); String fechaLLega1 = fechaToString(producto.getProductoDistribuido().getProductoProducido().getFechaLlegada()); traza.add(fechaLLega1); String fechaSali1 = fechaToString(producto.getProductoDistribuido().getProductoProducido().getFechaSalida()); traza.add(fechaSali1); String numLote = String.valueOf(producto.getProductoDistribuido().getProductoProducido().getNumLote()); traza.add(numLote); for(int i=0;i<producto.getProductoDistribuido().getProductoProducido().getMateriaPrima().size();i++){ String Farmer = producto.getProductoDistribuido().getProductoProducido().getMateriaPrima().get(i).getGranja(); traza.add(Farmer); String nombre1 = producto.getProductoDistribuido().getProductoProducido().getMateriaPrima().get(i).getNombre(); traza.add(nombre1); String destino1 = producto.getProductoDistribuido().getProductoProducido().getMateriaPrima().get(i).getDestino(); traza.add(destino1); String fechaLLega2 = fechaToString(producto.getProductoDistribuido().getProductoProducido().getMateriaPrima().get(i).getFechaLlegada()); traza.add(fechaLLega2); String fechaSali2 = fechaToString(producto.getProductoDistribuido().getProductoProducido().getMateriaPrima().get(i).getFechaSalida()); traza.add(fechaSali2); } traza.add(";"); return traza; } public boolean guardar(ArrayList<Venta> productos) throws IOException{ File archivo = new File(this.ruta); if(!archivo.exists()) archivo.createNewFile(); PrintStream salida = new PrintStream(archivo); for(Venta producto: productos){ ArrayList<String> traza = trazaProducto(producto); for(int i=0;i<traza.size();i++){ salida.println(traza.get(i)); salida.print(" "); } salida.print("\n"); } salida.flush(); salida.close(); return true; } } <file_sep>/* * 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 GUI.Formularios.FormulariosOpc2; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; /** * * @author Asus */ public class Opciones2 { private Scene escena; private VBox vbox; private Label descripcion; private Button b1; private Button b2; private Button b3; private Button regresar; private HBox fondo; private Image logo; private Text nombreE; private StackPane fondos; private HBox baseboton; public Opciones2() throws FileNotFoundException { this.vbox = new VBox(); vbox.setAlignment(Pos.CENTER); vbox.setSpacing(100); vbox.setPadding(new Insets(100, 0, 0, 0)); this.descripcion = new Label("Programas"); descripcion.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 30)); this.b1 = new Button("Programas de Colombia"); this.b2 = new Button("Programas de voluntariado"); this.b3 = new Button("Programas ICCP"); this.regresar = new Button("Regresar"); baseboton = new HBox(); baseboton.setAlignment(Pos.TOP_LEFT); baseboton.getChildren().add(regresar); baseboton.setPadding(new Insets(0,0,0,30)); vbox.getChildren().addAll(descripcion,b1,b2,b3,baseboton); this.fondo = new HBox(); this.logo = new Image(new FileInputStream("src/GUI/Logo.png")); this.nombreE = new Text("Base de datos YMCA"); nombreE.setFont(Font.font(50)); fondo.getChildren().addAll(nombreE, new ImageView(logo)); fondo.setPadding(new Insets(5, 10, 0, 10)); fondo.setSpacing(600); this.fondos = new StackPane(); Image pp = new Image(new FileInputStream("src/GUI/Fondo.png")); ImageView imagen = new ImageView(pp); fondos.getChildren().addAll(imagen, fondo, vbox); escena = new Scene(fondos, 1200, 670); } public void mostrar(Stage stage){ stage.setTitle("Menu opciones 1"); stage.setScene(this.escena); stage.show(); } public Button getB1() { return b1; } public Button getB2() { return b2; } public Button getB3() { return b3; } public Button getRegresar() { return regresar; } } <file_sep>/* * 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 GUI.Consultas.Opciones; import GUI.Consultas.ICCPAssign.ICCPAssignCVC; import GUI.Consultas.LocalVolunAssign.LocalVolunAssignCVC; import GUI.Consultas.PersInfo.PersIncoCVC; import GUI.Consultas.ProgramasColombia.ProgramsColombiaCVC; import GUI.Consultas.ProgramasICCP.ProgramsICCPC; import GUI.Consultas.ProgramasICCP.ProgramsICCPCVC; import GUI.Consultas.ProgramasVoluntariado.ProgramsVoluntariadoCVC; import GUI.Consultas.ProgramsAssignC.ProgramsAssignCVC; import GUI.Inicio.InicioVC; import GUI.Singleton; import ModeloNegocio.GestorPlataforma; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.Event; import javafx.event.EventHandler; /** * * @author Asus */ public class OpcionesCVC { private OpcionesC vista; private GestorPlataforma gestor; public OpcionesCVC(GestorPlataforma gestor) throws FileNotFoundException { this.gestor = gestor; this.vista = new OpcionesC(); vista.getSeleccionar().setOnMousePressed(new opcion()); vista.getRegresar().setOnMousePressed(new atras()); } public void mostrarVista(){ Singleton singleton = Singleton.getSingleton(); vista.mostrar(singleton.getStage()); } class opcion implements EventHandler<Event>{ @Override public void handle(Event event) { String opc = vista.getOpciones().getValue().toString(); switch(opc){ case "Informacion personal": PersIncoCVC pantalla = null; try { pantalla = new PersIncoCVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(OpcionesCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); break; case "Programas Colombia": ProgramsColombiaCVC pantalla1 = null; try { pantalla1 = new ProgramsColombiaCVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(OpcionesCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla1.mostrarVista(); break; case "Programas voluntariado": ProgramsVoluntariadoCVC pantalla2 = null; try { pantalla2 = new ProgramsVoluntariadoCVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(OpcionesCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla2.mostrarVista(); break; case "Programas ICCP": ProgramsICCPCVC pantalla3 = null; try { pantalla3 = new ProgramsICCPCVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(OpcionesCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla3.mostrarVista(); break; case "Asignacion programas Colombia": ProgramsAssignCVC pantalla4 = null; try { pantalla4 = new ProgramsAssignCVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(OpcionesCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla4.mostrarVista(); break; case "Asignacion programas voluntariado": LocalVolunAssignCVC pantalla5 = null; try { pantalla5 = new LocalVolunAssignCVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(OpcionesCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla5.mostrarVista(); break; case "Asignacion programas ICCP": ICCPAssignCVC pantalla6 = null; try { pantalla6 = new ICCPAssignCVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(OpcionesCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla6.mostrarVista(); break; } } } class atras implements EventHandler<Event>{ @Override public void handle(Event event) { InicioVC pantalla = null; try { pantalla = new InicioVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(PersIncoCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } } } <file_sep>import java.util.ArrayList; /* * 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. */ /** * Esta clase es para el control de la libreria * @author <NAME>, <NAME>, <NAME> * @version 24/09/2018 */ public class Libreria { private ArrayList<Estanteria> estanterias; ArrayList<EjemplaresDisponibles> catalogo; /** * Constructor de la libreria */ public Libreria() { this.estanterias = new ArrayList<>(); this.catalogo = new ArrayList<>(); } /** * Metodo que retorna las estanterias * @return devuelve las estanterias que hay en la libreria */ public ArrayList<Estanteria> getEstanterias() { return estanterias; } public void setEstanterias(ArrayList<Estanteria> estanterias) { this.estanterias = estanterias; } /** * Metodo que funciona como catalogo * @return devuelve los libros que hay, y la cantidad disponible de cada uno */ public ArrayList<EjemplaresDisponibles> getCatalogo() { return catalogo; } public void setCatalogo(ArrayList<EjemplaresDisponibles> catalogo) { this.catalogo = catalogo; } /** * Medodo para añadir una estanteria a la libreria * @param estanteria el parametro es una estanteria con todas sus caracteristicas */ public void addEstanteria(Estanteria estanteria){ estanterias.add(estanteria); } /** * Metodo para agregar un libro al catalogo * @param nuevoLibro el parametro es todas las caracteristicas del libro y sus ejemplares disponibles */ public void addLibro(EjemplaresDisponibles nuevoLibro){ catalogo.add(nuevoLibro); } /** * Metodo para saber la ubicacion de un libro * @param titulo el parametro es el titulo del libro a buscar * @return devuelve el numero de la estanteria donde esta el libro */ public int buscarUbicacionXTitulo(String titulo){ for(int i=0;i<catalogo.size();i++){ if(catalogo.get(i).getLibro().getTitulo().equals(titulo)) return catalogo.get(i).getLibro().getEstanteria(); } return 0; } /** * Metodo para conocer cuantoe ejemplares de un libro hay en la libreria * @param titulo el parametro es el titulo del libro a buscar * @return la cantidad de ejemplares disponibles que tiene la tienda */ public int ejemplaresDispobilesXTitulo(String titulo){ for(int i=0;i<catalogo.size();i++){ if(catalogo.get(i).getLibro().getTitulo().equals(titulo)) return catalogo.get(i).getEjemplaresDisponibles(); } return 0; } /** * Metodo para saber el origen del libro * @param titulo el parametro es el titulo del libro a buscar * @return devuelve si el libro es nuevo o usado */ public String origenXTitulo(String titulo){ for(int i=0;i<catalogo.size();i++){ if(catalogo.get(i).getLibro().getTitulo().equals(titulo)) return catalogo.get(i).getLibro().getOrigen(); } return null; } /** * Metodo para sabel el precio de un libro * @param titulo el parametro es el titulo del libro a buscar * @return devuelve el precio del libro, sin decuento */ public double precioXTitulo(String titulo){ for(int i=0;i<catalogo.size();i++){ if(catalogo.get(i).getLibro().getTitulo().equals(titulo)) return catalogo.get(i).getLibro().getPrecio().getPrecio(); } return 0; } }<file_sep>/* * 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 taller; /** * * @author Estudiante */ import java.util.ArrayList; public class Persona { private ArrayList<Carro> carros; public Persona() { this.carros = new ArrayList<>(); } public boolean addCarro(Carro c){ return this.carros.add(c); } public ArrayList<Carro> getCarros() { return carros; } public void setCarros(ArrayList<Carro> carros) { this.carros = carros; } } <file_sep>package Proceso; import java.util.*; /* * 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. */ /** * * @author Estudiante */ public class Retail extends Eslabon{ private ArrayList<Venta> produVenta; public Retail(String nombre, String descripcion, int latitud, int longitud) { super(nombre, descripcion, latitud, longitud); this.produVenta = new ArrayList<>(); } public boolean addProduVenta(float precio, int codVenta, Distribuido productoDistribuido){ return this.produVenta.add(new Venta(precio, codVenta, productoDistribuido)); } public ArrayList<Venta> getProduVenta() { return produVenta; } } <file_sep>/* * 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. */ /** * * @author Asus */ public class Main { public static void main(String[] args) { Airport aeropueto = new Airport("coco"); BookedFlight vuelo = new BookedFlight(2,"hoy","mañana"); vuelo.setFrom(aeropueto); System.out.println(vuelo.getFrom()); } } <file_sep>package Proceso; import java.util.*; /* * 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. */ /** * * @author Estudiante */ public class DistributionCenter extends Eslabon{ private ArrayList<Distribuido> produDistri; public DistributionCenter(String nombre, String descripcion, int latitud, int longitud) { super(nombre, descripcion, latitud, longitud); this.produDistri = new ArrayList<>(); } public boolean addProduDistri(Producido productoProducido, String nombre, String destino, Fecha fechaLlegada, Fecha fechaSalida){ return produDistri.add(new Distribuido(productoProducido, nombre, destino, fechaLlegada, fechaSalida)); } public ArrayList<Distribuido> getProduDistri() { return produDistri; } } <file_sep>/* * 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. */ /** * * @author Asus */ public class Libro { private String titulo; private String origen; private String editorial; private String genero; private int estanteria; private Precio precio; private Autor autor; public Libro(String titulo, String origen, String editorial, String genero, int estanteria, double precio, double descuento,String autor, String apellido) { this.titulo = titulo; this.origen = origen; this.editorial = editorial; this.genero = genero; this.estanteria = estanteria; this.precio = new Precio(precio,descuento); this.autor = new Autor(autor, apellido); } public String getTitulo() { return titulo; } public void setTitulo(String titulo) { this.titulo = titulo; } public String getOrigen() { return origen; } public void setOrigen(String origen) { this.origen = origen; } public String getEditorial() { return editorial; } public void setEditorial(String editorial) { this.editorial = editorial; } public String getGenero() { return genero; } public void setGenero(String genero) { this.genero = genero; } public int getEstanteria() { return estanteria; } public void setEstanteria(int estanteria) { this.estanteria = estanteria; } public Precio getPrecio() { return precio; } public void setPrecio(Precio precio) { this.precio = precio; } public Autor getAutor() { return autor; } public void setAutor(Autor autor) { this.autor = autor; } } <file_sep>libs.CopyLibs.classpath=\ ${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar libs.CopyLibs.displayName=CopyLibs Task libs.CopyLibs.prop-version=2.0 libs.MyLibrary.classpath=\ ${base}/CopyLibs/common-lang3.jar;\ ${base}/CopyLibs/commons-lang-2.6.jar;\ ${base}/CopyLibs/commons-logging-1.1.3.jar;\ ${base}/CopyLibs/hsqldb.jar;\ ${base}/CopyLibs/jackcess-2.1.11.jar;\ ${base}/CopyLibs/jackcess-3.0.0.jar;\ ${base}/CopyLibs/org-apache-commons-logging.jar;\ ${base}/CopyLibs/org-netbeans-modules-java-j2seproject-copylibstask.jar;\ ${base}/CopyLibs/ucanaccess-4.0.4.jar libs.MyLibrary.displayName=MyLibrary <file_sep>/* * 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 GUI.Formularios.FormularioICCPAssign; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; /** * * @author Asus */ public class FormICCPAssign { private Scene escena; private VBox vbox; private HBox hbox; private HBox hbox2; private HBox hbox3; private HBox hbox4; private Label informacion; private Label nombreParticipante; private TextField nombreParticipanteTF; private Label IdParticipante; private TextField IdParticipanteTF; private Label codigoCampamento; private TextField codigoCampamentoTF; private Label rol; private ChoiceBox rolTF; private Label fechaInicio; private DatePicker fechaInicioTF; private Label fechaFin; private DatePicker fechaFinTF; private Label calificacion; private TextField calificacionTF; private Label nota; private TextField notaTF; private Button boton; private Button regresar; private ObservableList names; private HBox fondo; private Image logo; private Text nombreE; private StackPane fondos; public FormICCPAssign() throws FileNotFoundException { this.vbox = new VBox(); this.hbox2 = new HBox(); this.hbox3 = new HBox(); this.hbox4 = new HBox(); vbox.setSpacing(90); vbox.setPadding(new Insets(100, 25, 25, 100)); Label info = new Label("Nota: Los campos con \"*\" son obligatorios"); info.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 15)); this.informacion = new Label("Introduzca la informacion de registro:", info); informacion.setContentDisplay(ContentDisplay.RIGHT); informacion.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 20)); this.nombreParticipanteTF = new TextField(); this.nombreParticipante = new Label("Nombre del participante: *", nombreParticipanteTF); nombreParticipante.setContentDisplay(ContentDisplay.RIGHT); this.IdParticipanteTF = new TextField(); this.IdParticipante = new Label("Identificacion del participante: *", IdParticipanteTF); IdParticipante.setContentDisplay(ContentDisplay.RIGHT); this.codigoCampamentoTF = new TextField(); this.codigoCampamento = new Label("Codigo del campamento: *", codigoCampamentoTF); codigoCampamento.setContentDisplay(ContentDisplay.RIGHT); names = FXCollections.observableArrayList(); names.add("Consejero"); names.add("<NAME>"); names.add("Salvavidas"); this.rolTF = new ChoiceBox(names); this.rol = new Label("Rol", rolTF); rol.setContentDisplay(ContentDisplay.RIGHT); this.fechaInicioTF = new DatePicker(); this.fechaInicio = new Label("Fecha de incio: *", fechaInicioTF); fechaInicio.setContentDisplay(ContentDisplay.RIGHT); this.fechaFinTF = new DatePicker(); this.fechaFin = new Label("Fecha de fin: *", fechaFinTF); fechaFin.setContentDisplay(ContentDisplay.RIGHT); this.calificacionTF = new TextField(); this.calificacion = new Label("Calificacion: *", calificacionTF); calificacion.setContentDisplay(ContentDisplay.RIGHT); this.notaTF = new TextField(); this.nota = new Label("Agregar una nota: ", notaTF); nota.setContentDisplay(ContentDisplay.RIGHT); this.hbox = new HBox(); hbox.setSpacing(100); this.boton = new Button("Agregar"); this.regresar = new Button("Regresar"); hbox.getChildren().addAll(regresar, boton); hbox2.getChildren().addAll(nombreParticipante, IdParticipante); hbox2.setSpacing(50); hbox3.getChildren().addAll(codigoCampamento, rol, fechaInicio); hbox3.setSpacing(75); hbox4.getChildren().addAll(fechaFin ,calificacion, nota); hbox4.setSpacing(50); vbox.getChildren().addAll(informacion, hbox2,hbox3,hbox4,hbox); this.fondo = new HBox(); this.logo = new Image(new FileInputStream("src/GUI/Logo.png")); this.nombreE = new Text("Base de datos YMCA"); nombreE.setFont(Font.font(50)); fondo.getChildren().addAll(nombreE, new ImageView(logo)); fondo.setPadding(new Insets(5, 10, 0, 10)); fondo.setSpacing(600); this.fondos = new StackPane(); Image pp = new Image(new FileInputStream("src/GUI/Fondo.png")); ImageView imagen = new ImageView(pp); fondos.getChildren().addAll(imagen, fondo, vbox); escena = new Scene(fondos, 1200, 670); } public void mostrar(Stage stage){ stage.setTitle("Formulario 1"); stage.setScene(this.escena); stage.show(); } public TextField getNombreParticipanteTF() { return nombreParticipanteTF; } public TextField getIdParticipanteTF() { return IdParticipanteTF; } public TextField getCodigoCampamentoTF() { return codigoCampamentoTF; } public DatePicker getFechaInicioTF() { return fechaInicioTF; } public DatePicker getFechaFinTF() { return fechaFinTF; } public ChoiceBox getRolTF() { return rolTF; } public TextField getCalificacionTF() { return calificacionTF; } public TextField getNotaTF() { return notaTF; } public Button getBoton() { return boton; } public Button getRegresar() { return regresar; } } <file_sep>import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /* * 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. */ /** * * @author Asus */ public class Main { public static void main(String[] args) { Scanner leer = new Scanner(System.in); System.out.println("Bienvenido, aqui podras crear tu propia universidad y administrarla\n1. Ingresa el nombre de la universidad: "); String nombre = leer.next(); Universidad uni = new Universidad(nombre); File guardarTexto = new File("guardarTexto.txt"); if(!guardarTexto.exists()){ try { guardarTexto.createNewFile(); ObjectOutputStream objeto = new ObjectOutputStream(new FileOutputStream(guardarTexto)); objeto.writeObject(uni); objeto.close(); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } }else{ try { ObjectInputStream entrada = new ObjectInputStream(new FileInputStream(guardarTexto)); uni = (Universidad)entrada.readObject(); } catch (FileNotFoundException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException | ClassNotFoundException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } int opc; do{ System.out.println("Este es tu menu de opciones, elige que quieres hacer: "); System.out.println("1. Agregar una nueva sede\n2. Administrar una sede\n3. Eliminar una sede\n4. Obtener informacion de una sede\n5. Obtener informacion de todas las sedes\n0. Salir del menu"); opc = leer.nextInt(); switch(opc){ case 1: System.out.println("Elige el tipo de sede que deseas crear: \n1. Profesional\n2. Tecnologica\n3. Educacion Continuada"); int tipoSede = leer.nextInt(); System.out.println("Ingresa el nombre de la sede: "); String nombreSede = leer.next(); System.out.println("Ingresa la direccion de la sede: "); String direccion = leer.next(); System.out.println("Ingresa el numero de telefono de la sede: "); int telefonoSede = leer.nextInt(); System.out.println("Ingrese el Area en metros cuadrados construidos de la sede: "); double AreaConsSede = leer.nextDouble(); switch(tipoSede){ case 1: System.out.println("Elige el tipo de programa para tu sede:\n1. profesional\n2. tecnologico\n3. educacion continuada "); int opcPro = leer.nextInt(); System.out.println("Ingrese el nombre del programa: "); String nomPrograma = leer.next(); System.out.println("Ingrese alguna descripcion del programa: "); String descripcion = leer.next(); System.out.println("Si el programa que ingreso es de alta calidad ingrese 1, de lo contrario ingrese 0: "); int num = leer.nextInt(); String tipoPrograma = null; if(opcPro==1){ tipoPrograma = "profesional"; }if(opcPro==2){ tipoPrograma = "profesional"; }if(opcPro==3){ tipoPrograma = "profesional"; } uni.addSedePro(num, nombreSede, direccion, telefonoSede, AreaConsSede, tipoPrograma, nomPrograma, descripcion); break; case 2: System.out.println("Ingrese el nombre del programa: "); String nomPrograma1 = leer.next(); System.out.println("Ingrese alguna descripcion del programa: "); String descripcion1 = leer.next(); System.out.println("Ingrese el numero de estudiantes de la sede: "); int num2 = leer.nextInt(); uni.addSedeTec(num2, nombreSede, direccion, telefonoSede, AreaConsSede, "tecnologico", nomPrograma1, descripcion1); break; case 3: System.out.println("Ingrese el nombre del programa: "); String nomPrograma2 = leer.next(); System.out.println("Ingrese alguna descripcion del programa: "); String descripcion2 = leer.next(); uni.addSedeEdCon(nomPrograma2, nombreSede, direccion, telefonoSede, AreaConsSede, "educacion continuada", nomPrograma2, descripcion2); break; } break; case 2: int opcion2; do{ System.out.println("Ingresa el nombre de la sede a administrar: "); String nombreSedeAdm = leer.next(); Sede sedeAdm = uni.buscarSede(nombreSedeAdm); System.out.println("Aqui esta el nuevo menu para administrar una sede: \n1. Cambiar el nombre de la sede\n2. Cambiar la direccion de la sede\n3. Cambiar numero de telefono" + " \n4. Cambiar area construida\n5. Administrar programas"); opcion2 = leer.nextInt(); switch(opcion2){ case 1: System.out.println("Ingrese el nuevo nombre de la sede: "); String nuevoNombre = leer.next(); uni.buscarSede(sedeAdm.getNombre()).setNombre(nuevoNombre); break; case 2: System.out.println("Ingrese la nueva direccion de la sede: "); String nuevaDir = leer.next(); uni.buscarSede(sedeAdm.getNombre()).setDireccion(nuevaDir); break; case 3: System.out.println("Ingrese el nuevo telefono de la sede: "); int nuevoTel = leer.nextInt(); uni.buscarSede(sedeAdm.getNombre()).setTelefono(nuevoTel); break; case 4: System.out.println("Ingrese la nueva area construida de la sede: "); double nueAreaCons = leer.nextDouble(); uni.buscarSede(sedeAdm.getNombre()).setAreaConstruida(nueAreaCons); break; case 5: int opcion3; do{ System.out.println("Desde aqui puedes administrar los programas de la sede: \n1. Crear programa\n2. Borrar programa\n3. Cambiar nombre al programa\n4. Cambiar descripcion al programa"); opcion3 = leer.nextInt(); switch(opcion3){ case 1: System.out.println("Ingrese el nombre del programa: "); String nomPrograma = leer.next(); System.out.println("Ingrese la descripcion del programa: "); String descripPrograma = leer.next(); System.out.println("Ingrese el tipo del programa: "); String tipoPrograma = leer.next(); uni.buscarSede(sedeAdm.getNombre()).agregarPrograma(tipoPrograma, nomPrograma, descripPrograma); break; case 2: System.out.println("Ingrese el nombre del programa a eliminar: "); String nomProgramaBorrar = leer.next(); uni.buscarSede(sedeAdm.getNombre()).eliminarPrograma(nomProgramaBorrar); break; case 3: System.out.println("Ingrese el nombre del programa que va a cambiar: "); String nomPrograCam = leer.next(); System.out.println("Ingrese el nuevo nombre: "); String nuevoNombrePrograma = leer.next(); uni.buscarSede(sedeAdm.getNombre()).getPrograma(nomPrograCam).setNombre(nuevoNombrePrograma); break; case 4: System.out.println("Ingrese el nombre del programa que va a cambiar: "); String nomPrograCam1 = leer.next(); System.out.println("Ingrese la nueva descripcion: "); String nuevaDescPrograma = leer.next(); uni.buscarSede(sedeAdm.getNombre()).getPrograma(nomPrograCam1).setDescripcion(nuevaDescPrograma); break; } break; }while(opcion3>0 && opcion3<5); } }while(opcion2>0 && opcion2<6); break; case 3: System.out.println("Ingrese el nombre de la sede que quiere borrar: "); String nombreSedeBorrar = leer.next(); uni.deleteSede(nombreSedeBorrar); break; case 4: System.out.println("Ingrese el nombre de la sede de la cual quiere obtener la informacion: "); String nomSedeInf = leer.next(); ArrayList inf = new ArrayList(); inf = uni.buscarSede(nomSedeInf).darInformacion(); for(int i=0;i<inf.size();i++){ System.out.println(inf.get(i)); } break; case 5: for(int i=0;i<uni.getSedes().size();i++){ ArrayList inf2 = new ArrayList(); inf2 = uni.getSedes().get(i).darInformacion(); for(int j=0;j<inf2.size();j++){ System.out.println(inf2.get(j)); } } break; } }while(opc>0 && opc<6); } } <file_sep>import java.io.Serializable; import java.util.*; /* * 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. */ /** * * @author Asus */ public abstract class Sede implements Serializable{ protected String nombre; protected String direccion; protected int telefono; protected double areaConstruida; protected ArrayList<ProgramaFormacion> programas; public Sede(String nombre, String direccion, int telefono, double areaConstruida,String tipoPrograma, String nombrePrograma, String descripcion) { this.nombre = nombre; this.direccion = direccion; this.telefono = telefono; this.areaConstruida = areaConstruida; this.programas = new ArrayList<>(); programas.add(new ProgramaFormacion(tipoPrograma, nombrePrograma, descripcion)); } public ArrayList darInformacion(){ ArrayList informacion = new ArrayList<>(); informacion.add(nombre); informacion.add(direccion); informacion.add(telefono); informacion.add(areaConstruida); for (int i = 0; i<programas.size(); i++) { informacion.add(programas.get(i).getNombre()); informacion.add(programas.get(i).getDescripcion()); } return informacion; } public boolean agregarPrograma(String tipoPrograma, String nombrePrograma, String descripcion){ return programas.add(new ProgramaFormacion(tipoPrograma, nombrePrograma, descripcion)); } public boolean eliminarPrograma(String nombrePrograma){ for(int i=0;i<programas.size();i++){ if(nombrePrograma.equals(programas.get(i).getNombre())) programas.set(i, null); } return false; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public int getTelefono() { return telefono; } public void setTelefono(int telefono) { this.telefono = telefono; } public double getAreaConstruida() { return areaConstruida; } public void setAreaConstruida(double areaConstruida) { this.areaConstruida = areaConstruida; } public ArrayList<ProgramaFormacion> getProgramas() { return programas; } public void setProgramas(ArrayList<ProgramaFormacion> programas) { this.programas = programas; } public ProgramaFormacion getPrograma(String nomPrograma){ for(int i=0;i<programas.size();i++){ if(programas.get(i).getNombre().equals(nomPrograma)) return programas.get(i); } return null; } } <file_sep>import java.util.*; import java.util.logging.Logger; /* * 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. */ /** * * @author Asus */ public class Organizacion { private String nombre; private ArrayList<Estudiante> estudiantes; private ArrayList<Premio> premios; private ArrayList<RegistroCarta> cartas; public Organizacion(String nombre) { this.nombre = nombre; } public boolean addPremio(Premio premio){ return this.premios.add(premio); } public boolean addEstudiante(Estudiante estudiante){ return this.estudiantes.add(estudiante); } public boolean addCarta(RegistroCarta registroCarta){ return this.cartas.add(registroCarta); } public ArrayList<RegistroCarta> getCartas() { return cartas; } } <file_sep>/* * 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 GUI.Consultas.Resultado; import GUI.Consultas.Opciones.*; import GUI.Consultas.ICCPAssign.ICCPAssignCVC; import GUI.Consultas.LocalVolunAssign.LocalVolunAssignCVC; import GUI.Consultas.PersInfo.PersIncoCVC; import GUI.Consultas.ProgramasColombia.ProgramsColombiaCVC; import GUI.Consultas.ProgramasICCP.ProgramsICCPC; import GUI.Consultas.ProgramasICCP.ProgramsICCPCVC; import GUI.Consultas.ProgramasVoluntariado.ProgramsVoluntariadoCVC; import GUI.Consultas.ProgramsAssignC.ProgramsAssignCVC; import GUI.Inicio.InicioVC; import GUI.Singleton; import ModeloNegocio.GestorPlataforma; import ModeloNegocio.PersonalInformation; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.Event; import javafx.event.EventHandler; /** * * @author Asus */ public class ResultadoVC { private Resultado vista; private GestorPlataforma gestor; public ResultadoVC(GestorPlataforma gestor, ArrayList<PersonalInformation> personas) throws FileNotFoundException { this.gestor = gestor; this.vista = new Resultado(personas); vista.getRegresar().setOnMousePressed(new atras()); } public void mostrarVista(){ Singleton singleton = Singleton.getSingleton(); vista.mostrar(singleton.getStage()); } class opcion implements EventHandler<Event>{ @Override public void handle(Event event) { } } class atras implements EventHandler<Event>{ @Override public void handle(Event event) { InicioVC pantalla = null; try { pantalla = new InicioVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(PersIncoCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } } } <file_sep>/* * 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 GUI.Consultas.ICCPAssign; import GUI.Consultas.ProgramsAssignC.*; import GUI.Consultas.ProgramasColombia.*; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; /** * * @author Asus */ public class ICCPAssignC { private Scene escena; private VBox vbox; private HBox hbox; private RadioButton namePers; private TextField namePersTF; private RadioButton idPers; private TextField idPersTF; private RadioButton nameCamp; private TextField nameCampTF; private HBox hbox2; private RadioButton rol; private TextField rolTF; private RadioButton calification; private TextField calificationTF; private RadioButton note; private TextField noteTF; private HBox hbox3; private RadioButton fechaIni; private TextField fechaIniTF; private RadioButton fechaFin; private TextField fechaFinTF; private Button consultar; private Button atras; private HBox menu; private ComboBox<String> opciones; private Button seleccionar; private HBox fondo; private Label label; private Image logo; private Text nombreE; private StackPane fondos; public ICCPAssignC() throws FileNotFoundException { this.vbox = new VBox(); vbox.setSpacing(60); vbox.setPadding(new Insets(100, 0, 0, 20)); this.opciones = new ComboBox<>(); opciones.getItems().addAll("Informacion personal","Programas Colombia", "programas voluntariado","Programas ICCP", "Asignacion programas Colombia" ,"Asignacion programas voluntariado","Asignacion programas ICCP"); this.seleccionar = new Button("Seleccionar tabla"); this.atras = new Button("Atras"); opciones.setPromptText("Asignacion programas Colombia"); this.menu = new HBox(); menu.setSpacing(100); Label info = new Label("Ingrese la tabla en la cual quiere hacer la consulta: ", opciones); info.setContentDisplay(ContentDisplay.RIGHT); menu.getChildren().addAll(info, seleccionar, atras); Label info2= new Label("Seleccione los atributos de la consulta, y sus criterios de busqueda: "); vbox.getChildren().addAll(menu, info2); this.hbox = new HBox(); hbox.setSpacing(20); this.namePers = new RadioButton("Nombre de la persona: "); this.namePersTF = new TextField(); this.idPers = new RadioButton("Id de la persona: "); this.idPersTF = new TextField(); this.nameCamp = new RadioButton("Nombre del campamento: "); this.nameCampTF = new TextField(); hbox.getChildren().addAll(namePers,namePersTF,idPers,idPersTF, nameCamp,nameCampTF); vbox.getChildren().add(hbox); this.hbox2 = new HBox(); hbox2.setSpacing(20); this.rol = new RadioButton("Rol: "); this.rolTF = new TextField(); this.calification = new RadioButton("Calificacion: "); this.calificationTF = new TextField(); this.note = new RadioButton("Nota: "); this.noteTF = new TextField(); hbox2.getChildren().addAll(rol, rolTF,calification,calificationTF,note,noteTF); vbox.getChildren().add(hbox2); this.hbox3 = new HBox(); hbox3.setSpacing(20); this.fechaIni = new RadioButton("Fecha Inicio: "); this.fechaIniTF = new TextField(); this.fechaFin = new RadioButton("Fecha Fin: "); this.fechaFinTF = new TextField(); hbox3.getChildren().addAll(fechaIni, fechaIniTF, fechaFin, fechaFinTF); vbox.getChildren().add(hbox3); this.consultar = new Button("Consultar"); vbox.getChildren().add(consultar); this.fondo = new HBox(); this.logo = new Image(new FileInputStream("src/GUI/Logo.png")); this.nombreE = new Text("Base de datos YMCA"); nombreE.setFont(Font.font(50)); fondo.getChildren().addAll(nombreE, new ImageView(logo)); fondo.setPadding(new Insets(5, 10, 0, 10)); fondo.setSpacing(600); this.fondos = new StackPane(); Image pp = new Image(new FileInputStream("src/GUI/Fondo.png")); ImageView imagen = new ImageView(pp); fondos.getChildren().addAll(imagen, fondo, vbox); escena = new Scene(fondos, 1200, 670); } public void mostrar(Stage stage) { stage.setTitle("Consulta"); stage.setScene(this.escena); stage.show(); } public Button getSeleccionar() { return seleccionar; } public ComboBox<String> getOpciones() { return opciones; } public RadioButton getNameCamp() { return nameCamp; } public TextField getNameCampTF() { return nameCampTF; } public RadioButton getNamePers() { return namePers; } public TextField getNamePersTF() { return namePersTF; } public RadioButton getIdPers() { return idPers; } public TextField getIdPersTF() { return idPersTF; } public RadioButton getRol() { return rol; } public TextField getRolTF() { return rolTF; } public RadioButton getCalification() { return calification; } public TextField getCalificationTF() { return calificationTF; } public RadioButton getNote() { return note; } public TextField getNoteTF() { return noteTF; } public Button getConsultar() { return consultar; } public Button getAtras() { return atras; } public Text getNombreE() { return nombreE; } public RadioButton getFechaIni() { return fechaIni; } public TextField getFechaIniTF() { return fechaIniTF; } public RadioButton getFechaFin() { return fechaFin; } public TextField getFechaFinTF() { return fechaFinTF; } } <file_sep>/* * 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 GUI.Consultas.PersInfo; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ComboBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; /** * * @author Asus */ public class PersInfoC { private Scene escena; private VBox vbox; private HBox hbox; private RadioButton name; private TextField nameTF; private RadioButton id; private TextField idTF; private RadioButton typeDocument; private TextField typeDocumentTF; private RadioButton gender; private TextField genderTF; private HBox hbox2; private RadioButton dateBirth; private TextField dateBirthTF; private RadioButton mobile; private TextField mobileTF; private RadioButton phone; private TextField phoneTF; private RadioButton citizen; private TextField citizenTF; private HBox hbox3; private RadioButton email; private TextField emailTF; private RadioButton sizeShirt; private TextField sizeShirtTF; private RadioButton currentOcu; private TextField currentOcuTF; private RadioButton fieldsStudy; private TextField fieldsStudyTF; private HBox hbox4; private RadioButton university; private TextField universityTF; private RadioButton graduate; private TextField graduateTF; private RadioButton currentAddress; private TextField currentAddressTF; private RadioButton currentCity; private TextField currentCityTF; private HBox hbox5; private RadioButton nameEmCon; private TextField nameEmConTF; private RadioButton numberEmCon; private TextField numberEmConTF; private RadioButton emailEmCon; private TextField emailEmConTF; private RadioButton relationship; private TextField relationshipTF; private Button consultar; private HBox menu; private ComboBox<String> opciones; private Button seleccionar; private Button atras; private HBox fondo; private Label label; private Image logo; private Text nombreE; private StackPane fondos; public PersInfoC() throws FileNotFoundException { this.vbox = new VBox(); vbox.setSpacing(50); vbox.setPadding(new Insets(100, 0, 0, 20)); this.opciones = new ComboBox<>(); opciones.getItems().addAll("Informacion personal","Programas Colombia", "programas voluntariado","Programas ICCP", "Asignacion programas Colombia" ,"Asignacion programas voluntariado","Asignacion programas ICCP"); this.seleccionar = new Button("Seleccionar tabla"); this.atras = new Button("Atras"); opciones.setPromptText("Informacion personal"); this.menu = new HBox(); menu.setSpacing(100); Label info = new Label("Ingrese la tabla en la cual quiere hacer la consulta: ", opciones); info.setContentDisplay(ContentDisplay.RIGHT); menu.getChildren().addAll(info, seleccionar,atras); Label info2= new Label("Seleccione los atributos de la consulta, y sus criterios de busqueda: "); vbox.getChildren().addAll(menu, info2); this.hbox = new HBox(); hbox.setSpacing(20); this.name = new RadioButton("Nombre completo: "); this.nameTF = new TextField(); this.id = new RadioButton("Id: "); this.idTF = new TextField(); this.typeDocument = new RadioButton("Tipo de documento: "); this.typeDocumentTF = new TextField(); this.gender = new RadioButton("Genero: "); this.genderTF = new TextField(); hbox.getChildren().addAll(name,nameTF,id,idTF,typeDocument,typeDocumentTF,gender,genderTF); vbox.getChildren().add(hbox); this.hbox2 = new HBox(); hbox2.setSpacing(20); this.dateBirth = new RadioButton("Fecha nacimiento: "); this.dateBirthTF = new TextField(); this.mobile = new RadioButton("Celular: "); this.mobileTF = new TextField(); this.phone = new RadioButton("Telefono: "); this.phoneTF = new TextField(); this.citizen = new RadioButton("Nacionalidad: "); this.citizenTF = new TextField(); hbox2.getChildren().addAll(dateBirth,dateBirthTF,mobile,mobileTF,phone,phoneTF,citizen,citizenTF); vbox.getChildren().add(hbox2); this.hbox3 = new HBox(); hbox3.setSpacing(20); this.email = new RadioButton("Email: "); this.emailTF = new TextField(); this.sizeShirt = new RadioButton("Talla camisa: "); this.sizeShirtTF = new TextField(); this.currentOcu = new RadioButton("Ocupacion actual: "); this.currentOcuTF = new TextField(); this.fieldsStudy = new RadioButton("Carrera: "); this.fieldsStudyTF = new TextField(); hbox3.getChildren().addAll(email, emailTF,sizeShirt,sizeShirtTF,currentOcu,currentOcuTF, fieldsStudy,fieldsStudyTF); vbox.getChildren().add(hbox3); this.hbox4 = new HBox(); hbox4.setSpacing(20); this.university = new RadioButton("Universidad: "); this.universityTF = new TextField(); this.graduate = new RadioButton("Graduado: "); this.graduateTF = new TextField(); this.currentAddress = new RadioButton("Direccion acutal: "); this.currentAddressTF = new TextField(); this.currentCity = new RadioButton("Ciudad actual: "); this.currentCityTF = new TextField(); hbox4.getChildren().addAll(university,universityTF,graduate,graduateTF,currentAddress,currentAddressTF,currentCity, currentCityTF); vbox.getChildren().add(hbox4); this.hbox5 = new HBox(); hbox5.setSpacing(5); this.nameEmCon = new RadioButton("Nombre Con. Emer.: "); this.nameEmConTF = new TextField(); this.numberEmCon = new RadioButton("Numero Con. Emer.: "); this.numberEmConTF = new TextField(); this.emailEmCon = new RadioButton("Email Con. Emer.: "); this.emailEmConTF = new TextField(); this.relationship = new RadioButton("Relacion Con. Emer.: "); this.relationshipTF = new TextField(); hbox5.getChildren().addAll(nameEmCon,nameEmConTF,numberEmCon,numberEmConTF,emailEmCon,emailEmConTF,relationship,relationshipTF); vbox.getChildren().add(hbox5); this.consultar = new Button("Consultar"); vbox.getChildren().add(consultar); this.fondo = new HBox(); this.logo = new Image(new FileInputStream("src/GUI/Logo.png")); this.nombreE = new Text("Base de datos YMCA"); nombreE.setFont(Font.font(50)); fondo.getChildren().addAll(nombreE, new ImageView(logo)); fondo.setPadding(new Insets(5, 10, 0, 10)); fondo.setSpacing(600); this.fondos = new StackPane(); Image pp = new Image(new FileInputStream("src/GUI/Fondo.png")); ImageView imagen = new ImageView(pp); fondos.getChildren().addAll(imagen, fondo, vbox); escena = new Scene(fondos, 1200, 670); } public void mostrar(Stage stage) { stage.setTitle("Consulta"); stage.setScene(this.escena); stage.show(); } public Button getSeleccionar() { return seleccionar; } public Button getAtras() { return atras; } public ComboBox<String> getOpciones() { return opciones; } public RadioButton getName() { return name; } public TextField getNameTF() { return nameTF; } public RadioButton getId() { return id; } public TextField getIdTF() { return idTF; } public RadioButton getTypeDocument() { return typeDocument; } public TextField getTypeDocumentTF() { return typeDocumentTF; } public RadioButton getGender() { return gender; } public TextField getGenderTF() { return genderTF; } public RadioButton getDateBirth() { return dateBirth; } public TextField getDateBirthTF() { return dateBirthTF; } public RadioButton getMobile() { return mobile; } public TextField getMobileTF() { return mobileTF; } public RadioButton getPhone() { return phone; } public TextField getPhoneTF() { return phoneTF; } public RadioButton getCitizen() { return citizen; } public TextField getCitizenTF() { return citizenTF; } public HBox getHbox3() { return hbox3; } public RadioButton getEmail() { return email; } public TextField getEmailTF() { return emailTF; } public RadioButton getSizeShirt() { return sizeShirt; } public TextField getSizeShirtTF() { return sizeShirtTF; } public RadioButton getCurrentOcu() { return currentOcu; } public TextField getCurrentOcuTF() { return currentOcuTF; } public RadioButton getFieldsStudy() { return fieldsStudy; } public TextField getFieldsStudyTF() { return fieldsStudyTF; } public RadioButton getUniversity() { return university; } public TextField getUniversityTF() { return universityTF; } public RadioButton getGraduate() { return graduate; } public TextField getGraduateTF() { return graduateTF; } public RadioButton getCurrentAddress() { return currentAddress; } public TextField getCurrentAddressTF() { return currentAddressTF; } public RadioButton getCurrentCity() { return currentCity; } public TextField getCurrentCityTF() { return currentCityTF; } public RadioButton getNameEmCon() { return nameEmCon; } public TextField getNameEmConTF() { return nameEmConTF; } public RadioButton getNumberEmCon() { return numberEmCon; } public TextField getNumberEmConTF() { return numberEmConTF; } public RadioButton getEmailEmCon() { return emailEmCon; } public TextField getEmailEmConTF() { return emailEmConTF; } public RadioButton getRelationship() { return relationship; } public TextField getRelationshipTF() { return relationshipTF; } public Button getConsultar() { return consultar; } public HBox getMenu() { return menu; } } <file_sep>package GUI; /* * 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. */ import javafx.stage.Stage; /** * * @author Estudiante */ public class Singleton { private Stage stage; private static Singleton singleton = null; public static Singleton getSingleton(){ if(singleton == null) singleton = new Singleton(); return singleton; } public Stage getStage() { return stage; } public void setStage(Stage stage) { this.stage = stage; } /* Label info = new Label("Nota: Los campos con \"*\" son obligatorios"); info.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 15)); this.informacion = new Label("Introduzca la informacion del campamento:", info); informacion.setContentDisplay(ContentDisplay.RIGHT); private HBox fondo; private Image logo; private Text nombreE; private StackPane fondos; this.fondo = new HBox(); this.logo = new Image(new FileInputStream("src/GUI/Logo.png")); this.nombreE = new Text("Base de datos YMCA"); nombreE.setFont(Font.font(50)); fondo.getChildren().addAll(nombreE, new ImageView(logo)); fondo.setPadding(new Insets(5, 10, 0, 10)); fondo.setSpacing(600); this.fondos = new StackPane(); Image pp = new Image(new FileInputStream("src/GUI/Fondo.png")); ImageView imagen = new ImageView(pp); fondos.getChildren().addAll(imagen, fondo, hbox); escena = new Scene(fondos, 1200, 670); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Debe llenar todos los campos que se encuentran como obligatorios"); alert.show(); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmacion"); alert.setHeaderText("La informacion ha sido registrada"); alert.show(); */ } <file_sep>/* * 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 GUI.Estadisticas.TipoDocumento; import GUI.Estadisticas.Genero.*; import GUI.Estadisticas.Torta.*; import GUI.Consultas.Opciones.OpcionesCVC; import GUI.Consultas.PersInfo.PersIncoCVC; import GUI.Consultas.ProgramsAssignC.ProgramsAssignC; import GUI.Consultas.ProgramsAssignC.ProgramsAssignCVC; import GUI.Inicio.InicioVC; import GUI.Singleton; import ModeloNegocio.GestorPlataforma; import java.io.FileNotFoundException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.Event; import javafx.event.EventHandler; /** * * @author diego */ public class TipoDocumentoVC { private GestorPlataforma gestor; private TipoDocumento vista; public TipoDocumentoVC(GestorPlataforma gestor,int s,int m,int l, int xl, int xxl) throws FileNotFoundException { this.gestor = gestor; this.vista = new TipoDocumento(s,m,l,xl,xxl); this.vista.getAtras().setOnMousePressed(new TipoDocumentoVC.atras()); } public void mostrarVista(){ Singleton singleton = Singleton.getSingleton(); vista.mostrar(singleton.getStage()); } class atras implements EventHandler<Event>{ @Override public void handle(Event event) { InicioVC pantalla = null; try { pantalla = new InicioVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(PersIncoCVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } } } <file_sep>/* * 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. */ /** * * @author Asus */ public class EjemplaresDisponibles { private int ejemplaresDisponibles; private Libro libro; public EjemplaresDisponibles(int ejemplaresDisponibles, Libro libro) { this.ejemplaresDisponibles = ejemplaresDisponibles; this.libro = libro; } public int getEjemplaresDisponibles() { return ejemplaresDisponibles; } public void setEjemplaresDisponibles(int ejemplaresDisponibles) { this.ejemplaresDisponibles = ejemplaresDisponibles; } public Libro getLibro() { return libro; } public void setLibro(Libro libro) { this.libro = libro; } } <file_sep>package Proceso; import java.util.*; /* * 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. */ /** * * @author Estudiante */ public class Farmer extends Eslabon{ private ArrayList<MateriaPrima> produCulti; public Farmer(String nombre, String descripcion, int latitud, int longitud) { super(nombre, descripcion, latitud, longitud); this.produCulti = new ArrayList<>(); } public boolean addProduCulti(String nombre, String destino, Fecha fechaLlegada, Fecha fechaSalida){ String granja = super.nombre; return produCulti.add(new MateriaPrima(nombre, destino, fechaLlegada, fechaSalida, granja)); } public ArrayList<MateriaPrima> getProduCulti() { return produCulti; } } <file_sep>/* * 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. */ /** * * @author Asus */ public class Precio { private double precio; private double Descuento; public Precio(double precio, double Descuento) { this.precio = precio; this.Descuento = Descuento; } public double getPrecio() { return precio; } public void setPrecio(double precio) { this.precio = precio; } public double getDescuento() { return Descuento; } public void setDescuento(double Descuento) { this.Descuento = Descuento; } public double precioCompra(){ double precio = this.precio; return precio*(100-Descuento)/100; } } <file_sep>package ModeloNegocio; import java.util.ArrayList; /* * 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. */ /** * * @author Asus */ public class LocalVolunteerAssignment extends Assignment{ private String IdPersona; private String nombrePersona; private String nombreCampamento; public LocalVolunteerAssignment(String IdPersona, String nombrePersona, String nombreCampamento, String role, String calification, String note) { super(role, calification, note); this.IdPersona = IdPersona; this.nombrePersona = nombrePersona; this.nombreCampamento = nombreCampamento; } public String getIdPersona() { return IdPersona; } public void setIdPersona(String IdPersona) { this.IdPersona = IdPersona; } public String getNombrePersona() { return nombrePersona; } public void setNombrePersona(String nombrePersona) { this.nombrePersona = nombrePersona; } public String getNombreCampamento() { return nombreCampamento; } public void setNombreCampamento(String nombreCampamento) { this.nombreCampamento = nombreCampamento; } } <file_sep>/* * 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 GUI.Formularios.FormularioICCPAssign; import GUI.Formularios.FormularioCampsICCP.*; import GUI.Formularios.FormulariosOpc.OpcionesVC; import GUI.Formularios.FormulariosOpc2.Opciones2VC; import GUI.Formularios.FormulariosOpc3.Opciones3VC; import GUI.Singleton; import ModeloNegocio.GestorPlataforma; import ModeloNegocio.ICCPAssignment; import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.control.Alert; /** * * @author Asus */ public class FormICCPAssignVC { private FormICCPAssign vista; private GestorPlataforma gestor; public FormICCPAssignVC(GestorPlataforma gestor) throws FileNotFoundException { this.gestor = gestor; this.vista= new FormICCPAssign(); vista.getBoton().setOnMousePressed(new siguiente()); vista.getRegresar().setOnMousePressed(new regresar()); } public void mostrarVista(){ Singleton singleton = Singleton.getSingleton(); vista.mostrar(singleton.getStage()); } class siguiente implements EventHandler<Event>{ @Override public void handle(Event event) { String idParticipante = vista.getIdParticipanteTF().getText(); String nombreParticipante = vista.getNombreParticipanteTF().getText(); String codigoCampamento = vista.getCodigoCampamentoTF().getText(); String calificacion = vista.getCalificacionTF().getText(); String nota = vista.getNotaTF().getText(); boolean t = true; if (idParticipante.equals("") || nombreParticipante.equals("") || codigoCampamento.equals("") || calificacion.equals("")) { t = false; Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Debe llenar todos los campos que se encuentran como obligatorios"); alert.show(); FormICCPAssignVC pantalla = null; try { pantalla = new FormICCPAssignVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormICCPAssignVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } boolean l = false; for(int i=0;i<gestor.getPersonas().size() && !l;i++){ if(gestor.getPersonas().get(i).getId().equals(idParticipante) && gestor.getPersonas().get(i).getFullName().equals(nombreParticipante)){ t = true; } } boolean q = false; for(int j=0;j<gestor.getProgramasICCP().size() && !q;j++){ if(gestor.getProgramasICCP().get(j).getCampYear().equals(codigoCampamento)){ q = true; } } if(l==false || q==false){ t = false; Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Puede que la persona o el campamento que ingreso no existan"); alert.show(); FormICCPAssignVC pantalla = null; try { pantalla = new FormICCPAssignVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormICCPAssignVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } if (t) { try { String fechaInicio = vista.getFechaInicioTF().getValue().toString(); String fechaFin = vista.getFechaFinTF().getValue().toString(); String rol = vista.getRolTF().getValue().toString(); ICCPAssignment asignacion = new ICCPAssignment( nombreParticipante, idParticipante, codigoCampamento, fechaInicio, fechaFin, rol, calificacion, nota); try { gestor.addICCPAssignment(asignacion); } catch (IOException ex) { Logger.getLogger(FormICCPAssignVC.class.getName()).log(Level.SEVERE, null, ex); } Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmacion"); alert.setHeaderText("La informacion ha sido registrada"); alert.show(); OpcionesVC pantalla = null; try { pantalla = new OpcionesVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormICCPAssignVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } catch (NullPointerException e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Debe llenar todos los campos que se encuentran como obligatorios"); alert.show(); FormICCPAssignVC pantalla = null; try { pantalla = new FormICCPAssignVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormICCPAssignVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } } } } class regresar implements EventHandler<Event>{ @Override public void handle(Event event) { Opciones3VC pantalla = null; try { pantalla = new Opciones3VC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormICCPAssignVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } } } <file_sep>import java.util.*; /* * 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. */ /** * * @author Asus */ public class LigaFutbol { private String nombre; private ArrayList<Equipo> equipos; public LigaFutbol(String nombre) { this.nombre = nombre; this.equipos = new ArrayList<>(); } public boolean addEquipo(String nombre, Gerente gerente){ return equipos.add(new Equipo(nombre,gerente)); } public ArrayList<Gerente> getGerentes(){ ArrayList<Gerente> gerentes = new ArrayList<Gerente>(); for(int i=0;i<equipos.size();i++){ gerentes.add(equipos.get(i).getGerente()); } return gerentes; } public ArrayList<Equipo> getEquipos() { return equipos; } } <file_sep> import java.util.ArrayList; import javafx.animation.AnimationTimer; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.scene.shape.Rectangle; import javafx.scene.shape.SVGPath; import javafx.scene.shape.Shape; import modelo.Carro; /** * * @author Estudiante */ public class LoopJuego extends AnimationTimer{ private Scene escena; private GraphicsContext lapiz; private Carro carro; private Image fondo; private Image cat; private Image nene; private int posFondo = 1024; private int secuencia = 0; private int contador = 0; private int moverse = 994; private int moverse2 = 473; private ArrayList<String> pulsacionTeclado = null; public LoopJuego(Scene escena, GraphicsContext lapiz) { this.lapiz = lapiz; this.escena = escena; this.carro = new Carro(0, 0, 110, 60); this.fondo = new Image("image/fondo.png"); this.cat = new Image("image/cats.gif"); this.nene = new Image("image/down1.png"); pulsacionTeclado = new ArrayList<>(); escena.setOnKeyPressed( new EventHandler<KeyEvent>() { public void handle(KeyEvent e) { String code = e.getCode().toString(); if ( !pulsacionTeclado.contains(code) ) pulsacionTeclado.add( code ); } }); escena.setOnKeyReleased( new EventHandler<KeyEvent>() { public void handle(KeyEvent e) { String code = e.getCode().toString(); pulsacionTeclado.remove( code ); } }); } @Override public void handle(long now) { //Carro lapiz.clearRect(0, 0, 1024, 512); lapiz.drawImage(this.fondo, this.posFondo-1024, 0); lapiz.drawImage(this.fondo, this.posFondo, 0); if (this.posFondo<=0) { this.posFondo=1024; }else{ this.posFondo--; } lapiz.drawImage(cat, this.secuencia*132, 0, 132, 80, this.carro.getXref(), this.carro.getYref(), 132, 80); lapiz.strokeRect(this.carro.getXref(), this.carro.getYref(), this.carro.getAncho(), this.carro.getAlto()); if (pulsacionTeclado.contains("LEFT")) carro.moverIzquierda(); if (pulsacionTeclado.contains("RIGHT")) carro.moverDerecha(); if (pulsacionTeclado.contains("UP")) carro.moverArriba(); if (pulsacionTeclado.contains("DOWN")) carro.moverAbajo(); lapiz.drawImage(nene, moverse, moverse2); lapiz.strokeRect(moverse, moverse2, 30, 39); if(this.contador%4==0){ if(this.secuencia<5) this.secuencia++; else this.secuencia = 0; } this.contador++; if(this.carro.getXref()>1024-this.carro.getAncho()) this.carro.setXref(1024-this.carro.getAncho()); if(this.carro.getXref()<0) this.carro.setXref(0); if(this.carro.getYref()>512-this.carro.getAlto()) this.carro.setYref(512-this.carro.getAlto()); if(this.carro.getYref()<0) this.carro.setYref(0); Shape sChasis = new Rectangle(carro.getXref(), carro.getYref(), carro.getAncho(), carro.getAlto()); Shape sObstaculo = new Rectangle(moverse, moverse2, 30, 39); Shape intersection = SVGPath.intersect(sChasis, sObstaculo); if (intersection.getBoundsInLocal().getWidth() != -1) { stop(); lapiz.clearRect(0, 0, 1024, 512); lapiz.fillText("Ganaste", 512, 264); } if(contador%100==0){ this.moverse = (int) (Math.random() * 1024); this.moverse2 = (int) (Math.random() * 512); } } } <file_sep>package Proceso; /* * 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. */ /** * * @author Estudiante */ public class Venta{ private float precio; private int codVenta; private Distribuido productoDistribuido; public Venta(float precio, int codVenta, Distribuido productoDistribuido) { this.precio = precio; this.codVenta = codVenta; this.productoDistribuido = productoDistribuido; } public float getPrecio() { return precio; } public int getCodVenta() { return codVenta; } public Distribuido getProductoDistribuido() { return productoDistribuido; } } <file_sep>/* * 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 GUI.Formularios.FormularioVolunteerPrograms; import GUI.Formularios.FormulariosOpc.OpcionesVC; import GUI.Formularios.FormulariosOpc2.Opciones2VC; import GUI.Singleton; import ModeloNegocio.GestorPlataforma; import ModeloNegocio.VolunteerPrograms; import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.control.Alert; /** * * @author Asus */ public class FormVoluntProgVC { private FormVoluntProg vista; private GestorPlataforma gestor; public FormVoluntProgVC(GestorPlataforma gestor) throws FileNotFoundException { this.gestor = gestor; this.vista= new FormVoluntProg(); } public void mostrarVista(){ Singleton singleton = Singleton.getSingleton(); vista.mostrar(singleton.getStage()); vista.getBoton().setOnMousePressed(new siguiente()); vista.getRegresar().setOnMousePressed(new regresar()); } class siguiente implements EventHandler<Event>{ @Override public void handle(Event event) { String company = vista.getNombreCompaniaTF().getText(); String Id = vista.getIdTF().getText(); String duracion = vista.getDuracionTF().getText(); boolean t = true; if (company.equals("") || Id.equals("") || duracion.equals("")) { t = false; Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Debe llenar todos los campos que se encuentran como obligatorios"); alert.show(); FormVoluntProgVC pantalla = null; try { pantalla = new FormVoluntProgVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormVoluntProgVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } if (t) { try { String tipoVoluntariado = vista.getTipoVoluntariadoTF().getValue().toString(); String FechaGrado = vista.getFechaGradoTF().getValue().toString(); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmacion"); alert.setHeaderText("La informacion ha sido registrada"); alert.show(); VolunteerPrograms volun = new VolunteerPrograms(company, FechaGrado, duracion, tipoVoluntariado, Id); try { gestor.addVoluntariado(volun); } catch (IOException ex) { Logger.getLogger(FormVoluntProgVC.class.getName()).log(Level.SEVERE, null, ex); } OpcionesVC pantalla = null; try { pantalla = new OpcionesVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormVoluntProgVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } catch (NullPointerException e) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Debe llenar todos los campos que se encuentran como obligatorios"); alert.show(); FormVoluntProgVC pantalla = null; try { pantalla = new FormVoluntProgVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormVoluntProgVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } } } } class regresar implements EventHandler<Event>{ @Override public void handle(Event event) { Opciones2VC pantalla = null; try { pantalla = new Opciones2VC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(FormVoluntProgVC.class.getName()).log(Level.SEVERE, null, ex); } pantalla.mostrarVista(); } } } <file_sep>/* * 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. */ /** * * @author Asus */ public class Grade { private int mark; private Module module; private Student student; } <file_sep>/* * 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 GUI.Formularios.FormularioVolunteerPrograms; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ContentDisplay; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; /** * * @author Asus */ public class FormVoluntProg { private Scene escena; private VBox vbox; private HBox hbox2; private HBox hbox3; private HBox hbox; private Label informacion; private Label nombreCompania; private TextField nombreCompaniaTF; private Label Id; private TextField IdTF; private Label fechaGrado; private DatePicker fechaGradoTF; private Label duracion; private TextField duracionTF; private Label tipoVoluntariado; private ChoiceBox tipoVoluntariadoTF; private Button boton; private Button regresar; private ObservableList names; private HBox fondo; private Image logo; private Text nombreE; private StackPane fondos; public FormVoluntProg() throws FileNotFoundException { this.vbox = new VBox(); this.hbox2 = new HBox(); this.hbox3 = new HBox(); vbox.setSpacing(100); vbox.setPadding(new Insets(100, 25, 25, 100)); Label info = new Label("Nota: Los campos con \"*\" son obligatorios"); info.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 15)); this.informacion = new Label("Introduzca la informacion del campamento:", info); informacion.setContentDisplay(ContentDisplay.RIGHT); informacion.setFont(Font.font(null, FontWeight.BOLD, FontPosture.REGULAR, 20)); this.nombreCompaniaTF = new TextField(); this.nombreCompania = new Label("Nombre de la compania: *", nombreCompaniaTF); nombreCompania.setContentDisplay(ContentDisplay.RIGHT); this.IdTF = new TextField(); this.Id = new Label("Identificacion del programa: *", IdTF); Id.setContentDisplay(ContentDisplay.RIGHT); this.fechaGradoTF = new DatePicker(); this.fechaGrado = new Label("Fecha de grado: *", fechaGradoTF); fechaGrado.setContentDisplay(ContentDisplay.RIGHT); this.duracionTF = new TextField(); this.duracion = new Label("Duracion del campamento: *", duracionTF); duracion.setContentDisplay(ContentDisplay.RIGHT); names = FXCollections.observableArrayList(); names.add("Blanco"); names.add("Azul"); names.add("Verde"); names.add("Rojo"); this.tipoVoluntariadoTF = new ChoiceBox(names); this.tipoVoluntariado = new Label("Tipo de voluntariado: *", tipoVoluntariadoTF); tipoVoluntariado.setContentDisplay(ContentDisplay.RIGHT); this.hbox = new HBox(); hbox.setSpacing(100); this.boton = new Button("Agregar"); this.regresar = new Button("Regresar"); hbox.getChildren().addAll(regresar, boton); hbox2.getChildren().addAll(nombreCompania, Id, fechaGrado); hbox2.setSpacing(50); hbox3.getChildren().addAll(duracion,tipoVoluntariado); hbox3.setSpacing(50); vbox.getChildren().addAll(informacion, hbox2,hbox3,hbox); this.fondo = new HBox(); this.logo = new Image(new FileInputStream("src/GUI/Logo.png")); this.nombreE = new Text("Base de datos YMCA"); nombreE.setFont(Font.font(50)); fondo.getChildren().addAll(nombreE, new ImageView(logo)); fondo.setPadding(new Insets(5, 10, 0, 10)); fondo.setSpacing(600); this.fondos = new StackPane(); Image pp = new Image(new FileInputStream("src/GUI/Fondo.png")); ImageView imagen = new ImageView(pp); fondos.getChildren().addAll(imagen, fondo, vbox); escena = new Scene(fondos, 1200, 670); } public void mostrar(Stage stage){ stage.setTitle("Formulario 1"); stage.setScene(this.escena); stage.show(); } public TextField getNombreCompaniaTF() { return nombreCompaniaTF; } public DatePicker getFechaGradoTF() { return fechaGradoTF; } public TextField getDuracionTF() { return duracionTF; } public ChoiceBox getTipoVoluntariadoTF() { return tipoVoluntariadoTF; } public TextField getIdTF() { return IdTF; } public Button getBoton() { return boton; } public Button getRegresar() { return regresar; } } <file_sep>/* * 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 GUI.Inicio; import GUI.Formularios.FormulariosOpc.OpcionesVC; import GUI.Consultas.Opciones.OpcionesCVC; import GUI.Estadisticas.Opciones.TipoVC; import GUI.Estadisticas.Torta.TortaVC; import GUI.Singleton; import ModeloNegocio.GestorPlataforma; import java.io.FileNotFoundException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.scene.control.Alert; /** * * @author Asus */ public class InicioVC { private Inicio inicio; private GestorPlataforma gestor; public InicioVC(GestorPlataforma gestor) throws FileNotFoundException { this.gestor = gestor; this.inicio = new Inicio(); inicio.getBoton().setOnMousePressed(new EventoEstadistica()); inicio.getBoton2().setOnMousePressed(new EventoGuardar()); inicio.getBoton3().setOnMousePressed(new EventoFormulario()); inicio.getBoton4().setOnMousePressed(new EventoConsulta()); } public void mostrarVista(){ Singleton singleton = Singleton.getSingleton(); inicio.mostrar(singleton.getStage()); } class EventoFormulario implements EventHandler<Event>{ @Override public void handle(Event event) { OpcionesVC vista = null; try { vista = new OpcionesVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(InicioVC.class.getName()).log(Level.SEVERE, null, ex); } vista.mostrarVista(); } } class EventoConsulta implements EventHandler<Event>{ @Override public void handle(Event event) { OpcionesCVC vista = null; try { vista = new OpcionesCVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(InicioVC.class.getName()).log(Level.SEVERE, null, ex); } vista.mostrarVista(); } } class EventoEstadistica implements EventHandler<Event>{ @Override public void handle(Event event) { TipoVC vista = null; try { vista = new TipoVC(gestor); } catch (FileNotFoundException ex) { Logger.getLogger(InicioVC.class.getName()).log(Level.SEVERE, null, ex); } vista.mostrarVista(); } } class EventoGuardar implements EventHandler<Event>{ @Override public void handle(Event event) { try { gestor.addPersonaDb(gestor.getNuevaspersonas()); gestor.addColombiaAssignmentDb(gestor.getNuevosprogramasColombiaAssignment()); gestor.addICCPAssignmentDb(gestor.getNuevosICCPAssignments()); gestor.addVoluntariadoAssignmentDb(gestor.getNuevosvolunteerAssignment()); gestor.addProgramaColombiaDb(gestor.getNuevosprogramasColombia()); gestor.addVoluntariadoDb(gestor.getNuevosprogramasVoluntariado()); gestor.addProgramaICCPDb(gestor.getNuevosprogramasICCP()); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmacion"); alert.setHeaderText("La informacion ha sido registrada"); alert.show(); } catch (IOException ex) { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error de validacion"); alert.setHeaderText("No se pudo registrar la informacion"); alert.setContentText("Debe llenar todos los campos que se encuentran como obligatorios"); alert.show(); Logger.getLogger(InicioVC.class.getName()).log(Level.SEVERE, null, ex); } } } }
52e748bea367c059762f444aa5e7a53d4d7b6fe7
[ "Java", "INI" ]
41
Java
SantiagoVargasAvendano/Proyecto1
c4420287e1799df405745fb6f3742bbb06ff1b1a
7610e7065ffcbf5ec72065af985cc8545ab546b8
refs/heads/master
<repo_name>rajmohanperiyasamy/blog<file_sep>/blog/admin.py from django.contrib import admin from blog.models import * admin.site.register(Articles) admin.site.register(Category)<file_sep>/blog/models.py from django.db import models from django.utils.translation import ugettext as _ from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=150,unique=True) def __unicode__(self): return self.name def get_default_category(): return Category.objects.get_or_create(name="Uncategorized") class Articles(models.Model): title = models.CharField(max_length=200) category=models.ForeignKey("Category", default=get_default_category) summary = models.TextField(null=True,blank=True) author= models.ForeignKey(User) hero_image=models.ImageField(upload_to ='media/',null=True,blank=False) extra_image=models.ImageField(upload_to ='media/',null=True,blank=True) publication_date= models.DateTimeField(auto_now_add=True) def __unicode__(self): return self.title<file_sep>/blog/views.py from django.shortcuts import render_to_response from django.template import RequestContext from blog.models import * def gale_task(request): data={} data['user']= request.user try: articles = Articles.objects.all().order_by('-publication_date') random_article=Articles.objects.all().order_by('?')[0] data['articles']= articles data['random_article']= random_article except: data={} pass return render_to_response('index3.html',data,context_instance=RequestContext(request)) def detail(request,pk=0): data={} try: article=Articles.objects.get(id=pk) data['article']= article articles = Articles.objects.all() data['articles']= articles except: data={} pass return render_to_response('detail.html',data,context_instance=RequestContext(request))<file_sep>/blog/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() from django.conf import settings from django.conf.urls.static import static urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), # url(r'^$', 'snap.views.display_article', name='home'), url(r'^$', 'blog.views.gale_task', name='home'), url(r'^detail/(?P<pk>\d+)$', 'blog.views.detail', name='detail'), )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
987d1fc4ef22bcdc5d2bc759739610f9da2bb10a
[ "Python" ]
4
Python
rajmohanperiyasamy/blog
9f4a20732dadac696e8d117ca1e2ac9a0a978608
8cd5277e3c1ebb0a8cec658f1423c8bbc13d439f
refs/heads/master
<file_sep>var config = require('../../modules/config'), request = require('../../modules/request'), cheerio = require('cheerio'), async = require('async'), urlencode = require('urlencode'), querystring = require('querystring'); var _self = module.exports = { checkAuth: function (callback) { console.log('check auth [fetch page]'.green); _self.getPage(config.url, function (html) { if (html) { console.log('check auth [check auth status]'.green); loginForm = html('input#login').length; if (loginForm === 0) { console.log('check auth [already auth]'.blue); callback(1); } else { console.log('check auth [need auth]'.yellow); console.log('check auth [do auth]'.yellow); _self.doAuth(function (auth) { if (auth === 1) { console.log('check auth [success]'.blue); callback(data); } else { console.log('check auth [failed]'.red); callback(0); } }) } } }); }, doAuth: function (callback) { console.log('do auth [send auth request]'.green); request({ uri: config.auth, referer: config.url, formData: { 'login': config.login, 'pass': config.<PASSWORD>, 'save': 'yes' }, method: 'POST' }, function (err, res) { if (!err && res.statusCode === 302) { console.log('do auth [success]'.blue); callback(1); } else { console.log('do auth [failed]'.red); callback(0); } }); }, search: function (string, callback) { var string1; if(string['url']==='pcode'){ var url = config.search + urlencode(string['art']); string1 = string['art']; }else{ var url = config.search_p + urlencode(string['url']); string1 = string['url']; } console.log('category (get) fetch page: '.green + url.bold.magenta); _self.getPage(url, function (page) { if (page) { console.log('category page [fetch success]'.blue); _self.getSystemVars(string1, page, function (variables) { console.log('emulate fetch alert'.green); request({ url: config.alert, headers: {'Content-Type': 'application/json; charset=utf-8'} }, function (err, res) { if (!err && res.statusCode === 200) { console.log('emulate fetch alert [fetch alert success]'.blue); console.log('search (post) fetch page: '.green + url.bold.magenta); var i = 0, interval = setInterval(function () { var msg = ''; i++; for (var j = 0; i != j; j++) { msg += '.'; } msg = 'Timeout' + msg; process.stdout.write(msg.rainbow + "\r"); }, 100); setTimeout(function () { console.log(); clearInterval(interval); request({ uri: url, referer: config.url, formData: variables, method: 'POST' }, function (err, res, body) { if (!err && res.statusCode === 200 && body != undefined) { console.log('search page (post) [fetch success]'.blue); var $ = cheerio.load(body); if ($ != undefined) { console.log('search (post) page [load success]'.blue); callback($); } else { console.log('search (post) page [load failed]'.red); callback(); } } else { console.log('search (post) page [fetch failed]'.red); callback(); } }); }, 3000); } else { console.log('emulate fetch alert [fetch alert failed]'.red); callback(); } }); }) } else { console.log('category (get) page [fetch failed]'.red); callback(); } }); }, parse: function (html, callback) { console.log('*'.red); if (html('h1').text().split(' ')[1]==='Артикул'){ console.log('1*'.red); html('tr').each(function(i,el){ console.log(el); //console.log(el.text().red); //var childrens = el.children(); /*var firmItem = children.eq(0).children().eq(0); var artItem = children.eq(0).children().eq(1); var urlItem = children.eq(1).children().eq(0); console.log('***'.red); var row = { 'firm' : firmItem.text(), 'art' : artItem.text().replace(' ',''), 'url' : urlItem.attr('href') }; console.log(row['firm']+' '+row['art']+' '+row['url']);*/ }); } else { callback(html('table').eq(2).text()); } //var row = []; //console.log(html('table').eq(2).text()); //html('div.artblock').each(function(i, elem){ //console.log($(this).text()); //var children = $(this).children(); //var artItem = children.eq(0).html(); //row.push(artItem); //}); //callback(row); }, getSystemVars: function (string, html, callback) { console.log('get system variables'.green); callback({ 'ctl00$ctl00$b$tm': 'ctl00$ctl00$b$tm|ctl00$ctl00$b$b$btnPost', __EVENTTARGET: 'ctl00$ctl00$b$b$btnPost', __VIEWSTATE: html('input#__VIEWSTATE').attr('value'), __EVENTVALIDATION: html('input#__EVENTVALIDATION').attr('value'), 'ctl00$ctl00$b$b$hdnPcode': string, __ASYNCPOST: 'true' }); }, getPage: function (url, callback) { request(url, function (err, res, body) { console.log('get page [fetch page: '.green + url.bold.magenta + ']'.green); if (!err && res.statusCode === 200 && body != undefined) { console.log('get page [fetch success]'.blue); console.log('get page [load html body]'.green); var $ = cheerio.load(body); if ($ != undefined) { console.log('get page [load success]'.blue); callback($); } else { console.log('get page [load failed]'.red); callback(); } } else { console.log('get page [fetch failed: ' + err + ']'.red); callback(); } }); } };<file_sep>var request = require('request'), random_ua = require('random-ua'), FileCookieStore = require('tough-cookie-filestore'), fs = require('fs'), config = require('../../modules/config'); var cookie = request.jar(new FileCookieStore(config.cookie)); request = request.defaults({ jar: cookie, headers: { 'User-Agent': random_ua.generate() } }); module.exports = request;<file_sep>var config = module.exports = {}; var root = __dirname.split('/'); root = root.slice(0, root.length - 2).join('/'); config.proto = 'http'; config.hostname = 'localhost'; config.login = '180673'; config.password = '<PASSWORD>'; config.root = root; config.cookie = config.root + '/modules/request/cookie.json'; config.url = config.proto + '://www.exist.ru/'; config.auth = config.url + 'Profile/Login.aspx?ReturnUrl=%2fProfile%2fExit.aspx'; config.alert = config.url + 'Profile/Api/Alerts.asmx/GetAlerts?a=null'; config.search = config.url + 'price.aspx?sr=-4&pcode='; config.search_p = config.url + 'price.aspx?pid='; <file_sep># node-exist ##install node modules use `npm i` ##run `node ./app.js`
c66214fe4277fd4288ecc48a7b78d4851e556161
[ "JavaScript", "Markdown" ]
4
JavaScript
ziyatdinov/node-exist
42782c9bc6b79ca9c03110942203475c6861f67b
c8afc00b9fdba0f613b6f116991b49f2f91dfcf8
refs/heads/master
<file_sep>require 'test_helper' class NetworkControllerTest < ActionController::TestCase test "should get sylab" do get :sylab assert_response :success end end <file_sep>class NetworkController < ApplicationController def grepIP (nmapOutput) sLine = nmapOutput sedRegex = [ 's/^.*report for//g', 's/^.*edu.tw//g', ] sLine = `echo '#{sLine}' |sed '#{sedRegex[0]}' |sed '#{sedRegex[1]}' ` sLine.slice! "\n" sLine.slice! ")" sLine.slice! "(" sLine.slice! " " return sLine end def grepPing (nmapOutput) #sLine = nmapOutput.grep(/Host is up/) sLine = nmapOutput sedRegex = [ 's/^.*Host is up (//g', 's/s latenc.*$//g' ] sLine = `echo '#{sLine}' |sed '#{sedRegex[0]}' |sed '#{sedRegex[1]}' ` sLine.slice! "\n" return sLine end def grepHostname (ip) # sLine = nmapOutput.grep(/Nmap scan report for/) # sedRegex = [ # 's/^.*scan report for //g', # ] # sLine = `echo '#{sLine}' |sed '#{sedRegex[0]}'' ` # sLine.slice! "\n" # return sLine sOutput = `sudo nslookup #{ip}` aOutput = sOutput.split( /\r?\n/ ) sLine = aOutput.grep(/name =/) sedRegex = [ 's/^.*name = //g', ] sLine = `echo '#{sLine}' |sed '#{sedRegex[0]}' ` sLine.slice! ".sylab.ee.ntu.edu.tw.\"]" sLine.slice! ".ee.ntu.edu.tw.\"]" sLine.slice! ".ntu.edu.tw.\"]" sLine.slice! "\n" return sLine end def grepStatus (nmapOutput, ip) sLine = nmapOutput #sLine = nmapOutput.grep(/Host is up/) if sLine.blank? sOutput = `sudo nmap -PN #{ip}` aOutput = sOutput.split( /\r?\n/ ) aLine = aOutput.grep(/Nmap done: 1 IP address/) if aLine[0].include? '0 hosts up' return 'offline' else return 'online' end end return 'online' end def grepMAC (nmapOutput) #sLine = nmapOutput.grep(/MAC Address/) sLine = nmapOutput sedRegex = [ 's/^.*Address: //g', 's/s (.*$//g' ] sLine = `echo '#{sLine}' |sed '#{sedRegex[0]}' |sed '#{sedRegex[1]}' |cut -c 1-17 ` sLine.slice! "\n" return sLine end def grepBrand (nmapOutput) #sLine = nmapOutput.grep(/MAC Address/) sLine = nmapOutput sedRegex = [ 's/^.*Address: //g', 's/s (.*$//g' ] sLine = `echo '#{sLine}' |sed '#{sedRegex[0]}' |sed '#{sedRegex[1]}' |cut -c 19- ` sLine.slice! "(" sLine.slice! "\"]" sLine.slice! "\n" sLine.slice! ")" return sLine end def getHostStatus (net) sOutput = `sudo nmap -sP #{net} --exclude 192.168.67.8 172.16.31.10 172.16.31.10` aOutput = sOutput.split( /\r?\n/ ) hosts = aOutput[2..-3] resp = [] # find keys is head heads = [] (0..hosts.length).each do |x| if hosts[x] if hosts[x].include? 'Nmap scan report for' heads.push x end end end (heads).each do |x| ip = self.grepIP(hosts[x]) info = { :ip => ip, :hostname => self.grepHostname(ip), :mac => self.grepMAC(hosts[x+2]), :ping => self.grepPing(hosts[x+1]), :status => self.grepStatus(hosts[x+1],ip), :brand => self.grepBrand(hosts[x+2]), } # host = {ip => info} resp.push info end return resp end def sylab end def scan if (params[:ip][0..9] == ('140.112.42')) || (params[:ip][0..9] == ('192.168.67')) net_sp = params[:ip].split('.') net = net_sp[0] + '.' + net_sp[1] + '.' + net_sp[2] + '.0/24' respond_to do |format| format.html format.json do hosts = getHostStatus net render :json => hosts end end end end def snipet end def ee end end<file_sep># Service List for SYLab SYLab Net Service Infomation Site Daily Snapshots Demo http://service.sylab.ee.ntu.edu.tw [![Build Status](https://travis-ci.org/JustinTW/service.sylab.png?branch=master)](https://travis-ci.org/JustinTW/service.sylab) ## To Do List This project is under development, welcome to fork project and send pull request. [Trello For This Project](https://trello.com/b/9mJU671E) ## Setting up development environment ### Setup RVM Please reference the link http://www.andrehonsberg.com/article/install-rvm-ubuntu-1204-linux-for-ruby-193 ### Add alias for ruby gems commands ```bash vi ~/.bashrc ``` add following line ```bash # rvm and ruby-gems commands alias rgl='rvm gemset list' alias rgu='rvm gemset use' alias rgc='rvm gemset create' alias rgd='rvm gemset delete' alias gl='gem list' alias gi='gem install --no-rdoc' ``` reload bashrc file ```bash source ~.bashrc ``` ### Clone Project ```bash cd ~/ && mkdir workspace && cd workspace git clone git@github.com:JustinTW/service.sylab.git ``` `if you want to contribute code, you must fork project before this step, and clone from your github repos` ### Add RVM gemset for this project ```bash rgc service.sylab ``` ### Install Gems ```bash cd ~/workspace/service.sylab.git bundle install ``` ### Install Nmap if you need to use scan ip function ```bash sudo apt-get install nmap -y ``` ### Start Rails ```bash rails s ``` For now, you can access this project on http://{your_develop_env_ip}:3000
5797bc70ee5076ebdecd8a3e4c3b0930f8370727
[ "Markdown", "Ruby" ]
3
Ruby
JustinTW/service.sylab
b7be124e62c369b3e65331b89fc172e548b3bb64
cbdd4a435bca51eb613e2069440798f4f6426a5f
refs/heads/master
<file_sep>package com.company; public class HeatMap2D { private int[][] tiles; HeatMap2D(Tile[][] grid){ tiles = new int[grid.length][grid[0].length]; } public int[][] getMap(){ return tiles; } public void setTile(int numberOfRow, int numberOfColumn, int value){ tiles[numberOfRow][numberOfColumn] = value; } public int getTileDistance(int numberOfRow, int numberOfColumn){ return tiles[numberOfRow][numberOfColumn]; } } <file_sep>package com.company; import java.util.ArrayList; import java.util.List; public class MapState implements IProblemState { Map _problem; int _currentRow; int _currentCol; private IProblemMove _lastMove; public MapState(Map problem, int currentRow, int currentCol,IProblemMove lastMove) { _problem = problem; _currentRow = currentRow; _currentCol = currentCol; _lastMove = lastMove; } @Override public List<IProblemState> getNeighborStates() { List<IProblemState> neighborStates = new ArrayList<IProblemState>(); List<TileMapMove> legalMoves = getLegalMoves(); for (TileMapMove move : legalMoves) { IProblemState newState = performMove(move); if (newState != null) neighborStates.add(newState); } return neighborStates; } @Override public IProblem getProblem() { return _problem; } @Override public boolean isGoalState() { int size = _problem._size; if (this._currentCol !=this._problem._goalCol) return false; if(this._currentRow!=this._problem._goalRow) return false; return true; } @Override public IProblemMove getStateLastMove() { return _lastMove; } @Override public double getStateLastMoveCost() { return 1; } @Override public boolean equals(Object obj) { if (obj instanceof MapState) { MapState otherState = (MapState) obj; if (_currentCol == otherState._currentCol && _currentRow ==otherState._currentRow) return true; } return false; } public IProblemState performMove(IProblemMove move) { // System.out.println(this.toString()); if (!(move instanceof TileMapMove)) return null; Map newProblem = _problem; int newCurrentRow = _currentRow; int newCurrentCol = _currentCol; TileMapMove tilePuzzleMove = (TileMapMove) move; // Find the moving cell if (tilePuzzleMove._move == TileMapMove.MOVE.DOWN) newCurrentRow--; else if (tilePuzzleMove._move == TileMapMove.MOVE.UP) newCurrentRow++; else if (tilePuzzleMove._move == TileMapMove.MOVE.RIGHT) newCurrentCol--; else if (tilePuzzleMove._move == TileMapMove.MOVE.LEFT) newCurrentCol++; // Validation if(_problem._tileMap[newCurrentRow][newCurrentCol]==1) //its a wal return null; if (notLegitMov(newCurrentRow, newCurrentCol)) return null; // Perform the action // _currentRow = newCurrentRow; // _currentCol = newCurrentCol; // Create new state return new MapState(newProblem, newCurrentRow, newCurrentCol,move); } private List<TileMapMove> getLegalMoves() { int size = _problem._size; List<TileMapMove> moveList = new ArrayList<TileMapMove>(); if (_currentRow != 0) moveList.add(new TileMapMove(TileMapMove.MOVE.DOWN)); if (_currentRow != size - 1) moveList.add(new TileMapMove(TileMapMove.MOVE.UP)); if (_currentCol != 0) moveList.add(new TileMapMove(TileMapMove.MOVE.RIGHT)); if (_currentCol != size - 1) moveList.add(new TileMapMove(TileMapMove.MOVE.LEFT)); return moveList; } private boolean notLegitMov(int row, int col) { if (row < 0 || row >= this._problem._size || col < 0 || col >= this._problem._size) if (this._problem._tileMap[row][col] == 1) { System.out.println(row+"-"+col); return true; } return false; } public String toString(){ return "<"+_currentCol+","+_currentRow+">"; } } <file_sep>package com.company; public class HitmapHeuristic implements IHeuristic { int[][] hitMap; HitmapHeuristic(GameGrid2D grid, Tile startTile) { DijkstraSearch dijkstraSearch = new DijkstraSearch(); HeatMap2D heatMap2D = dijkstraSearch.search(startTile,grid); hitMap = heatMap2D.getMap(); } public double getHeuristic(IProblemState problemState) { int h = 0; MapState state = (MapState) problemState; h = hitMap[state._currentCol][state._currentRow]; return h; } @Override public void HeuristicName() { System.out.println("-----------------------------------"); System.out.println("HitmapHeuristic:"); } } <file_sep>package com.company; public class AirGapDistanceHeuristic implements IHeuristic { public double getHeuristic(IProblemState problemState){ MapState state = (MapState) problemState; return Math.sqrt(Math.pow(state._currentCol - state._problem._goalCol,2) + Math.pow(state._currentRow - state._problem._goalRow,2)); } @Override public void HeuristicName() { System.out.println("-----------------------------------"); System.out.println("AirGapDistanceHeuristic:"); } } <file_sep>package com.company; public interface IProblem { public IProblemState getProblemState(); public IHeuristic getProblemHeuristic(); } <file_sep>package com.company; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { // long start = System.currentTimeMillis(); System.out.println("Start!"); AStarSearch astar = new AStarSearch(); GameGrid2D play = MapFileLoader.loadMapFile("/Users/maorr/Downloads/arena.map"); solveInstances(astar,play.gettheGrid() , new ManhattanDistanceHeuristic()); solveInstances(astar, play.gettheGrid(), new AirGapDistanceHeuristic()); solveInstances(astar, play.gettheGrid(), new HitmapHeuristic(play,play.getTile(10,10))); System.out.println(""); System.out.println("Done!"); // System.out.println("time: "+(System.currentTimeMillis() - start)); } public static void solveInstances(ASearch solvers, int [][] instance, IHeuristic heuristic) { long totalTime = 0; Map problem = new Map(instance,1,2,1,7, heuristic); long startTime = System.nanoTime(); List<IProblemMove> solution = solvers.solve(problem); long finishTime = System.nanoTime(); // if (cost >= 0) // valid solution { // printSolution(problem, solution); System.out.println("Moves: " + solution.size()); System.out.println("Time: " + (finishTime - startTime) / 1000000.0 + " ms"); System.out.println(solution); totalTime += (finishTime - startTime) / 1000000.0; }// else // invalid solution // System.out.println("Invalid solution."); System.out.println(""); System.out.println("Total time: " + totalTime / 60000.0 + " min"); System.out.println(""); } } <file_sep>package com.company; import java.util.ArrayList; public class Tile { public enum TileState {EMPTY,OCCUPIED} private TileState value; private ArrayList<int[]> neighbors; int X; int Y; public Tile( ){ this.setState(TileState.EMPTY); } public Tile(TileState value){ this.setState(value); } public void setState(TileState value){ this.value = value; } public void setNeighbors(ArrayList<int[]> neighbors){ this.neighbors = neighbors; } public Tile[] getNeighbors(GameGrid2D grid){ ArrayList<Tile> neighborsTiles = new ArrayList<Tile>(); for(int[] neighbor: neighbors){ neighborsTiles.add(grid.getTile(neighbor[0],neighbor[1])); } return neighborsTiles.toArray(new Tile[neighborsTiles.size()]); } public boolean isOccupied(){ return value == TileState.OCCUPIED; } public int getvalue() { if(value == TileState.EMPTY )return 0; return 1; } } <file_sep>package com.company; public class BlindSearchNode extends ASearchNode { double _g; public BlindSearchNode ( IProblemState currentProblemState ) { _prev = null; _currentProblemState = currentProblemState; _g = 0; } public BlindSearchNode ( ASearchNode prev, IProblemState currentProblemState, double g ) { _prev = prev; _currentProblemState = currentProblemState; _g = g; } @Override public double getH() { return 0; } @Override public double getG() { return _g; } @Override public double getF() { return _g; } @Override public ASearchNode createSearchNode ( IProblemState currentProblemState ) { double g = _g + currentProblemState.getStateLastMoveCost(); ASearchNode newNode = new BlindSearchNode(this, currentProblemState, g); return newNode; } @Override public boolean equals ( Object obj ) { if (obj instanceof BlindSearchNode) { BlindSearchNode otherNode = (BlindSearchNode)obj; if (_currentProblemState.equals(otherNode._currentProblemState)) return true; } return false; } @Override public String toString() { return super._currentProblemState.toString(); } }
024e1410548994d13544f331f2851ebdbfa2d4b2
[ "Java" ]
8
Java
maorRoz/DimensionSearchWithPDB
4a2ee9e3538c3a6c319e176ba54f5a2a5452897d
142af08be34f9ede49d8b3748e05fe741fc0d79a
refs/heads/main
<file_sep># Troubleshooting OSX Install Issues Many of the dependencies in this project are currently outdated. There are multiple potential issues which could crop up when attempting to install the dependencies and run the app locally whilst using a Mac. Some of these are described below: ## Installing Ruby The current Ruby version in `.ruby-version` is `2.6.3`. This is no longer supported, so it's best to use a newer version of Ruby such as `3.2.0`. ## Bundle Install You may need to remove the `Gemfile.lock` to get things running locally before running `bundle install`. You may also encounter the following issues: ### An error occurred while installing eventmachine (1.2.7) You will need to install eventmachine separately, using a cppflag to point to your install of OpenSSL. This assumes you have OpenSSL installed through Brew. See this [Stack Overflow ticket](https://stackoverflow.com/questions/30818391/gem-eventmachine-fatal-error-openssl-ssl-h-file-not-found) for more info. ``` gem install eventmachine -v '1.2.7' -- --with-cppflags=-I$(brew --prefix openssl)/include ``` ### An error occurred while installing thin (1.7.2) You will need to install thin separately, using a cflag. See this [Stack Overflow ticket](https://stackoverflow.com/questions/63278694/thin-and-puma-fail-with-similar-issues-error-failed-to-build-gem-native-exten). ``` gem install thin -v '1.7.2' -- --with-cflags="-Wno-error=implicit-function-declaration" ``` ### undefined method `untaint' If you have not modified the existing `Gemfile.lock` you may see this error due to the `BUNDLED WITH` section, which forces the install to use an older version of the Bundler which isn't compatible with the newer Ruby version. Try removing the `Gemfile.lock` before installing, but remember not to commit this change. <file_sep>--- title: Close down | ITSA (MTD) End-to-End Service Guide weight: 11 --- <!--- Section owner: MTD Programme ---> # Opting out of MTD Customers who are in MTD on a voluntary basis can leave (opt out) at any time. When this happens the customer’s filing obligations will change from MTD (quarterly) to a single annual obligation due on 31 January following the end of the tax year - this is their final declaration. Eligibility to opt out is determined on a tax year basis. For example, a customer can be mandated for the current year and voluntary for the next year, meaning the customer could opt out next year. A customer can opt out for the previous tax year if they signed up to MTD as a voluntary customer, then subsequently decided not to submit quarterly - opting out would allow the customer to file on an annual basis for that year. The opt out service will not be available through an API. * Customers can access the opt out service and see their changed obligations immediately from their HMRC online services account. * Agents will use their Agent Services Account to access their client’s account. Changed obligations will also be viewable immediately in their software. If the customer has submitted updates of business income and expenses (self-employment and/or property) through their software for the tax year they opt out of MTD, these updates will be deleted. The customer or their agent will receive a warning message to inform them that this is going to happen. The total business income and expenses (for the tax year) must then be submitted as part of the customer’s tax return before completing their final declaration. If a customer is mandated to be in MTD, they will not be eligible to opt out. The opt out service will only be available in HMRC online services for eligible customers. <file_sep>require 'govuk_tech_docs' GovukTechDocs.configure(self) set :relative_links, true activate :relative_assets<file_sep>--- title: Marriage Allowance | Income Tax (MTD) End-to-End Service Guide weight: 32 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- <!--- Section owner: MTD Programme ---> # Marriage Allowance Marriage Allowance allows the user to transfer £1,260 of their Personal Allowance to their husband, wife or civil partner. This reduces the recipient’s tax by up to £252 in the tax year (6 April to 5 April the next year). To create a Marriage Allowance claim the recipients name, date of birth and NINO must be provided. Use the [Create Marriage Allowance](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-disclosures-api/1.0/oas/page#tag/Marriage-Allowance/paths/~1individuals~1disclosures~1marriage-allowance~1%7Bnino%7D/post) endpoint in the [Individuals Disclosures API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-disclosures-api/). <file_sep>--- title: Payments and Liabilities | Income Tax (MTD) End-to-End Service Guide weight: 5 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- <!--- Section owner: MTD Programme ---> # Payments and Liabilities The [Self Assessment Accounts API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-accounts-api/) allows a developer to retrieve accounting information to be shown back to the customer. This includes listing payments the customer has made, how these payments have been allocated and details of any upcoming or outstanding liabilities. The data returned only relates to payments and liabilities arising for tax years since the customer joined the new service. There may also be outstanding liabilities and payment information a customer needs to view for the years prior to signing up to Making Tax Digital for Income Tax Self Assessment that can be viewed using their existing Personal Tax Account. With these endpoints a developer can: * retrieve the overall liability broken down into overdue, payable and pending amounts * retrieve a list of crystallised charges and payments for a given date range * list self-assessment charges between two dates * retrieve the history of changes to an individual charge * retrieve a list of payments for a given date range * retrieve the allocation details of a specific payment against one or more liabilities <a href="figures/payments-and-liabilities-rsab.svg" target="blank"><img src="figures/payments-and-liabilities-rsab.svg" alt="Retrieve a Self Assessment Balance Transactions diagram" style="width:720px;" /></a> <a href="figures/payments-and-liabilities-rsab.svg" target="blank">Open the Retrieve a Self Assessment Balance and Transactions diagram in a new tab</a>. [Retrieve Self Assessment Balance and Transactions](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-accounts-api/2.0/oas/page#tag/Payments-and-Liabilities/paths/~1accounts~1self-assessment~1%7Bnino%7D~1balance-and-transactions/get) This endpoint enables you to retrieve the overall liability broken down into overdue, currently due (payable) and pending (not yet due) amounts. A unique identifier (National Insurance number) for the account must be used. <a href="figures/payments-and-liabilities-lsat.svg" target="blank"><img src="figures/payments-and-liabilities-lsat.svg" alt="List Self Assessment Transactions diagram" style="width:720px;" /></a> <a href="figures/payments-and-liabilities-lsat.svg" target="blank">Open the List Self Assessment Payments and Allocation Details diagram in a new tab</a>. [List Self Assessment Payments and Allocation Details](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-accounts-api/2.0/oas/page#tag/Payments-and-Liabilities/paths/~1accounts~1self-assessment~1%7Bnino%7D~1payments-and-allocations/get) This endpoint enables you to list the payments and allocation details of one or more liabilities for a given National Insurance number. <a href="figures/payments-and-liabilities-rsach.svg" target="blank"><img src="figures/payments-and-liabilities-rsach.svg" alt="Retrieve a Self Assessment Charge's History diagram" style="width:720px;" /></a> <a href="figures/payments-and-liabilities-rsach.svg" target="blank">Open the Retrieve a Self Assessment Charge's History diagram in a new tab</a>. [Retrieve History of a Self-Assessment Charge](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-accounts-api/2.0/oas/page#tag/Payments-and-Liabilities/paths/~1accounts~1self-assessment~1%7Bnino%7D~1charges~1%7BtransactionId%7D/get) This endpoint enables you to retrieve the history of changes to an individual charge. The user must quote a unique identifier (National Insurance number) for the account and also a transaction ID. <file_sep>--- title: Business and Property Income weight: 3 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- <!--- Section owner: MTD Programme ---> # Business and Property Income The steps in this section (up to the End of Period Statement) will be the element that will be mandated for digital record keeping and submission through software under MTD (Making Tax Digital). ## Retrieving obligations Obligations are a set of date periods for which a customer must provide summary income and expense data. Each obligation has a start date and an end date which together define the obligation period. For MTD, each business has multiple obligations which are based on its accounting period. **Note:** It may take up to an hour for a change to an obligation to be updated within HMRC systems. Each obligation has an update period, which is a period of time during which the customer can submit summarised income and expense data. An update period might be a single day or the duration of the whole obligation period. Data may be provided as a single update covering the whole period, or as multiple, smaller updates. Once a business or agent has completed authentication and granted access to the software, the software can then use our APIs to request the information the customer provided at sign up and to find out the customer’s update obligation dates. The software must make customers aware of their obligations. Actions to take are as follows: * the [List All Businesses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/business-details-api/1.0/oas/page#/paths/~1individuals~1business~1details~1%7Bnino%7D~1list/get) endpoint provides a list of all the customer’s business income sources, along with the business ID which the software will need to send to HMRC * the [Retrieve Business Details](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/business-details-api/1.0/oas/page#/paths/~1individuals~1business~1details~1%7Bnino%7D~1%7BbusinessId%7D/get) endpoint will provide the information HMRC holds for a specific self-employment or property business You can retrieve a customer's obligations through the following endpoint: * [Retrieve Income Tax (Self Assessment) Income and Expenditure Obligations](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/obligations-api/1.0/oas/page#/paths/~1obligations~1details~1%7Bnino%7D~1income-and-expenditure/get) - provides obligation dates for all self-employment and property businesses, including grace periods and whether or not obligations have been met Note: the obligations for property obligations cover both FHL and non-FHL. ## Submit income and expense updates for self-employment and property businesses Businesses and agents who represent them, will be required to provide summary-level information of their business income and expenses (transactional information to be kept digitally) on a quarterly basis or more often. The quarterly obligations are initially created based on the accounting period for the income source. The deadline for meeting a quarterly obligation is one month after the obligation period end date. The software should present these deadlines clearly to the customer and prompt them to submit information when the update is due. Submissions of summary-level information cannot span an obligation period. If it does, the software will need to send two updates that fall into different obligations. The software package will need to convert the transactional information into summary totals for each category, for example, expenses by category. HMRC has provided APIs to enable the software to be able to send the summary information to HMRC for each income source and allow HMRC to provide a calculation based on all the information we have received to date. When the update is received, HMRC checks if the customer is signed up to MTD, if the submission is coming from an agent and if that agent is subscribed to agent services and authorised to act on behalf of the client if not, an error is returned. Note: If you still get the error and the client insists they have met all of the scenarios, check they have used the correct Government Gateway credentials when granting access to the software. * [List Self-Employment Period Summaries](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Period-Summaries/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1period/get) * [Create a Self-Employment Period Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Period-Summaries/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1period/post) * [Retrieve a Self-Employment Period Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Period-Summaries/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1period~1%7BperiodId%7D/get) * [Amend a Self-Employment Period Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Period-Summaries/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1period~1%7BperiodId%7D/put) The service will include a number of business validation rules to ensure that all submissions are cross-validated before being accepted. HMRC cannot apply these rules without knowing that no further submission (APIs calls) will be sent by the customer for the period being validated. Once all the information has been submitted to HMRC for that period, the software must use the [Trigger a Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D/post) endpoint to inform HMRC that the user has finished submitting their information. As a response, HMRC will provide a Calculation ID (calculationId). The triggering of the tax calculation will mark the obligation as fulfilled, if we have data covering the whole period. <a href="figures/submit-periodics.svg" target="blank"><img src="figures/submit-periodics.svg" alt="submit periodics diagram" style="width:720px;" /></a> <a href="figures/submit-periodics.svg" target="blank">Open the submit periodics diagram in a new tab</a>. 1. The customer enters digital records through accountancy software or a spreadsheet. The records are uploaded digitally. MTD mandates that a business keeps digital records for all self-employment and property businesses. 2. The software calls the [List All Businesses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/business-details-api/1.0/oas/page#/paths/~1individuals~1business~1details~1%7Bnino%7D~1list/get) endpoint which provides the business ID. You will need to call this the first time your customer uses the software but it's not needed for every interaction. 3. The HMRC API returns the business ID which is required to interact with other self-employment and property APIs. 4. The software receives the business ID. You should store the business ID which will save you having to repeatedly call this endpoint. 5. The software calls the [Retrieve Income Tax (Self Assessment) Income and Expenditure Obligations](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/obligations-api/1.0/oas/page#/paths/~1obligations~1details~1%7Bnino%7D~1income-and-expenditure/get) endpoint - quarterly obligations are initially created based on the accounting period for the income source. The deadline for meeting a quarterly obligation is one month after the obligation period end date. The software should communicate these deadlines clearly to the customer and prompt them to submit the information when the update is due. 6. HMRC returns obligations for the requested date range. 7. The software receives the obligations for the requested date range. It can hold on to this information and prompt the customer closer to the due date. 8. The software prompts the customer when they are due to submit an update. 9. The customer receives the prompt in the software. 10. Software prepares the summary information and displays it to the customer. 11. The customer reviews and submits information. 12. The customer starts the process of submitting data. 13. The software calls the [Create a Self-Employment Period Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Period-Summaries/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1period/post), [Create a Historic Non-FHL UK Property Income & Expenses Period Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-non-FHL-UK-Property-Income-and-Expenses-Period-Summary/paths/~1individuals~1business~1property~1uk~1period~1non-furnished-holiday-lettings~1%7Bnino%7D/post) or [Create a Historic FHL UK Property Income & Expenses Period Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-FHL-UK-Property-Income-and-Expenses-Period-Summary/paths/~1individuals~1business~1property~1uk~1period~1furnished-holiday-lettings~1%7Bnino%7D/post) endpoints, depending on the income source type being submitting. 14. HMRC receives and stores information and provides success response. 15. The software receives the success response. 15a. The software confirms with the customer that the update has been received and stored by HMRC. 16. The software calls the [Trigger a Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D/post) endpoint to get the calculation and ensure the obligation is marked as met, once the update(s) complete an obligation period. 17. HMRC marks the obligation as fulfilled, once the update(s) complete an obligation period. Note: that this can take up to an hour to show on our systems as met. 18. HMRC receives the request and returns a Calculation ID (calculationId). Software must use this when calling the Self Assessment tax calculation endpoint. 19. The software calls the [Retrieve a Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D~1%7BcalculationId%7D/get) endpoint to retrieve the calculation. Note: the tax calculation can take up to 5 seconds to run. We recommend you wait 5 seconds – this is optional and the software does not have to retrieve the tax calculation information at this point. 20. HMRC returns tax calculation. 21. The software displays the calculation to the user – this is optional, the software does not have to show the calculation to the customer at this point (some may want to do their own). 22. Customer reviews the tax calculation. Note: * The periodic information does not need to be provided in one go. Customers can submit data as frequently as they like, for example, monthly. * The customer does not have to declare that the submissions are ‘complete and correct’ (there is no ‘accuracy’ statement required at this point), only that the customer must indicate that they do not intend to provide any additional information at this point. There is nothing to stop them from providing additional information anytime by resubmitting the update period with any changes that have been made to the previous submission. * In some cases, the obligation can take up to an hour to be confirmed as met. * The met obligation must be presented clearly to the customer in the software. * Businesses can also check this information in their Business Tax Account. * The customer will not receive any communication from HMRC to confirm that the obligation has been met. The software should provide this confirmation to the customer. For property businesses, an update for either FHL or Non-FHL for the full quarter will mark the obligation as fulfilled, even if they have both income types. * There are separate income and expenses period summary endpoints for submitting historic data prior to the 2021-22 tax year (back to 2017-2018). For later years, use the main endpoints. Each update period cannot overlap the previous one, for example: Update 1 – 6 April to 1 May is accepted<br /> Update 2 – 2 May to 31 May is accepted<br /> Update 3 – 28 May to 6 June is rejected because it overlaps with previous updates ## Submit allowance and adjustment updates for SE and property businesses An annual summary is defined as a set of summary data for a tax year, containing allowances and adjustments broken down by category. Annual updates are mandatory annually but we have provided the functionality for customers to provide information more frequently if they choose. * amend a [Self-Employment Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Annual-Submission/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1annual~1%7BtaxYear%7D/put) - this enables the customer to provide any information about allowances and adjustments they might want to provide during the year to get a more accurate calculation * amend a [Historic Non-FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-non-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1non-furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/put) - this enables the customer to provide any information about allowances and adjustments they might want to provide during the year to obtain a more accurate calculation * amend a [Historic FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/put) - this enables the customer to provide any information about allowances and adjustments they might want to provide during the year to obtain a more accurate calculation ## Retrieve a tax calculation The software will need to use that Calculation ID when calling each endpoint within the [Individual Calculations API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/3.0). A calculation result once created (excluding metadata) is an immutable calculation that provides a calculation result at a particular point in time. Any further income updates will require a new calculation to be triggered. The [Individual Calculations API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/3.0) allows the software to, choose which elements of the tax calculation it wants to retrieve and play back to the customer: * [List Self Assessment Tax Calculations](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment/get) for a given National Insurance number (NINO) and tax year * [Trigger a Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D/post) for a given tax year. The software must use the trigger a self-assessment tax calculation endpoint to inform HMRC that the user has finished submitting their information. As a response, HMRC will provide a Calculation ID (calculationId). * The triggering of the tax calculation will mark the obligation as fulfilled, if HMRC has data covering the whole period. * [Retrieve Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D~1%7BcalculationId%7D/get) for a given CalculationID **Notes:** * It can take around 5 seconds for the tax calculation response to be ready to retrieve. To avoid getting an error, wait at least 5 seconds before retrieving the calculation. * It is possible to return both in-year and final declaration calculations using these endpoints. An in-year calculation is worked out if the calculation was triggered by the [Trigger a Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/2.0) endpoint ## Making changes to previously submitted data If a customer wants to make a change to the data that was included in a previously submitted update, customers should make the changes to the digital records and software to recalculate the summary totals and submit to HMRC using the following endpoints: ### For income and expense updates (quarterly) If a customer makes a change to a previously submitted periodic update, we suggest you call the following: * [List Self-Employment Period Summaries](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Period-Summaries/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1period/get) * [List Historic Non-FHL UK Property Income & Expenses Period Summaries](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-non-FHL-UK-Property-Income-and-Expenses-Period-Summary/paths/~1individuals~1business~1property~1uk~1period~1non-furnished-holiday-lettings~1%7Bnino%7D/get) or [List Historic FHL UK property Income & Expenses Period Summaries](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-FHL-UK-Property-Income-and-Expenses-Period-Summary/paths/~1individuals~1business~1property~1uk~1period~1furnished-holiday-lettings~1%7Bnino%7D/get) (depending on business income type) to get the period ID and check the update period date range, to ensure any changes are made to the exact date range otherwise it will be rejected. The software will have to recreate the update period including the new summary totals and resubmit the specific update period, using the following: * [Amend a Self-Employment Period Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Period-Summaries/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1period~1%7BperiodId%7D/put) * [Amend a Historic Non-FHL UK Property Income & Expenses Period Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-non-FHL-UK-Property-Income-and-Expenses-Period-Summary/paths/~1individuals~1business~1property~1uk~1period~1non-furnished-holiday-lettings~1%7Bnino%7D~1%7BperiodId%7D/put) or [Amend a Historic FHL UK Property Income & Expenses Period Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-FHL-UK-Property-Income-and-Expenses-Period-Summary/paths/~1individuals~1business~1property~1uk~1period~1furnished-holiday-lettings~1%7Bnino%7D~1%7BperiodId%7D/put) depending on the business income type. When a business resubmits an update period, the software will have to use the trigger a calculation endpoint and follow the same process as the submitting an update period process. ### For allowance and adjustment updates (annual) Use the same endpoints and process for submitting annual information as mentioned. * [Create and Amend Self-Employment Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Annual-Submission/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1annual~1%7BtaxYear%7D/put) * [Create and Amend a Historic Non-FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-non-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1non-furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Create and Amend a Historic FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/put) Note: where a business resubmits an annual summary update, previous figures that have been submitted must be sent again as well as any additional information. A zero or empty filed will overwrite previously provided information. The software will have to use the trigger a calculation endpoint and follow the same process. ### Key points for changing previously submitted updates * changes to periodic updates - the update period you are trying to change must match the original update period exactly, or it will be rejected * changes to annual updates - all figures previously supplied must be provided again, a zero or a null will overwrite any previously submitted information ## Finalise business income End of Period Statement (EOPS) ### Business or Agent able to submit End of Period Statement through software End of period statement (EOPS) is the process that allows the customer to finalise the profit or loss for any one source of business income. An EOPS must be completed for each source of business income the taxpayer has (just as the current Income Tax process for the SA103, SA105 and SA106 schedules) so, for example, if a customer has one self-employment business and one property business they will have to complete two EOPS. EOPS relates to the accounting period or basis period for each source of business income and cannot be completed before the end of that period. Customers can complete their EOPS at any point after the end of the accounting period and do not have to wait until the 31 January deadline. We would like to encourage this behaviour where possible as it helps customers manage their business income in line with the business accounts. However, the deadline to complete is 31 January, Year 2. The process will take into account all the periodic and annual data already provided by the customer throughout the year. Customers must make sure they are confident with the information they have provided and add any additional information they have. This is likely to include tax and accounting adjustments, allowances or reliefs. <a href="figures/eops.svg" target="blank"><img src="figures/eops.svg" alt="end of period statement diagram" style="width:720px;" /></a> <a href="figures/eops.svg" target="blank">Open the EOPS diagram in a new tab</a>. 1. The customer inputs information about allowances and adjustments for the business income source. They can provide this information throughout the year, but must do it before they complete the EOPS. 2. The software calls the [Retrieve a Self-Employment Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Annual-Submission/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1annual~1%7BtaxYear%7D/get), [Retrieve a Historic Non-FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-non-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1non-furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/get) or [Retrieve a Historic FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/get), depending on the business income type you need to submit. This step is optional, but we recommend it to ensure you are getting the most up-to-date information. 3. The customer views the allowances and adjustment information and updates relevant information. 4. The software submits information using the [Create and Amend Self-Employment Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Annual-Submission/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1annual~1%7BtaxYear%7D/put), [Create and Amend a Historic Non-FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-non-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1non-furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/put) or [Create and Amend a Historic FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/put). Depending on the business income type you need to update. 5. HMRC receives and stores information 6. The software calls the [Trigger a Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D/post) endpoint to get the calculation 7. HMRC receives the request and returns a Calculation ID (calculationId) software must use this when calling the Self Assessment Tax Calculation endpoints. 8. The software receives the calculationId. Note: you could display the calculation to customers at this point if you choose, if you do follow steps 20 and 21 in the periodic update section. 9. The customer wants to make some accounting adjustments following the business accounts being finalised. 10. The software calls the SA Accounting summary API (currently in development). 11. HMRC returns summary totals of all the information for that business income source. 12. The software displays information to the customer. 13. The customer makes adjustments, confirms and submits. 14. The software sends information to HMRC using the SA Accounting summary API (currently in development). 15. HMRC confirms receipt and stores the information. 16. The software calls the [Retrieve a Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D~1%7BcalculationId%7D/get) endpoint to retrieve the calculation. Note: the Tax Calculation can take up to 5 seconds to run, so we recommend the software waits 5 seconds – this is optional, the software does not have to retrieve the tax calculation information at this point. 17. The software displays the calculation to the user – this is optional software does not have to show the calculation to the customer at this point. 18. The customer is ready to finalise their business income source. 19. The software calls the [Retrieve a Business Income Source Summary (BISS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-biss-api/2.0/oas/page#/paths/~1individuals~1self-assessment~1income-summary~1%7Bnino%7D~1%7BtypeOfBusiness%7D~1%7BtaxYear%7D~1%7BbusinessId%7D/get) endpoint. Note: there is one BISS for each property type and it will show either FHL or non-FHL information in it. Calling the [BISS API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-biss-api) is optional, the software may choose to create a BISS themselves, but the information must be shown to the customer before they confirm the declaration. 20. The software displays BISS (Business Income Source Summary) information to the customer (listed below).</br> >This can be totalled up by software, or through the APIs from HMRC systems as well as BISS for self-employment or property: > >Total Business Income<br/> >Total Expenses<br/> >Business Net Profit<br/> >Business Net Loss<br/> >Total Additions to net profit or deductions to a net loss<br/> >Total Deductions to net profit or additions to a net loss<br/> >Accounting Adjustments<br/> >Taxable Profit<br/> >Taxable Loss<br/> > >This information must be shown to the customer for them to confirm it is complete and correct for that source of business income before they send the declaration.</br> > >You could use the [BISS API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-biss-api) or opt to create this information within your package. HMRC will need the declaration to confirm the customer has seen it. 21. Customer reviews and confirms the information. 22. The software uses Submit End of Period Statement for a Business endpoint depending on the income source you are finalising. 23. HMRC receives the declaration and marks the obligation as met and provides a success response. 24. The software receives the success response. 25. The software confirms with the customer that the update has been received and stored by HMRC. Note: data received must cover the whole accounting period. The declaration is the only mandatory requirement for this process, the exact text that HMRC requires you to present is below. Developers must replace '[insert tax year]' with the correct tax year. ### Declaration for Agents > **Declaration for Self Employment EOPS** > "I confirm that my client has reviewed the information provided to establish the taxable profits for the relevant period ending in [insert tax year] together with the designatory data provided for that period and that it is correct and complete to the best of their knowledge. They understand that they may have to pay financial penalties or face prosecution if they give false information." > **Declaration for Property EOPS** > "I confirm that my client has reviewed the information provided to establish taxable profits for the relevant period ending in [insert tax year] together with the designatory data for that period and that it is correct and complete to the best of their knowledge. They understand that they may have to pay financial penalties or face prosecution if they give false information." ### Declaration for Individuals > **Declaration for Self Employment EOPS** > “I confirm that I have reviewed the information provided to establish the taxable profits for the relevant period ending in [insert tax year] together with the designatory data provided for that period and that it is correct and complete to the best of my knowledge. I understand that I may have to pay financial penalties or face prosecution if I give false information.” > **Declaration for Property EOPS** > “I confirm that I have reviewed the information provided to establish taxable profits for the relevant period ending in [insert tax year] together with the designatory data for that period and that it is correct and complete to the best of my knowledge. I understand that I may have to pay financial penalties or face prosecution if I give false information.” Making changes to previously submitted data during and after an EOPS declaration: * if the information the customer has previously provided relating to that source of business income is not correct or complete (for example the previous information provided fails further validation, or a periodic update is missing), then the EOPS declaration is rejected, and error messages are returned. The changes must be made to any relevant periodic or annual summaries and then follow the existing process of submitting updates and triggering the calculation before attempting the declaration again. * if there are no error failures, it is recommended that customers review any warning messages they have at this point or earlier as warnings will cause a failure at final declaration. * if after the customer has completed their EOPS declaration, they need to revise any of the data relating to that source of business income then they must make the change to the relevant periodic or annual summaries and follow the existing process of submitting updates and triggering the calculation. Note: making changes to data for previously submitted periods is covered in the "[making changes to previously submitted data"](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/businessandpropertyincome.html#making-changes-to-previously-submitted-data) section. ## View previously submitted updates A customer may want to retrieve previously submitted data, for example before making a change the customer may want to request the last update provided before sending in any changes. If the customer has recently started using your software, you may need to retrieve previous data. ### Income and expense updates (Periodic) The software can use the list all self-employment or property update periods endpoints to retrieve the list of updates made for that income source, or to find one or more period IDs. The period ID is then used with the ‘get a self-employment/property (FHL or Non FHL) periodic update’ endpoint to retrieve data for that update. ### Annual accounting adjustments Within the annual self-assessment process, annual accounting adjustments are applied to income and expenses before the business or agent submits their tax return to HMRC. Within Making Tax Digital as the income and expenses are submitted to HMRC at least quarterly during the active accounting period, this means a new process to accommodate these adjustments is required. ### Submitting annual accounting adjustments After an accounting period has ended, a business or agent may need to submit accounting adjustments to the income and expenses that have been submitted throughout the year. Endpoints to call are: 1. [Trigger a Business Source Adjustable Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1trigger/post). 2. [Retrieve a Self-employment Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Self-employment-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1self-employment~1%7BcalculationId%7D/get), [Retrieve a UK Property Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/UK-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1uk-property~1%7BcalculationId%7D/get) or [Retrieve a Foreign Property Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Foreign-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1foreign-property~1%7BcalculationId%7D/get) - these endpoints provide the totals of all income and expenses submitted for a business that can have adjustments applied to them. 3. Apply the adjustments as appropriate to the total figures returned via the Retrieve BSAS endpoints. 4. [Submit Self-Employment Accounting Adjustments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Self-employment-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1self-employment~1%7BcalculationId%7D~1adjust/post), [Submit UK Property Accounting Adjustments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/UK-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1uk-property~1%7BcalculationId%7D~1adjust/post) or [Submit Foreign Property Accounting Adjustments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Foreign-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1foreign-property~1%7BcalculationId%7D~1adjust/post). Once submitted, if a further amendment is required, use the [Retrieve a Self-Employment Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Self-employment-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1self-employment~1%7BcalculationId%7D/get), [Retrieve a UK Property Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/UK-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1uk-property~1%7BcalculationId%7D/get) or [Retrieve a Foreign Property Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Foreign-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1foreign-property~1%7BcalculationId%7D/get) endpoints to retrieve the previously submitted data and then repeat steps 3 and 4. ## Business Income Source Summary The [Self Assessment BISS (Business Income Source Summary) API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-biss-api/) allows a developer to retrieve a summary of income and expenditure that has been submitted for a specified self-employment or property business (UK or foreign) for a given tax year. The data returned is the equivalent of the existing SA103, SA105 and SA106 schedule. <a href="figures/biss.svg" target="blank"><img src="figures/biss.svg" alt="BISS (Business Income Source Summary) diagram" style="width:720px;" /></a> <a href="figures/biss.svg" target="blank">Open the BISS diagram in a new tab</a>. * [Retrieve a Business Income Source Summary (BISS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-biss-api/2.0/oas/page#/paths/~1individuals~1self-assessment~1income-summary~1%7Bnino%7D~1%7BtypeOfBusiness%7D~1%7BtaxYear%7D~1%7BbusinessId%7D/get) ## Business Source Adjustable Summary The [Self Assessment BSAS (Business Source Adjustable Summary) API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/) allows a developer to retrieve an adjustable summary calculation for a specified self-employment or property business, for a given accounting period. This API should be used to submit any Annual Accounting Adjustments. The adjustments should be submitted as positive or negative amounts, for example, if advertising costs in the BSAS is £250 but the figure should be £200, then the adjustment required would be -50. **Note: Adjustments are always made against the total of the original quarterly updates. Each new adjustment will overwrite the previous adjustment.** | | Original (total of all 4 quarters) | 1<sup>st</sup> adjustment | Revised total | 2<sup>nd</sup> adjustment | Revised total | |----------------------|------------------------------------|---------------------------|---------------|---------------------------|---------------| | premisesRunningCosts | 500 | 25 | 525 | 23 | 523 | | travelCosts | 600 | -17 | 583 | -17 | 583 | <a href="figures/bsas.svg" target="blank"><img src="figures/bsas.svg" alt="BSAS (Business Source Adjustable Summary) diagram" style="width:720px;" /></a> <a href="figures/bsas.svg" target="blank">Open the BSAS diagram in a new tab</a>. * [List Business Source Adjustable Summaries](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D/get) * [Trigger a Business Source Adjustable Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1trigger/post) * [Retrieve a Self-Employment Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Self-employment-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1self-employment~1%7BcalculationId%7D/get) * [Submit Self-Employment Accounting Adjustments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Self-employment-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1self-employment~1%7BcalculationId%7D~1adjust/post) * [Retrieve a UK Property Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/UK-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1uk-property~1%7BcalculationId%7D/get) * [Submit UK Property Accounting Adjustments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/UK-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1uk-property~1%7BcalculationId%7D~1adjust/post) * [Retrieve a Foreign Property Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Foreign-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1foreign-property~1%7BcalculationId%7D/get) * [Submit Foreign Property Accounting Adjustments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Foreign-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1foreign-property~1%7BcalculationId%7D~1adjust/post) ## Multiple businesses Users with multiple self-employment businesses and those with a foreign property business will be able to sign up to Making Tax Digital. To enable this we are providing a number of new endpoints: * [List All Businesses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/business-details-api/1.0/oas/page#/paths/~1individuals~1business~1details~1%7Bnino%7D~1list/get) - returns a list of the business income sources * [Retrieve Business Details](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/business-details-api/1.0/oas/page#/paths/~1individuals~1business~1details~1%7Bnino%7D~1%7BbusinessId%7D/get) - returns further information about a single business income source * [Retrieve Income Tax (Self Assessment) Income and Expenditure Obligations](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/obligations-api/2.0/oas/page#/paths/~1obligations~1details~1%7Bnino%7D~1income-and-expenditure/get) - returns the quarterly obligations for each business income source * [Retrieve Income Tax (Self Assessment) End of Period Statement Obligations](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/obligations-api/2.0/oas/page#/paths/~1obligations~1details~1%7Bnino%7D~1end-of-period-statement/get) - returns the End of Period Statement obligations for a user’s business income sources * [Retrieve Income Tax (Self Assessment) Final Declaration Obligations](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/obligations-api/2.0/oas/page#/paths/~1obligations~1details~1%7Bnino%7D~1crystallisation/get) - returns the final declaration obligation for a user * [Amend Loss Claims Order](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-losses-api/4.0/oas/page#tag/Loss-Claims/paths/~1individuals~1losses~1%7Bnino%7D~1loss-claims~1order~1%7BtaxYearClaimedFor%7D/put) - permits a change in the order in which loss claims are consumed <a href="figures/list-all-businesses.svg" target="blank"><img src="figures/list-all-businesses.svg" alt="list all businesses diagram" style="width:720px;" /></a> <a href="figures/list-all-businesses.svg" target="blank">Open the list all businesses diagram in a new tab</a>. Property unspecified in the Gov test scenario means where we are unable to identify the type of property business - whether UK or foreign. In exceptional cases, we return a type of "property-unspecified". In the case where the query is made with a validly formed but incorrect National Insurance number for a user a “not found” can be returned. <a href="figures/retrieve-business-details.svg" target="blank"><img src="figures/retrieve-business-details.svg" alt="retrieve business details diagram" style="width:720px;" /></a> <a href="figures/retrieve-business-details.svg" target="blank">Open the retrieve details businesses diagram in a new tab</a>. <a href="figures/multiple-businesses-retrieve-itsa-income-expenditure-obligations.svg" target="blank"><img src="figures/multiple-businesses-retrieve-itsa-income-expenditure-obligations.svg" alt="retrieve business details diagram" style="width:720px;" /></a> <a href="figures/multiple-businesses-retrieve-itsa-income-expenditure-obligations.svg" target="blank">Open the retrieve Income Tax (Self Assessment) income and expenditure diagram in a new tab</a>. In the case where the query is made with a validly formed but incorrect National Insurance number for a user a “not found” can be returned. <a href="figures/multiple-businesses-retrieve-itsa-eops-statement.svg.svg" target="blank"><img src="figures/multiple-businesses-retrieve-itsa-eops-statement.svg" alt="multiple businesses diagram" style="width:720px;" /></a> <a href="figures/multiple-businesses-retrieve-itsa-eops-statement.svg" target="blank">Open the retrieve Income Tax (Self Assessment) End of Period Statement obligations diagram in a new tab.</a> <a href="figures/multiple-businesses-retrieve-income-tax-crystallisation-obligations.svg" target="blank"><img src="figures/multiple-businesses-retrieve-income-tax-crystallisation-obligations.svg" alt="multiple businesses diagram" style="width:720px;" /></a> <a href="figures/multiple-businesses-retrieve-income-tax-crystallisation-obligations.svg" target="blank">Open the retrieve Income Tax (Self Assessment) final declaration obligations diagram in a new tab.</a> The [List Loss Claims](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-losses-api/4.0/oas/page#tag/Loss-Claims/paths/~1individuals~1losses~1%7Bnino%7D~1loss-claims~1tax-year~1%7BtaxYearClaimedFor%7D/get) endpoint has been extended to include a sequence number that shows the order in which loss claims will be used. A user with multiple businesses may choose to list their businesses so that they can obtain the Business IDs of their active businesses. A developer can then return information about a specific business or retrieve obligations quoting a ```businessID```, so the user knows when they need to submit information. Where more than one business income source has incurred a loss at the end of the tax year and the user has opted to carry-sideways these losses (by listing loss claims) they will see the current order in which these loss claims will be applied. If they wish to change the order they can amend the loss claim order preference and list loss claims to review. Not all loss claims will have a sequence number to indicate the order of use (currently only carry-sideways, future functionality will enable you to carry backwards). When changing the order, all the loss claims of the same type (for example carry-sideways) must be included in the submission. To obtain the ```businessID``` a developer will need to call the [List All businesses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/business-details-api/1.0/oas/page#/paths/~1individuals~1business~1details~1%7Bnino%7D~1list/get) endpoint. This will then permit obligations to be retrieved for a particular Business ID so that the user is clear by when they must submit their business data. Once loss claims have been generated a user will be able to list them and determine if the order in which they are used needs to change. <file_sep>--- title: HMRC Assist | Income Tax (MTD) End-to-End Service Guide weight: 50 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- # HMRC Assist <!--- Section owner: Transactional Risking ---> ## Overview As part of Making Tax Digital, HMRC Assist is a set of APIs that will create a better customer experience by prompting customers with help via software when they request their end of year tax calculation before finalising their return. HMRC Assist is a new digital service for customers who are signed up for Making Tax Digital ITSA. It will provide targeted and tailored messaging to support individual customers with their tax affairs. Agents acting on behalf of clients will receive the same service when they request a tax calculation. The service will encourage customers to submit accurate information using personalised real-time guidance, increasing correct first-time submissions and compliance. The service will take the calculation data of the customer, analyse the submission and generate a series of guidance material, links and suggested actions for the customer to review. HMRC Assist will be integrated into HMRC’s ITSA Submission Service so that customers completing their final declaration or return amendment using HMRC online services will receive tailored assistance. ### High-level HMRC Assist customer journey <a href="figures/customer-journey-transactional-risking-high-level.svg" target="blank"><img src="figures/customer-journey-transactional-risking-high-level.svg" alt="High level diagram" style="width:720px;" /></a> <a href="figures/customer-journey-transactional-risking-high-level.svg" target="blank">Open the high-level diagram in a new tab.</a> ### HMRC Assist endpoints There are two endpoints: * [Produce a HMRC Self Assessment Assist Report](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-assist/1.0/oas/page#tag/Generate-Report/paths/~1individuals~1self-assessment~1assist~1reports~1%7Bnino%7D~1%7BtaxYear%7D~1%7BcalculationId%7D/post) - this endpoint enables you to generate and return a HMRC Self Assessment Assist report for a tax calculation for a given customer. * [Acknowledge a HMRC Self Assessment Assist Report](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-assist/1.0/oas/page#tag/Acknowledge-Report/paths/~1individuals~1self-assessment~1assist~1reports~1acknowledge~1%7Bnino%7D~1%7BreportId%7D~1%7BcorrelationId%7D/post) - this endpoint enables you to acknowledge that the customer or agent has read the report. ### Produce a HMRC Self Assessment Assist Report The report contains targeted feedback based on what the customer advises HMRC in their update for the given National Insurance number (NINO), Calculation ID, and tax year. <a href="figures/customer-journey-transactional-risking-produce-report.svg" target="blank"><img src="figures/customer-journey-transactional-risking-produce-report.svg" alt="Produce report" style="width:720px;" /></a> <a href="figures/customer-journey-transactional-risking-produce-report.svg" target="blank">Open the produce a report diagram in a new tab.</a> A HTTP 200 success code is returned and the targeted message, recommended action and guidance links are within the JSON for the software to display. ### Acknowledge a HMRC Self Assessment Assist Report This endpoint enables you to acknowledge that the given report has been read by either the customer or agent. <a href="figures/customer-journey-transactional-risking-acknowledge.svg" target="blank"><img src="figures/customer-journey-transactional-risking-acknowledge.svg" alt="Acknowledge a HMRC Assist Report" style="width:720px;" /></a> <a href="figures/customer-journey-transactional-risking-acknowledge.svg" target="blank">Open the Acknowledge HMRC Assist report diagram in a new tab</a>. To acknowledge the report, a HTTP 204 code is returned and contains no content. <file_sep>--- title: Final Declaration (Crystallisation) weight: 4 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- <!--- Section owner: MTD Programme ---> # Final Declaration (Crystallisation) **Note: The term 'final declaration' is now used instead of the term 'crystallisation'. Endpoints with 'crystallisation' or 'crystallise' in their names will continue to be used until further notice.** Final declaration is the process that allows customers to finalise their tax position for any one tax year, taking into account all sources of chargeable income and gains, whether business income or otherwise. It is also the process by which most formal claims for reliefs and allowances and any deductions are made, where these were previously included within a Self Assessment tax return. Customers are able to tell us at this point (subject to the existing limits) how they wish any losses available to them to be treated. Customers can make a final declaration from 6 April Year 1. The deadline for final declaration is 31 January Year 2. The software should remind customers to help them to meet this deadline. Before starting the final declaration journey, the software package must ensure that for the relevant tax year, the customer: * has finalised EOPS for all their businesses (self-employment, uk-property and foreign-property) * has already provided their entire income; for example, interest, dividends, other SA schedules * does not have any additional information to provide We suggest that you first check there are no validation errors by retrieving the self-assessment metadata using the [Retrieve A Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D~1%7BcalculationId%7D/get) endpoint. To trigger a self assessment tax calculation for the given tax year, you use the [Trigger A Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D/post) endpoint with the finalDeclaration query parameter set to true. If there are errors, the calculation is not generated. To view the error messages, call the [Retrieve A Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D~1%7BcalculationId%7D/get) endpoint. To prevent the errors from being generated, the customer must go back and amend the digital records. The software should resubmit the revised summary totals for the relevant periods, then call the [Trigger A Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D/post) endpoint again. ## Providing information about how to treat a loss ### Losses and claims A self-employed business can have a loss when the trade expenses are more than the trade income. If the business has a loss for a year prior to signing up to Making Tax Digital, the customer or agent will need to submit details of the loss to be brought forward. <a href="figures/losses-api-diagram.svg" target="blank"><img src="figures/losses-api-diagram.svg" alt="Losses API calls" style="width:720px;" /></a> <a href="figures/losses-api-diagram.svg" target="blank">Open the Losses diagram in a new tab</a>. Vendors can use the [create a brought forward loss](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-losses-api/4.0/oas/page#tag/Brought-Forward-Losses/paths/~1individuals~1losses~1%7Bnino%7D~1brought-forward-losses/post) endpoint to enable customers to submit the brought forward loss to HMRC. When the loss detail has been submitted, or if a loss arises for a tax year following sign up to Making Tax Digital, a claim will need to be made to either: * utilise the loss against an income source for a specific year, or * claim to carry the loss forward so that it is available to use in later years The [Loss claims](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-losses-api/4.0/oas/page#tag/Loss-Claims) endpoint allows the user to do the following: * provide a list of Loss claims * create a Loss claim against an income source for a specific tax year * show the detail of an existing Loss claim * delete a previously entered Loss claim * update a previously entered Loss claim ### Brought Forward Losses These resources allow software packages to provide a customer's financial data for their brought forward losses. Here the developer can: * provide a list of brought forward losses * create a new brought forward loss to submit against self-employment, self-employment class 4, UK FHL property, other UK (non-FHL) property, foreign property FHL in the European Economic Area (EEA) or other foreign property * show a single brought forward loss * delete an existing brought forward loss * update an existing brought forward loss To carry-back a loss, the customer should contact HMRC who will be able to apply this manually. ## Submit information about personal income ### Self-assessment return The software should prompt customers to make sure they have considered the following potential additional income sources (there are links to the APIs where the functionality is available, we will continue to release additional functionality and update this page). * any income from [bank or building society interest](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/1.0/oas/page#tag/UK-Savings-Account) (supported in live) * any income from [dividends](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/1.0/oas/page#tag/Dividends-Income) (supported in live) * any [gift aid contributions](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Charitable-Givings) they have made (supported in live) * any pension contributions * any pension income * capital gains * income from employment * additional information (currently provided on the SA101) * any income from partnerships * any income from trusts * any foreign income **Note:** Information currently provided through the existing self-assessment process: if a customer needs to report information to HMRC that is not yet supported under MTD or your software, they will need to complete a Self Assessment tax return. Any information they have provided through MTD will not be considered and they will have to submit everything through the existing HMRC Self Assessment service. ## Final Declaration The software will have to let HMRC know that the customer is ready to submit a final declaration, to do this you must call the [Trigger A Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D/post) endpoint under the [Individual Calculations (MTD) API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api) with the ```finalDeclaration``` parameter set to true. This will start the final declaration process in HMRC. It will trigger the business validation rules (which will become errors rather than warnings) and generate a final liability calculation. The response includes a ```calculationId```. The software will then have to retrieve the calculation using the ```calculationId``` to get the calculation output. The Calculation ID output provides a summary of each income source (for example self-employment, UK property, foreign property and UK bank and building society interest), plus a breakdown of allowances and reliefs applied, and a breakdown of the Income Tax and NIC payable - broadly the equivalent of the current SA302. As of v3.0, the results of the final declaration calculation are available at a single endpoint: * [Retrieve A Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D~1%7BcalculationId%7D/get) A final declaration Calculation ID will not always have a calculation result. It is possible that errors in previously submitted income data can prevent a calculation from being performed. If calculation errors are present, these errors are returned in the response to the Retrieve a Self Assessment Tax Calculation endpoint. <a href="figures/crystallisation-diagram.svg" target="blank"><img src="figures/crystallisation-diagram.svg" alt="crystallisation process API diagram" style="width:720px;" /></a> <a href="figures/crystallisation-diagram.svg" target="blank">Open the final declaration process diagram in a new tab</a>. 1. Customer is ready to complete their final tax return. 2. The software calls the [Trigger A Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D/post) endpoint with ```finalDeclaration``` as true – this triggers the creation of the final declaration calculation for the customer to agree. 3. HMRC receives the request and starts the tax calculation and returns a Calculation ID. 4. The software receives the ```calculationId```. 5. Generates the final declaration tax calculation - this process will also convert any business validation warnings into errors, if there are any errors the calculation will not run and the customer will not be able to declare the liability. 6. HMRC Stores tax calculation with ```calculationId```. 7. The software uses the [Submit a Self Assessment Final Declaration](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Final-Declaration/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D~1%7BcalculationId%7D~1final-declaration/post) to agree to the final declaration. We suggest that you retrieve the self-assessment metadata first to check there are no validation errors. If there are errors the calculation will not have been generated. The customer must go back and amend the digital records, software should resubmit the revised summary totals for the relevant periods, then call the Trigger A Self Assessment Tax Calculation endpoint again. 8. HMRC provides the calculation response. 9. Software surfaces the calculation to the customer – at this point in the journey, it is mandatory that the customer is shown a copy of the calculation resulting from the intent to final declaration ```calculationId```. As a minimum a customer must view the equivalent of what is currently in the SA302. 10. The customer reviews the calculation and declaration text. 11. The customer confirms the declaration and the software calls the Crystallisation endpoint using the Calculation ID to confirm the calculation to which the customer is agreeing. 12. HMRC receives the submission and confirms receipt with a success message and marks the obligation as fulfilled. 13. The software receives a success message and confirms that HMRC has received the return. 14. The customer views confirmation that the return has been successfully submitted to HMRC. The software must use the final declaration ```calculationId``` to retrieve the final calculation and display that calculation to the customer. The customer must review this calculation and confirm it is complete and correct by sending the declaration. If the customer thinks the calculation is incorrect as a result of the data they have submitted, they can go back and change the information, by resubmitting the relevant update with the correct information. Once they have done this the software will have to call the Trigger endpoint again to generate a new final liability. If the customer does not agree with the calculation based on rules HMRC have used, then they will still need to declare against this calculation and follow the existing process to challenge the calculation. If a software vendor identifies what they feel could be a technical issue with the Tax calculation API, they will need to contact the SDS Team immediately. Once a customer is confident with all the information, they will have to agree to a declaration and send it to HMRC. > **The Declaration** > “Before you can submit the information displayed here in response to your notice to file from HM Revenue & Customs, you must read and agree to the following statement by > [Here the vendor can decide how to manage the actual declaration in the user interface, for example a tick box, confirm button or other method] > I declare that the information and self-assessment I have filed are (taken together) correct and complete to the best of my knowledge. I understand that I may have to pay financial penalties and face prosecution if I give false information.” > **Declaration for Agents** > "I confirm that my client has received a copy of all the information being filed and approved the information as being correct and complete to the best of their knowledge and belief. My client understands that they may have to pay financial penalties and face prosecution if they give false information." The software must send the ```calculationId``` that matches the calculation the customer is declaring against with the declaration. ## Making an amendment after final declaration If a customer wants to make any changes following a final declaration they have 12 months from the statutory filing date to do this (the statutory filing date is 31 January following the end of the tax year, or 3 months from receipt of a Notice to File by the taxpayer whichever is the later). Note: any changes made following final declaration will be a formal amendment under section 9ZA TMA 1970 ## Pay or get a repayment Vendors should present messages to business users at key points in their user journey that gives them the option to make payments ahead of any obligation date to help spread the cost. We will deliver functionality that allows vendors to make users aware of payment dates. There are multiple ways to make a payment for Self Assessment which can be found on GOV.UK at: [https://www.gov.uk/pay-self-assessment-tax-bill](https://www.gov.uk/pay-self-assessment-tax-bill) Vendors should, in their messaging, ask customers to visit that link so the customer can make a payment in the method that suits them. The contents of this GOV.UK page will be updated and subject to change. For a business to view the previous payments it has made to HMRC, vendors should present messages at key points in their journey that encourage them to visit their Business Tax Account at: [https://www.access.service.gov.uk/login/signin/creds](https://www.access.service.gov.uk/login/signin/creds) Vendors in their messaging should ask customers to visit that link. Customers can pay their tax bills by direct debit, making it easy and convenient to pay. HMRC is delivering functionality for customers to set up direct debit instructions to pay tax when it becomes due. Customers may also set up a regular payment plan to ensure funds are available when tax becomes due. These services will be available when a customer first subscribes to HMRCs tax services, and at any time after a customer has been subscribed through their digital tax account. Access to the services will be via the customer’s digital tax account at: [https://www.access.service.gov.uk/login/signin/creds](https://www.access.service.gov.uk/login/signin/creds) Vendors in their messaging should ask customers to visit that link.   Customers will be able to view payments made to HMRC in the software. Details will be updated here once they are available. <file_sep>--- title: API Deprecation Guidance weight: 55 --- # API lifecycle & deprecation Each MTD API follows a lifecycle from the point where it is first published to the point where it is retired. More specifically, every version of each API follows a lifecycle. Different versions of the same API can be at different points in the lifecycle. For example, v1.0 might be retired, v2.0 might be stable and v3.0 might be in beta. ## API status The following table gives details of the possible API statuses: | Status | Meaning | Documentation visible? | Can be subscribed to in Developer Hub? | Endpoints enabled? | |------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------|----------------------------------------|--------------------| | ALPHA | Early prototype - documentation only, available in External Test. Intended for feedback on the initial API design and documentation. Expect breaking changes and behaviour changes. | Yes | No | No | | BETA | Live service but not stable. Breaking changes and behaviour changes are possible. | Yes | Yes | Yes | | STABLE | Stable live service. No breaking changes and only minor behaviour changes. | Yes | Yes | Yes | | DEPRECATED | Set to be retired, either because a new version of the API is available, or because the API is no longer supported. If applicable, a new version of the API will be available in external test when the current version is deprecated. | Yes | No | Yes | | RETIRED | API is no longer in use. | No | No | No | | No | No | No | ## Breaking changes Any change that might break software that relies on an API is counted as breaking change. The table below lists changes that we consider breaking. | Area | Breaking changes | |---------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Query Parameter | <ul><li>Adding mandatory query parameter</li><li>Removing a query parameter</li><li>Renaming a query parameter</li><li>Changing an optional query parameter to be mandatory</li><li>Removing/renaming a value from an enum </li></ul> | | Request Body | <ul><li> Adding a mandatory field </li><li> Removing a field </li><li> Renaming a field </li><li> Changing an optional field to be mandatory </li><li> Removing/renaming a value from an enum </li></ul> | | Response Body | <ul><li> Removing a field </li><li> Renaming a field </li><li> Changing a mandatory field to be optional </li><li> Adding/renaming a value to an enum </li></ul> | | Other | <ul><li> Changing the URL of the endpoint </li><li> Removing a resource/endpoint </li><li> Changing the semantics of a field value (for example, the value returned changes from inclusive of VAT to exclusive of VAT) </li><li> Changing validation to have stronger constraints </li></ul> | ### Changes to errors When we make changes to errors, we will not usually change the JSON structure returned (in the rare case when this is necessary, this will be considered a breaking change). The values of the error fields may change. #### Breaking changes for errors * Changing the HTTP Status code to a different value * Renaming an error code * Adding a new error code (but see below) If we add a new error code to an endpoint as part of a new field/object which is not itself a breaking change, then the new error is not counted as breaking change. For example, suppose we add a new optional string field to the request body and the field must satisfy a specific condition, otherwise it fails with a new error. This error is not considered a breaking change, since existing software will keep functioning as the error can only be returned if the new field is used. #### Non-breaking changes for errors * Removing an error code * Changing the message of an error ## Deprecating APIs If an API has been in production with a status of STABLE, we aim for a deprecation period of 6 months. For an API in BETA, we aim for a deprecation period of 6 weeks minimum. Applications cannot subscribe to a deprecated API version, but can still call the API version if the subscription was made before the status changed. The status of APIs is indicated in the API documentation. In releases from June 2023 onwards, deprecation status will also be indicated with a `Deprecation` response header like this: | Name | Example value | |-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| | Deprecation | This endpoint is deprecated. See the API documentation: https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api | ## Retiring APIs Once an API has been DEPRECATED for the amounts of time indicated above, it can be retired and the endpoints and documentation will be removed. Ensure that your application does not rely on any deprecated APIs. <file_sep># Income Tax (Making Tax Digital) end-to-end service guide **Version 3.1** issued June 2023 **Note:** This guide is currently under review to ensure it meets the needs of software providers. See the service guide [changelog](#changelog) for latest updates. >|Help us improve this guide | |---| |We&#39;d really like to hear from you if you have used this service guide.<br/><br/>If you are a Developer, Product Manager, Product Owner, Business Analyst or Delivery Manager, as part of our ongoing collaboration we&#39;d like to invite you to share your thoughts and feedback to help influence change within the ITSA MTD service.<br/><br/>The sessions will take place via an online video call, which will involve a 60-minute one-to-one interview.<br/><br/>We’d like to explore:<ul><li>Your current use of and experience with the service guide</li><li>Any challenges you face</li><li>How helpful you find the service guide</li><li>Your thoughts on the current service guide and exploring how it fits your needs and how it can be improved</li></ul><br/>If this sounds like something you would like to take part in, please contact our User Researcher <a href="mailto:<EMAIL>"><EMAIL></a> to arrange an interview.| ## Overview This guide explains how you can integrate your software with our APIs, and provides examples of how they fit into various end-to-end user journeys to enable agents and individuals to meet their obligations once they have signed up to Making Tax Digital, a service where quarterly updates and final declarations will replace the need for a Self Assessment return to be submitted. For more information about eligibility and how to use Making Tax Digital for Income Tax, please refer to the [Making Tax Digital step by step guidance](https://www.gov.uk/government/collections/making-tax-digital-for-income-tax-for-businesses-step-by-step). ## Making Tax Digital APIs This service guide explains how you can integrate your software with the [Income Tax (Making Tax Digital) APIs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api?filter=income-tax). ## Software provider overview HMRC expects software providers to offer customers a streamlined end-to-end journey, and as far as possible, to support all the things the customers need to do to comply with their MTD for ITSA obligations. This will include the ability to finalise the overall tax position using software. HMRC will provide the APIs for the software to support all of the personal data items that need to be submitted under Self Assessment. Although these elements will not be mandated through the software, there will be market demand for software that enables any user to finalise the entirety of their tax affairs. By developing a product now, you will support the mandate of the service, influence its design and ensure you have a product ready for the millions of customers that will need MTD-compatible software. ### Bridging software Some customers may wish to integrate their existing software solution for digital record keeping with another product that can submit quarterly updates, End of Period Statement, view tax liabilities, make a self assessment and final declaration, and so on. We generally refer to these products as bridging products. In order to be granted production credentials for a bridging product, it must be digitally linked to software that allows customers to maintain business records required by law. ### Non-MTD products Software products who wish to selectively use Making Tax Digital for Income Tax APIs and not build a Making Tax Digital product will have to submit a business case, justifying use of a particular or multiple API’s. Such products may be granted production credentials at HMRC discretion. ## Production approvals process for Making Tax Digital for Income Tax Self Assessment Our key objectives for MTD for Income Tax are to: * ensure customers have a streamlined end-to-end journey and software that supports everything a business customer needs to do to meet their Income Tax obligations * safeguard customer data and protect HMRC systems against fraud and criminal attack This section of the guide explains the features your product must include before production credentials are sought, together with features you should consider building into your products. ### Minimum functionality standards Previously, the production approvals process included an assessment of whether a product includes certain minimum functionality. In response to developer feedback, we are content for software developers to build MTD Income Tax products iteratively and be granted production credentials for specific elements of the minimum required functionality. However, an MTD Income Tax product will only be listed on the software choices viewer when it satisfies all the requirements listed below. The minimum required functionality is as follows: * A software product must submit the fraud prevention header data required by law. * A Making Tax Digital for Income Tax product must allow the customer to: * Create and maintain all business records a customer is required by law to keep in digital form (but see [Bridging Software](#bridging-software)) * Submit quarterly update information for each business income source (self-employment, multiple self-employments, UK property income) * Have the option to provide accounting and other adjustments and an estimate of allowances to be claimed for any business income source * Submit an End of Period Statement for each business income source (with declaration of completeness) * Call for and view an estimate of their Income Tax liability for each tax year at any time * Make a self-assessment of the tax and Class 4 National Insurance contributions due on their total taxable income and a final declaration of completeness and correctness no later than 31 January following the end of tax year in which that income is taxable * Carry forward or set sideways (when permitted) business losses occurring in any one year as well as to apply losses incurred in earlier years against current year profits * Have visibility of all their Class 2 National Insurance contributions (so that they can make additional voluntary contributions if they wish) The Making Tax Digital for Income Tax APIs that include the endpoints for the functionality described above are: * [Business Details](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/business-details-api/) * [Obligations](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/obligations-api/) * [Business Income Source Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-biss-api/) * [Individuals Business End of Period Statement](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-business-eops-api/) * [Individual Calculations](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api) * [Individual Losses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-losses-api) * [Individuals Disclosures (Class 2 NIC’s)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-disclosures-api) * [Business Source Adjustable Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api) ### Fraud Prevention Headers You must supply fraud prevention header information for all our APIs before approval can be granted and production credentials issued. HMRC must see evidence of fraud prevention headers being sent and be satisfied as to their level of accuracy. The developer must test their fraud prevention headers and provide SDST with screenshot evidence that the correct response is received from the [Test Fraud Prevention Headers API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/txm-fph-validator-api/). [Guidance on Fraud Prevention Headers](https://developer.service.hmrc.gov.uk/guides/fraud-prevention/) is available. ### Overview of developer journey to production credentials 1. Sign in to the [developer hub](https://developer.service.hmrc.gov.uk/api-documentation) and register your application for sandbox testing. 2. [Create a test user which is an individual](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/api-platform-test-user/1.0/oas/page#tag/create-test-user/operation/Createatestuserwhichisanindividual) to create test data. 3. Review the [API documentation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api?filter=income-tax) and Income Tax end-to-end service guide. 4. Test ITSA endpoints and develop your software application. Any queries during this phase should be sent to <EMAIL>. 5. Register your application for production credentials by creating a production application within your developer hub account and completing the requested sections. 6. Provide testing logs and credentials used for testing to HMRC. 7. Developer testing is reviewed by HMRC (including fraud header validity). - If satisfactory, you will be invited to demonstrate your product. - If not satisfactory, further testing and development will be required for review. 8. The software vendor demonstrates its software to HMRC via online screen sharing. 9. Production credentials are issued if all requirements are met. If not, further development is required and a new demonstration will be arranged. ### Product build Developers have the option to either build all elements required to meet [minimum functionality standards (MFS)](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/#minimum-functionality-standards) in one go or to build these elements iteratively. If you choose to build iteratively, you will be required to demonstrate your product after each stage of the build. There are three stages, although many developers choose to develop stages 2 and 3 together. The three stages are: 1. In year functionality (submitting periodic updates). 2. End of Period (EOPs). 3. Final declaration. The [API catalogue](https://developer.service.hmrc.gov.uk/roadmaps/mtd-itsa-vendors-roadmap/#apis-required-for-each-stage-of-development-of-a-minimum-functionality-standard-mfs-product) shows which APIs are required at each stage of the build. ### Testing requirements HMRC requires the software to test all the APIs that they require access to. The following points relate to access to both new API subscriptions and version updates of existing API subscriptions: - For APIs included in the [minimum functionality standards](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/#minimum-functionality-standards), you are required to test all endpoints shown within the documentation. - For APIs not included in the minimum functionality standards, you are only required to test the endpoints relating to the data sources that your software supports. Where your software doesn’t support all data items, please notify <EMAIL> separately to confirm which data items you do support, so we can take this into account when checking the testing logs. [Fraud prevention headers](https://developer.service.hmrc.gov.uk/guides/fraud-prevention/) must be included in sandbox calls. A specialist team will check these and they must be confirmed as compliant before we can proceed. Once testing is complete, please send details of the dummy NINO used to call the above endpoints in sandbox to <EMAIL>. You will need to contact us within 14 days of completing your API testing to enable us to view the data within our logs. SDST will advise you of the outcome of our checks within 10 working days.    Once we are satisfied that the relevant APIs and endpoints have been tested satisfactorily and that calls include compliant fraud prevention headers, you will be invited to demonstrate your product. Please note, demonstration is not generally required for access to updated APIs (that is, new versions), but satisfactory testing will be required. ### Product demonstration This is the final part of the process after all preceding steps have been completed.    During your product demonstration, HMRC expects to see a consumer-ready product for each income source your software supports; for example, Self-employment, UK property, and so on. If, in addition to the MFS APIs, you have also requested access to any non-MFS APIs, you should be ready to include these in your demonstration if requested to do so by SDST. The journey we expect to see for an MFS build will depend on whether you are building iteratively and if so, which stage you have built to: **Stage 1: In year build** 1. Authorisation – ITSA scopes only. 2. Retrieve Business Details. 3. Retrieve Obligations. 4. Digitally import data into the appropriate periodic update and submit. 5. Automatically trigger and display a tax calculation. 6. Submit an amended periodic update – automatically trigger and display the calculation. 7. Demonstrate how your software returns and displays error messages to the customer. **Stage 2: EOPS** 1. Submit details within the Annual Summary. 2. Automatically trigger and display a tax calculation. 3. Trigger a Business Source Adjustable Summary (BSAS). 4. Retrieve a BSAS. 5. Create and submit a Business Source Adjustable Summary for an accounting adjustment. 6. Automatically trigger and display a tax calculation. 7. **Either:** - Retrieve a Business Income Source Summary (BISS) and display it to the customer. **Or:** - The software may choose to create a BISS themselves by totalling the relevant information held in software and displaying it to the customer. 8. Show EOPS Declaration Statement - this must match the statement shown in the ITSA End to End Service Guide. 9. Submit EOPS. 10. Demonstrate how your software returns and displays error messages to the end user. **Note:** The end user must confirm they have read and agreed the declaration statement before the option to submit EOPS is made available. **Stage 3: Final Declaration** 1. Create and submit a loss. 2. Create/Amend and submit disclosures (Class 2 NICs). 3. Trigger a tax calculation with the ```finalDeclaration``` parameter set to “True”. 4. Retrieve and display this tax calculation for the customer to review. 5. Show the Final Declaration Statement – this must match the statement shown on the ITSA End to End Service Guide. 6. Submit a Final Declaration. 7. Demonstrate how your software returns and displays error messages to the end user. **Note:** The end user must confirm they have read and agreed the declaration statement before the option to submit the Final Declaration is made available. #### Important Considerations - Build functionality to allow business customers to report income from non-business sources that meets your customer model. - Consider the one-hour delay as part of the software workflow to update the status of obligations. - Consider a 5-second delay before retrieving the calculation. - Consider developing guidelines within the software for relevant users, including a reference to HMRC user interface journeys for customers and agents. - Use APIs as efficiently as possible to avoid exceeding the rate limit. - Build relevant error responses for your software to deal with exceptions. - Correct MTD gateway credentials or agent services credentials need to be used when logging into the system when authorising your software. - Consider providing notifications to customers when periodic submissions are due. - Consider building functionality that allows the customer to request a tax calculation at any time. ## Terms of use You must comply with our [terms of use](https://developer.service.hmrc.gov.uk/api-documentation/docs/terms-of-use). You must accept the terms of use before we can issue you with production credentials. ## Software choices Software Choices is a service designed to help users [find compatible software for Making Tax Digital for Income Tax](https://www.gov.uk/guidance/find-software-thats-compatible-with-making-tax-digital-for-income-tax) that meets their needs. An updated version is being developed with filters to help users find products that fit their specific requirements. For instance, a user may wish to find bridging software instead of a standalone product, or a product that suits their accessibility needs. It will also include a filter to find software that is also compatible with Making Tax Digital for VAT. Software vendors will be added to Software Choices once they have satisfied production credentials. We advise users to speak to their appointed tax agent, if they have one, before making a decision on software. ### Free-to-use software The government has committed to the availability of free software for small businesses mandated to use MTD for income tax. HMRC strongly encourages all developers to consider producing a free version of their MTD for Income Tax product for this customer group. By ‘small businesses’ we mean that eligibility for free software will apply where the business meets all of these conditions: * it is an individual (self-employed or a landlord) or a simple partnership * it is not VAT registered * it has no employees * it has a turnover (gross annual income from all business sources) of less than £85,000 * it uses cash basis accounting For the avoidance of any doubt, there is no expectation that a free product will include VAT, Corporation Tax or PAYE functionality. In addition to the minimum standards set out in the terms of use, and the general functionality standards applicable to all MTD for Income Tax software, we expect any free software product you provide to small businesses to: * enable the provision of a dataset that correlates to the current [SA103S self-employment supplementary page (short)](https://www.gov.uk/government/publications/self-assessment-self-employment-short-sa103s) * enable the provision of a dataset that correlates to the current [SA105 UK property](https://www.gov.uk/government/publications/self-assessment-uk-property-sa105) or [SA106 foreign property](https://www.gov.uk/government/publications/self-assessment-foreign-sa106) pages, where the number of properties does not exceed one * provide a reasonable level of guidance, help and support to users (HMRC is open to views on what might be ‘reasonable’ for a free product and will publish further advice on this in due course) * allow the end user to own and have access to all their records created using the software product (past and present) to enable them to retrieve data and promptly export it if necessary * be free for the business to use to comply with their MTD for Income Tax obligations for a full annual accounting period on the understanding the business continues to meet the eligibility criteria below HMRC would not require free software to link or integrate with an Agent product. ## Finalise business income End of Period Statement (EOPS) ### Business or Agent able to submit End of Period Statement through software This is the process that allows the customer to finalise the profit or loss for any one source of business income. An EOPS must be completed for each source of business income the customer has (similar to the current Income Tax process for the SA103, SA105 and SA106 schedules). For example, if a customer has one self-employment business and one property business they will have to complete two EOPS. EOPS relates to the accounting period or basis period for each source of business income and cannot be completed before the end of that period. Customers may complete their EOPS at any point after the end of the accounting period and do not have to wait until the 31 January deadline. This helps customers manage their business income in line with the business accounts. However, the deadline to complete is 31 January, Year 2. The process will take into account all the periodic and annual data already provided by the customer throughout the year. Customers must make sure they are confident with the information they have provided and add any additional information they have. This is likely to include tax and accounting adjustments, allowances or reliefs. ### EOPS process <!--- some endpoints below are deprecated, need to update with equivalents --> 1. The customer inputs information about allowances and adjustments for the business income source. They can provide this information throughout the year, but must do it before they complete the EOPS. 2. Depending on the business income type you need to submit, the software calls the [Retrieve a Self-Employment Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Annual-Submission/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1annual~1%7BtaxYear%7D/get), [Retrieve a Historic Non-FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-non-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1non-furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/get) or [Retrieve a Historic FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/get). This step is optional, but we recommend it to ensure you are getting the most up-to-date information. 3. The customer views the allowances and adjustment information and updates relevant information. 4. Depending on the business income type you need to update, the software submits information using the [Create and Amend Self-Employment Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-employment-business-api/2.0/oas/page#tag/Self-Employment-Annual-Submission/paths/~1individuals~1business~1self-employment~1%7Bnino%7D~1%7BbusinessId%7D~1annual~1%7BtaxYear%7D/put), [Create and Amend a Historic Non-FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-non-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1non-furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/put) or [Create and Amend a Historic FHL UK Property Business Annual Submission](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/property-business-api/2.0/oas/page#tag/Historic-FHL-UK-Property-Business-Annual-Submission/paths/~1individuals~1business~1property~1uk~1annual~1furnished-holiday-lettings~1%7Bnino%7D~1%7BtaxYear%7D/put). 5. HMRC receives and stores information 6. The software calls the [Trigger a Self Assessment Tax Calculation](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individual-calculations-api/4.0/oas/page#tag/Tax-Calculations/paths/~1individuals~1calculations~1%7Bnino%7D~1self-assessment~1%7BtaxYear%7D/post) endpoint to get the calculation. 7. HMRC receives the request and returns a Calculation ID (calculationId) software must use this when calling the Self Assessment Tax Calculation endpoints. 8. The software receives the calculationId. Note: you could display the calculation to customers at this point if you choose, if you do follow steps 20 and 21 in the periodic update section. 9. The customer wants to make some accounting adjustments following the business accounts being finalised. 10. The software calls the [BSAS API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api). 11. HMRC returns summary totals of all the information for that business income source. 12. The software displays information to the customer. 13. The customer makes adjustments, confirms and submits. 14. The software sends information to HMRC using the [BSAS API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api). 15. HMRC confirms receipt and stores the information. 16. The software calls the relevant endpoints to retrieve the calculation. Note: the Tax Calculation can take up to 5 seconds to run, so we recommend the software waits 5 seconds – this is optional, the software does not have to retrieve the tax calculation information at this point. * [List Business Source Adjustable Summaries](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D/get) * [Trigger a Business Source Adjustable Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1trigger/post) * [Retrieve a Self-Employment Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Self-employment-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1self-employment~1%7BcalculationId%7D/get) * [Submit Self-Employment Accounting Adjustments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Self-employment-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1self-employment~1%7BcalculationId%7D~1adjust/post) * [Retrieve a UK Property Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/UK-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1uk-property~1%7BcalculationId%7D/get) * [Submit UK Property Accounting Adjustments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/UK-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1uk-property~1%7BcalculationId%7D~1adjust/post) * [Retrieve a Foreign Property Business Source Adjustable Summary (BSAS)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Foreign-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1foreign-property~1%7BcalculationId%7D/get) * [Submit Foreign Property Accounting Adjustments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-bsas-api/3.0/oas/page#tag/Foreign-property-business/paths/~1individuals~1self-assessment~1adjustable-summary~1%7Bnino%7D~1foreign-property~1%7BcalculationId%7D~1adjust/post) ## End-to-end user journey These journeys show examples of use: * [Income Tax Self Assessment (ITSA) set up activities](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/signup.html) * [retrieving obligations](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/businessandpropertyincome.html#retrieving-obligations) * [submitting periodic updates for Self Employment and property businesses](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/businessandpropertyincome.html#submit-income-and-expense-updates-for-self-employment-and-property-businesses) * [submitting annual updates for Self Employment and property businesses](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/businessandpropertyincome.html#submit-allowance-and-adjustment-updates-for-se-and-property-businesses) * [retrieving a tax calculation](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/businessandpropertyincome.html#retrieve-a-tax-calculation) * [making changes to previously submitted data](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/businessandpropertyincome.html#making-changes-to-previously-submitted-data) * [finalising business income End of Period Statement (EOPS)](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/businessandpropertyincome.html#finalise-business-income-end-of-period-statement-eops) * [providing information about how to treat a loss](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/final-declaration-crystallisation.html#providing-information-about-how-to-treat-a-loss) * [making a final declaration](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/final-declaration-crystallisation.html#final-declaration) * [ITSA (MTD) close down activities](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/documentation/closedown.html) ## Changelog ### API changelog The full changelog for Income Tax MTD APIs is now at [https://github.com/hmrc/income-tax-mtd-changelog](https://github.com/hmrc/income-tax-mtd-changelog) - that is the best source for detailed and comprehensive information about API changes. ### Documentation changelog Below is a summary of significant updates to this service guide: #### Version 3.1 * Added 'API lifecycle & deprecation' section, removed some duplicated content #### Version 3.0 * Updated API and endpoint links. #### Version 2.9 * Updated direct links to endpoints to reflect changes in how API documentation is published #### Version 2.8 * Updated HMRC Assist section #### Version 2.7 * Updated guide to reflect simplified v3.0 Final Declaration process and update section on customers opting out of MTD. #### Version 2.6 * Updated guide to reflect API changes including refactored Self Assessment Accounts API. #### Version 2.5 * Updated guide to reflect new API versions, update links and correct and clarify some content. #### Version 2.4 * Updated Frequently Asked Questions section to remove some items. #### Version 2.3 * Added note and an example table demonstrating how adjustments submitted work #### Version 2.2 * Added a Frequently Asked Questions section to the menu tree #### Version 2.1 * Notice of version change to Business Income Source Summary V1.0 * "Set up" heading replaced by "Sign up" with the menu tree updated to only have three sections: **Agent**, **Individual** and **Link software to HMRC**. * Updated content in the **Minimum functionality standards** section with two other sections added: **Bridging software** and **Non-MTD products** * Updated content in the **Declaration** and **Declaration for agents** sections of **Final declaration** (previously called "crystallisation") #### Version 2.0 * Addition of Capital Gains Tax, Marriage Allowance, Non-PAYE Income, Coding out underpayments and debts. #### Version 1.9 * Addition of requirement for businesses and landlords to provide information about residential property disposals * Addition of information regarding BSAS adjustments * Addition of content changes to meet MTD Style Guide V2.2 * Replacing the term ‘crystallisation’ with ‘final declaration' #### Version 1.8 * Addition of deprecation dates for Self Assessment API Endpoints * Notice of version change to Business Source Adjustable Summary (MTD) - V 1.0 * Notice of version change to Individual Losses (MTD) - V1.0 * Notice of version change to Individual Calculations v 1.0 #### Version 1.7 * Change of title to Income Tax (Making Tax Digital) end-to-end Service Guide * Inclusion of Income Tax (MTD) APIs * Inclusion of Tax Terminology * Addition of Foreign Property reference to Obligations * Replaced the term, ‘taxpayers’ with ‘customers’ * Replaced references to SA Accounting Summary API with BSAS API #### Version 1.6 * Revised wording for Draft MTD ITSA Regulations 2021 page. #### Version 1.5 * Production approvals process for Making Tax Digital for Self Assessment. * Early draft MTD ITSA Regulations 2021 section added. #### Version 1.4 * Construction Industry Scheme (CIS) section updated. #### Version 1.3 * Losses updated. * Additional income section added. #### Version 1.2 * Multiple businesses section added. * Construction Industry Scheme (CIS) section added. #### Version 1.1 * Payments and Liabilities section added. <file_sep>--- title: Sign up weight: 2 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- # Sign up ## Signing up to Making Tax Digital for Income Tax Sign up via API has been ruled out for security reasons. Taxpayers can sign up for Making Tax Digital for Income Tax without having software in place. However, they must get and authorise [software](https://developer.service.hmrc.gov.uk/guides/income-tax-mtd-end-to-end-service-guide/index.html#software-choices) before they start using Making Tax Digital for Income Tax. To use Making Tax Digital for Income Tax, individuals need to sign up first. To sign up, a user must: - Be a sole trader (self-employed) and/or - Have income from property, either in the UK or abroad See [Sign up as an individual for Making Tax Digital for Income Tax](https://www.gov.uk/guidance/sign-up-your-business-for-making-tax-digital-for-income-tax) for more information. If an individual is a self employed partner in a partnership, they do not need to sign up to MTD ITSA unless they have other MTD qualifying income such as: - They are also a self employed sole trader - They receive UK or foreign property income If this is the case, the individual must not include either their partner or partnership business details in the sign up service. Instead, this income will continue to be submitted as part of their self assessment tax return. There is no requirement at this time to submit partner or partnership income quarterly to HMRC. A user can also get their appointed tax agent (for instance, an accountant or bookkeeper) to sign up on their behalf, with their permission. We advise customers to speak to their agent (if they have one) before choosing software to ensure that it is compatible. ## Agent sign-up Before agents can sign up clients to Making Tax Digital, they must: * [Create an agent services account](https://www.gov.uk/guidance/get-an-hmrc-agent-services-account) * Have authorisation in place from their clients. Existing authorisations can be copied from Self Assessment, or agents can request authorisation for new clients. Both of these tasks can be done using their [agent services account](https://www.gov.uk/guidance/sign-in-to-your-agent-services-account). For more information, visit: [Making Tax Digital for Income Tax as an agent: step by step](https://www.gov.uk/government/collections/making-tax-digital-for-income-tax-as-an-agent-step-by-step) ## Individual sign-up Individuals who are self employed and/or have property income can sign themselves up for Making Tax Digital for Income Tax. For more information, visit: [Making Tax Digital for Income Tax for individuals: step by steps](https://www.gov.uk/government/collections/making-tax-digital-for-income-tax-for-businesses-step-by-step) ## Linking software to HMRC Businesses and agents using your software to connect to the [Income Tax (Making Tax Digital) APIs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api?filter=income-tax) must grant authority to your software to interact with HMRC on their behalf. We use the open standard [OAuth 2.0](https://oauth.net/2/) (opens in a new tab), which involves the business or agent signing in via their Government Gateway account and following the grant authority user journey. <a href="figures/link-software-to-hmrc.svg" target="blank"><img src="figures/link-software-to-hmrc.svg" alt="Link software to HMRC" style="width:720px;" /></a> [Open the link software to HMRC process diagram in a new tab.](https://developer.service.hmrc.gov.uk/guides/vat-mtd-end-to-end-service-guide/documentation/figures/link-software-to-hmrc.svg) 1. Business or agent requests to link your software to HMRC. 2. Your software launches the grant authority user journey. 3. Business or agent views the HMRC start page for an overview of the process and chooses to continue. 4. Business or agent signs in with their Government Gateway user ID and password (**agents must use their new agent services user ID**). 5. Business or agent registers for or completes 2-step verification as applicable. 6. Business or agent completes identity checks if applicable. 7. Business or agent grants authority for the software to interact with HMRC on their behalf. 8. HMRC generates an OAuth token for the business or agent. 9. Your software stores the business or agent’s OAuth token for later use in API calls on their behalf. Businesses and agents authenticate directly with us using their Government Gateway user ID and password, and grant the software the authority to interact with HMRC on their behalf. They grant this for a set of functions called API scopes which are required for each ITSA (MTD) endpoint. In the case of agents, they must sign in to their Government Gateway account with the user ID and password for their new agent services account, which was generated as part of the agent services account journey. We then generate an OAuth 2.0 access token for the software which is specific to the business or agent. The software must pass this access token in subsequent API requests as explained in authorisation of user-restricted endpoints. <file_sep>--- title: Coding Out Underpayments and Debts | Income Tax (MTD) End-to-End Service Guide weight: 33 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- <!--- Section owner: MTD Programme ---> # Coding Out When a Self Assessment customer has PAYE income in addition to business income, HMRC will try to collect any tax due on their final declaration through their tax code for the following tax year. There are some restrictions around this - see [Pay your Self Assessment tax bill: Through your tax code](https://www.gov.uk/pay-self-assessment-tax-bill/through-your-tax-code). If a customer does not want us to collect the underpayment by using the tax code, they have to request this through [Self Assessment Accounts (MTD)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/self-assessment-accounts-api/2.0/oas/page). This can be also be done through the ITSA submission service. ## Collecting MTD debts through the tax code In future, where an MTD customer with PAYE income in addition to business income has overdue tax charges, HMRC may try to collect this debt via their PAYE tax code. <file_sep>--- title: Customer Support Model | Income Tax (MTD) End-to-End Service Guide weight: 8 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- # Customer Support Model <!--- Section owner: MTD Programme ---> The customer support model guides HMRC customers to the most appropriate support. This may be provided by HMRC or the software vendor depending on the issue. The support offering for Income Tax Self Assessment (ITSA) customers includes guidance on [GOV.UK](https://www.gov.uk/contact/hm-revenue-customs/income-tax-enquiries-for-individuals-pensioners-and-employees), webchat, support links on all HMRC online pages, and support over the phone. We will provide additional support material here as we continue to develop the service. <file_sep>--- title: Capital Gains Tax | Income Tax (MTD) End-to-End Service Guide weight: 31 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- <!--- Section owner: MTD Programme ---> # Capital Gains Tax Capital Gains Tax is a tax on the profit when you sell or dispose of an asset that’s increased in value. From the 6th April 2020, a user selling a residential property in the UK must report and pay Capital Gains Tax. This must be done within 30 days of the sale. These endpoints allow a user to create, retrieve, delete or amend Capitals Gains income. Use these endpoints for Capitals Gains income from residential property disposals: * [Retrieve All CGT Residential Property Disposals and Overrides (Includes PPD and Non-PPD)](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Capital-Gains-on-Residential-Property-Disposals/paths/~1individuals~1income-received~1disposals~1residential-property~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend CGT Residential Property Disposals](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Capital-Gains-on-Residential-Property-Disposals/paths/~1individuals~1income-received~1disposals~1residential-property~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete CGT Residential Property Disposals](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Capital-Gains-on-Residential-Property-Disposals/paths/~1individuals~1income-received~1disposals~1residential-property~1%7Bnino%7D~1%7BtaxYear%7D/delete) * [Create and Amend ‘Report and Pay Capital Gains Tax on Property’ Overrides](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Capital-Gains-on-Residential-Property-Disposals/paths/~1individuals~1income-received~1disposals~1residential-property~1%7Bnino%7D~1%7BtaxYear%7D~1ppd/put) * [Delete ‘Report and Pay Capital Gains Tax on Residential Property’ Overrides](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Capital-Gains-on-Residential-Property-Disposals/paths/~1individuals~1income-received~1disposals~1residential-property~1%7Bnino%7D~1%7BtaxYear%7D~1ppd/delete) Use these endpoints for other Capital Gains and disposals: * [Retrieve Other Capital Gains and Disposals](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Other-Capital-Gains-and-Disposals/paths/~1individuals~1income-received~1disposals~1other-gains~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Other Capital Gains and Disposals](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Other-Capital-Gains-and-Disposals/paths/~1individuals~1income-received~1disposals~1other-gains~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Other Capital Gains and Disposals](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Other-Capital-Gains-and-Disposals/paths/~1individuals~1income-received~1disposals~1other-gains~1%7Bnino%7D~1%7BtaxYear%7D/delete) <file_sep>--- title: Penalties and Appeals | VAT (MTD) End-to-End Service Guide weight: 10 --- <!--- Section owner: MTD Programme ---> # Penalties and Appeals ## Penalties for late payment and late submission The way that HMRC penalises ITSA late payments and late submissions will be changing. The changes, referred to as 'Penalty Reform for ITSA', will apply to ITSA customers from the tax year in which they become mandated to join MTD. More information will follow as it is made available. For tax years prior to the changes, the existing late payment and late filing penalties continue to apply. You can find more information about these penalties on gov.uk: - [Penalties for late filing of Self Assessment tax returns](https://www.gov.uk/self-assessment-tax-returns/penalties) - [Self Assessment: how to appeal against penalties for late filing and late payment](https://www.gov.uk/government/publications/self-assessment-appeal-against-penalties-for-late-filing-and-late-payment-sa370/self-assessment-how-to-appeal-against-penalties-for-late-filing-and-late-payment) ## Other penalties Other penalties that apply to ITSA customers are unchanged by Penalty Reform and will continue to be charged where appropriate. These include: - [Inaccuracy penalties - Factsheet CC/FS7a](https://www.gov.uk/government/publications/compliance-checks-penalties-for-inaccuracies-in-returns-or-documents-ccfs7a) - [Penalties for not telling HMRC about an under-assessment - Factsheet CC/FS7b](https://www.gov.uk/government/publications/compliance-checks-penalties-for-not-telling-hmrc-about-an-under-assessment-ccfs7b) - [Penalties for failure to notify HMRC of a liability to tax - Factsheet CC/FS11](https://www.gov.uk/government/publications/compliance-checks-penalties-for-failure-to-notify-ccfs11) ## Paying penalties and interest Penalties must be paid within 30 days of the date on the penalty notice. Late payment interest will be charged on penalties that are not paid on time. ## Appeals The [existing process for appeals](https://www.gov.uk/tax-appeals/penalty) will remain in place, although a provision will be made as part of Penalty Reform to allow the user to appeal their late submission and late payment penalties through the digital tax account. A customer or agent may contact HMRC if they have a query about a tax decision. If they don’t understand the decision they can also get advice from HMRC or professional help.<file_sep>--- title: HMRC online services weight: 9 description: Sign in to HMRC online services to manage your income tax. --- <!--- Section owner: MTD Programme ---> # HMRC online services People who have signed up for Making Tax Digital for Income Tax can [sign into HMRC online services](https://www.gov.uk/log-in-register-hmrc-online-services) to access relevant services. They will be able to see: * a tax calculation based on income submitted to date (or a calculation forecast for the year) * when their filings and payments are due * how much they owe * their Self Assessment calculation for the previous year * a link to earlier Self Assessment records from before they joined Making Tax Digital They will also be able to: * make a payment * change their contact preference between paper and digital secure messages * submit an Income Tax return for income and allowances that aren’t supported by the software they use ## Future changes More features will be added to users’ accounts in the future. They will let people: * claim a repayment * request a budget payment plan * change the amount of a payment on account * provide bank details for future repayments * change their business details * add new business details for a self-employment or property business * close (‘cease’) a self-employment or property business * leave MTD if they’re a voluntary customer - they will also be able to sign up again from their account * print their Self Assessment SA302 tax calculation ## Agent access Agents will be able to access Making Tax Digital for Income Tax services through their agent services account. They’ll be able to access all current and future services on behalf of their clients, except for: * changing their client’s repayment bank details * changing their client’s contact preference ## The customer journey between software and HMRC online services To support the filing of business income updates and finalising their Self Assessment for the year, customers will be able use their software to: * change their quarterly period dates - they’ll be able to set their periods to finish at month end, rather than the 5th of the following month * view filing and payment obligations * request tax calculations For services that are not supported in their software, customers must use [HMRC online services](https://www.gov.uk/log-in-register-hmrc-online-services) and agents must use their [agent services account](https://www.gov.uk/guidance/sign-in-to-your-agent-services-account). <file_sep>--- title: Additional Income | Income Tax (MTD) End-to-End Service Guide weight: 30 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- # Additional Income ## Employments This suite of endpoints display the PAYE information returned to HMRC by a user’s employers. The user will be able to add to or supply different employment data after the tax year has ended. This can include details of missing employments, or financial data. In addition, the user can choose to ignore the data HMRC holds, for the purpose of their self-assessment calculation. These endpoints can be broken into three categories: * details of the employment * financial data and benefits from a specific employment * employment expenses from all of the user’s employments [Add a Custom Employment](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1{nino}~1{taxYear}/post) [Amend a Custom Employment](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1{nino}~1{taxYear}~1{employmentId}/put) [Retrieve an Employment](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1%7Bnino%7D~1%7BtaxYear%7D~1%7BemploymentId%7D/get) [List Employments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1%7Bnino%7D~1%7BtaxYear%7D/get) [Delete a Custom Employment](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1%7Bnino%7D~1%7BtaxYear%7D~1%7BemploymentId%7D/delete) [Ignore Employment](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1%7Bnino%7D~1%7BtaxYear%7D~1%7BemploymentId%7D~1ignore/post) [Unignore Employment](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1%7Bnino%7D~1%7BtaxYear%7D~1%7BemploymentId%7D~1unignore/post) [Create and Amend Employment Financial Details](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1%7Bnino%7D~1%7BtaxYear%7D~1%7BemploymentId%7D~1financial-details/put) [Retrieve an Employment and its Financial Details](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1%7Bnino%7D~1%7BtaxYear%7D~1%7BemploymentId%7D~1financial-details/get) [Delete Employment Financial Details](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Employments/paths/~1individuals~1income-received~1employments~1%7Bnino%7D~1%7BtaxYear%7D~1%7BemploymentId%7D~1financial-details/delete) [Create and Amend Employment Expenses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-expenses-api/1.0/oas/page#tag/Employment-Expenses/paths/~1individuals~1expenses~1employments~1%7Bnino%7D~1%7BtaxYear%7D/put) [Retrieve Employment Expenses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-expenses-api/1.0/oas/page#tag/Employment-Expenses/paths/~1individuals~1expenses~1employments~1%7Bnino%7D~1%7BtaxYear%7D/get) [Delete Employment Expenses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-expenses-api/1.0/oas/page#tag/Employment-Expenses/paths/~1individuals~1expenses~1employments~1%7Bnino%7D~1%7BtaxYear%7D/delete) [Ignore Employment Expenses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-expenses-api/1.0/oas/page#tag/Employment-Expenses/paths/~1individuals~1expenses~1employments~1%7Bnino%7D~1%7BtaxYear%7D~1ignore/post) HMRC will pre-populate the employment information provided by employers. The user should check and correct the information, as necessary, prior to final declaration. **Note:** Pre-populated data can only be stopped (ignored) from being used in any tax calculation. User-generated content: * can be deleted * will only be applied in the tax calculation * will not overwrite pre-populated data Custom employments will only apply to the tax year and will not be carried over in subsequent years. The expenses values are summed values from all PAYE employments, they are not available by employment. ## Other Employment Income These endpoints allow a user to create, amend, retrieve and delete other employment income: Share options, Shares awarded or received, Lump sums, Disability and Foreign service. * [Retrieve Other Employment Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Other-Employment-Income/paths/~1individuals~1income-received~1employments~1other~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Other Employment Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Other-Employment-Income/paths/~1individuals~1income-received~1employments~1other~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Other Employment Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Other-Employment-Income/paths/~1individuals~1income-received~1employments~1other~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/other-employment-income.svg" target="blank"> <img src="figures/other-employment-income.svg" alt=" " style="width:720px;" /> </a> <a href="figures/other-employment-income.svg" target="blank">Open diagram in a new tab.</a> ## Dividends Income These endpoints allow a user to create, retrieve, amend and delete dividends income: foreign dividend, dividend income received whilst abroad, stock dividend, redeemable shares, bonus issues of securities and close company loans written off. * [Retrieve Dividends Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Dividends-Income/paths/~1individuals~1income-received~1dividends~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Dividends Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Dividends-Income/paths/~1individuals~1income-received~1dividends~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Dividends Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Dividends-Income/paths/~1individuals~1income-received~1dividends~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/dividends-income.svg" target="blank"> <img src="figures/dividends-income.svg" alt=" " style="width:720px;" /> </a> <a href="figures/dividends-income.svg" target="blank">Open diagram in a new tab.</a> ## Foreign Income These endpoints give a user the ability to manage their data related to foreign earnings and unremittable foreign income. The user can submit details of their foreign earnings and foreign income for a specific tax year, as well as amend submissions already made. They also have the option to delete previous submissions and to retrieve the information they have previously submitted. * [Retrieve Foreign Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Foreign-Income/paths/~1individuals~1income-received~1foreign~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Foreign Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Foreign-Income/paths/~1individuals~1income-received~1foreign~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Foreign Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Foreign-Income/paths/~1individuals~1income-received~1foreign~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/foreign-income.svg" target="blank"> <img src="figures/foreign-income.svg" alt=" " style="width:720px;" /> </a> <a href="figures/foreign-income.svg" target="blank">Open diagram in a new tab.</a> ## Insurance Policies Income These endpoints allow a user to create, retrieve, amend and delete insurance policies and income for less common types of income: Life Insurance Policies, Life Annuity Contracts, Capital Redemption Policies, Voided ISAs, and Foreign Policies. * [Retrieve Insurance Policies Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Insurance-Policies-Income/paths/~1individuals~1income-received~1insurance-policies~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Insurance Policies Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Insurance-Policies-Income/paths/~1individuals~1income-received~1insurance-policies~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Insurance Policies Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Insurance-Policies-Income/paths/~1individuals~1income-received~1insurance-policies~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/insurance-policies-income.svg" target="blank"> <img src="figures/insurance-policies-income.svg" alt=" " style="width:720px;" /> </a> <a href="figures/insurance-policies-income.svg" target="blank">Open diagram in a new tab.</a> ## Pensions Income These endpoints allow a user to create, retrieve, amend and delete previously populated foreign pensions and overseas pension contributions. * [Retrieve Pensions Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Pensions-Income/paths/~1individuals~1income-received~1pensions~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Pensions Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Pensions-Income/paths/~1individuals~1income-received~1pensions~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Pensions Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Pensions-Income/paths/~1individuals~1income-received~1pensions~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/pensions-income.svg" target="blank"> <img src="figures/pensions-income.svg" alt=" " style="width:720px;" /> </a> <a href="figures/pensions-income.svg" target="blank">Open diagram in a new tab.</a> ## Other Income These endpoints allow a user to create, retrieve, amend and delete other income: business receipts, all other income received whilst abroad, overseas income and gains, chargeable foreign benefits and gifts and omitted foreign income. * [Retrieve Other Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Other-Income/paths/~1individuals~1income-received~1other~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Other Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Other-Income/paths/~1individuals~1income-received~1other~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Other Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Other-Income/paths/~1individuals~1income-received~1other~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/other-income.svg" target="blank"> <img src="figures/other-income.svg" alt=" " style="width:720px;" /> </a> <a href="figures/other-income.svg" target="blank">Open diagram in a new tab.</a> ## Savings Income These endpoints allow a user to create, retrieve, amend and delete savings income for securities or foreign interest. * [Retrieve Savings Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Savings-Income/paths/~1individuals~1income-received~1savings~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Savings Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Savings-Income/paths/~1individuals~1income-received~1savings~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Savings Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Savings-Income/paths/~1individuals~1income-received~1savings~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/savings-income.svg" target="blank"> <img src="figures/savings-income.svg" alt=" " style="width:720px;" /> </a> <a href="figures/savings-income.svg" target="blank">Open diagram in a new tab.</a> ## Savings Accounts These endpoints allow a user to retrieve and maintain information about an individual's UK savings account. * [List All UK Savings Accounts](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/UK-Savings-Account/paths/~1individuals~1income-received~1savings~1uk-accounts~1%7Bnino%7D/get) * [Add a UK Savings Account](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/UK-Savings-Account/paths/~1individuals~1income-received~1savings~1uk-accounts~1%7Bnino%7D/post) * [Retrieve UK Savings Account Annual Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/UK-Savings-Account/paths/~1individuals~1income-received~1savings~1uk-accounts~1%7Bnino%7D~1%7BtaxYear%7D~1%7BsavingsAccountId%7D/get) * [Create and Amend a UK Savings Account Annual Summary](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/UK-Savings-Account/paths/~1individuals~1income-received~1savings~1uk-accounts~1%7Bnino%7D~1%7BtaxYear%7D~1%7BsavingsAccountId%7D/put) <a href="figures/savings-accounts.svg" target="blank"> <img src="figures/savings-accounts.svg" alt=" " style="width:720px;" /> </a> <a href="figures/savings-accounts.svg" target="blank">Open diagram in a new tab.</a> ## Disclosures These endpoints allow the user to manage their data related to the disclosure of tax avoidance schemes and undeclared income, for a given tax year. The user can submit details of any disclosures for a specific tax year, as well as amend submissions already made. They also have the option to delete previous submissions and to retrieve the information they have previously submitted. The user would normally call this when they have all the information necessary for disclosures for the tax year. * [Retrieve Disclosures](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-disclosures-api/1.0/oas/page#tag/Disclosures/paths/~1individuals~1disclosures~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Disclosures](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-disclosures-api/1.0/oas/page#tag/Disclosures/paths/~1individuals~1disclosures~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Disclosures](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-disclosures-api/1.0/oas/page#tag/Disclosures/paths/~1individuals~1disclosures~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/disclosures.svg" target="blank"> <img src="figures/disclosures.svg" alt=" " style="width:720px;" /> </a> <a href="figures/disclosures.svg" target="blank">Open diagram in a new tab.</a> ## Pension Charges These endpoints allow a user to manage data related to pension contributions and charges. The user can submit details of pension contributions and charges for a specific tax year, as well as amend submissions already made. The user also has the option to delete previous submissions, and to retrieve the information they have previously submitted. * [Retrieve Pension Charges](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-charges-api/2.0/oas/page#/paths/~1individuals~1charges~1pensions~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Pension Charges](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-charges-api/2.0/oas/page#/paths/~1individuals~1charges~1pensions~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Pension Charges](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-charges-api/2.0/oas/page#/paths/~1individuals~1charges~1pensions~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/pension-charges.svg" target="blank"> <img src="figures/pension-charges.svg" alt=" " style="width:720px;" /> </a> <a href="figures/pension-charges.svg" target="blank">Open diagram in a new tab.</a> ## Individual Reliefs ### Pensions Reliefs These endpoints give the user the ability to manage data related to reliefs on pensions. The user can submit details of reliefs on pensions for a specific tax year, as well as amend submissions already made. They also have the option to delete previous submissions, and to retrieve the information they have previously submitted. * [Retrieve Pensions Reliefs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Pensions-Reliefs/paths/~1individuals~1reliefs~1pensions~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Pensions Reliefs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Pensions-Reliefs/paths/~1individuals~1reliefs~1pensions~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Pensions Reliefs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Pensions-Reliefs/paths/~1individuals~1reliefs~1pensions~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/pension-reliefs.svg" target="blank"> <img src="figures/pension-reliefs.svg" alt=" " style="width:720px;" /> </a> <a href="figures/pension-reliefs.svg" target="blank">Open diagram in a new tab.</a> ### Relief Investments These endpoints allow a user to create, amend, delete and retrieve relief investments from VCT subscriptions, EIS subscriptions, Community Investments, Seed Enterprise Investments and Social Enterprise Investments. * [Retrieve Relief Investments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Relief-Investments/paths/~1individuals~1reliefs~1investment~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Relief Investments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Relief-Investments/paths/~1individuals~1reliefs~1investment~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Relief Investments](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Relief-Investments/paths/~1individuals~1reliefs~1investment~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/relief-investments.svg" target="blank"> <img src="figures/relief-investments.svg" alt=" " style="width:720px;" /> </a> <a href="figures/relief-investments.svg" target="blank">Open diagram in a new tab.</a> ### Other Reliefs These endpoints allow a user to create, amend, retrieve and delete reliefs other than investments that have previously been submitted. This includes loan interest, payroll giving, shares and securities redemptions, maintenance payments, post-cessation reliefs, annual payments and qualifying loan interest payments. * [Retrieve Other Reliefs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Other-Reliefs/paths/~1individuals~1reliefs~1other~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Other Reliefs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Other-Reliefs/paths/~1individuals~1reliefs~1other~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Delete Other Reliefs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Other-Reliefs/paths/~1individuals~1reliefs~1other~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/other-reliefs.svg" target="blank"> <img src="figures/other-reliefs.svg" alt=" " style="width:720px;" /> </a> <a href="figures/other-reliefs.svg" target="blank">Open diagram in a new tab.</a> ### Foreign Reliefs These endpoints allow a user to create, retrieve, amend, and delete foreign reliefs that have been previously submitted. * [Retrieve Foreign Reliefs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Foreign-Reliefs/paths/~1individuals~1reliefs~1foreign~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Foreign Reliefs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Foreign-Reliefs/paths/~1individuals~1reliefs~1foreign~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Foreign Reliefs](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-reliefs-api/1.0/oas/page#tag/Foreign-Reliefs/paths/~1individuals~1reliefs~1foreign~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/foreign-reliefs.svg" target="blank"> <img src="figures/foreign-reliefs.svg" alt=" " style="width:720px;" /> </a> <a href="figures/foreign-reliefs.svg" target="blank">Open diagram in a new tab.</a> ## Other Deductions At present this only relates to seafarers, but other deductions will be added in future. These endpoints allow a user to manage their data related to deductions from their tax bill. The user can submit details of their deductions for a specific tax year, as well as amend submissions already made. They also have the option to delete previous submissions, and to retrieve the information they have previously submitted. * [Retrieve Deductions](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/other-deductions-api/1.0/oas/page#/paths/~1individuals~1deductions~1other~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Deductions](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/other-deductions-api/1.0/oas/page#/paths/~1individuals~1deductions~1other~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Deductions](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/other-deductions-api/1.0/oas/page#/paths/~1individuals~1deductions~1other~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/other-deductions.svg" target="blank"> <img src="figures/other-deductions.svg" alt=" " style="width:720px;" /> </a> <a href="figures/other-deductions.svg" target="blank">Open diagram in a new tab.</a> ## Individual Expenses Other These endpoints allow the user to manage their data related to expenses income for trade union and patent royalties. The user can submit details of their expenses income for a specific tax year, as well as amend submissions already made. They also have the option to delete previous submissions, and to retrieve the information they have previously submitted. * [Retrieve Other Expenses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-expenses-api/1.0/oas/page#tag/Other-Expenses/paths/~1individuals~1expenses~1other~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create and Amend Other Expenses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-expenses-api/1.0/oas/page#tag/Other-Expenses/paths/~1individuals~1expenses~1other~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Delete Other Expenses](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-expenses-api/1.0/oas/page#tag/Other-Expenses/paths/~1individuals~1expenses~1other~1%7Bnino%7D~1%7BtaxYear%7D/delete) <a href="figures/expenses-other.svg" target="blank"> <img src="figures/expenses-other.svg" alt=" " style="width:720px;" /> </a> <a href="figures/expenses-other.svg" target="blank">Open diagram in a new tab.</a> ## Non-PAYE Income Use the [Non-PAYE Income resources of the Individuals Income Received API](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Non-PAYE-Employment-Income) to create, amend, retrieve and delete data relating to non PAYE income and tips: * [Create and Amend Non-PAYE Employment Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Non-PAYE-Employment-Income/paths/~1individuals~1income-received~1employments~1non-paye~1%7Bnino%7D~1%7BtaxYear%7D/put) * [Retrieve Non-PAYE Employment Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Non-PAYE-Employment-Income/paths/~1individuals~1income-received~1employments~1non-paye~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Delete Non-PAYE Employment Income](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-income-received-api/2.0/oas/page#tag/Non-PAYE-Employment-Income/paths/~1individuals~1income-received~1employments~1non-paye~1%7Bnino%7D~1%7BtaxYear%7D/delete) ## State Benefits These endpoints give a user the ability to manage data related to state benefits. The user can add details about state benefits for a specific tax year, as well as update submissions already made. They also have the option to delete previous submissions, and to retrieve the information they have previously submitted. **Note** * only pre-populated HMRC benefits can be ignored (end-of-year) or unignored * attempting to delete a pre-populated state benefit will fail with a 'forbidden' response. * a customer can only update amounts in-year for Job Seeker Allowance and Employment Support Allowance * [List State Benefits](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-state-benefits-api/1.0/oas/page#/paths/~1individuals~1state-benefits~1%7Bnino%7D~1%7BtaxYear%7D/get) * [Create State Benefit](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-state-benefits-api/1.0/oas/page#/paths/~1individuals~1state-benefits~1%7Bnino%7D~1%7BtaxYear%7D/post) * [Amend State Benefit](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-state-benefits-api/1.0/oas/page#/paths/~1individuals~1state-benefits~1%7Bnino%7D~1%7BtaxYear%7D~1%7BbenefitId%7D/put) * [Delete State Benefit](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-state-benefits-api/1.0/oas/page#/paths/~1individuals~1state-benefits~1%7Bnino%7D~1%7BtaxYear%7D~1%7BbenefitId%7D/delete) * [Amend State Benefit Amounts](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-state-benefits-api/1.0/oas/page#/paths/~1individuals~1state-benefits~1%7Bnino%7D~1%7BtaxYear%7D~1%7BbenefitId%7D~1amounts/put) * [Delete State Benefit Amounts](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-state-benefits-api/1.0/oas/page#/paths/~1individuals~1state-benefits~1%7Bnino%7D~1%7BtaxYear%7D~1%7BbenefitId%7D~1amounts/delete) * [Ignore State Benefit](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-state-benefits-api/1.0/oas/page#/paths/~1individuals~1state-benefits~1%7Bnino%7D~1%7BtaxYear%7D~1%7BbenefitId%7D~1ignore/post) * [Unignore State Benefit](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/individuals-state-benefits-api/1.0/oas/page#/paths/~1individuals~1state-benefits~1%7Bnino%7D~1%7BtaxYear%7D~1%7BbenefitId%7D~1unignore/post) <a href="figures/state-benefits.svg" target="blank"> <img src="figures/state-benefits.svg" alt=" " style="width:720px;" /> </a> <a href="figures/state-benefits.svg" target="blank">Open diagram in a new tab.</a> <file_sep>--- title: Construction Industry Scheme weight: 4 description: Software developers, designers, product owners or business analysts. Integrate your software with the Income Tax API for Making Tax Digital. --- <!--- Section owner: MTD Programme ---> # Construction Industry Scheme These endpoints allow a subcontractor working within the [Construction Industry Scheme (CIS)](https://www.gov.uk/what-is-the-construction-industry-scheme) to retrieve, submit, override and delete the gross income, cost of materials and tax deducted amounts if they disagree with the amounts submitted on their behalf by the contractors they have worked for during the tax year. The tax deducted monthly by the contractor will be credited to the subcontractor within their tax calculation during the tax year. When the user sends their quarterly update and retrieves a tax calculation this will include the tax deducted by the contractor, the user may want to call these endpoints to query or check the data supplied by the contractor. When the user does not agree with the data the contractor has reported to HMRC, the user can submit what they believe to be the correct amounts, or if no data from the contractor is included in the calculation, the user may want to submit the details so that they can be given credit for the tax the contractor has deducted on their behalf. This can only be supplied after the end of the tax year. During the year, the user should also query this with the contractor as they may need to amend the monthly return they make to HMRC, or query with the contractor why monthly returns are not being made to HMRC. If the user has submitted data after the end of the year because no data was supplied by the contractor or they did not agree with the data the contractor has reported to HMRC but the user later realises the data they submitted is incorrect, they can simply delete the data using the [Delete CIS Deductions for Subcontractor](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/cis-deductions-api/2.0/oas/page#/paths/~1individuals~1deductions~1cis~1%7Bnino%7D~1amendments~1%7BsubmissionId%7D/delete) endpoint. If any data the user has submitted is different from the records HMRC hold the user data is accepted. Any discrepancies will be flagged by the system for a HMRC review. [Create CIS Deductions for Subcontractor](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/cis-deductions-api/2.0/oas/page#/paths/~1individuals~1deductions~1cis~1%7Bnino%7D~1amendments/post) - this endpoint allows a user to create a customer override to the CIS deductions which have been previously populated by data submitted directly to HMRC by the contractor, or create CIS deductions if no data has been submitted to HMRC by the Contractor. A National Insurance number must be provided. <a href="figures/cis-create-cis.svg" target="blank"><img src="figures/cis-create-cis.svg" alt="CIS create diagram" style="width:720px;" /></a> <a href="figures/cis-create-cis.svg" target="blank">Open the CIS create deduction diagram in a new tab</a>. [Amend CIS Deductions for Subcontractor](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/cis-deductions-api/2.0/oas/page#/paths/~1individuals~1deductions~1cis~1%7Bnino%7D~1amendments~1%7BsubmissionId%7D/put) - this endpoint allows a user to amend the override CIS deductions that have been previously submitted by the user. A National Insurance number and submission ID must be provided. <a href="figures/cis-amend-cis.svg" target="blank"><img src="figures/cis-amend-cis.svg" alt="CIS amend diagram" style="width:720px;" /></a> <a href="figures/cis-amend-cis.svg" target="blank">Open the CIS amend deduction diagram in a new tab</a>. [Retrieve CIS Deductions for Subcontractor](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/cis-deductions-api/2.0/oas/page#/paths/~1individuals~1deductions~1cis~1%7Bnino%7D~1current-position/get) - this endpoint allows a user to retrieve the latest CIS deductions position and whether contractor or user data has been used in the latest calculation. A National Insurance number and submission ID must be provided. <a href="figures/cis-retrieve-cis.svg" target="blank"><img src="figures/cis-retrieve-cis.svg" alt="CIS create diagram" style="width:720px;" /></a> <a href="figures/cis-retrieve-cis.svg" target="blank">Open the CIS retrieve deduction diagram in a new tab</a>. [Delete CIS Deductions for Subcontractor](https://developer.service.hmrc.gov.uk/api-documentation/docs/api/service/cis-deductions-api/2.0/oas/page#/paths/~1individuals~1deductions~1cis~1%7Bnino%7D~1amendments~1%7BsubmissionId%7D/delete) - this endpoint allows a user to delete user submitted CIS overrides which have been previously submitted. A National Insurance number and submission ID must be provided. <a href="figures/cis-delete-cis.svg" target="blank"><img src="figures/cis-delete-cis.svg" alt="CIS delete diagram" style="width:720px;" /></a> <a href="figures/cis-delete-cis.svg" target="blank">Open the CIS delete deduction diagram in a new tab</a>. <file_sep># Technical Documentation - Income Tax MTD Service Guide ## Getting started To preview or build the website, you need to use the terminal. Install Ruby with Rubygems, preferably with a [Ruby version manager][rvm], and the [Bundler gem][bundler]. In the application folder type the following to install the required gems (you may encounter errors, see the [Troubleshooting Guide](./TROUBLESHOOTING.md)): ``` bundle install ``` ### Installation guidance by operating system macOS: do not use the built-in Ruby that comes with macOS. It is best to install a separate Ruby and rvm using [Homebrew](https://brew.sh/). Windows: the best approach on Windows is to use [RubyInstaller](https://rubyinstaller.org/). The guide is known to build correctly on Windows 10 using RubyInstaller 3.2.2. ## Making changes To make changes edit the source files in the `source` folder. ### Single page output Although a single page of HTML is generated, the markdown is spread across multiple files to make it easier to manage. They can be found in `source/documentation`. A new markdown file isn't automatically included in the generated output. If we add a new markdown file at the location `source/documentation/agile/scrum.md`, the following snippet in `source/index.html.md.erb`, includes it in the generated output. ``` <%= partial 'documentation/agile/scrum' %> ``` Including files manually like this lets you specify the position they appear in the page. The `weight` variable specified at the beginning of each markdown file can be used to specify the order of sections - a higher `weight` value is displayed lower on the output page. ### Multiple pages To add a completely new page, create a file with a `.html.md` extension in the `/source` directory. For example, `source/about.html.md` will be accessible on <http://localhost:4567/about.html>. ## Preview Whilst writing documentation you can run a middleman server to preview how the published version will look in the browser. After saving a change the preview in the browser will automatically refresh. Make sure to preview your changes locally before you commit them. The preview is only available on your own computer. Others won't be able to access it if they are given the link. Type the following to start the server: ``` bundle exec middleman server ``` If all goes well something like the following output will be displayed: ``` == The Middleman is loading == LiveReload accepting connections from ws://192.168.0.8:35729 == View your site at "http://Laptop.local:4567", "http://192.168.0.8:4567" == Inspect your site configuration at "http://Laptop.local:4567/__middleman", "http://192.168.0.8:4567/__middleman" ``` You should now be able to view a live preview at http://localhost:4567. ## Build If you want to publish the website without using a build script you may need to build the static HTML files. Type the following to build the HTML: ``` bundle exec middleman build ``` This will create a `build` subfolder in the application folder which contains the HTML and asset files ready to be published. [rvm]: https://www.ruby-lang.org/en/documentation/installation/#managers [bundler]: http://bundler.io/ ### License This code is open source software licensed under the [Apache 2.0 License]("http://www.apache.org/licenses/LICENSE-2.0.html").
ca4e085294c59a2a59ed123eda3bf6a02054b595
[ "Markdown", "Ruby" ]
19
Markdown
hmrc/income-tax-mtd-end-to-end-service-guide
765443e4b27f633c83970305904f0f729fa3afcf
319549f82772f1577ede622c126573eb91546738
refs/heads/master
<file_sep>class HomeController < ApplicationController def index end def test end def main end def show @searched_book_title = params[:book] @books = Book.all @book_list = [] @books.each do |book| if book.title.include? @searched_book_title @book_list.push(book) end end end def obj @shelf_id = params[:shelf_id] @shelf = Shelf.find(@shelf_id) @shelf_x = @shelf.x-50 if @shelf.z<0 @shelf_z = @shelf.z-360 else @shelf_z = @shelf.z+270 end end end <file_sep>// function init() { // var scene = new THREE.Scene(); // var camera = new THREE.PerspectiveCamera(80, window.innerWidth/window.innerHeight, 0.1, 1000); // var renderer = new THREE.WebGLRenderer(); // renderer.setClearColor(0xEEEEEE); // renderer.setSize(window.innerWidth, window.innerHeight); // //Show Axis // var axes = new THREE.AxisHelper(10); // scene.add(axes); // //Let's make a cube // var cubeGeometry = new THREE.BoxGeometry(6,6,6); // var cubeMeterial = new THREE.MeshBasicMaterial({color: 0x0089A0}); // var cube = new THREE.Mesh(cubeGeometry, cubeMeterial); // cube.position.x = 0; // cube.position.y = 10; // cube.position.z = 10; // scene.add(cube); // //Let's make a sphere // var sphereGeometry = new THREE.SphereGeometry(4,32,32); // var sphereMeterial = new THREE.MeshBasicMaterial({color: 0xFE98A0}); // var sphere = new THREE.Mesh(sphereGeometry, sphereMeterial); // sphere.position.x = -15; // sphere.position.y = 2; // sphere.position.z = 0; // scene.add(sphere); // var vShader = $('vertexshader'); // var fShader = $('fragmentshader'); // var shaderMaterial = // new THREE.ShaderMaterial({ // vertexShader: vShader.text(), // fragmentShader: fShader.text() // }); // //Let's make a plane // var planeGeometry = new THREE.PlaneGeometry(60,30,1,1); // var planeMaterial = new THREE.MeshBasicMaterial({color: 0xCCCCCC}); // var plane = new THREE.Mesh(planeGeometry, planeMaterial); // plane.rotation.x = -0.5 * Math.PI; // scene.add(plane); // camera.position.x = 0; // camera.position.y = 30; // camera.position.z = 30; // camera.lookAt(scene.position); // // 여기서 페이지에 올려줌. // document.getElementById("threejs_scene").appendChild(renderer.domElement); // renderScene(); // function renderScene() { // renderer.render(scene,camera); // } // } // window.onload = init(); // 쉐이더 부분 var container; var camera, scene, renderer; var uniforms, material, mesh; var mouseX = 0, mouseY = 0, lat = 0, lon = 0, phy = 0, theta = 0; var windowHalfX = window.innerWidth / 2; var windowHalfY = window.innerHeight / 2; init(); var startTime = Date.now(); animate(); function init() { container = document.getElementById( 'threejs_scene' ); camera = new THREE.Camera(); camera.position.z = 1; scene = new THREE.Scene(); uniforms = { time: { type: "f", value: 1.0 }, resolution: { type: "v2", value: new THREE.Vector2() } }; material = new THREE.ShaderMaterial( { uniforms: uniforms, vertexShader: document.getElementById( 'vertexShader' ).textContent, fragmentShader: document.getElementById( 'fragmentShader' ).textContent }); mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), material ); scene.add( mesh ); renderer = new THREE.WebGLRenderer(); container.appendChild( renderer.domElement ); uniforms.resolution.value.x = window.innerWidth; uniforms.resolution.value.y = window.innerHeight; renderer.setSize( window.innerWidth, window.innerHeight ); } function animate() { requestAnimationFrame( animate ); render(); } function render() { var elapsedMilliseconds = Date.now() - startTime; var elapsedSeconds = elapsedMilliseconds / 1000.; uniforms.time.value = 60. * elapsedSeconds; renderer.render( scene, camera ); }<file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # t.string :shelf_ew # t.integer :self_no # t.integer :x # t.integer :z # t.integer :kind # Section D shelf1 = Shelf.create({shelf_ew:'E', shelf_no:1, x:-1200, z:-360, kind:0}) shelf2 = Shelf.create({shelf_ew:'E', shelf_no:2, x:-1350, z:-360, kind:0}) shelf3 = Shelf.create({shelf_ew:'E', shelf_no:3, x:-1500, z:-360, kind:0}) shelf4 = Shelf.create({shelf_ew:'E', shelf_no:4, x:-1650, z:-360, kind:0}) shelf5 = Shelf.create({shelf_ew:'E', shelf_no:5, x:-1800, z:-360, kind:0}) shelf6 = Shelf.create({shelf_ew:'E', shelf_no:6, x:-1950, z:-360, kind:0}) shelf7 = Shelf.create({shelf_ew:'E', shelf_no:7, x:-2100, z:-360, kind:0}) shelf8 = Shelf.create({shelf_ew:'E', shelf_no:8, x:-2250, z:-360, kind:0}) shelf9 = Shelf.create({shelf_ew:'E', shelf_no:9, x:-2400, z:-360, kind:0}) # Section E shelf10 = Shelf.create({shelf_ew:'E', shelf_no:10, x:-1200, z:-1370, kind:0}) shelf11 = Shelf.create({shelf_ew:'E', shelf_no:11, x:-1350, z:-1370, kind:0}) shelf12 = Shelf.create({shelf_ew:'E', shelf_no:12, x:-1500, z:-1370, kind:0}) shelf13 = Shelf.create({shelf_ew:'E', shelf_no:13, x:-1650, z:-1370, kind:0}) shelf14 = Shelf.create({shelf_ew:'E', shelf_no:14, x:-1800, z:-1370, kind:0}) shelf15 = Shelf.create({shelf_ew:'E', shelf_no:15, x:-1950, z:-1370, kind:0}) shelf16 = Shelf.create({shelf_ew:'E', shelf_no:16, x:-2100, z:-1370, kind:0}) # Section A shelf17 = Shelf.create({shelf_ew:'W', shelf_no:1, x:3750, z:720, kind:0}) shelf18 = Shelf.create({shelf_ew:'W', shelf_no:2, x:3600, z:720, kind:0}) shelf19 = Shelf.create({shelf_ew:'W', shelf_no:3, x:3450, z:720, kind:0}) shelf20 = Shelf.create({shelf_ew:'W', shelf_no:4, x:3300, z:720, kind:0}) shelf21 = Shelf.create({shelf_ew:'W', shelf_no:5, x:3150, z:720, kind:0}) shelf22 = Shelf.create({shelf_ew:'W', shelf_no:6, x:3000, z:720, kind:0}) shelf23 = Shelf.create({shelf_ew:'W', shelf_no:7, x:2850, z:720, kind:0}) shelf24 = Shelf.create({shelf_ew:'W', shelf_no:8, x:2700, z:720, kind:0}) shelf25 = Shelf.create({shelf_ew:'W', shelf_no:9, x:2550, z:720, kind:0}) shelf26 = Shelf.create({shelf_ew:'W', shelf_no:10, x:2400, z:720, kind:0}) shelf27 = Shelf.create({shelf_ew:'W', shelf_no:11, x:2250, z:720, kind:0}) shelf28 = Shelf.create({shelf_ew:'W', shelf_no:12, x:2100, z:720, kind:0}) shelf29 = Shelf.create({shelf_ew:'W', shelf_no:13, x:1950, z:720, kind:0}) shelf30 = Shelf.create({shelf_ew:'W', shelf_no:14, x:1800, z:720, kind:0}) # Section B shelf31 = Shelf.create({shelf_ew:'W', shelf_no:15, x:3700, z:-180, kind:0}) shelf32 = Shelf.create({shelf_ew:'W', shelf_no:16, x:3550, z:-180, kind:0}) shelf33 = Shelf.create({shelf_ew:'W', shelf_no:17, x:3400, z:-180, kind:0}) shelf34 = Shelf.create({shelf_ew:'W', shelf_no:18, x:3250, z:-180, kind:0}) shelf35 = Shelf.create({shelf_ew:'W', shelf_no:19, x:3100, z:-180, kind:0}) shelf36 = Shelf.create({shelf_ew:'W', shelf_no:20, x:2950, z:-180, kind:0}) shelf37 = Shelf.create({shelf_ew:'W', shelf_no:21, x:2800, z:-180, kind:0}) shelf38 = Shelf.create({shelf_ew:'W', shelf_no:22, x:2650, z:-180, kind:0}) shelf39 = Shelf.create({shelf_ew:'W', shelf_no:23, x:2500, z:-180, kind:0}) shelf40 = Shelf.create({shelf_ew:'W', shelf_no:24, x:2350, z:-180, kind:0}) shelf41 = Shelf.create({shelf_ew:'W', shelf_no:25, x:2200, z:-180, kind:0}) shelf42 = Shelf.create({shelf_ew:'W', shelf_no:26, x:2050, z:-180, kind:0}) shelf43 = Shelf.create({shelf_ew:'W', shelf_no:27, x:1900, z:-180, kind:0}) shelf44 = Shelf.create({shelf_ew:'W', shelf_no:28, x:1750, z:-180, kind:0}) shelf45 = Shelf.create({shelf_ew:'W', shelf_no:29, x:1600, z:-180, kind:0}) shelf46 = Shelf.create({shelf_ew:'W', shelf_no:30, x:1450, z:-180, kind:0}) shelf47 = Shelf.create({shelf_ew:'W', shelf_no:31, x:1300, z:-180, kind:0}) shelf48 = Shelf.create({shelf_ew:'W', shelf_no:32, x:1150, z:-180, kind:0}) shelf49 = Shelf.create({shelf_ew:'W', shelf_no:33, x:1000, z:-180, kind:0}) # Section C shelf50 = Shelf.create({shelf_ew:'W', shelf_no:34, x:2650, z:-1190, kind:0}) shelf51 = Shelf.create({shelf_ew:'W', shelf_no:35, x:2500, z:-1190, kind:0}) shelf52 = Shelf.create({shelf_ew:'W', shelf_no:36, x:2350, z:-1190, kind:0}) shelf53 = Shelf.create({shelf_ew:'W', shelf_no:37, x:2200, z:-1190, kind:0}) shelf54 = Shelf.create({shelf_ew:'W', shelf_no:38, x:2050, z:-1190, kind:0}) shelf55 = Shelf.create({shelf_ew:'W', shelf_no:39, x:1900, z:-1190, kind:0}) shelf56 = Shelf.create({shelf_ew:'W', shelf_no:40, x:1750, z:-1460, kind:0}) shelf57 = Shelf.create({shelf_ew:'W', shelf_no:41, x:1600, z:-1190, kind:0}) shelf58 = Shelf.create({shelf_ew:'W', shelf_no:42, x:1450, z:-1190, kind:0}) shelf59 = Shelf.create({shelf_ew:'W', shelf_no:43, x:1300, z:-1190, kind:0}) shelf60 = Shelf.create({shelf_ew:'W', shelf_no:44, x:1150, z:-1190, kind:0}) shelf61 = Shelf.create({shelf_ew:'W', shelf_no:45, x:1000, z:-1190, kind:0}) # Book Data # 그래픽스 검색시 book = Book.create({title:'OpenGL로 배우는 3차원 컴퓨터 그래픽스', author:'주우석', index:'T385 주66 2012', shelf_id:'8'}) book = Book.create({title:'2D 그래픽스 기초이론', author:'유민호', index:'T385 투28 2007', shelf_id:'8'}) book = Book.create({title:'UG(유니그래픽스) NX-7 3D 모델링 프로젝트', author:'길부석', index:'T385 길46 2011', shelf_id:'7'}) book = Book.create({title:'모바일 플랫폼 기반 3차원 그래픽스 가속기 SoC구현', author:'김명환', index:'TK6570.M6 김34 2007', shelf_id:'12'}) book = Book.create({title:'R 그래픽스', author:'유충현', index:'T385 유85 2007', shelf_id:'8'}) book = Book.create({title:'유니그래픽스 NX3', author:'엄정섭', index:'TS155.6 엄74 2006', shelf_id:'15'}) book = Book.create({title:'컴퓨터 그래픽스 배움터', author:'최윤철', index:'T385 최66 2006', shelf_id:'8'}) book = Book.create({title:'(3Ds max를 이용한) 3D 그래픽스', author:'조용규', index:'TR897.7 조65 2006', shelf_id:'15'}) book = Book.create({title:'(3차원 공간이 보이는)컴퓨터 그래픽스', author:'김성호', index:'T385 김54 2013', shelf_id:'7'}) book = Book.create({title:'(컴퓨터 그래픽스를 활용한) C언어 배우기', author:'이경희', index:'QA76.73.C153 이14 2006', shelf_id:'59'}) book = Book.create({title:'애프터이펙트 애니그래픽스 VFX 튜토리얼 20', author:'문성철', index:'T385 문54 2008', shelf_id:'7'}) # Graphics 검색시 book = Book.create({title:'Advances in computer graphics III', author:'Ruiter', index:'T385 A38 1988', shelf_id:'8'}) book = Book.create({title:'Computer graphics : principles and practice', author:'Hughes', index:'T385 C66 2014', shelf_id:'8'}) book = Book.create({title:'Computer graphics with OpenGL', author:'Hearn', index:'T385 H43 2011', shelf_id:'8'}) book = Book.create({title:'Foundations of 3D computer graphics', author:'Gortler', index:'T385 G67 2012', shelf_id:'8'}) book = Book.create({title:'Point-based graphics', author:'Gross', index:'T385 P65 2007', shelf_id:'8'}) book = Book.create({title:'Interactive computer graphics : a top-down approach with WebGL', author:'Angel', index:'T385 A54 2015', shelf_id:'8'}) book = Book.create({title:'Mathematical tools in computer graphics with C# implementations', author:'Hardy', index:'T385 H37 2008', shelf_id:'8'}) book = Book.create({title:'Computer graphics and geometric modeling for engineers', author:'Anand', index:'T385 A53 1993', shelf_id:'8'}) book = Book.create({title:'Fundamentals of computer-aided engineering', author:'Raphael', index:'TA345 R39 2003', shelf_id:'8'}) book = Book.create({title:'Smart graphics : third International Symposium on Smart Graphics, SG 2003, Heidelberg, Germany, July 2-4, 2003 : proceedings', author:'Butz', index:'T385 S378 2003', shelf_id:'8'})
e847835de4bcb63c033369027c6c2686e8d3b6a6
[ "JavaScript", "Ruby" ]
3
Ruby
seobew/booksearch_webgl
043c27deb51fd7b914b20c16f9dfe2b58b5a6053
cf01d3184d760b5cbd2c1464f46525d216aec297
refs/heads/master
<repo_name>nashika/evernote-tasklog<file_sep>/src/common/entity/notebook.entity.ts import { BaseEvernoteEntity } from "./base-evernote.entity"; import { EntityParams } from "./base.entity"; export class NotebookEntity extends BaseEvernoteEntity { FIELD_NAMES!: | "name" | "defaultNotebook" | "serviceCreated" | "serviceUpdated" | "publishing" | "stack" | "sharedNotebookIds" | "sharedNotebooks" | "businessNotebooks" | "contact" | "restrictions" | "recipientSettings" | BaseEvernoteEntity["FIELD_NAMES3"]; static readonly params: EntityParams<NotebookEntity> = { name: "notebook", primaryKey: "guid", displayField: "name", archive: false, default: { order: { stack: "ASC", name: "ASC" }, take: 500, }, append: {}, columns: { guid: { type: "string", primary: true, nullable: false, }, name: { type: "string", nullable: false, }, updateSequenceNum: { type: "integer", nullable: false, }, defaultNotebook: { type: "boolean", nullable: false, }, serviceCreated: { type: "integer", nullable: true, }, serviceUpdated: { type: "integer", nullable: true, }, publishing: { type: "text", nullable: true, }, published: { type: "boolean", nullable: true, }, stack: { type: "string", nullable: true, }, sharedNotebookIds: { type: "text", nullable: true, }, sharedNotebooks: { type: "text", nullable: true, }, businessNotebooks: { type: "text", nullable: true, }, contact: { type: "text", nullable: true, }, restrictions: { type: "text", nullable: true, }, recipientSettings: { type: "text", nullable: true, }, }, jsonFields: [ "publishing", "sharedNotebookIds", "sharedNotebooks", "businessNotebooks", "contact", "restrictions", "recipientSettings", ], }; name!: string; defaultNotebook!: boolean; serviceCreated!: number | null; serviceUpdated!: number | null; publishing!: Object | null; published!: boolean | null; stack!: string | null; sharedNotebookIds!: number[] | null; sharedNotebooks!: Object[] | null; businessNotebooks!: Object | null; contact!: Object | null; restrictions!: Object | null; recipientSettings!: Object | null; } <file_sep>/src/common/entity/base-evernote.entity.ts import { BaseEntity } from "./base.entity"; export abstract class BaseEvernoteEntity extends BaseEntity { FIELD_NAMES3!: "guid" | "updateSequenceNum" | BaseEntity["FIELD_NAMES2"]; guid!: string; updateSequenceNum!: number; } <file_sep>/src/server/route/base.route.ts import _ from "lodash"; import SocketIO from "socket.io"; import { injectable } from "inversify"; import { logger } from "~/src/common/logger"; export abstract class CodeError extends Error { code: number = 0; } export class Code403Error extends CodeError { code: number = 403; message: string = "Access Forbidden"; } export class Code404Error extends CodeError { code: number = 404; message: string = "Not Found"; } export class Code500Error extends CodeError { code: number = 500; message: string = "Internal Server Error"; } @injectable() export abstract class BaseRoute { abstract get basePath(): string; abstract connect(_socket: SocketIO.Socket): Promise<void>; protected on( socket: SocketIO.Socket, action: string, func: (...args: any[]) => Promise<any> ) { const event = this.basePath + "::" + action; socket.on(event, (...args: any[]) => { const ack: (data: any) => void = _.last(args); const funcArgs: any[] = _.initial(args); logger.info( `Request from id="${ socket.id }", event="${event}", args=${JSON.stringify(funcArgs)}}` ); (<Promise<any>>func.call(this, socket, ...funcArgs)) .then((data) => { ack(data); }) .catch((err) => { logger.error( `Error occurred in socket.io request. id="${ socket.id }", event="${event}", args="${JSON.stringify(funcArgs)}".\n${ err.stack || err }` ); ack({ $$err: true, $$errMessage: err.toString() }); }); }); } } <file_sep>/src/server/index.ts import "reflect-metadata"; import * as https from "https"; import path from "path"; import * as fs from "fs"; import * as http from "http"; import express from "express"; // @ts-ignore import { Nuxt, Builder } from "nuxt"; // Import and Set Nuxt.js options import config from "../../nuxt.config"; import "~/src/server/inversify.config"; import { MainService } from "~/src/server/service/main.service"; import { container } from "~/src/common/inversify.config"; import { logger } from "~/src/common/logger"; import { appConfigLoader } from "~/src/common/util/app-config-loader"; const app = express(); config.dev = process.env.NODE_ENV !== "production"; async function start() { try { // Init Nuxt.js const nuxt = new Nuxt(config); const { host, port } = nuxt.options.server; await nuxt.ready(); // Build only in dev mode if (config.dev) { logger.info("nuxtアプリケーションをビルドします."); const builder = new Builder(nuxt); await builder.build(); } // Listen the server logger.info(`Webサーバを起動します.`); let server: http.Server; if (appConfigLoader.app.https) { const httpsServer = https.createServer( { key: fs.readFileSync(path.join(__dirname, "ssl/private_key.pem")), cert: fs.readFileSync(path.join(__dirname, "ssl/server.crt")), }, app ); server = httpsServer.listen(port); } else { server = app.listen(port); } // サービスの起動処理 const mainService = container.get(MainService); await mainService.initialize(app, server); // Give nuxt middleware to express logger.info(`Webサーバにnuxtミドルウェアを設定します.`); app.use(nuxt.render); logger.info( `Webサーバの起動を完了しました. ${ appConfigLoader.app.https ? "https" : "http" }://${host}:${port}` ); } catch (err) { logger.error(`Webサーバの起動に失敗しました. err=${err}`); if (err.stack) logger.error(err.stack); } } start(); <file_sep>/src/client/filter/index.ts import "./abbreviate.filter"; import "./filter-by-property.filter"; import "./numeral.filter"; import "./object-length.filter"; import "./order-object-by.filter"; import "./spent-time.filter"; <file_sep>/src/server/route/notebook.route.ts import { injectable } from "inversify"; import { BaseEntityRoute } from "~/src/server/route/base-entity.route"; import { NotebookEntity } from "~/src/common/entity/notebook.entity"; import { NotebookTable } from "~/src/server/table/notebook.table"; import { SessionService } from "~/src/server/service/session.service"; import { TableService } from "~/src/server/service/table.service"; @injectable() export class NotebookRoute extends BaseEntityRoute< NotebookEntity, NotebookTable > { constructor( protected tableService: TableService, protected sessionService: SessionService ) { super(tableService, sessionService); } } <file_sep>/.eslintrc.js module.exports = { root: true, env: { browser: true, node: true, }, extends: [ "@nuxtjs/eslint-config-typescript", "prettier", "prettier/vue", "plugin:prettier/recommended", "plugin:nuxt/recommended", ], plugins: ["prettier"], // add your custom rules here rules: { "nuxt/no-cjs-in-config": "off", "unicorn/number-literal-case": "off", "space-before-function-paren": [ "error", { anonymous: "never", named: "never", asyncArrow: "always", }, ], "require-await": "off", "no-undef": "off", "no-use-before-define": "off", "no-console": "off", "no-debugger": "off", }, ignorePatterns: ["vue-shim.d.ts"], }; <file_sep>/src/client/service/request.service.ts import _ from "lodash"; import { injectable } from "inversify"; import { SocketIoClientService } from "./socket-io-client.service"; import { BaseClientService } from "./base-client.service"; import { NoteEntity } from "~/src/common/entity/note.entity"; import { OptionEntity } from "~/src/common/entity/option.entity"; import { TEntityClass, FindManyEntityOptions, FindOneEntityOptions, BaseEntity, } from "~/src/common/entity/base.entity"; @injectable() export class RequestService extends BaseClientService { constructor(protected socketIoClientService: SocketIoClientService) { super(); } async find<T extends BaseEntity>( EntityClass: TEntityClass<T>, options: FindManyEntityOptions<T> = {} ): Promise<T[]> { const datas = await this.socketIoClientService.request<Partial<T>[]>( `${EntityClass.params.name}::find`, options ); return _.map(datas, (data) => new EntityClass(data)); } async findOne<T extends BaseEntity>( EntityClass: TEntityClass<T>, options: FindOneEntityOptions<T> = {} ): Promise<T> { const findOneOptions: FindManyEntityOptions<T> = _.clone(options); findOneOptions.take = 1; const datas = await this.socketIoClientService.request<Partial<T>>( `${EntityClass.params.name}::find`, findOneOptions ); const results: T[] = _.map(datas, (data) => new EntityClass(data)); return results[0] || null; } async count<T extends BaseEntity>( EntityClass: TEntityClass<T>, options: FindManyEntityOptions<T> ): Promise<number> { return this.socketIoClientService.request<number>( `${EntityClass.params.name}::count`, options ); } async save<T extends BaseEntity>( EntityClass: TEntityClass<T>, entity: T ): Promise<void> { await this.socketIoClientService.request( `${EntityClass.params.name}::save`, entity ); } async remove<T extends BaseEntity>( EntityClass: TEntityClass<T>, id: number | string ): Promise<void> { await this.socketIoClientService.request( `${EntityClass.params.name}::remove`, id ); } async loadOption(key: string): Promise<any> { const options: FindOneEntityOptions<any> = { where: { key } }; const optionEntity = await this.findOne<OptionEntity>( OptionEntity, options ); return optionEntity ? optionEntity.value : null; } async saveOption(key: string, value: any): Promise<void> { const optionEntity = new OptionEntity({ key, value }); await this.save<OptionEntity>(OptionEntity, optionEntity); } async loadSession(key: string): Promise<any> { return this.socketIoClientService.request("session::load", key); } async saveSession(key: string, value: any): Promise<void> { return this.socketIoClientService.request("session::save", key, value); } async sync(): Promise<void> { await this.socketIoClientService.request(`sync::run`); } async getNoteContent(guid: string): Promise<NoteEntity | null> { const data = await this.socketIoClientService.request( `note::getContent`, guid ); return data ? new NoteEntity(data) : null; } async reParseNote(): Promise<void> { await this.socketIoClientService.request(`note::reParse`, {}); } } <file_sep>/src/server/service/main.service.ts import { Server } from "http"; import Express from "express"; import { injectable } from "inversify"; import { TableService } from "./table.service"; import { BaseServerService } from "./base-server.service"; import { SocketIoService } from "./socket-io.service"; import { logger } from "~/src/common/logger"; import { SyncService } from "~/src/server/service/sync.service"; import { EvernoteClientService } from "~/src/server/service/evernote-client.service"; import { SessionService } from "~/src/server/service/session.service"; @injectable() export class MainService extends BaseServerService { constructor( protected tableService: TableService, protected socketIoService: SocketIoService, protected syncService: SyncService, protected evernoteClientService: EvernoteClientService, protected sessionService: SessionService ) { super(); } async initialize(app: Express.Application, server: Server): Promise<void> { logger.info(`サービスの初期化を開始します.`); this.socketIoService.initialize(server); await this.tableService.initialize(); this.evernoteClientService.initialize(); await this.sessionService.initialize(app); logger.info(`サービスの初期化を完了しました.`); const remoteUser = await this.evernoteClientService.getUser(); await this.tableService.optionTable.saveValueByKey("user", remoteUser); await this.syncService.sync(true); logger.info(`Init user finished. data was initialized.`); } } <file_sep>/src/server/route/profit-log.route.ts import { injectable } from "inversify"; import { ProfitLogEntity } from "../../common/entity/profit-log.entity"; import { ProfitLogTable } from "../table/profit-log.table"; import { BaseEntityRoute } from "./base-entity.route"; import { SessionService } from "~/src/server/service/session.service"; import { TableService } from "~/src/server/service/table.service"; @injectable() export class ProfitLogRoute extends BaseEntityRoute< ProfitLogEntity, ProfitLogTable > { constructor( protected tableService: TableService, protected sessionService: SessionService ) { super(tableService, sessionService); } } <file_sep>/src/common/entity/time-log.entity.ts import { BaseEntity, EntityParams } from "./base.entity"; export class TimeLogEntity extends BaseEntity { FIELD_NAMES!: | "id" | "noteGuid" | "comment" | "allDay" | "date" | "personId" | "spentTime" | BaseEntity["FIELD_NAMES2"]; static readonly params: EntityParams<TimeLogEntity> = { name: "timeLog", primaryKey: "id", displayField: "comment", archive: false, default: { order: { updatedAt: "DESC" }, take: 2000, }, append: {}, columns: { id: { type: "integer", primary: true, generated: true, nullable: false, }, noteGuid: { type: "string", nullable: false, }, comment: { type: "text", nullable: true, }, allDay: { type: "boolean", nullable: false, }, date: { type: "integer", nullable: false, }, personId: { type: "integer", nullable: false, }, spentTime: { type: "integer", nullable: true, }, }, }; id!: number; noteGuid!: string; comment!: string | null; allDay!: boolean; date!: number; personId!: number; spentTime!: number | null; } <file_sep>/src/client/filter/object-length.filter.ts import Vue from "vue"; import _ from "lodash"; export function objectLengthFilter( input: { [key: string]: any }, depth: number = 0 ): number { if (_.isObject(input)) return 0; if (depth === 0) return Object.keys(input).length; else { let result = 0; let value: any; // @ts-ignore for (const key in input) value = input[key]; result += objectLengthFilter(value, depth - 1); return result; } } Vue.filter("objectLength", objectLengthFilter); <file_sep>/src/client/plugins/service.ts import { Plugin } from "@nuxt/types"; import { myService } from "~/src/client/service"; const servicePlugin: Plugin = (_context, inject) => { inject("myService", myService); }; export default servicePlugin; declare module "vue/types/vue" { interface Vue { $myService: typeof myService; } } declare module "@nuxt/types" { interface NuxtAppOptions { $myService: typeof myService; } } /* declare module "vuex/types/index" { interface Store<S> { $myService: typeof myService; } } */ <file_sep>/src/client/filter/spent-time.filter.ts import Vue from "vue"; export function spentTimeFilter(input: any): string { if (input === undefined) return ""; if (!input) return "0m"; const hour = Math.floor(input / 60); const minute = input % 60; if (hour) return hour + "h" + minute + "m"; return minute + "m"; } Vue.filter("spentTime", spentTimeFilter); <file_sep>/jest.config.ts import type { Config } from "@jest/types"; const config: Config.InitialOptions = { moduleNameMapper: { "^@/(.*)$": "<rootDir>/$1", "^~/(.*)$": "<rootDir>/$1", "^vue$": "vue/dist/vue.common.js", }, moduleFileExtensions: ["ts", "js", "vue", "json"], transform: { "^.+\\.js$": "babel-jest", "^.+\\.ts$": "ts-jest", ".*\\.(vue)$": "vue-jest", }, collectCoverage: true, collectCoverageFrom: [ "<rootDir>/components/**/*.vue", "<rootDir>/pages/**/*.vue", ], testPathIgnorePatterns: ["/node_modules/", "/dist/"], }; export default config; <file_sep>/src/common/entity/option.entity.ts import { BaseEntity, EntityParams } from "./base.entity"; export class OptionEntity extends BaseEntity { FIELD_NAMES!: "key" | "value" | BaseEntity["FIELD_NAMES2"]; static readonly params: EntityParams<OptionEntity> = { name: "option", primaryKey: "key", displayField: "key", archive: false, default: { take: 500, }, append: {}, columns: { key: { type: "string", primary: true, nullable: false, }, value: { type: "text", nullable: true, }, }, jsonFields: ["value"], }; key!: string; value!: any | null; } <file_sep>/src/server/route/tag.route.ts import { injectable } from "inversify"; import { TagEntity } from "~/src/common/entity/tag.entity"; import { BaseEntityRoute } from "~/src/server/route/base-entity.route"; import { TagTable } from "~/src/server/table/tag.table"; import { SessionService } from "~/src/server/service/session.service"; import { TableService } from "~/src/server/service/table.service"; @injectable() export class TagRoute extends BaseEntityRoute<TagEntity, TagTable> { constructor( protected tableService: TableService, protected sessionService: SessionService ) { super(tableService, sessionService); } } <file_sep>/src/client/filter/abbreviate.filter.ts import Vue from "vue"; export function abbreviateFilter( text: string, len: number = 10, truncation: string = "..." ) { let count = 0; let str = ""; for (let i = 0; i < text.length; i++) { const n = encodeURI(text.charAt(i)); if (n.length < 4) count++; else count += 2; if (count > len) return str + truncation; str += text.charAt(i); } return text; } Vue.filter("abbreviate", abbreviateFilter); <file_sep>/src/client/service/socket-io-client.service.ts import SocketIoClient from "socket.io-client"; import { injectable } from "inversify"; import { logger } from "~/src/common/logger"; @injectable() export class SocketIoClientService { private socket: SocketIoClient.Socket; constructor() { logger.debug("socket.io client connection started."); this.socket = SocketIoClient.io(); this.on(this, "connect", this.onConnect); this.on(this, "disconnect", this.onDisconnect); } on(me: Object, event: string, func: Function) { this.socket.on(event, (...args: any[]) => { func.call(me, ...args); }); } private onConnect(): void { logger.info("socket.io client connection finished."); } private onDisconnect(): void { logger.info("socket.io client disconnected."); } async request<T = any>(event: string, ...params: any[]): Promise<T> { const data = await new Promise<T>((resolve) => { this.socket.emit(event, ...params, (data: T) => resolve(data)); }); if (data && (<any>data).$$err === true) throw (<any>data).$$errMessage; return data; } } <file_sep>/src/server/table/notebook.table.ts import { injectable } from "inversify"; import { NotebookEntity } from "~/src/common/entity/notebook.entity"; import { BaseEvernoteTable } from "~/src/server/table/base-evernote.table"; @injectable() export class NotebookTable extends BaseEvernoteTable<NotebookEntity> {} <file_sep>/src/server/service/socket-io.service.ts import { Server as HttpServer } from "http"; import SocketIo from "socket.io"; import { injectable } from "inversify"; import { BaseServerService } from "./base-server.service"; import { logger } from "~/src/common/logger"; import { container } from "~/src/common/inversify.config"; import { BaseRoute } from "~/src/server/route/base.route"; import { SYMBOL_TYPES } from "~/src/common/symbols"; @injectable() export class SocketIoService extends BaseServerService { private io!: SocketIo.Server; initialize(server: HttpServer) { logger.info("Socket.IOサービスの初期化を開始しました."); this.io = new SocketIo.Server(server); this.io.sockets.on("connect", (socket) => this.connect(socket)); logger.info("Socket.IOサービスの初期化を完了しました."); } initializeSession(sessionMiddleware: any) { this.io.use((socket, next) => { sessionMiddleware(socket.request, {}, next); }); } private async connect(socket: SocketIo.Socket): Promise<void> { logger.info(`Socket.IOによる接続が開始されました. socket.id=${socket.id}.`); for (const route of container.getAll<BaseRoute>(SYMBOL_TYPES.Route)) { await route.connect(socket); } logger.info(`Socket.IOによる接続が終了しました. socket.id=${socket.id}.`); } emitAll(event: string, ...args: any[]) { if (!this.io) throw new Error("初期化前にemitAllが呼び出されました"); this.io.sockets.emit(event, ...args); } } <file_sep>/src/client/service/push.service.ts import Push from "push.js"; import { injectable } from "inversify"; import { BaseClientService } from "./base-client.service"; import { SocketIoClientService } from "./socket-io-client.service"; import { logger } from "~/src/common/logger"; import DefaultLayoutComponent from "~/src/client/layouts/default.vue"; import { RequestService } from "~/src/client/service/request.service"; import { NoteEntity } from "~/src/common/entity/note.entity"; @injectable() export class PushService extends BaseClientService { lastUpdateCount: number = 0; rootComponent!: DefaultLayoutComponent; constructor( protected socketIoClientService: SocketIoClientService, protected requestService: RequestService ) { super(); this.socketIoClientService.on(this, "sync::update", this.update); this.socketIoClientService.on( this, "constraint::notify", this.notifyConstraint ); } initialize(rootComponent: DefaultLayoutComponent) { this.rootComponent = rootComponent; } private async update(eventHash: { [event: string]: string[]; }): Promise<void> { if (!eventHash["note::update"]) return; const this_ = this; const notes = await this.requestService.find(NoteEntity, { where: { guid: { $in: eventHash["note::update"] } }, }); await Push.create("Evernote更新通知", { body: notes.map((note) => note.title).join("\n"), link: "/activity", timeout: 5000, onClick(this: any) { this_.rootComponent.$router.push("activity"); this.close(); }, }); } private async notifyConstraint(): Promise<void> { logger.debug("Notify constraint from server."); const this_ = this; await Push.create("Evernote制約違反通知", { link: "/constraint", timeout: 10000, onClick(this: any) { this_.rootComponent?.$router.push("constraint"); this.close(); }, }); } } <file_sep>/src/client/filter/filter-by-property.filter.ts import _ from "lodash"; import Vue from "vue"; const checkItemMatches = ( item: { [key: string]: any }, props: { [key: string]: string } ): boolean => { for (const prop in props) { let text: string = props[prop]; text = text.toLowerCase(); if (item[prop].toString().toLowerCase().includes(text)) { return true; } } return false; }; export function filterByPropertyFilter( items: | Array<{ [property: string]: any }> | { [key: string]: { [property: string]: any } }, props: { [property: string]: string } ): any { let arrItems: Array<{ [property: string]: any }> = []; if (_.isArray(items)) arrItems = <Array<{ [property: string]: any }>>items; else if (_.isObject(items)) _.forEach(items, (item) => { arrItems.push(item); }); else return []; const results: Array<{ [key: string]: string }> = []; for (const item of arrItems) if (checkItemMatches(item, props)) results.push(item); return results; } Vue.filter("filterByProperty", filterByPropertyFilter); <file_sep>/src/server/route/constraint-result.route.ts import { injectable } from "inversify"; import { ConstraintResultEntity } from "~/src/common/entity/constraint-result.entity"; import { BaseEntityRoute } from "~/src/server/route/base-entity.route"; import { SessionService } from "~/src/server/service/session.service"; import { TableService } from "~/src/server/service/table.service"; import { ConstraintResultTable } from "~/src/server/table/constraint-result.table"; @injectable() export class ConstraintResultRoute extends BaseEntityRoute< ConstraintResultEntity, ConstraintResultTable > { constructor( protected tableService: TableService, protected sessionService: SessionService ) { super(tableService, sessionService); } } <file_sep>/src/server/table/option.table.ts import { injectable } from "inversify"; import { BaseTable } from "~/src/server/table/base.table"; import { OptionEntity } from "~/src/common/entity/option.entity"; @injectable() export class OptionTable extends BaseTable<OptionEntity> { async findValueByKey(key: string): Promise<any> { const entity = await this.findByPrimary(key); return entity ? entity.value : null; } async saveValueByKey(key: string, value: any): Promise<void> { const optionEntity = new OptionEntity({ key, value }); await this.save(optionEntity); } } <file_sep>/src/client/icons.ts export const icons = { solid: [ "faBars", "faCheckCircle", "faClock", "faFilter", "faHistory", "faIdCard", "faHome", "faSpinner", "faStickyNote", "faSync", ], }; <file_sep>/src/server/route/time-log.route.ts import { injectable } from "inversify"; import { TimeLogEntity } from "~/src/common/entity/time-log.entity"; import { BaseEntityRoute } from "~/src/server/route/base-entity.route"; import { TimeLogTable } from "~/src/server/table/time-log.table"; import { SessionService } from "~/src/server/service/session.service"; import { TableService } from "~/src/server/service/table.service"; @injectable() export class TimeLogRoute extends BaseEntityRoute<TimeLogEntity, TimeLogTable> { constructor( protected tableService: TableService, protected sessionService: SessionService ) { super(tableService, sessionService); } } <file_sep>/src/server/service/base-server.service.ts import { injectable } from "inversify"; @injectable() export abstract class BaseServerService {} <file_sep>/config/default/app.config.ts const appConfig: AppConfig.IAppConfigs = { "*": { port: 3000, https: true, logLevel: "info", sqlLogging: false, sandbox: false, token: "", persons: [ { id: 1, name: "Alpha" }, { id: 2, name: "Beta" }, { id: 3, name: "Gamma" }, ], warningNoteCount: 300, workingTimeStart: 9, workingTimeEnd: 19, defaultFilterParams: { timeline: {}, notes: { stacks: ["StackA", "StackB"], notebooks: ["NotebookA", "NotebookB"], }, activity: {}, }, constraints: [ { id: 1, label: "Constraint 1", query: { notebook: "Notebook1", reminderOrder: null, }, }, ], }, development: {}, "production*": { logLevel: "info", }, "production-pre": {}, production: {}, test: {}, }; export default appConfig; <file_sep>/src/common/entity/note.entity.ts import { BaseEvernoteEntity } from "./base-evernote.entity"; import { EntityParams, FindManyEntityOptions } from "./base.entity"; export class NoteEntity extends BaseEvernoteEntity { FIELD_NAMES!: | "title" | "content" | "contentHash" | "contentLength" | "created" | "updated" | "deleted" | "active" | "notebookGuid" | "tagGuids" | "resources" | "attributes" | "tagNames" | "sharedNotes" | "restrictions" | "limits" | "hasContent" | BaseEvernoteEntity["FIELD_NAMES3"]; static readonly params: EntityParams<NoteEntity> = { name: "note", primaryKey: "guid", displayField: "title", archive: true, default: { order: { updatedAt: "DESC", updateSequenceNum: "DESC" }, take: 500, }, append: { where: { deleted: null }, }, columns: { guid: { type: "string", primary: true, nullable: false, }, title: { type: "string", nullable: false, }, content: { type: "text", nullable: true, }, contentHash: { type: "text", nullable: false, }, contentLength: { type: "integer", nullable: false, }, created: { type: "integer", nullable: false, }, updated: { type: "integer", nullable: false, }, deleted: { type: "integer", nullable: true, }, active: { type: "boolean", nullable: false, }, updateSequenceNum: { type: "integer", nullable: false, }, notebookGuid: { type: "string", nullable: false, }, tagGuids: { type: "text", nullable: true, }, resources: { type: "text", nullable: true, }, attributes__subjectDate: { type: "integer", nullable: true, }, attributes__latitude: { type: "real", nullable: true, }, attributes__longitude: { type: "real", nullable: true, }, attributes__altitude: { type: "real", nullable: true, }, attributes__author: { type: "string", nullable: true, }, attributes__source: { type: "string", nullable: true, }, attributes__sourceURL: { type: "string", nullable: true, }, attributes__sourceApplication: { type: "string", nullable: true, }, attributes__shareDate: { type: "integer", nullable: true, }, attributes__reminderOrder: { type: "integer", nullable: true, }, attributes__reminderDoneTime: { type: "integer", nullable: true, }, attributes__reminderTime: { type: "integer", nullable: true, }, attributes__placeName: { type: "string", nullable: true, }, attributes__contentClass: { type: "string", nullable: true, }, attributes__applicationData: { type: "text", nullable: true, }, attributes__classifications: { type: "text", nullable: true, }, attributes__creatorId: { type: "integer", nullable: true, }, attributes__lastEditorId: { type: "integer", nullable: true, }, attributes__sharedWithBusiness: { type: "boolean", nullable: true, }, attributes__conflictSourceNoteGuid: { type: "string", nullable: true, }, attributes__noteTitleQuality: { type: "integer", nullable: true, }, tagNames: { type: "text", nullable: true, }, sharedNotes: { type: "text", nullable: true, }, restrictions: { type: "text", nullable: true, }, limits: { type: "text", nullable: true, }, }, jsonFields: [ "contentHash", "tagGuids", "resources", "attributes__applicationData", "tagNames", "sharedNotes", "restrictions", "limits", ], }; title!: string; content!: string | null; contentHash!: Object; contentLength!: number; created!: number; updated!: number; deleted!: number | null; active!: boolean; notebookGuid!: string; tagGuids!: string[] | null; resources!: Object[] | null; attributes?: { subjectDate: number | null; latitude: number | null; longitude: number | null; author: string | null; source: string | null; sourceURL: string | null; sourceApplication: string | null; shareDate: number | null; reminderOrder: number | null; reminderDoneTime: number | null; reminderTime: number | null; placeName: string | null; contentClass: string | null; applicationData: string | null; classifications: string | null; creatorId: number | null; lastEditorId: number | null; sharedWithBusiness: boolean | null; conflictSourceNoteGuid: string | null; noteTitleQuality: number | null; }; tagNames!: string[] | null; sharedNotes!: Object[] | null; restrictions!: any | null; limits!: any | null; hasContent!: boolean; } export interface IFindManyNoteEntityOptions extends FindManyEntityOptions<NoteEntity> { includeContent?: boolean; } <file_sep>/src/client/store/progress.ts import { Module, Mutation, VuexModule } from "vuex-module-decorators"; import { myStore } from "~/src/client/store/index"; @Module({ name: "progress", stateFactory: true, namespaced: true, }) export default class ProgressModule extends VuexModule { isActive: boolean = false; allCount: number = 0; completeCount: number = 0; message: string = ""; percentage: number = 0; @Mutation open(allCount: number): void { this.isActive = true; this.allCount = allCount; this.completeCount = 0; myStore.progress.set({ message: "processing...", percentage: 0, }); } @Mutation close(): void { this.isActive = false; } @Mutation set(payload: { message: string; percentage?: number }): void { this.message = payload.message; if (payload.percentage !== undefined) this.percentage = payload.percentage; } @Mutation next(message: string): void { this.completeCount++; myStore.progress.set({ message, percentage: Math.floor((this.completeCount / this.allCount) * 100), }); } } <file_sep>/src/common/entity/session.entity.ts import { ISession } from "connect-typeorm"; import { BaseEntity, EntityParams } from "~/src/common/entity/base.entity"; export class SessionEntity extends BaseEntity implements ISession { FIELD_NAMES!: "expiredAt" | "id" | "json" | BaseEntity["FIELD_NAMES2"]; static readonly params: EntityParams<SessionEntity> = { name: "session", primaryKey: "id", displayField: "id", archive: false, default: { take: 500, }, append: {}, columns: { expiredAt: { type: "integer", nullable: false, }, id: { type: "string", primary: true, nullable: false, }, json: { type: "text", nullable: false, }, }, indicies: [ { name: "expired_at", columns: ["expiredAt"], }, ], }; expiredAt = Date.now(); public id = ""; public json = ""; } <file_sep>/src/client/inversify.config.ts import { container } from "~/src/common/inversify.config"; import { NoteLogsService } from "~/src/client/service/note-logs.service"; import { PushService } from "~/src/client/service/push.service"; import { RequestService } from "~/src/client/service/request.service"; import { SocketIoClientService } from "~/src/client/service/socket-io-client.service"; import { SYMBOL_TYPES } from "~/src/common/symbols"; import { ILogger, initializeLogger } from "~/src/common/logger"; import { clientLogger } from "~/src/client/logger"; // Logger系 container.bind<ILogger>(SYMBOL_TYPES.Logger).toConstantValue(clientLogger); initializeLogger(); // Service系 container.bind<NoteLogsService>(NoteLogsService).toSelf().inSingletonScope(); container.bind<PushService>(PushService).toSelf().inSingletonScope(); container.bind<RequestService>(RequestService).toSelf().inSingletonScope(); container .bind<SocketIoClientService>(SocketIoClientService) .toSelf() .inSingletonScope(); <file_sep>/src/client/filter/order-object-by.filter.ts import Vue from "vue"; import _ from "lodash"; export function orderObjectByFilter( items: { [key: string]: any }, field: any = "$value", reverse = true ) { const filtered: Array<{ key: string; item: any }> = []; _.forEach(items, (item, key) => { filtered.push({ key, item, }); }); filtered.sort((a: any, b: any) => { if (field === "$key") return a.key > b.key ? -1 : 1; if (field === "$value") return a.item > b.item ? -1 : 1; if (typeof field === "string") return a[field] > b[field] ? -1 : 1; if (typeof field === "function") return field(a.item, a.key) > field(b.item, b.key) ? -1 : 1; return 0; }); if (reverse) filtered.reverse(); const results: Array<any> = []; _.forEach(filtered, (item: { key: string; item: any }) => { const result = item.item; result.$key = item.key; results.push(result); }); return results; } Vue.filter("orderObjectBy", orderObjectByFilter); <file_sep>/src/server/table/linked-notebook.table.ts import { injectable } from "inversify"; import { BaseEvernoteTable } from "~/src/server/table/base-evernote.table"; import { LinkedNotebookEntity } from "~/src/common/entity/linked-notebook.entity"; @injectable() export class LinkedNotebookTable extends BaseEvernoteTable<LinkedNotebookEntity> {} <file_sep>/src/common/symbols.ts export const SYMBOL_TYPES = { Entity: Symbol.for("Entity"), Logger: Symbol.for("Logger"), Route: Symbol.for("Route"), Service: Symbol.for("Service"), Table: Symbol.for("Table"), }; export const SYMBOL_TABLES = { attendance: Symbol.for("attendance"), constraintResult: Symbol.for("constraintResult"), linkedNotebook: Symbol.for("linkedNotebook"), note: Symbol.for("note"), notebook: Symbol.for("notebook"), option: Symbol.for("option"), profitLog: Symbol.for("profitLog"), savedSearch: Symbol.for("savedSearch"), session: Symbol.for("session"), tag: Symbol.for("tag"), timeLog: Symbol.for("timeLog"), }; <file_sep>/src/server/service/table.service.ts import path from "path"; import _ from "lodash"; import { injectable } from "inversify"; import { Connection, createConnection, EntitySchema } from "typeorm"; import { BaseServerService } from "./base-server.service"; import { container } from "~/src/common/inversify.config"; import { NotebookEntity } from "~/src/common/entity/notebook.entity"; import { TagEntity } from "~/src/common/entity/tag.entity"; import { BaseEntity, TEntityClass } from "~/src/common/entity/base.entity"; import { SYMBOL_TYPES } from "~/src/common/symbols"; import { BaseTable } from "~/src/server/table/base.table"; import { ConstraintResultTable } from "~/src/server/table/constraint-result.table"; import { ConstraintResultEntity } from "~/src/common/entity/constraint-result.entity"; import { LinkedNotebookTable } from "~/src/server/table/linked-notebook.table"; import { LinkedNotebookEntity } from "~/src/common/entity/linked-notebook.entity"; import { NoteTable } from "~/src/server/table/note.table"; import { NoteEntity } from "~/src/common/entity/note.entity"; import { NotebookTable } from "~/src/server/table/notebook.table"; import { OptionTable } from "~/src/server/table/option.table"; import { OptionEntity } from "~/src/common/entity/option.entity"; import { ProfitLogEntity } from "~/src/common/entity/profit-log.entity"; import { ProfitLogTable } from "~/src/server/table/profit-log.table"; import { SavedSearchTable } from "~/src/server/table/saved-search.table"; import { SavedSearchEntity } from "~/src/common/entity/saved-search.entity"; import { TagTable } from "~/src/server/table/tag.table"; import { TimeLogTable } from "~/src/server/table/time-log.table"; import { TimeLogEntity } from "~/src/common/entity/time-log.entity"; import { AttendanceTable } from "~/src/server/table/attendance.table"; import { AttendanceEntity } from "~/src/common/entity/attendance.entity"; import { SessionEntity } from "~/src/common/entity/session.entity"; import { SessionTable } from "~/src/server/table/session.table"; import { logger } from "~/src/common/logger"; import { appConfigLoader } from "~/src/common/util/app-config-loader"; @injectable() export class TableService extends BaseServerService { caches: { tags: { [guid: string]: TagEntity }; notebooks: { [guid: string]: NotebookEntity }; }; private connection: Connection | null = null; private readonly tables: { [name: string]: BaseTable<BaseEntity>; }; constructor() { super(); this.caches = { tags: {}, notebooks: {}, }; this.tables = {}; } get attendanceTable(): AttendanceTable { return this.getTable(AttendanceEntity); } get constraintResultTable(): ConstraintResultTable { return this.getTable(ConstraintResultEntity); } get linkedNotebookTable(): LinkedNotebookTable { return this.getTable(LinkedNotebookEntity); } get noteTable(): NoteTable { return this.getTable(NoteEntity); } get notebookTable(): NotebookTable { return this.getTable(NotebookEntity); } get optionTable(): OptionTable { return this.getTable(OptionEntity); } get profitLogTable(): ProfitLogTable { return this.getTable(ProfitLogEntity); } get savedSearchTable(): SavedSearchTable { return this.getTable(SavedSearchEntity); } get sessionTable(): SessionTable { return this.getTable(SessionEntity); } get tagTable(): TagTable { return this.getTable(TagEntity); } get timeLogTable(): TimeLogTable { return this.getTable(TimeLogEntity); } async initialize(reloadCache: boolean = true): Promise<void> { logger.info("テーブルサービスの初期化を開始しました."); await this.getConnection(); for (const table of container.getAll<BaseTable<BaseEntity>>( SYMBOL_TYPES.Table )) { await table.initialize(); this.tables[table.EntityClass.params.name] = table; } if (reloadCache) await this.reloadCache(); logger.info("テーブルサービスの初期化を完了しました."); } private async getConnection(): Promise<Connection> { if (!this.connection) { return this.initConnection(); } return this.connection; } private async initConnection(): Promise<Connection> { const filePath = path.join(__dirname, "../../../db/database.db"); const tables = container.getAll<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table); const schemas = tables.map((table) => table.schema); const archiveSchemas = tables .map((table) => table.archiveSchema) .filter( ( schema: EntitySchema<BaseEntity> | null ): schema is EntitySchema<BaseEntity> => !!schema ); this.connection = await createConnection({ type: "sqlite", database: filePath, entities: [...schemas, ...archiveSchemas], logging: appConfigLoader.app.sqlLogging, }); return this.connection; } getTable<TEntity extends BaseEntity, TTable extends BaseTable<TEntity>>( EntityClass: TEntityClass<TEntity> ): TTable { return <TTable>this.tables[EntityClass.params.name]; } async reloadCache(type: "tag" | "notebook" | "all" = "all"): Promise<void> { if (type === "tag" || type === "all") this.caches.tags = _.keyBy(await this.tagTable.findAll(), "guid"); if (type === "notebook" || type === "all") this.caches.notebooks = _.keyBy( await this.notebookTable.findAll(), "guid" ); } async sync(): Promise<void> { const connection = await this.getConnection(); await connection.synchronize(); } } <file_sep>/src/client/service/note-logs.service.ts import _ from "lodash"; import moment from "moment"; import { injectable } from "inversify"; import { IFindManyNoteEntityOptions, NoteEntity, } from "~/src/common/entity/note.entity"; import { TimeLogEntity } from "~/src/common/entity/time-log.entity"; import { ProfitLogEntity } from "~/src/common/entity/profit-log.entity"; import { BaseClientService } from "~/src/client/service/base-client.service"; import { RequestService } from "~/src/client/service/request.service"; import { FindManyEntityOptions, FindEntityWhereOptions, } from "~/src/common/entity/base.entity"; import { assertIsDefined } from "~/src/common/util/assert"; import { myStore } from "~/src/client/store"; import { appConfigLoader } from "~/src/common/util/app-config-loader"; export interface INoteLogsServiceNoteFilterParams { start?: moment.Moment; end?: moment.Moment; notebookGuids?: string[]; stacks?: string[]; hasContent?: boolean; archiveMinStepMinute?: number; } interface IDatastoreServiceTimeLogFilterParams { start?: moment.Moment; end?: moment.Moment; noteGuids?: string[]; } class TerminateResult { data: any; constructor(argData: any = null) { this.data = argData; } toString(): string { return this.data; } } export type TNotesResult = { [guid: string]: NoteEntity }; export type TTimeLogsResult = { [noteGuid: string]: { [id: number]: TimeLogEntity }; }; export type TProfitLogsResult = { [noteGuid: string]: { [id: number]: ProfitLogEntity }; }; interface INoteLogsResult { notes: TNotesResult | null; timeLogs: TTimeLogsResult | null; profitLogs: TProfitLogsResult | null; } @injectable() export class NoteLogsService extends BaseClientService { constructor(protected requestService: RequestService) { super(); } makeDefaultNoteFilterParams( params: AppConfig.IDefaultFilterParamsConfig ): INoteLogsServiceNoteFilterParams { const result: INoteLogsServiceNoteFilterParams = {}; result.stacks = params.stacks || []; result.notebookGuids = _(params.notebooks || []) .map( (notebookName: string) => myStore.datastore.notebooks[notebookName].guid ) .filter(_.isString) .value(); return result; } async getNoteLogs( params: INoteLogsServiceNoteFilterParams = {} ): Promise<INoteLogsResult | null> { if (myStore.progress.isActive) return null; const result: INoteLogsResult = { notes: null, timeLogs: null, profitLogs: null, }; myStore.progress.open(7); try { await this.runSync(); await this.checkNoteCount(params); result.notes = await this.getNotes(params); await this.getNoteContents(result.notes); result.timeLogs = await this.getTimeLogs(result.notes, params); result.profitLogs = await this.getProfitLogs(result.notes); myStore.progress.next("Done."); } catch (err) { alert(err); if (!(err instanceof TerminateResult)) throw err; } finally { myStore.progress.close(); } return result; } async getArchiveLogs( params: INoteLogsServiceNoteFilterParams = {} ): Promise<NoteEntity[] | null> { if (myStore.progress.isActive) return null; myStore.progress.open(4); let archiveNotes; try { await this.runSync(); await this.checkNoteCount(params); archiveNotes = await this.getArchiveNotes(params); myStore.progress.next("Done."); } catch (err) { alert(err); if (!(err instanceof TerminateResult)) throw err; } finally { myStore.progress.close(); } return archiveNotes ?? null; } private async runSync(): Promise<void> { myStore.progress.next("Syncing remote server."); await this.requestService.sync(); } private async checkNoteCount( params: INoteLogsServiceNoteFilterParams ): Promise<void> { myStore.progress.next("Checking notes count."); const options = this.makeNoteFindOptions(params); const count = await this.requestService.count(NoteEntity, options); if (count > appConfigLoader.app.warningNoteCount) if ( !window.confirm( `Current query find ${count} notes. It is too many. Continue anyway?` ) ) throw new TerminateResult(`User Canceled`); } protected async getNotes( params: INoteLogsServiceNoteFilterParams ): Promise<TNotesResult> { myStore.progress.next("Getting notes."); const options = this.makeNoteFindOptions(params); const notes = await this.requestService.find<NoteEntity>( NoteEntity, options ); return _.keyBy(notes, "guid"); } private async getArchiveNotes( params: INoteLogsServiceNoteFilterParams ): Promise<NoteEntity[]> { myStore.progress.next("ノート履歴を取得しています."); const options = this.makeNoteFindOptions(params); options.archive = true; options.includeContent = true; let notes = await this.requestService.find<NoteEntity>(NoteEntity, options); if (params.archiveMinStepMinute) { notes = _.filter(notes, (filterNote: NoteEntity) => { return !_.find(notes, (findNote: NoteEntity) => { if (filterNote.guid !== findNote.guid) return false; if (filterNote.updateSequenceNum >= findNote.updateSequenceNum) return false; return ( findNote.updated - filterNote.updated < (params.archiveMinStepMinute ?? 0) * 60 * 1000 ); }); }); } return notes; } private async getNoteContents(notes: TNotesResult): Promise<void> { myStore.progress.next("Request remote contents."); let count = 0; for (const noteGuid in notes) { const note = notes[noteGuid]; myStore.progress.set({ message: `Request remote contents. ${++count} / ${_.size(notes)}`, }); if (!note.hasContent) { const note = await this.requestService.getNoteContent(noteGuid); assertIsDefined(note); notes[note.guid] = note; } } } private async getTimeLogs( notes: TNotesResult, params: IDatastoreServiceTimeLogFilterParams ): Promise<TTimeLogsResult> { myStore.progress.next("Getting time logs."); const guids: string[] = []; for (const noteGuid in notes) { const note = notes[noteGuid]; guids.push(note.guid); } const options = this.makeTimeLogFindOptions( _.merge({}, params, { noteGuids: guids }) ); const timeLogs = await this.requestService.find<TimeLogEntity>( TimeLogEntity, options ); const result: TTimeLogsResult = {}; for (const timeLog of timeLogs) { if (!result[timeLog.noteGuid]) result[timeLog.noteGuid] = {}; result[timeLog.noteGuid][timeLog.id] = timeLog; } return result; } private async getProfitLogs(notes: TNotesResult): Promise<TProfitLogsResult> { myStore.progress.next("Getting profit logs."); const guids: string[] = []; for (const noteGuid in notes) { const note = notes[noteGuid]; guids.push(note.guid); } const profitLogs = await this.requestService.find<ProfitLogEntity>( ProfitLogEntity, { where: { noteGuid: { $in: guids } } } ); const result: TProfitLogsResult = {}; for (const profitLog of profitLogs) { if (!result[profitLog.noteGuid]) result[profitLog.noteGuid] = {}; result[profitLog.noteGuid][profitLog.id] = profitLog; } return result; } async reParse(): Promise<void> { myStore.progress.open(2); myStore.progress.next("Re Parse notes..."); await this.requestService.reParseNote(); myStore.progress.next("Done."); myStore.progress.close(); } async countNotes(params: INoteLogsServiceNoteFilterParams): Promise<number> { const options = this.makeNoteFindOptions(params); return this.requestService.count(NoteEntity, options); } async getPrevNote( archiveNotes: NoteEntity[], note: NoteEntity, minStepMinute: number ): Promise<NoteEntity> { const prevNote: NoteEntity | undefined = _.find( archiveNotes, (searchNote: NoteEntity) => { return ( searchNote.guid === note.guid && searchNote.updateSequenceNum < note.updateSequenceNum ); } ); if (prevNote) return Promise.resolve(prevNote); const options: IFindManyNoteEntityOptions = { where: { guid: note.guid, updateSequenceNum: { $lt: note.updateSequenceNum }, updated: { $lt: note.updated - minStepMinute * 60 * 1000 }, }, archive: true, includeContent: true, }; return this.requestService.findOne<NoteEntity>(NoteEntity, options); } private makeNoteFindOptions( params: INoteLogsServiceNoteFilterParams ): IFindManyNoteEntityOptions { const where: FindEntityWhereOptions<NoteEntity> = {}; if (params.start && params.end) where.updated = { $between: [params.start.valueOf(), params.end.valueOf()], }; else if (params.start) where.updated = { $gte: params.start.valueOf() }; else if (params.end) where.updated = { $lte: params.end.valueOf() }; // set hasContent query if (params.hasContent) where.content = { $ne: null }; // check notebooks const notebooksHash: { [notebookGuid: string]: boolean } = {}; if (params.stacks) for (const stack of params.stacks) for (const notebook of _.values(myStore.datastore.notebooks)) if (notebook.stack === stack) notebooksHash[notebook.guid] = true; if (_.size(params.notebookGuids) > 0) for (const notebookGuid of params.notebookGuids ?? []) notebooksHash[notebookGuid] = true; // set notebooks query if (_.size(notebooksHash) > 0) where.notebookGuid = { $in: _.keys(notebooksHash) }; return { where }; } private makeTimeLogFindOptions( params: IDatastoreServiceTimeLogFilterParams ): FindManyEntityOptions<TimeLogEntity> { const where: FindEntityWhereOptions<TimeLogEntity> = {}; // set date query if (params.start && params.end) where.date = { $between: [params.start.valueOf(), params.end.valueOf()] }; else if (params.start) where.date = { $gte: params.start.valueOf() }; else if (params.end) where.date = { $lte: params.end.valueOf() }; // set note guids query if (params.noteGuids && params.noteGuids.length > 0) where.noteGuid = { $in: params.noteGuids }; return { where }; } } <file_sep>/src/server/table/saved-search.table.ts import { injectable } from "inversify"; import { BaseEvernoteTable } from "~/src/server/table/base-evernote.table"; import { SavedSearchEntity } from "~/src/common/entity/saved-search.entity"; @injectable() export class SavedSearchTable extends BaseEvernoteTable<SavedSearchEntity> {} <file_sep>/src/common/entity/saved-search.entity.ts import { BaseEvernoteEntity } from "./base-evernote.entity"; import { EntityParams } from "./base.entity"; export class SavedSearchEntity extends BaseEvernoteEntity { FIELD_NAMES!: | "name" | "query" | "format" | "scope" | BaseEvernoteEntity["FIELD_NAMES3"]; static readonly params: EntityParams<SavedSearchEntity> = { name: "savedSearch", primaryKey: "guid", displayField: "name", archive: false, default: { order: { updatedAt: "DESC" }, take: 500, }, append: {}, columns: { guid: { type: "string", primary: true, nullable: false, }, name: { type: "string", nullable: false, }, query: { type: "string", nullable: true, }, format: { type: "integer", nullable: true, }, updateSequenceNum: { type: "integer", nullable: false, }, scope: { type: "text", nullable: true, }, }, jsonFields: ["scope"], }; name!: string; query!: string | null; format!: number | null; scope!: Object | null; } <file_sep>/src/client/service/index.ts import { NoteLogsService } from "~/src/client/service/note-logs.service"; import { PushService } from "~/src/client/service/push.service"; import { RequestService } from "~/src/client/service/request.service"; import { SocketIoClientService } from "~/src/client/service/socket-io-client.service"; import "~/src/client/inversify.config"; import { container } from "~/src/common/inversify.config"; interface IMyService { noteLogs: NoteLogsService; push: PushService; request: RequestService; socketIoClient: SocketIoClientService; } export const myService: IMyService = <any>{}; myService.noteLogs = container.get(NoteLogsService); myService.push = container.get(PushService); myService.request = container.get(RequestService); myService.socketIoClient = container.get(SocketIoClientService); <file_sep>/src/client/logger.ts import logLevel from "loglevel"; import { appConfigLoader } from "~/src/common/util/app-config-loader"; export const clientLogger = logLevel.getLogger("evernote-tasklog"); clientLogger.setLevel(appConfigLoader.app.logLevel); <file_sep>/src/server/service/constraint.service.ts import { injectable } from "inversify"; import _ from "lodash"; import { BaseServerService } from "~/src/server/service/base-server.service"; import { TableService } from "~/src/server/service/table.service"; import { logger } from "~/src/common/logger"; import { NoteEntity } from "~/src/common/entity/note.entity"; import { ConstraintResultEntity } from "~/src/common/entity/constraint-result.entity"; import { appConfigLoader } from "~/src/common/util/app-config-loader"; @injectable() export class ConstraintService extends BaseServerService { constructor(protected tableService: TableService) { super(); } async checkAll(): Promise<void> { logger.info(`全ての制約違反データを削除します.`); await this.tableService.constraintResultTable.clear(); const noteCount = await this.tableService.noteTable.count(); let notes: NoteEntity[]; let i = 0; do { logger.info(`ノートの制約をチェック中 ${i * 100} / ${noteCount}.`); notes = await this.tableService.noteTable.findAll({ take: 100, skip: 100 * i, }); for (const note of notes) await this.check(note); i++; } while (notes.length > 0); } async checkOne(note: NoteEntity): Promise<void> { await this.tableService.constraintResultTable.delete({ noteGuid: note.guid, }); await this.check(note); } async removeOne(guid: string): Promise<void> { await this.tableService.constraintResultTable.delete({ noteGuid: guid, }); } private async check(note: NoteEntity): Promise<void> { if (note.deleted) return; for (const constraint of appConfigLoader.app.constraints) { if (!this.eval(note, constraint.query)) continue; const constraintResult = new ConstraintResultEntity(); constraintResult.noteGuid = note.guid; constraintResult.constraintId = constraint.id; await this.tableService.constraintResultTable.save(constraintResult); } } private eval( note: NoteEntity, query: AppConfig.IConstraintConfigQuery ): boolean { if (!_.isUndefined(query.title)) if (!this.evalString(note.title, query.title)) return false; if (!_.isUndefined(query.created)) if (!this.evalNumber(note.created, query.created)) return false; if (!_.isUndefined(query.updated)) if (!this.evalNumber(note.updated, query.updated)) return false; if (!_.isUndefined(query.reminderOrder)) if (!this.evalNumber(note.attributes?.reminderOrder, query.reminderOrder)) return false; if (!_.isUndefined(query.reminderDoneTime)) if ( !this.evalNumber( note.attributes?.reminderDoneTime, query.reminderDoneTime ) ) return false; if (!_.isUndefined(query.reminderTime)) if (!this.evalNumber(note.attributes?.reminderTime, query.reminderTime)) return false; if (query.notebook || query.stack) { const notebook = note.notebookGuid ? this.tableService.caches.notebooks[note.notebookGuid] : null; if (!_.isUndefined(query.notebook)) if (!this.evalString(notebook?.name, query.notebook)) return false; if (!_.isUndefined(query.stack)) if (!this.evalString(notebook?.stack, query.stack)) return false; } if (query.tag) { const tagNames: string[] = []; for (const tagGuid of _.toArray(note.tagGuids)) { const tag = this.tableService.caches.tags[tagGuid]; if (!tag?.name) continue; tagNames.push(tag.name); } if (!this.evalTags(tagNames, query.tag)) return false; } return true; } private evalNumber( target: number | undefined | null, query: AppConfig.TConstraintConfigNumberOperator ): boolean { if (_.isNil(query)) return _.isNil(target); if (_.isNil(target)) return _.isNil(query); if (_.isNumber(query)) return target === query; if (_.isObject(query)) { if (!_.isUndefined(query.$eq) && !(target === query.$eq)) return false; if (!_.isUndefined(query.$ne) && !(target !== query.$ne)) return false; if (!_.isUndefined(query.$gt) && !(target > query.$gt)) return false; if (!_.isUndefined(query.$gte) && !(target >= query.$gte)) return false; if (!_.isUndefined(query.$lt) && !(target < query.$lt)) return false; if (!_.isUndefined(query.$lte) && !(target <= query.$lte)) return false; if ( !_.isUndefined(query.$between) && !(target >= query.$between[0] && target <= query.$between[1]) ) return false; if ( !_.isUndefined(query.$notBetween) && target >= query.$notBetween[0] && target <= query.$notBetween[1] ) return false; if (!_.isUndefined(query.$in) && !_.includes(query.$in, target)) return false; if (!_.isUndefined(query.$notIn) && _.includes(query.$notIn, target)) return false; if (!_.isUndefined(query.$not) && this.evalNumber(target, query.$not)) return false; } return true; } private evalString( target: string | undefined | null, query: AppConfig.TConstraintConfigStringOperator ): boolean { if (_.isNil(target)) return _.isNil(query); if (_.isNil(query)) return _.isNil(target); if (_.isArray(query)) return _.includes(query, target); if (_.isRegExp(query)) return query.test(target); if (_.isString(query)) return target === query; if (_.isObject(query)) { if (!_.isUndefined(query.$eq) && !(target === query.$eq)) return false; if (!_.isUndefined(query.$ne) && !(target !== query.$ne)) return false; if (!_.isUndefined(query.$in) && !_.includes(query.$in, target)) return false; if (!_.isUndefined(query.$notIn) && _.includes(query.$notIn, target)) return false; if (!_.isUndefined(query.$not) && this.evalString(target, query.$not)) return false; } return true; } private evalArray( target: string[] | undefined | null, query: AppConfig.TConstraintConfigArrayOperator ): boolean { if (_.isNil(target)) return false; if (_.isString(query)) return _.includes(target, query); if (_.isArray(query)) return _.every(query, (q) => _.includes(target, q)); if (_.isObject(query)) { if (!_.isUndefined(query.$in)) if (!_.some(query.$in, (q) => _.includes(target, q))) return false; if (!_.isUndefined(query.$notIn)) if (_.some(query.$notIn, (q) => _.includes(target, q))) return false; if (!_.isUndefined(query.$all)) if (!_.every(query.$all, (q) => _.includes(target, q))) return false; if (!_.isUndefined(query.$notAll)) if (_.every(query.$notAll, (q) => _.includes(target, q))) return false; } return true; } private evalTags( target: string[] | undefined | null, query: AppConfig.TConstraintConfigTagsOperator ): boolean { let expandQuery: AppConfig.TConstraintConfigArrayOperator = []; if (_.isString(query)) expandQuery = query; else if (_.isArray(query)) expandQuery = query; else if (_.isObject(query)) expandQuery = _.mapValues(query, (value) => _.isUndefined(value) ? undefined : this.expandTagTree(value) ); return this.evalArray(target, expandQuery); } private expandTagTree( target: AppConfig.TConstraintConfigTreeOperator ): string[] { if (_.isArray(target)) return target; if (_.isObject(target)) { if (target.$children) return this.expandTagTreeRoots(target.$children, false); if (target.$descendants) return this.expandTagTreeRoots(target.$descendants, true); } return []; } private expandTagTreeRoots( names: string | string[], recursive: boolean ): string[] { if (_.isString(names)) return this.expandTagTreeRecursive(names, recursive); if (_.isArray(names)) return _.flatMap(names, (name) => this.expandTagTreeRecursive(name, recursive) ); return []; } private expandTagTreeRecursive( name: string | undefined, recursive: boolean ): string[] { if (!name) return []; const currentTag = _.find( this.tableService.caches.tags, (tag) => tag.name === name ); if (!currentTag) return []; const childTags = _.filter( this.tableService.caches.tags, (tag) => tag.parentGuid === currentTag.guid ); const childTagNames = childTags .map((tag) => tag.name) .filter((name) => !!name); if (recursive) return [ ...childTagNames, ...childTagNames.flatMap((name) => this.expandTagTreeRecursive(name, true) ), ]; else return childTagNames; } } <file_sep>/src/server/route/note.route.ts import { injectable } from "inversify"; import SocketIO from "socket.io"; import { BaseEntityRoute } from "~/src/server/route/base-entity.route"; import { NoteEntity } from "~/src/common/entity/note.entity"; import { SessionService } from "~/src/server/service/session.service"; import { TableService } from "~/src/server/service/table.service"; import { NoteTable } from "~/src/server/table/note.table"; import { SyncService } from "~/src/server/service/sync.service"; import { FindEntityWhereOptions } from "~/src/common/entity/base.entity"; @injectable() export class NoteRoute extends BaseEntityRoute<NoteEntity, NoteTable> { constructor( protected tableService: TableService, protected sessionService: SessionService, protected syncService: SyncService ) { super(tableService, sessionService); } async connect(socket: SocketIO.Socket): Promise<void> { await super.connect(socket); this.on(socket, "getContent", this.onGetContent); this.on(socket, "reParse", this.onReParse); } protected async onGetContent( _socket: SocketIO.Socket, guid: string ): Promise<NoteEntity | null> { if (!guid) return null; await this.syncService.lock(); const note = await this.table.loadRemote(guid); await this.syncService.unlock(); return note; } protected async onReParse( _socket: SocketIO.Socket, query: FindEntityWhereOptions<NoteEntity> ): Promise<boolean> { await this.syncService.lock(); await this.table.reParseNotes(query); await this.syncService.unlock(); return true; } } <file_sep>/src/server/route/base-entity.route.ts import _ from "lodash"; import SocketIO from "socket.io"; import { BaseRoute } from "~/src/server/route/base.route"; import { container } from "~/src/common/inversify.config"; import { TableService } from "~/src/server/service/table.service"; import { SessionService } from "~/src/server/service/session.service"; import { TEntityClass, FindManyEntityOptions, BaseEntity, } from "~/src/common/entity/base.entity"; import { SYMBOL_TABLES, SYMBOL_TYPES } from "~/src/common/symbols"; import { BaseTable } from "~/src/server/table/base.table"; export abstract class BaseEntityRoute< TEntity extends BaseEntity, TTable extends BaseTable<TEntity> > extends BaseRoute { EntityClass: TEntityClass<TEntity>; protected constructor( protected tableService: TableService, protected sessionService: SessionService ) { super(); const name = _.lowerFirst(_.replace(this.Class.name, /Route$/, "")); this.EntityClass = container.getNamed( SYMBOL_TYPES.Entity, _.get(SYMBOL_TABLES, name) ); } get Class(): typeof BaseEntityRoute { return <typeof BaseEntityRoute>this.constructor; } get table(): TTable { return this.tableService.getTable<TEntity, TTable>(this.EntityClass); } get basePath(): string { return this.EntityClass.params.name; } async connect(socket: SocketIO.Socket): Promise<void> { this.on(socket, "find", this.onFind); this.on(socket, "count", this.onCount); this.on(socket, "save", this.onSave); this.on(socket, "remove", this.onRemove); await Promise.resolve(); } protected async onFind( _socket: SocketIO.Socket, options: FindManyEntityOptions<TEntity> ): Promise<TEntity[]> { const entities = await this.table.findAll(options); return entities; } protected async onCount( _socket: SocketIO.Socket, options: FindManyEntityOptions<TEntity> ): Promise<number> { const count = await this.table.count(options); return count; } protected async onSave( _socket: SocketIO.Socket, data: Object ): Promise<boolean> { const entity: TEntity = new this.EntityClass(data); await this.table.save(entity); return true; } protected async onRemove( _socket: SocketIO.Socket, id: number | string ): Promise<boolean> { if (!id) throw new Error("削除対象のIDが指定されていません"); await this.table.delete(<any>{ [this.EntityClass.params.primaryKey]: id, }); return true; } } <file_sep>/src/server/table/attendance.table.ts import { injectable } from "inversify"; import { BaseTable } from "~/src/server/table/base.table"; import { AttendanceEntity } from "~/src/common/entity/attendance.entity"; @injectable() export class AttendanceTable extends BaseTable<AttendanceEntity> {} <file_sep>/src/common/entity/base.entity.ts import _ from "lodash"; export interface EntityParams<T extends BaseEntity> { name: string; primaryKey: keyof T; displayField: keyof T; archive: boolean; default: FindManyEntityOptions<T>; append: FindManyEntityOptions<T>; columns?: { [P in keyof T | string]: EntityColumnParams; }; indicies?: { name: string; columns: string[]; unique?: boolean; }[]; jsonFields?: string[]; } export interface EntityColumnParams { type: EntityColumnType; primary?: boolean; generated?: true; nullable: boolean; } export type TEntityClass<T extends BaseEntity> = { new (data: any): T; readonly params: EntityParams<T>; }; export type EntityToInterface<T extends BaseEntity> = Pick<T, T["FIELD_NAMES"]>; export type EntityColumnType = | "integer" | "real" | "boolean" | "string" | "text" | "date" | "datetime"; export interface FindManyEntityOptions<T extends BaseEntity> extends FindOneEntityOptions<T> { take?: number; skip?: number; } export interface FindOneEntityOptions<T extends BaseEntity> { where?: FindEntityWhereOptions<T>; order?: { [P in keyof T]?: "ASC" | "DESC"; }; archive?: boolean; } export type FindEntityWhereOptions<T extends BaseEntity> = { [P in keyof T]?: FindEntityWhereColumnOptions<T[P]>; }; export type FindEntityWhereColumnOptions< P extends string | number | Date | null > = P | FindEntityWhereColumnOperators<P>; export type FindEntityWhereColumnOperators< P extends string | number | Date | null > = { $eq?: P; $ne?: P; $lt?: P extends number ? P : never; $lte?: P extends number ? P : never; $gt?: P extends number ? P : never; $gte?: P extends number ? P : never; $between?: P extends number | Date ? [P, P] : never; $in?: P[]; }; export abstract class BaseEntity { FIELD_NAMES!: string; FIELD_NAMES2!: "archiveId" | "createdAt" | "updatedAt"; static readonly params: EntityParams<BaseEntity>; constructor(data: any = {}) { for (const key of _.keys(data)) { _.set(this, key, data[key]); } } get Class(): typeof BaseEntity { return <typeof BaseEntity>this.constructor; } get primaryKey(): any { return _.get(this, this.Class.params.primaryKey); } get displayField(): any { return _.get(this, this.Class.params.displayField); } archiveId?: number; createdAt?: Date | number; updatedAt?: Date | number; [key: string]: any; } <file_sep>/src/iko/iko.sql ATTACH "database_old.db" AS old; INSERT INTO archive_note SELECT * FROM old.archiveNotes; INSERT INTO attendance SELECT * FROM old.attendances; INSERT INTO constraint_result SELECT * FROM old.constraintResults; INSERT INTO linked_notebook SELECT * FROM old.linkedNotebooks; INSERT INTO note SELECT * FROM old.notes; INSERT INTO notebook SELECT * FROM old.notebooks; INSERT INTO option SELECT * FROM old.options; INSERT INTO profit_log SELECT * FROM old.profitLogs; INSERT INTO saved_search SELECT * FROM old.savedSearches; INSERT INTO tag SELECT * FROM old.tags; INSERT INTO time_log SELECT * FROM old.timeLogs; UPDATE "attendance" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "constraint_result" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "linked_notebook" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "notebook" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "note" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "option" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "profit_log" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "saved_search" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "tag" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "time_log" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); UPDATE "archive_note" SET "createdAt" = strftime('%Y-%m-%d %H:%M:%S', "createdAt"), "updatedAt" = strftime('%Y-%m-%d %H:%M:%S', "updatedAt"); VACUUM; <file_sep>/src/client/plugins/my-store.ts import { Plugin } from "@nuxt/types"; import { myStore } from "~/src/client/store"; const myStorePlugin: Plugin = (_context, inject) => { inject("myStore", myStore); }; export default myStorePlugin; declare module "vue/types/vue" { interface Vue { $myStore: typeof myStore; } } declare module "@nuxt/types" { interface NuxtAppOptions { $myStore: typeof myStore; } } /* declare module "vuex/types/index" { interface Store<S> { $myStore: typeof myStore; } } */ <file_sep>/src/client/store/datastore.ts import { Module, Mutation, MutationAction, VuexModule, } from "vuex-module-decorators"; import Evernote from "evernote"; import _ from "lodash"; import { NotebookEntity } from "~/src/common/entity/notebook.entity"; import { TagEntity } from "~/src/common/entity/tag.entity"; import { myService } from "~/src/client/service"; import { appConfigLoader } from "~/src/common/util/app-config-loader"; @Module({ name: "datastore", stateFactory: true, namespaced: true, }) export default class DatastoreModule extends VuexModule { user: Evernote.Types.User | null = null; currentPersonId: number = 0; notebooks: { [guid: string]: NotebookEntity } = {}; stacks: string[] = []; tags: { [guid: string]: TagEntity } = {}; get currentPerson(): AppConfig.IPersonConfig | null { return ( _.find(appConfigLoader.app.persons, { id: this.currentPersonId }) ?? null ); } @Mutation setCurrentPersonId(id: number) { this.currentPersonId = id; } @MutationAction({ mutate: ["user", "currentPersonId", "notebooks", "stacks", "tags"], }) async initialize() { const user = await myService.request.loadOption("user"); const currentPersonId = _.toInteger( (await myService.request.loadSession("currentPersonId")) || 0 ); const notebooks = await myService.request.find<NotebookEntity>( NotebookEntity ); const tags = await myService.request.find<TagEntity>(TagEntity); return { user, currentPersonId, notebooks: _.keyBy(notebooks, "guid"), stacks: _(notebooks).map("stack").uniq().filter(_.isString).value(), tags: _.keyBy(tags, "guid"), }; } } <file_sep>/src/test/.eslintrc.js module.exports = { // add your custom rules here rules: { "dot-notation": "off", }, }; <file_sep>/src/server/route/attendance.route.ts import { injectable } from "inversify"; import { BaseEntityRoute } from "./base-entity.route"; import { SessionService } from "~/src/server/service/session.service"; import { TableService } from "~/src/server/service/table.service"; import { AttendanceEntity } from "~/src/common/entity/attendance.entity"; import { AttendanceTable } from "~/src/server/table/attendance.table"; @injectable() export class AttendanceRoute extends BaseEntityRoute< AttendanceEntity, AttendanceTable > { constructor( protected tableService: TableService, protected sessionService: SessionService ) { super(tableService, sessionService); } } <file_sep>/src/client/plugins/logger.ts import { Plugin } from "@nuxt/types"; import logLevel from "loglevel"; import { logger } from "~/src/common/logger"; const loggerPlugin: Plugin = (_context, inject) => { inject("logger", logger); }; export default loggerPlugin; declare module "vue/types/vue" { interface Vue { $logger: logLevel.Logger; } } declare module "@nuxt/types" { interface NuxtAppOptions { $logger: logLevel.Logger; } } /* declare module "vuex/types/index" { interface Store<S> { $logger: logLevel.Logger; } } */ <file_sep>/src/client/filter/numeral.filter.ts import Vue from "vue"; import numeral from "numeral"; export function numeralFilter(input: any, format: string): string { return numeral(input).format(format); } Vue.filter("numeral", numeralFilter); <file_sep>/src/server/table/base.table.ts import _ from "lodash"; import { Between, EntitySchema, EntitySchemaColumnOptions, EntitySchemaIndexOptions, Equal, FindConditions, FindManyOptions, getRepository, In, LessThan, LessThanOrEqual, MoreThan, MoreThanOrEqual, Not, Repository, } from "typeorm"; import { EntitySchemaOptions } from "typeorm/entity-schema/EntitySchemaOptions"; import { injectable } from "inversify"; import { SYMBOL_TABLES, SYMBOL_TYPES } from "~/src/common/symbols"; import { TEntityClass, EntityColumnType, FindEntityWhereColumnOperators, FindEntityWhereOptions, FindManyEntityOptions, FindOneEntityOptions, EntityToInterface, BaseEntity, } from "~/src/common/entity/base.entity"; import { container } from "~/src/common/inversify.config"; import { assertIsDefined } from "~/src/common/util/assert"; import { logger } from "~/src/common/logger"; @injectable() export abstract class BaseTable<T extends BaseEntity> { readonly EntityClass: TEntityClass<T>; readonly schema: EntitySchema<EntityToInterface<T>>; readonly archiveSchema: EntitySchema<EntityToInterface<T>> | null = null; private _repository: Repository<EntityToInterface<T>> | null = null; private _archiveRepository: Repository<EntityToInterface<T>> | null = null; get Class(): typeof BaseTable { return <typeof BaseTable>this.constructor; } get repository(): Repository<EntityToInterface<T>> { assertIsDefined(this._repository); return this._repository; } get archiveRepository(): Repository<EntityToInterface<T>> { assertIsDefined(this._archiveRepository); return this._archiveRepository; } constructor() { const name = _.lowerFirst(_.replace(this.Class.name, /Table$/, "")); this.EntityClass = container.getNamed( SYMBOL_TYPES.Entity, _.get(SYMBOL_TABLES, name) ); const schemaOptions = this.makeSchemaOptions(); this.schema = new EntitySchema(schemaOptions); if (this.EntityClass.params.archive) { const archiveSchemaOptions: EntitySchemaOptions<T> = _.clone( schemaOptions ); archiveSchemaOptions.name = "archive" + _.upperFirst(name); const addIndexes: EntitySchemaIndexOptions[] = []; archiveSchemaOptions.columns = {}; archiveSchemaOptions.columns.archiveId = { type: "int", primary: true, generated: true, }; _.each(schemaOptions.columns, (column, name) => { const addColumn = _.clone(column); if (!addColumn) return; if (addColumn.primary || addColumn.unique) addIndexes.push({ name: _.snakeCase(archiveSchemaOptions.name) + "_" + _.snakeCase(addColumn.name), unique: false, columns: [name], }); addColumn.primary = false; addColumn.unique = false; _.set(archiveSchemaOptions.columns, name, addColumn); }); archiveSchemaOptions.indices = _.union(addIndexes, schemaOptions.indices); this.archiveSchema = new EntitySchema(archiveSchemaOptions); } } private makeSchemaOptions(): EntitySchemaOptions<T> { return { name: this.EntityClass.params.name, columns: { ..._.mapValues( this.EntityClass.params.columns, (column, name): EntitySchemaColumnOptions => { assertIsDefined(column); return { name, type: this.makeSchemaColumnType(column.type), primary: column.primary, generated: column.generated, nullable: column.nullable, }; } ), createdAt: { type: "datetime", createDate: true, }, updatedAt: { type: "datetime", updateDate: true, }, }, indices: this.EntityClass.params.indicies?.map((index) => ({ name: _.snakeCase(this.EntityClass.params.name) + "_" + _.snakeCase(index.name), columns: index.columns, unique: index.unique, })), }; } private makeSchemaColumnType( type: EntityColumnType ): EntitySchemaColumnOptions["type"] { if (type === "string") return "text"; return type; } initialize() { this._repository = getRepository(this.schema); if (this.archiveSchema) this._archiveRepository = getRepository(this.archiveSchema); } async findOne(argOptions: FindOneEntityOptions<T> = {}): Promise<T | null> { this.message("find", ["local"], this.EntityClass.params.name, true, { query: argOptions, }); const options = this.parseFindOptions(argOptions); const data: | Partial<EntityToInterface<T>> | undefined = await this.repository.findOne(options); this.message("find", ["local"], this.EntityClass.params.name, false, { query: argOptions, }); return data ? this.prepareLoadEntity(data) : null; } async findByPrimary(primaryKey: number | string): Promise<T | null> { return this.findOne({ where: <any>{ [this.EntityClass.params.primaryKey]: primaryKey }, }); } async findAll(argOptions: FindManyEntityOptions<T> = {}): Promise<T[]> { const repository = this.chooseRepository(argOptions); this.message("find", ["local"], this.EntityClass.params.name, true, { query: argOptions, }); const options = this.parseFindOptions(argOptions); const datas: Partial<EntityToInterface<T>>[] = await repository.find( options ); this.message("find", ["local"], this.EntityClass.params.name, false, { length: datas.length, query: argOptions, }); return _.map(datas, (data) => this.prepareLoadEntity(data)); } async count(argOptions: FindManyEntityOptions<T> = {}): Promise<number> { const repository = this.chooseRepository(argOptions); this.message("count", ["local"], this.EntityClass.params.name, true, { query: argOptions, }); const options = this.parseFindOptions(argOptions); const count = await repository.count(options); this.message("count", ["local"], this.EntityClass.params.name, false, { count, query: argOptions, }); return count; } private chooseRepository(options: { archive?: boolean; }): Repository<EntityToInterface<T>> { const repository = options.archive ? this.archiveRepository : this.repository; assertIsDefined(repository); return repository; } private parseFindOptions( argOptions: FindManyEntityOptions<T> = {} ): FindManyOptions<EntityToInterface<T>> { argOptions.where = argOptions.where ?? _.clone(this.EntityClass.params.default.where); argOptions.where = _.merge( argOptions.where || {}, this.EntityClass.params.append.where || {} ); argOptions.order = argOptions.order || _.clone(this.EntityClass.params.default.order); _.merge(argOptions.order || {}, this.EntityClass.params.append.order || {}); // TODO: $gte等を処理する機能を組み込む const options: FindManyOptions<EntityToInterface<T>> = { where: this.parseFindWhereOptions(argOptions.where), order: argOptions.order, take: argOptions.take, skip: argOptions.skip, }; return options; } private parseFindWhereOptions( where: FindEntityWhereOptions<T> | undefined ): FindConditions<EntityToInterface<T>> | undefined { if (where === undefined) return undefined; const result: FindConditions<T> = {}; for (const key in where) { const whereColumn = where[key]; if (whereColumn === undefined) continue; else if (whereColumn === null) { result[key] = <T[keyof T]>null; continue; } else if (typeof whereColumn !== "object") { result[key] = <T[keyof T]>whereColumn; continue; } const wc: FindEntityWhereColumnOperators<T[keyof T]> = whereColumn ?? {}; // TODO: 型変換が上手くいっていないのでanyにしている if (wc.$eq !== undefined) result[key] = <any>Equal(wc.$eq); else if (wc.$ne !== undefined) result[key] = <any>Not(wc.$ne); else if (wc.$gt !== undefined) result[key] = <any>MoreThan(wc.$gt); else if (wc.$gte !== undefined) result[key] = <any>MoreThanOrEqual(wc.$gte); else if (wc.$lt !== undefined) result[key] = <any>LessThan(wc.$lt); else if (wc.$lte !== undefined) result[key] = <any>LessThanOrEqual(wc.$lte); else if (wc.$between !== undefined) result[key] = <any>Between(wc.$between[0], wc.$between[1]); else if (wc.$in !== undefined) result[key] = <any>In(wc.$in); } return result; } async save(entity: T, archive: boolean = false): Promise<T | null> { if (!entity) return null; const savedEntities = await this.saveAll([entity], archive); return savedEntities.length === 0 ? null : savedEntities[0]; } async saveAll(entities: T[], archive: boolean = false): Promise<T[]> { if (!entities || entities.length === 0) return []; this.message("save", ["local"], this.EntityClass.params.name, true, { count: entities.length, entities: entities.map((entity) => _.pick(entity, ["primaryKey", "displayField"]) ), }); const saveDatas = entities.map((entity) => this.prepareSaveEntity(entity)); const savedDatas: Partial<T>[] = await this.repository.save(saveDatas); const savedEntities = savedDatas.map((savedData) => this.prepareLoadEntity(savedData) ); this.message("save", ["local"], this.EntityClass.params.name, false, { count: entities.length, entities: savedEntities.map((savedEntity) => _.pick(savedEntity, ["primaryKey", "displayField"]) ), }); if (archive && this.archiveRepository) { this.message( "insert", ["local", "archive"], this.EntityClass.params.name, true, { count: savedDatas.length, entities: savedDatas.map((savedData) => _.pick(savedData, ["primaryKey", "displayField"]) ), } ); const archiveSaveDatas = savedEntities.map((entity) => this.prepareSaveEntity(entity) ); const archiveSavedDatas = await this.archiveRepository.save( archiveSaveDatas ); const archiveSavedEntities = archiveSavedDatas.map((savedData) => this.prepareLoadEntity(savedData) ); this.message( "insert", ["local", "archive"], this.EntityClass.params.name, false, { count: archiveSavedEntities.length, entities: archiveSavedEntities.map((entity) => _.pick(entity, ["archiveId", "primaryKey", "displayField"]) ), } ); } return savedEntities; } async delete( criteria: Parameters<Repository<EntityToInterface<T>>["delete"]>[0] ): Promise<void> { if (!criteria || (Array.isArray(criteria) && criteria.length === 0)) return; this.message("remove", ["local"], this.EntityClass.params.name, true, { criteria, }); const deleteResult = await this.repository.delete(criteria); this.message("remove", ["local"], this.EntityClass.params.name, false, { criteria, deleteResult, }); } async clear(): Promise<void> { this.message("clear", ["local"], this.EntityClass.params.name, true); await this.repository.clear(); this.message("clear", ["local"], this.EntityClass.params.name, false); } protected message( action: string, options: string[], name: string, isStart: boolean, dispData: Object | null = null ) { const message = `${_.startCase(action)} ${_.join( options, " " )} ${name} was ${isStart ? "started" : "finished"}. ${ dispData ? " " + JSON.stringify(dispData) : "" }`; logger.trace(message); } protected prepareSaveEntity(entity: T): Partial<T> { const data: Partial<T> = _.clone(entity); for (const jsonField of _.defaultTo( this.EntityClass.params.jsonFields, [] )) { _.set(data, jsonField, JSON.stringify(_.get(entity, jsonField))); } return data; } protected prepareLoadEntity(data: Partial<EntityToInterface<T>>): T { for (const jsonField of _.defaultTo( this.EntityClass.params.jsonFields, [] )) { const json = _.get(data, jsonField); _.set( data, jsonField, typeof json === "string" ? JSON.parse(json) : null ); } return new this.EntityClass(data); } } <file_sep>/src/server/route/option.route.ts import { injectable } from "inversify"; import { OptionTable } from "~/src/server/table/option.table"; import { OptionEntity } from "~/src/common/entity/option.entity"; import { BaseEntityRoute } from "~/src/server/route/base-entity.route"; import { TableService } from "~/src/server/service/table.service"; import { SessionService } from "~/src/server/service/session.service"; @injectable() export class OptionRoute extends BaseEntityRoute<OptionEntity, OptionTable> { constructor( protected tableService: TableService, protected sessionService: SessionService ) { super(tableService, sessionService); } } <file_sep>/src/types/nuxt.d.ts import { Route } from "vue-router"; import { Store } from "vuex"; export interface NuxtContext { isClient: boolean; isServer: boolean; isStatic: boolean; isDev: boolean; isHMR: boolean; route: Route; store: Store<any>; env: object; query: object; nuxtState: object; req: Request; res: Response; params: { [key: string]: any }; redirect: (code: number, path: string) => void; error: (params: { statusCode?: String; message?: String }) => void; // @ts-ignore beforeNuxtRender: (params: { Conmponents?: any; nuxtState: any }) => void; } <file_sep>/src/common/entity/attendance.entity.ts import { BaseEntity, EntityParams } from "./base.entity"; export class AttendanceEntity extends BaseEntity { FIELD_NAMES!: | "id" | "personId" | "year" | "month" | "day" | "arrivalTime" | "departureTime" | "restTime" | "remarks" | BaseEntity["FIELD_NAMES"]; static readonly params: EntityParams<AttendanceEntity> = { name: "attendance", primaryKey: "id", displayField: "id", archive: false, default: { take: 500, }, append: {}, columns: { id: { type: "integer", primary: true, generated: true, nullable: false, }, personId: { type: "integer", nullable: false, }, year: { type: "integer", nullable: false, }, month: { type: "integer", nullable: false, }, day: { type: "integer", nullable: false, }, arrivalTime: { type: "integer", nullable: true, }, departureTime: { type: "integer", nullable: true, }, restTime: { type: "integer", nullable: true, }, remarks: { type: "text", nullable: true, }, }, indicies: [ { name: "unique", columns: ["personId", "year", "month", "day"], unique: true, }, ], }; id!: number; personId!: number; year!: number; month!: number; day!: number; arrivalTime!: number | null; departureTime!: number | null; restTime!: number | null; remarks!: string | null; } <file_sep>/src/server/table/time-log.table.ts import { injectable } from "inversify"; import { BaseTable } from "~/src/server/table/base.table"; import { TimeLogEntity } from "~/src/common/entity/time-log.entity"; import { NoteEntity } from "~/src/common/entity/note.entity"; import { appConfigLoader } from "~/src/common/util/app-config-loader"; @injectable() export class TimeLogTable extends BaseTable<TimeLogEntity> { async parse(note: NoteEntity, lines: string[]): Promise<void> { const timeLogs: TimeLogEntity[] = []; for (const line of lines) { let matches = line.match(/(.*)[@@](\d{2,4}[/-]\d{1,2}[/-]\d{1,2}.+)/); if (matches) { const timeLog: TimeLogEntity = new TimeLogEntity({ id: undefined, noteGuid: note.guid, comment: matches[1], allDay: true, date: null, personId: 0, spentTime: null, }); const attributesText: string = matches[2]; // parse date and time matches = attributesText.match(/\d{2,4}[/-]\d{1,2}[/-]\d{1,2}/); const dateText: string = matches ? matches[0] : ""; matches = attributesText.match( /\d{1,2}:\d{1,2}:\d{1,2}|\d{1,2}:\d{1,2}/ ); const timeText: string = matches ? matches[0] : ""; timeLog.date = new Date(dateText + " " + timeText).getTime(); if (timeText) timeLog.allDay = false; // parse person for (const person of appConfigLoader.app.persons) { if (attributesText.includes(person.name)) timeLog.personId = person.id; } // parse spent time if ((matches = attributesText.match(/\d+h\d+m|\d+m|\d+h|\d+\.\d+h/i))) { const spentTimeText: string = matches[0]; matches = spentTimeText.match(/(\d+\.?\d*)h/); const spentHour: number = matches ? parseFloat(matches[1]) : 0; matches = spentTimeText.match(/(\d+\.?\d*)m/); const spentMinute: number = matches ? parseFloat(matches[1]) : 0; timeLog.spentTime = Math.round(spentHour * 60 + spentMinute); } if (timeLog.date && timeLog.personId) timeLogs.push(timeLog); } } await this.delete({ noteGuid: note.guid }); await this.saveAll(timeLogs); } } <file_sep>/src/server/route/session.route.ts import { injectable } from "inversify"; import SocketIO from "socket.io"; import { BaseRoute } from "~/src/server/route/base.route"; import { SessionService } from "~/src/server/service/session.service"; @injectable() export class SessionRoute extends BaseRoute { constructor(protected sessionService: SessionService) { super(); } get basePath(): string { return "session"; } async connect(socket: SocketIO.Socket): Promise<void> { this.on(socket, "load", this.onLoad); this.on(socket, "save", this.onSave); } protected async onLoad(socket: SocketIO.Socket, key: string): Promise<any> { return this.sessionService.load(socket, key); } protected async onSave( socket: SocketIO.Socket, key: string, value: any ): Promise<boolean> { await this.sessionService.save(socket, key, value); return true; } } <file_sep>/src/common/util/app-config-loader.ts import * as _ from "lodash"; import appConfig from "~/config/app.config"; class AppConfigLoader { private readonly caches: { [configName: string]: any }; constructor() { this.caches = {}; } get app(): AppConfig.IAppConfig { return this.load("app", appConfig); } private load(configName: string, config: any): any { if (!this.caches[configName]) { const targetEnvName: string = process.env.NODE_ENV || "development"; if (!config[targetEnvName]) { throw new Error( `/config/${configName}.config.ts has no "${targetEnvName}" setting.` ); } const targetEnvConfig: Object = {}; for (const envName in config) { const envConfig = config[envName]; if ( new RegExp("^" + envName.replace("*", ".*") + "$").test(targetEnvName) ) { _.merge(targetEnvConfig, envConfig); } } this.caches[configName] = targetEnvConfig; } return this.caches[configName]; } } export const appConfigLoader = new AppConfigLoader(); <file_sep>/src/client/store/index.ts import { Store } from "vuex"; import { getModule } from "vuex-module-decorators"; import DatastoreModule from "~/src/client/store/datastore"; import ProgressModule from "~/src/client/store/progress"; interface IMyStore { datastore: DatastoreModule; progress: ProgressModule; } export const myStore: IMyStore = <any>{}; function initialiseStores(store: Store<any>): void { myStore.datastore = getModule(DatastoreModule, store); myStore.progress = getModule(ProgressModule, store); } const initializer = (store: Store<any>) => initialiseStores(store); export const plugins = [initializer]; <file_sep>/src/common/entity/linked-notebook.entity.ts import { BaseEvernoteEntity } from "./base-evernote.entity"; import { EntityParams } from "./base.entity"; export class LinkedNotebookEntity extends BaseEvernoteEntity { FIELD_NAMES!: | "shareName" | "username" | "shareId" | "sharedNotebookGlobalId" | "uri" | "noteStoreUrl" | "webApiUriPrefix" | "stack" | "businessId" | BaseEvernoteEntity["FIELD_NAMES3"]; static readonly params: EntityParams<LinkedNotebookEntity> = { name: "linkedNotebook", primaryKey: "guid", displayField: "shareName", archive: false, default: { order: { updatedAt: "DESC" }, take: 500, }, append: {}, columns: { guid: { type: "string", primary: true, nullable: false, }, shareName: { type: "string", nullable: true, }, username: { type: "string", nullable: true, }, shareId: { type: "string", nullable: true, }, sharedNotebookGlobalId: { type: "string", nullable: true, }, uri: { type: "string", nullable: true, }, updateSequenceNum: { type: "integer", nullable: false, }, noteStoreUrl: { type: "string", nullable: true, }, webApiUrlPrefix: { type: "string", nullable: true, }, stack: { type: "string", nullable: true, }, businessId: { type: "integer", nullable: true, }, }, }; shareName!: string; username!: string | null; shareId!: string | null; sharedNotebookGlobalId!: string | null; uri!: string | null; noteStoreUrl!: string | null; webApiUrlPrefix!: string | null; stack!: string | null; businessId!: number | null; } <file_sep>/src/server/ddl/ddl.sql -- we don't know how to generate schema main (class Schema) :( create table archive_note ( archiveId integer not null primary key autoincrement, guid text not null, title text not null, content text, contentHash text not null, contentLength integer not null, created integer not null, updated integer not null, deleted integer, active boolean not null, updateSequenceNum integer not null, notebookGuid text not null, tagGuids text, resources text, attributes__subjectDate integer, attributes__latitude real, attributes__longitude real, attributes__altitude real, attributes__author text, attributes__source text, attributes__sourceURL text, attributes__sourceApplication text, attributes__shareDate integer, attributes__reminderOrder integer, attributes__reminderDoneTime integer, attributes__reminderTime integer, attributes__placeName text, attributes__contentClass text, attributes__applicationData text, attributes__classifications text, attributes__creatorId integer, attributes__lastEditorId integer, attributes__sharedWithBusiness boolean, attributes__conflictSourceNoteGuid text, attributes__noteTitleQuality integer, tagNames text, sharedNotes text, restrictions text, limits text, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create index archive_note_guid on archive_note (guid); create table attendance ( id integer not null primary key autoincrement, personId integer not null, year integer not null, month integer not null, day integer not null, arrivalTime integer, departureTime integer, restTime integer, remarks text, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create unique index attendance_unique on attendance (personId, year, month, day); create table constraint_result ( id integer not null primary key autoincrement, noteGuid text not null, constraintId integer not null, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create table linked_notebook ( guid text not null primary key, shareName text, username text, shareId text, sharedNotebookGlobalId text, uri text, updateSequenceNum integer not null, noteStoreUrl text, webApiUrlPrefix text, stack text, businessId integer, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create table note ( guid text not null primary key, title text not null, content text, contentHash text not null, contentLength integer not null, created integer not null, updated integer not null, deleted integer, active boolean not null, updateSequenceNum integer not null, notebookGuid text not null, tagGuids text, resources text, attributes__subjectDate integer, attributes__latitude real, attributes__longitude real, attributes__altitude real, attributes__author text, attributes__source text, attributes__sourceURL text, attributes__sourceApplication text, attributes__shareDate integer, attributes__reminderOrder integer, attributes__reminderDoneTime integer, attributes__reminderTime integer, attributes__placeName text, attributes__contentClass text, attributes__applicationData text, attributes__classifications text, attributes__creatorId integer, attributes__lastEditorId integer, attributes__sharedWithBusiness boolean, attributes__conflictSourceNoteGuid text, attributes__noteTitleQuality integer, tagNames text, sharedNotes text, restrictions text, limits text, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create table notebook ( guid text not null primary key, name text not null, updateSequenceNum integer not null, defaultNotebook boolean not null, serviceCreated integer, serviceUpdated integer, publishing text, published boolean, stack text, sharedNotebookIds text, sharedNotebooks text, businessNotebooks text, contact text, restrictions text, recipientSettings text, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create table option ( key text not null primary key, value text, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create table profit_log ( id integer not null primary key autoincrement, noteGuid text not null, comment text, profit integer not null, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create table saved_search ( guid text not null primary key, name text not null, query text, format integer, updateSequenceNum integer not null, scope text, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create table session ( expiredAt integer not null, id text not null primary key, json text not null, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create index session_expired_at on session (expiredAt); create table tag ( guid text not null primary key, name text not null, parentGuid text, updateSequenceNum integer not null, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); create table time_log ( id integer not null primary key autoincrement, noteGuid text not null, comment text, allDay boolean not null, date integer not null, personId integer not null, spentTime integer, createdAt datetime default datetime('now') not null, updatedAt datetime default datetime('now') not null ); <file_sep>/src/client/plugins/filter.ts import "~/src/client/filter"; <file_sep>/src/server/service/session.service.ts import { injectable } from "inversify"; import socketIo from "socket.io"; import Evernote from "evernote"; import Express from "express"; import ExpressSession from "express-session"; import { TypeormStore } from "connect-typeorm"; import { BaseServerService } from "./base-server.service"; import { logger } from "~/src/common/logger"; import { TableService } from "~/src/server/service/table.service"; import { SocketIoService } from "~/src/server/service/socket-io.service"; export interface ISession { user: Evernote.Types.User; } @injectable() export class SessionService extends BaseServerService { constructor( protected tableService: TableService, protected socketIoService: SocketIoService ) { super(); } async initialize(app: Express.Application) { logger.info(`セッションサービスの初期化を開始します.`); const sessionRepository = this.tableService.sessionTable.repository; const sessionMiddleware = ExpressSession({ name: "evernote-tasklog.connect.sid", secret: "keyboard cat", resave: false, saveUninitialized: true, store: new TypeormStore({ cleanupLimit: 100, }).connect(<any>sessionRepository), cookie: { maxAge: 7 * 24 * 60 * 60 * 1000, }, }); app.use(sessionMiddleware); this.socketIoService.initializeSession(sessionMiddleware); logger.info(`セッションサービスの初期化を完了しました.`); } load(socket: socketIo.Socket, key: string): ISession { return (<any>socket.request).session[key]; } async save(socket: socketIo.Socket, key: string, value: any): Promise<void> { await new Promise<void>((resolve, reject) => { (<any>socket.request).session[key] = value; (<any>socket.request).session.save((err: any) => { if (err) reject(err); resolve(); }); }); } } <file_sep>/src/server/route/sync.route.ts import { injectable } from "inversify"; import { Socket } from "socket.io"; import { BaseRoute } from "~/src/server/route/base.route"; import { SyncService } from "~/src/server/service/sync.service"; @injectable() export class SyncRoute extends BaseRoute { constructor(protected syncService: SyncService) { super(); } get basePath(): string { return "sync"; } async connect(socket: Socket): Promise<void> { this.on(socket, "run", this.onRun); } protected async onRun(_socket: Socket): Promise<boolean> { await this.syncService.sync(true); return true; } } <file_sep>/src/server/table/session.table.ts import { injectable } from "inversify"; import { BaseTable } from "~/src/server/table/base.table"; import { SessionEntity } from "~/src/common/entity/session.entity"; @injectable() export class SessionTable extends BaseTable<SessionEntity> {} <file_sep>/src/server/inversify.config.ts import { SYMBOL_TABLES, SYMBOL_TYPES } from "~/src/common/symbols"; import { BaseEntity } from "~/src/common/entity/base.entity"; import { container } from "~/src/common/inversify.config"; import { serverLogger } from "~/src/server/logger"; import { ILogger, initializeLogger } from "~/src/common/logger"; import { ConstraintService } from "~/src/server/service/constraint.service"; import { EvernoteClientService } from "~/src/server/service/evernote-client.service"; import { MainService } from "~/src/server/service/main.service"; import { TableService } from "~/src/server/service/table.service"; import { SocketIoService } from "~/src/server/service/socket-io.service"; import { SessionService } from "~/src/server/service/session.service"; import { SyncService } from "~/src/server/service/sync.service"; import { BaseRoute } from "~/src/server/route/base.route"; import { AttendanceRoute } from "~/src/server/route/attendance.route"; import { ConstraintResultRoute } from "~/src/server/route/constraint-result.route"; import { NoteRoute } from "~/src/server/route/note.route"; import { NotebookRoute } from "~/src/server/route/notebook.route"; import { OptionRoute } from "~/src/server/route/option.route"; import { ProfitLogRoute } from "~/src/server/route/profit-log.route"; import { SessionRoute } from "~/src/server/route/session.route"; import { SyncRoute } from "~/src/server/route/sync.route"; import { TagRoute } from "~/src/server/route/tag.route"; import { TimeLogRoute } from "~/src/server/route/time-log.route"; import { BaseTable } from "~/src/server/table/base.table"; import { AttendanceTable } from "~/src/server/table/attendance.table"; import { ConstraintResultTable } from "~/src/server/table/constraint-result.table"; import { LinkedNotebookTable } from "~/src/server/table/linked-notebook.table"; import { NoteTable } from "~/src/server/table/note.table"; import { NotebookTable } from "~/src/server/table/notebook.table"; import { OptionTable } from "~/src/server/table/option.table"; import { ProfitLogTable } from "~/src/server/table/profit-log.table"; import { SavedSearchTable } from "~/src/server/table/saved-search.table"; import { SessionTable } from "~/src/server/table/session.table"; import { TagTable } from "~/src/server/table/tag.table"; import { TimeLogTable } from "~/src/server/table/time-log.table"; // Logger container.bind<ILogger>(SYMBOL_TYPES.Logger).toConstantValue(serverLogger); initializeLogger(); // Service系 container .bind<ConstraintService>(ConstraintService) .toSelf() .inSingletonScope(); container .bind<EvernoteClientService>(EvernoteClientService) .toSelf() .inSingletonScope(); container.bind<MainService>(MainService).toSelf().inSingletonScope(); container.bind<TableService>(TableService).toSelf().inSingletonScope(); container.bind<SocketIoService>(SocketIoService).toSelf().inSingletonScope(); container.bind<SessionService>(SessionService).toSelf().inSingletonScope(); container.bind<SyncService>(SyncService).toSelf().inSingletonScope(); // Route系 container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(AttendanceRoute) .whenTargetNamed(SYMBOL_TABLES.attendance); container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(ConstraintResultRoute) .whenTargetNamed(SYMBOL_TABLES.constraintResult); container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(NoteRoute) .whenTargetNamed(SYMBOL_TABLES.note); container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(NotebookRoute) .whenTargetNamed(SYMBOL_TABLES.notebook); container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(OptionRoute) .whenTargetNamed(SYMBOL_TABLES.option); container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(ProfitLogRoute) .whenTargetNamed(SYMBOL_TABLES.profitLog); container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(SessionRoute) .whenTargetNamed("session"); container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(SyncRoute) .whenTargetNamed("sync"); container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(TagRoute) .whenTargetNamed(SYMBOL_TABLES.tag); container .bind<BaseRoute>(SYMBOL_TYPES.Route) .to(TimeLogRoute) .whenTargetNamed(SYMBOL_TABLES.timeLog); // Table系 container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(AttendanceTable) .whenTargetNamed(SYMBOL_TABLES.attendance); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(ConstraintResultTable) .whenTargetNamed(SYMBOL_TABLES.constraintResult); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(LinkedNotebookTable) .whenTargetNamed(SYMBOL_TABLES.linkedNotebook); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(NoteTable) .whenTargetNamed(SYMBOL_TABLES.note); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(NotebookTable) .whenTargetNamed(SYMBOL_TABLES.notebook); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(ProfitLogTable) .whenTargetNamed(SYMBOL_TABLES.profitLog); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(SavedSearchTable) .whenTargetNamed(SYMBOL_TABLES.savedSearch); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(SessionTable) .whenTargetNamed(SYMBOL_TABLES.session); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(OptionTable) .whenTargetNamed(SYMBOL_TABLES.option); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(TagTable) .whenTargetNamed(SYMBOL_TABLES.tag); container .bind<BaseTable<BaseEntity>>(SYMBOL_TYPES.Table) .to(TimeLogTable) .whenTargetNamed(SYMBOL_TABLES.timeLog); <file_sep>/src/server/table/profit-log.table.ts import { injectable } from "inversify"; import { BaseTable } from "~/src/server/table/base.table"; import { ProfitLogEntity } from "~/src/common/entity/profit-log.entity"; import { NoteEntity } from "~/src/common/entity/note.entity"; @injectable() export class ProfitLogTable extends BaseTable<ProfitLogEntity> { async parse(note: NoteEntity, lines: string[]): Promise<void> { const profitLogs: ProfitLogEntity[] = []; for (const line of lines) { const matches = line.match(/(.*)[@@][\\¥$$](.+)/i); if (matches) { profitLogs.push( new ProfitLogEntity({ id: undefined, noteGuid: note.guid, comment: matches[1], profit: parseInt(matches[2].replace(/,/g, "")), }) ); } } if (!note.guid) return; await this.delete({ noteGuid: note.guid }); await this.saveAll(profitLogs); } } <file_sep>/src/common/logger.ts import { SYMBOL_TYPES } from "~/src/common/symbols"; import { container } from "~/src/common/inversify.config"; export interface ILogger { trace(message: any, ...args: any[]): void; debug(message: any, ...args: any[]): void; info(message: any, ...args: any[]): void; warn(message: any, ...args: any[]): void; error(message: any, ...args: any[]): void; } // eslint-disable-next-line import/no-mutable-exports export let logger: ILogger; export function initializeLogger() { logger = container.get<ILogger>(SYMBOL_TYPES.Logger); } <file_sep>/src/server/table/base-evernote.table.ts import { injectable } from "inversify"; import { BaseTable } from "./base.table"; import { BaseEvernoteEntity } from "~/src/common/entity/base-evernote.entity"; @injectable() export class BaseEvernoteTable< T extends BaseEvernoteEntity > extends BaseTable<T> {} <file_sep>/src/types/config.d.ts declare namespace AppConfig { interface IAppConfigs { [env: string]: Partial<IAppConfig>; } interface IAppConfig { port: number; https: boolean; logLevel: "trace" | "debug" | "info" | "warn" | "error"; sqlLogging: boolean; sandbox: boolean; token: string; persons: IPersonConfig[]; warningNoteCount: number; workingTimeStart: number; workingTimeEnd: number; defaultFilterParams: { timeline: IDefaultFilterParamsConfig; notes: IDefaultFilterParamsConfig; activity: IDefaultFilterParamsConfig; }; constraints: IConstraintConfig[]; } interface IPersonConfig { id: number; name: string; } interface IDefaultFilterParamsConfig { stacks?: string[]; notebooks?: string[]; } interface IConstraintConfig { id: number; label: string; query: IConstraintConfigQuery; } interface IConstraintConfigQuery { title?: TConstraintConfigStringOperator; notebook?: TConstraintConfigStringOperator; stack?: TConstraintConfigStringOperator; tag?: TConstraintConfigTagsOperator; created?: TConstraintConfigNumberOperator; updated?: TConstraintConfigNumberOperator; reminderOrder?: TConstraintConfigNumberOperator; reminderDoneTime?: TConstraintConfigNumberOperator; reminderTime?: TConstraintConfigNumberOperator; $and?: IConstraintConfigQuery[]; $or?: IConstraintConfigQuery[]; } type TConstraintConfigStringOperator = | null | string | string[] | RegExp | { $eq?: string; $ne?: string; $in?: string[]; $notIn?: string[]; $not?: TConstraintConfigStringOperator; }; type TConstraintConfigNumberOperator = | null | number | { $gt?: number; $gte?: number; $lt?: number; $lte?: number; $ne?: number; $eq?: number; $between?: [number, number]; $notBetween?: [number, number]; $in?: number[]; $notIn?: number[]; $not?: TConstraintConfigNumberOperator; }; type TConstraintConfigArrayOperator = | string | string[] | { $in?: string[]; $notIn?: string[]; $all?: string[]; $notAll?: string[]; }; type TConstraintConfigTagsOperator = | string | string[] | { $in?: TConstraintConfigTreeOperator; $notIn?: TConstraintConfigTreeOperator; $all?: TConstraintConfigTreeOperator; $notAll?: TConstraintConfigTreeOperator; }; type TConstraintConfigTreeOperator = | string[] | { $children?: string | string[]; $descendants?: string | string[]; }; namespace loader { const app: IAppConfig; } } <file_sep>/src/server/table/tag.table.ts import { injectable } from "inversify"; import { BaseEvernoteTable } from "~/src/server/table/base-evernote.table"; import { TagEntity } from "~/src/common/entity/tag.entity"; @injectable() export class TagTable extends BaseEvernoteTable<TagEntity> {} <file_sep>/src/server/table/constraint-result.table.ts import { injectable } from "inversify"; import { ConstraintResultEntity } from "~/src/common/entity/constraint-result.entity"; import { BaseTable } from "~/src/server/table/base.table"; @injectable() export class ConstraintResultTable extends BaseTable<ConstraintResultEntity> {} <file_sep>/src/client/components/base.component.ts import { Vue } from "nuxt-property-decorator"; import _ from "lodash"; import moment from "moment"; import numeral from "numeral"; import "bootstrap-vue"; import { NuxtContext } from "~/src/types/nuxt"; export abstract class BaseComponent extends Vue { lodash = _; moment = moment; numeral = numeral; // インスタンスライフサイクルフックの定義 async beforeCreate(): Promise<void> {} async created(): Promise<void> {} async beforeMount(): Promise<void> {} async mounted(): Promise<void> {} async beforeUpdate(): Promise<void> {} async updated(): Promise<void> {} async beforeDestroy(): Promise<void> {} async destroyed(): Promise<void> {} // nuxt独自の処理を定義 async fetch(_context: NuxtContext): Promise<void> {} async asyncData(_context: NuxtContext): Promise<void> {} } <file_sep>/src/common/util/exclusive-exec.ts const lockMap: Map<any, boolean> = new Map(); export async function exclusiveExecSingle( me: Object, func: () => Promise<void>, key?: any ): Promise<void> { if (key === undefined) key = func; if (!lockMap.get(key)) { lockMap.set(key, true); try { await func.call(me); } finally { lockMap.set(key, false); } } } <file_sep>/src/test/server/service/constraint.service.test.ts import "reflect-metadata"; import { container } from "~/src/common/inversify.config"; import { ConstraintService } from "~/src/server/service/constraint.service"; import { TableService } from "~/src/server/service/table.service"; import { TagEntity } from "~/src/common/entity/tag.entity"; const constraintService = container.get<ConstraintService>(ConstraintService); const tableService = container.get<TableService>(TableService); tableService.caches.tags = { a001: new TagEntity({ guid: "a001", name: "Tag-a001", parentGuid: null, updateSequenceNum: 0, }), a002: new TagEntity({ guid: "a002", name: "Tag-a002", parentGuid: "a001", updateSequenceNum: 0, }), a003: new TagEntity({ guid: "a003", name: "Tag-a003", parentGuid: "a001", updateSequenceNum: 0, }), a004: new TagEntity({ guid: "a004", name: "Tag-a004", parentGuid: "a003", updateSequenceNum: 0, }), }; describe("evalNumber", () => { type paramTypes = Parameters<ConstraintService["evalNumber"]>; type paramsType = { target: paramTypes[0]; query: paramTypes[1]; result: boolean; }; const myTest = (params: paramsType) => { test(JSON.stringify(params), () => { expect(constraintService["evalNumber"](params.target, params.query)).toBe( params.result ); }); }; myTest({ target: null, query: null, result: true }); myTest({ target: undefined, query: null, result: true }); myTest({ target: null, query: 1, result: false }); myTest({ target: 1, query: null, result: false }); myTest({ target: 1, query: 1, result: true }); myTest({ target: 1, query: 0, result: false }); myTest({ target: 1, query: 0, result: false }); myTest({ target: 1, query: {}, result: true }); myTest({ target: 1, query: { $eq: 1 }, result: true }); myTest({ target: 1, query: { $eq: 0 }, result: false }); myTest({ target: 1, query: { $ne: 0 }, result: true }); myTest({ target: 1, query: { $ne: 1 }, result: false }); myTest({ target: 1, query: { $gt: 0 }, result: true }); myTest({ target: 1, query: { $gt: 1 }, result: false }); myTest({ target: 1, query: { $gte: 1 }, result: true }); myTest({ target: 1, query: { $gte: 2 }, result: false }); myTest({ target: 1, query: { $lt: 2 }, result: true }); myTest({ target: 1, query: { $lt: 1 }, result: false }); myTest({ target: 1, query: { $lte: 1 }, result: true }); myTest({ target: 1, query: { $lte: 0 }, result: false }); myTest({ target: 1, query: { $between: [1, 2] }, result: true }); myTest({ target: 1, query: { $between: [2, 3] }, result: false }); myTest({ target: 1, query: { $notBetween: [2, 3] }, result: true }); myTest({ target: 1, query: { $notBetween: [1, 2] }, result: false }); myTest({ target: 1, query: { $in: [1, 2, 3] }, result: true }); myTest({ target: 1, query: { $in: [2, 3] }, result: false }); myTest({ target: 1, query: { $notIn: [2, 3] }, result: true }); myTest({ target: 1, query: { $notIn: [1, 2, 3] }, result: false }); myTest({ target: 1, query: { $not: { $eq: 0 } }, result: true }); myTest({ target: 1, query: { $not: { $eq: 1 } }, result: false }); }); describe("evalString", () => { type paramTypes = Parameters<ConstraintService["evalString"]>; type paramsType = { target: paramTypes[0]; query: paramTypes[1]; result: boolean; }; const myTest = (params: paramsType) => { test(JSON.stringify(params), () => { expect(constraintService["evalString"](params.target, params.query)).toBe( params.result ); }); }; myTest({ target: null, query: null, result: true }); myTest({ target: undefined, query: null, result: true }); myTest({ target: "", query: null, result: false }); myTest({ target: null, query: "", result: false }); myTest({ target: "", query: "", result: true }); myTest({ target: "a", query: "a", result: true }); myTest({ target: "a", query: "b", result: false }); myTest({ target: "a", query: ["a", "b"], result: true }); myTest({ target: "a", query: ["b", "c"], result: false }); myTest({ target: "a", query: [], result: false }); myTest({ target: "abcde", query: /abc/, result: true }); myTest({ target: "abcde", query: /ace/, result: false }); myTest({ target: "a", query: { $eq: "a" }, result: true }); myTest({ target: "a", query: { $eq: "b" }, result: false }); myTest({ target: "a", query: { $ne: "b" }, result: true }); myTest({ target: "a", query: { $ne: "a" }, result: false }); myTest({ target: "a", query: { $in: ["a", "b"] }, result: true }); myTest({ target: "a", query: { $in: ["b", "c"] }, result: false }); myTest({ target: "a", query: { $notIn: ["b", "c"] }, result: true }); myTest({ target: "a", query: { $notIn: ["a", "b"] }, result: false }); myTest({ target: "a", query: { $not: { $eq: "b" } }, result: true }); myTest({ target: "a", query: { $not: { $eq: "a" } }, result: false }); }); describe("evalArray", () => { type paramTypes = Parameters<ConstraintService["evalArray"]>; const myTest = ( target: paramTypes[0], query: paramTypes[1], result: boolean ) => { test(JSON.stringify({ target, query, result }), () => { expect(constraintService["evalArray"](target, query)).toBe(result); }); }; myTest(null, "a", false); myTest(undefined, "a", false); myTest(["a", "b"], "a", true); myTest(["b", "c"], "a", false); myTest([], "a", false); myTest(["a", "b", "c"], ["a", "b"], true); myTest(["a", "b", "c"], ["a"], true); myTest(["a", "b", "c"], [], true); myTest(["a", "b"], ["a", "b", "c"], false); myTest([], ["a"], false); myTest(["a", "b", "c"], { $in: ["a"] }, true); myTest(["a", "b", "c"], { $in: ["a", "d"] }, true); myTest(["a", "b", "c"], { $in: ["d", "e"] }, false); myTest(["a", "b", "c"], { $in: [] }, false); myTest(["a", "b", "c"], { $notIn: ["d", "e"] }, true); myTest(["a", "b", "c"], { $notIn: [] }, true); myTest(["a", "b", "c"], { $notIn: ["a"] }, false); myTest(["a", "b", "c"], { $notIn: ["a", "d"] }, false); myTest(["a", "b", "c"], { $all: ["a", "b"] }, true); myTest(["a", "b", "c"], { $all: [] }, true); myTest(["a", "b", "c"], { $all: ["a", "d"] }, false); myTest(["a", "b", "c"], { $notAll: ["a", "d"] }, true); myTest(["a", "b", "c"], { $notAll: ["a", "b"] }, false); myTest(["a", "b", "c"], { $notAll: [] }, false); }); describe("expandTagTree", () => { type paramTypes = Parameters<ConstraintService["expandTagTree"]>; const myTest = (target: paramTypes[0], result: string[]) => { test(JSON.stringify({ target, result }), () => { expect(constraintService["expandTagTree"](target)).toStrictEqual(result); }); }; myTest([], []); myTest(["Tag-a001"], ["Tag-a001"]); myTest( ["Tag-a001", "Tag-a002", "Tag-a003"], ["Tag-a001", "Tag-a002", "Tag-a003"] ); myTest({ $children: "Tag-a001" }, ["Tag-a002", "Tag-a003"]); myTest({ $descendants: "Tag-a001" }, ["Tag-a002", "Tag-a003", "Tag-a004"]); }); <file_sep>/src/client/plugins/vendor.ts import "moment/locale/ja"; <file_sep>/src/common/entity/profit-log.entity.ts import { BaseEntity, EntityParams } from "./base.entity"; export class ProfitLogEntity extends BaseEntity { FIELD_NAMES!: | "id" | "noteGuid" | "comment" | "profit" | BaseEntity["FIELD_NAMES2"]; static readonly params: EntityParams<ProfitLogEntity> = { name: "profitLog", primaryKey: "id", displayField: "comment", archive: false, default: { order: { updatedAt: "DESC" }, take: 2000, }, append: {}, columns: { id: { type: "integer", primary: true, generated: true, nullable: false, }, noteGuid: { type: "string", nullable: false, }, comment: { type: "text", nullable: true, }, profit: { type: "integer", nullable: false, }, }, }; id!: number; noteGuid!: string; comment!: string | null; profit!: number; } <file_sep>/src/server/script/database-sync.ts import "reflect-metadata"; import { container } from "~/src/common/inversify.config"; import { TableService } from "~/src/server/service/table.service"; const tableService = container.get<TableService>(TableService); (async () => { await tableService.initialize(false); console.log("Synchronize database started."); await tableService.sync(); console.log("Synchronize database finished."); })(); <file_sep>/src/common/inversify.config.ts import "reflect-metadata"; import { Container } from "inversify"; import { SYMBOL_TABLES, SYMBOL_TYPES } from "~/src/common/symbols"; import { BaseEntity } from "~/src/common/entity/base.entity"; import { AttendanceEntity } from "~/src/common/entity/attendance.entity"; import { ConstraintResultEntity } from "~/src/common/entity/constraint-result.entity"; import { LinkedNotebookEntity } from "~/src/common/entity/linked-notebook.entity"; import { NoteEntity } from "~/src/common/entity/note.entity"; import { NotebookEntity } from "~/src/common/entity/notebook.entity"; import { OptionEntity } from "~/src/common/entity/option.entity"; import { ProfitLogEntity } from "~/src/common/entity/profit-log.entity"; import { SavedSearchEntity } from "~/src/common/entity/saved-search.entity"; import { SessionEntity } from "~/src/common/entity/session.entity"; import { TagEntity } from "~/src/common/entity/tag.entity"; import { TimeLogEntity } from "~/src/common/entity/time-log.entity"; export const container = new Container(); // Entity系 container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(AttendanceEntity) .whenTargetNamed(SYMBOL_TABLES.attendance); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(ConstraintResultEntity) .whenTargetNamed(SYMBOL_TABLES.constraintResult); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(LinkedNotebookEntity) .whenTargetNamed(SYMBOL_TABLES.linkedNotebook); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(NoteEntity) .whenTargetNamed(SYMBOL_TABLES.note); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(NotebookEntity) .whenTargetNamed(SYMBOL_TABLES.notebook); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(OptionEntity) .whenTargetNamed(SYMBOL_TABLES.option); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(ProfitLogEntity) .whenTargetNamed(SYMBOL_TABLES.profitLog); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(SavedSearchEntity) .whenTargetNamed(SYMBOL_TABLES.savedSearch); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(SessionEntity) .whenTargetNamed(SYMBOL_TABLES.session); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(TagEntity) .whenTargetNamed(SYMBOL_TABLES.tag); container .bind<BaseEntity>(SYMBOL_TYPES.Entity) .toConstructor(TimeLogEntity) .whenTargetNamed(SYMBOL_TABLES.timeLog); <file_sep>/src/common/entity/tag.entity.ts import { BaseEvernoteEntity } from "./base-evernote.entity"; import { EntityParams, EntityToInterface } from "./base.entity"; export class TagEntity extends BaseEvernoteEntity { FIELD_NAMES!: "name" | "parentGuid" | BaseEvernoteEntity["FIELD_NAMES3"]; // eslint-disable-next-line no-useless-constructor constructor(data: EntityToInterface<TagEntity>) { super(data); } static readonly params: EntityParams<TagEntity> = { name: "tag", primaryKey: "guid", displayField: "name", archive: false, default: { order: { name: "ASC" }, take: 500, }, append: {}, columns: { guid: { type: "string", primary: true, nullable: false, }, name: { type: "string", nullable: false, }, parentGuid: { type: "string", nullable: true, }, updateSequenceNum: { type: "integer", nullable: false, }, }, }; name!: string; parentGuid!: string | null; } <file_sep>/src/common/entity/constraint-result.entity.ts import { BaseEntity, EntityParams } from "./base.entity"; export class ConstraintResultEntity extends BaseEntity { FIELD_NAMES!: "id" | "noteGuid" | "constraintId" | BaseEntity["FIELD_NAMES2"]; static readonly params: EntityParams<ConstraintResultEntity> = { name: "constraintResult", primaryKey: "id", displayField: "id", archive: false, default: { take: 500, }, append: {}, columns: { id: { type: "integer", primary: true, generated: true, nullable: false, }, noteGuid: { type: "string", nullable: false, }, constraintId: { type: "integer", nullable: false, }, }, }; id!: number; noteGuid!: string; constraintId!: number; } <file_sep>/nuxt.config.ts import { NuxtConfig } from "@nuxt/types"; import webpack from "webpack"; import { icons } from "./src/client/icons"; const webpackConfig: webpack.Configuration = { /* ** You can extend webpack config here */ // extend(config: any, ctx: any) {} plugins: [ // Ignore all locale files of moment.js new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), ], }; const conf: NuxtConfig = { ssr: false, dir: { assets: "src/client/assets", layouts: "src/client/layouts", middleware: "src/client/middleware", pages: "src/client/pages", static: "src/client/static", store: "src/client/store", }, /* ** Headers of the page */ head: { title: process.env.npm_package_name || "", meta: [ { charset: "utf-8" }, { name: "viewport", content: "width=device-width, initial-scale=1" }, { hid: "description", name: "description", content: process.env.npm_package_description || "", }, ], link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }], }, /* ** Customize the progress-bar color */ loading: { color: "#fff" }, /* ** Global CSS */ css: ["~/src/client/scss/style.scss"], /* ** Plugins to load before mounting the App */ plugins: [ "~/src/client/plugins/vendor", "~/src/client/plugins/logger", "~/src/client/plugins/filter", "~/src/client/plugins/service", "~/src/client/plugins/my-store", ], /* ** Nuxt.js dev-modules */ buildModules: [ "@nuxt/typescript-build", // Doc: https://github.com/nuxt-community/eslint-module "@nuxtjs/eslint-module", // Doc: https://github.com/nuxt-community/stylelint-module "@nuxtjs/stylelint-module", ], /* ** Nuxt.js modules */ modules: [ // Doc: https://bootstrap-vue.js.org ["bootstrap-vue/nuxt", { css: false }], "@nuxtjs/fontawesome", ], /* ** Axios module configuration ** See https://axios.nuxtjs.org/options */ axios: {}, fontawesome: { component: "fa", icons, }, /* ** Build configuration */ build: <any>{ babel: { compact: false, }, ...webpackConfig, }, telemetry: true, }; export default conf; <file_sep>/src/server/ddl/ddl_old.sql -- we don't know how to generate schema main (class Schema) :( create table archive_note ( archiveId INTEGER primary key autoincrement, guid VARCHAR(255), title VARCHAR(255) not null, content TEXT, contentHash TEXT not null, contentLength INTEGER not null, created BIGINT, updated BIGINT, deleted BIGINT, active TINYINT(1) not null, updateSequenceNum INTEGER not null, notebookGuid VARCHAR(255), tagGuids TEXT, resources TEXT, attributes__subjectDate BIGINT, attributes__latitude DOUBLE PRECISION, attributes__longitude DOUBLE PRECISION, attributes__altitude DOUBLE PRECISION, attributes__author VARCHAR(255), attributes__source VARCHAR(255), attributes__sourceURL VARCHAR(255), attributes__sourceApplication VARCHAR(255), attributes__shareDate BIGINT, attributes__reminderOrder BIGINT, attributes__reminderDoneTime BIGINT, attributes__reminderTime BIGINT, attributes__placeName VARCHAR(255), attributes__contentClass VARCHAR(255), attributes__applicationData TEXT, attributes__classifications TEXT, attributes__creatorId INTEGER, attributes__lastEditorId INTEGER, attributes__sharedWithBusiness TINYINT(1), attributes__conflictSourceNoteGuid VARCHAR(255), attributes__noteTitleQuality INTEGER, tagNames TEXT, sharedNotes TEXT, restrictions TEXT, limits TEXT, createdAt DATETIME not null, updatedAt DATETIME not null ); create index archive_notes_guid on archive_note (guid); create table attendance ( id INTEGER primary key autoincrement, personId INTEGER not null, year INTEGER not null, month INTEGER not null, day INTEGER not null, arrivalTime INTEGER, departureTime INTEGER, restTime INTEGER, remarks TEXT, createdAt DATETIME not null, updatedAt DATETIME not null ); create unique index attendances_person_id_year_month_day on attendance (personId, year, month, day); create table constraint_result ( id INTEGER primary key autoincrement, noteGuid VARCHAR(255) not null, constraintId INTEGER not null, createdAt DATETIME not null, updatedAt DATETIME not null ); create table linked_notebook ( guid VARCHAR(255) primary key, shareName VARCHAR(255), username VARCHAR(255), shareId VARCHAR(255), sharedNotebookGlobalId VARCHAR(255), uri VARCHAR(255), updateSequenceNum INTEGER not null, noteStoreUrl VARCHAR(255), webApiUrlPrefix VARCHAR(255), stack VARCHAR(255), businessId INTEGER, createdAt DATETIME not null, updatedAt DATETIME not null ); create table note ( guid VARCHAR(255) primary key, title VARCHAR(255) not null, content TEXT, contentHash TEXT not null, contentLength INTEGER not null, created BIGINT, updated BIGINT, deleted BIGINT, active TINYINT(1) not null, updateSequenceNum INTEGER not null, notebookGuid VARCHAR(255), tagGuids TEXT, resources TEXT, attributes__subjectDate BIGINT, attributes__latitude DOUBLE PRECISION, attributes__longitude DOUBLE PRECISION, attributes__altitude DOUBLE PRECISION, attributes__author VARCHAR(255), attributes__source VARCHAR(255), attributes__sourceURL VARCHAR(255), attributes__sourceApplication VARCHAR(255), attributes__shareDate BIGINT, attributes__reminderOrder BIGINT, attributes__reminderDoneTime BIGINT, attributes__reminderTime BIGINT, attributes__placeName VARCHAR(255), attributes__contentClass VARCHAR(255), attributes__applicationData TEXT, attributes__classifications TEXT, attributes__creatorId INTEGER, attributes__lastEditorId INTEGER, attributes__sharedWithBusiness TINYINT(1), attributes__conflictSourceNoteGuid VARCHAR(255), attributes__noteTitleQuality INTEGER, tagNames TEXT, sharedNotes TEXT, restrictions TEXT, limits TEXT, createdAt DATETIME not null, updatedAt DATETIME not null ); create table notebook ( guid VARCHAR(255) primary key, name VARCHAR(255) not null, updateSequenceNum INTEGER not null, defaultNotebook TINYINT(1) not null, serviceCreated BIGINT, serviceUpdated BIGINT, publishing TEXT, published TINYINT(1), stack VARCHAR(255), sharedNotebookIds TEXT, sharedNotebooks TEXT, businessNotebooks TEXT, contact TEXT, restrictions TEXT, recipientSettings TEXT, createdAt DATETIME not null, updatedAt DATETIME not null ); create table option ( key VARCHAR(255) primary key, value TEXT, createdAt DATETIME not null, updatedAt DATETIME not null ); create table profit_log ( id INTEGER primary key autoincrement, noteGuid VARCHAR(255) not null, comment TEXT, profit INTEGER not null, createdAt DATETIME not null, updatedAt DATETIME not null ); create table saved_search ( guid VARCHAR(255) primary key, name VARCHAR(255) not null, query VARCHAR(255), format INTEGER, updateSequenceNum INTEGER not null, scope TEXT, createdAt DATETIME not null, updatedAt DATETIME not null ); create table tag ( guid VARCHAR(255) primary key, name VARCHAR(255) not null, parentGuid VARCHAR(255), updateSequenceNum INTEGER not null, createdAt DATETIME not null, updatedAt DATETIME not null ); create table time_log ( id INTEGER primary key autoincrement, noteGuid VARCHAR(255) not null, comment TEXT, allDay TINYINT(1) not null, date BIGINT not null, personId INTEGER not null, spentTime INTEGER, createdAt DATETIME not null, updatedAt DATETIME not null ); <file_sep>/src/server/logger.ts import * as path from "path"; import * as log4js from "log4js"; import { appConfigLoader } from "~/src/common/util/app-config-loader"; log4js.configure(<any>{ appenders: { system: { category: "system", type: "dateFile", filename: path.join(__dirname, "../../logs/system"), pattern: "-yyyyMMdd.log", backups: 365, alwaysIncludePattern: true, }, access: { category: "access", type: "dateFile", filename: path.join(__dirname, "../../logs/access"), pattern: "-yyyyMMdd.log", backups: 365, alwaysIncludePattern: true, }, out: { type: "stdout", }, }, categories: { default: { appenders: ["system", "out"], level: appConfigLoader.app.logLevel, }, access: { appenders: ["access", "out"], level: appConfigLoader.app.logLevel, }, }, }); export const serverLogger = log4js.getLogger(); <file_sep>/src/server/table/note.table.ts import { injectable } from "inversify"; import _ from "lodash"; import { TableService } from "~/src/server/service/table.service"; import { IFindManyNoteEntityOptions, NoteEntity, } from "~/src/common/entity/note.entity"; import { BaseEvernoteTable } from "~/src/server/table/base-evernote.table"; import { logger } from "~/src/common/logger"; import { EvernoteClientService } from "~/src/server/service/evernote-client.service"; import { FindEntityWhereOptions } from "~/src/common/entity/base.entity"; @injectable() export class NoteTable extends BaseEvernoteTable<NoteEntity> { constructor( protected tableService: TableService, protected evernoteClientService: EvernoteClientService ) { super(); } async findAll(options: IFindManyNoteEntityOptions): Promise<NoteEntity[]> { const notes = await super.findAll(options); if (options.includeContent) { return notes; } else { return _.map(notes, (note: NoteEntity) => { note.hasContent = note.content != null; note.content = null; return note; }); } } protected prepareSaveEntity(entity: NoteEntity): any { _.each(entity.attributes || {}, (value, key) => { _.set(entity, `attributes__${key}`, value); }); delete entity.attributes; return super.prepareSaveEntity(entity); } protected prepareLoadEntity(data: Partial<NoteEntity>): NoteEntity { const entity = super.prepareLoadEntity(data); _(_.keys(entity)) .filter((key) => _.includes(key, "__")) .each((key) => { _.set(entity, key.replace("__", "."), _.get(entity, key)); _.unset(entity, key); }); return entity; } async loadRemote(guid: string): Promise<NoteEntity> { this.message("load", ["remote"], "note", true, { guid }); const note = await this.evernoteClientService.getNote(guid); const lastNote: NoteEntity = note; await this.save(note, true); await this.parseNote(lastNote); this.message("load", ["remote"], "note", false, { guid: lastNote.guid, title: lastNote.title, }); return lastNote; } async reParseNotes( query: FindEntityWhereOptions<NoteEntity> = {} ): Promise<void> { const options: IFindManyNoteEntityOptions = {}; options.where = query; options.take = -1; options.includeContent = true; const notes = await this.findAll(options); let i = 1; for (const note of notes) { if (i % 100 === 0) logger.info(`parsing notes... ${i} / ${notes.length}`); await this.parseNote(note); i++; } } private async parseNote(note: NoteEntity): Promise<void> { if (!note.content) return; this.message("parse", ["local"], "note", true, { guid: note.guid, title: note.title, }); let content: string = note.content; content = content.replace(/\r\n|\r|\n|<br\/>|<\/div>|<\/ul>|<\/li>/g, "<>"); const lines: string[] = []; for (const line of content.split("<>")) { lines.push(line.replace(/<[^>]*>/g, "")); } await this.tableService.timeLogTable.parse(note, lines); await this.tableService.profitLogTable.parse(note, lines); this.message("parse", ["local"], "note", false, { guid: note.guid, title: note.title, }); } } <file_sep>/src/server/service/evernote-client.service.ts import { injectable } from "inversify"; import Evernote from "evernote"; import { NoteEntity } from "~/src/common/entity/note.entity"; import { BaseServerService } from "~/src/server/service/base-server.service"; import { assertIsDefined } from "~/src/common/util/assert"; import { logger } from "~/src/common/logger"; import { appConfigLoader } from "~/src/common/util/app-config-loader"; @injectable() export class EvernoteClientService extends BaseServerService { SYNC_CHUNK_COUNT = 100; private _client: Evernote.Client | null = null; private get client(): Evernote.Client { assertIsDefined(this._client); return this._client; } initialize(): void { logger.info("Evernoteクライアントサービスの初期化を開始しました."); this._client = new Evernote.Client({ token: appConfigLoader.app.token, sandbox: appConfigLoader.app.sandbox, }); logger.info("Evernoteクライアントサービスの初期化を完了しました."); } async getUser(): Promise<Evernote.Types.User> { this.mes_(true, "user", {}); try { const user = await this.client.getUserStore().getUser(); this.mes_(false, "user", {}); return user; } catch (err) { this.mes_(false, "user", {}, err); throw err; } } async getSyncState(): Promise<Evernote.NoteStore.SyncState> { this.mes_(true, "syncState"); try { const syncState = await this.client.getNoteStore().getSyncState(); this.mes_(false, "syncState"); return syncState; } catch (err) { this.mes_(false, "syncState", err); throw err; } } async getFilteredSyncChunk( updateCount: number ): Promise<Evernote.NoteStore.SyncChunk> { const syncChunkFilter: Evernote.NoteStore.SyncChunkFilter = new Evernote.NoteStore.SyncChunkFilter(); syncChunkFilter.includeNotes = true; syncChunkFilter.includeNotebooks = true; syncChunkFilter.includeTags = true; syncChunkFilter.includeSearches = true; syncChunkFilter.includeExpunged = true; this.mes_(true, "syncChunk", { startUSN: updateCount }); try { const syncChunk = await this.client .getNoteStore() .getFilteredSyncChunk( updateCount, this.SYNC_CHUNK_COUNT, syncChunkFilter ); this.mes_(false, "syncChunk", { startUSN: updateCount }); return syncChunk; } catch (err) { this.mes_(false, "syncChunk", { startUSN: updateCount }, err); throw err; } } async getNote(guid: string): Promise<NoteEntity> { this.mes_(true, "note", { guid }); try { const note = await this.client .getNoteStore() .getNote(guid, true, false, false, false); return new NoteEntity(note); } catch (err) { this.mes_(false, "note", { guid }, err); throw err; } } private mes_( start: boolean, name: string, dispData: Object = {}, err: any = null ) { logger.debug( `Load remote ${name} was ${ start ? "started" : err ? "failed" : "succeed" }. ${JSON.stringify(dispData)}` ); } } <file_sep>/src/server/service/sync.service.ts import { injectable } from "inversify"; import Evernote from "evernote"; import _ from "lodash"; import { LinkedNotebookEntity } from "~/src/common/entity/linked-notebook.entity"; import { TagEntity } from "~/src/common/entity/tag.entity"; import { NoteEntity } from "~/src/common/entity/note.entity"; import { NotebookEntity } from "~/src/common/entity/notebook.entity"; import { SavedSearchEntity } from "~/src/common/entity/saved-search.entity"; import { BaseServerService } from "~/src/server/service/base-server.service"; import { TableService } from "~/src/server/service/table.service"; import { EvernoteClientService } from "~/src/server/service/evernote-client.service"; import { ConstraintService } from "~/src/server/service/constraint.service"; import { SocketIoService } from "~/src/server/service/socket-io.service"; import { logger } from "~/src/common/logger"; import { assertIsDefined } from "~/src/common/util/assert"; @injectable() export class SyncService extends BaseServerService { private static startInterval = 10 * 1000; private static increaseInterval = 1.5; private static maxInterval = 5 * 60 * 1000; updateCount: number = 0; private nextLockPromise: Promise<void> = Promise.resolve(); private lockResolves: Array<() => void>; private timer: any; private interval: number = SyncService.startInterval; constructor( protected tableService: TableService, protected evernoteClientService: EvernoteClientService, protected socketIoService: SocketIoService, protected constraintService: ConstraintService ) { super(); this.lockResolves = []; } get Class(): typeof SyncService { return <typeof SyncService>this.constructor; } async lock(): Promise<void> { const next = this.nextLockPromise; this.nextLockPromise = new Promise<void>((resolve) => { this.lockResolves.push(resolve); }); logger.trace(`sync lock count=${this.lockResolves.length}`); if (this.lockResolves.length >= 2) return next; } async unlock(): Promise<void> { if (this.lockResolves.length < 1) throw new Error("Unlock need to lock first."); logger.trace(`sync unlock count=${this.lockResolves.length}`); const resolve = this.lockResolves.shift(); assertIsDefined(resolve); resolve(); } async sync(manual: boolean): Promise<void> { clearTimeout(this.timer); await this.lock(); let updated: boolean = false; try { let localSyncState: Evernote.NoteStore.SyncState = await this.tableService.optionTable.findValueByKey( "syncState" ); if (!localSyncState) localSyncState = { updateCount: 0 }; const remoteSyncState = await this.evernoteClientService.getSyncState(); logger.debug( `Evernoteサーバ同期の状態を確認しました. localUSN=${localSyncState.updateCount} remoteUSN=${remoteSyncState.updateCount}` ); if ( (localSyncState.updateCount ?? 0) < (remoteSyncState.updateCount ?? 0) ) { const eventHash: { [event: string]: string[] } = {}; // Sync process logger.info( `Evernoteサーバ同期を開始します. localUSN=${localSyncState.updateCount} remoteUSN=${remoteSyncState.updateCount}` ); while ( (localSyncState.updateCount ?? 0) < (remoteSyncState.updateCount ?? 0) ) { await this.getSyncChunk(localSyncState, eventHash); } await this.tableService.optionTable.saveValueByKey( "syncState", remoteSyncState ); logger.info( `Evernoteサーバ同期を完了しました. localUSN=${localSyncState.updateCount} remoteUSN=${remoteSyncState.updateCount}` ); assertIsDefined(localSyncState.updateCount); this.updateCount = localSyncState.updateCount; this.socketIoService.emitAll("sync::updateCount", this.updateCount); if (_.has(eventHash, ["notebook::update", "notebook::delete"])) await this.tableService.reloadCache("notebook"); if (_.has(eventHash, ["tag:update", "tag::delete"])) await this.tableService.reloadCache("tag"); if (eventHash["note::update"]) { if ((await this.tableService.constraintResultTable.count()) > 0) this.socketIoService.emitAll("constraint::notify"); } if (Object.keys(eventHash).length > 0) { this.socketIoService.emitAll("sync::update", eventHash); updated = true; } } } finally { await this.unlock(); this.interval = manual || updated ? this.Class.startInterval : Math.min( Math.round(this.interval * this.Class.increaseInterval), this.Class.maxInterval ); this.timer = setTimeout( () => this.sync(false).catch((err) => logger.error(err)), this.interval ); logger.debug( `次回のEvernoteサーバ同期は ${this.interval} ミリ秒後に実施されます.` ); await this.autoGetNoteContent(this.interval); } } private async getSyncChunk( localSyncState: Evernote.NoteStore.SyncState, eventHash: { [event: string]: string[] } ): Promise<void> { logger.info( `EvernoteサーバからSyncChunk取得を開始します. startUSN=${localSyncState.updateCount}` ); assertIsDefined(localSyncState.updateCount); const lastSyncChunk: Evernote.NoteStore.SyncChunk = await this.evernoteClientService.getFilteredSyncChunk( localSyncState.updateCount ); await this.tableService.noteTable.saveAll( _.map(lastSyncChunk.notes, (note) => new NoteEntity(note)) ); await this.tableService.noteTable.delete(lastSyncChunk.expungedNotes ?? []); await this.tableService.notebookTable.saveAll( _.map(lastSyncChunk.notebooks, (notebook) => new NotebookEntity(notebook)) ); await this.tableService.notebookTable.delete( lastSyncChunk.expungedNotebooks ?? [] ); await this.tableService.tagTable.saveAll( _.map(lastSyncChunk.tags, (tag) => new TagEntity(<any>tag)) ); await this.tableService.tagTable.delete(lastSyncChunk.expungedTags ?? []); await this.tableService.savedSearchTable.saveAll( _.map(lastSyncChunk.searches, (search) => new SavedSearchEntity(search)) ); await this.tableService.savedSearchTable.delete( lastSyncChunk.expungedSearches ?? [] ); await this.tableService.linkedNotebookTable.saveAll( _.map( lastSyncChunk.linkedNotebooks, (linkedNotebook) => new LinkedNotebookEntity(linkedNotebook) ) ); await this.tableService.linkedNotebookTable.delete( lastSyncChunk.expungedLinkedNotebooks ?? [] ); const mergeGuids = ( updateEventHash: { [event: string]: string[] }, event: string, guids: string[] | undefined ) => { if (!guids || guids.length === 0) return; updateEventHash[event] = updateEventHash[event] ? updateEventHash[event].concat(guids) : guids; }; const mergeGuidsUpdate = ( updateEventHash: { [event: string]: string[] }, event: string, datas: { guid?: string }[] | undefined ) => { if (!datas) return; const guids: string[] = []; datas.forEach((data) => { if (data.guid) guids.push(data.guid); }); mergeGuids(updateEventHash, event, guids); }; mergeGuidsUpdate(eventHash, "note::update", lastSyncChunk.notes); mergeGuids(eventHash, "note::delete", lastSyncChunk.expungedNotes); mergeGuidsUpdate(eventHash, "notebook::update", lastSyncChunk.notebooks); mergeGuids(eventHash, "notebook::delete", lastSyncChunk.expungedNotebooks); mergeGuidsUpdate(eventHash, "tag::update", lastSyncChunk.tags); mergeGuids(eventHash, "tag::delete", lastSyncChunk.expungedTags); mergeGuidsUpdate(eventHash, "search::update", lastSyncChunk.searches); mergeGuids(eventHash, "search::delete", lastSyncChunk.expungedSearches); mergeGuidsUpdate( eventHash, "linkedNotebook::update", lastSyncChunk.linkedNotebooks ); mergeGuids( eventHash, "linkedNotebook::delete", lastSyncChunk.expungedLinkedNotebooks ); if ((lastSyncChunk.notes?.length ?? 0) > 0) for (const note of lastSyncChunk.notes ?? []) await this.constraintService.checkOne(new NoteEntity(note)); if ((lastSyncChunk.expungedNotes?.length ?? 0) > 0) for (const guid of lastSyncChunk.expungedNotes ?? []) await this.constraintService.removeOne(guid); localSyncState.updateCount = lastSyncChunk.chunkHighUSN; await this.tableService.optionTable.saveValueByKey( "syncState", localSyncState ); logger.info( `EvernoteサーバからSyncChunk取得を完了しました. endUSN=${localSyncState.updateCount}` ); } private async autoGetNoteContent(interval: number): Promise<void> { await this.lock(); try { const numNote: number = Math.ceil(interval / (60 * 1000)); logger.debug( `自動ノート内容取得処理の状態を確認します. 取得するノートの最大数: ${numNote}.` ); const notes = await this.tableService.noteTable.findAll({ where: { content: null }, order: { updated: "DESC" }, take: numNote, }); if (notes.length > 0) { logger.info( `自動ノート内容取得処理を開始しました. 取得するノートの数: ${notes.length}.` ); for (const note of notes) { await this.tableService.noteTable.loadRemote(note.guid); } logger.info(`自動ノート内容取得処理を完了しました.`); } } finally { await this.unlock(); } } } <file_sep>/src/server/script/check-constraint.ts import "reflect-metadata"; import { container } from "~/src/common/inversify.config"; import { TableService } from "~/src/server/service/table.service"; import { ConstraintService } from "~/src/server/service/constraint.service"; const tableService = container.get<TableService>(TableService); const constraintService = container.get<ConstraintService>(ConstraintService); (async () => { await tableService.initialize(); console.log("Check constraint started."); await constraintService.checkAll(); console.log("Check constraint finished."); })();
b6bb8c62ae459e9de65a0907c17af93e9253bf19
[ "JavaScript", "SQL", "TypeScript" ]
91
TypeScript
nashika/evernote-tasklog
66a64d38720b25ffc8ef3cc273ffe5671cf8ade5
85da6ee1ccc1cacd3baf8c1dcc5d9ad51a7c72b5
refs/heads/master
<repo_name>Threedexter/ImprovisedSoundScape<file_sep>/ImprovisedSoundScape/Assets/Scripts/AreaTrigger.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AreaTrigger : MonoBehaviour { public ReverbScript reverbHandler; public ReverbScript.AreaTypes reverbType; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } private void OnTriggerEnter(Collider other) { if(other.tag == "Player") { reverbHandler.ChangeReverb(reverbType); } if(other.tag == "Ball") { BallScript ball = other.gameObject.GetComponent<BallScript>(); ball.setType(reverbType); } } } <file_sep>/ImprovisedSoundScape/Assets/Scripts/BallScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallScript : MonoBehaviour { enum ClipTypes { Bounce = 0, Dog, Cat, Bell }; public ReverbScript.AreaTypes type; public AudioClip[] clips; public AudioSource source; public PlayerControl player; private bool playAudio = true; private void Update() { if(this.GetComponent<Rigidbody>().velocity.magnitude < 1) { playAudio = false; } } private void OnCollisionEnter(Collision other) { if(other.gameObject.tag == "Ground" && playAudio) { float distvolume = 1 / (Mathf.Clamp(Vector3.Distance(this.transform.position, GameObject.FindGameObjectWithTag("Player").transform.position), 0, 20) / 20); float speedVolume = Mathf.Clamp(this.GetComponent<Rigidbody>().velocity.y, 0, 10)/10; Debug.Log("Volume:" + distvolume * speedVolume); source.volume = distvolume * speedVolume; switch(type) { case ReverbScript.AreaTypes.SmallInside: { source.PlayOneShot(clips[(int)ClipTypes.Dog]); break; } case ReverbScript.AreaTypes.LargeInside: { source.PlayOneShot(clips[(int)ClipTypes.Cat]); break; } case ReverbScript.AreaTypes.Outside: { source.PlayOneShot(clips[(int)ClipTypes.Bell]); break; } case ReverbScript.AreaTypes.Cathedral: { source.PlayOneShot(clips[(int)ClipTypes.Bounce]); break; } } } } public void setType(ReverbScript.AreaTypes areaType) { type = areaType; } } <file_sep>/ImprovisedSoundScape/Assets/Scripts/PlayerControl.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerControl : MonoBehaviour { public GameObject Player; public Camera cam; public AudioSource source; public GameObject ball; public ReverbScript.AreaTypes type; [Range(1.0f, 10.0f)] public float speedfactor; bool hasthrown = false; void Start() { if (Player == null) { Player = GameObject.Find("Player"); if (Player == null) { Debug.Log("Player is null"); } } } void Update() { HandleMovement(); HandleInteraction(); } void HandleMovement() { float ForBackAxis = Input.GetAxis("Forward/Backward"); float StrafeAxis = Input.GetAxis("Strafe"); Vector3 camVectorFwdLocked = new Vector3(cam.transform.forward.x, 0, cam.transform.forward.z); Vector3 camVectorRgtLocked = new Vector3(cam.transform.right.x, 0, cam.transform.right.z); if (Mathf.Abs(Input.GetAxis("Forward/Backward")) > 0) { transform.position = transform.position + (camVectorFwdLocked * Input.GetAxis("Forward/Backward") * (speedfactor / 10)); } if (Mathf.Abs(Input.GetAxis("Strafe")) > 0) { transform.position = transform.position + (camVectorRgtLocked * Input.GetAxis("Strafe") * (speedfactor / 10)); } } void HandleInteraction() { if (Input.GetButtonDown("Throw") && !hasthrown) { Vector3 camVectorFwdLocked = new Vector3(cam.transform.forward.x, cam.transform.forward.y, cam.transform.forward.z); Player.GetComponent<Rigidbody>().isKinematic = true; hasthrown = true; GameObject ballObject = Instantiate(ball,cam.transform.position + (camVectorFwdLocked * 2), cam.transform.rotation); ballObject.GetComponent<BallScript>().setType(type); ballObject.GetComponent<Rigidbody>().AddForce(camVectorFwdLocked * 2,ForceMode.Impulse); Destroy(ballObject, 20); } if (Input.GetButtonUp("Throw") && hasthrown) { Player.GetComponent<Rigidbody>().isKinematic = false; hasthrown = false; } } } <file_sep>/README.md # ImprovisedSoundScape ImproVive <file_sep>/ImprovisedSoundScape/Assets/Scripts/CameraControl.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraControl : MonoBehaviour { public Camera playerCamera; // Use this for initialization void Start() { Cursor.lockState = CursorLockMode.Locked; if (GetComponent<Camera>() == null) { GameObject.Find("Main Camera"); } } // Update is called once per frame void Update() { ControlCamera(); } private void ControlCamera() { float MouseX = Input.GetAxisRaw("Mouse X"); float MouseY = Input.GetAxisRaw("Mouse Y"); MouseY = clampYAxis(MouseY); playerCamera.transform.eulerAngles += new Vector3(-MouseY, MouseX); } float clampYAxis(float mouseval) { if (playerCamera.transform.eulerAngles.x > 85 && playerCamera.transform.eulerAngles.x < 90) { playerCamera.transform.eulerAngles = new Vector3(85, playerCamera.transform.eulerAngles.y); mouseval = 0; } else if (playerCamera.transform.eulerAngles.x < 275 && playerCamera.transform.eulerAngles.x > 270) { playerCamera.transform.eulerAngles = new Vector3(275, playerCamera.transform.eulerAngles.y); mouseval = 0; } return mouseval; } } <file_sep>/ImprovisedSoundScape/Assets/Scripts/ReverbScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; public class ReverbScript : MonoBehaviour { public enum AreaTypes { SmallInside, LargeInside, Outside, Cathedral }; public GameObject[] Areas; public GameObject Player; // Use this for initialization void Start() { } // Update is called once per frame void Update() { } public void ChangeReverb(AreaTypes type) { Player.GetComponent<PlayerControl>().type = type; } }
a5b4809857653f2669e630f0a85224f62c4914cc
[ "Markdown", "C#" ]
6
C#
Threedexter/ImprovisedSoundScape
59560d8f21c7d0e24f818f98dbdd58704a771485
343e6af1b6914996f0845891828a479995cf8c49
refs/heads/master
<repo_name>FransScholten/rails-mister-cocktail<file_sep>/app/controllers/doses_controller.rb class DosesController < ApplicationController before_action :set_doses, only: %i[ show edit update destroy ] def new @doses = Dose.new end def edit end def create @dose = Dose.new(dose_params) if @dose.save redirect_to doses_path(@doses) else render :new end end private def doses_params params.require(:cocktail).permit(:description) end end def set_dose @dose = Dose.find(params[:id]) end
c3bdb212d7f0d73ceee4b34823e321a4e8c9e9f4
[ "Ruby" ]
1
Ruby
FransScholten/rails-mister-cocktail
99e46d9c855e647fc01c15e2032b811cb53a806f
047b6f5c771c5f784fe06dd7161e3b47040469a4
refs/heads/main
<repo_name>Hussain-786/OpenCV-Motion-Detection<file_sep>/MotionDetection.py import cv2 cap = cv2.VideoCapture('vtest.avi') while cap.isOpened(): ret, frame1 = cap.read () ret, frame2 = cap.read () diff = cv2.absdiff(frame1, frame2) imgray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(imgray, (5,5), 0) _,thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY) dilated = cv2.dilate(thresh, None, iterations=3) contours,_ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: x,y,w,h = cv2.boundingRect(contour) if cv2.contourArea(contour)<700: continue cv2.rectangle(frame1, (x, y), (x+w, y+h), (0,255,0), 2) cv2.putText(frame1,"status : {}".format("movement"), (10,20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,255), 3) #cv2.drawContours(frame1, contours, -1, (0, 255, 0), 2) if cv2.waitKey(1) == ord('d'): break cv2.imshow ( 'vtest.avi', frame1 ) #frame1 = frame2 #ret, frame2 = cap.read() cv2.destroyAllWindows() cap.release()
a29a7b4080e085b82ab05adab46cf79702adcef8
[ "Python" ]
1
Python
Hussain-786/OpenCV-Motion-Detection
021ce0971c8bd39e097ede469d842e5f28a741f8
e60302cdad7037ca26808782450fcaa3d7e0a0f6
refs/heads/master
<repo_name>rickwwmp/github.repository<file_sep>/README.md # github.repository guthub first repository 20161001 <file_sep>/gitProjectDemo/src/com/test/common/TestUtils.java package com.test.common; public class TestUtils { public static void main(String[] args) { System.out.println("hasss"); } }
44118afc4f1cae5a94869aa352bfebf909cb6d6e
[ "Markdown", "Java" ]
2
Markdown
rickwwmp/github.repository
78bab38c03135c412e0bc44e1286cdcaa99d70b6
f034374c915ebba7cd493f6247b01a721fa87b2a
refs/heads/master
<file_sep>package com.champlain.androiddev.a1631152.powerlist; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import com.champlain.androiddev.a1631152.powerlist.DB.DBSQLiteManager; import com.champlain.androiddev.a1631152.powerlist.Models.Task; import java.util.ArrayList; public class edit_tasks extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_tasks); final Intent intent = getIntent(); final int userId = intent.getIntExtra("id", 0); Button saveEdit = findViewById(R.id.saveBtn); Button backEdit = findViewById(R.id.backBtn); backEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(); setResult(3, i); finish(); } }); EditText t1 = findViewById(R.id.Task1); EditText t2 = findViewById(R.id.Task2); EditText t3 = findViewById(R.id.Task3); EditText t4 = findViewById(R.id.Task4); EditText t5 = findViewById(R.id.Task5); CheckBox c1 = findViewById(R.id.Check1); CheckBox c2 = findViewById(R.id.Check2); CheckBox c3 = findViewById(R.id.Check3); CheckBox c4 = findViewById(R.id.Check4); CheckBox c5 = findViewById(R.id.Check5); c1.setChecked(sTb(intent.getStringExtra("ch1"))); c2.setChecked(sTb(intent.getStringExtra("ch2"))); c3.setChecked(sTb(intent.getStringExtra("ch3"))); c4.setChecked(sTb(intent.getStringExtra("ch4"))); c5.setChecked(sTb(intent.getStringExtra("ch5"))); t1.setText(intent.getStringExtra("d1")); t2.setText(intent.getStringExtra("d2")); t3.setText(intent.getStringExtra("d3")); t4.setText(intent.getStringExtra("d4")); t5.setText(intent.getStringExtra("d5")); saveEdit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int uId = intent.getIntExtra("uId", 0); int dId = intent.getIntExtra("dId", 0); EditText t1 = findViewById(R.id.Task1); EditText t2 = findViewById(R.id.Task2); EditText t3 = findViewById(R.id.Task3); EditText t4 = findViewById(R.id.Task4); EditText t5 = findViewById(R.id.Task5); CheckBox c1 = findViewById(R.id.Check1); CheckBox c2 = findViewById(R.id.Check2); CheckBox c3 = findViewById(R.id.Check3); CheckBox c4 = findViewById(R.id.Check4); CheckBox c5 = findViewById(R.id.Check5); String d1 = t1.getText().toString(); String d2 = t2.getText().toString(); String d3 = t3.getText().toString(); String d4 = t4.getText().toString(); String d5 = t5.getText().toString(); boolean complete = false; if(c1.isChecked() && c2.isChecked() && c3.isChecked() && c4.isChecked() && c5.isChecked()) { complete = true; } updateTasks(uId, dId, c1.isChecked(), c2.isChecked(), c3.isChecked(), c4.isChecked(), c5.isChecked(), d1, d2, d3, d4, d5,complete); Intent i = new Intent(); i.putExtra("comp", complete+""); i.putExtra("id", uId+""); setResult(2, i); finish(); } }); } private boolean sTb(String sb) { String t = "true"; if(sb.equals(t)) { return true; } else { return false; } } public void updateTasks(int userId, int dateId, boolean c1, boolean c2, boolean c3, boolean c4, boolean c5, String d1, String d2, String d3, String d4, String d5, Boolean complete) { DBSQLiteManager manager; manager = new DBSQLiteManager(this); manager.updateTasks(userId, dateId, c1, c2, c3, c4, c5, d1, d2, d3, d4, d5, complete); refreshT(userId); } public ArrayList<Task> refreshT(int userId) { ArrayList<Task> tasks; DBSQLiteManager manager; manager = new DBSQLiteManager(this); manager.getTasksWithId(userId); tasks = manager.getTask_list(); return tasks; } } <file_sep>package com.champlain.androiddev.a1631152.powerlist; import android.content.Intent; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.champlain.androiddev.a1631152.powerlist.Models.User; import com.champlain.androiddev.a1631152.powerlist.DB.DBSQLiteManager; import java.util.ArrayList; public class Create_Account extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create__account); ActionBar actionBar = getSupportActionBar(); if(actionBar!= null) { actionBar.setDisplayHomeAsUpEnabled(true); } Button bAdd = findViewById(R.id.create_account); bAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ArrayList<User> users = refresh(); EditText name = findViewById(R.id.name); EditText email = findViewById(R.id.username); EditText password = findViewById(R.id.password); EditText pass_confirm = findViewById(R.id.pass_confirm); String name1 = name.getText().toString(); String email1 = email.getText().toString(); String password1 = password.getText().toString(); String pass_confirm1 = pass_confirm.getText().toString(); if(password1.equals(pass_confirm1) && !name1.isEmpty() && !email1.isEmpty()) { boolean realUser = false; for(int x = 0; x<users.size(); x++) { User u = users.get(x); if(u.getEmail().equals(email1)) { realUser = true; } } if(!realUser) { User u = new User(1, email.getText().toString(), password.getText().toString(), name.getText().toString()); addUser(u); finish(); } else { Toast toast = Toast.makeText(getApplicationContext(), "Email already in use", Toast.LENGTH_LONG); toast.show(); } } else { Toast toast = Toast.makeText(getApplicationContext(), "Passwords don't match!", Toast.LENGTH_LONG); toast.show(); } } }); } private User addUser(User c) { DBSQLiteManager dbslm = new DBSQLiteManager(this); User createdUser = dbslm.addUser(c); Toast toast = Toast.makeText(getApplicationContext(), "New User Created", Toast.LENGTH_SHORT); toast.show(); return createdUser; } public ArrayList<User> refresh() { ArrayList<User> users; DBSQLiteManager manager; manager = new DBSQLiteManager(this); manager.getUsers(); users = manager.getUser_list(); return users; } } <file_sep>package com.champlain.androiddev.a1631152.powerlist.Models; public class User { public static final String TABLE_NAME = "users"; public static final String COLUMN_ID = "user_id"; public static final String COLUMN_EMAIL = "email"; public static final String COLUMN_PASSWORD = "<PASSWORD>"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_LAST_COMPLETED = "last_completed"; public static final String COLUMN_STREAK = "streak"; public static final String COLUMN_HIGNSCORE = "highscore"; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_EMAIL + " TEXT, " + COLUMN_PASSWORD + " TEXT, " + COLUMN_NAME + " TEXT," + COLUMN_LAST_COMPLETED + " INT, " + COLUMN_STREAK + " INT, " + COLUMN_HIGNSCORE + " INT)"; private int id; private String email; private String password; private String name; private int last_completed; private int streak; private int highcscore; public User() {} public User(int id, String email, String password, String name){ this.id = id; this.email = email; this.password = <PASSWORD>; this.name = name; this.last_completed = 0; this.streak = 0; this. highcscore = 0; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLast_completed() { return last_completed; } public void setLast_completed(int last_completed) { this.last_completed = last_completed; } public int getStreak() { return streak; } public void setStreak(int streak) { this.streak = streak; } public int getHighcscore() { return highcscore; } public void setHighcscore(int highcscore) { this.highcscore = highcscore; } public boolean search(String email) { if(this.getEmail().equals(email)) { return true; } else { return false; } } }
8b4ed75aeb8a28c7ffcb8da43d7ae8af7b239c98
[ "Java" ]
3
Java
Emmykinzy/PowerList
90ce6bc3fa7c8b657c5dbbc1cb717c2b641c177f
912b834574d247158fad43dcf3c84d867f0de580
refs/heads/master
<file_sep># Custom scroll This is a cool view, allowing user to scroll down and see more content only when they unlock the buttons. ## Getting Started Clone the proj and let it fly ### Installing Clone Open with Xcode Run Enjoy ![alt-text](https://github.com/sashamyshkina/scroll_custom/blob/master/Screen%20Recording%202020-05-03%20at%2016.58.18.gif) <file_sep>// // ViewController.swift // scroll // // Created by <NAME> on 01.05.2020. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { private let screenHeight: CGFloat = UIScreen.main.bounds.height private var bottomConstraint: NSLayoutConstraint! private var contentOpenedCount = 0 { didSet { if contentOpenedCount == 2 { self.button.setTitle("Finish", for: UIControl.State.normal) } } } private let button: UIButton = { let b = UIButton() b.backgroundColor = .clear b.setTitle("Next", for: .normal) b.setTitleColor(.black, for: .normal) b.titleLabel?.textColor = .black b.titleLabel?.font = UIFont.systemFont(ofSize: 15) b.layer.cornerRadius = 21.5 b.layer.borderWidth = 1 b.layer.borderColor = UIColor.black.cgColor b.layer.masksToBounds = true b.addTarget(self, action: #selector(buttonPressed), for: UIControl.Event.touchUpInside) b.translatesAutoresizingMaskIntoConstraints = false return b }() private let firstView: UIView = { let v = UIView() v.backgroundColor = .white v.translatesAutoresizingMaskIntoConstraints = false return v }() private let secondView: UIView = { let v = UIView() v.backgroundColor = .lightGray v.translatesAutoresizingMaskIntoConstraints = false return v }() private let thirdView: UIView = { let v = UIView() v.backgroundColor = .gray v.translatesAutoresizingMaskIntoConstraints = false return v }() private let scrollView: UIScrollView = { let v = UIScrollView() v.translatesAutoresizingMaskIntoConstraints = false v.backgroundColor = .cyan return v }() override func viewDidLoad() { super.viewDidLoad() print("screenHeight:",screenHeight) scrollView.delegate = self configureScrollView() configureFirstPage() } @objc fileprivate func buttonPressed() { if contentOpenedCount == 0 { configureSecondPage() contentOpenedCount += 1 let _ = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { (t) in self.scrollView.scrollToView(view: self.secondView, animated: true) } } else if contentOpenedCount == 1 { configureThirdPage() contentOpenedCount += 1 let _ = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: false) { (t) in self.scrollView.scrollToView(view: self.thirdView, animated: true) } } } fileprivate func configureScrollView() { self.view.addSubview(scrollView) scrollView.bounces = false scrollView.alwaysBounceVertical = false scrollView.showsVerticalScrollIndicator = false scrollView.contentInsetAdjustmentBehavior = .never scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 0).isActive = true scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 0).isActive = true scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true } fileprivate func configureButton(b: UIButton) { b.bottomAnchor.constraint(equalTo: b.superview!.bottomAnchor, constant: -40).isActive = true b.widthAnchor.constraint(equalToConstant: 170).isActive = true b.heightAnchor.constraint(equalToConstant: 43).isActive = true b.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true } fileprivate func configureFirstPage() { scrollView.addSubview(firstView) firstView.addSubview(button) NSLayoutConstraint.activate([ firstView.heightAnchor.constraint(equalTo: self.view.heightAnchor), firstView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), firstView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), firstView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0), firstView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor) ]) configureButton(b: button) } fileprivate func configureSecondPage() { scrollView.addSubview(secondView) bottomConstraint = secondView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0) NSLayoutConstraint.activate([ secondView.heightAnchor.constraint(equalToConstant: screenHeight), secondView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), secondView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), secondView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), secondView.topAnchor.constraint(equalTo: firstView.bottomAnchor, constant: 0), bottomConstraint ]) secondView.addSubview(button) configureButton(b: button) } fileprivate func configureThirdPage() { bottomConstraint.isActive = false scrollView.addSubview(thirdView) NSLayoutConstraint.activate([ thirdView.heightAnchor.constraint(equalTo: self.view.heightAnchor), thirdView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), thirdView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), thirdView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), thirdView.topAnchor.constraint(equalTo: secondView.bottomAnchor, constant: 0), thirdView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0) ]) thirdView.addSubview(button) configureButton(b: button) } } extension UIScrollView { func scrollToView(view:UIView, animated: Bool) { if let origin = view.superview { let childStartPoint = origin.convert(view.frame.origin, to: self) self.scrollRectToVisible(CGRect(x:0, y:childStartPoint.y,width: 1,height: self.frame.height), animated: animated) } } // Bonus: Scroll to top func scrollToTop(animated: Bool) { let topOffset = CGPoint(x: 0, y: -contentInset.top) setContentOffset(topOffset, animated: animated) } // Bonus: Scroll to bottom func scrollToBottom() { let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom) if(bottomOffset.y > 0) { setContentOffset(bottomOffset, animated: true) } } }
ebc7f337056a382e3321392500f9765d26bda65e
[ "Markdown", "Swift" ]
2
Markdown
sashamyshkina/scroll_custom
f8e45c24183fbbaf57c33dab01416ab1515324db
18046ca15d2a1dfeec19e839c64bce14d2413ef1
refs/heads/master
<repo_name>michaelspiss/charityrun<file_sep>/public/js/install_map.js var map = AmCharts.makeChart( "map", { "type": "map", "theme": "light", "panEventsEnabled": true, "projection": "equirectangular", "zoomOnDoubleClick": false, "dataProvider": { "map": "worldLow", "getAreasFromMap": true }, "areasSettings": { "autoZoom": false, "color": "#CDCDCD", "colorSolid": "#5EB7DE", "selectedColor": "#5EB7DE", "outlineColor": "#666666", "rollOverColor": "#88CAE7", "rollOverOutlineColor": "#FFFFFF", "selectable": true }, "linesSettings": { "arc": -0.7, // this makes lines curved. Use value from -1 to 1 "color": "#000000", "alpha": 0.4, "thickness": 2, "bringForwardOnHover": false, "arrowAlpha": 1, "arrowSize": 4, "arrow": "middle" }, "listeners": [ { "event": "clickMapObject", "method": function( event ) { var info = event.chart.getDevInfo(); if(emptyString(document.getElementById('latitude_from').value)) { document.getElementById('latitude_from').value = info.latitude; document.getElementById('longitude_from').value = info.longitude; } else { document.getElementById('latitude_to').value = info.latitude; document.getElementById('longitude_to').value = info.longitude; } } } ] } );<file_sep>/public/js/sidebar.js // get elements sidebar = document.getElementsByClassName('sidebar')[0]; background = document.getElementsByClassName('sidebar-background')[0]; // the button to trigger the sidebar more = document.getElementById('more'); // hide sidebar by clicking the background background.addEventListener("click", function (e) { // prevent the non-js fallback (redirect to /manage/{class}) e.preventDefault(); sidebar.classList.add("sidebar-hide"); background.classList.add("sidebar-hide"); setTimeout(function () { background.classList.add("hidden"); }, 300); }); // open sidebar by clicking the "more" button more.addEventListener("click", function (e) { // prevent the non-js fallback (redirect to /manage/{class}/more) e.preventDefault(); background.classList.remove("hidden"); sidebar.classList.remove("sidebar-hide"); background.classList.remove("sidebar-hide"); });<file_sep>/app/routes.php <?php /* |-------------------------------------------------------------------------- | SINGLE PAGES |-------------------------------------------------------------------------- */ use App\Auth\LoginCheckMiddleware as LCM; /* * Display the live map, with statistics about the run */ $app->get('/', function () { // /map $total_data["stats"] = app('database') ->query("SELECT id, value, active FROM stats ORDER BY item_order") ->fetchAll(PDO::FETCH_UNIQUE); $total_data["settings"] = app('database') ->query("SELECT id, value FROM settings WHERE id = 'total_km' OR id = 'km_per_round'") ->fetchAll(PDO::FETCH_KEY_PAIR); // prevent data from leaking if not enabled if($total_data['stats']['total_donations']['active'] == 0) unset($total_data['stats']['total_donations']); return view('map', $total_data); }); $app->get('/scoreboard', function () { $top_runners = app('database')->query('SELECT r.name, g.name as group_name, r.total_rounds FROM runners as r, groups as g WHERE r.class = g.id ORDER BY total_rounds DESC LIMIT 5'); $top_groups = app('database')->query('SELECT name, average_rounds FROM groups ORDER BY average_rounds DESC LIMIT 5'); if(!$top_groups) $top_groups = []; if(!$top_runners) $top_runners = []; return view('scoreboard', ['top_runners' => $top_runners, 'top_groups' => $top_groups]); }); /* * Returns all the data needed for the map to display */ $app->get('/map/json', \App\Controllers\MapData::class.':getData'); /* * Returns up-to-date stats */ $app->get('/stats/json', \App\Controllers\MapData::class.':getStats'); /* * Removes all assistant edit permissions */ $app->get('/remove-assistant-permissions', function () { // /remove-assistant-permissions requires_permission('removeAssistantEditPermission'); $assistant = new \App\Auth\User(1, 'Assistant'); app('auth')->addPackageToUser($assistant, new \App\Auth\AssistantPackage()); app('auth')->removePackageFromUser($assistant, new \App\Auth\ElevatedAssistantPackage()); return redirect('/manage'); }); /* * Display log in form, redirect if already logged in */ $app->get('/login', function ($request) { // /login if(app('auth')->loggedIn()) { //return redirect('/manage'); echo app('auth')->user()->username(); } /** @var \Slim\Http\Request $request */ // check if user wants to log in as admin $login_as_admin = isset($request->getQueryParams()['admin']); return view('login', ['login_as_admin' => $login_as_admin]); }); /* * If password is correct authenticate user and redirect to /manage, * else send back to login */ $app->post('/login', function ($request) { // POST: /login /** @var \Slim\Http\Request $request */ $password = $request->getParam('password'); // use username if provided, else log in as 'Assistant' $username = $request->getParam('username', 'Assistant'); $username = htmlspecialchars($username); if(app('auth')->login($username , $password)) { return redirect('/manage'); } else { return redirect('/login'); } }); /* * Log the user out, redirect to index */ $app->get('/logout', function () { // /logout // log the user out app('auth')->logout(); return redirect('/'); }); /** * Downloads a csv file containing all runner data */ $app->get('/download/runners', \App\Controllers\DownloadData::class.':downloadRunnerData')->add(new LCM()); /** * Downloads a csv file containing all donor data */ $app->get('/download/donors', \App\Controllers\DownloadData::class.':downloadDonorData')->add(new LCM()); /* |-------------------------------------------------------------------------- | MANAGE |-------------------------------------------------------------------------- */ /* * Display a list of all classes to choose from */ $app->get('/manage', function () { // /manage $group_names = app('database')->query('SELECT name from groups')->fetchAll(); return view('select_class', ['group_names' => $group_names]); })->add(new LCM()); /* * Get class selection, redirect to /manage/{class}, * where class is the selected class. * This will only be called if JavaScript is disabled */ $app->post('/manage', function ($request) { // POST: /manage /** @var \Slim\Http\Request $request */ $class = $request->getParam('class'); // if no class has been submitted if($class == "") { return redirect('/manage'); } return redirect('/manage/'.$class); })->add(new LCM()); $app->group('/manage/{class}', function () { /* * Display an overview of the selected class (runners, finished rounds) */ $this->get('', function ($request, $response, $class) { // /manage/{class} // make sure the group exists $group = db_prepared_query( 'SELECT name FROM groups WHERE name = :name', [':name' => $class] )->fetch(); if(empty($group)) { return app('notFoundHandler')($request, $response); } $runners = db_prepared_query( 'SELECT r.id, r.name, r.total_rounds FROM runners as r, groups as g WHERE g.name = :class AND r.class = g.id', [':class' => $class] )->fetchAll(); return view('manage.overview', ['class' => $class, 'runners' => $runners]); }); /* * Interface to add rounds to the runners */ $this->get('/add', function ($request, $response, $class) { // /manage/{class}/add requires_permission('addRounds'); $runners = db_prepared_query( 'SELECT r.id, r.name FROM runners as r, groups as g WHERE g.name = :class AND r.class = g.id', [':class' => $class] )->fetchAll(); return view('manage.add', ['class' => $class, 'runners' => $runners]); }); /* * Add rounds to the runners */ $this->post( '/add', \App\Controllers\Manage::class.':add_post'); /* * Display log of all recent updates of the runners rounds */ $this->get('/log[/{page:[0-9]+}]', function ($request, $response, $class, $page = 1) { // /manage/{class}/log/ $offset = 25*($page-1) > 0 ? 25*($page-1) : 0; $logs = db_prepared_query( 'SELECT l.id, l.log_string, l.datetime, l.rounds_changed, l.active, u.username as user_name FROM logs as l, users as u, groups AS g WHERE l.user = u.id AND l.class = g.id AND g.name = :class ORDER BY l.id DESC LIMIT 25 OFFSET :offset', [':class' => $class, ':offset' => $offset])->fetchAll(); return view('manage.log', ['class' => $class, 'logs' => $logs, 'page' => $page]); }); /* * Undo round updates, Undo undos */ $this->post('/log', \App\Controllers\Manage::class.':rollback_log_post'); /* * Display sidebar, from "more" * This will only be called if JavaScript is disabled */ $this->get('/more', function ($request, $response, $class) { // /manage/{class}/more return view('sidebar', ['class' => $class]); }); })->add(new LCM()); /* |-------------------------------------------------------------------------- | EDIT |-------------------------------------------------------------------------- */ $app->group('/edit', function () { /* * Display available data of a runner, with the ability to change it * NOT ROUNDS! */ $this->get('/runner/{id}', function ($request, $response, $id) { // /edit/runner/{id} requires_permission('editRunner'); // get runner data $runner = db_prepared_query( 'SELECT r.*, g.name as class_name FROM runners as r, groups as g WHERE r.id = :id and r.class = g.id', [':id' => $id] )->fetch(); if(empty($runner)) { return app('notFoundHandler')($request, $response); } // get all group names (and ids) $stmt = app('database')->query('SELECT id, name FROM groups'); $groups = $stmt->fetchAll(); // get donor data $donors = db_prepared_query( 'SELECT id, name FROM donors WHERE runner_id = :id', [':id' => $id] )->fetchAll(); return view('edit.runner', [ 'id' => $id, 'runner' => $runner, 'groups' => $groups, 'donors' => $donors ]); }); /* * Update the runner's data */ $this->post('/runner/{id}', function ($request, $response, $id) { // POST: /edit/runner/{id} requires_permission('editRunner'); $params = $request->getParams(); if(isset($params['name'], $params['group'])) { $group_data = db_prepared_query('SELECT id FROM groups WHERE id = :group', [':group' => htmlspecialchars($params['group'])])->fetch(); // make sure the group exists if(isset($group_data['id'])) { db_prepared_query( 'UPDATE runners SET name = :name, class = :class WHERE id = :id', [ ':name' => htmlspecialchars($params['name']), ':class' => $group_data['id'], ':id' => $id] ); } } if(isset($request->getParams()['doDelete'])) { $response = app()->subRequest('DELETE', '/edit/runner/'.$id); return $response; } return redirect("/edit/runner/$id"); }); /** * Deletes a runner */ $this->delete('/runner/{id}', function ($request, $response, $id) { requires_permission('editRunner'); $group = db_prepared_query('SELECT g.name FROM groups as g, runners as r WHERE r.class = g.id AND r.id = :id', [':id' => $id])->fetch(); if(isset($group['name'])) { $success = db_prepared_query('DELETE FROM runners WHERE id = :id', [':id' => $id]); if($success) { return redirect('/manage/'.$group['name']); } } echo 'something went wrong.'; exit(); }); /* * Display data of a class, with the ability to change it */ $this->get('/class/{class}', function ($request, $response, $class) { // /edit/class/{class} requires_permission('editClass'); // make sure the group exists $group = db_prepared_query( 'SELECT name FROM groups WHERE name = :name', [':name' => $class] )->fetch(); if(empty($group)) { return app('notFoundHandler')($request, $response); } return view('edit.class', ['class' => $class]); }); /* * Update class data */ $this->post('/class/{class}', function ($request, $response, $class) { // POST: /edit/class/{class} requires_permission('editClass'); if(!isset($request->getParams()['name']) || empty($request->getParam('name'))) { if(isset($request->getParams()['doDelete'])) { $response = app()->subRequest('DELETE', '/edit/class/'.$class); return $response; } return redirect('/manage/'.$class); } db_prepared_query('UPDATE groups SET name = :new_name WHERE name = :old_name', [':new_name' => htmlspecialchars($request->getParam('name')), ':old_name' => $class]); return redirect('/manage/'.urlencode($request->getParam('name'))); }); /** * Delete a class */ $this->delete('/class/{class}', function ($request, $response, $class) { requires_permission('editClass'); $runners = db_prepared_query('SELECT r.id FROM runners as r, groups as g WHERE g.name = :name AND r.class = g.id', [':name' => htmlspecialchars($class)])->fetch(); if(!empty($runners)) { echo 'This group still has runners. Please move them first.<br>'; echo '<a href="/edit/class/'.$class.'">back</a>'; exit(); } $success = db_prepared_query('DELETE FROM groups WHERE name = :name', [':name' => htmlspecialchars($class)]); if($success) { return redirect('/manage'); } echo 'something went wrong.'; exit(); }); /* * Display data of a donor, with the ability to change it */ $this->get('/donor/{id}', function ($request, $response, $id) { // /edit/donor/{id} requires_permission('editDonor'); $donor = db_prepared_query( 'SELECT d.*, r.name as runner_name, g.name as runner_class FROM donors as d, runners as r, groups as g WHERE d.id = :id AND d.runner_id = r.id AND r.class = g.id', [':id' => $id] )->fetch(); if(empty($donor)) { return app('notFoundHandler')($request, $response); } return view('edit.donor', ['id' => $id, 'donor' => $donor]); }); /* * Update donor data */ $this->post('/donor/{id}', function ($request, $response, $id) { // POST: /edit/donor/{id} requires_permission('editDonor'); extract($request->getParams()); if(isset($name, $donation, $amountIsFixed, $wantsReceipt) && preg_match('/^[0-9]+((\.|\,)[0-9]{1,2})?$/', $donation) && ($amountIsFixed === "1" || $amountIsFixed === "0") && ($wantsReceipt === "1" || $wantsReceipt === "0") && is_numeric($id)) { $donation = str_replace(',','.',$donation); $name = htmlspecialchars($name); db_prepared_query( 'UPDATE donors SET name = :name, donation = :donation, amountIsFixed = :amountIsFixed, wantsReceipt = :wantsReceipt WHERE id = :id', [':name' => $name, ':donation' => $donation, ':amountIsFixed' => $amountIsFixed, ':wantsReceipt' => $wantsReceipt, ':id' => $id] ); } if(isset($request->getParams()['doDelete'])) { $response = app()->subRequest('DELETE', '/edit/donor/'.$id); return $response; } $runner_id = db_prepared_query('SELECT runner_id FROM donors WHERE id = :id', [ ':id' => $id ])->fetch()['runner_id']; return redirect("/edit/runner/$runner_id"); }); /** * Deletes a donor */ $this->delete('/donor/{id}', function ($request, $response, $id) { requires_permission('editDonor'); $runner = db_prepared_query('SELECT runner_id as id FROM donors WHERE id = :id', [':id' => $id])->fetch(); if(isset($runner['id'])) { $success = db_prepared_query('DELETE FROM donors WHERE id = :id', [':id' => $id]); if($success) { return redirect('/edit/runner/'.$runner['id']); } } echo 'something went wrong.'; exit(); }); }); /* |-------------------------------------------------------------------------- | ADD |-------------------------------------------------------------------------- */ $app->group('/add', function () { /* * Displays a form to add a new donor */ $this->get( '/donor/{runner_id}', function ( $request, $response, $runner_id ) { // /add/donor/{runner_id} requires_permission('addDonor'); $runner = db_prepared_query( 'SELECT r.name, g.name as runner_class FROM runners as r, groups as g WHERE r.class = g.id AND r.id = :id', [':id' => $runner_id] )->fetch(); if(empty($runner)) { return app('notFoundHandler')($request, $response); } return view('add.donor', ['runner_id' => $runner_id, 'runner' => $runner]); }); /** * Adds the new donor to the database */ $this->post('/donor', function ($request, $response) { // /add/donor requires_permission('addDonor'); extract($request->getParams()); if(isset($name, $donation, $amountIsFixed, $wantsReceipt, $runner_id) && preg_match('/^[0-9]+((\.|\,)[0-9]{1,2})?$/', $donation) && ($amountIsFixed === "1" || $amountIsFixed === "0") && ($wantsReceipt === "1" || $wantsReceipt === "0") && is_numeric($runner_id)) { $donation = str_replace(',','.',$donation); $runner_existence_check = db_prepared_query( 'SELECT id FROM runners WHERE id = :id', [':id' => $runner_id])->fetch(); if(empty($runner_existence_check)) { return app('notFoundHandler')($request, $response); } $name = htmlspecialchars($name); $insert_operation = db_prepared_query( 'INSERT INTO donors (name, donation, amountIsFixed, wantsReceipt, runner_id) VALUES (:name, :donation, :amountIsFixed, :wantsReceipt, :runner_id)', [ ':name' => $name, ':donation' => $donation, ':amountIsFixed' => $amountIsFixed, ':wantsReceipt' => $wantsReceipt, ':runner_id' => $runner_id ] ); if($insert_operation) { return redirect('/edit/runner/'.$runner_id); } } echo 'something went wrong.'; exit(); }); /* * Displays a form to add a new runner */ $this->get( '/runner/{class}', function ( $request, $response, $class ) { // /add/runner/{class} requires_permission('addRunner'); $class_id = db_prepared_query( 'SELECT id FROM groups WHERE name = :class', [':class' => $class] )->fetch(); if(!isset($class_id['id'])) { return app('notFoundHandler')($request, $response); } $groups = app('database')->query('SELECT id, name FROM groups')->fetchAll(); return view('add.runner', ['class' => $class, 'groups' => $groups, 'class_id' => $class_id['id']]); }); /** * Saves the new runner to the database */ $this->post('/runner', function ($request, $response) { // /add/runner requires_permission('addRunner'); extract($request->getParams()); // creates $name & $group (if present) $group_id = db_prepared_query('SELECT id FROM groups WHERE name = :group_name', [':group_name' => $group ?? ''])->fetch(); if(isset($name, $group_id['id'])) { $success = db_prepared_query('INSERT INTO runners (name, class) VALUES (:name, :group_id)', [':name' => htmlspecialchars($name), ':group_id' => $group_id['id']]); if($success) { return redirect('/edit/runner/'.app('database')->lastInsertId()); } } echo 'something went wrong.'; exit(); }); /** * Displays a form to add a new class */ $this->get('/class', function ($request, $response) { requires_permission('addClass'); return view('add.class'); }); /** * Adds the class to the database */ $this->post('/class', function ($request) { requires_permission('addClass'); extract($request->getParams()); if(isset($name)) { $existence_check = db_prepared_query('SELECT id FROM groups WHERE name = :name', [':name' => htmlspecialchars($name)])->fetch(); if(!empty($existence_check)) { echo trans('static.group_already_exists'); exit(); } $insert_operation = db_prepared_query('INSERT INTO groups (name) VALUES (:name)', [':name' => htmlspecialchars($name)]); if($insert_operation) { return redirect('/manage/'.urlencode($name)); } } echo 'something went wrong.'; exit(); }); });<file_sep>/resources/lang/en/static.php <?php return [ 'home' => 'Home', 'login' => 'Log In', 'back' => 'Back', 'submit' => 'Submit', 'password' => '<PASSWORD>', 'select_class' => 'Select Class', 'next' => 'Next', 'more' => 'More', 'add' => 'Add', 'overview' => 'Overview', 'change_class' => 'Change Class', 'logout' => 'Log Out', 'map' => 'Map', 'total_km' => 'total km', 'km_run' => 'km run', 'km_left_to_go' => 'km left to go', 'total_rounds' => 'total rounds', 'log' => 'Log', 'add_rounds' => 'Add Rounds', 'save' => 'Save', 'cancel' => 'Cancel', 'name' => 'Name', 'class' => 'Class', 'donors' => 'Donors', 'display_donors' => 'Display Donors', 'display_students' => 'Display Students', 'students' => 'Students', 'donation' => 'Donation', 'fixed_amount' => 'Fixed Amount', 'wants_receipt' => 'Wants Receipt', 'donates_for' => 'Donates For', 'delete' => 'Delete', 'username' => 'Username', 'edit_class' => 'Edit Class', 'has_no_donors' => 'This runner does not have any donors assigned.', 'added_rounds' => 'Added Rounds', 'rolled_back' => 'Rolled Back', 'add_donor' => 'Add Donor', 'full_name' => '<NAME>', 'add_runner' => 'Add Runner', 'donors_can_be_added_once_runner_saved' => 'Donors can be added once the runner is saved', 'add_class' => 'Add Class', 'group_already_exists' => 'A group with this name already exists.', 'installation' => 'Installation', 'install' => 'Install', 'welcome' => 'Welcome!', 'thanks_for_using' => 'Thanks for using CharityRun!', 'admin_username' => 'Admin username', 'admin_password' => '<PASSWORD>', 'repeat_password' => '<PASSWORD>', 'assistant_password' => '<PASSWORD>', 'admin_settings' => 'Admin settings', 'assistant_settings' => 'Assistant settings', 'map_settings' => 'Map settings', 'from' => 'From', 'latitude' => 'Latitude', 'longitude' => 'Longitude', 'to' => 'To', 'click_to_insert_coordinates' => 'Click on the map to automatically insert the coordinates.', 'line_number' => 'Line Number', 'latitude_from' => 'Latitude from', 'longitude_from' => 'Longitude from', 'latitude_to' => 'Latitude to', 'longitude_to' => 'Longitude to', 'action' => 'Action', 'km_per_round' => 'km per round', 'display_total_rounds_on_map' => 'Display total rounds on map', 'display_run_km_on_map' => 'Display run km on map', 'display_km_left_to_go_on_map' => 'Display km left to go on map', 'stats' => 'Statistics', 'remove_assistant_edit_permission' => 'Remove Assistant Edit Permission', 'should_do_this_once_data_entered' => 'You should do this once all data has been entered.', 'class_does_not_have_members' => 'This class doesn\'t have any members.', 'runner' => 'Runner', 'rounds' => 'Rounds', 'no_classes_yet' => 'There are no classes yet.', 'add_new_runner' => 'Add a new runner to this class', 'total_donations' => 'euro in total', 'runner_name' => 'Runner name', 'donor_name' => 'Donor name', 'yes' => 'Yes', 'no' => 'No', 'scoreboard' => 'Scoreboard', 'average_rounds' => 'Average Rounds', 'top_five_runners' => 'Top 5 Runners', 'top_five_groups' => 'Top 5 Groups', 'display_total_donations' => 'Display total donations', 'download_runner_data' => 'Download runner data', 'download_donor_data' => 'Download donor data' ];<file_sep>/tests/app/src/Auth/PDOStorageTest.php <?php namespace tests\app\src\Auth; use App\Auth\PDOStorage; use App\Auth\User; class PDOStorageTest extends \PHPUnit_Framework_TestCase { /** * @var PDOStorage */ protected $PDOStorage; /** * @var \PDO */ protected $db; public function __construct() { $this->db = new \PDO('sqlite:../../../../storage/database/database.sqlite'); } public function setUp() { $this->PDOStorage = new PDOStorage($this->db); } public function testAuthFetchUserByUsernameReturnsFalseIfNotFound() { $actual = $this->PDOStorage->authFetchUserByUsername('test', 'user'); $this->assertFalse($actual); } public function testAuthFetchUserByUsernameReturnsDataIfFound() { $actual = $this->PDOStorage->authFetchUserByUsername('test', 'foo'); $this->assertEquals(['id' => 1, 'username' => 'foo', 'password' => 'xyz'], $actual); } public function testAuthFetchUserRepresentationReturnsUserObjectOnSuccess() { $actual = $this->PDOStorage->authFetchUserRepresentation('test', 1); $expected = new User('1', 'foo'); $this->assertEquals($expected, $actual); } } <file_sep>/app/src/Auth/ElevatedAssistantPackage.php <?php namespace App\Auth; use Solution10\Auth\Package; /** * Class ElevatedAssistantPackage * This set of permission is granted to the Assistant during setup phase. * The assistant will have less permissions once setup phase is over. * @see \App\Auth\AssistantPackage * @package App\Auth */ class ElevatedAssistantPackage extends Package { public function init() { $this ->precedence(7) ->permissions([ 'addDonor' => true, 'addRunner' => true, 'addClass' => true, 'viewManageHelp' => true, 'editClass' => true, 'editRunner' => true, 'editDonor' => true, 'viewEditHelp' => true, 'rollback' => false, 'editSettings' => false, 'addRounds' => true, 'removeAssistantEditPermission' => false, 'downloadData' => false ]); } }<file_sep>/app/src/Controllers/Manage.php <?php namespace App\Controllers; use Psr\Container\ContainerInterface; use Slim\Http\Request; class Manage { protected $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function add_post(Request $request, $response, $class) { // POST: /manage/{class}/add requires_permission('addRounds'); $log_string = ''; $rounds_changed = 0; $donation_change = 0; foreach($request->getParams() as $field_name => $value) { if(preg_match('/^runner[0-9]+$/', $field_name) && preg_match('/^[0-9]+$/', $value)) { $id = substr( $field_name, 6 ); // remove "runner" db_prepared_query( 'UPDATE runners SET total_rounds = total_rounds + :rounds WHERE id = :id', [':id' => $id, ':rounds' => $value] ); $log_string .= $id.'+'.$value.';'; $rounds_changed += $value; $donation_change += $this->updateDonations($id); db_prepared_query( 'UPDATE stats SET value = value + :donation_change WHERE id = :id', [':donation_change' => $donation_change] ); } } if($rounds_changed !== 0) { db_prepared_query( "UPDATE stats SET value = value + :donation_change WHERE id = 'total_donations'", [':donation_change' => $donation_change] ); db_prepared_query( "UPDATE stats SET value = value + :rounds WHERE id = 'total_rounds'", [':rounds' => $rounds_changed] ); $group_id = $this->getGroupIdFromName($class); if($group_id) { $this->addLog($group_id, $log_string,$rounds_changed); $this->updateGroupAverage($group_id); } } return redirect("/manage/$class"); } private function updateGroupAverage($group_id) { $runners = db_prepared_query('SELECT total_rounds FROM runners WHERE class = :group_id', [ ':group_id' => $group_id ])->fetchAll(); $runner_rounds = array_column($runners, 'total_rounds'); $total_rounds = array_sum($runner_rounds); $member_count = count(array_filter($runner_rounds)); // only members who actually ran are being counted $average_rounds = $member_count == 0 ? 0 : round($total_rounds / $member_count, 1); db_prepared_query("UPDATE groups SET average_rounds = :average_rounds WHERE id = :group_id", [ ':average_rounds' => $average_rounds, ':group_id' => $group_id ]); } // big helper function, mainly consisting of state detection private function updateDonations($runner_id, $is_rollback = false) { $rounds = db_prepared_query('SELECT total_rounds FROM runners WHERE id = :runner_id', [ ':runner_id' => $runner_id ])->fetch()['total_rounds']; // three scenarios: // 1: Runner now has 0 rounds -> set all to 0 // 2/3: Runner has >0 rounds -> set absolute to max, calculate relative $donors = db_prepared_query('SELECT id, donation, amountIsFixed, total_donation FROM donors WHERE runner_id = :runner_id', [ ':runner_id' => $runner_id ])->fetchAll(); if($rounds == 0) { db_prepared_query('UPDATE donors SET total_donation = 0 WHERE runner_id = :runner_id', [ ':runner_id' => $runner_id ]); $donations_changed = array_sum(array_column($donors, 'total_donation')); return -$donations_changed; } $donations_changed = 0; foreach($donors as $donor) { if($donor['amountIsFixed'] == 1 && $donor['total_donation'] > 0) { if($is_rollback) { $donations_changed += -$donor['donation']; db_prepared_query('UPDATE donors SET total_donation = :donation WHERE id = :id', [':id' => $donor['id'], ':donation' => 0]); } continue; } elseif($donor['amountIsFixed'] == 1 ) { // amountIsFixed && total_donation is 0 $donations_changed += $donor['donation']; db_prepared_query('UPDATE donors SET total_donation = :donation WHERE id = :id', [':id' => $donor['id'], ':donation' => $donor['donation']]); } else { // donation amount is depending on rounds $donations_changed += $donor['donation'] * $rounds - $donor['total_donation']; db_prepared_query('UPDATE donors SET total_donation = :donation WHERE id = :id', [':id' => $donor['id'], ':donation' => $donor['donation'] * $rounds]); } } return $donations_changed; } public function rollback_log_post($request, $response, $class) { // POST: /manage/{class}/log requires_permission('rollback'); $id = $request->getParams()['id'] ?? ''; if(preg_match('/^[0-9]+$/', $id)) { $rollback_data = db_prepared_query( 'SELECT log_string FROM logs WHERE id = :id AND active = 1', [':id' => $id] )->fetch(); if(isset($rollback_data['log_string'])) { if (strpos($rollback_data['log_string'], '+')) { $this->rollback_addition($rollback_data['log_string'], $class); $this->disable_log($id); } elseif (strpos($rollback_data['log_string'], '-')) { $this->rollback_rollback($rollback_data['log_string'], $class); $this->disable_log($id); } } } return redirect("/manage/$class/log"); } private function disable_log(int $id) { db_prepared_query('UPDATE logs SET active = 0 WHERE id = :id', [':id' => $id]); } /** * Helper method for rollback_log_post to roll back round additions * @param string $log_string * @param string $class * @see rollback_log_post() */ private function rollback_addition(string $log_string, string $class) { $round_changes = array_filter(explode(';', $log_string)); $total_change = 0; $donation_change = 0; $group_id = $this->getGroupIdFromName($class); if($group_id) { foreach ( $round_changes as $round_change ) { list($id, $change) = explode('+', $round_change); db_prepared_query('UPDATE runners SET total_rounds = total_rounds - :change WHERE id = :id', [':id' => $id, ':change' => $change]); $total_change = $total_change - $change; $donation_change += $this->updateDonations($id, true); } db_prepared_query( "UPDATE stats SET value = value + :rounds WHERE id = 'total_rounds'", [':rounds' => $total_change] ); db_prepared_query( "UPDATE stats SET value = value + :donation_change WHERE id = 'total_donations'", [':donation_change' => $donation_change] ); $this->addLog($group_id, str_replace('+', '-', $log_string),$total_change); $this->updateGroupAverage($group_id); } } /** * Helper method for rollback_log_post to roll back previous rollbacks * @param string $log_string * @param string $class * @see rollback_log_post() */ private function rollback_rollback(string $log_string, string $class) { $round_changes = array_filter(explode(';', $log_string)); $total_change = 0; $donation_change = 0; $group_id = $this->getGroupIdFromName($class); if($group_id) { foreach ( $round_changes as $round_change ) { list( $id, $change ) = explode( '-', $round_change ); db_prepared_query( 'UPDATE runners SET total_rounds = total_rounds + :change WHERE id = :id', [ ':id' => $id, ':change' => $change ] ); $total_change = $total_change + $change; $donation_change += $this->updateDonations($id, true); } db_prepared_query( "UPDATE stats SET value = value + :rounds WHERE id = 'total_rounds'", [':rounds' => $total_change] ); db_prepared_query( "UPDATE stats SET value = value + :donation_change WHERE id = 'total_donations'", [':donation_change' => $donation_change] ); $this->addLog( $group_id, str_replace( '-', '+', $log_string ), $total_change ); $this->updateGroupAverage($group_id); } } protected function addLog(int $group, string $log_string, string $rounds_changed) { db_prepared_query( 'INSERT INTO logs (`class`, `log_string`, `datetime`, `user`, `rounds_changed`) VALUES (:class, :log_string, :date_time, :user, :rounds_changed)', [ ':class' => $group, ':log_string' => $log_string, ':date_time' => date('Y-m-d H:m:s'), ':user' => app('auth')->user()->id(), ':rounds_changed' => $rounds_changed ]); } protected function getGroupIdFromName(string $name) { $group_data = db_prepared_query('SELECT id FROM groups WHERE name = :group', [':group' => $name])->fetch(); return $group_data['id'] ?? false; } }<file_sep>/tests/bootstrap.php <?php require __DIR__ . '/../vendor/autoload.php'; $container = new \Slim\Container([ 'database' => function() { return new PDO('sqlite:tests/storage/database/database.sqlite'); } ]); require __DIR__ . '/../app/helpers.php';<file_sep>/tests/app/src/Representatives/DonorTest.php <?php class DonorTest extends \PHPUnit_Framework_TestCase { /** * @var \PDO $pdo */ protected static $pdo = null; /** * @var \App\Representatives\Donor $donor */ protected static $donor = null; /** * @var mixed $id */ protected static $id = null; public static function setUpBeforeClass() { // set up database connection self::$pdo = app('database'); // create new Donor self::$pdo->query("INSERT INTO donors (name, \"runner-id\", donation, amountIsFixed, wantsReceipt) VALUES ('Foo', 1, 0.00, 0, 0)"); self::$id = self::$pdo->lastInsertId(); } public function setUp() { $this::$donor = new \App\Representatives\Donor(self::$id); } public function testDonorReturnsCorrectID() { $this->assertEquals(self::$id, $this::$donor->getId()); } public function testDonorSetsSingleValueCorrectly() { $this::$donor->set('name', 'FooBar'); $this->assertEquals('FooBar', $this::$donor->get('name')); } public function testDonorGetsSingleValueCorrectly() { $actual = $this::$donor->get('donation'); $this->assertEquals(0.00, $actual); } public static function tearDownAfterClass() { self::$donor->delete(); } }<file_sep>/tests/app/src/Representatives/GroupTest.php <?php class GroupTest extends \PHPUnit_Framework_TestCase { /** * @var \PDO $pdo */ protected static $pdo = null; /** * @var \App\Representatives\Group $group */ protected static $group = null; /** * @var mixed $id */ protected static $id = null; public static function setUpBeforeClass() { // set up database connection self::$pdo = app('database'); // create new runner self::$pdo->query("INSERT INTO classes (name) VALUES (00)"); self::$id = self::$pdo->lastInsertId(); } public function setUp() { $this::$group = new \App\Representatives\Group(self::$id); } public function testGroupReturnsCorrectID() { $this->assertEquals(self::$id, $this::$group->getId()); } public function testGroupSetsSingleValueCorrectly() { $this::$group->set('name', '01'); $this->assertEquals('01', $this::$group->get('name')); } public static function tearDownAfterClass() { self::$group->delete(); } }<file_sep>/tests/app/src/Representatives/UserTest.php <?php class UserTest extends \PHPUnit_Framework_TestCase { /** * @var \PDO $pdo */ protected static $pdo = null; /** * @var \App\Representatives\User $user */ protected static $user = null; /** * @var mixed $id */ protected static $id = null; public static function setUpBeforeClass() { // set up database connection self::$pdo = app('database'); // create new User self::$pdo->query("INSERT INTO users (username, password) VALUES ('foo', 'encrypted')"); self::$id = self::$pdo->lastInsertId(); } public function setUp() { $this::$user = new \App\Representatives\User(self::$id); } public function testUserReturnsCorrectID() { $this->assertEquals(self::$id, $this::$user->getId()); } public function testUserSetsSingleValueCorrectly() { $this::$user->set('username', 'FooBar'); $this->assertEquals('FooBar', $this::$user->get('username')); } public function testUserGetsSingleValueCorrectly() { $actual = $this::$user->get('password'); $this->assertEquals('encrypted', $actual); } public static function tearDownAfterClass() { self::$user->delete(); } }<file_sep>/app/src/Controllers/MapData.php <?php namespace App\Controllers; use Psr\Container\ContainerInterface; class MapData { protected $container; public function __construct(ContainerInterface $container) { $this->container = $container; } /** * Returns the data needed for the map in json format */ public function getData() { $data = [ "map" => "worldLow", "lines"=> [] ]; $lines = app('database')->query("SELECT * FROM `lines`")->fetchAll(); for($i = 0; $i<count($lines); $i++) { $line_data = [ "latitudes" => [ (float) $lines[$i]["from_lat"], (float) $lines[$i]["to_lat"] ], "longitudes" => [ (float) $lines[$i]["from_long"], (float) $lines[$i]["to_long"] ] ]; $data["lines"][] = $line_data; $line_data["id"] = "progress_".($i+1); $line_data["thickness"] = 4; $line_data["alpha"] = 1; $line_data["color"] = "#bb0000"; $line_data["customData"] = ['distance' => $lines[$i]['distance']]; $data["lines"][] = $line_data; } echo json_encode($data); } public function getStats() { $stats = app('database')->query("SELECT id, value FROM stats WHERE active = 1")->fetchAll(\PDO::FETCH_KEY_PAIR); $settings = app('database')->query("SELECT id, value FROM settings WHERE id = 'km_per_round' OR id = 'total_km'")->fetchAll(\PDO::FETCH_KEY_PAIR); echo json_encode(array_merge($stats, $settings)); } }<file_sep>/app/src/Auth/AdminPackage.php <?php namespace App\Auth; use Solution10\Auth\Package; /** * Class AdminPackage * The Administrator has full control over the system and thus all permissions. * @package App\Auth */ class AdminPackage extends Package { public function init() { $this ->precedence(10) ->permissions([ 'addDonor' => true, 'addRunner' => true, 'addClass' => true, 'viewManageHelp' => true, 'editClass' => true, 'editRunner' => true, 'editDonor' => true, 'viewEditHelp' => true, 'rollback' => true, 'editSettings' => true, 'addRounds' => true, 'removeAssistantEditPermission' => true, 'downloadData' => true ]); } }<file_sep>/app/src/Auth/User.php <?php namespace App\Auth; use Solution10\Auth\UserRepresentation; class User implements UserRepresentation { protected $id; protected $username; function __construct($id, $username) { $this->id = $id; $this->username = $username; } /** * Returns the ID of this user. Doesn't matter what type it returns. * @return mixed */ public function id() { return $this->id; } /** * Returns the user's username * @return string */ public function username() { return $this->username; } }<file_sep>/app/src/Auth/LoginCheckMiddleware.php <?php namespace App\Auth; class LoginCheckMiddleware { /** * @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request * @param \Psr\Http\Message\ResponseInterface $response PSR7 response * @param callable $next Next middleware * * @return \Psr\Http\Message\ResponseInterface */ public function __invoke($request, $response, $next) { // check if user is not logged in if(!app('auth')->loggedIn()) { // redirect returns a response, so this is fine return redirect('/login'); } // else just keep going $response = $next($request, $response); return $response; } }<file_sep>/public/js/install_functions.js function emptyString() { for(var i = 0; i<arguments.length; i++) { if(!arguments[i] || arguments[i] === "" || arguments[i] === null) { return true; } } return false; } function resetMapCoordinates() { document.getElementById('latitude_from').value = ''; document.getElementById('longitude_from').value = ''; document.getElementById('latitude_to').value = ''; document.getElementById('longitude_to').value = ''; } var lines_count = 0; function addMapCoordinates(lat_from, long_from, lat_to, long_to) { map.dataProvider.lines.push({ "id": "line_"+lines_count, "latitudes": [lat_from, lat_to], "longitudes": [long_from, long_to], 'title': lines_count }); map.validateData(); } var lines = {}; function addLine() { lat_from = document.getElementById('latitude_from').value; long_from = document.getElementById('longitude_from').value; lat_to = document.getElementById('latitude_to').value; long_to = document.getElementById('longitude_to').value; if(!emptyString(lat_from, long_from, lat_to, long_to)) { lines["line_"+lines_count] = { 'lat_from': lat_from, 'long_from': long_from, 'lat_to': lat_to, 'long_to': long_to }; document.getElementById('lines_input').setAttribute('value', JSON.stringify(getLines())); addMapCoordinates(lat_from, long_from, lat_to, long_to); addLineToTable(lat_from, long_from, lat_to, long_to); // reset only "to" coordinates document.getElementById('latitude_to').value = ''; document.getElementById('longitude_to').value = ''; lines_count++; } } function addLineToTable(lat_from, long_from, lat_to, long_to) { var tr = document.getElementById('new_table_row').cloneNode(true); tr.setAttribute('id', 'table_line_'+lines_count); tr.children[0].innerHTML = lines_count; tr.children[1].innerHTML = lat_from; tr.children[2].innerHTML = long_from; tr.children[3].innerHTML = lat_to; tr.children[4].innerHTML = long_to; tr.children[5].children[0].setAttribute('data-line-id', lines_count); document.getElementById('lines_table').appendChild(tr); } function getLines() { var values = []; for (var k in lines) { if (lines.hasOwnProperty(k)) { values.push(lines[k]); } } return values; } function removeLine(button) { var id = button.getAttribute('data-line-id'); if(lines["line_"+id] !== undefined) { delete lines['line_'+id]; document.getElementById('table_line_'+id).remove(); document.getElementById('lines_input').setAttribute('value', JSON.stringify(getLines())); // remove from map var index = map.dataProvider.lines.findIndex(function (sub) { return sub.id === 'line_'+id; }); map.dataProvider.lines.splice(index, 1); map.validateData(); } }<file_sep>/resources/lang/de/static.php <?php return [ 'home' => 'Home', 'login' => 'Anmelden', 'back' => 'Zurück', 'submit' => 'Absenden', 'password' => '<PASSWORD>', 'select_class' => 'Klasse auswählen', 'next' => 'Weiter', 'more' => 'Mehr', 'add' => 'Hinzufügen', 'overview' => 'Übersicht', 'change_class' => 'Klasse ändern', 'logout' => 'Abmelden', 'map' => 'Karte', 'total_km' => 'Kilometer gesamt', 'km_run' => 'Kilometer gelaufen', 'km_left_to_go' => 'Kilometer verbleibend', 'total_rounds' => 'Runden gesamt', 'log' => 'Log', 'add_rounds' => 'Runden hinzufügen', 'save' => 'Speichern', 'cancel' => 'Abbrechen', 'name' => 'Name', 'class' => 'Klasse', 'donors' => 'Spender', 'display_donors' => 'Spender anzeigen', 'display_students' => 'Schüler anzeigen', 'students' => 'Schüler', 'donation' => 'Spende', 'fixed_amount' => 'Absoluter Betrag', 'wants_receipt' => 'Verlangt Rechnung', 'donates_for' => 'Spendet für', 'delete' => 'Löschen', 'username' => 'Nutzername', 'edit_class' => 'Klasse bearbeiten', 'has_no_donors' => 'Dieser Läufer hat keine Spender.', 'added_rounds' => 'Hinzugefügte Runden', 'rolled_back' => 'Zurückgesetzt', 'add_donor' => 'Spender hinzufügen', 'full_name' => '<NAME>', 'add_runner' => 'Läufer hinzufügen', 'donors_can_be_added_once_runner_saved' => 'Spender können hinzugefügt werden, sobald der Läufer gespeichert wurde', 'add_class' => 'Klasse hinzufügen', 'group_already_exists' => 'Eine Gruppe mit diesem Namen existiert bereits.', 'installation' => 'Installation', 'install' => 'Installieren', 'welcome' => 'Willkommen!', 'thanks_for_using' => 'Vielen Dank für die Benutzung von CharityRun!', 'admin_username' => 'Administrator Nutzername', 'admin_password' => '<PASSWORD>', 'repeat_password' => '<PASSWORD>', 'assistant_password' => '<PASSWORD>', 'admin_settings' => 'Administrator-Einstellungen', 'assistant_settings' => 'Assistenten-Einstellungen', 'map_settings' => 'Karten-Einstellungen', 'from' => 'Von', 'latitude' => 'geographische Breite', 'longitude' => 'geographische Länge', 'to' => 'Nach', 'click_to_insert_coordinates' => 'Klicke auf die Karte um die Koordinaten automatisch einzufügen.', 'line_number' => 'Linien-Nummer', 'latitude_from' => 'geogr. Breite von', 'longitude_from' => 'geogr. Länge von', 'latitude_to' => 'geogr. Breite nach', 'longitude_to' => 'geogr. Länge nach', 'action' => 'Aktion', 'km_per_round' => 'Kilometer pro Runde', 'display_total_rounds_on_map' => 'Gesamt gelaufene Runden auf der Karte anzeigen', 'display_run_km_on_map' => 'Gesamt gelaufene Kilometer auf der Karte anzeigen', 'display_km_left_to_go_on_map' => 'Restliche Kilometer auf der Karte anzeigen', 'stats' => 'Statistiken', 'remove_assistant_edit_permission' => 'Assistenten Bearbeitungsberechtigung entziehen', 'should_do_this_once_data_entered' => 'Sollte ausgeführt werden sobald alle Daten eingetragen wurden.', 'class_does_not_have_members' => 'Diese Gruppe hat keine Läufer.', 'runner' => 'Läufer', 'rounds' => 'Runden', 'no_classes_yet' => 'Es sind noch keine Gruppen vorhanden.', 'add_new_runner' => 'Neuen Läufer zur Gruppe hinzufügen.', 'total_donations' => 'Euro gesamt', 'runner_name' => 'Läufername', 'donor_name' => 'Spendername', 'yes' => 'Ja', 'no' => 'Nein', 'scoreboard' => 'Scoreboard', 'average_rounds' => 'Durchschnittliche Runden', 'top_five_runners' => 'Top 5 Läufer', 'top_five_groups' => 'Top 5 Klassen', 'display_total_donations' => 'Gesammelte Spenden anzeigen', 'download_runner_data' => 'Läuferdaten herunterladen', 'download_donor_data' => 'Spenderdaten herunterladen' ];<file_sep>/app/src/Auth/PDOStorage.php <?php namespace App\Auth; use Solution10\Auth\Package; use Solution10\Auth\StorageDelegate; use Solution10\Auth\UserRepresentation; class PDOStorage implements StorageDelegate { /** * A pdo database connection * @var \PDO */ protected $db; public function __construct(\PDO $pdo) { $this->db = $pdo; } /** * Fetches a user by their username. This function should return either an * array containing: * - id: the unique identifier for this user * - username: the username we just looked up * - password: the hashed version of the users password. * If it's a success, or false if there's no user by that name * * @param string $instance_name Instance name * @param string $username Username to search for * @return array|bool */ public function authFetchUserByUsername($instance_name, $username) { $stmt = $this->db->prepare('SELECT id, username, password FROM users WHERE username = :username'); $stmt->bindParam('username', $username); $stmt->execute(); // return associative array return $stmt->fetch(\PDO::FETCH_ASSOC); } /** * Fetches the full user representation of a given ID. ie your active record * instance or the like. * * @param string $instance_name Instance name * @param int $user_id ID of the logged in user * @return UserRepresentation The representation you return must implement the UserRepresentation interface. */ public function authFetchUserRepresentation($instance_name, $user_id) { // fetch data $stmt = $this->db->prepare('SELECT id, username FROM users WHERE id = :id'); $stmt->bindParam('id', $user_id); $stmt->execute(); $user = $stmt->fetch(); return new User($user['id'], $user['username']); } /** * Adding a package to a given user. * * @param string $instance_name Auth instance name * @param UserRepresentation $user User representation (taken from authFetchUserRepresentation) * @param Package $package Package to add. * @return bool */ public function authAddPackageToUser($instance_name, UserRepresentation $user, Package $package) { $id = $user->id(); $package_name = $package->name(); $stmt = $this->db->prepare('INSERT INTO user_packages (user_id, package) VALUES (:id, :package)'); $stmt->bindParam('id', $id); $stmt->bindParam('package', $package_name); return $stmt->execute(); } /** * Removing a package from a given user. * * @param string $instance_name Auth instance name * @param UserRepresentation $user User representation (taken from authFetchUserRepresentation) * @param Package $package Package to remove. * @return bool */ public function authRemovePackageFromUser($instance_name, UserRepresentation $user, Package $package) { $id = $user->id(); $package_name = $package->name(); $stmt = $this->db->prepare('DELETE FROM user_packages WHERE package = :package AND user_id = :id'); $stmt->bindParam('id', $id); $stmt->bindParam('package', $package_name); return $stmt->execute(); } /** * Fetching all packages for a user * * @param string $instance_name Auth instance name * @param UserRepresentation $user User representation (taken from authFetchUserRepresentation) * @return array */ public function authFetchPackagesForUser($instance_name, UserRepresentation $user) { $id = $user->id(); $stmt = $this->db->prepare('SELECT package FROM user_packages WHERE user_id = :id'); $stmt->bindParam('id', $id); $stmt->execute(); $result = $stmt->fetch(\PDO::FETCH_ASSOC); if($result === false) { return []; } return $result; } /** * Returns whether a user has a given package or not. * * @param string $instance_name Auth instance name * @param UserRepresentation $user User representation * @param Package $package Package to check for * @return bool */ public function authUserHasPackage($instance_name, UserRepresentation $user, Package $package) { $id = $user->id(); $package_name = $package->name(); $stmt = $this->db->prepare('SELECT id FROM user_packages WHERE user_id = :id AND package = :package'); $stmt->bindParam('id', $id); $stmt->bindParam('package', $package_name); $stmt->execute(); // true if data was received, false if not return (bool) $stmt->fetch(); } /** * Stores an overridden permission for a user * * @param string $instance_name Auth instance name * @param UserRepresentation $user * @param string $permission Permission name * @param bool $new_value New value * @return bool */ public function authOverridePermissionForUser( $instance_name, UserRepresentation $user, $permission, $new_value ) { $id = $user->id(); $stmt = $this->db->prepare('INSERT INTO user_overrides (user_id, permission, value) VALUES (:id, :permission, :value)'); $stmt->bindParam('id', $id); $stmt->bindParam('permission', $permission); // Make sure values are booleans $new_value = (bool) $new_value; $stmt->bindParam('value', $new_value); return $stmt->execute(); } /** * Fetches all the permission overrides for a given user. * * @param string $instance_name Auth instance name * @param UserRepresentation $user * @return array An array of permission => (bool) values */ public function authFetchOverridesForUser($instance_name, UserRepresentation $user) { $id = $user->id(); $stmt = $this->db->prepare('SELECT permission, value FROM user_overrides WHERE user_id = :id'); $stmt->bindParam('id', $id); $stmt->execute(); // if no overrides exist, return empty array $overrides = $stmt->fetch(\PDO::FETCH_KEY_PAIR); if($overrides) { return $overrides; } return []; } /** * Removes a specific override from a given user * * @param string $instance_name Auth instance name * @param UserRepresentation $user * @param string $permission Permission override to remove * @return bool */ public function authRemoveOverrideForUser($instance_name, UserRepresentation $user, $permission) { $id = $user->id(); $stmt = $this->db->prepare('DELETE FROM user_overrides WHERE user_id = :id AND permission = :permission'); $stmt->bindParam('id', $id); $stmt->bindParam('permission', $permission); return $stmt->execute(); } /** * Removes all the overrides for a given user. * * @param string $instance_name Auth instance name * @param UserRepresentation $user * @return bool */ public function authResetOverridesForUser($instance_name, UserRepresentation $user) { $id = $user->id(); $stmt = $this->db->prepare('DELETE FROM user_overrides WHERE user_id = :id'); $stmt->bindParam('id', $id); return $stmt->execute(); } }<file_sep>/app/helpers.php <?php /** * Returns a service from the container */ if(!function_exists('app')) { function app($service = '') { if($service == '') { global $app; return $app; } global $container; return $container[$service]; } } /** * Returns the translation for a key */ if(!function_exists('trans')) { function trans($key, $replace = []) { return app('translator')->trans($key, $replace); } } /** * Returns a view with the given parameters */ if(!function_exists('view')) { function view($view, $args = []) { // allow dot notation $view = implode(DIRECTORY_SEPARATOR, explode('.', $view)).'.phtml'; return app('renderer')->render(app('response'), $view, $args); } } /** * Returns the base url */ if(!function_exists('base_url')) { function base_url() { /** @var \Psr\Http\Message\UriInterface $uri */ $uri = app('request')->getUri(); // if port is needed append it $port = ':'.$uri->getPort(); if($port == ':80' || $port == ':443') { $port = ''; } return $uri->getScheme().'://'.$uri->getHost().$port; } } /** * Returns a redirect response */ if(!function_exists('redirect')) { function redirect($path) { return app('response')->withRedirect($path); } } if(!function_exists('db_prepared_query')) { /** * Executes a prepared sql query with the given parameters. * @param string $query * @param array $params as key => value pairs * @param null $execute_return_value sets the given variable to * the execute's return value * @return PDOStatement */ function db_prepared_query(string $query, array $params, &$execute_return_value = null) { /** @var PDOStatement $stmt */ $stmt = app('database')->prepare($query); if(is_null($execute_return_value)) { $stmt->execute($params); } else { $execute_return_value = $stmt->execute($params); } return $stmt; } } if(!function_exists('requires_permission')) { function requires_permission(string $permission) { if(!app('auth')->can($permission)) { echo 'You don\'t have permission to do this'; exit(); } } } if(!function_exists('preferred_language')) { /** * Figures the user's preferred language out * @param string $default_language fallback if nothing matches * @param array $available_languages * @param string $http_accept_language $_SERVER['HTTP_ACCEPT_LANGUAGE'] * @return string */ function preferred_language($default_language, $available_languages, $http_accept_language) { $available_languages = array_flip($available_languages); $langs = array(); preg_match_all('~([\w-]+)(?:[^,\d]+([\d.]+))?~', strtolower($http_accept_language), $matches, PREG_SET_ORDER); foreach($matches as $match) { list($a, $b) = explode('-', $match[1]) + array('', ''); $value = isset($match[2]) ? (float) $match[2] : 1.0; if(isset($available_languages[$match[1]])) { $langs[$match[1]] = $value; continue; } if(isset($available_languages[$a])) { $langs[$a] = $value - 0.1; } } if($langs) { arsort($langs); return key($langs); // We don't need the whole array of choices since we have a match } else { return $default_language; } } }<file_sep>/public/js/functions.js function updateStats() { var associations = { "km_run": km_run, "km_left_to_go": Math.max((total_km - km_run), 0), "total_rounds": total_rounds, "total_donations": total_donations }; for(var id in associations) { if(associations.hasOwnProperty(id) && document.getElementById(id) !== null) { document.getElementById(id).innerText = associations[id]; } } draw_progress_lines(); } function getAsync(url, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState === 4 && xmlHttp.status === 200) callback(xmlHttp.response); }; xmlHttp.open("GET", url, true); // true for asynchronous xmlHttp.responseType = "json"; xmlHttp.send(null); } function doConfirm(){ return confirm('Are you sure?'); }<file_sep>/resources/lang/en/dynamic.php <?php return [ 'manage_class_x' => 'Manage Class {class}', 'class_x' => 'Class {class}', 'log_class_x' => 'Log Class {class}', 'edit_runner_x' => 'Edit Runner: {name}', 'edit_class_x' => 'Edit Class: {class}', 'edit_donor_x' => 'Edit Donor: {name}', 'log_in_as_x' => 'Log In as {role}' ];<file_sep>/app/dependencies.php <?php // DIC configuration $container = $app->getContainer(); // Alternative route strategy $container['foundHandler'] = function () { return new \Slim\Handlers\Strategies\RequestResponseArgs(); }; // view renderer $container['renderer'] = function ($c) { $settings = $c->get('settings')['renderer']; return new Slim\Views\PhpRenderer($settings['template_path']); }; // monolog $container['logger'] = function ($c) { $settings = $c->get('settings')['logger']; $logger = new Monolog\Logger($settings['name']); $logger->pushProcessor(new Monolog\Processor\UidProcessor()); $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level'])); return $logger; }; // translator $container['translator'] = function ($c) { $settings = $c->get('settings')['translator']; if(!isset($_SESSION['lang'])) { chdir($settings['path']); $available_languages = array_diff(glob('*', GLOB_ONLYDIR), ['.', '..']); chdir(__DIR__); $_SESSION['lang'] = preferred_language( $settings['default_locale'], $available_languages, $_SERVER['HTTP_ACCEPT_LANGUAGE']); } return new \MichaelSpiss\Translation\Translator($_SESSION['lang'], $settings['path']); }; $container['database'] = function ($c) { $settings = $c->get('settings')['database']; $pdo = new PDO($settings['dsn'], $settings['username'], $settings['password']); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); return $pdo; }; $container['auth'] = function () { $storageDelegate = new \App\Auth\PDOStorage(app('database')); $sessionDelegate = new \Solution10\Auth\Driver\Session(); return new Solution10\Auth\Auth('Default', $sessionDelegate, $storageDelegate); };<file_sep>/app/db.sql BEGIN TRANSACTION; CREATE TABLE IF NOT EXISTS `users` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `username` TEXT, `password` TEXT ); CREATE TABLE IF NOT EXISTS `user_packages` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `user_id` INTEGER, `package` TEXT ); INSERT INTO `user_packages` VALUES (1,1,'App\Auth\ElevatedAssistantPackage'); INSERT INTO `user_packages` VALUES (2,2,'App\Auth\AdminPackage'); CREATE TABLE IF NOT EXISTS `user_overrides` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `user_id` INTEGER, `permission` TEXT, `value` INTEGER ); CREATE TABLE IF NOT EXISTS `stats` ( `id` TEXT, `value` INTEGER, `active` INTEGER DEFAULT 1, `item_order` INTEGER UNIQUE ); CREATE TABLE IF NOT EXISTS `settings` ( `id` TEXT, `value` TEXT ); CREATE TABLE IF NOT EXISTS `runners` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `total_rounds` INTEGER DEFAULT 0, `class` INTEGER ); CREATE TABLE IF NOT EXISTS `logs` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `class` TEXT, `user` INTEGER, `log_string` TEXT, `rounds_changed` INTEGER, `datetime` TEXT, `active` INTEGER DEFAULT 1 ); CREATE TABLE IF NOT EXISTS `lines` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `from_lat` NUMERIC, `to_lat` NUMERIC, `from_long` NUMERIC, `to_long` NUMERIC, `distance` NUMERIC ); CREATE TABLE IF NOT EXISTS `groups` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `average_rounds` NUMERIC DEFAULT 0 ); CREATE TABLE IF NOT EXISTS `donors` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT, `donation` NUMERIC, `amountIsFixed` INTEGER, `wantsReceipt` INTEGER, `runner_id` INTEGER, `total_donation` NUMERIC DEFAULT 0 ); COMMIT; <file_sep>/tests/app/src/Representatives/RunnerTest.php <?php class RunnerTest extends \PHPUnit_Framework_TestCase { /** * @var \PDO $pdo */ protected static $pdo = null; /** * @var \App\Representatives\Runner $runner */ protected static $runner = null; /** * @var mixed $id */ protected static $id = null; public static function setUpBeforeClass() { // set up database connection self::$pdo = app('database'); // create new runner self::$pdo->query("INSERT INTO runners (class, name) VALUES (1, 'Wooabadoo')"); self::$id = self::$pdo->lastInsertId(); } public function setUp() { $this::$runner = new \App\Representatives\Runner(self::$id); } public function testRunnerReturnsCorrectID() { $this->assertEquals(self::$id, $this::$runner->getId()); } public function testRunnerSetsSingleValueCorrectly() { $this::$runner->set('name', 'FooBar'); $this->assertEquals('FooBar', $this::$runner->get('name')); } public function testRunnerGetsSingleValueCorrectly() { $actual = $this::$runner->get('total-rounds'); $this->assertEquals(0, $actual); } public static function tearDownAfterClass() { self::$runner->delete(); } }<file_sep>/app/install.php <?php /* * Handles the database installation and configuration */ if($_SERVER['REQUEST_METHOD'] == 'POST') { extract(app('request')->getParams()); /** * Saves the submitted values (except passwords) in a session. * @param bool $ignore_lines deletes all lines */ function saveState($ignore_lines = false) { $params = app('request')->getParams(); $_SESSION['retry'] = [ 'admin_username' => $params['admin_username'] ?? '', 'lines' => isset($params['lines']) && !$ignore_lines ? $params['lines'] : '{}', 'km_per_round' => $params['km_per_round'] ?? '', 'display_total_rounds' => isset($params['display_total_rounds']), 'display_run_km' => isset($params['display_run_km']), 'display_left_to_go' => isset($params['display_left_to_go']) ]; } if(isset($admin_password, $admin_password_confirmation, $admin_username, $assistant_password, $assistant_password_confirmation, $lines, $km_per_round)) { $display_total_rounds = isset($display_total_rounds) ? 1 : 0; $display_run_km = isset($display_run_km) ? 1 : 0; $display_left_to_go = isset($display_left_to_go) ? 1 : 0; $display_total_donations = isset($display_total_donations) ? 1 : 0; if(!preg_match('/^[0-9]+((\.|\,)[0-9]{1,2})?$/', $km_per_round)) { saveState(); echo 'Km per round in wrong format. Examples: 1,5 / 1.5 / 1 / 2<br>'; echo '<a href="/">back</a>'; exit(); } if($admin_password !== $admin_password_confirmation || $assistant_password !== $assistant_password_confirmation) { saveState(); echo 'Passwords don\'t match. Please try again.<br>'; echo '<a href="/">back</a>'; exit(); } $lines = json_decode($lines); if(empty($lines) || !is_array($lines)) { saveState(true); echo 'You haven\'t added any routes. Please go back and add at least one.<br>'; echo '<a href="/">back</a>'; exit(); } // delete saved state if there is one unset($_SESSION['retry']); /** @var \PDO $db */ $db = app('database'); $installer_script = file_get_contents('../app/db.sql'); $db->exec($installer_script); db_prepared_query("INSERT INTO `users` VALUES (1, 'Assistant', :password)", [':password' => app('auth')->hash<PASSWORD>($<PASSWORD>)]); db_prepared_query("INSERT INTO `users` VALUES (2, :username, :password)", [ ':username' => htmlspecialchars($admin_username), ':password' => app('auth')-><PASSWORD>($<PASSWORD>) ]); // which stats to display db_prepared_query("INSERT INTO `stats` VALUES ('total_rounds', 0, :active, 3)", [':active' => $display_total_rounds]); db_prepared_query("INSERT INTO `stats` VALUES ('km_left_to_go', 0, :active, 2)", [':active' => $display_left_to_go]); db_prepared_query("INSERT INTO `stats` VALUES ('km_run', 0, :active, 1)", [':active' => $display_run_km]); db_prepared_query("INSERT INTO `stats` VALUES ('total_donations', 0, :active, 4)", [':active' => $display_total_donations]); // map settings db_prepared_query("INSERT INTO `settings` VALUES ('km_per_round', :km_per_round)", [':km_per_round' => $km_per_round]); /** * Calculates the great-circle distance between two points, with * the Vincenty formula. * @param float $latitudeFrom Latitude of start point in [deg decimal] * @param float $longitudeFrom Longitude of start point in [deg decimal] * @param float $latitudeTo Latitude of target point in [deg decimal] * @param float $longitudeTo Longitude of target point in [deg decimal] * @param float $earthRadius Mean earth radius in [m] * @return float Distance between points in [m] (same as earthRadius) */ function coordinateDistance( $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000) { // convert from degrees to radians $latFrom = deg2rad($latitudeFrom); $lonFrom = deg2rad($longitudeFrom); $latTo = deg2rad($latitudeTo); $lonTo = deg2rad($longitudeTo); $lonDelta = $lonTo - $lonFrom; $a = pow(cos($latTo) * sin($lonDelta), 2) + pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2); $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta); $angle = atan2(sqrt($a), $b); return $angle * $earthRadius; } $total_km = 0; for ($i=0; $i<count($lines); $i++) { $line = $lines[$i]; $distance = round(coordinateDistance( $line->lat_from, $line->long_from, $line->lat_to, $line->long_to) / 1000); // /1000 to get km instead of meters $total_km = $total_km < $distance ? $distance : $total_km; db_prepared_query("INSERT INTO `lines` VALUES (:id, :from_lat, :to_lat, :from_long, :to_long, :distance)", [ ':id' => $i+1, ':from_lat' => $line->lat_from, ':to_lat' => $line->lat_to, ':from_long' => $line->long_from, ':to_long' => $line->long_to, ':distance' => $distance ]); } db_prepared_query("INSERT INTO `settings` VALUES ('total_km', :total_km)", [':total_km' => $total_km]); // success app()->respond(redirect('/')); } else { echo 'Information is missing. Please try again.<br>'; echo '<a href="/">back</a>'; } } else { // Display form $output = view('install'); // Send the page app()->respond(app('response')); } ?><file_sep>/resources/lang/de/dynamic.php <?php return [ 'manage_class_x' => 'Klasse {class} bearbeiten', 'class_x' => 'Klasse {class}', 'log_class_x' => 'Log Klasse {class}', 'edit_runner_x' => 'Bearbeite Läufer: {name}', 'edit_class_x' => 'Bearbeite Klasse: {class}', 'edit_donor_x' => 'Bearbeite Spender: {name}', 'log_in_as_x' => 'Anmelden als {role}' ];<file_sep>/app/src/Controllers/DownloadData.php <?php namespace App\Controllers; use Slim\Http\Response; class DownloadData { private function setHeaders(Response $response, $filename) { // output headers so that the file is downloaded rather than displayed $response = $response->withHeader('Content-type','text/csv'); $response = $response->withHeader('Content-Disposition', 'attachment; filename="'.$filename.'.csv"'); // do not cache the file $response = $response->withHeader('Pragma', 'no-cache'); $response = $response->withHeader('Expires', '0'); return $response; } private function createCSV() { // create a file pointer connected to the output stream $file = fopen('php://output', 'w'); fwrite($file, chr(255) . chr(254)); fwrite($file, mb_convert_encoding("sep=;" . "\n", 'UTF-16LE')); return $file; } private function addCSV($file, $data) { $sep = ";"; $eol = "\n"; $csv = implode($sep, $data).$eol; $csv = mb_convert_encoding($csv, 'UTF-16LE'); fwrite($file, $csv); } public function downloadRunnerData($request, Response $response){ requires_permission('downloadData'); $response = $this->setHeaders($response, 'runner_data'); $groups = app('database')->query("SELECT id, name FROM groups ORDER BY name")->fetchAll(); $file = $this->createCSV(); foreach ($groups as $group) { $total_rounds = 0; $runner_data = db_prepared_query("SELECT name, total_rounds FROM runners WHERE class = :class ORDER BY name", [ ':class' => $group['id'] ])->fetchAll(); $this->addCSV($file, [trans('dynamic.class_x', ['class' => $group['name']])]); $this->addCSV($file, [trans('static.name'), trans('static.total_rounds')]); foreach ($runner_data as $runner) { $total_rounds += $runner['total_rounds']; $this->addCSV($file, [$runner['name'], $runner['total_rounds']]); } $this->addCSV($file, ['', $total_rounds]); $this->addCSV($file, ['', '']); } fclose($file); return $response; } public function downloadDonorData($request, Response $response){ requires_permission('downloadData'); $response = $this->setHeaders($response, 'donor_data'); $groups = app('database')->query("SELECT id, name FROM groups ORDER BY name")->fetchAll(); $file = $this->createCSV(); foreach ($groups as $group) { $runner_data = db_prepared_query("SELECT id, name, total_rounds FROM runners WHERE class = :class ORDER BY name", [ ':class' => $group['id'] ])->fetchAll(); $this->addCSV($file, [trans('dynamic.class_x', ['class' => $group['name']])]); $this->addCSV($file, []); $this->addCSV($file, [trans('static.runner_name'), trans('static.donor_name'), trans('static.total_donations'), trans('static.wants_receipt')]); foreach ($runner_data as $runner) { $donor_data = db_prepared_query("SELECT name, total_donation, wantsReceipt FROM donors WHERE runner_id = :runner_id ORDER BY name", [ ':runner_id' => $runner['id'] ])->fetchAll(); $this->addCSV($file, [$runner['name']]); foreach($donor_data as $donor) { $wants_receipt = $donor['wantsReceipt'] == 1 ? trans('static.yes') : trans('static.no'); $this->addCSV($file, ['', $donor['name'], $donor['total_donation'], $wants_receipt]); } } $this->addCSV($file, []); } fclose($file); return $response; } }<file_sep>/README.md **CharityRun** CharityRun is a software that was developed for the Gymnasium Raubling, which does a charity run every four years for aid organizations in Sri Lanka and Bolivia. The goal was to display the distance that was run in total by the school on a map, with the ultimate goal of reaching Sri Lanka or Bolivia. Over time, the software's tasks grew and it has become rich in features, such as also being responsible for calculating the overall donations per person, which was previously done by hand. The first version of the software was used at the charity run in 2014, where it managed roughly a thousand pupils and teachers. For all other runs, beginning as of 2018, the software was completely rebuilt from scratch, with real world experience from the first run. I decided to release it as open source software under the MIT license, to allow others to build upon this platform or simply use it for their own runs. **How to use** The software was built with four types of devices in mind: * A server, which holds the data and does the processing * A presenter, which is connected to a projector, showing the live map * Multiple smartphones used my the run's assistants, to enter new round information * A router to connect all devices In our case, the server and presenter were one single device, a laptop connected to the projector and router. As server software, you can use packages like XAMPP, which bundles all software needed to install and is already preconfigured (the only requirements are php7+ and apache as server software). As second step, unzip the software files into your server root. (If you are using XAMPP, it is the htdocs directory in your XAMPP installation folder.) The router has to have the ability to let devices communicate within the same network, please check that. AVM routers all seem to work fine, but you may have to test that first. After connecting all devices to the router (which is not connected to the internet!) it's the last step to find out the server's local IP address. Entering it into a browser on any other connected device should bring up the installation page (enter it the same way as you would normally enter google.com, but now it's something like 192.168.178.100). After you are finished setting everything up, assistants can log in via the login button (bottom right corner) on their devices. Phase one begins now, which includes entering all data into the software. After that, the administrator logs in and revokes the assistant's permission to enter or edit user data. This is to assure that no one accidentally deletes a runner or alters some other data during the run. The administrator can revoke the their permission by clicking on the red banner on his sidebar. From now on, only the administrator is able to edit or delete runners, donators and donations. _Until that point, the administrator account should not have been used._ Phase two is the actual run, assistants are able to add rounds to runners sequentially. This can either be done in real time or in a fixed interval, e.g. every 30 minutes. After the run has finished, the administrator is able to download the donator and runner data, which includes the rounds ran per runner and per group, the donators, and how much they donate, already calculated. **Download** You can download the latest release here: https://github.com/michaelspiss/charityrun/releases **License** MIT <file_sep>/app/src/Auth/AssistantPackage.php <?php namespace App\Auth; use Solution10\Auth\Package; /** * Class AssistantPackage * This set of permissions is granted to the Assistant. * The assistant has elevated permissions during the setup phase. * @see \App\Auth\ElevatedAssistantPackage * @package App\Auth */ class AssistantPackage extends Package { public function init() { $this ->precedence(5) ->permissions([ 'addDonor' => false, 'addRunner' => false, 'addClass' => false, 'viewManageHelp' => true, 'editClass' => false, 'editRunner' => false, 'editDonor' => false, 'viewEditHelp' => false, 'rollback' => false, 'editSettings' => false, 'addRounds' => true, 'removeAssistantEditPermission' => false, 'downloadData' => false ]); } }<file_sep>/public/js/map_config.js var map = AmCharts.makeChart( "map", { "type": "map", "theme": "light", "projection": "equirectangular", "mouseEnabled": false, "dragMap": false, "zoomOnDoubleClick": false, "dataLoader": { "url": "map/json" }, "zoomControl": { "zoomControlEnabled": false, "homeButtonEnabled": false }, "linesSettings": { "arc": -0.7, // this makes lines curved. Use value from -1 to 1 "color": "#000000", "alpha": 0.4, "thickness": 2, "bringForwardOnHover": false }, "areasSettings": { "unlistedAreasColor": "#8dd9ef", "unlistedAreasAlpha": 1 } }); map.ready = false; map.addListener("init", function () { map.ready = true; draw_progress_lines(); }); map.addListener("resized", function () { draw_progress_lines(); }); function draw_progress_lines () { if(!map.ready) { return; } var i = 1; while(map.getObjectById("progress_"+i) !== undefined) { var line = map.getObjectById("progress_"+i).lineSvg.node; var length = line.getTotalLength(); var percent_run = Math.min(100, km_run / map.getObjectById("progress_"+i).customData.distance * 100); var one_percent = length / 100; line.setAttribute("stroke-dasharray", length); line.setAttribute("stroke-dashoffset", length - (one_percent * percent_run)); i++; } }
4088968348ee6f8bdda9e641b34c7d43210c8bd7
[ "JavaScript", "SQL", "Markdown", "PHP" ]
30
JavaScript
michaelspiss/charityrun
349c511d1e4ddaa4d51cb71a2b55e967064be7fd
64b31bbc2edf768e31ecea39165ad11c01422500
refs/heads/master
<file_sep>library(xml2) library(dplyr) options(stringsAsFactors = FALSE) correctAuthorNames <- function(n){ n <- unlist(strsplit(n, '\\s+')) n[2] <- toupper(n[2]) o <- unlist(strsplit(n[1], '')) o[1] <- toupper(o[1]) o[2:length(o)] <- tolower(o[2:length(o)]) n[1] <- paste0(o, collapse = '') n <- paste(n, collapse = ' ') n <- sub('\\-\\S', paste0('-', toupper(stringr::str_match(n, '\\-(\\S)')[,2]), collapse = ''), n) n } authors <- trimws(scan('author.list', what = 'character', sep = '\n')) authors <- sapply(authors, correctAuthorNames) # Base URL to find publications in pubmed within the last 5 years (1825 days). url <- 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&datetype=pdat&reldate=1825&RetMax=500&term=' r <- bind_rows(apply(t(combn(authors, 2)), 1, function(x){ u <- paste0(url, x[1], '[Author]+AND+', x[2], '[Author]') o <- as_list(read_xml(paste0(readLines(URLencode(u)), collapse = '\n'))) browser() data.frame(author1 = x[1], author2 = x[2], pubs = unlist(o$eSearchResult$Count), pubIDs = paste0(unlist(o$eSearchResult$IdList), collapse = ',')) })) save.image(file = 'image.RData') o <- read.table('author.overrides', sep=',', header = FALSE) invisible(apply(o, 1, function(x){ i <- which(r$author1 == x['V1'] & r$author2 == x['V2']) if(length(i) > 0) r[i,]$pubs <<- as.integer(x['V3']) i <- which(r$author1 == x['V2'] & r$author2 == x['V1']) if(length(i) > 0)r[i,]$pubs <<- as.integer(x['V3']) })) r2 <- subset(r, r$pubs > 0) departments <- read.table('author.departments', sep = '\t', quote = '', strip.white = TRUE, comment.char = '') departments$V1 <- sapply(departments$V1, correctAuthorNames) departments$V2 <- factor(departments$V2) departments$V3 <- as.integer(departments$V2) write.table(departments, sep = '\t', file = 'r.departments.tsv', col.names = FALSE, row.names = FALSE, quote = FALSE) r2$edgeType <- 'coPub' r2$pubs <- as.integer(r2$pubs) write.table(r2[,c('author1', 'edgeType', 'author2', 'pubs')], file = 'r.tsv', sep = '\t', col.names = FALSE, row.names = FALSE, quote = FALSE) <file_sep>library(xml2) library(dplyr) library(RColorBrewer) library(grDevices) library(xlsx) options(stringsAsFactors = FALSE) authorList <- 'traingGrantAuthor.singleInitial.list' # (!) Make sure to update reldate paramter: # reldate: when reldate is set to an integer n, the search returns only those items that have a date specified by datetype within the last n days. url <- 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&datetype=pdat&reldate=14600&RetMax=500&term=' authors <- read.table(authorList, sep = ';', strip.white = TRUE, header = FALSE, quote = '') a <- t(combn(authors$V2, 2)) n <- 0 r <- bind_rows(apply(a, 1, function(x){ n <<- n + 1 message(paste(x[1], '::', x[2], ' ', n, '/', nrow(a))) u <- paste0(url, '(', x[1], '[Author] OR ', x[1], '[Investigator]) AND (', x[2], '[Author] OR ', x[2], '[Investigator])') o <- as_list(read_xml(paste0(readLines(URLencode(u)), collapse = '\n'))) Sys.sleep(1) data.frame(author1 = x[1], author2 = x[2], pubs = unlist(o$eSearchResult$Count), pubIDs = paste0(unlist(o$eSearchResult$IdList), collapse = ', ')) })) r$pubs <- as.integer(r$pubs) # Write our an Excel spreadsheet and create a data image. write.xlsx(r, file = 'coPubs.xlsx', col.names = TRUE, row.names = FALSE) save.image(file = 'image.RData') # Subset the data to include only authors with 1 or more co-publications r <- subset(r, r$pubs > 0) dplyr::select(r, -pubIDs) write.csv(dplyr::select(r, -pubIDs), 'network.csv', row.names = FALSE, quote = FALSE)
03bc109e421f4a31dfd4d5777533a75d3cba66f8
[ "R" ]
2
R
helixscript/coPublicationNetworks
6b9d09afe675cef854626ee01ab784a3d9a23a5b
4b222bf882abb9175b0a06c798b11db804c45693
refs/heads/master
<repo_name>cheeseplus/riak-cluster<file_sep>/metadata.rb name 'riak-cluster' maintainer '<NAME>' maintainer_email '<EMAIL>' license 'all_rights' description 'Installs/Configures riak-cluster' long_description 'Installs/Configures riak-cluster' version '0.1.0' depends 'riak' depends 'hostsfile' #depends 'chef-provisioning-vagrant-helper' <file_sep>/Rakefile task :default => [:up] task :up => :setup do sh('chef-client -z recipes/provision_vagrant.rb ') end task :setup do unless Dir.exist?('vendor') sh('berks install --quiet') Dir.mkdir('vendor') sh('berks vendor vendor/ --quiet') else sh('berks update --quiet') sh('berks vendor vendor/ --quiet') end end task :destroy do sh('chef-client -z recipes/destroy_vagrant.rb ') end task :cleanup => :destroy <file_sep>/recipes/destroy_vagrant.rb require 'chef/provisioning/vagrant_driver' base_dir = ::File.join(::File.dirname(__FILE__), '..') vms_dir = ::File.join(base_dir, 'vagrants') log "base dir is #{base_dir}, #{vms_dir}" directory vms_dir vagrant_cluster vms_dir with_chef_local_server :chef_repo_path => base_dir, :cookbook_path => [ File.join(base_dir, 'vendor') ], :port => 9010.upto(9999) machine_batch do action :destroy machines search(:node, '*:*').map { |n| n.name } end <file_sep>/recipes/provision_vagrant.rb # # Cookbook Name:: riak-cluster # Recipe:: default # # Copyright (c) 2015 The Authors, All Rights Reserved. require 'chef/provisioning/vagrant_driver' base_dir = ::File.join(::File.dirname(__FILE__), '..') vms_dir = ::File.join(base_dir, 'vagrants') log "base dir is #{base_dir}, #{vms_dir}" directory vms_dir vagrant_cluster vms_dir with_chef_local_server :chef_repo_path => base_dir, :cookbook_path => [ File.join(base_dir, 'vendor') ], :port => 9010.upto(9999) riak_nodes = 3 vagrant_config = <<-ENDCONFIG config.vm.network 'private_network', type: 'dhcp' config.vm.provider 'virtualbox' do |v| v.customize [ 'modifyvm', :id, '--memory', "1024", '--cpus', "2", '--natdnshostresolver1', 'on', '--usb', 'off', '--usbehci', 'off' ] end ENDCONFIG machine_batch 'precreate' do action [:converge] 1.upto(riak_nodes) do |i| machine "riak#{i}" do recipe 'riak-cluster::default' attribute 'riak-cluster', { use_interface: 'eth1' } machine_options vagrant_options: { 'vm.box' => 'opscode-ubuntu-14.04', 'vm.box_url' => 'http://opscode-vm-bento.s3.amazonaws.com/vagrant/virtualbox/opscode_ubuntu-14.04_chef-provisionerless.box', 'vm.hostname' => "riak#{i}.example.com" }, vagrant_config: vagrant_config end end end <file_sep>/attributes/default.rb default['riak-cluster']['use_interface'] = 'eth0' default['riak']['config']['listener']['http']['internal'] = "0.0.0.0:8098" default['riak']['config']['listener']['protobuf']['internal'] = "0.0.0.0:8087" <file_sep>/recipes/default.rb # first, install riak include_recipe 'riak::default' # then, populate /etc/hosts from search results def extract_cluster_ip(node_results) use_interface = node['riak-cluster']['use_interface'] node_results['network_interfaces'][use_interface]['addresses'] .select { |k,v| v['family'] == 'inet' }.keys end found_nodes = search(:node, "name:riak*", filter_result: { 'name' => [ 'name' ], 'fqdn' => [ 'fqdn' ], 'network_interfaces' => [ 'network', 'interfaces' ] } ) found_nodes.each do |nodedata| next if nodedata['network_interfaces'].nil? hostsfile_entry extract_cluster_ip(nodedata) do hostname nodedata['fqdn'] aliases [ nodedata['name'] ] unique true comment 'Chef riak-cluster cookbook' end end # Phase 3 - join the cluster # TODO - is this sane or do I need to specify one? master_server = found_nodes.first if master_server['name'] == node.name log "I am the master, do nothing" else log "Joining the Riak cluster, talking to #{master_server['fqdn']}" execute 'Riak cluster join' do command "riak-admin cluster join riak@#{master_server['fqdn']}" action :run notifies :run, 'execute[Riak cluster plan]', :immediately not_if "riak-admin status |grep ring_members | grep #{master_server['fqdn']}" end execute 'Riak cluster plan' do command 'riak-admin cluster plan' action :nothing notifies :run, 'execute[Riak cluster commit]', :immediately end execute 'Riak cluster commit' do command 'riak-admin cluster commit' action :nothing end end <file_sep>/Berksfile source 'https://supermarket.chef.io' metadata cookbook 'riak', '~> 3.1' cookbook 'pkg_add', github: 'wanelo-chef/pkg_add' # Future #cookbook 'chef-provisioning-vagrant-helper', path: '../chef-provisioning-vagrant-helper' <file_sep>/.chef/knife.rb current_dir = ::File.dirname(__FILE__) chef_repo_path ::File.join(current_dir, '..') cookbook_path ::File.join(current_dir, '..') node_name 'cluster-provisioner' file_cache_path File.join(current_dir, 'local-mode-cache', 'cache')
200473731257b6df818ab7fb3d9ad08df004335a
[ "Ruby" ]
8
Ruby
cheeseplus/riak-cluster
34c02e0266f6c24deedbfb92b8319bf155c0dda5
56d183aabdf189b7386c8a831c771d671e278b3b
refs/heads/master
<repo_name>07kamrul/Android<file_sep>/MyLibrary/app/src/main/java/com/asa/mylibrary/AllBooksActivity.java package com.asa.mylibrary; public class AllBooksActivity { } <file_sep>/ListViewandSpinner/app/src/main/java/com/asa/listviewandspinner/MainActivity.java package com.asa.listviewandspinner; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private Spinner studentsSpinner; private ListView citiesList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); citiesList = findViewById(R.id.citiesList); studentsSpinner = findViewById(R.id.studentsSpinner); spinnerViewMethod(studentsSpinner); listViewMethod(citiesList); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.settings_menu: Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT).show(); return true; case R.id.alarm_menu: Toast.makeText(this, "Alarm selected", Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } // For Spinner public void spinnerViewMethod(Spinner studentsSpinner) { final ArrayList<String> students = new ArrayList<>(); students.add("Zakaria"); students.add("Shariful"); students.add("Ariful"); students.add("kamrul"); students.add("Nabila"); students.add("Tushar"); ArrayAdapter<String> studentAdapter = new ArrayAdapter<>( this, android.R.layout.simple_spinner_dropdown_item, students ); studentsSpinner.setAdapter(studentAdapter); studentsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, students.get(position) + " selected", Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } // For ListView public void listViewMethod(ListView citiesList) { final ArrayList<String> cities = new ArrayList<>(); cities.add("Dhaka"); cities.add("New York"); cities.add("Panjab"); cities.add("Berlin"); cities.add("Moscow"); cities.add("London"); ArrayAdapter<String> citiesAdapter = new ArrayAdapter<>( this, android.R.layout.simple_list_item_1, cities ); citiesList.setAdapter(citiesAdapter); citiesList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, cities.get(position) + " selected", Toast.LENGTH_SHORT).show(); } }); } }<file_sep>/RegistrationForm/app/src/main/java/com/asa/registrationform/MainActivity.java package com.asa.registrationform; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onRegistrationBtnClick (View view){ TextView firstTextView = findViewById(R.id.textViewFirstName); TextView lastTextView = findViewById(R.id.textViewLastName); TextView emailTextView = findViewById(R.id.textViewEmail); TextView FullNameTextView = findViewById(R.id.textViewFullName); EditText editTextFirstName = findViewById(R.id.editTextFirstName); EditText editTextLastName = findViewById(R.id.editTextLastName); EditText editTextEmail = findViewById(R.id.editTextEmail); firstTextView.setText("First Name: "+editTextFirstName.getText().toString()); lastTextView.setText("Last Name: "+editTextLastName.getText().toString()); emailTextView.setText("Email: "+editTextEmail.getText().toString()); FullNameTextView.setText("Full Name: "+editTextFirstName.getText().toString()+ " "+ editTextLastName.getText().toString()); } }<file_sep>/UIBasic/app/src/main/java/com/asa/uibasic/MainActivity.java package com.asa.uibasic; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.SystemClock; import android.text.Editable; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private CheckBox checkBoxHarry, checkBoxMatrix, checkBoxJoker; private RadioGroup rgMaritalStatus; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkBoxHarry = findViewById(R.id.checkboxHarry); checkBoxMatrix = findViewById(R.id.checkboxMatrix); checkBoxJoker = findViewById(R.id.checkboxJoker); String harry = "Harry"; String matrix = "Matrix"; String joker = "Joker"; checkBoxMethod(checkBoxHarry, harry); checkBoxMethod(checkBoxMatrix, matrix); checkBoxMethod(checkBoxJoker, joker); rgMaritalStatus = findViewById(R.id.rgMaritalStatus); int checkedbutton = rgMaritalStatus.getCheckedRadioButtonId(); progressBar = findViewById(R.id.progressBar); Thread thread = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { progressBar.incrementProgressBy(10); SystemClock.sleep(500); } } }); thread.start(); radioButton(checkedbutton, progressBar); } // For check box public void checkBoxMethod(CheckBox checkBox, String name) { if (checkBox.isChecked()) { Toast.makeText(MainActivity.this, "You have watched " + name + ", Yay.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "You need to watch " + name + ".", Toast.LENGTH_SHORT).show(); } checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { Toast.makeText(MainActivity.this, "You have watched " + name + ", Yay.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "You need to watch " + name + ".", Toast.LENGTH_SHORT).show(); } } }); } // For Radio Button public void radioButton(int checkedbutton, ProgressBar progressBar) { switch (checkedbutton) { case R.id.rbMarried: Toast.makeText(MainActivity.this, "Married", Toast.LENGTH_SHORT).show(); break; case R.id.rbSingle: Toast.makeText(MainActivity.this, "Single", Toast.LENGTH_SHORT).show(); break; case R.id.rbInRel: Toast.makeText(MainActivity.this, "In a Relationship", Toast.LENGTH_SHORT).show(); break; default: break; } rgMaritalStatus.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rbMarried: Toast.makeText(MainActivity.this, "Married", Toast.LENGTH_SHORT).show(); break; case R.id.rbSingle: Toast.makeText(MainActivity.this, "Single", Toast.LENGTH_SHORT).show(); break; case R.id.rbInRel: Toast.makeText(MainActivity.this, "In a Relationship", Toast.LENGTH_SHORT).show(); break; default: break; } } }); } }
dc67db18630c5a259d6f46c0e63f9fe5cd9e4a7f
[ "Java" ]
4
Java
07kamrul/Android
e7a553e7d57203b543f0cf71c6ef65d177028cfc
d9258bc9f79924f4e5fd58ee305698bebebfaf8d
refs/heads/master
<file_sep>module.exports = function(grunt) { grunt.initConfig({ phantomas: { gruntSite : { options : { indexPath : './build/', options : {}, url : 'http://localhost:8100/bundles/external/res/performance/checkout.html', buildUi : true } } }, devperf: { options: { urls: [ 'http://localhost:8100/bundles/external/res/performance/checkout.html' ], numberOfRuns: 10, timeout: 120, openResults: true, resultsFolder: './devperf' } } }); grunt.loadNpmTasks('grunt-phantomas'); grunt.loadNpmTasks('grunt-devperf'); grunt.registerTask('default', ['phantomas']); };<file_sep>performance-test ================ This is a very basic setup for performance test by using the awesome tool [phantomas](https://github.com/macbre/phantomas). To get started, just clone this repo and do the following steps: ```sh $ npm install ``` modify the `Gruntfile.js` to point to the web site you want to test, and then run ```sh $ grunt ``` it has two plugins for generate report: `phantomas` and `devperf`.
b658906f355d134f7cccd5c884f79e60b94c830b
[ "JavaScript", "Markdown" ]
2
JavaScript
abruzzi/performance-test
ceccf45a1711069925148433a63f50d0a9adeac1
b352d509274d1f5ea7a45f7320058fd99ae7e23a
refs/heads/master
<file_sep>namespace MichalBialecki.com.TicketStore.Console.App_Start { using System.Linq; using SimpleInjector; public static class ContainerConfig { private static Container Container; public static void Init() { Container = new Container(); RegisterAllTypesWithConvention(); Container.Verify(); } public static TService GetInstance<TService>() where TService : class { return Container.GetInstance<TService>(); } private static void RegisterAllTypesWithConvention() { var typesWithInterfaces = typeof(Program).Assembly.GetExportedTypes() .Where(t => t.Namespace.StartsWith("MichalBialecki.com.TicketStore")) .Where(ts => ts.GetInterfaces().Any() && ts.IsClass).ToList(); var registrations = typesWithInterfaces.Select(ti => new { Service = ti.GetInterfaces().Single(), Implementation = ti }); foreach (var reg in registrations) { Container.Register(reg.Service, reg.Implementation, Lifestyle.Singleton); } } } }
4d160653ad16296bc1551ecbd957c29fc764fc83
[ "C#" ]
1
C#
ChrisGoodallDance/console-app-net-core
27e710a9e232f860718b5d696d20b4347c222003
f5ba0394e4a9d40d58bbea55dd550f07eab95e29
refs/heads/master
<file_sep># smoky As a webdeveloper, you've certainly already made a website that contained a lightbox. The concept itself comes from <NAME>, who created the original [lightbox script][1] many years ago (which is now written as a jQuery plugin). ```bash npm install smoky --save-dev ``` ## Why? - There are plenty of lightbox scripts out there, we both know that. But smoky is not an alternative to them. It's completely written in vanilla JS (ES 6) and the latest web technologies. - Most of the scripts use JS to animate, smoky does not. It uses GPU-powered CSS animations (they're much faster and don't insert awkward number-chains into your code). ## Sounds interesting? Give it a spin and you'll be convinced fastly! **Important:** As smoky is written on ES 6 (which will probaply only be fully released in the end of 2015), it's only possible to use it in conjunction with a ES-5-to-ES-6 compiler like [Babel][2] or [Traceur][3]. You can set up each of them pretty quickly, just take a look at their documentation! 1. After you've set up and compiled the source and implemented both the CSS and the JS parts of smoky, give it a try: ```js new Smoky( 'a.lightbox' ); ``` 2. Now every click on an element that matches the selector will be captured by smoky and trigger the opening of the lightbox containing the child image of the link element. If you want to make some additional configuration, just overwrite the existing one: ```js new Smoky( 'a.lightbox', { option: value }); ``` ## Options | Name | Description | Default&nbsp;value | | --------- | --------------------------------------------------------------------------------------------------------------- | ------------- | | escKey | If the visitor can use the escape key to close the lightbox window after opening it. | true | | arrowKeys | Whether the user can use the arrow keys on his keyboard to move to the next or previous image within a gallery. | true | | className | The class that will be used for every interaction with the DOM. | 'smoky' | | cache | Allow smoky to preload the next images within a gallery. | true | | caption | The name of the attribute of the link element that will be used to display the image caption. | 'title' | ## Methods | Name | Description | | ----------- | --------------------------------------------------------------------------------------------------------------------------- | | .move() | Change the image to a different one within a gallery. For example, '-1' will move to the previous and '+1' to the next one. | | .shut() | Close the lightbox window if it's already shown. | | .isOpened() | Will return *true* if the lightbox is open. | If you've found any bugs or have some feedback for me, make sure to [open an issue][4]! [1]: https://github.com/lokesh/lightbox2 [2]: https://babeljs.io [3]: https://github.com/google/traceur-compiler/wiki/Getting-Started [4]: https://github.com/leo/smoky/issues/new <file_sep>class Smoky { constructor(select, options) { if (typeof select === 'undefined') { return } this.config = { disableCache: false, className: false, escKey: true, arrowKeys: true, callback: function () {} } this.items = [].slice.call(document.querySelectorAll(select)) for (var i = 0; i < this.items.length; i++) { this.items[i].addEventListener( 'click', this.seekElement.bind(this) ) } document.documentElement.addEventListener('click', this.shut.bind(this)) var makers = { load: this.spawn.bind(this), keydown: this.tryKeys.bind(this) } this.setEvents(window, makers) this.config = Object.assign({}, this.config, options) } addImage(preload, target) { var span = this.span this.figure.appendChild(preload) if (target.hasAttribute('title')) { var title = document.createElement('figcaption') title.innerHTML = target.title this.figure.appendChild(title) } function timeout () { this.addClass(this.aside, 'loaded') } this.timeout = setTimeout(timeout.bind(this), 3000) } getPosition(ele) { var group = this.items var i = 0 for (var sibling in group) { if (group[sibling].nodeType && group[sibling] == ele) { var position = i break } i++ } return position } seekElement(event) { var figure = this.figure var target = event.currentTarget this.current = this.getPosition(target) if (!figure.innerHTML.includes('img')) { var preload = new Image() } else { var preload = figure.firstChild } preload.src = target.href + '#' + Math.floor(Math.random() * 1000) + 1 this.addClass(this.aside, 'open') var actions = { load: this.addImage(preload, target), click: event.stopPropagation() } this.setEvents(preload, actions) event.stopPropagation() event.preventDefault() } setEvents (ele, events) { for (var handle in events) { ele.addEventListener(handle, events[handle]) } } move (direction) { var move = this.items[this.current + direction].href this.figure.firstChild.src = move } spawn () { var helper = [ 'aside', 'figure', 'section', 'span', 'b' ] for (var key in helper) { var tag = helper[key] var key = parseInt(key) if (key == 3 || key == 4) { var mother = this[helper[key - 1]] } else { var mother = key ? this.aside : document.body } for ( var i = 0; i < (mother == this.span ? 4 : 1); i++) { this[tag] = mother.appendChild(document.createElement(tag)) } } this.aside.className = 'smoky' } clearBox () { var fig = this.figure while (fig.firstChild) { fig.removeChild(fig.firstChild) } } tryKeys (event) { if (!this.isOpened()) { return } switch (event.keyCode) { case 39: this.move(1) break case 37: this.move(-1) break case 27: this.config.escKey && this.shut() break default: return false } } addClass (who, title) { var attr = who.className who.className = attr ? attr + ' ' + title : title } shut () { var smoky = this.aside if (! smoky.className.includes('open')) { return } var style = window.getComputedStyle(smoky, null).getPropertyValue('transition-duration'), speed = style.substr(-4).replace('s', '') smoky.className = 'smoky' setTimeout( this.clearBox.bind(this), speed * 1000 ) this.current = null } isOpened() { if (this.aside.className.includes('open')) { return true } } }
2cf0420dd1c22f91c43022009bfaecbb7612d1be
[ "Markdown", "JavaScript" ]
2
Markdown
leo/smoky
352aee6ae3654b63073f834f141a92ee383bf8e0
9f3fab6370c762c847ce5eca67f5632b0248fd5e
refs/heads/master
<repo_name>SidNJIT03/Database-Management-Projects-using-MS-SQL-Server<file_sep>/SQLQuery - Ch 5.sql -- Question 1 SELECT playerID, [Full Name], [Career Batting Average], RANK() OVER (ORDER BY [Career Batting Average] DESC) AS BA_rank FROM ar998_Player_History WHERE [Career Batting Average] < 0.40 ORDER BY BA_rank -- Question 2 SELECT playerID, [Full Name], [Career Batting Average], DENSE_RANK() OVER (ORDER BY [Career Batting Average] DESC) AS BA_rank FROM ar998_Player_History WHERE [Career Batting Average] < 0.40 ORDER BY BA_rank -- Question 3 SELECT playerID, [Full Name], [Last Played], [Career Batting Average], RANK() OVER (PARTITION BY [Last Played] ORDER BY [Career Batting Average] DESC) AS BA_rank FROM ar998_Player_History WHERE [Career Batting Average] > 0.00 AND [Career Batting Average] < 0.40 ORDER BY [Last Played] DESC -- Question 4 SELECT playerID, [Full Name], [Last Played], [Career Batting Average], NTILE(4) OVER (PARTITION BY [Last Played] ORDER BY [Career Batting Average] DESC) AS Ntile FROM ar998_Player_History WHERE [Career Batting Average] > 0.00 AND [Career Batting Average] < 0.40 ORDER BY [Last Played] DESC -- Question 5 SELECT A.teamID, A.yearID, Avg_Salary, AVG(Avg_Salary) OVER (PARTITION BY A.teamID ORDER BY A.teamID, A.yearID ROWS between 3 PRECEDING and 1 FOLLOWING) as Windowed_Salary FROM Salaries, (SELECT teamID, yearID, AVG(salary) AS Avg_Salary FROM Salaries GROUP BY teamID, yearID) A WHERE Salaries.teamID = A.teamID and Salaries.yearID = A.yearID GROUP BY A.teamID, A.yearID, Avg_Salary ORDER BY teamID, yearID -- Question 6 SELECT A.teamID, People.playerid, (nameGiven + ' (' + nameFirst + ') ' + nameLast) AS [Full Name], [Total Hits], [Total At Bats], [Batting Avg], RANK() OVER (PARTITION BY A.teamID ORDER BY [Batting Avg] DESC) AS Team_Batting_rank, RANK() OVER (ORDER BY [Batting Avg] DESC) AS All_Batting_rank FROM People, (SELECT playerID, teamID, SUM(H) AS [Total Hits], SUM(AB) AS [Total At Bats], (CONVERT(DECIMAL(5,4),SUM(H)*1.0/SUM(AB))) AS [Batting Avg] FROM Batting GROUP BY teamID, playerID HAVING SUM(AB)>0 and SUM(H)>=150) A WHERE People.playerID = A.playerID ORDER BY A.teamID, Team_Batting_rank <file_sep>/README.md # Database-Management-Projects-using-MS-SQL-Server
6651fa16cb45674cc4160cff130e29af0c540405
[ "Markdown", "SQL" ]
2
SQL
SidNJIT03/Database-Management-Projects-using-MS-SQL-Server
2c9e16bf139ea240608278ddd6d890c83023c1cb
58016d4b75c68db84881a6c32a3fc58dda8d783a
refs/heads/master
<file_sep># .net-lab1 - Buhos Teodora <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace Lab1._1.Models { public class Student { [Key] public int Id { get; set; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } [Required] [StringLength(13)] public string Cnp { get; set; } public string Course { get; set; } [Range(0,10)] public int Grade { get; set; } public DateTime AddedAt { get; set; } } }
faeceaf52c417a88df09af08eea0762a1aa26ce8
[ "Markdown", "C#" ]
2
Markdown
ChaneLaForet/dotnet-lab1
0976dc1cb68bd3a1224eef2010f3c8c55e1acc5a
dec15fe2a2ffc0556726fb7a4a80b34e644a51a8
refs/heads/master
<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var recurringSavingSchema = new Schema({ userId: { type: Schema.ObjectId, ref: 'Users', required: true }, amount: { type: Number, default: 0 , required: true }, modeOfPayment: { type: String, }, savingsMode: { type: String, default:'continousSavings' }, amountPerDeposit: { type: Number, default: 0 , }, amountDeposited: { type: Number, default: 0 , }, balance: { type: Number, default: 0 , }, paymentDate: { type: Date, default: new Date() }, paymentStatus: { type: String, }, duration: { type: Number, default: 12, required: true }, interest: { type: String, default: 0 }, accumulatedInterest : { type: Number, default: 0 }, amountExpected: { type: Number, default: 0 }, savingsPlan: { type: String, required: true, }, paymentDuration: { type: String, }, nextDateOfdeposit: { type: Date, }, dueDateForWithdrawal: { type: Date, }, withdrawalDate: { type: Date, }, depositStatus:{ type:String, }, amountWithdraw: { type: Number, default: 0.00, }, withdrawalStatus: { type: Boolean, default: false }, },{ collection: 'recurringSavings', timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }); const RecurringSavings = mongoose.model('recurringSaving', recurringSavingSchema); module.exports = RecurringSavings;<file_sep>angular.module('mainApp') .factory('dashboardService', ['$http', function ($http) { let factory = {}; factory.listSavingsHistory = async function (userId) { let url = `http://localhost:3000/saves/list/${userId}` var savings = {}; await $http.get(url).then(function (response) { savings = response.data.savings; }) return savings; } //on payment change payment status to true factory.updatePaidAmount = async function (saveId) { var updateObject = { saveId: saveId } let url = `http://localhost:3000/saves/updatePaymentStatus`; await $http.post(url, updateObject).then(function (response) { alert(response.data.message); }) } return factory } ])<file_sep>angular.module('mainApp') .controller('logoutController', ['$scope', '$cookies', '$state', 'AuthService', function ($scope, $cookies, $state, AuthService) { $scope.logout = function () { var details = $cookies.getObject('details'); var id = details.userId AuthService.logout(id).then( async function () { $state.go('login'); }); //destroying cookies with the object returned from service $cookies.remove('details'); } } ])<file_sep>// const UsersModel = require('../models/users'); const recurringSavingsModel = require('../models/recurringSavings'); const recurringPaymentModel = require('../models/payment') const moment = require('moment'); moment().format(); var cron = require('node-cron'); //function to display a users by userId function List(req, res) { var userId = req.params.userId; recurringSavingsModel.find({ userId: req.params.userId }, (err, savings) => { if (err) { return res.json({ 'status': false, 'message': 'An Error Occured' }) } if (!savings) { return res.status(200).send({ 'status': false, 'message': 'You do not have any savings.' }) } if (savings) { if (savings.length >= 1) { savings.forEach((savings, element) => { if (savings.duration <= 12) { savings.interest = '5%' } if (savings.duration > 12) { savings.interest = '7%' } if (savings.withdrawalStatus == false && savings.amountDeposited != 0) { amount = parseInt(savings.amount) paymentDate = moment(savings.paymentDate); dueDateForWithdrawal = moment(savings.dueDateForWithdrawal); amountDeposited = parseInt(savings.amountDeposited); amountExpected = parseInt(savings.amountExpected); //calculating days of saving totalSavingDays = dueDateForWithdrawal.diff(paymentDate, 'days') var totalInterest; //number of days money has been invested so far numOfDays = moment().diff(paymentDate, 'days'); if (savings.interest == "5%") { totalInterest = (amountDeposited * 0.05) } if (savings.interest == "7%") { totalInterest = (amountDeposited * 0.07) } //calculate daily interest by dividing total interest with total days calcInterest = (totalInterest / totalSavingDays) * numOfDays; accumulatedInterest = (amountDeposited + calcInterest).toFixed(2); savings.accumulatedInterest = accumulatedInterest; //for indicating full payment if (amount == amountDeposited) { savings.depositStatus = "fully paid" savings.paymentStatus = "fully paid" } else { savings.depositStatus = "payment incomplete" savings.paymentStatus = "payment savings up-to-date" } } }); } } return res.status(200).send({ 'status': true, 'message': 'Your savings history', 'savings': savings }) }) }; //function to create a new plan function makePayment(req, res) { paymentObject = { saveId: req.body.saveId, } recurringPaymentModel.save((err, paymentMade) => { if (err) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: null }) } return res.status(201).json({ 'status': true, 'message': 'You have successfully made your continous payment', 'payments': paymentMade }); }) } function createPlanRecurring(req, res) { var planCreationObject = { userId: req.body.userId, amount: Number(req.body.amount), modeOfPayment: req.body.modeOfPayment, amountPerDeposit: Number(req.body.amountPerDeposit), amountDeposited: Number(req.body.amountDeposited), savingsPlan: req.body.savingsPlan, duration: req.body.duration, }; //payment above 2,000,000 not allowed if (planCreationObject.amount > 2000000) { return res.json({ 'message': 'You can not transfer more than 2 million, Visit the nearest Riby bank' }); } //Recurring cannot be less than 5000 if (planCreationObject.amount < 5000) { return res.json({ 'message': 'Recurring savings cannot be less than 5000, apply with fixed savings!' }); } //Saving's duration must be greter than 6 months if (planCreationObject.duration < 6) { return res.json({ 'message': 'Duration must be greater than 6 months' }); } else { //calculating duration daily if (planCreationObject.modeOfPayment == "daily") { if (planCreationObject.amountPerDeposit == 0) { paymentDurationInMonth = 0 } if (planCreationObject.amountPerDeposit > 0) { var calcPaymentDuration = (planCreationObject.amount / planCreationObject.amountPerDeposit) planCreationObject.paymentDuration = Math.round(calcPaymentDuration) + "months" var paymentDurationInMonth = Math.round(calcPaymentDuration) } //savings duration must be greater than payment duration if (planCreationObject.duration < paymentDurationInMonth) { return res.json({ 'message': 'Your savings duration cannot be less than your payment duration' }); } //calculating date for repayment var durationVal = parseInt(planCreationObject.duration); var payBackDate = moment().add('months', durationVal) planCreationObject.dueDateForWithdrawal = payBackDate; //calculating balance planCreationObject.balance = planCreationObject.amount - planCreationObject.amountDeposited; var amount = planCreationObject.amount; var amountDeposited = planCreationObject.amountDeposited if (amount > amountDeposited) { planCreationObject.depositStatus = "payment incomplete"; planCreationObject.paymentStatus = "payment up-to-date" planCreationObject.amountDeposited = planCreationObject.amountDeposited; } else { planCreationObject.depositStatus == "fully paid"; planCreationObject.paymentStatus = "fully paid" } //calculating interest //interest for saving for less than or equal to 1year = 5% var amount = Number(planCreationObject.amount); if (durationVal <= 12) { var calcInterest = Math.round(amount * 0.05 * durationVal); planCreationObject.interest = "5%", planCreationObject.amountExpected = (calcInterest + amount).toFixed(2); } //When duration is more than 12 months (1 year) interest rate= 7% else if (durationVal > 12) { var calcInterest = Math.round(amount * 0.07 * durationVal); planCreationObject.interest = "7%", planCreationObject.amountExpected = (calcInterest + amount).toFixed(2); } //checking for next paymentDate and sending warning var previousPay = planCreationObject.amountDeposited; //comparing date to warn if there is no payment dateToday = moment(); //calculating the next date deposit nextDepositDate = moment().add('days', 1) planCreationObject.nextDateOfdeposit = nextDepositDate; } //calculating duration weekly if (planCreationObject.modeOfPayment == "weeks") { if (planCreationObject.amountPerDeposit == 0) { paymentDurationInMonth = 0 } if (planCreationObject.amountPerDeposit > 0) { var calcPaymentDuration = (planCreationObject.amount / planCreationObject.amountPerDeposit) planCreationObject.paymentDuration = Math.round(calcPaymentDuration) + "months" var paymentDurationInMonth = Math.round(calcPaymentDuration) } //savings duration must be greater than payment duration if (planCreationObject.duration < paymentDurationInMonth) { return res.json({ 'message': 'Your savings duration cannot be less than your payment duration' }); } //calculating date for repayment var durationVal = parseInt(planCreationObject.duration); var payBackDate = moment().add('months', durationVal) planCreationObject.dueDateForWithdrawal = payBackDate; //calculating balance planCreationObject.balance = planCreationObject.amount - planCreationObject.amountDeposited; var amount = planCreationObject.amount; var amountDeposited = planCreationObject.amountDeposited if (amount > amountDeposited) { planCreationObject.depositStatus = "payment incomplete"; planCreationObject.paymentStatus = "payment savings up-to-date" planCreationObject.amountDeposited = planCreationObject.amountDeposited; } else { planCreationObject.depositStatus == "fully paid"; planCreationObject.paymentStatus = "fully paid" } //calculating interest //interest for saving for less than or equal to 1year = 5% var amount = Number(planCreationObject.amount); if (durationVal <= 12) { var calcInterest = Math.round(amount * 0.05 * durationVal); planCreationObject.interest = "5%", planCreationObject.amountExpected = (calcInterest + amount).toFixed(2); } //When duration is more than 12 months (1 year) interest rate= 7% else if (durationVal > 12) { var calcInterest = Math.round(amount * 0.07 * durationVal); planCreationObject.interest = "7%", planCreationObject.amountExpected = (calcInterest + amount).toFixed(2); } //checking for next paymentDate and sending warning var previousPay = planCreationObject.amountDeposited; //comparing date to warn if there is no payment dateToday = moment(); //calculating the next date deposit nextDepositDate = moment().add('weeks', 1) planCreationObject.nextDateOfdeposit = nextDepositDate; } //Calculation for months if (planCreationObject.modeOfPayment == "months") { if (planCreationObject.amountPerDeposit == 0) { paymentDurationInMonth = 0 } if (planCreationObject.amountPerDeposit > 0) { var calcPaymentDuration = (planCreationObject.amount / planCreationObject.amountPerDeposit) planCreationObject.paymentDuration = Math.round(calcPaymentDuration) + "months" var paymentDurationInMonth = Math.round(calcPaymentDuration) } //savings duration must be greater than payment duration if (planCreationObject.duration < paymentDurationInMonth) { return res.json({ 'message': 'Your savings duration cannot be less than your payment duration' }); } //calculating date for repayment var durationVal = parseInt(planCreationObject.duration); var payBackDate = moment().add('months', durationVal) planCreationObject.dueDateForWithdrawal = payBackDate; //calculating balance planCreationObject.balance = planCreationObject.amount - planCreationObject.amountDeposited; var amount = planCreationObject.amount; var amountDeposited = planCreationObject.amountDeposited if (amount > amountDeposited) { planCreationObject.depositStatus = "payment incomplete"; planCreationObject.paymentStatus = "payment savings up-to-date" planCreationObject.amountDeposited = planCreationObject.amountDeposited; } else { planCreationObject.depositStatus == "fully paid"; planCreationObject.paymentStatus = "fully paid" } //calculating interest //interest for saving for less than or equal to 1year = 5% var amount = Number(planCreationObject.amount); if (durationVal <= 12) { var calcInterest = Math.round(amount * 0.05 * durationVal); planCreationObject.interest = "5%", planCreationObject.amountExpected = (calcInterest + amount).toFixed(2); } //When duration is more than 12 months (1 year) interest rate= 7% else if (durationVal > 12) { var calcInterest = Math.round(amount * 0.07 * durationVal); planCreationObject.interest = "7%", planCreationObject.amountExpected = (calcInterest + amount).toFixed(2); } //checking for next paymentDate and sending warning var previousPay = planCreationObject.amountDeposited; //comparing date to warn if there is no payment dateToday = moment() //calculating the next date deposit nextDepositDate = moment().add('months', 1) planCreationObject.nextDateOfdeposit = nextDepositDate; } //Calculation for years if (planCreationObject.modeOfPayment == "years") { if (planCreationObject.amountPerDeposit == 0) { paymentDurationInMonth = 0 } if (planCreationObject.amountPerDeposit > 0) { var calcPaymentDuration = (planCreationObject.amount / planCreationObject.amountPerDeposit) planCreationObject.paymentDuration = Math.round(calcPaymentDuration) + "months" var paymentDurationInMonth = Math.round(calcPaymentDuration) } //savings duration must be greater than payment duration if (planCreationObject.duration < paymentDurationInMonth) { return res.json({ 'message': 'Your savings duration cannot be less than your payment duration' }); } //calculating date for repayment var durationVal = parseInt(planCreationObject.duration / 12); var payBackDate = moment().add('years', durationVal) planCreationObject.dueDateForWithdrawal = payBackDate; //calculating balance planCreationObject.balance = planCreationObject.amount - planCreationObject.amountDeposited; var amount = planCreationObject.amount; var amountDeposited = planCreationObject.amountDeposited; if (amount > amountDeposited) { planCreationObject.depositStatus = "payment incomplete"; planCreationObject.paymentStatus = "payment savings up-to-date" planCreationObject.amountDeposited = planCreationObject.amountDeposited; } else { planCreationObject.depositStatus == "fully paid"; planCreationObject.paymentStatus = "fully paid" } //calculating interest //interest for saving for less than or equal to 1year = 5% var amount = Number(planCreationObject.amount); if (durationVal <= 12) { var calcInterest = Math.round(amount * 0.05 * durationVal); planCreationObject.interest = "5%", planCreationObject.amountExpected = (calcInterest + amount).toFixed(2); } //When duration is more than 12 months (1 year) interest rate= 7% else if (durationVal > 12) { var calcInterest = Math.round(amount * 0.07 * durationVal); planCreationObject.interest = "7%", planCreationObject.amountExpected = (calcInterest + amount).toFixed(2); } //checking for next paymentDate and sending warning var previousPay = planCreationObject.amountDeposited; //comparing date to warn if there is no payment dateToday = moment() //calculating the next date deposit nextDepositDate = moment().add('years', 1) planCreationObject.nextDateOfdeposit = nextDepositDate; } (new recurringSavingsModel(planCreationObject)).save((err, newSavings) => { if (err) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: err }) } return res.status(201).json({ 'status': true, 'message': 'You have created a new savings plan', 'savings': newSavings }); }) } } //adding on subsequent payment function updateTotalDeposit(req, res) { var saveId = req.body.saveId; paymentObject = { saveId: req.body.saveId } recurringSavingsModel.findById(req.body.saveId, (err, recurringPayment) => { if (err) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: null }) } amount = parseInt(recurringPayment.amount) modeOfPayment = recurringPayment.modeOfPayment previousDate = recurringPayment.nextDateOfdeposit amountDeposited = parseInt(recurringPayment.amountDeposited) amountPerDeposit = parseInt(recurringPayment.amountPerDeposit) balance = parseInt(recurringPayment.amountPerDeposit) modeOfPayment = recurringPayment.modeOfPayment recurringPayment.amountDeposited = amountPerDeposit + amountDeposited recurringPayment.balance = amount - parseInt(recurringPayment.amountDeposited) recurringPayment.nextDateOfdeposit = moment(previousDate, "YYYY-MM-DD").add(1, modeOfPayment) if ((amount < amountDeposited) && (moment() >= previousDate) && (newAmountPaid == 0)) { recurringPayment.depositStatus = "payment incomplete" newAmountPaid = recurringPayment.amountDeposited - amountDeposited recurringPayment.paymentStatus = "pending payment"; } if (balance == 0) { recurringPayment.depositStatus = "fully paid"; recurringPayment.paymentStatus = "fully paid"; } if(parseInt(recurringPayment.balance) < 0){ recurringPayment.balance = 0 } recurringPayment.save((err, recurringPaymentSaved) => { if (err) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: null }) } var payment = new recurringPaymentModel(paymentObject); recurringPayment.save((err, paymentObject) => { if (err) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: null }) } payment.save((err, paymentMade) => { if (err) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: null }) } return res.status(201).json({ 'status': true, 'message': 'You have successfully made your continous payment', 'payments': paymentMade }); }) }) }) }) } //to withdraw function withdraw(req, res) { var saveId = req.body.saveId; var status = req.body.status; recurringSavingsModel.findById(saveId, (error, savings) => { if (error) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: null }) } if (savings.withdrawalStatus == true) { return res.status(400).json({ 'status': false, 'message': 'Insufficient balance, you have withdrawn your savings' }) } if (status == "true") { savings.withdrawalDate = new Date(); savings.withdrawalStatus = "true"; savings.amountWithdraw = savings.amount; savings.amountWithdraw = savings.amountExpected; } if (status == "false") { savings.withdrawalDate = new Date(); savings.interest = 0; savings.amountWithdraw = savings.amount; savings.withdrawalStatus = "true"; } savings.save((err, saved) => { if (err) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: err }) } return res.status(201).json({ 'status': true, 'message': 'You have successfully withdrawn #' + saved.amountWithdraw + ' from your account, Your interest has been deducted', 'savings': saved }); }) }); } //to list payment details in recurring payment... //populating withdrawal's board function paymentList(req, res) { var saveId = req.params.saveId; var amountPerDeposit = req.params.amountPerDeposit; recurringPaymentModel.find({ saveId: req.params.saveId, amountPerDeposit: req.params.amountPerDeposit }, (err, paymentList) => { if (err) { return res.json({ 'status': false, 'message': 'An Error Occured' }) } else if (!paymentList) { return res.json({ 'status': false, 'message': 'You do not have any savings.' }) } else { return res.json({ 'status': true, 'message': 'Your savings history', 'savings': paymentList }) } }) }; module.exports = { List: List, createPlanRecurring: createPlanRecurring, withdraw: withdraw, updateTotalDeposit: updateTotalDeposit, paymentList: paymentList }<file_sep>angular.module('mainApp') .factory('editProfileService', ['$http', function ($http) { let factory = {}; factory.editUserProfile = async function (updateUserDetails, userId) { var userEditObject = { email: updateUserDetails.email, phoneNumber: updateUserDetails.phoneNumber, accountNumber: updateUserDetails.accountNumber, bankName: updateUserDetails.bankName } let url = `http://localhost:3000/users/update/${userId}` var userDetails = {}; await $http.post(url, userEditObject).then(function (response) { if (response.data.status == true) { userDetails = response.data.user; var userId = userDetails.userId; var account_number = userDetails.accountNumber; var bankName = userDetails.bankName; var account_bank = userDetails.userId //getting the bank_name codes var bankCode = function (bankName) { if (bankName == "ACCESS BANK NIGERIA") { return account_bank = "044" } if (bankName == "ACCESS MOBILE") { return account_bank = "323" } if (bankName == "AFRIBANK NIGERIA PLC") { return account_bank = "014" } if (bankName == "Aso Savings and Loans") { return account_bank = "401" } if (bankName == "DIAMOND BANK PLC") { return account_bank = "063" } if (bankName == "Ecobank Mobile") { return account_bank = "307" } if (bankName == "ECOBANK NIGERIA PLC") { return account_bank = "050" } if (bankName == "ENTERPRISE BANK LIMITED") { return account_bank = "084" } if (bankName == "FBN MOBILE") { return account_bank = "309" } if (bankName == "FIDELITY BANK PLC") { return account_bank = "070" } if (bankName == "FIRST BANK PLC") { return account_bank = "011" } if (bankName == "FIRST CITY MONUMENT BANK PLC") { return account_bank = "214" } if (bankName == "GTBank Mobile Money") { return account_bank = "315" } if (bankName == "GTBANK PLC") { return account_bank = "058" } if (bankName == "HERITAGE BANK") { return account_bank = "030" } if (bankName == "KEYSTONE BANK PLC") { return account_bank = "082" } if (bankName == "Parkway") { return account_bank = "311" } if (bankName == "PAYCOM") { return account_bank = "305" } if (bankName == "SKYE BANK PLC") { return account_bank = "076" } if (bankName == "STANBIC IBTC BANK PLC") { return account_bank = "221" } if (bankName == "Stanbic Mobile") { return account_bank = "304" } if (bankName == "STANDARD CHARTERED BANK NIGERIA LIMITED") { return account_bank = "068" } if (bankName == "STERLING BANK PLC") { return account_bank = "232" } if (bankName == "UNION BANK OF NIGERIA PLC") { return account_bank = "032" } if (bankName == "UNITED BANK FOR AFRICA PLC") { return account_bank = "033" } if (bankName == "UNITY BANK PLC") { return account_bank = "215" } if (bankName == "WEMA BANK PLC") { return account_bank = "035" } if (bankName == "ZENITH BANK PLC") { return account_bank = "057" } if (bankName == "ZENITH Mobile") { return account_bank = "322" } if (bankName == "Coronation Merchant Bank") { return account_bank = "599" } if (bankName == "FSDH Merchant Bank Limited") { return account_bank = "601" } if (bankName == "PARRALEX BANK") { return account_bank = "526" } } var account_bank = bankCode(bankName); var fetchTransferRecipients = { method: 'POST', url: 'https://ravesandboxapi.flutterwave.com/v2/gpx/transfers/beneficiaries/create', headers: { 'Content-Type': 'application/json' }, data: { "account_number": account_number, "account_bank": account_bank, "seckey": "FLWSECK-d56276b3a6526d0c11b4c9e1014268c1-X" } } $http.post(fetchTransferRecipients.url, fetchTransferRecipients.data).then(function (response) { }, function (Error) { console.log(Error); }); } else { alert(response.data.message); } }) return userDetails; } return factory; } ])<file_sep>angular.module('mainApp') .controller('viewDetailsController', ['$scope', 'viewDetailsService', '$state', '$cookies', 'result', function ($scope, viewDetailsService, $state, $cookies, result) { var details = $cookies.getObject('details'); $scope.name = details.name; //getting saveId, amountDeposited, amountPerDeposit from params $scope.saveId = $state.params.saveId; $scope.amountDeposited = $state.params.amountDeposited; $scope.amountPerDeposit = $state.params.amountPerDeposit; $scope.balance = $state.params.balance; var saveId = $cookies.put('saveId',$scope.saveId); $scope.savingsDetails = result; $scope.viewDetails = async function () { var saveId = $cookies.put('saveId',$scope.saveId); $scope.savingsDetails = await viewDetailsService.viewDetails(saveId) } } ])<file_sep>angular.directive('datepicker', function () { return { restrict: 'C', require: 'ngModel', link: function (scope, element, attrs, ngModelCtrl) { $(element).datepicker({ dateFormat: 'dd, MM, yy', onSelect: function (date) { scope.date = date; scope.$apply(); } }); } }; }).directive('restrictInput', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ctrl) { ctrl.$parsers.unshift(function (viewValue) { var options = scope.$eval(attr.restrictInput); if (!options.regex && options.type) { switch (options.type) { case 'digitsOnly': options.regex = '^[0-9]*$'; break; case 'lettersOnly': options.regex = '^[a-zA-Z]*$'; break; case 'lowercaseLettersOnly': options.regex = '^[a-z]*$'; break; case 'uppercaseLettersOnly': options.regex = '^[A-Z]*$'; break; case 'lettersAndDigitsOnly': options.regex = '^[a-zA-Z0-9]*$'; break; case 'validPhoneCharsOnly': options.regex = '^[0-9 ()/-]*$'; break; default: options.regex = ''; } } var reg = new RegExp(options.regex); if (reg.test(viewValue)) { //if valid view value, return it return viewValue; } else { //if not valid view value, use the model value (or empty string if that's also invalid) var overrideValue = (reg.test(ctrl.$modelValue) ? ctrl.$modelValue : ''); element.val(overrideValue); return overrideValue; } }); } }; });<file_sep>angular.module('mainApp') .controller('userProfileController', ['$scope', '$cookies', '$state', 'result', 'userProfileService', function ($scope, $cookies, $state, result, userProfileService) { var userId = $state.params.userId; $scope.userDetails = result; $scope.showUserProfile = async function (userId) { var details = $cookies.getObject('details', details); var userId = userId // $scope.userDetails = await userProfileService.showUserProfile(userId) } $scope.editUserProfile = async function (userId) { //var details = $cookies.getObject('details', details); var userId = userId; $state.go('editProfile', { userId }); }; } ])<file_sep>var express = require('express'); var logger = require('morgan'); var mongoose = require('mongoose'); const recurringSavingsRoute= require('./routes/recurringSavings') const usersRoute = require('./routes/users'); const savingsRoute = require('./routes/saves'); const cors = require('cors'); var app = express(); var mongooseConnectString = 'mongodb://localhost:27017/ribyProject' mongoose.connect(mongooseConnectString); mongoose.connection.on('connected', function(err) { console.log("Connected to DB using chain: " + mongooseConnectString); }); let bodyParser = require('body-parser'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(logger('dev')); app.use(cors({origin:"http://127.0.0.1:5500"})); app.all('/*', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); // res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With"); res.header("Access-Control-Allow-Methods", "GET, PUT, POST, HEAD"); return next(); }) // app.use(cors()); app.use('/users',usersRoute); app.use('/saves',savingsRoute); app.use('/recurringSavings',recurringSavingsRoute); app.listen(3000, ()=>{ console.log('Server running on port 3000'); }) // Setup a default catch-all route that sends back a welcome message in JSON format. // app.get('*', (req, res) => res.status(200).send({ // message: 'Welcome to Riby Saving App.', // })); module.exports = app; <file_sep>angular.module('mainApp') .controller('editProfileController', ['$scope', '$cookies', '$state', 'editProfileService', function ($scope, $cookies, $state, editProfileService) { var userId = $state.params.userId; //for resolve //$scope.userDetails = result; // console.log('from resolve', $scope.userDetails) $scope.editUserProfile = async function () { var Id = userId; $scope.userDetails = await editProfileService.editUserProfile($scope.updateUserDetails, Id); $state.go('userProfile', { userId }) } } ])<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var recurringPaymentSchema = new Schema({ saveId: { type: Schema.ObjectId, ref: 'recurringSavings', required: true }, paymentDate: { type: Date, default: new Date() }, },{ collection: 'recurringPayments', timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }); const RecurringPayments = mongoose.model('recurringPayment', recurringPaymentSchema); module.exports = RecurringPayments;<file_sep>angular.module('mainApp') .factory('recurringDashboardService', ['$http','$cookies', function ($http, $state, $cookies ) { let factory = {}; //list savings on Dashboard factory.listRecurringSavingsHistory = async function (userId) { let url = `http://localhost:3000/recurringSavings/list/${userId}` var savings = {}; await $http.get(url).then(function (response) { savings = response.data.savings; saveId = savings._id }) return savings; } //on payment for existing savings update amount deposited factory.updatePaidAmount = async function (saveId) { var updateObject = { saveId : saveId } let url = `http://localhost:3000/recurringSavings/updateTotalDeposit`; await $http.post(url, updateObject).then(function (response) { alert(response.data.message); }) } factory.viewDetails = async function (saveId) { var saveId = $cookies.get('saveId') let url = `http://localhost:3000/recurringSavings/listPayment/${saveId}` var savings = {}; await $http.get(url).then(function (response) { savings = response.data; }) return savings; } return factory } ])<file_sep>angular.module('mainApp') .factory('loginService', ['$http', '$state', '$rootScope','$cookies', function ($http, $state, $rootScope, $cookies) { let factory = {}; //url from backend *api for login* let url = 'http://localhost:3000/users/login'; factory.login = async function (user) { let usersDetails = {}; await $http.post(url, user).then(function (response) { if (response.data.status == true) { //response from the api //holding userId, name, token in usersDetails //to be passed as an object details in controllers usersDetails.userId = response.data.users._id; usersDetails.name = response.data.users.name; usersDetails.email = response.data.users.email; usersDetails.phoneNumber = response.data.users.phoneNumber; usersDetails.token = response.data.token; usersDetails.accountNumber = response.data.users.accountNumber; usersDetails.bankName = response.data.users.bankName; usersDetails.permission = response.data.users.permission; usersDetails.planType = response.data.users.planType; //setting cookies with the object returned from service $cookies.putObject('details', usersDetails); $state.go('dashboard'); } else { alert(response.data.message); } }) // return usersDetails; } return factory; } ])<file_sep>// register the interceptor as a service angular.module('mainApp') .factory('mainAppInterceptor', function ($q, $cookies) { return { // optional method 'request': function (config) { var details = $cookies.getObject('details'); if (details) { var token = details.token; //removing token from headers for creating recipient in flutterwave if (config.url == 'https://ravesandboxapi.flutterwave.com/v2/gpx/transfers/beneficiaries/create') { config.headers['Content-Type'] = 'application/json' } else { config.headers['x-access-token'] = token config.headers['Content-Type'] = 'application/json' } } return config; } } })<file_sep>angular.module('mainApp') .controller('listUserSavingsController', ['$scope','$state', 'listUserSavingsService','result', function ($scope, $state, listUserSavingsService, result) { $scope.name = $state.params.name ; var userId = $state.params.userId; $scope.savings = result; $scope.listUserSavings = async function (userId) { let userId = userId; // //$scope.savings = await listUserSavingsService.savingsList(userId) } } ])<file_sep>angular.module('mainApp') .factory('AuthService', ['$q', '$timeout', '$http', '$rootScope','$cookies', function ($q, $timeout, $http, $rootScope, $cookies) { // create user variable var details = $cookies.getObject('details'); // return available functions for use in the controllers return ({ isLoggedIn: isLoggedIn, logout: logout }); function isLoggedIn() { if (!details) { return false; } else { return true; } } async function logout(id) { let userId = id //create a new instance of a new deferred var deferred = $q.defer(); url = `localhost:3000/users/logout/${userId}` // send a get request to the server $http.get(url).then(function (response) { if (response.data.status == true) { deferred.resolve() }else { deferred.reject() } }) } } ]);<file_sep>angular.module('mainApp') .controller('recurringDashboardController', ['$scope', 'recurringDashboardService', 'viewDetailsService', '$state', '$cookies', 'result', function ($scope, recurringDashboardService, viewDetailsService, $state, $cookies, result) { var details = $cookies.getObject('details') $scope.userId = details.userId; $scope.name = details.name; $scope.email = details.email; $scope.phoneNumber = details.phoneNumber; $scope.permission = details.permission; phoneNumberFormatted = '+234' + parseInt($scope.phoneNumber); $scope.savings = result; $scope.savingsView = result; //counting number of plans that have pending payments save = result; var count = 0; for (i=0; i<save.length; i++) { if (save[i].balance > 0 && save[i].withdrawalStatus == false ) { count += 1; } $scope.pendingPayment = count; } $scope.payWithRave = function (savingsId, amountPerDeposit, balance) { let amountToDeposit; //avoid payment on completion if (balance == 0) { return alert('Payment completed'); } if (balance < amountPerDeposit){ amountPerDeposit = balance; } const API_publicKey = "<KEY>"; var x = getpaidSetup({ PBFPubKey: API_publicKey, customer_email: $scope.email, amount: amountPerDeposit, customer_phone: phoneNumberFormatted, currency: "NGN", payment_method: "both", txref: "rave-123456", meta: [{ metaname: "flightID", metavalue: "AP1234" }], onclose: function () {}, callback: function (response) { var txref = response.tx.txRef; // collect txRef returned and pass to a server page to complete status check. console.log("This is the response returned after a charge", response); if ( response.tx.chargeResponseCode == "00" || response.tx.chargeResponseCode == "0" ) { // redirect to a success page updatePaidAmount(savingsId); } else { // redirect to a failure page. alert('An error occurred'); } x.close(); // use this to close the modal immediately after payment. } }); } async function updatePaidAmount(savingsId) { await recurringDashboardService.updatePaidAmount(savingsId) $state.reload('recurringDashboard') } //for view deposit details $scope.viewDetails = async function (saveId, amountDeposited, amountPerDeposit, balance) { $cookies.put('saveId', saveId) $scope.amountDeposited = amountDeposited; $scope.amountPerDeposit = amountPerDeposit; $scope.balance = balance; $scope.savingsDetails = await viewDetailsService.viewDetails(saveId) } $scope.withdraw = function (save, withdrawalStatus, duePaymentDate, balance, planType, amountDeposited) { let status; console.log('@@@@@@@',save, withdrawalStatus, duePaymentDate, balance, planType, amountDeposited ) if (withdrawalStatus == true) { return $state.go('transactionClosed') } if (balance > 0) { alert(' You have not completed your payment'); return $state.reload('recurringDashboard') } //comparing date before withdrawal var date1 = new Date(duePaymentDate); var date2 = new Date(); var timeDiff = Math.abs(date2.valueOf() - date1.valueOf()); var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); if (date2 <= date1) { status = false; //$location.path(`/penaltyWithdrawal/${dueDateForWithdrawal}/${saveid}/${status}`) $state.go('penaltyWithdrawal', { save, duePaymentDate, withdrawalStatus, planType }) } if (date2 > date1) { status = true; $state.go('withdrawal', { save, duePaymentDate, withdrawalStatus, planType }) } }; } ])<file_sep>angular.module('mainApp') .factory('userProfileService', ['$http', function ($http) { let factory = {}; factory.showUserProfile = async function (userId) { let url = `http://localhost:3000/users/list/${userId}` var userDetails = {}; await $http.get(url).then(function (response) { userDetails = response.data; }) return userDetails; } return factory } ])<file_sep>var express = require('express'); var router = express.Router(); const recurringSavingsController = require('../controllers/recurringSavings.controllers'); router.get('/list/:userId', recurringSavingsController.List); router.post('/createplan', recurringSavingsController.createPlanRecurring); router.post('/withdraw', recurringSavingsController.withdraw); router.post('/updateTotalDeposit', recurringSavingsController.updateTotalDeposit); router.get('/listPayment/:saveId', recurringSavingsController.paymentList); // router.use(JWT_Verify.verifyToken); // router.put('/:id', UserController.UpdateProfile); module.exports = router;<file_sep>angular.module('mainApp') .factory('superAdminService', ['$http', function ($http) { let factory = {}; factory.newAdmin = async function(newAdminId){ newAdminIdObject = { newAdminId : newAdminId, } let url = `http://localhost:3000/users/updateToAdmin/${newAdminId}`; var admins = {}; await $http.post(url, newAdminIdObject).then(function(response){ admins = response.data }) return admins; } factory.changeToRegularUser = async function(newAdminId){ newUserObject = { newAdminId : newAdminId, } let url = `http://localhost:3000/users/changeAdminToUser/${newAdminId}`; var admins = {}; await $http.post(url, newUserObject).then(function(response){ admins = response.data }) return admins; } return factory; } ])<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var savingSchema = new Schema({ userId: { type: Schema.ObjectId, ref: 'Users', required: true }, amount: { type: Number, default: 0, required: true }, paymentStatus: { type: Boolean, default: false, required: true }, duration: { type: Number, default: 12, required: true }, interest: { type: String, default: 0 }, accumulatedInterest : { type: Number, default: 0 }, amountExpected: { type: Number, default: 0 }, savingsPlan: { type: String, required: true, }, paymentDate: { type: Date, default: new Date() }, dueDateForWithdrawal: { type: Date, }, withdrawalDate: { type: Date, // default: }, amountWithdraw: { type: Number, default: 0.00, }, withdrawalStatus: { type: Boolean, default: false }, }, { collection: 'savings', timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }); const Savings = mongoose.model('Saving', savingSchema); module.exports = Savings;<file_sep>angular.module('mainApp') .controller('loginController', ['$scope', 'loginService', '$cookies','$rootScope', function ($scope, loginService, $cookies, $rootScope) { $scope.login = async function () { //passing in users from login.html parameters loginService.login($scope.user); } //for showing error message $scope.showMessage = function (input) { var show = input.$invalid && (input.$dirty || input.$touched); return show; }; } ]) .directive('validPasswordC', function () { return { require: 'ngModel', link: function (scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function (viewValue, $scope) { var noMatch = viewValue != scope.loginForm.password.$viewValue ctrl.$setValidity('noMatch', !noMatch) }) } } }) .directive('restrictInput', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attr, ctrl) { ctrl.$parsers.unshift(function (viewValue) { var options = scope.$eval(attr.restrictInput); if (!options.regex && options.type) { switch (options.type) { case 'digitsOnly': options.regex = '^[0-9]*$'; break; case 'lettersOnly': options.regex = '^[a-zA-Z\s]*$'; break; case 'lowercaseLettersOnly': options.regex = '^[a-z]*$'; break; case 'uppercaseLettersOnly': options.regex = '^[A-Z]*$'; break; case 'lettersAndDigitsOnly': options.regex = '^[a-zA-Z0-9]*$'; break; case 'validPhoneCharsOnly': options.regex = '^[0-9 ()/-]*$'; break; default: options.regex = ''; } } var reg = new RegExp(options.regex); if (reg.test(viewValue)) { //if valid view value, return it return viewValue; } else { //if not valid view value, use the model value (or empty string if that's also invalid) var overrideValue = (reg.test(ctrl.$modelValue) ? ctrl.$modelValue : ''); element.val(overrideValue); return overrideValue; } }); } }; });<file_sep>var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, phoneNumber: { type: String, required: true, unique: true }, accountNumber: { type: String, }, bankName: { type: String, }, password: { type: String, required: true }, permission: { type: String, default: 'regularUser', enum: ['superAdmin', 'Admin', 'regularUser'] }, }, { collection: 'users', timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }); const Users = mongoose.model('User', userSchema); module.exports = Users;<file_sep>angular.module('mainApp') .factory('createPlanService', ['$http', '$state', function ($http, $state) { let factory = {}; factory.createPlan = function (userId, createPlanDetails) { let planDetails = {}; let url = 'http://localhost:3000/saves/createPlan'; var createPlanObject = { userId: userId, amount: createPlanDetails.amount, savingsPlan: createPlanDetails.savingsPlan, duration: createPlanDetails.duration, } $http.post(url, createPlanObject).then(function (response) { if (response.data.status) { $state.go('dashboard'); } var savings = response.data.savings; return alert(response.data.message); }); } factory.continuousSavingsCreatePlan = function (userId, continuousSavingsCreatePlanDetails) { let planDetails = {}; let url = 'http://localhost:3000/recurringSavings/createplan'; var continuousSavingsCreatePlanDetailsObject = { userId: userId, amount: continuousSavingsCreatePlanDetails.amount, modeOfPayment: continuousSavingsCreatePlanDetails.modeOfPayment, amountPerDeposit: continuousSavingsCreatePlanDetails.amountPerDeposit || 0, amountDeposited: continuousSavingsCreatePlanDetails.amountDeposited = 0, savingsPlan: continuousSavingsCreatePlanDetails.savingsPlan, duration: continuousSavingsCreatePlanDetails.duration, } $http.post(url, continuousSavingsCreatePlanDetailsObject).then(function (response) { if (response.data.status) { $state.go('recurringDashboard'); } var savings = response.data.savings; alert(response.data.message); }); } return factory; } ])<file_sep>angular.module('mainApp') .controller('viewAllUserController', ['$scope', 'viewAllUserService','superAdminService', '$state', '$cookies', 'result', function ($scope, viewAllUserService, superAdminService, $state, $cookies, result) { var details = $cookies.getObject('details') var userId = $state.params.userId; var permission = $state.params.permission; $scope.permission = details.permission; $scope.name = details.name; $scope.users = result; $scope.listAllUsers = async function (userId, permission) { var details = $cookies.getObject('details') var userId = details.userId; var permission = details.permission; // $scope.users = await viewAllUserService.listAllUsers( userId, permission ) } $scope.listUserSavings = async function (userlistId, name) { $state.go ('listUserSavings',{ userId:userlistId, name }) } $scope.newAdmin = async function (newAdminId) { $cookies.put( 'newAdminId', newAdminId); $scope.admins = await superAdminService.newAdmin(newAdminId); $state.reload('listAllUsers') } $scope.changeToRegularUser = async function (oldAdminId) { var oldAdminId = oldAdminId; //$cookies.put( 'newAdminId', newAdminId); $scope.admins = await superAdminService.changeToRegularUser(oldAdminId); $state.reload('listAllUsers') } } ])<file_sep>//Require nodemailer var nodemailer = require('nodemailer'); const recurringSavingsModel = require('../models/recurringSavings'); const recurringPaymentModel = require('../models/payment'); const userModel = require('../models/users'); const moment = require('moment'); moment().format(); var cron = require('node-cron'); // this email notification at 9pm cron.schedule('0 9 * * *', () => { console.log('node cron job running a task every minute'); emailsNotification(); }, { scheduled: true, timezone: "America/Sao_Paulo" }); function sendMail(mailOptions) { var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '<EMAIL>', pass: <PASSWORD>' } }); transporter.sendMail(mailOptions, function (error, info) { if (error) {} else { console.log('Email sent: ' + info.response); } }); } function registerEmailBody(bodyObject) { return ` <h3>Hello ${bodyObject.name},</h3> <p>Congratulations Your account have been created successfully</p> <p>Account Details<br/> Name: <span style="color:blue">${bodyObject.name}</span><br/> Email: <span style="color:blue">${bodyObject.email}</span><br/> Phone: <span style="color:blue">${bodyObject.phoneNumber}</span><br/> Token: <p style="color:blue" href="#">${bodyObject.token}</p><br/> </p> <p><a href="http://localhost:8000/">Visit Savers App by clicking on the link</a></p> ` } function updateProfileEmailBody(bodyObject) { return ` <h3>Hello ${bodyObject.name},</h3> <p>Do you want to update your profile</p> <p>Account Details<br/> Name: <span style="color:blue">${bodyObject.name}</span><br/> Email: <span style="color:blue">${bodyObject.email}</span><br/> Phone: <span style="color:blue">${bodyObject.phoneNumber}</span><br/> <button href="http://localhost:3000/updateProfile"> click to update profile</button> ` } function emailsNotification(req, res) { //if time is 9pm //check the next day of payment //if 3 -- 1 day send an email to remind //function to display a users savings by userId recurringSavingsModel .find({ "nextDateOfdeposit": { "$gte": moment(), "$lt": moment().add(2, 'days').format('MMM DD YYYY h:mm A'), } }, (error, notificaionlist) => { if (error) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: null }) } if (notificaionlist) { notificaionlist.forEach((notificaionlist, element) => { //get users details for the notification userId userId = notificaionlist.userId; userModel .findOne({ _id: userId }, (error, user) => { if (error) { return res.json({ 'status': false, 'message': 'An Error Occured', payload: null }) } if (user) { var notificaionlistObject = { name: user.name, email: user.email, phoneNumber: user.phoneNumber } sendMail({ from: '<EMAIL>', to: notificaionlistObject.email, subject: 'This is to kindly remind you that your payment date for recurring savings', html: registerEmailBody({ name: notificaionlistObject.name, email: notificaionlistObject.email, phoneNumber: notificaionlistObject.phoneNumber }) }) } }) }) } }) // if it is late already send a warning message if (moment()) { } } module.exports = { sendMail, registerEmailBody, updateProfileEmailBody, emailsNotification }<file_sep>var mainApps = angular.module("mainApp", [ 'ngMaterial', 'ngMessages', 'ui.router', 'ngCookies', 'angularUtils.directives.dirPagination' ]); mainApps.config(['$stateProvider', '$httpProvider', function ($stateProvider, $httpProvider) { $stateProvider .state('home', { url: '/home', templateUrl: './views/template.html', //controller: 'homeController' access: { restricted: false } }) .state('login', { url: '/login', templateUrl: './views/loginPage.html', controller: 'loginController', access: { restricted: false } }) .state('signUp', { url: '/signUp', templateUrl: './views/signUpPage.html', controller: 'signUpController', access: { restricted: false } }) .state('dashboard', { url: '/dashboard', resolve: { dashboardResolve: function (dashboardService, $cookies) { var details = $cookies.getObject('details'); userId = details.userId; return dashboardService.listSavingsHistory(userId); } }, templateUrl: './views/dashboardPage.html', controller: 'dashboardController', access: { restricted: true } }) .state('recurringDashboard', { url: '/recurringDashboard', resolve: { result: function (recurringDashboardService, $cookies) { var details = $cookies.getObject('details'); userId = details.userId; return recurringDashboardService.listRecurringSavingsHistory(userId); } }, templateUrl: './views/recurringDashboard.html', controller: 'recurringDashboardController', access: { restricted: true } }) .state('createPlan', { url: '/createplan', templateUrl: './views/createPlan.html', controller: 'createPlanController', access: { restricted: true } }) .state('withdrawal', { url: '/withdrawal/:duePaymentDate/:save/:withdrawalStatus/:planType', templateUrl: './views/withdrawal.html', controller: 'withdrawalController', access: { restricted: true } }) .state('penaltyWithdrawal', { url: '/penaltyWithdrawal/:duePaymentDate/:save/:withdrawalStatus/:planType', templateUrl: './views/penaltyWithdrawal.html', controller: 'withdrawalController', access: { restricted: true } }) .state('logout', { url: '/logout', templateUrl: './views/logout.html', controller: 'logoutController', access: { restricted: true } }) .state('transactionClosed', { url: '/transactionClosed', templateUrl: './views/transactionClosed.html', access: { restricted: true } }) .state('userProfile', { url: '/userProfile/:userId', resolve: { result: function (userProfileService, $cookies) { var details = $cookies.getObject('details'); userId = details.userId; return userProfileService.showUserProfile(userId) } }, templateUrl: './views/usersProfile.html', controller: 'userProfileController', access: { restricted: true } }) .state('listAllUsers', { url: '/listAllUsers/:userId/:permission', resolve: { result: function (viewAllUserService, $cookies) { var details = $cookies.getObject('details'); userId = details.userId; permission = details.permission; return viewAllUserService.listAllUsers(userId, permission) } }, templateUrl: './views/viewAllUserBoard.html', controller: 'viewAllUserController', access: { restricted: true } }) .state('listAdmin', { url: '/listAdmin/:userId/:permission', resolve: { result: function (viewAdminService, $cookies) { var details = $cookies.getObject('details'); userId = details.userId; permission = details.permission; return viewAdminService.listAdmin(userId, permission) } }, templateUrl: './views/viewAdminBoard.html', controller: 'viewAdminController', access: { restricted: true } }) .state('editProfile', { url: '/editProfile/:userId', templateUrl: './views/editProfile.html', controller: 'editProfileController', access: { restricted: true } }) .state('listUserSavings', { url: '/listUserSavings/:userId/:name', resolve: { result: function (listUserSavingsService) { return listUserSavingsService.savingsList(userId); } }, templateUrl: './views/dashboardPage.html', controller: 'listUserSavingsController', access: { restricted: true } }) // .state('contact', { // url: '/', // templateUrl: '/views/contact.html ', // controller: 'contactController', // controllerAs: 'vm', // }) .state('noRoute', { url: '*path', redirectTo: 'home', access: { restricted: false } }) $httpProvider.interceptors.push('mainAppInterceptor'); }]); mainApps.run(['$rootScope', '$cookies', '$state', 'AuthService', function ($rootScope, $cookies, $state, AuthService) { $rootScope.$on('$stateChangeStart', function (e, toState, toParams, fromState, fromParams, options) { //when a page is loading if (toState.resolve) { $rootScope.isLoading = true; } //assigning false to the state of user's sign in // todetermine buttons that will be displayed in the navigation bar $rootScope.newStateName = toState.name; //getting logged in status from user's details from cookies if ($cookies.getObject('details')) { var details = $cookies.getObject('details'); } // checking if accesss is not restricted and user is not logged in // return to login page //assigning promise response value in loggedIn if (!details && (toState.name != 'home' || toState.name != 'signUp' || toState.name != 'login' || toState.name != 'logout')) { $rootScope.state = false; if (toState.access.restricted == true) { $state.go('login'); e.preventDefault(); } } if (details) { $rootScope.state = true; } if (toState.redirectTo) { e.preventDefault(); $state.go(toState.redirectTo, fromState, { location: 'replace' }) } }) $rootScope.$on('$stateChangeSuccess', function (e, toState, toParsams, fromState, fromParams) { if (AuthService.isLoggedIn() == false || details == undefined) { $rootScope.state = false; } else { $rootScope.state = true; } if (toState.resolve) { $rootScope.isLoading = false; } var details = $cookies.getObject('details'); }) }]);<file_sep>angular.module('mainApp') .factory('viewAdminService', ['$http', function ($http) { let factory = {}; factory.listAdmin = async function (userId, permission) { var admins = {}; let url= `http://localhost:3000/users/listAdmin/${userId}/${permission}` await $http.get(url).then(function (response) { admins = response.data; }) return admins; } factory.createNewAdmin = async function (userId) { let userId = userId; state.go('createNewAdmin',{ userId }) } factory.AdminToUser = async function (userId) { state.go('AdminToUser',{ userId }) } return factory } ])<file_sep>angular.module('mainApp') .factory('viewDetailsService', ['$http', function ($http) { let factory = {}; factory.viewDetails = async function (saveId) { let url = `http://localhost:3000/recurringSavings/listPayment/${saveId}` var savingsDetails = {}; await $http.get(url).then(function (response) { savingsDetails = response.data.savings; }, (Error) => { alert(Error.data.message) console.log(Error) }) return savingsDetails; } return factory } ])<file_sep>angular.module ('mainApp') .factory('signupService',[ '$http', '$location', function ($http, $location) { let factory = {}; let url = 'http://localhost:3000/users/register'; factory.signUp = function (user){ $http.post(url, user).then( function (response) { if (response.data.status == true){ alert(response.data.message); $location.path('/login'); // return newUsers; } if (response.data.status == false){ var errorMessage = response.data.message; alert(response.data.message); } }) } return factory; } ])<file_sep>var express = require('express'); var router = express.Router(); const UserController = require('../controllers/users.controllers'); const superAdminFeatures = require('../controllers/superAdminfeaturesControllers'); router.get('/list/:userId', UserController.List); router.get('/listAllUsers/:userId/:permission', UserController.ListAllUsers); router.get('/listAdmin/:userId/:permission', UserController.ListAdmin); router.post('/register', UserController.Register); router.post('/login', UserController.Login); router.post('/update/:userId', UserController.updateProfile); router.post('/updateToAdmin/:userId', superAdminFeatures.changeUserToAdmin); router.post('/changeAdminToUser/:userId', superAdminFeatures.changeAdminToUser); // router.use(JWT_Verify.verifyToken); module.exports = router;<file_sep>angular.module('mainApp') .controller('dashboardController', ['$scope', '$state', '$cookies', 'dashboardResolve', 'dashboardService', function ($scope, $state, $cookies, dashboardResolve, dashboardService) { var details = $cookies.getObject('details') $scope.userId = details.userId; $scope.name = details.name; $scope.email = details.email; $scope.phoneNumber = details.phoneNumber; $scope.permission = details.permission; phoneNumberFormatted = '+234' + parseInt($scope.phoneNumber); // $scope.listSavingsHistory = async function (userId){ // // $scope.savings = await dashboardService.listSavingsHistory(details.userId) // } $scope.savings = dashboardResolve save = dashboardResolve; //counting number of plans that have pending payments var count = 0; for (i=0; i<save.length; i++) { if (save[i].paymentStatus == false) { count += 1; } $scope.pendingPayment = count; } $scope.withdraw = function (save, withdrawalStatus, duePaymentDate, paymentStatus) { let status; if (paymentStatus == false) { return alert('You can\'t withdraw you have not made your payment '); } if (withdrawalStatus == true) { return $state.go('transactionClosed') } //comparing date before withdrawal var date1 = new Date(duePaymentDate); var date2 = new Date(); var timeDiff = Math.abs(date2.valueOf() - date1.valueOf()); var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); //status is false if it is not due date for payment if (date2 <= date1) { status = false; //$location.path(`/penaltyWithdrawal/${dueDateForWithdrawal}/${saveid}/${status}`) $state.go('penaltyWithdrawal', { save, duePaymentDate, withdrawalStatus }) } //status is true if it is due date for payment if (date2 > date1) { status = true; $state.go('withdrawal', { save, duePaymentDate, withdrawalStatus }) } }; $scope.showUserProfile = function () { var details = $cookies.getObject('details') var userId = details.userId; $state.go('userProfile', { userId, }); }; $scope.viewAllUser = function (userId, permission) { $state.go('listAllUsers', { userId: userId, permission: permission }); }; $scope.viewAdmins = function (userId, permission) { $state.go('listAdmin', { userId: userId, permission: permission }); }; $scope.payWithRave = function (savingsId, amount, balance, withdrawalStatus) { let amountToWithdraw; //avoid payment on completion if (balance == 0) { return alert('Payment completed'); } if (withdrawalStatus == true) { return alert('You have withdrawn, this transaction closed') } //paying balance left if les than amon=unt per deposit // if (amount > balance) { // return alert('You are paying more than your invested amount') // } const API_publicKey = "<KEY>"; var x = getpaidSetup({ PBFPubKey: API_publicKey, customer_email: $scope.email, amount: amount, customer_phone: phoneNumberFormatted, currency: "NGN", payment_method: "both", txref: "rave-123456", meta: [{ metaname: "flightID", metavalue: "AP1234" }], onclose: function () {}, callback: function (response) { var txref = response.tx.txRef; // collect txRef returned and pass to a server page to complete status check. console.log("This is the response returned after a charge", response); if ( response.tx.chargeResponseCode == "00" || response.tx.chargeResponseCode == "0" ) { // redirect to a success page updatePaidAmount(savingsId); } else { // redirect to a failure page. alert('An error occurred'); } x.close(); // use this to close the modal immediately after payment. } }); } async function updatePaidAmount(savingsId) { await dashboardService.updatePaidAmount(savingsId) $state.reload('dashboard') } } ])<file_sep>angular.module('mainApp') .factory('viewAllUserService', ['$http', function ($http) { let factory = {}; factory.listAllUsers = async function (userId, permission) { let url = `http://localhost:3000/users/listAllUsers/${userId}/${permission}` var users = {}; await $http.get(url).then(function (response) { users = response.data; }) return users; } return factory } ])
b080e064917cb549472aeffc7e4a05deb0d302f3
[ "JavaScript" ]
33
JavaScript
adydams/rsa
484473d344700ef0ff6f0211cc6338b4d0362933
c6c90c75f47c186a9657b157a70141b92b2768ff
refs/heads/master
<repo_name>Juju-AM-Jam/TestRepoAMJam<file_sep>/Assets/TestFile.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestFile : MonoBehaviour { [SerializeField] private float _speed = 4; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey(KeyCode.RightArrow)) { transform.position += transform.right * (_speed * Time.deltaTime); } } }
b0ebd720d29542ff8c32acfe89ff254d1534ff93
[ "C#" ]
1
C#
Juju-AM-Jam/TestRepoAMJam
9879f1239ec7b8c95c90a45e16f19734bc7f589d
9bd0d5c2bef0666cf0959608e11b58f199a5f519
refs/heads/master
<file_sep>import pygame,sys,time,threading from pygame.locals import* from random import randint class Cuadro(object): x,y = 50,8 position = [[1,0,0],[0,1,0],[0,0,1]] def avanzar(self): self.x-=1 def girar(self): lista = [[0,0,0],[0,0,0],[0,0,0]] limite1 = 0 for i in range(3): limite2 = 2 for j in range(3): lista[i][j] = self.position[limite2][limite1] limite2-=1 limite1+=1 self.position = lista def arriba(self,matriz): bandera = False for i in range(3): for j in range(3): if self.position[i][j]==1: if (matriz[self.y+i-1][self.x+j]==-1): bandera = True if bandera==False: self.y-=1 def abajo(self,matriz): bandera = False for i in range(3): for j in range(3): if self.position[i][j]==1: if (matriz[self.y+i+1][self.x+j]==-1): bandera = True if bandera==False: self.y+=1 def crearMatriz(n,m): matriz = [] for i in range(n): matriz.append([]) for j in range(m): if i == (n-1) or i == 2 or j == m//2: matriz[i].append(-1) else : matriz[i].append(0) return matriz def dibujarMatriz(ventana,matriz,color): for i in range(3,len(matriz)-1): for j in range(1,len(matriz[0])-1): if matriz[i][j]==1 : pygame.draw.rect(ventana,(color[0],color[1],color[2],0),(j*25+10,i*25-30,25,25),0) elif matriz[i][j]==-1 : pygame.draw.rect(ventana,(0,160,0,0),(j*25+10,i*25-30,25,25),0) pygame.draw.rect(ventana,(0,0,0,0),(j*25+10,i*25-30,25,25),2) pass pass def dibujarBorrar(matriz,cuadrito, bandera, grabar): limite1 = 0 for i in range( cuadrito.y,(len(cuadrito.position)+cuadrito.y)): limite2 = 0 for j in range( cuadrito.x,(len(cuadrito.position[0])+cuadrito.x)) : if bandera==True and grabar==False and cuadrito.position[limite1][limite2]==1: matriz[i][j]=cuadrito.position[limite1][limite2] elif bandera==False and grabar==False and cuadrito.position[limite1][limite2]==1: matriz[i][j]=0 elif grabar==True and cuadrito.position[limite1][limite2]==1: matriz[i][j]=-1 limite2+=1 limite1+=1 def colorRandom(): nuevo = [randint(0,150),randint(0,150),randint(0,150)] return nuevo def condicion(m,c,color): bandera = False for i in range(3): for j in range(3): if c.position[i][j]==1: if m[c.y+(i)][c.x+j-1]==-1: #antes checkeaba si habian piezas abajo, ahora si estan al costado derecho bandera = True if bandera ==True: dibujarBorrar(m,c,False,True) c.y,c.x = 8,50 c.position = random() color = colorRandom() return color def random(): lista1 = [[0,1,0],[1,1,0],[1,0,0]] lista2 = [[0,0,0],[1,1,0],[1,1,0]] lista3 = [[0,0,0],[0,0,1],[1,1,1]] lista4 = [[0,0,1],[0,0,1],[0,0,1]] lista5 = [[0,0,0],[0,1,0],[0,0,0]] lista6 = [[0,0,0],[0,1,0],[1,1,1]] lista7 = [[1,0,0],[1,1,0],[0,1,0]] lista8 = [[0,1,0],[0,1,0],[0,0,0]] lista9 = [[1,0,1],[1,1,1],[0,0,1]] lista10= [[1,0,1],[1,0,1],[1,1,1]] lista11= [[1,1,1],[0,0,1],[0,0,1]] lista12= [[1,1,1],[0,1,1],[0,0,1]] lista13= [[1,1,0],[1,1,0],[0,1,0]] lista14= [[1,1,1],[1,1,1],[1,1,1]] lista15= [[1,1,1],[1,1,0],[0,1,0]] lista16= [[0,1,0],[1,1,1],[0,1,0]] lista17= [[0,0,0],[0,1,0],[0,0,0]] lista18= [[0,0,1],[0,0,1],[0,0,1]] lista19= [[0,1,0],[0,1,0],[0,0,0]] lista20= [[0,0,0],[0,1,0],[0,0,0]] lista21= [[0,0,1],[0,0,1],[0,0,1]] lista22= [[0,0,0],[0,1,0],[0,0,0]] lista23= [[0,0,0],[0,1,0],[0,0,0]] lista24= [[0,0,0],[0,1,0],[0,0,0]] lista25= [[0,0,0],[0,1,0],[0,0,0]] listota = [lista1,lista2,lista3,lista4,lista5,lista6,lista7,lista8,lista9,lista10,lista11,lista12, lista13,lista14,lista15,lista16,lista17,lista18,lista19,lista20,lista21,lista22,lista23,lista24,lista25] return listota[randint(0,len(listota)-1)] def revisarMatriz(matriz): indice =-1 for i in reversed(range(50,(len(matriz[0])//2))): bandera = False for j in range(3,len(matriz)-1): if matriz[i][j]==0: bandera = True, print(5) if bandera==False: print("entra") for n in range(i+1,1): for j in reversed(range(3,len(matriz)-1)): matriz[j][n] = matriz[j][n-1] def imprimir(matriz): for i in range(len(matriz)): print(matriz[i]) def principal(): izquierda = True ventana = pygame.display.set_mode((1350,620)) matriz = crearMatriz(16,53) cuadrito,contador,bandera,color = Cuadro(),0,False,[1,1,0] cuadrito.position = random() while True: ventana.fill((255,255,255,255)) dibujarBorrar(matriz,cuadrito,True,False) #pintar dibujarMatriz(ventana,matriz,color) #dibujar dibujarBorrar(matriz,cuadrito,False,False) #borrar revisarMatriz(matriz) #revisar color = condicion(matriz,cuadrito,color) if contador > 10 or bandera==True: cuadrito.avanzar() contador=0 contador+=1 for events in pygame.event.get(): if events.type==QUIT: pygame.quit() sys.exit() elif events.type==KEYDOWN: if events.key==K_UP: cuadrito.arriba(matriz) elif events.key==K_DOWN: cuadrito.abajo(matriz) #acelerar y girar elif events.key==K_RIGHT: if izquierda: bandera=True else: cuadrito.girar() elif events.key==K_LEFT: if izquierda: cuadrito.girar() else: bandera=True elif events.type==KEYUP: if events.key==K_RIGHT and izquierda: bandera=False elif events.key==K_LEFT and (not izquierda): bandera=False pygame.display.update() time.sleep(.08) def main(): principal() main()
a5b1884c101bfe68c733c1f3d0ee9e7ccb99ec1a
[ "Python" ]
1
Python
elutecs/Retetrix
5216289d81b524e31e88d9f76c5e352d80eba05b
d34cbcfb8565c0df55eebe33e5fb0121af366136
refs/heads/main
<file_sep>/*---------------------------------------------------------*/ /* ---------------- PROYECTO FINAL --------------------------*/ /*----------------- 2020-2 ---------------------------*/ /*------------- <NAME> ---------------*/ /*------------- <NAME> ---------------*/ /*------------- <NAME> ---------------*/ //#define STB_IMAGE_IMPLEMENTATION #include <glew.h> #include <glfw3.h> #include <stb_image.h> #include <Windows.h> #include <MMSystem.h> #include "camera.h" #include "Model.h" #include <iostream> #include <alut.h> #define NUM_BUFFERS 2 #define NUM_SOURCES 2 #define NUM_ENVRIONMENTS 1 // Config OpenAL ALfloat listenerPos[] = { 0.0, 0.0, 0.0 }; ALfloat listenerVel[] = { 0.0, 0.0, 0.0 }; ALfloat listenerOri[] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; // Source 0 ALfloat source0Pos[] = { 0.0, 0.0, 0.0 }; ALfloat source0Vel[] = { 0.0, 0.0, 0.0 }; // Source 1 ALfloat source1Pos[] = { 0.0, 0.0, 0.0 }; ALfloat source1Vel[] = { 0.0, 0.0, 0.0 }; // Buffers ALuint buffers[NUM_BUFFERS]; ALuint sources[NUM_SOURCES]; ALuint enviornment[NUM_ENVRIONMENTS]; // variables para inicializar audios ALsizei size, freq; ALenum format; ALvoid *data; int ch; ALboolean loop; // Other Libs #include "SOIL2/SOIL2.h" void resize(GLFWwindow *window, int width, int height); void my_input(GLFWwindow *window); void mouse_callback(GLFWwindow *window, double xpos, double ypos); void scroll_callback(GLFWwindow *window, double xoffset, double yoffset); // settings // Window size int SCR_WIDTH = 3800; int SCR_HEIGHT = 7600; GLFWwindow *window; GLFWmonitor *monitors; GLuint VBO, VAO, EBO; //Camera Camera camera(glm::vec3(-21.0f, 3.0f, -5.0f));//20.0f en z //Camera camera(glm::vec3(-38.0f, 7.0f, 12.0f)); //Camera camera(glm::vec3(0.0f, 5.0f, 25.0f)); /*************************************************************************************/ bool crece = true; float movA = 0.05f; /*************************************************************************************/ double lastX = 0.0f, mul = 1.0f, lastY = 0.0f, rot = 0.0f; bool firstMouse = true; ///VARIABLES ANIMACION DRON bool animacion = false; /*float movdron_x = -35.0f, movdron_y = 0.5f, movdron_z = 2.0f, dronRotY = 180.0f,*/ //VARIABLES PARA LAMBORGHINI float movAuto_z = 0.0f; float movAuto_y = -1.75f; int recorridoAuto = 0; //Timing double deltaTime = 0.0f, lastFrame = 0.0f; //Lighting glm::vec3 lightPosition(0.0f, 2.0f, 2.0f); glm::vec3 lightDirection(0.0f, -1.0f, -1.0f); void myData(void); void display(Shader, Model, Model); void getResolution(void); void animate(void); void LoadTextures(void); unsigned int generateTextures(char*, bool); int ESTADO = 0; //For Keyboard float movX = 0.0f, movY = 0.0f, j = 0.0f, movZ = -5.0f, rotY = 0.0f, dx = -49.0f, dy = -1.3f, dz = -10.0f, //rotY = 55.0f, rotP = 0.0f; float movLuzX = 0.0f; //Texture unsigned int t_smile, t_toalla, t_unam, t_white, t_panda, t_cubo, t_caja, t_caja_brillo, t_pared_A, t_pared_B, t_pared_C, lamp, imagen; //For model //bool animacion = false; bool ro = false; bool uno = false; bool dos = false; bool ho = false; bool cam1 = false; bool cam2 = false; bool E1 = false; bool E2 = false; bool E3 = false; bool E4 = false; bool E5 = false; //Keyframes //Variables de dibujo float posX = -5.0f, posY = 10.0f, posZ = 0.0f, giro = 0.0f, //VARIABLES PARA DRON posAX = -60.0f, posAY = 0.0f,//4 posAZ = 0.0f, giroA = 180.0f, //VARIABLES PARA CARRO1 posBX = -67.0f, //3.0f posBY = -2.0f, posBZ = 18.0f, giroB = 0.0f, //VARIABLES PARA ROBOT posCX = -12.0f,//2 posCY = -2.0f,//2 posCZ = 0.0f,//4 giroMano1 = 0.0f, giroPieIzq = 0.0f, giroCuerpo = -90.0f, wing = 0.0f, //VARIABLES CARRO2 EL QUE SE VA A ESTACIONAR EN LA COCHERA posDX = 3.0f, posDY = -2.0f, posDZ = 2.0f, giroD = 0.0f; float incX = 0.0f, incY = 0.0f, incZ = 0.0f, giroaveInc = 0.0f, giroDronInc = 0.0f, giroCarro1Inc = 0.0f, giroCarro2Inc = 0.0f, incAX = 0.0f, incAY = 0.0f, incAZ = 0.0f, incBX = 0.0f, incBY = 0.0f, incBZ = 0.0f, incCX = 0.0f, incCY = 0.0f, incCZ = 0.0f, incDX = 0.0f, incDY = 0.0f, incDZ = 0.0f, incMano1 = 0.0f, incPie = 0.0f; float movBrazoInc = 0.0f; #define MAX_FRAMES 10 int i_max_steps = 30; int i_curr_steps = 0; typedef struct _frame { //Variables para GUARDAR Key Frames float posX; //Variable para PosicionX float posY; //Variable para PosicionY float posZ; //Variable para PosicionZ float giro; float giroMano1; float giroPieIzq; }FRAME; FRAME KeyFrame[MAX_FRAMES]; FRAME KeyFrame2[MAX_FRAMES]; FRAME KeyFrame3[MAX_FRAMES]; FRAME KeyFrame4[MAX_FRAMES]; FRAME KeyFrame5[MAX_FRAMES]; int FrameIndex = 6; //Introducir datos bool play = false; //Indica cuando se inicia la animacion int playIndex = 6; int FrameIndex2 = 6; //Introducir datos bool play2 = false; //Indica cuando se inicia la animacion int playIndex2 = 6; int FrameIndex3 = 6; //Introducir datos bool play3 = false; //Indica cuando se inicia la animacion int playIndex3 = 6; int FrameIndex4 = 6; //Introducir datos bool play4 = false; //Indica cuando se inicia la animacion int playIndex4 = 6; int FrameIndex5 = 6; //Introducir datos bool play5 = false; //Indica cuando se inicia la animacion int playIndex5 = 6; void carro2Frame(void) { KeyFrame5[0].posX = 1.0f; KeyFrame5[0].posY = 0.0f; KeyFrame5[0].posZ = 2.0f; KeyFrame5[0].giro = 0.0f; KeyFrame5[1].posX = 30.50f; KeyFrame5[1].posY = 0.0f; KeyFrame5[1].posZ = 0.0f; KeyFrame5[1].giro = 0.0f; KeyFrame5[2].posX = 7.50f; KeyFrame5[2].posY = 0.0f; KeyFrame5[2].posZ = 0.0f; KeyFrame5[2].giro = 0.0f; KeyFrame5[3].posX = 7.50f; KeyFrame5[3].posY = 0.0f; KeyFrame5[3].posZ = 0.0f; KeyFrame5[3].giro = 50.0f; KeyFrame5[4].posX = 7.50f; KeyFrame5[4].posY = 0.0f; KeyFrame5[4].posZ = 0.0f; KeyFrame5[4].giro = 0.0f; KeyFrame5[5].posX = -5.0f; KeyFrame5[5].posY = 0.0f; KeyFrame5[5].posZ = 0.0f; KeyFrame5[5].giro = 0.0f; } void resetElements5(void) { posDX = KeyFrame5[0].posX; posDY = KeyFrame5[0].posY; posDZ = KeyFrame5[0].posZ; giroD = KeyFrame5[0].giro; } void interpolation5(void) { incDX = (KeyFrame5[playIndex + 1].posX - KeyFrame5[playIndex].posX) / i_max_steps; incDY = (KeyFrame5[playIndex + 1].posY - KeyFrame5[playIndex].posY) / i_max_steps; incDZ = (KeyFrame5[playIndex + 1].posZ - KeyFrame5[playIndex].posZ) / i_max_steps; giroCarro2Inc = (KeyFrame5[playIndex + 1].giro - KeyFrame5[playIndex].giro) / i_max_steps; } /*posAX = -40.0f, posAY = 4.0f, posAZ = 0.0f,*/ void dronFrame(void) { KeyFrame2[0].posX = -60.0f; KeyFrame2[0].posY = 0.0f; KeyFrame2[0].posZ = 0.0f; KeyFrame2[0].giro = 0.0f; KeyFrame2[1].posX = -62.0f; KeyFrame2[1].posY = 4.0f; KeyFrame2[1].posZ = 3.0f; KeyFrame2[1].giro = 90.0f; KeyFrame2[2].posX = -65.0f; KeyFrame2[2].posY = 8.0f; KeyFrame2[2].posZ = 5.0f; KeyFrame2[2].giro = 0.0f; KeyFrame2[3].posX = -65.0f; KeyFrame2[3].posY = 12.0f; KeyFrame2[3].posZ = 8.0f; KeyFrame2[3].giro = 0.0f; KeyFrame2[4].posX = -65.0f; KeyFrame2[4].posY = 12.0f; KeyFrame2[4].posZ = 8.0f; KeyFrame2[4].giro = 0.0f; KeyFrame2[5].posX = -62.0f; KeyFrame2[5].posY = 12.0f; KeyFrame2[5].posZ = 8.0f; KeyFrame2[5].giro = 0.0f; KeyFrame2[6].posX = -60.0f; KeyFrame2[6].posY = 12.0f; KeyFrame2[6].posZ = 5.0f; KeyFrame2[6].giro = 0.0f; KeyFrame2[5].posX = -60.0f; KeyFrame2[5].posY = 10.0f; KeyFrame2[5].posZ = 3.0f; KeyFrame2[5].giro = 0.0f; } void resetElements2(void) { posAX = KeyFrame2[0].posX; posAY = KeyFrame2[0].posY; posAZ = KeyFrame2[0].posZ; giroA = KeyFrame2[0].giro; } void interpolation2(void) { incAX = (KeyFrame2[playIndex + 1].posX - KeyFrame2[playIndex].posX) / i_max_steps; incAY = (KeyFrame2[playIndex + 1].posY - KeyFrame2[playIndex].posY) / i_max_steps; incAZ = (KeyFrame2[playIndex + 1].posZ - KeyFrame2[playIndex].posZ) / i_max_steps; giroDronInc = (KeyFrame2[playIndex + 1].giro - KeyFrame2[playIndex].giro) / i_max_steps; } void robotFrame(void) { KeyFrame4[0].posX = -12.0f; KeyFrame4[0].posY = -2.0f; KeyFrame4[0].posZ = 0.0f; KeyFrame4[0].giro = -0.0f; KeyFrame4[1].posX = -14.0f; KeyFrame4[1].posY = -2.0f; KeyFrame4[1].posZ = 0.0f; KeyFrame4[1].giro = -0.0f; KeyFrame4[1].giroMano1 = 0.0f; KeyFrame4[1].giroPieIzq = 60.0f; KeyFrame4[2].posX = -16.0f; KeyFrame4[2].posY = -2.0f; KeyFrame4[2].posZ = 0.0f; KeyFrame4[2].giro = -0.0f; KeyFrame4[1].giroMano1 = 0.0f; KeyFrame4[1].giroPieIzq = -60.0f; KeyFrame4[3].posX = -18.50f; KeyFrame4[3].posY = -2.0f; KeyFrame4[3].posZ = 0.0f; KeyFrame4[3].giro = -0.0f; KeyFrame4[1].giroMano1 = 0.0f; KeyFrame4[1].giroPieIzq = 60.0f; KeyFrame4[4].posX = -20.0f; KeyFrame4[4].posY = -2.0f; KeyFrame4[4].posZ = 0.0f; KeyFrame4[4].giro = -0.0f; KeyFrame4[1].giroMano1 = 0.0f; KeyFrame4[1].giroPieIzq = -60.0f; KeyFrame4[5].posX = -24.0f; KeyFrame4[5].posY = -2.0f; KeyFrame4[5].posZ = 0.0f; KeyFrame4[5].giro = -0.0f; KeyFrame4[1].giroMano1 = 0.0f; KeyFrame4[1].giroPieIzq = 60.0f; } void resetElements4(void) { posCX = KeyFrame4[0].posX; posCY = KeyFrame4[0].posY; posCZ = KeyFrame4[0].posZ; giroCuerpo = KeyFrame4[0].giro; giroMano1 = KeyFrame4[0].giroMano1; giroPieIzq = KeyFrame4[0].giroPieIzq; } void interpolation4(void) { incCX = (KeyFrame4[playIndex + 1].posX - KeyFrame4[playIndex].posX) / i_max_steps; incCY = (KeyFrame4[playIndex + 1].posY - KeyFrame4[playIndex].posY) / i_max_steps; incCZ = (KeyFrame4[playIndex + 1].posZ - KeyFrame4[playIndex].posZ) / i_max_steps; giroCuerpo = (KeyFrame4[playIndex + 1].giro - KeyFrame4[playIndex].giro) / i_max_steps; incMano1 = (KeyFrame4[playIndex + 1].giroMano1 - KeyFrame4[playIndex].giroMano1) / i_max_steps; incPie = (KeyFrame4[playIndex + 1].giroPieIzq - KeyFrame4[playIndex].giroPieIzq) / i_max_steps; } void carro1Frame(void) { KeyFrame3[0].posX = -67.0f; KeyFrame3[0].posY = -2.0f; KeyFrame3[0].posZ = 15.0f; KeyFrame3[0].giro = 0.0f; KeyFrame3[1].posX = -67.0f; KeyFrame3[1].posY = -2.0f; KeyFrame3[1].posZ = 11.0f; KeyFrame3[1].giro = 0.0f; KeyFrame3[2].posX = -67.0f; KeyFrame3[2].posY = -2.0f; KeyFrame3[2].posZ = 9.0f; KeyFrame3[2].giro = 0.0f; KeyFrame3[3].posX = -67.0f; KeyFrame3[3].posY = -2.0f; KeyFrame3[3].posZ = 7.0f; KeyFrame3[3].giro = 0.0f; KeyFrame3[4].posX = -67.0f; KeyFrame3[4].posY = -2.0f; KeyFrame3[4].posZ = 5.0f; KeyFrame3[4].giro = 0.0f; KeyFrame3[5].posX = -67.0f; KeyFrame3[5].posY = -2.0f; KeyFrame3[5].posZ = 4.5f; KeyFrame3[5].giro = 0.0f; } void resetElements3(void) { posBX = KeyFrame3[0].posX; posBY = KeyFrame3[0].posY; posBZ = KeyFrame3[0].posZ; giroB = KeyFrame3[0].giro; } void interpolation3(void) { incBX = (KeyFrame3[playIndex + 1].posX - KeyFrame3[playIndex].posX) / i_max_steps; incBY = (KeyFrame3[playIndex + 1].posY - KeyFrame3[playIndex].posY) / i_max_steps; incBZ = (KeyFrame3[playIndex + 1].posZ - KeyFrame3[playIndex].posZ) / i_max_steps; giroCarro1Inc = (KeyFrame3[playIndex + 1].giro - KeyFrame3[playIndex].giro) / i_max_steps; } void aveFrame(void) { KeyFrame[0].posX = -40.0f; KeyFrame[0].posY = 10.0f; KeyFrame[0].posZ = 0.0f; KeyFrame[0].giro = -20.0f; KeyFrame[1].posX = -60.0f; KeyFrame[1].posY = 10.0f; KeyFrame[1].posZ = 0.0f; KeyFrame[1].giro = 10.0f; KeyFrame[2].posX = -65.0f; KeyFrame[2].posY = 10.0f; KeyFrame[2].posZ = 15.0f; KeyFrame[2].giro = -20.0f; KeyFrame[3].posX = -40.0f; KeyFrame[3].posY = 10.0f; KeyFrame[3].posZ = 0.0f; KeyFrame[3].giro = 10.0f; KeyFrame[4].posX = -50.0f; KeyFrame[4].posY = 10.0f; KeyFrame[4].posZ = 0.0f; KeyFrame[4].giro = -20.0f; KeyFrame[5].posX = -55.0f; KeyFrame[5].posY = 10.0f; KeyFrame[5].posZ = 0.0f; KeyFrame[5].giro = 10.0f; } void resetElements(void) { posX = KeyFrame[0].posX; posY = KeyFrame[0].posY; posZ = KeyFrame[0].posZ; giro = KeyFrame[0].giro; } void interpolation(void) { incX = (KeyFrame[playIndex + 1].posX - KeyFrame[playIndex].posX) / i_max_steps; incY = (KeyFrame[playIndex + 1].posY - KeyFrame[playIndex].posY) / i_max_steps; incZ = (KeyFrame[playIndex + 1].posZ - KeyFrame[playIndex].posZ) / i_max_steps; giroaveInc = (KeyFrame[playIndex + 1].giro - KeyFrame[playIndex].giro) / i_max_steps; } /////////////////////////////// unsigned int generateTextures(const char* filename, bool alfa) { unsigned int textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis. unsigned char *data = stbi_load(filename, &width, &height, &nrChannels, 0); if (data) { if (alfa) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); return textureID; } else { std::cout << "Failed to load texture" << std::endl; return 100; } stbi_image_free(data); } void getResolution() { const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); SCR_WIDTH = mode->width; SCR_HEIGHT = (mode->height) - 80; lastX = SCR_WIDTH / 2.0f; lastY = SCR_HEIGHT / 2.0f; } void LoadTextures() { t_pared_A = generateTextures("Texturas/Textura_Pared.png", 1); t_pared_B = generateTextures("Texturas/Textura_pared_B.png", 1); t_pared_C = generateTextures("Texturas/Cortina.png", 1); imagen = generateTextures("Texturas/w.jpg", 0); lamp = generateTextures("Texturas/lamp.png", 1); } void myData() { float vertices[] = { 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, //0 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, //1 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, //2 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, //3 }; unsigned int indices[] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // normal attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // texture coord attribute glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(2); } int mov_dron = 0; float velocidad = 0; void animate(void) { if (crece) { movA += 0.005; if (movA > 1.0f) crece = false; } else { movA -= 0.005; if (movA < 0.2f) crece = true; } //ANIMACION DRON /*if (animacion) { if (mov_dron == 0) { //avionRotY = 0.0f; movdron_y += velocidad; if (movdron_y >= 35.0f) { mov_dron = 1; } } if (mov_dron == 1) { movdron_z += velocidad; //avionRotY = 90.0f; if (movdron_z >= 35.0f) mov_dron = 2; } if (mov_dron == 2) { movdron_x += velocidad; dronRotY = -90.0f; if (movdron_x >= 40.0f) mov_dron = 3; } if (mov_dron == 3) { movdron_z -= velocidad; dronRotY = 360.0f; if (movdron_z <= -60.0f) mov_dron = 4; } if (mov_dron == 4) { movdron_x -= velocidad; dronRotY = 90.0f; if (movdron_x <= -35.0f) mov_dron = 5; } if (mov_dron == 5) { dronRotY = 180.0f; //if (movdron_z <= 30.0f) mov_dron = 1; } }*/ //ANIMACION LAMBO { switch (recorridoAuto) { case 1: if (movAuto_z >= 5.0) movAuto_z += 0.03f;//-7 else recorridoAuto = 2; break; case 2: if (movAuto_z <= 5.0) movAuto_z += 0.03f; else recorridoAuto = 0; break; default: break; } } /////////////KEYFRAMES//////////////////////////////////////////////////// if (play) { if (i_curr_steps >= i_max_steps) //end of animation between frames? { playIndex++; if (playIndex > FrameIndex - 2) //end of total animation? { printf("Termina animacion\n"); playIndex = 0; resetElements(); resetElements2(); resetElements3(); resetElements4(); resetElements5(); //play = false; } else //Next frame interpolations { i_curr_steps = 0; //Reset counter interpolation(); //Interpolation interpolation2(); interpolation3(); interpolation4(); interpolation5(); } } else { //Draw animation posX += incX; posY += incY; posZ += incZ; giro += giroaveInc; posAX += incAX; posAY += incAY; posAZ += incAZ; giroA += giroDronInc; posBX += incBX; posBY += incBY; posBZ += incBZ; giroB += giroCarro1Inc; posCX += incCX; posCY += incCY; posCZ += incCZ; giroCuerpo += giroCuerpo; giroMano1 += incMano1; giroPieIzq += incPie; posDX += incDX; posDY += incDY; posDZ += incDZ; giroD += giroCarro2Inc; i_curr_steps++; } } //2/////////////////RECORRIDO 1//////////////// if (ro) { E1 = true; if (E1) { mul += .5; camera.Cambio(glm::vec3(7.0f - mul, 8.0f, 2.0f), 180); camera.ProcessMouseMovement(0, 0); if (mul >= 50.0) { E1 = false; E2 = true; } } if (E2) { mul += .5; camera.Cambio(glm::vec3(-43.0f, 8.0f, 2.0f), 180 - mul); camera.ProcessMouseMovement(0, 0); if (mul >= 180.0) { E2 = false; E3 = true; mul = 0; } } if (E3) { mul += .005; camera.Cambio(glm::vec3(-43.0f, 8.0f - mul, 2.0f), 0); camera.ProcessMouseMovement(0, 0); if (mul >= 8.0) { E3 = false; E4 = true; } } if (E4) { mul += .0005; camera.Cambio(glm::vec3(-43.0f + mul, 0.0f, 2.0f), 0); camera.ProcessMouseMovement(0, 0); if (mul >= 43) { E4 = false; ro = false; } } } ////////////////////////////////////////////////// //3/////////////////RECORRIDO//////////////// if (ho) { E1 = true; if (E1) { mul += 0.5; camera.Cambio(glm::vec3(0.0f - mul, 0.0f, 2.0f), 0); camera.ProcessMouseMovement(0, 0); if (mul >= 40) { ho = false; } } } ////////////////////////////////////////////////// /////////////////////////////////////////////////// /////////////////////5//////////////////////////// } bool flag = false; void display(Shader shader, Shader text, Model cielo, Model ave, Model alaDer, Model alaIzq, Model PieDer, Model PieIzq, Model casa, Model comedor, Model alberca, Model sala, Model cocina, Model Salma, Model baño1, Model baño2, Model Javi, Model Mau, Model jardin, Model cochera, Model carro1, Model dron, Model carro2, Model robot, Model BraDer, Model BraIzq,Model Rosa) { //text.use(); shader.use(); float i = 0; //iluminacion SHADER MULTI LUCES SHADE_LIGHTS shader.setVec3("viewPos", camera.Position); shader.setVec3("dirLight.direction", camera.Front); shader.setVec3("dirLight.ambient", glm::vec3(0.6f, 0.6f, 0.6f)); shader.setVec3("dirLight.diffuse", glm::vec3(1.0f, 1.0f, 1.0f)); shader.setVec3("dirLight.specular", glm::vec3(0.6f, 0.6f, 0.6f)); shader.setFloat("material_shininess", 32.0f); // create transformations and Projection glm::mat4 temp01 = glm::mat4(1.0f); glm::mat4 temp02 = glm::mat4(1.0f); glm::mat4 temp03 = glm::mat4(1.0f); glm::mat4 tmp = glm::mat4(1.0f); glm::mat4 model = glm::mat4(1.0f); // initialize Matrix, Use this matrix for individual models glm::mat4 view = glm::mat4(1.0f); //Use this matrix for ALL models glm::mat4 projection = glm::mat4(1.0f); //This matrix is for Projection glm::mat4 temporal = glm::mat4(1.0f);//VARIABLE TEMPORAL PARA UBICAR CENTRO DE NUESTRO ESCENARIO //Use "projection" to include Camera projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); view = camera.GetViewMatrix(); //view = glm::rotate(view, glm::radians(rotY), glm::vec3(0.0f, 1.0f, 0.0f)); // pass them to the shaders shader.setMat4("model", model); shader.setMat4("view", view); // note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once. shader.setMat4("projection", projection); ///////////////////////////////////MODELADO DEL SALON//////////////////////////////////////////////////////////////////////////// if (cam1) { shader.setVec3("dirLight.ambient", glm::vec3(0.1f, 0.1f, 0.1f)); shader.setVec3("dirLight.diffuse", glm::vec3(0.6f, 0.6f, 0.6f)); shader.setVec3("pointLight[0].position", glm::vec3(-30.0f, 8.1f, 0.0f)); shader.setVec3("pointLight[0].ambient", glm::vec3(0.07f, 0.005f, 0.0f)); shader.setVec3("pointLight[0].diffuse", glm::vec3(0.07f, 0.005f, 0.0f)); shader.setVec3("pointLight[0].specular", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setFloat("pointLight[0].constant", 0.2f); shader.setFloat("pointLight[0].linear", 0.0004f); shader.setFloat("pointLight[0].quadratic", 0.004f); shader.setVec3("pointLight[1].position", glm::vec3(-8.0f, 8.1f, 0.0f)); shader.setVec3("pointLight[1].ambient", glm::vec3(0.07f, 0.005f, 0.0f)); shader.setVec3("pointLight[1].diffuse", glm::vec3(0.07f, 0.005f, 0.0f)); shader.setVec3("pointLight[1].specular", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setFloat("pointLight[1].constant", 0.2f); shader.setFloat("pointLight[1].linear", 0.0004f); shader.setFloat("pointLight[1].quadratic", 0.004f); } else { shader.setVec3("pointLight[0].position", glm::vec3(-30.0f, 8.1f, 0.0f)); shader.setVec3("pointLight[0].ambient", glm::vec3(0.0f, 0.00f, 0.00f)); shader.setVec3("pointLight[0].diffuse", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[0].specular", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setFloat("pointLight[0].constant", 0.5f); shader.setFloat("pointLight[0].linear", 0.0004f); shader.setFloat("pointLight[0].quadratic", 0.004f); shader.setVec3("pointLight[1].position", glm::vec3(8.0f, 8.1f, 0.0f)); shader.setVec3("pointLight[1].ambient", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[1].diffuse", glm::vec3(0.0f, 0.f, 0.0f)); shader.setVec3("pointLight[1].specular", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setFloat("pointLight[1].constant", 0.5f); shader.setFloat("pointLight[1].linear", 0.0004f); shader.setFloat("pointLight[1].quadratic", 0.004f); } /*model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 4.0f, 1.25f));//-1.8f model = glm::scale(model, glm::vec3(0.007f, 0.001f, 0.0061f)); shader.setMat4("model", model); piso.Draw(shader);*/ model = glm::rotate(glm::mat4(1.0f), glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::translate(model, glm::vec3(40.0f, -47.5f, 0.0f)); model = glm::scale(model, glm::vec3(1.4f, 0.9f, 0.7f)); shader.setMat4("model", model); cielo.Draw(shader); //glm::mat4 origin = glm::mat4(1.0f); glBindVertexArray(VAO); ////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////MODELADO DE LOS ELEMENTOS ////////////////////////////// temporal = model = glm::translate(glm::mat4(1.0f), glm::vec3(-25.0f, -2.0f, 5.0f));//ORIGEN DEL ESCENARIO model = glm::rotate(model, glm::radians(0.0f), glm::vec3(1.0f, 0.0f, 0.0f));//GIRO EN X PARA PONER EL PISO ABAJO model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(0.0f), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.03f, 0.03f, 0.03f)); shader.setMat4("model", model); casa.Draw(shader); // CASA model = glm::translate(temporal, glm::vec3(42.0f, 0.5f, -4.0f)); model = glm::rotate(model, glm::radians(270.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.1f, 0.1f, 0.1f)); shader.setMat4("model", model); alberca.Draw(shader); // ALBERCA model = glm::translate(temporal, glm::vec3(-13.0f, 0.0f, -8.0f)); model = glm::rotate(model, glm::radians(-180.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.05f, 0.05f, 0.05f)); shader.setMat4("model", model); sala.Draw(shader); // SALA model = glm::translate(temporal, glm::vec3(13.0f, 0.0f, 2.4f)); //model = glm::rotate(model, glm::radians(270.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.10f, 0.10f, 0.10f)); shader.setMat4("model", model); Salma.Draw(shader); // RECAMARA SALMA model = glm::translate(temporal, glm::vec3(0.0f, 0.0f, -15.0f)); model = glm::rotate(model, glm::radians(-360.0f), glm::vec3(0.0f, 1.0f, .0f)); model = glm::scale(model, glm::vec3(0.05f, 0.05f, 0.05f)); shader.setMat4("model", model); cocina.Draw(shader); // COCINA model = glm::translate(temporal, glm::vec3(10.0f, 0.0f, -10.0f)); //model = glm::rotate(model, glm::radians(270.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.05f, 0.05f, 0.05f)); shader.setMat4("model", model); comedor.Draw(shader); // COMEDOR model = glm::translate(temporal, glm::vec3(0.0f, 0.0f, 15.5f)); model = glm::rotate(model, glm::radians(-180.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.07f, 0.07f, 0.07f)); shader.setMat4("model", model); baño1.Draw(shader); // BAÑO1 model = glm::translate(temporal, glm::vec3(-13.0f, 0.0f, 5.0f)); //model = glm::rotate(model, glm::radians(-180.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.05f, 0.05f, 0.05f)); shader.setMat4("model", model); baño2.Draw(shader); // BAÑO2 model = glm::translate(temporal, glm::vec3(28.0f, 0.0f, 5.0f)); model = glm::rotate(model, glm::radians(-180.0f), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.05f, 0.05f, 0.05f)); shader.setMat4("model", model); Javi.Draw(shader); // RECAMARA JAVI model = glm::translate(temporal, glm::vec3(-13.0f, 0.0f, 12.2f)); model = glm::scale(model, glm::vec3(0.05f, 0.05f, 0.05f)); shader.setMat4("model", model); Mau.Draw(shader); // RECAMARA MAU model = glm::translate(temporal, glm::vec3(40.0f, 0.0f, 15.0f)); //model = glm::rotate(model, glm::radians(270.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.05f, 0.05f, 0.05f)); shader.setMat4("model", model); jardin.Draw(shader); // JARDIN /*****Animacion Prueba**********/ //Rosa model = glm::translate(temporal, glm::vec3(37.0f, 0.0f, 10.0f)); model = glm::scale(model, glm::vec3(0.5f*movA, movA, 0.5f*movA)); model = glm::scale(model, glm::vec3(0.05f, 0.05f, 0.05f)); model = glm::rotate(model, glm::radians(45.0f), glm::vec3(0.0f, 1.0f, 0.0f)); shader.setMat4("model", model); Rosa.Draw(shader); /***************/ model = glm::translate(temporal, glm::vec3(-40.8f, 0.5f, -4.5f)); //model = glm::rotate(model, glm::radians(270.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::scale(model, glm::vec3(0.04f, 0.04f, 0.04f)); shader.setMat4("model", model); cochera.Draw(shader); // COCHERA /*model = glm::scale(model, glm::vec3(0.004f, 0.004f, 0.004f)); //model = glm::rotate(model, glm::radians(270.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::translate(temporal, glm::vec3(movdron_x, movdron_y, movdron_z)); model = glm::rotate(model, glm::radians(dronRotY), glm::vec3(0.0f, 1.0f, 0.0f)); shader.setMat4("model", model); dron.Draw(shader); // DRON*/ //LAMBO /*//glm::mat4 temporal = glm::mat4(1.0f);//declaración matriz temporal model = glm::translate(temporal, glm::vec3(-40.8f, 0.5f, -4.5f)); model = glm::rotate(glm::mat4(1.0f), glm::radians(90.0f), glm::vec3(0.0f, 1.0f, 0.0f)); temporal = model = glm::translate(model, glm::vec3(-40.8f, movAuto_y, movAuto_z)); model = glm::scale(model, glm::vec3(0.01f, 0.01f, 0.01f)); //model = glm::scale(model, glm::vec3(0.3f, 0.3f, 0.3f)); shader.setMat4("model", model); lambo.Draw(shader); model = glm::translate(temporal, glm::vec3(0.85f, 0.25f, 1.29f)); model = glm::scale(model, glm::vec3(0.01f, 0.01, 0.01f)); shader.setMat4("model", model); llanta.Draw(shader); //DELANTERA IZQ LLANTA model = glm::translate(temporal, glm::vec3(-0.85f, 0.25f, 1.29f)); model = glm::scale(model, glm::vec3(0.01f, 0.01, 0.01f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 0.0f)); shader.setMat4("model", model); llanta.Draw(shader); //DELANTERA DER LLANTA model = glm::translate(temporal, glm::vec3(-0.85f, 0.25f, -1.45f)); model = glm::scale(model, glm::vec3(0.01f, 0.01, 0.01f)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 0.0f)); shader.setMat4("model", model); llanta.Draw(shader); //TRASERA DER LLANTA model = glm::translate(temporal, glm::vec3(0.85f, 0.25f, -1.45f)); model = glm::scale(model, glm::vec3(0.01f, 0.01, 0.01f)); shader.setMat4("model", model); llanta.Draw(shader); //TRASERA IZQ LLANTA*/ if (cam2) { shader.setVec3("dirLight.ambient", glm::vec3(0.6f, 0.6f, 0.6f)); shader.setVec3("dirLight.diffuse", glm::vec3(1.0f, 1.0f, 1.0f)); shader.setVec3("dirLight.specular", glm::vec3(0.6f, 0.6f, 0.6f)); } else { shader.setVec3("pointLight[2].position", glm::vec3(-40.0f, 1.0f, 1.25f)); shader.setVec3("pointLight[2].ambient", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[2].diffuse", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[2].specular", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setFloat("pointLight[2].constant", 1.0f); shader.setFloat("pointLight[2].linear", 0.0004f); shader.setFloat("pointLight[2].quadratic", 0.004f); shader.setVec3("pointLight[3].position", glm::vec3(-52.0f, -1.3f, 5.0f)); shader.setVec3("pointLight[3].ambient", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[3].diffuse", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[3].specular", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setFloat("pointLight[3].constant", 0.2f); shader.setFloat("pointLight[3].linear", 0.004f); shader.setFloat("pointLight[3].quadratic", 0.04f); shader.setVec3("pointLight[4].position", glm::vec3(-44.0f, -1.3f, 5.0f)); shader.setVec3("pointLight[4].ambient", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[4].diffuse", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[4].specular", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setFloat("pointLight[4].constant", 0.2f); shader.setFloat("pointLight[4].linear", 0.004f); shader.setFloat("pointLight[4].quadratic", 0.04f); shader.setVec3("pointLight[5].position", glm::vec3(-38.0f, 7.0f, 12.0f)); shader.setVec3("pointLight[5].ambient", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[5].diffuse", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("pointLight[5].specular", glm::vec3(0.0f, 0.0f, 0.0f)); shader.setFloat("pointLight[5].constant", 0.2f); shader.setFloat("pointLight[5].linear", 0.004f); shader.setFloat("pointLight[5].quadratic", 0.04f); } //DRON model = glm::translate(glm::mat4(1.0f), glm::vec3(posAX, posAY, posAZ)); model = glm::scale(model, glm::vec3(0.10f, 0.10f, 0.10f)); tmp = model = glm::rotate(model, glm::radians(giroA), glm::vec3(0.0f, 1.0f, 0.0)); shader.setMat4("model", model); dron.Draw(shader); //CARRO1 model = glm::translate(glm::mat4(1.0f), glm::vec3(posBX, posBY, posBZ)); model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 0.0)); temp02 = model = glm::scale(model, glm::vec3(0.10f, 0.10f, 0.10f)); //model = glm::rotate(model, glm::radians(-rotRodIzq), glm::vec3(1.0f, 0.0f, 0.0f)); shader.setMat4("model", model); carro1.Draw(shader); //CARRO2 model = glm::translate(glm::mat4(1.0f), glm::vec3(posDX, posDY, posDZ)); //model = glm::rotate(model, glm::radians(180.0f), glm::vec3(0.0f, 1.0f, 0.0)); model = glm::scale(model, glm::vec3(0.10f, 0.10f, 0.10f)); //model = glm::rotate(model, glm::radians(-rotRodIzq), glm::vec3(1.0f, 0.0f, 0.0f)); shader.setMat4("model", model); carro2.Draw(shader); //Ave model = glm::translate(glm::mat4(1.0f), glm::vec3(posX, posY, posZ)); model = glm::rotate(model, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0)); temp01 = model = glm::scale(model, glm::vec3(0.05f, 0.05f, 0.05f)); //model = glm::rotate(model, glm::radians(-rotRodIzq), glm::vec3(1.0f, 0.0f, 0.0f)); shader.setMat4("model", model); ave.Draw(shader); /*//<NAME> model = glm::translate(temp01, glm::vec3(0, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(giro), glm::vec3(0.0f, 1.0f, 0.0f)); shader.setMat4("model", model); alaDer.Draw(shader); //<NAME> model = glm::translate(temp01, glm::vec3(0.0f, 0.0f, 0.0f)); model = glm::rotate(model, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::rotate(model, glm::radians(-giro), glm::vec3(0.0f, 1.0f, 0.0f)); shader.setMat4("model", model); alaIzq.Draw(shader);*/ //ROBOT model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(0, 1, 0)); model = glm::translate(model, glm::vec3(posCX, posCY, posCZ)); temp03 = model = glm::rotate(model, glm::radians(-90.0f), glm::vec3(0.0f, 1.0f, 0.0)); temp03 = model = glm::scale(model, glm::vec3(0.08f, 0.08f, 0.08f)); shader.setMat4("model", model); robot.Draw(shader); /*//<NAME> model = glm::translate(temp03, glm::vec3(0.00f, 0.0f, -0.01f)); model = glm::rotate(model, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0)); model = glm::rotate(model, glm::radians(-giroPieIzq), glm::vec3(1.0f, 0.0f, 0.0f)); shader.setMat4("model", model); PieDer.Draw(shader); model = glm::translate(temp03, glm::vec3(0.00f, 0.0f, -0.01f)); model = glm::rotate(model, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0)); model = glm::rotate(model, glm::radians(giroPieIzq), glm::vec3(1.0f, 0.0f, 0.0f)); shader.setMat4("model", model); PieIzq.Draw(shader);*/ //Brazo derecho model = glm::translate(temp03, glm::vec3(-0.050f, -0.05f, 0.0f)); model = glm::rotate(model, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0)); model = glm::rotate(model, glm::radians(giroMano1), glm::vec3(1.0f, 0.0f, 0.0f)); shader.setMat4("model", model); BraDer.Draw(shader); model = glm::translate(temp03, glm::vec3(0.01f, -0.05f, 0.0f)); model = glm::rotate(model, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0)); model = glm::rotate(model, glm::radians(-giroMano1), glm::vec3(1.0f, 0.0f, 0.0f)); shader.setMat4("model", model); BraIzq.Draw(shader); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// glBindVertexArray(0); // Libreria de audio // openal sound data Posicion del sonido source0Pos[0] = -15; source0Pos[1] = 10; source0Pos[2] = -5; alSourcefv(sources[0], AL_POSITION, source0Pos); source1Pos[0] = -15; source1Pos[1] = -10; source1Pos[2] = -5; alSourcefv(sources[1], AL_POSITION, source1Pos); // Position listener listenerPos[0] = camera.Position.x; listenerPos[1] = camera.Position.y; listenerPos[2] = camera.Position.z; alListenerfv(AL_POSITION, listenerPos); // Orientation listener listenerOri[0] = camera.Front.x; listenerOri[1] = camera.Front.y; listenerOri[2] = camera.Front.z; listenerOri[3] = camera.Up.x; listenerOri[4] = camera.Up.y; listenerOri[5] = camera.Up.z; alListenerfv(AL_ORIENTATION, listenerOri); } int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); /*glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);*/ #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X #endif // glfw window creation // -------------------- monitors = glfwGetPrimaryMonitor(); getResolution(); GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "PROYECTO CG2021-1 * <NAME> * <NAME> * <NAME> *", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwSetWindowPos(window, 0, 30); glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, resize); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); //To Enable capture of our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); glewInit(); // OpenAL init alutInit(0, nullptr); alListenerfv(AL_POSITION, listenerPos); alListenerfv(AL_VELOCITY, listenerVel); alListenerfv(AL_ORIENTATION, listenerOri); alGetError(); // Limpiamos los errores previos de OpenAL if (alGetError() != AL_NO_ERROR) { printf("Error al crear los buffers"); exit(1); } else printf("Se crearon los buffers"); alGenBuffers(NUM_BUFFERS, buffers); buffers[0] = alutCreateBufferFromFile("Harry_Styles_Lights_Up.wav"); buffers[1] = alutCreateBufferFromFile("Harry_Styles_Lights_Up.wav"); int errorAlut = alutGetError(); if (errorAlut != ALUT_ERROR_NO_ERROR) { printf("Error al crear los buffers %d", errorAlut); exit(2); } else printf("Se crearon los buffers"); glGetError(); alGenSources(NUM_SOURCES, sources); if (alutGetError() != AL_NO_ERROR) { printf("Error al crear las fuentes de sonidos"); exit(2); } else printf("Se crearon las fuentes de sonido"); //Volumendo y distancia alSourcef(sources[0], AL_PITCH, 1.0f); alSourcef(sources[0], AL_GAIN, 4.0f); alSourcefv(sources[0], AL_VELOCITY, source0Vel); alSourcefv(sources[0], AL_POSITION, source0Pos); alSourcei(sources[0], AL_BUFFER, buffers[0]); alSourcei(sources[0], AL_LOOPING, AL_TRUE); alSourcei(sources[0], AL_MAX_DISTANCE, 2000); alSourcef(sources[1], AL_PITCH, 1.0f); alSourcef(sources[1], AL_GAIN, 4.0f); alSourcefv(sources[1], AL_VELOCITY, source0Vel); alSourcefv(sources[1], AL_POSITION, source1Pos); alSourcei(sources[1], AL_BUFFER, buffers[1]); alSourcei(sources[1], AL_LOOPING, AL_TRUE); alSourcei(sources[1], AL_MAX_DISTANCE, 2000); //Mis funciones //Datos a utilizar LoadTextures(); myData(); glEnable(GL_DEPTH_TEST); //Shader modelShader("Shaders/modelLoading.vs", "Shaders/modelLoading.fs"); Shader modelShader("Shaders/shader_Lights.vs", "Shaders/shader_Lights.fs"); //Shader modelShader("shaders/shader_Lights.vs", "shaders/shader_texture_light_dir.fs"); //Shader modelShader("shaders/shader_Lights.vs", "shaders/shader_texture_light_pos.fs"); //Shader modelShader("shaders/shader_texture_light_spot.vs", "shaders/shader_texture_light_spot.fs"); //Spotlight Shader text("shaders/shader_texture_color.vs", "shaders/shader_texture_color.fs"); // Load models Model cieloModel = ((char *)"Models/cielo/cielo.obj"); Model aveModel = ((char *)"Models/ave/ave.obj"); Model alaDerModel = ((char *)"Models/ave/AlaDer.obj"); Model alaIzqModel = ((char *)"Models/ave/AlaIzq.obj"); Model PieDer = ((char *)"Models/Mono/PieDer.obj"); Model PieIzq = ((char *)"Models/Mono/PieIzq.obj"); Model casa = ((char *)"Models/CASA3/CASA.obj"); Model comedor = ((char *)"Models/COMEDOR/COMEDOR.obj"); Model alberca = ((char *)"Models/ALBERCA/alberca.obj"); Model sala = ((char *)"Models/SALA/sala.obj"); Model Salma = ((char *)"Models/RECAMARASALMA/RecamaraSalma.obj"); Model cocina = ((char *)"Models/COCINA/Cocina.obj"); Model baño1 = ((char *)"Models/BAÑO1/BAÑO1.obj"); Model baño2 = ((char *)"Models/BAÑO2/BAÑO2.obj"); Model Javi = ((char *)"Models/RECAMARA JAVI/Javi.obj"); Model Mau = ((char *)"Models/RECAMARA MAU/mau.obj"); Model jardin = ((char *)"Models/JARDIN/Jardin.obj"); Model cochera = ((char *)"Models/COCHERA/COCHERA.obj"); //Model avionModel = ((char *)"Models/avion/avion.obj"); Model dron = ((char *)"Models/DRON/Dron.obj"); Model carro1 = ((char *)"Models/CARRO1/coche1.obj"); Model llanta = ((char *)"Models/Lambo/Wheel.obj"); Model carro2 = ((char *)"Models/CARRO2/carro2.obj"); Model robot = ((char *)"Models/mono/mono.obj"); Model BrazoDer = ((char *)"Models/mono/brazo.obj"); /*************************************************************************/ Model Rosa = ((char *)"Models/Rosa/Rose.obj"); /************************************************************************/ Model BrazoIzq = ((char *)"Models/mono/brazo.obj"); //Inicialización de KeyFrames for (int i = 0; i < MAX_FRAMES; i++) { KeyFrame[i].posX = 0; KeyFrame[i].posY = 0; KeyFrame[i].posZ = 0; KeyFrame[i].giro = 0; KeyFrame2[i].posX = 0; KeyFrame2[i].posY = 0; KeyFrame2[i].posZ = 0; KeyFrame2[i].giro = 0; KeyFrame3[i].posX = 0; KeyFrame3[i].posY = 0; KeyFrame3[i].posZ = 0; KeyFrame3[i].giro = 0; } glm::mat4 projection = glm::mat4(1.0f); //This matrix is for Projection projection = glm::perspective(glm::radians(camera.Zoom), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); // render loop // While the windows is not closed while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- double currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- my_input(window); animate(); // render // Backgound color glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //display(modelShader, ourModel, llantasModel); display(modelShader, text, /*pisoModel*/ cieloModel, aveModel, alaDerModel, alaIzqModel, PieDer, PieIzq, casa, comedor, alberca, sala, cocina, Salma, baño1, baño2, Javi, Mau, jardin, cochera, carro1, dron, carro2, robot, BrazoDer, BrazoIzq,Rosa);// dron llantas std::cout << "Frame:" << (1 / deltaTime) << std::endl; // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glfwTerminate(); return 0; } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- void my_input(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) animacion = true; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera.ProcessKeyboard(FORWARD, (float)deltaTime); animacion = true; } if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) camera.ProcessKeyboard(BACKWARD, (float)deltaTime); if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) camera.ProcessKeyboard(LEFT, (float)deltaTime); if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) camera.ProcessKeyboard(RIGHT, (float)deltaTime); if (glfwGetKey(window, GLFW_KEY_O) == GLFW_PRESS) { cam1 = false; cam2 = false; } if (glfwGetKey(window, GLFW_KEY_L) == GLFW_PRESS) { cam1 = true; cam2 = true; } if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { animacion = !animacion; } if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS) { animacion = true; recorridoAuto = 1; movAuto_z = 0.0; } ////////////////////CAMARAS///////////////////// if (glfwGetKey(window, GLFW_KEY_3) == GLFW_PRESS) { mul = 0.0f; rotP = 0.0f; cam1 = true; cam2 = false; ro = true; alSourcePlay(sources[0]); alSourceStop(sources[1]); } if (glfwGetKey(window, GLFW_KEY_1) == GLFW_PRESS) { camera.Cambio(glm::vec3(7.0f, 8.0f, 0.0f), 180); cam1 = true; cam2 = false; camera.ProcessMouseMovement(0.0f, 0.0f); alSourcePlay(sources[0]); alSourceStop(sources[1]); } if (glfwGetKey(window, GLFW_KEY_2) == GLFW_PRESS) { camera.Cambio(glm::vec3(-43.0f, 0.0f, 2.0f), 0); cam1 = true; cam2 = false; camera.ProcessMouseMovement(0.0f, 0.0f); alSourcePlay(sources[0]); alSourceStop(sources[1]); } /////////////////////////////////////////////////////// ////////////////////CAMARA PRINCIPAL////////////////// if (glfwGetKey(window, GLFW_KEY_0) == GLFW_PRESS) { cam1 = false; cam2 = false; ro = false; ho = false; camera.Cambio(glm::vec3(-21.0f, 3.0f, 20.0f), -90);//20.0f en z camera.ProcessMouseMovement(0.0f, 0.0f); alSourceStop(sources[1]); alSourceStop(sources[0]); } ///////////////////////////////////////////////////// //////////////////CAMARAS ///////////////////// if (glfwGetKey(window, GLFW_KEY_4) == GLFW_PRESS) { camera.Cambio(glm::vec3(7.0f, 8.0f, 0.0f), 180); camera.ProcessMouseMovement(0.0f, 0.0f); cam1 = false; cam2 = true;; alSourcePlay(sources[1]); alSourceStop(sources[0]); } if (glfwGetKey(window, GLFW_KEY_5) == GLFW_PRESS) { mul = 0.0f; cam1 = false; cam2 = true; ho = true; alSourcePlay(sources[1]); alSourceStop(sources[0]); } if (glfwGetKey(window, GLFW_KEY_6) == GLFW_PRESS) { camera.Cambio(glm::vec3(-43.0f, 0.0f, 2.0f), 0); cam1 = false; cam2 = true; camera.ProcessMouseMovement(0.0f, 0.0f); alSourcePlay(sources[1]); alSourceStop(sources[0]); } ////////////////////////////////////////////////////// //To play KeyFrame animation if (glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS) { if (FrameIndex < MAX_FRAMES) { aveFrame(); dronFrame(); carro1Frame(); robotFrame(); carro2Frame(); } if (play == false && (FrameIndex > 1)) { resetElements(); resetElements2(); resetElements3(); resetElements4(); resetElements5(); //First Interpolation interpolation(); interpolation2(); interpolation3(); interpolation4(); interpolation5(); play = true; playIndex = 0; i_curr_steps = 0; } } } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void resize(GLFWwindow* window, int width, int height) { // Set the Viewport to the size of the created window glViewport(0, 0, width, height); } // glfw: whenever the mouse moves, this callback is called // ------------------------------------------------------- void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } double xoffset = xpos - lastX; double yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(yoffset); }<file_sep># ProyectoTeoriaCG Proyecto final de Teoria para la materia de Computación Gráfica
df2b220c60453b44c9fd49566dbb4ca0bf97c1f6
[ "Markdown", "C++" ]
2
C++
SalmaFierro23/ProyectoTeoriaCG
095e41add9bdfca86bc0a28467e235c723c1cf6d
61e9b91cabca8083f0d01a1ffcabbabe1cd3b741
refs/heads/master
<file_sep>/* * 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.faw.jFrame; import javax.swing.table.DefaultTableModel; /** * * @author iloops */ public class Transaksi { //atribut private double subTotal = 0; private double detailBarang; private DefaultTableModel tabel = new DefaultTableModel(); public double countsubTotal(){ subTotal = 0; for(int i = 0; i<tabel.getRowCount();i++){ subTotal=subTotal+Double.parseDouble(tabel.getValueAt(i, 1).toString()); } return subTotal; } //method output hasil public String detailBarang(){ String detailBarang =""; for (int i = 0; i < tabel.getRowCount(); i++) { detailBarang += tabel.getValueAt(i, 0); } return detailBarang; } public double getSubTotal() { return subTotal; } public void setSubTotal(double subTotal) { this.subTotal = subTotal; } public double getDetailBarang() { return detailBarang; } public void setDetailBarang(double detailBarang) { this.detailBarang = detailBarang; } public DefaultTableModel getTabel() { return tabel; } public void setTabel(DefaultTableModel tabel) { this.tabel = tabel; } }
840e38908b1ce5e1c04bfacf423550c48fe9f3cf
[ "Java" ]
1
Java
fawwazramzy/pbo-quiz2
484f6a0f7dcd04fca92dad6b1be3fccc14678be0
c7c208f82735f8d31db775276e7a2f69578c5e01
refs/heads/master
<file_sep>-Es para Aprender y reutilizar usa bower y dejara en su defecto en la carpeta public/assets todo lo descargado con esta <file_sep>var unaRuta=[ { method:"GET", path:"/unaRuta", handler:function(request,write){ write("Hola una Ruta"); } } ]; module.exports=unaRuta;<file_sep>'use strict'; const Hapi=require("hapi"); const Path=require("path"); const Hoek=require("hoek"); const rutas=require("./config/routes/index.js"); const Moment=require("moment-timezone"); const ServerConfig=require("./config/server.js"); const server=new Hapi.Server(); server.connection(ServerConfig); server.register( [require("vision"),require("inert")], (er)=>{ Hoek.assert(!er,er); server.views({ engines:{ html:require("handlebars") }, relativeTo:__dirname, path:"./public", layoutPath:"./public/layout", helpersPath:"./public/helpers" }); server.route(rutas); } ); server.start( (er)=>{ if(er) throw er; console.log("Servidor Corriendo "+server.info.uri); var date=Moment().tz("America/Santiago").format("YYYY-MM-DD HH:MM:SS"); console.log(date); } );
12ebc088ed0ba7490a6d41a6c40cd5892ae34c6f
[ "Markdown", "JavaScript" ]
3
Markdown
mmedinabobadilla/hapihandlebars
0159be7bdddebacc699dd00f40e7cdcd3b4799c1
1fd987a4545e3e07d6d63e47161246144f47ed0b
refs/heads/main
<file_sep> export const useRouteName = () => { let name = "dashboard"; return name; }; <file_sep># esqueletoDjango Django, ReactJS, Material UI <file_sep>import React, {Component} from "react"; import {render} from "react-dom"; import Admin from "./Dashboard/src/layouts/Admin"; import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom"; import "./Dashboard/src/assets/css/material-dashboard-react.css?v=1.10.0" import RTL from "./Dashboard/src/layouts/RTL"; const App =(props) => { return ( <BrowserRouter> <Switch> <Route path="/admin" component={Admin} /> <Route path="/rtl" component={RTL} /> <Redirect from="/" to="/admin/dashboard" /> </Switch> </BrowserRouter> ); } const appDiv = document.getElementById("app"); render(<App name="tim" />, appDiv); export default App<file_sep>from django.contrib import admin from django.urls import path, include from .views import PrioritizationView, PrioritizationGetFile urlpatterns = [ path('priority',PrioritizationView.as_view()), path('get_priority',PrioritizationGetFile), ]<file_sep>/*! ========================================================= * Material Dashboard React - v1.10.0 ========================================================= * Product Page: https://www.creative-tim.com/product/material-dashboard-react * Copyright 2021 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/material-dashboard-react/blob/master/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import React from "react"; import ReactDOM from "react-dom"; import App from "./components/App";<file_sep>from django.contrib import admin # Register your models here. from .models import Prioritization admin.site.register(Prioritization) <file_sep># Generated by Django 3.0.1 on 2021-08-23 19:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.AlterField( model_name='prioritization', name='objective', field=models.IntegerField(), ), ] <file_sep># Generated by Django 3.0.1 on 2021-08-23 19:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20210823_1924'), ] operations = [ migrations.AddField( model_name='prioritization', name='rowid', field=models.IntegerField(default=1), ), ] <file_sep>from django.shortcuts import render import csv, io from django.shortcuts import render from django.contrib import messages from rest_framework import generics, status from rest_framework.views import APIView from .models import Prioritization from .serializers import PrioritizationSerializer # Create your views here. class PrioritizationView(generics.ListAPIView): queryset = Prioritization.objects.all() serializer_class = PrioritizationSerializer # one parameter named request def PrioritizationGetFile(request): # declaring template template = "prioritization_upload.html" data = Prioritization.objects.all() serializer_class = PrioritizationSerializer # prompt is a context variable that can have different values depending on their context prompt = { 'order': 'El orden del CSV debe ser: counter, name, project_name, issue_key, priority, priority_number, case_title, status, progress, sprint, due_date, sys_fiscal_week, created, a, project_size, report_table, request_item, request_owner, notes, objective, rowid', 'prioritization_info': data } # GET request returns the value of the data with the specified key. if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] # let's check if it is a csv file if not csv_file.name.endswith('.csv'): messages.error(request, 'Este no es un CSV :(') data_set = csv_file.read().decode('UTF-8') # setup a stream which is when we loop through each line we are able to handle a data in a stream io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created = Prioritization.objects.update_or_create( counter = column[0], name = column[1], project_name = column[2], issue_key = column[3], priority = column[4], priority_number = column[5] or 0, case_title = column[6], status = column[7], progress = column[8], sprint = column[9], due_date = column[10], sys_fiscal_week = column[11], created = column[12], a = column[13], project_size = column[14], report_table = column[15], request_item = column[16], request_owner = column[17], notes = column[18], objective = column[19], rowid = column[20] ) context = {} return render(request, template, context) <file_sep>import openpyxl wb = openpyxl.load_workbook("scpl.xlsx") sheets = wb.sheetnames print(wb.active.title) sh = wb['#LN00011'] data = sh['B3'].value print(data)<file_sep>const redux = require('redux'); const counterReducer = (state = {counter:0}, action) => { if(action.type === 'increment'){ return { counter: state.counter + 1 }; } if(action.type === 'decrement'){ return { counter: state.counter - 1 }; } }; const store = redux.createStore(counterReducer); const counterSuscriber = () => { //get the last state const latesState = store.getState(); console.log(latesState); } store.subscribe(counterSuscriber); store.dispatch({type:'increment'}); store.dispatch({type:'decrement'}); <file_sep>from django.db import models import string # Create your models here. def get_file_info(): return '' class Prioritization(models.Model): counter = models.IntegerField() name = models.CharField(max_length=50) project_name = models.CharField(max_length=50) issue_key = models.CharField(max_length=50) priority = models.CharField(max_length=50) priority_number = models.IntegerField() case_title = models.CharField(max_length=250) status = models.CharField(max_length=50) progress = models.CharField(max_length=50) sprint = models.CharField(max_length=50) due_date = models.CharField(max_length=50) sys_fiscal_week = models.CharField(max_length=50) created = models.CharField(max_length=50) a = models.CharField(max_length=50) project_size = models.CharField(max_length=50) report_table = models.CharField(max_length=50) request_item = models.CharField(max_length=100) request_owner = models.CharField(max_length=50) notes = models.CharField(max_length=100) objective = models.IntegerField() rowid = models.IntegerField(default=1) def _str_(self): return self.title<file_sep># Generated by Django 3.0.1 on 2021-08-23 19:04 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Prioritization', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('counter', models.IntegerField()), ('name', models.CharField(max_length=50)), ('project_name', models.CharField(max_length=50)), ('issue_key', models.CharField(max_length=50)), ('priority', models.CharField(max_length=50)), ('priority_number', models.IntegerField()), ('case_title', models.CharField(max_length=250)), ('status', models.CharField(max_length=50)), ('progress', models.CharField(max_length=50)), ('sprint', models.CharField(max_length=50)), ('due_date', models.CharField(max_length=50)), ('sys_fiscal_week', models.CharField(max_length=50)), ('created', models.CharField(max_length=50)), ('a', models.CharField(max_length=50)), ('project_size', models.CharField(max_length=50)), ('report_table', models.CharField(max_length=50)), ('request_item', models.CharField(max_length=100)), ('request_owner', models.CharField(max_length=50)), ('notes', models.CharField(max_length=100)), ('objective', models.IntegerField(unique=True)), ], ), ] <file_sep>import React, {useState} from 'react'; import Admin from "./Dashboard/src/layouts/Admin"; const DashboardUi = (props) =>{ const [counter, setCounter] = useState(0); return <Admin/>; } export default DashboardUi<file_sep>import React, {useState} from 'react'; import {BrowserRouter as Router, Switch, Route, Link, Redirect} from "react-router-dom"; const HomePage = (props) =>{ const [counter, setCounter] = useState(0); return ( <Router> <Switch> <Route exact path='/'> <p onClick={()=>setCounter(counter+1)}> Home Page {counter} </p> </Route> </Switch> </Router> ); } export default HomePage<file_sep>from rest_framework import serializers from .models import Prioritization class PrioritizationSerializer(serializers.ModelSerializer): class Meta: model = Prioritization fields = ('counter','name','project_name','issue_key','priority','priority_number', 'case_title','status','progress','sprint','due_date','sys_fiscal_week', 'created','a','project_size','report_table','request_item','request_owner' ,'notes','objective','rowid')
31db31674ce3fdae190acb6922a6d7669de0615c
[ "JavaScript", "Python", "Markdown" ]
16
JavaScript
OrlandoRocks/esqueletoDjango
e0f0550659dd630e64fb1e1007413c1f033e759d
1a3644887827f2247c32d10ccba977f3d66e542d
refs/heads/main
<file_sep>from client import Client from server import HOST, PORT class Messenger(Client): def __init__(self): super().__init__() def write(self): message = f"{self.nickname} : {self.input_area.get('1.0', 'end')}" self.sock.send(message.encode('utf-8')) self.input_area.delete('1.0', 'end') def stop(self): self.running = False self.screen.destroy() self.sock.close() exit() def receive(self): while self.running: try: message = self.sock.recv(1024) if message == 'NICK': self.sock.send(self.nickname.encode('utf-8')) else: if self.gui_done: self.text_area.config(state='normal') self.text_area.insert('end', message) self.text_area.yview('end') self.text_area.config(state='disabled') except ConnectionAbortedError: break except: print("Error") self.sock.close() break client = Client(HOST, PORT)<file_sep>import socket import threading import tkinter import tkinter.scrolledtext from tkinter import simpledialog from frontend import FrontEnd from messenger import Messenger HOST = '127.0.0.1' PORT = 9090 class Client: def __init__(self, host, port): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) msg = tkinter.Tk() msg.withdraw() self.nickname = simpledialog.askstring("Nickname", "please choose a nickname", parent=msg) self.gui_done = False self.running = True gui_thread = threading.Thread(target=self.gui_loop) receive_thread = threading.Thread(target=self.receive) gui_thread.start() receive_thread.start() self.frontend = FrontEnd() self.messenger = Messenger()<file_sep>import tkinter import tkinter.scrolledtext from tkinter import simpledialog import Client from messenger import write, stop class FrontEnd(Client): def __init__(self): super().__init__() def gui_loop(self): self.screen = tkinter.Tk() self.screen.configure(bg="lightgray") self.chat_label = tkinter.Label(self.screen, text="Chat: ", bg="lightgray") self.chat_label.config(font=("Arial", 12)) self.chat_label.pack(padx=20, pady=5) self.text_area = tkinter.scrolledtext.ScrolledText(self.screen) self.text_area.pack(padx=20, pady=5) self.text_area.config(state='disabled') self.msg_label = tkinter.Label(self.screen, text="Message", bg="lightgray") self.msg_label.config(font=("Arial", 12)) self.msg_label.pack(padx=20, pady=5) self.input_area = tkinter.Text(self.screen, height=3) self.input_area.pack(padx=20, pady=5) self.send_button = tkinter.Button(self.screen, text="Send", command=self.write) self.send_button.config(font=("Arial", 12)) self.send_button.pack(padx=20, pady=5) self.gui_done = True self.screen.protocol("WM_DELETE_WINDOW", self.stop) self.screen.mainloop()
edfafcbac3defbf99485b9aa4bcc1d60aef2b493
[ "Python" ]
3
Python
roblivesinottawa/chat_app
5681c0aaef4cf0483316d35cf3b44b17f7644f5f
5e601eb3e7d74205861985410e3496f7bed718db
refs/heads/master
<repo_name>VolitionDevelopment/google-maps<file_sep>/js/data.js function City(yearRank,city,state,yearEstimate,lastCensus,change,landArea,landAreaInKm,lastPopDensity,lastPopDensityInKM,latLon){ this.yearRank = yearRank; this.city = city; this.state = state; this.yearEstimate = yearEstimate; this.lastCensus = lastCensus; this.change = change; this.landArea = landArea; this.landAreaInKm = landAreaInKm; this.lastPopDensity = lastPopDensity; this.lastPopDensityInKM = lastPopDensityInKM; var latLonArray = latLon.split(","); this.lat = Number(latLonArray[0]); this.lon = Number(latLonArray[1]); this.latLon = latLon; } var cities = []; cities.push(new City("1","New York","New York","8,491,079","8,175,133","+3.86%","302.6 sq mi","783.8 km2","27,012 per sq mi","10,430 km−2","40.6643,-73.9385")); cities.push(new City("2","Los Angeles","California","3,928,864","3,792,621","+3.59%","468.7 sq mi","1,213.9 km2","8,092 per sq mi","3,124 km−2","34.0194,-118.4108")); cities.push(new City("3","Chicago","Illinois","2,722,389","2,695,598","+0.99%","227.6 sq mi","589.6 km2","11,842 per sq mi","4,572 km−2","41.8376,-87.6818")); cities.push(new City("4","Houston","Texas","2,239,558","2,100,263","+6.63%","599.6 sq mi","1,552.9 km2","3,501 per sq mi","1,352 km−2","29.7805,-95.3863")); cities.push(new City("5","Philadelphia","Pennsylvania","1,560,297","1,526,006","+2.25%","134.1 sq mi","347.3 km2","11,379 per sq mi","4,394 km−2","40.0094,-75.1333")); cities.push(new City("6","Phoenix","Arizona","1,537,058","1,445,632","+6.32%","516.7 sq mi","1,338.3 km2","2,798 per sq mi","1,080 km−2","33.5722,-112.0880")); cities.push(new City("7","San Antonio","Texas","1,436,697","1,327,407","+8.23%","460.9 sq mi","1,193.8 km2","2,880 per sq mi","1,112 km−2","29.4724,-98.5251")); cities.push(new City("8","San Diego","California","1,381,069","1,307,402","+5.63%","325.2 sq mi","842.2 km2","4,020 per sq mi","1,552 km−2","32.8153,-117.1350")); cities.push(new City("9","Dallas","Texas","1,281,047","1,197,816","+6.95%","340.5 sq mi","881.9 km2","3,518 per sq mi","1,358 km−2","32.7757,-96.7967")); cities.push(new City("10","San Jose","California","1,015,785","945,942","+7.38%","176.6 sq mi","457.3 km2","5,359 per sq mi","2,069 km−2","37.2969,-121.8193")); cities.push(new City("11","Austin","Texas","912,791","790,390","+15.49%","322.48 sq mi","835.2 km2","2,653 per sq mi","1,024 km−2","30.3072,-97.7560")); cities.push(new City("12","Jacksonville","Florida","853,382","821,784","+3.85%","747.0 sq mi","1,934.7 km2","1,120 per sq mi","433 km−2","30.3370,-81.6613")); cities.push(new City("13","San Francisco","California","852,469","805,235","+5.87%","46.9 sq mi","121.4 km2","17,179 per sq mi","6,633 km−2","37.7751,-122.4193")); cities.push(new City("14","Indianapolis","Indiana","848,788","820,445","+3.45%","361.4 sq mi","936.1 km2","2,270 per sq mi","876 km−2","39.7767,-86.1459")); cities.push(new City("15","Columbus","Ohio","835,957","787,033","+6.22%","217.2 sq mi","562.5 km2","3,624 per sq mi","1,399 km−2","39.9848,-82.9850")); cities.push(new City("16","Fort Worth","Texas","812,238","741,206","+9.58%","339.8 sq mi","880.1 km2","2,181 per sq mi","842 km−2","32.7795,-97.3463")); cities.push(new City("17","Charlotte","North Carolina","809,958","731,424","+10.74%","297.7 sq mi","771.0 km2","2,457 per sq mi","949 km−2","35.2087,-80.8307")); cities.push(new City("18","Detroit","Michigan","680,250","713,777","−4.70%","138.8 sq mi","359.4 km2","5,144 per sq mi","1,986 km−2","42.3830,-83.1022")); cities.push(new City("19","El Paso","Texas","679,036","649,121","+4.61%","255.2 sq mi","661.1 km2","2,543 per sq mi","982 km−2","31.8484,-106.4270")); cities.push(new City("20","Seattle","Washington","668,342","608,660","+9.81%","83.9 sq mi","217.4 km2","7,251 per sq mi","2,800 km−2","47.6205,-122.3509")); <file_sep>/README.md # google-maps A quick and dirty exploration into the Google Maps API ![alt-text](https://puu.sh/qxJd7/5fbf3c4d74.png "Maps")
848b7b6e4cc9c12324796c1c1bc01aefcc315029
[ "JavaScript", "Markdown" ]
2
JavaScript
VolitionDevelopment/google-maps
6f6944c75fef86b42d1e5f4789df1686978c5873
485e93b6df975f4878dd0acd1b9cd511b7de79e7
refs/heads/main
<file_sep>import matplotlib.pyplot as plot x_values = [1, 2, 3, 4, 5] y_values = [1, 8, 27, 64, 125] plot.scatter(x_values, y_values, c='green', s=40) plot.title("Cubic Numbers", fontsize=24) plot.xlabel("Value", fontsize=14) plot.ylabel("Value Cubic", fontsize=14) plot.show() x_values = list(range(1,5001)) y_values = [x**3 for x in x_values] plot.scatter(x_values, y_values, c=y_values, cmap=plot.cm.Greens, s=40) plot.title("Cubic Numbers", fontsize=24) plot.xlabel("Value", fontsize=14) plot.ylabel("Value Cubic", fontsize=14) plot.axis([0, 5000, 0, 5000**3]) plot.tick_params(axis='both', which='major', labelsize=14) plot.show() <file_sep>import pygal from pygal.style import LightColorizedStyle, RotateStyle import json from countries_code import get_country_code # Load data filename = "population_data.json" with open(filename) as f: population_data = json.load(f) # Print the 2010 population for each country. countrycode_populations = {} for population in population_data: if population['Year'] == '2010': country_name = population['Country Name'] population_total = int(float(population['Value'])) code = get_country_code(country_name) if code: countrycode_populations[code] = population_total # Group the countries into three populations levels populations_level_1, populations_level_2, populations_level_3, = {}, {}, {} for country_code, population in countrycode_populations.items(): if population < 10000000: populations_level_1[country_code] = population elif population < 1000000000: populations_level_2[country_code] = population else: populations_level_3[country_code] = population print( len(populations_level_1), len(populations_level_2), len(populations_level_3) ) world_map_style = RotateStyle('#336699', base_style=LightColorizedStyle) world_map = pygal.maps.world.World(style=world_map_style) world_map.title = "World population in 2010, by country" world_map.add('0-10m', populations_level_1) world_map.add('10m-1b', populations_level_2) world_map.add('>1b', populations_level_3) world_map.render_to_file('world_population.svg') <file_sep>import matplotlib.pyplot as plot values = [1, 2, 3, 4, 5] squares = [1, 4, 9, 16, 25] plot.plot(values, squares, linewidth=5) # Set chart title and label axes. plot.title("Square Numbers", fontsize=24) plot.xlabel("Value" , fontsize=14) plot.ylabel("Square of Value", fontsize=14) # Set size of tick labels. plot.tick_params(axis='both', labelsize=14) plot.show() <file_sep>import pygal from die import Die # Create Dices die_1 = Die(8) die_2 = Die(8) max_result = die_1.num_sides + die_2.num_sides roll_times = 100000000 # Make some rolls, and store results in a list results = [] for roll_num in range(roll_times): result = die_1.roll() + die_2.roll() results.append(result) # Analyze the results. frequencies = [] for value in range(2, max_result+1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results. historic = pygal.Bar() str_roll_times = str("{:,}".format(roll_times)) str_d1 = "D" + str(die_1.num_sides) str_d2 = "D" + str(die_2.num_sides) historic.title = ("Results of rolling a " + str_d1 + " and a " + str_d2 + " " + str_roll_times + " times.") labels = list(range(2,max_result+1)) historic.x_labels = labels historic.x_title = "Result" historic.y_title = "Frequency of Result" historic.add(str_d1 + "+" + str_d2, frequencies) historic.render_to_file('die_visual.svg') <file_sep># data_visualization codes training data visualization <file_sep>import requests import pygal from pygal.style import LightColorizedStyle as LCS, LightenStyle as LS # Make an API call and store the response. url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' response = requests.get(url) print("Status code:", response.status_code) response_dictionary = response.json() # Process results. print("Total repositories:", response_dictionary['total_count']) # Explore information about the repositories. repositories_dictionaries = response_dictionary['items'] names, plot_datas = [], [] print("\nSelected information about first repository:") for repository_dict in repositories_dictionaries: names.append(repository_dict['name']) plot_data = { 'value': repository_dict['stargazers_count'], 'label': repository_dict['description'] or "", 'xlink': repository_dict['html_url'] } plot_datas.append(plot_data) chart_style = LS('#333366', base_style=LCS) chart_config = pygal.Config() chart_config.x_label_rotation = 45 chart_config.show_legend = False chart_config.title_font_size = 24 chart_config.label_font_size = 14 chart_config.major_label_font_size = 18 chart_config.truncate_label = 15 chart_config.show_y_guides = False chart_config.width = 1000 chart = pygal.Bar(chart_config, style=chart_style) chart.title = "Most-starred Python projects on Github" chart.x_labels = names chart.add('', plot_datas) chart.render_to_file('python_repos.svg') <file_sep>import pygal from die import Die def get_str_d(dice): return "D" + str(die_1.num_sides) # Configs die_1 = Die() die_2 = Die() die_3 = Die() roll_times = 1000000 # Constants num_dices = 3 max_result = die_1.num_sides + die_2.num_sides + die_3.num_sides min_result = num_dices # Calcuating results = [] for roll_num in range(roll_times): result = die_1.roll() result += die_2.roll() result += die_3.roll() results.append(result) # Labels to plot and count frequency labels = list(range(min_result, max_result+1)) # Merge results frequencies = [] for value in labels: frequency = results.count(value) frequencies.append(frequency) # Visualize the results. chart = pygal.Bar() str_roll_times = str("{:,}".format(roll_times)) str_d1 = get_str_d(die_1) str_d2 = get_str_d(die_2) str_d3 = get_str_d(die_3) chart.title = "Results of rolling a " chart.title += str_d1 + ", " + str_d2 + " and a " + str_d3 chart.title += " " + str_roll_times + " times." chart.x_labels = labels chart.x_title = "Results" chart.y_title = " Frequency " chart.add(str_d1 + "+" + str_d2 + "+" + str_d3, frequencies) chart.render_to_file('die_visual.svg') <file_sep>import matplotlib.pyplot as plot from random_walk import RandomWalk # Keep making new walks while True: # Make a random walk, and plot the points rw = RandomWalk(5000) rw.fill_walk() # Set the size of the plotting window plot.figure(figsize=(20,12)) point_numbers = list(range(rw.num_points)) plot.plot(rw.x_values, rw.y_values, c="green", linewidth=5) # Mark the first and last points plot.scatter(0, 0, c='red', edgecolors='none', s=100) plot.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100) # Remove the axes. plot.axis('off') plot.show() keep_running = input("Make another walk? (y/n): ") while keep_running != 'y' and keep_running != 'n': keep_running = input("Make another walk? (y/n): ") if keep_running == 'n': break <file_sep>import pygal from die import Die # Create a D6. die_1 = Die() die_2 = Die() # Make some rolls, and store results in a list results = [] for roll_num in range(1000): result = die_1.roll() + die_2.roll() results.append(result) # Analyze the results. frequencies = [] max_result = die_1.num_sides + die_2.num_sides for value in range(2, max_result+1): frequency = results.count(value) frequencies.append(frequency) # Visualize the results. historic = pygal.Bar() historic.title = "Results of rolling two D6 1000 times." labels = list(range(2,max_result+1)) historic.x_labels = labels historic.x_title = "Result" historic.y_title = "Frequency of Result" historic.add('D6 + D6', frequencies) historic.render_to_file('die_visual.svg') <file_sep>import matplotlib.pyplot as plot x_values = list(range(1,1001)) y_values = [x**2 for x in x_values] plot.scatter(x_values, y_values, c=y_values, cmap=plot.cm.Blues, edgecolor='none', s=40) # Set chart title and label axes. plot.title("Square Numbers", fontsize=24) plot.xlabel("Value", fontsize=14) plot.ylabel("Square of Value", fontsize=14) # Set the range ofr each exis. plot.axis([0, 1100, 0, 1100000]) # Set size of tick labels. plot.tick_params(axis='both', which='major', labelsize=14) plot.savefig('squares_plot.png', bbox_inches='tight')
78377e2240a8cc93eeacbf23ff11d42765d85573
[ "Markdown", "Python" ]
10
Python
fernando-stteffen/data_visualization
9a7325edf32c9ba50bc7bf196620a042f1ca7f87
d210c5d27b58a02ff1405a8192c65b3b2447df2f
refs/heads/master
<repo_name>Pjmcnally/lolapp<file_sep>/api_query/tests_u.py from django.core.urlresolvers import resolve from django.test import TestCase from django.http import HttpRequest from django.template.loader import render_to_string from api_query.views import home_page # from lists.models import Item class NewVisitorTest(TestCase): def test_root_url_resolves_to_home_page_view(self): found = resolve('/') self.assertEqual(found.func, home_page) def test_home_page_returns_correct_html(self): request = HttpRequest() response = home_page(request) expected_html = render_to_string('home.html') self.assertEqual(response.content.decode(), expected_html) def test_home_page_can_save_a_POST_request(self): request = HttpRequest() request.method = 'POST' request.POST['summoner_name'] = 'Pjmcnally' response = home_page(request) self.assertIn('Pjmcnally', response.content.decode()) self.assertIn('45764164', response.content.decode()) expected_html = render_to_string( 'home.html', {'sum_name': 'Pjmcnally', 'sum_id': '45764164'} ) self.assertEqual(expected_html, response.content.decode()) # def test_home_page_only_saves_items_when_necessary(self): # request = HttpRequest() # home_page(request) # self.assertEqual(Item.objects.count(), 0) # class ItemModelTest(TestCase): # def test_saving_and_retrieving_items(self): # sum_name = Item() <file_sep>/README.md # Patrick's LoL App __Note__ This site is unfortunately now obsolete. Ongoing changes to the League of Legends API have made my site no longer work. Since this was create as a learning project I have not taken the time to update the project to keep it in line with the current LoL API. If I chose to continue work on this the goal would be to update, clean up, and incorporate this project into my portfolio page. If that occurs future development will happen in that repo. This project also needs to be modernized to work with new game modes and champions added by Riot. __Welcome to my PDX CodeGuild capstone project.__ League of Legends is a video game played, typically, between two teams of 5 people. The goal of the game is to fight the other team and to destroy their base. There are over 120 champions (playable characters) in the game and each of them can be configured many, many different ways. Knowing more about your opponents and your team can help you to play better and win more games. My app provides current game information about both the skill level of your opponents and the champions they playing as well as how that champion is configured. Use ----- To use Patrick's LoL App simply enter a League of Legends summoner name into the box on the home page. If that player is currently playing a game you will be taken to the dashboard where game data is displayed. Click any player to get more detailed info. Built with: ----- * Django 1.9.13 * PostgresSQL * JavaScript * jQuery * Bootstrap 3.3.6 * requests 2.9.1 * simplejson 3.3.1 * selenium 2.48.0 * Conda 3.18.6 * pip 7.1.2 * Sublime Text 3 * [Slide-in_Panel jQuery plugin](https://codyhouse.co/gem/css-slide-in-panel/) Installation ----- #### Establish the environment The root directory of this repository contains a "Requirements file", requirements.txt. To set up the environment required to run this web app first install [python](https://www.python.org/downloads/), [virtualenv and virtualenv wrapper](http://docs.python-guide.org/en/latest/dev/virtualenvs/). Type the following command to create a virtual environment using python 3.4: $ mkvirtualenv \<env name> -ppython3.4 Activate the virtual environment. $ workon \<env name> Install all of the required packages. $ pip3 install -r requirements.txt #### Fork the repository and clone it to your computer On GitHub, navigate to the [project repo](https://github.com/Pjmcnally/lolapp), click fork to create a personal copy, and then use [this guide](https://help.github.com/articles/fork-a-repo/) to clone your forked copy to your local computer. #### Create a League of Legends account and create secrets file with your API key. Go to the [Riot API Getting Started page](https://developer.riotgames.com/docs/getting-started) and follow the instructions to create an account and to get your API key. Create a file called secrets.py. The only line in this file should be: API_KEY = 'Put your API Key here (leave the quotes)' Copy the secrets file into the the two directories below: * lolapp/ * lolapp/api_query/fixtures #### Establish and populate the database Create a postgres user and a database for the app. The default database name is lolappdb. If you use a name other than lolappdb change the database section of lolapp/lolapp/settings.txt. Once the database has been established run the following terminal commands from the root of directory of your fork to populate the database. $ python api_query/fixtures/generate_fixtures.py $ python manage.py loaddata all_fix.json #### You are now good to go. From the repo's root directory (/lolapp/) run the following command to launch this web app. $ python3 manage.py runserver To-Do ----- ### Refactors & Minor improvements * Add input validation and sanitization * Refactor to add template inheritance * Add nav menu collapse * Refactor secrets file from two to opponents ### New features * Include ranked data for previous season * Add much more robust history data * Games played/won/lost * Average Kills/Deaths/Assists per game * Build new database with average stats per rank tier * Compare player stats to their ranked tier. Screenshots ----- [Home page](https://github.com/Pjmcnally/lolapp/blob/master/screenshots/Patricks%20LoL%20App%20Home.png) [Dashboard](https://github.com/Pjmcnally/lolapp/blob/master/screenshots/Patricks%20lol%20app%20dashboard.png) [Slide in panel](https://github.com/Pjmcnally/lolapp/blob/master/screenshots/Patricks%20LoL%20app%20slide%20in.png) <file_sep>/api_query/views.py from django.shortcuts import render, redirect from django.contrib import messages from api_query.models import Game from secrets import API_KEY import requests from datetime import timedelta from random import choice base_url = 'https://na.api.pvp.net/' region = 'na' platform = 'NA1' payload = {'api_key': API_KEY} # Create your views here. def home_page(request, error_msg=""): """ Renders home page with random featured game participant """ featured_url = 'https://na.api.pvp.net/observer-mode/rest/featured' r = requests.get(featured_url, params=payload) player_list = [] player = "" if r.status_code == 200: for game in r.json()['gameList']: for summ in game['participants']: player_list.append(summ['summonerName']) player = choice(player_list) else: messages.error(request, 'Featured game API is down at the moment.', extra_tags='api_down') return render(request, 'home.html', { 'player': player, }) def get_game(request): """ gets summoner ID and passes info to dashboard """ if request.POST: sum_name = request.POST.get('summoner_name', '') sum_id = get_id(sum_name) if sum_id == "error": messages.error(request, 'That does not appear to be a valid\ summoner name. Please try again', extra_tags='search') return redirect('/') else: return redirect('/dashboard?sum_id={sum_id}'.format( sum_id=str(sum_id))) else: return redirect('/') def get_id(sum_name): """ Makes API call to get player ID from summoner name and returns it """ id_url = '{b}api/lol/{r}/v1.4/summoner/by-name/{n}' sum_name = sum_name.replace(" ", "") r = requests.get(id_url.format(b=base_url, r=region, n=sum_name), params=payload) if r.status_code == 200: return r.json()[sum_name.lower()]['id'] else: return "error" def dashboard(request): """ renders dashboard """ sum_id = request.GET.get('sum_id', '') game_url = '{b}observer-mode/rest/consumer/getSpectatorGameInfo/{p}/{s_id}' rank_url = '{b}api/lol/{r}/v2.5/league/by-summoner/{ids}/entry' r = requests.get(game_url.format(b=base_url, p=platform, s_id=sum_id), params=payload) if r.status_code != 200: messages.error(request, 'That summoner is not currently playing a game.\ Please try again', extra_tags='search') return redirect('/') else: game_info = r.json() p_id_list = [summ['summonerId'] for summ in game_info['participants']] r = requests.get(rank_url.format(b=base_url, r=region, ids=", ".join(map(str, p_id_list))), params=payload) if r.status_code == 200: rank_info = r.json() else: rank_info = {} this_game = Game(game_info, rank_info) return render(request, 'dashboard.html', { 'id_searched': int(sum_id), 'blue_team': [x for x in this_game.players if x.team == "blue"], 'red_team': [x for x in this_game.players if x.team == "red"], 'map': this_game.map, 'mode': this_game.mode, 'time': timedelta(seconds=this_game.length), 'duration': this_game.length, }) <file_sep>/tests_f.py from selenium import webdriver from selenium.webdriver.common.keys import Keys import unittest class NewVisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) def tearDown(self): self.browser.quit() def test_can_enter_summoner_name_and_get_summoner_id(self): # A user, Patrick, starts a game of League of Legends. # Having heard about a new, aweseome, LoL site he navigates to it while # waiting to load into his game. self.browser.get('http://localhost:8000') # Patrick notices it says "Patrick's LoL App" in the title. self.assertIn("Patrick's LoL App", self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn("Patrick's LoL App", header_text) # He is invited to enter a summoner name inputbox = self.browser.find_element_by_id('sum_name_input') self.assertEqual( inputbox.get_attribute('placeholder'), 'Enter a summoner name' ) # He types his summoner name into the field. inputbox.send_keys('Pjmcnally') # When he hits enter the page changes and displays his summoner name inputbox.send_keys(Keys.ENTER) result = self.browser.find_element_by_id('name_result') self.assertIn('Pjmcnally', result.text) # and unique summoner ID (first step). result = self.browser.find_element_by_id('summoner_id') self.assertIn('45764164', result.text) # This is my summonder ID. # Patrick is sutibly impressed (which is to say not very impressed). self.fail("Finish writing tests") if __name__ == '__main__': unittest.main(warnings='ignore') <file_sep>/api_query/migrations/0003_auto_20160107_1909.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api_query', '0002_remove_mastery_descript'), ] operations = [ migrations.RenameModel( old_name='Champion', new_name='ChampStatic', ), migrations.RenameModel( old_name='Mastery', new_name='MastStatic', ), migrations.RenameModel( old_name='Rune', new_name='RuneStatic', ), migrations.RenameModel( old_name='Spell', new_name='SpellStatic', ), ] <file_sep>/api_query/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Champion', fields=[ ('id', models.IntegerField(serialize=False, primary_key=True)), ('name', models.CharField(default='', max_length=500)), ('descript', models.CharField(default='', max_length=500)), ('image', models.CharField(default='', max_length=500)), ('version', models.CharField(default='', max_length=500)), ], ), migrations.CreateModel( name='Mastery', fields=[ ('id', models.IntegerField(serialize=False, primary_key=True)), ('name', models.CharField(default='', max_length=500)), ('descript', models.CharField(default='', max_length=500)), ('tree', models.CharField(default='', max_length=500)), ('ranks', models.CharField(default='', max_length=500)), ('image', models.CharField(default='', max_length=500)), ('version', models.CharField(default='', max_length=500)), ], ), migrations.CreateModel( name='Rune', fields=[ ('id', models.IntegerField(serialize=False, primary_key=True)), ('name', models.CharField(default='', max_length=500)), ('descript', models.CharField(default='', max_length=500)), ('image', models.CharField(default='', max_length=500)), ('version', models.CharField(default='', max_length=500)), ], ), migrations.CreateModel( name='Spell', fields=[ ('id', models.IntegerField(serialize=False, primary_key=True)), ('name', models.CharField(default='', max_length=500)), ('descript', models.CharField(default='', max_length=500)), ('image', models.CharField(default='', max_length=500)), ('version', models.CharField(default='', max_length=500)), ], ), ] <file_sep>/api_query/models.py from django.db import models from abc import ABCMeta, abstractmethod class ChampStatic(models.Model): """ Class to store Riot static champion data in database""" id = models.IntegerField(primary_key=True) name = models.CharField(max_length=500, default='') descript = models.CharField(max_length=500, default='') image = models.CharField(max_length=500, default='') version = models.CharField(max_length=500, default='') class MastStatic(models.Model): """ Class to store Riot static mastery data in database""" id = models.IntegerField(primary_key=True) name = models.CharField(max_length=500, default='') descript = models.CharField(max_length=500, default='') tree = models.CharField(max_length=500, default='') ranks = models.CharField(max_length=500, default='') image = models.CharField(max_length=500, default='') version = models.CharField(max_length=500, default='') class RuneStatic(models.Model): """ Class to store Riot static rune data in database""" id = models.IntegerField(primary_key=True) name = models.CharField(max_length=500, default='') descript = models.CharField(max_length=500, default='') image = models.CharField(max_length=500, default='') version = models.CharField(max_length=500, default='') class SpellStatic(models.Model): """ Class to store Riot static summoner spell data in database""" id = models.IntegerField(primary_key=True) name = models.CharField(max_length=500, default='') descript = models.CharField(max_length=500, default='') image = models.CharField(max_length=500, default='') version = models.CharField(max_length=500, default='') class Game(): """ Class to store and process all game data Game class takes in a Current Game JSON object and a rank JSON object both of which are requested from Riots API. """ def __init__(self, game_json, rank_json): self.startTime = game_json['gameStartTime'] self.length = game_json['gameLength'] self.id = game_json['gameId'] self.start_time = game_json['gameStartTime'] self.mode = self.mode_name(game_json['gameQueueConfigId']) self.map = self.map_name(game_json['mapId']) self.bans = [] # place holder for future feature. self.players = [ Player(summ, rank_json) for summ in game_json['participants'] ] def __str__(self): return "Game length = {}\nGame Id = {}\nGame start time = {}\ \n{}\n{}".format(self.startTime, self.length, self.id, self.start_time, self.mode, self.map) def mode_name(self, info): """ converts mode id into human readable string """ mode_dict = { 0: "Custom game", 2: "Normal 5v5 (Blind Pick)", 4: "Ranked 5v5 (Solo Queue)", 6: "Ranked 5v5 (Premade)", 7: "Coop vs AI", 8: "Normal 3v3 (Draft Pick)", 9: "Ranked 3v3 (Premade)", 14: "Normal 5v5 (Draft Pick)", 16: "Dominion 5v5 (Blind Pick)", 17: "Dominion 5v5 (Draft Pick)", 25: "Dominion Coop vs AI", 31: "Coop vs AI (Intro Bots)", 32: "Coop vs AI (Beginner Bots)", 33: "Coop vs AI (Intermediate Bots)", 41: "Ranked Team 3v3", 42: "Ranked Team 5v5", 52: "Coop vs AI", 61: "Team Builder Game", 65: "ARAM", 70: "One for All", 72: "Snowdown 1v1", 73: "Snowdown 2v2", 75: "Hexakill (6v6)", 76: "Ultra Rapid Fire", 83: "Ultra Rapid Fire (Bots)", 91: "Doom Bots Rank 1", 92: "Doom Bots Rank 2", 93: "Doom Bots Rank 5", 96: "Ascension", 98: "Hexakill", 100: "Butcher's Bridge", 300: "Poro King", 310: "Nemesis", 313: "Black Market Brawlers", 400: "Normal 5v5 (Draft Pick)", 410: "Ranked 5v5 (Draft Pick)" } return mode_dict[info] def map_name(self, info): """ converts map id into human readable string """ map_dict = {10: "Twisted Treeline", 11: "Summoner's Rift", 12: "Howling Abyss"} return map_dict[info] class Player(): """ Class to store and process player data Player class takes in a portion of Current Game JSON object and a rank JSON object both of which are requested from Riots API. """ def __init__(self, summ, rank_info): self.id = summ['summonerId'] self.name = summ['summonerName'] self.team = self.team_func(summ['teamId']) self.champion = Champion(summ['championId']) self.spell1 = Spell(summ['spell1Id']) self.spell2 = Spell(summ['spell2Id']) self.runes = self.runes_func(summ['runes']) self.masteries = self.masteries_func(summ['masteries']) self.keystone = self.find_keystone(summ['masteries']) self.rank = self.parse_rank_info(self.id, rank_info) def __str__(self): return "{n} is playing {c}\n on {t} team".format(n=self.name, c=self.champion.name, t=self.team) def find_keystone(self, raw_mast): """ Identifies and returns keystone masteries The numbers below are magic numbers they are the range in which keystone masteries occur. """ for mast in raw_mast: if 6160 <= mast['masteryId'] <= 6169 or\ 6260 <= mast['masteryId'] <= 6269 or\ 6360 <= mast['masteryId'] <= 6369: return Mastery(mast['masteryId'], mast['rank']) return None def parse_rank_info(self, s_id, rank_info): """ Parses player and rank info and returns Rank object Takes in a player ID and rank JSON object and indetifies the rank of the player with the given ID and returns that as a rank object. If the player is not ranked None is returned. """ if str(s_id) in rank_info: for x in rank_info[str(s_id)]: if x["queue"] == "RANKED_SOLO_5x5": league = x["tier"] division = x["entries"][0]['division'] return Rank(league, division) return None def masteries_func(self, raw_mast): """ Counts and returns the number of each mastery per type """ masteries = {'ferocity': 0, 'cunning': 0, 'resolve': 0} for mast in raw_mast: if MastStatic.objects.get(id=mast['masteryId']).tree == "Ferocity": masteries['ferocity'] += mast['rank'] elif MastStatic.objects.get(id=mast['masteryId']).tree == "Cunning": masteries['cunning'] += mast['rank'] elif MastStatic.objects.get(id=mast['masteryId']).tree == "Resolve": masteries['resolve'] += mast['rank'] return "{f}/{c}/{r}".format(f=masteries['ferocity'], c=masteries['cunning'], r=masteries['resolve']) def runes_func(self, raw_runes): """ Takes in runes as part of a JSON object and returns a list of Rune objects """ runes = [] for rune in raw_runes: runes.append(Rune(rune["runeId"], rune["count"])) return runes def team_func(self, team): if team == 100: return "blue" elif team == 200: return "red" class Asset(object): """A base asset class for all Riot game assets""" __metaclass__ = ABCMeta link = None db_location = None def __init__(self, asset_id, num=1): self.name = self.db_location.objects.get(id=asset_id).name self.descript = self.db_location.objects.get(id=asset_id).descript self.image = self.db_location.objects.get(id=asset_id).image self.version = self.db_location.objects.get(id=asset_id).version self.image_link = self.link.format(v=self.version, n=self.image) self.num = num def __str__(self): return "{n}: {d}".format(n=self.name, d=self.descript) @abstractmethod def asset_type(): """"Return a string representing the type of asset this is.""" pass class Champion(Asset): """ Champion asset class """ link = "https://ddragon.leagueoflegends.com/cdn/{v}/img/champion/{n}.png" db_location = ChampStatic def asset_type(self): return 'Champion' class Spell(Asset): """ Spell asset class """ link = "https://ddragon.leagueoflegends.com/cdn/{v}/img/spell/{n}" db_location = SpellStatic def asset_type(self): return 'Spell' class Rune(Asset): """ Rune asset class """ link = "https://ddragon.leagueoflegends.com/cdn/{v}/img/rune/{n}" db_location = RuneStatic def asset_type(self): return 'Rune' class Mastery(Asset): """ Mastery asset class """ link = "https://ddragon.leagueoflegends.com/cdn/{v}/img/mastery/{n}" db_location = MastStatic def asset_type(self): return 'Mastery' class Rank(object): """ Rank asset class """ link = "/static/icons/{n}" def __init__(self, league, tier): self.name = "{} {}".format(league.capitalize(), tier) self.descript = "" # Placeholder self.image = "{}_{}.png".format(league.lower(), tier.lower()) self.image_link = self.link.format(n=self.image) <file_sep>/api_query/static/js/main.js jQuery(document).ready(function($){ //open the lateral panel $('.cd-btn').on('click', function(event){ event.preventDefault(); var parId = $(event.target).parent().attr("id"); $("."+parId).addClass('is-visible'); }); //clode the lateral panel $('.cd-panel').on('click', function(event){ if( $(event.target).is('.cd-panel') || $(event.target).is('.cd-panel-close') ) { $('.cd-panel').removeClass('is-visible'); event.preventDefault(); } }); var clock = document.getElementById("clock"); var time = document.getElementById("clockVar").value; setInterval(function() { time ++; if (time <= 0) { clock.innerHTML = "Loading"; } else { seconds = Math.floor(time % 60); minutes = Math.floor((time/60) % 60); hours = Math.floor(time/3600); clock.innerHTML = ": " + hours + ":" + checkNum(minutes) + ":" + checkNum(seconds); } }, 1000); function checkNum(num) { if (num < 10) { return "0" + num; } else { return num; } } });<file_sep>/api_query/fixtures/gen_all_fix.py import json import requests from secrets import API_KEY def list_check(stuff): if type(stuff) == list: return stuff.pop() else: return stuff def get_all_data(): output = [] def get_champ_data(): url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion" payload = {'api_key': API_KEY} r = requests.get(url, params=payload) data = r.json() version = data["version"] for val in data["data"].values(): champ = {} champ["pk"] = val["id"] champ["model"] = "api_query.ChampStatic" champ["fields"] = {} champ["fields"]["name"] = val["name"] champ["fields"]["descript"] = val["title"] champ["fields"]["image"] = val["key"] champ["fields"]["version"] = version output.append(champ) def get_mast_data(): url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/mastery" payload = {'masteryListData':'all', 'api_key': API_KEY} r = requests.get(url, params=payload) data = r.json() version = data["version"] for val in data["data"].values(): mast = {} mast["pk"] = val["id"] mast["model"] = "api_query.MastStatic" mast["fields"] = {} mast["fields"]["name"] = val["name"] mast["fields"]["descript"] = list_check(val["sanitizedDescription"]) mast["fields"]["tree"] = val["masteryTree"] mast["fields"]["ranks"] = val["ranks"] mast["fields"]["image"] = val["image"]["full"] mast["fields"]["version"] = version output.append(mast) def get_rune_data(): url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/rune" payload = {'runeListData':'all', 'api_key': API_KEY} r = requests.get(url, params=payload) data = r.json() version = data["version"] for val in data["data"].values(): rune = {} rune["pk"] = val["id"] rune["model"] = "api_query.RuneStatic" rune["fields"] = {} rune["fields"]["name"] = val["name"] rune["fields"]["descript"] = val["sanitizedDescription"] rune["fields"]["image"] = val["image"]["full"] rune["fields"]["version"] = version output.append(rune) def get_spell_data(): url = "https://global.api.pvp.net/api/lol/static-data/na/v1.2/summoner-spell" payload = {'spellData':'all', 'api_key': API_KEY} r = requests.get(url, params=payload) data = r.json() version = data["version"] for val in data["data"].values(): spell = {} spell["pk"] = val["id"] spell["model"] = "api_query.SpellStatic" spell["fields"] = {} spell["fields"]["name"] = val["name"] spell["fields"]["descript"] = val["sanitizedDescription"] spell["fields"]["image"] = val["image"]["full"] spell["fields"]["version"] = version output.append(spell) get_champ_data() get_mast_data() get_rune_data() get_spell_data() with open('all_fix.json', "w") as f: json.dump(output, f, indent=2) if __name__ == '__main__': get_all_data() <file_sep>/requirements.txt Django==1.11.29 psycopg2==2.6.1 requests>=2.20.0 simplejson==3.8.1
e7b97ff2fd9e0a37fe22639fe34019159c1491ff
[ "Markdown", "Python", "JavaScript", "Text" ]
10
Python
Pjmcnally/lolapp
078aa0cbd16aa6e1eb0f856408dd3638c558b983
95f47e58dc60644649fd2b69c8a2f3af54c947c2
refs/heads/master
<file_sep># DC-Project The Scene...You arrive in a museum, with offices and rooms surrounding. You have a priceless stolen artifact in your hand and your fingerprints are everywhere! You need to get out, without being caught. The night guards are armed and constantly patrolling the building. How the game works: if you get caught you must restart from that room you were in. However the rest of the level resets and all your previous collected items are lost. If you get shot: Same as before and you escape. Game ends. All scores saved. BONUS MISSIONS: 1. no deaths = +1000 points 2. no shooting = +2000 points 3. Die 100 times = +1 points 4. Don't use any diagonal moves = +1000 points 5. spend 10+ minutes on 1 attempt = +500 points Highscores are saved in HIGH SCORES folder in the repository. <file_sep>import pygame import os import ctypes from time import sleep pygame.init() BLACK = (0, 0, 0) RED = (255,0,0) #Definign Colours GREEN = (0, 255, 0) # v BLUE = (0, 0, 255) # v GRAY = ( 128, 128, 128) #---------------- BROWN = (182, 155, 76) LIGHTBLUE = (78, 104, 183) WALLGREY = (93, 100, 51) DOOR = (139,69,19) bullet_hit_list = pygame.sprite.Group() block_list = pygame.sprite.Group() all_sprites_list = pygame.sprite.Group() # a list for all the sprites within the gaem bullet_list = pygame.sprite.Group() # list for the bullets imagelist = pygame.sprite.Group() # images which dont act as a wall list enemylist = pygame.sprite.Group() # list for the enemies walllist = pygame.sprite.Group() # list for the walls playerlist = pygame.sprite.Group() #putting player in its own list screen= pygame.display.set_mode((800, 800))#Screen size keypress = pygame.key.get_pressed() rol = 0 #right or left setting to 0 uod = 0 # setting up or down to 0 score = 0 deaths = 99 myfont = pygame.font.SysFont("monospace", 30) # set font for the game key = 0 # flag type attribute for if key has been collected clock = pygame.time.Clock() #taking the pygame clock RC = 1 roomnumber = 1 rooms = [0, 0] #============================================================================================== #--------------------------------------------Classes------------------------------------------- #============================================================================================== class Player(pygame.sprite.Sprite): def __init__(self, health, zero, damage): self.health = health #Creating attributes of PLAYER --to be used later in game self.velocityx = zero # v self.velocityy = zero # v self.damage = damage self.roomchange = 1 #------------------------------------------------------ super().__init__() self.image = pygame.image.load("N.png") #Load default image for player self.rect = self.image.get_rect() self.direction=100 def facing(rol, uod): if keypress[pygame.K_RIGHT]:#Determining the durection of user (If Right AND.... if keypress[pygame.K_UP]: #If Right and up player.image = pygame.image.load("NE.png") #Change player image to NE.png player.direction=2 elif keypress[pygame.K_DOWN]: #If right and down player.image = pygame.image.load("SE.png") #Change player image to SE.png player.direction=4 else: #If it isnt up or down or left then it must be right which is East player.image = pygame.image.load("E.png") #change player image to E.png player.direction=3 elif keypress[pygame.K_LEFT]: #Same system with the left side of the compass if keypress[pygame.K_UP]: #If left and up player.image = pygame.image.load("NW.png") #Change player image to NW.png player.direction=8 elif keypress[pygame.K_DOWN]: #If left and down player.image = pygame.image.load("SW.png") #Change player image to SW.png player.direction=6 else: #If it isnt up or down or right then it must be left which is West player.image = pygame.image.load("W.png") #Change player image to W.png player.direction=7 elif keypress[pygame.K_DOWN]: #Is it north or south and changing player.image = pygame.image.load("S.png") # Image player.direction=5 else: # v player.image = pygame.image.load("N.png") player.direction=1 #--------------------------------- def moving(): #Moving function consisting of direction + the determined velocity. player.rect.centerx = player.rect.centerx + player.velocityx player.rect.centery = player.rect.centery + player.velocityy def newroomchange(): # has the player left the boundaries of the map? 800 x 800 map, if so set room to change if player.rect.bottom <= 0: player.rect.bottom = 800 rooms[1] = rooms[1] + 1 player.roomchange = 1 if player.rect.top >= 800: player.rect.top = 0 rooms[1] = rooms[1] - 1 player.roomchange = 1 if player.rect.right <= 0: player.rect.right = 800 rooms[0] = rooms[0] - 1 player.roomchange = 1 if player.rect.left >= 800: player.rect.left = 0 rooms[0] = rooms[0] + 1 player.roomchange = 1 def update(self): # Update the player's position # Get the current mouse position. This returns the position pos = pygame.mouse.get_pos() class Enemy(pygame.sprite.Sprite): def __init__(self): # initial position super().__init__() self.image = pygame.image.load("enemy.png") #Load default image for enemy self.rect = self.image.get_rect() def move(speed): # Movement along x direction if enemy.rect.centerx > player.rect.centerx: enemy.rect.centerx -= speed elif enemy.rect.centerx < player.rect.centerx: enemy.rect.centerx += speed # Movement along y direction if enemy.rect.centery < player.rect.centery: enemy.rect.centery += speed elif enemy.rect.centery > player.rect.centery: enemy.rect.centery -= speed class Enemy2(pygame.sprite.Sprite): def __init__(self): # initial position super().__init__() self.image = pygame.image.load("enemy.png") #Load default image for enemy No 2 self.rect = self.image.get_rect() def move(speed): # Movement along x direction if enemy2.rect.centerx > player.rect.centerx: enemy2.rect.centerx -= speed elif enemy2.rect.centerx < player.rect.centerx: enemy2.rect.centerx += speed # Movement along y direction if enemy2.rect.centery < player.rect.centery: enemy2.rect.centery += speed elif enemy2.rect.centery > player.rect.centery: enemy2.rect.centery -= speed class Wall(pygame.sprite.Sprite): #wall def, used for all wall in the game def __init__(self, width, height, colour ): self.colour = colour super().__init__() self.image = pygame.Surface([width, height]) self.image.fill(self.colour) self.rect = self.image.get_rect() #------------------------------------------------------------------------------------- # THE FOLLOWING DEFENITIONS ARE VARIABLES OF WALLS IN WHICH DIFFERENT IMAGES ARE USED #------------------------------------------------------------------------------------- class Bench(pygame.sprite.Sprite): def __init__(self, width, height): super().__init__() self.image = pygame.image.load("bench1.png") self.rect = self.image.get_rect() class FrontDesk(pygame.sprite.Sprite): def __init__(self, width, height): super().__init__() self.image = pygame.image.load("desk.png") self.rect = self.image.get_rect() class Desk1(pygame.sprite.Sprite): def __init__(self, width, height): super().__init__() self.image = pygame.image.load("desk1.png") self.rect = self.image.get_rect() class Sofa(pygame.sprite.Sprite): def __init__(self, width, height): super().__init__() self.image = pygame.image.load("sofa.png") self.rect = self.image.get_rect() class Sofa1(pygame.sprite.Sprite): def __init__(self, width, height): super().__init__() self.image = pygame.image.load("sofa1.png") self.rect = self.image.get_rect() class Image(pygame.sprite.Sprite): def __init__(self, width, height): super().__init__() self.image = pygame.image.load("download.png") self.rect = self.image.get_rect() class Floor(pygame.sprite.Sprite): def __init__(self, width, height): super().__init__() self.image = pygame.image.load("floor.jpg") self.rect = self.image.get_rect() class Bullet(pygame.sprite.Sprite): """ This class represents the bullet . """ def __init__(self, player_x, player_y, player_direction): # Call the parent class (Sprite) constructor super().__init__() self.image = pygame.Surface([3, 3]) self.image.fill(BLACK) self.rect = self.image.get_rect() self.rect.x=player_x self.rect.y=player_y #self.direction=player_direction def move(self): if player.direction==1: self.rect.y-=8 if player.direction==2: self.rect.x+=8 self.rect.y-=8 if player.direction==3: self.rect.x+=8 if player.direction==4: self.rect.x+=8 self.rect.y+=8 if player.direction==5: self.rect.y+=8 if player.direction==6: self.rect.x-=8 self.rect.y+=8 if player.direction==7: self.rect.x-=8 if player.direction==8: self.rect.x-=8 self.rect.y-=8 ##def MakeBullet() #Searchable locations: class Box(pygame.sprite.Sprite): def __init__(self, width, height): super().__init__() self.image = pygame.image.load("box.png") self.rect = self.image.get_rect() def Score(): # Pretty simply a score message_display(score) def Deaths(): # Pretty simply a score message_display(deaths) #image = Image() enemy = Enemy() #assingment enemy2 = Enemy2() #assingment def newrooms(): #location of rooms called from Rooms() and locations of enemies if rooms == [-1,1]: roomnumber = 9 if rooms[0] == 0 and rooms[1] == 1: print("triggered") roomnumber = 2 enemy2 = Enemy2() enemy2.rect.centerx = 700 enemy2.rect.centery = 700 enemylist.add(enemy2) if rooms == [1,1]: roomnumber = 3 enemy.rect.centerx = 100 enemy.rect.centery = 100 enemylist.add(enemy) if rooms == [-1,0]: roomnumber = 8 enemy.rect.centerx = 100 enemy.rect.centery = 100 enemylist.add(enemy) ## enemy2 = Enemy2() ## enemy2.rect.centerx = 700 ## enemy2.rect.centery = 700 ## enemylist.add(enemy2) if rooms[0] == 0 and rooms[1] == 0: # determin9ing the room in which the player is roomnumber = 1 if rooms == [1, 0]: roomnumber = 4 if rooms == [-1,-1]: roomnumber = 7 #enemy = Enemy() enemy.rect.centerx = 100 enemy.rect.centery = 100 enemylist.add(enemy) if rooms == [0,-1]: roomnumber = 6 if rooms == [1,-1]: roomnumber = 5 #============================================================================== # ________ ________ ________ _____ ______ _____ # # |\ __ \|\ __ \|\ __ \|\ _ \ _ \ / __ \ # # \ \ \|\ \ \ \|\ \ \ \|\ \ \ \\\__\ \ \ |\/_|\ \ # # \ \ _ _\ \ \\\ \ \ \\\ \ \ \\|__| \ \ \|/ \ \ \ # # \ \ \\ \\ \ \\\ \ \ \\\ \ \ \ \ \ \ \ \ \ # # \ \__\\ _\\ \_______\ \_______\ \__\ \ \__\ \ \__\ # # \|__|\|__|\|_______|\|_______|\|__| \|__| \|__| # # # #============================================================================== if roomnumber == 1: #===========================DEFAULT WALLS wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #=============================END bench = Bench(300, 300) bench.rect.left = 20 bench.rect.bottom = 780 walllist.add(bench) bench = Bench(300, 300) bench.rect.right = 780 bench.rect.bottom = 780 walllist.add(bench) #image = Image(300, 300) #image.rect.right = 780 #image.rect.bottom = 780 #imagelist.add(image) #============================================================================== # ________ ________ ________ _____ ______ _____ # # |\ __ \|\ __ \|\ __ \|\ _ \ _ \ / ___ \ # # \ \ \|\ \ \ \|\ \ \ \|\ \ \ \\\__\ \ /__/|_/ /| # # \ \ _ _\ \ \\\ \ \ \\\ \ \ \\|__| \ \ |__|// / / # # \ \ \\ \\ \ \\\ \ \ \\\ \ \ \ \ \ \ / /_/__ # # \ \__\\ _\\ \_______\ \_______\ \__\ \ \__\ |\________\ # # \|__|\|__|\|_______|\|_______|\|__| \|__| \|_______| # # # #============================================================================== if roomnumber == 2: #===========================DEFAULT WALLS wall = Wall(1100, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #=============================END wall = Wall(5, 590, WALLGREY) #Long Wall wall.rect.centerx = 326 wall.rect.bottom = 600 walllist.add(wall) wall = Wall(5, 344, WALLGREY) #Short wall wall.rect.centerx = 326 wall.rect.centery = 850 walllist.add(wall) wall = Wall(350, 5, WALLGREY) #office horizontal wall.rect.centerx = 650 wall.rect.centery = 477 walllist.add(wall) wall = Wall(5, 320, WALLGREY) #office verticle wall.rect.centerx = 477 wall.rect.bottom = 800 walllist.add(wall) wall = Wall(100, 5, DOOR) #office door right wall.rect.centerx = 550 wall.rect.centery = 477 walllist.add(wall) wall = Wall(100, 5, DOOR) #office door left wall.rect.centerx = 279 wall.rect.centery = 675 walllist.add(wall) wall = Wall(160, 5, WALLGREY) #office top left (left wall) wall.rect.centerx = 90 wall.rect.centery = 322.5 walllist.add(wall) wall = Wall(100, 5, WALLGREY) #office top left (right wall) wall.rect.right = 325 wall.rect.centery = 322.5 walllist.add(wall) wall = Wall(100, 5, WALLGREY) #office top right (left wall) wall.rect.right = 800 wall.rect.centery = 260 walllist.add(wall) wall = Wall(250, 5, WALLGREY) #office door right (right wall) wall.rect.left = 325 wall.rect.centery = 260 walllist.add(wall) #============================================================================== # ________ ________ ________ _____ ______ ________ # # |\ __ \|\ __ \|\ __ \|\ _ \ _ \ |\_____ \ # # \ \ \|\ \ \ \|\ \ \ \|\ \ \ \\\__\ \ \ \|____|\ /_ # # \ \ _ _\ \ \\\ \ \ \\\ \ \ \\|__| \ \ \|\ \ # # \ \ \\ \\ \ \\\ \ \ \\\ \ \ \ \ \ \ __\_\ \ # # \ \__\\ _\\ \_______\ \_______\ \__\ \ \__\ |\_______\ # # \|__|\|__|\|_______|\|_______|\|__| \|__| \|_______| # # # #============================================================================== if roomnumber == 3: #===========================DEFAULT WALLS wall = Wall(1100, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 1100, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #=============================END #============================================================================== # ________ ________ ________ _____ ______ ___ ___ # # |\ __ \|\ __ \|\ __ \|\ _ \ _ \ |\ \ |\ \ # # \ \ \|\ \ \ \|\ \ \ \|\ \ \ \\\__\ \ \ \ \ \\_\ \ # # \ \ _ _\ \ \\\ \ \ \\\ \ \ \\|__| \ \ \ \______ \ # # \ \ \\ \\ \ \\\ \ \ \\\ \ \ \ \ \ \ \|_____|\ \ # # \ \__\\ _\\ \_______\ \_______\ \__\ \ \__\ \ \__\ # # \|__|\|__|\|_______|\|_______|\|__| \|__| \|__| # # # #============================================================================== if roomnumber == 4: #===========================DEFAULT WALLS wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 1100, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #=============================END #============================================================================== # ________ ________ ________ _____ ______ |\ ____\ # # |\ __ \|\ __ \|\ __ \|\ _ \ _ \ \ \ \___|_ # # \ \ \|\ \ \ \|\ \ \ \|\ \ \ \\\__\ \ \ \ \_____ \ # # \ \ _ _\ \ \\\ \ \ \\\ \ \ \\|__| \ \ \|____|\ \ # # \ \ \\ \\ \ \\\ \ \ \\\ \ \ \ \ \ \ ____\_\ \ # # \ \__\\ _\\ \_______\ \_______\ \__\ \ \__\ |\_________\ # # \|__|\|__|\|_______|\|_______|\|__| \|__| \|_________| # # # #============================================================================== if roomnumber == 5: #===========================DEFAULT WALLS wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(1100, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 1100, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #=============================END #============================================================================== # ________ ________ ________ _____ ______ ________ # # |\ __ \|\ __ \|\ __ \|\ _ \ _ \ |\ ____\ # # \ \ \|\ \ \ \|\ \ \ \|\ \ \ \\\__\ \ \ \ \ \___| # # \ \ _ _\ \ \\\ \ \ \\\ \ \ \\|__| \ \ \ \ \___ # # \ \ \\ \\ \ \\\ \ \ \\\ \ \ \ \ \ \ \ \ ___ \ # # \ \__\\ _\\ \_______\ \_______\ \__\ \ \__\ \ \_______\ # # \|__|\|__|\|_______|\|_______|\|__| \|__| \|_______| # # # #============================================================================== if roomnumber == 6: #===========================DEFAULT WALLS wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(1100, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #=============================END #============================================================================== # ________ ________ ________ _____ ______ ________ # # |\ __ \|\ __ \|\ __ \|\ _ \ _ \ |\_____ \ # # \ \ \|\ \ \ \|\ \ \ \|\ \ \ \\\__\ \ \ \|___/ /| # # \ \ _ _\ \ \\\ \ \ \\\ \ \ \\|__| \ \ / / / # # \ \ \\ \\ \ \\\ \ \ \\\ \ \ \ \ \ \ / / / # # \ \__\\ _\\ \_______\ \_______\ \__\ \ \__\ /__/ / # # \|__|\|__|\|_______|\|_______|\|__| \|__| |__|/ # # # #============================================================================== if roomnumber == 7: #===========================DEFAULT WALLS wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(1100, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 1100, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #=============================END wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #============================================================================== # ________ ________ ________ _____ ______ ________ # # |\ __ \|\ __ \|\ __ \|\ _ \ _ \ |\ __ \ # # \ \ \|\ \ \ \|\ \ \ \|\ \ \ \\\__\ \ \ \ \ \|\ \ # # \ \ _ _\ \ \\\ \ \ \\\ \ \ \\|__| \ \ \ \ __ \ # # \ \ \\ \\ \ \\\ \ \ \\\ \ \ \ \ \ \ \ \ \|\ \ # # \ \__\\ _\\ \_______\ \_______\ \__\ \ \__\ \ \_______\ # # \|__|\|__|\|_______|\|_______|\|__| \|__| \|_______| # # # #============================================================================== if roomnumber == 8: #===========================DEFAULT WALLS wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 1100, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #=============================END desk = FrontDesk(300, 300) desk.rect.centerx = 400 desk.rect.bottom = 400 walllist.add(desk) desk = FrontDesk(300, 300) desk.rect.centerx = 400 desk.rect.top = 400 walllist.add(desk) # desk1 = Desk1(300, 300) desk1.rect.centerx = 100 desk1.rect.bottom = 150 walllist.add(desk1) desk1 = Desk1(300, 300) desk1.rect.centerx = 100 desk1.rect.top = 225 walllist.add(desk1) desk1 = Desk1(128, 128) desk1.rect.centerx = 100 desk1.rect.top = 450 walllist.add(desk1) desk1 = Desk1(128, 128) desk1.rect.centerx = 100 desk1.rect.bottom = 775 walllist.add(desk1) # sofa = Sofa(300, 300) sofa.rect.right = 740 sofa.rect.bottom = 780 walllist.add(sofa) sofa = Sofa(128, 128) sofa.rect.right = 600 sofa.rect.bottom = 780 walllist.add(sofa) sofa1 = Sofa1(300, 300) sofa1.rect.centerx = 770 sofa1.rect.bottom = 730 walllist.add(sofa1) sofa1 = Sofa1(300, 300) sofa1.rect.centerx = 770 sofa1.rect.bottom = 600 walllist.add(sofa1) # #============================================================================== # ________ ________ ________ _____ ______ ________ # # |\ __ \|\ __ \|\ __ \|\ _ \ _ \ |\ ___ \ # # \ \ \|\ \ \ \|\ \ \ \|\ \ \ \\\__\ \ \ \ \____ \ # # \ \ _ _\ \ \\\ \ \ \\\ \ \ \\|__| \ \ \|____|\ \ # # \ \ \\ \\ \ \\\ \ \ \\\ \ \ \ \ \ \ __\_\ \ # # \ \__\\ _\\ \_______\ \_______\ \__\ \ \__\ |\_______\ # # \|__|\|__|\|_______|\|_______|\|__| \|__| \|_______| # # # #============================================================================== if roomnumber == 9: #===========================DEFAULT WALLS wall = Wall(1100, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(650, 30, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 1100, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 0 wall.rect.centery = 800 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 0 walllist.add(wall) wall = Wall(30, 650, LIGHTBLUE) wall.rect.centerx = 800 wall.rect.centery = 800 walllist.add(wall) #=============================END wall = Wall(100, 5, WALLGREY) # office horizontal wall.rect.right = 800 wall.rect.centery = 200 walllist.add(wall) wall = Wall(100, 5, WALLGREY) # office horizontal wall.rect.right = 650 wall.rect.centery = 200 walllist.add(wall) wall = Wall(100, 5, WALLGREY) # office horizontal wall.rect.right = 550 wall.rect.centery = 200 walllist.add(wall) wall = Wall(100, 5, WALLGREY) # office horizontal wall.rect.right = 400 wall.rect.centery = 200 walllist.add(wall) wall = Wall(100, 5, WALLGREY) # office horizontal wall.rect.right = 300 wall.rect.centery = 200 walllist.add(wall) wall = Wall(100, 5, WALLGREY) # office horizontal wall.rect.right = 150 wall.rect.centery = 200 walllist.add(wall) wall = Wall(5, 200, WALLGREY) wall.rect.centerx = 550 wall.rect.top = 0 walllist.add(wall) wall = Wall(5, 200, WALLGREY) wall.rect.centerx = 300 wall.rect.top = 0 walllist.add(wall) wall = Wall(5, 200, WALLGREY) wall.rect.centerx = 100 wall.rect.top = 0 walllist.add(wall) #=============================================================================================== #------------------------------Variable setting/code before loop-------------------------------- #=============================================================================================== for counter in range(1): player = Player(100, 0, 10) #Setting Players Health and samage player.rect.centerx = 137 #Setting players start X co-ordinate player.rect.centery = 137 #Setting players start Y co-ordinate playerlist.add(player) pygame.display.set_caption("Game Game") #Setting caption at top to Game all_sprites_list.add(enemy) all_sprites_list.add(player) block_list.add(enemy) #roomnumber = 1 #enemy = Enemy() #enemy.rect.centerx = 100 #enemy.rect.centery = 100 #enemylist.add(enemy) #enemy2 = Enemy2() #enemy.rect.centerx = 700 #enemy.rect.centery = 700 #enemylist.add(enemy2) ctypes.windll.user32.MessageBoxW(0, "You have 1 life, 1 mission. Find a way out", "Welcome to 9tmare", 1) #=============================================================================================== #------------------------------------------Game Loop-------------------------------------------- #=============================================================================================== done = False while not done: #Inputs for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEBUTTONDOWN: # Fire a bullet if the user clicks the mouse button bullet = Bullet() # Set the bullet so it is where the player is bullet.rect.x = player.rect.centerx bullet.rect.y = player.rect.centery # Add the bullet to the lists all_sprites_list.add(bullet) bullet_list.add(bullet) all_sprites_list.update() if player.roomchange == 1: walllist = pygame.sprite.Group() newrooms() player.roomchange = 0 print("trig") if keypress[pygame.K_LEFT]: # if left hey is pressed player.velocityx = - 3 # X velocity set to go backwards rol = 2 # rol value set to 2 to be used later for player in playerlist: Player.facing(rol, uod) elif keypress[pygame.K_RIGHT]: # if right key is pressed player.velocityx = 3 # X velocity is set to go forewards 1 rol = 1 # rol value set to 1 for player in playerlist: Player.facing(rol, uod) player_x=player.rect.centerx player_y=player.rect.centery if keypress[pygame.K_y]: print("hello") bullet=Bullet(player_x, player_y, player.direction) bullet_list.add(bullet) bullet.move() if keypress[pygame.K_UP]: # if up key is pressed player.velocityy = - 3 # Y velocity set to go down 1 which is up in pygame uod = 1 # uod value set to 2 for player in playerlist: Player.facing(rol, uod) elif keypress[pygame.K_DOWN]: # if down key is pressed player.velocityy = 3 # Y velocity set to go up 1 which is down in pyagme uod = 2 # uod value set to 2 for player in playerlist: Player.facing(rol, uod) if player.rect.centerx >= 50 and player.rect.centerx <= 100 and player.rect.centery >= 50 and player.rect.centery <= 100 and rooms == [-1, 1] and keypress[pygame.K_f]: ctypes.windll.user32.MessageBoxW(0, "You found a key, but whats it for?", "Alert", 1) key = 1 if key == 1 and player.rect.centerx >= 700 and player.rect.centerx <= 800 and player.rect.centery >= 0 and player.rect.centery <= 100 and rooms == [1, -1] and keypress[pygame.K_f]: ctypes.windll.user32.MessageBoxW(0, "you made it out!!", "Congratulations", 1) break for player in playerlist: Player.moving() Player.newroomchange() # Searching zone, multiple of the smae systems #end of searching zones for enemy in enemylist: Enemy.move(1) for enemy2 in enemylist: Enemy2.move(1) for bullet in bullet_list: bullet.move() if player.roomchange == 1: enemylist.remove(enemy) if player.roomchange == 1: enemylist.remove(enemy2) ## if pygame.spritecollide(bullet_list, enemylist): ## enemylist.remove(enemy) ## bullet_list.remove(bullet) bullet_hit_list = pygame.sprite.spritecollide(enemy, bullet_list, True) for bullet in bullet_hit_list: enemylist.remove(enemy) all_sprites_list.remove(bullet) score += 1 for wall in walllist: #======================================================================================== if player.rect.left >= wall.rect.left and player.rect.right <= wall.rect.right: # THE FOLLOWING IS CHECKING WHETHER OR NOT THE PLAYER OR ENEMYIES LOCATION IS EQUAL TO ONE OF THE WALLS if player.rect.bottom >= wall.rect.top and player.rect.top <= wall.rect.top: # IN WHICH CASE, VELOCITY IS SET TO 0 AND THE PLAYER OR ENEMY IS UNABLE TO MOVE if uod == 2: player.rect.bottom = wall.rect.top if player.rect.top <= wall.rect.bottom and player.rect.bottom >= wall.rect.bottom: if uod == 1: player.rect.top = wall.rect.bottom elif player.rect.left <= wall.rect.right and player.rect.left >= wall.rect.left: if player.rect.bottom >= wall.rect.top and player.rect.top <= wall.rect.top: if rol == 2: player.rect.left = wall.rect.right elif rol == 1: rol = 1 elif uod == 2: player.rect.bottom = wall.rect.top if player.rect.top <= wall.rect.bottom and player.rect.bottom >= wall.rect.bottom: if rol == 2: player.rect.left = wall.rect.right if player.rect.top >= wall.rect.top and player.rect.bottom <=wall.rect.bottom: if rol == 2: player.rect.left = wall.rect.right elif player.rect.right >= wall.rect.left and player.rect.right <= wall.rect.right: if player.rect.bottom >= wall.rect.top and player.rect.top <= wall.rect.top: if rol == 1: player.rect.right = wall.rect.left if player.rect.top <= wall.rect.bottom and player.rect.bottom >= wall.rect.bottom: if rol == 1: player.rect.right = wall.rect.left if player.rect.top >= wall.rect.top and player.rect.bottom <=wall.rect.bottom: if rol == 1: player.rect.right = wall.rect.left #========================================================== if enemy.rect.left >= wall.rect.left and enemy.rect.right <= wall.rect.right: if enemy.rect.bottom >= wall.rect.top and enemy.rect.top <= wall.rect.top: enemy.rect.bottom = wall.rect.top if enemy.rect.top <= wall.rect.bottom and enemy.rect.bottom >= wall.rect.bottom: enemy.rect.top = wall.rect.bottom elif enemy.rect.left <= wall.rect.right and enemy.rect.left >= wall.rect.left: if enemy.rect.bottom >= wall.rect.top and enemy.rect.top <= wall.rect.top: enemy.rect.left = wall.rect.right enemy.rect.bottom = wall.rect.top if enemy.rect.top <= wall.rect.bottom and enemy.rect.bottom >= wall.rect.bottom: enemy.rect.left = wall.rect.right if enemy.rect.top >= wall.rect.top and enemy.rect.bottom <=wall.rect.bottom: enemy.rect.left = wall.rect.right elif enemy.rect.right >= wall.rect.left and enemy.rect.right <= wall.rect.right: if enemy.rect.bottom >= wall.rect.top and enemy.rect.top <= wall.rect.top: enemy.rect.right = wall.rect.left if enemy.rect.top <= wall.rect.bottom and enemy.rect.bottom >= wall.rect.bottom: enemy.rect.right = wall.rect.left if enemy.rect.top >= wall.rect.top and enemy.rect.bottom <=wall.rect.bottom: enemy.rect.right = wall.rect.left #Enemy 2 if enemy2.rect.left >= wall.rect.left and enemy2.rect.right <= wall.rect.right: if enemy2.rect.bottom >= wall.rect.top and enemy2.rect.top <= wall.rect.top: enemy2.rect.bottom = wall.rect.top if enemy2.rect.top <= wall.rect.bottom and enemy2.rect.bottom >= wall.rect.bottom: enemy2.rect.top = wall.rect.bottom elif enemy2.rect.left <= wall.rect.right and enemy2.rect.left >= wall.rect.left: if enemy2.rect.bottom >= wall.rect.top and enemy2.rect.top <= wall.rect.top: enemy2.rect.left = wall.rect.right enemy.rect.bottom = wall.rect.top if enemy2.rect.top <= wall.rect.bottom and enemy2.rect.bottom >= wall.rect.bottom: enemy2.rect.left = wall.rect.right if enemy2.rect.top >= wall.rect.top and enemy2.rect.bottom <=wall.rect.bottom: enemy2.rect.left = wall.rect.right elif enemy2.rect.right >= wall.rect.left and enemy2.rect.right <= wall.rect.right: if enemy2.rect.bottom >= wall.rect.top and enemy2.rect.top <= wall.rect.top: enemy2.rect.right = wall.rect.left if enemy2.rect.top <= wall.rect.bottom and enemy2.rect.bottom >= wall.rect.bottom: enemy2.rect.right = wall.rect.left if enemy2.rect.top >= wall.rect.top and enemy2.rect.bottom <=wall.rect.bottom: enemy2.rect.right = wall.rect.left #END if enemy.rect.centerx == player.rect.centerx and enemy.rect.centery == player.rect.centery or enemy2.rect.centerx == player.rect.centerx and enemy2.rect.centery == player.rect.centery: player.roomchange = 1 #is the player and the enemy is the same position, if so increase deaths, set postion back to origional and start screen rooms = [0,0] player.rect.centerx = 137 player.rect.centery = 137 deaths = deaths + 1 key = 0 enemylist.remove(enemy) enemylist.remove(enemy) score = 0 if enemy2.rect.centerx == player.rect.centerx and enemy2.rect.centery == player.rect.centery: player.roomchange = 1 #is the player and the enemy is the same position, if so increase deaths, set postion back to origional and start screen rooms = [0,0] player.rect.centerx = 137 player.rect.centery = 137 deaths = deaths + 1 key = 0 enemylist.remove(enemy) enemylist.remove(enemy2) score = 0 scoretext = myfont.render("Score {0}".format(score), 1, (255,0,0)) screen.blit(scoretext, (625, 10)) if deaths == 100: ctypes.windll.user32.MessageBoxW(0, "Game Over", "Alert", 1) testVar = input("Save Highscore. Name?") with open('scores.txt', 'w') as output: output.write("HIGHSCORE: " ) output.write(testVar) output.write(":") output.write(" ") output.write(str(score)) pygame.quit() keypress = pygame.key.get_pressed() screen.fill(BROWN) # Screen fill BROWN bullet_list.draw(screen) imagelist.draw(screen) enemylist.draw(screen) walllist.draw(screen) playerlist.draw(screen) # draw the player onto pf the screen player.velocityx = 0 # default x velocity = 0 player.velocityy = 0 # default y velocity = 0 deathstext = myfont.render("Deaths {0}".format(deaths), 1, (0,0,0)) screen.blit(deathstext, (5, 10)) scoretext = myfont.render("Score {0}".format(score), 1, (0,0,0)) screen.blit(scoretext, (625, 10)) pygame.display.flip() clock.tick(60) pygame.quit()
b3093cd774301782decd4440f925e6a0b0450e77
[ "Markdown", "Python" ]
2
Markdown
CameronDC/DC-Project
a442b125d14950e9977b51f1d88b0127d76e239b
e2f651e807fd361a228a354fdc252f9463bd5e43
refs/heads/master
<file_sep>package model; public class ReservationDetails { private int rid; private User user; private Room room; private int startHour; private int startMinute; private int periodHour; private int periodMinute; private String userName; private String emailAddress; private String buildingName; private int floor; private String roomName; public int getRid() { return rid; } public void setRid(int rid) { this.rid = rid; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Room getRoom() { return room; } public void setRoom(Room room) { this.room = room; } public int getStartHour() { return startHour; } public void setStartHour(int startHour) { this.startHour = startHour; } public int getStartMinute() { return startMinute; } public void setStartMinute(int startMinute) { this.startMinute = startMinute; } public int getPeriodHour() { return periodHour; } public void setPeriodHour(int periodHour) { this.periodHour = periodHour; } public int getPeriodMinute() { return periodMinute; } public void setPeriodMinute(int periodMinute) { this.periodMinute = periodMinute; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } public String getBuildingName() { return buildingName; } public void setBuildingName(String buildingName) { this.buildingName = buildingName; } public int getFloor() { return floor; } public void setFloor(int floor) { this.floor = floor; } public String getRoomName() { return roomName; } public void setRoomName(String roomName) { this.roomName = roomName; } } <file_sep>package db; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.util.LinkedList; import org.junit.Test; import common.TestDataBase; import model.Reservation; import model.Room; import model.TestDataFactory; import model.User; public class ReservationManagerTest { @Test public void 予約を読み込む() { // データベースにテストデータを挿入 TestDataBase db=new TestDataBase(); db.setTestData("./testdata/story08/dbaccess_test.xls"); // データベースから予約を読み込み ReservationManager rm = new ReservationManager(); LinkedList<Reservation> reservations = rm.getReservations(); // 読み込んだオブジェクトの数が適切かどうかをチェック assertThat(reservations.size(),is(2)); // 読み込んだオブジェクトのプロパティの値が適切かどうかをチェック Reservation res1 = reservations.get(0); assertThat(res1.getRid(),is(1)); assertThat(res1.getUser().getRid(),is(1)); assertThat(res1.getRoom().getRid(),is(2)); assertThat(res1.getStartYear(),is(2016)); assertThat(res1.getStartMonth(),is(12)); assertThat(res1.getStartDay(),is(5)); assertThat(res1.getStartHour(),is(13)); assertThat(res1.getStartMinute(),is(0)); assertThat(res1.getPeriodHour(),is(1)); assertThat(res1.getPeriodMinute(),is(30)); Reservation res2 = reservations.get(1); assertThat(res2.getRid(),is(2)); assertThat(res2.getUser().getRid(),is(2)); assertThat(res2.getRoom().getRid(),is(5)); assertThat(res2.getStartYear(),is(2016)); assertThat(res2.getStartMonth(),is(1)); assertThat(res2.getStartDay(),is(1)); assertThat(res2.getStartHour(),is(1)); assertThat(res2.getStartMinute(),is(1)); assertThat(res2.getPeriodHour(),is(2)); assertThat(res2.getPeriodMinute(),is(30)); } } <file_sep>package db; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import java.util.LinkedList; import org.junit.Test; import common.TestDataBase; import model.ReservationDetails; public class BookingRoomManagerTest { @Test public void 予約詳細を読み込む() { // データベースにテストデータを挿入 TestDataBase db = new TestDataBase(); db.setTestData("./testdata/story09/bookingRoomManagerTest.xls"); BookingRoomManager brm = new BookingRoomManager(); // データベースから予約を読み込み ReservationDetails rd = brm.getReservationDetail(1); // 読み込んだオブジェクトのプロパティの値が適切かどうかをチェック assertThat(rd.getRid(), is(1)); assertThat(rd.getBuildingName(), is("物質・材料経営情報棟")); assertThat(rd.getFloor(), is(2)); assertThat(rd.getStartHour(), is(13)); assertThat(rd.getStartMinute(), is(0)); assertThat(rd.getPeriodHour(), is(1)); assertThat(rd.getPeriodMinute(), is(30)); assertThat(rd.getUserName(), is("Mr.x")); assertThat(rd.getEmailAddress(), is("<EMAIL>")); LinkedList<ReservationDetails> rds = brm.getReservationDetails(); // 読み込んだオブジェクトの数が適切かどうかをチェック assertThat(rds.size(), is(2)); ReservationDetails rd1 = rds.get(0); assertThat(rd1.getRid(), is(1)); assertThat(rd1.getBuildingName(), is("物質・材料経営情報棟")); assertThat(rd1.getFloor(), is(2)); assertThat(rd1.getRoomName(), is("ゼミ室")); assertThat(rd1.getStartHour(), is(13)); assertThat(rd1.getStartMinute(), is(0)); assertThat(rd1.getPeriodHour(), is(1)); assertThat(rd1.getPeriodMinute(), is(30)); assertThat(rd1.getUserName(), is("Mr.x")); assertThat(rd1.getEmailAddress(), is("<EMAIL>")); ReservationDetails rd2 = rds.get(1); assertThat(rd2.getRid(), is(2)); assertThat(rd2.getBuildingName(), is("総合研究棟")); assertThat(rd2.getFloor(), is(6)); assertThat(rd2.getRoomName(), is("ゼミ室")); assertThat(rd2.getStartHour(), is(1)); assertThat(rd2.getStartMinute(), is(1)); assertThat(rd2.getPeriodHour(), is(2)); assertThat(rd2.getPeriodMinute(), is(30)); assertThat(rd2.getUserName(), is("Ms.z")); assertThat(rd2.getEmailAddress(), is("<EMAIL>")); } }
568c2a8464f0fd3c9f0b328e10b6679ae777d7c4
[ "Java" ]
3
Java
fyoshida2016/RemoteRepoForSeReserveB
ceeb0697d51bb64b0d12ce552d0b760f1c1d9ec3
250adae244aad2d23acf852f64cceacec8ec1911
refs/heads/main
<file_sep>// 1 ВАРИАНТ FOR....OF const findBestEmployee = function (employees) { "use strict"; let bestEmployee = ""; let maxTasks = 0; const keys = Object.keys(employees); for (const key of keys) { if (maxTasks < employees[key]) { maxTasks = employees[key]; bestEmployee = key; } } return bestEmployee; }; // 2 ВАРИАНТ FOR // const findBestEmployee = function (employees) { // "use strict"; // let bestEmployee = ""; // let maxTasks = 0; // const keys = Object.keys(employees); // for (let i = 0; i < keys.length; i += 1) { // if (employees[keys[i]] > maxTasks) { // maxTasks = employees[keys[i]]; // bestEmployee = keys[i]; // } // } // return bestEmployee; // }; // 3 ВАРИАНТ FOR....IN // function findBestEmployee(employees) { // let max = 0; // let bestEmployee; // for (const employee in employees) { // const numOfTasks = employees[employee]; // if (numOfTasks > max) { // max = numOfTasks; // bestEmployee = employee; // } // } // return bestEmployee; // } // Объекты и ожидаемый результат const developers = { ann: 29, david: 35, helen: 1, lorence: 99, }; console.log(findBestEmployee(developers)); // 'lorence' const supports = { poly: 12, mango: 17, ajax: 4, }; console.log(findBestEmployee(supports)); // 'mango' const sellers = { lux: 147, david: 21, kiwi: 19, chelsy: 38, }; console.log(findBestEmployee(sellers)); // 'lux'
e2f61c1c967e16469a91a050ab4eaf24aa435fc2
[ "JavaScript" ]
1
JavaScript
lenakernytska/goit-js-hw-03
a2d514ac9ba2b8470f0293452cac8e875459bb1e
bcc1a729cc665db020fae623e390c0ea4adafd60
refs/heads/master
<file_sep>package com.jiajun.imagehosting.util; import java.util.Random; public class FileUtils { /** * 获得文件的存储名称 0fec8b58b60a8983 ce00de0d24c5bdb0 * @return */ public static String generatorStoreName() { String str = ""; char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; Random random = new Random(); for (int i = 0; i < 16; i++) { str += hexDigits[random.nextInt(15)]; } return str; } } <file_sep>(function($) { var B = !!navigator.userAgent.match(/AppleWebKit.*Mobile.*/); $.dialog = { showMsgLayer: function(a, b, c, d, e) { this.show(430, a, b, null, 1, 0, c, 0, d, e) }, showMsgFuncLayer: function(a, b, c, d, e, f) { this.show(430, a, b, c, 1, 0, 0, d, e, f) }, showFuncLayer: function(a, b, c, d, e, f, g, h) { this.show(a, b, c, d, e, 0, 0, f, g, h) }, showIframeDialog: function(a, b, c, d, e) { this.show(a, b, c, null, 1, 1, 0, 0, d, e) }, show: function(c, d, f, g, h, i, j, k, l, m) { var n = $('#dialoglayer'); if (!n.length) { n = $('<div id="dialoglayer"><div id="dlhead"><span id="dltitle"></span><span id="dlclose" ></span></div><div id="dlcont" style="text-align:center"></div><div id="dlbtn"><input type="button" value="确定" id="dlbtnconfirm" /><input type="button" value="取消" id="dlbtncancel" /></div></div>'); n.css({ 'position': 'absolute', 'z-index': '999', 'background-color': '#fff', 'font-size': '14px', 'color': '#666', 'padding-bottom': '10px', 'border': '5px solid #666', '-webkit-border-radius': '4px', '-moz-border-radius': '4px', 'border-radius': '4px' }); n.find('#dlhead').css({ 'width': '100%', 'height': '50px', 'background-color': '#f8f8f8', 'border-bottom': '4px solid #eee', 'font-weight': 'bold' }); n.find('#dltitle').css({ 'float': 'left', 'width': '80%', 'height': '50px', 'line-height': '50px', 'letter-spacing': '2px', 'text-indent': '1.5em' }); n.find('#dlclose').css({ 'float': 'right', 'width': '24px', 'height': '24px', 'margin': '13px 18px 0 0', 'cursor': 'pointer' }); n.find('#dlclose').hover(function() { $(this).css({ 'background-position': '-24px 0' }) }, function() { $(this).css({ 'background-position': '-24px 0' }) }); n.find('#dlcont').css({ 'line-height': '20px' }); n.find('#dlbtn').css({ 'width': '100%', 'height': '50px', 'text-align': 'center' }); n.find('#dlbtn input').css({ 'width': '80px', 'height': '30px', 'border': '0', 'line-height': '30px', 'letter-spacing': '5px', 'background-color': '#090', 'font-size': '14px', 'font-weight': 'bold', 'color': '#fff', 'cursor': 'pointer', '-webkit-border-radius': '4px', '-moz-border-radius': '4px', 'border-radius': '4px' }); n.find('#dlbtn input').hover(function() { $(this).css({ 'background-color': '#0c0' }) }, function() { $(this).css({ 'background-color': '#090' }) }); n.find('#dlbtncancel').css({ 'margin-left': '20px' }); n.remove(); n.appendTo(document.body); n.find('#dlclose').click(function() { $.dialog.hidden() }); n.find('#dlbtncancel').click(function() { $.dialog.hidden() }); if (!B) { $(window).bind('resize scroll', function() { if (!l) { var a = $('#dialoglayermask'); a.width($(document).width()); a.height($(document).height()) } o() }) } } var o = function() { var a = $(window).height() - n.height(); var b = $(window).width() - n.width(); if (a > 0) { a = $(window).scrollTop() + a / 2 } else { a = 0 } if (b > 0) { b = $(window).scrollLeft() + b / 2 } else { b = 0 } n.css({ top: a, left: b }) }; if (l) { n.css({ 'border': '1px solid #ccc', 'backgroundColor': '#eee' }) } else { var p = $('#dialoglayermask'); if (!p.length) { p = $('<div id="dialoglayermask"></div>'); p.css({ 'position': 'absolute', 'z-index': '888', 'top': '0', 'left': '0', 'width': '100%', 'min-height': '100%', 'background-color': '#000', 'filter': 'alpha(opacity=30)', '-moz-opacity': '0.30', 'opacity': '0.30' }); p.appendTo(document.body) } else { p.show() } p.width($(document).width()); p.height($(document).height()) } n.width(c); n.find('#dltitle').html(d); var q = n.find('#dlclose'); if (k) { q.remove() } else { q.show() } var r = n.find('#dlcont'); r.css({ 'margin': '20px 25px', 'width': c - 50, 'text-align': 'center' }); r.html(f); if (i) { n.find('#dlbtn').remove() } else { n.find('#dlbtn').show(); var s = n.find('#dlbtnconfirm'); s.unbind('click'); if (typeof g == 'function') { s.click(g) } else { s.click(function() { $.dialog.hidden() }) } var t = n.find('#dlbtncancel'); if (h) { t.remove(); s.focus() } else { t.show(); t.focus() } } if (j) { window.setTimeout('$.dialog.hidden();', (j * 1000)) } var u = $('#dlhead'); if (m) { u.unbind() } else { var v = 0, beginY = 0; var w = 0, posLeft = 0; var x = 0, y = 0; var z = function(e) { x = posLeft + e.clientX - v; y = w + e.clientY - beginY; n.css({ top: y, left: x }); if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true }; var A = function(e) { $(document).unbind("mousemove", z); $(document).unbind("mouseup", A); if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true }; u.unbind(); u.mousedown(function(e) { v = e.clientX; beginY = e.clientY; w = parseInt(n.position().top); posLeft = parseInt(n.position().left); $(document).unbind("mousemove", z); $(document).unbind("mouseup", A); $(document).bind("mousemove", z); $(document).bind("mouseup", A); if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; if (e.preventDefault) e.preventDefault(); else e.returnValue = false }) } o(); n.show(); if (r.height() < 30) { r.css('text-align', 'center') } else { r.css('text-align', 'left') } }, hidden: function() { var a = $('#dialoglayermask'); var b = $('#dialoglayer'); if (a.length) { a.remove() } if (b.length) { b.remove() } } }; $.alert = { show: function(c, d, e) { var f = $('#alertlayer'); if (!f.length) { f = $('<div id="alertlayer"><div id="alertcont"></div><div id="alertbtn"><input type="button" value="确定" id="alertconfirm"/><input type="button" value="取消" id="alertcancel"/></div></div>'); f.css({ 'position': 'absolute', 'z-index': '1111', 'max-width': '460px', 'min-width': '300px', 'background-color': '#fff', 'font-size': '14px', 'color': '#333', 'border': '5px solid #666', '-webkit-border-radius': '4px', '-moz-border-radius': '4px', 'border-radius': '4px' }); f.find("#alertcont").css({ 'margin': '20px', 'line-height': '20px' }); f.find("#alertbtn").css({ 'width': '100%', 'height': '50px', 'text-align': 'center' }); f.find("#alertbtn input").css({ 'width': '80px', 'height': '30px', 'border': '0', 'line-height': '30px', 'letter-spacing': '5px', 'background-color': '#090', 'font-size': '14px', 'font-weight': 'bold', 'color': '#fff', 'cursor': 'pointer', '-webkit-border-radius': '4px', '-moz-border-radius': '4px', 'border-radius': '4px' }); f.find("#alertbtn input").hover(function() { $(this).css({ 'background-color': '#0c0' }) }, function() { $(this).css({ 'background-color': '#090' }) }); f.find("#alertcancel").css({ 'margin-left': '20px', 'display': 'none' }); f.remove(); f.appendTo(document.body); f.find("#alertcancel").click(function() { $.alert.hidden() }); if (!B) { $(window).bind('resize scroll', function() { var a = $('#alertlayermask'); a.width($(document).width()); a.height($(document).height()); g() }) } f.width() > 460 ? f.width(380) : f.width() < 300 ? f.width(300) : null } var g = function() { var a = $(window).height() - f.height(); var b = $(window).width() - f.width(); if (a > 0) { a = $(window).scrollTop() + a / 2 } else { a = 0 } if (b > 0) { b = $(window).scrollLeft() + b / 2 } else { b = 0 } f.css({ top: a, left: b }) }; var h = $('#alertlayermask'); if (!h.length) { h = $('<div id="alertlayermask"></div>'); h.css({ 'position': 'absolute', 'z-index': '1100', 'top': '0', 'left': '0', 'width': '100%', 'min-height': '100%', 'background-color': '#fff', 'filter': 'alpha(opacity=0)', '-moz-opacity': '0', 'opacity': '0' }); h.appendTo(document.body) } else { h.show() } h.width($(document).width()); h.height($(document).height()); var i = f.find('#alertcont'); i.html(c); var j = f.find('#alertconfirm'); j.unbind('click'); if (typeof d == 'function') { j.click(d) } else { j.click(function() { $.alert.hidden() }) } var k = f.find('#alertcancel'); if (e) { k.show(); k.focus() } else { k.remove(); j.focus() } g(); f.show(); if (i.height() < 30) { i.css('text-align', 'center') } else { i.css('text-align', 'left') } f.find("#alertbtn").css({ 'width': f.width() }) }, hidden: function() { var a = $('#alertlayermask'); if (a.length) { a.remove() } var b = $('#alertlayer'); if (b.length) { b.remove() } }, showb: function(c, d, e) { var f = $('#alertlayer'); if (!f.length) { f = $('<div id="alertlayer"><div id="alertcont"></div><div id="alertbtn"><input type="button" value="下一步" id="alertconfirm"/><input type="button" value="取消" id="alertcancel"/></div></div>'); f.css({ 'position': 'absolute', 'z-index': '1111', 'max-width': '460px', 'min-width': '300px', 'background-color': '#fff', 'font-size': '14px', 'color': '#333', 'border': '5px solid #666', '-webkit-border-radius': '4px', '-moz-border-radius': '4px', 'border-radius': '4px' }); f.find("#alertcont").css({ 'margin': '20px', 'line-height': '20px' }); f.find("#alertbtn").css({ 'width': '100%', 'height': '50px', 'text-align': 'center' }); f.find("#alertbtn input").css({ 'width': '80px', 'height': '30px', 'border': '0', 'line-height': '30px', 'letter-spacing': '5px', 'background-color': '#090', 'font-size': '14px', 'font-weight': 'bold', 'color': '#fff', 'cursor': 'pointer', '-webkit-border-radius': '4px', '-moz-border-radius': '4px', 'border-radius': '4px' }); f.find("#alertbtn input").hover(function() { $(this).css({ 'background-color': '#0c0' }) }, function() { $(this).css({ 'background-color': '#090' }) }); f.find("#alertcancel").css({ 'margin-left': '20px', 'display': 'none', 'background-color': '#999' }); f.remove(); f.appendTo(document.body); f.find("#alertcancel").click(function() { $.alert.hidden() }); if (!B) { $(window).bind('resize scroll', function() { var a = $('#alertlayermask'); a.width($(document).width()); a.height($(document).height()); g() }) } f.width() > 460 ? f.width(380) : f.width() < 300 ? f.width(300) : null } var g = function() { var a = $(window).height() - f.height(); var b = $(window).width() - f.width(); if (a > 0) { a = $(window).scrollTop() + a / 2 } else { a = 0 } if (b > 0) { b = $(window).scrollLeft() + b / 2 } else { b = 0 } f.css({ top: a, left: b }) }; var h = $('#alertlayermask'); if (!h.length) { h = $('<div id="alertlayermask"></div>'); h.css({ 'position': 'absolute', 'z-index': '1100', 'top': '0', 'left': '0', 'width': '100%', 'min-height': '100%', 'background-color': '#fff', 'filter': 'alpha(opacity=0)', '-moz-opacity': '0', 'opacity': '0' }); h.appendTo(document.body) } else { h.show() } h.width($(document).width()); h.height($(document).height()); var i = f.find('#alertcont'); i.html(c); var j = f.find('#alertconfirm'); j.unbind('click'); if (typeof d == 'function') { j.click(d) } else { j.click(function() { $.alert.hidden() }) } var k = f.find('#alertcancel'); if (e) { k.show(); k.focus() } else { k.remove(); j.focus() } g(); f.show(); if (i.height() < 30) { i.css('text-align', 'center') } else { i.css('text-align', 'left') } f.find("#alertbtn").css({ 'width': f.width() }) } }; $.prompt = { show: function(b) { var c = $('#promptlayer'); if (!c.length) { c = $('<div id="promptlayer"></div>'); c.css({ 'position': 'absolute', 'z-index': '11111', 'float': 'left', 'padding': '6px 18px', 'background-color': '#ffff99', 'font-size': '12px', 'font-weight': 'bold', 'color': '#000' }); c.remove(); c.appendTo(document.body); $(window).bind('resize scroll', function() { d() }) } c.html(b); var d = function() { var a = $(window).width() - c.width(); if (a > 0) { a = $(window).scrollLeft() + a / 2 } else { a = 0 } c.css({ top: $(window).scrollTop(), left: a }) }; d(); c.show() }, hidden: function() { var a = $('#promptlayer'); if (a.length) { a.remove() } } }; $.tips = { show: function(a, b, c, d, e) { if (a && $(a).length) { var f = $(a).find('.dltipsbox'); if (!f.length) { $(a).css({ 'position': 'relative', 'z-index': '665' }); f = $('<div class="dltipsbox"><div class="dltipsboxjt"></div><div class="dltipsboxclose">x</div><div class="dltipsboxcont"></div></div>'); f.css({ 'position': 'absolute', 'z-index': '1111' }); f.find(".dltipsboxjt").css({ 'position': 'absolute', 'width': '16px', 'height': '8px', 'background': 'url(/js/dialog/tipsbg.gif) no-repeat', 'overflow': 'hidden' }); f.find(".dltipsboxclose").css({ 'position': 'absolute', 'top': '0', 'right': '5px', 'line-height': '12px', 'font-size': '12px', 'color': '#999', 'font-family': '宋体,Arial,sans-serif', 'cursor': 'pointer' }); f.find(".dltipsboxcont").css({ 'padding': '10px', 'background-color': '#ffc', 'border': '1px solid #fc6' }); f.remove(); f.appendTo(a) } if (e) f.find(".dltipsboxclose").remove(); else f.find(".dltipsboxclose").click(function() { $.tips.hidden(a) }); f.find('.dltipsboxcont').html(c); var g = 0, left = 0; if (b) { if (b.top) g = b.top; if (b.left) left = b.left } if (d == "bl" || d == "lb" || d == "br" || d == "lr") { f.find('.dltipsboxjt').css({ 'top': f.height() - 1, 'background-position': '0 -8px' }); if (d == "bl" || d == "lb") f.find('.dltipsboxjt').css('left', '10px'); else f.find('.dltipsboxjt').css('right', '10px'); g = g - f.height() - 8 } else { f.find('.dltipsboxjt').css({ 'top': '-7px' }); if (d == "tr" || d == "rt") f.find('.dltipsboxjt').css('right', '10px'); else f.find('.dltipsboxjt').css('left', '10px'); g = g + 7 } f.css({ top: g, left: left }); f.show() } }, hidden: function(a) { var b; if (a) b = $(a).find('.dltipsbox'); else b = $('.dltipsbox'); if (b.length) b.remove() } } })(jQuery);<file_sep>package com.jiajun.common.base; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.beans.factory.annotation.Autowired; import com.jiajun.common.bo.Page; public abstract class BaseDao<T> extends SqlSessionDaoSupport { private static final String DEFAULT_PAGE_COUNT_STATEMENT = "selectPageCount"; private static final String DEFAILT_PAGE_LIST_STATEMENT = "selectPageList"; protected abstract String getNamespace(); @Autowired public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) { super.setSqlSessionFactory(sqlSessionFactory); } public final int deleteByPrimaryKey(Object id) { return this.getSqlSession().delete(getNamespace() + "." + "deleteByPrimaryKey", id); } public final T selectByPrimaryKey(Object id) { return this.getSqlSession().selectOne(getNamespace() + "." + "selectByPrimaryKey", id); } public final int insert(T t) { return this.getSqlSession().insert(getNamespace() + "." + "insert", t); } public final int insertSelective(T t) { return this.getSqlSession().insert(getNamespace() + "." + "insertSelective", t); } public final int updateByPrimaryKey(T t) { return this.getSqlSession().update(getNamespace() + "." + "updateByPrimaryKey", t); } public final int updateByPrimaryKeySelective(T t) { return this.getSqlSession().update(getNamespace() + "." + "updateByPrimaryKeySelective", t); } /** * 分页查询 * @param page * @param countStatement 查询总个数sql * @param listStatement list sql @ */ public final void page(Page<T> page, String countStatement, String listStatement) { Map<String, Object> conditions = page.getConditions(); int count = (int) selectObject(countStatement, conditions); page.setCount(count); if (count > 0) { int pageSize = page.getPageSize(); int begin = (page.getCurrentPage() - 1) * pageSize; conditions.put("begin", begin); conditions.put("pageSize", pageSize); List<T> list = selectList(listStatement, conditions); page.setList(list); int totalPage = (count - 1) / page.getPageSize() + 1; page.setTotalPage(totalPage); conditions.remove("begin"); conditions.remove("pageSize"); } } /** * 使用默认的查询语句 * @countStatement: selectPageCount * @listStatement: selectPageList * @param page @ */ public final void page(Page<T> page) { this.page(page, DEFAULT_PAGE_COUNT_STATEMENT, DEFAILT_PAGE_LIST_STATEMENT); } protected final int insert(String statement, Object obj) { return this.getSqlSession().insert(getNamespace() + "." + statement, obj); } protected final int delete(String statement, Object obj) { return this.getSqlSession().delete(getNamespace() + "." + statement, obj); } protected final int update(String statement, Object obj) { return this.getSqlSession().update(getNamespace() + "." + statement, obj); } protected final <E> List<E> selectList(String statement, Object obj) { return this.getSqlSession().selectList(getNamespace() + "." + statement, obj); } protected final Object selectObject(String statement, Object obj) { return this.getSqlSession().selectOne(getNamespace() + "." + statement, obj); } protected final <E> void batchInsert(String statement, List<E> list) { for (Object object : list) { this.getSqlSession().insert(getNamespace() + "." + statement, object); } } protected final <E> void batchUpdate(String statement, List<E> list) { for (Object object : list) { this.getSqlSession().update(getNamespace() + "." + statement, object); } } protected final <E> void batchDelete(String statement, List<E> list) { for (Object object : list) { this.getSqlSession().delete(getNamespace() + "." + statement, object); } } } <file_sep>package com.jiajun.common.bo; public enum ResultCode { SUCCESS(200), // success FAIL(400), // 参数之类错误 FORBIDDEN(403), // 服务器拒绝 ERROR(500); // 服务器内部错误 public int code; ResultCode(int code) { this.code = code; } } <file_sep>package com.jiajun.imagehosting.service; import java.util.List; import com.jiajun.imagehosting.domain.AlbumEntity; public interface AlbumService { AlbumEntity getById(int id) throws Exception; void save(AlbumEntity albumEntity) throws Exception; /** * 查询用户下是否具有此名称的相册 * @param id * @return */ AlbumEntity getByUserAndName(Integer userId, String albumName) throws Exception; /** * 获得用户下的所有相册, 相册下具有的图片总数, 和6张预览图 * @param id * @return * @throws Exception */ List<AlbumEntity> getHasAlbumsContainImage(Integer userId) throws Exception; /** * 获得用户下的具有的相册以及相册下具有的图片总数 * @param id * @return * @throws Exception */ List<AlbumEntity> getHasAlbumsWithImageNums(Integer userId) throws Exception; /** * 获得拥有的所有相册, 不包括image * @param id * @return * @throws Exception */ List<AlbumEntity> getHasAlbums(Integer id)throws Exception; /** * 获得具备的Id * @param id * @return * @throws Exception */ List<Integer> getHasAlbumIds(Integer id)throws Exception; /** * 修改相册的访问权限 * @param albumId * @param type * @throws Exception */ void updateAlbumAuthority(Integer albumId, int type) throws Exception; void delete(Integer albumId) throws Exception; void update(AlbumEntity album) throws Exception; } <file_sep>var keyStr = "<KEY>; function strUnicode2Ansi(asContents) { var len1 = asContents.length; var temp = ""; for (var i = 0; i < len1; i++) { var varasc = asContents.charCodeAt(i); if (varasc < 0) varasc += 65536; if (varasc > 127) varasc = UnicodeToAnsi(varasc); if (varasc > 255) { var varlow = varasc & 65280; varlow = varlow >> 8; var varhigh = varasc & 255; temp += String.fromCharCode(varlow) + String.fromCharCode(varhigh); } else { temp += String.fromCharCode(varasc); } } return temp; } function encode64(input) { input = strUnicode2Ansi(input); var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; do { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while ( i < input . length ); return output; } function decode64(input) { var output = ""; var chr1, chr2, chr3 = ""; var enc1, enc2, enc3, enc4 = ""; var i = 0; if (input.length % 4 != 0) { return ""; } var base64test = /[^A-Za-z0-9\+\/\=]/g; if (base64test.exec(input)) { return ""; } do { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output += String.fromCharCode(chr2); } if (enc4 != 64) { output += String.fromCharCode(chr3); } chr1 = chr2 = chr3 = ""; enc1 = enc2 = enc3 = enc4 = ""; } while ( i < input . length ); return strAnsi2Unicode(output); }<file_sep>package com.jiajun.imagehosting.domain; import java.util.Date; import org.apache.commons.lang3.StringUtils; import com.jiajun.imagehosting.util.ImageProcess; public class ImageEntity implements java.io.Serializable{ /** * 获得缩略图 imageZoomUrl * @return */ public String getImageZoomUrl() { if(StringUtils.isNotEmpty(httpUrl)) { return ImageProcess.doZoomProcess(httpUrl); } else { return ""; } } private Integer id; private Integer albumId; private String fileName; private String fileType; private String uniqueName; private Integer width; private Integer height; private Long size; private String httpUrl; private Date createTime; private Date deleteTime; private Date updateTime; private Boolean isDelete; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getAlbumId() { return albumId; } public void setAlbumId(Integer albumId) { this.albumId = albumId; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getUniqueName() { return uniqueName; } public void setUniqueName(String uniqueName) { this.uniqueName = uniqueName; } public Integer getWidth() { return width; } public void setWidth(Integer width) { this.width = width; } public Integer getHeight() { return height; } public void setHeight(Integer height) { this.height = height; } public Long getSize() { return size; } public void setSize(Long size) { this.size = size; } public String getHttpUrl() { return httpUrl; } public void setHttpUrl(String httpUrl) { this.httpUrl = httpUrl; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getDeleteTime() { return deleteTime; } public void setDeleteTime(Date deleteTime) { this.deleteTime = deleteTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Boolean getIsDelete() { return isDelete; } public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } private static final long serialVersionUID = -1025504280966718306L; }<file_sep>package com.jiajun.common.util; import java.io.IOException; import java.io.InputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * jackson json工具类 */ @SuppressWarnings("unchecked") public class JsonUtils { private static Logger logger = LoggerFactory.getLogger(JsonUtils.class); private static ObjectMapper objectMapper = new ObjectMapper(); /** * 对象转换为json字符串 * @param obj * @return */ public static String toString(Object obj) { try { return objectMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { logger.error("encode(Object)", e); } catch (JsonMappingException e) { logger.error("encode(Object)", e); } catch (IOException e) { logger.error("encode(Object)", e); } return null; } /** * 将集合类型的json转化为对象 * @param json * @param jsonTypeReference * @return */ public static <T> T toString(String json, TypeReference<T> jsonTypeReference) { try { return (T) objectMapper.readValue(json, jsonTypeReference); } catch (JsonParseException e) { logger.error("decode(String, JsonTypeReference<T>)", e); } catch (JsonMappingException e) { logger.error("decode(String, JsonTypeReference<T>)", e); } catch (IOException e) { logger.error("decode(String, JsonTypeReference<T>)", e); } return null; } /** * 将json string反序列化成对象 * @param json * @param valueType * @return */ public static <T> T toObject(String json, Class<T> valueType) { try { return objectMapper.readValue(json, valueType); } catch (JsonParseException e) { logger.error("decode(String, Class<T>)", e); } catch (JsonMappingException e) { logger.error("decode(String, Class<T>)", e); } catch (IOException e) { logger.error("decode(String, Class<T>)", e); } return null; } /** * 将集合类型的json转化为对象 * @param is * @param jsonTypeReference * @return */ public static <T> T toObject(InputStream is, TypeReference<T> jsonTypeReference) { try { return (T) objectMapper.readValue(is, jsonTypeReference); } catch (JsonParseException e) { logger.error("decode(String, JsonTypeReference<T>)", e); } catch (JsonMappingException e) { logger.error("decode(String, JsonTypeReference<T>)", e); } catch (IOException e) { logger.error("decode(String, JsonTypeReference<T>)", e); } return null; } } <file_sep>var iptless = function(exp, maxipt, lab) { var val = $(exp).val(); if (val.length > maxipt) { val = val.substr(0, maxipt); $(exp).val(val); } if (lab) lab.html(val.length); else $(exp).parent().find("label").first().html(val.length); } var loadalbumwait = false, creatalbumwait = false; $(function() { //查询cookie, 设置选中的album var selectAId = $.cookie("selected_album_"+user); $('#albums').val(selectAId); }); $('#albums').change(function() { //设置cookie, 存储用户行为, 并且session缓存 var albumId = $(this).val(); d_album = albumId; $.post(basePath+'album/selected', {"albumId": albumId}, function(result) { if (result.code == 200) { //存储cookie $.cookie('selected_album_'+user, albumId, { expires : 30, path:'/' }); } }); }); $(".upload_c_a_b").hover(function() { $(this).css("border-color", "#0c0"); $(".upload_c_a_b_b").css("background-position", "-105px -110px"); }, function() { if (!$('.upload_c_a_c:visible').length) { $(this).css("border-color", "#ccc"); $(".upload_c_a_b_b").css("background-position", "0 -110px"); } }).click(function() { return false; var ealo = $('.upload_c_a_c'); if (ealo.length) ealo.toggle(); else { if (!loadalbumwait) { $.ajax({ beforeSend: function() { loadalbumwait = true; $.prompt.show('正在加载相册列表......'); }, complete: function() { loadalbumwait = false; }, cache: false, dataType: "json", error: function() { $.prompt.show('加载相册列表失败!'); setTimeout(function() { $.prompt.hidden(); }, 3000); }, success: function(result) { if (result && result.album && $.isArray(result.album)) { $.prompt.hidden(); var al = ''; al += '<span class="upload_c_a_c" style="z-index:100">'; if (result.album.length) { al += '<span class="upload_c_a_c_a">'; $.each(result.album, function(i, v) { al += '<label pri_album="' + v.type + '" data-obj="' + v.aid + '" title="' + v.albumname + '">' + v.albumname + '(' + v.num + ')</label>'; }); al += '</span>'; } al += '<span class="upload_c_a_c_b">'; al += '<span class="upload_c_a_c_b_a">'; al += '<input type="text" name="newalbum" maxlength="20" />'; al += '<span><label>0</label><label class="upload_c_a_c_b_a_s">/</label>20</span>'; al += '</span>'; al += '<input type="button" value="创建相册" class="cbtn upload_c_a_c_b_a_b" />'; al += '</span>'; al += '</span>'; $('.upload_c_a').append(al); $('.upload_c_a_c_a label').click(function() { $('.upload_c_a_b_a').html($(this).html().replace(/(\d+)$/g, '')); $.post('/?m=Home&c=Pic&a=setDefaultAlbum', { 'pri_album': $(this).attr("pri_album"), 'd_album': $(this).attr("data-obj"), 'd_album_name': $(this).html().replace(/(\d+)$/g, '') }, function(t) { if (t) { window.location.reload(); } }); $(document).click(); }); $('.upload_c_a_c_b_a :text[name=newalbum]').keyup(function() { iptless(this, 20); }); $(':button.upload_c_a_c_b_a_b').click(function() { var newalbum = $('.upload_c_a_c_b_a :text[name=newalbum]').val(); if (!newalbum.length) $.alert.show("请输入相册名称!"); else { if (!creatalbumwait) { $.ajax({ beforeSend: function() { creatalbumwait = true; $.prompt.show('正在创建相册......') }, complete: function() { creatalbumwait = false; $.prompt.hidden() }, cache: false, data: { "name": newalbum }, error: function() { $.alert.show('对不起,系统出现异常,相册创建失败!'); }, success: function(result) { if ("mgc" == result) { $.alert.show("相册名称中包含敏感词,请修改!"); } else if (result == "had") { $.alert.show('已存在同名相册,请更改名称!'); } else if (result == 'ok') { $.alert.show("创建成功", function() { window.location.reload(); }); } else if (result == "unsignin") $.alert.show("登录已失效,请重新登录!", function() { showSignIn(); }); else if (result == "ulock") $.alert.show('你的账户被锁定了,不能完成操作!'); else { $.alert.show('相册创建失败!'); } }, type: 'POST', url: '#' }); } } }); } else { $.prompt.show('加载相册列表失败!'); setTimeout(function() { $.prompt.hidden(); }, 3000); } }, url: '#' }); } } return false; }); $(".upload_c_a").click(function() { return false; }); $(document).click(function() { var ealo = $('.upload_c_a .upload_c_a_c'); if (ealo.length) { ealo.hide(); $(".upload_c_a_b").css("border-color", "#ccc"); $(".upload_c_a_b_b").css("background-position", "0 -110px"); } }); var fileServer = ''; var imageInfo = []; var imageCount = 0; var dontleave = false; function initnormal() { $(".upload_t span").html($("<a>").attr("href", "#flash").html("Flash上传").click(function() { initflash(); })); $("#uploadcontainer").empty(); imageInfo = []; imageCount = 0; var uploadnormal = $('<div class="upload_c_n"><div id="uploadcontainernormal"><div class="upload_c_n_i"><span>本地图片</span><input type="file" name="picdata" /></div></div></div>'); var addfile = function(obj) { obj.one("change", function() { if (imageCount > 299) { $.dialog.showMsgLayer('提示', '一次最多只能上传300张图片!'); } else { if ($(this).parents('.upload_c_n').find('.upload_c_n_i').last().find(":file[name='picdata']").val().length) { var ni = $('<div class="upload_c_n_i"><span>&nbsp;</span><input type="file" name="picdata" />&nbsp;&nbsp;<a href="###" onclick="return false;">[移除]</a></div>'); ni.find("a").click(function() { addfile($(this).parents('.upload_c_n_i').prev('.upload_c_n_i').find(":file[name='picdata']")); $(this).parents('.upload_c_n_i').remove(); imageCount--; }); addfile(ni.find(":file[name='picdata']")); ni.appendTo("#uploadcontainernormal"); imageCount++; } } }); }; addfile(uploadnormal.find(":file[name='picdata']")); uploadnormal.find(":file[name='picdata']").live("change", function() { var val = this.value; if (val.length) { var extension = val.substr(val.lastIndexOf(".") + 1).toLowerCase(); if (! (extension == "bmp" || extension == "gif" || extension == "png" || extension == "jpg" || extension == "jpeg")) $.dialog.showMsgLayer("提示", "只能上传JPG、JPEG、GIF、PNG、BMP格式的图片!"); } }); uploadnormal.appendTo("#uploadcontainer"); imageCount++; $("#uploadbtn").show(); $("#uploadbtn").unbind('click'); $("#uploadbtn").click(function() { var val, extension; var uplistarray = new Array(); var gonext = true; uploadnormal.find(":file[name='picdata']").each(function() { val = this.value; if (val.length) { extension = val.substr(val.lastIndexOf(".") + 1).toLowerCase(); if (extension == "gif" || extension == "png" || extension == "jpg" || extension == "jpeg") { var has = false; for (var i = 0; i < uplistarray.length; i++) { if (uplistarray[i] == val) { $(this).parents('.upload_c_n_i').remove(); imageCount--; has = true; break; } } if (!has) uplistarray.push(val); } else { $.dialog.showMsgLayer("提示", "上传图片格式只可以是JPG、JPEG、GIF、PNG、BMP!"); gonext = false; return false; } } else { if (imageCount > 1) { $(this).parents('.upload_c_n_i').remove(); imageCount--; } } }); if (gonext) { if (uploadnormal.find(":file[name='picdata']").length && uploadnormal.find(":file[name='picdata']").val().length) { up("#uploadcontainernormal .upload_c_n_i", {}, fileServer + '/?action=upload&w=n', fileServer + '/?action=status', function(result) { imageInfo = eval('[' + result.replace(/}{/g, '},{') + ']'); wsuploaded(); }); $("#uploadbtn").hide(); dontleave = true; } else $.dialog.showMsgLayer("提示", "请选择要上传的图片!"); } }); } function initquote() { $("#uploadcontainer").empty(); imageInfo = []; imageCount = 0; $("#uploadcontainer").html('<div class="upload_c_q"><div class="upload_c_q_a">请输入网址:<input type="text" class="upload_c_q_a_ipt" /><input type="button" class="upload_c_q_a_btn cbtn" value="查找图片" onclick="asyncloadimg()" /></div></div>'); $("#uploadcontainer").find(":input").keypress(function(e) { var key = e.charCode ? e.charCode: e.keyCode ? e.keyCode: 0; if (key == 13) { asyncloadimg(); } }); $("#uploadbtn").hide(); } function addmorepic() { if (!$('#albums').val()) { $.dialog.showMsgLayer("加载失败", "未登录每次只能上传一张图片"); return false; } var url = $.trim($("#morepicv").val()); if (url.length && url.indexOf('.') > 0) { $("<img>").load(function() { var ris = ''; ris += '<div class="upload_c_q_r_b_i">'; ris += '<div class="upload_c_q_r_b_i_i"><img src="' + this.src + '" alt=""/></div>'; ris += '<div class="upload_c_q_r_b_i_c">'; ris += this.width + 'x' + this.height; ris += '</div>'; ris += '</div>'; $(ris).appendTo(('.upload_c_q_r_b')); $("#morepicv").val(''); $("#morepicv").focus(); }).error(function() { $.dialog.showMsgLayer("加载失败", "这不是一个有效的图片地址!"); }).attr("src", url); } else $("#morepicv").focus(); } $(".upload_c_q_a_ipt").focus(); $(".upload_c_q_a_ipt").keypress(function(e) { if(e.keyCode == 13) { asyncloadimg(); } }); var asyncloadimgwait = false; function asyncloadimg() { if($('#albums').val() == 0) { $.dialog.showMsgFuncLayer("提示", "请选择一个相册再上传"); return; } var url = $.trim($(".upload_c_q_a_ipt").val()); if(url == null || url.length==0) { return false; } if(!isImageUrl(url)) { $.dialog.showMsgFuncLayer("提示", "网址错误, 请以http/https开头, 且支持JPG、JPEG、GIF、PNG格式图片"); $(".upload_c_q_a_ipt").focus(); return false; } if (url.length) { $.ajax({ type: "POST", url: basePath+"network/upload", data: {"fileurl": url}, beforeSend: function() { $.prompt.show('努力上传中......'); }, success: function(result) { $.prompt.hidden(); var code = result.code; if (code == 200) { $.dialog.showMsgFuncLayer("提示", "上传成功", function() { $.dialog.hidden(); window.location.href = basePath+"detail/" + result.data; }); } else if(code == 403) { $.dialog.showMsgLayer("上传失败", "登录信息过期,请先登录", function() { showSignIn(); }, 1); } else { $.dialog.showMsgLayer("上传失败", result.message); } }, error: function() { $.prompt.hidden(); $.dialog.showMsgLayer("上传失败", "服务器异常..."); } }); } else $(".upload_c_q_a_ipt").focus(); } function isImageUrl(url) { var re = /((https|http):\/\/)[^\s]+\.(jpg|png|jpeg|gif)/gi; return re.test(url); } var asyncupwait = false; function asyncloadimgover(surl, wris, result) { if (wris && wris.length) { var ris = '<div class="upload_c_q_r">'; ris += '<div class="upload_c_q_r_a">请选择要上传的图片</div>'; ris += '<div class="upload_c_q_r_b">'; ris += wris; ris += '</div>'; ris += '<div class="upload_c_q_r_c"></div>'; ris += '</div>'; $(".upload_c_q").empty(); $(".upload_c_q").html(ris); $(".upload_c_q").find("#checkall").click(function() { $(".upload_c_q").find(":checkbox").attr("checked", "checked"); }); $(".upload_c_q").find("#invert").click(function() { $(".upload_c_q").find(":checkbox").each(function() { if ($(this).is(":checked")) $(this).attr("checked", ""); else $(this).attr("checked", "checked"); }); }); $("#uploadbtn").show(); $("#uploadbtn").unbind('click'); $("#uploadbtn").click(function() { $.prompt.show('努力上传中......'); $('.upload_c_q_a').hide(); $(".upload_c_b_a #uploadbtn").val('上传中...').attr('disabled', true).css('background', '#A3A3A3'); var imgurls = ''; var obj = $('.upload_c_q_r_b_i img'); for (var i = 0; i < obj.length; i++) { imgurls += obj[i].src + '|||||'; } $.post("/?m=Home&c=Pic&a=webup", { 'imgs': imgurls }, function(t) { if (t.status == 1) { $.prompt.hidden(); $.dialog.showMsgFuncLayer("上传成功", t.info, function() { if (t.num > 1) { window.location.href = '/album/' + getcookie('d_album'); } else { window.location.href = '/' + t.ps; } }, 1); } else { $.prompt.hidden(); $.dialog.showMsgFuncLayer("上传失败", t.info); } }); }); } else $.dialog.showMsgFuncLayer("没有满足条件的图片", "呃,没有找到宽或高大于200像素的图片哦!", function() { initquote(); $.dialog.hidden(); }, 1); } var wswait = false; function wsuploaded() { if (imageInfo.length) { window.onbeforeunload = function() { if (dontleave) window.event.returnValue = '图片上传未完成,确定要离开吗?'; }; var container = $(".upload"); container.empty(); var ws = '<div class="upload_t">完善图片信息</div>'; ws += '<div class="uploaded_ws_a">'; ws += '<span class="uploaded_ws_a_l"><span>同步分享到</span><span class="user_t_r_b"><span class="bdqq"></span><span class="bdsina"></span><span class="bdrenren"></span><span class="bdkaixin"></span></span></span>'; ws += '<span class="uploaded_ws_a_r"><input type="checkbox" name="wsbat" value="" class="cbrva" /> 统一添加信息</span>'; ws += '</div>'; ws += '<div class="uploaded_ws_b">'; ws += '<div class="uploaded_ws_b_a"><label>名称:</label><input type="text" id="cws_name" maxlength="30" /><label class="cog">*</label><span><label class="iptless">0</label>/30</span></div>'; ws += '<div class="uploaded_ws_b_a"><label>标签:</label><input type="text" id="cws_tag" maxlength="30" /><label class="cog">*</label><span><label class="iptless">0</label>/30</span></div>'; ws += '<div class="uploaded_ws_b_a uploaded_ws_b_h"><label>描述:</label><textarea id="cws_intro" rows="4" cols="101"></textarea><span class="uploaded_ws_b_h_s"><label class="iptless">0</label>/150</span></div>'; ws += '</div>'; ws += '<form id="ws_form" action="" method="post" onsubmit="return false;">'; for (var idx in imageInfo) { ws += '<input type="hidden" name="obj" value="' + imageInfo[idx].obj + '" />'; ws += '<div class="uploaded_ws_c">'; ws += '<div class="uploaded_ws_c_a"><div class="uploaded_ws_c_a_a"><img src="' + imageInfo[idx].preview + '" alt="" /></div></div>'; ws += '<div class="uploaded_ws_c_b">'; ws += '<div class="uploaded_ws_b_a"><label>名称:</label><input type="text" name="name" maxlength="30" value="' + imageInfo[idx].name + '" /><label class="cog">*</label><span><label class="iptless">' + imageInfo[idx].name.length + '</label>/30</span></div>'; ws += '<div class="uploaded_ws_b_a"><label>标签:</label><input type="text" name="tag" maxlength="30" value="" /><label class="cog">*</label><span><label class="iptless">0</label>/30</span></div>'; ws += '<div class="uploaded_ws_b_a uploaded_ws_b_h"><label>描述:</label><textarea name="intro" rows="4" cols="101">' + imageInfo[idx].intro + '</textarea><span class="uploaded_ws_b_h_s"><label class="iptless">' + imageInfo[idx].intro.length + '</label>/150</span></div>'; ws += '</div>'; ws += '</div>'; } ws += '</form>'; ws += '<div class="upload_c_b_a uploaded_ws_d"><input type="button" id="ws_btn" class="cbtn" value="保存" /></div>'; container.html(ws); $.getJSON("/getuserconnect.do?v=" + Math.random(), function(rs) { if (rs) container.find(".user_t_r_b").html(rs.uc); }); var getconnecting = function(url) { var form = $("<form>"); var ua = url.split("?"); if (ua.length > 1) { var qp = ua[1].split("&"); $.each(qp, function(i, p) { var kv = p.split("="); if (kv.length > 1) { var input = $("<input>"); input.attr("type", "hidden"); input.attr("name", kv[0]); input.attr("value", kv[1]); input.appendTo(form); } }); } form.attr("action", ua[0]); form.attr("method", "get"); form.attr("target", '_blank'); form.appendTo(document.body); form.submit(); form.empty(); form.remove(); }; container.find(".user_t_r_b span").live("click", function() { if ($(this).is("[class^='bd']")) $(this).attr("class", $(this).attr("class").replace("bd", "")); else { if ($(this).is("[data-bd='0']")) { var tc = $(this).attr("class"); if (tc == "qq") getconnecting('https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=100271575&redirect_uri=http://www.tuzhan.com/connect-tx.do&scope=get_user_info,add_share,get_info,add_pic_t,add_idol'); else if (tc == "sina") getconnecting('https://api.weibo.com/oauth2/authorize?client_id=843887157&response_type=code&redirect_uri=http://www.tuzhan.com/connect-xl.do'); else if (tc == "renren") getconnecting('https://graph.renren.com/oauth/authorize?client_id=f5d67f69833c4179b4e10a6e47d22a0a&redirect_uri=http://www.tuzhan.com/connect-rr.do&response_type=code&scope=publish_feed publish_share'); else if (tc == "kaixin") getconnecting('http://api.kaixin001.com/oauth2/authorize?client_id=8500894183902c301fda1674c0f47afc&response_type=code&redirect_uri=http://www.tuzhan.com/connect-kx.do&scope=basic user_birthday user_intro send_feed'); $(this).removeAttr("data-bd"); $(this).attr("class", "bd" + $(this).attr("class")); } else $(this).attr("class", "bd" + $(this).attr("class")); } }); container.find(":checkbox[name='wsbat']").click(function() { if ($(this).is(":checked")) container.find(".uploaded_ws_b").show(); else container.find(".uploaded_ws_b").hide(); }); container.find("#cws_name").keyup(function() { var nv = this.value; container.find(":input[name='name']").each(function(i) { this.value = nv + "_" + (i + 1); iptless(this, 30, $(this).parent().find("label.iptless").first()); }); iptless(this, 30, $(this).parent().find("label.iptless").first()); }); container.find("#cws_tag").keyup(function() { var tv = this.value; container.find(":input[name='tag']").each(function(i) { this.value = tv; iptless(this, 30, $(this).parent().find("label.iptless").first()); }); iptless(this, 30, $(this).parent().find("label.iptless").first()); }); container.find("#cws_intro").keyup(function() { var iv = this.value; container.find("textarea[name='intro']").each(function(i) { this.value = iv; iptless(this, 150, $(this).parent().find("label.iptless").first()); }); iptless(this, 150, $(this).parent().find("label.iptless").first()); }); container.find(":input[name='name']").keyup(function(e) { iptless(this, 30, $(this).parent().find("label.iptless").first()); }); container.find(":input[name='tag']").keyup(function(e) { iptless(this, 30, $(this).parent().find("label.iptless").first()); }); container.find("textarea[name='intro']").keyup(function(e) { iptless(this, 150, $(this).parent().find("label.iptless").first()); }); var sug_tags = ''; container.find("#cws_tag,:input[name='tag']").focus(function() { var nthis = $(this); if (sug_tags.length) showsugtags(nthis); else { $.getJSON("/suggesttags.do?v=" + Math.random(), function(rs) { if (rs) { sug_tags = rs.tags; showsugtags(nthis); } }); } }); container.find("#cws_tag,:input[name='tag']").click(function() { return false; }); $(document).click(function() { $.tips.hidden(); }); var showsugtags = function(nthis) { $.tips.hidden(); $.tips.show(nthis.parent(), { top: 41, left: 41 }, sug_tags); nthis.parent().find(".us_tags a").click(function() { if ($(this).hasClass("current")) { $(this).removeClass("current"); nthis.val($.trim(nthis.val().replace(new RegExp($(this).html(), "g"), '').replace(/(\s)\s/g, '$1'))); } else { var nval = $.trim(nthis.val() + ' ' + $(this).html()); if (nval.length < 30) { $(this).addClass("current"); nthis.val(nval); } } nthis.keyup(); return false; }); $.each(nthis.val().split(' '), function(i, v) { if ($.trim(v).length) { nthis.parent().find(".us_tags a:contains('" + v.replace(/'/g, "\\'").replace(/"/g, "\\'") + "')").each(function(x, o) { if ($(o).html() == v) $(o).addClass("current"); }); } }); }; container.find("#ws_btn").show(); container.find("#ws_btn").click(function() { $.tips.hidden(); if (container.find(":input[name='name'][value='']").length) { $.dialog.showMsgLayer('提示', '请完善图片名称!'); } else if (container.find(":input[name='tag'][value='']").length) { $.dialog.showMsgLayer('提示', '请完善图片标签!'); } else if (!wswait) { var tbfx = 0; var unshare = ''; if (container.find(".user_t_r_b span[class^='bd']").length) { tbfx = 1; $.each(container.find(".user_t_r_b span:not([class^='bd'])"), function(i, v) { unshare += $(v).attr("class") + ","; }); } $.ajax({ beforeSend: function() { wswait = true; $.prompt.show('正在保存......'); }, complete: function() { wswait = false; $.prompt.hidden(); dontleave = false; }, cache: false, data: $("#ws_form").serialize().replace(/,|%2c/gi, ' ') + "&tbfx=" + encodeURIComponent(tbfx) + "&unshare=" + encodeURIComponent(unshare) + "&preview=" + encodeURIComponent(imageInfo[0].preview), error: function() { $.dialog.showMsgLayer('系统异常', '对不起,系统出现异常,图片信息保存失败!'); }, success: function(result) { if (result.indexOf("ok|") > -1) { $.dialog.showMsgFuncLayer("保存成功", "图片信息保存成功!", function() { window.location.href = result.split('|')[1]; }, 1); } else $.dialog.showMsgLayer('保存失败', '图片信息保存失败!'); }, type: "POST", url: '/wsuploaded.do' }); } }); } else { $.dialog.showMsgLayer('上传失败', '没有上传成功的文件!'); dontleave = false; } }<file_sep>package com.jiajun.imagehosting.dao; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.jiajun.common.base.BaseDao; import com.jiajun.imagehosting.domain.AlbumEntity; @Repository public class AlbumDao extends BaseDao<AlbumEntity> { @Override protected String getNamespace() { return "albumEntityMapper"; } public AlbumEntity selectByAlbumNameAndUserId(String albumName, Integer userId) { Map<String, Object> params = new HashMap<>(); params.put("name", albumName); params.put("userId", userId); return (AlbumEntity)selectObject("selectByUserAndName", params); } public List<AlbumEntity> selectContainImageByUserId(Integer id) { return selectList("selectContainImageByUserId", id); } public List<AlbumEntity> selectByUserId(Integer userId) { return selectList("selectByUserId", userId); } public List<Integer> selectIdsByUserId(Integer userId) { return selectList("selectIdsByUserId",userId); } public void updateAlbumAuthority(Integer albumId, int isPublic) { Map<String, Object> params = new HashMap<>(); params.put("id", albumId); params.put("isPublic", isPublic); params.put("updateTime", new Date()); update("updateAlbumAuthority", params); } public List<AlbumEntity> selectContainImageNumsByUserId(Integer userId) { return selectList("selectContainImageNumsByUserId", userId); } } <file_sep>function ltrim(str) { return str.replace(/[0]/g, ""); } var successFindurl; (function($) { $(function() { var $wrap = $('#uploader'), $queue = $('<ul class="filelist"></ul>').appendTo($wrap.find('.queueList')), $statusBar = $wrap.find('.statusBar'), $info = $statusBar.find('.info'), $upload = $wrap.find('.uploadBtn'), $placeHolder = $wrap.find('.placeholder'), $progress = $statusBar.find('.progress').hide(), fileCount = 0, fileSize = 0, ratio = window.devicePixelRatio || 1, thumbnailWidth = 110 * ratio, thumbnailHeight = 110 * ratio, state = 'pedding', percentages = {}, isSupportBase64 = (function() { var data = new Image(); var support = true; data.onload = data.onerror = function() { if (this.width != 1 || this.height != 1) { support = false; } } data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw=="; return support; })(), supportTransition = (function() { var s = document.createElement('p').style, r = 'transition' in s || 'WebkitTransition' in s || 'MozTransition' in s || 'msTransition' in s || 'OTransition' in s; s = null; return r; })(), uploader; if (!WebUploader.Uploader.support()) { alert('贴图库上传不支持您的浏览器!如果你使用的是IE浏览器,请尝试升级 flash 播放器'); throw new Error('WebUploader does not support the browser you are using.'); } uploader = WebUploader.create({ pick: { id: '#filePicker', label: '点击选择图片' }, formData: { Token: '' }, compress: null, dnd: '#dndArea', paste: '#uploader', swf: '/static/js/upload/Uploader.swf', chunked: false, chunkSize: 512 * 1024, server: basePath+'local/upload', accept: { title: 'Images', extensions: 'gif,jpg,jpeg,png', mimeTypes: 'image/jpg,image/jpeg,image/png,image/gif' }, disableGlobalDnd: true, fileNumLimit: allownum, fileSizeLimit: 1024 * 1024 * 200, fileSingleSizeLimit: 10 * 1024 * 1024 }); uploader.on('uploadBeforeSend', function(block, data) { /* data.Token = token; console.log(token);*/ }); uploader.on('dndAccept', function(items) { var denied = false, len = items.length, i = 0, unAllowed = 'text/plain;application/javascript '; for (; i < len; i++) { if (~unAllowed.indexOf(items[i].type)) { denied = true; break; } } return ! denied; }); uploader.addButton({ id: '#filePicker2', label: '继续添加' }); uploader.on('ready', function() { window.uploader = uploader; }); function addFile(file) { var $li = $('<li id="' + file.id + '">' + '<p class="title">' + file.name + '</p>' + '<p class="imgWrap"></p>' + '<p class="progress"><span></span></p>' + '</li>'), $btns = $('<div class="file-panel">' + '<span class="cancel">删除</span>' + '<span class="rotateRight">向右旋转</span>' + '<span class="rotateLeft">向左旋转</span></div>').appendTo($li), $prgress = $li.find('p.progress span'), $wrap = $li.find('p.imgWrap'), $info = $('<p class="error"></p>'), showError = function(code) { switch (code) { case 'exceed_size': text = '文件大小超出'; break; case 'interrupt': text = '上传暂停'; break; default: text = '上传失败,请重试'; break; } $info.text(text).appendTo($li); }; if (file.getStatus() === 'invalid') { showError(file.statusText); } else { $wrap.text('预览中'); uploader.makeThumb(file, function(error, src) { var img; if (error) { $wrap.text('不能预览'); return; } if (isSupportBase64) { img = $('<img src="' + src + '">'); $wrap.empty().append(img); } else { $.ajax('./preview.php', { method: 'POST', data: src, dataType: 'json' }).done(function(response) { if (response.result) { img = $('<img src="' + response.result + '">'); $wrap.empty().append(img); } else { $wrap.text("预览出错"); } }); } }, thumbnailWidth, thumbnailHeight); percentages[file.id] = [file.size, 0]; file.rotation = 0; } file.on('statuschange', function(cur, prev) { if (prev === 'progress') { $prgress.hide().width(0); } else if (prev === 'queued') { $li.off('mouseenter mouseleave'); $btns.remove(); } if (cur === 'error' || cur === 'invalid') { showError(file.statusText); percentages[file.id][1] = 1; } else if (cur === 'interrupt') { showError('interrupt'); } else if (cur === 'queued') { percentages[file.id][1] = 0; } else if (cur === 'progress') { $info.remove(); $prgress.css('display', 'block'); } else if (cur === 'complete') { $li.append('<span class="success"></span>'); } $li.removeClass('state-' + prev).addClass('state-' + cur); }); $li.on('mouseenter', function() { $btns.stop().animate({ height: 30 }); }); $li.on('mouseleave', function() { $btns.stop().animate({ height: 0 }); }); $btns.on('click', 'span', function() { var index = $(this).index(), deg; switch (index) { case 0: uploader.removeFile(file); return; case 1: file.rotation += 90; break; case 2: file.rotation -= 90; break; } if (supportTransition) { deg = 'rotate(' + file.rotation + 'deg)'; $wrap.css({ '-webkit-transform': deg, '-mos-transform': deg, '-o-transform': deg, 'transform': deg }); } else { $wrap.css('filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + (~~ ((file.rotation / 90) % 4 + 4) % 4) + ')'); } }); $li.appendTo($queue); } function removeFile(file) { var $li = $('#' + file.id); delete percentages[file.id]; updateTotalProgress(); $li.off().find('.file-panel').off().end().remove(); } function updateTotalProgress() { var loaded = 0, total = 0, spans = $progress.children(), percent; $.each(percentages, function(k, v) { total += v[0]; loaded += v[0] * v[1]; }); percent = total ? loaded / total: 0; spans.eq(0).text(Math.round(percent * 100) + '%'); spans.eq(1).css('width', Math.round(percent * 100) + '%'); updateStatus(); } function updateStatus() { var text = '', stats; if (state === 'ready') { text = '选中' + fileCount + '张图片,共' + WebUploader.formatSize(fileSize) + '。'; } else if (state === 'confirm') { stats = uploader.getStats(); if (stats.uploadFailNum) { text = '已成功上传' + stats.successNum + '张照片至相册,' + stats.uploadFailNum + '张照片上传失败,<a class="retry" href="#" style="color:#6194E9;text-decoration;">重新上传</a>失败图片或<a class="ignore" href="#" style="color:#6194E9;text-decoration;">忽略</a>' } } else { stats = uploader.getStats(); text = '共' + fileCount + '张(' + WebUploader.formatSize(fileSize) + '),已上传' + stats.successNum + '张'; if (stats.uploadFailNum) { text += ',失败' + stats.uploadFailNum + '张'; } } $info.html(text); } function setState(val) { var file, stats; if (val === state) { return; } $upload.removeClass('state-' + state); $upload.addClass('state-' + val); state = val; switch (state) { case 'pedding': $placeHolder.removeClass('element-invisible'); $queue.hide(); $statusBar.addClass('element-invisible'); uploader.refresh(); break; case 'ready': $placeHolder.addClass('element-invisible'); $('#filePicker2').removeClass('element-invisible'); $queue.show(); $statusBar.removeClass('element-invisible'); uploader.refresh(); break; case 'uploading': $('#filePicker2').addClass('element-invisible'); $progress.show(); $upload.text('暂停上传'); break; case 'paused': $progress.show(); $upload.text('继续上传'); break; case 'confirm': $progress.hide(); $upload.text('开始上传').addClass('disabled'); stats = uploader.getStats(); if (stats.successNum && !stats.uploadFailNum) { setState('finish'); return; } if (stats.successNum && stats.uploadFailNum) { $.dialog.showFuncLayer(430, "提示", stats.successNum + "张图片上传成功<br/><span class='cog'>失败" + stats.uploadFailNum + "张</span>", function() { $.dialog.hidden(); window.location.href = "/temp/" + encode64(successpid); }); $('#dialoglayer #dlbtnconfirm').val('查看上传成功的图片').css({ 'width': '145px', 'letter-spacing': '0' }); $('#dialoglayer #dlbtncancel').val('重新上传').css({ 'width': '80px', 'letter-spacing': '0' }).attr('onclick', '$(".retry").click()'); $('#dialoglayer #dlcont').css({ 'text-align': 'center' }); } if (!stats.successNum && stats.uploadFailNum) { $.dialog.showMsgFuncLayer("提示", "全部上传失败(" + stats.uploadFailNum + "张) (×_×)", function() { $.dialog.hidden(); }); } break; case 'finish': stats = uploader.getStats(); if (stats.successNum) { $('.progress').hide(); $.dialog.showMsgFuncLayer("提示", stats.successNum + "张图片全部上传成功", function() { successpid = successpid.substring(0, successpid.length - 1); if (successpid.split(',').length < 2) { if (!successFindurl) { alert('图片异常,上传处理失败'); return false; } //上传成功一张图片 window.location.href = basePath+"detail/"+successFindurl; } else { //成功多条 window.location.href = basePath+"list/" + d_album; } }, 1); } else { console.log(stats); alert(stats); state = 'done'; location.reload(); } break; } updateStatus(); } uploader.onUploadProgress = function(file, percentage) { var $li = $('#' + file.id), $percent = $li.find('.progress span'); $percent.css('width', percentage * 100 + '%'); percentages[file.id][1] = percentage; updateTotalProgress(); }; uploader.onFileQueued = function(file) { fileCount++; fileSize += file.size; if (fileCount === 1) { $placeHolder.addClass('element-invisible'); $statusBar.show(); } addFile(file); setState('ready'); updateTotalProgress(); }; uploader.onFileDequeued = function(file) { fileCount--; fileSize -= file.size; if (!fileCount) { setState('pedding'); } removeFile(file); updateTotalProgress(); }; uploader.on('uploadError', function(file, response) { response = JSON.parse(response); alert("上传失败:" + response.info + "(" + response.code + ")"); }); uploader.on('uploadSuccess', function(file, response) { if (response.code == '4791') { $.dialog.showMsgFuncLayer("提示", "全部上传失败,相册内图片数量已达上限", function() { $.dialog.hidden(); }); return false; } if (successpid == '0') successpid = ''; successpid += response.findurl + ','; successFindurl = response.data; }); uploader.on('all', function(type) { var stats; switch (type) { case 'uploadFinished': setState('confirm'); break; case 'startUpload': setState('uploading'); break; case 'stopUpload': setState('paused'); break; } }); uploader.onError = function(code) { $.alert.show(code); }; $upload.on('click', function() { //必须选择相册才能上传 if($("#albums").val() == 0) { $.dialog.showMsgLayer("提示", '请选择一个相册再上传!'); return false; } if ($(this).hasClass('disabled')) { return false; } if (state === 'ready') { uploader.upload(); } else if (state === 'paused') { uploader.upload(); } else if (state === 'uploading') { uploader.stop(true); } }); $info.on('click', '.retry', function() { uploader.retry(); }); $info.on('click', '.ignore', function() { window.location.reload(); }); $upload.addClass('state-' + state); updateTotalProgress(); }); })(jQuery); var absDecodeChars = new Array( - 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1); function absdecode(str) { var c1, c2, c3, c4; var i, len, out; len = str.length; i = 0; out = ""; while (i < len) { do { c1 = absDecodeChars[str.charCodeAt(i++) & 0xff]; } while ( i < len && c1 == - 1 ); if (c1 == -1) break; do { c2 = absDecodeChars[str.charCodeAt(i++) & 0xff]; } while ( i < len && c2 == - 1 ); if (c2 == -1) break; out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4)); do { c3 = str.charCodeAt(i++) & 0xff; if (c3 == 61) return out; c3 = absDecodeChars[c3]; } while ( i < len && c3 == - 1 ); if (c3 == -1) break; out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2)); do { c4 = str.charCodeAt(i++) & 0xff; if (c4 == 61) return out; c4 = absDecodeChars[c4]; } while ( i < len && c4 == - 1 ); if (c4 == -1) break; out += String.fromCharCode(((c3 & 0x03) << 6) | c4); } return out; } function utf16to8(str) { var out, i, len, c; out = ""; len = str.length; for (i = 0; i < len; i++) { c = str.charCodeAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { out += str.charAt(i); } else if (c > 0x07FF) { out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); } else { out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F)); out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); } } return out; } function utf8to16(str) { var out, i, len, c; var char2, char3; out = ""; len = str.length; i = 0; while (i < len) { c = str.charCodeAt(i++); switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: out += str.charAt(i - 1); break; case 12: case 13: char2 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: char2 = str.charCodeAt(i++); char3 = str.charCodeAt(i++); out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0)); break; } } return out; }<file_sep>var mzb; $(function() { if (mzb) { var script = document.createElement("script"); script.type = "text/javascript"; document.body.appendChild(script); } loadover(); }); var loadover = function() { var ot = $(".user_nav").offset().top; var fh = 78 + ot + $(window).height() - ($(".header").outerHeight() + $(".container").outerHeight() + $(".footer").outerHeight()); if (fh > 0) $("<div>").css({ "float": "left", "height": fh }).appendTo(document.body); $(window).scrollTop(0); var the = $(".photo_a img"); var prt = the.parent(); $(prt).hover(function() { var imgrotateleft = $("#imgrotateleft"); if (imgrotateleft.length) { imgrotateleft.show(); $("#imgrotateright").show(); } else { prt.css("position", "relative"); $("<a>").css({ "position": "absolute", "left": "0", "top": "0", "width": "16px", "height": "18px", "overflow": "hidden", "background": "#fff url("+basePath+"static/image/bg.png) no-repeat -321px -535px", "_background-image": "url("+basePath+"static/image/bg.gif)" }).attr({ "href": "###", "id": "imgrotateleft", "title": "向左旋转" }).click(function(e) { the.rotateLeft(); if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; return false; }).appendTo(prt); $("<a>").css({ "position": "absolute", "right": "0", "top": "0", "width": "16px", "height": "18px", "overflow": "hidden", "background": "#fff url("+basePath+"static/image/bg.png) no-repeat -425px -535px", "_background-image": "url("+basePath+"static/image/bg.gif)" }).attr({ "href": "###", "id": "imgrotateright", "title": "向右旋转" }).click(function(e) { the.rotateRight(); if (e.stopPropagation) e.stopPropagation(); else e.cancelBubble = true; return false; }).appendTo(prt); } }, function() { $("#imgrotateleft").hide(); $("#imgrotateright").hide(); }); }; var latlng, marktitle; function showmap(lat, lng) { latlng = [lat, lng]; marktitle = '拍摄地点'; $.dialog.showIframeDialog(680, '拍摄地点', '<div id="placemarkmap" style="width:100%;height:380px;"></div>'); var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=mapready"; document.body.appendChild(script); } function mapready() { var myOptions = { center: new google.maps.LatLng(latlng[0], latlng[1]), mapTypeControl: false, mapTypeId: google.maps.MapTypeId.ROADMAP, streetViewControl: false, zoom: 15 }; var map = new google.maps.Map(document.getElementById("placemarkmap"), myOptions); if (map) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(latlng[0], latlng[1]), map: map, title: marktitle }); } } $(".c_p_l_c_i_d .impeach").live('click', function() { impeach('photo', $(this).parents('.c_p_l_c_i').attr('data-obj')); }); function reply(dom) { if ($.cookie('puid')) { $(".c_p_l_c_i_d .comm").click(); var commipt = $(dom).parents(".c_p_l_c_i_e").find(".c_p_l_c_i_e_f_a input"); if (commipt.length) { commipt.focus(); commipt.val("@" + $(dom).parents(".c_p_l_c_i_e_i").find(".c_p_l_c_i_e_i_b a").text().replace(/"/g, "&quot;") + ":"); } } else $.dialog.showMsgFuncLayer("请登录", "对不起,仅登录用户可进行此操作!", function() { showSignIn(); }); } function showcomm(dom, obj, p) { $.getJSlive('/photocomment.do?r=' + Math.random(), { "obj": obj, "p": (p ? p: '') }, function(result) { if ($.isArray(result.comment)) { var ch = ''; $.each(result.comment, function(i, comment) { ch += '<div class="c_p_l_c_i_e_i">'; ch += '<span class="c_p_l_c_i_e_i_a"><a href="' + comment.culink + '" target="_blank"><img src="' + comment.cuimg + '" alt="" /></a></span>'; ch += '<span class="c_p_l_c_i_e_i_b"><a href="' + comment.culink + '" target="_blank">' + comment.cuname + '</a>' + comment.ctime + '</span>'; if (comment.clock == 'True') ch += '<span class="c_p_l_c_i_e_i_c">内容审核中!</span>'; else { ch += '<span class="c_p_l_c_i_e_i_c">' + comment.cont + '<span class="c_p_l_c_i_e_i_c_f"><a href="###" onclick="impeach(\'comment\',\'' + comment.cobj + '\');return false;">举报</a>&nbsp;&nbsp;<a href="###" onclick="delcomment(this,\'' + comment.cobj + '\',\'' + obj + '\');return false;">删除</a></span></span>'; } ch += '</div>'; }); ch += '<div class="c_p_l_c_i_e_p">' + result.page + '</div>'; $(dom).parents(".c_p_l_c_i_e").html(ch); } }); } var delcmWait = false; function delcomment(dom, obj, forobj) { if ($.cookie('puid')) { $.dialog.showFuncLayer(430, "确认删除", '确定要删除这条评论吗?', function() { if (!delcmWait) { $.ajax({ beforeSend: function() { delcmWait = true; }, complete: function() { delcmWait = false; }, cache: false, data: { 'obj': obj, 'forobj': forobj }, error: function() { $.dialog.showMsgLayer('系统异常', '对不起,系统出现异常,操作失败!'); }, success: function(result) { if ("unsignin" == result) { $.dialog.showMsgFuncLayer("登录失效", "登录已失效,请重新登录!", function() { showSignIn(); }, 1); } else if ("unown" == result) { $.dialog.showMsgLayer('没有权限', "呃,只能删除自己的评论或上传图片的评论哦!"); } else if ("ok" == result) { $.dialog.hidden(); $(dom).parents(".c_p_l_c_i_e_i").hide(); } else { $.dialog.showMsgLayer('删除失败', "呃,删除评论失败了!"); } }, type: "POST", url: '/delcomment.do' }); } }); } else $.dialog.showMsgFuncLayer("请登录", "对不起,请登录后再进行此操作!", function() { showSignIn(); }); }<file_sep>package com.jiajun.imagehosting.service.impl; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import com.jiajun.imagehosting.dao.UserDao; import com.jiajun.imagehosting.domain.UserEntity; import com.jiajun.imagehosting.service.UserService; @Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public UserEntity getByUsernameAndPw(String username, String password) throws Exception { Assert.notNull(username, "username can not be null"); Assert.notNull(password, "password can not be null"); return userDao.selectByUsernameAndPw(username, password); } @Override public void updateLoginInfo(Integer userId, String loginIp) throws Exception { UserEntity userEntity = new UserEntity(); userEntity.setId(userId); userEntity.setLastLogin(new Date()); userEntity.setLoginIp(loginIp); userDao.updateByPrimaryKeySelective(userEntity); } } <file_sep>package com.jiajun.imagehosting.domain; import java.util.Date; import java.util.List; public class AlbumEntity implements java.io.Serializable{ private static final long serialVersionUID = 5196824696603211610L; private Integer id; private Integer userId; private String name; private Boolean isPublic; private Boolean isSelected; private Date createTime; private Date updateTime; private Date deleteTime; private Boolean isDelete; private int imageSize; private List<ImageEntity> imageList; public int getImageSize() { return imageSize; } public void setImageSize(int imageSize) { this.imageSize = imageSize; } public List<ImageEntity> getImageList() { return imageList; } public void setImageList(List<ImageEntity> imageList) { this.imageList = imageList; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getIsPublic() { return isPublic; } public void setIsPublic(Boolean isPublic) { this.isPublic = isPublic; } public Boolean getIsSelected() { return isSelected; } public void setIsSelected(Boolean isSelected) { this.isSelected = isSelected; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Date getDeleteTime() { return deleteTime; } public void setDeleteTime(Date deleteTime) { this.deleteTime = deleteTime; } public Boolean getIsDelete() { return isDelete; } public void setIsDelete(Boolean isDelete) { this.isDelete = isDelete; } public AlbumEntity selectByUserAndName(Integer id2) { return null; } } <file_sep>$(function() { $('.bds_more').css({ 'background': 'none', 'width': '70px', 'height': '30px', 'margin': '0 0 0 -50px', 'clear': 'both', 'text-indent': '30px', 'color': '#999', 'font-size': '13px', 'line-height': '28px' }); $('#sub_nav').css('z-index', '1000'); $('.user_nav_b .upload_c_a_c_b_a :text[name=newalbum]').keyup(function() { var val = $(this).val(); if (val.length > 20) { val = val.substr(0, 20); $(this).val(val); } $(this).parent().find("label").first().html(val.length); }); document.onkeydown = function(event) { var e = event || window.event || arguments.callee.caller.arguments[0]; if (e && e.keyCode == 13) { $('#dlbtnconfirm').first().click(); } if (e && e.keyCode == 27) { $('#dlclose').first().click(); } } /* $.post("/?c=User&a=getmessnum", {}, function(ret) { if (ret > 0) { if (ret > 10) { ret = '10+' } $('#messtip').html(ret); $('#messnum').show(); } });*/ $('.delete.admin').click(function() { var title = $(this).parents('.c_p_l_c_i').find('.c_p_l_c_i_b a').html(); var r = confirm("彻底KO掉【" + title + "】,你确定吗?"); if (r == false) { return false; } var pid = $(this).parents('.c_p_l_c_i').attr('pid'); var obj = $(this).parents('.c_p_l_c_i'); $.post("/?m=Home&c=Index&a=ajaxDelPic", { pid: pid }, function(data) { if (data.code == '1') { $.dialog.showMsgFuncLayer("图片彻底删除成功", data.tip, function() { obj.remove(); $('.c_p_l_col').resize(); $.dialog.hidden(); }); } }, "json"); }); $('.deleteimginfo.admin').click(function() { var title = $(this).parents('.c_p_l_c_i.photo').find('.photo_b_a_a strong').html(); var r = confirm("彻底KO掉【" + title + "】,你确定吗?"); if (r == false) { return false; } var pid = $(this).parents('.c_p_l_c_i.photo').attr('pid'); $.post("/?m=Home&c=Index&a=ajaxDelPic", { pid: pid }, function(data) { if (data.code == '1') { $.dialog.showMsgFuncLayer("图片彻底删除成功", data.tip, function() { $.dialog.hidden(); }); } }, "json"); }); $('.is_admin_delete').click(function() { var title = $(this).parents('.c_p_l_c_i').find('.c_p_l_c_i_b a').html(); var pid = $(this).parents('.c_p_l_c_i').attr('pid') || $(this).attr('pid'); var obj = $(this).parents('.c_p_l_c_i'); $.post("/?m=Home&c=Index&a=ajax_is_admin_delete", { pid: pid }, function(data) { $.prompt.show(data.tip); setTimeout(function() { $.prompt.hidden() }, 1000); if (data.code == 1) { obj.find('.is_admin_delete').remove(); } }, "json"); }); }) function impeach(t, s) { $.dialog.showIframeDialog(550, '举报', '<iframe frameborder="0" width="500" height="270" marginheight="0" marginwidth="0" scrolling="no" src="/impeach?photo=' + s + '"></iframe>'); } function showSignIn() { window.location.href = basePath+"/index"; } function isScrollBottom() { return $(document).scrollTop() + $(window).height() >= $(document).height() - ( !! navigator.userAgent.match(/AppleWebKit.*Mobile.*/) || !!navigator.userAgent.match(/AppleWebKit/) ? 200 : 0); } function backTop() { var scrollTopDom = $("#scrolltopdom"); if ($(document).scrollTop() > 0) { if (!scrollTopDom.length) { scrollTopDom = $('<div id="scrolltopdom">回 到顶 部</div>'); scrollTopDom.css({ "position": "fixed", "bottom": "5px", "right": "5px", "width": "50px", "height": "50px", "padding": "10px", "font-size": "18px", "text-align": "center", "border": "1px solid #ccc", "background": "#fff", "color": "#999", "cursor": "pointer" }); if ( !! window.ActiveXObject && !window.XMLHttpRequest) { scrollTopDom.css({ "position": "absolute", "bottom": "auto", "display": "none" }); } scrollTopDom.hover(function() { scrollTopDom.css({ "background": "#f8f8f8", "color": "#666" }); }, function() { scrollTopDom.css({ "background": "#fff", "color": "#999" }); }); scrollTopDom.click(function() { $("html,body").animate({ scrollTop: 0 }, 1000); }); scrollTopDom.appendTo(document.body); } else scrollTopDom.show(); if ( !! window.ActiveXObject && !window.XMLHttpRequest) { scrollTopDom.css({ "top": $(document).scrollTop() + $(window).height() - 80 }); } } else if (scrollTopDom.length) scrollTopDom.hide(); }; (function($) { $.fn.scrollshowtips = function(act) { if ("show" === act && !this.find(".scrollshowtips").length) $('<div class="scrollshowtips"><span class="scrollshowtipsloading">正在加载中,请稍候......</span></div>').appendTo(this); else if ("null" === act) this.find(".scrollshowtips").html('呃,没有了!'); else if ("fail" === act) this.find(".scrollshowtips").html('加载失败了!<a href="###" onclick="$(this).parent().remove();scrollload();return false;">重新加载</a>'); else if ("remove" === act && this.find(".scrollshowtipsloading").length) this.find(".scrollshowtips").remove(); else if ("removeall" === act) this.find(".scrollshowtips").remove(); }; })(jQuery); /*=======================================================cookie操作===============================================*/ function setcookie(a, b) { var d = new Date(); var v = arguments; var c = arguments.length; var e = (c > 2) ? v[2] : null; var p = (c > 3) ? v[3] : null; var m = (c > 4) ? v[4] : window.location.host; var r = (c > 5) ? v[5] : false; if (e != null) { var T = parseFloat(e); var U = e.replace(T, ""); T = (isNaN(T) || T <= 0) ? 1 : T; U = ("snhdwmqy".indexOf(U) == -1 || U == "") ? 's': U.toLowerCase(); switch (U) { case 's': d.setSeconds(d.getSeconds() + T); break; case 'n': d.setMinutes(d.getMinutes() + T); break; case 'h': d.setHours(d.getHours() + T); break; case 'd': d.setDate(d.getDate() + T); break; case 'w': d.setDate(d.getDate() + 7 * T); break; case 'm': d.setMonth(d.getMonth() + 1 + T); break; case 'q': d.setMonth(d.getMonth() + 1 + 3 * T); break; case 'y': d.setFullYear(d.getFullYear() + T); break } } document.cookie = a + "=" + escape(b) + ((e == null) ? "": ("; expires=" + d.toGMTString())) + ((p == null) ? ("; path=/") : ("; path=" + p)) + ("; domain=tietuku.cn") + ((r == true) ? "; secure": "") } function getcookieval(a) { var b = document.cookie.indexOf(";", a); if (b == -1) b = document.cookie.length; return unescape(document.cookie.substring(a, b)) } function getcookie(a) { var v = a + "="; var i = 0; while (i < document.cookie.length) { var j = i + v.length; if (document.cookie.substring(i, j) == v) return getcookieval(j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break } return null } function delcookie(a) { var e = new Date(); e.setTime(e.getTime() - 1); var b = getCookie(a); document.cookie = a + "=" + a + ";path=/; domain=" + window.location.host + "; expires=" + e.toGMTString() } /*======================================================================================================================*/ function movedown(id, imgtop) { var img = $('#box' + id + ' img'); img.css('position', 'absolute'); if (img.width() < 200) { var t = img.height() - 500; } else { var t = imgtop - 500; } img.animate({ top: -t }, parseInt(String(t) + 0)); } function moveup(id) { var img = $('#box' + id + ' img'); img.css('position', 'absolute'); img.animate({ top: 0 }, 500); if (img.css('top') > 0) { img.stop(); } } function stopAni(id) { var img = $('#box' + id + ' img'); if (img.is(":animated")) { img.stop(); } } function enjoy(id) { $.get("/?m=Home&c=User&a=addenjoy_ajax", { 'pid': id }, function(t) { if (t.status == 1) { $('#box' + id).find('.favr').html('移除'); $('#box' + id).find('.favr').attr('onclick', 'delenjoy(' + id + ')'); $('#box' + id).find('.favr').attr('class', 'favred'); } else {} }); } function delenjoy(id) { $.get("/?m=Home&c=User&a=delenjoy_ajax", { 'pid': id }, function(t) { if (t.status == 1) { $('#box' + id).find('.favred').html('喜欢'); $('#box' + id).find('.favred').attr('onclick', 'enjoy(' + id + ')'); $('#box' + id).find('.favred').attr('class', 'favr'); } }) }
980c2ee9f832641df95c6f0b5cc4229f4936f695
[ "JavaScript", "Java" ]
15
Java
jiajun6416/imagehost-springboot
91df34aadd1ffa6ac66d67f5ef33381fda2fd78f
02141a3806fbef010bb7a4d7ddcb2f34b66a608c
refs/heads/master
<file_sep>#!/usr/bin/env ruby require 'faraday' require 'json' require 'ostruct' require 'optparse' require 'open3' @options = OpenStruct.new parser = OptionParser.new do |opts| opts.banner = 'Usage: createTag [options]' opts.on('-u URL', '--url', 'URL for GitHub') do |url| @options.url = url end opts.on('-o OWNER', '--owner', 'Owner or Organization name') do |owner| @options.owner = owner end opts.on('-r REPO', '--repo','Repository name') do |repo| @options.repo = repo end opts.on_tail('-h', 'Print Help menu') do |help| puts opts exit end end parser.parse! if @options.url.nil? and @options.repo.nil? puts 'You must specify the repo, owner and url. Please run with -h' exit end def getData(url, owner, repo) refs = Faraday.get "#{url}/repos/#{owner}/#{repo}/tags" @tag = JSON.parse(refs.body).map { |i| i['name'] }.sort.reverse.first if @tag.nil? @newVer = 'v0.1.0' tagBranch() else @incriment = JSON.parse(IO.read('version.json')).values.first octet = @tag.split('.') @major = octet[0] @minor = octet[1] @patch = octet[2] doIteration() end end getData(@options.url, @options.owner, @options.repo) def doIteration() case @incriment when 'patch' patch = @patch.to_i newPatch = patch += 1 @newVer = "#{@major}.#{@minor}.#{newPatch}" when 'minor' minor = @minor.to_i newMinor = minor += 1 @newVer = "#{@major}.#{newMinor}.0" when 'major' if @major.include?('v') major = @major.delete('v') major = major.to_i newMajor = major += 1 @newVer = "v#{newMajor}.0.0" else major = @major.to_i newMajor = major += 1 @newVer = "#{newMajor}.0.0" end end tagBranch() end def tagBranch() message = `git log --oneline -n 1` tagCMD = [ "git tag -a #{@newVer} -m #{message}", 'git push origin --tags' ] tagCMD.each do |cmd| Open3.popen3(cmd) do |_, stdout, stderr, _| while out = stdout.gets puts out end while err = stderr.gets puts err end end end end
1f89ebf36761a1f3717d7dc5ff0a13770af71e1f
[ "Ruby" ]
1
Ruby
discreet/createTag
df60522150ae6e435507660e0bbad7ae5ed9f08d
cc0fe3408700fd930cf6d34ee3e243a19a4e9add
refs/heads/master
<file_sep>#include "robot.hpp" int userSelection; bool run = true; bool lastTurnUTurn = false; //arrays int middle[150]; int front[150]; int back[150]; //left/right wheel speeds double vLeft = 0.0; double vRight = 0.0; //string corneringPath; int frontWhitePixelValue = 0; int leftWhitePixelValue = 0; int rightWhitePixelValue = 0; //USER INTERFACE - ASK USER FOR CORE/COMP OR CHALLENGE ROUTE //RUN THE SPECIFIED CODE //CORE/COMP FOLLOWS THE WHITE LINE //CHALLENGE FOLLOWS THE LEFT RED WALL //Sets up the user Interface menu int userInterface(){ int userSelection; //Just a variable to store the selected option in std::cout<<">> "<<std::endl; std::cout<<">> Please enter maze difficulty/type"<<std::endl; std::cout<<">> Enter 1 for CORE and COMPLETION maps"<<std::endl; std::cout<<">> Enter 2 for CHALLENGE map"<<std::endl; std::cout<<">> Enter 3 to QUIT"<<std::endl; std::cin>>userSelection; //cin (console in or something like that)- input that stores the result in the userSelection variable //std::cout<<userSelection<<" input works correctly"<<std::endl; //Line that it just printing out the variable to check the input is correct return userSelection; } //Right turn void right(int t){ //slowly turns right for "t" long for (int i =0; i< t;i++){ setMotors(20,-20); } } //Left turn void left(int t){ //slowly turns left for "t" long for (int i =0; i< t;i++){ setMotors(-20,+20); } } //Calculates how far the robot is from the wall int howFar(){ int count =0; for (int i = 100;i>0;i--){ int p1= get_pixel(cameraView,i,75,0); int p2= get_pixel(cameraView,i-1,75,0); if ((p1<250) && (p2>250)){ break; //if it sees a red pixel it will stop counting } count++; } return count; //returns how far it is from the wall in front } //checks if there is a red pixel on the left bool leftWallPresent(int values1[]){ for (int i =0;i<150;i++){ if (values1[i] > 0){ return true; //if there is red pixel: there is a wall } else { return false;} //vise versa } } //calculates the distance from the left wall to the camera centre double redMiddle(int values1[]){ int numreds1 = 0; //similar to the white line middle int reds1 = 0; for (int i = 0;i < 150;i++){ if (values1[i] > 0) { reds1 = reds1+i; numreds1++; } } if (numreds1 > 10) { //Bot was breaking previously when dividing by 0 so this is required (also useful for the turning around function. double redlinelocation = reds1/numreds1; //red line location on line double camMiddle = cameraView.width/2; //the actual middle of the line double distFromWall = redlinelocation-camMiddle; //calculates the how far of the line is from the middle return distFromWall; } } //calculates the middle of white line double lineMiddle(int values[], int blackPixelCount){ int numwhites = 0; int whites = 0; for (int i = 0;i < 150;i++){ if (values[i] > 0) { whites = whites+i; numwhites++; } } if (numwhites > 0) { //Bot was breaking previously when dividing by 0 so this is required (also useful for the turning around function. double whitelinelocation = whites/numwhites; //middle of white line location on line double camMiddle = cameraView.width/2; //the actual middle of the line double errors = whitelinelocation - camMiddle ; //calculates the how far of the line is from the middle return errors; } else { if (blackPixelCount > 5) { //If it detects the flag will do this in an attempt to not turn around - doesn't quite work for core, that still runs off run = false; std::cout<<"Flag has been reached!"<<std::endl; std::cout<<"Maze has been completed!"<<std::endl; return 0; } else { //If the white line is not detected (and flag not seen) at the check point this will turn the bot around - Essentially handles dead ends. return(400/3); //This value is equivalent to 40 when multiplied by 0.3 as in adjustmotors() allows for swift turn arounds if no white pixel in front. } } } //Motor speed adjustment double adjustMotors(double errorValue) { //Positive calculated error val will cause bot to turn right, negative error val will cause bot to turn left //This if statement forces the bot to try the rightmost exit option when coming to an intersection if (frontWhitePixelValue > 0 && leftWhitePixelValue > 0 && rightWhitePixelValue == 0) { //std::cout<<"forced straightening occuring"; vLeft = 20; vRight = 20; } else { //std::cout<<errorValue; //1 is for coore and completion //2 is for challenge if (userSelection == 1){ vLeft = 20 + (0.3 * errorValue); //different error values for comp and challenge vRight = 20 - (0.3 * errorValue); setMotors(vLeft,vRight); } if (userSelection == 2){ vLeft = 20 + (0.1 * errorValue); vRight = 20 - (0.1 * errorValue); setMotors(vLeft,vRight); } } return 0; } int Challenge() { int count = howFar(); //calls the howfar function for how far away the robot is from the wall int error_Val = 0; //stores all the pixels as 1 and 0 in the arrays for the front and back for (int i=0;i<150;i++){ //back scanners int p3red = get_pixel(cameraView,90,i,0); int p3blue = get_pixel(cameraView,90,i,2); //front scanners int p4red = get_pixel(cameraView,10,i,2); int p4blue = get_pixel(cameraView,10,i,2); int isRed; //the first if handles the white line at the start of the maze //else section handles normal part of maze if ((p4blue > 250) || (p3blue > 250)) { adjustMotors(0); } else { //add to back array if (p3red > 250 && p3blue < 250){ isRed = 1; } else {isRed =0;} back[i]=isRed; //add to front array if (p4red > 250 && p4blue < 250){ isRed = 1; } else {isRed =0;} front[i]=isRed; } } //stores the two distance in the variables from the redmiddle double distance1 = redMiddle(front); double distance2 = redMiddle(back); error_Val = (distance1-distance2); //new error from the difference std::cout<<"error val: "<<error_Val<<std::endl; bool wallThere = true; //checks if there is a left wall from the leftwallpresent function wallThere = leftWallPresent(back); //If last move was a u turn this code will try and force the bot to find a wall on the left. //Will keep turning left until another wall is found to follow OR a left/right turn has to be made //at a wall in front which will indicate walls are going to be found. //The left and right turns adjust lastTurnUTurn to ensure it only runs when the previous turn was a u-turn if(count > 75 && lastTurnUTurn == true && wallThere == false) { error_Val = -28; //value to turn to find left hand wall } //turns right when the wall is less than 25 pixels away if ((count < 25) && (!count == 0)){ if (wallThere == true){ right(6); lastTurnUTurn = false; } else { left(6); lastTurnUTurn = false; } } //Completes the u turn if left/right turning can not result in a corrective turn. if (count < 10 && count != 0) { right(12); //Does a 180 lastTurnUTurn = true; } std::cout<<"Count: "<<count<<std::endl; std::cout<<"Left Wall: "<<wallThere<<std::endl; return(error_Val); } int main(){ if (initClientRobot() !=0){ std::cout<<" Error initializing robot"<<std::endl; } setMotors(40,40); userSelection = userInterface(); //Just a variable to store the selected option in //follow quit process if(userSelection == 3){ //confirm if user wants to QUIT... std::cout<<">> ARE YOU SURE YOU WANT TO QUIT? (1 to quit / 2 to restart)"<<std::endl; std::cin>>userSelection; if(userSelection == 1){ setMotors(0,0); return 0; } else if(userSelection == 2){ userSelection = userInterface(); if (userSelection == 3){ setMotors(0,0); return 0; } } } SavePPMFile("i0.ppm",cameraView); lastTurnUTurn = false; while(run){ takePicture(); double error; //Core/Completion section - runs only if user selects the 1st option if(userSelection == 1) { int frontRegionCheck; int leftRegionCheck; int rightRegionCheck; frontWhitePixelValue = 0; leftWhitePixelValue = 0; rightWhitePixelValue = 0; int blackpixels = 0; for (int i = 0; i<150;i++){ int pix = get_pixel(cameraView,90,i,3); int isWhite; if (pix >250){isWhite = 1;} else {isWhite = 0;} middle[i] = isWhite; //Checks for flag, will end while if flag is detected int blackPixelCheck = get_pixel(cameraView, 70, i, 3); if (blackPixelCheck < 20) { blackpixels++; } //std::cout<<middle[i]<<" "; } for (int j = 0; j < 20; j++) { leftRegionCheck = get_pixel(cameraView, 80 + j, 55, 3); if (leftRegionCheck > 250) { leftWhitePixelValue++; } rightRegionCheck = get_pixel(cameraView, 80 + j, 95, 3); if (rightRegionCheck > 250) { rightWhitePixelValue++; } frontRegionCheck = get_pixel(cameraView, 75, 65 + j, 3); if (frontRegionCheck > 250) { frontWhitePixelValue++; } } error = lineMiddle(middle, blackpixels); } //Challenge section of code - runs only if the user selects 2nd option else if (userSelection == 2) { error = Challenge(); //restart program if invalid input } else if( (userSelection != 1) && (userSelection != 2) && (userSelection != 3) ){ userSelection = userInterface();//restart } //Calls for the robot's direction to be changed based on the error value found adjustMotors(error); } //while } // main <file_sep># Installation MANUAL for Windows 10 (mingW and Geany) NOTE: ideally you should already have MingW and Geany installed before you begin the following STEPS: If you do not have MinGW installed follow the steps entitled **Getting MinGW:**, otherwise follow **Updating MinGW:** where there are instrictions for updating your currently installed version of MinGW to the correct corresponding version for the SFML build used. If you do not have Geany installed download and follow the steps from https://www.geany.org/ **Getting MinGW:** - Follow the link to the download page on the SFML website: www.sfml-dev.org/download/sfml/2.5.1/ - Download the corresponding version of "MinGW Builds 7.3.0" as what will be your chosen SFML install. For this program it is highly recommended (and assumed) that you will insall "MinGW Builds 7.3.0 (64-bit)" - This is the version that is verified to work correctly and should be used with "GCC 7.3.0 MinGW (SEH) - 64-bit" . Do not mix and match these versions - you should use this specific pair. - Create a folder in your C drive entitled "MinGW" - the directory should be C:\MinGW - Extract (Ideally using 7Zip or a similar program) the file downloaded through selecting "GCC 7.3.0 MinGW (SEH) - 64-bit" wherever downloaded. This will result in a folder named "mingw64" being created. The files within this folder should then be moved into the C:\MinGW folder - There should be no intermediary folders meaning that opening the MinGW folder in the C drive will lead directly to the folder containing files "bin" and "lib" for example. To ensure that this is correct the directory within the bin folder should be C:\MinGW\bin if following along exactly - Press your windows button (or just open windows search) and type in / search for environment variables - click on and open the option "Edit the system environment variables" - From there select the "Environment Variables..." button then select the variable entitled "Path" and press the "Edit" button underneath the box entitled "User variables for \[your username here\]" - Press "New" and paste in the directory to the "bin" folder in the MinGW C drive folder - It should be along the lines of C:\MinGW\bin if installed in the directed place. To get this yourself open the bin folder and click into the file path that shows the current folder and then copy/paste when selected "New" - Restart your PC to ensure changes are applied and move onto the installation step. (It may be a good idea to check that the compiler is working correctly by attempting to compile, build and run a sample file (perhaps a simple hello world program)) **Updating MinGW:** - Follow the link to the download page on the SFML website: www.sfml-dev.org/download/sfml/2.5.1/ - Download the corresponding version of "MinGW Builds 7.3.0" as what will be your chosen SFML install. For this program it is highly recommended (and assumed) that you will insall "MinGW Builds 7.3.0 (64-bit)" - This is the version that is verified to work correctly and should be used with "GCC 7.3.0 MinGW (SEH) - 64-bit" . Do not mix and match these versions - you should use this specific pair. - Extract the file downloaded through selecting (using 7Zip or similar) "MinGW Builds 7.3.0 (64-bit)", replace the contents of your C:\MinGW folder with everything in this new folder. *If you do not have this folder in your C drive follow **Getting MinGW** instead* - The contents of this install should replace everything in the currently existing folder so you should delete all current contents and then move the new contents inside the extracted "mingw64" folder into C:\MinGW - This should update your install of MinGW (if it has been set up correctly before with changing environment variables) **INSTALLING:** Before being able to run robot.cpp and have the robot complete the maze you must first install the correct versions of the minGW c++ compiler and the corresponding SFML build. - Follow this link to the download page on the SFML website: www.sfml-dev.org/download/sfml/2.5.1/ - Download the "MinGW Builds 7.3.0" and "GCC 7.3.0 MinGW (SEH)" files from the above website. Choose 32bit or 64bit version files, depending on your PC. Make sure these versions selected match and we highly recomment the 64 bit option. If you are to follow this manual as intended install "MinGW Builds 7.3.0 (64-bit)" and "GCC 7.3.0 MinGW (SEH) - 64-bit" - ***follow the instuctions around getting or updating MinGW to correctly configure your MinGW install*** - Extract the "GCC 7.3.0 MinGW (SEH)" Zip folder to your C drive. Rename the extracted folder to 'SFML' - This should provide you with a directory location of C:\SFML - Ensure that the folders and files of the SFML build (i.e. bin, doc) are within C:\SFML and not nested in another folder (i.e. ensure directory to bin folder is C:\SFML\bin) - Download the "AVC_Win10_KDLCBoys.zip" folder from this repository if you haven't got it already - Extract the 'AVC_Win10_KDLCBoys.zip' folder to the destination you would like it to be stored - Go to C:\SFML\bin and copy all the .dll files (There will be 11) in this folder - Paste these files into the "AVC_robot" and "AVC_server" folders - selecting replace current files in destination folder to ensure the .dll files match - Open up the 'robot.cpp' file which is in the 'AVC_robot" folder, with Geany (This should be the correct updated version, however it may be a good idea to copy the code from opening "robot.cpp" from the GitHub repository directly and copy in this code to robot.cpp, save then carry on) - Once you have the cpp file in geany, click the drop-down menu next to the 'build' button, then click 'set build commands'. - A small window will open up...so then change the 'Independent commands' by adding "mingw32-" to the front of the three fields which should result in "mingw32-make" for Independant commands 1 and 2, and "mingw32-make %e.o" for command 3. - then click "OK"! - Open the "makefile" in both "AVC_robot" and "AVC_server" folders with Geany. ensure that the spacing in line 6 and 8 are tabbed indented. To do this remove the space on these lines and then readd it by pressing your TAB key **ONCE** - It would also be ideal to check that the directory on line 1 is correct - meaning that the line "DIR = C:\\SFML" should be pointing to where your SFML folder is on your C drive. **TESTING ROBOT PROGRAM:** - Open "server3.cpp" from the AVC_server folder with geany then click "Compile". Once this is done press "Make all" from the drop down menu next to "Build" and then once this is complete press "Execute" to run the server (Alternatively select server3.exe from the AVC_server folder when "Make all" completes.) Leave the console open. - Return back to the robot.cpp file in Geany. Click the build drop-down...then click "Make all". Wait for the message "compilation finished successfully" - Then click "Execute" - Select which map type is being tried by entering "1" for Core and Completion or "2" for Challenge in the server console. The robot should then begin moving. - If robot moves after execution...then SETUP is successful - To change the map being tested open "config.txt" in the AVC_server folder and change where it says "challenge.txt" after the comma to be "core.txt" for the Core map, "completion.txt" for the Completion map or "challenge.txt" for the Challenge map. **TROUBLESHOOTING (try following STEPS if SETUP unsuccessful):** - go to the "AVC_robot" folder and open up the "makefile" document. In lines 6 and 8...remove the indenting and then press "Tab" for each line - check your current environment variables are correct - follow this process in **Getting MinGW** - check that your 'MingW' program and 'SFML' folder are matching. Are they both 32bit or are they both 64bit? - Make sure you have the correct build of MingW for the SFML build we are using (MinGW version 7.3.0) <br /> # AVC Project Plan ### Team Name: KDLC Boys Team Members & contact info: <NAME> (<EMAIL>) <NAME> (<EMAIL>) <NAME> (<EMAIL>) <NAME> (<EMAIL>) Communication tool: Facebook Messenger, Zoom Roles:\ Project Manager/Developer - Kevin Software Developer - Daniel Software Developer - Lee Software Developer - Christian Role Descriptions: * **Project Manager** (organising team meetings, reporting regularly on progress) * **Software Developer** (writing core code and extending functionality, testing and documentation, debugging and committing to git, writing test cases and documenting performance against milestones) Development Stages: * **Core** - following the line * **Completion** - includes obstacles and dead-ends, 90-deg corners * **Challenge** - more of a maze structure...stay between the walls...corridor shape --------------------------------------------------------------------------------------------------------------------------------- ### DATED PLAN AND MILESTONE GOALS ## **Week 1 (Ending 5<sup>th</sup> June 2020)** Objective for this week: **Start the project** Tasks to complete this: 1. - [x] Make contact with the team. 2. - [x] Ensure everyone's installations are corrrect. - [x] Check to make sure everyone will have capability to work on project. - [x] Ensure SFML is installed for everyone. - [x] Test all installations work and everyone's machines can run server3.cpp and robot.cpp correctly. 3. - [x] Complete plan and goals for team to adhere by through project. 4. - [x] Assign roles and tasks for team members to complete. 5. - [x] Oragnise team meetings (to be continued throughout project) for extra discussion of project direction, issues or any other point to be raised regarding progress. 6. - [x] Begin individual time management logs. Challenges / conflicts of this week: - SFML issues causing problems with getting ready for project. - Lee facing issues with his setup/installation; waiting on him to FINISH. Due this week: - AVC project plan. --------------------------------------------------------------------------------------------------------------------------- ## **Week 2 (Ending 12<sup>th</sup> June 2020)** Objective for this week: **Core and Completion Code.** Tasks to complete this: 1. - [x] Write the code to allow robot to complete CORE difficulty maze. 2. - [x] Write the code to allow robot to complete COMPLETION difficulty maze. 3. - [x] TESTING: Check code completes maze consistently within given time - debug and fix to ensure this occurs. 4. - [x] Ensure everyone is contributing as expected, following the plan and keeping contact/guiding team to keep within schedule. 5. - [x] Maintain GitHub repository - Including updating plan/README, updating Wiki and maintaining files. Challenges / conflicts of this week: - Assignments for COMP102/112 , ENGR121 and CYBR171 may reduce time commited to AVC project, possibly impeding progress - Making the functions work together...smart collaboration/communication NEEDED! - Kevin faced some issues when running/testing the program...but eventually sorted it out by end of week Due this week: - Project progress check (Wiki discussion etc) - Core code should be done (At the very least...if completion or further work is possible) by the end of this week. -------------------------------------------------------------------------------------------------------------------------------- ## **Week 3 (Ending 19<sup>th</sup> June 2020)** Objective for this week: **Challenge Code - Coding part of project complete** Tasks to complete this: 1. - [x] Ensure everyone contributes as expected within team environment, plan is followed within schedule. 2. - [x] Write the code to allow robot to complete challenge difficulty maze. 3. - [x] Iterative TESTING: Make checkpoints and keep testing code as devleopment is made. Ensure that current code is functioning as it should. Do the necessary debugging and fixes as it is needed. 4. - [x] Clean up all of written code to ensure it complies with given restrictions and is more accessible and readable. Add more functions and make more modular if necessary. 5. - [x] FULL-PROGRAM TESTING: Do a full/overall test of the program...this might happen on FINAL day of development. Make sure all functions and capabilities are working as intended. Check this code completes the course consistently within given time - make any minor tweaks and fixes where it's needed. 7. - [x] Final check/read-through of code to be submitted, carefully checking to ensure all works as intended before submission date. 8. - [x] Maintain GitHub repository. - Including updating plan/README, updating Wiki, adding branches to MASTER code and maintaining files. 9. - [x] Submit final code. 10. - [x] Ensure everyone is on track for remainder of project 3 (Logs and reports) 11. - [x] Add in the Installation Manual into the README.md Challenges / conflicts of this week: - ENGR121 test and COMP102/112 assignments to complete as well - will be a big draw of time from team members that will impact on time working on AVC project. Due this week: - Code of project (All of core, completion and challenge) to be submitted on 19<sup>th</sup> June. ---------------------------------------------------------------------------------------------------------------------------------- ## **Week 4 (Ending 24th<sup>th</sup> June 2020)** ### Individual Work from HERE.... - Update and clean up individual logs, make presentable - Write brief (1 page) manual for new contractors of the company: How to manage your time - Write a comprehensive report...about this software which we developed (max. 10 pgs)
74a9ecf38ea29492ee70b29258c6d26de7f6cc75
[ "Markdown", "C++" ]
2
C++
kevyJose/AVC-Project_ENGR101
0a21488ff5c3c2352bb60ca687f88cb0b05e5202
759ead944f5c241793126cc6cc4c2ddf94439368
refs/heads/master
<repo_name>domenukk/TimberTreeUtils<file_sep>/timbertreeutils/src/main/java/net/ypresto/utils/timbertree/FailFastTree.java /* * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package net.ypresto.utils.timbertree; import android.util.Log; import timber.log.Timber; /** * An implementation of {@link Timber.Tree} which throws {@link Error} when priority of * log is exceeded the limit. Useful for developing or testing environment. * * @author ypresto */ public class FailFastTree extends Timber.Tree { private final int mFailFastPriority; /** * Create instance with default log priority to throw an error. * Default priority is ERROR. */ public FailFastTree() { this(Log.ERROR); } /** * Create instance with minimum log priority to throw an error. * * @param failFastPriority Tree will throw error if priority of log is greater or equal than * specified value. Expected to be one of constants from {@link Log}. */ public FailFastTree(int failFastPriority) { mFailFastPriority = failFastPriority; } private void assertPriority(int priority, Throwable t) { if (priority >= mFailFastPriority) { if (t != null) throw new LogPriorityExceededException(priority, mFailFastPriority, t); else throw new LogPriorityExceededException(priority, mFailFastPriority); } } @Override public void v(String s, Object... objects) { assertPriority(Log.VERBOSE, null); } @Override public void v(Throwable throwable, String s, Object... objects) { assertPriority(Log.VERBOSE, throwable); } @Override public void d(String s, Object... objects) { assertPriority(Log.DEBUG, null); } @Override public void d(Throwable throwable, String s, Object... objects) { assertPriority(Log.DEBUG, throwable); } @Override public void i(String s, Object... objects) { assertPriority(Log.INFO, null); } @Override public void i(Throwable throwable, String s, Object... objects) { assertPriority(Log.INFO, throwable); } @Override public void w(String s, Object... objects) { assertPriority(Log.WARN, null); } @Override public void w(Throwable throwable, String s, Object... objects) { assertPriority(Log.WARN, throwable); } @Override public void e(String s, Object... objects) { assertPriority(Log.ERROR, null); } @Override public void e(Throwable throwable, String s, Object... objects) { assertPriority(Log.ERROR, throwable); } @Override protected void log(int priority, String tag, String message, Throwable t) { assertPriority(priority, t); } } <file_sep>/settings.gradle include 'timbertreeutils' <file_sep>/README.md TimberTreeUtils =============== Includes [timber](https://github.com/JakeWharton/timber) tree for crashlytics, and debugging with forced crash. ## Trees ### CrashlyticsTree Send non-fatal exception report when `Timber.e()` is called (ONLY SEND REPORT instead of actual crash :) , be calm). Requires Crashlytics Android SDK. ### FailFastTree Throws LogPriorityExceededException (extends RuntimeException) when Timber log method called which log priority exceeds specified one. Useful when dog feeding, debug or quality assuarance. DON'T plant() this on production environment. ### LINCENSE Public domain (refer [http://unlicense.org/]).
1fd753e1b79949be55b35f66f85f798374cbcd49
[ "Markdown", "Java", "Gradle" ]
3
Java
domenukk/TimberTreeUtils
1fb4a9bbc5242ff95e23b19e899555337734fce8
1df84db1ef6cca38652713117ce1b70bd2b4cd01
refs/heads/master
<repo_name>stevemul/openshift-heat<file_sep>/deploy.sh #!/bin/bash # Usage: # deploy.sh [password] # # password is the password for the OpenStack tenancy for this cluster # # If the password is not supplied, the user will be prompted for it. # (this prevents the password being stored in your history, but still # allows scripted execution in pipelines to work) openshift_openstack_password="$1" multinetwork=$(python -c "import yaml;d=yaml.load(open('environment.yaml'));print(d['parameter_defaults']['multinetwork'])" | tr '[:upper:]' '[:lower:]') extra_gateway=$(python -c "import yaml;d=yaml.load(open('environment.yaml'));print(d['parameter_defaults']['deploy_extra_gateway'])" | tr '[:upper:]' '[:lower:]') if [[ $multinetwork == true ]]; then purpose_ident=$(python -c "import yaml;d=yaml.load(open('environment.yaml'));print(d['parameter_defaults']['net2_external_network'])" | tr '[:upper:]' '[:lower:]') fi function validateSetup() { if [[ -z ${OS_TENANT_ID} ]]; then echo -e "\nYou must source your OpenStack RC file so we can access the OpenStack API\n" exit 1 fi } function getPassword() { if [[ -z ${openshift_openstack_password} ]]; then echo -e "Please provide a password for the OpenStack tenancy OpenShift will be deployed to..." read -s openshift_openstack_password echo -e "Starting deployment..." fi } function setupHeatTemplate() { ansible-playbook ./setup-heat-templates.yaml \ --extra-vars "multinetwork=${multinetwork}" \ --extra-vars "extra_gateway=${extra_gateway}" \ --extra-vars "purpose_ident=${purpose_ident}" } function deployHeatStack() { openstack stack create -f yaml -t openshift.yaml openshift-${OS_TENANT_NAME} \ -e rhel_reg_creds.yaml \ -e environment.yaml \ --parameter time="$(date)" \ --parameter os_auth_url="${OS_AUTH_URL}" \ --parameter os_tenant_id="${OS_TENANT_ID}" \ --parameter os_tenant_name="${OS_TENANT_NAME}" \ --parameter os_region="${OS_REGION_NAME}" \ --parameter openshift_openstack_password="${<PASSWORD>}" \ --wait } function showBastionIp() { openstack stack output show openshift-${OS_TENANT_NAME} --all } validateSetup getPassword setupHeatTemplate deployHeatStack showBastionIp
7b3efab097c3615ad205bad06aed981794f41de1
[ "Shell" ]
1
Shell
stevemul/openshift-heat
30bc21afa2ef5a0a0665cb6caa36647fdfb039d8
b07c92177befd15ae0faae85c97194ced35aef7c
refs/heads/master
<repo_name>Aravinthr20/hangmangame<file_sep>/README.md # hangmangame Hangman is a word game where the player can make guesses and reveal the word. <file_sep>/HangManGame.java import java.util.Scanner; public class HangManGame { private static String[] words = {"r o b o t ","a g e n t ","c o g n i t i v e ","a u t o m a t a ","c h a t b o t ","h e u r i s t i c s ","f u z z y ","l i s p ","l o g i s t i c s ","m e c h a t r o n i c s ","p r o l o g ","h u m a n o i d ","b o t s ","s e a r c h ","c h a i n i n g ","e n t a i l m e n t ","p r u n i n g ","p e r c e p t ","s h e l l ","g a m i n g ","r e a s o n i n g ","a c t u a t o r ","s e n s o r ","n e u r a l n e t w o r k ","k n o w l e d g e b a s e "}; private static String word = words[(int) (Math.random()* words.length)]; private static String dash = new String(new char[word.length()/2]).replace("\0", "_ "); private static int count = 0; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Give a brave guess"); while (count < 5 && dash.contains("_")) { System.out.println(dash); String guess = sc.next(); hang(guess); } sc.close(); } public static void hang(String guess) { String newDash = ""; for (int i = 0; i < word.length(); i++) { if (word.charAt(i) == guess.charAt(0)) { newDash += guess.charAt(0); } else if (dash.charAt(i) != '_') { newDash += word.charAt(i); } else { newDash += "_"; } } if (dash.equals(newDash)) { count++; image(); } else { dash = newDash; } if (dash.equals(word)) { System.out.println("Great job! You proved your intelligence :)"); System.out.println(word); } } public static void image() { if (count == 1) { System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println("___|___"); } if (count == 2) { System.out.println(" ____________"); System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println(" | "); System.out.println("___|___"); } if (count == 3) { System.out.println(" ____________"); System.out.println(" | _|_"); System.out.println(" | / \\"); System.out.println(" | | |"); System.out.println(" | \\_ _/"); System.out.println(" |"); System.out.println(" |"); System.out.println(" |"); System.out.println("___|___"); } if (count == 4 ) { System.out.println(" ____________"); System.out.println(" | _|_"); System.out.println(" | / \\"); System.out.println(" | | |"); System.out.println(" | \\_ _/"); System.out.println(" | |"); System.out.println(" | |"); System.out.println(" |"); System.out.println("___|___"); System.out.println("Do you want hint?"); Scanner sc=new Scanner(System.in); String hint=sc.next(); if(hint.equals("yes")) System.out.println("HINT: The word is related to Artificial Intelligence"); } if (count == 5) { System.out.println("Sorry try to prove your intelligence next time!"); System.out.println(" ____________"); System.out.println(" | _|_"); System.out.println(" | / \\"); System.out.println(" | | |"); System.out.println(" | \\_ _/"); System.out.println(" | _|_"); System.out.println(" | / | \\"); System.out.println(" | / \\ "); System.out.println("___|___ / \\"); System.out.println("GAME OVER! The word was " + word); } } }
ed203ef94342de62a530d599f16eee8c8f8eb9cc
[ "Markdown", "Java" ]
2
Markdown
Aravinthr20/hangmangame
2191fad217219b386cae413fd9d0705254e58e4c
8d17aac3a25144191b0501903bf443b961d3b2ec
refs/heads/master
<repo_name>Harshit-Chaturvedi/harshit-chaturvedi.github.io<file_sep>/README.md # harshit-chaturvedi.github.io : https://harshit-chaturvedi.github.io/ - This is my personal portfolio showing my projects. <file_sep>/app.js const burger = document.getElementById("burger"); const navUL = document.querySelector(".nav-links"); burger.addEventListener("click", () => { navUL.classList.toggle("show") })
a257b169a5c678da65f067ea9e8a23bfa72ab5b3
[ "Markdown", "JavaScript" ]
2
Markdown
Harshit-Chaturvedi/harshit-chaturvedi.github.io
d6469f6b9131f79cdbcc94677c1fd805bb723dfc
9f2b760fb904aaef184a790e041cd1b125e294f8
refs/heads/master
<file_sep>// Import dependency var urlParser = require('js-video-url-parser'); // initialise the input output editors setupInputEditor(); setupOutputEditor(); // Add click events to buttons document.querySelector('#run').addEventListener('click', run); document.querySelector('#copy').addEventListener('click', copyOutput); // This variable is for requesting to the API var apiKey = '<KEY>'; //Check vimeo links var isVimeoVideoFound = true; // Pre-connect to Youtube api to speed up the generating process setTimeout(function() { loadYoutubeClient(); }, 500); var youtubeResponseTotal = ''; //This function is called by the Generate button async function run() { //Only run if the input is more than 10 chars if (isValidUrl == true) { getUrls(); //Only send requests to Youtube if urls exist if (youtubeVideoID) { await youtubeRequest(); youtubeResponseTotal = youtubeResponse.result.pageInfo.totalResults; findYoutubeUrlError(); } await vimeoRequest(); //Show errors if (isVimeoVideoFound == false && youtubeUrlCounter == youtubeResponseTotal) { outputEditor.setValue(''); showErrorMsg('.outputMessage1', `Error: ${vimeoErrorUrlCounter} of ${vimeoUrlCounter} Vimeo links are broken or inaccessible through the API.`); showErrorMsg('.outputMessage2',`Broken Vimeo url(s): </br>${vimeoErrorUrl}</br> Reason: Uploaders can set the privacy setting of their Vimeo videos to "Embed only", therefore they can't be found anywhere else on the web.`); } else if (isVimeoVideoFound == true && youtubeUrlCounter !== youtubeResponseTotal) { outputEditor.setValue(''); showErrorMsg('.outputMessage1', `Error: ${youtubeUrlCounter-youtubeResponseTotal} of ${youtubeUrlCounter} Youtube links are broken. Please check.`); showErrorMsg('.outputMessage2',`Broken Youtube video ID(s): </br>${youtubeErrorUrl}</br>`); } else if (isVimeoVideoFound == false && youtubeUrlCounter !== youtubeResponseTotal) { outputEditor.setValue(''); showErrorMsg('.outputMessage1', `Error: ${youtubeUrlCounter-youtubeResponseTotal} of ${youtubeUrlCounter} Youtube links are broken and </br>${vimeoErrorUrlCounter} of ${vimeoUrlCounter} Vimeo links are broken or inaccessible through the API.`); showErrorMsg('.outputMessage2',`Broken Vimeo url(s): </br>${vimeoErrorUrl}</br> Broken Youtube video ID(s): </br>${youtubeErrorUrl}</br> Reason: Uploaders can set the privacy setting of their Vimeo videos to "Embed only", therefore they can't be found anywhere else on the web.`); } else { hideErrorMsg('.outputMessage1'); hideErrorMsg('.outputMessage2'); printOutput(); } } } function printOutput() { printTitle(); printIframe(); } //initiate error message container var node = outputEditor.renderer.emptyMessageNode; node = outputEditor.renderer.emptyMessageNode = document.createElement('div'); node.className = 'outputMessage1'; outputEditor.renderer.scroller.appendChild(node); var node = outputEditor.renderer.emptyMessageNode; node = outputEditor.renderer.emptyMessageNode = document.createElement('div'); node.className = 'outputMessage2'; outputEditor.renderer.scroller.appendChild(node); function showErrorMsg(outputClass, errMsg) { document.querySelector(outputClass).innerHTML = errMsg; } function hideErrorMsg(outputClass) { var node = outputEditor.renderer.emptyMessageNode; if (node) { document.querySelector(outputClass).innerHTML = ''; } } //Variable for storing just the video id not the entire youtube url //Youtube API only accept video ids not the full url var youtubeVideoIdArr = []; var youtubeVideoID = ''; //Vimeo accepts OEMBED so full url is accepted and no api key is needed var vimeoUrlArr = []; ////////////////////////////////////////////////////////// //////////////////Youtube request section///////////////// ////////////////////////////////////////////////////////// //This function loads the API using the api key function loadYoutubeClient() { gapi.client.setApiKey(apiKey); return gapi.client.load('https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest') .then(function() {}, function(err) { console.error('Error loading GAPI client for API', err); }); } //Youtube error checking var youtubeErrorUrlArr = []; var youtubeErrorUrl = ''; var youtubeResponseVideoId=[]; function findYoutubeUrlError() { getyoutubeResponseVideoIdArr(); //Compare Youtube Video Ids sent against the response form Youtube youtubeErrorUrlArr = arrDiff(youtubeVideoIdArr, youtubeResponseVideoId); youtubeErrorUrlArr.forEach(function(element) { youtubeErrorUrl = youtubeErrorUrl + `&bullet; ${element}</br>`; }) } function getyoutubeResponseVideoIdArr(){ for(let i=0;i<youtubeResponse.result.items.length;i++){ youtubeResponseVideoId.push(youtubeResponse.result.items[i].id); } } var youtubeResponse = []; // Sends request to Youtube function youtubeRequest() { return gapi.client.youtube.videos.list({ 'part': 'snippet,contentDetails', 'id': youtubeVideoID }) .then(function(response) { youtubeResponse = response; }, function(err) { console.error('Execute error', err); }); } //end function gapi.load('client'); //Compare elements between 2 arrays and returns the different elements function arrDiff(arr1, arr2) { var arrays = [arr1, arr2].sort((a, b) => a.length - b.length); var smallSet = new Set(arrays[0]); return arrays[1].filter(x => !smallSet.has(x)); } ////////////////////////////////////////////////////////// /////////////////End Youtube request section////////////// ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// ///////////////////Vimeo request section////////////////// ////////////////////////////////////////////////////////// var vimeoErrorUrlCounter = 0; var vimeoErrorUrl=''; //This function takes in a full Vimeo url function vimeoFetch(url) { return fetch('https://vimeo.com/api/oembed.json?url=' + url) // return this promise .then((resp) => resp.json()) .catch((err) => { isVimeoVideoFound = false; vimeoErrorUrlCounter++; //For error checking: showing which urls are error vimeoErrorUrl = vimeoErrorUrl + `&bullet; ${url}</br>`; }); } var vimeoResponse = []; //Send request to Vimeo async function vimeoRequest() { //reset counter vimeoErrorUrlCounter = 0; var counter = 0; for (var o = 0; o < vimeoUrlArr.length; o++) { if (vimeoUrlArr[o]) { await vimeoFetch(vimeoUrlArr[o]) .then(function(data) { vimeoResponse[counter] = data; counter++; }) } } //end for loop } //end function ////////////////////////////////////////////////////////// ///////////////////End Vimeo request section////////////// ////////////////////////////////////////////////////////// //counter for youtube urls var youtubeUrlCounter = 0; var vimeoUrlCounter = 0; // This function gets urls from the input editor function getUrls() { //Reset arrays vimeoUrlArr = []; youtubeVideoIdArr = []; youtubeVideoID = ''; //Reset Youtube error checking youtubeErrorUrlArr = []; youtubeErrorUrl = ''; youtubeResponseVideoId=[]; youtubeResponseTotal=0; youtubeUrlCounter = 0; vimeoUrlCounter = 0; //Reset video checking isVimeoVideoFound = true; vimeoErrorUrl=''; //Get all lines from the input editor var urls = inputEditor.session.doc.getAllLines(); var urlCounter = 0; for (var i = 0; i < urls.length; i++) { //parse each line, if returned 'undefined': not a correct url var parsedUrl = urlParser.parse(urls[i]); if (parsedUrl) { if (parsedUrl.provider == 'youtube') { //for requesting to Youtube Api youtubeVideoID = youtubeVideoID + ',' + parsedUrl.id; //For printing youtube iframe youtubeVideoIdArr[urlCounter] = parsedUrl.id; urlCounter++; youtubeUrlCounter++; } //if vimeo url, add the full url to vimeoUrlArr array if (parsedUrl.provider == 'vimeo') { //Use urlParser.prase(url[i]) and then create link using below var createdUrl = urlParser.create({ videoInfo: { provider: parsedUrl.provider, id: parsedUrl.id, mediaType: parsedUrl.mediaType, } }) vimeoUrlArr[urlCounter] = createdUrl; vimeoUrlCounter++; urlCounter++; } } //end check returned value } //end for loop } //end function ////////////////////////////////////////////////////////// ////////////////////Print section///////////////////////// ////////////////////////////////////////////////////////// //This function prints out titles of the videos in li function printTitle() { //Clear output editor outputEditor.setValue(''); var videoNumber = 0; //Add <ol> outputEditor.session.insert(0, '<ol>'); addEmptyLine(); //Get the biggest array var arrSize = getBiggestArr(vimeoUrlArr, youtubeVideoIdArr); var vimeo = 0; var youtube = 0; for (var r = 0; r < arrSize; r++) { //Print vimeo titles if (vimeoUrlArr[r]) { var title = vimeoResponse[vimeo].title; var duration = convertVimeoDuration(vimeoResponse[vimeo].duration); var li = ` <li><strong>Video #${++videoNumber} ${title} (Duration: ${duration})</strong></li>`; outputEditor.session.insert(0, li); addEmptyLine(); vimeo++; } //Print youtube titles if (youtubeVideoIdArr[r]) { var title = youtubeResponse.result.items[youtube].snippet.title; var duration = convertYoutubeDuration(youtubeResponse.result.items[youtube].contentDetails.duration); var li = ` <li><strong>Video #${++videoNumber} ${title} (Duration: ${duration})</strong></li>`; outputEditor.session.insert(0, li); addEmptyLine(); youtube++; } } //Add </ol> outputEditor.session.insert(0, '</ol>'); addEmptyLine(); } //end function ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// function printIframe() { outputEditor.session.insert(0, '<p>'); //Get the biggest array var arrSize = getBiggestArr(vimeoUrlArr, youtubeVideoIdArr); var vimeo = 0; var youtube = 0; for (var r = 0; r < arrSize; r++) { addEmptyLine(); //Print vimeo titles if (vimeoUrlArr[r]) { var videoId = vimeoResponse[vimeo].video_id; var iframe = ` <iframe width='120' height='120' src='https://player.vimeo.com/video/${videoId}?color=ffffff&amp;title=0&amp;byline=0&amp;portrait=0' frameborder='0' webkitallowfullscreen='' mozallowfullscreen='' allowfullscreen=''></iframe>`; outputEditor.session.insert(r, iframe); addEmptyLine(); vimeo++; } //Print youtube titles if (youtubeVideoIdArr[r]) { var iframe = ` <iframe width='120' height='120' src='https://www.youtube.com/embed/${youtubeVideoIdArr[r]}?rel=0;showinfo=0' frameborder='0' allowfullscreen=''></iframe>`; outputEditor.session.insert(0, iframe); addEmptyLine(); youtube++; } } outputEditor.session.insert(0, '</p>'); } //Find the biggest array between vimeoUrlArr and youtubeVideoIdArr function getBiggestArr(arr1, arr2) { var arrSize = 0; if (arr1.length > arr2.length) { arrSize = arr1.length; } else if (arr1.length < arr2.length) { arrSize = arr2.length; } else { arrSize = arr1.length; } return arrSize; } ////////////////////////////////////////////////////////// /////////////////////End Print section//////////////////// ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// ///////////////////Counter section//////////////////////// ////////////////////////////////////////////////////////// //Calls updateUrlCounter function when inputEditor changes inputEditor.on('change', updateUrlCounter); var totalUrl = 0; var youtubeCounter = 0; var vimeoCounter = 0; // Get elements var youtubeCounterElement = document.querySelector('#youtubeCounter'); var vimeoCounterElement = document.querySelector('#vimeoCounter'); // Assigns default value to the counter youtubeCounterElement.innerHTML = ` ${youtubeCounter}`; vimeoCounterElement.innerHTML = ` ${vimeoCounter}`; var youtubeFlashTime = 0; var vimeoFlashTime = 0; //Variables for checking var isValidUrl = false; var isAtleastOneMatch = false; // This function outputs values to counter div element function updateUrlCounter() { isValidUrl = false; // Reset values youtubeCounter = 0; vimeoCounter = 0; // Get all lines from the input editor var urls = inputEditor.session.doc.getAllLines(); if (inputEditor.session.getValue().length < 1) { isAtleastOneMatch = false; } for (var i = 0; i < urls.length; i++) { // parse each line, if returned 'undefined': not a correct url var parsedUrl = urlParser.parse(urls[i]); if (parsedUrl) { if (parsedUrl.provider === 'youtube') { youtubeCounter++; isValidUrl = true; isAtleastOneMatch = true; } else if (parsedUrl.provider === 'vimeo') { vimeoCounter++; isValidUrl = true; isAtleastOneMatch = true; } } else if (isAtleastOneMatch == false) { isValidUrl = false; } // end check returned value } // end for loop vimeoCounterElement.innerHTML = ` ${vimeoCounter}`; youtubeCounterElement.innerHTML = ` ${youtubeCounter}`; // Add flash effect to counters when value changes if (youtubeCounter > youtubeFlashTime || youtubeCounter < youtubeFlashTime) { youtubeFlashTime = youtubeCounter; youtubeCounterElement.classList.add('youtubeCounterFlash'); setTimeout(function() { youtubeCounterElement.classList.remove('youtubeCounterFlash'); }, 500); } if (vimeoCounter > vimeoFlashTime || vimeoCounter < vimeoFlashTime) { vimeoFlashTime = vimeoCounter; vimeoCounterElement.classList.add('vimeoCounterFlash'); setTimeout(function() { vimeoCounterElement.classList.remove('vimeoCounterFlash'); }, 500); } } // End function ////////////////////////////////////////////////////////// /////////////////End Counter section////////////////////// ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// ///////////////////Input & Output setup/////////////////// ////////////////////////////////////////////////////////// function setupInputEditor() { window.inputEditor = ace.edit('input'); inputEditor.setTheme('ace/theme/tomorrow_night_eighties'); inputEditor.getSession().setMode('ace/mode/html'); inputEditor.on('input', updateInput); setTimeout(updateInput, 100); inputEditor.focus(); inputEditor.setOptions({ fontSize: '10.5pt', showLineNumbers: true, showGutter: true, vScrollBarAlwaysVisible: false, wrap: true }); inputEditor.setShowPrintMargin(false); inputEditor.setBehavioursEnabled(false); inputEditor.getSession().setUseWorker(false); } function updateInput() { var shouldShow = !inputEditor.session.getValue().length; var node = inputEditor.renderer.emptyMessageNode; if (!shouldShow && node) { inputEditor.renderer.scroller.removeChild(inputEditor.renderer.emptyMessageNode); inputEditor.renderer.emptyMessageNode = null; } else if (shouldShow && !node) { node = inputEditor.renderer.emptyMessageNode = document.createElement('div'); node.textContent = "Paste the whole HTML of an item and make sure there's only one link on each line" node.className = 'emptyMessage' inputEditor.renderer.scroller.appendChild(node); } } function setupOutputEditor() { window.outputEditor = ace.edit('output'); outputEditor.setTheme('ace/theme/tomorrow_night_eighties'); outputEditor.getSession().setMode('ace/mode/html'); outputEditor.setOptions({ fontSize: '10.5pt', showLineNumbers: true, showGutter: true, vScrollBarAlwaysVisible: false, wrap: true }); outputEditor.setShowPrintMargin(false); outputEditor.setBehavioursEnabled(false); } ////////////////////////////////////////////////////////// /////////////////End Input & Output setup///////////////// ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// /////////////////////////Copy function//////////////////// ////////////////////////////////////////////////////////// function copyOutput() { if (outputEditor.session.getValue().length > 0) { var copyTextarea = document.querySelector('#copiedText'); copyTextarea.value = outputEditor.getValue(); copyTextarea.select(); document.execCommand('copy'); // Reset textarea copyTextarea.value = ''; //Add flashStart class to overlay div to create a flash effect when copyOutput is called document.querySelector('.copyAlert').classList.add('flash'); setTimeout(function() { document.querySelector('.copyAlert').classList.remove('flash'); }, 500); } } //Create an overlay over outputEditor copyAlertOverlay(); function copyAlertOverlay() { var node = document.createElement('div'); node.className = 'copyAlert'; document.querySelector('#output .ace_scroller .ace_content').appendChild(node); } ////////////////////////////////////////////////////////// ///////////////////////End Copy function////////////////// ////////////////////////////////////////////////////////// //This function adds an empty line to the output editor function addEmptyLine() { outputEditor.session.insert({ row: outputEditor.session.getLength(), column: 0 }, '\n'); } //This function converts seconds to HH:MM::SS format function convertVimeoDuration(Seconds) { var hours = Math.floor(Seconds / 3600); var minutes = Math.floor((Seconds - (hours * 3600)) / 60); var seconds = Seconds - (hours * 3600) - (minutes * 60); // round seconds seconds = Math.round(seconds * 100) / 100; var result = ''; if (hours > 0) { result += (hours < 10 ? +hours : hours); result += ':'; } if (minutes > 0) { result += (minutes < 10 ? '0' + minutes : minutes); } else if (minutes < 1) { result += '0'; } result += ':'; result += (seconds < 10 ? '0' + seconds : seconds); return result; } //This function converts ISO 8601 duration to HH:MM:SS format function convertYoutubeDuration(t) { //dividing period from time var x = t.split('T'), duration = '', time = {}, period = {}, //just shortcuts s = 'string', v = 'variables', l = 'letters', // store the information about ISO8601 duration format and the divided strings d = { period: { string: x[0].substring(1, x[0].length), len: 4, // years, months, weeks, days letters: ['Y', 'M', 'W', 'D'], variables: {} }, time: { string: x[1], len: 3, // hours, minutes, seconds letters: ['H', 'M', 'S'], variables: {} } }; //in case the duration is a multiple of one day if (!d.time.string) { d.time.string = ''; } for (var i in d) { var len = d[i].len; for (var j = 0; j < len; j++) { d[i][s] = d[i][s].split(d[i][l][j]); if (d[i][s].length > 1) { d[i][v][d[i][l][j]] = parseInt(d[i][s][0], 10); d[i][s] = d[i][s][1]; } else { d[i][v][d[i][l][j]] = 0; d[i][s] = d[i][s][0]; } } } period = d.period.variables; time = d.time.variables; time.H += 24 * period.D + 24 * 7 * period.W + 24 * 7 * 4 * period.M + 24 * 7 * 4 * 12 * period.Y; if (time.H) { duration = time.H + ':'; if (time.M < 10) { time.M = '0' + time.M; } } if (time.S < 10) { time.S = '0' + time.S; } duration += time.M + ':' + time.S; return duration; } <file_sep># CORTEX-Video-Template-Generator-Web-Tool In-depth Report: https://docs.google.com/document/d/1Vg9QyxD_paHMckyipnaAJGwRr5w6GOlIGxCTJ3L5GqI/edit?usp=sharing<br/> Web App: https://chimeng62.github.io/ <file_sep>(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ // Import dependency var urlParser = require('js-video-url-parser'); // initialise the input output editors setupInputEditor(); setupOutputEditor(); // Add click events to buttons document.querySelector('#run').addEventListener('click', run); document.querySelector('#copy').addEventListener('click', copyOutput); // This variable is for requesting to the API var apiKey = '<KEY>'; //Check vimeo links var isVimeoVideoFound = true; // Pre-connect to Youtube api to speed up the generating process setTimeout(function() { loadYoutubeClient(); }, 500); var youtubeResponseTotal = ''; //This function is called by the Generate button async function run() { //Only run if the input is more than 10 chars if (isValidUrl == true) { getUrls(); //Only send requests to Youtube if urls exist if (youtubeVideoID) { await youtubeRequest(); youtubeResponseTotal = youtubeResponse.result.pageInfo.totalResults; findYoutubeUrlError(); } await vimeoRequest(); //Show errors if (isVimeoVideoFound == false && youtubeUrlCounter == youtubeResponseTotal) { outputEditor.setValue(''); showErrorMsg('.outputMessage1', `Error: ${vimeoErrorUrlCounter} of ${vimeoUrlCounter} Vimeo links are broken or inaccessible through the API.`); showErrorMsg('.outputMessage2',`Broken Vimeo url(s): </br>${vimeoErrorUrl}</br> Reason: Uploaders can set the privacy setting of their Vimeo videos to "Embed only", therefore they can't be found anywhere else on the web.`); } else if (isVimeoVideoFound == true && youtubeUrlCounter !== youtubeResponseTotal) { outputEditor.setValue(''); showErrorMsg('.outputMessage1', `Error: ${youtubeUrlCounter-youtubeResponseTotal} of ${youtubeUrlCounter} Youtube links are broken. Please check.`); showErrorMsg('.outputMessage2',`Broken Youtube video ID(s): </br>${youtubeErrorUrl}</br>`); } else if (isVimeoVideoFound == false && youtubeUrlCounter !== youtubeResponseTotal) { outputEditor.setValue(''); showErrorMsg('.outputMessage1', `Error: ${youtubeUrlCounter-youtubeResponseTotal} of ${youtubeUrlCounter} Youtube links are broken and </br>${vimeoErrorUrlCounter} of ${vimeoUrlCounter} Vimeo links are broken or inaccessible through the API.`); showErrorMsg('.outputMessage2',`Broken Vimeo url(s): </br>${vimeoErrorUrl}</br> Broken Youtube video ID(s): </br>${youtubeErrorUrl}</br> Reason: Uploaders can set the privacy setting of their Vimeo videos to "Embed only", therefore they can't be found anywhere else on the web.`); } else { hideErrorMsg('.outputMessage1'); hideErrorMsg('.outputMessage2'); printOutput(); } } } function printOutput() { printTitle(); printIframe(); } //initiate error message container var node = outputEditor.renderer.emptyMessageNode; node = outputEditor.renderer.emptyMessageNode = document.createElement('div'); node.className = 'outputMessage1'; outputEditor.renderer.scroller.appendChild(node); var node = outputEditor.renderer.emptyMessageNode; node = outputEditor.renderer.emptyMessageNode = document.createElement('div'); node.className = 'outputMessage2'; outputEditor.renderer.scroller.appendChild(node); function showErrorMsg(outputClass, errMsg) { document.querySelector(outputClass).innerHTML = errMsg; } function hideErrorMsg(outputClass) { var node = outputEditor.renderer.emptyMessageNode; if (node) { document.querySelector(outputClass).innerHTML = ''; } } //Variable for storing just the video id not the entire youtube url //Youtube API only accept video ids not the full url var youtubeVideoIdArr = []; var youtubeVideoID = ''; //Vimeo accepts OEMBED so full url is accepted and no api key is needed var vimeoUrlArr = []; ////////////////////////////////////////////////////////// //////////////////Youtube request section///////////////// ////////////////////////////////////////////////////////// //This function loads the API using the api key function loadYoutubeClient() { gapi.client.setApiKey(apiKey); return gapi.client.load('https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest') .then(function() {}, function(err) { console.error('Error loading GAPI client for API', err); }); } //Youtube error checking var youtubeErrorUrlArr = []; var youtubeErrorUrl = ''; var youtubeResponseVideoId=[]; function findYoutubeUrlError() { getyoutubeResponseVideoIdArr(); //Compare Youtube Video Ids sent against the response form Youtube youtubeErrorUrlArr = arrDiff(youtubeVideoIdArr, youtubeResponseVideoId); youtubeErrorUrlArr.forEach(function(element) { youtubeErrorUrl = youtubeErrorUrl + `&bullet; ${element}</br>`; }) } function getyoutubeResponseVideoIdArr(){ for(let i=0;i<youtubeResponse.result.items.length;i++){ youtubeResponseVideoId.push(youtubeResponse.result.items[i].id); } } var youtubeResponse = []; // Sends request to Youtube function youtubeRequest() { return gapi.client.youtube.videos.list({ 'part': 'snippet,contentDetails', 'id': youtubeVideoID }) .then(function(response) { youtubeResponse = response; }, function(err) { console.error('Execute error', err); }); } //end function gapi.load('client'); //Compare elements between 2 arrays and returns the different elements function arrDiff(arr1, arr2) { var arrays = [arr1, arr2].sort((a, b) => a.length - b.length); var smallSet = new Set(arrays[0]); return arrays[1].filter(x => !smallSet.has(x)); } ////////////////////////////////////////////////////////// /////////////////End Youtube request section////////////// ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// ///////////////////Vimeo request section////////////////// ////////////////////////////////////////////////////////// var vimeoErrorUrlCounter = 0; var vimeoErrorUrl=''; //This function takes in a full Vimeo url function vimeoFetch(url) { return fetch('https://vimeo.com/api/oembed.json?url=' + url) // return this promise .then((resp) => resp.json()) .catch((err) => { isVimeoVideoFound = false; vimeoErrorUrlCounter++; //For error checking: showing which urls are error vimeoErrorUrl = vimeoErrorUrl + `&bullet; ${url}</br>`; }); } var vimeoResponse = []; //Send request to Vimeo async function vimeoRequest() { //reset counter vimeoErrorUrlCounter = 0; var counter = 0; for (var o = 0; o < vimeoUrlArr.length; o++) { if (vimeoUrlArr[o]) { await vimeoFetch(vimeoUrlArr[o]) .then(function(data) { vimeoResponse[counter] = data; counter++; }) } } //end for loop } //end function ////////////////////////////////////////////////////////// ///////////////////End Vimeo request section////////////// ////////////////////////////////////////////////////////// //counter for youtube urls var youtubeUrlCounter = 0; var vimeoUrlCounter = 0; // This function gets urls from the input editor function getUrls() { //Reset arrays vimeoUrlArr = []; youtubeVideoIdArr = []; youtubeVideoID = ''; //Reset Youtube error checking youtubeErrorUrlArr = []; youtubeErrorUrl = ''; youtubeResponseVideoId=[]; youtubeResponseTotal=0; youtubeUrlCounter = 0; vimeoUrlCounter = 0; //Reset video checking isVimeoVideoFound = true; vimeoErrorUrl=''; //Get all lines from the input editor var urls = inputEditor.session.doc.getAllLines(); var urlCounter = 0; for (var i = 0; i < urls.length; i++) { //parse each line, if returned 'undefined': not a correct url var parsedUrl = urlParser.parse(urls[i]); if (parsedUrl) { if (parsedUrl.provider == 'youtube') { //for requesting to Youtube Api youtubeVideoID = youtubeVideoID + ',' + parsedUrl.id; //For printing youtube iframe youtubeVideoIdArr[urlCounter] = parsedUrl.id; urlCounter++; youtubeUrlCounter++; } //if vimeo url, add the full url to vimeoUrlArr array if (parsedUrl.provider == 'vimeo') { //Use urlParser.prase(url[i]) and then create link using below var createdUrl = urlParser.create({ videoInfo: { provider: parsedUrl.provider, id: parsedUrl.id, mediaType: parsedUrl.mediaType, } }) vimeoUrlArr[urlCounter] = createdUrl; vimeoUrlCounter++; urlCounter++; } } //end check returned value } //end for loop } //end function ////////////////////////////////////////////////////////// ////////////////////Print section///////////////////////// ////////////////////////////////////////////////////////// //This function prints out titles of the videos in li function printTitle() { //Clear output editor outputEditor.setValue(''); var videoNumber = 0; //Add <ol> outputEditor.session.insert(0, '<ol>'); addEmptyLine(); //Get the biggest array var arrSize = getBiggestArr(vimeoUrlArr, youtubeVideoIdArr); var vimeo = 0; var youtube = 0; for (var r = 0; r < arrSize; r++) { //Print vimeo titles if (vimeoUrlArr[r]) { var title = vimeoResponse[vimeo].title; var duration = convertVimeoDuration(vimeoResponse[vimeo].duration); var li = ` <li><strong>Video #${++videoNumber} ${title} (Duration: ${duration})</strong></li>`; outputEditor.session.insert(0, li); addEmptyLine(); vimeo++; } //Print youtube titles if (youtubeVideoIdArr[r]) { var title = youtubeResponse.result.items[youtube].snippet.title; var duration = convertYoutubeDuration(youtubeResponse.result.items[youtube].contentDetails.duration); var li = ` <li><strong>Video #${++videoNumber} ${title} (Duration: ${duration})</strong></li>`; outputEditor.session.insert(0, li); addEmptyLine(); youtube++; } } //Add </ol> outputEditor.session.insert(0, '</ol>'); addEmptyLine(); } //end function ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// function printIframe() { outputEditor.session.insert(0, '<p>'); //Get the biggest array var arrSize = getBiggestArr(vimeoUrlArr, youtubeVideoIdArr); var vimeo = 0; var youtube = 0; for (var r = 0; r < arrSize; r++) { addEmptyLine(); //Print vimeo titles if (vimeoUrlArr[r]) { var videoId = vimeoResponse[vimeo].video_id; var iframe = ` <iframe width='120' height='120' src='https://player.vimeo.com/video/${videoId}?color=ffffff&amp;title=0&amp;byline=0&amp;portrait=0' frameborder='0' webkitallowfullscreen='' mozallowfullscreen='' allowfullscreen=''></iframe>`; outputEditor.session.insert(r, iframe); addEmptyLine(); vimeo++; } //Print youtube titles if (youtubeVideoIdArr[r]) { var iframe = ` <iframe width='120' height='120' src='https://www.youtube.com/embed/${youtubeVideoIdArr[r]}?rel=0;showinfo=0' frameborder='0' allowfullscreen=''></iframe>`; outputEditor.session.insert(0, iframe); addEmptyLine(); youtube++; } } outputEditor.session.insert(0, '</p>'); } //Find the biggest array between vimeoUrlArr and youtubeVideoIdArr function getBiggestArr(arr1, arr2) { var arrSize = 0; if (arr1.length > arr2.length) { arrSize = arr1.length; } else if (arr1.length < arr2.length) { arrSize = arr2.length; } else { arrSize = arr1.length; } return arrSize; } ////////////////////////////////////////////////////////// /////////////////////End Print section//////////////////// ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// ///////////////////Counter section//////////////////////// ////////////////////////////////////////////////////////// //Calls updateUrlCounter function when inputEditor changes inputEditor.on('change', updateUrlCounter); var totalUrl = 0; var youtubeCounter = 0; var vimeoCounter = 0; // Get elements var youtubeCounterElement = document.querySelector('#youtubeCounter'); var vimeoCounterElement = document.querySelector('#vimeoCounter'); // Assigns default value to the counter youtubeCounterElement.innerHTML = ` ${youtubeCounter}`; vimeoCounterElement.innerHTML = ` ${vimeoCounter}`; var youtubeFlashTime = 0; var vimeoFlashTime = 0; //Variables for checking var isValidUrl = false; var isAtleastOneMatch = false; // This function outputs values to counter div element function updateUrlCounter() { isValidUrl = false; // Reset values youtubeCounter = 0; vimeoCounter = 0; // Get all lines from the input editor var urls = inputEditor.session.doc.getAllLines(); if (inputEditor.session.getValue().length < 1) { isAtleastOneMatch = false; } for (var i = 0; i < urls.length; i++) { // parse each line, if returned 'undefined': not a correct url var parsedUrl = urlParser.parse(urls[i]); if (parsedUrl) { if (parsedUrl.provider === 'youtube') { youtubeCounter++; isValidUrl = true; isAtleastOneMatch = true; } else if (parsedUrl.provider === 'vimeo') { vimeoCounter++; isValidUrl = true; isAtleastOneMatch = true; } } else if (isAtleastOneMatch == false) { isValidUrl = false; } // end check returned value } // end for loop vimeoCounterElement.innerHTML = ` ${vimeoCounter}`; youtubeCounterElement.innerHTML = ` ${youtubeCounter}`; // Add flash effect to counters when value changes if (youtubeCounter > youtubeFlashTime || youtubeCounter < youtubeFlashTime) { youtubeFlashTime = youtubeCounter; youtubeCounterElement.classList.add('youtubeCounterFlash'); setTimeout(function() { youtubeCounterElement.classList.remove('youtubeCounterFlash'); }, 500); } if (vimeoCounter > vimeoFlashTime || vimeoCounter < vimeoFlashTime) { vimeoFlashTime = vimeoCounter; vimeoCounterElement.classList.add('vimeoCounterFlash'); setTimeout(function() { vimeoCounterElement.classList.remove('vimeoCounterFlash'); }, 500); } } // End function ////////////////////////////////////////////////////////// /////////////////End Counter section////////////////////// ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// ///////////////////Input & Output setup/////////////////// ////////////////////////////////////////////////////////// function setupInputEditor() { window.inputEditor = ace.edit('input'); inputEditor.setTheme('ace/theme/tomorrow_night_eighties'); inputEditor.getSession().setMode('ace/mode/html'); inputEditor.on('input', updateInput); setTimeout(updateInput, 100); inputEditor.focus(); inputEditor.setOptions({ fontSize: '10.5pt', showLineNumbers: true, showGutter: true, vScrollBarAlwaysVisible: false, wrap: true }); inputEditor.setShowPrintMargin(false); inputEditor.setBehavioursEnabled(false); inputEditor.getSession().setUseWorker(false); } function updateInput() { var shouldShow = !inputEditor.session.getValue().length; var node = inputEditor.renderer.emptyMessageNode; if (!shouldShow && node) { inputEditor.renderer.scroller.removeChild(inputEditor.renderer.emptyMessageNode); inputEditor.renderer.emptyMessageNode = null; } else if (shouldShow && !node) { node = inputEditor.renderer.emptyMessageNode = document.createElement('div'); node.textContent = "Paste the whole HTML of an item and make sure there's only one link on each line" node.className = 'emptyMessage' inputEditor.renderer.scroller.appendChild(node); } } function setupOutputEditor() { window.outputEditor = ace.edit('output'); outputEditor.setTheme('ace/theme/tomorrow_night_eighties'); outputEditor.getSession().setMode('ace/mode/html'); outputEditor.setOptions({ fontSize: '10.5pt', showLineNumbers: true, showGutter: true, vScrollBarAlwaysVisible: false, wrap: true }); outputEditor.setShowPrintMargin(false); outputEditor.setBehavioursEnabled(false); } ////////////////////////////////////////////////////////// /////////////////End Input & Output setup///////////////// ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////// /////////////////////////Copy function//////////////////// ////////////////////////////////////////////////////////// function copyOutput() { if (outputEditor.session.getValue().length > 0) { var copyTextarea = document.querySelector('#copiedText'); copyTextarea.value = outputEditor.getValue(); copyTextarea.select(); document.execCommand('copy'); // Reset textarea copyTextarea.value = ''; //Add flashStart class to overlay div to create a flash effect when copyOutput is called document.querySelector('.copyAlert').classList.add('flash'); setTimeout(function() { document.querySelector('.copyAlert').classList.remove('flash'); }, 500); } } //Create an overlay over outputEditor copyAlertOverlay(); function copyAlertOverlay() { var node = document.createElement('div'); node.className = 'copyAlert'; document.querySelector('#output .ace_scroller .ace_content').appendChild(node); } ////////////////////////////////////////////////////////// ///////////////////////End Copy function////////////////// ////////////////////////////////////////////////////////// //This function adds an empty line to the output editor function addEmptyLine() { outputEditor.session.insert({ row: outputEditor.session.getLength(), column: 0 }, '\n'); } //This function converts seconds to HH:MM::SS format function convertVimeoDuration(Seconds) { var hours = Math.floor(Seconds / 3600); var minutes = Math.floor((Seconds - (hours * 3600)) / 60); var seconds = Seconds - (hours * 3600) - (minutes * 60); // round seconds seconds = Math.round(seconds * 100) / 100; var result = ''; if (hours > 0) { result += (hours < 10 ? +hours : hours); result += ':'; } if (minutes > 0) { result += (minutes < 10 ? '0' + minutes : minutes); } else if (minutes < 1) { result += '0'; } result += ':'; result += (seconds < 10 ? '0' + seconds : seconds); return result; } //This function converts ISO 8601 duration to HH:MM:SS format function convertYoutubeDuration(t) { //dividing period from time var x = t.split('T'), duration = '', time = {}, period = {}, //just shortcuts s = 'string', v = 'variables', l = 'letters', // store the information about ISO8601 duration format and the divided strings d = { period: { string: x[0].substring(1, x[0].length), len: 4, // years, months, weeks, days letters: ['Y', 'M', 'W', 'D'], variables: {} }, time: { string: x[1], len: 3, // hours, minutes, seconds letters: ['H', 'M', 'S'], variables: {} } }; //in case the duration is a multiple of one day if (!d.time.string) { d.time.string = ''; } for (var i in d) { var len = d[i].len; for (var j = 0; j < len; j++) { d[i][s] = d[i][s].split(d[i][l][j]); if (d[i][s].length > 1) { d[i][v][d[i][l][j]] = parseInt(d[i][s][0], 10); d[i][s] = d[i][s][1]; } else { d[i][v][d[i][l][j]] = 0; d[i][s] = d[i][s][0]; } } } period = d.period.variables; time = d.time.variables; time.H += 24 * period.D + 24 * 7 * period.W + 24 * 7 * 4 * period.M + 24 * 7 * 4 * 12 * period.Y; if (time.H) { duration = time.H + ':'; if (time.M < 10) { time.M = '0' + time.M; } } if (time.S < 10) { time.S = '0' + time.S; } duration += time.M + ':' + time.S; return duration; } },{"js-video-url-parser":2}],2:[function(require,module,exports){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.urlParser = factory()); }(this, (function () { 'use strict'; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } var getQueryParams = function getQueryParams(qs) { if (typeof qs !== 'string') { return {}; } qs = qs.split('+').join(' '); var params = {}; var match = qs.match(/(?:[?](?:[^=]+)=(?:[^&#]*)(?:[&](?:[^=]+)=(?:[^&#]*))*(?:[#].*)?)|(?:[#].*)/); var split; if (match === null) { return {}; } split = match[0].substr(1).split(/[&#=]/); for (var i = 0; i < split.length; i += 2) { params[decodeURIComponent(split[i])] = decodeURIComponent(split[i + 1] || ''); } return params; }; var combineParams = function combineParams(op) { if (_typeof(op) !== 'object') { return ''; } op.params = op.params || {}; var combined = '', i = 0, keys = Object.keys(op.params); if (keys.length === 0) { return ''; } //always have parameters in the same order keys.sort(); if (!op.hasParams) { combined += '?' + keys[0] + '=' + op.params[keys[0]]; i += 1; } for (; i < keys.length; i += 1) { combined += '&' + keys[i] + '=' + op.params[keys[i]]; } return combined; }; //parses strings like 1h30m20s to seconds function getLetterTime(timeString) { var totalSeconds = 0; var timeValues = { 's': 1, 'm': 1 * 60, 'h': 1 * 60 * 60, 'd': 1 * 60 * 60 * 24, 'w': 1 * 60 * 60 * 24 * 7 }; var timePairs; //expand to "1 h 30 m 20 s" and split timeString = timeString.replace(/([smhdw])/g, ' $1 ').trim(); timePairs = timeString.split(' '); for (var i = 0; i < timePairs.length; i += 2) { totalSeconds += parseInt(timePairs[i], 10) * timeValues[timePairs[i + 1] || 's']; } return totalSeconds; } //parses strings like 1:30:20 to seconds function getColonTime(timeString) { var totalSeconds = 0; var timeValues = [1, 1 * 60, 1 * 60 * 60, 1 * 60 * 60 * 24, 1 * 60 * 60 * 24 * 7]; var timePairs = timeString.split(':'); for (var i = 0; i < timePairs.length; i++) { totalSeconds += parseInt(timePairs[i], 10) * timeValues[timePairs.length - i - 1]; } return totalSeconds; } var getTime = function getTime(timeString) { if (typeof timeString === 'undefined') { return 0; } if (timeString.match(/^(\d+[smhdw]?)+$/)) { return getLetterTime(timeString); } if (timeString.match(/^(\d+:?)+$/)) { return getColonTime(timeString); } return 0; }; var util = { getQueryParams: getQueryParams, combineParams: combineParams, getTime: getTime }; var getQueryParams$1 = util.getQueryParams; function UrlParser() { var _arr = ['parseProvider', 'parse', 'bind', 'create']; for (var _i = 0; _i < _arr.length; _i++) { var key = _arr[_i]; this[key] = this[key].bind(this); } this.plugins = {}; } var urlParser = UrlParser; UrlParser.prototype.parseProvider = function (url) { var match = url.match(/(?:(?:https?:)?\/\/)?(?:[^.]+\.)?(\w+)\./i); return match ? match[1] : undefined; }; UrlParser.prototype.parse = function (url) { if (typeof url === 'undefined') { return undefined; } var provider = this.parseProvider(url); var result; var plugin = this.plugins[provider]; if (!provider || !plugin || !plugin.parse) { return undefined; } result = plugin.parse.call(plugin, url, getQueryParams$1(url)); if (result) { result = removeEmptyParameters(result); result.provider = plugin.provider; } return result; }; UrlParser.prototype.bind = function (plugin) { this.plugins[plugin.provider] = plugin; if (plugin.alternatives) { for (var i = 0; i < plugin.alternatives.length; i += 1) { this.plugins[plugin.alternatives[i]] = plugin; } } }; UrlParser.prototype.create = function (op) { var vi = op.videoInfo; var params = op.params; var plugin = this.plugins[vi.provider]; params = params === 'internal' ? vi.params : params || {}; if (plugin) { op.format = op.format || plugin.defaultFormat; if (plugin.formats.hasOwnProperty(op.format)) { return plugin.formats[op.format].apply(plugin, [vi, Object.assign({}, params)]); } } return undefined; }; function removeEmptyParameters(result) { if (result.params && Object.keys(result.params).length === 0) { delete result.params; } return result; } var parser = new urlParser(); var base = parser; var combineParams$1 = util.combineParams; function CanalPlus() { this.provider = 'canalplus'; this.defaultFormat = 'embed'; this.formats = { embed: this.createEmbedUrl }; this.mediaTypes = { VIDEO: 'video' }; } CanalPlus.prototype.parseParameters = function (params) { delete params.vid; return params; }; CanalPlus.prototype.parse = function (url, params) { var _this = this; var result = { mediaType: this.mediaTypes.VIDEO, id: params.vid }; result.params = _this.parseParameters(params); if (!result.id) { return undefined; } return result; }; CanalPlus.prototype.createEmbedUrl = function (vi, params) { var url = 'http://player.canalplus.fr/embed/'; params.vid = vi.id; url += combineParams$1({ params: params }); return url; }; base.bind(new CanalPlus()); var combineParams$2 = util.combineParams; function Coub() { this.provider = 'coub'; this.defaultFormat = 'long'; this.formats = { long: this.createLongUrl, embed: this.createEmbedUrl }; this.mediaTypes = { VIDEO: 'video' }; } Coub.prototype.parseUrl = function (url) { var match = url.match(/(?:embed|view)\/([a-zA-Z\d]+)/i); return match ? match[1] : undefined; }; Coub.prototype.parse = function (url, params) { var result = { mediaType: this.mediaTypes.VIDEO, params: params, id: this.parseUrl(url) }; if (!result.id) { return undefined; } return result; }; Coub.prototype.createUrl = function (baseUrl, vi, params) { var url = baseUrl + vi.id; url += combineParams$2({ params: params }); return url; }; Coub.prototype.createLongUrl = function (vi, params) { return this.createUrl('https://coub.com/view/', vi, params); }; Coub.prototype.createEmbedUrl = function (vi, params) { return this.createUrl('//coub.com/embed/', vi, params); }; base.bind(new Coub()); var combineParams$3 = util.combineParams; var getTime$1 = util.getTime; function Dailymotion() { this.provider = 'dailymotion'; this.alternatives = ['dai']; this.defaultFormat = 'long'; this.formats = { short: this.createShortUrl, long: this.createLongUrl, embed: this.createEmbedUrl, image: this.createImageUrl }; this.mediaTypes = { VIDEO: 'video' }; } Dailymotion.prototype.parseParameters = function (params) { return this.parseTime(params); }; Dailymotion.prototype.parseTime = function (params) { if (params.start) { params.start = getTime$1(params.start); } return params; }; Dailymotion.prototype.parseUrl = function (url) { var match = url.match(/(?:\/video|ly)\/([A-Za-z0-9]+)/i); return match ? match[1] : undefined; }; Dailymotion.prototype.parse = function (url, params) { var _this = this; var result = { mediaType: this.mediaTypes.VIDEO, params: _this.parseParameters(params), id: _this.parseUrl(url) }; return result.id ? result : undefined; }; Dailymotion.prototype.createUrl = function (base$$2, vi, params) { return base$$2 + vi.id + combineParams$3({ params: params }); }; Dailymotion.prototype.createShortUrl = function (vi, params) { return this.createUrl('https://dai.ly/', vi, params); }; Dailymotion.prototype.createLongUrl = function (vi, params) { return this.createUrl('https://dailymotion.com/video/', vi, params); }; Dailymotion.prototype.createEmbedUrl = function (vi, params) { return this.createUrl('https://www.dailymotion.com/embed/video/', vi, params); }; Dailymotion.prototype.createImageUrl = function (vi, params) { delete params.start; return this.createUrl('https://www.dailymotion.com/thumbnail/video/', vi, params); }; base.bind(new Dailymotion()); var combineParams$4 = util.combineParams; var getTime$2 = util.getTime; function Twitch() { this.provider = 'twitch'; this.defaultFormat = 'long'; this.formats = { long: this.createLongUrl, embed: this.createEmbedUrl }; this.mediaTypes = { VIDEO: 'video', STREAM: 'stream', CLIP: 'clip' }; } Twitch.prototype.seperateId = function (id) { return { pre: id[0], id: id.substr(1) }; }; Twitch.prototype.parseChannel = function (result, params) { var channel = params.channel || params.utm_content || result.channel; delete params.utm_content; delete params.channel; return channel; }; Twitch.prototype.parseUrl = function (url, result, params) { var match; match = url.match(/(clips\.)?twitch\.tv\/(?:(?:videos\/(\d+))|(\w+)(?:\/clip\/(\w+))?)/i); if (match && match[2]) { //video result.id = 'v' + match[2]; } else if (params.video) { //video embed result.id = params.video; delete params.video; } else if (params.clip) { //clips embed result.id = params.clip; result.isClip = true; delete params.clip; } else if (match && match[1] && match[3]) { //clips.twitch.tv/id result.id = match[3]; result.isClip = true; } else if (match && match[3] && match[4]) { //twitch.tv/channel/clip/id result.channel = match[3]; result.id = match[4]; result.isClip = true; } else if (match && match[3]) { result.channel = match[3]; } return result; }; Twitch.prototype.parseMediaType = function (result) { var mediaType; if (result.id) { if (result.isClip) { mediaType = this.mediaTypes.CLIP; delete result.isClip; } else { mediaType = this.mediaTypes.VIDEO; } } else if (result.channel) { mediaType = this.mediaTypes.STREAM; } return mediaType; }; Twitch.prototype.parseParameters = function (params) { if (params.t) { params.start = getTime$2(params.t); delete params.t; } return params; }; Twitch.prototype.parse = function (url, params) { var _this = this; var result = {}; result = _this.parseUrl(url, result, params); result.channel = _this.parseChannel(result, params); result.mediaType = _this.parseMediaType(result); result.params = _this.parseParameters(params); return result.channel || result.id ? result : undefined; }; Twitch.prototype.createLongUrl = function (vi, params) { var url = ''; if (vi.mediaType === this.mediaTypes.STREAM) { url = 'https://twitch.tv/' + vi.channel; } if (vi.mediaType === this.mediaTypes.VIDEO) { var sep = this.seperateId(vi.id); url = 'https://twitch.tv/videos/' + sep.id; if (params.start) { params.t = params.start + 's'; delete params.start; } } if (vi.mediaType === this.mediaTypes.CLIP) { if (vi.channel) { url = 'https://www.twitch.tv/' + vi.channel + '/clip/' + vi.id; } else { url = 'https://clips.twitch.tv/' + vi.id; } } url += combineParams$4({ params: params }); return url; }; Twitch.prototype.createEmbedUrl = function (vi, params) { var url = 'https://player.twitch.tv/'; if (vi.mediaType === this.mediaTypes.STREAM) { params.channel = vi.channel; } if (vi.mediaType === this.mediaTypes.VIDEO) { params.video = vi.id; if (params.start) { params.t = params.start + 's'; delete params.start; } } if (vi.mediaType === this.mediaTypes.CLIP) { url = 'https://clips.twitch.tv/embed'; params.clip = vi.id; } url += combineParams$4({ params: params }); return url; }; base.bind(new Twitch()); var combineParams$5 = util.combineParams; var getTime$3 = util.getTime; function Vimeo() { this.provider = 'vimeo'; this.alternatives = ['vimeopro', 'vimeocdn']; this.defaultFormat = 'long'; this.formats = { long: this.createLongUrl, embed: this.createEmbedUrl, image: this.createImageUrl }; this.mediaTypes = { VIDEO: 'video' }; } Vimeo.prototype.parseUrl = function (url, result) { var match = url.match(/(vimeo(?:cdn|pro)?)\.com\/(?:(?:channels\/[\w]+|(?:(?:album\/\d+|groups\/[\w]+|staff\/frame)\/)?videos?)\/)?(\d+)(?:_(\d+)(?:x(\d+))?)?(\.\w+)?/i); if (!match) { return result; } result.id = match[2]; if (match[1] === 'vimeocdn') { if (match[3]) { result.imageWidth = parseInt(match[3]); if (match[4]) { //height can only be set when width is also set result.imageHeight = parseInt(match[4]); } } result.imageExtension = match[5]; } return result; }; Vimeo.prototype.parseParameters = function (params) { return this.parseTime(params); }; Vimeo.prototype.parseTime = function (params) { if (params.t) { params.start = getTime$3(params.t); delete params.t; } return params; }; Vimeo.prototype.parse = function (url, params) { var result = { mediaType: this.mediaTypes.VIDEO, params: this.parseParameters(params) }; result = this.parseUrl(url, result); return result.id ? result : undefined; }; Vimeo.prototype.createUrl = function (baseUrl, vi, params) { var url = baseUrl + vi.id; var startTime = params.start; delete params.start; url += combineParams$5({ params: params }); if (startTime) { url += '#t=' + startTime; } return url; }; Vimeo.prototype.createLongUrl = function (vi, params) { return this.createUrl('https://vimeo.com/', vi, params); }; Vimeo.prototype.createEmbedUrl = function (vi, params) { return this.createUrl('//player.vimeo.com/video/', vi, params); }; Vimeo.prototype.createImageUrl = function (vi, params) { var url = 'https://i.vimeocdn.com/video/' + vi.id; if (vi.imageWidth && vi.imageHeight) { url += '_' + vi.imageWidth + 'x' + vi.imageHeight; } else if (vi.imageWidth) { url += '_' + vi.imageWidth; } if (vi.imageExtension === undefined) { vi.imageExtension = '.webp'; } url += vi.imageExtension; delete vi.imageExtension; url += combineParams$5({ params: params }); return url; }; base.bind(new Vimeo()); var combineParams$6 = util.combineParams; var getTime$4 = util.getTime; function Wistia() { this.provider = 'wistia'; this.alternatives = []; this.defaultFormat = 'long'; this.formats = { long: this.createLongUrl, embed: this.createEmbedUrl, embedjsonp: this.createEmbedJsonpUrl }; this.mediaTypes = { VIDEO: 'video', EMBEDVIDEO: 'embedvideo' }; } Wistia.prototype.parseUrl = function (url) { var match = url.match(/(?:(?:medias|iframe)\/|wvideo=)([\w-]+)/); return match ? match[1] : undefined; }; Wistia.prototype.parseChannel = function (url) { var match = url.match(/(?:(?:https?:)?\/\/)?([^.]*)\.wistia\./); var channel = match ? match[1] : undefined; if (channel === 'fast' || channel === 'content') { return undefined; } return channel; }; Wistia.prototype.parseParameters = function (params, result) { if (params.wtime) { params.start = getTime$4(params.wtime); delete params.wtime; } if (params.wvideo === result.id) { delete params.wvideo; } return params; }; Wistia.prototype.parseMediaType = function (result) { if (result.id && result.channel) { return this.mediaTypes.VIDEO; } else if (result.id) { delete result.channel; return this.mediaTypes.EMBEDVIDEO; } else { return undefined; } }; Wistia.prototype.parse = function (url, params) { var result = { id: this.parseUrl(url), channel: this.parseChannel(url) }; result.params = this.parseParameters(params, result); result.mediaType = this.parseMediaType(result); if (!result.id) { return undefined; } return result; }; Wistia.prototype.createUrl = function (vi, params, url) { if (params.start) { params.wtime = params.start; delete params.start; } url += combineParams$6({ params: params }); return url; }; Wistia.prototype.createLongUrl = function (vi, params) { if (vi.mediaType !== this.mediaTypes.VIDEO) { return ''; } var url = 'https://' + vi.channel + '.wistia.com/medias/' + vi.id; return this.createUrl(vi, params, url); }; Wistia.prototype.createEmbedUrl = function (vi, params) { var url = 'https://fast.wistia.com/embed/iframe/' + vi.id; return this.createUrl(vi, params, url); }; Wistia.prototype.createEmbedJsonpUrl = function (vi) { return 'https://fast.wistia.com/embed/medias/' + vi.id + '.jsonp'; }; base.bind(new Wistia()); var combineParams$7 = util.combineParams; function Youku() { this.provider = 'youku'; this.defaultFormat = 'long'; this.formats = { embed: this.createEmbedUrl, long: this.createLongUrl, flash: this.createFlashUrl, static: this.createStaticUrl }; this.mediaTypes = { VIDEO: 'video' }; } Youku.prototype.parseUrl = function (url) { var match = url.match(/(?:(?:embed|sid)\/|v_show\/id_|VideoIDS=)([a-zA-Z0-9]+)/); return match ? match[1] : undefined; }; Youku.prototype.parseParameters = function (params) { if (params.VideoIDS) { delete params.VideoIDS; } return params; }; Youku.prototype.parse = function (url, params) { var _this = this; var result = { mediaType: this.mediaTypes.VIDEO, id: _this.parseUrl(url), params: _this.parseParameters(params) }; if (!result.id) { return undefined; } return result; }; Youku.prototype.createUrl = function (baseUrl, vi, params) { var url = baseUrl + vi.id; url += combineParams$7({ params: params }); return url; }; Youku.prototype.createEmbedUrl = function (vi, params) { return this.createUrl('http://player.youku.com/embed/', vi, params); }; Youku.prototype.createLongUrl = function (vi, params) { return this.createUrl('http://v.youku.com/v_show/id_', vi, params); }; Youku.prototype.createStaticUrl = function (vi, params) { return this.createUrl('http://static.youku.com/v1.0.0638/v/swf/loader.swf?VideoIDS=', vi, params); }; Youku.prototype.createFlashUrl = function (vi, params) { var url = 'http://player.youku.com/player.php/sid/' + vi.id + '/v.swf'; url += combineParams$7({ params: params }); return url; }; base.bind(new Youku()); var combineParams$8 = util.combineParams; var getTime$5 = util.getTime; function YouTube() { this.provider = 'youtube'; this.alternatives = ['youtu', 'ytimg']; this.defaultFormat = 'long'; this.formats = { short: this.createShortUrl, long: this.createLongUrl, embed: this.createEmbedUrl, shortImage: this.createShortImageUrl, longImage: this.createLongImageUrl }; this.imageQualities = { '0': '0', '1': '1', '2': '2', '3': '3', DEFAULT: 'default', HQDEFAULT: 'hqdefault', SDDEFAULT: 'sddefault', MQDEFAULT: 'mqdefault', MAXRESDEFAULT: 'maxresdefault' }; this.defaultImageQuality = this.imageQualities.HQDEFAULT; this.mediaTypes = { VIDEO: 'video', PLAYLIST: 'playlist', SHARE: 'share', CHANNEL: 'channel' }; } YouTube.prototype.parseVideoUrl = function (url) { var match = url.match(/(?:(?:v|vi|be|videos|embed)\/(?!videoseries)|(?:v|ci)=)([\w-]{11})/i); return match ? match[1] : undefined; }; YouTube.prototype.parseChannelUrl = function (url) { // Match an opaque channel ID var match = url.match(/\/channel\/([\w-]+)/); if (match) { return { id: match[1], mediaType: this.mediaTypes.CHANNEL }; } // Match a vanity channel name or a user name. User urls are deprecated and // currently redirect to the channel of that same name. match = url.match(/\/(?:c|user)\/([\w-]+)/); if (match) { return { name: match[1], mediaType: this.mediaTypes.CHANNEL }; } }; YouTube.prototype.parseParameters = function (params, result) { if (params.start || params.t) { params.start = getTime$5(params.start || params.t); delete params.t; } if (params.v === result.id) { delete params.v; } if (params.list === result.id) { delete params.list; } return params; }; YouTube.prototype.parseMediaType = function (result) { if (result.params.list) { result.list = result.params.list; delete result.params.list; } if (result.id && !result.params.ci) { result.mediaType = this.mediaTypes.VIDEO; } else if (result.list) { delete result.id; result.mediaType = this.mediaTypes.PLAYLIST; } else if (result.params.ci) { delete result.params.ci; result.mediaType = this.mediaTypes.SHARE; } else { return undefined; } return result; }; YouTube.prototype.parse = function (url, params) { var channelResult = this.parseChannelUrl(url); if (channelResult) { return channelResult; } else { var result = { params: params, id: this.parseVideoUrl(url) }; result.params = this.parseParameters(params, result); result = this.parseMediaType(result); return result; } }; YouTube.prototype.createShortUrl = function (vi, params) { var url = 'https://youtu.be/' + vi.id; if (params.start) { url += '#t=' + params.start; } return url; }; YouTube.prototype.createLongUrl = function (vi, params) { var url = ''; var startTime = params.start; delete params.start; if (vi.mediaType === this.mediaTypes.CHANNEL) { if (vi.id) { url += 'https://www.youtube.com/channel/' + vi.id; } else if (vi.name) { url += 'https://www.youtube.com/c/' + vi.name; } } if (vi.mediaType === this.mediaTypes.PLAYLIST) { params.feature = 'share'; url += 'https://www.youtube.com/playlist'; } if (vi.mediaType === this.mediaTypes.VIDEO) { params.v = vi.id; url += 'https://www.youtube.com/watch'; } if (vi.mediaType === this.mediaTypes.SHARE) { params.ci = vi.id; url += 'https://www.youtube.com/shared'; } if (vi.list) { params.list = vi.list; } url += combineParams$8({ params: params }); if (vi.mediaType !== this.mediaTypes.PLAYLIST && startTime) { url += '#t=' + startTime; } return url; }; YouTube.prototype.createEmbedUrl = function (vi, params) { var url = 'https://www.youtube.com/embed'; if (vi.mediaType === this.mediaTypes.PLAYLIST) { params.listType = 'playlist'; } else { url += '/' + vi.id; //loop hack if (params.loop === '1') { params.playlist = vi.id; } } if (vi.list) { params.list = vi.list; } url += combineParams$8({ params: params }); return url; }; YouTube.prototype.createImageUrl = function (baseUrl, vi, params) { var url = baseUrl + vi.id + '/'; var quality = params.imageQuality || this.defaultImageQuality; return url + quality + '.jpg'; }; YouTube.prototype.createShortImageUrl = function (vi, params) { return this.createImageUrl('https://i.ytimg.com/vi/', vi, params); }; YouTube.prototype.createLongImageUrl = function (vi, params) { return this.createImageUrl('https://img.youtube.com/vi/', vi, params); }; base.bind(new YouTube()); var combineParams$9 = util.combineParams; var getTime$6 = util.getTime; function SoundCloud() { this.provider = 'soundcloud'; this.defaultFormat = 'long'; this.formats = { long: this.createLongUrl, embed: this.createEmbedUrl }; this.mediaTypes = { TRACK: 'track', PLAYLIST: 'playlist', APITRACK: 'apitrack', APIPLAYLIST: 'apiplaylist' }; } SoundCloud.prototype.parseUrl = function (url, result) { var match = url.match(/soundcloud\.com\/(?:([\w-]+)\/(sets\/)?)([\w-]+)/i); if (!match) { return result; } result.channel = match[1]; if (match[1] === 'playlists' || match[2]) { //playlist result.list = match[3]; } else { //track result.id = match[3]; } return result; }; SoundCloud.prototype.parseParameters = function (params) { if (params.t) { params.start = getTime$6(params.t); delete params.t; } return params; }; SoundCloud.prototype.parseMediaType = function (result) { if (result.id) { if (result.channel === 'tracks') { delete result.channel; delete result.params.url; result.mediaType = this.mediaTypes.APITRACK; } else { result.mediaType = this.mediaTypes.TRACK; } } if (result.list) { if (result.channel === 'playlists') { delete result.channel; delete result.params.url; result.mediaType = this.mediaTypes.APIPLAYLIST; } else { result.mediaType = this.mediaTypes.PLAYLIST; } } return result; }; SoundCloud.prototype.parse = function (url, params) { var result = {}; result = this.parseUrl(url, result); result.params = this.parseParameters(params); result = this.parseMediaType(result); if (!result.id && !result.list) { return undefined; } return result; }; SoundCloud.prototype.createLongUrl = function (vi, params) { var url = ''; var startTime = params.start; delete params.start; if (vi.mediaType === this.mediaTypes.TRACK) { url = 'https://soundcloud.com/' + vi.channel + '/' + vi.id; } if (vi.mediaType === this.mediaTypes.PLAYLIST) { url = 'https://soundcloud.com/' + vi.channel + '/sets/' + vi.list; } if (vi.mediaType === this.mediaTypes.APITRACK) { url = 'https://api.soundcloud.com/tracks/' + vi.id; } if (vi.mediaType === this.mediaTypes.APIPLAYLIST) { url = 'https://api.soundcloud.com/playlists/' + vi.list; } url += combineParams$9({ params: params }); if (startTime) { url += '#t=' + startTime; } return url; }; SoundCloud.prototype.createEmbedUrl = function (vi, params) { var url = 'https://w.soundcloud.com/player/'; delete params.start; if (vi.mediaType === this.mediaTypes.APITRACK) { params.url = 'https%3A//api.soundcloud.com/tracks/' + vi.id; } if (vi.mediaType === this.mediaTypes.APIPLAYLIST) { params.url = 'https%3A//api.soundcloud.com/playlists/' + vi.list; } url += combineParams$9({ params: params }); return url; }; base.bind(new SoundCloud()); var lib = base; return lib; }))); },{}]},{},[1]);
8d0425a27fface1ef041e30aaa53f11a75aab5ba
[ "JavaScript", "Markdown" ]
3
JavaScript
chimeng62/CORTEX-Video-Template-Generator-Web-Tool
865a11d5d3b55967978d7309b50017f5b88db892
46dc797830107930fce9a91b120f0caaa344d18d
refs/heads/master
<repo_name>hbougdal/cloud-foundation-toolkit<file_sep>/dm/templates/sap_hana/README.md # SAP HANA This template creates an SAP HANA deployment. It supports two types of deployments: - A **standalone** SAP HANA instance ![GitHub Logo](/dm/templates/sap_hana/images/sap_hana_standalone.png) - A **highly-available** SAP HANA deployment ![GitHub Logo](/dm/templates/sap_hana/images/sap_hana_ha.png) Below are the main steps performed by the template: 1) Create a custom VPC with two subnets: - subnetwork-1 will be used as DMZ and the bastion host will be deployed into it. - subnetwork-2 will be used for the HANA DB. 2) Set up a NAT gateway: so that your VMs can access the internet without having to have a public IP address. 3) Create necessary firewall rules, to allow connectivity between bastion hosts and the instance where HANA is deployed. 4) Install SAP HANA using by leveraging existing [templates](https://cloud.google.com/solutions/sap/docs/sap-hana-deployment-guide). 5) Deploy two bastion-hosts. A Linux instance for SSH and a Windows instance for RDP/HANA Studio access. ## Prerequisites - Install [gcloud](https://cloud.google.com/sdk) - Create a [GCP project, set up billing, enable requisite APIs](../project/README.md) ## Deployment ### Resources - [compute.v1.instance](https://cloud.google.com/compute/docs/reference/rest/v1/instances) - [compute.v1.network](https://cloud.google.com/compute/docs/reference/latest/networks) - [compute.v1.subnetwork](https://cloud.google.com/compute/docs/reference/latest/subnetworks) - [compute.beta.firewall](https://cloud.google.com/compute/docs/reference/rest/beta/firewalls) - [compute.v1.router](https://cloud.google.com/compute/docs/reference/rest/v1/routers) ### Properties See `properties` section in the schema file(s): - [SAP HANA template](sap_hana_template.py.schema) ### Usage 1. Clone the [Deployment Manager samples repository](https://github.com/GoogleCloudPlatform/cloud-foundation-toolkit): ```shell git clone https://github.com/GoogleCloudPlatform/cloud-foundation-toolkit ``` 2. Go to the [dm](../../) directory: ```shell cd dm ``` 3. Copy the example DM config to be used as a model for the deployment; in this case, [examples/hana_standalone_scenario.yaml](examples/hana_standalone_scenario.yaml) for standalone HANA or [examples/hana_ha_scenario.yaml](examples/hana_ha_scenario.yaml) for HANA HA scenario : ```shell cp templates/sap_hana/examples/sap_hana_ha.yaml my_sap_hana_ha.yaml ``` 4. Change the values in the config file to match your specific GCP setup (for properties, refer to the schema files listed above): ```shell vim my_sap_hana_ha.yaml # <== change values to match your GCP setup ``` 5. Create your deployment (replace <YOUR_DEPLOYMENT_NAME> with the relevant deployment name): ```shell gcloud deployment-manager deployments create <YOUR_DEPLOYMENT_NAME> \ --config my_sap_hana_ha.yaml ``` 6. In case you need to delete your deployment: ```shell gcloud deployment-manager deployments delete <YOUR_DEPLOYMENT_NAME> ``` ## How to test it? You need to perform the the testing steps are the following: 1) Deploy the template as described in step 5 above 2) Wait until HANA is deployed successfully. This can be done by checking the Stackdriver Logs for **INSTANCE DEPLOYMENT COMPLETE**. 3) Connect vis SSH to the Linux bastion host 4) From the bastion host, connect to the HANA instance using the command ```gcloud compute INSTANCE-NAME --internal-ip```, then: * For a standalone HANA deployment, follow the steps described [here](https://cloud.google.com/solutions/sap/docs/sap-hana-deployment-guide#verifying_deployment). * For a HANA HA deployment, follow the steps described [here](https://cloud.google.com/solutions/sap/docs/sap-hana-ha-deployment-guide#checking_the_configuration_of_the_vm_and_the_sap_hana_installation). ## Examples - [A standlone SAP Hana deployment](examples/sap_hana_ha.yaml) - [A highly-available SAP HANA deployment](examples/sap_hana_standalone.yaml) <file_sep>/dm/templates/sap_hana/sap_hana_template.py # Copyright 2020 Google Inc. All rights reserved. # # 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. """ This template deploys SAP HANA and all required infrastructure resources (network, firewall rules, NAT, etc). """ def generate_config(context): properties = context.properties # Creating the network (VPC + subnets) resource network = { 'name': 'sap-poc-vpc', 'type': 'network.py', 'properties': { 'autoCreateSubnetworks': False, 'subnetworks': [{ 'name': 'subnetwork-1', 'region': properties['region'], 'ipCidrRange': '10.0.0.0/24', }, { 'name': 'subnetwork-2', 'region': properties['region'], 'ipCidrRange': '192.168.0.0/24', }] } } #Create a Cloud NAT Gateway cloud_router = { 'name': 'cloud-nat-gateway', 'type': 'cloud_router.py', 'properties': { 'name': 'cloud-nat-router', 'network': '$(ref.sap-poc-vpc.name)', 'region': properties['region'], 'nats': [{ 'name': 'cloud-nat', 'sourceSubnetworkIpRangesToNat': 'LIST_OF_SUBNETWORKS', 'natIpAllocateOption': 'AUTO_ONLY', 'subnetworks': [{ 'name': '$(ref.subnetwork-1.selfLink)' }] }] } } #Create a windows bastion host to be used for installing HANA Studio and connecting to HANA DB windows_bastion_host = { 'name': 'windows-bastion-host', 'type': 'instance.py', 'properties': { 'zone': properties['primaryZone'], 'diskImage': 'projects/windows-cloud/global/images/family/windows-2019', 'machineType': 'n1-standard-1', 'diskType': 'pd-ssd', 'networks': [{ 'network': "$(ref.sap-poc-vpc.selfLink)", 'subnetwork': "$(ref.subnetwork-2.selfLink)", 'accessConfigs': [{ 'type': 'ONE_TO_ONE_NAT' }] }], 'tags': { 'items': ['jumpserver'] } } } #Create a linux bastion host which will be used to connect to HANA DB CLI and run commands. linux_bastion_host = { 'name': 'linux-bastion-host', 'type': 'instance.py', 'properties': { 'zone': properties['primaryZone'], 'diskImage': 'projects/ubuntu-os-cloud/global/images/family/ubuntu-1804-lts', 'machineType': 'f1-micro', 'diskType': 'pd-ssd', 'networks': [{ 'network': '$(ref.sap-poc-vpc.selfLink)', 'subnetwork': '$(ref.subnetwork-2.selfLink)', 'accessConfigs': [{ 'type': 'ONE_TO_ONE_NAT' }] }], 'tags': { 'items': ['jumpserver'] } } } # Create necessary Firewall rules to allow connectivity to HANA DB from both bastion hosts. firewall_rules = { 'name': 'firewall-rules', 'type': 'firewall.py', 'properties': { 'network': '$(ref.sap-poc-vpc.selfLink)', 'rules': [{ 'name': 'allow-ssh-and-rdp', 'allowed':[ { 'IPProtocol': 'tcp', 'ports': ['22', '3389'] }], 'description': 'Allow SSH and RDP from outside to bastion host.', 'direction': 'INGRESS', 'targetTags': ["jumpserver"], 'sourceRanges': [ '0.0.0.0/0' ] }, { 'name': 'jumpserver-to-hana', 'allowed': [{ 'IPProtocol': 'tcp', 'ports': ['22', '30015'] # In general,the port to open is 3 <Instance number> 15 to allow HANA Studio to Connect to HANA DB < -- -- -TODO }], 'description': 'Allow SSH from bastion host to HANA instances', 'direction': 'INGRESS', 'targetTags': ["hana-db"], 'sourceRanges': ['$(ref.subnetwork-2.ipCidrRange)'] } ] } } sap_hana_resource = {} if properties.get('secondaryZone'): # HANA HA deployment sap_hana_resource = { 'name': 'sap_hana', "type": 'sap_hana_ha.py', 'properties': { 'primaryInstanceName': properties['primaryInstanceName'], 'secondaryInstanceName': properties['secondaryInstanceName'], 'primaryZone': properties['primaryZone'], 'secondaryZone': properties['secondaryZone'], 'sap_vip': '10.1.0.10', #TO DO: improve this by reserving an internal IP address in advance. } } else: sap_hana_resource = { #HANA standalone setup 'name': 'sap_hana', "type": 'sap_hana.py', 'properties': { 'instanceName': properties['primaryInstanceName'], 'zone': properties['primaryZone'], 'sap_hana_scaleout_nodes': 0 } } #Add the rest of "common & manadatory" properties sap_hana_resource['properties']['dependsOn'] = ['$(ref.cloud-nat-gateway.selfLink)'] sap_hana_resource['properties']['instanceType'] = properties['instanceType'] sap_hana_resource['properties']['subnetwork'] = 'subnetwork-1' sap_hana_resource['properties']['linuxImage'] = properties['linuxImage'] sap_hana_resource['properties']['linuxImageProject'] = properties['linuxImageProject'] sap_hana_resource['properties']['sap_hana_deployment_bucket'] = properties['sap_hana_deployment_bucket'] sap_hana_resource['properties']['sap_hana_sid'] = properties['sap_hana_sid'] sap_hana_resource['properties']['sap_hana_instance_number'] = 00 sap_hana_resource['properties']['sap_hana_sidadm_password'] = properties['sap_hana_sidadm_password'] sap_hana_resource['properties']['sap_hana_system_password'] = properties['sap_hana_system_password'] sap_hana_resource['properties']['networkTag'] = 'hana-db' sap_hana_resource['properties']['publicIP'] = False # Define optional properties. optional_properties = [ 'serviceAccount', 'sap_hana_backup_size', 'sap_hana_double_volume_size', 'sap_hana_sidadm_uid', 'sap_hana_sapsys_gid', 'sap_deployment_debug', 'post_deployment_script' ] # Add optional properties if there are any. for prop in optional_properties: append_optional_property(sap_hana_resource, properties, prop) resources = [network, cloud_router, windows_bastion_host, linux_bastion_host, firewall_rules, sap_hana_resource] return { 'resources': resources} def append_optional_property(resource, properties, prop_name): """ If the property is set, it is added to the resource. """ val = properties.get(prop_name) if val: resource['properties'][prop_name] = val return<file_sep>/config-connector/solutions/iam/README.md # Config Connector IAM Solutions This is a collection of Config Connector solutions that make it easier to non-destructively manage multiple IAM roles for resources on Google Cloud Platform: - [Member IAM](./kpt/member-iam) Details about usage can be found in each solution.<file_sep>/config-connector/solutions/projects/kpt/shared-vpc/README.md Shared VPC Network ================================================== # NAME shared-vpc # SYNOPSIS Config Connector YAML files to create a VPC network inside a host project to be consumed from within a service project. ## Consumption Download the package using [kpt](https://googlecontainertools.github.io/kpt/): ``` kpt pkg get https://github.com/GoogleCloudPlatform/cloud-foundation-toolkit.git/config-connector/solutions/projects/kpt/shared-vpc . ``` ## Requirements A working cluster with Config Connector installed. The cnrm-system service account, which must have: - `roles/resourcemanager.projectCreator` in the target organization if service and host projects do not yet exist, or the `owner` role in the projects if they already exist. - `roles/compute.xpnAdmin` in the target organization - `roles/billing.user` in the target billing account - Cloud Billing and Cloud Resource Manager APIs enabled in the project managed by Config Connector ## Usage Set the ID for billing account, host project, service project, and organization: ``` kpt cfg set . billing-account VALUE kpt cfg set . host-project VALUE kpt cfg set . service-project VALUE kpt cfg set . org-id VALUE ``` Set the default namespace setter to reflect the namespace you will apply the solution YAMLs to. This may be the namespace you set [here](https://cloud.google.com/config-connector/docs/how-to/setting-default-namespace). ``` kpt cfg set . default-namespace VALUE ``` where `VALUE` is the name of the namespace you found to be applicable above. _Optionally,_ you can also change the name of the VPC network, from the default value of `sharedvpcnetwork`. Once your configuration is complete, simply apply: ``` kubectl apply -f . ``` Note: To see the applied resources for a given namespace, run `kubectl get gcp --namespace <namespace>`, where `<namespace>` is replaced by the corresponding namespace in the `0-namespace.yaml` file. Services that have been applied will have type `gcpservice`. # License Apache 2.0 - See [LICENSE](/LICENSE) for more information. <file_sep>/config-connector/solutions/README.md # Config Connector Solutions ## Overview Config Connector Solutions provides best practice solutions to common cloud applications, formatted as YAML definitions for Config Connector CRDs. These YAMLs can be applied to clusters running [Config Connector](https://cloud.google.com/config-connector/docs/how-to/getting-started). ## Structure Folders under this directory denote general solution areas. In each solution area folder, there are folders for each package & customization tool (currently helm and kpt), under which are nested all available solutions in that solution area and package format. ## Solutions The full list of solutions grouped by area: * **apps** - automate creation of a canonical sample application and provision required GCP services with Config Connector * wordpress [ [helm](apps/helm/wordpress) ] - provision Wordpress application powered by GCP MySQL database * **projects** - automate creation of GCP projects, folders and project services using Config Connector * project-hierarcy [ [kpt](projects/kpt/project-hierarchy) ] - get started with a folder and a project * project-services [ [kpt](projects/kpt/project-services) ] - enable GCP API for a project * simple-project [ [kpt](projects/kpt/simple-project) ] - get started with a simple project ## Usage ### helm These samples are consumable as [helm charts](https://helm.sh/docs/topics/charts/). Common targets for modification are listed in `values.yaml`. * [Installing helm 3.0](https://helm.sh/docs/intro/install/). These solutions have been verified with Helm v.3+. * Showing values: `helm show PATH_TO_CHART` * Validating chart: `helm template PATH_TO_CHART` * Setting chart: `helm install PATH_TO_CHART -generate-name` Comprehensive documentation at [https://helm.sh/docs/](https://helm.sh/docs/). ### kpt These samples are consumable as [kpt packages](https://googlecontainertools.github.io/kpt/). Common targets for modification are provided kpt setters, and can be listed with `kpt cfg list-setters`. * Installing kpt: follow the instructions on [the kpt GitHub](https://github.com/GoogleContainerTools/kpt). * Listing setters: See which values are available for kpt to change `kpt cfg list-setters` * Setting setters: `kpt cfg set DIR NAME VALUE --set-by NAME` Comprehensive documentation at [https://googlecontainertools.github.io/kpt/](https://googlecontainertools.github.io/kpt/). ## License Apache 2.0 - See [LICENSE](/LICENSE) for more information.
914728bff97aa18c7ffa3226d419804a6db3aa6a
[ "Markdown", "Python" ]
5
Markdown
hbougdal/cloud-foundation-toolkit
996614d6c116b36b4a932bf747a0cfd53e5a51c9
8ba6c3c697980dd2a11ecedca9f7e74e3070b9d0
refs/heads/master
<repo_name>yux20000304/data_structure-in-HUST<file_sep>/数据结构课设/base.cpp #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #define MaxNumVar 100000 #define TRUE 1 #define FALSE 0 #define OK 1 typedef struct varWatch { struct varList *positive; //邻接表:正文字,负文字. struct varList *negative; int pos_num; int neg_num; int flag; } Var_watch,varWatch; typedef struct varList { struct clause *p; //指向一个子句,用来存储该子句的地址 struct varList *next; //指向下一个与该文字关联的子句 int satisfied; } Var_List,VarList; typedef struct clause { struct clauseLiteral *p; //指向子句中的下一个文字 struct clause *nextclause; //指向下一个子句 int word_num; int flag; } clause; typedef struct clauseLiteral { int data; //文字的值 struct clauseLiteral *next; //指向子句中的下一个文字 } clauseLiteral; typedef int status; static int number_var; //变元数 static int clause_num; //语句数 int answer[MaxNumVar]; //完成答案输出 int stack_answer[MaxNumVar];//搜索路径栈 int *top=stack_answer,*bottom=stack_answer; int decision[MaxNumVar]; int *first=decision,*last=decision; int InitSat(clause **S, Var_watch *var_watch); int LoadCnf(clause **S, Var_watch var_watch[], FILE *fp); int GetNum(FILE *fp); int Putclause(clause *ctemp, int var, Var_watch var_watch[]); int abs(int a); int DPLL(clause *S,Var_watch *var_watch); clause *pan_duan(clause *S); int unique(clause *single,Var_watch *var_watch); int empty_set(clause *q); int empty_clause(clause *q); int stragety(Var_watch *var_watch); int reset(varWatch *var_watch,int temp); int delete_var(clause *pt,int temp); int search(Var_watch *var_watch,int temp); int print_answer(); int save_answer(int result, char *filename,int time); int SAT(); int answer_test(clause *S,FILE *fp,varWatch *var_watch); int last_branch(varWatch *var_watch); char cnfpath[100]; status Sudoku(); status InitSudoku(int level); status calculate(int n, int m); status Generatecnf(int level); status Rule1(int level, FILE *fp); status Rule2(int level, FILE *fp); status Rule3(int level, FILE *fp); void Rule2_clause(int arr[], int level, int wordnum, int k1, int k2, FILE *fp); int main() { int op = 1; while (op) { printf("\n\n"); printf("\t\t Menu \n"); printf("\t=====================================================\n"); printf("\t\t1. Sudoku 2. SAT 0.Exit\n"); printf("\t=====================================================\n"); printf("\t\t CS1806 YYX U201814655\n\n\n"); printf("\t\t Choose your operation[0~2]: "); scanf("%d", &op); system("cls"); switch (op) { case 1: Sudoku(); break; case 2: SAT(); break; case 0: exit(0); default: printf("\t\t\tPlease choose your operation again[0~2]:"); scanf("%d", &op); } } return 0; } int SAT() { clause *S = NULL; //分配一个字句指针 Var_watch var_watch[MaxNumVar + 1]; //最大变元数目加一个空间 FILE *fp; //文件指针 char filename[300]; //文件名 int op = 1, result, i; clock_t start, finish; int time_sign; while (op) { printf("\n\n"); printf("\t SAT Menu\n"); printf("=====================================================================\n"); printf("\t1. New SAT 2. Answer Test 0. Main menu\n"); printf("=====================================================================\n"); printf("\t\t Choose your operation[0~2]: "); scanf("%d", &op); system("cls"); switch (op) { case 1: InitSat(&S, var_watch); //初始化 printf("please input the cnf path:\n"); scanf("%s", filename, 300); fp = fopen(filename, "r"); start = clock(); if (fp == NULL) { printf("open document failed!\n "); break; } else LoadCnf(&S, var_watch, fp); //调用LoadCnf 函数,读取文件 result = DPLL(S, var_watch); finish = clock(); time_sign = (finish - start); //时间记录 if (result == TRUE) { printf("time to solve the sat problem is: %d ms\n", time_sign); print_answer(); save_answer(result, filename, time_sign); } else { printf("no solution!\n"); } break; case 2: InitSat(&S, var_watch); //初始化 printf("please input the cnf path you want to prove:\n"); scanf("%s", filename, 300); fp = fopen(filename, "r"); if (fp == NULL) { printf("res open failed!\n "); break; } else LoadCnf(&S, var_watch, fp); //调用LoadCnf 函数,读取文件 printf("please input the res path tou want to prove:\n"); scanf("%s", filename, 300); fp = fopen(filename, "r"); result = answer_test(S, fp, var_watch); if (result == TRUE) { printf("satisfied!\n"); } else { printf("unsatisfied!\n"); } break; case 0: return 0; default: printf("\t\t\tPlease choose your operation again[0~2]:"); scanf("%d", &op); } } return 0; } int InitSat(clause **S, Var_watch var_watch[]) { clause *cfront = *S, *crear; //头尾子句指针 clauseLiteral *lfront, *lrear; //头尾文字指针,子句初始化 int i; while (cfront) //如果头字句不为空 { crear = cfront->nextclause; //把尾字句指针设为头字句指针的指针域 lfront = cfront->p; //把头文字指针设为头字句指针的文字域 while (lfront) //如果头文字指针不为空 { lrear = lfront->next; //把尾文字指针移到头文字指针的后面 free(lfront); //释放头文字指针 lfront = lrear; //再将头文字指针向后移一位 } free(cfront); //把最后的文字释放 cfront = crear; //把头字句指针往后一位 } //到此处已经把所有的字句以及文字删除 *S = NULL; //把字句指针赋值为NULL number_var = 0; //把变元数目赋值为0 clause_num = 0; //把已知变元数目赋值为0 for (i = 1; i < MaxNumVar; i++) { var_watch[i].positive = NULL; //文字邻接表指针指向空 var_watch[i].negative = NULL; var_watch[i].pos_num=0; var_watch[i].neg_num=0; var_watch[i].flag=0; answer[i] = 0; } top = stack_answer; bottom = stack_answer; return 0; } int LoadCnf(clause **S, Var_watch *var_watch, FILE *fp) { char c; clause *clausetemp, *cp = NULL; //两个指针,用来构建字句单链表 clauseLiteral *p, *q; //两个指针,用来构建文字单链表 int var; //变量的值 int numclauseVar; //作为计数器统计子句中的文字个数 fscanf(fp, "%c", &c); while (c == 'c') { while (c != '\n' && c != '\r') fscanf(fp, "%c", &c); fscanf(fp, "%c", &c); if (c == '\n') //读取换行符 fscanf(fp, "%c", &c); } fscanf(fp, " cnf "); //读到文件的信息段 number_var = GetNum(fp); //读取变量数,并赋值给numVar clause_num = GetNum(fp); //读取子句数 var = GetNum(fp); //再次调用,读取下一行第一个变量值,把值赋给var while (1) { numclauseVar = 0; //把计数器初始化 clausetemp = (clause *)malloc(sizeof(clause)); //创建字句链表的头指针 p = clausetemp->p; //p为头子句的下一个文字 while (var) //var不为0,即该子句还有文字没有读取 { ++numclauseVar; //计数器,统计子句的变元数目 q = (clauseLiteral *)malloc(sizeof(clauseLiteral)); //把单链表的表头创建出来 q->data = var; //文字的值域改成var q->next = NULL; //文字的指针域赋值为NULL,防止回溯出现问题 if (numclauseVar == 1) //如果为该语句的第一个文字 { clausetemp->p = q; //把子句的文字指针指向第一个文字 p = q; //把p指针指向第一个文字 } else //如果不为该语句的第一个文字 { p->next = q; //把两个文字之间联系起来 p = p->next; //把p指针往后移动一位,和q指向同一文字 } Putclause(clausetemp, var, var_watch); //储存该文字所处子句的字句地址 var = GetNum(fp); //继续读取下一个文字 } //该子句读取完毕 clausetemp->word_num = numclauseVar; //把该子句的文字个数存储 clausetemp->flag = 0; //把子句设置为未满足子句 if (*S == NULL) //如果此时S指向的为空子句,即刚读取了第一个不可化简的字句 { *S = clausetemp; //S赋值为字句的头指针 cp = clausetemp; //子句的尾指针赋值为子句的头指针 cp->nextclause = NULL; } else //刚读取了一个不可简化的子句 { cp->nextclause = clausetemp; cp = cp->nextclause; cp->nextclause = NULL; } var = GetNum(fp); //读取下一行字句的第一个文字 if (feof(fp)) //若到达文件尾,再执行一次读文件操作时,设置文件结束标志 break; } return 0; } int GetNum(FILE *fp) { char c; int sign = 1, num = 0; //num 文字的值,sign标记文字极性 fscanf(fp, "%c", &c); if (c == '-') { sign = -1; //sign变为-1,为负文字 fscanf(fp, "%c", &c); } else if (c == '0') { //子句结束 fscanf(fp, "%c", &c); if (c == '\r') //换行 fscanf(fp, "%c", &c); return num; } else if (c == '\n') return 0; else if (feof(fp)) return 0; while (c != ' ' && c != '\n' && c != '\r') { num = num * 10 + c - '0'; //得到文字的值 fscanf(fp, "%c", &c); } if (c == '\r') fscanf(fp, "%c", &c); return sign * num; //用来得到有正负号的文字 } int Putclause(clause *ctemp, int var, Var_watch var_watch[]) //ctemp为要记录的子句地址 { Var_List *p, *q; //varlist指针 if (var > 0) { //如果该变元大于0 p = var_watch[var].positive; //p指针为该变元所在位置的第一个正文字 var_watch[var].pos_num++; } else{ //如果该变元小于0 p = var_watch[-var].negative; //p指针为该变元所在位置的第一个负文字 var_watch[-var].neg_num++; } if (p == NULL) { //如果p是链表的第一个 p = (VarList *)malloc(sizeof(VarList)); p->p = ctemp; //将需要储存的子句地址存储下来 if (var > 0){ var_watch[var].positive = p; } else{ var_watch[-var].negative = p; } } else { //p不是链表的第一个 while (p->next) p = p->next; q = (VarList *)malloc(sizeof(VarList)); q->p = ctemp; p->next = q; p = p->next; } p->satisfied = 0; //把标记清0 p->next = NULL; //将p的指针域赋值为NULL return 0; } int abs(int a) { if (a >= 0) return a; else return -a; } int DPLL(clause *S, Var_watch *var_watch) { int response; clause *temp; if (empty_set(S)) return TRUE; else if (!empty_clause(S)) return FALSE; while (temp = pan_duan(S)) { unique(temp, var_watch); if (empty_set(S)) return TRUE; else if (!empty_clause(S)) return FALSE; } if (empty_set(S)) return TRUE; else if (!empty_clause(S)) return FALSE; response = stragety(var_watch); *top = response; top++; *first = response; first++; search(var_watch, response); //删除含有response的文字 if (DPLL(S, var_watch)) //对现在的邻接表进行递归 return TRUE; response = last_branch(var_watch); //返回上一个分支点 search(var_watch, response); return DPLL(S, var_watch); } clause *pan_duan(clause *S) { //判断子句集是否含有单子句,返回一个单子句 clause *q = S; while (q) { if (q->flag == 1) { q = q->nextclause; continue; } if (q->word_num != 1) { q = q->nextclause; continue; } else break; } return q; } int unique(clause *single, Var_watch *var_watch) { //传入一个单子句,对子句集进行单子句操作 int temp; Var_List *p, *q; temp = single->p->data; *top = temp; top++; if (temp > 0) { //该文字为正文字 p = var_watch[temp].positive; while (p) { if (p->p->flag == 0) { //该文字所在子句为未满足 p->p->flag = 1; p->satisfied = 1; } p = p->next; } q = var_watch[temp].negative; while (q) { if (q->p->flag == 0) { //该文字所在的子句为未满足 q->p->word_num--; delete_var(q->p, -temp); } q = q->next; } } else { //该文字为负文字 p = var_watch[-temp].negative; while (p) { if (p->p->flag == 0) { //该文字所在子句为未满足 p->p->flag = 1; p->satisfied = 1; } p = p->next; } q = var_watch[-temp].positive; while (q) { if (q->p->flag == 0) { //该文字所在的子句为未满足 q->p->word_num--; delete_var(q->p, -temp); } q = q->next; } } var_watch[abs(temp)].flag=1; return OK; } int empty_set(clause *q) { //判断子句集是否为空 int i=0; for(i=0;i<clause_num;i++) { if (q->flag == 0) return FALSE; q = q->nextclause; } return TRUE; } int empty_clause(clause *q) { //判断是否有空子句 while (q) { if (q->flag == 0 && q->p == NULL) return FALSE; q = q->nextclause; } return TRUE; } int stragety(Var_watch *var_watch) { int i=1; int max_num=0; int choose_num=0; for(i=1;i<=number_var;i++){ if(var_watch[i].flag==1){ continue; } else{ if(var_watch[i].pos_num>max_num){ max_num=var_watch[i].pos_num; choose_num=i; } if(var_watch[i].neg_num>max_num){ max_num=var_watch[i].neg_num; choose_num=-i; } } } return choose_num; } int reset(varWatch *var_watch, int temp) { //重新将上一步撤销 Var_List *p, *q; if (temp > 0) { //该文字为正文字 p = var_watch[temp].positive; while (p) { if (p->p->flag == 1 && p->satisfied == 1) { //该文字所在子句为已满足且为此次操作造成 p->p->flag = 0; p->satisfied = 0; } p = p->next; } q = var_watch[temp].negative; while (q) { if (q->p->flag == 0) { //该文字所在的子句为未满足 q->p->word_num++; clauseLiteral *pt = (clauseLiteral *)malloc(sizeof(clauseLiteral)); pt->data = -temp; pt->next = q->p->p; q->p->p = pt; } q = q->next; } } else { //该文字为负文字 p = var_watch[-temp].negative; while (p) { if (p->p->flag == 1 && p->satisfied == 1) { //该文字所在子句为满足,且是由本次操作造成的 p->p->flag = 0; p->satisfied = 0; } p = p->next; } q = var_watch[-temp].positive; while (q) { if (q->p->flag == 0) { //该文字所在的子句为未满足 q->p->word_num++; clauseLiteral *pt = (clauseLiteral *)malloc(sizeof(clauseLiteral)); pt->data = -temp; pt->next = q->p->p; q->p->p = pt; } q = q->next; } } var_watch[abs(temp)].flag=0; return OK; } int delete_var(clause *pt, int temp) { //把该变元从子句集中删除 clauseLiteral *p = pt->p, *q = NULL; if (p->data == temp) { pt->p = p->next; free(p); } else { while (p->next->data != temp) p = p->next; q = p->next; p->next = q->next; free(q); } return OK; } int search(Var_watch *var_watch, int temp) { //删除所有与含temp的文字 Var_List *p, *q; if (temp > 0) { //该文字为正文字 p = var_watch[temp].positive; while (p) { if (p->p->flag == 0) { //该文字所在子句为未满足 p->p->flag = 1; p->satisfied = 1; } p = p->next; } q = var_watch[temp].negative; while (q) { if (q->p->flag == 0) { //该文字所在的子句为未满足 q->p->word_num--; delete_var(q->p, -temp); } q = q->next; } } else { //该文字为负文字 p = var_watch[-temp].negative; while (p) { if (p->p->flag == 0) { //该文字所在子句为未满足 p->p->flag = 1; p->satisfied = 1; } p = p->next; } q = var_watch[-temp].positive; while (q) { if (q->p->flag == 0) { //该文字所在的子句为未满足 q->p->word_num--; delete_var(q->p, -temp); } q = q->next; } } var_watch[abs(temp)].flag=1; return OK; } int last_branch(varWatch *var_watch) { top--; first--; while (*top != *first) { reset(var_watch, *top); top--; } reset(var_watch, *top); *top = -*top; top++; return *(top - 1); } int print_answer() { int i; while (top != bottom) { answer[abs(*bottom)] = (*bottom) / (abs(*bottom)); bottom++; } for (i = 1; i <= number_var; i++) { if (answer[i] == 1 || answer[i] == 0) printf("%d ", i); if (answer[i] == -1) printf("%d ", answer[i] * i); } return OK; } int save_answer(int result, char *filename, int time) { FILE *fp; int p = 0, i; while (filename[p] != 0) p++; while (filename[p] != '.') p--; p++; filename[p] = 'r'; p++; filename[p] = 'e'; p++; filename[p] = 's'; p++; //把文件名补充完整 filename[p] = 0; fp = fopen(filename, "w"); if (result == 1) fprintf(fp, "s 1\r\n"); else fprintf(fp, "s 0\r\n"); fprintf(fp, "v "); for (i = 1; i <= number_var; i++) { if (answer[i] == 1) fprintf(fp, "%d ", answer[i] * i); else if (answer[i] == -1) fprintf(fp, "%d ", answer[i] * i); else if (answer[i] == 0) fprintf(fp, "%d ", i); } fprintf(fp, "\r\n"); fprintf(fp, "t %d\r\n", time); fclose(fp); return 0; } int answer_test(clause *S, FILE *fp, varWatch *var_watch) { char c; int temp, i; fscanf(fp, "%c", &c); while (c != 'v') { fscanf(fp, "%c", &c); } fscanf(fp, "%c", &c); //读取空格 temp = GetNum(fp); for (i = 1; i <= number_var; i++) { if (temp > 0) { answer[temp] = 1; } else { answer[-temp] = -1; } temp = GetNum(fp); } for (i = 1; i <= number_var; i++) { VarList *pt = NULL; if (answer[i] == 1) { pt = var_watch[i].positive; while (pt) { pt->p->flag = 1; pt = pt->next; } } if (answer[i] == -1) { pt = var_watch[i].negative; while (pt) { pt->p->flag = 1; pt = pt->next; } } } return empty_set(S); } status Sudoku(){ int level,temp,i,j,k; clause *S = NULL; Var_watch var_watch[MaxNumVar + 1]; FILE *fp; srand((unsigned)time(NULL)); printf("please input the level of the binary sudoku:\n"); scanf("%d",&level); InitSudoku(level); InitSat(&S, var_watch); //初始化 fp = fopen(cnfpath, "r"); if (fp == NULL){ printf("open document failed!\n "); } else LoadCnf(&S, var_watch, fp); //调用LoadCnf 函数,读取文件 for(i=0;i<level/2;i++){ temp=rand()%(level*level)+1; *top=temp; top++; search(var_watch,temp); } DPLL(S, var_watch); while (top != bottom) { answer[abs(*bottom)] = (*bottom) / (abs(*bottom)); bottom++; } for(i=1;i<=level*level;){ for(k = 0; k < level; k++) printf("____"); printf("\n|"); for(j=1;j<=level;j++){ if(answer[i]==1) printf("1 |"); else printf("0 |"); i++; } printf("\n"); } for(k = 0; k < level; k++) printf("____"); printf("\n"); for(i=1;i<level*(level-2)+1;i++){ temp=rand()%(level*level)+1; answer[temp]=0; } printf("the sudoku is:\n"); for(i=1;i<=level*level;){ for(k = 0; k < level; k++) printf("____"); printf("\n|"); for(j=1;j<=level;j++){ if(answer[i]==1) printf("1 |"); else if(answer[i]==-1) printf("0 |"); else printf(" |"); i++; } printf("\n"); } for(k = 0; k < level; k++) printf("____"); printf("\n"); return 0; } status InitSudoku(int level) { //初始化数独,level代表阶数 int result; //判断是否有解 int *puzzle = (int *)malloc((level * level + 1) * sizeof(int)); //给数独分配空间 number_var = level * level; clause_num = 0; clause_num += 2 * level * (level - 2) * 2; //第一个约束,每一行要取level-3个语句数 clause_num += 2 * level * calculate(level, level / 2 + 1) * 2; //第二个约束产生的语句数 number_var += 2 * calculate(level, 2) * (3 * level + 2); clause_num += 2 * calculate(level, 2) * (10 * level + 2); //第三个约束产生的语句数和变元数 Generatecnf(level); //加载数独cnf文件 return 0; } status calculate(int n, int m) //n>=m>=0 { int i, a; if (m + m > n) m = n - m; //be faster for (i = 1, a = 1; i <= m; i++, n--) a = a * n / i; return a; } status Generatecnf(int level) { FILE *fp; strcpy(cnfpath, "./binary_puzzle.cnf"); fp = fopen(cnfpath, "w+"); // 打开文件 fprintf(fp, "p cnf %d %d\n", number_var, clause_num); Rule1(level, fp); Rule2(level, fp); Rule3(level, fp); fclose(fp); return OK; } status Rule1(int level, FILE *fp) { //第一个约束条件,每行每列不允许有连续的三个0或三个1出现 int i, j; for (i = 0; i < level; i++) //行生成的语句 { for (j = 0; j < level - 2; j++) { fprintf(fp, "%d ", i * level + j + 1); fprintf(fp, "%d ", i * level + j + 2); fprintf(fp, "%d ", i * level + j + 3); fprintf(fp, "0\n"); } for (j = 0; j < level - 2; j++) { fprintf(fp, "%d ", -(i * level + j + 1)); fprintf(fp, "%d ", -(i * level + j + 2)); fprintf(fp, "%d ", -(i * level + j + 3)); fprintf(fp, "0\n"); } } for (i = 0; i < level - 2; i++) //列生成的语句 { for (j = 0; j < level; j++) { fprintf(fp, "%d ", i * level + j + 1); fprintf(fp, "%d ", (i + 1) * level + j + 1); fprintf(fp, "%d ", (i + 2) * level + j + 1); fprintf(fp, "0\n"); } for (j = 0; j < level; j++) { fprintf(fp, "%d ", -(i * level + j + 1)); fprintf(fp, "%d ", -((i + 1) * level + j + 1)); fprintf(fp, "%d ", -((i + 2) * level + j + 1)); fprintf(fp, "0\n"); } } return OK; } status Rule2(int level, FILE *fp) { //第二个约束条件,每一行每一列中的1和0的个数相同 int i, j, wordnum = level / 2 + 1, l[1000]; //wordnum代表阶数的一半加一,用来代表生成的语句的文字数量 for (i = 0; i < level; i++) //行 { for (j = 0; j < level; j++) //记录该行的正变元 l[j] = level * i + j + 1; Rule2_clause(l, level, wordnum, 0, 0, fp); //把该行生成的正变元子句存储起来 for (j = 0; j < level; j++) //记录该行的负变元 l[j] = -(level * i + j + 1); Rule2_clause(l, level, wordnum, 0, 0, fp); //把该行的负变元子句存储起来 } for (i = 0; i < level; i++) //列 { for (j = 0; j < level; j++) l[j] = level * j + i + 1; Rule2_clause(l, level, wordnum, 0, 0, fp); for (j = 0; j < level; j++) l[j] = -(level * j + i + 1); Rule2_clause(l, level, wordnum, 0, 0, fp); } return OK; } void Rule2_clause(int arr[], int level, int wordnum, int k1, int k2, FILE *fp) //把生成的子句写入文件中 { static int rec[1000]; //记录组合序列 int i; if (k1 == wordnum) //输出当前序列 { for (i = 0; i < wordnum; ++i) fprintf(fp, "%d ", rec[i]); fprintf(fp, "0\n"); } else { for (i = k2; i < level; ++i) { rec[k1] = arr[i]; //子序列赋值 Rule2_clause(arr, level, wordnum, k1 + 1, i + 1, fp); //递归回溯 } } } status Rule3(int level, FILE *fp) { //第三个约束条件 int i, j, k, literal_name = level * level + 1; //生成的中间变元从的编号接在数独最大变元的后一位 for (i = 0; i < level - 1; i++) //从第一行开始选取第一个比较行 { for (j = i + 1; j < level; j++) //从第一个比较行之后逐行进行比对 { for (k = 0; k < level; k++) //确定需要比较的两行之后开始从每行的第一个开始比较 { // 15711= 51∧71转换的结果 fprintf(fp, "%d %d 0\n", i * level + k + 1, -literal_name); //51∨ ?15711 fprintf(fp, "%d %d 0\n", j * level + k + 1, -literal_name); //71∨ ?15711 fprintf(fp, "%d %d %d 0\n", -(i * level + k + 1), -(j * level + k + 1), literal_name); //?51∨ ?71∨15711 literal_name += 1; //获得下一个变元编号 // 15710= ?51∧?71转换的结果 fprintf(fp, "%d %d 0\n", -(i * level + k + 1), -literal_name); //?51∨ ?15710 fprintf(fp, "%d %d 0\n", -(j * level + k + 1), -literal_name); //?71∨ ?15710 fprintf(fp, "%d %d %d 0\n", i * level + k + 1, j * level + k + 1, literal_name); //51∨71∨15710 literal_name += 1; // 1571= 15711∨15710转换的结果 fprintf(fp, "%d %d 0\n", -(literal_name - 2), literal_name); //?15711∨1571 fprintf(fp, "%d %d 0\n", -(literal_name - 1), literal_name); //?15710∨1571 fprintf(fp, "%d %d %d 0\n", literal_name - 1, literal_name - 2, -literal_name); //15711∨15710∨?1571 literal_name += 1; } // 157= ?[1571∧1572∧…∧1578] fprintf(fp, "%d ", -literal_name); //?157∨?1571∨?1572∨…∨?1578 for (k = 1; k < level + 1; k++) fprintf(fp, "%d ", -(literal_name + 2 - k * 3)); fprintf(fp, "0\n"); for (k = 1; k < level + 1; k++) //(1571∨157)∧(1572∨157)…(1578∨157) fprintf(fp, "%d %d 0\n", literal_name + 2 - k * 3, literal_name); fprintf(fp, "%d 0\n", literal_name); literal_name += 1; } } for (i = 0; i < level - 1; i++) //列,和行的类似 { for (j = i + 1; j < level; j++) { for (k = 0; k < level; k++) { fprintf(fp, "%d %d 0\n", k * level + i + 1, -literal_name); fprintf(fp, "%d %d 0\n", k * level + j + 1, -literal_name); fprintf(fp, "%d %d %d 0\n", -(k * level + i + 1), -(k * level + j + 1), literal_name); literal_name += 1; fprintf(fp, "%d %d 0\n", -(k * level + i + 1), -literal_name); fprintf(fp, "%d %d 0\n", -(k * level + j + 1), -literal_name); fprintf(fp, "%d %d %d 0\n", k * level + i + 1, k * level + j + 1, literal_name); literal_name += 1; fprintf(fp, "%d %d 0\n", -(literal_name - 2), literal_name); fprintf(fp, "%d %d 0\n", -(literal_name - 1), literal_name); fprintf(fp, "%d %d %d 0\n", literal_name - 1, literal_name - 2, -literal_name); literal_name += 1; } fprintf(fp, "%d ", -literal_name); for (k = 1; k < level + 1; k++) fprintf(fp, "%d ", -(literal_name + 2 - k * 3)); fprintf(fp, "0\n"); for (k = 1; k < level + 1; k++) fprintf(fp, "%d %d 0\n", literal_name + 2 - k * 3, literal_name); fprintf(fp, "%d 0\n", literal_name); literal_name += 1; } } return OK; } <file_sep>/数据结构试验/linked_list.c /* Linked List On sequence Structure */ #include <stdio.h> #include <malloc.h> #include <stdlib.h> /*---------page 10 on textbook ---------*/ #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASTABLE -1 #define OVERFLOW -2 typedef int status; typedef int ElemType; //数据元素类型定义 /*-------page 22 on textbook -------*/ #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 typedef struct ListNode { //链表元素结构体 ElemType elem; struct ListNode *next; } ListNode,*ListNodePtr; //ListNode为结构体,*ListNodePtr为结构体元素指针 status InitList(ListNode **L); status DestroyList(ListNodePtr L); status ClearList(ListNodePtr L); status ListEmpty(ListNodePtr L); int ListLength(ListNodePtr L); status GetElem(ListNodePtr L, int i, ElemType *e); int LocateElem(ListNodePtr L, ElemType e); status PriorElem(ListNodePtr L, ElemType cur, ElemType *pre_e); status NextElem(ListNodePtr L, ElemType cur, ElemType *next_e); status ListInsert(ListNodePtr L, int i, ElemType e); status ListDelete(ListNodePtr L, ElemType *e, int i); status ListTrabverse(ListNodePtr L); status LoadList(ListNodePtr L); status SaveList(ListNodePtr L); status InputData(ListNodePtr L); /*功能函数声明*/ int main(void) { ListNodePtr L[3]; int i; for(i=0;i<3;i++) L[i]=NULL; int op = 1, renumber, flag, mail, id = 1; while (op) { system("cls"); printf("\n\n"); printf(" Menu for Linked List On Sequence Structure \n"); printf("-------------------------------------------------\n"); printf(" 1. InitList 8. PriorElem\n"); printf(" 2. DestroyList 9. NextElem\n"); printf(" 3. ClearList 10. ListInsert\n"); printf(" 4. ListEmpty 11. ListDelete\n"); printf(" 5. ListLength 12. ListTrabverse\n"); printf(" 6. GetElem 13.LoadList\n"); printf(" 7. LocateElem 14.SaveList\n"); printf(" 0. Exit 15.InputData\n"); printf("-------------------------------------------------\n"); printf(" 请选择你的操作[0~15]:"); scanf("%d", &op); switch (op) { case 1: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if(id<0||id>3) printf("超出id范围\n"); else{ if (InitList(L+id-1) == OK) { printf("线性表创建成功!\n"); } else printf("线性表创建失败!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 2: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id < 0||id>3) printf("超出id范围\n"); else{ if ((renumber = DestroyList(L[id-1])) == OK) { printf("线性表删除成功!\n"); L[id-1] = NULL; } else if (renumber == INFEASTABLE) printf("线性表不存在!\n"); else printf("线性表删除失败!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 3: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else{ if ((renumber = ClearList(L [id - 1])) == OK) printf("线性表清除成功!\n"); else if (renumber == INFEASTABLE) printf("线性!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 4: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else{ if ((renumber = ListEmpty(L [ id - 1])) == INFEASTABLE) printf("线性表不存在!\n"); else if (renumber == TRUE) printf("线性表是空的!\n"); else printf("线性表不是空的!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 5: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else{ if ((renumber = ListLength(L [id - 1])) != INFEASTABLE) printf("线性表长度为:%d\n", renumber); else printf("线性表不存在!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 6: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("请输入元素位置"); scanf("%d", &flag); if ((renumber = GetElem(L [ id - 1], flag, &mail)) == OK) printf("位置%d的元素是%d\n", flag, mail); else if (renumber == ERROR) printf("该位置越界!\n"); else printf("线性表不存在!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 7: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("输入需要定位的元素:"); scanf("%d", &flag); if ((renumber = LocateElem(L [id - 1], flag)) > 0) printf("匹配成功,该元素位置为:%d\n", renumber); else if (renumber == ERROR) printf("匹配失败!\n"); else printf("线性表不存在!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 8: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("输入需要寻找前驱的元素:"); scanf("%d", &flag); if ((renumber = PriorElem(L [id - 1], flag, &mail)) == OK) printf("该数据的前驱元素为:%d\n", mail); else if (renumber == ERROR) printf("该元素没有前驱元素\n"); else printf("线性表不存在!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 9: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("输入需要寻找后继的元素:"); scanf("%d", &flag); if ((renumber = NextElem(L [id - 1], flag, &mail)) == OK) printf("该数据的后继元素为:%d\n", mail); else if (renumber == ERROR) printf("该数据没有后继元素\n"); else printf("线性表不存在\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 10: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("请输入需要插入元素的位置:"); scanf("%d", &flag); printf("请输入插入元素的值"); scanf("%d", &mail); if ((renumber = ListInsert(L [id - 1], flag, mail)) == OK) printf("插入成功!\n"); else if (renumber == OVERFLOW) printf("存储分配失败\n"); else if (renumber == ERROR) printf("插入元素的位置输入不合法\n"); else printf("线性表不存在\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 11: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("请输入需要删除的元素的位置:"); scanf("%d", &flag); if ((renumber = ListDelete(L [id - 1], &mail, flag)) == OK) printf("该节点删除成功,删除的节点的值为:%d\n", mail); else if (renumber == ERROR) printf("删除元素的位置输入不合法\n"); else printf("线性表不存在\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 12: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else{ if (ListTrabverse(L[id - 1])==INFEASTABLE) printf("线性表不存在!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 13: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else if ((renumber = LoadList(L[id - 1])) == OK) printf("线性表成功赋值\n"); else if (renumber == 1) printf("无法打开文件\n"); else printf("线性表不存在\n"); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 14: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else{ if ((renumber = SaveList(L [id - 1])) == OK) printf("文件成功保存\n"); else if (renumber == 1) printf("无法打开文件\n"); else printf("线性表不存在\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 15: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) { printf("超出id范围\n"); getchar(); } else if (InputData(L [id - 1]) == OK) printf("数据成功输入\n"); else { printf("线性表不存在\n"); getchar(); } printf("请输入任意键继续\n"); getchar(); break; case 0: break; } //end of switch } //end of while printf("欢迎下次再使用本系统!\n"); return 0; } //end of main() status InitList(ListNode **L){ *L=(ListNode *)malloc(sizeof(ListNode)); if(!L) return OVERFLOW; (*L)->elem=0; //把表长清0 (*L)->next=NULL; //把指针域赋值为NULL return OK; } status DestroyList(ListNodePtr L){ if(!L) return INFEASTABLE; ListNodePtr p=L; while(!p){ p=p->next; //两个指针,一个用来判断是否到了表的尾部,另外一个用来释放存储空间 free(L); L=p; } return OK; } status ClearList(ListNodePtr L){ if(!L) return INFEASTABLE; DestroyList(L->next); //调用销毁表的函数,把除了表头以外的节点全部摧毁掉 L->next=NULL; L->elem=0; return OK; } status ListEmpty(ListNodePtr L){ if(!L) return INFEASTABLE; if(L->elem==0) return TRUE; else return FALSE; } int ListLength(ListNodePtr L){ if(!L) return INFEASTABLE; return L->elem; //把表长赋值给e元素的数据域 } status GetElem(ListNodePtr L, int i, ElemType *e){ if(!L) return INFEASTABLE; ListNode *p=L; if(i<1||i>L->elem) return ERROR; while(i>0){ //遍历整个线性表,直到找到所输入的位置 p=p->next; i--; } *e=p->elem; //把该位置的元素赋值给e的数据域 return OK; } int LocateElem(ListNodePtr L, ElemType e){ if(!L) return INFEASTABLE; int count=0; ListNode *p=L; while(p){ if(p->elem==e) //判断该节点存储的元素是否为需要寻找的元素 return count; //该元素的的位置 p=p->next; count++; } return ERROR; } status PriorElem(ListNodePtr L, ElemType cur, ElemType *pre_e){ if(!L) return INFEASTABLE; ListNode *p=L->next; while(p->next!=NULL){ if(p->next->elem==cur){ //如果该节点的后继节点的存储值和cur变量相同,则把该节点的存储值赋值给pre_e *pre_e=p->elem; return OK; } p=p->next; } return ERROR; } status NextElem(ListNodePtr L, ElemType cur, ElemType *next_e){ if(!L) return INFEASTABLE; ListNode *p=L->next; while(p&&p->next){ //注意要排除p不是尾节点 if(cur==p->elem){ *next_e=p->next->elem; return OK; } p=p->next; } return ERROR; } status ListInsert(ListNodePtr L, int i, ElemType e){ if(!L) return INFEASTABLE; if(i<1||i>L->elem+1) return ERROR; ListNode *p=L,*q=NULL; while(i>1){ //把p指针移动到需要添加元素的位置 p=p->next; i--; } q=(ListNodePtr)malloc(sizeof(ListNode)); q->elem=e; q->next=p->next; p->next=q; L->elem++; return OK; } status ListDelete(ListNodePtr L, ElemType *e, int i){ if(!L) return INFEASTABLE; if(i<1||i>L->elem) return ERROR; ListNode *p=L; while(i>1){ //把p指针移动到需要删除的位置 p=p->next; i--; } *e=p->next->elem; p->next=p->next->next; L->elem--; return OK; } status ListTrabverse(ListNodePtr L){ if (!L) return INFEASTABLE; ListNode *p=L->next; printf("\n-----------all elements -----------------------\n"); for (; p ; p=p->next) printf("%d ",p->elem); printf("\n------------------ end ------------------------\n"); return OK; } status LoadList(ListNodePtr L) { if (!L) // 线性表未创建 return INFEASTABLE; //读文件 FILE *fp; char filename[30]; printf("input file name: "); scanf("%s", filename); L->elem = 0; if ((fp = fopen(filename, "rb")) == NULL) { printf("File open error\n "); return 1; } ListNode *p=L,*q=NULL; q=(ListNode *)malloc(sizeof(ListNode)); while (fread(&(q->elem), sizeof(ElemType), 1, fp)){ p->next=q; q=(ListNode *)malloc(sizeof(ListNode)); p=p->next; p->next=NULL; L->elem++; } fclose(fp); return OK; } status SaveList(ListNodePtr L) { if (!L) return INFEASTABLE; FILE *fp; char filename[30]; printf("input file name: "); scanf("%s", filename); // 写文件 if ((fp = fopen(filename, "wb")) == NULL) //文件打开失败 { printf("File open error\n "); return 1; } int a[100],i; ListNode *p=L; for(i=0;i<L->elem&&p->next!=NULL;i++){ //把链表中的元素存储到数组中 p=p->next; a[i]=p->elem; } fwrite(a, sizeof(ElemType), L->elem, fp); fclose(fp); return OK; } status InputData(ListNodePtr L){ if(!L) return INFEASTABLE; ListNode *p=L; while(p->next!=NULL) p=p->next; char str[100]; int i = 0, count = 0, a[100] = {0}, symbol = 0; printf("请输入一串元素\n"); getchar(); gets(str); while (1) { while (str[i] && (str[i] < '0' || str[i] > '9') && str[i] != '-') //判断负数的情况 i++; if (str[i]) { if (str[i] == '-') { symbol = 1; i++; } while (str[i] >= '0' && str[i] <= '9') { a[count] = 10 * a[count] + str[i] - '0'; i++; } if (symbol == 1) a[count] = -a[count]; symbol = 0; count++; } else break; } for (i = 0; i < count; i++) { //接着之前的数据在之后继续加新的数据 p->next=(ListNode *)malloc(sizeof(ListNode)); p=p->next; p->elem=a[i]; p->next=NULL; } L->elem += i; return OK; }<file_sep>/数据结构试验/binary_tree.c /* Binary Tree On sequence Structure */ #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include<math.h> /*---------page 10 on textbook ---------*/ #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASTABLE -1 #define OVERFLOW -2 typedef int status; typedef char ElemType; //数据元素类型定义 int key_value = 0; /*-------page 22 on textbook -------*/ #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 typedef struct BiNode { ElemType elem; struct BiNode *pre; struct BiNode *left; struct BiNode *right; int key; } BiNode; //BiNode为二叉树结构体 typedef struct Treehead { char name[100]; BiNode *root; int id; //表示该树的id值 struct Treehead *next; struct Treehead *pre; int nodes; } Treehead; //Treehead为二叉树的头部,用来存储树的名字以及树的节点个数 BiNode *CreateBiTree(BiNode *T); //创建二叉树 status DestroyBiTree(Treehead *T); //销毁二叉树 status ClearBiTree(BiNode *T); //清空二叉树 status BiTreeEmpty(BiNode *T); //检查二叉树是否为空 status BiTreeDepth(BiNode *T); //检查树的深度 BiNode *LocateNode(BiNode *T, int e); //根据键值定位节点 status Assign(BiNode *T, int e, ElemType value); //修改节点的值 BiNode *GetSibling(BiNode *T, int e); //获得兄弟节点 status InsertNode(BiNode *T, int e, int LR, BiNode *c); //插入节点 BiNode *DeleteNode(BiNode *T, int e); //删除节点 status PreOrderTraverse(BiNode *T); //先序遍历 status InOrderTraverse(BiNode *T); //中序遍历 status PostOrderTraverse(BiNode *T); //后序遍历 status LevelOrderTraverse(BiNode *T); //层序遍历 status SaveBiTree(Treehead *T); //保存二叉树 BiNode *LoadBiTree(BiNode *T); //加载二叉树 BiNode *CreateBiTree2(BiNode *T, ElemType **p); BiNode visualprint(BiNode *T); /*功能函数声明*/ int main(void) { Treehead *head = NULL, *tail = NULL, *p = NULL, *q = NULL; int op = 1, id, renumber, key, LR; ElemType value; while (op) { system("cls"); printf("\n\n"); printf(" Menu for Binary Tree On Sequence Structure \n"); printf("-------------------------------------------------\n"); printf(" 1. CreateTree 9. InsertNode\n"); printf(" 2. DestroyTree 10. DeleteNode\n"); printf(" 3. ClearTree 11. PreOrderTraverse\n"); printf(" 4. TreeEmpty 12. InOrderTrabverse\n"); printf(" 5. TreeDepth 13.PostOrderTraverse\n"); printf(" 6. LocateNode 14.LevelOrderTraverse\n"); printf(" 7. AssignNode 15.SaveBiTree\n"); printf(" 8. GetSibling 16.LoadBiTree\n"); printf(" 0. Exit \n"); printf("-------------------------------------------------\n"); printf(" 请选择你的操作[0~15]:"); scanf("%d", &op); switch (op) { case 1: printf("请输入二叉树的前序序列:\n"); if (head == NULL) { head = (Treehead *)malloc(sizeof(Treehead)); tail = head; head->id = 1; p = head; head->pre = NULL; head->next = NULL; } else if (head != NULL) { tail = (Treehead *)malloc(sizeof(Treehead)); p->next = tail; tail->pre = p; tail->id = p->id + 1; p = tail; tail->next = NULL; } tail->root = NULL; tail->nodes = 0; q = head; if ((tail->root = CreateBiTree(tail->root)) != NULL) { tail->root->pre = NULL; printf("请输入二叉树的名称:\n"); fflush(stdin); gets(p->name); printf("二叉树创建成功!\n"); } else printf("二叉树创建失败!\n"); q->nodes = key_value; key_value = 0; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 2: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { if (q == head) head = head->next; if (q == tail) tail = tail->pre; DestroyBiTree(q); printf("二叉树删除成功!\n"); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 3: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { ClearBiTree(q->root); q->root = NULL; printf("二叉树清空成功!\n"); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 4: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { if (BiTreeEmpty(q->root) == OK) printf("二叉树%s是空树!\n", q->name); else printf("二叉树%s不是空树!\n", q->name); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 5: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { printf("二叉树的深度为:%d\n", BiTreeDepth(q->root)); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 6: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { printf("请输入需要查找节点的键值:\n"); scanf("%d", &key); BiNode *node; node = LocateNode(q->root, key); if (node != NULL) printf("该节点的值为:%c\n", node->elem); else printf("该节点不存在!\n"); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 7: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { printf("请输入需要修改的节点的键值:\n"); scanf("%d", &key); printf("输入修改后的节点值:\n"); fflush(stdin); scanf("%c", &value); if (Assign(q->root, key, value) == OK) printf("节点值成功修改!\n"); else printf("节点值修改失败!\n"); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 8: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { printf("请输入需要获取兄弟结点的键值:\n"); scanf("%d", &key); BiNode *bro; bro = GetSibling(q->root, key); if (bro == NULL) printf("该节点的兄弟节点不存在!\n"); else printf("该节点的兄弟节点的节点值为:%c\n", bro->elem); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 9: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { printf("请输入需要插入的的节点的键值:\n"); scanf("%d", &key); printf("请输入需要插入的子树,0代表左树,1代表右树\n"); scanf("%d", &LR); printf("请输入需要插入节点的值:\n"); fflush(stdin); scanf("%c", &value); BiNode *c = NULL; c = (BiNode *)malloc(sizeof(BiNode)); c->elem = value; c->left = NULL; c->right = NULL; c->pre = NULL; c->key = ++q->nodes; if (InsertNode(q->root, key, LR, c) == OK) printf("节点成功插入!\n"); else { printf("节点插入失败!\n"); q->nodes--; } } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 10: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { printf("请输入需要删除结点的键值:\n"); scanf("%d", &key); q->root = DeleteNode(q->root, key); q->nodes--; } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 11: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { PreOrderTraverse(q->root); } q = head; printf("\n请输入任意键继续\n"); getchar(); getchar(); break; case 12: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { InOrderTraverse(q->root); } q = head; printf("\n请输入任意键继续\n"); getchar(); getchar(); break; case 13: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { PostOrderTraverse(q->root); } q = head; printf("\n请输入任意键继续\n"); getchar(); getchar(); break; case 14: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { LevelOrderTraverse(q->root); } q = head; printf("\n请输入任意键继续\n"); getchar(); getchar(); break; case 15: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { SaveBiTree(q); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 16: printf("请输入二叉树的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("二叉树不存在!\n"); else { q->root = LoadBiTree(q->root); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 0: break; } //end of switch } //end of while printf("欢迎下次再使用本系统!\n"); return 0; } //end of main() BiNode *CreateBiTree(BiNode *T) { char ch; BiNode *trans = NULL; //用来存储函数的返回值的指针 fflush(stdin); //清空缓存区 scanf("%c", &ch); if (ch != '#') { if (!(T = (BiNode *)malloc(sizeof(BiNode)))) return NULL; T->elem = ch; T->key = ++key_value; trans = CreateBiTree(T->left); T->left = trans; if (trans != NULL) trans->pre = T; trans = CreateBiTree(T->right); T->right = trans; if (trans != NULL) trans->pre = T; } else { T = NULL; //若输入为‘#’,则返回NULL指针 } return T; } status DestroyBiTree(Treehead *T) { ClearBiTree(T->root); //调用清空函数把二叉树清空 if (T->pre != NULL) //删除存储树的表头 T->pre->next = T->next; if (T->next != NULL) T->next->pre = T->pre; free(T); T = NULL; return OK; } status ClearBiTree(BiNode *T) { if (T == NULL) return INFEASTABLE; else { ClearBiTree(T->left); ClearBiTree(T->right); free(T); T = NULL; } return OK; } status BiTreeEmpty(BiNode *T) //检查二叉树的头节点来判断是否为空树 { if (!T) return OK; else return ERROR; } status BiTreeDepth(BiNode *T) { int HL = 0, HR = 0, MAXH = 0; if (T != NULL) { //递归查找左右子树的深度,选取深度较大的子节点的深度加一作为返回值 HL = BiTreeDepth(T->left); HR = BiTreeDepth(T->right); MAXH = (HL > HR) ? HL : HR; return (MAXH + 1); } return MAXH; } BiNode *LocateNode(BiNode *T, int e) { if (T == NULL) return NULL; else { if (T->key == e) return T; else { //递归查找左右子树 BiNode *pl = NULL, *pr = NULL, *p; pl = LocateNode(T->left, e); pr = LocateNode(T->right, e); p = pl ? pl : pr; return p; } } } status Assign(BiNode *T, int e, ElemType value) { BiNode *p; p = LocateNode(T, e); //根据键值定位需要修改的节点 if (p == NULL) return ERROR; p->elem = value; return OK; } BiNode *GetSibling(BiNode *T, int e) { BiNode *p; p = LocateNode(T, e); if (p == NULL || p->pre == NULL) //判断该节点是否在树中 return NULL; if (p->pre->left == p) return p->pre->right; else if (p->pre->right == p) return p->pre->left; } status InsertNode(BiNode *T, int e, int LR, BiNode *c) { //根据传入的键值,以及LR判断插入左树还是右树,c为需要插入的节点 BiNode *p; p = LocateNode(T, e); if (p == NULL) return ERROR; if (LR == 0) { c->right = p->left; if (c->right != NULL) c->right->pre = c; p->left = c; c->pre = p; } else if (LR == 1) { c->right = p->right; if (c->right != NULL) c->right->pre = c; p->right = c; c->pre = p; } return OK; } BiNode *DeleteNode(BiNode *T, int e) { //根据传入的键值删除相应的节点 BiNode *p; p = LocateNode(T, e); if (p == NULL) return T; if (p->pre == NULL) { //该节点为根节点,分为四种情况,第一种左右子树都为空,第二种左子树为空,第三种右子树为空,第四种左右子树都不为空 if (p->left == NULL && p->right == NULL) { free(p); T = NULL; } if (p->right != NULL && p->left == NULL) { T = p->right; T->pre = NULL; free(p); } if (p->right == NULL && p->left != NULL) { T = p->left; T->pre = NULL; free(p); } else if (p->right != NULL && p->left != NULL) { T = p->left; BiNode *q = p->left; while (q->right != NULL) q = q->right; q->right = p->right; q->right->pre = q; T->pre = NULL; free(p); } } //若删除的为根节点,该节点没有父亲节点,故需要单独分情况讨论 else { //删除的节点不为根节点 if (p->left == NULL && p->right == NULL) { if (p->pre->left == p) p->pre->left = NULL; else p->pre->right = NULL; free(p); } if (p->right != NULL && p->left == NULL) { if (p->pre->left == p) p->pre->left = p->right; else p->pre->right = p->right; free(p); } if (p->right == NULL && p->left != NULL) { if (p->pre->left == p) p->pre->left = p->left; else p->pre->right = p->left; free(p); } else if (p->right != NULL && p->left != NULL) { if (p->pre->left == p) { p->pre->left = p->left; p->left->pre = p->pre; BiNode *q = p->left; while (q->right != NULL) q = q->right; q->right = p->right; p->right->pre = q; free(p); } if (p->pre->right == p) { p->pre->right = p->left; p->left->pre = p->pre; BiNode *q = p->left; while (q->right != NULL) q = q->right; q->right = p->right; p->right->pre = q; free(p); } } } printf("该节点成功删除!\n"); return T; } status PreOrderTraverse(BiNode *T) { //利用堆栈实现 BiNode *ptr[100]; int top = -1; BiNode *pt = T; ptr[++top] = pt; while (top != -1) { pt = ptr[top--]; //每次栈顶元素出栈 printf("%c ", pt->elem); //输出 if (pt->right) ptr[++top] = pt->right; if (pt->left) ptr[++top] = pt->left; } return OK; } status InOrderTraverse(BiNode *T) { //利用递归实现 if (T != NULL) { InOrderTraverse(T->left); printf("%c ", T->elem); InOrderTraverse(T->right); } return OK; } status PostOrderTraverse(BiNode *T) { //利用递归实现 if (T != NULL) { PostOrderTraverse(T->left); PostOrderTraverse(T->right); printf("%c ", T->elem); } return OK; } status LevelOrderTraverse(BiNode *T) { //利用队列实现层序遍历 BiNode queue[100], *front = queue, *back = queue; if (T != NULL) { *back = *T; back++; while (front != back) { if (front->left != NULL) { *back = *front->left; back++; } if (front->right != NULL) { *back = *front->right; back++; } printf("%c ", front->elem); front++; } } return OK; } status SaveBiTree(Treehead *T) { FILE *fp; char filename[30]; printf("input file name: "); scanf("%s", filename); // 写文件 if ((fp = fopen(filename, "wb")) == NULL) //文件打开失败 { printf("File open error\n "); return 1; } ElemType a; BiNode *ptr[100]; int top = -1; BiNode *pt = T->root; ptr[++top] = pt; while (top != -1) { pt = ptr[top--]; //每次栈顶元素出栈 if (pt) a = pt->elem; else a = '#'; fwrite(&a, sizeof(ElemType), 1, fp); if (pt->right) ptr[++top] = pt->right; else if (pt->elem != '#' && pt->right == NULL) { ptr[++top] = (BiNode *)malloc(sizeof(BiNode)); ptr[top]->elem = '#'; ptr[top]->left = NULL; ptr[top]->right = NULL; } if (pt->left) ptr[++top] = pt->left; else if (pt->elem != '#' && pt->left == NULL) { ptr[++top] = (BiNode *)malloc(sizeof(BiNode)); ptr[top]->elem = '#'; ptr[top]->left = NULL; ptr[top]->right = NULL; } } fclose(fp); printf("文件成功保存!\n"); return OK; } BiNode *LoadBiTree(BiNode *T) { FILE *fp; char filename[30]; printf("input file name: "); scanf("%s", filename); if ((fp = fopen(filename, "rb")) == NULL) { printf("File open error\n "); return NULL; } BiNode *p = T; ElemType a[100], *b; b = a; while (fread(b, sizeof(ElemType), 1, fp)) { b++; } b = a; T = CreateBiTree2(T, &b); fclose(fp); return T; } BiNode *CreateBiTree2(BiNode *T, ElemType **p) { //利用递归实现二叉树的加载,该函数使用了二级指针 char ch; BiNode *trans = NULL; ch = **p; ElemType *q = *p; q = q + 1; *p = q; if (ch != '#') { if (!(T = (BiNode *)malloc(sizeof(BiNode)))) return NULL; T->elem = ch; T->key = ++key_value; trans = CreateBiTree2(T->left, p); T->left = trans; if (trans != NULL) trans->pre = T; trans = CreateBiTree2(T->right, p); T->right = trans; if (trans != NULL) trans->pre = T; } else { T = NULL; } return T; } BiNode visualprint(BiNode *T){ int i=pow(2,BiTreeDepth(T)),n=2,k=0; BiNode queue[100], *front = queue, *back = queue; if (T != NULL) { *back = *T; back++; while (front != back) { if (front->left != NULL) { *back = *front->left; back++; } if (front->right != NULL) { *back = *front->right; back++; } while(k<i/n) printf(" "); printf("%c", front->elem); front++; } } }<file_sep>/数据结构试验/Graph.c /*Graph On Adjacency List*/ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <string.h> #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 #define DG 1 #define DN 2 #define UDG 3 #define UDN 4 //常量定义 #define INITLENGTH 80 #define INCREMENT 20 #define MAXVERTEXNUM 20 int visit[20]; typedef int status; typedef int ElemType; typedef int KeyType;//数据元素类型定义 typedef struct ArcNode { //弧度定义 int rad; struct ArcNode *next; }ArcNode; typedef struct Vertex { //顶点定义 char data; int key; struct ArcNode *firstArc; }Vertex; typedef struct Graph{ //图定义 struct Vertex elem[MAXVERTEXNUM]; char name[100]; int vernum; //顶点数 int arcnum; //弧度数 int id; //表示该图的id值 struct Graph *next; struct Graph *pre; }Graph; status CreateGraph(char value[],int arcnode[],int vnum,int arcnum,Graph *a); status DestroyGraph(Graph *a); Vertex *LocateVex(Graph *a,int key); status PutVex (Graph *a,int key,char value); Vertex *FirstAdjVex(Graph *a,int key); Vertex *NextAdjVex(Graph *a,int v,int w); status InsertVex(Graph *a,char v); status DeleteVex(Graph *a,int v); //v是删除节点的键值 status InsertArc(Graph *a,int v,int w); status DeleteArc(Graph *a,int v,int w); status DFSTraverse(Graph *a); void DFS(Graph *a,int v); status BFSTraverse(Graph *a); void BFS(int i,Graph *a); status SaveGraph(Graph *a); status LoadGraph(Graph *a); int main(void) { Graph *head=NULL,*tail=NULL,*p=NULL,*q=NULL; int op = 1,vnum=0,anum=0,i=0,id=0,key_value; while (op) { system("cls"); printf("\n\n"); printf(" Menu for Digraph On Sequence Structure \n"); printf("-------------------------------------------------\n"); printf(" 1. CreateGraph 9. InsertArc\n"); printf(" 2. DestroyGraph 10. DeleteArc\n"); printf(" 3. LocateVex 11. DFSTraverse\n"); printf(" 4. PutVex 12. BFSTrabverse\n"); printf(" 5. FirstAdjVex 13.SaveGraph\n"); printf(" 6. NextAdjVex 14.LoadGraph\n"); printf(" 7. InsertVex \n"); printf(" 8. DeleteVex \n"); printf(" 0. Exit \n"); printf("-------------------------------------------------\n"); printf(" 请选择你的操作[0~15]:"); scanf("%d", &op); switch (op) { case 1: if(head==NULL){ head=(Graph *)malloc(sizeof(Graph)); tail=head; head->id = 1; p=head; head->pre=NULL; head->next=NULL; } else if (head != NULL) { tail = (Graph *)malloc(sizeof(Graph)); p->next = tail; tail->pre = p; tail->id = p->id + 1; p = tail; tail->next = NULL; } q = head; printf("请输入图的名称:\n"); fflush(stdin); gets(tail->name); printf("请输入顶点数和边数:\n"); scanf("%d %d",&vnum,&anum); char a[1000]; int b[1000]; printf("请输入顶点的值:\n"); fflush(stdin); for(i=0;i<vnum;i++){ scanf("%c",&a[i]); fflush(stdin); } printf("请输入弧的信息(a,b):\n"); for(i=0;i<anum*2;i++){ scanf("%d",&b[i]); scanf("%d",&b[++i]); } CreateGraph(a,b,vnum,anum,tail); printf("图%s创建成功!\n",tail->name); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 2: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { if (q == head) head = head->next; if (q == tail) tail = tail->pre; DestroyGraph(q); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 3: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { printf("请输入需要查找的顶点的键值:\n"); scanf("%d",&key_value); Vertex *node=NULL; node=LocateVex(q,key_value); if(node==NULL||node->key==-1) printf("该节点不存在!\n"); else printf("该顶点的值为%c\n",node->data); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 4: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { char ch; printf("请输入需要修改的顶点的键值:\n"); scanf("%d",&key_value); printf("请输入修改后的节点的值:\n"); fflush(stdin); scanf("%c",&ch); if(PutVex(q,key_value,ch)==ERROR) printf("修改失败!\n"); else printf("修改成功\n"); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 5: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { Vertex *p=NULL; printf("请输入需要寻找的弧度的顶点的键值:\n"); scanf("%d",&key_value); p=FirstAdjVex(q,key_value); if(p==NULL) printf("不存在第一邻接点!\n"); else printf("第一邻接点值为:%c\n",p->data); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 6: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { Vertex *p=NULL; int v,w; printf("请输入需要寻找下一邻接点的两个顶点的键值:(a,b)\n"); scanf("%d %d",&v,&w); p=NextAdjVex(q,v,w); if(p==NULL) printf("不存在下一邻接点!\n"); else printf("下一邻接点值为:%c\n",p->data); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 7: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { char ch; int re; printf("请输入需要添加的点的值:\n"); fflush(stdin); scanf("%c",&ch); re=InsertVex(q,ch); if(re==OK) printf("节点成功添加!\n"); else printf("节点添加失败\n"); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 8: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { int re,key; printf("请输入需要删除的顶点的键值:\n"); scanf("%d",&key); re=DeleteVex(q,key); if(re==OK) printf("该节点成功删除!\n"); else printf("该节点删除失败!\n"); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 9: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { int v,w,re; printf("请输入需要插入的弧的信息:(a,b)\n"); scanf("%d %d",&v,&w); re=InsertArc(q,v,w); if(re==OK) printf("弧成功插入!\n"); else printf("弧插入失败!\n"); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 10: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { int v,w,re; printf("请输入需要删除的弧的信息:(a,b)\n"); scanf("%d %d",&v,&w); re=DeleteArc(q,v,w); if(re==OK) printf("弧成功删除!\n"); else printf("弧删除失败!\n"); } q = head; printf("请输入任意键继续\n"); getchar(); getchar(); break; case 11: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { DFSTraverse(q); } q = head; printf("\n请输入任意键继续\n"); getchar(); getchar(); break; case 12: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { BFSTraverse(q); } q = head; printf("\n请输入任意键继续\n"); getchar(); getchar(); break; case 13: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { SaveGraph(q); } q = head; printf("\n请输入任意键继续\n"); getchar(); getchar(); break; case 14: printf("请输入图的id:\n"); scanf("%d", &id); while (q != NULL && q->id != id) q = q->next; if (q == NULL) printf("图不存在!\n"); else { LoadGraph(q); } q = head; printf("\n请输入任意键继续\n"); getchar(); getchar(); break; case 15: printf("请输入任意键继续\n"); getchar(); getchar(); break; case 16: printf("请输入任意键继续\n"); getchar(); getchar(); break; case 0: break; } //end of switch } //end of while printf("欢迎下次再使用本系统!\n"); return 0; } //end of main() status CreateGraph(char value[],int arcnode[],int vnum,int arcnum,Graph *a){ if(a==NULL) return ERROR; int i; ArcNode *p=NULL; a->vernum=vnum; a->arcnum=arcnum; for(i=0;i<a->vernum;i++){ (a->elem+i)->data=value[i]; (a->elem+i)->firstArc=NULL; (a->elem+i)->key=i+1; } for(i=0;i<a->arcnum*2;i++){ p=(struct ArcNode *)malloc(sizeof(ArcNode)); p->next=a->elem[arcnode[i]-1].firstArc; a->elem[arcnode[i]-1].firstArc=p; p->rad=arcnode[++i]; } return OK; } status DestroyGraph(Graph *a){ if (a->pre != NULL) //删除存储树的表头 a->pre->next = a->next; if (a->next != NULL) a->next->pre = a->pre; printf("图%s删除成功!\n",a->name); free(a); a = NULL; return OK; } Vertex *LocateVex(Graph *a,int key){ int i; for(i=0;i<a->vernum;i++) { if(key==(a->elem+i)->key) return (a->elem+i); } return NULL; } status PutVex (Graph *a,int key,char value){ Vertex *p=NULL; p=LocateVex(a,key); if(p==NULL) return ERROR; p->data=value; return OK; } Vertex *FirstAdjVex(Graph *a,int key){ Vertex *p=NULL,*q=NULL; p=LocateVex(a,key); if(p==NULL) return NULL; if(p->firstArc==NULL) return NULL; else{ q=LocateVex(a,p->firstArc->rad); return q; } } Vertex *NextAdjVex(Graph *a,int v,int w){ Vertex *p=LocateVex(a,v); if(p==NULL) return NULL; ArcNode *q=p->firstArc; while(q!=NULL){ if(q->rad==w){ if(q->next==NULL) return NULL; else return LocateVex(a,q->next->rad); } else q=q->next; } if(q==NULL) return NULL; } status InsertVex(Graph *a,char v){ if(a->vernum>=MAXVERTEXNUM) return ERROR; a->elem[a->vernum].data=v; a->elem[a->vernum].firstArc=NULL; a->elem[a->vernum].key=a->elem[a->vernum-1].key+1; a->vernum++; return OK; } status DeleteVex(Graph *a,int v){ int i; for(i=1;i<=a->vernum;i++){ DeleteArc(a,v,i); DeleteArc(a,i,v); } Vertex *p=NULL; p=LocateVex(a,v); if(p==NULL) return ERROR; while(a->elem[a->vernum].key!=p->key){ p->data=(p+1)->data; p->key=(p+1)->key; p->firstArc=(p+1)->firstArc; p=p+1; } a->vernum--; return OK; } status InsertArc(Graph *a,int v,int w){ Vertex *q=LocateVex(a,v); if(q==NULL) return ERROR; ArcNode *p=q->firstArc; while(p!=NULL){ if(p->rad==w) return ERROR; p=p->next; } p=(ArcNode *)malloc(sizeof(ArcNode)); p->rad=w; p->next=q->firstArc; q->firstArc=p; a->arcnum++; return OK; } status DeleteArc(Graph *a,int v,int w){ Vertex *q=LocateVex(a,v); if(q==NULL) return ERROR; else{ ArcNode *p=q->firstArc,*ql=NULL; if(p==NULL) return OK; if(p->rad==w){ q->firstArc=p->next; free(p); a->arcnum--; p=NULL; return OK; } while(p->next!=NULL){ if(p->next->rad==w) break; p=p->next; } if(p->next==NULL) return OK; if(p->next->rad==w){ ql=p->next; p->next=ql->next; free(ql); a->arcnum--; ql=NULL; } return OK; } } status DFSTraverse(Graph* a) { int v=0; for(v=0;v<a->vernum;v++) visit[v]=0; for(v=0;v<a->vernum;v++){ if(!visit[v]) DFS(a,v); } return OK; } void DFS(Graph *a,int v){ visit[v]=1; printf("%c ",a->elem[v].data); int w=0; ArcNode *p=a->elem[v].firstArc; while(p!=NULL){ Vertex *q=NULL; q=LocateVex(a,p->rad); for(w=0;w<a->vernum;w++){ if(a->elem[w].key==q->key) break; } if(!visit[w]) DFS(a,w); p=p->next; } } status BFSTraverse(Graph* a) { int v=0,w; for(v=0;v<a->vernum;v++) visit[v]=0;; Vertex *queue[20],*pt=NULL,*front=queue,*back=queue; for(v=0;v<a->vernum;v++){ if(!visit[v]){ *back=a->elem[v]; back++; while(front!=back){ ArcNode *q=front->firstArc; for(w=0;w<a->vernum;w++){ if(a->elem[w].key==front->key) break; } if(!visit[w]) printf("%c ",front->data); visit[w]=1; front++; while(q!=NULL){ *back=*LocateVex(a,q->rad); back++; q=q->next; } } } } return OK; } status SaveGraph(Graph *a) { FILE *fp; char filename[30]; printf("input file name: "); scanf("%s", filename); // 写文件 if ((fp = fopen(filename, "wb")) == NULL) //文件打开失败 { printf("File open error\n "); return 1; } fwrite(&a->vernum, sizeof(ElemType), 1, fp); fwrite(&a->arcnum, sizeof(ElemType), 1, fp); int i; for(i=0;i<a->vernum;i++) { fwrite(&(a->elem[i].data),sizeof(char),1,fp); fwrite(&(a->elem[i].key),sizeof(int),1,fp); } for(i=0;i<a->arcnum;i++){ ArcNode *p=a->elem[i].firstArc; while(p!=NULL) { fwrite(&(a->elem[i].key),sizeof(int),1,fp); fwrite(&(p->rad),sizeof(int),1,fp); p=p->next; } } fclose(fp); printf("文件成功保存!\n"); return OK; } status LoadGraph(Graph *a){ FILE *fp; char filename[30]; printf("input file name: "); scanf("%s", filename); if ((fp = fopen(filename, "rb")) == NULL) { printf("File open error\n "); return ERROR; } int i,vnum,anum; fread(&(a->vernum), sizeof(int), 1, fp); fread(&(a->arcnum), sizeof(int), 1, fp); if(a==NULL) return ERROR; ArcNode *p=NULL; for(i=0;i<a->vernum;i++){ fread(&((a->elem+i)->data), sizeof(char), 1, fp); fread(&((a->elem+i)->key), sizeof(int), 1, fp); (a->elem+i)->firstArc=NULL; } int b[100]; for(i=0;i<a->arcnum*2;i++){ fread(&b[i],sizeof(int),1,fp); } for(i=0;i<a->arcnum*2;i++){ p=(struct ArcNode *)malloc(sizeof(ArcNode)); p->next=LocateVex(a,b[i])->firstArc; LocateVex(a,b[i])->firstArc=p; p->rad=b[++i]; } fclose(fp); return OK; }<file_sep>/README.md # data_structure-in-HUST # 华中科技大学数据结构实验以及课程设计 ## 一.课设 ### 文件 #### 1.base文件拿频次做的,效果不好 #### 2.test文件拿最简单的变元选取策略做的,效果反而不错 #### 3.binary——puzzle是exe文件生成的数独cnf子句集 ## 二.数据结构试验 ### 文件 #### 1.顺序表 #### 2.单链表 #### 3.树 #### 4.图 <file_sep>/数据结构试验/linear_table.c /* Linear Table On sequence Structure */ #include <stdio.h> #include <malloc.h> #include <stdlib.h> /*---------page 10 on textbook ---------*/ #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASTABLE -1 #define OVERFLOW -2 typedef int status; typedef int ElemType; //数据元素类型定义 /*-------page 22 on textbook -------*/ #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 typedef struct { //顺序表(顺序结构)的定义 ElemType *elem; int length; int listsize; } SqList; /*-----page 19 on textbook ---------*/ status InitList(SqList *L); status DestroyList(SqList *L); status ClearList(SqList *L); status ListEmpty(SqList *L); int ListLength(SqList *L); status GetElem(SqList *L, int i, ElemType *e); int LocateElem(SqList *L, ElemType e); status PriorElem(SqList *L, ElemType cur, ElemType *pre_e); status NextElem(SqList *L, ElemType cur, ElemType *next_e); status ListInsert(SqList *L, int i, ElemType e); status ListDelete(SqList *L, ElemType *e, int i); status ListTrabverse(SqList L); status LoadList(SqList *L); status SaveList(SqList *L); status InputData(SqList *L); /*功能函数声明*/ int main(void) { SqList L[3] = {0}; int op = 1, renumber, flag, mail, id = 0; while (op) { system("cls"); printf("\n\n"); printf(" Menu for Linear Table On Sequence Structure \n"); printf("-------------------------------------------------\n"); printf(" 1. InitList 8. PriorElem\n"); printf(" 2. DestroyList 9. NextElem\n"); printf(" 3. ClearList 10. ListInsert\n"); printf(" 4. ListEmpty 11. ListDelete\n"); printf(" 5. ListLength 12. ListTrabverse\n"); printf(" 6. GetElem 13.LoadList\n"); printf(" 7. LocateElem 14.SaveList\n"); printf(" 0. Exit 15.InputData\n"); printf("-------------------------------------------------\n"); printf(" 请选择你的操作[0~15]:"); scanf("%d", &op); switch (op) { case 1: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else if (InitList(L + id - 1) == OK) { printf("线性表创建成功!\n"); } else printf("线性表创建失败!\n"); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 2: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else if ((renumber = DestroyList(L + id - 1)) == OK) { printf("线性表删除成功!\n"); L->elem = NULL; } else if (renumber == INFEASTABLE) printf("线性表不存在!\n"); else printf("线性表删除失败!\n"); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 3: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else if ((renumber = ClearList(L + id - 1)) == OK) printf("线性表清除成功!\n"); else if (renumber == INFEASTABLE) printf("线性表是空的!\n"); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 4: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else if ((renumber = ListEmpty(L + id - 1)) == INFEASTABLE) printf("线性表不存在!\n"); else if (renumber == TRUE) printf("线性表是空的!\n"); else printf("线性表不是空的!\n"); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 5: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else if ((renumber = ListLength(L + id - 1)) != INFEASTABLE) printf("线性表长度为:%d\n", renumber); else printf("线性表不存在!\n"); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 6: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("请输入元素位置"); scanf("%d", &flag); if ((renumber = GetElem(L + id - 1, flag, &mail)) == OK) printf("位置%d的元素是%d\n", flag, mail); else if (renumber == ERROR) printf("该位置越界!\n"); else printf("线性表不存在!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 7: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("输入需要定位的元素:"); scanf("%d", &flag); if ((renumber = LocateElem(L + id - 1, flag)) > 0) printf("匹配成功,该元素位置为:%d\n", renumber); else if (renumber == ERROR) printf("匹配失败!\n"); else printf("线性表不存在!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 8: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("输入需要寻找前驱的元素:"); scanf("%d", &flag); if ((renumber = PriorElem(L + id - 1, flag, &mail)) == OK) printf("该数据的前驱元素为:%d\n", mail); else if (renumber == ERROR) printf("该元素没有前驱元素\n"); else printf("线性表不存在!\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 9: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("输入需要寻找后继的元素:"); scanf("%d", &flag); if ((renumber = NextElem(L + id - 1, flag, &mail)) == OK) printf("该数据的后继元素为:%d\n", mail); else if (renumber == ERROR) printf("该数据没有后继元素\n"); else printf("线性表不存在\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 10: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("请输入需要插入元素的位置:"); scanf("%d", &flag); printf("请输入插入元素的值"); scanf("%d", &mail); if ((renumber = ListInsert(L + id - 1, flag, mail)) == OK) printf("插入成功!\n"); else if (renumber == OVERFLOW) printf("存储分配失败\n"); else if (renumber == ERROR) printf("插入元素的位置输入不合法\n"); else printf("线性表不存在\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 11: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else { printf("请输入需要删除的元素的位置:"); scanf("%d", &flag); if ((renumber = ListDelete(L + id - 1, &mail, flag)) == OK) printf("该节点删除成功,删除的节点的值为:%d\n", mail); else if (renumber == ERROR) printf("删除元素的位置输入不合法\n"); else printf("线性表不存在\n"); } printf("请输入任意键继续\n"); getchar(); getchar(); break; case 12: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else if (ListTrabverse(L[id - 1])) printf("线性表不存在!\n"); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 13: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else if ((renumber = LoadList(L + id - 1)) == OK) printf("线性表成功赋值\n"); else if (renumber == 1) printf("无法打开文件\n"); else printf("线性表不存在\n"); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 14: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) printf("超出id范围\n"); else if ((renumber = SaveList(L + id - 1)) == OK) printf("文件成功保存\n"); else if (renumber == 1) printf("无法打开文件\n"); else printf("线性表不存在\n"); printf("请输入任意键继续\n"); getchar(); getchar(); break; case 15: printf("请输入表的id值[1~3]:"); scanf("%d", &id); if (id > 3 || id < 0) { printf("超出id范围\n"); getchar(); } else if (InputData(L + id - 1) == OK) printf("数据成功输入\n"); else { printf("线性表不存在\n"); getchar(); } printf("请输入任意键继续\n"); getchar(); break; case 0: break; } //end of switch } //end of while printf("欢迎下次再使用本系统!\n"); return 0; } //end of main() /*--------page 23 on textbook --------------------*/ status InitList(SqList *L) //初始化表 { L->elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType)); //分配内存 if (!L->elem) //如果L分配失败,返回overflow exit(OVERFLOW); L->length = 0; L->listsize = LIST_INIT_SIZE; return OK; } status DestroyList(SqList *L) { if (!L->elem) return INFEASTABLE; L->listsize = L->length = 0; //把表长和空间清0 free(L->elem); //释放存储空间 return OK; } status ClearList(SqList *L) { //把表中的数据清除 if (!L->elem) return INFEASTABLE; L->length = 0; return OK; } status ListEmpty(SqList *L) { //检测线性表是否为空 if (!L->elem) return INFEASTABLE; if (L->length == 0) { return TRUE; } else { return FALSE; } } int ListLength(SqList *L) { //输出线性表长度 if (!L->elem) return INFEASTABLE; return L->length; } status GetElem(SqList *L, int i, ElemType *e) { if (!L->elem) return INFEASTABLE; if (i < 1 || i > L->length) return ERROR; // 判断位置是否越界,越界则返回错误 *e = *(L->elem + i - 1); //e变量用来存储该元素的值 return OK; } int LocateElem(SqList *L, ElemType e) { //e为需要定位的元素 if (!L->elem) return INFEASTABLE; int i; for (i = 1; i <= L->length; i++) { if (L->elem[i - 1] == e) //如果匹配成功,则返回该元素的位置 return i; } return ERROR; //匹配失败,返回ERROR } status PriorElem(SqList *L, ElemType cur, ElemType *pre_e) { //pre_e用来存储前驱存储的元素 if (!L->elem) return INFEASTABLE; int index = LocateElem(L, cur) - 1; //定义位置变量 if (index <= 0) return ERROR; *pre_e = *(L->elem + index - 1); //pre_e指针指向前驱元素 return OK; } status NextElem(SqList *L, ElemType cur, ElemType *next_e) { //next_e用来存储后继的元素 if (!L->elem) return INFEASTABLE; int index = LocateElem(L, cur); //定义位置变量 if (index < 0 || index >= L->length) return ERROR; *next_e = *(L->elem + index); //next_e指针指向后继元素 return OK; } status ListInsert(SqList *L, int i, ElemType e) { //在顺序线性表L中第i个位置之前插入新的元素e //i的合法值为1<=i<=L->length+1 ElemType *newbase; ElemType *p, *q; if (!L->elem) return INFEASTABLE; if (i < 1 || i > L->length + 1) return ERROR; //i值不合法 if (L->length >= L->listsize) { //当前存储空间已满,增加分配 newbase = (ElemType *)realloc(L->elem, (L->listsize + LISTINCREMENT) * sizeof(ElemType)); if (!newbase) return OVERFLOW; //存储分配失败 L->elem = newbase; //新的基址 L->listsize += LISTINCREMENT; //增加存储容量 } q = &(L->elem[i - 1]); //q为插入位置 for (p = &(L->elem[L->length]); p >= q; --p) //插入位置及之后的元素右移 *(p + 1) = *p; *q = e; //插入e ++L->length; //表长增1 return OK; } status ListDelete(SqList *L, ElemType *e, int i) { //删除表中的第i个元素,并用e返回其值 ElemType *p, *q; if (!L->elem) return INFEASTABLE; if ((i < 1) || (i > L->length)) return ERROR; //i值不合法 p = &(L->elem[i - 1]); //p为被删除元素的位置 *e = *p; //被删除元素的值赋给e q = L->elem + L->length - 1; //表尾元素的位置 for (++p; p <= q; ++p) *(p - 1) = *p; //被删除元素之后的元素左移 --L->length; //表长减一 return OK; } status ListTrabverse(SqList L) { if (!L.elem) return INFEASTABLE; int i; printf("\n-----------all elements -----------------------\n"); for (i = 0; i < L.length; i++) printf("%d ", L.elem[i]); printf("\n------------------ end ------------------------\n"); return L.length; } status SaveList(SqList *L) { if (!L->elem) return INFEASTABLE; FILE *fp; char filename[30]; printf("input file name: "); scanf("%s", filename); // 写文件 if ((fp = fopen(filename, "wb")) == NULL) //文件打开失败 { printf("File open error\n "); return 1; } fwrite(L->elem, sizeof(ElemType), L->length, fp); fclose(fp); return OK; } status LoadList(SqList *L) { if (!L) // 线性表未创建 return INFEASTABLE; else if (!L->elem) return INFEASTABLE; //读文件 FILE *fp; char filename[30]; printf("input file name: "); scanf("%s", filename); L->length = 0; if ((fp = fopen(filename, "rb")) == NULL) { printf("File open error\n "); return 1; } while (fread(&(L->elem[L->length]), sizeof(ElemType), 1, fp)) L->length++; fclose(fp); return OK; } status InputData(SqList *L) { if (!L->elem) return INFEASTABLE; char str[100]; int i = 0, count = 0, a[100] = {0}, symbol = 0; printf("请输入一串元素\n"); getchar(); gets(str); while (1) { while (str[i] && (str[i] < '0' || str[i] > '9') && str[i] != '-') //判断负数的情况 i++; if (str[i]) { if (str[i] == '-') { symbol = 1; i++; } while (str[i] >= '0' && str[i] <= '9') { a[count] = 10 * a[count] + str[i] - '0'; i++; } if (symbol == 1) a[count] = -a[count]; symbol = 0; count++; } else break; } for (i = 0; i < count; i++) { //接着之前的数据在之后继续加新的数据 L->elem[L->length + i] = a[i]; } L->length += i; return OK; }
402a7a867c3b2e4494ef0863105f9beaf3f9b03f
[ "Markdown", "C", "C++" ]
6
C++
yux20000304/data_structure-in-HUST
97f06c66cdd7b104a266ec329e2f9947208e2a2c
7b0e47928ce74ff6c9c889d5212dad77a7e8d87c
refs/heads/master
<file_sep>package com.collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; public class HashSetExample { public static void main(String args[]) { System.out.println("Hello HashSet/HashMap Example"); // Properties // #1. HashSet cannot contain duplicate values. // #2. HashSet allows null value. // #3. HashSet is an unordered collection. It does not maintain the order in which the elements are inserted. // #4. HashSet internally uses a HashMap to store its elements. // #5. HashSet is not thread-safe. If multiple threads try to modify a HashSet at the same time, then the final outcome is not-deterministic. You must explicitly synchronize concurrent access to a HashSet in a multi-threaded environment. // Create Hash Set Set<String> hashSet = new HashSet<>(); hashSet.add("Krishna"); hashSet.add("Prasad"); // Adding duplicate elements will be ignored hashSet.add("Prasad"); System.out.print("HashSet: "); System.out.println(hashSet); // Constructors in HashSet: // // HashSet h = new HashSet(); // Default initial capacity is 16 and default load factor is 0.75. // HashSet h = new HashSet(int initialCapacity); // default loadFactor of 0.75 // HashSet h = new HashSet(int initialCapacity, float loadFactor); // HashSet h = new HashSet(Collection C); // Example: If internal capacity is 16 and load factor is 0.75 then, number of buckets will automatically get increased when the table has 12 elements in it. HashMap<String, String> hashMap = new HashMap<>(); hashMap.put("1", "Krishna"); hashMap.put("2", "Prasad"); hashMap.put("0", "0th ele"); hashMap.put("0", "0th ele, other"); hashMap.put("11", "11th ele"); System.out.print("HashMap: "); System.out.print(hashMap); } } <file_sep>/* * Copyright 2012-2019 the original author or authors. * * 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 * * https://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 sample.data.mongo.main; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; import org.springframework.web.client.RestTemplate; import sample.data.mongo.models.ChangeEvent; import sample.data.mongo.models.Stores; import sample.data.mongo.repository.SpringDataRepository; import sample.data.mongo.services.CustomFindQueryExecutor; import sample.data.mongo.services.LookupAggregation; import sample.data.mongo.services.SystemOsLevelInfo; import sample.data.mongo.services.TextSearchQueryExample; @SpringBootApplication(scanBasePackages = "sample.data.mongo") @EnableConfigurationProperties @EnableMongoRepositories(basePackages = "sample.data.mongo.repository") public class Application { @Autowired private MongoOperations mongoOperation; @Autowired private MongoTemplate mongoTemplate; @Autowired private LookupAggregation lookupAggregation; @Autowired private TextSearchQueryExample textSearchQueryExample; @Autowired private CustomFindQueryExecutor customFindQueryExecutor; @Autowired private SystemOsLevelInfo systemOsLevelInfo; @Bean public RestTemplate restTemplate() { return new RestTemplate(); } private static final Logger logger = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean CommandLineRunner init(final SpringDataRepository springDataRepository) { return new CommandLineRunner() { public void run(String... args) throws Exception { // System.out.println("===================="); // System.out.println("Get the value by findFieldDataByRegexMatch"); // System.out.println(springDataRepository.findFieldDataByRegexMatch("Org1", "key2", "iso")); // // System.out.println(springDataRepository.getDataByQueryAnnotation("Org1", "key2", "iso.*" )); // System.out.println("===================="); // // System.out.println("=================Simple Example============="); //// System.out.println(springDataRepository.getDataByQueryRegex()); // System.out.println("=================Simple Example============="); //// // // System.out.println("Heelo"); // // List<Criteria> criteriaListAnd = new ArrayList<>(); // Criteria criteria = new Criteria(); // String pattern = "/iso/i"; // String key = "key2"; // // criteriaListAnd.add(Criteria.where("organization").is("Org1")); // criteriaListAnd.add(Criteria.where("active").is(true)); // criteriaListAnd.add(Criteria.where("fields").elemMatch(Criteria.where("key").is(key).and("value").regex(pattern))); // criteria.andOperator(criteriaListAnd.toArray(new Criteria[criteriaListAnd.size()])); // // Query query = new Query(); // query.addCriteria(criteria); // List<Springdata> objects = mongoTemplate().find(query, Springdata.class); // Function for Questions: https://stackoverflow.com/questions/59034265/mongotemplate-pull-query // stackoverflowQ59034265(); // https://stackoverflow.com/questions/59167359/why-does-spring-data-fail-on-date-queries // stackoverflow59167359(); // // Insert and return // Customer newCustomer = new Customer("First Name", "Last Name", "ABC address"); // customerRepository.insert(newCustomer); // System.out.println("newCustomer object updated, you can return from here "); // System.out.println(newCustomer); // // return newCustomer; // // // find and update and then return // Query query = new Query(); // query.addCriteria(Criteria.where("firstName").is("First Name")); // // Update update = new Update(); // update.set("lastName", "modified last name"); // // FindAndModifyOptions options = new FindAndModifyOptions(); // options.upsert(true); // options.returnNew(true); // // try { // Customer modifiedCustomer = mongoOperation // .findAndModify(query, update, options, Customer.class); // // Modified data // System.out.println("Modified Custom data\n"); // System.out.println(modifiedCustomer); // // Return from here; // } catch (Exception e) { // System.out.println(e.getMessage()); // throw e; // } //https://stackoverflow.com/questions/59495531/about-springdata-mongodb-aggregation // lookupAggregation.LookupAggregationExample(); // https://stackoverflow.com/questions/59467010/creating-a-repository-query-that-include-textcriteria-and-one-other-field // textSearchQueryExample.getCampaignWithSearchQuery(); // https://stackoverflow.com/questions/59469988/how-do-i-execute-a-mongodb4-2-js-script-using-the-spring-data-mongodb-or-java-mo // customFindQueryExecutor.RunCustomQuery(); // https://stackoverflow.com/questions/12807797/java-get-available-memory systemOsLevelInfo.getMemoryInfo(); } public void stackoverflowQ59034265() { System.out.println(mongoTemplate.getDb().getName()); for (String name : mongoTemplate.getDb().listCollectionNames()) { System.out.println(name); } List<Stores> storesList = mongoTemplate.find(new Query(), Stores.class); for(Stores stores : storesList) { System.out.println(stores.toString()); } mongoTemplate.updateMulti(new Query(), new Update().pull("vegetables", "squash"), "stores"); List<Stores> afterModificationStoresList = mongoTemplate.find(new Query(), Stores.class); for(Stores stores : afterModificationStoresList) { System.out.println(stores.toString()); } } }; } // https://stackoverflow.com/questions/59167359/why-does-spring-data-fail-on-date-queries public void stackoverflow59167359() { //Find change list query: Query: { "bappid" : "BAPP0131337", "changedOn" : { "$gte" : { "$date" : 1575418473670 } } }, Fields: { }, Sort: { } fetchChangeList("BAPP0131337", new Date(1543889916), null); } public List<ChangeEvent> fetchChangeList(String bappid, Date from, Date to) { Criteria criteria = null; criteria = Criteria.where("bappid").is(bappid); Query query = Query.query(criteria); if (from != null && to == null) { criteria = Criteria.where("changedOn").gte(from); query.addCriteria(criteria); } else if (to != null && from == null) { criteria = Criteria.where("changedOn").lte(to); query.addCriteria(criteria); } else if (from != null && to != null) { criteria = Criteria.where("changedOn").gte(from).lte(to); query.addCriteria(criteria); } logger.info("Find change list query: {}", query.toString()); List<ChangeEvent> result = mongoTemplate.find(query, ChangeEvent.class, "changeEvents"); logger.info("Result set is " + result.toString()); // return result; System.out.println(mongoTemplate.getDb().getName()); Query query1 = new Query(Criteria.where("bappid").is(bappid)); // Below commented query will not work // List<ChangeEvent> result1 = mongoTemplate.find(query, ChangeEvent.class); // Below query works fine: List<ChangeEvent> result1 = mongoTemplate.find(query1, ChangeEvent.class, "changeEvents"); logger.info("Result set is " + result1.toString()); // mongoTemplate.find return result1; } // @Bean // CommandLineRunner init(final CustomerRepository customerRepository) { // // // // //// System.out.println(customerRepository.findByFirstName("Alice")); // System.out.println(customerRepository.findByFirstName("Alice")); // // // return new CommandLineRunner() { // public void run(String... args) throws Exception { // // // Insert and return // Customer newCustomer = new Customer("First Name", "Last Name", "ABC address"); // customerRepository.insert(newCustomer); // System.out.println("newCustomer object updated, you can return from here "); // System.out.println(newCustomer); // // return newCustomer; // // // find and update and then return // Query query = new Query(); // query.addCriteria(Criteria.where("firstName").is("First Name")); // // Update update = new Update(); // update.set("lastName", "modified <NAME>"); // // FindAndModifyOptions options = new FindAndModifyOptions(); // options.upsert(true); // options.returnNew(true); // // try { // Customer modifiedCustomer = mongoOperation // .findAndModify(query, update, options, Customer.class); // // Modified data // System.out.println("Modified Custom data\n"); // System.out.println(modifiedCustomer); // // Return from here; // } catch (Exception e) { // System.out.println(e.getMessage()); // throw e; // } // // // } // }; // // } } <file_sep>package sample.data.mongo.models; import java.util.Date; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.index.TextIndexed; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.format.annotation.DateTimeFormat; @Document(collection = "campaign") public class Campaign { @Id private String id; @Indexed @TextIndexed(weight = 1f) private String name; private String mediaLink; private String imageLink; @TextIndexed(weight = 2f) private String text; @TextIndexed(weight = 2f) private String target; private String ownerId; // Who can modify this except "MANAGER" private String useScope; // Who can Use this Campaign [me, dl, all] i.e. Visibility @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") private Date startOn; // @ this date the campaign becomes available and usable @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX") private Date expireOn; // @ this date the campaign becomes expired and not usable private Date timestamp; // Inserted the below records for verification purposes //db.campaign.insert({name:"Krishna", mediaLink:"www.abc.com", imageLink:"www.image.abc.com/a.jpg", // text: "Hello this is text field", target: "this is target one",ownerId:"12", startOn: new ISODate() }]) @Override public String toString() { return "Campaign{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", mediaLink='" + mediaLink + '\'' + ", imageLink='" + imageLink + '\'' + ", text='" + text + '\'' + ", target='" + target + '\'' + ", ownerId='" + ownerId + '\'' + ", useScope='" + useScope + '\'' + ", startOn=" + startOn + ", expireOn=" + expireOn + ", timestamp=" + timestamp + '}'; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMediaLink() { return mediaLink; } public void setMediaLink(String mediaLink) { this.mediaLink = mediaLink; } public String getImageLink() { return imageLink; } public void setImageLink(String imageLink) { this.imageLink = imageLink; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public String getOwnerId() { return ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; } public String getUseScope() { return useScope; } public void setUseScope(String useScope) { this.useScope = useScope; } public Date getStartOn() { return startOn; } public void setStartOn(Date startOn) { this.startOn = startOn; } public Date getExpireOn() { return expireOn; } public void setExpireOn(Date expireOn) { this.expireOn = expireOn; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } } <file_sep>package com.basics; import org.json.JSONException; import org.json.JSONObject; public class Main { public static void main(String[] args) throws JSONException { // write your code here JSONObject jsonObject = new JSONObject(); jsonObject.put("abc", "Krishna"); System.out.println(jsonObject.getString("abc")); System.out.println("Hello"); Integer integer = 0; integer = 4; System.out.println("Value of integer is " + integer); for (int i =0; i < 10; i++) { if (i < integer) { System.out.println("Less than 4"); } else { System.out.println("Greater than 4"); } System.out.println("Current value of i is " + i); } try { int j = 10000/integer; System.out.println("value of j is" + j); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>package javaStrings; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.stream.IntStream; public class RegexExamples { public static void main(String[] args) { // Scanner sc = new Scanner(System.in); String a = " ";//sc.next(); // String b = sc.next(); // sc.close(); // System.out.println(isAnagram("anagramm", "marganaa")); // System.exit(0); a = a.trim(); java.util.List<String> alist = Arrays.asList(a.split("[!,?._'@\\s]+")); System.out.println(alist); System.out.println(alist.size()); System.out.println(alist.isEmpty()); List<String> aaa = new ArrayList<>(); System.out.println(aaa.isEmpty()); if (a.isEmpty()) { System.out.println("aaaaaaaaaa"); } System.out.println(aaa.size()); a.charAt(0); a = a.toLowerCase(); System.out.println(a); java.util.Map<Character, Integer> aMap = new HashMap<>(); java.util.Map<Character, Integer> bMap = new HashMap<>(); System.out.println(aMap.getOrDefault('a', 0)); for(int i =0; i < a.length() -1; i++) { aMap.put(a.charAt(i), aMap.getOrDefault(a.charAt(i), 0) + 1); bMap.put(a.charAt(i), bMap.getOrDefault(a.charAt(i), 0) + 1); } System.out.println(aMap); System.out.println(bMap); if (aMap.equals(bMap)) { System.out.println("Two maps are equals"); } else { System.out.println("Not equals"); } System.exit(0); int[] sample = new int[]{1,20,3,4,5}; System.out.println("list: " + sample); int size = sample.length; int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1]) .toArray(); // Arrays.stream(reverseSample).map(i -> System.out.println(i)); System.out.println("updated list " + reverseSample.toString()); } } <file_sep>package concurrency.threads; public class RunnableExampleMain2 { public static void main(String[] args) { System.out.println("Executing program..."); // Create a new instance of our class that implements the Runnable interface. // This class can be provided as an argument to a Thread instance. RunnableExample2 r = new RunnableExample2(); // Create a new Thread instance, provide the task that we want to run // (by providing the Runnable as an argument) and give the thread a name. // Now we can use Thread.start() to run it! Thread thread1 = new Thread(r, "Thread 1"); thread1.start(); // We are creating a second thread. Take notice that we are // providing the same Runnable, so this thread will run the same task // as the first one. Thread thread2 = new Thread(r, "Thread 2"); thread2.start(); // Create a thread and provide the Runnable argument as an anonymous inner class. // Since we are creating the class "on the spot", we need to provide the implementation // of the run() method here. // This way is faster and more compact, but it lacks Reusability. Thread thread3 = new Thread(new Runnable() { @Override public void run() { // We are doing the same thing as with the MyRunnableImplementation class for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + "\twith Runnable: Inner class Runnable runs..." + i); } } }, "Thread 3"); Thread thread4 = new Thread(new Runnable() { @Override public void run() { // We are doing the same thing as with the MyRunnableImplementation class for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + "\twith Runnable: Inner class Runnable runs..." + i); } } }, "Thread 4"); thread3.start(); thread4.start(); } } <file_sep>package miniproject0.edu.coursera.concurrent.incrementExamples; public class IncrementTest { public static void main(String args[]) { Increment increment = new Increment(); for (int i = 0; i <= 1000; i++) { Thread t0 = new Thread(new ACounter(increment)); Thread t1 = new Thread(new ACounter(increment)); Thread t2 = new Thread(new ACounter(increment)); Thread t3 = new Thread(new BCounter(increment)); Thread t4 = new Thread(new BCounter(increment)); Thread t5 = new Thread(new BCounter(increment)); Thread t6 = new Thread(new BCounter(increment)); t0.start(); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); System.out.format("State of thread t0 %s, is %s%n", t0.getName(), t0.getState()); System.out.format("State of thread t1 %s, is %s%n", t1.getName(), t1.getState()); System.out.format("State of thread t3 %s, is %s%n", t2.getName(), t2.getState()); System.out.format("State of thread t4 %s, is %s%n", t3.getName(), t3.getState()); System.out.format("State of thread t5 %s, is %s%n", t4.getName(), t4.getState()); System.out.format("State of thread t6 %s, is %s%n", t5.getName(), t5.getState()); System.out.format("State of thread t7 %s, is %s%n", t6.getName(), t6.getState()); } System.out.format( "Value of simple counter after increment by A & B thread : %s%n", increment .getSimpleCounter()); System.out.format( "Value of synchronized counter after increment by A & B thread : %s%n", increment .getSynchronizedCounter()); System.out.format( "Value of volatile Counter after increment by A & B thread : %s%n%n", increment .getVolatileCounter()); System.out.format( "Value of AtomicIncrement Counter after increment by A & B thread : %s%n%n", increment .getAtomicInterger()); } } <file_sep>package com.generics; interface GenericInterface<T> { T genericMethod(T t); } <file_sep>package oops.Polymorphism; public class SuperClassA { public void add () { System.out.println(this.getClass().getName()); } } <file_sep>package memory.examples; import java.util.ArrayList; import java.util.List; public class SharingData { public static void main(String[] args) { List<String> myList = new ArrayList<>(); myList.add("One"); myList.add("Two"); myList.add("Three"); String one = myList.get(0); System.out.println(one); one = one + " changed"; System.out.println(one); printList(myList); printListLocalAccess(myList); } public static void printList(List<String> data) { System.out.println(data.getClass()); System.out.println(data); } public static void printListLocalAccess(List<String> data) { String value = data.get(1); System.out.println(value); value = "Changed from Two to this values"; System.out.println(value); data.add("Four"); printList(data); } } <file_sep>package kp.collectionutils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ArrayListExample { public static void main(String[] args) { // ArrayList arrayList = new ArrayList(); // arrayList.add("Krishna"); // arrayList.add("Prasad"); // //// System.out.println(arrayList.toArray().toString()); // Iterator it = arrayList.iterator(); // // while (it.hasNext()) { // System.out.println(it.next()); // } List<String> a = Arrays.asList((new String[]{"a", "b", "c"})); System.out.println(a); List<String> aa = Arrays.asList((new String[]{"a", "c"})); // Find the difference of a and aa i.e here only will be the ans b List<String> ans = a.stream() .filter(elm -> { return !aa.contains(elm); }) .collect(Collectors.toList()); System.out.println(ans); // Below removeAll not work // a.removeAll(aa); System.out.println(a); System.out.println(aa); //If we only want find missing values in a, you can do: List toReturn = new ArrayList(a); toReturn.removeAll(aa); System.out.println(toReturn); // System.out.println(aa); // // // String aaa[] = new String[]{"abc", "axys"}; // // System.out.println(Arrays.stream(aaa).findAny().get()); } } <file_sep>package com.generics; public class GenericImplementation implements GenericInterface<String> { @Override public String genericMethod(String o) { System.out.println("Implemented generic interface method, arguments: " + o.toString()); return "Success"; } } <file_sep>public class LinkedListMain { private static class Node<T> { T item; Node<T> next; Node(T item, Node<T> next) { this.item = item; this.next = next; } // public String toString() { // return item + " -> " + next; // } } private static class LinkedList<E> { private Node<E> head; private void addAtFirst(Node node) { if (this.head == null) { this.head = node; } else { node.next = this.head; this.head = node; } } private void addAtLast(Node node) { if (this.head == null) { this.head = node; } else { Node temp = this.head; while (temp.next != null) { System.out.println("Processing the node item " + temp.item); temp = temp.next; } temp.next = node; } } public void printLinkedList() { // System.out.println(this.head); Node temp = this.head; while (temp != null) { System.out.print(temp.item + "->"); temp = temp.next; } System.out.println("Null"); } } private Node head = null; public static void main(String[] args) { LinkedList linkedList = new LinkedList(); Node node = new Node<String>("4", null); Node node1 = new Node<String>("33", null); Node node2 = new Node<String>("89", null); Node node3 = new Node<String>("93", null); linkedList.addAtLast(node); linkedList.printLinkedList(); linkedList.printLinkedList(); linkedList.addAtLast(node1); linkedList.printLinkedList(); System.out.println(isCircularLinkedList(linkedList)); linkedList.addAtLast(node2); linkedList.printLinkedList(); linkedList.addAtLast(node3); linkedList.printLinkedList(); // Below addition of node 3 at first make the linkedList in circular linkedList. linkedList.addAtFirst(node3); // linkedList.printLinkedList(); System.out.println(isCircularLinkedList(linkedList)); } public static Boolean isCircularLinkedList(LinkedList linkedList) { Node temp1 = linkedList.head; Node temp2 = linkedList.head; while (temp1 != null & temp2 != null) { temp1 = temp1.next; if (temp2.next == null) { return false; } else { temp2 = temp2.next.next; } if (temp1 == temp2) { return true; } } return false; } } <file_sep>package com.oop.concepts; public class Complex implements Number<Complex> { private Double x; private Double y ; public Complex (Double x, Double y) { this.x = x; this.y = y; } @Override public String toString() { return "Complex{" + "x=" + x + ", y=" + y + '}'; } @Override public Complex add(Complex n) { return new Complex(this.x + n.x, this.y + n.y); } } <file_sep>package loadbalancer.round.robin.algorithm; import java.util.Random; import java.util.TreeMap; public class algoTreeMap { public static void main(String[] args) { // Declaring the tree map of Integer and String TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // assigning the values in the tree map // using put() treemap.put(20, "server 1"); // 20% traffic will goes to server 1 treemap.put(70, "server 2"); // 50% traffic will goes to server 2 treemap.put(100, "server 3");// 30% traffic will goes to server 3 int server1Counter = 0; int server2Counter = 0; int server3Counter = 0; for(int i =0; i<100; i++) { int rnd = (new Random()).nextInt(100); // System.out.println("The next server is : " + treemap.ceilingEntry(rnd).getValue()); String selectedServer = treemap.ceilingEntry(rnd).getValue(); if (selectedServer.equals("server 1")) { server1Counter++; } if (selectedServer.equals("server 2")) { server2Counter++; } if (selectedServer.equals("server 3")) { server3Counter++; } } System.out.println("server 1 selected " + server1Counter); System.out.println("server 2 selected " + server2Counter); System.out.println("server 3 selected " + server3Counter); } } <file_sep>package non.concurrency.threads; import java.util.Date; public class MyExampleMain1 { public static void main(String[] args) { long start = new Date().getTime(); for (int i = 0; i < 500; i++) { MyExample1 myExample1 = new MyExample1(10000000L + i); myExample1.reciprocalSum(); } long end = new Date().getTime(); //Total time consumed is ms 6945 --> with the MyRunnableExampleMain1 System.out.println("Total time consumed is ms " + (end - start)); // With this calss: Total time consumed is ms 49333 } } <file_sep>package com.ds; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; public class Main { public static void main(String[] args) { String cart = "[{\"size\":\"S\", \"id\":11}, {\"size\":\"8\", \"id\":19}]"; Type type = new TypeToken<ArrayList<CObject>>() { }.getType(); ArrayList<CObject> cObjectList = (new Gson()).fromJson(cart, type); System.out.println(cObjectList); System.out.println(cObjectList.size()); } public class CObject { private String id; private String size; public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getId() { return id; } public void setId(String id) { this.id = id; } @Override public String toString() { return "CObject{" + "id='" + id + '\'' + ", size='" + size + '\'' + '}'; } } } <file_sep>package com.generics; public class GenericTests { public static void main(String args[]) { GenericImplementation genericImplementation = new GenericImplementation(); System.out.println(genericImplementation.genericMethod("Hello")); } } <file_sep>package oops.overriding; import java.io.OutputStream; import java.io.IOException; public class BufferOutput { private OutputStream o; BufferOutput(OutputStream o) { this.o = o; } protected byte[] buf = new byte[512]; protected int pos = 0; public void putchar(char c) throws IOException { if (pos == buf.length) flush(); buf[pos++] = (byte)c; } public void putstr(String s) throws IOException { for (int i = 0; i < s.length(); i++) putchar(s.charAt(i)); } public void flush() throws IOException { o.write(buf, 0, pos); pos = 0; } } <file_sep>package memory.escaping.references; public class MainBook { public static void main(String[] args) { BookCollection bc = new BookCollection(); // bc.printAllBooks(); //get price of book called <NAME> in EUR System.out.println(bc.findBookByName("<NAME>").getPrice().convert("EUR")); System.out.println(bc.findBookByName("<NAME>").getPrice().convert("EUR")); System.out.println(bc.findBookByName("<NAME>").getPrice().convert("EUR")); // Without fixing the convert method all three above sentences print different price. // bc.printAllBooks(); } } <file_sep>package sample.data.mongo.services; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; import org.springframework.stereotype.Service; @Service public class SystemOsLevelInfo { public void getMemoryInfo() throws IOException { Runtime runtime = Runtime.getRuntime(); BufferedReader br = new BufferedReader( new InputStreamReader(runtime.exec("free -m").getInputStream())); String line; String memLine = ""; int index = 0; while ((line = br.readLine()) != null) { if (index ==1) { memLine = line; } index++; } // total used free shared buff/cache available // Mem: 15933 3153 9683 310 3097 12148 // Swap: 3814 0 3814 List<String> memInfoList = Arrays.asList(memLine.split("\\s+")); int totalSystemMemory = Integer.parseInt(memInfoList.get(1)); int totalSystemUsedMemory = Integer.parseInt(memInfoList.get(2)); int totalSystemFreeMemory = Integer.parseInt(memInfoList.get(3)); System.out.println("Total system memory in mb: " + totalSystemMemory); System.out.println("Total system used memory in mb: " + totalSystemUsedMemory); System.out.println("Total system free memory in mb: " + totalSystemFreeMemory); } public void LoadAvg() throws IOException { // cat /proc/loadavg Runtime runtime = Runtime.getRuntime(); BufferedReader br = new BufferedReader( new InputStreamReader(runtime.exec("cat /proc/loadavg").getInputStream())); String line; String avgLine = ""; while ((line = br.readLine()) != null) { avgLine = line; System.out.println(line); } System.out.println(avgLine); } } <file_sep>package com.ds.binarysearchtree; import com.sun.deploy.util.StringUtils; public class BinarySearchTree { public static String inOrder = ""; // Node to hold the elements class Node { int key; Node left, right; public Node(int item) { this.key = item; this.left = null; this.right = null; } } // Root node Node root; public BinarySearchTree() { root = null; } void insert(int item) { root = insertRec(root, item); } // Recursive function to add elements on BST Node insertRec(Node root, int item) { if (root == null) { root = new Node(item); return root; } if (root.key > item) { root.left = insertRec(root.left, item); } else if (root.key < item) { root.right = insertRec(root.right, item); } else { System.out.println("Duplicate elements ignoring it as of now"); } return root; } void inOrderPrint() { inOrderRec(root); } void inOrderRec(Node root) { if (root != null) { inOrderRec((root.left)); // System.out.println(root.key); int value = root.key; inOrder += (String.valueOf(value)).concat("->"); inOrderRec(root.right); } else { System.out.println(" In left or right left element present"); } } void preORderPrint() { preOrderRec(root); } void preOrderRec(Node root) { if (root != null) { preOrderRec(root.left); preOrderRec(root.right); System.out.println(root.key); } } void postOrderPrint() { postOrderRec(root); } void postOrderRec(Node root) { if (root != null) { System.out.println(root.key); postOrderRec(root.left); postOrderRec(root.right); } } public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); tree.insert(30); tree.insert(50); tree.insert(20); tree.insert(10); System.out.println("In-Order"); tree.inOrderPrint(); System.out.println(inOrder); // System.out.println("Pre-Order"); // tree.preORderPrint(); // System.out.println("Post-Order"); // tree.postOrderPrint(); } } <file_sep>package JunitTestingExample; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; public class TestClassTest1 { @InjectMocks TestClass testClass2; @Mock TestClass testClass; protected boolean mockInitialized = false; @Before public void setUp() { if (!mockInitialized) { MockitoAnnotations.initMocks(this); mockInitialized = true; } } @Test public void calculateTest() { int expected = 100; TestClass testClass = Mockito.spy(new TestClass()); Mockito.doReturn("square").when(testClass).getShape(ArgumentMatchers.anyInt()); // int actual = testClass.calculate(); // Assert.assertEquals(expected, actual); } } <file_sep>package memory.examples; public class StringImmutableExample { public static void main(String[] args) { testMethod(); } private static void testMethod() { String a = "a"; System.out.println("a 1-->" + a); a = "ty"; System.out.println("a 2-->" + a); // Check the details on stackoverflow example: // https://stackoverflow.com/questions/8798403/string-is-immutable-what-exactly-is-the-meaning // https://stackoverflow.com/questions/93091/why-cant-strings-be-mutable-in-java-and-net } } <file_sep>package completable.future.main; public class ApplicationTest { } <file_sep>package com.ds.linkList; import java.util.*; public class javaLinkedList { public static void main(String args[]) { // Creating object of class linked list LinkedList<String> linkList = new LinkedList<>(); linkList.add("Hello"); linkList.addFirst("first"); linkList.addLast("last"); linkList.add(1, "Added at index 1"); System.out.println("Linked list: " + linkList); linkList.remove("first"); System.out.println("Linked list: " + linkList); linkList.removeFirst(); System.out.println("Linked list: " + linkList); linkList.removeLast(); System.out.println("Linked list: " + linkList); } } <file_sep>package JunitTestingExample; import org.springframework.stereotype.Service; @Service public class TestClass { public void methodA() { int number = 4; String callingMethod = shouldCallTo(number); if (callingMethod.equals("evenMethod")) { } } public String shouldCallTo(int number) { if (number / 2 == 0 ) { return "evenMethod"; } else { return "oddMethod"; } } public void evenMethod(int number) { System.out.println("Even number"); } public void oddMethod(int number) { } public String getShape(int index) { System.out.println(index); if (index == 1) { return "circle"; } else { return "square"; } } public int findArea(String shape, int radius) { if (shape.equals("circle")) { return 3 * radius * radius; } else { return radius * radius; } } } <file_sep>package sample.data.mongo.services; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Service; import sample.data.mongo.models.Course; @Service public class CustomFindQueryExecutor { @Autowired private MongoTemplate mongoTemplate; public void RunCustomQuery() { String query2 = "{\"name\" : \"mathematics\"}"; List<Course> courseList = (List<Course>) mongoTemplate.find(new CustomFindPreparator(query2), Course.class, "course"); System.out.println(courseList); } } <file_sep>package memory; public class MemoryTest { public static void main(String[] args) { MemoryTest main = new MemoryTest(); main.start(); } public void start() { String last = "z"; Container container = new Container(); container.setInitial("C"); another(container, last); System.out.println(container.getInitial()); } public void another(Container initialHolder, String newInitial) { newInitial.toLowerCase(); initialHolder.setInitial("B"); Container initial2 = new Container(); initialHolder = initial2; System.out.println(initialHolder.getInitial()); System.out.println(newInitial); } public class Container { private String initial = "A"; public String getInitial() { return initial; } public void setInitial(String initial) { this.initial = initial; } } } <file_sep>package pool.threads; import java.time.LocalDateTime; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class ExecutorServiceExample { public static void main(String[] args) { // Demo runnable task: Runnable runnableTask = () -> { try { TimeUnit.MILLISECONDS.sleep(1000l); System.out.println("Current time :: " + LocalDateTime.now()); } catch (InterruptedException e) { e.printStackTrace(); } return; }; //1. ExecutorService instance : newSingleThreadExecutor ExecutorService executorService = Executors.newSingleThreadExecutor(); // 2. execute the task using execute method of executorService executorService.execute(runnableTask); // this method will closed for new task // executorService.shutdown(); // 3. Execute the task using submit method Future<String> result = executorService.submit(runnableTask, "Donek"); while(result.isDone() == false) { try { System.out.println("The method return value : " + result.get()); break; } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } //Sleep for 1 second try { System.out.println("Sleep for 1000"); Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("Break from the other thread works and now at main thread"); // executorService.shutdownNow(); System.out.println(executorService.isTerminated()); System.out.println(executorService.isShutdown()); //Shut down the executor service, without below line, code will not exited. executorService.shutdown(); } } <file_sep>package com.ds.object.clone; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ObjectClone { public static void main (String args[]) { ClassAICloneable objectA = new ClassAICloneable(); List<String> idsA = new ArrayList<>(); idsA.add("A"); objectA.setIds(idsA); ClassAICloneable objectBofA = null; try { objectBofA = (ClassAICloneable) objectA.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } System.out.println("objectBofA=" + objectBofA); System.out.println("objectA=" + objectA); List<String> ids2 = objectA.getIds(); System.out.println(ids2); ids2.add("B"); System.out.println(ids2); objectBofA.setIds(ids2); System.out.println("objectBofA=" + objectBofA); System.out.println("objectA=" + objectA); List<String> newIds = new ArrayList<>(); newIds.addAll(objectA.getIds()); newIds.add("B"); objectBofA.setIds(newIds); System.out.println("objectBofA=" + objectBofA); System.out.println("objectA=" + objectA); ClassB classB = new ClassB(); classB.setName("KP"); List<String> ids = Arrays.asList("a", "b", "c"); classB.setIds(ids); ClassB classBClone = deepClone.byGson(classB, classB.getClass()); List<String> ids3 = classBClone.getIds(); ids3.add("abc"); classBClone.setIds(ids3); classBClone.setName("VS"); System.out.println("Class B" + classB); System.out.println("clone Class: " + classBClone); } } <file_sep>package pool.threads; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class ExecutorExample2 { public static Executor executor = Executors.newSingleThreadExecutor(); public static Runnable testing() { Runnable runnableTask = () -> { System.out.println("Running time consuming tasks"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Return from the non-daemon thread"); System.out.println(Thread.currentThread().isDaemon()); return; }; return runnableTask; } public static void main(String[] args) { System.out.println("Hello Executing the main thread"); executor.execute(ExecutorExample2.testing()); System.out.println("After completing the time consuming task"); System.out.println(Thread.currentThread().getName()); System.out.println("\n"); System.out.println(Thread.getAllStackTraces()); } } <file_sep>package sample.data.mongo.services; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import sample.data.mongo.models.FirstColl; import sample.data.mongo.repository.FirstCollRepository; public class FirstCollService { @Autowired FirstCollRepository firstCollRepository; public void getFirstCollById() { String id = "573fcafd-584d-447c-a762-53567283b2b0"; Optional<FirstColl> firstColl = firstCollRepository.findById(id); if(firstColl.isPresent()) { System.out.println(firstColl.get()); } else { System.out.println("No record found"); } } } <file_sep>package com.basics; public class ThreadedDebugging { public static void main(String[] args) { String[] arguments = args; Thread a = new Thread(() -> { while (true) { System.out.print("A"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread b = new Thread(() -> { while (true) { System.out.print("B"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }); b.start(); a.start(); } } <file_sep>package kp.collectionutils; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.TreeMap; public class QueueExample { public static void main(String args[]) { PriorityQueue<String> queue = new PriorityQueue<String>(); // creating priority queue queue.add("Amit"); // adding elements queue.add("Rachit"); queue.add("Rahul"); System.out.println("head:" + queue.element()); System.out.println("head:" + queue.peek()); System.out.println("iterating the queue elements:"); Iterator itr = queue.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } queue.remove(); queue.poll(); System.out.println("after removing two elements:"); Iterator<String> itr2 = queue.iterator(); while (itr2.hasNext()) { System.out.println(itr2.next()); } TreeMap<String, String> ob = new TreeMap<>(); ob.put("a", "krishna"); ob.put("b", "krishna"); ob.put("c", "krishna"); for (Map.Entry<String, String> e : ob.entrySet()) { System.out.println(e); System.out.println(e.getValue()); System.out.println(e.getKey()); System.out.println(e.toString()); } } } <file_sep>package com.ds; public class HelloWorld { public static void method1(int i, int num) { for (int j = 1; j <= i; j++) { System.out.print(num + " "); num *= 2; } System.out.println(); } public static String s = ""; public static void main(String args[]) { // // int i = 1; // while (i <= 6) { // method1(i, 2); // i++; // } String a = "krishna"; String b = a.concat(" Prasad"); System.out.println(a); System.out.println(b); System.out.println(s); for(Character c : a.toCharArray()) { System.out.println(String.valueOf(c)); System.out.println(s); // s.concat(String.valueOf(c)); s += String.valueOf(c); } System.out.println("Value of s : " + s); // System.out.println("Hello world!!!"); // // // String a = "abc"; // String b = "abc"; // System.out.println(a.getClass()); // if (a == b) { // System.out.println("Two String a and b are equal with == operator"); // System.out.println(a==b); // } // // if (a.equals(b)) { // System.out.println("Two String a and b are equal with .equeals operator"); // System.out.println(a.equals(b)); // } // // // // System.out.println("=====String object======="); // String strA = new String("abc"); // String strB = new String("abc"); // System.out.println(strA.getClass()); // System.out.println(strA == strB); // System.out.println(strA.equals(strB)); // if (strA == strB) { // System.out.println("Two String strA and strB are equal with == operator"); // System.out.println(strA==strB); // } // // if (strA.equals(strB)) { // System.out.println("Two String a and b are equal with .equeals operator"); // System.out.println(strA.equals(strB)); // } } } <file_sep>package memory.examples; public class ValuesAndReferences { public static class Customer { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Customer(String name) { this.name = name; } } public static void main(String[] args) { int localValue = 5; calculate(localValue); // Alwayds passing the copy of the variable System.out.println(localValue); // For object // 1. Changes the attribute of object Customer c = new Customer("Sallay"); renameCustomer(c); System.out.println(c.getName()); // 2. Changes entire object in callee method, wouldn't reflect here. Customer c1 = new Customer("KP"); System.out.println("Before method call " + c1.getName()); changeCustomerObj(c1); System.out.println("After method call " + c1.getName()); // 3. Final keyword System.out.println("Final keyword"); final Customer finalC = new Customer("Krishna"); System.out.println(finalC.getName()); // Even in the getName method we can change the value of name, java will not restrict on its // attributes unless final keyword used in its attributes. renameCustomer(finalC); System.out.println(finalC.getName()); } private static void calculate(int calValue) { calValue = calValue*100; } private static void renameCustomer(Customer cust) { cust.setName("Diane"); } private static void changeCustomerObj(Customer cust) { Customer newC1 = new Customer("PRASAD"); cust = newC1; System.out.println("Name in the changeCustomerObj method: " + cust.getName()); } } <file_sep>package sample.data.mongo.models; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document public class IdGenerator { @Id private String identifier; private long counter; public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public long getCounter() { return counter; } public void setCounter(long counter) { this.counter = counter; } } <file_sep>#!/bin/sh BASE_URL = "http://localhost:8085"; echo "/health data\n"; # Make call to /health URL = "$BASE_URL". "/endpoints/health"; echo $URL curl --request GET \ --url $URL echo "/info data \n"; curl --request GET \ --url '$BASE_URL'/endpoints/info <file_sep>package kp.collectionutils; public class CustomLinkedListExampleTest { public static void main(String[] args) { CustomLinkedListExample<String> ll = new CustomLinkedListExample<String>(); ll.addAtFirst("Prasad"); ll.addAtFirst("Krishna"); ll.addAtFirst("Prasad"); ll.addAtFirst("KP0"); ll.addAtFirst("KP1"); ll.addAtFirst("KP2"); ll.addAtFirst("KP3"); ll.addAtFirst("KP4"); ll.addAtLast("Hello"); ll.addAtFirst("Hello1"); ll.addAfterIndex(7, "After Krishna"); ll.addBeforeIndex(2, "before KP3"); ll.DisplayElements(); CustomLinkedListExample<Integer> linkedInteger = new CustomLinkedListExample<Integer>(); linkedInteger.addAtFirst(10); linkedInteger.addAtLast(20); linkedInteger.addAtLast(30); linkedInteger.addAtLast(40); linkedInteger.addAtFirst(1); linkedInteger.DisplayElements(); } } <file_sep>package pool.threads; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.swing.text.AbstractDocument.ElementEdit; public class ExecutorServiceExample1 { private static ExecutorService executor1 = Executors.newFixedThreadPool(1); public static void main(String[] args) { // ExecutorExample1 executorExample1 = new ExecutorExample1(); // executorExample1.test(); test(); System.out.println("khatam ho gya.............."); } public static void test() { // ExecutorService executor = Executors.newSingleThreadExecutor(); for(int i = 1; i < 10; i++) { final int f = i; executor1.execute(() -> System.out.println("Single thread pool test " + f)); } System.out.println("Finished all the single jobs"); // executor1.shutdown(); // Shutdown and program exited // How to shutdown only the Executor as below: // ((ExecutorService) executor1).submit() // executor1.execute(() -> System.out.println("Single thread pool test 2")); // executor1.execute(() -> System.out.println("Single thread pool test 3")); // executor1.execute(() -> System.out.println("Single thread pool test 4")); executor1.submit(() -> { System.out.println("current thread name is : " + Thread.currentThread().getName()); System.out.println("is Alive " + executor1.isTerminated()); }); System.out.println("Finished all the single jobs"); executor1.shutdown(); // Program is never exited if the above shutdown handler not called. } } <file_sep>package gsa; import java.util.HashMap; import java.util.Map; public class TypeErasure { public static void main(String args[]) { Map genericsMap = new HashMap(); Map<String, String> noGenericsMap = new HashMap(); genericsMap.put("1954", "FORTRAN String key"); Object language = genericsMap.get("1954"); System.out.println("Language: "+language); genericsMap.put(1954, "FORTRAN Integer key"); // var language1 = genericsMap.get(1954); Object language1 = genericsMap.get(1954); System.out.println("Language: "+language1); // noGenericsMap.put("T", "A"); } }<file_sep>package sample.data.mongo.models; import org.springframework.data.annotation.Id; public class AbsenceEntity { @Id private String id; private String name; } <file_sep>package miniproject0.edu.coursera.concurrent; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; public class BlockingQueue { private List queue = new LinkedList(); private int limit; public BlockingQueue(int limit) { this.limit = limit; } public int size() { return this.queue.size(); } public synchronized void enqueue(Object item) throws InterruptedException { while (this.queue.size() == this.limit) { wait(); } if (this.queue.size() == 0) { notifyAll(); } this.queue.add(item); } public synchronized Object dequeue() throws InterruptedException { if (this.queue.size() == 0) { wait(); } if (this.queue.size() == this.limit) { notifyAll(); } return this.queue.remove(0); } public static void main(String args[]) throws InterruptedException { // define capacity of ArrayBlockingQueue int capacity = 5; // create object of ArrayBlockingQueue // ArrayBlockingQueue<String> // queue = new ArrayBlockingQueue<String>(capacity); BlockingQueue queue = new BlockingQueue(5); // // // Add elements to ArrayBlockingQueue using put method // queue.put("StarWars"); // queue.put("SuperMan"); // queue.put("Flash"); // queue.put("BatMan"); // queue.put("Avengers"); // queue.put("Avengers 21"); // // System.out.println(queue.size()); Thread putThread = new Thread(() -> { for(int i =0; i < 10; i++) { try { queue.enqueue("values"); System.out.println("Push elemenets successfully, total size " + queue.size()); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread pullThread = new Thread(() -> { for(int i =0; i< 10; i++) { try { Object s = queue.dequeue(); System.out.println("Got value from queue: " + s + " now size is " + queue.size()); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }); putThread.start(); pullThread.start(); // BlockingQueue blockingQueue = new BlockingQueue(5); // //// for(int i =0; i < 10; i++) { // // Thread putThread = new Thread( () -> { // try { // for(int i=0; i <= 10; i++) { // blockingQueue.enqueue(5); // System.out.println("Enqueue successfully"); // } // } catch (InterruptedException e) { // e.printStackTrace(); // } // }); // // Thread pullThread = new Thread( () -> { // try { // Object t = blockingQueue.dequeue(); // System.out.println("Got element :" + t); // } catch (InterruptedException e) { // e.printStackTrace(); // } // }); // // putThread.start(); // pullThread.start(); // System.out.println(putThread.getState()); // System.out.println(pullThread.getState()); //// } // } } <file_sep>package oops.Polymorphism; public class PolymorphismExample { // public void addition () { // System.out.println("Assuming the super class of Polymorphism example"); // } public static void main(String[] args) { SuperClassA superClassA = new SuperClassA(); superClassA.add(); // This call to super class add method SuperClassA superClassA1 = new SubClassOfA(); superClassA1.add(); // This call to sub-class add method i.e polymorphism applied here // and will not the parent class method add, so it overrides the super class method and is known as method overriding // Overriding happens if sub class method satisfies below conditions with the super class method // 1. Method name should be same. // 2. Argument should be same. // 3. Return type also should be same. // Overloading // 1. Same method name // 2. Different Argument type. // 3. May have different return types // Polymorphism is not applicable for method overloading // SubClassOfA subClassOfA = new SuperClassA(); SubClassOfA subClassOfA = new SubClassOfA(); subClassOfA.add(); } } <file_sep>package JunitTestingExample; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; public class TestClassTest { //TestClass testClass; @Before public void init() { TestClass testClass = new TestClass(); System.out.println("Inside before"); } @Test public void calculateTest() { int expected = 100; TestClass testClass = new TestClass(); TestClass testClassMock = Mockito.mock(TestClass.class); Mockito.when(testClassMock.getShape(2)).thenReturn("square"); // int actual = testClass.calculate(); // Assert.assertEquals(expected, actual); } } <file_sep>package com.oop.concepts; public class Fraction implements Number<Fraction> { private float a; public Fraction(float a) { this.a = a; } @Override public String toString() { return "Fraction{" + "a=" + a + '}'; } @Override public Fraction add(Fraction n) { return new Fraction(this.a + n.a); } } <file_sep>package miniproject0.edu.coursera.concurrent; public class HelloRunnable implements Runnable { private Integer value; public HelloRunnable( Integer value){ this.value = value; } /** * Provide a Runnable object. The Runnable interface defines a single method, run, * meant to contain the code executed in the thread. * The Runnable object is passed to the Thread constructor, as in the HelloRunnable example: */ @Override public void run() { System.out.println("First statement with value = " + this.value); System.out.println("Second statement with value = " + this.value); } public static void main(String args[]) { for(int i=0; i<10; i++) { new Thread(new HelloRunnable(i)).start(); } } } <file_sep>package sample.data.mongo.repository; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import sample.data.mongo.models.Campaign; public interface CampaignRepository extends MongoRepository<Campaign, String> { @Query("{$and:[ {'ownerId': ?0} , {'$text' : { '$search' : ?1}} ]}") Page<Campaign> searchByByOwnerIdAndText(String ownerId, String keywords, Pageable page); } <file_sep>package sample.data.mongo.models; import java.util.List; import javax.validation.constraints.NotNull; import lombok.AccessLevel; import lombok.Data; import lombok.Getter; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; @Data @Document(collection = "calendriers") public class CalendrierEntity { @Id private Long id; @NotNull private String label; @DBRef(lazy = true) @Getter(AccessLevel.NONE) private List<AbsenceEntity> absenceEntities; } <file_sep>package edu.coursera.distributed; import edu.coursera.distributed.util.MPI; import edu.coursera.distributed.util.MPI.MPIException; /** * A wrapper class for a parallel, MPI-based matrix multiply implementation. */ public class MatrixMult { /** * A parallel implementation of matrix multiply using MPI to express SPMD parallelism. In * particular, this method should store the output of multiplying the matrices a and b into the * matrix c. * * This method is called simultaneously by all MPI ranks in a running MPI program. For * simplicity MPI_Init has already been called, and MPI_Finalize should not be called in * parallelMatrixMultiply. * * On entry to parallelMatrixMultiply, the following will be true of a, b, and c: * * 1) The matrix a will only be filled with the input values on MPI rank zero. Matrix a on all * other ranks will be empty (initialized to all zeros). 2) Likewise, the matrix b will only be * filled with input values on MPI rank zero. Matrix b on all other ranks will be empty * (initialized to all zeros). 3) Matrix c will be initialized to all zeros on all ranks. * * Upon returning from parallelMatrixMultiply, the following must be true: * * 1) On rank zero, matrix c must be filled with the final output of the full matrix * multiplication. The contents of matrix c on all other ranks are ignored. * * Therefore, it is the responsibility of this method to distribute the input data in a and b * across all MPI ranks for maximal parallelism, perform the matrix multiply in parallel, and * finally collect the output data in c from all ranks back to the zeroth rank. You may use any * of the MPI APIs provided in the mpi object to accomplish this. * * A reference sequential implementation is provided below, demonstrating the use of the Matrix * class's APIs. * * @param a Input matrix * @param b Input matrix * @param c Output matrix * @param mpi MPI object supporting MPI APIs * @throws MPIException On MPI error. It is not expected that your implementation should throw * any MPI errors during normal operation. */ public static void parallelMatrixMultiply(Matrix a, Matrix b, Matrix c, final MPI mpi) throws MPIException { // Each process has a Rank to Identify it final int myRank = mpi.MPI_Comm_rank(mpi.MPI_COMM_WORLD); // Number of Processes final int size = mpi.MPI_Comm_size(mpi.MPI_COMM_WORLD); final int rows = c.getNRows(); final int rowChunk = (rows + size - 1) / size; // Divide into Chunks for each process. Each Process runs only the row chunk // Get Start and End Index of each chunk final int start = myRank * rowChunk; int end = (myRank + 1) * rowChunk; if (end > rows) { end = rows; } // Edge Case check -> endIndex is bound by actual Size of Resultant matrix //BroadCast Matrix a and b to other ranks //Broadcast sends data in array => need to convert 2D Matrix to Array mpi.MPI_Bcast(a.getValues(), 0, a.getNRows() * a.getNCols(), 0, mpi.MPI_COMM_WORLD); //BroadCast sends array of info, takes offset, num of elements, Root Rank, Communicator as args mpi.MPI_Bcast(b.getValues(), 0, b.getNRows() * b.getNCols(), 0, mpi.MPI_COMM_WORLD); for (int i = start; i < end; i++) { for (int j = 0; j < c.getNCols(); j++) { c.set(i, j, 0.0); for (int k = 0; k < b.getNRows(); k++) { c.incr(i, j, a.get(i, k) * b.get(k, j)); } } } if (myRank == 0) { // Buffer for the Other Process's Results that Rank 0 will receive MPI.MPI_Request[] requests = new MPI.MPI_Request[size - 1]; // Iterate through Ranks and Receive their Results in non Blocking way for (int i = 1; i < size; i++) { // get Row Start and Row End for ith Chunk final int rankStartRow = i * rowChunk; int rankEndRow = (i + 1) * rowChunk; // EdgeCase if Rank End row -> (i + 1) * chunkSize is greater than number of Actual Rows if (rankEndRow > rows) { rankEndRow = rows; } final int rowOffset = rankStartRow * c.getNCols(); //Number of Elements in the chunk final int nElements = (rankEndRow - rankStartRow) * c.getNCols(); // Non Blocking Receive from other ranks requests[i - 1] = mpi .MPI_Irecv(c.getValues(), rowOffset, nElements, i, i, mpi.MPI_COMM_WORLD); // Buffer to Receive, RowOffset, num of Elements, Rank of Sender, Tag for Message, Comm } mpi.MPI_Waitall(requests); // like async-await, wait for all other ranks to return result (Async -> reason for Speedup) } else { // Other Ranks send their Results to rook rank mpi.MPI_Send(c.getValues(), start * c.getNCols(), (end - start) * c.getNCols(), 0, myRank, mpi.MPI_COMM_WORLD); // Buffer to send , offset, num elements, destination rank, myrank, comm } } } <file_sep>package com.dp; public class CandiesMakingSolution { public static long minimumPasses(long m, long w, long p, long n) { // Write your code here long pass = 0; long result = (long) Math.ceil(n/(m*w)); // Maximum number of passes; long resource = 0; while (pass < result) { // Calculation // Straight passes long st_pass = (long) Math.ceil(p-resource / (m*w)); pass += st_pass; resource = m * w * st_pass; // bulk hiring if (Math.floor(resource/p) >= Math.abs(m-w)) { resource -= Math.abs(m-w)*p; if (m > w) { w = m; } else { m = w; } } } return 1l; } public static void main(String[] args) { } } <file_sep>package non.concurrency.threads; public class MyExample1 { private long countUntil; MyExample1(long countUntil) { this.countUntil = countUntil; } public void reciprocalSum() { // System.out.println("Running thread name is: " + Thread.currentThread().getName()); double sum = 0; for (long i = 0; i < countUntil; i++) { sum += i > 0 ? 1.0 / (i * 1.0) : i; } // System.out.println("Total reciprocal sum is : " + sum); } } <file_sep>package sample.data.mongo.models; import java.util.List; public class Springdata { private String organization; private boolean active; private List<Fields> fields; public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public List<Fields> getFields() { return fields; } public void setFields(List<Fields> fields) { this.fields = fields; } } <file_sep># learningJava Repo for learning Java <file_sep>package oops.overriding; public class SubClassA extends superClassA { @Override public void methodA1() { System.out.println("In the class " + this.getClass().getName() + " method name: methodA1"); } } <file_sep>package HttpExamples; public class PostForEntityExample { private class VehicleType { private String ispName; public String getIspName() { return ispName; } public void setIspName(String ispName) { this.ispName = ispName; } } // private void invokeProcessorDispatcher(Set<VehicleType> vehicleTypes) { // Set<String> results = new HashSet<>(); // Iterator<VehicleType> itr = vehicleTypes.iterator(); // while (itr.hasNext()) { // VehicleType value = itr.next(); // LOGGER.info("Value" + value); // if ("Fund".equals(value.getIspName()) || "US".equals(value.getIspName())) { // results.add(value.getIspName()); // LOGGER.info("RESULTS" + results); // } // } // try { // HttpHeaders headers = new HttpHeaders(); // // headers.setContentType( // org.springframework.http.MediaType.APPLICATION_JSON); // // Map<String, String> requestBody = new HashMap<>(); // // HttpEntity<Set<String>> // request = // new HttpEntity<>(results, headers); // // String // result = restTemplate // .postForObject("http://localhost:3000/dispatcher/service/api/message", // results, String.class); // } catch (HttpClientErrorException e) { // LOGGER.error("Errors: " + e.getResponseBodyAsString()); // ErrorHolder eh = objectMapper.readValue(e.getResponseBodyAsString(), ErrorHolder.class); // logger.error("error: " + eh.getErrorMessage()); // throw e; // } // } } <file_sep>package miniproject0.edu.coursera.concurrent.incrementExamples; public class ACounter implements Runnable { private Increment increment; public ACounter(Increment increment) { this.increment = increment; } @Override public void run() { this.increment.incSimpleCounter(); this.increment.incSynchronizedCounter(); this.increment.incVolatileCounter(); this.increment.incAtomicInteger(); } }
d1fef6b3d2ade0a1fe244269757644ec17eb701a
[ "Markdown", "Java", "Shell" ]
58
Java
sonwani237/learningJava
648b57211c92b932235f2cdc1c0abb7a557521f6
188d09c6c2dedd07679ce7905a48a9e3a76cebce
refs/heads/master
<repo_name>r0mainp/Jason<file_sep>/src/Controller/ArgonautsController.php <?php namespace App\Controller; use App\Entity\Argonaut; use App\Repository\ArgonautRepository; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class ArgonautsController extends AbstractController { /** * @Route("/", name="app_index") */ public function index(ArgonautRepository $argoRepo): Response { $argonauts = $argoRepo->findAll(); return $this->render('argonauts/index.html.twig', [ 'argonauts' => $argonauts, ]); } /** * @Route("/add", name="add_argonaut") */ public function addArgonaut(EntityManagerInterface $em, Request $request) { $argonaut = new Argonaut(); if (!empty($request->query->get('name'))) { $argonaut->setName($request->query->get('name')); $em->persist($argonaut); $em->flush(); } return $this->redirectToRoute("app_index"); } }
889594c5018b1ca7242305344704f86efea4f7e5
[ "PHP" ]
1
PHP
r0mainp/Jason
8cb066aad8f9348807ed2d3ace26d73626514d8e
a2125b20608f68a86ccadaf07266c309bb58505a
refs/heads/master
<repo_name>ImranAdan/MongoDbExample<file_sep>/src/main/java/org/adani/examples/customer/Customer.java package org.adani.examples.customer; import com.fasterxml.jackson.annotation.JsonProperty; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.springframework.data.annotation.Id; public class Customer { @Id @JsonProperty("id") private String id; @JsonProperty("firstName") String firstName; @JsonProperty("lastName") String lastName; public Customer(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getId() { return id; } } <file_sep>/src/main/java/org/adani/examples/config/JerseyConfig.java package org.adani.examples.config; import org.adani.examples.customer.CustomerServiceEndpoint; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.ServerProperties; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; @Component public class JerseyConfig extends ResourceConfig { public JerseyConfig() { // Add Service Endpoint beans register(getServiceList()); // Register an instance of LoggingFilter. register(new LoggingFilter()); // Register JACKSON Binding Feature. register(JacksonFeature.class); // Enable Tracing support. property(ServerProperties.TRACING, "ALL"); } private List<?> getServiceList(){ return Arrays.asList(CustomerServiceEndpoint.class); } }<file_sep>/src/test/java/org/adani/examples/customer/CustomerServiceEndpointTest.java package org.adani.examples.customer; import org.adani.examples.Application; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) public class CustomerServiceEndpointTest { @Autowired CustomerServiceEndpoint ep; @Test public void testSaveCustomer() throws Exception { Customer c = new Customer("Imran", "Adan"); Response savedCustomer = ep.saveCustomer(c); assertThat(savedCustomer, is(notNullValue())); Response customer = ep.findByFirstName("Imran"); assertTrue(customer.hasEntity()); } @Test public void testFindByFirstName() throws Exception { Response response = ep.findByFirstName("Alice"); assertTrue(response.hasEntity()); } @Test public void testFindAll() throws Exception { Response response = ep.findAll(); assertTrue(response.hasEntity()); } }<file_sep>/README.md # SpringMongoDb Template for Spring Boot, Jersey, MongoDb<file_sep>/src/main/java/org/adani/examples/customer/CustomerServiceEndpoint.java package org.adani.examples.customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.List; import java.util.Map; import java.util.Set; @Component @Path("/customer-service") @Consumes("application/json") @Produces("application/json") public class CustomerServiceEndpoint { @Autowired CustomerRepository repository; @POST public Response saveCustomer(Customer customer){ Customer savedCustomer = repository.save(customer); return buildResponse(ResponseEntity.ok(savedCustomer)); } @GET @Path("/{name}") public Response findByFirstName(@PathParam("name") String name){ Customer byFirstName = repository.findByFirstName(name); return buildResponse(ResponseEntity.ok(byFirstName)); } @GET @Path("/names") public Response findAll(){ List<Customer> all = repository.findAll(); return buildResponse(ResponseEntity.ok(all)); } private <T> Response buildResponse(ResponseEntity<T> item) { final HttpStatus statusCode = item.getStatusCode(); final T body = item.getBody(); final Response.ResponseBuilder responseBuilder = Response.status(statusCode.value()).entity(body); final HttpHeaders headers = item.getHeaders(); final Set<Map.Entry<String, List<String>>> entries = headers.entrySet(); for (Map.Entry<String, List<String>> entry : entries) { String s = entry.getKey(); Object o = entry.getValue(); responseBuilder.header(s, o); } return Response.ok().entity(item).status(Response.Status.OK).build(); } } <file_sep>/src/test/java/org/adani/examples/customer/CustomerRepositoryTest.java package org.adani.examples.customer; import org.adani.examples.Application; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) public class CustomerRepositoryTest { private static final Logger LOGGER = LoggerFactory.getLogger(CustomerRepositoryTest.class); @Autowired private CustomerRepository repository; @Before public void setUp(){ repository.deleteAll(); } @Test public void testFindByFirstName() throws Exception { repository.save(new Customer("Alice", "Smith")); Customer alice = repository.findByFirstName("Alice"); assertThat(alice, is(notNullValue())); LOGGER.info(alice.toString()); } @Test public void testFindByLastName() throws Exception { repository.save(new Customer("Alice", "Smith")); repository.save(new Customer("Lana", "Smith")); List<Customer> customerList = repository.findByLastName("Smith"); assertThat(customerList.size(), is(greaterThan(0))); LOGGER.info(customerList.toString()); } }
b0160fc9991ef6fd445341f2eeafa7661370cfff
[ "Markdown", "Java" ]
6
Java
ImranAdan/MongoDbExample
82bf65c9989212949b1b53fd557d32b22a26af93
84dbd875b20250df8d7c898dac9e4879594a0e79
refs/heads/master
<repo_name>khacnhat/bob-runner<file_sep>/config.ru require_relative 'src/external' require_relative 'src/rack_dispatcher' require_relative 'src/runner' require 'prometheus/middleware/collector' require 'prometheus/middleware/exporter' require 'rack' use Rack::Deflater, if: ->(_, _, _, body) { body.any? && body[0].length > 512 } use Prometheus::Middleware::Collector use Prometheus::Middleware::Exporter runner = Runner.new(External.new) run RackDispatcher.new(runner) <file_sep>/src/well_formed_args.rb require_relative 'base58' require_relative 'client_error' require_relative 'image_name' require 'json' # Checks for arguments syntactic correctness module WellFormedArgs def well_formed_args(s) @args = JSON.parse(s) if @args.nil? || !@args.is_a?(Hash) malformed('json') end rescue malformed('json') end # - - - - - - - - - - - - - - - - def image_name name = __method__.to_s arg = @args[name] unless image_name?(arg) malformed(name) end arg end include ImageName # - - - - - - - - - - - - - - - - def id name = __method__.to_s arg = @args[name] unless well_formed_id?(arg) malformed(name) end arg end # - - - - - - - - - - - - - - - - def files name = __method__.to_s arg = @args[name] unless well_formed_files?(arg) malformed(name) end arg end # - - - - - - - - - - - - - - - - def max_seconds name = __method__.to_s arg = @args[name] unless well_formed_max_seconds?(arg) malformed(name) end arg end private # = = = = = = = = = = = = def well_formed_id?(arg) Base58.string?(arg) && arg.size === 6 end def well_formed_files?(arg) arg.is_a?(Hash) && arg.all?{|_f,content| content.is_a?(String) } end def well_formed_max_seconds?(arg) arg.is_a?(Integer) && (1..20).include?(arg) end # - - - - - - - - - - - - - - - - def malformed(arg_name) raise ClientError, "#{arg_name}:malformed" end end
b838d14e15ab4caca3ab2719c7ba85a984388296
[ "Ruby" ]
2
Ruby
khacnhat/bob-runner
e4aa6c689ca140529d6fab2a8a7132be89e1f05e
119bb8b5c761d3a9137288ed8062e602e90e5447
refs/heads/master
<file_sep>'use strict'; const _ = require('lodash'); const uuid = require('uuid/v4'); const opentracing = require('opentracing'); const Span = require('./Span'); module.exports = class Tracer extends opentracing.Tracer { constructor(logger, config={}) { super(); this._logger = logger; this.config = config; } _startSpan(name, opts={}) { const spanid = uuid(); const traceid = _.size(opts.references) ? opts.references[0].referencedContext().toTraceId() : uuid(); return new Span({ name, id: spanid, trace: traceid, tracer: this, // TODO: baggage references: opts.references, tags: _.extend({}, this.config.tags, opts.tags), startTime: opts.startTime || Date.now(), logger: this._logger.child({span: spanid, trace: traceid}) }); } } <file_sep>'use strict'; module.exports = class SpanContext { constructor(span) { this._span = span; } toSpanId() { return this._span._id; } toTraceId() { return this._span._trace; } } <file_sep># OpenTracing-Bunyan [OpenTracing](https://opentracing.io) [Tracer](https://opentracing-javascript.surge.sh/classes/tracer.html) extending [opentracing-javascript](https://github.com/opentracing/opentracing-javascript/) outputting to a [Bunyan](https://github.com/trentm/node-bunyan) logger. <file_sep>'use strict'; const _ = require('lodash'); const opentracing = require('opentracing'); const SpanContext = require('./SpanContext'); const ARGS = ['name', 'id', 'trace', 'tracer', 'references', 'tags', 'startTime', 'logger']; module.exports = class Span extends opentracing.Span { constructor(args={}) { super(); _.defaults(args, {references: [], tags: {}, startTime: Date.now()}); _.each(_.pick(args, ARGS), (v, k) => this['_'+k] = v); this._finishTime; this._logger.info({span_evt: 'start', span_name: this._name}) } _addTags(tags={}) { this._tags = _.extend(this._tags, tags); } _context() { return new SpanContext(this); } _finish(timestamp) { this._finishTime = timestamp || Date.now(); this._logger.info({ span_evt: 'finish', span_name: this._name, references: _.map(this._references, v => ({type: v.type(), span: v.referencedContext().toSpanId()})), tags: this._tags, // baggage time_start: this._startTime, time_finish: this._finishTime, duration: this._finishTime - this._startTime }) } // _getBaggageItem _log(keyValuePairs={}) { debugger // TODO: make stack capture configurable if(_.isError(keyValuePairs.error)) { const stack = keyValuePairs.error.stack; keyValuePairs.error = keyValuePairs.error.toJSON ? keyValuePairs.error.toJSON() : _.pick(keyValuePairs.error, 'name', 'message'); if(this._tracer.config.captureErrorStack) keyValuePairs.error.stack = stack; } this._logger.debug(_.extend({span_evt: 'log'}, keyValuePairs)); } // _setBaggageItem // _setOperationName _tracer() { return this._tracer; } }
b6ed0ec3db0d7ae72b6d3467adc6006476d36ed0
[ "JavaScript", "Markdown" ]
4
JavaScript
NathanRSmith/opentracing-bunyan
643e6de619efc50525829142a38964a320b3d6dd
0002e5c523c6a713a5f0cbf3f567180a4d89db74
refs/heads/master
<file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.test; import javax.measure.Quantity; import javax.measure.Unit; import javax.measure.quantity.Area; import javax.measure.quantity.Length; import javax.measure.quantity.Speed; import javax.measure.quantity.Time; import javax.measure.quantity.Volume; import javax.measure.test.quantity.DistanceQuantity; import javax.measure.test.quantity.TestQuantities; import javax.measure.test.quantity.VolumeQuantity; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static javax.measure.BinaryPrefix.*; import static javax.measure.test.unit.AreaUnit.*; import static javax.measure.test.unit.DistanceUnit.*; import static javax.measure.test.unit.SpeedUnit.*; import static javax.measure.test.unit.TimeUnit.*; import static javax.measure.test.unit.VolumeUnit.*; public class BinaryPrefixTest { @Test public void testKibi() { final Quantity<Length> m1 = new DistanceQuantity(1, m); final Unit<Length> km = KIBI(m); assertEquals("Ki", KIBI.getSymbol()); assertEquals("KIBI", KIBI.getName()); assertEquals(1d, m1.getValue()); assertEquals("m * 1024.0", km.toString()); if (km instanceof TestUnit) { @SuppressWarnings("rawtypes") TestUnit testKm = (TestUnit) km; assertEquals(1024d, testKm.getMultFactor()); } } @Test public void testMebi() { assertEquals("Mi", MEBI.getSymbol()); assertEquals("MEBI", MEBI.getName()); Quantity<Time> t1 = TestQuantities.getQuantity(1.0, MEBI(s)); assertNotNull(t1); assertEquals("1.0 s * 1048576.0", t1.toString()); } @Test public void testExbi() { Quantity<Volume> v1 = new VolumeQuantity(1.0, litre); assertEquals(1d, v1.getValue()); assertEquals("litre * 0.001", v1.getUnit().toString()); Quantity<Volume> v2 = v1.to(EXBI(litre)); assertNull(v2); // TODO temporary workaround } @Test public void testGibi() { assertEquals("Gi", GIBI.getSymbol()); Quantity<Speed> s1 = TestQuantities.getQuantity(1.0, GIBI(mph)); assertNotNull(s1); assertEquals("1.0 2779789807058944", s1.toString()); } @Test public void testTebi() { assertEquals("Ti", TEBI.getSymbol()); Quantity<Volume> v1 = TestQuantities.getQuantity(1.0, TEBI(litre)); assertNotNull(v1); assertEquals("1.0 1099511627.776", v1.toString()); } @Test public void testPebi() { assertEquals("Pi", PEBI.getSymbol()); Quantity<Area> a1 = TestQuantities.getQuantity(1.0, PEBI(acre)); assertNotNull(a1); assertEquals("1.0 4556516922992099300", a1.toString()); } @Test public void testYobi() { assertEquals("Yi", YOBI.getSymbol()); Quantity<Area> a1 = TestQuantities.getQuantity(1.0, YOBI(acre)); assertNotNull(a1); assertEquals("1.0 4892522791980404000000000000", a1.toString()); } @Test public void testZebi() { assertEquals("Zi", ZEBI.getSymbol()); Quantity<Area> a1 = TestQuantities.getQuantity(1.0, ZEBI(acre)); assertNotNull(a1); assertEquals("1.0 4777854289043363500000000", a1.toString()); } } <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.test; import javax.measure.Quantity; import javax.measure.Unit; import javax.measure.quantity.Area; import javax.measure.quantity.Length; import javax.measure.quantity.Mass; import javax.measure.quantity.Speed; import javax.measure.quantity.Time; import javax.measure.quantity.Volume; import javax.measure.test.quantity.DistanceQuantity; import javax.measure.test.quantity.TestQuantities; import javax.measure.test.quantity.VolumeQuantity; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static javax.measure.MetricPrefix.*; import static javax.measure.test.unit.AreaUnit.*; import static javax.measure.test.unit.DistanceUnit.*; import static javax.measure.test.unit.MassUnit.*; import static javax.measure.test.unit.SpeedUnit.*; import static javax.measure.test.unit.TimeUnit.*; import static javax.measure.test.unit.VolumeUnit.*; /** * JUnit tests for the 24 prefixes used in the metric system (decimal multiples and submultiples of units). * * @author <a href="mailto:<EMAIL>"><NAME></a> * @version 2.2, May 9, 2023 * @since 2.0 */ public class MetricPrefixTest { @Test public void testAtto() { assertEquals("a", ATTO.getSymbol()); assertEquals("ATTO", ATTO.getName()); Quantity<Time> t1 = TestQuantities.getQuantity(1.0, ATTO(min)); assertEquals("min * 0.000000000000000060", t1.getUnit().toString()); } @Test public void testCenti() { assertEquals("c", CENTI.getSymbol()); assertEquals("CENTI", CENTI.getName()); Quantity<Length> l1 = TestQuantities.getQuantity(1.0, CENTI(m)); assertEquals("m * 0.01", l1.getUnit().toString()); } @Test public void testDeci() { Quantity<Volume> m1 = new VolumeQuantity(1.0, litre); assertEquals(1d, m1.getValue()); assertEquals("litre * 0.001", m1.getUnit().toString()); Quantity<Volume> m2 = m1.to(DECI(litre)); assertNull(m2); // TODO temporary workaround } @Test public void testDeca() { assertEquals("da", DECA.getSymbol()); Quantity<Volume> v1 = TestQuantities.getQuantity(1.0, DECA(litre)); assertEquals("0.01", v1.getUnit().toString()); } @Test public void testDeka() { assertEquals("da", DECA.getSymbol()); Quantity<Volume> v1 = TestQuantities.getQuantity(1.0, DEKA(litre)); assertEquals("0.01", v1.getUnit().toString()); } @Test public void testExa() { assertEquals("E", EXA.getSymbol()); Quantity<Length> l1 = TestQuantities.getQuantity(1.0, EXA(m)); assertEquals("m * 1000000000000000000", l1.getUnit().toString()); } @Test public void testFemto() { assertEquals("f", FEMTO.getSymbol()); Quantity<Time> t1 = TestQuantities.getQuantity(1.0, FEMTO(s)); assertEquals("s * 0.0000000000000010", t1.getUnit().toString()); } @Test public void testGiga() { assertEquals("G", GIGA.getSymbol()); Quantity<Area> a1 = TestQuantities.getQuantity(1.0, GIGA(acre)); assertEquals("4047000000000", a1.getUnit().toString()); } @Test public void testHecto() { assertEquals("h", HECTO.getSymbol()); Quantity<Volume> v1 = TestQuantities.getQuantity(1.0, HECTO(litre)); assertEquals("0.1", v1.getUnit().toString()); } @Test public void testKilo() { final Quantity<Length> m1 = new DistanceQuantity(1, m); final Unit<Length> km = KILO(m); assertEquals("k", KILO.getSymbol()); assertEquals(1d, m1.getValue()); assertEquals("m * 1000.0", km.toString()); if (km instanceof TestUnit) { @SuppressWarnings("rawtypes") final TestUnit testKm = (TestUnit) km; assertEquals(1000d, testKm.getMultFactor()); } } @Test public void testMega() { assertEquals("M", MEGA.getSymbol()); Quantity<Volume> v1 = TestQuantities.getQuantity(1.0, MEGA(litre)); assertEquals("1000.0", v1.getUnit().toString()); } @Test public void testMilli() { Quantity<Volume> m1 = TestQuantities.getQuantity(10, MILLI(litre)); assertEquals(10d, m1.getValue()); assertEquals("0.0000010", m1.getUnit().toString()); } @Test public void testMicro() { assertEquals("\\u00b5", toUnicode(MICRO.getSymbol().charAt(0))); assertEquals("\u00b5", MICRO.getSymbol()); Quantity<Length> m1 = TestQuantities.getQuantity(1.0, m); assertEquals(1d, m1.getValue()); assertEquals("m", m1.getUnit().getSymbol()); Quantity<Length> m2 = m1.to(MICRO(m)); assertNull(m2); // the unit model in the test implementation is only partial, hence null here } @Test public void testNano() { Quantity<Length> m1 = TestQuantities.getQuantity(1.0, m); assertEquals(1d, m1.getValue()); assertEquals("m", m1.getUnit().getSymbol()); Quantity<Length> m2 = m1.to(NANO(m)); assertNull(m2); // the unit model in the test implementation is only partial, hence null here } @Test public void testPeta() { assertEquals("P", PETA.getSymbol()); Quantity<Speed> s1 = TestQuantities.getQuantity(10, PETA(kmh)); assertEquals(10d, s1.getValue()); assertEquals("1000000000000000", s1.getUnit().toString()); } @Test public void testPico() { assertEquals("p", PICO.getSymbol()); Quantity<Volume> v1 = TestQuantities.getQuantity(10, PICO(litre)); assertEquals(10d, v1.getValue()); assertEquals("0.0000000000000010", v1.getUnit().toString()); } @Test public void testTera() { assertEquals("T", TERA.getSymbol()); Quantity<Length> l1 = TestQuantities.getQuantity(10, TERA(m)); assertEquals(10d, l1.getValue()); assertEquals("m * 1000000000000", l1.getUnit().toString()); } @Test public void testYocto() { assertEquals("y", YOCTO.getSymbol()); Quantity<Volume> v1 = TestQuantities.getQuantity(10, YOCTO(litre)); assertEquals(10d, v1.getValue()); assertEquals("0.000000000000000000000000001", v1.getUnit().toString()); } @Test public void testYotta() { assertEquals("Y", YOTTA.getSymbol()); Quantity<Area> a1 = TestQuantities.getQuantity(10, YOTTA(sqmetre)); assertEquals(10d, a1.getValue()); assertEquals("1000000000000000000000000", a1.getUnit().toString()); } @Test public void testZepto() { assertEquals("z", ZEPTO.getSymbol()); Quantity<Time> t1 = TestQuantities.getQuantity(10, ZEPTO(s)); assertEquals(10d, t1.getValue()); assertEquals("s * 0.000000000000000000001", t1.getUnit().toString()); } @Test public void testZetta() { assertEquals("Z", ZETTA.getSymbol()); Quantity<Length> l1 = TestQuantities.getQuantity(10, ZETTA(m)); assertEquals(10d, l1.getValue()); assertEquals("m * 1000000000000000000000", l1.getUnit().toString()); } @Test public void testRonna() { assertEquals("R", RONNA.getSymbol()); Quantity<Length> l1 = TestQuantities.getQuantity(10, RONNA(m)); assertEquals(10d, l1.getValue()); assertEquals("m * 1000000000000000000000000000", l1.getUnit().toString()); } @Test public void testRonto() { assertEquals("r", RONTO.getSymbol()); Quantity<Length> l1 = TestQuantities.getQuantity(1, RONTO(m)); assertEquals(1d, l1.getValue()); assertEquals("m * 0.000000000000000000000", l1.getUnit().toString()); } @Test public void testQuetta() { assertEquals("Q", QUETTA.getSymbol()); Quantity<Mass> m1 = TestQuantities.getQuantity(2, QUETTA(g)); assertEquals(2d, m1.getValue()); assertEquals("g * 1000000000000000000000000000", m1.getUnit().toString()); } @Test public void testQuecto() { assertEquals("q", QUECTO.getSymbol()); Quantity<Length> l1 = TestQuantities.getQuantity(1, QUECTO(m)); assertEquals(1d, l1.getValue()); assertEquals("m * 0.000000000000000000000", l1.getUnit().toString()); } private static String toUnicode(char ch) { return String.format("\\u%04x", (int) ch); } } <file_sep><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="de"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../jacoco-resources/report.gif" type="image/gif"/><title>MetricPrefix.java</title><link rel="stylesheet" href="../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../index.html" class="el_report">Units of Measurement API</a> &gt; <a href="index.source.html" class="el_package">javax.measure</a> &gt; <span class="el_source">MetricPrefix.java</span></div><h1>MetricPrefix.java</h1><pre class="source lang-java linenums">/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure; /** * Provides support for the 24 prefixes used in the metric system (decimal multiples and submultiples of units). For example: * * &lt;pre&gt; * {@code import static tech.units.indriya.unit.Units.*; // Static import (from the RI). * import static javax.measure.MetricPrefix.*; // Static import. * import javax.measure.*; * import javax.measure.quantity.*; * ... * Unit&lt;Pressure&gt; HECTOPASCAL = HECTO(PASCAL); * Unit&lt;Length&gt; KILOMETRE = KILO(METRE);} * &lt;/pre&gt; * You could also apply &lt;code&gt;Unit.prefix&lt;/code&gt;: * &lt;pre&gt; * {@code ... * Unit&lt;Pressure&gt; HECTOPASCAL = PASCAL.prefix(HECTO); * Unit&lt;Length&gt; KILOMETRE = METRE.prefix(KILO);} * &lt;/pre&gt; * * &lt;p&gt; * &lt;b&gt;Do not use ordinal() to obtain the numeric representation of MetricPrefix. Use getValue() and getExponent() instead.&lt;/b&gt; * &lt;/p&gt; * * &lt;dl&gt; * &lt;dt&gt;&lt;span class=&quot;strong&quot;&gt;Implementation Requirements&lt;/span&gt;&lt;/dt&gt;&lt;dd&gt;This is an immutable and thread-safe enum.&lt;/dd&gt; * &lt;/dl&gt; * * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Metric_prefix&quot;&gt;Wikipedia: Metric Prefix&lt;/a&gt; * @author &lt;a href=&quot;mailto:<EMAIL>&quot;&gt;<NAME>&lt;/a&gt; * @author &lt;a href=&quot;mailto:<EMAIL>&quot;&gt;<NAME>&lt;/a&gt; * @version 2.3, May 20, 2023 * @since 2.0 */ <span class="fc" id="L65">public enum MetricPrefix implements Prefix {</span> /** Prefix for 10&lt;sup&gt;30&lt;/sup&gt;. */ <span class="fc" id="L67"> QUETTA(&quot;Q&quot;, 30),</span> /** Prefix for 10&lt;sup&gt;27&lt;/sup&gt;. */ <span class="fc" id="L69"> RONNA(&quot;R&quot;, 27),</span> /** Prefix for 10&lt;sup&gt;24&lt;/sup&gt;. */ <span class="fc" id="L71"> YOTTA(&quot;Y&quot;, 24),</span> /** Prefix for 10&lt;sup&gt;21&lt;/sup&gt;. */ <span class="fc" id="L73"> ZETTA(&quot;Z&quot;, 21),</span> /** Prefix for 10&lt;sup&gt;18&lt;/sup&gt;. */ <span class="fc" id="L75"> EXA(&quot;E&quot;, 18),</span> /** Prefix for 10&lt;sup&gt;15&lt;/sup&gt;. */ <span class="fc" id="L77"> PETA(&quot;P&quot;, 15),</span> /** Prefix for 10&lt;sup&gt;12&lt;/sup&gt;. */ <span class="fc" id="L79"> TERA(&quot;T&quot;, 12),</span> /** Prefix for 10&lt;sup&gt;9&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Giga-&quot;&gt;Wikipedia: Giga&lt;/a&gt; */ <span class="fc" id="L83"> GIGA(&quot;G&quot;, 9),</span> /** Prefix for 10&lt;sup&gt;6&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Mega-&quot;&gt;Wikipedia: Mega&lt;/a&gt; */ <span class="fc" id="L86"> MEGA(&quot;M&quot;, 6),</span> /** Prefix for 10&lt;sup&gt;3&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Kilo-&quot;&gt;Wikipedia: Kilo&lt;/a&gt; */ <span class="fc" id="L90"> KILO(&quot;k&quot;, 3),</span> /** Prefix for 10&lt;sup&gt;2&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Hecto-&quot;&gt;Wikipedia: Hecto&lt;/a&gt; */ <span class="fc" id="L93"> HECTO(&quot;h&quot;, 2),</span> /** Prefix for 10&lt;sup&gt;1&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Deca-&quot;&gt;Wikipedia: Deca&lt;/a&gt; */ <span class="fc" id="L96"> DECA(&quot;da&quot;, 1),</span> /** Prefix for 10&lt;sup&gt;-1&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Deci-&quot;&gt;Wikipedia: Deci&lt;/a&gt; */ <span class="fc" id="L99"> DECI(&quot;d&quot;, -1),</span> /** Prefix for 10&lt;sup&gt;-2&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Centi-&quot;&gt;Wikipedia: Centi&lt;/a&gt; */ <span class="fc" id="L102"> CENTI(&quot;c&quot;, -2),</span> /** Prefix for 10&lt;sup&gt;-3&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Milli-&quot;&gt;Wikipedia: Milli&lt;/a&gt; */ <span class="fc" id="L105"> MILLI(&quot;m&quot;, -3),</span> /** Prefix for 10&lt;sup&gt;-6&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Micro-&quot;&gt;Wikipedia: Micro&lt;/a&gt; */ <span class="fc" id="L108"> MICRO(&quot;\u00b5&quot;, -6),</span> /** Prefix for 10&lt;sup&gt;-9&lt;/sup&gt;. * @see &lt;a href=&quot;https://en.wikipedia.org/wiki/Nano-&quot;&gt;Wikipedia: Nano&lt;/a&gt; */ <span class="fc" id="L111"> NANO(&quot;n&quot;, -9),</span> /** Prefix for 10&lt;sup&gt;-12&lt;/sup&gt;. */ <span class="fc" id="L113"> PICO(&quot;p&quot;, -12),</span> /** Prefix for 10&lt;sup&gt;-15&lt;/sup&gt;. */ <span class="fc" id="L115"> FEMTO(&quot;f&quot;, -15),</span> /** Prefix for 10&lt;sup&gt;-18&lt;/sup&gt;. */ <span class="fc" id="L117"> ATTO(&quot;a&quot;, -18),</span> /** Prefix for 10&lt;sup&gt;-21&lt;/sup&gt;. */ <span class="fc" id="L119"> ZEPTO(&quot;z&quot;, -21),</span> /** Prefix for 10&lt;sup&gt;-24&lt;/sup&gt;. */ <span class="fc" id="L121"> YOCTO(&quot;y&quot;, -24),</span> /** Prefix for 10&lt;sup&gt;-27&lt;/sup&gt;. */ <span class="fc" id="L123"> RONTO(&quot;r&quot;, -27),</span> /** Prefix for 10&lt;sup&gt;-30&lt;/sup&gt;. */ <span class="fc" id="L125"> QUECTO(&quot;q&quot;, -30);</span> /** * The symbol of this prefix, as returned by {@link #getSymbol}. * * @serial * @see #getSymbol() */ private final String symbol; /** * Exponent part of the associated factor in base^exponent representation. */ private final int exponent; /** * Creates a new prefix. * * @param symbol * the symbol of this prefix. * @param exponent * part of the associated factor in base^exponent representation. */ <span class="fc" id="L148"> private MetricPrefix(String symbol, int exponent) {</span> <span class="fc" id="L149"> this.symbol = symbol;</span> <span class="fc" id="L150"> this.exponent = exponent;</span> <span class="fc" id="L151"> }</span> /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;30&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e30)&lt;/code&gt;. * @see #QUETTA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; QUETTA(Unit&lt;Q&gt; unit) { <span class="fc" id="L164"> return unit.prefix(QUETTA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;27&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e27)&lt;/code&gt;. * @see #RONNA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; RONNA(Unit&lt;Q&gt; unit) { <span class="fc" id="L178"> return unit.prefix(RONNA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;24&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e24)&lt;/code&gt;. * @see #YOTTA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; YOTTA(Unit&lt;Q&gt; unit) { <span class="fc" id="L192"> return unit.prefix(YOTTA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;21&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e21)&lt;/code&gt;. * @see #ZETTA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; ZETTA(Unit&lt;Q&gt; unit) { <span class="fc" id="L206"> return unit.prefix(ZETTA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;18&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e18)&lt;/code&gt;. * @see #EXA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; EXA(Unit&lt;Q&gt; unit) { <span class="fc" id="L220"> return unit.prefix(EXA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;15&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e15)&lt;/code&gt;. * @see #PETA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; PETA(Unit&lt;Q&gt; unit) { <span class="fc" id="L234"> return unit.prefix(PETA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;12&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e12)&lt;/code&gt;. * @see #TERA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; TERA(Unit&lt;Q&gt; unit) { <span class="fc" id="L248"> return unit.prefix(TERA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;9&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e9)&lt;/code&gt;. * @see #GIGA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; GIGA(Unit&lt;Q&gt; unit) { <span class="fc" id="L262"> return unit.prefix(GIGA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;6&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e6)&lt;/code&gt;. * @see #MEGA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; MEGA(Unit&lt;Q&gt; unit) { <span class="fc" id="L276"> return unit.prefix(MEGA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;3&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e3)&lt;/code&gt;. * @see #KILO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; KILO(Unit&lt;Q&gt; unit) { <span class="fc" id="L290"> return unit.prefix(KILO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;2&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e2)&lt;/code&gt;. * @see #HECTO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; HECTO(Unit&lt;Q&gt; unit) { <span class="fc" id="L304"> return unit.prefix(HECTO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;1&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e1)&lt;/code&gt;. * @see #DECA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; DECA(Unit&lt;Q&gt; unit) { <span class="fc" id="L318"> return unit.prefix(DECA);</span> } /** * US alias for &lt;code&gt;DECA&lt;/code&gt;. * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e1)&lt;/code&gt;. * @see #DECA */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; DEKA(Unit&lt;Q&gt; unit) { <span class="fc" id="L332"> return unit.prefix(DECA);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-1&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-1)&lt;/code&gt;. * @see #DECI */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; DECI(Unit&lt;Q&gt; unit) { <span class="fc" id="L346"> return unit.prefix(DECI);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-2&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-2)&lt;/code&gt;. * @see #CENTI */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; CENTI(Unit&lt;Q&gt; unit) { <span class="fc" id="L360"> return unit.prefix(CENTI);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-3&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-3)&lt;/code&gt;. * @see #MILLI */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; MILLI(Unit&lt;Q&gt; unit) { <span class="fc" id="L374"> return unit.prefix(MILLI);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-6&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-6)&lt;/code&gt;. * @see #MICRO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; MICRO(Unit&lt;Q&gt; unit) { <span class="fc" id="L388"> return unit.prefix(MICRO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-9&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-9)&lt;/code&gt;. * @see #NANO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; NANO(Unit&lt;Q&gt; unit) { <span class="fc" id="L402"> return unit.prefix(NANO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-12&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-12)&lt;/code&gt;. * @see #PICO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; PICO(Unit&lt;Q&gt; unit) { <span class="fc" id="L416"> return unit.prefix(PICO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-15&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-15)&lt;/code&gt;. * @see #FEMTO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; FEMTO(Unit&lt;Q&gt; unit) { <span class="fc" id="L430"> return unit.prefix(FEMTO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-18&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-18)&lt;/code&gt;. * @see #ATTO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; ATTO(Unit&lt;Q&gt; unit) { <span class="fc" id="L444"> return unit.prefix(ATTO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-21&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-21)&lt;/code&gt;. * #see ZEPTO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; ZEPTO(Unit&lt;Q&gt; unit) { <span class="fc" id="L458"> return unit.prefix(ZEPTO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-24&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-24)&lt;/code&gt;. * @see #YOCTO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; YOCTO(Unit&lt;Q&gt; unit) { <span class="fc" id="L472"> return unit.prefix(YOCTO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-27&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-27)&lt;/code&gt;. * @see #RONTO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; RONTO(Unit&lt;Q&gt; unit) { <span class="fc" id="L486"> return unit.prefix(RONTO);</span> } /** * Returns the specified unit multiplied by the factor &lt;code&gt;10&lt;sup&gt;-30&lt;/sup&gt;&lt;/code&gt; * * @param &lt;Q&gt; * type of the quantity measured by the unit. * @param unit * any unit. * @return &lt;code&gt;unit.times(1e-30)&lt;/code&gt;. * @see #QUECTO */ public static &lt;Q extends Quantity&lt;Q&gt;&gt; Unit&lt;Q&gt; QUECTO(Unit&lt;Q&gt; unit) { <span class="fc" id="L500"> return unit.prefix(QUECTO);</span> } /** * Returns the symbol of this prefix. * * @return this prefix symbol, not {@code null}. */ @Override public String getSymbol() { <span class="fc" id="L510"> return symbol;</span> } /** * Base part of the associated factor in {@code base^exponent} representation. For metric prefix, this is always 10. */ @Override public Integer getValue() { <span class="fc" id="L518"> return 10;</span> } /** * Exponent part of the associated factor in {@code base^exponent} representation. */ @Override public int getExponent() { <span class="fc" id="L526"> return exponent;</span> } /** * Returns the name of this prefix. * * @return this prefix name, not {@code null}. */ @Override public String getName() { <span class="fc" id="L536"> return name();</span> } } </pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.10.202304240956</span></div></body></html><file_sep>unit-api ======== [![Maven Central](https://maven-badges.herokuapp.com/maven-central/javax.measure/unit-api/badge.svg)](https://maven-badges.herokuapp.com/maven-central/javax.measure/unit-api) [![javadoc](https://javadoc.io/badge2/javax.measure/unit-api/javadoc.svg)](https://javadoc.io/doc/javax.measure/unit-api) [![CircleCI](https://circleci.com/gh/unitsofmeasurement/unit-api/tree/master.svg?style=svg)](https://circleci.com/gh/unitsofmeasurement/unit-api/tree/master) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/598a357e2a584ce5bb36eebf23f28e23)](https://www.codacy.com/gh/unitsofmeasurement/unit-api/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=unitsofmeasurement/unit-api&amp;utm_campaign=Badge_Grade) [![Coverage Status](https://coveralls.io/repos/github/unitsofmeasurement/unit-api/badge.svg)](https://coveralls.io/github/unitsofmeasurement/unit-api) ![stability-frozen](https://img.shields.io/badge/stability-frozen-brightgreen.svg) [![License](http://img.shields.io/badge/license-BSD3-blue.svg?style=flat-square)](http://opensource.org/licenses/BSD-3-Clause) [![Stack Overflow](http://img.shields.io/badge/stack%20overflow-uom-4183C4.svg)](http://stackoverflow.com/questions/tagged/units-of-measurement) [![Join the chat at https://gitter.im/unitsofmeasurement/unit-api](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/unitsofmeasurement/unit-api?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) JSR 385 - Units of Measurement API 2.1 The Unit of Measurement API provides a set of Java language programming interfaces for handling units and quantities. The interfaces provide a layer which separates client code, that would call the API, from library code, which implements the API. ## Contribute [Contribution Guide](https://github.com/unitsofmeasurement/unit-api/wiki/Contribution-Guide) ## Quality [![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=javax.measure%3Aunit-api&metric=alert_status)](https://sonarcloud.io/dashboard?id=javax.measure%3Aunit-api) [![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=javax.measure%3Aunit-api&metric=security_rating)](https://sonarcloud.io/dashboard?id=javax.measure%3Aunit-api) [![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=javax.measure%3Aunit-api&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=javax.measure%3Aunit-api) [![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=javax.measure%3Aunit-api&metric=bugs)](https://sonarcloud.io/dashboard?id=javax.measure%3Aunit-api) [![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=javax.measure%3Aunit-api&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=javax.measure%3Aunit-api) ## Planning [![GitHub issues](https://img.shields.io/github/issues-raw/unitsofmeasurement/unit-api.svg)](https://github.com/unitsofmeasurement/unit-api/issues) [![GitHub issues](https://img.shields.io/github/issues-closed-raw/unitsofmeasurement/unit-api.svg)](https://github.com/unitsofmeasurement/unit-api/issues?q=is%3Aissue+is%3Aclosed) [![GitHub pull requests](https://img.shields.io/github/issues-pr-raw/unitsofmeasurement/unit-api.svg)](https://github.com/unitsofmeasurement/unit-api/pulls) [![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed-raw/unitsofmeasurement/unit-api.svg)](https://github.com/unitsofmeasurement/unit-api/pulls) [![P1](https://img.shields.io/github/issues/unitsofmeasurement/unit-api/prio:1.svg?style=flat )](https://github.com/unitsofmeasurement/unit-api/labels/prio%3A1) [![P2](https://img.shields.io/github/issues/unitsofmeasurement/unit-api/prio:2.svg?style=flat )](https://github.com/unitsofmeasurement/unit-api/labels/prio%3A2) [![P3](https://img.shields.io/github/issues/unitsofmeasurement/unit-api/prio:3.svg?style=flat )](https://github.com/unitsofmeasurement/unit-api/labels/prio%3A3)<file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.test.function; import javax.measure.UnitConverter; import javax.measure.test.TestConverter; import java.util.Objects; /** * <p> * This class represents a converter multiplying numeric values by a constant scaling factor (<code>double</code> based). * </p> * * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>"><NAME></a> * @version 1.1, June 28, 2019 * @since 2.0 */ public final class MultiplyConverter extends TestConverter implements Comparable<UnitConverter> { /** * Holds the scale factor. */ private double factor; /** * Creates a multiply converter with the specified scale factor. * * @param factor * the scaling factor. * @throws IllegalArgumentException * if coefficient is <code>1.0</code> (would result in identity converter) */ public MultiplyConverter(double factor) { if (factor == 1.0) throw new IllegalArgumentException("Would result in identity converter"); this.factor = factor; } /** * Creates a multiply converter with the specified scale factor. * * @param factor * the scaling factor. * @throws IllegalArgumentException * if coefficient is <code>1.0</code> (would result in identity converter) */ public MultiplyConverter(Number factor) { this(factor.doubleValue()); } /** * Returns the scale factor of this converter. * * @return the scale factor. */ public double getFactor() { return factor; } @Override public UnitConverter concatenate(UnitConverter converter) { if (!(converter instanceof MultiplyConverter)) return super.concatenate(converter); double newfactor = factor * ((MultiplyConverter) converter).factor; return newfactor == 1.0 ? IDENTITY : new MultiplyConverter(newfactor); } @Override public MultiplyConverter inverse() { return new MultiplyConverter(1.0 / factor); } @Override public double convert(double value) { return value * factor; } @Override public final String toString() { return MultiplyConverter.class.getSimpleName() + "(" + factor + ")"; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof MultiplyConverter) { MultiplyConverter that = (MultiplyConverter) obj; return Objects.equals(factor, that.factor); } return false; } @Override public int hashCode() { return Objects.hashCode(factor); } @Override public boolean isLinear() { return true; } public Double getValue() { return factor; } @Override public int compareTo(UnitConverter o) { if (this == o) { return 0; } if (o instanceof MultiplyConverter) { return getValue().compareTo(((MultiplyConverter) o).getValue()); } return -1; } } <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.spi; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.measure.Quantity; import javax.measure.format.QuantityFormat; import javax.measure.format.UnitFormat; /** * Service Provider for Units of Measurement services. * <p> * All the methods in this class are safe to use by multiple concurrent threads. * </p> * * @version 2.2, November 16, 2020 * @author <NAME> * @author <NAME> * @since 1.0 */ public abstract class ServiceProvider { /** * Class name of JSR-330 annotation for naming a service provider. * We use reflection for keeping JSR-330 an optional dependency. */ private static final String LEGACY_NAMED_ANNOTATION = "javax.inject.Named"; /** * Class name of JSR-250 annotation for assigning a priority level to a service provider. * We use reflection for keeping JSR-250 an optional dependency. */ private static final String LEGACY_PRIORITY_ANNOTATION = "javax.annotation.Priority"; /** * Class name of Jakarta Dependency Injection annotation for naming a service provider. * We use reflection for keeping Jakata Injection an optional dependency. */ private static final String NAMED_ANNOTATION = "jakarta.inject.Named"; /** * Class name of Jakarta Common Annotation for assigning a priority level to a service provider. * We use reflection for keeping Jakarta Annotations an optional dependency. */ private static final String PRIORITY_ANNOTATION = "jakarta.annotation.Priority"; /** * The current service provider, or {@code null} if not yet determined. * * <p>Implementation Note: We do not cache a list of all service providers because that list depends * indirectly on the thread invoking the {@link #available()} method. More specifically, it depends * on the context class loader. Furthermore caching the {@code ServiceProvider}s can be a source of * memory leaks. See {@link ServiceLoader#load(Class)} API note for reference.</p> */ private static final AtomicReference<ServiceProvider> current = new AtomicReference<>(); /** * Creates a new service provider. Only to be used by subclasses. */ protected ServiceProvider() { } /** * Allows to define a priority for a registered {@code ServiceProvider} instance. * When multiple providers are registered in the system, the provider with the highest priority value is taken. * * <p>If the {@value #PRIORITY_ANNOTATION} annotation (from Jakarta Annotations) * or {@value #LEGACY_PRIORITY_ANNOTATION} annotation (from JSR-250) is present on the {@code ServiceProvider} * implementation class, then that annotation (first if both were present) is taken and this {@code getPriority()} method is ignored. * Otherwise – if a {@code Priority} annotation is absent – this method is used as a fallback.</p> * * @return the provider's priority (default is 0). */ public int getPriority() { return 0; } /** * Returns the service to obtain a {@link SystemOfUnits}, or {@code null} if none. * * @return the service to obtain a {@link SystemOfUnits}, or {@code null}. */ public abstract SystemOfUnitsService getSystemOfUnitsService(); /** * Returns the service to obtain {@link UnitFormat} and {@link QuantityFormat} or {@code null} if none. * * @return the service to obtain a {@link UnitFormat} and {@link QuantityFormat}, or {@code null}. * @since 2.0 */ public abstract FormatService getFormatService(); /** * Returns a factory for the given {@link Quantity} type. * * @param <Q> * the type of the {@link Quantity} instances created by the factory * @param quantity * the quantity type * @return the {@link QuantityFactory} for the given type */ public abstract <Q extends Quantity<Q>> QuantityFactory<Q> getQuantityFactory(Class<Q> quantity); /** * A filter and a comparator for processing the stream of service providers. * The two tasks (filtering and sorting) are implemented by the same class, * but the filter task shall be used only if the name to search is non-null. * The comparator is used in all cases, for sorting providers with higher priority first. */ private static final class Selector implements Predicate<ServiceLoader.Provider<ServiceProvider>>, Comparator<ServiceLoader.Provider<ServiceProvider>> { /** * The name of the provider to search, or {@code null} if no filtering by name is applied. */ private final String toSearch; /** * The {@code value()} method in the {@value #NAMED_ANNOTATION} annotation, * or {@code null} if that class is not on the classpath. */ private final Method nameGetter; /** * The {@code value()} method in the {@value #PRIORITY_ANNOTATION} annotation, * or {@code null} if that class is not on the classpath. */ private final Method priorityGetter; /** * The {@code value()} method in the {@value #LEGACY_NAMED_ANNOTATION} annotation, * or {@code null} if that class is not on the classpath. */ private final Method legacyNameGetter; /** * The {@code value()} method in the {@value #LEGACY_PRIORITY_ANNOTATION} annotation, * or {@code null} if that class is not on the classpath. */ private final Method legacyPriorityGetter; /** * Creates a new filter and comparator for a stream of service providers. * * @param name name of the desired service provider, or {@code null} if no filtering by name is applied. */ Selector(String name) { toSearch = name; try { if (name != null) { nameGetter = getValueMethod(NAMED_ANNOTATION); legacyNameGetter = getValueMethod(LEGACY_NAMED_ANNOTATION); } else { nameGetter = null; legacyNameGetter = null; } priorityGetter = getValueMethod(PRIORITY_ANNOTATION); legacyPriorityGetter = getValueMethod(LEGACY_PRIORITY_ANNOTATION); } catch (NoSuchMethodException e) { // Should never happen since value() is a standard public method of those annotations. throw new ServiceConfigurationError("Cannot get annotation value", e); } } /** * Returns the {@code value()} method in the given annotation class. * * @param classname name of the class from which to get the {@code value()} method. * @return the {@code value()} method, or {@code null} if the annotation class was not found. */ private static Method getValueMethod(final String classname) throws NoSuchMethodException { try { return Class.forName(classname).getMethod("value", (Class[]) null); } catch (ClassNotFoundException e) { // Ignore because JSR-330, JSR-250 and Jakarta are optional dependencies. return null; } } /** * Invokes the {@code value()} method on the annotation of the given class. * The annotation on which to invoke the method is given by {@link Method#getDeclaringClass()}. * * @param provider class of the provider on which to invoke annotation {@code value()}. * @param getter the preferred {@code value()} method to invoke, or {@code null}. * @param fallback an alternative {@code value()} method to invoke, or {@code null}. * @return the value, or {@code null} if none. */ private static Object getValue(final Class<?> provider, Method getter, Method fallback) { if (getter == null) { getter = fallback; fallback = null; } while (getter != null) { final Annotation a = provider.getAnnotation(getter.getDeclaringClass().asSubclass(Annotation.class)); if (a != null) try { return getter.invoke(a, (Object[]) null); } catch (IllegalAccessException | InvocationTargetException e) { // Should never happen since value() is a public method and should not throw exception. throw new ServiceConfigurationError("Cannot get annotation value", e); } getter = fallback; fallback = null; } return null; } /** * Returns {@code true} if the given service provider has the name we are looking for. * This method shall be invoked only if a non-null name has been specified to the constructor. * This method looks for the {@value #NAMED_ANNOTATION} and {@value #LEGACY_NAMED_ANNOTATION} * annotations in that order, and if none are found fallbacks on {@link ServiceProvider#toString()}. */ public boolean test(final ServiceProvider provider) { Object value = getValue(provider.getClass(), nameGetter, legacyNameGetter); if (value == null) { value = provider.toString(); } return toSearch.equals(value); } /** * Same test than {@link #test(ServiceProvider)} but applied on a service provider with deferred instantiation. */ @Override public boolean test(final ServiceLoader.Provider<ServiceProvider> provider) { Object value = getValue(provider.type(), nameGetter, legacyNameGetter); if (value == null) { value = provider.get().toString(); } return toSearch.equals(value); } /** * Returns the priority of the given service provider. * This method looks for the {@value #PRIORITY_ANNOTATION} and {@value #LEGACY_PRIORITY_ANNOTATION} * annotations in that order, and if none are found falls back on {@link ServiceProvider#getPriority()}. */ private int priority(final ServiceLoader.Provider<ServiceProvider> provider) { Object value = getValue(provider.type(), priorityGetter, legacyPriorityGetter); if (value != null) { return (Integer) value; } return provider.get().getPriority(); } /** * Compares the given service providers for order based on their priority. * The priority of each provider is determined as documented by {@link ServiceProvider#getPriority()}. */ @Override public int compare(final ServiceLoader.Provider<ServiceProvider> p1, final ServiceLoader.Provider<ServiceProvider> p2) { return Integer.compare(priority(p2), priority(p1)); // reverse order, higher number first. } /** * Gets all {@link ServiceProvider}s sorted by priority and optionally filtered by the name in this selector. * The list of service providers is <strong>not</strong> cached because it depends on the context class loader, * which itself depends on which thread is invoking this method. */ private Stream<ServiceProvider> stream() { Stream<ServiceLoader.Provider<ServiceProvider>> stream = ServiceLoader.load(ServiceProvider.class).stream(); if (toSearch != null) { stream = stream.filter(this); } return stream.sorted(this).map(ServiceLoader.Provider::get); } } /** * Returns the list of all service providers available for the current thread's context class loader. * The {@linkplain #current() current} service provider is always the first item in the returned list. * Other service providers after the first item may depend on the caller thread * (see {@linkplain ServiceLoader#load(Class) service loader API note}). * * @return all service providers available for the current thread's context class loader. */ public static final List<ServiceProvider> available() { ArrayList<ServiceProvider> providers = new Selector(null).stream().collect(Collectors.toCollection(ArrayList::new)); final ServiceProvider first = current.get(); /* * Make sure that 'first' is the first item in the 'providers' list. If that item appears * somewhere else, we have to remove the second occurrence for avoiding duplicated elements. * We compare the classes, not the instances, because new instances may be created each time * this method is invoked and we have no guaranteed that implementors overrode 'equals'. */ setcur: if (first != null) { final Class<?> cf = first.getClass(); final int size = providers.size(); for (int i=0; i<size; i++) { if (cf.equals(providers.get(i).getClass())) { if (i == 0) break setcur; // No change needed (note: labeled breaks on if statements are legal). providers.remove(i); break; } } providers.add(0, first); } return providers; } /** * Returns the {@link ServiceProvider} with the specified name. * The given name must match the name of at least one service provider available in the current thread's * context class loader. * The service provider names are the values of {@value #NAMED_ANNOTATION} (from Jakarta Annotations) or * {@value #LEGACY_NAMED_ANNOTATION} (from JSR-330) annotations when present (first if both were present), * or the value of {@link #toString()} method for providers without {@code Named} annotation. * * <p>Implementors are encouraged to provide an {@code Named} annotation or to override {@link #toString()} * and use a unique enough name, e.g. the class name or other distinct attributes. * Should multiple service providers nevertheless use the same name, the one with the highest * {@linkplain #getPriority() priority} wins.</p> * * @param name * the name of the service provider to return * @return the {@link ServiceProvider} with the specified name * @throws IllegalArgumentException * if available service providers do not contain a provider with the specified name * @throws NullPointerException * if {@code name} is null * @see #toString() * @since 2.0 */ public static ServiceProvider of(String name) { Objects.requireNonNull(name); Selector select = new Selector(name); ServiceProvider p = current.get(); if (p != null && select.test(p)) { return p; } Optional<ServiceProvider> first = select.stream().findFirst(); if (first.isPresent()) { return first.get(); } else { throw new IllegalArgumentException("No Measurement ServiceProvider " + name + " found ."); } } /** * Returns the current {@link ServiceProvider}. If necessary the {@link ServiceProvider} will be lazily loaded. * <p> * If there are no providers available, an {@linkplain IllegalStateException} is thrown. * Otherwise the provider with the highest priority is used * or the one explicitly designated via {@link #setCurrent(ServiceProvider)}. * </p> * * @return the {@link ServiceProvider} used. * @throws IllegalStateException * if no {@link ServiceProvider} has been found. * @see #getPriority() * @see #setCurrent(ServiceProvider) */ public static final ServiceProvider current() { ServiceProvider p = current.get(); if (p == null) { Optional<ServiceProvider> first = new Selector(null).stream().findFirst(); if (first.isPresent()) { p = first.get(); } else { throw new IllegalStateException("No Measurement ServiceProvider found."); } } return p; } /** * Replaces the current {@link ServiceProvider}. * * @param provider * the new {@link ServiceProvider} * @return the replaced provider, or null. */ public static final ServiceProvider setCurrent(ServiceProvider provider) { Objects.requireNonNull(provider); ServiceProvider old = current.getAndSet(provider); if (old != provider) { System.getLogger("javax.measure.spi").log(System.Logger.Level.DEBUG, "Measurement ServiceProvider {1,choice,0#set to|1#replaced by} {0}.", new Object[] {provider.getClass().getName(), (old == null) ? 0 : 1}); } return old; } } <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure; /** * Provides support for common binary prefixes to be used by units. For example: * <pre> * {@code import static systems.uom.unicode.CLDR.*; // Static import (from Unicode System). * import static javax.measure.BinaryPrefix.*; // Static import. * import javax.measure.*; * import systems.uom.quantity.Information; // (from Systems Quantities) * ... * Unit<Information> MEBIT = MEBI(BIT); * Unit<Information> GIBYTE = GIBI(BYTE);} * </pre> * You could also apply <code>Unit.prefix</code>: * <pre> * {@code ... * Unit<Information> MEBIT = BIT.prefix(MEBI); * Unit<Information> GIBYTE = BYTE.prefix(GIBI);} * </pre> * * <p> * <b>Do not use ordinal() to obtain the numeric representation of BinaryPrefix. Use getValue() and getExponent() instead.</b> * </p> * * <dl> * <dt><span class="strong">Implementation Requirements</span></dt><dd>This is an immutable and thread-safe enum.</dd> * </dl> * * @author <a href="mailto:<EMAIL>"><NAME></a> * @version 2.2, May 20, 2023 * @see <a href="https://en.wikipedia.org/wiki/Binary_prefix">Wikipedia: Binary Prefix</a> * @since 2.0 */ public enum BinaryPrefix implements Prefix { /** Prefix for 1024. */ KIBI("Ki", 1), /** Prefix for 1024<sup>2</sup>. */ MEBI("Mi", 2), /** Prefix for 1024<sup>3</sup>. */ GIBI("Gi", 3), /** Prefix for 1024<sup>4</sup>. */ TEBI("Ti", 4), /** Prefix for 1024<sup>5</sup>. */ PEBI("Pi", 5), /** Prefix for 1024<sup>6</sup>. */ EXBI("Ei", 6), /** Prefix for 1024<sup>7</sup>. */ ZEBI("Zi", 7), /** Prefix for 1024<sup>8</sup>. */ YOBI("Yi", 8); /** * The symbol of this prefix, as returned by {@link #getSymbol}. * * @serial * @see #getSymbol() */ private final String symbol; /** * Exponent part of the associated factor in base^exponent representation. */ private final int exponent; /** * Creates a new prefix. * * @param symbol * the symbol of this prefix. * @param exponent * part of the associated factor in base^exponent representation. */ private BinaryPrefix(String symbol, int exponent) { this.symbol = symbol; this.exponent = exponent; } /** * Returns the specified unit multiplied by the factor <code>1024</code> (binary prefix). * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.multiply(1024)</code>. */ public static <Q extends Quantity<Q>> Unit<Q> KIBI(Unit<Q> unit) { return unit.prefix(KIBI); } /** * Returns the specified unit multiplied by the factor <code>1024<sup>2</sup></code> (binary prefix). * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.multiply(1048576)</code>. */ public static <Q extends Quantity<Q>> Unit<Q> MEBI(Unit<Q> unit) { return unit.prefix(MEBI); } /** * Returns the specified unit multiplied by the factor <code>1024<sup>3</sup></code> (binary prefix). * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.multiply(1073741824)</code>. */ public static <Q extends Quantity<Q>> Unit<Q> GIBI(Unit<Q> unit) { return unit.prefix(GIBI); } /** * Returns the specified unit multiplied by the factor <code>1024<sup>4</sup></code> (binary prefix). * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.multiply(1099511627776L)</code>. */ public static <Q extends Quantity<Q>> Unit<Q> TEBI(Unit<Q> unit) { return unit.prefix(TEBI); } /** * Returns the specified unit multiplied by the factor <code>1024<sup>5</sup></code> (binary prefix). * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.multiply(1125899906842624L)</code>. */ public static <Q extends Quantity<Q>> Unit<Q> PEBI(Unit<Q> unit) { return unit.prefix(PEBI); } /** * Returns the specified unit multiplied by the factor <code>1024<sup>6</sup></code> (binary prefix). * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.multiply(1152921504606846976L)</code>. */ public static <Q extends Quantity<Q>> Unit<Q> EXBI(Unit<Q> unit) { return unit.prefix(EXBI); } /** * Returns the specified unit multiplied by the factor <code>1024<sup>7</sup></code> (binary prefix). * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.multiply(1152921504606846976d)</code>. */ public static <Q extends Quantity<Q>> Unit<Q> ZEBI(Unit<Q> unit) { return unit.prefix(ZEBI); } /** * Returns the specified unit multiplied by the factor <code>1024<sup>8</sup></code> (binary prefix). * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.multiply(1208925819614629174706176d)</code>. */ public static <Q extends Quantity<Q>> Unit<Q> YOBI(Unit<Q> unit) { return unit.prefix(YOBI); } /** * Returns the symbol of this prefix. * * @return this prefix symbol, not {@code null}. */ @Override public String getSymbol() { return symbol; } /** * Base part of the associated factor in {@code base^exponent} representation. For binary prefix, this is always 1024. */ @Override public Integer getValue() { return 1024; } /** * Exponent part of the associated factor in {@code base^exponent} representation. */ @Override public int getExponent() { return exponent; } /** * Returns the name of this prefix. * * @return this prefix name, not {@code null}. */ @Override public String getName() { return name(); } } <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.test.quantity; import javax.measure.Quantity; import javax.measure.Unit; import javax.measure.quantity.Volume; import javax.measure.test.unit.AreaUnit; import javax.measure.test.unit.DistanceUnit; import javax.measure.test.unit.VolumeUnit; /** * @author <NAME> * @version 0.6 */ public class VolumeQuantity extends TestQuantity<Volume> { public VolumeQuantity() { super(Volume.class); } public VolumeQuantity(double val, VolumeUnit un) { this(); value = val; unit = un; scalar = val * unit.getMultFactor(); } public VolumeQuantity(Number val, Unit un) { this(val.doubleValue(), (VolumeUnit) un); } public VolumeQuantity add(VolumeQuantity d1) { VolumeQuantity dn = new VolumeQuantity(); Object o = super.add(dn, this, d1, VolumeUnit.REF_UNIT); return (VolumeQuantity) o; } public VolumeQuantity subtract(VolumeQuantity d1) { VolumeQuantity dn = new VolumeQuantity(); Object o = super.subtract(dn, this, d1, VolumeUnit.REF_UNIT); return (VolumeQuantity) o; } public boolean eq(VolumeQuantity d1) { return super.eq(d1); } public boolean ne(VolumeQuantity d1) { return super.ne(d1); } public boolean gt(VolumeQuantity d1) { return super.gt(d1); } public boolean lt(VolumeQuantity d1) { return super.lt(d1); } public boolean ge(VolumeQuantity d1) { return super.ge(d1); } public boolean le(VolumeQuantity d1) { return super.le(d1); } public VolumeQuantity multiply(double v) { return new VolumeQuantity(value * v, (VolumeUnit) unit); } public VolumeQuantity divide(double v) { return new VolumeQuantity(value / v, (VolumeUnit) unit); } // mixed type operations public AreaQuantity divide(DistanceQuantity d1) { VolumeQuantity dq0 = convert(VolumeUnit.cumetre); DistanceQuantity dq1 = d1.convert(DistanceUnit.m); return new AreaQuantity(dq0.value / dq1.value, AreaUnit.sqmetre); } public DistanceQuantity divide(AreaQuantity a1) { VolumeQuantity dq0 = convert(VolumeUnit.cumetre); AreaQuantity dq1 = a1.convert(AreaUnit.sqmetre); return new DistanceQuantity(dq0.value / dq1.value, DistanceUnit.m); } public VolumeQuantity convert(VolumeUnit newUnit) { return new VolumeQuantity(scalar / newUnit.getMultFactor(), newUnit); } public String showInUnits(VolumeUnit u, int precision) { return super.showInUnits(u, precision); } public Quantity<?> divide(Quantity<?> that) { // TODO Auto-generated method stub return null; } public Quantity<Volume> subtract(Quantity<Volume> that) { // TODO Auto-generated method stub return null; } public Quantity<Volume> add(Quantity<Volume> that) { // TODO Auto-generated method stub return null; } public Quantity<Volume> divide(Number that) { return divide(that.doubleValue()); } public Quantity<Volume> inverse() { // TODO Auto-generated method stub return null; } public Quantity<Volume> multiply(Number that) { return multiply(that.doubleValue()); } public Quantity<Volume> to(Unit<Volume> unit) { // TODO Auto-generated method stub return null; } public Quantity<?> multiply(Quantity<?> that) { // TODO Auto-generated method stub return null; } @Override public Quantity<Volume> negate() { return new VolumeQuantity(-value, getUnit()); } @SuppressWarnings({ "unchecked", "rawtypes" }) public final <T extends Quantity<T>> Quantity<T> asType(Class<T> type) throws ClassCastException { this.getUnit().asType(type); // Raises ClassCastException is dimension // mismatches. return (Quantity) this; } } <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.test; import java.util.ArrayList; import java.util.List; import javax.measure.UnitConverter; /** * <p> * Test class for our {@link UnitConverter} implementations. * </p> * * @author <a href="mailto:<EMAIL>"><NAME></a> * @version 0.8.1, $Date: 2016-02-11 $ */ public abstract class TestConverter implements UnitConverter { /** * Holds identity converter. */ public static final TestConverter IDENTITY = new Identity(); /** * Default constructor. */ protected TestConverter() { } /** * Concatenates this physics converter with another unit converter. The resulting converter is equivalent to first converting by the specified * converter (right converter), and then converting by this converter (left converter). * * @param that * the other converter. * @return the concatenation of this converter with that converter. */ public TestConverter concatenate(TestConverter that) { return (IDENTITY.equals(that)) ? this : new Pair(this, that); } public boolean isIdentity() { return false; } @Override public abstract boolean equals(Object cvtr); @Override public abstract int hashCode(); @Override public abstract TestConverter inverse(); @Override public UnitConverter concatenate(UnitConverter converter) { return (IDENTITY.equals(converter)) ? this : new Pair(this, converter); } @Override public List<? extends UnitConverter> getConversionSteps() { final List<TestConverter> steps = new ArrayList<TestConverter>(); steps.add(this); return steps; } /** * @throws IllegalArgumentException * if the value is <code>null</code>. */ public Number convert(Number value) { if (value != null) { return convert(value.doubleValue()); } else { throw new IllegalArgumentException("Value cannot be null"); } } public abstract double convert(double value); /** * This class represents the identity converter (singleton). */ private static final class Identity extends TestConverter { @Override public boolean isIdentity() { return true; } @Override public Identity inverse() { return this; } @Override public double convert(double value) { return value; } @Override public UnitConverter concatenate(UnitConverter converter) { return converter; } @Override public boolean equals(Object cvtr) { return (cvtr instanceof Identity); } @Override public int hashCode() { return 0; } public boolean isLinear() { return true; } } /** * This class represents converters made up of two or more separate converters (in matrix notation <code>[pair] = [left] x [right]</code>). */ public static final class Pair extends TestConverter { /** * Holds the first converter. */ private final UnitConverter left; /** * Holds the second converter. */ private final UnitConverter right; /** * Creates a compound converter resulting from the combined transformation of the specified converters. * * @param left * the left converter. * @param right * the right converter. * @throws IllegalArgumentException * if either the left or right converter are <code>null</code> */ public Pair(UnitConverter left, UnitConverter right) { this.left = left; this.right = right; } public boolean isLinear() { return left.isLinear() && right.isLinear(); } @Override public boolean isIdentity() { return false; } @Override public List<UnitConverter> getConversionSteps() { final List<UnitConverter> steps = new ArrayList<UnitConverter>(); List<? extends UnitConverter> leftCompound = left.getConversionSteps(); List<? extends UnitConverter> rightCompound = right.getConversionSteps(); steps.addAll(leftCompound); steps.addAll(rightCompound); return steps; } @Override public Pair inverse() { return new Pair(right.inverse(), left.inverse()); } @Override public double convert(double value) { return left.convert(right.convert(value)); } @Override public boolean equals(Object cvtr) { if (this == cvtr) return true; if (!(cvtr instanceof Pair)) return false; Pair that = (Pair) cvtr; return (this.left.equals(that.left)) && (this.right.equals(that.right)); } @Override public int hashCode() { return left.hashCode() + right.hashCode(); } public UnitConverter getLeft() { return left; } public UnitConverter getRight() { return right; } } } <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.format; import java.io.IOException; import java.text.ParsePosition; import javax.measure.Unit; /** * Formats instances of {@link Unit} to a {@link String} or {@link Appendable} and parses a {@link CharSequence} to a {@link Unit}. * * <dl> * <dt><span class="strong"><a id="synchronization">Synchronization</a></span></dt> * </dl> * <p> * Instances of this class are not required to be thread-safe. It is recommended to use separate format instances for each thread. If multiple threads * access a format concurrently, it must be synchronized externally. * </p> * * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>"><NAME></a> * * @version 2.2, May 20, 2023 * @since 1.0 * * @see Unit */ public interface UnitFormat { /** * Formats the specified {@link Unit}. * * @param unit * the {@link Unit} to format, not {@code null} * @param appendable * the appendable destination. * @return the appendable destination passed in with formatted text appended. * @throws IOException * if an error occurs while writing to the destination. */ Appendable format(Unit<?> unit, Appendable appendable) throws IOException; /** * Formats the specified {@link Unit}. * * @param unit * the {@link Unit} to format, not {@code null} * @return the string representation using the settings of this {@link UnitFormat}. */ String format(Unit<?> unit); /** * Attaches a system-wide label to the specified {@link Unit}. * <p> * This method overrides the previous unit's label (e.g. label from unit database or unit system) as units may only have one label. Depending on the * {@link UnitFormat} implementation, this call may be ignored if the particular unit already has a label. * </p> * If a {@link UnitFormat} implementation is explicitly <b>immutable</b>, similar to e.g. the result of <code>Collections.unmodifiableList()</code>, * then an {@linkplain UnsupportedOperationException} may be thrown upon this call. * <p> * Since <code>UnitFormat</code> implementations often apply the Singleton pattern, <b>system-wide</b> means, the label applies to every instance of * <code>UnitFormatA</code> implementing <code>UnitFormat</code> in this case, but not every instance of <code>UnitFormatB</code> or <code>UnitFormatC</code> both * also implementing <code>UnitFormat</code>. If a <code>UnitFormat</code> #isLocaleSensitive() it is up to the implementation, whether the label is * ignored, applied in a local-neutral manner (in addition to its local-sensitive information) or locale-specific. * </p> * * @param unit * the unit being labeled. * @param label * the new label for this unit. * @throws IllegalArgumentException * if the label is not a valid identifier. This may include characters not supported by a particular {@link UnitFormat} implementation * (e.g. only <b>ASCII</b> characters for certain devices) * @throws UnsupportedOperationException * if the <code>label</code> operation is not supported by this {@link UnitFormat} */ void label(Unit<?> unit, String label); /** * Returns <code>true</code> if this {@link UnitFormat} depends on a <code>Locale</code> to perform its tasks. * <p> * In environments that do not support a <code>Locale</code>, e.g. Java ME, this usually returns <code>false</code>. * </p> * * @return Whether this format depends on a locale. */ default boolean isLocaleSensitive() { return false; } /** * Parses a portion of the specified <code>CharSequence</code> from the specified position to produce a {@link Unit}. * If parsing succeeds, then the index of the <code>pos</code> argument is updated to the index after the last character used. * * @param csq * the <code>CharSequence</code> to parse. * @param pos * a ParsePosition object holding the current parsing index and error parsing index information as described above. * @return the unit parsed from the specified character sub-sequence. * @throws MeasurementParseException * if any problem occurs while parsing the specified character sequence (e.g. illegal syntax). * @since 2.0 */ Unit<?> parse(CharSequence csq, ParsePosition pos) throws MeasurementParseException; /** * Parses the text into an instance of {@link Unit}. * <p> * The parse must complete normally and parse the entire text. If the parse completes without reading the entire length of the text, an exception * is thrown. If any other problem occurs during parsing, an exception is thrown. * </p> * * @param csq * the {@code CharSequence} to parse. * @return the unit parsed from the specified character sequence. * @throws MeasurementParseException * if any problem occurs while parsing the specified character sequence (e.g. illegal syntax). * @throws UnsupportedOperationException * if the {@link UnitFormat} is unable to parse. * @since 2.0 */ Unit<?> parse(CharSequence csq) throws MeasurementParseException; } <file_sep>EMF --- To load or edit UML diagrams... Use [Eclipse Papyrus ](http://eclipse.org/papyrus/) <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure; /** * Provides support for the 24 prefixes used in the metric system (decimal multiples and submultiples of units). For example: * * <pre> * {@code import static tech.units.indriya.unit.Units.*; // Static import (from the RI). * import static javax.measure.MetricPrefix.*; // Static import. * import javax.measure.*; * import javax.measure.quantity.*; * ... * Unit<Pressure> HECTOPASCAL = HECTO(PASCAL); * Unit<Length> KILOMETRE = KILO(METRE);} * </pre> * You could also apply <code>Unit.prefix</code>: * <pre> * {@code ... * Unit<Pressure> HECTOPASCAL = PASCAL.prefix(HECTO); * Unit<Length> KILOMETRE = METRE.prefix(KILO);} * </pre> * * <p> * <b>Do not use ordinal() to obtain the numeric representation of MetricPrefix. Use getValue() and getExponent() instead.</b> * </p> * * <dl> * <dt><span class="strong">Implementation Requirements</span></dt><dd>This is an immutable and thread-safe enum.</dd> * </dl> * * @see <a href="https://en.wikipedia.org/wiki/Metric_prefix">Wikipedia: Metric Prefix</a> * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>"><NAME></a> * @version 2.3, May 20, 2023 * @since 2.0 */ public enum MetricPrefix implements Prefix { /** Prefix for 10<sup>30</sup>. */ QUETTA("Q", 30), /** Prefix for 10<sup>27</sup>. */ RONNA("R", 27), /** Prefix for 10<sup>24</sup>. */ YOTTA("Y", 24), /** Prefix for 10<sup>21</sup>. */ ZETTA("Z", 21), /** Prefix for 10<sup>18</sup>. */ EXA("E", 18), /** Prefix for 10<sup>15</sup>. */ PETA("P", 15), /** Prefix for 10<sup>12</sup>. */ TERA("T", 12), /** Prefix for 10<sup>9</sup>. * @see <a href="https://en.wikipedia.org/wiki/Giga-">Wikipedia: Giga</a> */ GIGA("G", 9), /** Prefix for 10<sup>6</sup>. * @see <a href="https://en.wikipedia.org/wiki/Mega-">Wikipedia: Mega</a> */ MEGA("M", 6), /** Prefix for 10<sup>3</sup>. * @see <a href="https://en.wikipedia.org/wiki/Kilo-">Wikipedia: Kilo</a> */ KILO("k", 3), /** Prefix for 10<sup>2</sup>. * @see <a href="https://en.wikipedia.org/wiki/Hecto-">Wikipedia: Hecto</a> */ HECTO("h", 2), /** Prefix for 10<sup>1</sup>. * @see <a href="https://en.wikipedia.org/wiki/Deca-">Wikipedia: Deca</a> */ DECA("da", 1), /** Prefix for 10<sup>-1</sup>. * @see <a href="https://en.wikipedia.org/wiki/Deci-">Wikipedia: Deci</a> */ DECI("d", -1), /** Prefix for 10<sup>-2</sup>. * @see <a href="https://en.wikipedia.org/wiki/Centi-">Wikipedia: Centi</a> */ CENTI("c", -2), /** Prefix for 10<sup>-3</sup>. * @see <a href="https://en.wikipedia.org/wiki/Milli-">Wikipedia: Milli</a> */ MILLI("m", -3), /** Prefix for 10<sup>-6</sup>. * @see <a href="https://en.wikipedia.org/wiki/Micro-">Wikipedia: Micro</a> */ MICRO("\u00b5", -6), /** Prefix for 10<sup>-9</sup>. * @see <a href="https://en.wikipedia.org/wiki/Nano-">Wikipedia: Nano</a> */ NANO("n", -9), /** Prefix for 10<sup>-12</sup>. */ PICO("p", -12), /** Prefix for 10<sup>-15</sup>. */ FEMTO("f", -15), /** Prefix for 10<sup>-18</sup>. */ ATTO("a", -18), /** Prefix for 10<sup>-21</sup>. */ ZEPTO("z", -21), /** Prefix for 10<sup>-24</sup>. */ YOCTO("y", -24), /** Prefix for 10<sup>-27</sup>. */ RONTO("r", -27), /** Prefix for 10<sup>-30</sup>. */ QUECTO("q", -30); /** * The symbol of this prefix, as returned by {@link #getSymbol}. * * @serial * @see #getSymbol() */ private final String symbol; /** * Exponent part of the associated factor in base^exponent representation. */ private final int exponent; /** * Creates a new prefix. * * @param symbol * the symbol of this prefix. * @param exponent * part of the associated factor in base^exponent representation. */ private MetricPrefix(String symbol, int exponent) { this.symbol = symbol; this.exponent = exponent; } /** * Returns the specified unit multiplied by the factor <code>10<sup>30</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e30)</code>. * @see #QUETTA */ public static <Q extends Quantity<Q>> Unit<Q> QUETTA(Unit<Q> unit) { return unit.prefix(QUETTA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>27</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e27)</code>. * @see #RONNA */ public static <Q extends Quantity<Q>> Unit<Q> RONNA(Unit<Q> unit) { return unit.prefix(RONNA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>24</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e24)</code>. * @see #YOTTA */ public static <Q extends Quantity<Q>> Unit<Q> YOTTA(Unit<Q> unit) { return unit.prefix(YOTTA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>21</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e21)</code>. * @see #ZETTA */ public static <Q extends Quantity<Q>> Unit<Q> ZETTA(Unit<Q> unit) { return unit.prefix(ZETTA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>18</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e18)</code>. * @see #EXA */ public static <Q extends Quantity<Q>> Unit<Q> EXA(Unit<Q> unit) { return unit.prefix(EXA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>15</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e15)</code>. * @see #PETA */ public static <Q extends Quantity<Q>> Unit<Q> PETA(Unit<Q> unit) { return unit.prefix(PETA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>12</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e12)</code>. * @see #TERA */ public static <Q extends Quantity<Q>> Unit<Q> TERA(Unit<Q> unit) { return unit.prefix(TERA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>9</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e9)</code>. * @see #GIGA */ public static <Q extends Quantity<Q>> Unit<Q> GIGA(Unit<Q> unit) { return unit.prefix(GIGA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>6</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e6)</code>. * @see #MEGA */ public static <Q extends Quantity<Q>> Unit<Q> MEGA(Unit<Q> unit) { return unit.prefix(MEGA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>3</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e3)</code>. * @see #KILO */ public static <Q extends Quantity<Q>> Unit<Q> KILO(Unit<Q> unit) { return unit.prefix(KILO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>2</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e2)</code>. * @see #HECTO */ public static <Q extends Quantity<Q>> Unit<Q> HECTO(Unit<Q> unit) { return unit.prefix(HECTO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>1</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e1)</code>. * @see #DECA */ public static <Q extends Quantity<Q>> Unit<Q> DECA(Unit<Q> unit) { return unit.prefix(DECA); } /** * US alias for <code>DECA</code>. * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e1)</code>. * @see #DECA */ public static <Q extends Quantity<Q>> Unit<Q> DEKA(Unit<Q> unit) { return unit.prefix(DECA); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-1</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-1)</code>. * @see #DECI */ public static <Q extends Quantity<Q>> Unit<Q> DECI(Unit<Q> unit) { return unit.prefix(DECI); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-2</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-2)</code>. * @see #CENTI */ public static <Q extends Quantity<Q>> Unit<Q> CENTI(Unit<Q> unit) { return unit.prefix(CENTI); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-3</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-3)</code>. * @see #MILLI */ public static <Q extends Quantity<Q>> Unit<Q> MILLI(Unit<Q> unit) { return unit.prefix(MILLI); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-6</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-6)</code>. * @see #MICRO */ public static <Q extends Quantity<Q>> Unit<Q> MICRO(Unit<Q> unit) { return unit.prefix(MICRO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-9</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-9)</code>. * @see #NANO */ public static <Q extends Quantity<Q>> Unit<Q> NANO(Unit<Q> unit) { return unit.prefix(NANO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-12</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-12)</code>. * @see #PICO */ public static <Q extends Quantity<Q>> Unit<Q> PICO(Unit<Q> unit) { return unit.prefix(PICO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-15</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-15)</code>. * @see #FEMTO */ public static <Q extends Quantity<Q>> Unit<Q> FEMTO(Unit<Q> unit) { return unit.prefix(FEMTO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-18</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-18)</code>. * @see #ATTO */ public static <Q extends Quantity<Q>> Unit<Q> ATTO(Unit<Q> unit) { return unit.prefix(ATTO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-21</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-21)</code>. * #see ZEPTO */ public static <Q extends Quantity<Q>> Unit<Q> ZEPTO(Unit<Q> unit) { return unit.prefix(ZEPTO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-24</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-24)</code>. * @see #YOCTO */ public static <Q extends Quantity<Q>> Unit<Q> YOCTO(Unit<Q> unit) { return unit.prefix(YOCTO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-27</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-27)</code>. * @see #RONTO */ public static <Q extends Quantity<Q>> Unit<Q> RONTO(Unit<Q> unit) { return unit.prefix(RONTO); } /** * Returns the specified unit multiplied by the factor <code>10<sup>-30</sup></code> * * @param <Q> * type of the quantity measured by the unit. * @param unit * any unit. * @return <code>unit.times(1e-30)</code>. * @see #QUECTO */ public static <Q extends Quantity<Q>> Unit<Q> QUECTO(Unit<Q> unit) { return unit.prefix(QUECTO); } /** * Returns the symbol of this prefix. * * @return this prefix symbol, not {@code null}. */ @Override public String getSymbol() { return symbol; } /** * Base part of the associated factor in {@code base^exponent} representation. For metric prefix, this is always 10. */ @Override public Integer getValue() { return 10; } /** * Exponent part of the associated factor in {@code base^exponent} representation. */ @Override public int getExponent() { return exponent; } /** * Returns the name of this prefix. * * @return this prefix name, not {@code null}. */ @Override public String getName() { return name(); } } <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.spi; import jakarta.inject.Named; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; import java.util.Collection; import javax.measure.BinaryPrefix; import javax.measure.MetricPrefix; import javax.measure.Prefix; import javax.measure.Quantity; /** * Tests for {@link ServiceProvider}. */ public class ServiceProviderTest { @Test public void testSetCurrentNull() { assertThrows(NullPointerException.class, () -> { ServiceProvider.setCurrent(null); }); } /** * Tests {@link ServiceProvider#current()} and {@link ServiceProvider#setCurrent(ServiceProvider)}. The getter and setter are tested in a single * method for avoiding issues with the order in which JUnit executes tests. */ @Test public void testGetAndSetCurrent() { assertEquals(0, ServiceProvider.available().size()); try { ServiceProvider.current(); fail("Expected no ServiceProvider before we set one."); } catch (IllegalStateException e) { // This is the expected exception. } ServiceProvider testProv = new TestServiceProvider(); assertNull(ServiceProvider.setCurrent(testProv), "Expected no ServiceProvider before we set one."); assertSame(testProv, ServiceProvider.setCurrent(testProv), "Setting the same ServiceProvider twice should be a no-op."); assertSame(testProv, ServiceProvider.current()); assertArrayEquals(new ServiceProvider[] { testProv }, ServiceProvider.available().toArray()); assertNotNull(ServiceProvider.of("Dummy ServiceProvider")); } /** * Tests {@link ServiceProvider#getPriority()}. */ @Test public void testPriority() { assertEquals(0, ServiceProvider.current().getPriority()); } /** * Tests ServiceProvider#of() by passing null. */ @Test public void testOfNull() { assertThrows(NullPointerException.class, () -> { @SuppressWarnings("unused") ServiceProvider dummy = ServiceProvider.of(null); }); } /** * Tests ServiceProvider#of() by passing a non-existing name. */ @Test public void testOfNonExistent() { assertThrows(IllegalArgumentException.class, () -> { @SuppressWarnings("unused") ServiceProvider dummy = ServiceProvider.of("ThisServiceProviderWillNeverExistHere"); }); } @Test public void testGetMetricPrefixes() { final ServiceProvider testProv = new TestServiceProvider(); final SystemOfUnitsService service = testProv.getSystemOfUnitsService(); Collection<MetricPrefix> prefixes = service.getPrefixes(MetricPrefix.class); assertNotNull(prefixes); assertEquals(24, prefixes.size()); } @Test public void testGetBinaryPrefixes() { final ServiceProvider testProv = new TestServiceProvider(); final SystemOfUnitsService service = testProv.getSystemOfUnitsService(); assertNotNull(service); Collection<BinaryPrefix> prefixes = service.getPrefixes(BinaryPrefix.class); assertNotNull(prefixes); assertEquals(8, prefixes.size()); } @Test public void testWrongPrefixType() { final ServiceProvider testProv = new TestServiceProvider(); final SystemOfUnitsService service = testProv.getSystemOfUnitsService(); assertNotNull(service); assertThrows(ClassCastException.class, () -> { @SuppressWarnings({ "unused", "rawtypes", "unchecked" }) Collection<Prefix> prefixes = service.getPrefixes((Class) String.class); }); } @Test public void testWrongEnumType() { final ServiceProvider testProv = new TestServiceProvider(); final SystemOfUnitsService service = testProv.getSystemOfUnitsService(); assertNotNull(service); assertThrows(ClassCastException.class, () -> { @SuppressWarnings({ "unused", "rawtypes", "unchecked" }) Collection<Prefix> prefixes = service.getPrefixes((Class) DummyEnum.class); }); } @Named("Dummy ServiceProvider") // Intentionally use a name different than "TestServiceProvider". private static final class TestServiceProvider extends ServiceProvider { @Override public SystemOfUnitsService getSystemOfUnitsService() { return new TestSystemOfUnitsService(); } @Override public <Q extends Quantity<Q>> QuantityFactory<Q> getQuantityFactory(Class<Q> quantity) { return null; } @Override public FormatService getFormatService() { return null; } @Override public String toString() { return "TestServiceProvider"; } } private static enum DummyEnum { A, B } } <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.test.format; import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import javax.measure.Quantity; import javax.measure.Unit; import javax.measure.format.MeasurementParseException; import javax.measure.format.UnitFormat; import javax.measure.quantity.Length; import javax.measure.quantity.Speed; import javax.measure.test.quantity.DistanceQuantity; import javax.measure.test.unit.DistanceUnit; import javax.measure.test.unit.SpeedUnit; import javax.measure.test.unit.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * @author <a href="mailto:<EMAIL>"><NAME></a> * */ public class UnitFormatTest { private Quantity<Length> sut; private UnitFormat format; @BeforeEach public void init() { sut = new DistanceQuantity(10, DistanceUnit.m); format = SimpleTestUnitFormat.getInstance(); } @Test public void testFormatKph() { Unit<Speed> kph = SpeedUnit.kmh; assertEquals("km/h", kph.toString()); } @Test public void testParseSimple() { assertThrows(MeasurementParseException.class, () -> { Unit<?> u = format.parse("s"); assertNotNull(u); assertEquals("s", u.getSymbol()); }); } @Test public void testFormatFromQuantity() { assertThrows(IllegalArgumentException.class, () -> { final Appendable a = new StringBuilder(); try { format.format(DistanceUnit.m, a); } catch (IOException e) { fail(e.getMessage()); } assertEquals(DistanceUnit.m, sut.getUnit()); assertEquals("m", a.toString()); final Appendable a2 = new StringBuilder(); @SuppressWarnings("unchecked") Unit<Speed> v = (Unit<Speed>) sut.getUnit().divide(TimeUnit.s); try { format.format(v, a2); } catch (IOException e) { fail(e.getMessage()); } assertEquals("m/s", a2.toString()); }); } @Test public void testParseIrregularString() { assertThrows(MeasurementParseException.class, () -> { @SuppressWarnings("unused") Unit<?> u = format.parse("bl//^--1a"); }); } @Test public void testParserException() { assertThrows(MeasurementParseException.class, () -> { throw new MeasurementParseException(new IllegalArgumentException()); }); } @Test public void testParserExceptionWithPosition() { MeasurementParseException pe = assertThrows(MeasurementParseException.class, () -> { throw new MeasurementParseException("test", 1); }); assertEquals(1, pe.getPosition()); assertEquals("test", pe.getParsedString()); } @Test public void testParserExceptionWithNullString() { final MeasurementParseException pe = assertThrows(MeasurementParseException.class, () -> { throw new MeasurementParseException(null, 0); }); assertEquals(0, pe.getPosition()); assertNull(pe.getParsedString()); } @Test public void testLocalSensitive() { assertFalse(format.isLocaleSensitive()); } @Test public void testMoreLocalSensitive() { final UnitFormat simple = SimpleTestUnitFormat.getInstance(); assertFalse(simple.isLocaleSensitive()); } } <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.spi; import java.util.Collection; import java.util.EnumSet; import java.util.Set; import javax.measure.Prefix; /** * This interface represents the service to obtain a {@link SystemOfUnits system * of units}. * * <p> * Common systems of units are "SI" (System International) or Metric system, * "Imperial" (British), or "US" (US Customary). * </p> * * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>"><NAME></a> * @author <a href="mailto:<EMAIL>">Martin * Desruisseaux</a> * @version 1.8, April 3, 2023 * @since 1.0 * * @see <a href= * "https://en.wikipedia.org/wiki/International_System_of_Units">Wikipedia: * International System of Units</a> */ public interface SystemOfUnitsService { /** * Returns the default {@link SystemOfUnits system of units}. Depending on the * implementation this may be the <a href="https://en.wikipedia.org/wiki/International_System_of_Units">International * System of Units</a> or another default system. * * @return the default system of units. */ SystemOfUnits getSystemOfUnits(); /** * Returns the system of units having the specified name or {@code null} if * none is found. * * @param name the system of unit name. * @return the system of units for the given name. */ SystemOfUnits getSystemOfUnits(String name); /** * Gets a list with available systems for this {@link SystemOfUnitsService}. * * @return list of available systems of units, never null. */ Collection<SystemOfUnits> getAvailableSystemsOfUnits(); /** * Returns a {@link Set} containing the values of a particular {@link Prefix} * type. * * <p> * This method may be used to iterate over certain prefixes as follows: * </p> * <pre>{@code * for(MetricPrefix mp : service.getPrefixes(MetricPrefix.class)) * System.out.println(p); * }</pre> * * The default implementation assumes that prefixes of the given type are implemented as an enumeration. * This is the case of the two default prefix implementations provided in JSR 385, * namely {@link javax.measure.MetricPrefix} and {@link javax.measure.BinaryPrefix}. * Implementors shall override this method if they provide prefixes implemented in a different way. * * @param <P> compile-time value of the {@code prefixType} argument * @param prefixType the {@link Prefix} type * @return a set containing the constant values of this Prefix type, in the * order they're declared * @throws ClassCastException if the class is not compatible with the desired * Prefix implementation or does not implement Prefix at all. * @since 2.0 */ @SuppressWarnings({"unchecked", "rawtypes"}) default <P extends Prefix> Set<P> getPrefixes(Class<P> prefixType) { // Following check is redundant with parameterized type but nevertheless applied as a safety. if (Prefix.class.isAssignableFrom(prefixType)) { EnumSet<? extends Enum<?>> prefixes = EnumSet.allOf(prefixType.asSubclass(Enum.class)); /* * Following unchecked cast is safe for read operations because the given class implements * 'prefixType' in addition of being an enumeration. It is also safe for write operations * because all enumerations are closed universes (so users can not add an instance unknown * to EnumSet) and we would have got an exception before this point if 'prefixType' was not * an enumeration in the sense of Class.isEnum(). */ return (EnumSet) prefixes; } else { throw new ClassCastException(String.format("%s does not implement Prefix", prefixType)); // TODO or should we throw a different exception here, MeasurementException or IllegalArgumentException? } } } <file_sep>Note ======== `jdk11` is currently unused. It may be enabled if the toolchain plugin already in place for the RI Indriya and other modules was used here, too.<file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.test.quantity; import javax.measure.Quantity; import javax.measure.Unit; import javax.measure.quantity.Time; import javax.measure.test.unit.DistanceUnit; import javax.measure.test.unit.TimeUnit; /** * @author <NAME> * @version 0.6 */ public class TimeQuantity extends TestQuantity<Time> { public TimeQuantity(double val, TimeUnit un) { this(); value = val; unit = un; scalar = val * unit.getMultFactor(); } public TimeQuantity(Number val, @SuppressWarnings("rawtypes") Unit un) { this(val.doubleValue(), (TimeUnit) un); } public TimeQuantity() { super(Time.class); } /* * Time(double val) { * * value = val; unit = m; // reference Unit scalar = val; * * } */ public TimeQuantity add(TimeQuantity d1) { TimeQuantity dn = new TimeQuantity(); Object o = super.add(dn, this, d1, TimeUnit.REF_UNIT); return (TimeQuantity) o; } public TimeQuantity subtract(TimeQuantity d1) { TimeQuantity dn = new TimeQuantity(); Object o = super.subtract(dn, this, d1, TimeUnit.REF_UNIT); return (TimeQuantity) o; } public boolean eq(TimeQuantity d1) { return super.eq(d1); } public boolean ne(TimeQuantity d1) { return super.ne(d1); } public boolean gt(TimeQuantity d1) { return super.gt(d1); } public boolean lt(TimeQuantity d1) { return super.lt(d1); } public boolean ge(TimeQuantity d1) { return super.ge(d1); } public boolean le(TimeQuantity d1) { return super.le(d1); } public TimeQuantity multiply(double v) { return new TimeQuantity(value * v, (TimeUnit) unit); } public TimeQuantity divide(double v) { return new TimeQuantity(value / v, (TimeUnit) unit); } public TimeQuantity convert(TimeUnit newUnit) { return new TimeQuantity(scalar / newUnit.getMultFactor(), newUnit); } public String showInUnits(DistanceUnit u, int precision) { return super.showInUnits(u, precision); } public Quantity<?> divide(Quantity<?> that) { // TODO Auto-generated method stub return null; } public Quantity<Time> subtract(Quantity<Time> that) { // TODO Auto-generated method stub return null; } public Quantity<Time> add(Quantity<Time> that) { return add((TimeQuantity) that); } public Quantity<Time> divide(Number that) { return divide(that.doubleValue()); } public Quantity<Time> inverse() { // TODO Auto-generated method stub return null; } public Quantity<Time> multiply(Number that) { return multiply(that.doubleValue()); } public Quantity<Time> to(Unit<Time> unit) { // TODO Auto-generated method stub return null; } public Quantity<?> multiply(Quantity<?> that) { // TODO Auto-generated method stub return null; } @Override public Quantity<Time> negate() { return new TimeQuantity(-value, getUnit()); } @SuppressWarnings({ "unchecked", "rawtypes" }) public final <T extends Quantity<T>> Quantity<T> asType(Class<T> type) throws ClassCastException { this.getUnit().asType(type); // Raises ClassCastException is dimension // mismatches. return (Quantity) this; } } <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>javax.measure</groupId> <artifactId>unit-api</artifactId> <name>Units of Measurement API</name> <packaging>bundle</packaging> <url>https://unitsofmeasurement.github.io/unit-api/</url> <description>Units of Measurement Standard - This JSR specifies Java packages for modeling and working with measurement values, quantities and their corresponding units.</description> <organization> <name><NAME>, <NAME>, <NAME></name> <url>http://unitsofmeasurement.github.io</url> </organization> <inceptionYear>2014</inceptionYear> <licenses> <license> <name>BSD 3-Clause</name> <url>LICENSE</url> <distribution>manual</distribution> </license> </licenses> <parent> <groupId>tech.uom</groupId> <artifactId>uom-parent</artifactId> <version>2.2</version> </parent> <!-- Issue managements and mailing lists. --> <issueManagement> <system>GitHub</system> <url>https://github.com/unitsofmeasurement/unit-api/issues</url> </issueManagement> <ciManagement> <system>CircleCI</system> <url>https://circleci.com/gh/unitsofmeasurement/unit-api</url> </ciManagement> <mailingLists> <mailingList> <name>Units-Dev</name> <subscribe>https://groups.google.com/group/units-dev/subscribe</subscribe> <post><EMAIL></post> </mailingList> <mailingList> <name>Units-Users</name> <subscribe>https://groups.google.com/group/units-users/subscribe</subscribe> <post><EMAIL></post> </mailingList> </mailingLists> <scm> <connection>scm:git:git<EMAIL>:unitsofmeasurement/unit-api.git</connection> <developerConnection> scm:git:git<EMAIL>:unitsofmeasurement/unit-api.git</developerConnection> <url>https://github.com/unitsofmeasurement/unit-api</url> </scm> <!-- Build Settings --> <properties> <basedir>.</basedir> <sourceEncoding>UTF-8</sourceEncoding> <!-- in Maven 3. --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>${sourceEncoding}</project.reporting.outputEncoding> <jdkVersion>8</jdkVersion> <jdkOptionalVersion>9</jdkOptionalVersion> <project.build.javaVersion>${jdkVersion}</project.build.javaVersion> <maven.compile.targetLevel>${jdkVersion}</maven.compile.targetLevel> <maven.compile.sourceLevel>${jdkVersion}</maven.compile.sourceLevel> <additionalparam>-Xdoclint:none</additionalparam> <thisYear>2023</thisYear> <!-- Plugins --> <github.maven.version>0.12</github.maven.version> <github.global.server>github</github.global.server> <maven.surefire-report.version>3.1.0</maven.surefire-report.version> <jakarta.inject.version>2.0.1</jakarta.inject.version> <spotbugs-maven.version>4.7.3.4</spotbugs-maven.version> <!--Exclude the files here --> <sonar.exclusions> src/main/java/javax/measure/BinaryPrefix.java,src/main/java/javax/measure/MetricPrefix.java</sonar.exclusions> </properties> <!-- Developers and Contributors --> <developers> <developer> <id>dautelle</id> <name><NAME></name> <email><EMAIL></email> <organization>Airbus</organization> <organizationUrl>http://www.airbus.com</organizationUrl> <timezone>+1</timezone> <roles> <role>Architect</role> <role>Java Developer</role> <role>Spec Lead</role> </roles> </developer> <developer> <id>keilw</id> <name><NAME></name> <email><EMAIL></email> <organization>Creative Arts &amp; Technologies</organization> <organizationUrl>http://www.catmedia.us</organizationUrl> <timezone>+1</timezone> <roles> <role>Architect</role> <role>Java Developer</role> <role>Spec Lead</role> </roles> </developer> <developer> <id>otaviojava</id> <name><NAME></name> <email><EMAIL></email> <organization>Individual / SouJava</organization> <timezone>0</timezone> <roles> <role>Expert</role> <role>Java Developer</role> <role>Spec Lead</role> </roles> </developer> <developer> <id>desruisseaux</id> <name><NAME></name> <email><EMAIL></email> <organization>Geomatys</organization> <organizationUrl>http://www.geomatys.com</organizationUrl> <timezone>+1</timezone> <roles> <role>Expert</role> <role>Java Developer</role> <role>Architect</role> </roles> </developer> <developer> <id>thodorisbais</id> <name><NAME></name> <email><EMAIL></email> <organization>Individual / Utrecht JUG</organization> <timezone>+1</timezone> <roles> <role>Expert</role> <role>Java Developer</role> </roles> </developer> <developer> <id>Daniel-Dos</id> <name><NAME></name> <email><EMAIL></email> <organization>Individual / SouJava</organization> <timezone>-5</timezone> <roles> <role>Expert</role> <role>Java Developer</role> </roles> </developer> <developer> <id>jhg023</id> <name><NAME></name> <organization>Individual</organization> <timezone>-4</timezone> <roles> <role>Expert</role> <role>Java Developer</role> </roles> </developer> <developer> <id>magesh678</id> <name><NAME></name> <organization>Individual</organization> <timezone>+4</timezone> <roles> <role>Expert</role> <role>Java Developer</role> </roles> </developer> <developer> <id>mohalmo</id> <name><NAME></name> <organization>Individual</organization> <timezone>+2</timezone> <roles> <role>Expert</role> <role>Java Developer</role> </roles> </developer> </developers> <contributors> <contributor> <name><NAME></name> <organization>Individual</organization> <timezone>+1</timezone> <roles> <role>Contributor</role> </roles> </contributor> <contributor> <name><NAME></name> <email><EMAIL></email> <organization>Computas</organization> <timezone>+1</timezone> <roles> <role>Contributor</role> </roles> </contributor> <contributor> <name><NAME></name> <organization>Computas</organization> <timezone>+1</timezone> <roles> <role>Contributor</role> </roles> </contributor> <contributor> <name><NAME></name> <organization>Utrecht Java User Group</organization> <timezone>+1</timezone> <roles> <role>Contributor</role> </roles> </contributor> <contributor> <name><NAME></name> <organization>Individual</organization> <timezone>+5.5</timezone> <roles> <role>Contributor</role> </roles> </contributor> <contributor> <name><NAME></name> <organization>Individual</organization> <timezone>+3</timezone> <roles> <role>Contributor</role> </roles> </contributor> <contributor> <name><NAME></name> <email><EMAIL></email> <organization>Red Hat</organization> <timezone>+10</timezone> <roles> <role>Contributor Emeritus</role> </roles> </contributor> <contributor> <!-- id>duckasteroid</id --> <name><NAME></name> <email><EMAIL></email> <organization>Snap-on Inc.</organization> <roles> <role>Expert Emeritus</role> </roles> </contributor> <contributor> <!-- id>leomrlima</id --> <name><NAME></name> <email><EMAIL></email> <organization>V2COM</organization> <organizationUrl>http://www.v2com.mobi/</organizationUrl> <timezone>-5</timezone> <roles> <role>Expert Emeritus</role> <role>Java Developer</role> </roles> </contributor> <contributor> <!-- id>eralmas7</id --> <name><NAME></name> <email><EMAIL></email> <organization>Individual / JP Morgan</organization> <timezone>+5.5</timezone> <roles> <role>Test Engineer</role> </roles> </contributor> <contributor> <!-- id>rajmahendra</id --> <name><NAME></name> <email><EMAIL></email> <organization>JUG Chennai</organization> <timezone>+5.5</timezone> <roles> <role>Expert Emeritus</role> </roles> </contributor> <contributor> <!-- id>karen_legrand</id --> <name><NAME></name> <email><EMAIL></email> <organization>Innovation Emergency Management (IEM)</organization> <organizationUrl>http://www.iem.com</organizationUrl> <timezone>-5</timezone> <roles> <role>Expert Emeritus</role> </roles> </contributor> <contributor> <!-- id>mohamed-taman</id --> <name><NAME></name> <email><EMAIL></email> <organization>Individual / Morocco JUG</organization> <timezone>+2</timezone> <roles> <role>Expert Emeritus</role> </roles> </contributor> <contributor> <name><NAME></name> <email><EMAIL></email> <organization>Ikayzo</organization> <timezone>-9</timezone> <roles> <role>Supporter</role> </roles> </contributor> <contributor> <name><NAME></name> <email><EMAIL></email> <timezone>-5</timezone> <roles> <role>Supporter</role> </roles> </contributor> <contributor> <name><NAME></name> <organization>J.P. Morrison Enterprises, Ltd.</organization> <timezone>-5</timezone> <roles> <role>Supporter</role> </roles> </contributor> <contributor> <name><NAME></name> <email><EMAIL></email> <roles> <role>Supporter</role> </roles> <timezone>+1</timezone> </contributor> </contributors> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.compiler.version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>1.8</version> </plugin> <!-- Format --> <plugin> <groupId>net.revelc.code</groupId> <artifactId>formatter-maven-plugin</artifactId> <version>0.5.2</version> </plugin> <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself. --> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <pluginExecution> <pluginExecutionFilter> <groupId>org.jacoco</groupId> <artifactId> jacoco-maven-plugin </artifactId> <versionRange> [0.7.1.201405082137,) </versionRange> <goals> <goal>prepare-agent</goal> </goals> </pluginExecutionFilter> <action> <ignore></ignore> </action> </pluginExecution> <pluginExecution> <pluginExecutionFilter> <groupId> net.revelc.code </groupId> <artifactId> formatter-maven-plugin </artifactId> <versionRange> [0.5.2,) </versionRange> <goals> <goal>format</goal> </goals> </pluginExecutionFilter> <action> <ignore></ignore> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <!-- Compilation --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <release>${maven.compile.targetLevel}</release> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <phase>prepare-package</phase> <goals> <goal>run</goal> </goals> <configuration> <target> <mkdir dir="${project.build.directory}/classes/META-INF/versions/${jdkOptionalVersion}" /> <javac destdir="${project.build.directory}/classes/META-INF/versions/${jdkOptionalVersion}" srcdir="${project.basedir}/src/main/jdk${jdkOptionalVersion}" includeAntRuntime="false"> <compilerarg line="--release=${jdkOptionalVersion} --patch-module java.measure=${project.build.directory}/classes" /> </javac> </target> </configuration> </execution> </executions> </plugin> <!-- Need to specificy at least 2.22.0 for JUnit 5 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <forkCount>1.5C</forkCount> </configuration> </plugin> <!-- Coverage --> <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <configuration> <excludes> <exclude>META-INF/versions/**</exclude> </excludes> </configuration> <executions> <execution> <id>pre-unit-test</id> <goals> <goal>prepare-agent</goal> </goals> </execution> <execution> <id>post-unit-test</id> <phase>test</phase> <goals> <goal>report</goal> <goal>check</goal> </goals> <configuration> <rules> <rule> <element>BUNDLE</element> <limits> <limit implementation="org.jacoco.report.check.Limit"> <counter>INSTRUCTION</counter> <value>COVEREDRATIO</value> <minimum>0.5</minimum> </limit> <limit> <counter>COMPLEXITY</counter> <value>COVEREDRATIO</value> <minimum>0.5</minimum> </limit> </limits> </rule> </rules> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.eluder.coveralls</groupId> <artifactId>coveralls-maven-plugin</artifactId> <version>4.3.0</version> <dependencies> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.2.3</version> </dependency> </dependencies> <configuration> <repoToken>${env.COVERALLS_REPO_TOKEN}</repoToken> </configuration> </plugin> <!-- Attach Sources --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <id>attach-sources</id> <phase>package</phase> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <executions> <execution> <id>attach-javadocs</id> <goals> <goal>jar</goal> </goals> </execution> </executions> <configuration> <!-- Workaround for https://github.com/unitsofmeasurement/unit-api/issues/220 --> <source>8</source> </configuration> </plugin> <!-- JAR packaging --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> <Specification-Title>${project.name}</Specification-Title> <Specification-Version>${project.version}</Specification-Version> <Specification-Vendor>${project.organization.name}</Specification-Vendor> <Automatic-Module-Name>java.measure</Automatic-Module-Name> <Multi-Release>true</Multi-Release> </manifestEntries> <addMavenDescriptor>false</addMavenDescriptor> </archive> </configuration> <executions> <execution> <goals> <goal>test-jar</goal> </goals> </execution> </executions> </plugin> <!-- Packaging (OSGi bundle) --> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Import-Package> !jakarta.annotation,!jakarta.inject,!javax.annotation,!javax.inject,*</Import-Package> </instructions> </configuration> </plugin> <!-- Resources --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <!-- Maven License Plugin --> <plugin> <groupId>com.mycila</groupId> <artifactId>license-maven-plugin</artifactId> <configuration> <licenseSets> <licenseSet> <header>src/main/config/header.txt</header> <properties> <owner>${project.organization.name}</owner> <currentYear>${thisYear}</currentYear> </properties> <excludes> <exclude>.editorconfig</exclude> <exclude>.gitattributes</exclude> <exclude>.github/**</exclude> <exclude>.circleci/**</exclude> <exclude>**/LICENSE</exclude> <exclude>**/README</exclude> <exclude>**/pom.xml</exclude> <exclude>**/settings.xml</exclude> <exclude>docs/**</exclude> <exclude>src/test/resources/**</exclude> <exclude>src/main/resources/**</exclude> <exclude>src/main/config/**</exclude> <exclude>src/main/emf/**</exclude> <exclude>src/site/**</exclude> <exclude>src/etc/**</exclude> <exclude>*.css</exclude> <exclude>*.jpg</exclude> <exclude>*.png</exclude> <exclude>*.yml</exclude> </excludes> <headerDefinitions> <headerDefinition>src/main/config/headers.xml</headerDefinition> </headerDefinitions> </licenseSet> </licenseSets> <mapping> <java>JAVA_STYLE</java> </mapping> </configuration> </plugin> <!-- Maven Code Formatter --> <plugin> <groupId>net.revelc.code</groupId> <artifactId>formatter-maven-plugin</artifactId> <configuration> <configFile> ${project.basedir}/src/main/config/eclipse-formatter-config.xml </configFile> </configuration> <executions> <execution> <goals> <goal>format</goal> </goals> </execution> </executions> </plugin> <!-- Maven web site --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.1.0</version> <reportSets> <reportSet> <reports> <report>index</report> <report>summary</report> <report>licenses</report> <report>scm</report> <report>ci-management</report> <report>team</report> <report>mailing-lists</report> <report>issue-management</report> </reports> </reportSet> </reportSets> </plugin> <!-- Javadoc generation --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>${maven.javadoc.version}</version> <configuration> <source>${maven.compile.sourceLevel}</source> <encoding>${project.build.sourceEncoding}</encoding> <docencoding>${project.reporting.outputEncoding}</docencoding> <charset>${project.reporting.outputEncoding}</charset> <locale>en</locale> <detectJavaApiLink>false</detectJavaApiLink> <noqualifier>all</noqualifier> <quiet>true</quiet> <keywords>true</keywords> <links> <link>http://docs.oracle.com/javase/11/docs/api/</link> </links> </configuration> </plugin> <!-- Code analysis --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>3.13.0</version> <configuration> <sourceEncoding>${project.build.sourceEncoding}</sourceEncoding> </configuration> </plugin> <!-- Report on test results --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>${maven.surefire-report.version}</version> </plugin> <!-- Static analysis for occurrences of bug patterns --> <plugin> <groupId>com.github.spotbugs</groupId> <artifactId>spotbugs-maven-plugin</artifactId> <version>${spotbugs-maven.version}</version> </plugin> </plugins> </reporting> <!-- Deployment to public servers --> <distributionManagement> <repository> <id>ossrh</id> <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url> </repository> <snapshotRepository> <id>ossrh</id> <url>https://oss.sonatype.org/content/repositories/snapshots</url> </snapshotRepository> <site> <id>JSR-385</id> <name>JSR-385 Maven reports</name> <url>file:///var/www/www.unitsofmeasurement.github.io/unit-api</url> <!-- No longer active, just a placeholder! --> </site> </distributionManagement> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${junit.jupiter.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>jakarta.inject</groupId> <artifactId>jakarta.inject-api</artifactId> <scope>test</scope> </dependency> </dependencies> <!-- Additional repositories --> <!-- Helps to resolve Parent POM and Snapshot artifacts --> <repositories> <repository> <snapshots> <enabled>true</enabled> </snapshots> <id>ossrh-snapshot</id> <name>OSSRH Snapshots</name> <url>https://oss.sonatype.org/content/repositories/snapshots/</url> </repository> </repositories> <profiles> <!-- Individual JARs --> <profile> <id>base-jar</id> <!-- This profile builds only the base (root level) elements into a separate JAR file --> <activation> <activeByDefault>false</activeByDefault> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <executions> <execution> <phase>prepare-package</phase> <goals> <goal>run</goal> </goals> <configuration> <target> <mkdir dir="${project.build.directory}/classes/META-INF/versions/${jdkOptionalVersion}" /> <javac destdir="${project.build.directory}/classes/META-INF/versions/${jdkOptionalVersion}" srcdir="${project.basedir}/src/etc/modules/base/jdk${jdkOptionalVersion}" includeAntRuntime="false"> <compilerarg line="--release=${jdkOptionalVersion} --patch-module java.measure.base=${project.build.directory}/classes" /> </javac> </target> </configuration> </execution> </executions> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> <Specification-Title>${project.name}</Specification-Title> <Specification-Version>${project.version}</Specification-Version> <Specification-Vendor> ${project.organization.name}</Specification-Vendor> <Automatic-Module-Name>java.measure.base</Automatic-Module-Name> <Multi-Release>true</Multi-Release> </manifestEntries> <addMavenDescriptor>false</addMavenDescriptor> </archive> </configuration> <executions> <execution> <id>base-jar</id> <goals> <goal>jar</goal> </goals> <configuration> <classifier>base</classifier> <excludes> <exclude>javax/measure/format/**</exclude> <exclude>javax/measure/quantity/**</exclude> <exclude>javax/measure/spi/**</exclude> </excludes> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>format-jar</id> <!-- This profile builds (optional) format elements into separate JAR files --> <build> <plugins> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>${maven.jar.version}</version> <configuration> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> <Specification-Title>${project.name}</Specification-Title> <Specification-Version>${project.version}</Specification-Version> <Specification-Vendor> ${project.organization.name}</Specification-Vendor> <Automatic-Module-Name>java.measure.format</Automatic-Module-Name> <Multi-Release>false</Multi-Release> </manifestEntries> <addMavenDescriptor>false</addMavenDescriptor> </archive> </configuration> <executions> <execution> <id>format-jar</id> <goals> <goal>jar</goal> </goals> <configuration> <classifier>format</classifier> <includes> <include>javax/measure/format/**</include> </includes> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>quantity-jar</id> <!-- This profile builds (optional) quantities into separate JAR files --> <build> <plugins> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>${maven.jar.version}</version> <configuration> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> <Specification-Title>${project.name}</Specification-Title> <Specification-Version>${project.version}</Specification-Version> <Specification-Vendor> ${project.organization.name}</Specification-Vendor> <Automatic-Module-Name>java.measure.quantity</Automatic-Module-Name> <Multi-Release>false</Multi-Release> </manifestEntries> <addMavenDescriptor>false</addMavenDescriptor> </archive> </configuration> <executions> <execution> <id>quanity-jar</id> <goals> <goal>jar</goal> </goals> <configuration> <classifier>quantity</classifier> <includes> <include>javax/measure/quantity/**</include> </includes> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>spi-jar</id> <!-- This profile builds (optional) SPI into separate JAR files --> <build> <plugins> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>${maven.jar.version}</version> <configuration> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> <manifestEntries> <Specification-Title>${project.name}</Specification-Title> <Specification-Version>${project.version}</Specification-Version> <Specification-Vendor> ${project.organization.name}</Specification-Vendor> <Automatic-Module-Name>java.measure.spi</Automatic-Module-Name> <Multi-Release>false</Multi-Release> </manifestEntries> <addMavenDescriptor>false</addMavenDescriptor> </archive> </configuration> <executions> <execution> <id>spi-jar</id> <goals> <goal>jar</goal> </goals> <configuration> <classifier>spi</classifier> <includes> <include>javax/measure/spi/**</include> </includes> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <!-- Documentation --> <profile> <id>documentation</id> <build> <plugins> <plugin> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctor-maven-plugin</artifactId> <executions> <execution> <id>output-html</id> <phase>generate-resources</phase> <goals> <goal>process-asciidoc</goal> </goals> <configuration> <outputDirectory>target/docs</outputDirectory> <sourceHighlighter>highlightjs</sourceHighlighter> <!-- coderay --> <backend>html</backend> <embedAssets>true</embedAssets> <imagesDir>src/main/asciidoc/images</imagesDir> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>localCopySite</id> <!-- Locally copies the "site" into the GitHub pages folder --> <build> <plugins> <plugin> <artifactId>maven-resources-plugin</artifactId> <executions> <execution> <id>copy-resources</id> <phase>site</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${basedir}/docs/site</outputDirectory> <resources> <resource> <directory>target/site</directory> <filtering>false</filtering> </resource> </resources> </configuration> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>sonar</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <sonar.host.url>https://sonarcloud.io</sonar.host.url> <sonar.projectKey>${env.SONARCLOUD_PROJECT_KEY}</sonar.projectKey> <sonar.login>${env.SONARCLOUD_LOGIN}</sonar.login> <sonar.organization>${env.SONARCLOUD_ORG}</sonar.organization> <sourceEncoding>UTF-8</sourceEncoding> <!-- in Maven 3. --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>${sourceEncoding}</project.reporting.outputEncoding> <jdkVersion>8</jdkVersion> <jdkOptionalVersion>9</jdkOptionalVersion> <project.build.javaVersion>${jdkVersion}</project.build.javaVersion> <maven.compile.targetLevel>${jdkVersion}</maven.compile.targetLevel> <maven.compile.sourceLevel>${jdkVersion}</maven.compile.sourceLevel> </properties> </profile> </profiles> <version>2.2.1-SNAPSHOT</version> </project> <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.test.quantity; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import javax.measure.Quantity; import javax.measure.quantity.Volume; import javax.measure.test.unit.AreaUnit; import javax.measure.test.unit.DistanceUnit; import javax.measure.test.unit.VolumeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * @author <NAME> */ public class AreaQuantityTest { AreaQuantity area; AreaUnit m2; @BeforeEach public void setUp() { m2 = AreaUnit.sqmetre; area = new AreaQuantity(100, m2); } @Test public void testAreaQuantity() { assertNotNull(area); } @Test public void testAdd() { AreaQuantity area2 = new AreaQuantity(50, m2); AreaQuantity result = area.add(area2); assertEquals(150d, result.scalar); } @Test public void testSubtract() { AreaQuantity area2 = new AreaQuantity(50, m2); AreaQuantity result = area.subtract(area2); assertEquals(50d, result.scalar); } @Test public void testEq() { AreaQuantity area2 = new AreaQuantity(100, m2); assertTrue(area2.eq(area)); } @Test public void testGt() { AreaQuantity area2 = new AreaQuantity(120, m2); assertTrue(area2.gt(area)); } @Test public void testLt() { AreaQuantity area2 = new AreaQuantity(20, m2); assertTrue(area2.lt(area)); } @Test public void testGe() { AreaQuantity area2 = new AreaQuantity(120, m2); assertTrue(area2.ge(area)); area2 = new AreaQuantity(100, m2); assertTrue(area2.ge(area)); } @Test public void testLe() { AreaQuantity area2 = new AreaQuantity(20, m2); assertTrue(area2.le(area)); area2 = new AreaQuantity(100, m2); assertTrue(area2.le(area)); } @Test public void testMultiplyDouble() { AreaQuantity result = area.multiply(3d); assertEquals(300d, result.scalar); } @Test public void testDivideDouble() { AreaQuantity result = area.divide(10d); assertEquals(10d, result.scalar); } @Test public void testDivideDistanceQuantity() { DistanceQuantity distance = new DistanceQuantity(10, DistanceUnit.m); DistanceQuantity result = area.divide(distance); assertEquals(10d, result.scalar); } @Test public void testMultiplyDistanceQuantity() { DistanceQuantity distance = new DistanceQuantity(15, DistanceUnit.m); VolumeQuantity result = area.multiply(distance); assertEquals(VolumeUnit.class, result.getUnit().getClass()); assertEquals(VolumeQuantity.class, result.getClass()); assertEquals(Volume.class, result.getType()); assertEquals(1500d, result.getValue()); } @Test public void testConvert() { AreaQuantity result = area.convert(AreaUnit.acre); assertEquals(100d, result.scalar); } @Test public void testShowInUnits() { String result = area.showInUnits(AreaUnit.hectare, 2); assertEquals("0.01 hectare", result); } @Test public void testToSystemUnit() { assertEquals(area.toSystemUnit(), area.to(area.getUnit().getSystemUnit())); } @Test public void testNegate() { assertEquals(area.negate().getValue(), -area.getValue().doubleValue()); } @Test public void testScale() { assertEquals(Quantity.Scale.ABSOLUTE, area.getScale()); } } <file_sep><!DOCTYPE HTML> <html lang="de"> <head> <!-- Generated by javadoc (17) on Sat May 20 22:21:02 CEST 2023 --> <title>ServiceProvider (Units of Measurement API 2.2 API)</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="dc.created" content="2023-05-20"> <meta name="description" content="declaration: package: javax.measure.spi, class: ServiceProvider"> <meta name="generator" content="javadoc/ClassWriterImpl"> <meta name="keywords" content="javax.measure.spi.ServiceProvider class"> <meta name="keywords" content="getPriority()"> <meta name="keywords" content="getSystemOfUnitsService()"> <meta name="keywords" content="getFormatService()"> <meta name="keywords" content="getQuantityFactory()"> <meta name="keywords" content="available()"> <meta name="keywords" content="of()"> <meta name="keywords" content="current()"> <meta name="keywords" content="setCurrent()"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../script-dir/jquery-ui.min.css" title="Style"> <link rel="stylesheet" type="text/css" href="../../../jquery-ui.overrides.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> <script type="text/javascript" src="../../../script-dir/jquery-3.6.0.min.js"></script> <script type="text/javascript" src="../../../script-dir/jquery-ui.min.js"></script> </head> <body class="class-declaration-page"> <script type="text/javascript">var evenRowColor = "even-row-color"; var oddRowColor = "odd-row-color"; var tableTab = "table-tab"; var activeTableTab = "active-table-tab"; var pathtoroot = "../../../"; loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="flex-box"> <header role="banner" class="flex-header"> <nav role="navigation"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="top-nav" id="navbar-top"> <div class="skip-nav"><a href="#skip-navbar-top" title="Skip navigation links">Skip navigation links</a></div> <ul id="navbar-top-firstrow" class="nav-list" title="Navigation"> <li><a href="../../../index.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="nav-bar-cell1-rev">Class</li> <li><a href="class-use/ServiceProvider.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html#class">Help</a></li> </ul> </div> <div class="sub-nav"> <div> <ul class="sub-nav-list"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor-summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method-summary">Method</a></li> </ul> <ul class="sub-nav-list"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor-detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method-detail">Method</a></li> </ul> </div> <div class="nav-list-search"><label for="search-input">SEARCH:</label> <input type="text" id="search-input" value="search" disabled="disabled"> <input type="reset" id="reset-button" value="reset" disabled="disabled"> </div> </div> <!-- ========= END OF TOP NAVBAR ========= --> <span class="skip-nav" id="skip-navbar-top"></span></nav> </header> <div class="flex-content"> <main role="main"> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="sub-title"><span class="package-label-in-type">Package</span>&nbsp;<a href="package-summary.html">javax.measure.spi</a></div> <h1 title="Class ServiceProvider" class="title">Class ServiceProvider</h1> </div> <div class="inheritance" title="Inheritance Tree"><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html" title="class or interface in java.lang" class="external-link">java.lang.Object</a> <div class="inheritance">javax.measure.spi.ServiceProvider</div> </div> <section class="class-description" id="class-description"> <hr> <div class="type-signature"><span class="modifiers">public abstract class </span><span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-64">ServiceProvider</a></span> <span class="extends-implements">extends <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html" title="class or interface in java.lang" class="external-link">Object</a></span></div> <div class="block">Service Provider for Units of Measurement services. <p> All the methods in this class are safe to use by multiple concurrent threads. </p></div> <dl class="notes"> <dt>Since:</dt> <dd>1.0</dd> <dt>Version:</dt> <dd>2.3, May 19, 2023</dd> <dt>Author:</dt> <dd><NAME>, <NAME></dd> </dl> </section> <section class="summary"> <ul class="summary-list"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <li> <section class="constructor-summary" id="constructor-summary"> <h2>Constructor Summary</h2> <div class="caption"><span>Constructors</span></div> <div class="summary-table three-column-summary"> <div class="table-header col-first">Modifier</div> <div class="table-header col-second">Constructor</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color"><code>protected </code></div> <div class="col-constructor-name even-row-color"><code><a href="#%3Cinit%3E()" class="member-name-link">ServiceProvider</a>()</code></div> <div class="col-last even-row-color"> <div class="block">Creates a new service provider.</div> </div> </div> </section> </li> <!-- ========== METHOD SUMMARY =========== --> <li> <section class="method-summary" id="method-summary"> <h2>Method Summary</h2> <div id="method-summary-table"> <div class="table-tabs" role="tablist" aria-orientation="horizontal"><button id="method-summary-table-tab0" role="tab" aria-selected="true" aria-controls="method-summary-table.tabpanel" tabindex="0" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table', 3)" class="active-table-tab">All Methods</button><button id="method-summary-table-tab1" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab1', 3)" class="table-tab">Static Methods</button><button id="method-summary-table-tab2" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab2', 3)" class="table-tab">Instance Methods</button><button id="method-summary-table-tab3" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab3', 3)" class="table-tab">Abstract Methods</button><button id="method-summary-table-tab4" role="tab" aria-selected="false" aria-controls="method-summary-table.tabpanel" tabindex="-1" onkeydown="switchTab(event)" onclick="show('method-summary-table', 'method-summary-table-tab4', 3)" class="table-tab">Concrete Methods</button></div> <div id="method-summary-table.tabpanel" role="tabpanel"> <div class="summary-table three-column-summary" aria-labelledby="method-summary-table-tab0"> <div class="table-header col-first">Modifier and Type</div> <div class="table-header col-second">Method</div> <div class="table-header col-last">Description</div> <div class="col-first even-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"><code>static final <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a>&gt;</code></div> <div class="col-second even-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"><code><a href="#available()" class="member-name-link">available</a>()</code></div> <div class="col-last even-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"> <div class="block">Returns the list of all service providers available for the current thread's context class loader.</div> </div> <div class="col-first odd-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"><code>static final <a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a></code></div> <div class="col-second odd-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"><code><a href="#current()" class="member-name-link">current</a>()</code></div> <div class="col-last odd-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"> <div class="block">Returns the current <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a>.</div> </div> <div class="col-first even-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab3"><code>abstract <a href="FormatService.html" title="interface in javax.measure.spi">FormatService</a></code></div> <div class="col-second even-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab3"><code><a href="#getFormatService()" class="member-name-link">getFormatService</a>()</code></div> <div class="col-last even-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab3"> <div class="block">Returns the service to obtain <a href="../format/UnitFormat.html" title="interface in javax.measure.format"><code>UnitFormat</code></a> and <a href="../format/QuantityFormat.html" title="interface in javax.measure.format"><code>QuantityFormat</code></a> or <code>null</code> if none.</div> </div> <div class="col-first odd-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab4"><code>int</code></div> <div class="col-second odd-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab4"><code><a href="#getPriority()" class="member-name-link">getPriority</a>()</code></div> <div class="col-last odd-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab4"> <div class="block">Allows to define a priority for a registered <code>ServiceProvider</code> instance.</div> </div> <div class="col-first even-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab3"><code>abstract &lt;Q extends <a href="../Quantity.html" title="interface in javax.measure">Quantity</a>&lt;Q&gt;&gt;<br><a href="QuantityFactory.html" title="interface in javax.measure.spi">QuantityFactory</a>&lt;Q&gt;</code></div> <div class="col-second even-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab3"><code><a href="#getQuantityFactory(java.lang.Class)" class="member-name-link">getQuantityFactory</a><wbr>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html" title="class or interface in java.lang" class="external-link">Class</a>&lt;Q&gt;&nbsp;quantity)</code></div> <div class="col-last even-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab3"> <div class="block">Returns a factory for the given <a href="../Quantity.html" title="interface in javax.measure"><code>Quantity</code></a> type.</div> </div> <div class="col-first odd-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab3"><code>abstract <a href="SystemOfUnitsService.html" title="interface in javax.measure.spi">SystemOfUnitsService</a></code></div> <div class="col-second odd-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab3"><code><a href="#getSystemOfUnitsService()" class="member-name-link">getSystemOfUnitsService</a>()</code></div> <div class="col-last odd-row-color method-summary-table method-summary-table-tab2 method-summary-table-tab3"> <div class="block">Returns the service to obtain a <a href="SystemOfUnits.html" title="interface in javax.measure.spi"><code>SystemOfUnits</code></a>, or <code>null</code> if none.</div> </div> <div class="col-first even-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"><code>static <a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a></code></div> <div class="col-second even-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"><code><a href="#of(java.lang.String)" class="member-name-link">of</a><wbr>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&nbsp;name)</code></div> <div class="col-last even-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"> <div class="block">Returns the <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a> with the specified name.</div> </div> <div class="col-first odd-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"><code>static final <a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a></code></div> <div class="col-second odd-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"><code><a href="#setCurrent(javax.measure.spi.ServiceProvider)" class="member-name-link">setCurrent</a><wbr>(<a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a>&nbsp;provider)</code></div> <div class="col-last odd-row-color method-summary-table method-summary-table-tab1 method-summary-table-tab4"> <div class="block">Replaces the current <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a>.</div> </div> </div> </div> </div> <div class="inherited-list"> <h3 id="methods-inherited-from-class-java.lang.Object">Methods inherited from class&nbsp;java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html" title="class or interface in java.lang" class="external-link">Object</a></h3> <code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone()" title="class or interface in java.lang" class="external-link">clone</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals(java.lang.Object)" title="class or interface in java.lang" class="external-link">equals</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#finalize()" title="class or interface in java.lang" class="external-link">finalize</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#getClass()" title="class or interface in java.lang" class="external-link">getClass</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode()" title="class or interface in java.lang" class="external-link">hashCode</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notify()" title="class or interface in java.lang" class="external-link">notify</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notifyAll()" title="class or interface in java.lang" class="external-link">notifyAll</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString()" title="class or interface in java.lang" class="external-link">toString</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait()" title="class or interface in java.lang" class="external-link">wait</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait(long)" title="class or interface in java.lang" class="external-link">wait</a>, <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait(long,int)" title="class or interface in java.lang" class="external-link">wait</a></code></div> </section> </li> </ul> </section> <section class="details"> <ul class="details-list"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <li> <section class="constructor-details" id="constructor-detail"> <h2>Constructor Details</h2> <ul class="member-list"> <li> <section class="detail" id="&lt;init&gt;()"> <h3>ServiceProvider</h3> <div class="member-signature"><span class="modifiers">protected</span>&nbsp;<span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-102">ServiceProvider</a></span>()</div> <div class="block">Creates a new service provider. Only to be used by subclasses.</div> </section> </li> </ul> </section> </li> <!-- ============ METHOD DETAIL ========== --> <li> <section class="method-details" id="method-detail"> <h2>Method Details</h2> <ul class="member-list"> <li> <section class="detail" id="getPriority()"> <h3>getPriority</h3> <div class="member-signature"><span class="modifiers">public</span>&nbsp;<span class="return-type">int</span>&nbsp;<span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-116">getPriority</a></span>()</div> <div class="block">Allows to define a priority for a registered <code>ServiceProvider</code> instance. When multiple providers are registered in the system, the provider with the highest priority value is taken. <p>If the "jakarta.annotation.Priority" annotation (from Jakarta Annotations) or "javax.annotation.Priority" annotation (from JSR-250) is present on the <code>ServiceProvider</code> implementation class, then that annotation (first if both were present) is taken and this <code>getPriority()</code> method is ignored. Otherwise – if a <code>Priority</code> annotation is absent – this method is used as a fallback.</p></div> <dl class="notes"> <dt>Returns:</dt> <dd>the provider's priority (default is 0).</dd> </dl> </section> </li> <li> <section class="detail" id="getSystemOfUnitsService()"> <h3>getSystemOfUnitsService</h3> <div class="member-signature"><span class="modifiers">public abstract</span>&nbsp;<span class="return-type"><a href="SystemOfUnitsService.html" title="interface in javax.measure.spi">SystemOfUnitsService</a></span>&nbsp;<span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-125">getSystemOfUnitsService</a></span>()</div> <div class="block">Returns the service to obtain a <a href="SystemOfUnits.html" title="interface in javax.measure.spi"><code>SystemOfUnits</code></a>, or <code>null</code> if none.</div> <dl class="notes"> <dt>Returns:</dt> <dd>the service to obtain a <a href="SystemOfUnits.html" title="interface in javax.measure.spi"><code>SystemOfUnits</code></a>, or <code>null</code>.</dd> </dl> </section> </li> <li> <section class="detail" id="getFormatService()"> <h3>getFormatService</h3> <div class="member-signature"><span class="modifiers">public abstract</span>&nbsp;<span class="return-type"><a href="FormatService.html" title="interface in javax.measure.spi">FormatService</a></span>&nbsp;<span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-133">getFormatService</a></span>()</div> <div class="block">Returns the service to obtain <a href="../format/UnitFormat.html" title="interface in javax.measure.format"><code>UnitFormat</code></a> and <a href="../format/QuantityFormat.html" title="interface in javax.measure.format"><code>QuantityFormat</code></a> or <code>null</code> if none.</div> <dl class="notes"> <dt>Returns:</dt> <dd>the service to obtain a <a href="../format/UnitFormat.html" title="interface in javax.measure.format"><code>UnitFormat</code></a> and <a href="../format/QuantityFormat.html" title="interface in javax.measure.format"><code>QuantityFormat</code></a>, or <code>null</code>.</dd> <dt>Since:</dt> <dd>2.0</dd> </dl> </section> </li> <li> <section class="detail" id="getQuantityFactory(java.lang.Class)"> <h3>getQuantityFactory</h3> <div class="member-signature"><span class="modifiers">public abstract</span>&nbsp;<span class="type-parameters">&lt;Q extends <a href="../Quantity.html" title="interface in javax.measure">Quantity</a>&lt;Q&gt;&gt;</span> <span class="return-type"><a href="QuantityFactory.html" title="interface in javax.measure.spi">QuantityFactory</a>&lt;Q&gt;</span>&nbsp;<span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-144">getQuantityFactory</a></span><wbr><span class="parameters">(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html" title="class or interface in java.lang" class="external-link">Class</a>&lt;Q&gt;&nbsp;quantity)</span></div> <div class="block">Returns a factory for the given <a href="../Quantity.html" title="interface in javax.measure"><code>Quantity</code></a> type.</div> <dl class="notes"> <dt>Type Parameters:</dt> <dd><code>Q</code> - the type of the <a href="../Quantity.html" title="interface in javax.measure"><code>Quantity</code></a> instances created by the factory</dd> <dt>Parameters:</dt> <dd><code>quantity</code> - the quantity type</dd> <dt>Returns:</dt> <dd>the <a href="QuantityFactory.html" title="interface in javax.measure.spi"><code>QuantityFactory</code></a> for the given type</dd> </dl> </section> </li> <li> <section class="detail" id="available()"> <h3>available</h3> <div class="member-signature"><span class="modifiers">public static final</span>&nbsp;<span class="return-type"><a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html" title="class or interface in java.util" class="external-link">List</a>&lt;<a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a>&gt;</span>&nbsp;<span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-307">available</a></span>()</div> <div class="block">Returns the list of all service providers available for the current thread's context class loader. The <a href="#current()">current</a> service provider is always the first item in the returned list. Other service providers after the first item may depend on the caller thread (see <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html#load(java.lang.Class)" title="class or interface in java.util" class="external-link">service loader API note</a>).</div> <dl class="notes"> <dt>Returns:</dt> <dd>all service providers available for the current thread's context class loader.</dd> </dl> </section> </li> <li> <section class="detail" id="of(java.lang.String)"> <h3>of</h3> <div class="member-signature"><span class="modifiers">public static</span>&nbsp;<span class="return-type"><a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a></span>&nbsp;<span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-354">of</a></span><wbr><span class="parameters">(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html" title="class or interface in java.lang" class="external-link">String</a>&nbsp;name)</span></div> <div class="block">Returns the <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a> with the specified name. The given name must match the name of at least one service provider available in the current thread's context class loader. The service provider names are the values of "jakarta.inject.Named" (from Jakarta Annotations) or "javax.inject.Named" (from JSR-330) annotations when present (first if both were present), or the value of <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString()" title="class or interface in java.lang" class="external-link"><code>Object.toString()</code></a> method for providers without <code>Named</code> annotation. <p>Implementors are encouraged to provide an <code>Named</code> annotation or to override <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString()" title="class or interface in java.lang" class="external-link"><code>Object.toString()</code></a> and use a unique enough name, e.g. the class name or other distinct attributes. Should multiple service providers nevertheless use the same name, the one with the highest <a href="#getPriority()">priority</a> wins.</p></div> <dl class="notes"> <dt>Parameters:</dt> <dd><code>name</code> - the name of the service provider to return</dd> <dt>Returns:</dt> <dd>the <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a> with the specified name</dd> <dt>Throws:</dt> <dd><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalArgumentException.html" title="class or interface in java.lang" class="external-link">IllegalArgumentException</a></code> - if available service providers do not contain a provider with the specified name</dd> <dd><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html" title="class or interface in java.lang" class="external-link">NullPointerException</a></code> - if <code>name</code> is null</dd> <dt>Since:</dt> <dd>2.0</dd> <dt>See Also:</dt> <dd> <ul class="see-list"> <li><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#toString()" title="class or interface in java.lang" class="external-link"><code>Object.toString()</code></a></li> </ul> </dd> </dl> </section> </li> <li> <section class="detail" id="current()"> <h3>current</h3> <div class="member-signature"><span class="modifiers">public static final</span>&nbsp;<span class="return-type"><a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a></span>&nbsp;<span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-383">current</a></span>()</div> <div class="block">Returns the current <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a>. If necessary the <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a> will be lazily loaded. <p> If there are no providers available, an <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html" title="class or interface in java.lang" class="external-link">IllegalStateException</a> is thrown. Otherwise the provider with the highest priority is used or the one explicitly designated via <a href="#setCurrent(javax.measure.spi.ServiceProvider)"><code>setCurrent(ServiceProvider)</code></a>. </p></div> <dl class="notes"> <dt>Returns:</dt> <dd>the <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a> used.</dd> <dt>Throws:</dt> <dd><code><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalStateException.html" title="class or interface in java.lang" class="external-link">IllegalStateException</a></code> - if no <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a> has been found.</dd> <dt>See Also:</dt> <dd> <ul class="see-list"> <li><a href="#getPriority()"><code>getPriority()</code></a></li> <li><a href="#setCurrent(javax.measure.spi.ServiceProvider)"><code>setCurrent(ServiceProvider)</code></a></li> </ul> </dd> </dl> </section> </li> <li> <section class="detail" id="setCurrent(javax.measure.spi.ServiceProvider)"> <h3>setCurrent</h3> <div class="member-signature"><span class="modifiers">public static final</span>&nbsp;<span class="return-type"><a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a></span>&nbsp;<span class="element-name"><a href="../../../src-html/javax/measure/spi/ServiceProvider.html#line-403">setCurrent</a></span><wbr><span class="parameters">(<a href="ServiceProvider.html" title="class in javax.measure.spi">ServiceProvider</a>&nbsp;provider)</span></div> <div class="block">Replaces the current <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a>.</div> <dl class="notes"> <dt>Parameters:</dt> <dd><code>provider</code> - the new <a href="ServiceProvider.html" title="class in javax.measure.spi"><code>ServiceProvider</code></a></dd> <dt>Returns:</dt> <dd>the replaced provider, or null.</dd> </dl> </section> </li> </ul> </section> </li> </ul> </section> <!-- ========= END OF CLASS DATA ========= --> </main> <footer role="contentinfo"> <hr> <p class="legal-copy"><small>Copyright &#169; 2014&#x2013;2023 <a href="http://unitsofmeasurement.github.io"><NAME>, <NAME>, <NAME></a>. All rights reserved.</small></p> </footer> </div> </div> </body> </html> <file_sep>/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure.test.quantity; import javax.measure.Quantity; import javax.measure.Unit; import javax.measure.quantity.Area; import javax.measure.quantity.Dimensionless; import javax.measure.test.TestUnit; import javax.measure.test.unit.BaseUnit; /** * @author <NAME> * @version 0.5 */ class DimensionlessQuantity extends TestQuantity<Dimensionless> implements Dimensionless { public DimensionlessQuantity(double val, TestUnit un) { this(); value = val; unit = un; scalar = val * unit.getMultFactor(); } public DimensionlessQuantity(Number val, Unit un) { this(val.doubleValue(), (TestUnit) un); } public DimensionlessQuantity() { super(Dimensionless.class); } public boolean eq(DimensionlessQuantity d1) { return super.eq(d1); } public boolean ne(DimensionlessQuantity d1) { return super.ne(d1); } public boolean gt(DimensionlessQuantity d1) { return super.gt(d1); } public boolean lt(DimensionlessQuantity d1) { return super.lt(d1); } public boolean ge(DimensionlessQuantity d1) { return super.ge(d1); } public boolean le(DimensionlessQuantity d1) { return super.le(d1); } public DimensionlessQuantity multiply(double v) { return new DimensionlessQuantity(value * v, (BaseUnit) unit); } public DimensionlessQuantity divide(double v) { return new DimensionlessQuantity(value / v, (BaseUnit) unit); } // public Speed divide(TimeInterval t1) { // return new Speed(scalar / // t1.scalar, Speed.refUnit); // } // public TimeInterval divide(Speed s1) { // return new TimeInterval(scalar / // s1.scalar, TimeInterval.refUnit); // } public DimensionlessQuantity convert(BaseUnit newUnit) { return new DimensionlessQuantity(scalar / newUnit.getMultFactor(), newUnit); } public String showInUnits(BaseUnit u, int precision) { return super.showInUnits(u, precision); } public Quantity<?> divide(Quantity<?> that) { // TODO Auto-generated method stub return null; } public Quantity<Dimensionless> to(Unit<Dimensionless> unit) { // TODO Auto-generated method stub return null; } public Quantity<Dimensionless> subtract(Quantity<Dimensionless> that) { // TODO Auto-generated method stub return null; } public Quantity<Dimensionless> add(Quantity<Dimensionless> that) { // TODO Auto-generated method stub return null; } @Override public Quantity<Dimensionless> negate() { return new DimensionlessQuantity(-value, getUnit()); } public Quantity<Dimensionless> divide(Number that) { return divide(that.doubleValue()); } public Quantity<Dimensionless> inverse() { // TODO Auto-generated method stub return null; } public Quantity<Dimensionless> multiply(Number that) { // TODO Auto-generated method stub return null; } public Quantity<?> multiply(Quantity<?> that) { // TODO Auto-generated method stub return null; } @SuppressWarnings({ "unchecked", "rawtypes" }) public final <T extends Quantity<T>> Quantity<T> asType(Class<T> type) throws ClassCastException { this.getUnit().asType(type); // Raises ClassCastException is dimension // mismatches. return (Quantity) this; } public Area multiply(Dimensionless l) { // TODO Auto-generated method stub return null; } } <file_sep><?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="de"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../jacoco-resources/report.gif" type="image/gif"/><title>UnconvertibleException.java</title><link rel="stylesheet" href="../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../index.html" class="el_report">Units of Measurement API</a> &gt; <a href="index.source.html" class="el_package">javax.measure</a> &gt; <span class="el_source">UnconvertibleException.java</span></div><h1>UnconvertibleException.java</h1><pre class="source lang-java linenums">/* * Units of Measurement API * Copyright (c) 2014-2023, <NAME>, <NAME>, <NAME>. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions * and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of JSR-385 nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package javax.measure; /** * Signals that a problem of some sort has occurred due to the impossibility of constructing a converter between two units. For example, the * multiplication of offset units are usually units not convertible to their {@linkplain Unit#getSystemUnit() system unit}. * * @author &lt;a href=&quot;mailto:<EMAIL>&quot;&gt;<NAME>&lt;/a&gt; * @author &lt;a href=&quot;mailto:<EMAIL>&quot;&gt;<NAME>&lt;/a&gt; * @version 1.0, Aug 8, 2016 * */ public class UnconvertibleException extends MeasurementException { /** * For cross-version compatibility. */ private static final long serialVersionUID = -4623551240019830166L; /** * Constructs a {@code UnconvertibleException} with the given message. * * @param message * the detail message, or {@code null} if none. */ public UnconvertibleException(final String message) { <span class="fc" id="L54"> super(message);</span> <span class="fc" id="L55"> }</span> /** * Constructs a {@code UnconvertibleException} with the given cause. * * @param cause * the cause of this exception, or {@code null} if none. */ public UnconvertibleException(final Throwable cause) { <span class="fc" id="L64"> super(cause);</span> <span class="fc" id="L65"> }</span> /** * Constructs a {@code UnconvertibleException} with the given message and cause. * * @param message * the detail message, or {@code null} if none. * @param cause * the cause of this exception, or {@code null} if none. * */ public UnconvertibleException(final String message, final Throwable cause) { <span class="fc" id="L77"> super(message, cause);</span> <span class="fc" id="L78"> }</span> } </pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.10.202304240956</span></div></body></html>
3f28a9317dc2e25968cab0cffe6ecbca8a29108e
[ "Markdown", "Java", "Maven POM", "HTML" ]
22
Java
unitsofmeasurement/unit-api
b0a0ef159a76f923d6f068ebd1dfc591a85b9116
035f95ace46349f28d02f4d215e203cbe55e0459
refs/heads/master
<file_sep>import http.server PORT = 8900 DIRECTORY = "web" def run(): class Handler(http.server.SimpleHTTPRequestHandler): def __init__(self, *args, **kwargs): super().__init__(*args, directory=DIRECTORY, **kwargs) try: httpd = http.server.HTTPServer(("", PORT), Handler) httpd.serve_forever() except KeyboardInterrupt: print('接收到关闭指令,退出程序') httpd.shutdown()
fb76c6131ec24625eb9eb4a8efad7d93bc534d9c
[ "Python" ]
1
Python
mellven/SOC_Sankey_Generator
ec29adb629eb0646b5df34ec423000de791e676e
8116f16071da622669999ec4a941e25236c080ac
refs/heads/master
<repo_name>l-feng/numberpickerChoose<file_sep>/Numpicker/MyApplication/app/src/main/java/com/example/lunatic/numpicker/NumberPickerActivity.java package com.example.lunatic.numpicker; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.NumberPicker; import android.widget.TextView; import java.lang.reflect.Field; import java.util.List; /** * Created by liufeng on 2017/9/10. */ public class NumberPickerActivity extends Activity implements View.OnClickListener, NumberPicker.OnScrollListener, NumberPicker.OnValueChangeListener { private TextView titleView; private NumberPicker numberPicker; //private List<Tags> optionList; private List<String> optionTitleList; private int chooseIndex; private String title; private View viewNumber; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.choose_number_dialog); // Intent intent = this.getIntent(); //获取已有的intent对象 // Bundle bundle = intent.getExtras(); //获取intent里面的bundle对象 // title = bundle.getString(IntentConstants.PARAM_OPTION_TITLE); // String options = bundle.getString(IntentConstants.PARAM_OPTION_LIST); // if (StringUtils.isNotBlank(options)) { // optionList = (List<Tags>) JsonUtil.getInstance().deserialize(options, List.class, Tags.class); // } // chooseIndex = bundle.getInt(IntentConstants.PARAM_OPTION_SELECT_INDEX, 0); getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); initView(); initPicker(); } private void initView() { findViewById(R.id.back).setOnClickListener(this); findViewById(R.id.sure).setOnClickListener(this); titleView = (TextView) findViewById(R.id.title); numberPicker = (NumberPicker) findViewById(R.id.number_choose); viewNumber=findViewById(R.id.number_view); titleView.setText(title); setNumberPickerDividerColorAndHeight(numberPicker); setNumberPickerTextColor(numberPicker, Color.BLACK); viewNumber.setOnClickListener(this); } public void initPicker() { // optionTitleList = new ArrayList<>(); // for (Tags tags : optionList) { // optionTitleList.add(tags.getName()); // } String[] optionList={"一月","二月","三月"}; numberPicker.setMinValue(0); numberPicker.setMaxValue(optionList.length - 1); numberPicker.setValue(chooseIndex); numberPicker.setWrapSelectorWheel(true);//是否循环滚动 numberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); numberPicker.setDisplayedValues(optionList); numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { chooseIndex = picker.getValue(); } }); } @Override public void onClick(View v) { if (v.getId() == R.id.back||v.getId()==R.id.number_view) { Intent intent = new Intent(NumberPickerActivity.this, MainActivity.class); setResult(2, intent); this.finish(); } else if (v.getId() == R.id.sure) { Intent intent = new Intent(NumberPickerActivity.this, MainActivity.class); // intent.putExtra(IntentConstants.PARAM_OPTION_SELECT_INDEX, chooseIndex); setResult(2, intent); finish(); } } @Override public void onScrollStateChange(NumberPicker view, int scrollState) { } @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { } private void setNumberPickerDividerColorAndHeight(NumberPicker numberPicker) { NumberPicker picker = numberPicker; Field[] pickerFields = NumberPicker.class.getDeclaredFields(); for (Field pf : pickerFields) { if (pf.getName().equals("mSelectionDivider")) { pf.setAccessible(true); try { //设置分割线的颜色值 pf.set(picker, new ColorDrawable(this.getResources().getColor(R.color.colorAccent))); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (Resources.NotFoundException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } break; } } for (Field pf2 : pickerFields) { if (pf2.getName().equals("mSelectionDividerHeight")) { pf2.setAccessible(true); try { int result = 1; pf2.set(picker, result); } catch (IllegalAccessException e) { e.printStackTrace(); } break; } } } public static boolean setNumberPickerTextColor(NumberPicker numberPicker, int color) { final int count = numberPicker.getChildCount(); for (int i = 0; i < count; i++) { View child = numberPicker.getChildAt(i); if (child instanceof EditText) { try { Field selectorWheelPaintField = numberPicker.getClass() .getDeclaredField("mSelectorWheelPaint"); selectorWheelPaintField.setAccessible(true); ((Paint) selectorWheelPaintField.get(numberPicker)).setColor(color); ((EditText) child).setTextColor(color); numberPicker.invalidate(); return true; } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } } return false; } } <file_sep>/README.md # numberpickerChoose android 的numberpicker控件制作金额选择器,月份选择器。修改number的分割线高度和颜色
9919da5b037ef91ed072908f726d37684e4f9ed8
[ "Markdown", "Java" ]
2
Java
l-feng/numberpickerChoose
871720cfcdd949bbbe643f1b776154ba92570adb
480a92b54d14f056f5ebf66270036720583275b0