branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>#include <stdio.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> #include <fcntl.h> #include <time.h> #include <netdb.h> #include <string.h> #include <arpa/inet.h> #define MAX_REQUEST 2048 #define MAX_URL 2048 struct args { int id; int connfd; char buffer[MAX_REQUEST]; char ip[20]; }; struct req { char request[MAX_REQUEST]; char method[16]; char path[MAX_URL]; char version[16]; char host[MAX_URL]; char page[MAX_URL]; }; void *handleConnection(void *args); FILE *fp_log; //log pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char** argv) { int port = atoi(argv[1]); int threadID = 0; int sockfd; struct sockaddr_in serv_addr; sockfd=socket(PF_INET, SOCK_STREAM,0); if(sockfd<0){ perror("Error open socket\n"); exit(0); } memset(&serv_addr,0,sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(atoi(argv[1])); if(bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr))==-1){ perror("Error bind socket\n"); exit(0); } while (1) { struct args* myargs; int /*clnt_addr_size,*/clnt_sock; socklen_t clnt_addr_size; struct sockaddr_in clnt_addr; char *str_temp; myargs = (struct args*) malloc(sizeof(struct args)); if(listen(sockfd,5)==-1){ perror("listen() error"); exit(0); } clnt_addr_size=sizeof(clnt_addr); clnt_sock=accept(sockfd,(struct sockaddr*)&clnt_addr,&clnt_addr_size); if(clnt_sock==-1){ perror("accept() error"); exit(0); } myargs->connfd=clnt_sock; getpeername(clnt_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size); str_temp = inet_ntoa(clnt_addr.sin_addr); strcpy(myargs->ip,str_temp); printf("%s\n",myargs->ip); pthread_t thread; threadID++; myargs->id = threadID; pthread_create(&thread, NULL, handleConnection, myargs); //thread never joins pthread_detach(thread); printf("%d loop end\n",myargs->id); } close(sockfd); return 0; } void *handleConnection(void *args) { struct args* myarg = (struct args*) args; struct req* myreq; int bytesRead=0; char *temp; char host[MAX_URL], page[MAX_URL]; //to send the message to server and receive the content by server //and send the content to client int chunkRead; size_t fd; char data[100000]; char reqBuffer[512]; int totalBytesWritten = 0; int chunkWritten=0; time_t result; result = time(NULL); struct tm* brokentime = localtime(&result); //for connect to server int serv_sock; struct sockaddr_in serv_addr; struct hostent *server; myreq = (struct req*) malloc(sizeof(struct req)); printf("thread %d created\n",myarg->id); memset(myarg->buffer,0,MAX_REQUEST); bytesRead = read(myarg->connfd, myarg->buffer, sizeof(myarg->buffer)); printf("byteRead=%d\n",bytesRead); if(strcmp(myarg->buffer,"")==0){ printf("it is no data\n"); pthread_exit(NULL); return; } strncpy(myreq->request,myarg->buffer,MAX_REQUEST-1); strncpy(myreq->method, strtok_r(myarg->buffer," ",&temp),15); strncpy(myreq->path,strtok_r(NULL," ",&temp),MAX_URL-1); strncpy(myreq->version, strtok_r(NULL, "\r\n",&temp),15); sscanf(myreq->path,"http://%99[^/]%99[^\n]",host,page); strncpy(myreq->page,page,MAX_URL-1); strncpy(myreq->host,host,MAX_URL-1); printf("request : %s\n method : %s\n path : %s\n version : %s\n page : %s\n host : ",myreq->request,myreq->method,myreq->path,myreq->version,myreq->page,myreq->host); memset(reqBuffer,0,512); serv_sock = socket(AF_INET, SOCK_STREAM, 0); server = gethostbyname(host); if (server == NULL) { printf("No such host\n"); exit(0); } memset((char *)&serv_addr,0,sizeof(serv_addr)); serv_addr.sin_family = AF_INET; memmove((char *)&serv_addr.sin_addr.s_addr,(char *)server->h_addr,server->h_length); serv_addr.sin_port = htons(80); if (connect(serv_sock,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){ printf("Error Connecting\n"); exit(0); } strcat(reqBuffer, myreq->method); strcat(reqBuffer," "); strcat(reqBuffer, myreq->page); strcat(reqBuffer," "); strcat(reqBuffer, myreq->version); strcat(reqBuffer,"\r\n"); strcat(reqBuffer, "host: "); strcat(reqBuffer, host); strcat(reqBuffer, "\r\n"); strcat(reqBuffer, "\r\n"); printf("request sent to %s :\n%s\nSent at: %s\n", host, reqBuffer, asctime(brokentime)); chunkRead = write(serv_sock, reqBuffer, strlen(reqBuffer)); while ((chunkRead = read(serv_sock, data, sizeof(data)))!= (size_t)NULL) { chunkWritten = write(myarg->connfd, data, chunkRead); totalBytesWritten += chunkWritten; } pthread_mutex_lock(&mutex); fp_log = fopen("proxy.log", "a"); fprintf(fp_log,"%s %s %s %d\n",asctime(brokentime),myarg->ip,myreq->path,totalBytesWritten); fclose(fp_log); pthread_mutex_unlock(&mutex); printf("completed sending %s at %d bytes at %s\n------------------------------------------------------------------------------------\n", myreq->page, totalBytesWritten, asctime(brokentime)); printf("%s %s %s %d\n",asctime(brokentime),myarg->ip,myreq->path,totalBytesWritten); close(serv_sock); close(myarg->connfd); printf("Thread %d exits\n", myarg->id); pthread_exit(NULL); }
78b24292d2fd8640f9da82ad89fc931a1f359bb7
[ "C" ]
1
C
hot486two/bachelor_network-proxy-
928b7e1c6ed8ebc1648faa2ed5ca5c2927019eb5
613029a6e3e3abad949e4657297ef622bc73dd4e
refs/heads/master
<repo_name>jarvis149/Todo<file_sep>/Makefile todo: todo.o java -classpath C:\Users\Vinamra\Documents\NetBeansProjects\java Todo todo.o: javac Todo.java test: todo install npm run test clean: rm -f Todo.class package-lock.json rm -rf node_modules install: npm install <file_sep>/Todo.java import java.io.*; import java.nio.file.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class Todo { private int count=0; public static void main(String[] args) throws IOException{ //Scanner ob=new Scanner(System.in); FileWriter writer= new FileWriter("c:\\tmp\\todo.txt",true); PrintWriter pw=new PrintWriter(writer); FileWriter writer1= new FileWriter("c:\\tmp\\done.txt",true); PrintWriter pw1=new PrintWriter(writer1); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //String argsString = reader.readLine(); //This method is good String argsString =""; //Still this method is not reliable to read a full string for(int i=0;i<args.length;i++){ argsString=argsString+args[i]+" "; } System.out.println(argsString); String[] arg = argsString.split(" ",2); Todo p=new Todo(); p.countinit(); //String in=ob.next(); switch(arg[0]){ case "help": p.help(); pw.close(); break; case "add": p.add(arg[1],pw); pw.close(); break; case "del": pw.close(); p.del(arg[1]); break; case "done": pw.close(); p.done(arg[1],pw1); break; case "ls": pw.close(); p.ls(); break; case "report": pw.close(); p.report(); break; } pw1.close(); } public void countinit() throws FileNotFoundException, IOException{ DataInputStream inn= new DataInputStream(new FileInputStream("Counter")); count=inn.readInt(); } public void help(){ System.out.println("Usage:-"); System.out.println("./todo add 'todo item' # Add a new todo"); System.out.println("./todo ls # Show remaining todos"); System.out.println("./todo del NUMBER # Delete a todo"); System.out.println("./todo done NUMBER # Complete a todo"); System.out.println("./todo help # Show usage"); System.out.println("./todo report # Statistics"); } public void add(String inp,PrintWriter pw) throws FileNotFoundException, IOException{ ++count; DataOutputStream ut= new DataOutputStream(new FileOutputStream("Counter")); ut.writeInt(count); inp= count+" "+inp; pw.println(inp); System.out.println("Added todo: \""+inp+"\""); } public void del(String inp) throws FileNotFoundException, IOException{ String fl="c:\\tmp\\temp.txt"; String fp="c:\\tmp\\todo.txt"; File nf=new File(fl); File of=new File(fp); String cline,data[];boolean flag=false; try{ FileWriter fw=new FileWriter(fl,true); BufferedWriter bw=new BufferedWriter(fw); PrintWriter pw=new PrintWriter(bw); FileReader fr=new FileReader(fp); BufferedReader br=new BufferedReader(fr); while((cline=br.readLine())!= null){ data=cline.split(" "); if(!(data[0].equalsIgnoreCase(inp))){ pw.println(cline); } else flag=true; } pw.flush(); pw.close(); fr.close(); fw.close(); bw.close(); br.close(); if(flag==false){ nf.delete(); System.out.println("Error: todo #"+inp+" does not exist. Nothing deleted.");} else{ --count; DataOutputStream ut= new DataOutputStream(new FileOutputStream("Counter")); ut.writeInt(count); of.delete(); File dump=new File(fp); nf.renameTo(dump); System.out.println("Deleted todo #"+inp); } }catch(Exception e){ } } public void done(String inp,PrintWriter pw1) throws FileNotFoundException, IOException{ String fl="c:\\tmp\\temp.txt"; String fp="c:\\tmp\\todo.txt"; File nf=new File(fl); File of=new File(fp); String cline,data[];boolean flag=false; try{ FileWriter fw=new FileWriter(fl,true); BufferedWriter bw=new BufferedWriter(fw); PrintWriter pw=new PrintWriter(bw); FileReader fr=new FileReader(fp); BufferedReader br=new BufferedReader(fr); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); while((cline=br.readLine())!= null){ data=cline.split(" "); if(!(data[0].equalsIgnoreCase(inp))){ pw.println(cline); } else {flag=true; pw1.println("x "+dateFormat.format(date)+" "+cline); } } pw.flush(); pw.close(); fr.close(); fw.close(); bw.close(); br.close(); if(flag==false){ nf.delete(); System.out.println("Error: todo #"+inp+" does not exist.");} else{ --count; DataOutputStream ut= new DataOutputStream(new FileOutputStream("Counter")); ut.writeInt(count); of.delete(); File dump=new File(fp); nf.renameTo(dump); System.out.println("Marked todo #"+inp+" as done."); } }catch(Exception e){ } } public void ls() throws FileNotFoundException, IOException{ String fp="c:\\tmp\\todo.txt"; String cline; FileReader fr=new FileReader(fp); BufferedReader br=new BufferedReader(fr); while((cline=br.readLine())!= null){ System.out.println(cline); } br.close(); } public void report() throws FileNotFoundException, IOException{ String tp="c:\\tmp\\todo.txt"; String dp="c:\\tmp\\done.txt"; int comp=0,uncomp=0; String cline; FileReader fr=new FileReader(tp); BufferedReader br=new BufferedReader(fr); FileReader fr1=new FileReader(dp); BufferedReader br1=new BufferedReader(fr1); DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); Date date = new Date(); while((cline=br.readLine())!= null){ uncomp++; } while((cline=br1.readLine())!= null){ comp++; } System.out.println(dateFormat.format(date)+" Pending : "+uncomp+" Completed : "+comp); br.close(); } }
b40edd8ef41cf5bdfe5d46f07ba0a94a844d1c19
[ "Java", "Makefile" ]
2
Makefile
jarvis149/Todo
63d04527e403528ed2b94d67939bbbb1493bdb41
c734eafd719f51ec5da6d6b028e9a8ad2448014b
refs/heads/master
<file_sep>'use strict'; angular.module('imm3.license.mgmt.service', [ 'ngResource' ]) .factory('cfgLicenseMgmtService', [ '$resource', '$http', function($resource, $http) { var basePath = '/api/providers/'; var service = { restLicenseInfo:function(params) { var url = basePath + 'imm_fod'; return $http.get(url, params); }, importBy: function (params) { var url = basePath + 'imm_fod'; var param = {'FOD_LicenseKeyInstall':params}; return $http.post(url, param); }, deleteBy: function (params) { var url = basePath + 'imm_fod'; var param = {'FOD_LicenseKeyDelete':params}; return $http.post(url, param); }, exportBy: function (params) { var url = basePath + 'imm_fod'; var param = {'FOD_LicenseKeyExport':params}; return $http.post(url, param); } }; return service; } ]) <file_sep>'use strict'; angular.module('imm3.network.service', [ 'ngResource' ]) .factory('networkService', [ '$resource', function($resource) { var service = {}; service.restGetEthernetInfo = function() { return $resource('/api/dataset/imm_ethernet'); }; service.restSetEthernet = function(){ return $resource('/api/dataset'); } service.restGetDNS = function(){ return $resource('/api/dataset/imm_dns'); } service.restGetDDNS = function(){ return $resource('/api/dataset/imm_ddns'); } service.restSetDNS = function(){ return $resource('/api/dataset'); } service.restSetDDNS = function(){ return $resource('/api/dataset'); } service.restGetEthOverUsb = function(){ return $resource('/api/dataset/imm_usb'); } service.restSetEthUsb = function(){ return $resource('/api/dataset'); } service.restAddEthUsb = function(){ return $resource('/api/function'); } service.restRemoveEth = function(){ return $resource('/api/function'); } service.restGetPortAssignment = function(){ return $resource('/api/dataset/imm_ports'); } service.restSetPortAssign = function(){ return $resource('/api/dataset'); } service.restGetBlockList = function(){ return $resource('/api/function/net_access_control'); } service.restSetBlock = function(){ return $resource('/api/function'); } service.restGetFpUsb = function(){ return $resource('/api/providers/fp_usb_port_cfg'); } service.restSetFpUsb = function(){ return $resource('/api/providers/fp_usb_port_cfg'); } service.restGetIpmi = function(){ return $resource('/api/dataset/imm_ipmi'); } service.restSetIpmi = function(){ return $resource('/api/function'); } return service; } ]) <file_sep>'use strict'; angular.module('imm3.properties', [ 'ngRoute' ]) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/properties', { templateUrl : 'www/views/properties.html', controller : 'propertiesCtrl' }); }]) .factory("locationContactService", ['$resource', function($resource){ var service = {}; service.getLocationContact = function() { return $resource('/api/dataset/imm_general'); }; service.saveLocationContact = function() { return $resource('/api/dataset'); }; service.getServerTimeouts = function() { return $resource('/api/dataset/imm_timeouts'); }; return service; }]) .controller('propertiesCtrl', ['$scope', '$rootScope', '$localStorage', 'locationContactService', function($scope, $rootScope, $localStorage, locationContactService) { $rootScope.loginInfo = angular.copy($localStorage.loginInfo); if(!$rootScope.loginInfo.loginStatus){ $location.path("/login"); }else{ console.log("I am in server properties page"); } $scope.showLocationContactBtn = false; var origContact = ""; var origRackName = ""; var origRoomNo = ""; var origBuilding = ""; var origLowestU = ""; var origAddress = ""; $scope.modiContact = ""; $scope.modiRackName = ""; $scope.modiRoomNo = ""; $scope.modiBuilding = ""; $scope.modiLowestU = ""; $scope.modiAddress = ""; var getLocationContactInfo = function(){ locationContactService.getLocationContact().get(function(data){ $scope.modiContact = origContact = data["items"][0].contact_person; $scope.modiRackName = origRackName = data["items"][0].rack_id; $scope.modiRoomNo = origRoomNo = data["items"][0].room_id; $scope.modiBuilding = origBuilding = data["items"][0].location; $scope.modiLowestU = origLowestU = data["items"][0].lowest_u_position; $scope.modiAddress = origAddress = data["items"][0].full_postal_addr; }, function(err){ console.log("Failed to get location & contact information from /api/dataset/imm_general, error: "+ err); }) }; $scope.contactOnChange = function(value){ if(value != origContact){ $scope.modiContact = value; $scope.showLocationContactBtn = true; } }; $scope.rackNameOnChange = function(value){ if(value != origRackName){ $scope.modiRackName = value; $scope.showLocationContactBtn = true; }else{} }; $scope.roomNoOnChange = function(value){ if(value != origRoomNo){ $scope.modiRoomNo = value; $scope.showLocationContactBtn = true; }else{} }; $scope.buildingOnChange = function(value){ if(value != origBuilding){ $scope.modiBuilding = value; $scope.showLocationContactBtn = true; }else{} }; $scope.lowestUOnChange = function(value){ if(value != origLowestU){ $scope.modiLowestU = value; $scope.showLocationContactBtn = true; }else{} }; $scope.addressOnChange = function(value){ if(value != origAddress){ $scope.modiAddress = value; $scope.showLocationContactBtn = true; }else{} }; var errMsg = ""; $scope.saveLocationContactChanges = function(){ // $scope.modiContact = $scope.modiContact.replace(",", "\\,"); console.log($scope.modiContact); locationContactService.saveLocationContact().save({"IMM_Contact":$scope.modiContact,"IMM_RackID":$scope.modiRackName, "IMM_RoomID":$scope.modiRoomNo, "IMM_Location":$scope.modiBuilding,"IMM_LowestUPos":$scope.modiLowestU.toString(),"IMM_FullPostalAddr":$scope.modiAddress }, (function(data){ if(data.return != 0){ errMsg = "Failed to save the location & contact info, error code: "+data.return; console.error(errMsg); $scope.$emit('showErrMsgBox', errMsg); }else{ console.log("Successfully saved location & contact info."); getLocationContactInfo(); $scope.showLocationContactBtn = false; } }), (function(err){ errMsg = "Failed to post /api/dataset, error: "+err; console.error(errMsg); $scope.$emit('showErrMsgBox', errMsg); })); }; $scope.locationContactResetFn = function(){ $scope.modiContact = ""; $scope.modiRackName = ""; $scope.modiRoomNo = ""; $scope.modiBuilding = ""; $scope.modiLowestU = ""; $scope.modiAddress = ""; $scope.saveLocationContactChanges(); }; $scope.os_watchdog_time = {}; $scope.os_watchdog_time.map = { "0":"None", "150":"2.5 minutes", "180":"3 minutes", "210":"3.5 minutes", "240":"4 minutes", "600":"10 minutes" }; $scope.loader_watchdog = {}; $scope.loader_watchdog.map = { "0":"None", "30":"0.5 minutes", "60":"1 minutes", "120":"2 minutes", "180":"3 minutes", "240":"4 minutes", "300":"5 minutes", "450":"7.5 minutes", "600":"10 minutes", "900":"15 minutes", "1200":"20 minutes", "1800":"30 minutes", "3600":"60 minutes", "7200":"120 minutes" }; $scope.power_off_delay = {}; $scope.power_off_delay.map = { "0":"None", "30":"0.5 minutes", "60":"1 minutes", "90":"1.5 minutes", "120":"2 minutes", "150":"2.5 minutes", "180":"3 minutes", "210":"3.5 minutes", "240":"4 minutes", "270":"4.5 minutes", "300":"5 minutes", "450":"7.5 minutes", "600":"10 minutes", "900":"15 minutes", "1200":"20 minutes", "1800":"30 minutes", "3600":"60 minutes", "7200":"120 minutes" }; var os_watchdog_time_orig = "0"; var loader_watchdog_orig = "0"; var power_off_delay_orig = "0"; $scope.os_watchdog_time.value = "0"; $scope.loader_watchdog.value = "0"; $scope.power_off_delay.value = "0"; var getServerTimeouts = function(){ locationContactService.getServerTimeouts().get(function(data){ $scope.os_watchdog_time.value = os_watchdog_time_orig = data["items"][0].os_watchdog_timeout; $scope.loader_watchdog.value = loader_watchdog_orig = data["items"][0].loader_watchdog_timeout; $scope.power_off_delay.value = power_off_delay_orig = data["items"][0].power_off_delay; }, function(err){ console.log("Failed to get server timeouts from /api/dataset/imm_timeouts, error: "+ err); }) }; $scope.showServerTimeoutsBtn = false; $scope.osWatchdogOnChange = function(value){ console.log(os_watchdog_time_orig); if(value != os_watchdog_time_orig){ $scope.os_watchdog_time.value = value; console.log($scope.os_watchdog_time.value); $scope.showServerTimeoutsBtn = true; }else{} }; $scope.loaderWatchdogOnChange = function(value){ console.log(os_watchdog_time_orig); if(value != loader_watchdog_orig){ $scope.loader_watchdog.value = value; console.log($scope.loader_watchdog.value); $scope.showServerTimeoutsBtn = true; }else{} }; $scope.powerOffDelayOnChange = function(value){ console.log(value); if(value != power_off_delay_orig){ $scope.power_off_delay.value = value; console.log($scope.power_off_delay.value); $scope.showServerTimeoutsBtn = true; }else{} }; $scope.serverTimeoutResetFn = function(){ $scope.os_watchdog_time.value = "0"; $scope.loader_watchdog.value = "0"; $scope.power_off_delay.value = "0"; $scope.saveServerTimeoutsChanges(); }; $scope.saveServerTimeoutsChanges = function(){ locationContactService.saveLocationContact().save({"SRVR_OSWatchdogTimeout":$scope.os_watchdog_time.value.toString(),"SRVR_LoaderTimeout":$scope.loader_watchdog.value.toString(), "SRVR_PowerOffTimeout":$scope.power_off_delay.value.toString() }, (function(data){ if(data.return != 0){ errMsg = "Failed to save the server timeouts, error code: "+data.return; console.error(errMsg); $scope.$emit('showErrMsgBox', errMsg); }else{ console.log("Successfully saved the server timeouts."); getServerTimeouts(); $scope.showLocationContactBtn = false; } }), (function(err){ errMsg = "Failed to post the server timesouts saving /api/dataset, error: "+err; console.error(errMsg); $scope.$emit('showErrMsgBox', errMsg); })); }; $scope.$on('$viewContentLoaded', function() { getLocationContactInfo(); getServerTimeouts(); setTimeout(function() { $scope.$emit('clickMenuItem1', 'menuTitleServerProperties'); $scope.$apply(); }, 100); }); } ]);<file_sep>'use strict'; angular.module('myApp.view2', [ 'ngRoute' ]) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/view2', { templateUrl : 'www/views/view2.html', controller : 'View2Ctrl' }); } ]) .controller('View2Ctrl', ['$scope', function($scope) { $scope.$on('$viewContentLoaded', function() { setTimeout(function() { $scope.$emit('clickMenuItem1', 'menuTitleBootOptions'); $scope.$apply(); }, 100); }); } ]);<file_sep>'use strict'; angular.module('myApp.userldap', [ 'ngRoute', 'pascalprecht.translate','angularjs-dropdown-multiselect','imm3.home.cfg.userldap.service']) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/userLDAP', { templateUrl : 'www/views/cfg.users.view.html', controller : 'usersCtrl' }); } ]) .controller('usersCtrl', [ '$scope','$rootScope','$localStorage', '$location','cfgUserInfoService', function($scope,$rootScope,$localStorage,$location,cfgUserInfoService) { $rootScope.loginInfo = angular.copy($localStorage.loginInfo); console.log("$rootScope.loginInfo on user page\t"+JSON.stringify($localStorage.loginInfo)); if(!$rootScope.loginInfo.loginStatus){ $location.path("/login"); }else{ console.log("I am in user page"); } $scope.$emit('clickMenuItem1', 'menuTitleUserLdap'); $scope.inputTest ={}; $scope.authMethodata = [{id:0,value:'Local only'},{id:1,value:'LDAP only'},{id:2,value:'Local first, then LDAP'},{id:3,value:'LDAP first, then local user'}]; $scope.yesOrNoData = [{id:0,value:'Yes'},{id:1,value:'No'}]; $scope.globalSettings ={}; //Get global settings var restGetGlobalSetting = cfgUserInfoService.restGetGlobalSetting(); restGetGlobalSetting.get(function(data) { $scope.globalSettings.userAuthMethod = data['items'][0].UserAuthMethod; $scope.globalSettings.pwdRequired = data['items'][0].pass_required; $scope.globalSettings.complexpwdRequired = data['items'][0].pass_complex_required; $scope.globalSettings.forceChange = data['items'][0].force_change; $scope.globalSettings.forceChangeNext = data['items'][0].factory_force_change; $scope.globalSettings.passExpireDays = data['items'][0].pass_expire_days; //$scope.globalSettings.miniPwdLength = data['items'][0].pass_min_length;//pass_min_length should nevel be 0, var pass_min_len = parseInt(data['items'][0].pass_min_length); if(pass_min_len < 5){ $scope.globalSettings.miniPwdLength =5; }else{ $scope.globalSettings.miniPwdLength = pass_min_len; } $scope.globalSettings.miniPwdReuse=data['items'][0].pass_min_resuse; $scope.globalSettings.pwdChangeInterval=data['items'][0].pass_change_interval; $scope.globalSettings.maxLoginFailure=data['items'][0].max_login_failures; $scope.globalSettings.lockoutPeriod=data['items'][0].lockout_period; $scope.globalSettings.minDiffChars=data['items'][0].pass_min_diff_chars; //web time out var webTimeOut = parseInt(data['items'][0].session_timeout); if(webTimeOut > 1 && (webTimeOut ==5 || webTimeOut ==10 || webTimeOut ==20)){ $scope.userLdapSelectTimeout.value =webTimeOut+' minutes'; }else if(webTimeOut ==1){ $scope.userLdapSelectTimeout.value =webTimeOut+' minute'; }else if(webTimeOut ==0){ $scope.userLdapSelectTimeout.value ='No Timeout'; }else{//6 was returned on real systems, which is not expected $scope.userLdapSelectTimeout.value ='5 minutes'; } //global security level var globalSecLevel = parseInt(data['items'][0].security_level); if(globalSecLevel = 1){ $scope.userLdapSelectSecLevel.value="Custom Security Settings"; }else if(globalSecLevel = 2){ $scope.userLdapSelectSecLevel.value = "High"; }else{ $scope.userLdapSelectSecLevel.value = "Low"; } //console.log('get settings done\t'); }); //Apply global settings changes var restSetGlobalSetting = cfgUserInfoService.restSetGlobalSetting(); $scope.applyGlobalSetting = function(){ var globalSetting ={ "USER_GlobalAuthMethod": "0", "USER_GlobalLockoutPeriod": "0", //"USER_GlobalWebTimeout": "0",// commented out due to the backend is not working for this , will enable once backend works //"USER_GlobalSecLvl": "0", need to move out as we need to set this one first before we set others "USER_GlobalPassReqEna": "0", "USER_GlobalPassExpPeriod": "0", "USER_GlobalMinPassLen": "0", "USER_GlobalMinPassReuseCycle": "0", "USER_GlobalMinPassChgInt": "0", "USER_GlobalMinDifPassChars": "0", "USER_GlobalMaxLoginFailures": "0", "USER_GlobalDefaultPassForceChg": "0" //"USER_GlobalUserPassForceChg": "0", //"USER_GlobalPwComplexReq": "0" }; globalSetting.USER_GlobalAuthMethod = ""+$scope.globalSettings.userAuthMethod; globalSetting.USER_GlobalLockoutPeriod = ""+ $scope.globalSettings.lockoutPeriod; //web session timeout //commented out due to the backend is not working for this, it cannot be set successfully, need to enable once backend works /* var webTimeOutVal = $scope.userLdapSelectTimeout.value; webTimeOutVal = webTimeOutVal.substring(0,2); if(parseInt(webTimeOutVal) < 21){ globalSetting.USER_GlobalWebTimeout = ""+parseInt(webTimeOutVal); }else{ globalSetting.USER_GlobalWebTimeout = ""+ 0 ;//No Timeout } */ //global security level var globalSecLelVal = $scope.userLdapSelectSecLevel.value; var globalSecLelNum = ""; if(globalSecLelVal == 'Custom Security Settings'){ //globalSetting.USER_GlobalSecLvl =""+1; globalSecLelNum = "1"; }else if(globalSecLelVal == 'High'){ //globalSetting.USER_GlobalSecLvl =""+2; globalSecLelNum = "2"; }else{ //globalSetting.USER_GlobalSecLvl =""+3; globalSecLelNum = "3"; } globalSetting.USER_GlobalPassReqEna = ""+$scope.globalSettings.pwdRequired; globalSetting.USER_GlobalPassExpPeriod = ""+$scope.globalSettings.passExpireDays; globalSetting.USER_GlobalMinPassLen = ""+$scope.globalSettings.miniPwdLength; globalSetting.USER_GlobalMinPassReuseCycle = ""+$scope.globalSettings.miniPwdReuse; globalSetting.USER_GlobalMinPassChgInt = ""+$scope.globalSettings.pwdChangeInterval; globalSetting.USER_GlobalMinDifPassChars = ""+$scope.globalSettings.minDiffChars; globalSetting.USER_GlobalMaxLoginFailures = ""+$scope.globalSettings.maxLoginFailure; globalSetting.USER_GlobalDefaultPassForceChg = ""+$scope.globalSettings.forceChangeNext; globalSetting.USER_GlobalUserPassForceChg = ""+$scope.globalSettings.forceChange; globalSetting.USER_GlobalPwComplexReq = ""+$scope.globalSettings.complexpwdRequired; //restSetGlobalSetting.save({},globalSetting,function(data){ restSetGlobalSetting.save({},{"USER_GlobalSecLvl":globalSecLelNum},function(data){ if(data["return"] !== 0){ $scope.$emit('showErrMsgBox', "Failed to apply global settings !"); return; }else{ //USER_GlobalSecLvl was set successfully, we need to set the others now restSetGlobalSetting.save({},globalSetting,function(data){ if(data["return"] !== 0){ $scope.$emit('showErrMsgBox', "Failed to apply global settings !"); return; } $scope.$emit('showErrMsgBox', "Global settings has been saved successfully!"); }, function(err) { $scope.$emit('showErrMsgBox', "Failed to apply global settings !"); }); } //$scope.$emit('showErrMsgBox', "Global settings has been saved successfully!"); }, function(err) { $scope.$emit('showErrMsgBox', "Failed to apply global settings !"); }); $scope.showGlobalSettings = false; } $scope.cancelGlobalSetting = function(){ $scope.showGlobalSettings = false; } //Create user $scope.createUserInfo ={}; $scope.createUserInfo.snmpv3 ={}; $scope.createUserInfo.ssh ={}; $scope.createUserInfo.authLvl = 1; //default //will get an available id from the user list retrieved , this is a workaround $scope.createUserInfo.userId = 0; //auth level, custom -start $scope.selectModel = [{id: 8, label: "Adapter Configuration - Networking and Security"}, ]; $scope.options = [ {id: 16, label: "User Account Management"}, {id: 32, label: "Remote Console Access"}, {id: 64, label: "Remote Console and Remote Disk Access"}, {id: 128, label: "Remote Server Power/Restart"}, {id: 512, label: "Ability to Clear Event Logs"}, {id: 256, label: "Adapter Configuration - Basic"}, {id: 8, label: "Adapter Configuration - Networking and Security"}, {id: 1024, label: "Adapter Configuration - Advanced (Firmware Update, Restart IMM, Restore Configuration)"}]; $scope.selectSettings = {externalIdProp: ''}; // $scope.showCustomOptions = false; $scope.userAuthLevelSelect = {}; $scope.userAuthLevelSelect.map = { "Supervisor": "supervisorLabel", "Read-only": "readOnlyLabel", "Custom": "customLabel" }; //need to read default via rest call $scope.userAuthLevelSelect.value="Supervisor"; $scope.selAuthLevelChanged = function(value) { if(value == 'Supervisor' || value == 'Read-only' ){ $scope.showCustomOptions = false; if( value == 'Read-only'){ $scope.createUserInfo.authLvl = 2; } }else{ $scope.showCustomOptions = true; $scope.createUserInfo.authLvl = 3; } return false; }; //SNMP for create//TODO $scope.createUserInfo.usesnmpAuthProtocol = 0; //auth level, custom -end //TODO LDAP $scope.ldapAuthSelect = {}; $scope.ldapAuthSelect.map = { "Use LDAP server for Authentication and Authorization": "nonLocalAuthorizationLabel", "Use LDAP server for Authentication only(with local authorization)": "localAuthorizationLabel" }; //need to read default via rest call $scope.ldapAuthSelect.value ='Use LDAP server for Authentication and Authorization'; $scope.authMethodChanged = function(value){ if(value == 'Use LDAP server for Authentication and Authorization'){ $scope.ldap.ldap_use_server_method_val = 0; }else{ $scope.ldap.ldap_use_server_method_val = 1; } } $scope.ldapServerSelect = {}; $scope.ldapServerSelect.map = { "Use Pre-Configured Servers": "usePreCfgedServerLabel", "Use DNS to find Servers": "userDNSLabel" }; //need to read default via rest call $scope.ldapServerSelect.value ='Use Pre-Configured Servers'; $scope.ldapServerChanged = function(value){ if(value == 'Use Pre-Configured Servers'){ $scope.ldap.ldap_source_select_val = 0; }else{ $scope.ldap.ldap_source_select_val = 1; } } $scope.customOptionsDisabled = false; $scope.userLdapSelectSecLevel ={}; $scope.userLdapSelectSecLevel.map = { "Custom Security Settings": "customLabel", "Low": "lowLabel", "High": "highLabel" }; $scope.userLdapSelectSecLevel.value ='Custom Security Settings'; $scope.selSecChanged = function(value) { //$scope.userLdapSelectSecLevel.value = value; if(value == 'Low' || value == 'High' ){ $scope.customOptionsDisabled = true; }else{ $scope.customOptionsDisabled = false; } return false; }; //golbal setting web time out $scope.userLdapSelectTimeout ={}; $scope.userLdapSelectTimeout.map = { "1 minute": "userSession1", "5 minutes": "userSession5", "10 minutes": "userSession10", "20 minutes": "userSession20", "No Timeout": "userSession0" }; //need to read default via rest call $scope.userLdapSelectTimeout.value ='10 minutes'; $scope.selTimeoutChanged = function(value) { console.log(value); return false; } //snmpv3 for create user: auth protocol $scope.createUserInfo.snmpv3.authProMap = { "HMAC-MD5":"HMAC-MD5Label", "HMAC-SHA":"HMAC-SHALabel", "None":"NoneLabel" }; $scope.createUserInfo.snmpv3.authProValue ='None'; $scope.snmpv3AuthProChanged = function(value){ console.log('value\t'+value); } //snmpv3 for create user privacy protocol $scope.createUserInfo.snmpv3.privProMap = { "AES":"AESLabel", "CBC - DES":"CBC-DESLabel", "None":"NoneLabel" }; $scope.createUserInfo.snmpv3.privProValue ='None'; $scope.snmpv3PrivProChanged = function(value){ console.log('value\t'+value); } //Get user info var restUsersInfo = cfgUserInfoService.restUsersInfo(); var getUserData = function(){ restUsersInfo.get(function(data) { console.log('loading user...'); $scope.users = data['items'][0]['users']; $scope.userCount = 0; var activeSession = data['items'][0]['active_sessions']; // iterate all the user to get count and append active session info angular.forEach($scope.users , function(userData,index){ if(userData['users_user_name']!= '' && userData['users_access_effective'] == 1){ $scope.userCount ++; } //workaround to get an available id if(userData['users_user_name']== ''){ $scope.createUserInfo.userId = parseInt(userData['users_user_id']); } angular.forEach(activeSession, function(sessionData,index){ var uid = sessionData['active_sessions.uid']; var type = sessionData['active_sessions.type']; var typeStr; var addr = sessionData['active_sessions.address']; if(type==4){// what about other types typeStr = "(Web-HTTPS)"; } if(uid == userData['users_user_id']){ userData['users_activeSession'] = addr+" "+typeStr; } }); }); }); } //get user list upon page load getUserData(); // local user view $scope.showLocalUser = true; // create user view $scope.showCreateUser = false; // show golbal settings view $scope.showGlobalSettings = false; // SNMPV3 settings view, folded up by default $scope.showSNMPv3Setting = false; // $scope.showAddingSSHKey=false; // additional Params on the ldap view, folded up by default $scope.showAdditionalParam = false; // $scope.showAddServerName = false; //Edit user $scope.editUserInfo ={}; //TODO $scope.editUserInfo.snmpv3 ={}; $scope.editUserInfo.ssh ={}; $scope.editUserInfo.ssh.showTextArea = false; $scope.editUserInfo.ssh.textVal = ""; $scope.editUserInfo.showEditCustomOptions = false; var updateCustomAuthCode = function(type){ var customAuthCode = 0; angular.forEach($scope.selectModel , function(data,index){ customAuthCode =customAuthCode + parseInt(data.id); }); if(type==1){//create user $scope.createUserInfo.customAuthCode = customAuthCode; }else{//edit user $scope.editUserInfo.customAuthCode = customAuthCode; } } $scope.editUserInfo.userAuthLevelSelect = {}; $scope.editUserInfo.userAuthLevelSelect.map = { "Supervisor": "supervisorLabel", "Read-only": "readOnlyLabel", "Custom": "customLabel" }; //need to read default via rest call $scope.editUserInfo.userAuthLevelSelect.value="Supervisor"; $scope.authLevelSelChanged = function(value){ if(value == 'Supervisor' || value == 'Read-only' ){ $scope.showCustomOptions = false; if( value == 'Read-only'){ $scope.editUserInfo.userAccess = 2; }else{ $scope.editUserInfo.userAccess = 1; } }else{ $scope.showCustomOptions = true; $scope.editUserInfo.userAccess = 3; } } //snmpv3 for edit user: auth protocol $scope.editUserInfo.snmpv3.authProMap = { "HMAC-MD5":"HMAC-MD5Label", "HMAC-SHA":"HMAC-SHALabel", "None":"NoneLabel" }; $scope.editUserInfo.snmpv3.authProValue ='None'; $scope.snmpv3AuthProChanged4Edit = function(value){ console.log('value\t'+value); } //snmpv3 for edit user privacy protocol passwt $scope.editUserInfo.snmpv3.privProMap = { "AES":"AESLabel", "CBC - DES":"CBC-DESLabel", "None":"NoneLabel" }; $scope.editUserInfo.snmpv3.privProValue ='None'; $scope.snmpv3PrivProChanged4Edit = function(value){ console.log('value\t'+value); } var populateCustomPreBits = function(val){ $scope.selectModel = [ ]; var val = parseInt(val); //var data = val.toString(16).split("").reverse().join("")+"000000000"; //var data = val.toString(16).split("").join(""); var power = 10; var optionId = Math.pow(2,power); for(; power >= 0 ;){ if(val >= optionId){ angular.forEach($scope.options, function(data,index){ if(data.id == optionId){ $scope.selectModel.push(data); } }); } val = val % optionId; optionId = Math.pow(2,power); power--; } } //populateCustomPreBits("1032"); //populateCustomPreBits("1536"); $scope.snmpv3settings = {}; var restSNMPV3Setting = cfgUserInfoService.restSNMPV3Setting(); var getSNMPV3Data = function(){ restSNMPV3Setting.get(function(data) { $scope.snmpv3settings = data['items'][0]; }); } getSNMPV3Data(); var populateEditUseInfo = function(id){ angular.forEach($scope.users , function(userData,index){ if(id == userData['users_user_id']){ $scope.editUserInfo.userId = id; $scope.editUserInfo.username = userData['users_user_name']; $scope.editUserInfo.password ="********"; $scope.editUserInfo.cfmpassword ="********"; $scope.editUserInfo.userAccess = parseInt(userData['users_access']); if($scope.editUserInfo.userAccess == 1){ $scope.editUserInfo.authLevel ="Supervisor"; }else if($scope.editUserInfo.userAccess == 2){ $scope.editUserInfo.userAuthLevelSelect.value="Read-only"; }else{ $scope.editUserInfo.userAuthLevelSelect.value="Custom"; var customCode = parseInt(userData['users_auth_custom']); populateCustomPreBits(customCode); $scope.showCustomOptions = true; } } }); getSNMPV3Data(); //populate snmpv3 settings angular.forEach($scope.snmpv3settings['snmp_local_users'] , function(data,index){ if(id == data['user_id']){ $scope.editUserInfo.snmpv3.addr4Traps = data['access_address']; $scope.editUserInfo.snmpv3.privPassword = "********"; $scope.editUserInfo.snmpv3.cfmPrivPassword = "********"; var authProtocol = data['auth_protocol']; if(authProtocol == 0){ $scope.editUserInfo.snmpv3.authProValue = "None"; }else if(authProtocol == 1){ $scope.editUserInfo.snmpv3.authProValue = "HMAC-MD5"; }else{ $scope.editUserInfo.snmpv3.authProValue = "HMAC-SHA"; } var privProtocol = data['privacy_protocol']; if(privProtocol == 0){ $scope.editUserInfo.snmpv3.privProValue = "None"; }else if(privProtocol == 1){ $scope.editUserInfo.snmpv3.privProValue = "CBC - DES"; }else{ $scope.editUserInfo.snmpv3.privProValue = "AES"; } } }); } var restCreateUser = cfgUserInfoService.restCreateUser(); var restUploadSSHKeyStr = cfgUserInfoService.restUploadSSHKeyStr(); $scope.editUserSubmit = function(id){ //max user number on imm is 12 if($scope.editUserInfo.userId != 0){ var payload =""+$scope.editUserInfo.userId+","+$scope.editUserInfo.username+","; if($scope.editUserInfo.cfmpassword !='' && $scope.editUserInfo.password != '' && ($scope.editUserInfo.cfmpassword != $scope.editUserInfo.password)){ $scope.inputTest.customErr="Password mismatch !"; return; } if(angular.isDefined($scope.editUserInfo.snmpv3.privPassword) && angular.isDefined($scope.editUserInfo.snmpv3.cfmPrivPassword) && $scope.editUserInfo.snmpv3.privPassword !='' && $scope.editUserInfo.snmpv3.cfmPrivPassword != '' && ($scope.editUserInfo.snmpv3.privPassword != $scope.editUserInfo.snmpv3.cfmPrivPassword)){ $scope.inputTest.customErr="Password mismatch !"; return; } payload =payload + (($scope.editUserInfo.password == "********")?"":$scope.editUserInfo.password) +","+$scope.editUserInfo.userAccess +","; updateCustomAuthCode(); payload = payload + $scope.editUserInfo.customAuthCode +","; //workaround, use default snmp/ssh settings //payload = payload + "1,2,0,0,,1,"; //snmpv3 settings , auth protocol var useAuthProtocal; var authProtocal; if(angular.isDefined($scope.editUserInfo.snmpv3.authProValue)){ if($scope.editUserInfo.snmpv3.authProValue == 'None'){ useAuthProtocal = 0; authProtocal = 0; }else if($scope.editUserInfo.snmpv3.authProValue == 'HMAC-MD5'){ useAuthProtocal = 1; authProtocal = 1; }else{ useAuthProtocal = 1; authProtocal = 2; } }else{ useAuthProtocal = 0; authProtocal = 0; } //appending auth protocol payload = payload + useAuthProtocal +"," + authProtocal +","; //snmpv3 settings , privacy protocol var usePrivProtocal; var privProtocal; if(angular.isDefined($scope.editUserInfo.snmpv3.privProValue)){ if($scope.editUserInfo.snmpv3.privProValue == 'None'){ usePrivProtocal = 0; privProtocal = 0; }else if($scope.editUserInfo.snmpv3.privProValue == 'AES'){ usePrivProtocal = 1; privProtocal = 2; }else{ usePrivProtocal = 1; privProtocal = 2; } }else{ usePrivProtocal = 0; privProtocal = 0; } //appending priv protocol payload = payload + usePrivProtocal +"," + privProtocal +","; //appending priv password if(angular.isDefined($scope.editUserInfo.snmpv3.privPassword) && $scope.editUserInfo.snmpv3.privPassword != "********"){ payload = payload + $scope.editUserInfo.snmpv3.privPassword +","; }else{ payload = payload +","; } //do not have access type defind,so set 'snmpAccType' to read by default //appending access type payload = payload + 1+","; var userId = $scope.editUserInfo.userId; var keyStr = $scope.editUserInfo.ssh.textVal; //appending traps ip or host if(angular.isDefined($scope.editUserInfo.snmpv3.addr4Traps) && '' != $scope.editUserInfo.snmpv3.addr4Traps){ payload = payload + $scope.editUserInfo.snmpv3.addr4Traps; } console.log("payload\t"+payload); restCreateUser.save({},{"USER_UserModify":payload},function(data){ if(data["return"] !== 0){ $scope.$emit('showErrMsgBox', "Failed to edit the selected user !"); return; } //$scope.$emit('showErrMsgBox', "User has been created successfully !"); //save ssh key console.log("userId\t"+userId); console.log("keyStr\t"+keyStr); if("" != keyStr){ restUploadSSHKeyStr.save({},{"USER_SSHKeyUploadFromText":""+userId+","+keyStr},function(data){ if(data["return"] !== 0){ $scope.$emit('showErrMsgBox', "The user has been modified but the SSH Key upload failed !"); return; }else{ $scope.$emit('showErrMsgBox', "User has been modified successfully !"); //did an update getUserData(); getSNMPV3Data(); } }, function(err) { console.log(err); $scope.$emit('showErrMsgBox', "Failed to create user !"); }); }else{ $scope.$emit('showErrMsgBox', "User has been modified successfully !"); } //did an update getUserData(); getSNMPV3Data(); //$scope.$emit('showErrMsgBox', "User info has been modified successfully !"); }, function(err) { console.log(err); $scope.$emit('showErrMsgBox', "Failed to edit the selected user !"); }); }else{ $scope.$emit('showErrMsgBox', "Can not create new user due to user number exceed limit !"); } //$scope.editUserInfo ={}; //hide the edit div $scope.displayEditDiv(id); } $scope.editUserCancel = function(id){ //hide the edit div $scope.displayEditDiv(id); } // id2del stores the user id to be deleted, if non-empty, the page will display the deleting message box // click Ok, removeItem() will be call to do a fake del operations // click cancel, the deleting message box will be hidden // the id2edit works exactly like the id2del $scope.id2del=''; $scope.id2edit=''; $scope.displayDelDiv = function(id) { if($scope.id2del != ''){ $scope.id2edit=''; $scope.id2del = ''; }else{ $scope.id2edit=''; $scope.id2del = id; } }; $scope.displayEditDiv = function(id) { if($scope.id2edit != ''){ $scope.id2del=''; $scope.id2edit = ''; }else{ $scope.id2del=''; $scope.id2edit = id; //populate edit user info populateEditUseInfo(id); } }; $scope.checkDel = function(id) { if($scope.id2del==id){ return true; }else{ return false; } }; $scope.checkEdit = function(id) { if($scope.id2edit==id){ return true; }else{ return false; } }; //Delete user var restDelUser = cfgUserInfoService.restDelUser(); $scope.deleteUser = function (id,name) { $scope.id2del=''; var payloadStr = id+","+name; restDelUser.save({},{"USER_UserDelete":payloadStr},function(data){ if(data["return"] !== 0){ //$scope.$emit('showErrMsgBox', JSON.stringify(data)); $scope.$emit('showErrMsgBox', "Failed to delete the selected user !"); return; } $scope.$emit('showErrMsgBox', "The selected user has been deleted successfully !"); getUserData(); }, function(err) { $scope.$emit('showErrMsgBox', "Failed to delete the selected user !"); }); } //LDAP //TODO start // [Hostname or IPv4, IPv6 address Port] groups on the ldap config view // we can add at least one group by default, max 3 groups $scope.ldap ={}; $scope.ldap.serverAndPorts =[]; $scope.addRows = function() { var len = $scope.ldap.serverAndPorts.length; var emptyItem = {"addr":"","port":0}; if(len < 4){ $scope.ldap.serverAndPorts.push(emptyItem); } }; $scope.delRows = function(index) { var len = $scope.ldap.serverAndPorts.length; if(len>1){ $scope.ldap.serverAndPorts.splice(index,1); } }; //Get LDAP settings $scope.bindingMethodData = [{id:0,value:'No Credentials Required'},{id:1,value:'Use Configured Credentials'},{id:2,value:'Use Login Credentials'}]; var restGetLDAPSetting = cfgUserInfoService.restGetLDAPSetting(); restGetLDAPSetting.get(function(data) { $scope.ldap.ldap_use_server_method_val = data['items'][0].ldap_use_server_method; if($scope.ldap.ldap_use_server_method_val == 0){ $scope.ldapAuthSelect.value ='Use LDAP server for Authentication and Authorization'; }else{ $scope.ldapAuthSelect.value ='Use LDAP server for Authentication only(with local authorization)'; } $scope.ldap.ldap_source_select_val = data['items'][0].ldap_source_select; if($scope.ldap.ldap_source_select_val == 0){ $scope.ldapServerSelect.value ='Use Pre-Configured Servers'; }else{ $scope.ldapServerSelect.value = 'Use DNS to find Servers'; } //enable roles $scope.ldap.ldap_enable_roles_val = data['items'][0].ldap_enable_roles; if($scope.ldap.ldap_enable_roles_val == 1){ $scope.ldap.EnableRole = true; $scope.showAddServerName = true; var srvName = data['items'][0].ldap_forest_name; $scope.ldap.srvName = srvName } //server and ports var ldap_server_address_1 = data['items'][0].ldap_server_address_1; var ldap_server_address_2 = data['items'][0].ldap_server_address_2; var ldap_server_address_3 = data['items'][0].ldap_server_address_3; var ldap_server_address_4 = data['items'][0].ldap_server_address_4; var ldap_server_port_1 = data['items'][0].ldap_server_port_1; var ldap_server_port_2 = data['items'][0].ldap_server_port_2; var ldap_server_port_3 = data['items'][0].ldap_server_port_3; var ldap_server_port_4 = data['items'][0].ldap_server_port_4; console.log(ldap_server_address_1+"|\t"+ldap_server_address_2+"|\t"+ldap_server_address_3+"|\t"+ldap_server_address_2); if(ldap_server_address_1 != '' && ldap_server_address_1 != ' ' && ldap_server_address_1 != '0.0.0.0'){ console.log('pushing1'); $scope.ldap.serverAndPorts.push({"addr":ldap_server_address_1,"port":ldap_server_port_1}); } if(ldap_server_address_2 != '' && ldap_server_address_2 != ' ' && ldap_server_address_2 != '0.0.0.0'){ console.log('pushing2'); $scope.ldap.serverAndPorts.push({"addr":ldap_server_address_2,"port":ldap_server_port_2}); } if(ldap_server_address_3 != '' && ldap_server_address_4 != ' ' && ldap_server_address_3 != '0.0.0.0'){ console.log('pushing3'); $scope.ldap.serverAndPorts.push({"addr":ldap_server_address_3,"port":ldap_server_port_3}); } if(ldap_server_address_4 != '' && ldap_server_address_4 != ' ' && ldap_server_address_4 != '0.0.0.0'){ console.log('pushing4'); $scope.ldap.serverAndPorts.push({"addr":ldap_server_address_4,"port":ldap_server_port_4}); } //if all empty if($scope.ldap.serverAndPorts.length <1){ console.log(" serverAndPorts empty"); $scope.ldap.serverAndPorts =[{"addr":"","port":0}]; } //Additional Parameters //binding method $scope.ldap.ldap_bind_method_val = data['items'][0].ldap_bind_method; $scope.ldap.ldap_root_dn = data['items'][0].ldap_root_dn; $scope.ldap.ldap_uid_search_attr = data['items'][0].ldap_uid_search_attr; $scope.ldap.ldap_group_filter = data['items'][0].ldap_group_filter; $scope.ldap.ldap_group_search_attr = data['items'][0].ldap_group_search_attr; $scope.ldap.ldap_perm_attr = data['items'][0].ldap_perm_attr; }); $scope.ldap.EnableRole = false; $scope.checkLDAPSecChg = function(ldapEnableRole) { if(ldapEnableRole){ $scope.showAddServerName = true; }else{ $scope.showAddServerName = false; } }; //Apply LDAP settings var restSetLDAPSetting = cfgUserInfoService.restSetLDAPSetting(); $scope.applyLDAPSetting = function(){ var ldapSetting ={ "USER_GlobalAuthMethod": "0", "LDAP_ServerSource": "0", "LDAP_RootDN": "", "LDAP_UIDSearchAttribute": "", "LDAP_BindingMethod": "0", "LDAP_RoleBasedSecurityEna": "0", "LDAP_DomainSource": "", "LDAP_SearchDomain": "", "LDAP_ServiceName": "ldap", "LDAP_ServerHost_1": "", "LDAP_ServerHost_2": "", "LDAP_ServerHost_3": "", "LDAP_ServerHost_4": "", "LDAP_ServerPort_1": "389", "LDAP_ServerPort_2": "389", "LDAP_ServerPort_3": "389", "LDAP_ServerPort_4": "389", "LDAP_ClientDN": "", "LDAP_ClientPassword": "", "LDAP_ServerTargetName": "", "LDAP_GroupFilter": "", "LDAP_GroupSearchAttribute": "", "LDAP_LoginPermissionAttribute": "", "LDAP_UseServerMethod": "0", "LDAP_ForestName": "", "LDAP_DomainName": "" }; // ldapSetting.USER_GlobalAuthMethod = ""+$scope.globalSettings.userAuthMethod; ldapSetting.LDAP_RootDN = ""+$scope.ldap.ldap_root_dn; ldapSetting.LDAP_UIDSearchAttribute = ""+$scope.ldap.ldap_uid_search_attr; ldapSetting.LDAP_BindingMethod= ""+$scope.ldap.ldap_bind_method_val; if($scope.ldap.EnableRole){ ldapSetting.LDAP_RoleBasedSecurityEna = "1"; }else{ ldapSetting.LDAP_RoleBasedSecurityEna = "0"; } ldapSetting.LDAP_DomainSource = ""+2;//what is this field used for ldapSetting.LDAP_SearchDomain = "";//what is this field used for ldapSetting.LDAP_ServiceName = "ldap" //server and ports //$scope.ldap.serverAndPorts $scope.ldap.validServerCount = 0; angular.forEach($scope.ldap.serverAndPorts, function(srvAndPort,index){ if(srvAndPort.addr !='' && srvAndPort.addr !=' ' && srvAndPort.addr !='0.0.0.0'){ $scope.ldap.validServerCount ++; }else{ $scope.ldap.serverAndPorts.splice(index,1); } }); var srvNum =$scope.ldap.serverAndPorts.length; if(srvNum == 1){ ldapSetting.LDAP_ServerHost_1=$scope.ldap.serverAndPorts[0].addr; ldapSetting.LDAP_ServerPort_1=$scope.ldap.serverAndPorts[0].port; }else if(srvNum == 2){ ldapSetting.LDAP_ServerHost_1=$scope.ldap.serverAndPorts[0].addr; ldapSetting.LDAP_ServerPort_1=$scope.ldap.serverAndPorts[0].port; ldapSetting.LDAP_ServerHost_2=$scope.ldap.serverAndPorts[1].addr; ldapSetting.LDAP_ServerPort_2=$scope.ldap.serverAndPorts[1].port; }else if(srvNum == 3){ ldapSetting.LDAP_ServerHost_1=$scope.ldap.serverAndPorts[0].addr; ldapSetting.LDAP_ServerPort_1=$scope.ldap.serverAndPorts[0].port; ldapSetting.LDAP_ServerHost_2=$scope.ldap.serverAndPorts[1].addr; ldapSetting.LDAP_ServerPort_2=$scope.ldap.serverAndPorts[1].port; ldapSetting.LDAP_ServerHost_3=$scope.ldap.serverAndPorts[2].addr; ldapSetting.LDAP_ServerPort_3=$scope.ldap.serverAndPorts[2].port; }else if(srvNum == 4){ ldapSetting.LDAP_ServerHost_1=$scope.ldap.serverAndPorts[0].addr; ldapSetting.LDAP_ServerPort_1=$scope.ldap.serverAndPorts[0].port; ldapSetting.LDAP_ServerHost_2=$scope.ldap.serverAndPorts[1].addr; ldapSetting.LDAP_ServerPort_2=$scope.ldap.serverAndPorts[1].port; ldapSetting.LDAP_ServerHost_3=$scope.ldap.serverAndPorts[2].addr; ldapSetting.LDAP_ServerPort_3=$scope.ldap.serverAndPorts[2].port; ldapSetting.LDAP_ServerHost_4=$scope.ldap.serverAndPorts[3].addr; ldapSetting.LDAP_ServerPort_4=$scope.ldap.serverAndPorts[3].port; } ldapSetting.LDAP_GroupFilter = ""+$scope.ldap.ldap_group_filter; ldapSetting.LDAP_GroupSearchAttribute = ""+$scope.ldap.ldap_group_search_attr; ldapSetting.LDAP_LoginPermissionAttribute = ""+$scope.ldap.ldap_perm_attr; ldapSetting.LDAP_UseServerMethod = ""+$scope.ldap.ldap_use_server_method_val; ldapSetting.LDAP_ForestName = ""+$scope.ldap.srvName; restSetLDAPSetting.save({},ldapSetting,function(data){ if(data["return"] !== 0){ //$scope.$emit('showErrMsgBox', JSON.stringify(data)); $scope.$emit('showErrMsgBox', "Failed to apply LDAP settings !"); return; } $scope.$emit('showErrMsgBox', "LDAP settings has been saved successfully!"); }, function(err) { $scope.$emit('showErrMsgBox', "Failed to apply LDAP settings !"); }); $scope.showGlobalSettings = false; } // changing views $scope.chgMap = function(viewName){ if(viewName == 'localUserOrLDAP'){ $scope.showLocalUser = !$scope.showLocalUser; if(!$scope.showLocalUser){ $scope.showGlobalSettings = false; $scope.showCreateUser = false; } } if(viewName == 'createUser'){ //always hidden gobal settings view if it is displayed if($scope.showGlobalSettings){ $scope.showGlobalSettings = !$scope.showGlobalSettings; } $scope.showCreateUser = !$scope.showCreateUser; } if(viewName == 'globalSettings'){ if($scope.showCreateUser){ $scope.showCreateUser = !$scope.showCreateUser; } $scope.showGlobalSettings = !$scope.showGlobalSettings; } if(viewName == 'SNMPV3'){ if($scope.showAddingSSHKey){ $scope.showAddingSSHKey =false; } $scope.showSNMPv3Setting = !$scope.showSNMPv3Setting; } if(viewName == 'additionalParam'){ $scope.showAdditionalParam = !$scope.showAdditionalParam; } if(viewName == 'addingSSHKey'){ if($scope.showSNMPv3Setting){ $scope.showSNMPv3Setting = false; } $scope.showAddingSSHKey = !$scope.showAddingSSHKey; } }; //Create users $scope.createUserInfo.customAuthCode = 0; //$scope.createUserInfo.ssh $scope.createUserInfo.ssh.showTextArea = false; $scope.createUserInfo.ssh.textVal = ""; $scope.toggleTextareaVisibility = function(val){ if(val == '1'){//create user $scope.createUserInfo.ssh.showTextArea = !$scope.createUserInfo.ssh.showTextArea; }else if(val == '2'){//edit user $scope.editUserInfo.ssh.showTextArea = !$scope.editUserInfo.ssh.showTextArea; } } $scope.createUser = function() { if(angular.isDefined($scope.createUserInfo.snmpv3.privPassword) && angular.isDefined($scope.createUserInfo.snmpv3.cfmPrivPassword) && $scope.createUserInfo.snmpv3.privPassword !='' && $scope.createUserInfo.snmpv3.cfmPrivPassword != '' && ($scope.createUserInfo.snmpv3.privPassword != $scope.createUserInfo.snmpv3.cfmPrivPassword)){ $scope.inputTest.customErr="Password mismatch !"; return; } //max user number on imm is 12 if($scope.createUserInfo.userId != 0){ var payload =""+$scope.createUserInfo.userId+","+$scope.createUserInfo.username+","; if($scope.createUserInfo.cfmpassword !='' && $scope.createUserInfo.password != '' && ($scope.createUserInfo.cfmpassword != $scope.createUserInfo.password)){ $scope.inputTest.customErr="Password mismatch !"; return; } payload =payload + $scope.createUserInfo.password +","+$scope.createUserInfo.authLvl +","; updateCustomAuthCode(1); payload = payload + $scope.createUserInfo.customAuthCode +","; //snmpv3 settings , auth protocol var useAuthProtocal; var authProtocal; if(angular.isDefined($scope.createUserInfo.snmpv3.authProValue)){ if($scope.createUserInfo.snmpv3.authProValue == 'None'){ useAuthProtocal = 0; authProtocal = 0; }else if($scope.createUserInfo.snmpv3.authProValue == 'HMAC-MD5'){ useAuthProtocal = 1; authProtocal = 1; }else{ useAuthProtocal = 1; authProtocal = 2; } }else{ useAuthProtocal = 0; authProtocal = 0; } //appending auth protocol payload = payload + useAuthProtocal +"," + authProtocal +","; //snmpv3 settings , privacy protocol var usePrivProtocal; var privProtocal; if(angular.isDefined($scope.createUserInfo.snmpv3.privProValue)){ if($scope.createUserInfo.snmpv3.privProValue == 'None'){ usePrivProtocal = 0; privProtocal = 0; }else if($scope.createUserInfo.snmpv3.privProValue == 'AES'){ usePrivProtocal = 1; privProtocal = 2; }else{ usePrivProtocal = 1; privProtocal = 2; } }else{ usePrivProtocal = 0; privProtocal = 0; } //appending priv protocol payload = payload + usePrivProtocal +"," + privProtocal +","; //appending priv password if(angular.isDefined($scope.createUserInfo.snmpv3.privPassword)){ payload = payload + $scope.createUserInfo.snmpv3.privPassword +","; }else{ payload = payload +","; } //do not have access type defind,so set 'snmpAccType' to read by default //appending access type payload = payload + 1+","; //appending traps ip or host if(angular.isDefined($scope.createUserInfo.snmpv3.addr4Traps) && '' != $scope.createUserInfo.snmpv3.addr4Traps){ payload = payload + $scope.createUserInfo.snmpv3.addr4Traps; } console.log("payload\t"+payload); console.log("$scope.createUserInfo.ssh.textVal\t"+$scope.createUserInfo.ssh.textVal); //return; //workaround, use default snmp/ssh settings //payload = payload + "1,2,0,0,,1,"; var userId = $scope.createUserInfo.userId; var keyStr = $scope.createUserInfo.ssh.textVal; restCreateUser.save({},{"USER_UserCreate":payload},function(data){ if(data["return"] !== 0){ $scope.$emit('showErrMsgBox', "Failed to create user !"); return; }else{ //$scope.$emit('showErrMsgBox', "User has been created successfully !"); //save ssh key console.log("userId\t"+userId); console.log("keyStr\t"+keyStr); if("" != keyStr){ restUploadSSHKeyStr.save({},{"USER_SSHKeyUploadFromText":""+userId+","+keyStr},function(data){ if(data["return"] !== 0){ $scope.$emit('showErrMsgBox', "The user has been created but the SSH Key upload failed !"); return; }else{ $scope.$emit('showErrMsgBox', "User has been created successfully !"); //did an update getUserData(); getSNMPV3Data(); } }, function(err) { console.log(err); $scope.$emit('showErrMsgBox', "Failed to create user !"); }); }else{ $scope.$emit('showErrMsgBox', "User has been created successfully !"); } //did an update getUserData(); getSNMPV3Data(); } }, function(err) { console.log(err); $scope.$emit('showErrMsgBox', "Failed to create user !"); }); $scope.showCreateUser = false; $scope.createUserInfo ={}; }else{ $scope.$emit('showErrMsgBox', "Can not create new user due to user number exceed limit !"); } }; $scope.cancelCreate = function(){ $scope.showCreateUser = false; $scope.createUserInfo ={}; } $scope.showCertContentArea = false; $scope.showDownloadCertDailog = function(dailogId, certId, certType){ $scope.downloadCertContent = "-----BEGIN CERTIFICATE-----<KEY>IjK66Iauf+RcUph6+<KEY>-----END CERTIFICATE-----" $("#"+dailogId).modal(); } $scope.showCertContent = function(){ $scope.showCertContentArea = !$scope.showCertContentArea; if($scope.showCertContentArea) { $("#cert_arrow_img").attr("src", "www/images/network/u279.png"); } else { $("#cert_arrow_img").attr("src", "www/images/arrow_right.png"); } } $scope.removeCertDailogTitle = ""; $scope.removeCertDailogContent = ""; $scope.removeCertificate = function(type, certId, category, dailogId){ //alert(type + " " + certId + " " + category); if(category == "https"){ $scope.removeCertDailogTitle = "HTTPs"; $scope.removeCertDailogContent = "Changes to the security settings will cause existing web session to be terminated. HTTPs will be disabled and a new login via HTTP protocol will be required."; } else if (category == "cim_over_https"){ $scope.removeCertDailogTitle = "CIM Over HTTPs"; $scope.removeCertDailogContent = "Changes to the security settings will cause existing session to be terminated. CIM Over HTTPs will be disabled."; } else if (category == "secureLdap"){ $scope.removeCertDailogTitle = "Secure LDAP"; $scope.removeCertDailogContent = "Changes to the security settings will cause existing session to be terminated. Secure LDAP will be disabled."; } else{ $scope.removeCertDailogTitle = ""; $scope.removeCertDailogContent = ""; } $("#"+dailogId).modal(); } $scope.showImportCertDailog = function(dailogId, dialogType){ if(dialogType == "HTTPs" || dialogType == "CIM Over HTTPS"){ $scope.importCertDlgTitle = "Signed"; $scope.importCertDlgContent = "The certificate being imported must have been created from the Certificate Signing Request most recently created."; } else if(dialogType == "Secure LDAP") { $scope.importCertDlgTitle = "LDAP Trusted"; $scope.importCertDlgContent = ""; } else if(dialogType == "SKLM") { $scope.importCertDlgTitle = "SKLM Server"; $scope.importCertDlgContent = "A certificate is required to commnunicate with the SKLM servers."; } $scope.importModalDailogtype = dialogType; $("#"+dailogId).modal(); } $scope.showPasteEditArea = false; $scope.showPasteInput = function(){ $scope.showPasteEditArea = !$scope.showPasteEditArea; if($scope.showPasteEditArea) { $("#sec_arrow_img").attr("src", "www/images/network/u279.png"); } else { $("#sec_arrow_img").attr("src", "www/images/network/u279left.png"); } } $scope.submitImportTrustedCertificate = function(dailogId){ $("#"+dailogId).modal(); } } ]); <file_sep><div style="margin: 20px;"> <button type="button" class="close" aria-label="Close" ng-click="clkCancel()"><span aria-hidden="true">&times;</span></button> <!-- <div style="font-size: 16px; color: #666;" translate="confirmRestartImm"></div> --> <div class="modal-nobottom-header"> <h5 class="modal-nobottom-title">{{'homeRemoteRemoteConsoleSettings'|translate}}</h5> </div> <div class="modal-body"> <span>{{'homeRemoteSelectAccessMode'|translate}}</span> <div class="radio"> <label style="font-size:12px"> <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked> {{'homeRemoteSingleUserMode'|translate}} </label> </div> <div class="radio"> <label style="font-size:12px"> <input type="radio" name="optionsRadios" id="optionsRadios2" value="option2"> {{'homeRemoteMultiUserMode'|translate}} </label> </div> <span>{{'homeRemoteAdvSettings'|translate}}</span> <div class="checkbox"> <label style="font-size:12px"class="checkbox"> <input type="checkbox">{{'homeRemoteEncryptTransmission'|translate}}</label> </div> <div class="checkbox"><label style="font-size:12px" class="checkbox"> <input type="checkbox">{{'homeRemoteAllowDisconnectReuqest'|translate}}</label></div> <div class="row" style="margin-left:20px;font-size:12px"> <span >{{'homeRemoteNoResponseInterval'|translate}}</span> <select id="u259_input"> <option value="1 hour">1 hour</option> </select> </div> </div> <div style="margin: 20px 20px;"> <button style="width: 100px;" type="button" class="btn btn-primary btn-default-size" ng-click="clkOk()" >{{'homeRemoteApply'|translate}}</button> <button style="margin-left: 20px; width: 100px;" type="button" class="btn btn-default btn-default-size" ng-click="clkCancel()" translate="lblCancel"></button> </div> </div><file_sep>'use strict'; angular.module('imm3.security.service', ['ngResource']) .factory('securityService', ['$resource', '$http', '$q', function ($resource, $http, $q) { var basePath = '/api/'; var service = { resetSecureServicesConfiguration: function (params) { var url = basePath + 'dataset'; return $http.post(url, params); }, /*------------------------------*/ getSecurityStatusSummary: function (params) { var url = basePath + 'dataset/imm_security'; return $http.get(url, params); }, getCountryinfo: function (params) { var url = basePath + 'countryinfo'; return $http.get(url, params); }, /*------------------------------*/ generateSSC: function (param) { var url = basePath + 'function'; return $http.post(url, {'Sec_GenKeyAndCert': param}); }, generateCSR: function (param) { var url = basePath + 'function'; return $http.post(url, {'Sec_GenKeyAndCSR': param}); }, importCertificate: function (param) { var url = basePath + 'function'; return $http.post(url, {'Sec_ImportCert': param}); }, notifyCertificateFileUpload: function (params) { var deferred = $q.defer(); var url = basePath + 'providers/cert_upload'; $http.post(url, params) .success(function (data) { if (0 == data.return) { deferred.resolve(true); } else { deferred.resolve(false); } }) .error(function (data) { deferred.reject(false); }); return deferred.promise; }, removeCertificate: function (param) { var url = basePath + 'function'; return $http.post(url, {'Sec_RemoveCert': param}); }, downloadCertificateFormat: function (param) { var deferred = $q.defer(); var url = basePath + 'dataset'; $http.post(url, {'CSR_Format': param}) .success(function (data) { if (0 == data.return) { deferred.resolve(true); } else { deferred.resolve(false); } }) .error(function (data) { deferred.reject(false); }); return deferred.promise; }, downloadCertificate: function (param) { var url = basePath + 'function'; return $http.post(url, {'Sec_DownloadCSRANDCert': param}); }, viewCertificate: function (param) { var url = basePath + 'function'; return $http.post(url, {"Sec_ViewCSRANDCert": param}); }, /*------------------------------*/ /*------------------------------*/ getSSHServeStatus: function (params) { var url = basePath + 'dataset/imm_security_ssh_server'; return $http.get(url, params); }, resetSSHServeStatus: function (param) { var url = basePath + 'dataset'; return $http.post(url, {'SSH_Ena': param}); }, generateSSHServerPrivateKey: function (param) { var url = basePath + 'dataset'; return $http.post(url, {'Sec_SSHD_generatePrivateKeys': param}); }, /*------------------------------*/ resetFirmwareDownLevelStatus: function (param) { var url = basePath + 'dataset'; return $http.post(url, {'Rollback_Ena': param}); }, resetPhysicalPrenseceStatus: function (param) { var url = basePath + 'dataset'; return $http.post(url, {'IMM_RPPAssert': param}); }, /*------------------------------*/ resetIPMIStatus: function (param) { var url = basePath + 'dataset'; return $http.post(url, {'IPMI_Ena': param}); }, resetIPMIOverKCSStatus: function (param) { var url = basePath + 'dataset'; return $http.post(url, {'IPMIoverKCS_Ena': param}); }, /*------------------------------*/ resetCryptographicMode: function (param) { var url = basePath + 'dataset'; return $http.post(url, {'sec_level_mode': param}); } /*------------------------------*/ }; return service; }]);<file_sep>'use strict'; angular.module('imm3.utilization.service', [ 'ngResource', 'pascalprecht.translate' ]) .factory('utGraphicTemperatureService', ['$resource', '$q', '$translate', function($resource, $q, $translate) { var service = {}; service.restAmbientTemperature = function() { return $resource('/api/dataset/imm_props_environ'); }; var tempOption = { tooltip : { formatter: "{c}\u2109", textStyle: { fontSize: 10 } }, title : { show : false, // offsetCenter: [0, 0], textStyle: { fontWeight: 'bolder', fontSize: 14 }, text: "68.9C" }, min: 0, max: 150, series : [{ type:'gauge', startAngle: 180, endAngle: 0, center: ["40%", "70%"], radius: [0, 70], axisLine: { lineStyle: { color: [[0.6, '#6ABF4A'], [0.8, '#FFFF00'], [0.9, '#FF6A00'], [1, '#E2231A']], // color: ['#6ABF4A','#FFFF00', '#FF6A00', '#E2231A'], width: 10 } }, axisTick: { show: false }, axisLabel: { show: false }, splitLine: { show: false }, pointer : { width : 5 }, detail : { show: true, formatter: '{value}\u2109', offsetCenter: [0, '10%'], textStyle: { fontWeight: 'bolder', color: '#333', fontSize : 15 } }, data:[{value: 0, name: ''}] }] }; var greyOutTempChart = function (){ tempOption.series[0].data[0].value = 0; tempOption.series[0].data[0].name = 'N/A'; tempOption.series[0].axisLine.lineStyle.color[0][0] = 0; tempOption.series[0].axisLine.lineStyle.color[1][0] = 0; tempOption.series[0].axisLine.lineStyle.color[2][0] = 0; //grey out the chart tempOption.series[0].axisLine.lineStyle.color[0][1] = '#DDDDDC'; tempOption.series[0].axisLine.lineStyle.color[1][1] = '#DDDDDC'; tempOption.series[0].axisLine.lineStyle.color[2][1] = '#DDDDDC'; tempOption.series[0].axisLine.lineStyle.color[3][1] = '#DDDDDC'; }; var fahren2Centi = function(fahData){ return ((parseFloat(fahData)-parseFloat(32))/parseFloat(1.8)).toFixed(1); }; service.drawTemperature = function(fahrenFlag) { service.restAmbientTemperature().get(function(data) { var temps = data["items"][0]["temps"]; if(temps != undefined){ var max = 135; if(fahrenFlag){ angular.forEach(temps, function(item) { var sour = item['temps.source']; if(sour == 'Ambient Temp') { max = item['temps.fatal_upper_threshold']-item['temps.value']>0 ? parseFloat(item['temps.fatal_upper_threshold'])+parseFloat(5) : parseFloat(item['temps.value'])+parseFloat(5); tempOption.series[0].data[0].value = parseFloat(item['temps.value']); tempOption.series[0].detail.formatter = '{value}\u2109'; tempOption.tooltip.formatter = "{c}\u2109"; tempOption.series[0].axisLine.lineStyle.color[0][0] = item['temps.noncritical_upper_threshold'] / max; tempOption.series[0].axisLine.lineStyle.color[1][0] = item['temps.critical_upper_threshold'] / max; tempOption.series[0].axisLine.lineStyle.color[2][0] = item['temps.fatal_upper_threshold'] / max; } }); }else{ angular.forEach(temps, function(item) { var sour = item['temps.source']; if(sour == 'Ambient Temp'){ max = item['temps.fatal_upper_threshold']-item['temps.value']>0 ? fahren2Centi(parseFloat(item['temps.fatal_upper_threshold'])+parseFloat(5)) : fahren2Centi(parseFloat(item['temps.value'])+parseFloat(5)); tempOption.series[0].data[0].value = fahren2Centi(item['temps.value']); tempOption.series[0].detail.formatter = '{value}\u2103'; tempOption.tooltip.formatter = "{c}\u2103"; tempOption.series[0].axisLine.lineStyle.color[0][0] = fahren2Centi(item['temps.noncritical_upper_threshold']) / max; tempOption.series[0].axisLine.lineStyle.color[1][0] = fahren2Centi(item['temps.critical_upper_threshold']) / max; tempOption.series[0].axisLine.lineStyle.color[2][0] = fahren2Centi(item['temps.fatal_upper_threshold']) / max; } }); } }else{ console.log("/api/dataset/imm_props_environ response null."); greyOutTempChart(); } $translate([ 'lblAmbientTemperature' ]).then(function() { //tempOption.series[0].data[0].value = translations['lblAmbientTemperature']; var tempChart = echarts.init(document.getElementById("utAmbientTemper")); tempChart.setOption(tempOption); }); }, function(err) { console.log("Failed to get data from /api/dataset/imm_props_environ, error: "+err); greyOutTempChart(); $translate([ 'lblAmbientTemperature' ]).then(function() { var tempChart = echarts.init(document.getElementById("utAmbientTemper")); tempChart.setOption(tempOption); }); }); }; var utComponentTemperOptions = { grid: { borderWidth: 0, x: 15, y: 0, height: 100 }, tooltip: { show: true, trigger: 'item', formatter: "{c}\u2109", textStyle: { fontSize: 10 } }, xAxis: [{ show: true, type: 'category', axisLine: { show: false }, axisTick: { show: false }, splitLine: false, data: [] }], yAxis: [{ show: false, type: 'value', min: 0, max: 200 }], title : { show : false }, series: [{ name: 'Normal', type: 'bar', stack: 'sum', barWidth: 10, itemStyle: { normal: { color: '#6ABF4A', label: { show: false } } }, markLine: { symbol: "arrow", symbolSize: [3, 0], data: [[]], itemStyle: { normal: { color: "#333333", label: { show: true, formatter: "{c}\u2109", textStyle: { color: "#333333", fontSize: 12, fontWeight: 700 } } } } }, data: [] }, { name: 'Warning', type: 'bar', stack: 'sum', itemStyle: { normal: { color: '#FFFF00', label: { show: false } } }, data: [] }, { name: 'Critical', type: 'bar', stack: 'sum', itemStyle: { normal: { color: '#FF6A00', label: { show: false } } }, data: [] }, { name: 'Fatal', type: 'bar', stack: 'sum', itemStyle: { normal: { color: '#E2231A', label: { show: false } } }, data: [] }] }; var timeoutDrawComponentTemper = function(divName, option) { var dom = document.getElementById(divName); if(dom == undefined) { setTimeout(function() { timeoutDrawComponentTemper(divName, option); }, 300); return false; } var utComponentTemperChart = echarts.init(dom); utComponentTemperChart.setOption(option); }; var tmpCompCpu = {}; var tmpCpuTemper = -1; var tmpCompDimm = {}; var tmpDimmTmper = -1; var tmpCharts = []; var tmpCharts2 = []; var utCompTemperOptions = []; var utCompTemperCharts = []; service.drawComponentTemperature = function(fahrenFlag) { var deferred = $q.defer(); service.restAmbientTemperature().get(function(data) { tmpCharts = []; tmpCharts2 = []; angular.forEach(data["items"][0]["temps"], function(item) { var currtTemp = parseFloat(item["temps.value"]); var nonCrititTmp = parseFloat(item["temps.noncritical_upper_threshold"]); var criticTmp = parseFloat(item["temps.fatal_upper_threshold"]); if(item["temps.source"].indexOf("Amb") == -1) { if (item["temps.source"].indexOf("CPU") != -1) { if (isNaN(currtTemp)){ }else if(isNaN(nonCrititTmp) && isNaN(nonCrititTmp) && isNaN(criticTmp)){ }else { if (currtTemp > tmpCpuTemper) { tmpCpuTemper = currtTemp; tmpCompCpu = item; } } } else if(item["temps.source"].indexOf("DIMM") != -1){ if (isNaN(currtTemp)) { }else if(isNaN(nonCrititTmp) && isNaN(nonCrititTmp) && isNaN(criticTmp)){ }else { if (currtTemp > tmpDimmTmper) { tmpDimmTmper = currtTemp; tmpCompDimm = item; } } }else if (isNaN(currtTemp)){ } else if(isNaN(nonCrititTmp) && isNaN(nonCrititTmp) && isNaN(criticTmp)){ }else{ tmpCharts2.push(item); } } }); if(tmpCpuTemper != -1){ tmpCharts.push(tmpCompCpu); } if(tmpDimmTmper != -1){ tmpCharts.push(tmpCompDimm); } if(tmpCharts2[0] != ""){ angular.forEach(tmpCharts2, function(item){ tmpCharts.push(item); }) } angular.forEach(tmpCharts, function(item, index){ utCompTemperOptions[index] = {}; angular.copy(utComponentTemperOptions, utCompTemperOptions[index]); utCompTemperOptions[index].series[0].data[0] = {}; if(fahrenFlag){ utCompTemperOptions[index].series[0].data[0].value = item["temps.noncritical_upper_threshold"]; utCompTemperOptions[index].series[0].data[0].tooltip = {formatter: "< "+item["temps.noncritical_upper_threshold"] + "\u2109"}; utCompTemperOptions[index].series[0].markLine.itemStyle.normal.label.formatter = "{c}\u2109"; utCompTemperOptions[index].series[1].data[0] = {}; utCompTemperOptions[index].series[1].data[0].value = parseFloat(item["temps.critical_upper_threshold"] - item["temps.noncritical_upper_threshold"])+parseFloat(40); utCompTemperOptions[index].series[1].data[0].tooltip = {formatter: item["temps.noncritical_upper_threshold"]+" ~ "+item["temps.critical_upper_threshold"]+"\u2109"}; utCompTemperOptions[index].series[2].data[0] = {}; utCompTemperOptions[index].series[2].data[0].value = parseFloat(item["temps.fatal_upper_threshold"] - item["temps.critical_upper_threshold"])+parseFloat(40); utCompTemperOptions[index].series[2].data[0].tooltip = {formatter: item["temps.critical_upper_threshold"]+" ~ "+item["temps.fatal_upper_threshold"]+"\u2109"}; utCompTemperOptions[index].series[3].data[0] = {}; utCompTemperOptions[index].series[3].data[0].value = item["temps.fatal_upper_threshold"]-item["temps.value"]>0 ? parseFloat(40) : parseFloat(item["temps.value"])+parseFloat(40)-parseFloat(item["temps.fatal_upper_threshold"]); utCompTemperOptions[index].series[3].data[0].tooltip = {formatter: "> "+item["temps.fatal_upper_threshold"]+"\u2109"}; utCompTemperOptions[index].xAxis[0].data[0] = item["temps.source"]; utCompTemperOptions[index].yAxis[0].max = parseFloat(utCompTemperOptions[index].series[0].data[0].value)+parseFloat(utCompTemperOptions[index].series[1].data[0].value)+ parseFloat(utCompTemperOptions[index].series[2].data[0].value)+parseFloat(utCompTemperOptions[index].series[3].data[0].value); utCompTemperOptions[index].series[0].markLine.data[0][0] = {}; utCompTemperOptions[index].series[0].markLine.data[0][1] = {}; utCompTemperOptions[index].series[0].markLine.data[0][0].value = item["temps.value"]; utCompTemperOptions[index].series[0].markLine.data[0][0].xAxis = 0.1; utCompTemperOptions[index].series[0].markLine.data[0][1].xAxis = 0.2; if(parseFloat(item["temps.value"])<parseFloat(item["temps.noncritical_upper_threshold"])){ utCompTemperOptions[index].series[0].markLine.data[0][0].yAxis = parseFloat(item["temps.value"]); utCompTemperOptions[index].series[0].markLine.data[0][1].yAxis = parseFloat(item["temps.value"]); } else if(parseFloat(item["temps.noncritical_upper_threshold"]) <= parseFloat(item["temps.value"]) && parseFloat(item["temps.value"]) < parseFloat(item["temps.critical_upper_threshold"])){ utCompTemperOptions[index].series[0].markLine.data[0][0].yAxis = parseFloat(item["temps.value"])+parseFloat(20); utCompTemperOptions[index].series[0].markLine.data[0][1].yAxis = parseFloat(item["temps.value"])+parseFloat(20); }else if(parseFloat(item["temps.critical_upper_threshold"]) <= parseFloat(item["temps.value"] && item["temps.value"]) < parseFloat(item["temps.fatal_upper_threshold"])){ utCompTemperOptions[index].series[0].markLine.data[0][0].yAxis = parseFloat(item["temps.value"])+parseFloat(60); utCompTemperOptions[index].series[0].markLine.data[0][1].yAxis = parseFloat(item["temps.value"])+parseFloat(60); }else if(parseFloat(item["temps.value"]) >= parseFloat(item["temps.fatal_upper_threshold"])){ utCompTemperOptions[index].series[0].markLine.data[0][0].yAxis = parseFloat(item["temps.value"])+parseFloat(40*2); utCompTemperOptions[index].series[0].markLine.data[0][1].yAxis = parseFloat(item["temps.value"])+parseFloat(40*2); } utCompTemperOptions[index].xAxis[0].data[1] = ""; utCompTemperCharts[index] = {"divName": item["temps.source"].split(" ").join("")}; setTimeout(function() { timeoutDrawComponentTemper(utCompTemperCharts[index].divName, utCompTemperOptions[index]); }, 300); }else{ utCompTemperOptions[index].series[0].data[0].value = fahren2Centi(item["temps.noncritical_upper_threshold"]); utCompTemperOptions[index].series[0].data[0].tooltip = {formatter: "< "+fahren2Centi(item["temps.noncritical_upper_threshold"]) + "\u2103"}; utCompTemperOptions[index].series[0].markLine.itemStyle.normal.label.formatter = "{c}\u2103"; utCompTemperOptions[index].series[1].data[0] = {}; utCompTemperOptions[index].series[1].data[0].value = fahren2Centi(parseFloat(item["temps.critical_upper_threshold"] - item["temps.noncritical_upper_threshold"])+parseFloat(60)); utCompTemperOptions[index].series[1].data[0].tooltip = {formatter: fahren2Centi(item["temps.noncritical_upper_threshold"])+" ~ "+fahren2Centi(item["temps.critical_upper_threshold"])+"\u2103"}; utCompTemperOptions[index].series[2].data[0] = {}; utCompTemperOptions[index].series[2].data[0].value = fahren2Centi(parseFloat(item["temps.fatal_upper_threshold"] - item["temps.critical_upper_threshold"])+parseFloat(60)); utCompTemperOptions[index].series[2].data[0].tooltip = {formatter: fahren2Centi(item["temps.critical_upper_threshold"])+" ~ "+fahren2Centi(item["temps.fatal_upper_threshold"])+"\u2103"}; utCompTemperOptions[index].series[3].data[0] = {}; utCompTemperOptions[index].series[3].data[0].value = fahren2Centi(item["temps.fatal_upper_threshold"]-item["temps.value"])>0 ? fahren2Centi(parseFloat(60)) : fahren2Centi(parseFloat(item["temps.value"])+parseFloat(60)-parseFloat(item["temps.fatal_upper_threshold"])); utCompTemperOptions[index].series[3].data[0].tooltip = {formatter: "> "+fahren2Centi(item["temps.fatal_upper_threshold"])+"\u2103"}; utCompTemperOptions[index].xAxis[0].data[0] = item["temps.source"]; utCompTemperOptions[index].yAxis[0].max = parseFloat(utCompTemperOptions[index].series[0].data[0].value)+parseFloat(utCompTemperOptions[index].series[1].data[0].value)+ parseFloat(utCompTemperOptions[index].series[2].data[0].value)+parseFloat(utCompTemperOptions[index].series[3].data[0].value); utCompTemperOptions[index].series[0].markLine.data[0][0] = {}; utCompTemperOptions[index].series[0].markLine.data[0][1] = {}; utCompTemperOptions[index].series[0].markLine.data[0][0].value = fahren2Centi(item["temps.value"]); utCompTemperOptions[index].series[0].markLine.data[0][0].xAxis = 0.1; utCompTemperOptions[index].series[0].markLine.data[0][1].xAxis = 0.2; if(parseFloat(item["temps.value"])<parseFloat(item["temps.noncritical_upper_threshold"])){ utCompTemperOptions[index].series[0].markLine.data[0][0].yAxis = fahren2Centi(parseFloat(item["temps.value"])); utCompTemperOptions[index].series[0].markLine.data[0][1].yAxis = fahren2Centi(parseFloat(item["temps.value"])); } else if(parseFloat(item["temps.noncritical_upper_threshold"]) <= parseFloat(item["temps.value"]) && parseFloat(item["temps.value"]) < parseFloat(item["temps.critical_upper_threshold"])){ utCompTemperOptions[index].series[0].markLine.data[0][0].yAxis = fahren2Centi(parseFloat(item["temps.value"])+parseFloat(20)); utCompTemperOptions[index].series[0].markLine.data[0][1].yAxis = fahren2Centi(parseFloat(item["temps.value"])+parseFloat(20)); }else if(parseFloat(item["temps.critical_upper_threshold"]) <= parseFloat(item["temps.value"] && item["temps.value"]) < parseFloat(item["temps.fatal_upper_threshold"])){ utCompTemperOptions[index].series[0].markLine.data[0][0].yAxis = fahren2Centi(parseFloat(item["temps.value"])+parseFloat(60)); utCompTemperOptions[index].series[0].markLine.data[0][1].yAxis = fahren2Centi(parseFloat(item["temps.value"])+parseFloat(60)); }else if(parseFloat(item["temps.value"]) >= parseFloat(item["temps.fatal_upper_threshold"])){ utCompTemperOptions[index].series[0].markLine.data[0][0].yAxis = fahren2Centi(parseFloat(item["temps.value"])+parseFloat(40*2)); utCompTemperOptions[index].series[0].markLine.data[0][1].yAxis = fahren2Centi(parseFloat(item["temps.value"])+parseFloat(40*2)); } utCompTemperOptions[index].xAxis[0].data[1] = ""; utCompTemperCharts[index] = {"divName": item["temps.source"].split(" ").join("")}; setTimeout(function() { timeoutDrawComponentTemper(utCompTemperCharts[index].divName, utCompTemperOptions[index]); }, 300); } }); deferred.resolve(utCompTemperCharts); }, function(err) { console.log("failed"); deferred.reject(err); }); return deferred.promise; }; var temperatureHistoryOption = { grid: { borderWidth: 0, x: 35, y: 25, height: 105, width: "93%" }, tooltip: { trigger: 'axis', textStyle: { fontSize: 10 }, axisPointer: { lineStyle: { color: 'rgba(204, 204, 204, 1)' } }, // formatter: "{b}<br/>{a0}: {c0}W<br/>{a1}: {c1}W<br/>{a2}: {c2}W" formatter: "{b}<br/>{a0}: {c}℉" }, /* legend: { x: 'right', textStyle: { fontSize: 10 }, selectedMode: false, data:['CPU','Memory','I/O'] },*/ xAxis: [{ type: 'category', splitLine: { lineStyle: { color: 'rgba(204, 204, 204, 0.25)' } }, axisLine: { lineStyle : { color: 'rgba(204, 204, 204, 0.25)' } }, boundaryGap : false, data: [] }], yAxis: [{ type : 'value', splitLine: { lineStyle: { color: 'rgba(204, 204, 204, 0.25)' } }, axisLine: { lineStyle : { color: 'rgba(204, 204, 204, 0.25)' } } }], series: [{ name: 'temperItem', type: 'line', smooth: true, symbol: 'emptyCircle', itemStyle: { normal: { color: '#006DB9', lineStyle: { width: 1 }, areaStyle: { type: 'default', color: 'rgba(0, 109, 185, 0.1)' } } }, markPoint : { data : [ {type : 'max', name: 'max'}, {type : 'min', name: 'min'} ] }, data: [] }] }; service.restTemperatureHistory = function() { return $resource('/api/dataset/pwrmgmt', {params: '@params'}); }; var timeoutDrawTemperHistory = function(divName, option) { var dom = document.getElementById(divName); if(dom == undefined) { setTimeout(function() { timeoutDrawTemperHistory(divName, option); }, 300); return false; } var temperHistoryChart = echarts.init(dom); temperHistoryChart.setOption(option); }; service.drawTemperatureHistory = function(hours, historyItem) { var deferred = $q.defer(); service.restTemperatureHistory().get({params:"GetThermalHistoryByPeriod,"+hours}, function(data) { if(data["items"] == undefined || isNaN(data["items"][0].samplesCount)){ console.log("Failed to get temperature history data from GetThermalHistoryByPeriod"); var maxValue = 100; var minValue = 0; temperatureHistoryOption.series[0].data = [0]; temperatureHistoryOption.xAxis[0].data = ["N/A"]; temperatureHistoryOption.tooltip.formatter = "N/A"; temperatureHistoryOption.yAxis[0].max = maxValue; temperatureHistoryOption.yAxis[0].min = minValue; setTimeout(function() { timeoutDrawTemperHistory("utilizationTemperatureHistory", temperatureHistoryOption); }, 300); }else{ var tmpTimeLabel = data["items"][0]["labels"]; var tmpAmbTemper = data["items"][0]["Ambient Temp"]; var tmpDimmTemper = data["items"][0]["DIMM Temp"]; var tmpCpu1Temper = data["items"][0]["CPU 1 Temp"]; var sampleCnt = data["items"][0]["samplesCount"]; var timeLabel = []; var ambTemper = []; var dimmTemper = []; var cpu1Temper = []; var minPoint = 10000; var maxPoint = 0; var realIndex = 0; angular.forEach(tmpTimeLabel, function(item, index) { realIndex = parseInt(sampleCnt) - parseInt(1) - parseInt(index); timeLabel[realIndex] = item.timestamp; }); if(historyItem == 0){ angular.forEach(tmpAmbTemper, function(item, index) { realIndex = parseInt(sampleCnt) - parseInt(1) - parseInt(index); ambTemper[realIndex] = item; if(ambTemper[realIndex] < minPoint){ minPoint = ambTemper[realIndex]; } if(ambTemper[realIndex] > maxPoint){ maxPoint = ambTemper[realIndex]; } }); temperatureHistoryOption.series[0].name = "Ambient Temp"; temperatureHistoryOption.series[0].data = ambTemper; }else if(historyItem == 1){ angular.forEach(tmpDimmTemper, function(item, index) { realIndex = parseInt(sampleCnt) - parseInt(1) - parseInt(index); dimmTemper[realIndex] = item; if(dimmTemper[realIndex] < minPoint){ minPoint = dimmTemper[realIndex]; } if(dimmTemper[realIndex] > maxPoint){ maxPoint = dimmTemper[realIndex]; } }); temperatureHistoryOption.series[0].name = "DIMM Temp"; temperatureHistoryOption.series[0].data = dimmTemper; }else if(historyItem == 2){ angular.forEach(tmpCpu1Temper, function(item, index) { realIndex = parseInt(sampleCnt) - parseInt(1) - parseInt(index); cpu1Temper[realIndex] = item; if(cpu1Temper[realIndex] < minPoint){ minPoint = cpu1Temper[realIndex]; } if(cpu1Temper[realIndex] > maxPoint){ maxPoint = cpu1Temper[realIndex]; } }); temperatureHistoryOption.series[0].name = "CPU 1 Temp"; temperatureHistoryOption.series[0].data = cpu1Temper; } temperatureHistoryOption.xAxis[0].data = timeLabel; // temperatureHistoryOption.yAxis[0].min = parseFloat(minPoint)-parseFloat(1)>=0 ? Math.floor(parseFloat(minPoint)-parseFloat(1)) : Math.floor(minPoint); temperatureHistoryOption.yAxis[0].min = (minPoint / 1.5).toFixed(1); // temperatureHistoryOption.yAxis[0].max = Math.ceil(maxPoint); temperatureHistoryOption.yAxis[0].max = (maxPoint * 1.1).toFixed(1); temperatureHistoryOption.tooltip.formatter = "{b}<br/>{a0}: {c}℉"; setTimeout(function() { timeoutDrawTemperHistory("utilizationTemperatureHistory", temperatureHistoryOption); }, 300); } }, function(err) { console.log("Failed to send GetThermalHistory, error: "+err); deferred.reject(err); }); return deferred.promise; }; return service; }]) .factory('utGraphicPowerService', ['$resource', '$q', function($resource, $q) { var service = {}; service.restUtilPowerConsumption = function() { return $resource('/api/dataset/pwrmgmt', {params: '@params'}); }; var powerOption = { tooltip: { show: true, trigger: 'item', formatter: "{b}: {c}W", enterable: true, textStyle: { fontSize: 10 } }, legend: { orient : 'vertical', //x : 'right', x : 175, y: 'center', textStyle: { fontSize: 10 }, selectedMode: false, data:['CPU','MEM','Other','Spare'] }, series: [{ type:'pie', radius: ['50%', '80%'], center: ['30%', '50%'], itemStyle: { normal : { label : { show : true, formatter: "", position: 'center', textStyle: { fontSize: '12', color: '#333333' } }, labelLine : { show : false }, color: function(params) { var colorList = {"CPU": "#0096E7", "MEM": "#006DB9", "Other": "#44BFBC", "Spare": "#7DC7D9"}; return (colorList[params.series.data[params.dataIndex].name]); } } }, data: [] }] }; var greyPowerConsumChart = function(){ powerOption.series[0].data[0] = {}; powerOption.series[0].data[0].name = "CPU"; powerOption.series[0].data[0].value = 25; powerOption.series[0].data[1] = {}; powerOption.series[0].data[1].name = "MEM"; powerOption.series[0].data[1].value = 25; powerOption.series[0].data[2] = {}; powerOption.series[0].data[2].name = "Other"; powerOption.series[0].data[2].value = 25; powerOption.series[0].data[3] = {}; powerOption.series[0].data[3].name = "Spare"; powerOption.series[0].data[3].value = 25; powerOption.series[0].itemStyle.normal.color = "#DDDDDC"; powerOption.tooltip.formatter = 'N/A'; var currentUse = 'N/A'; powerOption.series[0].itemStyle.normal.label.formatter = currentUse; }; service.drawPowerConsumption = function() { var powerGreyChart = ""; service.restUtilPowerConsumption().get({params:"GetPowerRealtimeData"}, function(data) { // if(data.return != 0 && isNaN(data['items'][0]['cpu_power_dc'])){ if(data['items'] == undefined || isNaN(data['items'][0]['cpu_power_dc'])){ console.log("Failed to get data from /api/dataset/pwrmgmt GetPowerRealtimeData."); greyPowerConsumChart(); powerGreyChart = echarts.init(document.getElementById("utilizationPowerConsumption")); powerGreyChart.setOption(powerOption); }else{ var cpuPowerValue = parseFloat(data['items'][0]['cpu_power_dc']); var memPowerValue = parseFloat(data['items'][0]['mem_power_dc']); var sysPowerValue = parseFloat(data['items'][0]['sys_power_dc']); var powerAvaValue = parseFloat(data['items'][0]['power_available']); if(isNaN(cpuPowerValue) || isNaN(memPowerValue) || isNaN(sysPowerValue) || isNaN(powerAvaValue)){ console.log("Failed to get data from /api/dataset/pwrmgmt GetPowerRealtimeData."); greyPowerConsumChart(); powerGreyChart = echarts.init(document.getElementById("utilizationPowerConsumption")); powerGreyChart.setOption(powerOption); }else{ powerOption.series[0].data[0] = {}; powerOption.series[0].data[0].name = "CPU"; powerOption.series[0].data[0].value = cpuPowerValue; powerOption.series[0].data[1] = {}; powerOption.series[0].data[1].name = "MEM"; powerOption.series[0].data[1].value = memPowerValue; powerOption.series[0].data[2] = {}; powerOption.series[0].data[2].name = "Other"; powerOption.series[0].data[2].value = sysPowerValue - cpuPowerValue - memPowerValue; powerOption.series[0].data[3] = {}; powerOption.series[0].data[3].name = "Spare"; powerOption.series[0].data[3].value = powerAvaValue - sysPowerValue; var currentUse = sysPowerValue; powerOption.series[0].itemStyle.normal.label.formatter = currentUse + "W"; } var powerChart = echarts.init(document.getElementById("utilizationPowerConsumption")); powerChart.setOption(powerOption); } }, function(err) { console.log("Failed to get data from /api/dataset/pwrmgmt GetPowerRealtimeData, error: "+err); greyPowerConsumChart(); powerGreyChart = echarts.init(document.getElementById("utilizationPowerConsumption")); powerGreyChart.setOption(powerOption); }); }; var powerHistoryOption = { grid: { borderWidth: 0, x: 40, y: 25, height: 105, width: "93%" }, tooltip: { trigger: 'axis', textStyle: { fontSize: 10 }, axisPointer: { lineStyle: { color: 'rgba(204, 204, 204, 1)' } }, formatter: "{b}<br/>{a0}: {c0}W<br/>{a1}: {c1}W<br/>{a2}: {c2}W" }, /* legend: { x: 'right', textStyle: { fontSize: 12 }, selectedMode: false, data:['Max','Average','Min'] },*/ xAxis: [{ type: 'category', splitLine: { lineStyle: { color: 'rgba(204, 204, 204, 0.25)' } }, axisLine: { lineStyle : { color: 'rgba(204, 204, 204, 0.25)' } }, boundaryGap : false, data: [] }], yAxis: [{ type : 'value', splitLine: { lineStyle: { color: 'rgba(204, 204, 204, 0.25)' } }, axisLine: { lineStyle : { color: 'rgba(204, 204, 204, 0.25)' } } /*axisLine: { show: false }, axisLabel: { show: false }*/ }], series: [{ name: 'Max', type: 'line', smooth: true, symbol: 'emptyCircle', itemStyle: { normal: { color: '#006DB9', lineStyle: { width: 1 }, areaStyle: { type: 'default', color: 'rgba(0, 109, 185, 0.1)' } } }, /* markPoint : { data : [ {type : 'max', name: 'max'}, {type : 'min', name: 'min'} ] },*/ data: [] }, { name:'Average', type:'line', smooth:true, symbol: 'emptyCircle', itemStyle: { normal: { color: '#0097DE', lineStyle: { width: 1 }, areaStyle: { type: 'default', color: 'rgba(0, 151, 222, 0.3)' } } }, data:[] }, { name:'Min', type:'line', smooth:true, symbol: 'emptyCircle', itemStyle: { normal: { color: '#7DC7D9', lineStyle: { width: 1 }, areaStyle: { type: 'default', color: 'rgba(125, 199, 217, 0.5)' } } }, data:[] }] }; service.restPowerHistory = function() { return $resource('/api/dataset/pwrmgmt', {params: '@params'}); }; service.drawPowerHistory = function(domainItem, hourPeriod, dcFlag) { service.restPowerHistory().get({params:"GetPowerConsumptionHistory,"+domainItem+","+hourPeriod}, function(data){ if(data["items"] == undefined || isNaN(data["items"][0].avgDCValues[0])){ console.log("Failed to get power history data from GetPowerConsumptionHistory"); var maxValue = 100; var minValue = 0; powerHistoryOption.series[0].data = [0]; powerHistoryOption.series[1].data = [0]; powerHistoryOption.series[2].data = [0]; powerHistoryOption.xAxis[0].data = ["N/A"]; powerHistoryOption.tooltip.formatter = "N/A"; powerHistoryOption.yAxis[0].max = maxValue; powerHistoryOption.yAxis[0].min = minValue; var powerHistoryChart = echarts.init(document.getElementById("utilizationPowerHistory")); powerHistoryChart.setOption(powerHistoryOption); }else{ var tmpTimeLabel = data["items"][0].labels; var tmpMaxACValues = data["items"][0].maxACValues; var tmpMaxDCValues = data["items"][0].maxDCValues; var tmpAvgACValues = data["items"][0].avgACValues; var tmpAvgDCValues = data["items"][0].avgDCValues; var tmpMinACValues = data["items"][0].minACValues; var tmpMinDCValues = data["items"][0].minDCValues; var timeLabel = []; var maxDCValues = []; var avgDCValues = []; var minDCValues = []; var maxACValues = []; var avgACValues = []; var minACValues = []; var maxIndex = tmpTimeLabel.length; var realIndex = 0; var minPoint = 10000; var maxPoint = 0; if(dcFlag){ angular.forEach(tmpTimeLabel, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); timeLabel[realIndex] = item.timestamp; }); angular.forEach(tmpMaxDCValues, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); maxDCValues[realIndex] = item; if(maxDCValues[realIndex] < minPoint){ minPoint = maxDCValues[realIndex]; } if(maxDCValues[realIndex] > maxPoint){ maxPoint = maxDCValues[realIndex]; } }); angular.forEach(tmpAvgDCValues, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); avgDCValues[realIndex] = item; if(avgDCValues[realIndex] < minPoint){ minPoint = avgDCValues[realIndex]; } if(avgDCValues[realIndex] > maxPoint){ maxPoint = avgDCValues[realIndex]; } }); angular.forEach(tmpMinDCValues, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); minDCValues[realIndex] = item; if(minDCValues[realIndex] < minPoint){ minPoint = minDCValues[realIndex]; } if(minDCValues[realIndex] > maxPoint){ maxPoint = minDCValues[realIndex]; } }); powerHistoryOption.series[0].data = maxDCValues; powerHistoryOption.series[1].data = avgDCValues; powerHistoryOption.series[2].data = minDCValues; powerHistoryOption.xAxis[0].data = timeLabel; // powerHistoryOption.yAxis[0].min = parseFloat(minPoint)-parseFloat(1)>=0 ? Math.floor(parseFloat(minPoint)-parseFloat(1)) : Math.floor(minPoint); powerHistoryOption.yAxis[0].min = (minPoint / 1.5).toFixed(1); // powerHistoryOption.yAxis[0].max = Math.ceil(maxPoint); powerHistoryOption.yAxis[0].max = (maxPoint * 1.1).toFixed(1); powerHistoryOption.tooltip.formatter = "{b}<br/>{a0}: {c0}W<br/>{a1}: {c1}W<br/>{a2}: {c2}W"; var powerHistoryDcChart = echarts.init(document.getElementById("utilizationPowerHistory")); powerHistoryDcChart.setOption(powerHistoryOption); }else{ angular.forEach(tmpTimeLabel, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); timeLabel[realIndex] = item.timestamp; }); angular.forEach(tmpMaxACValues, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); maxACValues[realIndex] = item; if(maxACValues[realIndex] < minPoint){ minPoint = maxACValues[realIndex]; } if(maxACValues[realIndex] > maxPoint){ maxPoint = maxACValues[realIndex]; } }); angular.forEach(tmpAvgACValues, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); avgACValues[realIndex] = item; if(avgACValues[realIndex] < minPoint){ minPoint = avgACValues[realIndex]; } if(avgACValues[realIndex] > maxPoint){ maxPoint = avgACValues[realIndex]; } }); angular.forEach(tmpMinACValues, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); minACValues[realIndex] = item; if(minACValues[realIndex] < minPoint){ minPoint = minACValues[realIndex]; } if(minACValues[realIndex] > maxPoint){ maxPoint = minACValues[realIndex]; } }); powerHistoryOption.series[0].data = maxACValues; powerHistoryOption.series[1].data = avgACValues; powerHistoryOption.series[2].data = minACValues; powerHistoryOption.xAxis[0].data = timeLabel; // powerHistoryOption.yAxis[0].min = parseFloat(minPoint)-parseFloat(1)>=0 ? Math.floor(parseFloat(minPoint)-parseFloat(1)) : Math.floor(minPoint); powerHistoryOption.yAxis[0].min = (minPoint / 1.5).toFixed(1); // powerHistoryOption.yAxis[0].max = Math.ceil(maxPoint); powerHistoryOption.yAxis[0].max = (maxPoint * 1.1).toFixed(1); powerHistoryOption.tooltip.formatter = "{b}<br/>{a0}: {c0}W<br/>{a1}: {c1}W<br/>{a2}: {c2}W"; var powerHistoryAcChart = echarts.init(document.getElementById("utilizationPowerHistory")); powerHistoryAcChart.setOption(powerHistoryOption); } } }, function(err) { console.log("Failed to send GetPowerConsumptionHistory, error: "+err); }); }; var voltThresOption = { grid: { borderWidth: 0, x: 65, y: 0, height: 100 }, tooltip: { show: true, formatter: '{c} V', textStyle: { fontSize: 10 } }, xAxis: [{ show: true, type: 'category', axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false }, /* axisLabel: { textStyle: { fontSize: 10, family: 'Arial' } },*/ data: [] }], yAxis: [{ show: false, type: 'value', // scale: true, min:0, max:8 }], series: [{ name: 'critLow', type: 'bar', stack: 'sum', barWidth: 30, itemStyle: { normal: { color: '#FF6A00', label: { show: false } } }, markLine: { symbol: "arrow", symbolSize: [3, 0], data: [[]], itemStyle: { normal: { label: { show: true, formatter: "{c}V", textStyle: { color: "#0096E7", fontSize: 12, fontWeight: 700 } }, color: "#000" } } }, data: [] }, { name: 'normal', type: 'bar', stack: 'sum', barWidth: 30, itemStyle: { normal: { color: '#6ABF4A', label: { show: false } } }, data: [] }, { name: 'critUpper', type: 'bar', stack: 'sum', barWidth: 30, itemStyle: { normal: { color: '#FF6A00', label: { show: false } } }, data: [] }] }; service.restVolThresholds = function() { return $resource('/api/dataset/imm_props_environ'); }; var voltThresOptionArray = []; var voltThresCharts = []; var timeoutDrawComponentTemper = function(divName, option) { var dom = document.getElementById(divName); if(dom == undefined) { setTimeout(function() { timeoutDrawComponentTemper(divName, option); }, 300); return false; } var voltThresholdsChart = echarts.init(dom); voltThresholdsChart.setOption(option); }; service.drawVoltageThresholds = function() { var deferred = $q.defer(); var voltTop = 0; service.restVolThresholds().get(function(data) { if(data["items"][0].voltages != undefined){ angular.forEach(data["items"][0].voltages, function(item, index) { voltThresOptionArray[index] = {}; angular.copy(voltThresOption, voltThresOptionArray[index]); voltThresOptionArray[index].series[0].data[0] = {}; voltThresOptionArray[index].series[0].data[0].value = item["voltages.critical_lower_threshold"]; voltThresOptionArray[index].series[0].data[0].tooltip = {formatter: '< ' + item["voltages.critical_lower_threshold"] + 'V'}; voltThresOptionArray[index].series[1].data[0] = {}; voltThresOptionArray[index].series[2].data[0] = {}; if(item["voltages.noncritical_lower_threshold"] != "N/A"){ voltThresOptionArray[index].series[1].data[0].value = item["voltages.noncritical_lower_threshold"] - item["voltages.critical_lower_threshold"]; voltThresOptionArray[index].series[1].data[0].tooltip = {formatter: item["voltages.critical_lower_threshold"] + 'V ~ ' + item["voltages.noncritical_lower_threshold"] + 'V'}; voltThresOptionArray[index].series[1].itemStyle.normal.color = "#FFFF00"; voltTop = item["voltages.noncritical_lower_threshold"]-item["voltages.value"] > 0 ? parseFloat(item["noncritical_lower_threshold"])+parseFloat(2)-item["voltages.noncritical_lower_threshold"] : parseFloat(item["voltages.value"])+parseFloat(2)-item["voltages.noncritical_lower_threshold"]; voltThresOptionArray[index].series[2].data[0].value = voltTop; voltThresOptionArray[index].series[2].data[0].tooltip = {formatter: '> ' + item["voltages.noncritical_lower_threshold"] + 'V'}; voltThresOptionArray[index].series[2].itemStyle.normal.color = "#6ABF4A"; }else if(item["voltages.critical_upper_threshold"] != "N/A"){ voltThresOptionArray[index].series[1].data[0].value = item["voltages.critical_upper_threshold"] - item["voltages.critical_lower_threshold"]; voltThresOptionArray[index].series[1].data[0].tooltip = {formatter: item["voltages.critical_lower_threshold"] + 'V ~ ' + item["voltages.critical_upper_threshold"] + 'V'}; voltTop = item["voltages.critical_upper_threshold"]-item["voltages.value"] > 0 ? parseFloat(item["voltages.critical_upper_threshold"])+parseFloat(2)-item["voltages.critical_upper_threshold"] : parseFloat(item["voltages.value"])+parseFloat(2)-item["voltages.critical_upper_threshold"]; voltThresOptionArray[index].series[2].data[0].value = voltTop; voltThresOptionArray[index].series[2].data[0].tooltip = {formatter: '> ' + item["voltages.critical_upper_threshold"] + 'V'}; }else{ voltTop = item["voltages.value"]-item["voltages.critical_upper_threshold"] > 0 ? parseFloat(item["voltages.value"])+parseFloat(2) : parseFloat(item["voltages.critical_lower_threshold"])+parseFloat(2)-item["voltages.critical_lower_threshold"]; voltThresOptionArray[index].series[1].data[0].value = voltTop; voltThresOptionArray[index].series[1].data[0].tooltip = {formatter: '> ' + item["voltages.critical_lower_threshold"] + 'V'}; voltThresOptionArray[index].series[2].data[0].value = 0; } voltThresOptionArray[index].xAxis[0].data[0] = item["voltages.source"]; voltThresOptionArray[index].yAxis[0].max = parseFloat(voltThresOptionArray[index].series[0].data[0].value)+ parseFloat(voltThresOptionArray[index].series[1].data[0].value)+parseFloat(voltThresOptionArray[index].series[2].data[0].value); voltThresOptionArray[index].series[0].markLine.data[0][0] = {}; if(item["voltages.value"] != "Unavailable"){ voltThresOptionArray[index].series[0].markLine.data[0][0].value = " "+item["voltages.value"]; voltThresOptionArray[index].series[0].markLine.data[0][0].xAxis = 0.5; voltThresOptionArray[index].series[0].markLine.data[0][0].yAxis = item["voltages.value"]; voltThresOptionArray[index].series[0].markLine.data[0][1] = {}; voltThresOptionArray[index].series[0].markLine.data[0][1].xAxis = 1; voltThresOptionArray[index].series[0].markLine.data[0][1].yAxis = item["voltages.value"]; }else{ voltThresOptionArray[index].series[0].markLine.data[0][0].value = 0; voltThresOptionArray[index].series[0].markLine.itemStyle.normal.label.formatter = " Unavailable"; voltThresOptionArray[index].series[0].markLine.data[0][0].xAxis = 0.5; voltThresOptionArray[index].series[0].markLine.data[0][0].yAxis = 0; voltThresOptionArray[index].series[0].markLine.data[0][1] = {}; voltThresOptionArray[index].series[0].markLine.data[0][1].xAxis = 1; voltThresOptionArray[index].series[0].markLine.data[0][1].yAxis = 0; } voltThresCharts[index] = {"divName": "utilizationVolThresholds" + item["voltages.source"].split(" ").join("")}; setTimeout(function() { timeoutDrawComponentTemper(voltThresCharts[index].divName, voltThresOptionArray[index]); }, 300); }); }else{} deferred.resolve(voltThresCharts); }, function(err) { console.log("Failed to get the voltage data from /api/dataset/imm_props_environ, error: "+err); deferred.reject(err); }); return deferred.promise; }; return service; }]) .factory('utGraphicPerformanceService', ['$resource', function($resource){ var service = {}; service.restGetPerformance = function() { return $resource('/api/dataset/pwrmgmt', {params: '@params'}); }; service.graphicPerformancePresent = function(hours) { return $resource('www/data/:path/:history.json', { path: 'utilization.performance.graphic', history: hours }); }; var performanceBarOption = { grid: { borderWidth: 0, x: 40, y: 30, height: 120, width: "70%" }, tooltip: { show: false, formatter: "", textStyle: { fontSize: 10 } }, xAxis: [ { show: true, type: 'category', axisLine: { lineStyle : { color: '#F2F2F2' } }, splitLine: { show: false }, axisTick:{ show: false }, data: ['System','CPU','MEM','I/O'] } ], yAxis : [ { show: false, type : 'value' } ], series : [{ name: 'Performance', type: 'bar', stack: 'sum', barWidth: 10, itemStyle: { normal: { color: '#7DC7D9', label: { show: false, position: 'insideTop', formatter: "{c}%", textStyle: { color: '#333', fontSize: 10 } } } }, data: [] },{ name: 'Blank', type : 'bar', stack: 'sum', barWidth: 10, itemStyle: { normal: { color: '#F2F2F2', label: { show: true, position: 'insideBottom', formatter: function(params){ return (parseFloat(100)-parseFloat(params.value))+"%"; }, textStyle: { color: '#333', fontSize: 10 } } } }, data: [] }] }; var greyPerformanceBarChart = function(){ performanceBarOption.series[1].data[0] = {}; performanceBarOption.series[1].data[0].name = "System"; performanceBarOption.series[1].data[0].value = 100; performanceBarOption.series[1].data[1] = {}; performanceBarOption.series[1].data[1].name = "CPU"; performanceBarOption.series[1].data[1].value = 100; performanceBarOption.series[1].data[2] = {}; performanceBarOption.series[1].data[2].name = "MEM"; performanceBarOption.series[1].data[2].value = 100; performanceBarOption.series[1].data[3] = {}; performanceBarOption.series[1].data[3].name = "I/O"; performanceBarOption.series[1].data[3].value = 100; performanceBarOption.series[1].itemStyle.normal.color = "#DDDDDC"; performanceBarOption.tooltip.show = true; performanceBarOption.tooltip.formatter = "N/A"; }; service.drawPerformanceBarFunction = function(){ service.restGetPerformance().get({params:"GetPowerRealtimeData"}, function(data){ // if(data.return != 0 && isNaN(data['items'][0]['sys_pctg'])){ if(data['items'] == undefined || isNaN(data['items'][0]['sys_pctg'])){ console.log("Error to get performance data from /api/dataset/pwrmgmt get performance response null, error:"+data.return); greyPerformanceBarChart(); }else { var sysPerform = data['items'][0].sys_pctg; var cpuPerform = data['items'][0].cpu_pctg; var memPerform = data['items'][0].mem_pctg; var ioPerform = data['items'][0].io_pctg; if (isNaN(sysPerform) || isNaN(cpuPerform) || isNaN(memPerform) || isNaN(ioPerform)) { console.log("/api/dataset/pwrmgmt get performance response contains invalid."); greyPerformanceBarChart(); } else { performanceBarOption.series[0].data[0] = {}; performanceBarOption.series[0].data[0].name = "System"; performanceBarOption.series[0].data[0].value = sysPerform; performanceBarOption.series[1].data[0] = {}; performanceBarOption.series[1].data[0].name = "System"; performanceBarOption.series[1].data[0].value = 100 - performanceBarOption.series[0].data[0].value; performanceBarOption.series[0].data[1] = {}; performanceBarOption.series[0].data[1].name = "CPU"; performanceBarOption.series[0].data[1].value = cpuPerform; performanceBarOption.series[1].data[1] = {}; performanceBarOption.series[1].data[1].name = "CPU"; performanceBarOption.series[1].data[1].value = 100 - performanceBarOption.series[0].data[1].value; performanceBarOption.series[0].data[2] = {}; performanceBarOption.series[0].data[2].name = "MEM"; performanceBarOption.series[0].data[2].value = memPerform performanceBarOption.series[1].data[2] = {}; performanceBarOption.series[1].data[2].name = "MEM"; performanceBarOption.series[1].data[2].value = 100 - performanceBarOption.series[0].data[2].value; performanceBarOption.series[0].data[3] = {}; performanceBarOption.series[0].data[3].name = "I/O"; performanceBarOption.series[0].data[3].value = ioPerform; performanceBarOption.series[1].data[3] = {}; performanceBarOption.series[1].data[3].name = "I/O"; performanceBarOption.series[1].data[3].value = 100 - performanceBarOption.series[0].data[3].value; } } var performChart = echarts.init(document.getElementById("utGraphicPerformanceBar")); performChart.setOption(performanceBarOption); }, function(err) { console.log("Failed to get performance data from /api/dataset/pwrmgmt, error: "+err); greyPerformanceBarChart(); var performGreyChart = echarts.init(document.getElementById("utGraphicPerformanceBar")); performGreyChart.setOption(performanceBarOption); }); }; var performanceHistoryOptions = { grid: { borderWidth: 0, x: 40, y: 25, height: 105, width: "93%" }, tooltip: { trigger: 'axis', textStyle: { fontSize: 10 }, axisPointer: { lineStyle: { color: 'rgba(204, 204, 204, 1)' } }, formatter: "{b}<br/>{a0}: {c0}W<br/>{a1}: {c1}W<br/>{a2}: {c2}W" }, /* legend: { x: 'right', textStyle: { fontSize: 12 }, selectedMode: false, data:['CPU','Memory','I/O'] },*/ xAxis: [{ type: 'category', splitLine: { lineStyle: { color: 'rgba(204, 204, 204, 0.25)' } }, axisLine: { lineStyle : { color: 'rgba(204, 204, 204, 0.25)' } }, boundaryGap : false, data: [] }], yAxis: [{ type : 'value', splitLine: { lineStyle: { color: 'rgba(204, 204, 204, 0.25)' } }, axisLine: { lineStyle : { color: 'rgba(204, 204, 204, 0.25)' } } }], series: [{ name: 'CPU', type: 'line', smooth: true, symbol: 'emptyCircle', itemStyle: { normal: { color: '#006DB9', lineStyle: { width: 1 }, areaStyle: { type: 'default', color: 'rgba(0, 109, 185, 0.1)' } } }, /* markPoint : { data : [ {type : 'max', name: 'max'}, {type : 'min', name: 'min'} ] },*/ data: [] }, { name:'Memory', type:'line', smooth:true, symbol: 'emptyCircle', itemStyle: { normal: { color: '#0097DE', lineStyle: { width: 1 }, areaStyle: { type: 'default', color: 'rgba(0, 151, 222, 0.3)' } } }, data:[] }, { name:'I/O', type:'line', smooth:true, symbol: 'emptyCircle', itemStyle: { normal: { color: '#7DC7D9', lineStyle: { width: 1 }, areaStyle: { type: 'default', color: 'rgba(125, 199, 217, 0.5)' } } }, data:[] }] }; service.restPerformanceHistory = function() { return $resource('/api/dataset/pwrmgmt', {params: '@params'}); }; service.drawPerformanceHistoryFunction = function(hourPeriod) { console.log("GetPowerPerformanceHistory,"+hourPeriod); service.restPerformanceHistory().get({params:"GetPowerPerformanceHistory,"+hourPeriod}, function(data){ if(data["items"] == undefined || isNaN(data["items"][0].cpuValues[0])){ console.log("Failed to get performance history data from GetPowerPerformanceHistory"); var maxValue = 100; var minValue = 0; performanceHistoryOptions.series[0].data = [0]; performanceHistoryOptions.series[1].data = [0]; performanceHistoryOptions.series[2].data = [0]; performanceHistoryOptions.xAxis[0].data = ["N/A"]; performanceHistoryOptions.tooltip.formatter = "N/A"; performanceHistoryOptions.yAxis[0].max = maxValue; performanceHistoryOptions.yAxis[0].min = minValue; var performanceHistoryGreyChart = echarts.init(document.getElementById("utGraphicPerformanceHistory")); performanceHistoryGreyChart.setOption(performanceHistoryOptions); }else{ var tmpTimeLabel = data["items"][0].labels; var tmpCpuValues = data["items"][0].cpuValues; var tmpMemValues = data["items"][0].memValues; var tmpIoValues = data["items"][0].ioValues; var timeLabel = []; var cpuValues = []; var ioValues = []; var memValues = []; var maxIndex = tmpTimeLabel.length; var realIndex = 0; var minPoint = 10000; var maxPoint = 0; angular.forEach(tmpTimeLabel, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); timeLabel[realIndex] = item.timestamp; }); angular.forEach(tmpCpuValues, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); cpuValues[realIndex] = item; if(cpuValues[realIndex] < minPoint){ minPoint = cpuValues[realIndex]; } if(cpuValues[realIndex] > maxPoint){ maxPoint = cpuValues[realIndex]; } }); angular.forEach(tmpMemValues, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); memValues[realIndex] = item; if(memValues[realIndex] < minPoint){ minPoint = memValues[realIndex]; } if(memValues[realIndex] > maxPoint){ maxPoint = memValues[realIndex]; } }); angular.forEach(tmpIoValues, function(item, index) { realIndex = parseInt(maxIndex) - parseInt(1) - parseInt(index); ioValues[realIndex] = item; if(ioValues[realIndex] < minPoint){ minPoint = ioValues[realIndex]; } if(ioValues[realIndex] > maxPoint){ maxPoint = ioValues[realIndex]; } }); performanceHistoryOptions.series[0].data = cpuValues; performanceHistoryOptions.series[1].data = memValues; performanceHistoryOptions.series[2].data = ioValues; performanceHistoryOptions.xAxis[0].data = timeLabel; // performanceHistoryOptions.yAxis[0].min = Math.floor(minPoint); performanceHistoryOptions.yAxis[0].min = (minPoint / 1.5).toFixed(1); // performanceHistoryOptions.yAxis[0].max = Math.ceil(maxPoint); performanceHistoryOptions.yAxis[0].max = (maxPoint * 1.1).toFixed(1); performanceHistoryOptions.tooltip.formatter = "{b}<br/>{a0}: {c0}%<br/>{a1}: {c1}%<br/>{a2}: {c2}%"; var performanceHistoryDcChart = echarts.init(document.getElementById("utGraphicPerformanceHistory")); performanceHistoryDcChart.setOption(performanceHistoryOptions); } }, function(err) { console.log("Failed to send the GetPowerPerformanceHistory request, error: "+err); }); }; return service; }]) .factory('utGraphicFanSpeedService', ['$resource', '$q', function($resource, $q) { var service = {}; service.graphicGetFanList = function() { return $resource('/api/dataset/fan-list'); }; var fanSpeedOption = { tooltip : { formatter: "{c}%", textStyle: { fontSize: 10 } }, series : [{ type:'gauge', startAngle: 180, endAngle: 0, // min: 0, // max: 100, center: [], radius: [0, 36], axisLine: { lineStyle: { // color: [[0.03, '#F2F2F2'], [1, '#0C8CD1']], // color: [[0.03, '#990000'], [1, '#0C8CD1']], color: '#0C8CD1', width: 5 } }, axisTick: { show: false }, axisLabel: { show: false }, splitLine: { show: false }, pointer : { width : 3 }, detail : { show: true, formatter: '{value}%', offsetCenter: [0, "-10%"], textStyle: { fontWeight: 'bolder', color: '#333', fontSize : 12 } }, title : { show: true, offsetCenter: ['0', '-140%'], textStyle: { color: '#333', fontSize: 12 } }, data:[] }] }; var utFanOptionArray = []; var utFanCharArray = []; var timeoutDrawFan = function(divName, option){ var dom = document.getElementById(divName); if(dom == undefined) { setTimeout(function() { timeoutDrawFan(divName, option); }, 300); return false; } var utFanChart = echarts.init(dom); utFanChart.setOption(option); }; service.drawFanSpeedFunction = function() { var deferred = $q.defer(); service.graphicGetFanList().get(function(data) { angular.forEach(data["avct"], function(item, index) { utFanOptionArray[index] = {}; angular.copy(fanSpeedOption, utFanOptionArray[index]); utFanOptionArray[index].series[0].data[0] = {}; utFanOptionArray[index].series[0].data[0].name = item["source"]; utFanOptionArray[index].series[0].data[0].value = item["valuepct"]; utFanCharArray[index] = {"divName": item["source"]}; setTimeout(function() { timeoutDrawFan(utFanCharArray[index].divName, utFanOptionArray[index]); }, 300); }); deferred.resolve(utFanCharArray); }, function(err) { console.log("failed"); deferred.reject(err); }); return deferred.promise; }; return service; }]);<file_sep>'use strict'; angular.module('imm3.login.service', [ 'ngResource','ngStorage', 'pascalprecht.translate' ]) .factory('loginSysDetailInfoService', [ '$resource', function($resource) { var service = {}; service.restLoginSysDetailInfo = function() { return $resource('/api/providers/logoninfo'); }; service.restActiveEvents = function() { return $resource('/api/providers/imm_active_events'); }; return service; } ]) .factory('loginService', ['$http', '$localStorage','$resource', function($http, $localStorage,$resource){ var service = {}; service.restDoLogin = function() { return $resource('/api/login',{},{ 'save': { method: 'POST', headers: { 'Content-Type': 'application/json' } } }); }; service.restDoLogout = function() { return $resource('/api/logout'); }; service.restGetTire = function() { return $resource('/api/providers/imm_fod_tier'); }; return service; function changeUser(user) { angular.extend(currentUser, user); } function urlBase64Decode(str) { var output = str.replace('-', '+').replace('_', '/'); switch (output.length % 4) { case 0: break; case 2: output += '=='; break; case 3: output += '='; break; default: throw 'Illegal base64url string!'; } return window.atob(output); } function getUserFromToken() { var token = $localStorage.token; var user = {}; if (typeof token !== 'undefined') { var encoded = token.split('.')[1]; user = JSON.parse(urlBase64Decode(encoded)); } return user; } var currentUser = getUserFromToken(); return { save: function(data, success, error) { $http.post('/signin', data).success(success).error(error) }, signin: function(data, success, error) { $http.post('/api/login', data).success(success).error(error) }, me: function(success, error) { $http.get('/me').success(success).error(error) }, logout: function(success) { changeUser({}); delete $localStorage.token; success(); } }; } ]);<file_sep>'use strict'; angular.module('imm3.hw.general.info.directive', []) .directive('hwCpu', [function() { return { restrict: 'AE', scope: { hwTypeStr: '@', msgCount: '=', msgType: '=', hwSlotsCount: '=', hwSlotsInstall: '=', hwMsgList: '=' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/hardware-cpu-info-directive.html' }; }]) .directive('hwMemory', [function() { return { restrict: 'AE', scope: { hwTypeStr: '@', msgCount: '=', msgType: '=', hwSlotsCount: '=', hwSlotsInstall: '=', hwMsgList: '=' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/hardware-memory-info-directive.html' }; }]) .directive('hwStorage', [function() { return { restrict: 'AE', scope: { hwTypeStr: '@', msgCount: '=', msgType: '=', hwSlotsCount: '=', hwSlotsInstall: '=', hwMsgList: '=' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/hardware-storage-info-directive.html' }; }]) .directive('hwPci', [function() { return { restrict: 'AE', scope: { hwTypeStr: '@', msgCount: '=', msgType: '=', hwSlotsCount: '=', hwSlotsInstall: '=', hwMsgList: '=' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/hardware-pci-info-directive.html' }; }]) .directive('hwPowerSupply', [function() { return { restrict: 'AE', scope: { hwTypeStr: '@', msgCount: '=', msgType: '=', hwSlotsCount: '=', hwSlotsInstall: '=', hwMsgList: '=' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/hardware-power-supply-info-directive.html' }; }]) .directive('hwFan', [function() { return { restrict: 'AE', scope: { hwTypeStr: '@', msgCount: '=', msgType: '=', hwSlotsCount: '=', hwSlotsInstall: '=', hwMsgList: '=' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/hardware-fan-info-directive.html' }; }]) .directive('hwSystemBoard', [function() { return { restrict: 'AE', scope: { hwTypeStr: '@', msgCount: '=', msgType: '=', hwMsgList: '=' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/hardware-system-board-info-directive.html' }; }]) .directive('hwSystem', [function() { return { restrict: 'AE', scope: { hwTypeStr: '@', msgCount: '=', msgType: '=', hwMsgList: '=' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/hardware-system-info-directive.html' }; }]);<file_sep>'use strict'; /* * hwGeneralInfo.hwType: {0: Storage, 1: CPU, 2: FAN, 3: MEMORY, 4: PCI, 5: Power Supply, 6: System Board, 7: System} * hwGeneralInfo.msgType: {0: Normal, 1: Critical, 2: Warning} * * sysDetailInfo.power: {0: Slow, 1: On, 2: Fast, Other: unknown} * sysDetailInfo.location.ledState: {0: Off, 1: On, 2: Blink} * * */ angular.module('imm3.home.ctrl', [ 'ngRoute', 'ui.bootstrap', 'ui.uploader', 'ngAnimate', 'imm3.home.service', 'imm3.hw.general.info.directive', 'imm3.quick.action.directive', 'imm3.home.filter' ,'imm3.fmUpdate','imm3.login.service']) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/home', { templateUrl : 'www/views/home-view.html', controller : 'homeCtrl', reload:true }); } ]) .controller('homeCtrl', [ '$scope', '$rootScope','$window','$localStorage','$location','$uibModal', 'uiUploader', '$interval', '$http','homeMainService', 'homeHwInfoService', 'homeSysDetailInfoService', 'homeQuickActionService', 'homePowerAndTempService', 'dataSetService', 'homeUsbService', 'updateRestService','loginService', function($scope,$rootScope,$window,$localStorage,$location, $uibModal, uiUploader, $interval, $http, homeMainService, homeHwInfoService, homeSysDetailInfoService, homeQuickActionService, homePowerAndTempService, dataSetService, homeUsbService, updateRestService,loginService) { //get user tier console.log("tier aaaaaaaa"); $localStorage.tier = 1; loginService.restGetTire().get(function(data){ $rootScope.tier = data.tier; $localStorage.tier = data.tier; console.log("tier is:"+$localStorage.tier); }); $scope.hardwareGeneralInfo = {}; //workaround:perform home page refresh after login $rootScope.$watch('loginInfo.loginStatus',function(newVal, oldVal){ if(angular.isDefined($rootScope.loginInfo)){ if (newVal) { if(newVal == oldVal){ return; } $rootScope.loginInfo = angular.copy($localStorage.loginInfo); $window.location.reload(); } } }); $rootScope.loginInfo = angular.copy($localStorage.loginInfo); if(angular.isDefined($rootScope.loginInfo) && $rootScope.loginInfo.loginStatus ){ console.log("I am in home page"); }else{ $location.path("/login"); } $scope.sysDetailInfo = {}; $scope.sysDetailInfo.power = {}; $scope.sysDetailInfo.location = {}; $scope.sysDetailInfo.immVersion = {}; $scope.sysDetailInfo.uefiVersion = {}; /* Hardware Info Start */ //model structure for hardware health panel $scope.hardwareGeneralInfo = { "criticalCount": 0, "warningCount": 0, "cpu": { "msgWarningCount": 0, "msgCriticalCount": 0, "hwSlotsCount": 0, "hwSlotsInstall": 0, "msgType":0, "msgCount":0, "hwMsgList": [] }, "memory": { "msgWarningCount": 0, "msgCriticalCount": 0, "hwSlotsCount": 0, "hwSlotsInstall": 0, "msgType":0, "msgCount":0, "hwMsgList": [] }, "storage": { "msgWarningCount": 0, "msgCriticalCount": 0, "hwSlotsCount": 0, "hwSlotsInstall": 0, "msgType":0, "msgCount":0, "hwMsgList": [] }, "pci": { "msgWarningCount": 0, "msgCriticalCount": 0, "hwSlotsCount": 0, "hwSlotsInstall": 0, "msgType":0, "msgCount":0, "hwMsgList": [] }, "powerSupply": { "msgWarningCount": 0, "msgCriticalCount": 0, "hwSlotsCount": 0, "hwSlotsInstall": 0, "msgType":0, "msgCount":0, "hwMsgList": [] }, "fan": { "msgWarningCount": 0, "msgCriticalCount": 0, "hwSlotsCount": 0, "hwSlotsInstall": 0, "msgType":0, "msgCount":0, "hwMsgList": [] }, "systemBoard": { "msgWarningCount": 0, "msgCriticalCount": 0, "hwMsgList": [] }, "system": { "msgWarningCount": 0, "msgCriticalCount": 0, "hwMsgList": [] } }; $scope.hardwareGeneralInfo.map = true; var hwTypeArray = ["storage", "cpu", "fan", "memory", "pci", "powerSupply", "systemBoard", "system"]; //get and parse general sys inventory var restGeneralSysInventoryInfo = homeHwInfoService.restGeneralSysInventoryInfo(); var generalSysInventoryInfo = restGeneralSysInventoryInfo.get({params:"Sys_GetInvGeneral"},function(data) { $scope.parseInt = parseInt; angular.forEach(data['items'], function(item, index) { var type = angular.lowercase(item['type']); var install = (angular.equals(parseInt(item['install']) ,NaN))?0:parseInt(item['install']); var max = (angular.equals(parseInt(item['max']) ,NaN))?0:parseInt(item['max']); if(type=='ps'){ type='powerSupply'; } $scope.hardwareGeneralInfo[type].exist = true; $scope.hardwareGeneralInfo[type].hwSlotsInstall = install; $scope.hardwareGeneralInfo[type].hwSlotsCount = max; }); $scope.hardwareGeneralInfo['systemBoard'].exist = true; $scope.hardwareGeneralInfo['system'].exist = true; console.log(); }); $scope.chgMap = function() { $scope.hardwareGeneralInfo.map = !$scope.hardwareGeneralInfo.map; }; //basic event model structure $scope.getBasicEventItem = function (){ var item = { "type": 1, "hwName": "", "message": "", "evtId": "", "hwFru": "", "time": "" }; return item; } // get and parse active events info var restActiveEventsInfo = homeHwInfoService.restActiveEventsInfo(); var activeEventsInfo = restActiveEventsInfo.get(function(data) { //get raw data for active events tab $scope.activeEvents = data["items"]; //get and parse the event for pop-ups //hwGeneralInfo.msgType: {0: Normal, 1: Critical, 2: Warning} angular.forEach(data['items'], function(item, index) { var hwName = item['source']; //Cooling, Power, Disks, Processors,Memory, converting needed //Fan, power supply, Storage, CPU, Memory, [mother board & system] if(angular.lowercase(hwName) == 'cooling'){ hwName = 'fan'; }else if(angular.lowercase(hwName) == 'disks'){ hwName = 'storage'; }else if(angular.lowercase(hwName) == 'processors'){ hwName = 'cpu'; }else if(angular.lowercase(hwName) == 'memory'){ hwName = 'memory'; }else if(angular.lowercase(hwName) == 'power'){ hwName = 'powerSupply'; }else{//TODO, need to add more filters here once we got all the types, mother board, system, pci hwName = 'system'; } var evtId = item['eventid']; var time = item['date']; var message = item['message']; var typeMsg = item['severity']; var type= (typeMsg == 'E')?1:((typeMsg == 'W')?2:0) if(type == 1){ $scope.hardwareGeneralInfo[hwName].msgCriticalCount ++; }else if(type==2){ $scope.hardwareGeneralInfo[hwName].msgWarningCount ++; } var eventItem = $scope.getBasicEventItem(); eventItem.type = type; eventItem.hwName = hwName; eventItem.evtId = evtId; eventItem.time = time; eventItem.message = message; $scope.hardwareGeneralInfo[hwName]['hwMsgList'].push(eventItem); }); //get the total number of critical and warning events angular.forEach(hwTypeArray, function(item, index) { if($scope.hardwareGeneralInfo[item].msgCriticalCount !== 0){ $scope.hardwareGeneralInfo[item].msgType = 1; $scope.hardwareGeneralInfo[item].msgCount = $scope.hardwareGeneralInfo[item].msgCriticalCount; $scope.hardwareGeneralInfo.criticalCount += $scope.hardwareGeneralInfo[item].msgCriticalCount; }else if($scope.hardwareGeneralInfo[item].msgWarningCount !== 0){ $scope.hardwareGeneralInfo[item].msgType = 2; $scope.hardwareGeneralInfo[item].msgCount = $scope.hardwareGeneralInfo[item].msgWarningCount; $scope.hardwareGeneralInfo.warningCount += $scope.hardwareGeneralInfo[item].msgWarningCount; }else{ $scope.hardwareGeneralInfo[item].msgType = 0; } }); console.log("data\t"+JSON.stringify($scope.hardwareGeneralInfo)); }); $scope.chgMap = function() { $scope.hardwareGeneralInfo.map = !$scope.hardwareGeneralInfo.map; }; /* Hardware Info End */ /* System Detail Info Start */ $scope.sysDetailInfo.addMarginTop = false; $scope.sysDetailInfo.editSrvName = {}; $scope.sysDetailInfo.editSrvName.show = false; $scope.sysDetailInfo.location.editLocLed = false; $scope.isExportLicense = false; $scope.importNoFileSel = true; var importLicenseFile = ""; var restSysDetailInfo = homeSysDetailInfoService.restSysDetailInfo(); var restDataSet = dataSetService.restDataSet(); var sysDetailInfo = function(){ restSysDetailInfo.get(function(data) { console.log("*************"); console.log("machine_name:"+data["items"]["0"]["machine_name"]); console.log("*************"); var items = data["items"]["0"]; $scope.sysDetailInfo.firmwares = items["firmware"]; console.log("firmwares length:"+$scope.sysDetailInfo.firmwares.length); //console.log("fiemware is :"+JSON.stringify(firmware)); //console.log("firmware.index is :"+firmware["firmware.index"]); console.log("location is :"+items["location"]); $scope.sysDetailInfo.machine_name = items["machine_name"]; $scope.sysDetailInfo.system_name = items["system_name"]; $scope.sysDetailInfo.srvName = items["machine_name"]; //angular.extend($scope.sysDetailInfo.power, data["power"]); $scope.sysDetailInfo.power_state = items["power_state"]; $scope.sysDetailInfo.server_state = items["server_state"]; $scope.sysDetailInfo.machType = items["machine_typemodel"]; $scope.sysDetailInfo.serialNo = items["serial_number"]; //angular.extend($scope.sysDetailInfo.location, items["location"]); $scope.sysDetailInfo.location["location"] = items["location"]; //angular.extend($scope.sysDetailInfo.immVersion, firmware); //angular.extend($scope.sysDetailInfo.uefiVersion, firmware); //console.log("$scope.sysDetailInfo.uefiVersion:"+$scope.sysDetailInfo.uefiVersion); $scope.sysDetailInfo.immIpAddr = items["ipv4_address"]; $scope.sysDetailInfo.immHostName = items["hostname"]; //$scope.sysDetailInfo.license = data["license"]; }); } sysDetailInfo(); $scope.chgSrvName = function() { $scope.sysDetailInfo.editSrvName.srvName = $scope.sysDetailInfo.system_name; $scope.sysDetailInfo.editSrvName.show = true; return false; }; $scope.editSrvNameCancel = function() { $scope.sysDetailInfo.editSrvName.show = false; return false; }; $scope.editSrvNameOk = function() { restDataSet.save({},{"IMM_DescName":$scope.sysDetailInfo.editSrvName.srvName},function(data){ if(data["return"] !== 0){ $scope.$emit('showErrMsgBox', JSON.stringify(data)); return; } $scope.sysDetailInfo.system_name = $scope.sysDetailInfo.editSrvName.srvName; $scope.$emit('chgSrvNameSuc1', $scope.sysDetailInfo.system_name); $scope.$emit('showErrMsgBox', "Saved successfully!"); }, function(err) { $scope.$emit('showErrMsgBox', error); sysDetailInfo["srvName"] = $scope.sysDetailInfo.srvName; $scope.$emit('showErrMsgBox', "editSrvNameFailed"); }); $scope.sysDetailInfo.editSrvName.show = false; return false; }; //location led discarded $scope.chgLocLed = function() { $scope.sysDetailInfo.location.editLocLed = true; return false; }; $scope.saveLocLed = function(ledState) { sysDetailInfo["location"]["ledState"] = ledState; sysDetailInfo.$save(function(){ $scope.sysDetailInfo.location.ledState = sysDetailInfo["location"]["ledState"]; }, function(err) { sysDetailInfo["location"]["ledState"] = $scope.sysDetailInfo.location.ledState; $scope.$emit('showErrMsgBox', "editLocLedFailed"); }); $scope.sysDetailInfo.location.editLocLed = false; return false; }; //location led discarded due to design change $scope.updLicense = function() { $scope.isExportLicense = true; $scope.importNoFileSel = true; uiUploader.removeAll(); return false; }; $scope.exportLicense = function() { homeSysDetailInfoService.restDownloadLicenseOperation().startExport(function() { window.open("fod.fod"); }, function(err) { $scope.$emit('showErrMsgBox', "exportLicenseFailed"); }); return false; }; $scope.clkImportLicenseCancel = function() { $scope.isExportLicense = false; $scope.importNoFileSel = true; uiUploader.removeAll(); return false; }; $scope.clkImportLicenseUpgrade = function() { if($scope.importNoFileSel) { return false; } var thisFile = uiUploader.getFiles()[0]; updateRestService.restWebRequestSpaceURI().save({"UPD_WebReserve":1},function(data){ if(data.return!=0){ $scope.$emit('showErrMsgBox', "error:"+data.return); }else{ $http({ method: 'POST', url: '/upload?X-Progress-ID='+updateRestService.randomNum, headers: { 'Content-Type': undefined }, transformRequest: function() { var formData = new FormData(); formData.append(thisFile.name, thisFile); return formData; } }).success(function(data){ console.log("get path success"); var path = data['items'][0].path; homeSysDetailInfoService.restUploadFod().save({},{"FOD_LicenseKeyInstall": path}, function(data){ if(data.return != 0){ $scope.$emit('showErrMsgBox', "error:"+data.return); }else{ $scope.$emit('showErrMsgBox', "Upload successfully!"); } }), function(err){ $scope.$emit('showErrMsgBox', JSON.stringify(err)); }; }).error(function(err){ $scope.$emit('showErrMsgBox', JSON.stringify(err)); }); } }); console.log(uiUploader.getFiles().length); $scope.isExportLicense = false; return false; }; var bindImportSelFileChg = function() { var element = document.getElementById('btnImportLicenseSel'); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); importLicenseFile = uiUploader.getFiles()[0]; $scope.importLicenseFileName = importLicenseFile.name; $scope.importNoFileSel = false; $scope.$apply(); }); element = null; }; /* front panel usb ownership on home page start 0118*/ var restPFUsb = homeUsbService.restPFUsb(); $scope.sysDetailInfo.editUSBOwnership = {}; $scope.sysDetailInfo.editUSBOwnership.show = false; restPFUsb.get(function(data){ var owner = data.owner; if(owner == 0){ $scope.sysDetailInfo.editUSBOwnership.value = "HOST only"; }else if(owner == 1){ $scope.sysDetailInfo.editUSBOwnership.value = "BMC only"; }else if(owner == 2){ $scope.sysDetailInfo.editUSBOwnership.value = "Shared mode: owned by HOST"; }else if(owner == 3){ $scope.sysDetailInfo.editUSBOwnership.value = "Shared mode: owned by BMC"; } $scope.sysDetailInfo.usbOwnershipOptions.currentValue = $scope.sysDetailInfo.editUSBOwnership.value; }); $scope.chgUSBOwnership = function() { $scope.sysDetailInfo.editUSBOwnership.show = true; return false; }; $scope.editOwnerShipOk = function() { var curVal = $scope.sysDetailInfo.usbOwnershipOptions.currentValue; var owner = ""; if(curVal == "HOST Only"){ owner = 0; }else if(curVal == "BMC Only"){ owner = 1; }else if(curVal == "Shared mode: owned by HOST"){ owner = 2; }else if(curVal == "Shared mode: owned by BMC"){ owner = 3; } restPFUsb.save({},{"Set_FPUSB_Owner": owner},function(data){ if(data.return == 0){ console.log("set usb successfully!"); $scope.sysDetailInfo.editUSBOwnership.value = $scope.sysDetailInfo.usbOwnershipOptions.currentValue; $scope.sysDetailInfo.editUSBOwnership.show = false; $scope.$emit('showErrMsgBox', "Saved successfully!"); }else{ $scope.$emit('showErrMsgBox', JSON.stringify(data)); } }, function(error){ $scope.$emit('showErrMsgBox', error); }); return false; }; $scope.editUSBOwnershipCancel = function() { $scope.sysDetailInfo.usbOwnershipOptions.currentValue = $scope.sysDetailInfo.editUSBOwnership.value; $scope.sysDetailInfo.editUSBOwnership.show = false; return false; }; $scope.sysDetailInfo.usbOwnershipOptions = {}; $scope.sysDetailInfo.usbOwnershipOptions.map = { "Shared mode: owned by BMC":"Shared mode: owned by BMC", "Shared mode: owned by HOST":"Shared mode: owned by HOST", "HOST Only":"HOST Only", "BMC Only":"BMC Only" }; $scope.ownsership_change = function(){ $scope.sysDetailInfo.editUSBOwnership.value = $scope.sysDetailInfo.usbOwnershipOptions.currentValue; } /* front panel usb ownership on home page start */ /* System Detail Info End */ /* Quick Action Start */ $scope.showConfirmDownloadFfdc = false; $scope.isDownloadFfdc = false; $scope.ffdcProgress = 0; var downloadFfdcProgressInterval = 0; var restDownloadFfdcOperation = homeQuickActionService.restDownloadFfdcOperation(); var restPowerActionList = homeQuickActionService.restPowerActionList(); //common method to retrieve power action list var getPowStatusAndParse = function (){ restPowerActionList = homeQuickActionService.restPowerActionList(); // this will enable all the power items except power on and power off var basePowCode = 508; restPowerActionList.get(function(data) { //power_state 1:on, 0 off, 2 sleeping var power_state = data['items'][0]['power_state']; if(power_state == '0'){// currently off, disable power off option(1) basePowCode += 2; }else if(power_state == '1'){// currently on, disable power off option(2) basePowCode += 1; } $scope.powerActionOperList = basePowCode.toString(2).split("").reverse().join("") + "000000000"; }, function(err) { console.log('base power code in error0\t' + basePowCode); console.log("error happened\t"+JSON.stringify(err)); console.log("Something went wrong, disable power off first"); basePowCode += 2; $scope.powerActionOperList = basePowCode.toString(2).split("").reverse().join("") + "000000000"; }); }; //retrieved power status upon page load getPowStatusAndParse(); $scope.callAtInterval = function() { //retrieve power status by interval if(angular.isDefined($localStorage.loginInfo) && angular.isDefined($localStorage.loginInfo.token) && $localStorage.loginInfo.loginStatus && $location.url() == "/home"){ getPowStatusAndParse(); } if($scope.powerActionOperList[0]=='1'){ $("#alreadyOffPopover").unbind(); }else{ $("#alreadyOffPopover").popover({content: "Server is already off !",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); } if($scope.powerActionOperList[1]=='1'){ $("#alreadyOnPopover").unbind(); }else{ $("#alreadyOnPopover").popover({content: "Server is already on !",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); } } $interval( function(){ $scope.callAtInterval(); }, 5000); $scope.powBaseData = { "count": 2, "powMsgInfo": [ { "id":1, "succMsg":"Server has been powered off successfully.", "failMsg": "Failed to power off server.", "reqBody": [ { "powerAction": 1 } ] }, { "id":2, "succMsg":"Server has been powered on successfully.", "failMsg": "Failed to power on server.", "reqBody": [ { "powerAction": 0 } ] },{ "id":3, "succMsg":"Shutdown OS and then Power off request has been handled successfully.", "failMsg": "Failed to handle Shutdown OS and then Power off request.", "reqBody": [ { "powerAction": 4 } ] },{ "id":4, "succMsg":"Shut down OS and then Restart Request has been handled successfully.", "failMsg": "Failed to handle Shut down OS and then Restart request.", "reqBody": [ { "powerAction": 8 } ] }, { "id":5, "succMsg":"Restart server Request has been handled successfully.", "failMsg": "Failed to handle Restart server request", "reqBody": [ { "powerAction": 16 } ] }, { "id":6, "succMsg":"Boot to F1 request has been handled successfully.", "failMsg": "Failed to handle Boot to F1 request.", "reqBody": [ { "powerAction": 32 } ] }, { "id":7, "succMsg":"Schedule Power Action Request has been handled successfully.", "failMsg": "Failed to handle Schedule Power Action request.", "reqBody": [ { "powerAction": 64 } ] }, { "id":8, "succMsg":"Restart IMM Request has been handled successfully.", "failMsg": "Failed to handle Restart IMM request.", "reqBody": [ { "powerAction": 128 } ] }, { "id":9, "succMsg":"Trigger IMM request has been handled successfully.", "failMsg": "Failed to handle Trigger IMM request.", "reqBody": [ { "powerAction": 256 } ] }, { "id":10, "succMsg":"Reset IMM request has been handled successfully.", "failMsg": "Failed to handle Reset IMM request.", "reqBody": [ { "IMMColdReset":1 } ] } ] }; $scope.downloadFFDC = function() { $scope.showConfirmDownloadFfdc = true; return false; }; var chkDownloadFfdcProgressFailedTimes = 0; $scope.ffdcProgress = 10; var chkDownloadFfdcProgress = function() { homeQuickActionService.getCurDownloadFfdcProgress().then(function(data) { var status = data['status']; chkDownloadFfdcProgressFailedTimes = 0; if(status == '1') { clearInterval(downloadFfdcProgressInterval); $scope.isDownloadFfdc = false; window.open("ffdc/"+data['FileName']); }else if(status =='2' && $scope.ffdcProgress < 90){ console.log("getting status2 progress\t"+$scope.ffdcProgress); $scope.ffdcProgress = $scope.ffdcProgress + 5; } }, function(err) { if(chkDownloadFfdcProgressFailedTimes < 3) { ++chkDownloadFfdcProgressFailedTimes; } else { clearInterval(downloadFfdcProgressInterval); $scope.$emit('showErrMsgBox', "downloadFfdcFailed"); } }); }; $scope.clkConfirmDownloadFfdcOk = function() { $scope.showConfirmDownloadFfdc = false; restDownloadFfdcOperation.generateFFDC({"Generate_FFDC":1},function() { chkDownloadFfdcProgressFailedTimes = 0; downloadFfdcProgressInterval = setInterval(chkDownloadFfdcProgress, 5000); $scope.isDownloadFfdc = true; }, function(err) { $scope.$emit('showErrMsgBox', "downloadFfdcFailed"); }); return false; }; $scope.clkConfirmDownloadFfdcCancel = function() { $scope.showConfirmDownloadFfdc = false; return false; }; $scope.cancelDownloadFfdc = function() { $scope.isDownloadFfdc = false; restDownloadFfdcOperation.stopDownload(function() { //Nothing to do }, function(err) { //Nothing to do console.log("Failed to stop download FFDC"); }); return false; }; $scope.restartIMM = function(size) { $uibModal.open({ animation: true, templateUrl: 'www/views/home-restart-imm.html', controller: 'homeRestartImmCtrl', size: size }); return false; }; /*schedule power action start */ $scope.baseData = {}; $scope.baseData.daysOfWeek ={}; $scope.baseData.daysOfWeek.map = { "Monday":"Monday", "Tuesday":"Tuesday", "Wednesday":"Wednesday", "Thursday":"Thursday", "Friday":"Friday", "Saturday":"Saturday", "Sunday":"Sunday" }; var getDayOfWeekByID = function(id){ switch(id) { case 1: return "Monday" break; case 2: return "Tuesday" break; case 3: return "Wednesday" break; case 4: return "Thursday" break; case 5: return "Friday" break; case 6: return "Saturday" break; case 7: return "Sunday" break; default: return "" } } //init the date and time picker in the schedule power action popup window //Daily and Weekly power actions $("#shutdownOSAndPowOffSrvDateContainer").datepicker({ autoclose: true, 'default': 'now' }); $("#shutdownOSAndPowOffSrvClockPicker").clockpicker({ placement: 'left', autoclose :true, align: 'left', donetext: 'Done', 'default': 'now', afterDone: function() { $scope.schedulePowActionData['items'][0]['powerActions'][0].timeOfDay = $("#shutdownOSAndPowOffSrvTime").val(); } }); $("#powOnSrvClockPicker").clockpicker({ placement: 'left', autoclose :true, align: 'left', donetext: 'Done', 'default': 'now', afterDone: function() { $scope.schedulePowActionData['items'][0]['powerActions'][1].timeOfDay = $("#powOnSrvTime").val(); } }); $("#shutdownOSAndRestartSrvClockPicker").clockpicker({ placement: 'left', autoclose :true, align: 'left', donetext: 'Done', 'default': 'now', afterDone: function() { $scope.schedulePowActionData['items'][0]['powerActions'][2].timeOfDay = $("#shutdownOSAndRestartSrvTime").val(); } }); //one time schedule power actions $("#onetimeShutdownOSAndPowOffSrvDateContainer").datepicker({ autoclose: true, 'default': 'now' }); $("#onetimeShutdownOSAndPowOffSrvClockPicker").clockpicker({ placement: 'left', autoclose :true, align: 'left', donetext: 'Done', 'default': 'now' }); $("#onetimePowOnSrvDateContainer").datepicker({ autoclose: true, 'default': 'now' }); $("#onetimePowOnSrvClockPicker").clockpicker({ placement: 'left', autoclose :true, align: 'left', donetext: 'Done', 'default': 'now' }); $("#onetimeShutdownOSAndRestartSrvDateContainer").datepicker({ autoclose: true, 'default': 'now' }); $("#onetimeShutdownOSAndRestartSrvClockPicker").clockpicker({ placement: 'left', autoclose :true, align: 'left', donetext: 'Done', 'default': 'now' }); //Model data for schedule power action popup window, //will be automatically updated when launching the schedule power action window $scope.schedulePowActionData = { "items": [ { "type": "dailyWeeklyPowerAction", "powerActions": [ { "id": "1", "enabled":false, "action": "Shut down OS and power off server", "powerCode": "4", "interval": "Weekly", "startDate": "", "dayOfWeek": "", "timeOfDay": "" }, { "id": "2", "enabled":false, "action": "Power on server", "powerCode": "2", "interval": "Weekly", "startDate": "", "dayOfWeek": "", "timeOfDay": "" }, { "id": "3", "enabled":false, "action": "Shut down OS and restart server", "powerCode": "8", "interval": "Weekly", "startDate": "", "dayOfWeek": "", "timeOfDay": "" } ] }, { "type": "oneTimePowerAction", "powerActions": [ { "id": "4", "enabled":false, "action": "Shut down OS and power off server", "powerCode": "4", "interval": "", "startDate": "", "dayOfWeek": "", "timeOfDay": "" }, { "id": "5", "enabled":false, "action": "Power on server", "powerCode": "2", "interval": "", "startDate": "", "dayOfWeek": "", "timeOfDay": "" }, { "id": "6", "enabled":false, "action": "Shut down OS and restart server", "powerCode": "8", "interval": "", "startDate": "", "dayOfWeek": "", "timeOfDay": "" } ] } ] }; $scope.itemChecked= function(gid,iid){ } $scope.toggleInterval = function(gid,iid){ console.log(gid+" "+iid + " "+$scope.schedulePowActionData['items'][gid]['powerActions'][iid].interval); if($scope.schedulePowActionData['items'][gid]['powerActions'][iid].interval == 'Weekly'){ $scope.schedulePowActionData['items'][gid]['powerActions'][iid].interval = 'Daily'; }else{ $scope.schedulePowActionData['items'][gid]['powerActions'][iid].interval = 'Weekly'; } } var restSchedulePowerActionList = homeQuickActionService.restSchedulePowerActionList(); //update model data for schedule power action popup window, always fetch latest power status first var parserPowerState = function (){ // retrieve data from server first /* this is fake data var restData = { "items" : [ { "datetime_current" : "2015-06-21T10:50:05.121", "power_state" : 1, "S3Enable_state" : 0, "power_on_datetime_enabled" : 0, "power_on_datetime" : "0-00-00T00:00", //"power_off_enabled" : 0, //"power_off_interval" : 0, //"power_off_dow" : 1, //"power_off_time" : "00:00", "power_off_enabled" : 1, "power_off_interval" : 1, "power_off_dow" : 4, "power_off_time" : "1:00", "power_on_enabled" : 1, "power_on_interval" : 0,//daily "power_on_dow" : 1, "power_on_time" : "2:00", "restart_enabled" : 1, "restart_interval" : 1,//weekly "restart_dow" : 7, "restart_time" : "3:00" } ] }; */ restSchedulePowerActionList.get(function(restData) { //transform data //power on server console.log("restData111\t"+JSON.stringify(restData)); if(restData['items'][0].power_on_enabled ==1){ //schedule power on enabled $scope.schedulePowActionData['items'][0]['powerActions'][1].enabled = true; if(restData['items'][0].power_on_interval == 0){//daily $scope.schedulePowActionData['items'][0]['powerActions'][1].interval ="Daily"; }else{ //weekly $scope.schedulePowActionData['items'][0]['powerActions'][1].interval ="Weekly"; $scope.schedulePowActionData['items'][0]['powerActions'][1].dayOfWeek =getDayOfWeekByID(restData['items'][0].power_on_dow); } $scope.schedulePowActionData['items'][0]['powerActions'][1].timeOfDay = restData['items'][0].power_on_time; } //restart on server if(restData['items'][0].restart_enabled ==1){ //schedule power on enabled $scope.schedulePowActionData['items'][0]['powerActions'][2].enabled = true; if(restData['items'][0].restart_interval == 0){//daily $scope.schedulePowActionData['items'][0]['powerActions'][2].interval ="Daily"; }else{ //weekly $scope.schedulePowActionData['items'][0]['powerActions'][2].interval ="Weekly"; $scope.schedulePowActionData['items'][0]['powerActions'][2].dayOfWeek =getDayOfWeekByID(restData['items'][0].restart_dow); } $scope.schedulePowActionData['items'][0]['powerActions'][2].timeOfDay = restData['items'][0].restart_time; } //power off server if(restData['items'][0].power_off_enabled ==1){ //schedule power on enabled $scope.schedulePowActionData['items'][0]['powerActions'][0].enabled = true; if(restData['items'][0].power_off_interval == 0){//daily $scope.schedulePowActionData['items'][0]['powerActions'][0].interval ="Daily"; }else{ //weekly $scope.schedulePowActionData['items'][0]['powerActions'][0].interval ="Weekly"; $scope.schedulePowActionData['items'][0]['powerActions'][0].dayOfWeek =getDayOfWeekByID(restData['items'][0].power_off_dow); } $scope.schedulePowActionData['items'][0]['powerActions'][0].timeOfDay = restData['items'][0].power_off_time; } }, function(err) { console.log("Something went wrong when retrieving power status"); }); } //Generate request payload according to user input(all updated to model) $scope.schedulePowPayload = {}; $scope.genSchedulePowActionReuqestBody = function (){ $scope.parseInt = parseInt; var dayInAWeek = ['','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']; //var emptyRestData = {"items" : []}; var emptyRestData = { "SRVR_PwrOffEna": "0", "SRVR_PwrOffInt": "0", "SRVR_PwrOffDow": "1", "SRVR_PwrOffTime": "0:0", "SRVR_PwrOnEna": "0", "SRVR_PwrOnInt": "0", "SRVR_PwrOnDow": "1", "SRVR_PwrOnTime": "0:0", "SRVR_RestartEna": "0", "SRVR_RestartInt": "0", "SRVR_RestartDow": "0", "SRVR_RestartTime": "0:0" }; restSchedulePowerActionList.get(function(restData) { //power off server if($scope.schedulePowActionData['items'][0]['powerActions'][0].enabled){ //schedule power on enabled emptyRestData.SRVR_PwrOffEna = "1"; if($scope.schedulePowActionData['items'][0]['powerActions'][0].interval == "Daily"){//daily emptyRestData.SRVR_PwrOffInt = "0"; emptyRestData.SRVR_PwrOffDow = "1"; }else{ //weekly emptyRestData.SRVR_PwrOffInt = "1"; emptyRestData.SRVR_PwrOffDow = "" + dayInAWeek.indexOf($scope.schedulePowActionData['items'][0]['powerActions'][0].dayOfWeek); } emptyRestData.SRVR_PwrOffTime = $scope.schedulePowActionData['items'][0]['powerActions'][0].timeOfDay; } //power on server if($scope.schedulePowActionData['items'][0]['powerActions'][1].enabled){ //schedule power on enabled emptyRestData.SRVR_PwrOnEna = "1"; if($scope.schedulePowActionData['items'][0]['powerActions'][1].interval == "Daily"){//daily emptyRestData.SRVR_PwrOnInt = "0"; emptyRestData.SRVR_PwrOnDow = "1"; }else{ //weekly emptyRestData.SRVR_PwrOnInt = "1"; emptyRestData.SRVR_PwrOnDow = "" + dayInAWeek.indexOf($scope.schedulePowActionData['items'][1]['powerActions'][1].dayOfWeek); } emptyRestData.SRVR_PwrOnTime = $scope.schedulePowActionData['items'][0]['powerActions'][1].timeOfDay; } //restart server if($scope.schedulePowActionData['items'][0]['powerActions'][2].enabled){ //schedule power on enabled emptyRestData.SRVR_RestartEna = "1"; if($scope.schedulePowActionData['items'][0]['powerActions'][2].interval == "Daily"){//daily emptyRestData.SRVR_RestartInt = "0"; emptyRestData.SRVR_RestartDow = "1"; }else{ //weekly emptyRestData.SRVR_RestartInt = "1"; emptyRestData.SRVR_RestartDow = "" + dayInAWeek.indexOf($scope.schedulePowActionData['items'][0]['powerActions'][2].dayOfWeek); } emptyRestData.SRVR_RestartTime = $scope.schedulePowActionData['items'][0]['powerActions'][2].timeOfDay; } $scope.schedulePowPayload = angular.copy(emptyRestData); }, function(err) { console.log("Something went wrong when retrieving power status"); $scope.schedulePowPayload = angular.copy(emptyRestData); }); } var launchSchedulePowerAction = function(){ parserPowerState(); $("#launchSchedulePowerAction").modal(); } $scope.cfmSchedulePoweraction = function (){ $scope.genSchedulePowActionReuqestBody(); console.log("schedulePowPayload \t"+JSON.stringify($scope.schedulePowPayload)); var restSchedulePowerAction = homeQuickActionService.restSchedulePowerAction(); restSchedulePowerAction.save($scope.schedulePowPayload,function(){ //console.log('The power request has been handled properly.\n'+$scope.powBaseData['powMsgInfo'][6].succMsg); //$scope.$emit('chgSrvNameSuc1', $scope.powBaseData['powMsgInfo'][6].succMsg); $scope.$emit('showErrMsgBox', $scope.powBaseData['powMsgInfo'][6].succMsg); }, function(err) { console.log('post request failed due to the following reason\t\n'+JSON.stringify(err));//+response.message); $scope.$emit('showErrMsgBox', $scope.powBaseData['powMsgInfo'][6].failMsg); //$scope.$emit('showErrMsgBox', err.statusText); }); } $scope.showConfirmPowerActions = false; $scope.cfmPowerActionSuffix = ""; $scope.powerActionSel = function(powerAction) { var state = $scope.powerActionOperList[Math.log(powerAction)/Math.log(2)]; if(powerAction == '512'){//handle reset IMM separately $scope.cfmPowerActionSuffix = powerAction; $scope.showConfirmPowerActions = true; }else if(state == '1' && powerAction != '64'){//handle other power actions except schedule power action $scope.cfmPowerActionSuffix = powerAction; $scope.showConfirmPowerActions = true; }else if(powerAction == '64'){//handle schedule power action //schedule power action launchSchedulePowerAction(); } return false; }; $scope.clkConfirmPowerActionOk = function(powerAction) { console.log("power action code\t"+powerAction); $scope.showConfirmPowerActions = false; var restPowerAction = homeQuickActionService.restPowerAction(); var restResetIMM = homeQuickActionService.restResetIMM(); if(powerAction == '512'){//reset imm restResetIMM.save($scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)]['reqBody'][0],function(data){ if(data["return"] == 0){ sysDetailInfo(); $scope.$emit('showErrMsgBox', $scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)].succMsg); }else if(data["return"] == 506){ $scope.$emit('showErrMsgBox', data['error']+' !\t'+data['description']); }else{ $scope.$emit('showErrMsgBox', $scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)].failMsg); } }, function(err) { console.log('post request failed due to the following reason\t\n'+JSON.stringify(err));//+response.message); $scope.$emit('showErrMsgBox', $scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)].failMsg); }); }else{//other power action except schedule power action restPowerAction.save($scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)]['reqBody'][0],function(data){ //console.log('The power request has been handled properly.\n'+$scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)].succMsg); //$scope.$emit('chgSrvNameSuc1', $scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)].succMsg); if(data["return"] == 0){ sysDetailInfo(); $scope.$emit('showErrMsgBox', $scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)].succMsg); }else if(data["return"] == 506){ $scope.$emit('showErrMsgBox', data['error']+' !\t'+data['description']); }else{ $scope.$emit('showErrMsgBox', $scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)].failMsg); } }, function(err) { console.log('post request failed due to the following reason\t\n'+JSON.stringify(err));//+response.message); $scope.$emit('showErrMsgBox', $scope.powBaseData['powMsgInfo'][Math.log(powerAction)/Math.log(2)].failMsg); }); } return false; }; $scope.clkConfirmPowerActionCancel = function() { $scope.showConfirmPowerActions = false; return false; }; /*schedule power action end */ /* location led start */ $scope.locationStatus="On"; var restLocaltionLed = homeQuickActionService.restLocaltionLed(); var getLocationLedStatus = function (){ restLocaltionLed.get(function(ledData) { if(ledData.status == '1'){ $scope.locationStatus="Off"; }else if(ledData.status == '2'){ $scope.locationStatus="On"; } else{ $scope.locationStatus="Blink"; } }, function(err) { console.log("something went wrong when retrieving led status"); }); }; getLocationLedStatus(); $scope.getLedStsAtInterval = function() { //retrieve led status status by interval if(angular.isDefined($localStorage.loginInfo) && angular.isDefined($localStorage.loginInfo.token) && $localStorage.loginInfo.loginStatus && $location.url()=="/home"){ getLocationLedStatus(); } } $interval( function(){ $scope.getLedStsAtInterval(); }, 10000); $scope.locLEDActionSel = function(locLEDAction) { restLocaltionLed.save({"led_status":locLEDAction},function(data){ if(data["return"] == 0){ $scope.$emit('showErrMsgBox', 'Location LED staus has been changed successfully.'); }else if(data["return"] == 506){ $scope.$emit('showErrMsgBox', data['error']+' !\t'+data['description']); }else{ $scope.$emit('showErrMsgBox', 'Failed to change location LED status'); } }, function(err) { //console.log('failed to save location led status');//+response.message); $scope.$emit('showErrMsgBox', 'Failed to change location LED status'); }); getLocationLedStatus(); //remove the following if/else block once /*if(locLEDAction == '2'){ $scope.locationStatus="On"; }else if(locLEDAction == '1'){ $scope.locationStatus="Off"; }else if(locLEDAction == '3'){ $scope.locationStatus="Blank"; } */ return false; }; /* location led end */ /* Quick Action End */ /* Consumption Start */ var drawPowerConsumption = function() { homePowerAndTempService.drawPowerConsumption(); }; //show the temperature of CPU with highest temperature var drawTempConsumption = function() { homePowerAndTempService.drawTempConsumption(); }; //show the speed of FAN with highest speed var drawFanSpeed = function() { homePowerAndTempService.drawFanSpeed(); }; $scope.hwPowerTempRefresh = function() { drawPowerConsumption(); drawTempConsumption(); drawFanSpeed(); }; $scope.viewDetail = function (){ $location.path("/utilization"); } /* Consumption End */ var resizeDiv = function() { switch(homeMainService.resizeDiv()) { case 0: $scope.sysDetailInfo.addMarginTop = false; break; case 1: $scope.sysDetailInfo.addMarginTop = true; break; default: console.log("not in home page"); return; } drawTempConsumption(); drawFanSpeed(); }; //remote console $scope.testuserinfo = function(){ console.log("userinfo in $rootScope.loginInfo\n"+ JSON.stringify($rootScope.loginInfo)) }; $scope.userRolesType = 0; if($rootScope.loginInfo.userName == 'USERID'){ console.log('setting user roles'); $scope.userRolesType =1; }else if ($rootScope.loginInfo.userName == 'testreq'){ $scope.userRolesType =3; }else if($rootScope.loginInfo.userName == 'testkey'){ $scope.userRolesType =4; }else{ $scope.userRolesType =2; } /////////launch remote console in mini screen start /*disable the mini screen due to design change var viewerAPIErrorCallback = function(errorFunctionName, errorCode){ alert('API Error! \n\nFunction Name:' + errorFunctionName + " \nError Code:" + errorCode); } $scope.remote = {}; $scope.remote.host_addr = $location.host(); $scope.remote.port = 3900; var htmlViewer = null; var viewerWidth; var viewerHeight var parentDiv = document.getElementById("canvasParentDiv"); viewerWidth = parentDiv.clientWidth; viewerHeight = parentDiv.clientHeight; var connectViewer = function(){ console.log('prepare to connect'); htmlViewer = new RPViewer("kvmCanvas", viewerAPIErrorCallback); console.log('initializing...'); htmlViewer.setRPWebSocketTimeout(3); htmlViewer.setRPCredential("USERID", "PASSW0RD");//TODO, do not hardcode htmlViewer.setRPServerConfiguration($scope.remote.host_addr, $scope.remote.port); htmlViewer.setRPEmbeddedViewerSize(viewerWidth, viewerHeight); htmlViewer.setRPAllowSharingRequests(true); htmlViewer.setRPMouseInputSupport(true); htmlViewer.setRPTouchInputSupport(true); htmlViewer.setRPKeyboardInputSupport(true); htmlViewer.setRPDebugMode(true); htmlViewer.setRPMaintainAspectRatio(true); htmlViewer.setRPInitialBackgroundColor('burlywood'); htmlViewer.setRPInitialMessageColor('black'); htmlViewer.setRPInitialMessage('Connecting Viewer...'); htmlViewer.connectRPViewer(); } connectViewer(); $scope.refreshScreen = function(){ console.log('refreshing screen'); htmlViewer.requestRPRefresh(); } $scope.captureScreen = function(){ console.log('capture screen'); htmlViewer.requestRPCaptureScreenShot(); } $scope.$on('$routeChangeStart', function() { console.log('closing RP Viewer session'); htmlViewer.closeRPViewerSession(); }); $scope.$on('$locationChangeSuccess', function() { console.log('closing RP Viewer session'); htmlViewer.closeRPViewerSession(); }); */ /////////launch remote console in mini screen end $scope.launchRemoteConsole = function(size) { $uibModal.open({ animation: true, templateUrl: 'www/views/home-remote-console-launch.html', controller: 'homeLaunchRemoteConsoleCtrl', size: size }); return false; }; $scope.sendSessionRequest = function(size) { $uibModal.open({ animation: true, templateUrl: 'www/views/home-remote-console-send-request.html', controller: 'homeSendRemoteConsoleSessionReqCtrl', size: size }); return false; }; $scope.updateIMM3AdvKey = function(size) { $uibModal.open({ animation: true, templateUrl: 'www/views/home-remote-update-key.html', controller: 'homeUpdateIMM3AdvKeyCtrl', size: size }); return false; }; $scope.launchRemoteConsoleSetting = function(size) { $uibModal.open({ animation: true, templateUrl: 'www/views/home-remote-console-setting.html', controller: 'homeSendRemoteConsoleSettingCtrl', size: size }); return false; }; $scope.$on('$viewContentLoaded', function() { bindImportSelFileChg(); window.onresize = resizeDiv; drawPowerConsumption(); drawTempConsumption(); //It will be excuted in resizeDiv. drawFanSpeed(); setTimeout(function() { $scope.$emit('clickMenuItem1', 'menuTitleHome'); $scope.$apply(); }, 100); }); } ]) .controller('homeRestartImmCtrl', ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.clkOk = function() { console.log("Restart IMM"); $uibModalInstance.dismiss('Ok'); }; $scope.clkCancel = function() { console.log("Cancel"); $uibModalInstance.dismiss('Cancel'); }; }]) .controller('homeLaunchRemoteConsoleCtrl', ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.clkOk = function() { window.open("#remote", "RemoteControl",'height=768,width=1024,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,status=no'); $uibModalInstance.dismiss('Ok'); }; $scope.clkCancel = function() { console.log("Cancel"); $uibModalInstance.dismiss('Cancel'); }; }]) .controller('homeSendRemoteConsoleSessionReqCtrl', ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.clkOk = function() { console.log("Restart IMM"); $uibModalInstance.dismiss('Ok'); }; $scope.clkCancel = function() { console.log("Cancel"); $uibModalInstance.dismiss('Cancel'); }; }]) /* .controller('homeSchedulePowerActionCtrl', ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.clkOk = function() { console.log("launch schedule power action"); $uibModalInstance.dismiss('Ok'); }; $scope.clkCancel = function() { console.log("Cancel lanuch power action"); $uibModalInstance.dismiss('Cancel'); }; }]) */ .controller('homeSendRemoteConsoleSettingCtrl', ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.clkOk = function() { console.log("Restart IMM"); $uibModalInstance.dismiss('Ok'); }; $scope.clkCancel = function() { console.log("Cancel"); $uibModalInstance.dismiss('Cancel'); }; }]) .controller('homeUpdateIMM3AdvKeyCtrl', ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.clkOk = function() { console.log("Restart IMM"); $uibModalInstance.dismiss('Ok'); }; $scope.clkCancel = function() { console.log("Cancel"); $uibModalInstance.dismiss('Cancel'); }; } ]);<file_sep>'use strict'; angular.module('imm3.remote.console.ctrl', [ 'ngRoute', 'ui.bootstrap', 'ui.uploader', 'ngAnimate','imm3.virtualMedia']) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/remote', { templateUrl : 'www/views/remote-console.html', controller : 'remoteCtrl', reload:true }); } ]) .factory('powerService', ['$resource', '$q', function($resource, $q) { var service = {}; service.restPowerActionList = function() { return $resource('api/providers/poweraction'); }; return service; }]) /** user defined macro, no apis chat dialog, no ui design */ .controller('remoteCtrl', [ '$scope', '$rootScope','$window','$localStorage','$location','$uibModal', 'uiUploader','powerService' , function($scope,$rootScope,$window,$localStorage,$location, $uibModal, uiUploader,powerService) { $scope.remote ={}; //hide menu when loading remote page $("#menu").css({"display":"none","width":"0px","height":"0px"}); $("#divSysGenInfo").css({"display":"none","width":"0px","height":"0px"}); $("#app").css({"margin-left":"-5px","margin-top":"-45px"}); $scope.remote.host_addr = $location.host(); $scope.remote.port = 3900; $("#headTitleSpan").html($scope.remote.host_addr + ", Power is ON, USERID"); var htmlViewer = null; var sessionSharingTimeout = null; var viewerWidth; var viewerHeight; //some api(s) can only be called when viewer connected to the avct server var bLaunchViewer = false; var bLaunchVMedia = false; var bSessionReadonly = false; //inventory data var invData = []; var viewerAPIErrorCallback = function(errorFunctionName, errorCode){ alert('API Error! \n\nFunction Name:' + errorFunctionName + " \nError Code:" + errorCode); } var parentDiv = document.getElementById("canvasParentDiv"); viewerWidth = parentDiv.clientWidth; viewerHeight = parentDiv.clientHeight; //credentials/security/authentication not implemented yet, hard code for now //once implemented, the username/password will needs to be decoded from the token (JWT) $scope.remote.credentials ={}; $scope.remote.credentials.username ="USERID"; $scope.remote.credentials.passw0rd ="<PASSWORD>"; $scope.remote.sessionUserList = [ { "userName":"USERID", "userID":"userID", "ipAddress":"10.20.30.40", "isCurrentUser":true, "sessionID":"1", } ]; //CallBacks /** * Function is used to report login status. * @param {type} loginStatus * */ var reportLoginStatus = function(loginStatus) { //report login exception status caught in notifications.js. Reported //here to allow customized handling. 0 <= loginStatus <= 15 console.log('loginStatus::' + loginStatus); var message = null; var loginResult = RPViewer.RP_LOGIN_RESULT; switch (loginStatus) { case loginResult.LOGIN_INVALID_USER: case loginResult.LOGIN_INVALID_PASSWORD: message = "Login failed.\n\nInvalid User name or Password."; //message = ResourceManager.ConnectionDialog_LoginFailed_Invalid; break; case loginResult.LOGIN_DENIED: message = "Login denied"; //message = ResourceManager.ConnectionDialog_AccessDenied; break; case loginResult.LOGIN_FULL: message = "Login failed\n\nThe max number of session has been exceeded."; //message = ResourceManager.ConnectionDialog_NoChannelsAvailable; break; case loginResult.LOGIN_NOSHARE: message = "Sharing request has been denied."; //message = ResourceManager.ConnectionDialog_SharingDenied; break; case loginResult.LOGIN_CERTIFICATE_NOT_VERIFIED: message = "Failed to connect viewer. Certificate may not be verified."; break; case loginResult.LOGIN_CERTIFICATE_TIMEDOUT: message = "The session has timed out waiting for verification of the certificate.\nAll the connections will be closed."; break; case loginResult.LOGIN_WEBSOCKET_EXCEPTION: message = "Failed to connect viewer due to Websocket exception."; break; default: message = "Login failed."; //message = ResourceManager.ConnectionDialog_LoginFailed; break; } if (message != null) { $scope.$emit('showErrMsgBox', message); } } /** * Callback function for login response * @param {type} loginStatus * */ var loginResponseCallback = function(loginStatus){ console.log('loginResponseCallback::' + loginStatus); if (loginStatus === RPViewer.RP_LOGIN_RESULT.LOGIN_SUCCESS) { console.log("logged in successfully"); //TODO return; } else if (loginStatus === RPViewer.RP_LOGIN_RESULT.LOGIN_INUSE) { console.log('another user is using session. sending sharing request'); var confirmMsg = "A session to this device already exists. Do you want to try to share this session?"; var ans = confirm(confirmMsg); // console.log('confirm ans..'+ans); htmlViewer.requestRPSharedMode(ans); return; } //shared session else { reportLoginStatus(loginStatus); //report status via user exposed routine. htmlViewer.closeRPViewerSession(); } } /** * Callback function to report sharing request. * @param {type} userName * */ var sharingRequestCallback = function(userName){ htmlViewer.exitRPFullScreen(); console.log('sharingRequestCallback...userName::' + userName); sessionSharingTimeout = setTimeout(function() { $("#sharedDialog").modal('hide'); sessionSharingTimeout = null; htmlViewer.sendRPSharingResponse(RPViewer.RP_SESSION_SHARING.SHARING_TIMEOUT);}, 30000); var reqMsg = "A connection request has been received from user '" + userName + "'."; $scope.remote.shareReqMsg = reqMsg; $("#sharedDialog").modal('show'); } /** * * Function is used to handle sharing action. */ var cfmShareAction = function() { $("#sharedDialog").modal('hide'); clearTimeout(sessionSharingTimeout); var actionVal; if($scope.remote.shareAction == 2){ actionVal = RPViewer.RP_SESSION_SHARING.SHARING_ACCEPT; }else if($scope.remote.shareAction == 1){ actionVal = RPViewer.RP_SESSION_SHARING.SHARING_REJECT; }else{ actionVal = RPViewer.RP_SESSION_SHARING.SHARING_PASSIVE; } htmlViewer.sendRPSharingResponse(actionVal); } $scope.cfmShareActionOk = cfmShareAction; /** * * Callback function to report sharing cancel request. */ $scope.sharingCancelRequest =function(){ console.log('canceling.....'); if (sessionSharingTimeout !== null) { clearTimeout(sessionSharingTimeout); sessionSharingTimeout = null; } $("#sharedDialog").modal('hide'); } /** * * Callback function */ var exitViewerCallback = function() { //called on page unload, or indirectly from a disconnect button press. invData.length = 0; console.log('exitViewerCallback...'); bLaunchViewer = false; bLaunchVMedia = false; bSessionReadonly = false; sessionUserList = null; localStorage.removeItem("VIEWER_CHAT_DATA"); if(htmlViewer.isRPVirtualKeyboardPoppedUp()){ htmlViewer.closeRPVirtualKeyboard(); } } /** * Function is used to push inventory data to an array * @param {type} json * @param {type} rootKey * */ var getInvValues =function(json, rootKey) { for (var key in json[rootKey]) { for (var key1 in json[rootKey][key]) { if (typeof json[rootKey][key][key1] === "object") { var arr = json[rootKey][key][key1]; for (var prop in arr) { if (typeof arr[prop] === "object") { for (var elem in arr[prop]) { var propName = "jsonobj." + rootKey + "." + key + "." + key1 + "." + prop + "." + elem; var propValue = arr[prop][elem]; invData.push({ name: propName, value: propValue }); // console.log("jsonobj."+rootKey+ "."+ key + "." + key1 + "."+prop + "."+ elem + " = "+arr[prop][elem]); } } else { var propName = "jsonobj." + rootKey + "." + key + "." + key1 + "." + prop; var propValue = arr[prop]; invData.push({ name: propName, value: propValue }); //console.log(propName+ " = "+propValue); } } } else { var propName = "jsonobj." + rootKey + "." + key + "." + key1; var propValue = json[rootKey][key][key1]; invData.push({ name: propName, value: propValue }); // console.log(propName + " == "+ propValue ); } } } } /** * Callback function to update RPViewer inventory data. * @param {type} data * */ var inventoryCallback = function(data) { var jsonData = JSON.parse(data); var rootKey; invData.length = 0; for (var prop in jsonData) { if (typeof (jsonData[prop]) === 'object' && !(jsonData[prop] instanceof Array)) { rootKey = prop; getInvValues(jsonData, rootKey); } else { var propName = "jsonobj." + prop; var propValue = jsonData[prop]; invData.push({ name: propName, value: propValue }); //console.log(propName +" = "+ propValue); } } } /** * Callback function is used to update user infomation. * @param {type} userList * */ $scope.currentUser = {}; var userListChangeCallback = function(userList){ $scope.remote.sessionUserList = userList; for (var i = 0; i < userList.length; i++) { var userRecord = userList[i]; if(userRecord.isCurrentUser){ $scope.currentUser.userName = userRecord.userName; $scope.currentUser.sessionID = userRecord.sessionID; } console.log('actSession UserName:: ' + i + " " + userRecord.userName + " userID::" + userRecord.userID + " IPAddress:" + userRecord.ipAddress + " Current User:" + userRecord.isCurrentUser + " SessionId::" + userRecord.sessionID); } } /** * Callback function is used to update mouse acceleration value. * @param {type} val * */ var mouseAccelerationCallback =function(val) { $scope.remote.accSetting = val; } /** * Callback function for session read-only info update * @param {type} bReadOnly * */ var sessionReadonlyCallback =function(bReadOnly) { bSessionReadonly = bReadOnly; if (bReadOnly) { //TODO, disbale mouse and keyboard //document.getElementById("macroFieldSet").style.display = 'none'; //document.getElementById('keyboardTd').style.display = 'none'; $scope.$emit('chgSrvNameSuc1', 'Read Only privilege granted.'); alert(); } } /** * Function is used to report RPViewer terminate reason. * @param {type} messageNum * */ var reportTerminationReason = function(messageNum, isViewer) { //report termination status caught in notifications.js. Reported //here to allow customized handling. Logger.logDebug('Termination Reason::' + messageNum); var shutdownReason = RPViewer.RP_SHUTDOWN_REASON; var reason; switch (messageNum) { case shutdownReason.SHUTDOWN_ADMIN: reason = "Administrator Disconnect"; break; case shutdownReason.SHUTDOWN_TIMEOUT: reason = "Exceeded Idle Time Out"; break; case shutdownReason.SHUTDOWN_WEBSOCKET: reason = "the network connection has been dropped"; break; case shutdownReason.SHUTDOWN_REBOOT: reason = "Appliance Reboot"; break; case shutdownReason.SHUTDOWN_UPGRADE: reason = "Pending DSRIQ Upgrade"; break; case shutdownReason.SHUTDOWN_PREEMPT: reason = "Local User Channel Premption"; break; case shutdownReason.SHUTDOWN_UNSHARE: reason = "Last Active User Disconnection"; break; case shutdownReason.SHUTDOWN_EXLUSIVE: reason = "Primary User Getting into Exclusive Mode"; break; default: reason = "Unknown Problem"; break; } var message = "Client has been shut down as a result of "; if (! isViewer) message = "Virtual Media has terminated as a result of "; message += reason + "."; $scope.$emit('showErrMsgBox', message); } /** * Callback function for session termination. * @param {type} reason * */ var sessionTermCallback = function(reason) { console.log('onSessionTermination...' + reason); reportTerminationReason(reason, true); //report status via user exposed routine. htmlViewer.closeRPViewerSession(); } /** * Callback function to update message for video stopped reasons. * @param {type} reason * @param {type} xRes * @param {type} yRes * @param {type} colorDepth * @returns {String} */ var videoStoppedCallback = function(reason, xRes, yRes, colorDepth) { //Logger.logDebug('videoStoppedCallback...'+reason); var videoStoppedMsg; switch (reason) { case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_CALIBRATING: videoStoppedMsg = "Calibrating"; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_NO_SIGNAL: videoStoppedMsg = "No Signal"; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_OUT_OF_RANGE: videoStoppedMsg = "Out of Range"; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_PERMISSION_DENIED: case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_BLOCKED: videoStoppedMsg = "The remote vKVM feature\nhas been currently disabled\nby the local system administrator"; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_RESOLUTION_NOT_SUPPORTED: videoStoppedMsg = "Out of Range\nReason:Resolution Not Supported\nDetected Resolution:"; videoStoppedMsg += " " + xRes + "x" + yRes; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_CAPTURE_FAILED: videoStoppedMsg = "Out of Range\nReason:Video Capture Failure\nDetected Resolution:"; videoStoppedMsg += " " + xRes + "x" + yRes; videoStoppedMsg += "\n" + "Detected Color Depth:" + colorDepth + "bpp"; break; default: videoStoppedMsg = "No Signal"; break; } return videoStoppedMsg; } //virtual media call back var loginVMCallback = function(loginStatus, loggedUserName) { Logger.logDebug('loginVMCallback response::' + loginStatus); // report status via user exposed routine. if (loginStatus === RPViewer.RP_LOGIN_RESULT.LOGIN_INUSE_CAN_PREEMPT) { $scope.$emit('showErrMsgBox', 'LOGIN_INUSE_CAN_PREEMPT'); } //preempt session else if (loginStatus === RPViewer.RP_LOGIN_RESULT.LOGIN_FAILED_PREEMPT_DENIED) { $scope.$emit('showErrMsgBox', "The preempt request has been refused."); } else if (loginStatus === RPViewer.RP_LOGIN_RESULT.LOGIN_FULL) { $scope.$emit('showErrMsgBox', "Virtual Media redirection is already in use by another user."); } } $scope.theOtherUser ={}; $scope.theOtherUser.userName =''; $scope.chatHisData =[]; var populateChatMsg = function(){ $scope.chatHisData =[]; angular.forEach($scope.chatMsgs, function(msg, index) { console.log(JSON.stringify(msg)); var msgDataArr = msg.message.split("->");//string.split(','); var senderId = msgDataArr[0]; var senderName = msgDataArr[1]; var receiverId = msgDataArr[2]; var receiverName = msgDataArr[3]; var msgText = msgDataArr[4]; console.log("getData\t"+msgDataArr[0]+"\t"+msgDataArr[1]+"\t"+msgDataArr[2]+"\t"+msgDataArr[3]+"\t"+msgDataArr[4]+"\t"); if((senderId == $scope.theOtherUser.sessionID && receiverId == $scope.currentUser.sessionID)|| (receiverId == $scope.theOtherUser.sessionID && senderId == $scope.currentUser.sessionID)){ $scope.chatHisData.push({"senderId":senderId,"senderName":senderName,"receiverId":receiverId,"receiverName":receiverName,"msgText":msgText}); } }); var len = $scope.chatHisData.length; if(len >8){ $scope.chatHisData = $scope.chatHisData.slice(len-9,len-1); } } $scope.openChatDlg = function(id,name,ipaddr){ $scope.theOtherUser.sessionID = id; $scope.theOtherUser.userName = name; $scope.theOtherUser.userIpAddr = ipaddr; populateChatMsg(); htmlViewer.setRPFocus(false); $("#chatDlg").modal(); } $scope.lastSendMsg = ""; $scope.sendChatMsg = function(msg){ var chatText = document.getElementById('txtChat'); var msg = chatText.value; msg=msg.replace(/</g, "&lt"); msg=msg.replace(/->/g, "-&gt"); msg=msg.replace(/>/g, "&gt"); chatText.value =''; var formatedMsg = $scope.currentUser.sessionID+"->"+$scope.currentUser.userName+"->"+$scope.theOtherUser.sessionID+"->"+$scope.theOtherUser.userName+"->"+msg; htmlViewer.sendRPChatMessage(formatedMsg); var msgData = {"senderName":$scope.currentUser.userName,"senderSessionid":$scope.currentUser.sessionID,"message":formatedMsg}; $scope.lastSendMsg = formatedMsg; $scope.chatMsgs.push(msgData); populateChatMsg(); } $scope.chatMsgs =[]; var chatMessageCallback = function(userName, sessionId, message, bCurrentUser) { console.log("chat msg received\t"+userName+"\t"+sessionId+"\t"+message+"\t"+bCurrentUser); var msgData = {"senderName":userName,"senderSessionid":sessionId,"message":message}; if(message != $scope.lastSendMsg){ $scope.chatMsgs.push(msgData); } var msgDataArr = message.split("->");//string.split(','); var receiverId = msgDataArr[2]; if(receiverId == $scope.currentUser.sessionID){ $scope.theOtherUser.sessionID = msgDataArr[0]; $scope.theOtherUser.userName = msgDataArr[1]; //get sender ip addr angular.forEach($scope.remote.sessionUserList, function(user, index) { if(user.sessionID == $scope.theOtherUser.sessionID ){ $scope.theOtherUser.userIpAddr = user.ipAddress; } }); populateChatMsg(); htmlViewer.setRPFocus(false);//need to setRPFocus as false or you can not type anything into the textarea $("#chatDlg").modal(); } console.log("all messages\t"+JSON.stringify($scope.chatMsgs)); } var reportTerminationReason =function(messageNum, isViewer) { //report termination status caught in notifications.js. Reported //here to allow customized handling. Logger.logDebug('Termination Reason::' + messageNum); var shutdownReason = RPViewer.RP_SHUTDOWN_REASON; var reason; switch (messageNum) { case shutdownReason.SHUTDOWN_ADMIN: reason = "Administrator Disconnect"; break; case shutdownReason.SHUTDOWN_TIMEOUT: reason = "Exceeded Idle Time Out"; break; case shutdownReason.SHUTDOWN_WEBSOCKET: reason = "the network connection has been dropped"; break; case shutdownReason.SHUTDOWN_REBOOT: reason = "Appliance Reboot"; break; case shutdownReason.SHUTDOWN_UPGRADE: reason = "Pending DSRIQ Upgrade"; break; case shutdownReason.SHUTDOWN_PREEMPT: reason = "Local User Channel Premption"; break; case shutdownReason.SHUTDOWN_UNSHARE: reason = "Last Active User Disconnection"; break; case shutdownReason.SHUTDOWN_EXLUSIVE: reason = "Primary User Getting into Exclusive Mode"; break; default: reason = "Unknown Problem"; break; } var message = "Client has been shut down as a result of "; if (! isViewer) message = "Virtual Media has terminated as a result of "; message += reason + "."; $scope.$emit('showErrMsgBox',message); } /** * Callback function for VMedia session diconnect * @param {type} reason * */ var disconnectVMCallback = function(reason) { Logger.logDebug('disconnectVMCallback response::' + reason); if (reason == RPViewer.RP_SHUTDOWN_REASON.SHUTDOWN_PREEMPT) { //preemption occurred so we are quietly shutting down. } else { reportTerminationReason(reason, false); } } $scope.$on('$viewContentLoaded', function() { htmlViewer = new RPViewer("kvmCanvas", viewerAPIErrorCallback); htmlViewer.setRPWebSocketTimeout(2); htmlViewer.setRPCredential($scope.remote.credentials.username, $scope.remote.credentials.passw0rd); htmlViewer.setRPServerConfiguration($scope.remote.host_addr, $scope.remote.port); htmlViewer.setRPEmbeddedViewerSize(viewerWidth, viewerHeight); htmlViewer.setRPAllowSharingRequests(true); htmlViewer.setRPMouseInputSupport(true); htmlViewer.setRPTouchInputSupport(true); htmlViewer.setRPKeyboardInputSupport(true); htmlViewer.setRPDebugMode(true); htmlViewer.setRPMaintainAspectRatio(true); htmlViewer.setRPInitialBackgroundColor('burlywood'); htmlViewer.setRPInitialMessageColor('black'); htmlViewer.setRPVirtualKeyboardPosition(50,100); htmlViewer.setRPVMPort($scope.remote.port); //htmlViewer.setRPVMCredential($scope.remote.credentials.username, $scope.remote.credentials.passw0rd); //htmlViewer.activateRPVMedia(false); htmlViewer.activateRPVMedia(true); htmlViewer.setRPInitialMessage('Connecting Viewer...'); //Setting Callbacks htmlViewer.registerRPLoginResponseCallback(loginResponseCallback); // htmlViewer.registerRPSharingRequestCallback(sharingRequestCallback); //htmlViewer.registerRPSharedRequestCancelCallback(sharingCancelRequestCallback);//do not need this htmlViewer.registerRPExitViewerCallback(exitViewerCallback); htmlViewer.registerRPUserListChangeCallback(userListChangeCallback); //htmlViewer.registerRPColorModeChangeCallback(reportColorModeChange); //TODO htmlViewer.registerRPChatMessageCallback(chatMessageCallback);//don't have a chat UI design currently, no UI implementation htmlViewer.registerRPMouseAccelerationChangeCallback(mouseAccelerationCallback); htmlViewer.registerRPSessionReadOnlyCallback(sessionReadonlyCallback); htmlViewer.registerRPSessionTerminationCallback(sessionTermCallback); htmlViewer.registerRPVideoStoppedCallback(videoStoppedCallback); //htmlViewer.registerRPLEDKeyStatusCallback(ledStatusCallback); // don't have a LED status UI design currently, no UI implementation htmlViewer.registerRPInventoryCallback(inventoryCallback); //htmlViewer.registerRPUserInteractionCallback(userInteractionCallback);//not used htmlViewer.registerRPVMLoginResponseCallback(loginVMCallback); //TODO virtual media htmlViewer.registerRPVMSessionDisconnectCallback(disconnectVMCallback);//TODO virtual media //htmlViewer.registerRPVMDeviceInfoUpdateCallback(infoVMDevicesCallback);//TODO virtual media //htmlViewer.registerRPVMDeviceStatusUpdateCallback(statusVMDeviceCallback);//TODO virtual media htmlViewer.connectRPViewer(); bLaunchViewer = true; }); $scope.onExit = function(){ console.log('exiting viewer....'); htmlViewer.closeRPViewerSession(); return 'bye bye'; } $window.onbeforeunload = $scope.onExit; $scope.showKeyboard = function(){ htmlViewer.setRPFocus(true); if (htmlViewer.isRPVirtualKeyboardPoppedUp()) { htmlViewer.closeRPVirtualKeyboard(); } else { console.log('Keybord size...'+htmlViewer.getRPVirtualKeyboardSize()); htmlViewer.showRPVirtualKeyboard(RPViewer.RP_VKEYBOARD_LANGUAGE.ENGLISH_EN); } } $scope.exitViewer = function(){ console.log('exiting viewer....'); htmlViewer.closeRPViewerSession(); } $scope.captureScreenShot = function(){ console.log('capture screen....'); htmlViewer.requestRPCaptureScreenShot(); } $scope.refreshScreen = function(){ console.log('refresh viewer....'); htmlViewer.requestRPRefresh(); } /** * * Function is used to show RPViewer in full screen mode. */ $scope.showFullScreen = function(){ var bSupport = htmlViewer.showRPFullScreen(); if (bSupport === false) { $scope.$emit('showErrMsgBox', "Your browser doesn't support full screen mode."); } else { fullScreen = true; } } /** * Function is used to resize the canvas based on browser's size. * */ $scope.fitToScreen = function(){ if (htmlViewer !== null) { htmlViewer.setRPEmbeddedViewerSize(viewerWidth, viewerHeight); } } $scope.notSupported = function(){ $scope.$emit('showErrMsgBox', 'Not supported!'); } $scope.$on('$routeChangeStart', function() { /*alert('route changing remote page'); $("#menu").css({"height": "100%", "padding-top": "48px"}); $("#divSysGenInfo").css({"background-color": "#F3F3F6", "height": "48px", "position": "fixed", "width": "100%", "z-index": "999"}); $("#app").css({"height": "100%", "overflow-x": "hidden","overflow-y": "auto","background-color": "#F3F3F6"}); */ }); $scope.$on('$locationChangeSuccess', function() { /* alert('location change'); $("#menu").css({"height": "100%", "padding-top": "48px"}); $("#divSysGenInfo").css({"background-color": "#F3F3F6", "height": "48px", "position": "fixed", "width": "100%", "z-index": "999"}); $("#app").css({"height": "100%", "overflow-x": "hidden","overflow-y": "auto","background-color": "#F3F3F6"}); alert('location change done'); */ }); // power action $scope.powerMessages = [ { "powAlertMsg":"Force power off?", "succMsg":"Server has been powered off successfully.", "failMsg": "Failed to power off server." }, { "powAlertMsg":"Power on this server?", "succMsg":"Server has been powered on successfully.", "failMsg": "Failed to power on server." }, { "powAlertMsg":"Shutdown os and then power off?", "succMsg":"Shutdown OS and then Power off request has been handled successfully.", "failMsg": "Failed to handle Shutdown OS and then Power off request." }, { "powAlertMsg":"Shutdown OS and then restart this server?", "succMsg":"Shut down OS and then Restart Request has been handled successfully.", "failMsg": "Failed to handle Shut down OS and then Restart request." }, { "powAlertMsg":"Reboot this server immediately?", "succMsg":"Restart server Request has been handled successfully.", "failMsg": "Failed to handle Restart server request" }, { "powAlertMsg":"Boot to system setup?", "succMsg":"Boot to system setup request has been handled successfully.", "failMsg": "Failed to handle Boot to system setup request.", }]; $scope.powerCode =0; $scope.powerMessage =""; $scope.powerActionSel = function(powerAction) { $scope.powerCode = powerAction; $scope.powerMessage = $scope.powerMessages[Math.log(powerAction)/Math.log(2)].powAlertMsg; $("#cfmPowerAction").modal(); return false; }; //TODO need to provide remote service to send power action code var restPowerAction = powerService.restPowerActionList(); $scope.cfmPoweraction = function (){ console.log("power code \t "+$scope.powerCode); restPowerAction.save({"powerAction": $scope.powerCode},function(){ $scope.$emit('showErrMsgBox', $scope.powerMessages[Math.log($scope.powerCode)/Math.log(2)].succMsg); }, function(err) { console.log('failed to send request'); $scope.$emit('showErrMsgBox', $scope.powerMessages[Math.log($scope.powerCode)/Math.log(2)].failMsg); }); } //show mouse single cursor mode $scope.showSingleCursorMode = function (){ $("#singleCursorMode").modal(); } $scope.enableSingleCursorMode = function (){ console.log("single cursor mode"); //htmlViewer.requestRPAbsoluteMouseSync(true); htmlViewer.setRPMouseInputSupport(true); } //show mouse setting $scope.remote.accSetting = 1; $scope.showMouseSetting = function (){ // If set to false, the mouse and keyboard events are disabled. htmlViewer.setRPFocus(true); $("#mouseSettings").modal(); } $scope.applyAccSetting = function () { htmlViewer.setRPMouseAccelerationMode($scope.remote.accSetting); } //color mode $scope.applyColorMode = function (value_x){ console.log("value_x\t"+value_x); if (htmlViewer.getPlatformID() === 4)//Pilot4 { if (value_x > 5) { htmlViewer.setRPVideoColorMode(value_x, true); } else { htmlViewer.setRPVideoColorMode(value_x, false); } } else { if (value_x > 6) { htmlViewer.setRPVideoColorMode(value_x, true); } else { htmlViewer.setRPVideoColorMode(value_x, false); } } } //show screen mode setting $scope.remote.modeSetting = 0; $scope.showModeSetting = function (){ $("#modeSettings").modal(); } $scope.applyModeSetting = function (){ console.log("$scope.remote.modeSetting \t"+$scope.remote.modeSetting); } //show sharing settings $scope.remote.shareAction = 3; $scope.remote.shareReqMsg =""; $scope.showSharingDialog = sharingRequestCallback; /*$scope.showSharingDialog = function (){ $("#sharedDialog").modal(); } $scope.applyShareAction = function(){ console.log("share action\t"+$scope.remote.shareAction); }*/ $scope.applyMacro = function(macroIndex){ htmlViewer.setRPFocus(true); var macroName = null; var macroLanguage = RPViewer.RP_VKEYBOARD_LANGUAGE.ENGLISH_EN; switch (macroIndex) { case 0: //Ctrl+Alt+Del macroName = "Ctrl+Alt+Del"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_DELETE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 1: //Alt-Tab macroName = "Alt+Tab"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_TAB; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 2: //Alt-Esc macroName = "Alt+Esc"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ESCAPE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 3: //Ctrl-Esc macroName = "Ctrl+Esc"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ESCAPE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 4: //Alt-Space macroName = "Alt+Space"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_SPACE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 5: //Alt-Enter macroName = "Alt+Enter"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ENTER; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 6: //Alt-Hyphen macroName = "Alt+Hyphen"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_SEPARATOR; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 7: //Alt-F4 macroName = "Alt+F4"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_F4; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 8: //Prt Scr macroName = "Prt Scr"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PRINTSCREEN; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 9: //Alt + PrintScreen macroName = "Alt+PrintScreen"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PRINTSCREEN; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 10: //F1 macroName = "F1"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_F1; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 11: //Pause macroName = "Pause"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PAUSE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 12: //Tab macroName = "Tab"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_TAB; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 13: //Ctrl+Enter macroName = "Ctrl+Enter"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ENTER; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 14: //SysRq macroName = "SysRq"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PRINTSCREEN; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 15: //Alt+SysRq macroName = "Alt+SysRq"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PRINTSCREEN; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 16: //Windows Start macroName = "Windows Start"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_WINDOWS_START; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; } console.log("macroName\t"+macroName); htmlViewer.sendRPMacro(macroName); } //launch virtual media popup $scope.launchVirtualMedia = function(size) { $uibModal.open({ animation: true, templateUrl: 'www/views/virtual-media-included.html', controller: 'remoteVirtualMediaCtrl', resolve:{ viewer : function() { return htmlViewer; } }, size: size }); return false; }; }]) .controller('remoteVirtualMediaCtrl', ['$scope', '$rootScope','$localStorage','$location','$uibModal','uiUploader','$document','virtualMediaInfoService','viewer', function($scope, $rootScope, $localStorage,$location,$uibModal,uiUploader,$document,virtualMediaInfoService,viewer,$http) { $scope.$emit('clickMenuItem1', 'menuTitleVirtualMedia'); var htmlViewer = viewer; // the data needs to be read from the server $scope.fileBlobArray = []; $scope.vMediaData={ "virHD":[ /* { "id": "1", "name": "myoperatingsystem.img", "localPath":"c/myoperatingsystem.img", "srvPath":"/var/image/myoperatingsystem.img", "size": "1000M", "readonly":true, "newMedia":false } */ { "id": "1", "name": "", "localPath":"", "srvPath":"", "size": "", "readonly":true, "newMedia":true, fileBlobArray : [] } ], "CD":[ /* { "id": "2", "name": "myoperatingsystem.iso", "localPath":"c/myoperatingsystem.iso", "srvPath":"/var/image/myoperatingsystem.iso", "size": "200M", "readonly":true, "newMedia":false } */ { "id": "2", "name": "", "localPath":"", "srvPath":"", "size": "", "readonly":true, "newMedia":true, fileBlobArray : [] } ], "RDOC":[ /* { "id": "3", "name": "myscript1.img", "localPath":"c/myscript1.img", "srvPath":"/var/image/myscript1.img", "size": "10M", "readonly":true, "newMedia":false } */ { "id": "3", "name": "", "localPath":"", "srvPath":"", "size": "10M", "readonly":true, "newMedia":true } ] }; /* $scope.vMediaData = {}; var restVirtualMediaInfo = virtualMediaInfoService.restVirtualMediaInfo(); restVirtualMediaInfo.get(function(data) { $scope.vMediaData = data["virMediaInfo"]; }); */ //stores the media names in this array and used as model for the select options, //adding a default one(defaultItem) during initialization $scope.mediaNameOptionArr = []; var defaultItem = { "id": "0", "name": "- Select one mounted media -" }; $scope.mediaNameOptionArr.push(defaultItem); //update the selection options when opening [Select one virtual media to boot at next restart] $scope.updateSelectOption = function () { angular.forEach($scope.vMediaData, function(item, index) { angular.forEach(item, function(media, index1) { if(!media.newMedia){ var found = false; angular.forEach($scope.mediaNameOptionArr, function(existingItem, index2){ if(existingItem.id == media.id){ found = true;; } }); if(!found){ var mediaIteam = { "id": "", "name": "" } mediaIteam.id = media.id; mediaIteam.name = media.name; $scope.mediaNameOptionArr.push(mediaIteam); } } }); }); } //get all the mounted media numbers $scope.getMediaNum = function(){ var count = 0; angular.forEach($scope.vMediaData, function(item, index) { angular.forEach(item, function(media, index1) { if(!media.newMedia){ count ++ ; } }); }); return count; }; //get all mounted RDOC media number $scope.getRDOCMediaNum = function(){ var count = 0; angular.forEach($scope.vMediaData['RDOC'], function(item, index) { if(!item.newMedia){ count ++ ; } }); return count; }; // only one HD is supported //bind a change event to the virHDInput element(file browser) once the Browser... is clicked, , var bindVirHDSelect = function() { var element = document.getElementById("virHDInput"); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); console.log("file length\t"+uiUploader.getFiles().length); $scope.vMediaData["virHD"][0].name = uiUploader.getFiles()[0].name; $scope.vMediaData["virHD"][0].fileBlobArray = uiUploader.getFiles()[0]; $scope.$apply(); }); element = null; }; //binding change event to the first RDOC file browser var bindVirRDOCSelect0 = function() { var element = document.getElementById("virRDOC0"); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); $scope.vMediaData["RDOC"][0].name = uiUploader.getFiles()[0].name; $scope.$apply(); }); element = null; }; //binding change event to the first RDOC file browser as a max of 2 RDOC media is supported var bindVirRDOCSelect1 = function() { var element = document.getElementById("virRDOC1"); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); $scope.vMediaData["RDOC"][1].name = uiUploader.getFiles()[0].name; $scope.$apply(); }); element = null; }; //binding change event to the CD file browser var bindVirCDSelect = function() { var element = document.getElementById("virCDInput"); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); console.log("file length\t"+uiUploader.getFiles().length); $scope.vMediaData["CD"][0].name = uiUploader.getFiles()[0].name; $scope.vMediaData["CD"][0].fileBlobArray = uiUploader.getFiles()[0]; $scope.$apply(); }); element = null; }; //show the second file browser for the RDOC media $scope.addRDOCDevice = function(){ if( $scope.vMediaData["RDOC"].length < 2 ){ var item = { "id": "", "name": "", "localPath":"", "srvPath":"", "size": "10M", "readonly":true, "newMedia":true }; $scope.vMediaData["RDOC"].push(item); angular.element(document.getElementById("virRDOC0")).ready(function(){ bindVirRDOCSelect1(); }); } } angular.element(document.getElementById("virHDInput")).ready(function(){ bindVirHDSelect(); console.log('HD binded'); }); angular.element(document.getElementById("virRDOC0")).ready(function(){ bindVirRDOCSelect0(); console.log('RDOC binded'); }); angular.element(document.getElementById("virCDInput")).ready(function(){ bindVirCDSelect(); console.log('CD binded'); }); //bind the event on page load, $scope.$on('$viewContentLoaded', function() { // console.log('begin binding'); angular.element(document.getElementById("virHDInput")).ready(function(){ bindVirHDSelect(); console.log('HD binded'); }); angular.element(document.getElementById("virRDOC0")).ready(function(){ bindVirRDOCSelect0(); }); angular.element(document.getElementById("virCDInput")).ready(function(){ bindVirCDSelect(); }); }); $scope.umountVirHD = function(){ $scope.vMediaData["virHD"][0].name = ""; $scope.vMediaData["virHD"][0].newMedia = true; //workaround:once a media is umounted, a file browser will be shown, need to bind again angular.element(document.getElementById("virHDInput")).ready(function(){ bindVirHDSelect(); }); } $scope.mountVirHD = function(){ if($scope.vMediaData["virHD"][0].name == ''){ return false; } $scope.vMediaData["virHD"][0].newMedia = false; uiUploader.startUpload({ url: '/upload', concurrency: 2, onProgress: function(file) { // file contains a File object console.log(file); }, onCompleted: function(file, response) { // file contains a File object //$scope.vMediaData["virHD"][0].fileBlobArray = file; $scope.fileBlobArray[0] = file; console.log("upload completed start mapping"); htmlViewer.mapRPDevice(0, file); console.log("mapping completed?"); // response contains the server response console.log(response); }, onCompletedAll: function(files) { // files is an array of File objects console.log(files); } }); } $scope.umountVirCD = function(){ $scope.vMediaData["CD"][0].name = ""; $scope.vMediaData["CD"][0].newMedia = true; //workaround:once a media is umounted, a file browser will be shown, need to bind again angular.element(document.getElementById("virCDInput")).ready(function(){ bindVirCDSelect(); }); } $scope.mountVirCD = function(){ if($scope.vMediaData["CD"][0].name == ''){ return false; } $scope.vMediaData["CD"][0].newMedia = false; uiUploader.startUpload({ url: '/upload', concurrency: 2, onProgress: function(file) { // file contains a File object console.log(file); }, onCompleted: function(file, response) { // file contains a File object //$scope.vMediaData["virHD"][0].fileBlobArray = file; $scope.fileBlobArray[0] = file; console.log("upload completed start mapping"); htmlViewer.mapRPDevice(1, file); // response contains the server response console.log(response); }, onCompletedAll: function(files) { // files is an array of File objects console.log(files); } }); } $scope.umountVirRDOC = function(index){ $scope.vMediaData["RDOC"][index].name = ""; $scope.vMediaData["RDOC"][index].newMedia = true; //workaround:once a media is umounted, a file browser will be shown, need to bind again angular.element(document.getElementById("virRDOC"+index)).ready(function(){ if(index == 0){ bindVirRDOCSelect0(); }else if (index == 1){ bindVirRDOCSelect1(); } }); } $scope.mountVirRDOC = function(index){ if($scope.vMediaData["RDOC"][index].name == ''){ return false; } $scope.vMediaData["RDOC"][index].newMedia = false; //should also fill in other infos such as file size/path etc to $scope.vMediaData["virHD"][0] from the uploader } //control the table(select media and boot options) display $scope.showLaunchTableFlag = false ; $scope.arrowIcon ="www/images/arrow_right.png"; $scope.showLaunchTable = function (){ $scope.showLaunchTableFlag = !$scope.showLaunchTableFlag; if($scope.showLaunchTableFlag){ $scope.updateSelectOption(); $scope.arrowIcon ="www/images/arrow_down.png"; }else{ $scope.arrowIcon ="www/images/arrow_right.png"; } } $scope.bootOptions = [ { "id":1, "value":"Restart immediately" }, { "id":2, "value":"Shut down OS and then restart" }, { "id":3, "value":"Manually restart later" } ]; // boot options select model $scope.defaultBootOption = $scope.bootOptions[2].value; $scope.settingsApplied = false ; $scope.changeBootOpt = function(bootOption){ $scope.settingsApplied = false ; } //mounted media select model $scope.selectedMedia = $scope.mediaNameOptionArr[0].name; $scope.changeSelectMedia = function (selectedMedia){ $scope.selectedMedia = selectedMedia; console.log('selectMedia\t' + selectedMedia); $scope.settingsApplied = false ; } $scope.cfmSelectMedia = function(){ console.log('bootOption\t'+$scope.defaultBootOption); if($scope.defaultBootOption != 'Restart immediately'){ $scope.settingsApplied = true ; }else if( $scope.selectedMedia != '- Select one mounted media -'){ $("#confirmRestartImmediate").modal(); } } $scope.cancelAction = function(){ $scope.showLaunchTableFlag = false ; } $scope.submitRestartImmediately = function () { $("#restartSubmittedSucDlg").modal(); } $scope.launchRemoteConsole = function(size) { $uibModal.open({ animation: true, templateUrl: 'www/views/home-remote-console-launch.html', controller: 'homeLaunchRemoteConsoleCtrl', size: size }); return false; }; } ]) .controller('remoteVirtualMediaCtrlTest', ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.clkOk = function() { console.log("Ok"); $uibModalInstance.dismiss('Ok'); }; $scope.clkCancel = function() { console.log("Cancel"); $uibModalInstance.dismiss('Cancel'); }; } ]); <file_sep>'use strict'; angular.module('imm3.virtualMedia', [ 'ngRoute' ]) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/virmedia', { templateUrl : 'www/views/virtual-media.html', controller : 'VirtualMediaCtrl' }); } ]) .controller('VirtualMediaCtrl', ['$scope', '$rootScope','$localStorage','$location','$uibModal','uiUploader','$document','virtualMediaInfoService', function($scope, $rootScope, $localStorage,$location,$uibModal,uiUploader,$document,virtualMediaInfoService,$http) { //$scope.test = "Virtual Media"; //$scope.$emit('setCurPage1', ["Inventory"]); //$scope.$emit('setMenuItemClass1', 'menuTitleSecurity'); $scope.$emit('clickMenuItem1', 'menuTitleVirtualMedia'); $rootScope.loginInfo = angular.copy($localStorage.loginInfo); if(!$rootScope.loginInfo.loginStatus){ $location.path("/login"); }else{ console.log("I am in virtual media page"); } // the data needs to be read from the server $scope.vMediaData={ "virHD":[ /* { "id": "1", "name": "myoperatingsystem.img", "localPath":"c/myoperatingsystem.img", "srvPath":"/var/image/myoperatingsystem.img", "size": "1000M", "readonly":true, "newMedia":false } */ { "id": "1", "name": "", "localPath":"", "srvPath":"", "size": "", "readonly":true, "newMedia":true } ], "CD":[ /* { "id": "2", "name": "myoperatingsystem.iso", "localPath":"c/myoperatingsystem.iso", "srvPath":"/var/image/myoperatingsystem.iso", "size": "200M", "readonly":true, "newMedia":false } */ { "id": "2", "name": "", "localPath":"", "srvPath":"", "size": "", "readonly":true, "newMedia":true } ], "RDOC":[ { "id": "3", "name": "myscript1.img", "localPath":"c/myscript1.img", "srvPath":"/var/image/myscript1.img", "size": "10M", "readonly":true, "newMedia":false } /* { "id": "3", "name": "", "localPath":"", "srvPath":"", "size": "10M", "readonly":true, "newMedia":true } */ ] }; /* $scope.vMediaData = {}; var restVirtualMediaInfo = virtualMediaInfoService.restVirtualMediaInfo(); restVirtualMediaInfo.get(function(data) { $scope.vMediaData = data["virMediaInfo"]; }); */ //stores the media names in this array and used as model for the select options, //adding a default one(defaultItem) during initialization $scope.mediaNameOptionArr = []; var defaultItem = { "id": "0", "name": "- Select one mounted media -" }; $scope.mediaNameOptionArr.push(defaultItem); //update the selection options when opening [Select one virtual media to boot at next restart] $scope.updateSelectOption = function () { angular.forEach($scope.vMediaData, function(item, index) { angular.forEach(item, function(media, index1) { if(!media.newMedia){ var found = false; angular.forEach($scope.mediaNameOptionArr, function(existingItem, index2){ if(existingItem.id == media.id){ found = true;; } }); if(!found){ var mediaIteam = { "id": "", "name": "" } mediaIteam.id = media.id; mediaIteam.name = media.name; $scope.mediaNameOptionArr.push(mediaIteam); } } }); }); } //get all the mounted media numbers $scope.getMediaNum = function(){ var count = 0; angular.forEach($scope.vMediaData, function(item, index) { angular.forEach(item, function(media, index1) { if(!media.newMedia){ count ++ ; } }); }); return count; }; //get all mounted RDOC media number $scope.getRDOCMediaNum = function(){ var count = 0; angular.forEach($scope.vMediaData['RDOC'], function(item, index) { if(!item.newMedia){ count ++ ; } }); return count; }; // only one HD is supported //bind a change event to the virHDInput element(file browser) once the Browser... is clicked, , var bindVirHDSelect = function() { var element = document.getElementById("virHDInput"); console.log('binding....'); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); $scope.vMediaData["virHD"][0].name = uiUploader.getFiles()[0].name; $scope.$apply(); }); element = null; }; //binding change event to the first RDOC file browser var bindVirRDOCSelect0 = function() { var element = document.getElementById("virRDOC0"); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); $scope.vMediaData["RDOC"][0].name = uiUploader.getFiles()[0].name; $scope.$apply(); }); element = null; }; //binding change event to the first RDOC file browser as a max of 2 RDOC media is supported var bindVirRDOCSelect1 = function() { var element = document.getElementById("virRDOC1"); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); $scope.vMediaData["RDOC"][1].name = uiUploader.getFiles()[0].name; $scope.$apply(); }); element = null; }; //binding change event to the CD file browser var bindVirCDSelect = function() { var element = document.getElementById("virCDInput"); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); $scope.vMediaData["CD"][0].name = uiUploader.getFiles()[0].name; $scope.$apply(); }); element = null; }; //show the second file browser for the RDOC media $scope.addRDOCDevice = function(){ if( $scope.vMediaData["RDOC"].length < 2 ){ var item = { "id": "", "name": "", "localPath":"", "srvPath":"", "size": "10M", "readonly":true, "newMedia":true }; $scope.vMediaData["RDOC"].push(item); angular.element(document.getElementById("virRDOC0")).ready(function(){ bindVirRDOCSelect1(); }); } } //bind the event on page load, $scope.$on('$viewContentLoaded', function() { // angular.element(document.getElementById("virHDInput")).ready(function(){ bindVirHDSelect(); }); angular.element(document.getElementById("virRDOC0")).ready(function(){ bindVirRDOCSelect0(); }); angular.element(document.getElementById("virCDInput")).ready(function(){ bindVirCDSelect(); }); }); $scope.umountVirHD = function(){ $scope.vMediaData["virHD"][0].name = ""; $scope.vMediaData["virHD"][0].newMedia = true; //workaround:once a media is umounted, a file browser will be shown, need to bind again angular.element(document.getElementById("virHDInput")).ready(function(){ bindVirHDSelect(); }); } $scope.mountVirHD = function(){ if($scope.vMediaData["virHD"][0].name == ''){ return false; } $scope.vMediaData["virHD"][0].newMedia = false; //should also fill in other infos such as file size/path etc to $scope.vMediaData["virHD"][0] from the uploader } $scope.umountVirCD = function(){ $scope.vMediaData["CD"][0].name = ""; $scope.vMediaData["CD"][0].newMedia = true; //workaround:once a media is umounted, a file browser will be shown, need to bind again angular.element(document.getElementById("virCDInput")).ready(function(){ bindVirCDSelect(); }); } $scope.mountVirCD = function(){ if($scope.vMediaData["CD"][0].name == ''){ return false; } $scope.vMediaData["CD"][0].newMedia = false; //should also fill in other infos such as file size/path etc to $scope.vMediaData["virHD"][0] from the uploader } $scope.umountVirRDOC = function(index){ $scope.vMediaData["RDOC"][index].name = ""; $scope.vMediaData["RDOC"][index].newMedia = true; //workaround:once a media is umounted, a file browser will be shown, need to bind again angular.element(document.getElementById("virRDOC"+index)).ready(function(){ if(index == 0){ bindVirRDOCSelect0(); }else if (index == 1){ bindVirRDOCSelect1(); } }); } $scope.mountVirRDOC = function(index){ if($scope.vMediaData["RDOC"][index].name == ''){ return false; } $scope.vMediaData["RDOC"][index].newMedia = false; //should also fill in other infos such as file size/path etc to $scope.vMediaData["virHD"][0] from the uploader } //control the table(select media and boot options) display $scope.showLaunchTableFlag = false ; $scope.arrowIcon ="www/images/arrow_right.png"; $scope.showLaunchTable = function (){ $scope.showLaunchTableFlag = !$scope.showLaunchTableFlag; if($scope.showLaunchTableFlag){ $scope.updateSelectOption(); $scope.arrowIcon ="www/images/arrow_down.png"; }else{ $scope.arrowIcon ="www/images/arrow_right.png"; } } $scope.bootOptions = [ { "id":1, "value":"Restart immediately" }, { "id":2, "value":"Shut down OS and then restart" }, { "id":3, "value":"Manually restart later" } ]; // boot options select model $scope.defaultBootOption = $scope.bootOptions[2].value; $scope.settingsApplied = false ; $scope.changeBootOpt = function(bootOption){ $scope.settingsApplied = false ; } //mounted media select model $scope.selectedMedia = $scope.mediaNameOptionArr[0].name; $scope.changeSelectMedia = function (selectedMedia){ $scope.selectedMedia = selectedMedia; console.log('selectMedia\t' + selectedMedia); $scope.settingsApplied = false ; } $scope.cfmSelectMedia = function(){ console.log('bootOption\t'+$scope.defaultBootOption); if($scope.defaultBootOption != 'Restart immediately'){ $scope.settingsApplied = true ; }else if( $scope.selectedMedia != '- Select one mounted media -'){ $("#confirmRestartImmediate").modal(); } } $scope.cancelAction = function(){ $scope.showLaunchTableFlag = false ; } $scope.submitRestartImmediately = function () { $("#restartSubmittedSucDlg").modal(); } $scope.launchRemoteConsole = function(size) { $uibModal.open({ animation: true, templateUrl: 'www/views/home-remote-console-launch.html', controller: 'homeLaunchRemoteConsoleCtrl', size: size }); return false; }; } ]) /*.filter('countFilter',function(){ return function(inputArray){ console.log("size\t"+JSON.stringify(inputArray)); return inputArray.length; } }) */ .controller('homeLaunchRemoteConsoleCtrl', ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) { $scope.clkOk = function() { console.log("launch remote console"); $uibModalInstance.dismiss('Ok'); }; $scope.clkCancel = function() { console.log("Cancel"); $uibModalInstance.dismiss('Cancel'); }; }]);<file_sep>'use strict'; angular.module('IMM3-Login', [ 'ngRoute', 'pascalprecht.translate', 'imm3.login.service']) .config([ '$routeProvider','$httpProvider', function($routeProvider,$httpProvider) { $routeProvider.when('/login', { templateUrl : 'www/views/login.html', controller : 'loginCtrl' }); $httpProvider.interceptors.push(['$q', '$location', '$localStorage','$rootScope', function($q, $location, $localStorage,$rootScope) { return { 'request': function (config) { config.headers = config.headers || {}; if (angular.isDefined($localStorage.loginInfo)) { if (angular.isDefined($localStorage.loginInfo.token)) { config.headers.Authorization = 'Bearer ' + $localStorage.loginInfo.token; } } return config; }, 'responseError': function(response) { if(response.status === 401 || response.status === 403) { delete $localStorage.token; delete $localStorage.loginInfo; $rootScope.loginInfo = {}; $localStorage.loginInfo = {}; $location.path('/login'); } return $q.reject(response); } }; }]); }]) .controller('loginCtrl', ['$scope','$rootScope' ,'$location' ,'$localStorage','loginSysDetailInfoService','loginService', function($scope,$rootScope, $location,$localStorage,loginSysDetailInfoService,loginService) { $scope.loginData = {}; $rootScope.isLogin = false; if(angular.isDefined($localStorage.loginInfo) && angular.isDefined($localStorage.loginInfo.token) && $localStorage.loginInfo.loginStatus){ $location.path("/home"); }else{ $location.path("/login"); } $scope.credentials={}; $scope.credentials.uname = ""; $scope.credentials.upassword = ""; $scope.loginSysDetailInfo = {}; $scope.loginSysDetailInfo.langMap ={ "Chinese (Simplified Chinese)":"Chinese (Simplified Chinese)", "English":"English", "French":"French" }; $scope.loginSysDetailInfo.currLang = "English"; $scope.loginSysDetailInfo.loginErr = false; $scope.lang_change = function(value){ console.log('language changed'+"\t"+value); $scope.loginSysDetailInfo.currLang = value; if($scope.loginSysDetailInfo.currLang != 'English'){ $scope.$emit('showErrMsgBox', "Only English is supported currently !"); $scope.loginSysDetailInfo.currLang = "English"; } } $scope.showSupportedBrowser = function(){ $("#supportedBrowser").modal(); } var restLoginSysDetailInfo = loginSysDetailInfoService.restLoginSysDetailInfo(); var loginSysDetailInfo = restLoginSysDetailInfo.get(function(data){ $scope.loginSysDetailInfo.proName = data['items'][0].machine_name; $scope.loginSysDetailInfo.srvName = data['items'][0].system_name; $scope.loginSysDetailInfo.serialNum = data['items'][0].serial_number; $scope.loginSysDetailInfo.machType = data['items'][0].machine_typemodel; var powState =data['items'][0].power_state; if(powState == 0){ $scope.loginSysDetailInfo.powerState = "Off"; }else{ $scope.loginSysDetailInfo.powerState = "On"; } $scope.loginSysDetailInfo.immIpAddr = data['items'][0].ipv4_address; $scope.loginSysDetailInfo.location = data['items'][0].location; }); //hard code the license since no api can call TODO: &#169; $scope.loginSysDetailInfo.licensePre = "Licensed Materials - Property of Lenovo. © Copyright Lenovo and other(s) 2017."; $scope.loginSysDetailInfo.licenseSuf = "Lenovo is a trademark of Lenovo in the United States, other countries, or both."; $scope.loginSysDetailInfo.criticalCount = 0; $scope.loginSysDetailInfo.warningCount = 0; var restActiveEvents = loginSysDetailInfoService.restActiveEvents(); restActiveEvents.get(function(data){ angular.forEach(data['items'], function(item, index) { var type = item['severity']; if(type == 'E'){ $scope.loginSysDetailInfo.criticalCount ++; }else if(type == 'W'){ $scope.loginSysDetailInfo.warningCount ++; } }); }); $scope.signin = function() { console.log("$scope.credentials.uname\t"+$scope.credentials.uname); //login workaround var loginData = {"loginStatus":true, "userName":"USERID", "authorizedRoles":["Supervisor","viewer"], "token":"<KEY>"}; var restDoLogin = loginService.restDoLogin(); var restGetTire = loginService.restGetTire(); restDoLogin.save({},{"username":$scope.credentials.uname,"password":$scope.<PASSWORD>},function(data){ if(undefined !=data.access_token){ $rootScope.isLogin = true; loginData["loginStatus"] = true; loginData["userName"] = $scope.credentials.uname; loginData["token"] = data.access_token; $localStorage.loginInfo = angular.copy(loginData); $rootScope.loginInfo = angular.copy(loginData); $localStorage.tier = 1; restGetTire.get(function(data){ if(data.return == 0){ $rootScope.tier = data.tier; $localStorage.tier = data.tier; console.log("tier is :"+$rootScope.tier); } }); $location.path("/home"); }else{ $scope.loginSysDetailInfo.loginErr = true; } }, function(err) { $scope.loginSysDetailInfo.loginErr = true; }); }; $scope.hideErrMsg = function(){ $scope.loginSysDetailInfo.loginErr = false; } }]);<file_sep>'use strict'; angular.module('imm3.virtual.media.service', [ 'ngResource' ]) .factory('virtualMediaInfoService', [ '$resource', function($resource) { var service = {}; service.restVirtualMediaInfo = function() { return $resource('www/data/:path.json', { path: 'virtual.media.info' }); }; return service; } ]) <file_sep>'use strict'; angular.module('myApp.backupRestore', [ 'ngRoute' ]) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/backupRestore', { templateUrl : 'www/views/backup-restore.html', controller : 'BackupRestoreCtrl' }); }]) .factory("bkRestoreService", ['$resource', function($resource){ var service = {}; service.getBkStatus = function(){ return $resource('/api/dataset/imm_backup_status'); }; service.restBkConfigRequest = function(){ return $resource('/api/function'); }; service.restRestoreInformUploaded = function(){ return $resource('/api/providers/restore_upload'); }; service.restResetDefalt = function(){ return $resource('/api/dataset'); }; return service; }]) .controller('BackupRestoreCtrl', ['$scope', '$rootScope' ,'$localStorage','$location','uiUploader','bkRestoreService','$http', function($scope, $rootScope,$localStorage,$location,uiUploader,bkRestoreService,$http) { $scope.test = "I am on backup/restore page now"; $rootScope.loginInfo = angular.copy($localStorage.loginInfo); if(!$rootScope.loginInfo.loginStatus){ $location.path("/login"); }else{ console.log($scope.test); } $scope.showBkupConfigView = false; $scope.showRestoreView = false; $scope.showRestoreToDefaultView =false; //images $scope.arrow_right = "www/images/arrow_right.png"; $scope.arrow_down = "www/images/arrow_down.png"; $scope.toggleBackUpView = function(){ $scope.showBkupConfigView = ! $scope.showBkupConfigView; if($scope.showBkupConfigView){ $scope.showRestoreView = false; $scope.showRestoreToDefaultView = false; $scope.initStateMachine(); } }; $scope.toggleRestoreView = function(){ $scope.showRestoreView = ! $scope.showRestoreView; if($scope.showRestoreView){ $scope.showBkupConfigView = false; $scope.showRestoreToDefaultView =false; $scope.initStateMachine(); } }; $scope.toggleRestoreToDefaultView = function(){ $scope.showRestoreToDefaultView = ! $scope.showRestoreToDefaultView; if($scope.showRestoreToDefaultView){ $scope.showBkupConfigView = false; $scope.showRestoreView = false; } }; $scope.showArrowIcon = function(selectedFlag){ if(selectedFlag){ return $scope.arrow_right; }else{ return $scope.arrow_down; } }; //backup restore state machine $scope.bkupRestoreStateMachine={ highLightedImgUrl:"www/images/u116.png", nonHighLightedImgUrl:"www/images/u114.png", backLightedImgUrl:"www/images/u91.png" }; $scope.bkupRestoreStateMachine.step1={ stepFocused: true, imgurl : $scope.bkupRestoreStateMachine.highLightedImgUrl }; $scope.bkupRestoreStateMachine.step2={ stepFocused: false, imgurl : $scope.bkupRestoreStateMachine.nonHighLightedImgUrl }; $scope.bkupRestoreStateMachine.step3={ stepFocused: false, imgurl : $scope.bkupRestoreStateMachine.nonHighLightedImgUrl }; var activateStep = function(stepNum, flag){ if(stepNum == '1'){ if(flag == 'on'){ $scope.bkupRestoreStateMachine.step1.stepFocused = true; $scope.bkupRestoreStateMachine.step1.imgurl = $scope.bkupRestoreStateMachine.highLightedImgUrl; }else if(flag == 'off'){ $scope.bkupRestoreStateMachine.step1.stepFocused = false; $scope.bkupRestoreStateMachine.step1.imgurl = $scope.bkupRestoreStateMachine.nonHighLightedImgUrl; } }else if(stepNum == '2'){ if(flag == 'on'){ $scope.bkupRestoreStateMachine.step2.stepFocused = true; $scope.bkupRestoreStateMachine.step1.imgurl = $scope.bkupRestoreStateMachine.backLightedImgUrl; $scope.bkupRestoreStateMachine.step2.imgurl = $scope.bkupRestoreStateMachine.highLightedImgUrl; }else if(flag == 'off'){ $scope.bkupRestoreStateMachine.step2.stepFocused = false; $scope.bkupRestoreStateMachine.step2.imgurl = $scope.bkupRestoreStateMachine.nonHighLightedImgUrl; } }else if(stepNum == '3'){ if(flag == 'on'){ $scope.bkupRestoreStateMachine.step3.stepFocused = true; $scope.bkupRestoreStateMachine.step1.imgurl = $scope.bkupRestoreStateMachine.backLightedImgUrl; $scope.bkupRestoreStateMachine.step2.imgurl = $scope.bkupRestoreStateMachine.backLightedImgUrl; $scope.bkupRestoreStateMachine.step3.imgurl = $scope.bkupRestoreStateMachine.highLightedImgUrl; }else if(flag == 'off'){ $scope.bkupRestoreStateMachine.step3.stepFocused = false ; $scope.bkupRestoreStateMachine.step3.imgurl = $scope.bkupRestoreStateMachine.nonHighLightedImgUrl; } } }; $scope.initStateMachine = function(){ $scope.bkupRestoreStateMachine.step1={ stepFocused: true, imgurl: $scope.bkupRestoreStateMachine.highLightedImgUrl }; $scope.bkupRestoreStateMachine.step2={ stepFocused: false, imgurl: $scope.bkupRestoreStateMachine.nonHighLightedImgUrl }; $scope.bkupRestoreStateMachine.step3={ stepFocused: false, imgurl: $scope.bkupRestoreStateMachine.nonHighLightedImgUrl }; }; $scope.bkPasswdAlert = false; $scope.bkPasswdInconsistAlert = false; $scope.bkPasswdLenNotEnough = false; $scope.bkProgressBarFail = false; $scope.bkBusyFlag = false; var encrtValue = 0; $scope.encrtSwitch = function(){ if(document.getElementById("encrtWhole").checked){ encrtValue = 0; }else{ encrtValue = 1; } }; var bkStopClock = false; $scope.bkProgressBarFail = false; var waitDownloadBk = function(){ bkRestoreService.getBkStatus().get(function(data){ if(data["items"][0] == undefined){ $scope.bkProgressBarFail = true; bkStopClock = true; console.log("Failed to check backup progress status in waitDownloadBk."); }else{ if(data["items"][0].backup_status == 4 || data["items"][0].backup_status == 5){ $scope.bkProgressBarFail = true; bkStopClock = true; console.error("Backup fails."); }else if(data["items"][0].backup_status == 1){ if($scope.bkProgressBarValue < 90){ $scope.bkProgressBarValue = $scope.bkProgressBarValue + 10; }else{ $scope.bkProgressBarValue = 100; } }else if(data["items"][0].backup_status == 6){ $scope.bkProgressBarValue = 100; bkStopClock = true; console.log("Successfully backup, waiting to download"); } } }, function(err){ $scope.bkProgressBarFail = true; bkStopClock = true; console.error("Failed to get backup status in waitDownloadBk, error: " + err); }); }; var waitDownloadBkTimeout = function(){ if($scope.bkProgressBarValue < 100 || !bkStopClock){ setTimeout(waitDownloadBk(), 2000); } }; var bkupFile = ""; $scope.startBackUp = function(){ var bkSetPasswd = document.getElementById("bkSetPasswd").value; var bkConfirmPasswd = document.getElementById("bkConfirmPasswd").value; if(bkSetPasswd == "" || bkConfirmPasswd == ""){ $scope.bkPasswdInconsistAlert = false; $scope.bkPasswdAlert = true; }else if(bkSetPasswd.length < 9 || bkConfirmPasswd.length < 9){ $scope.bkPasswdInconsistAlert = false; $scope.bkPasswdAlert = true; }else{ if(bkSetPasswd != bkConfirmPasswd){ $scope.bkPasswdAlert = false; $scope.bkPasswdInconsistAlert = true; }else{ $scope.bkPasswdAlert = false; $scope.bkPasswdInconsistAlert = false; activateStep(1,'off'); activateStep(2,'on'); activateStep(3,'off'); $scope.bkProgressBarFail = false; $scope.bkProgressBarValue = 0; bkStopClock = false; $scope.bkBusyFlag = false; bkRestoreService.getBkStatus().get(function(data){ if(data["items"][0] == undefined){ console.log("IMM backup status returns error."); }else{ var bkStatus = data["items"][0].backup_status; if(bkStatus == 1 || bkStatus == 2){ $scope.bkBusyFlag = true; }else{ waitDownloadBkTimeout(); bkRestoreService.restBkConfigRequest().save({"IMM_CfgDoBackup":encrtValue+","+bkSetPasswd}, (function(data){ if(data.return != 0){ $scope.bkProgressBarFail = true; bkStopClock = true; console.error("Failed to backup the imm configuration."); }else{ bkupFile = data['FileName']; console.log("Successfully send backup configuration request."); activateStep(1,'off'); activateStep(2,'off'); activateStep(3,'on'); } }), (function(err){ $scope.bkProgressBarFail = true; bkStopClock = true; console.error("Failed to post backup configuration request, error: "+err); })); } } }, function(err){ $scope.bkProgressBarFail = true; bkStopClock = true; console.error("Failed to get backup status, error: " + err); }); } } }; $scope.cancelBkDownload = function(){ activateStep(1,'on'); activateStep(2,'off'); activateStep(3,'off'); }; $scope.bkupDownload = function(){ window.open("download/"+bkupFile); }; $scope.backUpFile = ""; angular.element(document.getElementById("backupFileInput")).ready(function(){ bindFileInput(); }); var bindFileInput = function() { var element = document.getElementById("backupFileInput"); element.addEventListener('change', function(e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); $scope.backUpFile = uiUploader.getFiles()[0].name; $scope.$apply(); }); element = null; }; $scope.restoreSelectFileAlert = false; $scope.restorePasswdAlert = false; $scope.restoreUploadFailAlert = false; $scope.restoreNotifyUploadedAlert = false; $scope.restoreGetContentsAlert = false; var restorePasswd = ""; $scope.restoreVerifyFunct = function(){ var restoreFileName = document.getElementById('restoreSelectedFile').value; restorePasswd = document.getElementById("restorePasswd").value; if( restoreFileName == ""){ $scope.restoreSelectFileAlert = true; $scope.restorePasswdAlert = false; activateStep(1,'on'); activateStep(2,'off'); activateStep(3,'off'); }else if(restorePasswd == ""){ $scope.restoreSelectFileAlert = false; $scope.restorePasswdAlert = true; activateStep(1,'on'); activateStep(2,'off'); activateStep(3,'off'); }else{ activateStep(1,'off'); activateStep(2,'on'); activateStep(3,'off'); $scope.restoreSelectFileAlert = false; $scope.restorePasswdAlert = false; $scope.restoreUploadFailAlert = false; $scope.restoreNotifyUploadedAlert = false; $scope.restoreGetContentsAlert = false; $http({ method: 'POST', url: '/upload?X-Progress-ID='+(new Date()).valueOf(), headers: { 'Content-Type': undefined }, transformRequest: function() { var formData = new FormData(); formData.append(document.getElementById('backupFileInput').files[0].name, document.getElementById('backupFileInput').files[0]); return formData; } }).success(function(data){ console.log("Successfully uploaded restore file."); var uploadedRestoreFileRes = data['items'][0].path; bkRestoreService.restRestoreInformUploaded().save({"FileName":uploadedRestoreFileRes}, (function(data){ if(data.return != 0){ $scope.restoreNotifyUploadedAlert = true; console.error("Failed to notify the uploaded restore file, error: "+data.return); }else{ console.log("Successfully send the notify restore file uploaded request."); bkRestoreService.restBkConfigRequest().save({"IMM_CfgReturnUploadFileContents":restorePasswd}, (function(data){ if(data.PreviewUploadContent == undefined){ $scope.restoreGetContentsAlert = true; console.error("Failed to get the uploaded restore file contents."); }else{ console.log("Successfully get the uploaded restore file contents."); } }), (function(err){ $scope.restoreGetContentsAlert = true; console.error("Failed to send the request getting the uploaded file contents, error: "+err); })); } }), (function(err){ $scope.restoreNotifyUploadedAlert = true; console.error("Failed to post the notification request of uploaded restore file, error: "+err); })); }).error(function(err){ $scope.restoreUploadFailAlert = true; console.error("Failed to post /upload restore file request, error: "+err); }); } }; var restoreStopClock = false; $scope.restoreProgressBarFail = false; var getRestoreProgress = function(){ bkRestoreService.getBkStatus().get(function(data){ if(data["items"][0] == undefined){ $scope.restoreProgressBarFail = true; restoreStopClock = true; console.log("Failed to check the restore progress status in getRestoreProgress."); }else{ var restoreStatus = data["items"][0].restore_status; if(restoreStatus == 4 || restoreStatus == 5 || restoreStatus == 8){ $scope.restoreProgressBarFail = true; restoreStopClock = true; console.error("Restore fails."); }else if(data["items"][0].restore_status == 1){ if($scope.restoreProgressBarValue < 90){ $scope.restoreProgressBarValue = $scope.restoreProgressBarValue + 10; }else{ $scope.restoreProgressBarValue = 100; } }else if(data["items"][0].backup_status == 3){ $scope.restoreProgressBarValue = 100; restoreStopClock = true; console.log("Successfully restored"); } } }, function(err){ $scope.restoreProgressBarFail = true; restoreStopClock = true; console.error("Failed to get the restore status, error: " + err); }); }; var getRestoreProgressTimeout = function(){ if($scope.restoreProgressBarValue < 100 || !restoreStopClock){ setTimeout(getRestoreProgress(), 2000); } }; $scope.toRestore = function(){ if($scope.restoreUploadFailAlert || $scope.restoreNotifyUploadedAlert || $scope.restoreGetContentsAlert){ activateStep(1,'off'); activateStep(2,'on'); activateStep(3,'off'); }else{ activateStep(1,'off'); activateStep(2,'off'); activateStep(3,'on'); $scope.restoreProgressBarValue = 0; getRestoreProgressTimeout(); bkRestoreService.restBkConfigRequest().save({"IMM_CfgDoUploadFileRestore":restorePasswd}, (function(data){ if(data.return != 0){ restoreStopClock = true; $scope.restoreProgressBarFail = true; console.error("Failed to do file restore, error: "+data.return); }else{ console.log("Successfully send the restore request."); } }), (function(err){ restoreStopClock = true; $scope.restoreProgressBarFail = true; console.error("Failed to send the request doing file restore, error: "+err); })); } }; $scope.startToResetDefault = function(){ $("#resetIMMDefaultModal").modal().css({ "margin-top": "180px" }); }; $scope.resetDefalt = function(){ bkRestoreService.restResetDefalt().save({"CFG_ResetToFactoryDef":"1"}, (function(){ console.log("Imm reset to factory default."); }), (function(){ })); }; $scope.$on('$viewContentLoaded', function() { setTimeout(function() { $scope.$emit('clickMenuItem1', 'menuTitleBackupRestore'); $scope.$apply(); }, 100); }); }]);<file_sep>'use strict'; angular.module('myApp.network', [ 'ngRoute' , 'imm3.network.service']) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/network', { templateUrl : 'www/views/network.html', }); } ]) .controller('NetworkCtrl', ['$scope','$rootScope','$localStorage','$location', 'networkService', function($scope, $rootScope,$localStorage,$location, networkService) { $rootScope.loginInfo = angular.copy($localStorage.loginInfo); if(!$rootScope.loginInfo.loginStatus){ $location.path("/login"); }else{ console.log("I am in network page"); } console.log("tier is :"+$localStorage.tier); $scope.tier = $localStorage.tier; var numberToBoolean = function(obj, attrs){ angular.forEach(attrs, function(attr, index){ obj[attr] = !!obj[attr]; }); } var objEquals = function(obj0,obj){ //if ((obj0===obj)){return true;} //if (!(obj instanceof Object) || (obj===null)){ // return false;} // null is not instanceof Object. //var i = 0; // object property counter. //for (var k in obj0){ // i++; // var o1 = obj0[k]; // var o2 = obj[k]; // if ((o1!=null) && !(objEquals(o1, o2))) // { // return false; // } // inner object. //} // return true; return JSON.stringify(obj0) == JSON.stringify(obj); }; var restGetEthernetInfo = networkService.restGetEthernetInfo(); var restSetEthernet = networkService.restSetEthernet(); var restGetDNS = networkService.restGetDNS(); var restGetDDNS = networkService.restGetDDNS(); var restSetDNS = networkService.restSetDNS(); var restSetDDNS = networkService.restSetDDNS(); var restGetEthOverUsb = networkService.restGetEthOverUsb(); var restSetEthUsb = networkService.restSetEthUsb(); var restAddEthUsb = networkService.restAddEthUsb(); var restRemoveEth = networkService.restRemoveEth(); var restGetPortAssignment = networkService.restGetPortAssignment(); var restSetPortAssign = networkService.restSetPortAssign(); var restGetBlockList = networkService.restGetBlockList(); var restSetBlock = networkService.restSetBlock(); var restGetFpUsb = networkService.restGetFpUsb(); var restSetFpUsb = networkService.restSetFpUsb(); var restGetIpmi = networkService.restGetIpmi(); var restSetIpmi = networkService.restSetIpmi(); $scope.OriginImm_ethernet = {}; $scope.imm_ethernet = {}; restGetEthernetInfo.get(function(data){ $scope.imm_ethernet = data['items'][0]; $scope.imm_ethernet.eth_mac_select = $scope.imm_ethernet.eth_mac_select+''; var attrs = ['ipv4_enabled', 'ipv6_enabled','ipv6_use_stateful_address','ipv6_use_stateless_address','ipv6_use_static_address','eth_vlan_enabled']; numberToBoolean($scope.imm_ethernet, attrs); $scope.imm_ethernet.ipv4_address_source = $scope.imm_ethernet.ipv4_address_source + ''; $scope.imm_ethernet.eth_auto_negotiate = $scope.imm_ethernet.eth_auto_negotiate + ''; $scope.ipV6AddrForEdit = $scope.imm_ethernet.ipv6_static_address; $scope.ipV6PreLenghForEdit = $scope.imm_ethernet.ipv6_static_prefix_length; $scope.ipV6GateForEdit = $scope.imm_ethernet.ipv6_static_gateway_address; $scope.OriginImm_ethernet = angular.copy($scope.imm_ethernet); console.log("is equal:"+ objEquals($scope.OriginImm_ethernet,$scope.imm_ethernet)); }); restGetDNS.get(function(data){ $scope.imm_DNS = data['items'][0]; $scope.imm_DNS.dns_preferred_type += ''; var attrs = ['dns_use_additional']; numberToBoolean($scope.imm_DNS, attrs); if($scope.imm_DNS.dns_preferred_type == 1){ $scope.showV4DNS = true; }else{ $scope.showV4DNS = false; } $scope.originDns = angular.copy($scope.imm_DNS); }); restGetDDNS.get(function(data){ $scope.imm_DDNS = data['items'][0]; var attrs = ['ddns_enabled']; numberToBoolean($scope.imm_DDNS, attrs); $scope.imm_DDNS.ddns_mode += ''; $scope.originDDNS = angular.copy($scope.imm_DDNS); }); var getEthOverUsb = function(){ restGetEthOverUsb.get(function(data){ $scope.ethOverUsb = data['items'][0]; $scope.indexList = [1,2,3,4,5,6,7,8,9,10,11]; var attrs = ['usb_eth_over_usb_enabled','lan_over_usb_enabled','usb_eth_to_eth_enabled']; numberToBoolean($scope.ethOverUsb, attrs); for(var i=0; i<$scope.ethOverUsb.usb_mapped_ports.length;i++ ){ if($scope.ethOverUsb.usb_mapped_ports[i].eth_port!=0 || $scope.ethOverUsb.usb_mapped_ports[i].ext_port!=0){ $scope.indexList.remove($scope.ethOverUsb.usb_mapped_ports[i].id); } } $scope.selectedId = $scope.indexList[0]+''; $scope.originEthUsb = angular.copy($scope.ethOverUsb); console.log("when you get data, and after angular copy:"+ JSON.stringify($scope.originEthUsb)); }); } getEthOverUsb(); $scope.addPort = function(){ console.log($scope.addPort_eth + ' '+ $scope.addPort_ext + ' '+ $scope.selectedId); var payLoad = {"USB_AddMapping": ''+$scope.selectedId+','+$scope.addPort_ext+','+$scope.addPort_eth}; restAddEthUsb.save({},payLoad, function(data){ if(data.return == 0){ getEthOverUsb(); }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } }); } $scope.deletePort = function(id){ restRemoveEth.save({},{"USB_RemoveMapping": id+''},function(data){ if(data.return == 0){ getEthOverUsb(); }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } }); } restGetIpmi.get(function(data){ $scope.ipmi_enabled = !!data['items'][0]['ipmi_enabled']; $scope.ori_ipmi_enabled = $scope.ipmi_enabled; }); restGetPortAssignment.get(function(data){ $scope.portAssign = data['items'][0]; $scope.originPortAssign = angular.copy($scope.portAssign); }); restGetBlockList.get({params:"Net_GetAccessControl"}, function(data){ $scope.blockList = {}; $scope.blockList = data['items'][0]; console.log("***type of date:"+$scope.blockList.begin_time_date); if($scope.blockList.begin_time_date != ""){ var beginDate = $scope.blockList.begin_time_date.split('-'); $scope.blockList.begin_time_date = beginDate[1] + '/' +beginDate[2] + '/' + beginDate[0]; } if($scope.blockList.end_time_date != ""){ var endDate = $scope.blockList.end_time_date.split('-'); $scope.blockList.end_time_date = endDate[1] + '/' +endDate[2] + '/' + endDate[0]; } $scope.originBlockList = angular.copy($scope.blockList); }); restGetFpUsb.get(function(data){ $scope.fpUsb = data; switch(data.owner) { case 0: $scope.selectedValue = 'hostOnlyMode'; break; case 1: $scope.selectedValue = 'IMMOnlyMode'; break; case 2: $scope.selectedValue = 'sharedModeOwnedByIMM'; break; case 3: $scope.selectedValue = 'sharedModeOwnedByHost'; break; default: } $scope.currentStatus = $scope.selectedValue; $scope.fpUsb.enableIDButton = !!$scope.fpUsb.enableIDButton; $scope.originFpUsb = angular.copy($scope.fpUsb); }); //$scope.isObjectValueEqual = function(a, b){ // return a.equals(b); //} $scope.testIpV4 = "aaa"; $scope.test = "Network"; $scope.$emit('setCurPage1', ["Netowrk"]); $scope.$emit('setMenuItemClass1', 'menuTitleNetwork'); var original_ipsetting_hostname = "IMM2-40f2e9af0d7d"; var original_ipsetting_ipv4_address = "10.240.210.219"; var original_psetting_ipv4_netmask = "255.255.255.0"; var original_ipsetting_ipv4_default_gateway = "10.240.210.1"; var original_ipsetting_ipv6_ip = "FE80::4242:99FF:FEFE:EA55"; var original_ipsetting_ipv6_prefix = "64"; var original_ipsetting_advanced_vlan_id = "1234"; var original_ipsetting_advanced_mac_address = "6c:ae:8b:4e:83:c6"; var original_ipsetting_advanced_data_rate = 10; var original_max_transmission_unit = 1500; var original_ipsetting_advanced_duplex = "Full"; var original_show_advanced_ethernet = false; var original_show_ipv6_configure_table = false; var original_show_configure_ipv6_title = false; var original_show_apply_button = false; var original_ipsetting_ipv4_state = "enabled"; var original_ipsetting_ipv6_state = "disabled"; var original_ipsetting_ipv4_method = "Use static IP address"; var original_ipsetting_enable_vlan = false; var original_ipsetting_use_stateless_addr_config = false; var original_ipsetting_use_stateful_addr_config = false; var orginal_ipsetting_use_static_assigned_ip_addr_config = false; var original_ipsetting_mac_address_method = "Use burned-in MAC address"; var original_dns_domain_name_method="Use custom domain name"; var original_ipsetting_data_rate_and_duplex = "auto-configure"; var submit_success=false; var submit_dns_success = false; var original_ipsetting_ipv6_gateway = ""; var orignal_dns_domain_name_method = "Use domain name obtained from the DHCP server"; var original_additional_dns_addr_servers_1 = ""; var original_additional_dns_addr_servers_2 = ""; var original_additional_dns_addr_servers_3 = ""; var original_ddns_domain_name = ""; var oringial_ddns_enable_disable = "disabled"; var original_prefer_addr_type = "ipv4"; $scope.showExternalEthernetOverUsbTable=false; $scope.showDomainNameEdit = false; $scope.showAdditionalDns = false; $scope.show_dns_setting_apply_button = false; $scope.showStaticIpAddrInput = false; $scope.ipsetting_hostname = original_ipsetting_hostname; $scope.ipsetting_ipv4_state = original_ipsetting_ipv4_state; $scope.ipsetting_ipv6_state = original_ipsetting_ipv6_state; $scope.ipsetting_ipv4_method = original_ipsetting_ipv4_method; $scope.ipsetting_ipv4_address=original_ipsetting_ipv4_address; $scope.ipsetting_ipv4_netmask=original_psetting_ipv4_netmask; $scope.ipsetting_ipv4_default_gateway=original_ipsetting_ipv4_default_gateway; $scope.ipsetting_ipv6_ip=original_ipsetting_ipv6_ip; $scope.ipsetting_ipv6_prefix=original_ipsetting_ipv6_prefix; $scope.ipsetting_advanced_vlan_id=original_ipsetting_advanced_vlan_id; $scope.ipsetting_advanced_mac_address=original_ipsetting_advanced_mac_address; $scope.show_apply_button = original_show_apply_button; $scope.ipsetting_enable_vlan = original_ipsetting_enable_vlan; $scope.ipsetting_use_stateless_addr_config = original_ipsetting_use_stateless_addr_config; $scope.ipsetting_use_stateful_addr_config = original_ipsetting_use_stateful_addr_config; $scope.ipsetting_use_static_assigned_ip_addr_config = orginal_ipsetting_use_static_assigned_ip_addr_config; $scope.ipsetting_mac_address_method = original_ipsetting_mac_address_method; $scope.dns_domain_name_method = original_dns_domain_name_method; $scope.ipsetting_data_rate_and_duplex = original_ipsetting_data_rate_and_duplex; $scope.ipsetting_max_transmission_unit = original_max_transmission_unit; $scope.ipsetting_ipv6_gateway = original_ipsetting_ipv6_gateway; $scope.additional_dns_addr_servers_1 = original_additional_dns_addr_servers_1; $scope.additional_dns_addr_servers_2 = original_additional_dns_addr_servers_2; $scope.additional_dns_addr_servers_3 = original_additional_dns_addr_servers_3; $scope.ddns_domain_name = original_ddns_domain_name $scope.ddns_enable_disable = oringial_ddns_enable_disable; $scope.prefer_addr_type = original_prefer_addr_type; $scope.ipsetting_ipv4_method_select = {}; $scope.ipsetting_ipv4_method_select.map = { "1":"Obtain IP from DHCP", "2":"First DHCP, then static IP address" }; $scope.ipsetting_ipv4_method_select.value = "Obtain IP from DHCP"; $scope.ipsetting_mac_address_method_select = {}; $scope.ipsetting_mac_address_method_select.map = { "0":"Use burned-in MAC address", "1":"Use custom MAC address", }; $scope.ipsetting_mac_address_method_select.value = "Use burned-in MAC address"; $scope.dns_domain_name_method_select = {}; $scope.dns_domain_name_method_select.map = { "2":"Use custom domain name", "1":"Use domain name obtained from the DHCP server" }; $scope.dns_domain_name_method_select.value = "Use domain name obtained from the DHCP server"; $scope.dns_domain_name_method = orignal_dns_domain_name_method; $scope.select_domain_name_method_change = function(){ $scope.dns_domain_name_method = $("#domain_name_method").val(); if($scope.dns_domain_name_method == "Use custom domain name") { $scope.showDomainNameEdit = true; } else { $scope.showDomainNameEdit = false; } $scope.onDnsInputChange(); }; $scope.testModel = function(){ console.log($scope.imm_ethernet.hostname); } $scope.selectPreferAddrType = function(type){ if(type == 'ipv4'){ $scope.showV4DNS = true; $scope.imm_DNS.dns_preferred_type = 1; }else { $scope.showV4DNS = false; $scope.imm_DNS.dns_preferred_type = 2; } } $scope.onDnsInputChange = function(){ if(document.getElementById("ddns_enable_disable").checked) { $scope.ddns_enable_disable = "enabled"; } else { $scope.ddns_enable_disable = "disabled"; } if( $scope.prefer_addr_type != original_prefer_addr_type || $scope.ddns_domain_name != original_ddns_domain_name || $scope.ddns_enable_disable != oringial_ddns_enable_disable || $scope.dns_domain_name_method != orignal_dns_domain_name_method || $scope.additional_dns_addr_servers_1 != original_additional_dns_addr_servers_1 || $scope.additional_dns_addr_servers_2 != original_additional_dns_addr_servers_2 || $scope.additional_dns_addr_servers_3 != original_additional_dns_addr_servers_3) { $scope.show_dns_setting_apply_button = true; $("#dns_setting_table").removeClass("network_background_table"); $("#dns_setting_table").addClass("network_background_highlight_table"); $("#showDnsDdnsApplyRestButton").show(); } if(submit_dns_success){ $("#dns_setting_table").removeClass("network_background_highlight_table"); $("#dns_setting_table").addClass("network_background_table"); $scope.show_dns_setting_apply_button = false; $("#showDnsDdnsApplyRestButton").hide(); } }; $scope.confirm_dns_setting = function(){ $("#confirmDnsDdns").modal(); } $scope.submit_dns_ddns_setting = function(){ submit_dns_success = true; var dnsLoad = { "DNS_PreferredType": $scope.imm_DNS.dns_preferred_type + '', "DNS_UseAdditional": $scope.imm_DNS.dns_use_additional*1 + '', "DNS_IPv4Server_1": $scope.imm_DNS.dns_ipv4_primary, "DNS_IPv4Server_2": $scope.imm_DNS.dns_ipv4_secondary, "DNS_IPv4Server_3": $scope.imm_DNS.dns_ipv4_tertiary, "DNS_IPv6Server_1": $scope.imm_DNS.dns_ipv6_primary, "DNS_IPv6Server_2": $scope.imm_DNS.dns_ipv6_secondary, "DNS_IPv6Server_3": $scope.imm_DNS.dns_ipv6_tertiary, }; var ddnsLoad = { "DDNS_Ena": $scope.imm_DDNS.ddns_enabled*1 + '', "DDNS_Mode": $scope.imm_DDNS.ddns_mode + '' }; restSetDNS.save({}, dnsLoad, function(data){ if(data.return == 0){ restSetDDNS.save({}, ddnsLoad, function(ddnsData){ if(ddnsData.return == 0){ $scope.originDns = angular.copy($scope.imm_DNS); $scope.originDDNS = angular.copy($scope.imm_DDNS); $scope.$emit('showErrMsgBox', "Saved successfully!"); }else{ $scope.$emit('showErrMsgBox', "DDNS error:"+ddnsData.return); } }, function(error){ $scope.$emit('showErrMsgBox', "DDNS error:"+JSON.stringify(error)); }); }else{ $scope.$emit('showErrMsgBox', "DNS error:"+data.return); } }, function(error){ $scope.$emit('showErrMsgBox', "DNS error:"+JSON.stringify(error)); }); } $scope.reset_dns_setting = function(){ $scope.imm_DNS = angular.copy($scope.originDns); $scope.imm_DDNS = angular.copy($scope.originDDNS); } $scope.useAdditonalDnsAddrServers = function(){ $scope.showAdditionalDns = !$scope.showAdditionalDns; } $scope.ipsetting_advanced_data_rate=function(){ return original_ipsetting_advanced_data_rate; }; $scope.max_transmission_unit=function(){ return original_max_transmission_unit; }; $scope.ipsetting_advanced_duplex=function(){ return original_ipsetting_advanced_duplex; }; $scope.show_advanced_ethernet=original_show_advanced_ethernet; $scope.show_ipv6_configure_table = original_show_ipv6_configure_table; $scope.show_configure_ipv6_title = original_show_configure_ipv6_title; $scope.show_advanced_ethernet_setting=function(){ $scope.show_advanced_ethernet = !$scope.show_advanced_ethernet; if($scope.show_advanced_ethernet) { $("#arrow_img").attr("src", "www/images/arrow_down.png"); } else { $("#arrow_img").attr("src", "www/images/arrow_right.png"); } } //$scope.show_configure_ipv6_details = function(){ // if(document.getElementById("ipv6enable_disable").checked) // { // $scope.show_configure_ipv6_title = true; // $scope.show_ipv6_configure_table = false; // } // else // { // $scope.show_configure_ipv6_title = false; // $scope.show_ipv6_configure_table = false; // } // $scope.onInputChange(); // //} $scope.show_ipv6_configure = function(){ $scope.show_ipv6_configure_table = !$scope.show_ipv6_configure_table; } $scope.applyEthernet = function(){ console.log("test ip:"+$scope.testIpV4); console.log("data in apply:"+$scope.imm_ethernet.hostname); var macAddress = $scope.imm_ethernet.eth_mac_select == '0'?$scope.imm_ethernet.eth_burned_mac_address:$scope.imm_ethernet.eth_mac_address; if(typeof $scope.imm_ethernet.eth_auto_negotiate == 'boolean'){ $scope.imm_ethernet.eth_auto_negotiate = $scope.imm_ethernet.eth_auto_negotiate*1; }else { $scope.imm_ethernet.eth_auto_negotiate == parseInt($scope.imm_ethernet.eth_auto_negotiate); } var payLoad = { "IMM_HostName": $scope.imm_ethernet.hostname, "ENET_IPv4Ena": $scope.imm_ethernet.ipv4_enabled*1 + '', "ENET_IPv4AddrSource": $scope.imm_ethernet.ipv4_address_source + '', "ENET_IPv4StaticIPAddr": $scope.imm_ethernet.ipv4_address, "ENET_IPv4StaticIPNetMask": $scope.imm_ethernet.ipv4_subnet_mask, "ENET_IPv4GatewayIPAddr": $scope.imm_ethernet.ipv4_gateway, "ENET_IPv6Ena": $scope.imm_ethernet.ipv6_enabled*1 + '', "ENET_IPv6StatelessConfigEna": $scope.imm_ethernet.ipv6_use_stateless_address*1 + '', "ENET_IPv6StatefulConfigEna": $scope.imm_ethernet.ipv6_use_stateful_address*1 + '', "ENET_IPv6StaticIPEna": $scope.imm_ethernet.ipv6_use_static_address*1 + '', "ENET_IPv6StaticIPAddr": $scope.ipV6AddrForEdit, "ENET_IPv6StaticIPPrefixLen": $scope.ipV6PreLenghForEdit + '', "ENET_IPv6GatewayIPAddr": $scope.ipV6GateForEdit, "ENET_AutoNegotiate": $scope.imm_ethernet.eth_auto_negotiate + '', "ENET_DataRate": $scope.imm_ethernet.eth_data_rate + '', "ENET_Duplex": $scope.imm_ethernet.eth_duplex + '', "ENET_VlanEnabled": $scope.imm_ethernet.eth_vlan_enabled*1 + '', "ENET_VlanId": $scope.imm_ethernet.eth_vlan_id + '', "ENET_MACAddrSelect": $scope.imm_ethernet.eth_mac_select + '', "ENET_MACAddr": macAddress, "ENET_MTU": $scope.imm_ethernet.eth_mtu + '' }; restSetEthernet.save({},payLoad,function(data){ if(data['return'] == 0){ $scope.OriginImm_ethernet = angular.copy($scope.imm_ethernet); $scope.$emit('showErrMsgBox', "Saved successfully!"); } }, function(error){ $scope.$emit('showErrMsgBox', JSON.stringify(error)); }); } $scope.reset_ipsetting=function(){ $scope.imm_ethernet = angular.copy($scope.OriginImm_ethernet); } $scope.submit_ipsetting=function(){ submit_success = true; $scope.onInputChange(); } $scope.switchUsb = function(){ var owner = ''; switch($scope.selectedValue) { case 'hostOnlyMode': owner = 0; break; case 'IMMOnlyMode': owner = 1; break; case 'sharedModeOwnedByIMM': owner = 2; break; case 'sharedModeOwnedByHost': owner = 3; break; default: } var payLoad = { "owner": owner, "timeout": $scope.fpUsb.timeout, "enableIDButton": $scope.fpUsb.enableIDButton * 1, "hysteresis": $scope.fpUsb.hysteresis }; restSetFpUsb.save({},payLoad, function(data){ if(data.return == 0){ $scope.originFpUsb = angular.copy($scope.fpUsb); $scope.currentStatus = $scope.selectedValue; $scope.$emit('showErrMsgBox', "Saved successfully!"); }else{ $scope.$emit('showErrMsgBox', "eror:"+ data.return); } }, function(error){ $scope.$emit('showErrMsgBox', JSON.stringify(error)); }); } $scope.$on('$viewContentLoaded', function() { $scope.$emit('clickMenuItem1', 'menuTitleNetwork'); }); $("#ipv4_method").on("change", function(){ $scope.ipsetting_ipv4_method = $("#ipv4_method").val(); $scope.onInputChange(); }); $scope.select_ipv4_method_change = function(){ $scope.ipsetting_ipv4_method = $("#ipv4_method").val(); $scope.onInputChange(); } $scope.select_mac_address_change = function(){ $scope.ipsetting_mac_address_method = $scope.ipsetting_mac_address_method_select.value; $scope.onInputChange(); } $scope.onShowStaticalIpAddrInput = function(){ if(document.getElementById("use_static_assigned_ip_addr").checked){ //$scope.ipsetting_use_static_assigned_ip_addr_config = true; $scope.showStaticIpAddrInput = true; } else { //$scope.ipsetting_use_static_assigned_ip_addr_config = false; $scope.showStaticIpAddrInput = false; } } $scope.highlightHelpPic = function(paraId){ $("#" + paraId).attr("src", "www/images/help_focus.png"); } $scope.unHighlightHelpPic = function(paraId){ $("#" + paraId).attr("src", "www/images/help.png"); } $scope.ipv6_setting_details = [ { id:0, name:"Link local IP", value:"FE80::4242:99FF:FEFE:EA55", prefix:"64" }, { id:1, name:"Stateless IP", value:"FE80::4242:99FF:FEFE:EA55", prefix:"64" }, { id:2, name:"Stateful IP", value:"2002:97b:c242:99FF:FEFE:EA55", prefix:"64" }, { id:3, name:"Static IP", value:"2002:97b:c242:99FF:FEFE:EA55", prefix:"64" } ]; $scope.applyIPMI = function(){ var payLoad = { "IPMI_Ena": $scope.ipmi_enabled * 1 + '' }; restSetIpmi.save({},payLoad, function(data){ if(data.return == 0){ $scope.ori_ipmi_enabled = $scope.ipmi_enabled; $scope.$emit('showErrMsgBox', "Saved successfully!"); } }); } $scope.resetIPMI = function(){ $scope.ipmi_enabled = $scope.ori_ipmi_enabled; } //$scope.onInputChange = function(){ // if(document.getElementById("ipv4enable_disable").checked) // { // $scope.ipsetting_ipv4_state = "enabled"; // } // else // { // $scope.ipsetting_ipv4_state = "disabled"; // } // // if(document.getElementById("enable_vlan").checked){ // $scope.ipsetting_enable_vlan = true; // } // else // { // $scope.ipsetting_enable_vlan = false; // } // // if(document.getElementById("use_stateless_addr_config").checked){ // $scope.ipsetting_use_stateless_addr_config = true; // } // else // { // $scope.ipsetting_use_stateless_addr_config = false; // } // // if(document.getElementById("use_stateful_addr_config").checked){ // $scope.ipsetting_use_stateful_addr_config = true; // } // else // { // $scope.ipsetting_use_stateful_addr_config = false; // } // // if(document.getElementById("data_rate_duplex_auto_config").checked) // { // $scope.ipsetting_data_rate_and_duplex = "auto-configure"; // } // else // { // $scope.ipsetting_data_rate_and_duplex = "custom"; // } // // if(document.getElementById("data_rate_duplex_custome").checked) // { // $scope.ipsetting_data_rate_and_duplex = "custom"; // } // else // { // $scope.ipsetting_data_rate_and_duplex = "auto-configure"; // } // // $scope.ipsetting_max_transmission_unit = $("#max_transmission_unit").val(); // // if($scope.ipsetting_hostname != original_ipsetting_hostname // || $scope.ipsetting_ipv4_address != original_ipsetting_ipv4_address // || $scope.ipsetting_ipv4_netmask != original_psetting_ipv4_netmask // || $scope.ipsetting_ipv4_default_gateway != original_ipsetting_ipv4_default_gateway // || $scope.ipsetting_ipv6_ip != original_ipsetting_ipv6_ip // || $scope.ipsetting_ipv6_prefix != original_ipsetting_ipv6_prefix // || $scope.ipsetting_advanced_vlan_id != original_ipsetting_advanced_vlan_id // || $scope.ipsetting_advanced_mac_address != original_ipsetting_advanced_mac_address // || $scope.ipsetting_ipv4_state != original_ipsetting_ipv4_state // || $scope.ipsetting_ipv6_state != original_ipsetting_ipv6_state // || $scope.ipsetting_ipv4_method != original_ipsetting_ipv4_method // || $scope.ipsetting_enable_vlan != original_ipsetting_enable_vlan // || $scope.ipsetting_mac_address_method != original_ipsetting_mac_address_method // || $scope.ipsetting_data_rate_and_duplex != original_ipsetting_data_rate_and_duplex // || $scope.ipsetting_max_transmission_unit != original_max_transmission_unit // || $scope.ipsetting_use_stateless_addr_config != original_ipsetting_use_stateless_addr_config // || $scope.ipsetting_use_stateful_addr_config != original_ipsetting_use_stateful_addr_config // || $scope.ipsetting_use_static_assigned_ip_addr_config != orginal_ipsetting_use_static_assigned_ip_addr_config // || $scope.ipsetting_ipv6_gateway != original_ipsetting_ipv6_gateway // ){ // $scope.show_apply_button = true; // $("#ethernet_setting_table").removeClass("network_background_table"); // $("#ethernet_setting_table").addClass("network_background_highlight_table"); // $("#show_apply_reset_button").show(); // } // // if(submit_success){ // $("#ethernet_setting_table").removeClass("network_background_highlight_table"); // $("#ethernet_setting_table").addClass("network_background_table"); // $scope.show_apply_button = false; // $("#show_apply_reset_button").hide(); // } // //} $scope.showExternalEthernetOverUsbSetting = function(){ if(document.getElementById("enableExternalEthernet").checked) { $scope.showExternalEthernetOverUsbTable=true; } else { $scope.showExternalEthernetOverUsbTable=false; } } var original_imm_ip_addr = ""; var original_os_ip_addr = ""; var original_network_mask = ""; var original_ipv6_link_local_addr = ""; var original_ethernet_over_usb_state = "enabled"; $scope.imm_ip_addr = original_imm_ip_addr; $scope.os_ip_addr = original_os_ip_addr; $scope.network_mask = original_network_mask; $scope.ipv6_link_local_addr = original_ipv6_link_local_addr; $scope.ethernet_over_usb_state = original_ethernet_over_usb_state; $scope.showExternalEthernetOverUsbApplyRestButton = false; $scope.externalEthernetOverUsbTableRows = 1; $scope.getNumber = function(num) { return new Array(num); } $scope.dynamicAddRow = function() { $scope.externalEthernetOverUsbTableRows = $scope.externalEthernetOverUsbTableRows + 1; } $scope.dynamicDeleteRow = function() { if($scope.externalEthernetOverUsbTableRows > 1){ $scope.externalEthernetOverUsbTableRows--; } } $scope.onExternalEthernetOverUsbChange = function(){ if(document.getElementById("ethernet_over_usb_enable_disable").checked) { $scope.ethernet_over_usb_state = "enabled"; } else { $scope.ethernet_over_usb_state = "disabled"; } if($scope.imm_ip_addr != original_imm_ip_addr || $scope.os_ip_addr != original_os_ip_addr || $scope.network_mask != original_network_mask || $scope.ipv6_link_local_addr != original_ipv6_link_local_addr || $scope.ethernet_over_usb_state != original_ethernet_over_usb_state) { $scope.showExternalEthernetOverUsbApplyRestButton = true; $("#ethernet_over_usb_setting_table").removeClass("network_background_table"); $("#ethernet_over_usb_setting_table").addClass("network_background_highlight_table"); $("#showExternalEthernetOverUsbApplyRestButton").show(); } if(submit_success){ $("#ethernet_over_usb_setting_table").removeClass("network_background_highlight_table"); $("#ethernet_over_usb_setting_table").addClass("network_background_table"); $scope.showExternalEthernetOverUsbApplyRestButton = false; $("#showExternalEthernetOverUsbApplyRestButton").hide(); } } $scope.reset_ext_ethernet_over_usb_setting = function(){ $scope.ethOverUsb = angular.copy($scope.originEthUsb); } $scope.confirm_ext_ethernet_over_usb_setting = function(){ $("#confirmEthernetOverUsb").modal(); } $scope.submit_ethernet_over_usb_setting = function(){ console.log("test Ip:"+$scope.testIpV4); console.log("IP V4 Address:"+$scope.ethOverUsb.lan_over_usb_ipv4_address); var payLoad = { "USB_EthOverUsbEna": $scope.ethOverUsb.usb_eth_over_usb_enabled*1 + '', "USB_PortForwardEna": $scope.ethOverUsb.usb_eth_to_eth_enabled*1 + '', "USB_IPChangeEna": 0 + '', "USB_LANOverUSBIPv4IPAddr": $scope.ethOverUsb.lan_over_usb_ipv4_address, "USB_OSLANOverUSBIPv4IPAddr": $scope.ethOverUsb.os_lan_over_usb_ipv4_address, "USB_LANOverUSBIPv4IPNetMask": $scope.ethOverUsb.lan_over_usb_ipv4_subnet_marks }; restSetEthUsb.save({}, payLoad, function(data){ if(data.return == 0){ $scope.originEthUsb = angular.copy($scope.ethOverUsb); $scope.$emit('showErrMsgBox', "Saved Successfully!"); }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } },function(error){ $scope.$emit('showErrMsgBox', JSON.stringify(error)); }); submit_success = true; } $scope.enableExternalEthernetHelpInfo = "Allows you to map an external Ethernet port to a different port number of Ethernet over USB."; $("#enableExternalEthernetHelp").popover({content: "<div class=\"helpInfoText\">" + $scope.enableExternalEthernetHelpInfo + "</div>",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $scope.onIpmiAccessChange = function (){ } var original_http_port = "80"; var original_https_port = "443"; var original_ssh_cli_port = "22"; var original_snmp_agent_port = "161"; var original_snmp_traps_port = "162"; var original_remote_control_port = "3900"; var original_cim_over_https_port = "5989"; var original_cim_over_http_port = "5988"; $scope.http_port = original_http_port; $scope.https_port = original_https_port; $scope.ssh_cli_port = original_ssh_cli_port; $scope.snmp_agent_port = original_snmp_agent_port; $scope.snmp_traps_port = original_snmp_traps_port; $scope.remote_control_port = original_remote_control_port; $scope.cim_over_https_port = original_cim_over_https_port; $scope.cim_over_http_port = original_cim_over_http_port; $scope.showPortAssignmentApplyRestButton = false; $scope.onPortAssignmentChange = function (){ if($scope.http_port != original_http_port || $scope.https_port != original_https_port || $scope.ssh_cli_port != original_ssh_cli_port || $scope.snmp_agent_port != original_snmp_agent_port || $scope.snmp_traps_port != original_snmp_traps_port || $scope.remote_control_port != original_remote_control_port || $scope.cim_over_https_port != original_cim_over_https_port || $scope.cim_over_http_port != original_cim_over_http_port){ $scope.showPortAssignmentApplyRestButton = true; $("#port_assignment_setting_table").removeClass("network_background_table"); $("#port_assignment_setting_table").addClass("network_background_highlight_table"); $("#showPortAssignmentApplyRestButton").show(); } if(submit_success){ $("#port_assignment_setting_table").removeClass("network_background_highlight_table"); $("#port_assignment_setting_table").addClass("network_background_table"); $scope.showPortAssignmentApplyRestButton = false; $("#showPortAssignmentApplyRestButton").hide(); } } $scope.reset_port_assignment_setting = function(){ $scope.portAssign = angular.copy($scope.originPortAssign); } $scope.showPortAssignmentDailog = function(){ $("#confirmCommonDlg").modal(); } $scope.submitPortAssignmentSetting = function(){ var payLoad = { "Web_HTTPPort": $scope.portAssign.port_http + '', "Web_HTTPSPort":$scope.portAssign.port_https + '', "CLI_TelnetPort":$scope.portAssign.port_telnet_cli + '', "CLI_SSHPort":$scope.portAssign.port_ssh_cli + '', "SNMP_AgentPort":$scope.portAssign.port_snmp_agent + '', "SNMP_TrapsPort":$scope.portAssign.port_snmp_traps + '', "RP_Port":$scope.portAssign.port_remote_control + '', "CIM_HTTPPort":$scope.portAssign.port_cim_https + '', "CIM_HTTPSPort":$scope.portAssign.port_cim_http + '' }; restSetPortAssign.save({}, payLoad, function(data){ if(data.return == 0){ $scope.originPortAssign = angular.copy($scope.portAssign); $scope.$emit('showErrMsgBox', "Saved Successfully!"); }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } }, function(error){ $scope.$emit('showErrMsgBox', JSON.stringify(error)); }); submit_success = true; } $scope.showBlockedIpAddrList = false; $scope.showBlockedMacAddrList = false; $scope.showOutOfBandAccessIntervalImg = false; $scope.showBlackListApplyRestButton = false; var original_blockedIpAddrList = ""; var original_blockedMacAddrList = ""; var original_beginDate = "01/01/1970"; var original_beginTime = "00:00"; var original_endDate = "01/01/1970"; var original_endTime = "00:00"; $scope.blockedIpAddrList = original_blockedIpAddrList; $scope.blockedMacAddrList = original_blockedMacAddrList; $scope.beginDate = $("#beginDate").val(); $scope.beginTime = $("#beginTime").val(); $scope.endDate = $("#endDate").val(); $scope.endTime = $("#endTime").val(); //$('.datepicker').datepicker({ dateFormat: 'yy-mm-dd'}); $("#beginTimeContainer").datepicker({ autoclose: true, dateFormat: 'yyyy-mm-dd' }); $("#endTimeContainer").datepicker({ autoclose: true, dateFormat: 'yyyy-mm-dd' }); $("#beginClockPicker").clockpicker({ placement: 'top', align: 'left', donetext: 'Done', afterDone: function() { $scope.onBlacklistAndRestritChange(); } }); $("#endClockPicker").clockpicker({ placement: 'top', align: 'left', donetext: 'Done', afterDone: function() { $scope.onBlacklistAndRestritChange(); } }); $scope.showBlacklistAndRestritInput = function(modelId){ if(modelId == "listBlcIpImg"){ $scope.showBlockedIpAddrList = !$scope.showBlockedIpAddrList; if($scope.showBlockedIpAddrList){ $("#listBlcIpImg").attr("src", "www/images/arrow_down.png"); } else{ $("#listBlcIpImg").attr("src", "www/images/arrow_right.png"); } } else if(modelId == "listBlcMacImg"){ $scope.showBlockedMacAddrList = !$scope.showBlockedMacAddrList; if($scope.showBlockedMacAddrList){ $("#listBlcMacImg").attr("src", "www/images/arrow_down.png"); } else{ $("#listBlcMacImg").attr("src", "www/images/arrow_right.png"); } } else if(modelId == "outOfBandAccessIntervalImg"){ $scope.showOutOfBandAccessIntervalImg = !$scope.showOutOfBandAccessIntervalImg; if($scope.showOutOfBandAccessIntervalImg){ $("#outOfBandAccessIntervalImg").attr("src", "www/images/arrow_down.png"); } else{ $("#outOfBandAccessIntervalImg").attr("src", "www/images/arrow_right.png"); } } } $scope.onBlacklistAndRestritChange = function(){ $scope.beginDate = $("#beginDate").val(); $scope.beginTime = $("#beginTime").val(); $scope.endDate = $("#endDate").val(); $scope.endTime = $("#endTime").val(); if($scope.blockedIpAddrList != original_blockedIpAddrList || $scope.blockedMacAddrList != original_blockedMacAddrList || $scope.beginDate != original_beginDate || $scope.beginTime != original_beginTime || $scope.endDate != original_endDate || $scope.endTime != original_endTime){ $scope.showBlackListApplyRestButton = true; $("#black_list_time_restrict_setting_table").removeClass("network_background_table"); $("#black_list_time_restrict_setting_table").addClass("network_background_highlight_table"); $("#showBlackListApplyRestButton").show(); } } $scope.resetBlacklistAndRestrit = function(){ $scope.blockList = angular.copy($scope.originBlockList); } $scope.applyBlock = function(){ console.log("*****begin time*****") var formartBegin = $scope.blockList.begin_time_date.split('/'); var formatEnd = $scope.blockList.end_time_date.split('/'); var begin_time = formartBegin[2]+'-'+formartBegin[0]+'-'+formartBegin[1]+ 'T' +$scope.blockList.begin_time_time; var end_time = formatEnd[2]+'-'+formatEnd[0]+'-'+formatEnd[1]+ 'T' + $scope.blockList.end_time_time; var begin = new Date(begin_time); var end = new Date(end_time); console.log("begin is:"+begin+" and end is:"+end); console.log("compare date:"+ begin<end); if(begin >= end){ $scope.$emit('showErrMsgBox', "Begin time must be less than end time"); return null; } var payLoad = {"Net_SetAccessControl": ''+$scope.blockList.ip_enabled+','+$scope.blockList.ip_address +','+$scope.blockList.mac_enabled+','+$scope.blockList.mac_address+','+$scope.blockList.time_enabled +','+begin_time+','+end_time}; // var payLoad = { // "ip_enabled": $scope.blockList.ip_enabled + '', // "ip_address": $scope.blockList.ip_address + '', // mac_enabled: $scope.blockList.mac_enabled + '', // mac_address: $scope.blockList.mac_address + '', // time_enabled: $scope.blockList.time_enabled + '', // begin_time: begin_time + '', // end_time: end_time + '' // //}; restSetBlock.save({},payLoad, function(data){ if(data.return == 0){ $scope.originBlockList = angular.copy($scope.blockList); $scope.$emit('showErrMsgBox', "Saved Successfully!"); }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } }, function(error){ $scope.$emit('showErrMsgBox', JSON.stringify(error)); }); } /* front panel usb support 0119*/ //read initial value(s) from server $scope.powerOn = true; $scope.initialUSBMode = "sharedModeOwnedByIMM"; $scope.showTimeOut=false; $scope.selectedValue =$scope.initialUSBMode; $scope.switchChecked = false; $scope.showSwitchCheckBox = false; $scope.showUSBButtons =false; //common modal title and content var cfmMsgTitle="message title"; var cfmMsgContent="message content"; //handle ng-change for radios $scope.hostOnlyModeChecked=false; $scope.IMMOnlyModeChecked=false; $scope.sharedModeOwnedByIMMChecked=false; $scope.sharedModeOwnedByHostChecked=false; //mark the current/initial usb mode with a '(current)' $scope.currentHostOnlyMode=false; $scope.currentIMMOnlyMode=false; $scope.currentSharedModeOwnedByIMM=false; $scope.currentSharedModeOwnedByHost=false; $scope.initCurrent = function (value){ switch(value) { case "hostOnlyMode": $scope.currentHostOnlyMode=true; break; case "IMMOnlyMode": $scope.currentIMMOnlyMode=true; break; case "sharedModeOwnedByIMM": $scope.currentSharedModeOwnedByIMM=true; break; case "sharedModeOwnedByHost": $scope.currentSharedModeOwnedByHost=true; break; default: console.log("wrong option"); return; } } $scope.initCurrent ($scope.initialUSBMode); //handle radio switching, need to disable checkbox and disable timeout fields on certain mode $scope.initOptions = function (selectedValue){ $scope.showSwitchCheckBox = false; $scope.showTimeOut=false; $scope.hostOnlyModeChecked=false; $scope.IMMOnlyModeChecked=false; $scope.sharedModeOwnedByIMMChecked=false; $scope.sharedModeOwnedByHostChecked=false; switch(selectedValue) { case "hostOnlyMode": $scope.hostOnlyModeChecked=true; $scope.showSwitchCheckBox = true; $scope.switchChecked = false; break; case "IMMOnlyMode": $scope.IMMOnlyModeChecked=true; $scope.showSwitchCheckBox = true; $scope.switchChecked = false; break; case "sharedModeOwnedByIMM": $scope.sharedModeOwnedByIMMChecked=true; $scope.showSwitchCheckBox = true; if($scope.powerOn) $scope.showTimeOut =true; break; case "sharedModeOwnedByHost": $scope.showSwitchCheckBox = false; $scope.sharedModeOwnedByHostChecked=true; break; default: console.log("wrong option"); return; } } $scope.initOptions($scope.selectedValue); $scope.modeChanging = function(selectedValue){ $scope.showUSBButtons =true; $scope.initOptions(selectedValue); //Current-Shared : Host/ Current-Host Only --> Switch to Shared : IMM if(($scope.initialUSBMode == "sharedModeOwnedByHost" || $scope.initialUSBMode == "hostOnlyMode") && $scope.selectedValue=="sharedModeOwnedByIMM"){ cfmMsgTitle="Switch USB port to shared mode: owned by IMM?"; cfmMsgContent=$scope.powerOn?("Note that when the server is in powered-on state, the USB in shared mode will be switched to host when the port is no longer used by IMM."): ("2This action may disrupt any on-going operations. Note that the USB port in shared mode will be switched to Host when the server is powered on and when the port is no longer used by IMM."); } //Current-IMM Only --> Switch to Shared : IMM if($scope.initialUSBMode == "IMMOnlyMode" && $scope.selectedValue=="sharedModeOwnedByIMM"){ cfmMsgTitle="Switch USB port to shared mode: owned by IMM?"; cfmMsgContent=$scope.powerOn?("Note that when the server is in powered-on state, the USB in shared mode will be switched to host when the port is no longer used by IMM."): ("Note that the USB port in shared mode will be switched to host when the server is powered on and when the port is no longer used by IMM."); } //Current-Shared : IMM/Current-IMM Only -->Switch to Shared : Host || power on/off show the same warning if(($scope.initialUSBMode == "IMMOnlyMode" || $scope.initialUSBMode == "sharedModeOwnedByIMM") && $scope.selectedValue=="sharedModeOwnedByHost"){ cfmMsgTitle="Switch USB port to shared mode: owned by host?"; cfmMsgContent="This action may disrupt any on-going operations. Be sure that the USB is not used by IMM. Note that the USB port in shared mode will be switched to IMM the server is powered off next time."; } //Current-Host Only --> Switch to Shared: Host if($scope.initialUSBMode == "hostOnlyMode" && $scope.selectedValue=="sharedModeOwnedByHost") { cfmMsgTitle="Switch USB port to shared mode: owned by host?"; cfmMsgContent="Note that the USB port in shared mode will be switched to IMM the server is powered off next time."; } //Current-Shared : Host/ Current-Host Only --> Switch to IMM Only if(($scope.initialUSBMode == "sharedModeOwnedByHost" || $scope.initialUSBMode == "hostOnlyMode") && $scope.selectedValue=="IMMOnlyMode"){ cfmMsgTitle="Switch USB port to IMM only mode?"; cfmMsgContent="This action may distrupt any on-going operations."; } //Current-Shared : IMM --> Switch to IMM Only if($scope.initialUSBMode == "sharedModeOwnedByIMM" && $scope.selectedValue=="IMMOnlyMode"){ cfmMsgTitle="Switch USB port to IMM only mode?"; cfmMsgContent=""; } //Current-Shared : IMM/ Current-IMM Only --> Switch to Host Only if(($scope.initialUSBMode == "sharedModeOwnedByIMM" || $scope.initialUSBMode == "IMMOnlyMode") && $scope.selectedValue=="hostOnlyMode"){ cfmMsgTitle="Switch USB port to Host only mode?"; cfmMsgContent="This action may distrupt any on-going operations. Be sure that the USB is not used by IMM."; } //Current-Shared : Host --> Switch to Host Only if($scope.initialUSBMode == "sharedModeOwnedByHost" && $scope.selectedValue=="hostOnlyMode"){ cfmMsgTitle="Switch USB port to Host only mode?"; cfmMsgContent=""; } $scope.cfmMsgTitle=cfmMsgTitle; $scope.cfmMsgContent=cfmMsgContent; } $scope.pickADay = function(){ console.log("pcik a day"); var day = $('#beginDate').val(); console.log(day); } $scope.toggleSwitch = function(value){ console.log("checkbox value\t"+value); } $('#confirmUSBChange').on('hidden', function() { $(this).removeData('modal'); }); $('#beginDate').on('change', function(){ console.log('date change'); console.log(this.value); $scope.blockList.begin_time_date = this.value; $scope.$apply(); }) $('#beginTime').on('change', function(){ console.log('date change'); console.log(this.value); $scope.blockList.begin_time_time = this.value; $scope.$apply(); }) $('#endDate').on('change', function(){ console.log('date change'); console.log(this.value); $scope.blockList.end_time_date = this.value; $scope.$apply(); }) $('#endTime').on('change', function(){ console.log('date change'); console.log(this.value); $scope.blockList.end_time_time = this.value; $scope.$apply(); }) //$scope.isBlockEqual = function(){ // console.log("data origin:"+JSON.stringify($scope.originBlockList)); // console.log("data now:"+JSON.stringify($scope.blockList)); // return JSON.stringify($scope.originBlockList) == JSON.stringify($scope.blockList); //} $scope.confirm_usb_change = function(){ console.log("$scope.cfmMsgTitle\t"+$scope.cfmMsgTitle); console.log("$scope.cfmMsgContent\t"+$scope.cfmMsgContent); $('#confirmUSBChangeLabel').html($scope.cfmMsgTitle); $('#confirmUSBChangeContent').html($scope.cfmMsgContent); $("#confirmUSBChange").modal().css({ "margin-top": "250px" }); } $scope.resetFpUsb = function(){ $scope.fpUsb = angular.copy($scope.originFpUsb); $scope.selectedValue = $scope.currentStatus; } $scope.isObjectValueEqual = function(a, b){ // console.log("conpare:"+objEquals(a, b)); return objEquals(a, b); } }]); <file_sep>'use strict'; angular.module('imm3.main.body.ctrl', [ 'ui.bootstrap', 'ngAnimate' ]) .controller('mainBodyCtrl', [ '$scope', '$uibModal','mainHeaderService', function($scope, $uibModal,mainHeaderService) { var restHeader = mainHeaderService.restHeader(); restHeader.get(function(data) { $scope.rsrvName = data["items"][0].machine_name; $scope.rhostname = data["items"][0].system_name; }); $scope.$on('clickMenuItem1', function(event, curPage) { $scope.$broadcast('clickMenuItem2', curPage); }); $scope.$on('clickMainSubItem1', function(event, clickMainSubItemTitle) { $scope.$broadcast('clickMainSubItem2', clickMainSubItemTitle); }); $scope.$on('chgSrvNameSuc1', function(event, newSrvName) { $scope.$broadcast('chgSrvNameSuc2', newSrvName); }); $scope.$on('showErrMsgBox', function(event, msgBoxText, size) { $uibModal.open({ animation: true, templateUrl: 'www/views/error-message-box.html', controller: 'mainErrBoxCtrl', size: size, resolve: { msgBoxText: function() { return msgBoxText; } } }); }); $scope.hideMenu = function () { angular.element(document.getElementsByTagName("body")[0]).removeClass("showMenu"); $scope.$broadcast('clickAppCommon'); return false; }; } ]) .controller('mainErrBoxCtrl', ['$scope', '$uibModalInstance', 'msgBoxText', function($scope, $uibModalInstance, msgBoxText) { $scope.msgBoxText = msgBoxText; $scope.clkOk = function() { $uibModalInstance.dismiss('Ok'); }; }]);<file_sep>'use strict'; angular.module('imm3.menu.directive', [ 'imm3.menu.list' ]) .directive('datePicker',function(){ return{ restrict: 'EA', template: '<input class="lineInput datePicker" type="text" style="width: 70px;">', replace: true, transclude: true, link: function($scope, iElm, iAttrs, controller){ $('.datePicker').datepicker().on('changeDate',function(e){ $scope.$emit('dateChange',$('.datePicker').val()); $scope.$apply(); }); } } }) .directive('menuItemDirectiveWithSubsItem', [function() { return { restrict: 'AE', scope: { menuTitle: '@', html: '@' }, replace: true, link: function(scope, elem, attrs) { scope.selected = false; scope.$on('clickMenuItem2', function(event, curPage) { if(angular.equals(angular.element(elem).attr("menu-title"), curPage)) { scope.selected = true; } else { scope.selected = false; } }); scope.hideMenu = function () { angular.element(document.getElementsByTagName("body")[0]).removeClass("showMenu"); return false; }; }, templateUrl: 'www/scripts/directives/templateUrl/menu-item-directive-with-subs-item.html' }; }] ) .directive('menuItemDirectiveWithSubsList', [function() { return { transclude : true, restrict: 'AE', scope: {}, replace: true, templateUrl: 'www/scripts/directives/templateUrl/menu-item-directive-with-subs-list.html' }; }]) .directive('menuItemDirectiveWithSubsMain', ['$filter', 'menuList', function($filter, menuList) { return { restrict: 'AE', scope: { menuTitle: '@', image: '@' }, replace: true, link: function(scope, elem, attrs) { scope.on = false; scope.toggleClass = function() { angular.element(document.getElementsByTagName("body")[0]).addClass("showMenu"); if(scope.selected == true && scope.on == true) { return; } scope.on = !scope.on; if(scope.on) { scope.$emit('clickMainSubItem1', angular.element(elem).attr("menu-title")); } }; scope.$on('clickMainSubItem2', function(event, clickMainSubItemTitle) { if(!angular.equals(angular.element(elem).attr("menu-title"), clickMainSubItemTitle)) { scope.on = false; } }); scope.selected = false; scope.$on('clickMenuItem2', function(event, curPage) { var item = $filter('filter')(menuList, {'title': angular.element(elem).attr("menu-title")}, true); if(item[0]["subItems"].length != 0) { if($filter('filter')(item[0]["subItems"], {'title': curPage}, true).length > 0) { scope.selected = true; scope.on = true; } else { scope.selected = false; scope.on = false; } } else { scope.selected = false; scope.on = false; } }); scope.$on('clickAppCommon', function(event) { if(scope.selected) { scope.on = true; } else { scope.on = false; } }); }, templateUrl: 'www/scripts/directives/templateUrl/menu-item-directive-with-subs-main.html' }; }]) .directive('menuItemDirectiveWithSubs', [function() { return { transclude : true, restrict : 'AE', scope : {}, replace : true, templateUrl : 'www/scripts/directives/templateUrl/menu-item-directive-with-subs.html' }; } ]) .directive('menuItemDirectiveWithoutSubs', [function() { return { restrict : 'AE', scope : { menuTitle : '@', html : '@', image: '@' }, replace : true, link: function(scope, elem, attrs) { scope.selected = false; scope.$on('clickMenuItem2', function(event, curPage) { if(angular.equals(angular.element(elem).attr("menu-title"), curPage)) { scope.selected = true; } else { scope.selected = false; } }); scope.hideMenu = function () { angular.element(document.getElementsByTagName("body")[0]).removeClass("showMenu"); return false; }; }, templateUrl : 'www/scripts/directives/templateUrl/menu-item-directive-without-subs.html' }; } ]) .directive('menuListDirective',['menuList', function(menuList) { var retTemplateWithoutSubs = function(item) { var ngIfEx = ""; if(angular.isDefined(item["show"])) { ngIfEx = " ng-if='$root." + item["show"] + "'"; } return ("<menu-item-directive-without-subs menu-title=\"" + item["title"] + "\" html=\"" + item["html"] + "\" image=\"" + item["image"] + "\"" + ngIfEx + "></menu-item-directive-without-subs>"); }; var retTemplateWithSubsMain = function(title, image) { return ("<menu-item-directive-with-subs-main menu-title=\"" + title + "\" image=\"" + image + "\"></menu-item-directive-with-subs-main>"); }; var retTemplateWithSubsItem = function(title, html, show) { var ngIfEx = ""; if(angular.isDefined(show)) { ngIfEx = " ng-if='$root." + show + "'"; } return ("<menu-item-directive-with-subs-item menu-title=\"" + title + "\" html=\"" + html + "\"" + ngIfEx + "></menu-item-directive-with-subs-item>"); }; var retTemplateWithSubsList = function(subItems) { var strSubsList = ""; angular.forEach(subItems, function(item, index) { strSubsList += retTemplateWithSubsItem(item["title"], item["html"], item["show"]); }); return ("<menu-item-directive-with-subs-list>" + strSubsList + "</menu-item-directive-with-subs-list>"); }; var retTemplateWithSubs = function(item) { return ("<menu-item-directive-with-subs>" + retTemplateWithSubsMain(item["title"], item["image"]) + retTemplateWithSubsList(item["subItems"]) + "</menu-item-directive-with-subs>"); }; var retTemplate = function() { var strMenuList = ""; angular.forEach(menuList, function(item, index) { if(item["subItems"].length == 0) { strMenuList += retTemplateWithoutSubs(item); } else { strMenuList += retTemplateWithSubs(item); } }); return '<ul class="menuList">' + strMenuList + '</ul>'; }; return { restrict : 'AE', scope : {}, replace : true, template : retTemplate }; } ]) .directive('menuTabDirective', [function() { return { transclude : true, restrict: 'AE', scope: { tabShow: '=', chgMap: '&' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/menu-tab-directive.html' }; }]) .directive('selectExDirective',[function() { return { transclude : true, restrict: 'AE', scope:{ options: '=', selectedValue: '=' }, replace: true, link: function(scope, elem, attrs){ $(document).click(function(){ scope.showLi = false; }); $("#fakeInput").click(function(event){ event.stopPropagation(); }); scope.demoValue = ""; scope.showList = function(){ console.log("aaa"); scope.showLi = !scope.showLi; } scope.selectValue = function(key, value){ scope.$emit('selectAValue',key); //scope.selectedValue = key; scope.demoValue = value; scope.showLi = false; } }, templateUrl: 'www/scripts/directives/templateUrl/select-ex-directive.html' } }]) ;<file_sep>'use strict'; angular.module('imm3.main.header.filter', []) .filter('headerUserAccess', [function() { return function(access) { if(undefined == access) { return; } switch(access) { case 1: return "userAccessSupervisor"; case 2: return "userAccessReadOnly"; case 3: return "userAccessCustom"; default: return access; } }; }]);<file_sep>'use strict'; angular.module('imm3.quick.action.directive', []) .directive('buttomQuickAction', [function () { return { restrict: 'AE', scope: { actionTitle: '@', actionImage: '@', clickAction: '&' }, replace: true, templateUrl: 'www/scripts/directives/templateUrl/quick-action-directive.html' }; }]) .directive('fileUpload', ['$parse','uiUploader', function ($parse, uiUploader) { return { restrict: 'A', scope: { fileName: '=', showValue: '=', }, link: function ($scope, element, attrs, ngModel) { element.bind('change', function (e) { uiUploader.removeAll(); var files = e.target.files; uiUploader.addFiles(files); $scope.fileName = uiUploader.getFiles()[0].name; $scope.$apply(); }); } }; }]);<file_sep>'use strict'; angular.module('imm3.div.shadow.directive', []) .directive('divShadow', [ function() { return { transclude : true, restrict : 'AE', replace : true, template : '<div class="divWithShadow" ng-transclude></div>' }; } ]);<file_sep>'use strict'; angular.module('imm3.inventory.service', [ 'ngResource','ngStorage', 'pascalprecht.translate' ]) .factory('inventoryService', [ '$resource', function($resource) { var service = {}; service.restGetCpuInfo = function () { return $resource('/api/dataset/imm_processors'); } service.restGetMemoryInfo = function() { return $resource('/api/dataset/imm_memory'); } service.restGetAllDevicesInfo = function() { return $resource('/api/function/raid_alldevices', {params:'@params'}); } service.restGetPSU = function() { return $resource('/api/dataset/imm_power_supplies'); } service.restGetAdapterInfo = function(){ return $resource('/api/dataset/imm_adapters',{params:'@params'}); } service.restGetFirmwareInfo = function() { return $resource('/api/dataset/imm_firmware'); } service.restGetSysBoardInfo = function() { return $resource('/api/dataset/imm_system'); } service.restGetGeneralCompoInfo = function() { return $resource('/api/dataset/imm_props_hardware_com'); } service.restGetFanList = function() { return $resource('/api/dataset/fan-list'); } service.restGetSysInven = function() { return $resource('/api/dataset/sys_inventory'); } service.restGetSysInfo = function() { return $resource('/api/dataset/sys_info'); } return service; } ]);<file_sep>'use strict'; /** * @description New Security Ctrl * @module myApp.security * @since 2016-08-02 * @author <EMAIL> * @static */ angular.module('myApp.security', ['ngRoute']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/security', { templateUrl: 'www/views/security.html', controller: 'SecurityCtrl' }); }]) /** * @description Security Configuration Controller * @namespace SecurityCtrl * @since 2016-08-02 * @author <EMAIL> * @public */ .controller('SecurityCtrl', ['$scope', 'uiUploader', '$rootScope', '$localStorage', '$location', 'securityService', function ($scope, uiUploader, $rootScope, $localStorage, $location, securityService) { //Check Status $scope.$emit('setCurPage1', ["Security"]); $scope.$emit('setMenuItemClass1', 'menuTitleSecurity'); $rootScope.loginInfo = angular.copy($localStorage.loginInfo); if (!$rootScope.loginInfo.loginStatus) { $location.path("/login"); } else { console.log("I am in security page"); var content = "To use SSL, a client web browser must be configured to use SSL3 and/or TLS. Older export-grade browsers with only SSL2 support cannot be used."; //$(".help-info").popover({container: 'body', content: content, trigger:'hover click'}); //$(".help-sm-info").popover({container: 'body', content: content, trigger:'hover click'}); } /** * Init Status */ $scope.initStatus = function () { //Init Status $scope.security = {}; $scope.security.service = {}; $scope.security.https = {}; $scope.security.sklm = {}; securityService.getSecurityStatusSummary() .success(function (data) { if (data.items != null && data.items[0] != null) { //Web / REST $scope.security.service.webSSC = data.items[0].https_cert_status; $scope.security.service.webCSR = data.items[0].https_csr_present; $scope.security.service.webCertEXP = data.items[0].https_webCertEXP; // CIM $scope.security.service.cimSSC = data.items[0].cim_cert_status; $scope.security.service.cimCSR = data.items[0].cim_csr_present; $scope.security.service.cimCertEXP = data.items[0].cim_webCertEXP; //Prevent System Firmware Down-Level Status, default able $scope.security.downLevel = !Boolean(data.items[0].secureRollback); //Remote Physical Prensece Status, default assert $scope.security.physicalPresence = !Boolean(data.items[0].rpp_Assert); $scope.security.physicalPresenceEnable = Boolean(data.items[0].rpp_enabled); //IPMI Access service disable status, default disabled $scope.security.service.ipmiOverLan = Boolean(data.items[0].ipmi_enabled); $scope.security.service.ipmiOverKcs = !Boolean(data.items[0].ipmioverkcs_enabled); //Cryptographic Mode $scope.security.cryptographicMode = data.items[0].cryp_sec_level_mode; $scope.security.defaultCryptographicMode = $scope.security.cryptographicMode; //Security Key Lifecycle Manager $scope.security.sklm.fodKeyValid = data.items[0].sklm_FodKey_Valid; $scope.security.service.sklmSSC = data.items[0].sklm_drive_client_cert_status; $scope.security.service.sklmCSR = data.items[0].sklm_drive_client_csr_present; $scope.security.service.sklmSCS = data.items[0].sklm_drive_server_cert_status; $scope.security.sklm.httpsCertStatus = data.items[0].sklm_https_cert_status; $scope.security.sklm.driveAddressOne = data.items[0].sklm_drive_address_1; $scope.security.sklm.driveAddressTwo = data.items[0].sklm_drive_address_2; $scope.security.sklm.driveAddressThree = data.items[0].sklm_drive_address_3; $scope.security.sklm.driveAddressFour = data.items[0].sklm_drive_address_4; var a1 = $scope.security.sklm.driveAddressOne == '' ? 0 : 1; var a2 = $scope.security.sklm.driveAddressTwo == '' ? 0 : 1; var a3 = $scope.security.sklm.driveAddressThree == '' ? 0 : 1; var a4 = $scope.security.sklm.driveAddressFour == '' ? 0 : 1; $scope.security.sklm.serverConnectedCount = a1 + a2 + a3 + a4; $scope.security.sklm.driveDeviceGroup = data.items[0].sklm_drive_device_group; $scope.security.sklm.drivePortOne = data.items[0].sklm_drive_port_1; $scope.security.sklm.drivePortTwo = data.items[0].sklm_drive_port_2; $scope.security.sklm.drivePortThree = data.items[0].sklm_drive_port_3; $scope.security.sklm.drivePortFour = data.items[0].sklm_drive_port_4; //SSH keys Server, default disable $scope.security.service.sshServer = Boolean(!data.items[0].ssh_svr_enable_ssh_server); $scope.security.service.generatePrivateKeys = data.items[0].ssh_svr_generate_private_keys_status; } else { console.log('error') } }) .error(function (data) { }); //Init Country $scope.security_cert_country_select = {}; $scope.security_cert_country_select.map = {}; securityService.getCountryinfo() .success(function (data) { if (data.items != null && data.items[0] != null) { $scope.countries = data.items; } else { console.log('error') } }) .error(function (data) { }); $scope.security.sslCertStateProvince = ""; $scope.security.sslCertCityLocality = ""; $scope.security.sslCertOrganizationName = ""; $scope.security.sslCertCommonName = ""; $scope.security.sslCertContactPerson = ""; $scope.security.sslCertEmailAddr = ""; $scope.security.sslCertOrgUnit = ""; $scope.security.sslCertSurname = ""; $scope.security.sslCertGivenName = ""; $scope.security.sslCertInit = ""; $scope.security.sslCertDNQual = ""; $scope.security.sslCertChallengePassword = ""; $scope.security.sslCertUnstructuredName = ""; $scope.security.importCertificate = 'No file selected.'; $scope.security.parseContent = false; $scope.security.certificateFormat = 0; }; /** * Set Country Map Data * @param county */ $scope.setCountryMap = function (county) { $scope.security_cert_country_select.map[county.country_value.substr(0, 2)] = county.country_label; }; /** * Reset Status */ var resetStatus = function (generate) { var statusNames = ['changeDownLevelStatus', 'applyCryptographicMode', 'restartService', 'restartHTTPs', 'enableHTTPS', 'signedCertificate', 'trustedCertificate', 'changeTheWordings', 'ActivateSSHKey', 'generatedSSC', 'generatedCSR', 'downloadCertificate', 'removeCertificate', 'generated' ]; for (var i in statusNames) { var status = $scope.security[statusNames[i]]; if (status != null && typeof (status) != 'undefined') { $scope.security[statusNames[i]] = null; } } if (generate) { $scope.security.sslCertStateProvince = ""; $scope.security.sslCertCityLocality = ""; $scope.security.sslCertOrganizationName = ""; $scope.security.sslCertCommonName = ""; $scope.security.sslCertContactPerson = ""; $scope.security.sslCertEmailAddr = ""; $scope.security.sslCertOrgUnit = ""; $scope.security.sslCertSurname = ""; $scope.security.sslCertGivenName = ""; $scope.security.sslCertInit = ""; $scope.security.sslCertDNQual = ""; $scope.security.sslCertChallengePassword = ""; $scope.security.sslCertUnstructuredName = ""; } }; /** * change line style when csr generated * @param type * @returns {*} */ $scope.lineStyle = function (type) { if(type == 1) { var style = { 'line-height': '20px' }; return style; } else { return {} } }; /*---------------------------------------------------------------------*/ var applyChangeService = function (label) { /*if (false) { } else if (false) { } else if (false) { } else if (false) { } else*/ if (label.indexOf('SSH') > -1) {//Disable SSH key server securityService.resetSSHServeStatus(Number(!$scope.security.service.sshServer).toString()) .success(function (data) { if (0 == data.return) { console.log('success'); } else { $scope.security.service.ipmiOverLan = !$scope.security.service.ipmiOverLan; } }) .error(function (data, status, headers, config) { }); } else if (label.indexOf('LAN') > -1) {//Disable IPMI over LAN securityService.resetIPMIStatus(Number(!$scope.security.service.ipmiOverLan).toString()) .success(function (data) { if (0 == data.return) { console.log('success'); } else { $scope.security.service.ipmiOverLan = !$scope.security.service.ipmiOverLan; } }) .error(function (data, status, headers, config) { }); } else if (label.indexOf('KCS') > -1) {//Disable IPMI over KCS securityService.resetIPMIOverKCSStatus(Number(!$scope.security.service.ipmiOverKcs).toString()) .success(function (data) { if (0 == data.return) { console.log('success'); } else { $scope.security.service.ipmiOverKcs = !$scope.security.service.ipmiOverKcs; } }) .error(function (data, status, headers, config) { }); } } /** * When Change Service Disable Status, Show Warning Dialog Or Do Post * @param disable * @param index * @param label * @param type */ $scope.changeServiceStatus = function (disable, index, label, type) { $scope.security.selectedServiceLabel = label; $scope.security.selectedServiceType = type; var _disableStr = ''; if (disable) {//Disable $scope.security.service.title = 'Disable'; _disableStr = 'not'; $scope.security.service.label = label; $scope.security.service.type = type; //disable type if (type) {//Web UI $scope.security.service.content = 'You will ' + _disableStr + ' be able to access ' + label + ' at next IMM restart'; } else { $scope.security.service.content = 'The existing sessions will be disconnected.'; } //Show Service Disable Warning $("#changeServiceStatus").on('hide.bs.modal', function () { $scope.security.service[index] = !disable; }); $("#changeServiceStatus").modal('show').css({'margin-top': '150px'}); } else if (!disable) {//Enable $scope.security.service.title = 'Enable'; $scope.security.service.restart = false; applyChangeService(label); } }; /** * Apply Service Change */ $scope.applyServiceChange = function () { $("#changeServiceStatus").off('hide.bs.modal'); var type = $scope.security.service.type; if (type) {//Web UI $scope.security.service.restart = true; } var label = $scope.security.selectedServiceLabel; applyChangeService(label); }; /*---------------------------------------------------------------------*/ /** * When Change Https Disable Status, Show Warning Dialog Or Do Post * @param disable * @param index * @param label * @param type */ $scope.changeHttpsStatus = function (disable, index, label, type) { var _disableStr = ''; if (!disable) {//Disable $scope.security.https.title = 'Disable'; $scope.security.https.result = 'disabled'; _disableStr = 'unavailable'; } else if (disable) {//Enable $scope.security.https.title = 'Enable'; $scope.security.https.result = 'enabled'; _disableStr = 'available'; } $scope.security.https.label = label; $scope.security.https.type = type; $scope.security.https.content = 'This action will cause ' + label + ' service restart. '; $scope.security.https.content += label + ' access will be ' + _disableStr + ' untill the restart is complete.' $scope.security.https.resultContent = 'Web GUI access will be ' + _disableStr + ' until the web server restart is complete. At that point, you will need to login to the web again.'; $scope.security.title = label + 'over HTTPS ' + _disableStr; //Show Warning $("#changeHttpsStatus").on('hide.bs.modal', function () { $scope.security.https[index] = !disable; }); $("#changeHttpsStatus").modal('show').css({'margin-top': '150px'}); }; /** * Apply Https Change */ $scope.applyHttpsChange = function () { $("#changeHttpsStatus").off('hide.bs.modal'); $scope.security.inProgress = 'Applying Settings'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); resetStatus(); if (!$scope.security.https.type) { $scope.security.enableHTTPS = true; } setTimeout(function () { $("#inProgress").modal('hide'); if ($scope.security.https.type) {//Web UI $scope.security.https.restart = true; $('#changeWebHttpsStatusSuccess').modal('show').css({'margin-top': '150px'}); } else { $('#success').modal('show').css({'margin-top': '150px'}); } }, 1000); }; /*---------------------------------------------------------------------*/ /** * When Change Prevent Firmware DownLevel Status, Show Warning Dialog Then Do Post * @param disable * @param index */ $scope.changeDownLevelStatus = function (disable, index) { if (disable) {//Disable resetStatus(); $scope.security.title = 'Disable this function?'; $scope.security.content = 'Disabling this function will allow IMM/uEFI/LEPT to be replaced with earlier versions.'; $scope.security.changeDownLevelStatus = true; //Show Service Disable Warning $("#changeStatus").on('hide.bs.modal', function () { $scope.security[index] = !disable; }); $("#changeStatus").modal('show').css({'margin-top': '150px'}); } else {//Enable ,take effect immediately. securityService.resetFirmwareDownLevelStatus(Number(!$scope.security.downLevel).toString()) .success(function (data) { if (0 == data.return) { console.log('success'); } else { $scope.security.downLevel = !$scope.security.downLevel; } }) .error(function (data, status, headers, config) { }); } }; /** * Apply Prevent Firmware DownLevel Status */ $scope.applyDownLevelStatus = function () { $("#changeStatus").off('hide.bs.modal'); securityService.resetFirmwareDownLevelStatus(Number(!$scope.security.downLevel).toString()) .success(function (data) { if (0 == data.return) { console.log('success'); } else { $scope.security.downLevel = !$scope.security.downLevel; } }) .error(function (data, status, headers, config) { }); }; /** * Change Physical Presence Status * @param status */ $scope.changePhysicalPresenceStatus = function (status) { securityService.resetPhysicalPrenseceStatus(Number(!status).toString()) .success(function (data) { if (0 == data.return) { console.log('success'); } else { $scope.security.physicalPresence = !status; } }) .error(function (data, status, headers, config) { }); }; /*---------------------------------------------------------------------*/ /** * Show Generate Certificate Menu * @param $event * @param status * @param serviceType * @param label * @param type */ $scope.showGenerateMenu = function ($event, status, serviceType, label, type) { $scope.security.selectedHTTPSStatus = status; $scope.security.selectedServiceType = serviceType; $scope.security.selectedHTTPSLabel = label; $scope.security.selectedHTTPSType = type; var top, left; if (type) { top = $($event.target).offset().top + 30; left = $($event.target).offset().left - 200; } else { top = $($event.target).offset().top - 100; left = $($event.target).offset().left - 100; } $('body').on('click', function () { $('#generateCertificateAction').css({ 'display': 'none' }); }); $('#app').scroll(function () { $('#generateCertificateAction').css({ 'display': 'none' }); }); setTimeout(function () { $('#generateCertificateAction').css({ 'display': 'block', 'left': left + 'px', 'top': top + 'px' }); }, 0); }; /** * Confirm Generate self-signed certificate */ $scope.confirmGenerateSSC = function () { resetStatus(true); $('#generateSelfSignedCert').modal('show'); }; /** * Generate self-signed certificate */ $scope.generateSSC = function () { $scope.security.inProgress = 'Generating a new certificate ...'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); resetStatus(); var _disableStr = ''; var _label = ''; var _operate = ''; if ($scope.security.selectedHTTPSStatus) { $scope.security.restartHTTPs = true; _disableStr = 'unavailable'; _operate = 'restart'; if ($scope.security.selectedHTTPSLabel.indexOf('Web') > -1) { $scope.security.selectedHTTPSLabel = 'IMM'; _label = 'IMM' } else { _label = $scope.security.selectedHTTPSLabel; } } else { $scope.security.changeTheWordings = true; _disableStr = 'available'; _operate = 'enable'; if ($scope.security.selectedHTTPSLabel.indexOf('Web') > -1) { $scope.security.selectedHTTPSLabel = 'Web'; } _label = $scope.security.selectedHTTPSLabel; } $scope.security.title = 'The self-signed certificate has been generated successfully.You must ' + _operate + ' ' + _label + ' to activate it.'; $scope.security.content = _label + ' access will be ' + _disableStr + ' until the restart is complete.'; $scope.security.generatedSSC = true; if ($scope.security.selectedHTTPSLabel.indexOf('SKLM') > -1) { var params = {}; params.drive_address_1 = $scope.security.sklm.driveAddressOne; params.drive_port_1 = $scope.security.sklm.drivePortOne; params.drive_address_2 = $scope.security.sklm.driveAddressTwo; params.drive_port_2 = $scope.security.sklm.drivePortTwo; params.drive_address_3 = $scope.security.sklm.driveAddressThree; params.drive_port_3 = $scope.security.sklm.drivePortThree; params.drive_address_4 = $scope.security.sklm.driveAddressFour; params.drive_port_4 = $scope.security.sklm.drivePortFour; params.drive_device_group = $scope.security.sklm.driveDeviceGroup; securityService.resetSecureServicesConfiguration(params) .success(function (data) { if (0 == data.return) { //$('#success').modal('show').css({'margin-top': '150px'}); } else { //$('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { }); } // Check Again var datas = []; datas.push($scope.security.selectedServiceType); datas.push($scope.security_cert_country_select.value); datas.push($scope.security.sslCertStateProvince); datas.push($scope.security.sslCertCityLocality); datas.push($scope.security.sslCertOrganizationName); datas.push($scope.security.sslCertCommonName); datas.push($scope.security.sslCertContactPerson); datas.push($scope.security.sslCertEmailAddr); datas.push($scope.security.sslCertOrgUnit); datas.push($scope.security.sslCertSurname); datas.push($scope.security.sslCertGivenName); datas.push($scope.security.sslCertInit); datas.push($scope.security.sslCertDNQual); var param = datas.join(','); securityService.generateSSC(param) .success(function (data) { $("#inProgress").modal('hide'); if (0 == data.return) { $('#success').modal('show').css({'margin-top': '150px'}); $scope.initStatus(); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { }); }; /** * Confirm Generate CSR (certificate signing request) */ $scope.confirmGenerateCSR = function () { resetStatus(true); $('#generateCsr').modal('show'); }; /** * Generate CSR (certificate signing request) */ $scope.generateCSR = function () { $scope.security.inProgress = 'Generating a new CSR (certificate signing request) ...'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); resetStatus(); $scope.security.title = 'The CSR has been generated successfully .'; $scope.security.content = 'You can download it and sent to a certificate authority (CA) for signing.'; $scope.security.generatedCSR = true; if ($scope.security.selectedHTTPSLabel.indexOf('SKLM') > -1) { var params = {}; params.drive_address_1 = $scope.security.sklm.driveAddressOne.toString(); params.drive_port_1 = $scope.security.sklm.drivePortOne.toString(); params.drive_address_2 = $scope.security.sklm.driveAddressTwo.toString(); params.drive_port_2 = $scope.security.sklm.drivePortTwo.toString(); params.drive_address_3 = $scope.security.sklm.driveAddressThree.toString(); params.drive_port_3 = $scope.security.sklm.drivePortThree.toString(); params.drive_address_4 = $scope.security.sklm.driveAddressFour.toString(); params.drive_port_4 = $scope.security.sklm.drivePortFour.toString(); params.drive_device_group = $scope.security.sklm.driveDeviceGroup; securityService.resetSecureServicesConfiguration(params) .success(function (data) { if (0 == data.return) { //$('#success').modal('show').css({'margin-top': '150px'}); } else { //$('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { }); } // Check Again var datas = []; datas.push($scope.security.selectedServiceType); datas.push($scope.security_cert_country_select.value); datas.push($scope.security.sslCertStateProvince); datas.push($scope.security.sslCertCityLocality); datas.push($scope.security.sslCertOrganizationName); datas.push($scope.security.sslCertCommonName); datas.push($scope.security.sslCertContactPerson); datas.push($scope.security.sslCertEmailAddr); datas.push($scope.security.sslCertOrgUnit); datas.push($scope.security.sslCertSurname); datas.push($scope.security.sslCertGivenName); datas.push($scope.security.sslCertInit); datas.push($scope.security.sslCertDNQual); datas.push($scope.security.sslCertChallengePassword); datas.push($scope.security.sslCertUnstructuredName); var param = datas.join(','); securityService.generateCSR(param) .success(function (data) { $("#inProgress").modal('hide'); if (0 == data.return) { $('#success').modal('show').css({'margin-top': '150px'}); $scope.initStatus(); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { }); }; /** * Select Removable Certificate */ $scope.selectRemovableCertificate = function (status, serviceType, label, type) { $scope.security.selectedHTTPSStatus = status; $scope.security.selectedHTTPSLabel = label; $scope.security.selectedServiceType = serviceType; $scope.security.selectedCertType = type; resetStatus(); if (status) { $scope.security.title = 'Remove the ' + label + ' Over HTTPs certificate?'; if (label.indexOf('Web') > -1) { $scope.security.content = 'The existing web session will restart. HTTPs will be disabled and a new login via HTTP protocol will be required.'; } else { $scope.security.content = 'Changes to the security settings will cause existing session to be terminated. ' + label + ' Over HTTPs will be disabled.'; } } else { if (label.indexOf('Web') > -1) { $scope.security.title = 'Remove the HTTPs certificate?'; } else { $scope.security.title = 'Remove the ' + label + ' Over HTTPs certificate?'; } $scope.security.content = ''; } $("#removeCertificate").modal('show').css({'margin-top': '80px'}); }; /** * Remove Certificate */ $scope.removeCertificate = function () { $("#removeCertificate").off('hide.bs.modal'); $("#removeCertificate").modal('hide'); $scope.security.inProgress = 'Removing certificate ...'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); resetStatus(); $scope.security.removeCertificate = true; // Chack Again var datas = []; datas.push($scope.security.selectedServiceType); datas.push($scope.security.selectedCertType); datas.push(0); var param = datas.join(','); securityService.removeCertificate(param) .success(function (data) { $("#inProgress").modal('hide'); if (0 == data.return) { $('#success').modal('show').css({'margin-top': '150px'}); $scope.initStatus(); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { }); }; /** * Select Downloadable Certificate */ $scope.selectDownloadableCertificate = function (status, serviceType, label, type) { $scope.security.selectedHTTPSStatus = status; $scope.security.selectedHTTPSLabel = label; $scope.security.selectedServiceType = serviceType; $scope.security.selectedCertType = type; $("#downloadCertificate").on('hide.bs.modal', function () { $scope.security.certificateFormat = 0; }); resetStatus(); $scope.security.title = 'Download Certificate'; $scope.security.downloadCertificate = true; $scope.security.parseContent = false; $("#downloadCertificate").modal('show').css({'margin-top': '80px'}); }; /** * Downloadable Certificate */ $scope.downloadCertificate = function () { $("#downloadCertificate").off('hide.bs.modal'); $("#downloadCertificate").modal('hide'); $scope.security.inProgress = 'Downloading certificate ...'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); resetStatus(); $scope.security.downloadCertificate = true; // Check Again securityService.downloadCertificateFormat($scope.security.certificateFormat.toString()) .then(function (formated) { if (formated) {//notified var datas = []; datas.push($scope.security.selectedServiceType); datas.push($scope.security.selectedCertType); datas.push(0); var param = datas.join(','); securityService.downloadCertificate(param) .success(function (data) { $("#inProgress").modal('hide'); if (0 == data.return) { $scope.initStatus(); $('#success').modal('show').css({'margin-top': '150px'}); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { }); } }, function (err) { console.log(err); } ); }; /** * Select Import Certificate : Signed Certificate/LDAP Trusted Certificate * @param status HTTPs is currently enabled Or disable * @param label * @param type Signed Certificate/LDAP Trusted Certificate */ $scope.selectImportCertificate = function (status, serviceType, label, type) { $scope.security.selectedHTTPSStatus = status; $scope.security.selectedHTTPSLabel = label; $scope.security.selectedServiceType = serviceType; $scope.security.selectedCertType = type; if (type == 2) { $scope.security.selectedCertTypeStr = 'trusted'; } else if (type != 2) { $scope.security.selectedCertTypeStr = 'cert'; } $("#importCertificate").on('hide.bs.modal', function () { $scope.security.importCertificate = 'No file selected.'; $scope.security.parseContent = false; }); $scope.security.importCertificate = ''; $scope.security.persent = null; resetStatus(); if (type != 2) { $scope.security.title = 'Import Signed Certificate'; $scope.security.content = 'The certificate being imported must have been created from the Certificate Signing Request most recently created.'; $scope.security.signedCertificate = true; } else if (type == 2) { $scope.security.title = 'Import LDAP Trusted Certificate'; $scope.security.content = ''; $scope.security.trustedCertificate = true; } $("#importCertificate").modal('show').css({'margin-top': '80px'}); }; /** * Show/Hide Import Certificate Parse Content */ $scope.showImportParseContent = function (view) { $scope.security.parseContent = !$scope.security.parseContent; $scope.security.certParseContent = ''; if (view && $scope.security.parseContent) { // Check Again var datas = []; datas.push($scope.security.selectedServiceType); datas.push($scope.security.selectedCertType); datas.push(0); var param = datas.join(','); securityService.viewCertificate(param) .success(function (data) { if (data.DownloadContent != null) { $scope.security.certificateContent = data.DownloadContent; } else { $scope.security.certificateContent = ''; } }) .error(function (data, status, headers, config) { }); } }; /** * Import Signed Certificate */ $scope.importSignedCertificate = function () { $("#importCertificate").off('hide.bs.modal'); $("#importCertificate").modal('hide'); $scope.security.inProgress = 'Importing certificate ...'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); resetStatus(); var _disableStr = ''; var _label = ''; var _labelPart = '' var _operate = ''; if ($scope.security.selectedHTTPSStatus) { $scope.security.restartHTTPs = true; _disableStr = 'unavailable'; _operate = 'restart '; if ($scope.security.selectedHTTPSLabel.indexOf('Web') > -1) { $scope.security.selectedHTTPSLabel = 'IMM'; _label = 'IMM'; _labelPart = ' Web GUI'; } else { _label = $scope.security.selectedHTTPSLabel; } } else { $scope.security.changeTheWordings = true; _disableStr = 'available'; _operate = 'enable '; if ($scope.security.selectedHTTPSLabel.indexOf('Web') > -1) { $scope.security.selectedHTTPSLabel = 'Web'; } _label = $scope.security.selectedHTTPSLabel; } $scope.security.title = 'The self-signed certificate has been imported successfully.You must ' + _operate + _label + ' to activate it.'; $scope.security.content = _label + _labelPart + ' access will be ' + _disableStr + ' until the restart is complete.'; $scope.security.generatedSSC = true;// if (!$scope.security.parseContent) { uiUploader.startUpload({ 'url': '/upload', 'onProgress': function (file) { var persent = (file.loaded / uiUploader.getFiles()[0].size * 100).toFixed(0); $scope.security.persent = persent; $scope.$apply(); }, 'onCompleted': function (file, data) {//file, data, status $('#inProgress').modal('hide'); $scope.security.persent = null; data = angular.fromJson(data); if (data.items != null && data.items[0] != null) { //after upload success, Notify Certificate File Upload // Check Again var params = {}; params.FileName = data.items[0].path; params.CertType = 'cert'; params.ServiceType = $scope.security.selectedServiceType; params.index = 0; securityService.notifyCertificateFileUpload(params) .then(function (notified) { if (notified) {//notified // Check Again var datas = []; datas.push($scope.security.selectedServiceType); datas.push(true); datas.push($scope.security.selectedCertType); datas.push(0); datas.push(data.items[0].name); datas.push(''); var param = datas.join(','); securityService.importCertificate(param) .success(function (data) { $("#inProgress").modal('hide'); if (0 == data.return) { $scope.security.generated = true; $scope.initStatus(); $('#success').modal('show').css({'margin-top': '150px'}); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { $("#inProgress").modal('hide'); }); } }, function (err) { console.log(err); } ); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } } }); } else { var datas = []; datas.push($scope.security.selectedServiceType); datas.push(true); datas.push($scope.security.selectedCertType); datas.push(0); datas.push(''); datas.push($scope.security.certParseContent); var param = datas.join(','); securityService.importCertificate(param) .success(function (data) { $("#inProgress").modal('hide'); if (0 == data.return) { $scope.security.generated = true; $scope.initStatus(); $('#success').modal('show').css({'margin-top': '150px'}); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { $("#inProgress").modal('hide'); }); } }; /** * Import LDAP Trusted Certificate */ $scope.importLDAPTrustedCertificate = function () { $("#importCertificate").off('hide.bs.modal'); $("#importCertificate").modal('hide'); $scope.security.inProgress = 'Importing certificate ...'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); resetStatus(); if ($scope.security.selectedHTTPSStatus) { $scope.security.content = 'It will take effect immediately.'; } else {//Secure LDAP disabled $scope.security.content = 'It\'s required to enable secure LDAP to activate the certificate.'; } $scope.security.title = 'The LDAP trusted certificate has been imported successfully .'; $scope.security.trustedCertificate = true; if (!$scope.security.parseContent) { uiUploader.startUpload({ 'url': '/upload', 'onProgress': function (file) { var persent = (file.loaded / uiUploader.getFiles()[0].size * 100).toFixed(0); $scope.security.persent = persent; $scope.$apply(); }, 'onCompleted': function (file, data) {//file, data, status $('#inProgress').modal('hide'); $scope.security.persent = null; data = angular.fromJson(data); if (data.items != null && data.items[0] != null) { //after upload success, Notify Certificate File Upload // Check Again var params = {}; params.FileName = data.items[0].path; params.CertType = 'trusted'; params.ServiceType = $scope.security.selectedServiceType; params.index = 0; securityService.notifyCertificateFileUpload(params) .then(function (notified) { if (notified) {//notified // Check Again var datas = []; datas.push($scope.security.selectedServiceType); datas.push(true); datas.push($scope.security.selectedCertType); datas.push(0); datas.push(data.items[0].name); datas.push(''); var param = datas.join(','); securityService.importCertificate(param) .success(function (data) { $("#inProgress").modal('hide'); if (0 == data.return) { $scope.security.generated = true; $scope.initStatus(); $('#success').modal('show').css({'margin-top': '150px'}); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { $("#inProgress").modal('hide'); }); } }, function (err) { console.log(err); } ); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } } }); } else { var datas = []; datas.push($scope.security.selectedServiceType); datas.push(true); datas.push($scope.security.selectedCertType); datas.push(0); datas.push(''); datas.push($scope.security.certParseContent); var param = datas.join(','); securityService.importCertificate(param) .success(function (data) { $("#inProgress").modal('hide'); if (0 == data.return) { $scope.security.generated = true; $('#success').modal('show').css({'margin-top': '150px'}); } else { $('#failed').modal('show').css({'margin-top': '150px'}); } }) .error(function (data, status, headers, config) { $("#inProgress").modal('hide'); }); } }; /** * Enable Secure LDAP */ $scope.enableSecureLDAP = function () { //abandon }; /** * After Generate Or Import : Enable Web/CIM/Redfish Https */ $scope.enableHttps = function (id) { $('#' + id).trigger('click'); }; /** * After Generate Or Import : Restart Web/CIM/Redfish Https */ $scope.restartHttps = function (label, type) { $("#changeHttpsStatus").off('hide.bs.modal'); $("#success").css({ 'display': 'none' }).modal('hide'); $scope.security.inProgress = 'Restarting ...'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); resetStatus(); if (type) {//Web UI $scope.security.https.resultContent = 'Web GUI access will be unavailable until the web server restart is complete. At that point, you will need to login to the web again.'; } else { $scope.security.restartService = true; $scope.security.title = 'The ' + label + ' has restarted to use the new certificate.'; } //abandon setTimeout(function () { $("#inProgress").modal('hide'); if (1 == 1) { if (type) {//Web UI $('#changeWebHttpsStatusSuccess').modal('show').css({'margin-top': '150px'}); } else { $('#success').modal('show').css({'margin-top': '150px'}); } } else { $('#failed').modal('show').css({'margin-top': '150px'}); } }, 1000); }; /*---------------------------------------------------------------------*/ /** * Generate SSH Serve Keys */ $scope.generateSSHKeys = function () { $scope.security.inProgress = 'Generating SSH Server Private Key ...'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); resetStatus(); var _operate = ''; if (!$scope.security.service.sshServer) { $scope.security.restartHTTPs = true; _operate = 'restart'; } else { $scope.security.changeTheWordings = true; _operate = 'enable'; } $scope.security.title = 'The SSH key has been generated successfully.'; $scope.security.content = 'It\'s required to ' + _operate + ' SSH server to activate the certificate.'; securityService.generateSSHServerPrivateKey('1') .success(function (data) { $("#inProgress").modal('hide'); if ('0' == data.return) { $scope.security.service.generatedSSHKey = true; $scope.initStatus(); $("#changeStatus").off('hide.bs.modal').modal('show').css({'margin-top': '150px'}); } else { $scope.security.service.sshServer = !$scope.security.service.sshServer; } }) .error(function (data, status, headers, config) { $("#inProgress").modal('hide'); }); }; /** * After Generate : Restart SSH Server To Activate The Certificate. */ $scope.restartSSHServe = function () { //abandon }; /** *After Generate : Enable SSH Server To Activate The Certificate. */ $scope.enableSSHServe = function () { $scope.security.service.sshServer = false; securityService.resetSSHServeStatus(Number(!$scope.security.service.sshServer).toString()) .success(function (data) { if (0 == data.return) { console.log('success'); } else { $scope.security.service.sshServer = !$scope.security.service.sshServer; } }) .error(function (data, status, headers, config) { }); }; /** * Confirm Activate SSH Serve Keys */ $scope.confirmActivateSSHKeys = function () { resetStatus(); $scope.security.title = 'Activate the new SSH server key?'; $scope.security.content = 'Changes to the security settings will cause existing session to be terminated. A new login will be required.'; $scope.security.ActivateSSHKey = true; //Show Cryptographic Chaneg Dialog $("#changeStatus").off('hide.bs.modal').modal('show').css({'margin-top': '150px'}); }; /** * Activate SSH Serve Keys */ $scope.activateSSHKeys = function () { $("#changeStatus").off('hide.bs.modal'); $scope.security.inProgress = 'Applying Settings'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); //abandon setTimeout(function () { $("#inProgress").modal('hide'); if (1 != 1) {//Web UI $('#failed').modal('show').css({'margin-top': '150px'}); } else { $('#success').modal('show').css({'margin-top': '150px'}); } }, 1000); }; /*---------------------------------------------------------------------*/ /** * Change Cryptographic Mode */ $scope.changeCryptographicMode = function () { if ($scope.security.cryptographicMode != $scope.security.defaultCryptographicMode) { $scope.security.cryptographicButtons = true; } else { $scope.security.cryptographicButtons = false; } }; /** * Confirm Cryptographic Mode Change */ $scope.confirmCryptographicModeChange = function () { resetStatus(); $scope.security.title = 'Apply the security settings?'; $scope.security.content = 'This action may cause Web restart. IMM web UI will be unavailable untill the restart is complete.'; $scope.security.applyCryptographicMode = true; //Show Cryptographic Chaneg Dialog $("#changeStatus").off('hide.bs.modal').modal('show').css({'margin-top': '150px'}); }; /** * Apply Cryptographic Mode */ $scope.applyCryptographicMode = function () { $("#changeStatus").off('hide.bs.modal'); $scope.security.inProgress = 'Applying Settings'; $("#inProgress").modal({backdrop: 'static', keyboard: false}).css({'margin-top': '150px'}); securityService.resetCryptographicMode(Number(!$scope.security.defaultCryptographicMode).toString()) .success(function (data) { $("#inProgress").modal('hide'); if (0 == data.return) { $('#success').modal('show').css({'margin-top': '150px'}); } else if (0 == data.return) { $('#failed').modal('show').css({'margin-top': '150px'}); $scope.security.service.ipmiOverLan = !$scope.security.service.ipmiOverLan; } }) .error(function (data, status, headers, config) { }); }; /** * Reset Cryptographic Mode */ $scope.resetCryptographicMode = function () { $scope.security.cryptographicMode = $scope.security.defaultCryptographicMode; $scope.security.cryptographicButtons = false; }; /*---------------------------------------------------------------------*/ /** * Select Activation Key To Import */ $scope.selectActivationKey = function () { $("#importActivationKey").modal('show').css({'margin-top': '150px'}); }; /** * Configure to add server */ $scope.configureToAddServer = function () { $("#configureToAddServer").modal('show').css({'margin-top': '100px'}); }; /** * */ $scope.applyConfigure = function () { }; }]); <file_sep>'use strict'; /* * Author : <EMAIL> * Desc : Boot Order Option Ctrl * Create Date : 2016-06-20 * Update Date : 2016-07-28 */ angular.module('imm3.license.mgmt.ctrl', ['ngRoute', 'pascalprecht.translate', 'imm3.license.mgmt.service']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/licensemgmt', { templateUrl: 'www/views/license-mgmt.html', controller: 'licenseMgmtCtrl' }); }]) .controller('licenseMgmtCtrl', ['$scope', '$rootScope', '$localStorage', '$location', 'uiUploader', 'cfgLicenseMgmtService', function ($scope, $rootScope, $localStorage, $location, uiUploader, cfgLicenseMgmtService) { //$scope.$emit('clickMenuItem1', 'menuTitlePowerPolicy'); /** * check login status * @type {*} */ $rootScope.loginInfo = angular.copy($localStorage.loginInfo); if (!$rootScope.loginInfo.loginStatus) { $location.path("/login"); } else { console.log("I am in license mgmt page"); } $scope.licenseData = {};//post data $scope.deletedList = [];//deleted license list $scope.descriptorType = { '1':'SP', '4':'Remote Control' }; /** * Get License datas TODO Result Dialog */ $scope.getLicenseData = function () { cfgLicenseMgmtService.restLicenseInfo() .success(function (data) { console.log('loading License...'); if(data.items != null && data.items[0] != null && data.items[0].keys != null) { $scope.licenseList = data.items[0].keys; } else { } }) .error(function (data, status, headers, config) { }); }; /** * Refresh License Data */ var refreshLicenseData = function () { cfgLicenseMgmtService.restLicenseInfo() .success(function (data) { if(data.items != null && data.items[0] != null && data.items[0].keys != null) { $scope.licenseList = data.items[0].keys; } else { } }) .error(function (data, status, headers, config) { }); }; /** * upload license & import license */ $scope.addLicense = function () { $('#progress').modal('show'); //at first should upload license uiUploader.startUpload({ 'url':'/upload', 'onProgress':function (file) { var persent = (file.loaded / uiUploader.getFiles()[0].size * 100).toFixed(0); $scope.licenseData.persent = persent; $scope.$apply(); }, 'onCompleted':function (file, data) {//file, data, status $('#progress').modal('hide'); $('#result').modal('show'); $scope.licenseData.persent = null; data = angular.fromJson(data); if(data.items != null && data.items[0] != null) { //after upload success, do import license var params = data.items[0].path; cfgLicenseMgmtService.importBy(params) .success(function (data) { data = angular.fromJson(data); if(0 == data.return) { $scope.licenseData.uploadSuccessful = true; refreshLicenseData(); } else { $scope.licenseData.uploadSuccessful = false; } }) .error(function (data, status, headers, config) { }); } else { $scope.licenseData.uploadSuccessful = false; } $scope.$apply(); setTimeout(function() { $('#result').modal('hide'); }, 1300); } }); }; /** * Clear Add Tmp Data */ $scope.clearAddLicense = function () { $scope.licenseData.licenseName = ''; $scope.licenseData.persent = null; }; /** * Remove License(FOD key) TODO Result Dialog * @returns {boolean} */ $scope.deleteLicense = function () { if(typeof ($scope.licenseData.selected) == 'undefined' && $scope.licenseData.selected == null) { return false; } $('#progress').modal('show'); var params = $scope.licenseData.selected; cfgLicenseMgmtService.deleteBy(params) .success(function (data) { $('#progress').modal('hide'); data = angular.fromJson(data); if(0 == data.return) { refreshLicenseData(); $scope.licenseData.selected = null; } else { } }) .error(function (data, status, headers, config) { }); }; /** * Check Is In Deleted License List Or Not * @param obj deleted license tag * @returns {boolean} is in deleted license list or not */ $scope.deletedContains = function (obj) { var _tmp = $scope.deletedList; var i = _tmp.length; while (i--) { if (_tmp[i] == obj) { return true; } } return false; }; /** * Export License(FOD key) TODO Result Dialog */ $scope.exportLicense = function () { if(typeof ($scope.licenseData.selected) == 'undefined' && $scope.licenseData.selected == null) { return false; } $('#progress').modal('show'); var params = $scope.licenseData.selected; cfgLicenseMgmtService.exportBy(params) .success(function (data) { $('#progress').modal('hide'); data = angular.fromJson(data); if(0 == data.return) { $scope.licenseData.exportFileName = data.FileName; } else { } }) .error(function (data, status, headers, config) { }); } }]); <file_sep>'use strict'; /** * @description Boot Order Option Ctrl * @module myApp.bootoptions * @since 2016-07-04 * @author <EMAIL> * @static */ angular.module('myApp.bootoptions', ['ngRoute', 'pascalprecht.translate', 'imm3.home.cfg.bootoptions.service']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/bootOptions', { templateUrl: 'www/views/boot-options.html', controller: 'bootOptionsCtrl' }); }]) /** * Set Boot Order Controller */ .controller('bootOptionsCtrl', ['$scope', '$timeout', 'cfgBootOptionsService', 'homeQuickActionService', '$q', function ($scope, $timeout, cfgBootOptionsService, homeQuickActionService, $q) { $scope.test = "BootOptions"; $scope.$emit('setCurPage1', ["BootOptions"]); $scope.$emit('clickMenuItem1', 'menuTitleBootOptions'); //locate sub-page in the navigate memu. $scope.$on('$viewContentLoaded', function () { $scope.$emit('clickMenuItem1', 'menuTitleBootOptions'); }); /** * Get Boot Device and One-Time Boot Device */ $scope.initDeviceList = function () { //Need to Read The Initial Values Via Rest Call? $scope.bootTypeDefault = 'UEFI Boot';//`bootTypeDefault $scope.bootOrder = {}; $scope.groupOrder = {}; $scope.deviceOrder = {}; //$scope.wolBootOrderDefault = [];remove on 2016-07-26 by lucuicheng $scope.bootOptionTypeBtns = false;//default value $scope.bootOrderOpsInfo = {}; $scope.bootOrderOpsInfo.map = true;//default value, boot order or wol boot order $scope.bootOrderOpsInfo.selectedRestrtWay = ''; $scope.bootOrderOpsInfo.selectedBootType = $scope.bootTypeDefault;//default value cfgBootOptionsService.getBootDevice() .success(function (data) { if (data.items != null && data.items[0] != null) { var tmp = data.items[0].devices; $scope.bootDeviceList = setBootDeviceList(tmp); console.log(angular.fromJson($scope.bootDeviceList)); $scope.bootOrderSetting = data.items[0].setting_id; $scope.bootOrder.defaultGroup = []; $scope.bootOrder.defaultDevice = []; } }) .error(function (data, status, headers, config) { }); }; /** * * @param datas */ var setBootDeviceList = function (datas) { angular.forEach(datas, function (group, index) { group.mriName = group.label.replace(' ', '') + 'BootOrder'; group.index = index; var _tmp = {}; if(group.order > 0) { group.ordered = 1; _tmp = { "index": "0", "label": "", "order": 1, "ordered": 1, "value": "" }; group.content = [_tmp]; group.count = 0; group.orderedCount = 1; } else { group.ordered = 0; _tmp = { "index": "0", "label": "", "order": 0, "ordered": 0, "value": "" }; group.content = [_tmp]; group.count = 1; group.orderedCount = 0; } if(group.hasOwnProperty('content') && angular.isArray(group.content)) { angular.forEach(group.content, function (device, index) { }); } }); return datas; }; /** * * @param group */ var setGroups = function (group) { //Add Select Group if ($scope.isInSelected(group.index, $scope.bootOrder.selectedGroupIndex)) { $scope.bootOrder.selectedGroupIndex.remove(group.index); } else {//Remove Group $scope.bootOrder.selectedGroupIndex.push(group.index); } }; /** * * @param group * @param groupTag * @param device */ var setDevices = function (group, groupTag, device) { //Set Group for (var attr in group) { if (group.hasOwnProperty(attr) && !angular.isArray(group[attr])) { $scope.deviceOrder[groupTag][attr] = group[attr]; } } //Device Data if ($scope.deviceOrder[groupTag].content == null) { $scope.deviceOrder[groupTag].content = []; } //Add Select Device if (!$scope.isInSelected(device, $scope.deviceOrder[groupTag].content)) { $scope.deviceOrder[groupTag].content.push(device); $scope.bootOrder.selectedDeviceIndex.push(group.index + '_' + device.index); } else {//Remove Device $scope.deviceOrder[groupTag].content.remove(device); $scope.bootOrder.selectedDeviceIndex.remove(group.index + '_' + device.index); } //Rest Select Device if (!$scope.isInSelected($scope.deviceOrder[groupTag], $scope.bootOrder.selectedDevices) && $scope.deviceOrder[groupTag] != null) { $scope.bootOrder.selectedDevices.push($scope.deviceOrder[groupTag]); } if ($scope.deviceOrder[groupTag].content.length == 0) { $scope.bootOrder.selectedDevices.remove($scope.deviceOrder[groupTag]); } }; /** * * @param groupTag * @param group * @param ordered */ $scope.selectGroup = function (groupTag, group, ordered) { if ($scope.bootOrder.selectedGroupIndex == null) { $scope.bootOrder.selectedGroupIndex = []; } $scope.groupOrder.ordered = ordered; if (group != null) { setGroups(group); angular.forEach(group.content, function (device) { if (!device.ordered == ordered) {//Only add that ordered or not ordered at one time $scope.selectDevices(group.mriName, group, device, ordered); } }); } }; /** * * @param groupTag * @param group * @param device * @param ordered */ $scope.selectDevices = function (groupTag, group, device, ordered) { if ($scope.bootOrder.selectedDevices == null) { $scope.bootOrder.selectedDevices = []; $scope.bootOrder.selectedDeviceIndex = []; } if ($scope.deviceOrder[groupTag] == null) { $scope.deviceOrder[groupTag] = {}; } // $scope.bootOrder.selectedGroupIndex = null; $scope.deviceOrder.ordered = ordered; if (device != null) { setDevices(group, groupTag, device); } }; /** * * @param target * @param selectedList * @returns {boolean} */ $scope.isInSelected = function (target, selectedList) { var existed = false; //If Object if (angular.isObject(target)) { angular.forEach(selectedList, function (data) { if (_.isEqual(target, data) || data == target) { existed = true; } }); } else if (angular.isNumber(target)) { angular.forEach(selectedList, function (data) { if (data == target) { existed = true; } }); } //If return existed; }; /** * Filter : Exclude the device that not in boot order list * @param item device * @returns {boolean} not in boot order list */ $scope.noBootFilter = function (item) { return !(item.ordered > 0); }; /** * Filter : Include the device that in boot order list * @param item device * @returns {boolean} in boot order list */ $scope.bootOrderFilter = function (item) { return (item.ordered > 0); }; /** * Get Current Boot Order */ var getCurrentOrder = function (bootDeviceList) { $scope.bootOrder.current = []; $scope.bootOrder.currentGroup = []; $scope.bootOrder.currentDevice = []; var groupList = angular.copy(bootDeviceList); groupList.sort(function (a, b) { return a.order - b.order }); //set current group and device angular.forEach(groupList, function (group) { if (group.ordered > 0) { $scope.bootOrder.currentGroup.push(group.value); var deviceList = angular.copy(group.content); deviceList.sort(function (a, b) { return a.order - b.order }); angular.forEach(deviceList, function (device) { if (device.ordered > 0) { $scope.bootOrder.currentDevice.push(group.value + '_' + device.value); } }); } }); //get current group order string $scope.bootOrder.current.push($scope.bootOrderSetting + ':' + $scope.bootOrder.currentGroup.join(',')); //get current device order string angular.forEach($scope.bootOrder.currentGroup, function (group) { var currentDevice = $scope.bootOrder.currentDevice; var data = []; var _tmp = null; for (var i = 0; i < currentDevice.length; i++) { _tmp = currentDevice[i].split('_'); if(group == _tmp[0] && _tmp[1] != '') { data.push(_tmp[1]); } } if(data.length > 0) { $scope.bootOrder.current.push(group + ':' + data.join(',')); } }); }; /** * * @param order * @param defaultOrder */ /** * Set Initial Boot Order into bootOrder.default and wolBootOrderDefault * @param ordered is ordered or not * @param value group.index / group.index_device.value * @param defaultOrder default boot order list * @param currentOrder current boot order list */ $scope.setDefaultOrder = function (ordered, value, defaultOrder) { if (Boolean(ordered)) { defaultOrder.push(value); } }; /** * Current Order Compared To Default Order * @param currentOrder current boot order list * @param defaultOrder default boot order list * @returns {boolean} is same or not */ $scope.orderCompareToDefault = function (currentOrder, defaultOrder) { return currentOrder.join(";") != defaultOrder.join(";"); }; /** * Check Order Changed, If Changed Show Radio Group And Button Group * @returns {boolean} is changed or not */ $scope.checkOrderChg = function () { var flag = false; //get default group order string $scope.bootOrder.default = []; $scope.bootOrder.default.push($scope.bootOrderSetting + ':' + $scope.bootOrder.defaultGroup.join(',')); //get default device order string angular.forEach($scope.bootOrder.defaultGroup, function (group) { var defaultDevice = $scope.bootOrder.defaultDevice; var data = []; var _tmp = null; for (var i = 0; i < defaultDevice.length; i++) { _tmp = defaultDevice[i].split('_'); if(group == _tmp[0] && _tmp[1] != '') { data.push(_tmp[1]); } } if(data.length > 0) { $scope.bootOrder.default.push(group + ':' + data.join(',')); } }); //if changed show apply radio and button groups getCurrentOrder($scope.bootDeviceList); if (($scope.bootOrderOpsInfo.selectedBootType != $scope.bootTypeDefault) || $scope.orderCompareToDefault($scope.bootOrder.current, $scope.bootOrder.default)) { flag = true; } $scope.bootOptionTypeBtns = flag; // console.log('---------- default : ' + $scope.bootOrder.default.join(';')); // console.log('---------- current : ' + $scope.bootOrder.current.join(';')); return flag; }; /** * Add Group Or Device in Order List * @param item group/device * @param itemList order list */ var addInOrderList = function (item, itemList) { var count = 0; for (var index in itemList) { if (itemList.hasOwnProperty(index) && itemList[index].order > 0) { count++; } } item.order = count + 1; }; /** * Remove Group Or Device From Order List * @param item group/device * @param itemIndex group/device index * @param itemList order list */ var removeFromOrderList = function (item, itemIndex, itemList) { angular.forEach(itemList, function (data, index) { if (data.order > item.order && index != itemIndex) { data.order--; itemList[index] = data; } }); item.order = 0; }; /** * Changing Available Boot Order, Add To Or Remove From Order List * @param ordered is in order list or not, true : Add, false : Remove */ $scope.generateOrderList = function (ordered) { var selectedGroupDeivces = $scope.bootDeviceList; var selectedDeviceIndex = $scope.bootOrder.selectedDeviceIndex; if ($scope.deviceOrder.ordered == ordered) { angular.forEach(selectedDeviceIndex, function (indexStr) { var _gIndex = indexStr.split('_')[0];//group index var _dIndex = indexStr.split('_')[1];//device index var _group = selectedGroupDeivces[_gIndex];//get group data var _devices = _group.content;//get device list data var _device = _group.content[_dIndex];//get device data //set group in order list _group.ordered = ordered; //set device in order list _device.ordered = ordered; //modify group ordered count and no ordered count if (ordered) { _group.count--; _group.orderedCount++; if (_group.orderedCount == 1) { addInOrderList(_group, selectedGroupDeivces); } addInOrderList(_device, _devices); } else { _group.count++; _group.orderedCount--; if (_group.orderedCount == 0) { removeFromOrderList(_group, _gIndex, selectedGroupDeivces); } removeFromOrderList(_device, _dIndex, _devices); } _devices[_dIndex] = _device;//set device _group.content = _devices;//set ordered devices list which contains ordered device $scope.bootDeviceList[_gIndex] = _group;//set ordered group }); } //reset data status $scope.bootOrder.selectedDevices = null; $scope.bootOrder.selectedGroupIndex = null; $scope.bootOrder.selectedDeviceIndex = null; $scope.deviceOrder = {}; $scope.checkOrderChg();// }; /** * move up (ascending) * @param item selected item * @param itemIndex selected item index * @param itemList selected itemlist */ var ascending = function (item, itemIndex, itemList) { //set selected order if (item.order > 1) { item.order--; itemList[itemIndex] = item; } //reset selected prev's order angular.forEach(itemList, function (data, index) { if (itemList[itemIndex].order == data.order && index != itemIndex) { data.order++; itemList[index] = data; } }); }; /** *move down (descending) * @param item selected item * @param itemIndex selected item index * @param itemList selected itemlist */ var descending = function (item, itemIndex, itemList) { //set selected order if (item.order < itemList.length) { item.order++; itemList[itemIndex] = item; } //reset selected next's order angular.forEach(itemList, function (data, index) { if (itemList[itemIndex].order == data.order && index != itemIndex) { data.order--; itemList[index] = data; } }); }; /** * Change Group Or Device Order * @param order order way, if ascending is true, order num + 1, or -1 * @returns {boolean} */ $scope.changeOrder = function (order) { var selectedGroupIndex = $scope.bootOrder.selectedGroupIndex; var selectedDeviceIndex = $scope.bootOrder.selectedDeviceIndex; //Group Ordering First angular.forEach(selectedGroupIndex, function (indexStr) { var _gIndex = indexStr;//group index var _group = $scope.bootDeviceList[_gIndex];//get group data if (order) { //move up (ascending) ascending(_group, _gIndex, $scope.bootDeviceList); } else { //move down (descending) descending(_group, _gIndex, $scope.bootDeviceList); } $scope.bootDeviceList[_gIndex] = _group;//set ordered group }); // Device Ordering Second angular.forEach(selectedDeviceIndex, function (indexStr) { var _gIndex = indexStr.split('_')[0];//group index var _dIndex = indexStr.split('_')[1];//device index var _group = $scope.bootDeviceList[_gIndex];//get group data var _devices = _group.content;//get device list data var _device = _group.content[_dIndex];//get device data if (order) { //move up (ascending) ascending(_device, _dIndex, _devices); } else { //move down (descending) descending(_device, _dIndex, _devices); } _group.content = _devices;//set ordered devices list which contains ordered device $scope.bootDeviceList[_gIndex] = _group;//set ordered group }); $scope.checkOrderChg(); }; /** * Apply Boot Order, and if set successful show confirm restart dialog * @param dailogId confirm restart dialog id */ $scope.applyBootOrderSetting = function (dailogId) { $scope.applyBootOrderResult = -1; if ($scope.bootOrderOpsInfo.selectedRestrtWay == '') { $("#alert").modal(); return; } //compare to default, only changed do apply if ($scope.orderCompareToDefault($scope.bootOrder.current, $scope.bootOrder.default)) { var param = {'DeviceSeqList': $scope.bootOrder.current.join(";")}; cfgBootOptionsService.setBootOrder(param) .success(function (data) { if (0 == data.return) { $scope.applyBootOrderResult = 0; } else { $scope.applyBootOrderResult += 2; } }) .error(function (data, status, headers, config) { }); } $timeout(function () { $scope.$watch($scope.applyBootOrderResult, function () { //only success, do restart if ($scope.applyBootOrderResult <= 0) { $("#" + dailogId).modal(); } else if ($scope.applyBootOrderResult > 0) { $("#orderResult").modal(); } }) }, 0); }; /** * Reset Boot Order Setting */ $scope.resetBootOrderSetting = function () { $scope.bootOrder.default = []; //$scope.wolBootOrderDefault = [];remove on 2016-07-26 by lucuicheng $scope.bootOrderOpsInfo.selectedBootType = $scope.bootTypeDefault; $scope.bootOptionTypeBtns = false; $scope.initDeviceList(); }; /** * confirm to apply Boot Order Setting * @param dialogId result dialog Id */ $scope.confirmRestartToApplyBootOrder = function (dialogId) { var _powerAction = null; switch ($scope.bootOrderOpsInfo.selectedRestrtWay) { case 'altRestartImm': _powerAction = 8; break; case 'altShutdown': _powerAction = 4; break; default: _powerAction = null; } if(_powerAction != null) { var param = {"powerAction": _powerAction}; var restPowerAction = homeQuickActionService.restPowerAction(); restPowerAction.save(param, function (data) { if (0 == data.return) { $("#" + dialogId).modal(); } }, function (err) { console.log("failed"); }); } else { $scope.initDeviceList(); } }; /*--------------------------------One-Time settting--------------------------------*/ $scope.showApplyBootSetting = true;//default value, the following two are the same $scope.showRadioSetting = false; $scope.showPXEdesc = false; $scope.bootDeviceOpsInfo = {}; $scope.bootDeviceOpsInfo.selectedRestrtWay = ''; //need to read default via rest call $scope.bootDeviceOpsInfo.default = 'none'; $scope.bootDeviceOpsInfo.map = {}; $scope.setDeviceOpsInfoMap = function (key, value) { $scope.bootDeviceOpsInfo.map[key] = value; }; $scope.bootDeviceOpsInfo.value = $scope.bootDeviceOpsInfo.default; //check dev change, if changed show radio group and button group $scope.selChanged = function (value) { if (value != $scope.bootDeviceOpsInfo.default) { $scope.showRadioSetting = true; } else { $scope.showRadioSetting = false; } if ('06' == value) { $scope.showPXEdesc = !$scope.showPXEdesc; } else { $scope.showPXEdesc = false; } }; //show confirm dialog $scope.applyBootDevSetting = function (dailogId) { if ($scope.bootDeviceOpsInfo.selectedRestrtWay == '') { $("#alert").modal(); return; } var param = {'Device': $scope.bootDeviceOpsInfo.value}; cfgBootOptionsService.setOneTimeBoot(param) .success(function (data) { if ('0' == data.return) { $scope.applyBootDeviceResult = 0; $("#" + dailogId).modal(); } else { $scope.applyBootDeviceResult = 1; $("#deviceResult").modal(); } }) .error(function (data, status, headers, config) { }); }; //reset Boot Dev Setting $scope.resetBootDevSetting = function () { $scope.bootDeviceOpsInfo.value = $scope.bootDeviceOpsInfo.default; $scope.showRadioSetting = false; $scope.showPXEdesc = false; }; //confirm to apply Boot Dev Setting $scope.confirmBootDevSettingToApply = function (dailogId) { var _powerAction = null; switch ($scope.bootDeviceOpsInfo.selectedRestrtWay) { case 'altRestartImm': _powerAction = 8; break; case 'altShutdown': _powerAction = 4; break; default: _powerAction = null; } var restPowerAction = homeQuickActionService.restPowerAction(); if(_powerAction != null) { var param = {"powerAction": _powerAction}; restPowerAction.save(param, function (data) { if (0 == data.return) { $("#" + dailogId).modal(); } }, function (err) { console.log("failed"); }); } else { $scope.initDeviceList(); } } }]); <file_sep>'use strict'; angular.module('imm3.storage.service', ['ngResource']) .factory('storageInfoService', ['$resource', '$http', function ($resource, $http) { var basePath = '/api/'; var service = { restStorageInfo: function (params) { var url = basePath + 'storageinfo'; return $http.get(url, params); }, restDriveInfo: function (params) { var url = basePath + 'driveinfo'; return $http.get(url, params); }, restControllerInfo: function (params) { var url = basePath + 'function/raid_alldevices'; return $http.get(url, params); }, restControllerOps: function (params) { var url = basePath + 'function'; return $http.post(url, params); }, restControllerQuery: function (params) { var url = basePath + 'function/raid_conf'; return $http.get(url, params); } }; return service; }])<file_sep>'use strict'; /* * * */ angular.module('myApp.powerpolicy', [ 'ngRoute', 'pascalprecht.translate','imm3.home.cfg.powerpolicy.service']) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/powerPolicy', { templateUrl : 'www/views/power.policy.html', controller : 'powerPolicyCtrl' }); } ]) .controller('powerPolicyCtrl', [ '$scope','$rootScope', '$localStorage','$location','cfgPowerPolicyService', function($scope,$rootScope,$localStorage,$location,cfgPowerPolicyService) { $scope.$emit('clickMenuItem1', 'menuTitlePowerPolicy'); $rootScope.loginInfo = angular.copy($localStorage.loginInfo); if(!$rootScope.loginInfo.loginStatus){ $location.path("/login"); }else{ console.log("I am in power policy page"); } $scope.tier = $localStorage.tier; $scope.powPolicy = {}; $scope.powPolicy.map = { "0": "translatedACLabel", "1": "translatedDCLabel" }; //need to read default via rest call $scope.selChanged = function(value) { console.log(value); return false; }; $scope.showAdditionalInvInfo = false; var valLimit = function(cur, min, max){ if(cur < min){ return min; }else if(cur > max){ return max; }else{ return cur; } } var powerCapInfo = cfgPowerPolicyService.powerCapInfo(); var setCapInfo = cfgPowerPolicyService.setCapInfo(); var setRedun = cfgPowerPolicyService.setRedun(); var getPsInfo = cfgPowerPolicyService.getPsInfo(); var getPsDetail = cfgPowerPolicyService.getPsDetail(); getPsInfo.get(function(data){ angular.forEach(data['items'],function(item){ if(item.type == "ps"){ $scope.psInfo =item; } }); }); getPsDetail.get(function(data){ $scope.psDetails = data['items'][0]['power']; console.log("ps lenght:"+$scope.psDetails.length); }); powerCapInfo.get({params:"GetPowerInfoForRedunMode"}, function(data){ $scope.redun = data['items'][0]; $scope.non_redun = data['items'][1]; }); //powerCapInfo.get({params:"GetPowerCappingRanges"}, function(data){ // $scope.capping_mode = data['items'][0]['capping_mode']+''; // $scope.ori_capping_mode = $scope.capping_mode; //}); //start power cap var getPowerCapInfo = function(){ powerCapInfo.get({params:"GetPowerPolicySettings"}, function(data){ var item = data["items"][0]; $scope.cap_enable = item["cap_enable"] + ''; $scope.redun_mode = item["redun_mode"] + ''; $scope.cap_mode = item["cap_mode"]+ ''; $scope.cap_min_pwr_ac = item["cap_min_pwr_ac"]; $scope.cap_max_pwr_ac = item["cap_max_pwr_ac"]; $scope.cap_soft_pwr_ac = item["cap_soft_pwr_ac"]; $scope.cap_min_pwr_dc = item["cap_min_pwr_dc"]; $scope.cap_max_pwr_dc = item["cap_max_pwr_dc"]; $scope.cap_soft_pwr_dc = item["cap_soft_pwr_dc"]; $scope.cap_value_ac = item["cap_value"]; $scope.cap_value_dc = item["cap_value"]; $scope.ori_cap_enable = $scope.cap_enable; $scope.ori_redun_mode = $scope.redun_mode; $scope.ori_cap_mode = $scope.cap_mode; $scope.ori_cap_min_pwr_ac = $scope.cap_min_pwr_ac; $scope.ori_cap_max_pwr_ac = $scope.cap_max_pwr_ac; $scope.ori_cap_soft_pwr_ac = $scope.cap_soft_pwr_ac; $scope.ori_cap_min_pwr_dc = $scope.cap_min_pwr_dc; $scope.ori_cap_max_pwr_dc = $scope.cap_max_pwr_dc; $scope.ori_cap_soft_pwr_dc = $scope.cap_soft_pwr_dc; $scope.ori_cap_value_ac = $scope.cap_value_ac; $scope.ori_cap_value_dc = $scope.cap_value_dc; console.log("value:"+$scope.cap_value); //init slider $('#sliderDiv').fadeIn(2000); $('#sliderBgDiv').fadeIn(3000); console.log("init slider"); $("#acSlider").slider({ // always display the tips tooltip: 'always', height:"2px", min:$scope.cap_soft_pwr_ac, max:$scope.cap_max_pwr_ac, value:$scope.cap_value_ac, formatter: function(value) { //return 'Current value: ' + value; return value+' Watts'; } }).on("slide", function(slideEvt) { $("#ex6SliderValAc").val(slideEvt.value); $scope.cap_value_ac = slideEvt.value; }).on("slideStop", function(slideStopEvt) { $("#ex6SliderValAc").val(slideStopEvt.value); $scope.cap_value_ac = slideStopEvt.value; }); // .on("slidechange", function(slideChangeEvt) { // $("#ex6SliderVal").val(slideChangeEvt.value); // console.log("slide change:"+slideChangeEvt.value); //}) $("#dcSlider").slider({ // always display the tips tooltip: 'always', height:"2px", min:$scope.cap_soft_pwr_dc, max:$scope.cap_max_pwr_dc, value:$scope.cap_value_dc, formatter: function(value) { //return 'Current value: ' + value; return value+' Watts'; } }).on("slide", function(slideEvt) { $("#ex6SliderValDc").val(slideEvt.value); $scope.cap_value_dc = slideEvt.value; }).on("slideStop", function(slideStopEvt) { $("#ex6SliderValDc").val(slideStopEvt.value); $scope.cap_value_dc = slideStopEvt.value; }); }); } getPowerCapInfo(); $scope.compareCap = function(){ if($scope.ori_cap_enable != $scope.cap_enable){ console.log("1"); return true; }else if($scope.ori_cap_mode != $scope.cap_mode){ console.log("2"); console.log("ori mode is:"+$scope.ori_cap_mode); console.log("cur mode is:"+$scope.cap_mode); return true; }else if($scope.ori_cap_min_pwr_ac != $scope.cap_min_pwr_ac){ console.log("3"); return true; }else if($scope.ori_cap_max_pwr_ac != $scope.cap_max_pwr_ac){ console.log("4"); return true; }else if($scope.ori_cap_soft_pwr_ac != $scope.cap_soft_pwr_ac){ console.log("5"); return true; }else if($scope.ori_cap_min_pwr_dc != $scope.cap_min_pwr_dc){ console.log("6"); return true; }else if($scope.ori_cap_max_pwr_dc != $scope.cap_max_pwr_dc){ console.log("7"); return true; }else if($scope.ori_cap_soft_pwr_dc != $scope.cap_soft_pwr_dc){ console.log("8"); return true; }else if($scope.ori_cap_value_ac != $scope.cap_value_ac){ console.log("9"); return true; }else if($scope.ori_cap_value_dc != $scope.cap_value_dc){ console.log("10"); return true; }else{ return false; } } $scope.resetCap = function(){ $scope.cap_enable = $scope.ori_cap_enable; $scope.cap_mode = $scope.ori_cap_mode; $scope.cap_min_pwr_ac = $scope.ori_cap_min_pwr_ac; $scope.cap_max_pwr_ac = $scope.ori_cap_max_pwr_ac; $scope.cap_soft_pwr_ac = $scope.ori_cap_soft_pwr_ac; $scope.cap_min_pwr_dc = $scope.ori_cap_min_pwr_dc; $scope.cap_max_pwr_dc = $scope.ori_cap_max_pwr_dc; $scope.cap_soft_pwr_dc = $scope.ori_cap_soft_pwr_dc; $scope.cap_value_ac = $scope.ori_cap_value_ac; $scope.cap_value_dc = $scope.ori_cap_value_dc; $('#acSlider').slider('setValue', $scope.cap_value_ac); $('#dcSlider').slider('setValue', $scope.cap_value_dc); } $scope.policyApply = function(){ var cap_val = 0; if($scope.redun_mode == 0){ cap_val = $scope.cap_value_ac; }else{ cap_val = $scope.cap_value_dc; } var payLoad = $scope.cap_enable+','+$scope.cap_mode+','+cap_val; setCapInfo.save({},{"SetPowerCappingPolicy":payLoad},function(data){ if(data["return"] == 0){ $scope.$emit('showErrMsgBox', "Saved successfully!"); }else{ $scope.$emit('showErrMsgBox', "error code:"+data.return); } }, function(error){ $scope.$emit('showErrMsgBox',error); }); } //end power cap //start power Redundancy //powerCapInfo.get({params:"GetRedundant"}, function(data){ // $scope.redudant = data["items"][0]; // console.log("data 0:"+JSON.stringify($scope.redudant)); // $scope.non_redudant = data["items"][1]; // $scope.reduUsage = Math.round(100 * $scope.redudant["estimated_usage"]/$scope.redudant["max_power_limit"]); // $scope.nonReduUsage = Math.round(100 * $scope.non_redudant["estimated_usage"]/$scope.non_redudant["max_power_limit"]); // console.log("redundant data:"+JSON.stringify(data)); //}); $scope.redundantReset = function(){ $scope.redun_mode = $scope.ori_redun_mode; } $scope.redundantApply = function(){ var payLoad = { "SetPowerRedunMode": $scope.redun_mode + '' }; setCapInfo.save({},payLoad,function(data){ if(data["return"] == 0){ $scope.$emit('showErrMsgBox', "Saved successfully!"); } },function(error){ $scope.$emit('showErrMsgBox', error); }); } //need to read the initial values via rest call? //$scope.redundantChecked=true; //$scope.rValue="Redundant";// $scope.redundantChecked=false; $scope.rValue="Non-redundant";//Non-redundant //need to read the initial values via rest call? $scope.cappingEnabled="Enable" //false as default, the apply/reset buttons will //only be displayed when there are changes $scope.powerRedundantBtns=false; //false as default, the apply/reset buttons will //only be displayed when there are changes $scope.powCappingBtns=false; // $scope.showInventory=false; $scope.onePowSupplyWarning=false; //2(non-redun) as default, 1-redun, 2-non $scope.selectedRedun = 2; $("#myPopOver1").popover({content: "Help content for<br> Power Redundant !",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#myPopOver2").popover({content: "Help content for<br> Power Capping Policy !",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#myPopOver3").popover({content: "<font size=\"1px\">Estimated power usage is over thresthold.<br><br> Recommended actions:<br>1. Enable \"Throttling\";<br> 2. Replace failed power supply or add more;<br> 3. Reduce components.</font>",trigger: 'manual'}) //.on("mouseover", function() { // $(this).popover('show'); //}) .on("click", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $('.sliderValue').on('keypress',function(event){ if(event.keyCode == "13") { if($scope.cap_mode == "0"){ console.log("ac"); $scope.cap_value_ac = $('#ex6SliderValAc').val(); $scope.cap_value_ac = valLimit($scope.cap_value_ac, $scope.cap_soft_pwr_ac, $scope.cap_max_pwr_ac); document.getElementById('ex6SliderValAc').value = $scope.cap_value_ac; console.log("ac value:"+ $scope.cap_value_ac); $('#acSlider').slider('setValue', parseInt($('#ex6SliderValAc').val())); }else{ $scope.cap_value_dc = $('#ex6SliderValDc').val(); $scope.cap_value_dc = valLimit($scope.cap_value_dc, $scope.cap_soft_pwr_dc, $scope.cap_max_pwr_dc); document.getElementById('ex6SliderValDc').value = $scope.cap_value_dc; $('#dcSlider').slider('setValue', parseInt($('#ex6SliderValDc').val())); } } }); $scope.showPowSuppInvTable = function(id) { $scope.showInventory =! $scope.showInventory; }; $scope.checkRedundantChg = function(radioValue) { console.log("radioValue is:"+radioValue); $scope.powerRedundantBtns=true; if(radioValue == "Redundant"){ $scope.selectedRedun = 1; }else if(radioValue == "Non-redundant"){ $scope.selectedRedun = 2; } /* if(radioValue != $scope.rValue){ $scope.redundantChecked=!$scope.redundantChecked; $scope.powerRedundantBtns=true; }else{ $scope.powerRedundantBtns=false; } */ }; $scope.checkCappingChg = function(radioValue) { var max = $( "#slider" ).slider( "option", "max" ); // alert("value:"+$scope.cap_value); console.log(radioValue); if(radioValue == "enable"){ $scope.cap_enable = 1; }else{ $scope.cap_enable = 0; } $scope.powCappingBtns=true; /*if(radioValue != $scope.cappingEnabled){ $scope.powCappingChecked=!$scope.powCappingChecked; $scope.powCappingBtns=true; }else{ $scope.powCappingBtns=false; } */ }; $scope.closeTip = function() { $('#myTip').alert('close'); }; $scope.onInputChange = function(){ console.log('saving changes'); }; } ]); <file_sep>'use strict'; angular.module('imm3.home.filter', []) .filter('homeHwEvtCount', [function() { return function(count) { if(undefined == count) { return; } if(count === 0) { return; } else { return count; } }; }]) .filter('homeHwInstallCount', [function() { return function(slotsCount, slotsInstall) { if(undefined == slotsCount || undefined == slotsInstall) { return; } if(slotsInstall === 0) { return; } else { return " / " + slotsCount; } }; }]) .filter('homePowerState', [function() { return function(state) { if(undefined == state) { return; } switch(state) { case 0: return "Off"; case 1: return "On"; case 2: return "Suspend to memory"; default: return "Unknown"; } }; } ]) .filter('homeServerState', [function(){ return function(state){ if(undefined == state) { return; } switch(state) { case 0: return "Power off/State unknown"; case 1: return "System on/Starting UEFI"; case 2: return "System running in UEFI"; case 3: return "System stopped in UEFI (error detected)"; case 4: return "Booting OS or in undetected OS"; case 5: return "OS booted"; case 6: return "Suspend to RAM"; case 7: return "System running in setup"; default: return "Unknown"; } } }]) .filter('homePowerDuration', [function() { return function(duration) { if(undefined == duration) { return; } return Math.floor((duration / 60)) + "h " + (duration % 60) + "min"; }; }]) .filter('homeLocation', [function() { return function(location) { if(undefined == location) { return; } return location.location + ", " + location.roomId + ", " + location.rackId + " Rack, " + location.lowestUnit + "(" + location.height + ")U"; }; }]) .filter('homeLocationLed', [function() { return function(locLedState) { if(undefined == locLedState) { return; } switch(locLedState) { case 0: return "off"; case 1: return "on"; case 2: return "blink"; } }; }]) .filter('homeImmVersion', [function() { return function(immVersion) { if(undefined == immVersion) { return; } return "V" + immVersion["firmware.version"] + " Build ID: " + immVersion["firmware.build"] + ", " + immVersion["firmware.release_date"]; }; }]) .filter('homeUefiVersion', [function() { return function(uefiVersion) { if(undefined == uefiVersion) { return; } return "V" + uefiVersion.version + " " + uefiVersion.releaseDate; }; }]) .filter('homeversion', [function() { return function(firmware) { if(undefined == firmware) { return; } return "V" + firmware["version"] + " Build ID: " + firmware["build"]; }; }]) .filter('eventsrcpic', [function() { return function(severity) { if(undefined == severity) { return; } if(severity == "I"){ return "www/images/event/info_icon.png"; }else if(severity == "W"){ return "www/images/event/warning_icon.png"; }else if(severity == "E"){ return "www/images/event/ic_error_red.png"; } }; }]) .filter('dateFormat', [function() { return function(date) { var monArray = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']; if(undefined == date) { return; } var transformedDate = new Date(Date.parse(date)); var day = transformedDate.getDate(); var month = monArray[transformedDate.getMonth()]; var year = transformedDate.getFullYear(); var hour = transformedDate.getHours()>11?transformedDate.getHours()-11:transformedDate.getHours() + 1; var minute = transformedDate.getMinutes() + 1; var second = transformedDate.getSeconds() + 1; var aORp = transformedDate.getHours()>11?'PM':'AM'; var formattedDate = day+' '+ month+' '+ year+', '+hour+':'+minute+':'+second+' '+aORp; return formattedDate; }; }]) .filter('dateFormatReverse', [function() { return function(date) { var monArray = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']; if(undefined == date) { return; } var transformedDate = new Date(Date.parse(date)); var day = transformedDate.getDate(); var month = monArray[transformedDate.getMonth()]; var year = transformedDate.getFullYear(); var hour = transformedDate.getHours()>11?transformedDate.getHours()-11:transformedDate.getHours() + 1; var minute = transformedDate.getMinutes() + 1; var second = transformedDate.getSeconds() + 1; var aORp = transformedDate.getHours()>11?'PM':'AM'; var formattedDate = hour+':'+minute+ ' '+ aORp + ', '+ month + ' ' +day + ', ' + year; return formattedDate; }; }]) .filter('firmwareType',[function() { return function(type){ if(type == 0){ return 'UEFI Active'; }else if(type == 1){ return 'UEFI Primary'; }else if(type == 2){ return 'UEFI Backup'; }else if(type == 3){ return 'DSA'; }else if(type == 4){ return 'IMM Active'; }else if(type == 5){ return 'IMM Primary'; }else if(type == 6){ return 'IMM Backup'; }else if(type == 7){ return 'LEPT'; }else{ return 'data error'; } } }]) ; <file_sep>'use strict'; angular.module('imm3.home.cfg.userldap.service', [ 'ngResource' ]) .factory('cfgUserInfoService', [ '$resource', function($resource) { var service = {}; service.restUsersInfo = function() { return $resource('/api/dataset/imm_users'); }; service.restSNMPV3Setting = function() { return $resource('/api/dataset/imm_snmp'); }; service.restCreateUser = function() { return $resource('/api/function'); }; service.restDelUser = function() { return $resource('/api/function'); }; service.restUploadSSHKeyStr = function() { return $resource('/api/function'); }; service.restGetGlobalSetting = function() { return $resource('/api/dataset/imm_users_global'); }; service.restSetGlobalSetting = function() { return $resource('/api/dataset'); }; service.restGetLDAPSetting = function() { return $resource('/api/dataset/imm_ldap'); }; service.restSetLDAPSetting = function() { return $resource('/api/dataset'); }; return service; } ]) <file_sep>'use strict'; angular.module('imm3.home.cfg.powerpolicy.service', [ 'ngResource' ]) .factory('cfgPowerPolicyService', [ '$resource', function($resource) { var service = {}; service.powerCapInfo = function() { return $resource('/api/dataset/pwrmgmt',{params:'@params'}); }; service.setCapInfo = function() { return $resource('/api/function'); } service.setRedun = function(){ return $resource('/api/function'); } service.getPsInfo = function(){ return $resource('/api/dataset/sys_inventory'); } service.getPsDetail = function(){ return $resource('/api/dataset/imm_power_supplies'); } return service; } ]) <file_sep>'use strict'; angular.module('myApp.event', [ 'ngRoute', 'pascalprecht.translate', 'angularjs-dropdown-multiselect', 'imm3.event.service','imm3.menu.directive' ]) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/event', { templateUrl : 'www/views/event.html', controller : 'eventCtrl' }); } ]) .controller('eventCtrl', ['$scope', '$rootScope', '$localStorage', '$location', '$filter', '$interval', '$timeout','cfgEventService', 'cfgDeleteEventService', 'cfgAuditService', 'cfgMaintainHistoryService', 'cfgAlertRecipientService' , 'cfgAlertSNMPv3RecipientService','cfgSMTPServerService', function($scope, $rootScope, $localStorage, $location, $filter, $interval,$timeout, cfgEventService, cfgDeleteEventService, cfgAuditService, cfgMaintainHistoryService, cfgAlertRecipientService, cfgAlertSNMPv3RecipientService, cfgSMTPServerService) { $scope.$emit('setCurPage1', ["event"]); $scope.$emit('clickMenuItem1', 'menuTitleEvent'); /*login session*/ $rootScope.loginInfo = angular.copy($localStorage.loginInfo); if(!$rootScope.loginInfo.loginStatus){ $location.path("/login"); }else{ console.log("I am in event page"); }; $scope.tier = $localStorage.tier; console.log("tier is :"+$scope.tier); /*locate sub-page in the navigate memu*/ $scope.$on('$viewContentLoaded', function() { $scope.$emit('clickMenuItem1', 'menuTitleEvent'); }); /*Event Page control */ //filter log $scope.icons = ["I","W","E"]; $scope.source = "All Source"; $scope.expectedDate = new Date(0); $scope.auditIcons = ["I","W","E"]; $scope.auditSource = "All Source"; $scope.auditExpectedDate = new Date(0); $scope.selectedType = "All"; $scope.hisExpectedDate = new Date(0); //changing views true $scope.showEventLog = true; $scope.showAuditLog = false; $scope.showMaintenanceHistory = false; $scope.showAlertRecipients = false; $scope.showSNMPv3AlertRecipients = false; $scope.showCustomizeTab = false; $scope.showAuditCustomizeTab = false; $scope.showCustomNote = false; $scope.showCreateEmailRecipient = false; $scope.showCreateSyslogRecipient = false; $scope.showCreateSNMPv3Recipient = false; $scope.showAlertRecipientsTab = false; $scope.showConfigureAlert = true; /*sub pop dlg*/ $scope.showSubCreateEmailRecipient = false; $scope.showSubCreateSyslogRecipient = false; $scope.showSubCreateSNMPv3Recipient = false; $scope.showSMTPServer = false; $scope.showRetryAndDelay = false; $scope.showSNMPv3Setting = false; $scope.showEditSnmpv3User = false; $scope.query=""; $scope.snmpV3Setting = {}; //suit modal style $scope.subCreateSysStyle = { "margin": "0px" } /*clear log*/ $scope.eveCheck = false; $scope.audCheck = false; // local user view /*get event data */ var restEventInfo = cfgEventService.restEventInfo(); restEventInfo.save({},{CEM_LogType: 0},function(data) { console.log('loading event information ...'); $scope.events = data["items"]; $scope.baseEvents = $scope.events.concat(); console.log("number of events:"+$scope.events.length); },function(error){ //alert("Error:"+JSON.stringify(error)); }); /*delete logs*/ var deleteEvent = cfgDeleteEventService.deleteEvent(); $scope.clearEvent = function(){ if($scope.showAuditLog){ deleteEvent.save({},{CEM_LogType:1},function(data) { console.log('delete event ...'); if(data.return == '0'){ $scope.audits = []; }else{ //alert("error:"+data.return); } },function(error){ //alert("Error:"+JSON.stringify(error)); }); }else{ deleteEvent.save({},{CEM_LogType:0},function(data) { console.log('delete event ...'); if(data.return == '0'){ $scope.events = []; }else{ //alert("error:"+data.return); } },function(error){ //alert("Error:"+JSON.stringify(error)); }); } }; //$scope.clearAudit = function(){ // deleteEvent.save({},{CEM_LogType:'1'},function(data) { // console.log('delete audit ...'); // if(data.return == '0'){ // $scope.audits = []; // }else{ // alert("error:"+data.return); // } // // },function(error){ // alert("Error:"+JSON.stringify(error)); // }); //} //get audit data restEventInfo.save({},{CEM_LogType: 1},function(data) { console.log('loading event information ...'); $scope.audits = data["items"]; $scope.baseAudits = $scope.audits.concat(); console.log("number of events:"+$scope.audits.length); },function(error){ //alert("Error:"+JSON.stringify(error)); }); /*get maintain history data*/ var restMaintainHistoryInfo = cfgMaintainHistoryService.restMaintainHistoryInfo(); var restClearMaintainHis = cfgMaintainHistoryService.restClearMaintainHis(); restMaintainHistoryInfo.get({params:"Maintainance_GetLogs,0,0,1"},function(data) { console.log('loading maintainHistoryInfo....'); $scope.maintainHistories = data['items']; $scope.baseHistories = angular.copy($scope.maintainHistories); }); /*get email/syslog recipients data*/ $scope.selectableIndex = []; var restAlertRecipientInfo = cfgAlertRecipientService.restAlertRecipientInfo(); var getAlertRecip = function(){ restAlertRecipientInfo.get(function(data) { $scope.recipients = data['items'][0]['recipients']; for(var i=0; i<$scope.recipients.length; i++){ if($scope.recipients[i]['name']){ $scope.showAlertRecipientsTab = true; $scope.showConfigureAlert = false; }else{ $scope.selectableIndex.push($scope.recipients[i]['index']); } } console.log("selectableIndex:"+$scope.selectableIndex); }); } getAlertRecip(); /*get snmpv3 recipients data*/ var restAlertSNMPv3RecipientInfo = cfgAlertSNMPv3RecipientService.restAlertSNMPv3RecipientInfo(); restAlertSNMPv3RecipientInfo.get(function(data){ console.log('loading snmpv3 recipient info....') $scope.snmpv3Recipients = data["snmpv3RecipientsInfo"]; }); /*Event Severity Filter*/ $scope.critical_image = "www/images/event/ic_error_red.png"; $scope.warning_image = "www/images/event/warning_icon.png"; $scope.info_image = "www/images/event/info_icon.png"; $scope.eventFilterCritical = function() { console.log('critical img clicked'); var element = $("#critical_img"); if(element.hasClass("blueBorder")){ console.log("it has blue border"); element.removeClass("blueBorder"); }else{ console.log("it doesnt has blue border"); element.addClass("blueBorder"); } ; $scope.criticalEvent = []; angular.forEach($scope.baseEvents, function(item, index) { console.log("level\t"+item.level); if(item.level == 'critical') { $scope.criticalEvent.push(item); } var tmpData1 = $scope.events; $scope.events = $scope.criticalEvent; }); }; $scope.eventFilterWarn = function() { console.log('warning img clicked'); var element = $("#warning_image"); if(element.hasClass("blueBorder")){ console.log("it has blue border"); element.removeClass("blueBorder"); }else{ console.log("it doesnt has blue border"); element.addClass("blueBorder"); } $scope.warnEvent = []; angular.forEach($scope.baseEvents, function(item, index) { console.log("level\t"+item.level); if(item.level == 'warning') { $scope.warnEvent.push(item); } var tmpData1 = $scope.events; $scope.events = $scope.warnEvent; }); }; $scope.alterBorderAndList = function(whichPic){ var element = $('#'+whichPic+''); var elements = $(".aa"); var severity = ""; console.log("which pic:"+whichPic); switch (whichPic) { case "critical_img": severity = "E"; break; case "warning_image": severity = "W"; break; case "info_image": severity = "I"; break; } console.log("length of base events:"+$scope.baseEvents.length); if(element.hasClass("blueBorder")){ element.removeClass("blueBorder"); $scope.icons.remove(severity); }else{ element.addClass("blueBorder"); if($scope.icons.indexOf(severity)<0){ $scope.icons.push(severity); } } $scope.events = $scope.filterLog($scope.baseEvents,$scope.icons,$scope.source,$scope.expectedDate); console.log("number of icons:"+$scope.icons.length); }; $scope.eventFilterInfo = function() { console.log('info img clicked'); var element = $("#info_image"); if(element.hasClass("blueBorder")){ console.log("it has blue border"); element.removeClass("blueBorder"); }else{ console.log("it doesnt has blue border"); element.addClass("blueBorder"); } $scope.infoEvent = []; angular.forEach($scope.baseEvents, function(item, index) { console.log("level\t"+item.level); if(item.level == 'info') { $scope.infoEvent.push(item); } var tmpData1 = $scope.events; $scope.events = $scope.infoEvent; }); }; /*Audit severity filter*/ $scope.alterAuditBorder = function(whichPic){ var element = $('#'+whichPic+''); var severity = ""; console.log("which pic:"+whichPic); switch (whichPic) { case "audit_critical_img": severity = "E"; break; case "audit_warning_image": severity = "W"; break; case "audit_info_image": severity = "I"; break; } console.log("length of base events:"+$scope.baseEvents.length); if(element.hasClass("blueBorder")){ console.log("has class"); element.removeClass("blueBorder"); $scope.auditIcons.remove(severity); }else{ console.log("dose not"); element.addClass("blueBorder"); if($scope.auditIcons.indexOf(severity)<0){ $scope.auditIcons.push(severity); } } console.log("length of auditicons:"+$scope.auditIcons.length); $scope.audits = $scope.filterLog($scope.baseAudits,$scope.auditIcons,$scope.auditSource,$scope.auditExpectedDate); }; /*Audit Severity Filter*/ $scope.auditFilterCritical = function() { $scope.criticalEvent = []; angular.forEach($scope.baseAudits, function(item, index) { console.log("level\t"+item.level); if(item.level == 'critical') { $scope.criticalEvent.push(item); } var tmpData1 = $scope.audits; $scope.audits = $scope.criticalEvent; }); }; $scope.auditFilterWarn = function() { $scope.warnEvent = []; angular.forEach($scope.baseAudits, function(item, index) { console.log("level\t"+item.level); if(item.level == 'warning') { $scope.warnEvent.push(item); } var tmpData1 = $scope.audits; $scope.audits = $scope.warnEvent; }); }; $scope.auditFilterInfo = function() { $scope.infoEvent = []; angular.forEach($scope.baseAudits, function(item, index) { console.log("level\t"+item.level); if(item.level == 'info') { $scope.infoEvent.push(item); } var tmpData1 = $scope.audits; $scope.audits = $scope.infoEvent; }); }; /**** Audit Filter Source colum *****/ $scope.auditFilterAll = function() { $scope.allSource = []; angular.forEach($scope.baseAudits, function(item, index) { console.log("Source\t"+item.Source); if(item.Source == 'All') { $scope.allSource.push(item); } var tmpData1 = $scope.audits; $scope.audits = $scope.allSource; }); }; $scope.filterAuditSource = function(s){ $scope.auditSource = s; $scope.audits = $scope.filterLog($scope.baseAudits,$scope.auditIcons,s,$scope.auditExpectedDate); } $scope.auditFilterSys = function() { $scope.systemEvent = []; angular.forEach($scope.baseAudits, function(item, index) { console.log("Source\t"+item.Source); if(item.Source == 'System') { $scope.systemEvent.push(item); } var tmpData1 = $scope.audits; $scope.audits = $scope.systemEvent; }); }; $scope.auditFilterDriver = function() { $scope.driverEvent = []; angular.forEach($scope.baseAudits, function(item, index) { console.log("Source\t"+item.Source); if(item.Source == 'Driver') { $scope.driverEvent.push(item); } var tmpData1 = $scope.audits; $scope.audits = $scope.driverEvent; }); }; $scope.auditFilterCPU = function() { $scope.cpuEvent = []; angular.forEach($scope.baseAudits, function(item, index) { console.log("Source\t"+item.Source); if(item.Source == 'CPU') { $scope.cpuEvent.push(item); } var tmpData1 = $scope.audits; $scope.audits = $scope.cpuEvent; }); }; $scope.auditFilterRAID = function() { $scope.raidEvent = []; angular.forEach($scope.baseAudits, function(item, index) { console.log("Source\t"+item.Source); if(item.Source == 'RAID') { $scope.raidEvent.push(item); } var tmpData1 = $scope.audits; $scope.audits = $scope.raidEvent; }); }; /**** Event Filter Source colum *****/ $scope.filterAll = function() { $scope.allSource = []; angular.forEach($scope.baseEvents, function(item, index) { console.log("Source\t"+item.Source); if(item.Source == 'All') { $scope.allSource.push(item); } var tmpData1 = $scope.events; $scope.events = $scope.allSource; }); }; $scope.filterSys = function() { $scope.systemEvent = []; angular.forEach($scope.baseEvents, function(item, index) { console.log("Source\t"+item.Source); if(item["source"] == 'System') { $scope.systemEvent.push(item); } var tmpData1 = $scope.events; $scope.events = $scope.systemEvent; }); }; $scope.filterDriver = function() { $scope.driverEvent = []; angular.forEach($scope.baseEvents, function(item, index) { console.log("Source\t"+item.Source); if(item.Source == 'Driver') { $scope.driverEvent.push(item); } var tmpData1 = $scope.events; $scope.events = $scope.driverEvent; }); }; $scope.filterCPU = function() { $scope.cpuEvent = []; angular.forEach($scope.baseEvents, function(item, index) { console.log("Source\t"+item.Source); if(item.Source == 'CPU') { $scope.cpuEvent.push(item); } var tmpData1 = $scope.events; $scope.events = $scope.cpuEvent; }); }; $scope.filterRAID = function() { $scope.raidEvent = []; angular.forEach($scope.baseEvents, function(item, index) { console.log("Source\t"+item.Source); if(item.Source == 'RAID') { $scope.raidEvent.push(item); } var tmpData1 = $scope.events; $scope.events = $scope.raidEvent; }); }; /*input source, change source title to selected source, then call filterLog*/ $scope.filterSource = function(s) { $scope.source = s; $scope.events = $scope.filterLog($scope.baseEvents,$scope.icons,s,$scope.expectedDate); } /*filter function, input icons, source, date, events are supposed to be changed*/ $scope.filterLog = function(logs,i,s,d){ //console.log("*****filterLog function*****"); //console.log("icons are"+i+", source is:"+s+", date is:"+d); var tempEvents = []; logs.forEach(function(item){ var eventDate = item["date"]; var transformedDate = new Date(Date.parse(eventDate)); //console.log("item severity is :"+item["severity"]); //console.log("item severity is in i?"+(i.indexOf(item["severity"])>=0)); if(i.indexOf(item["severity"])<0){ return; }else{ //console.log("source is :"+s); //console.log("transformedDate is:"+transformedDate+", expected date is:"+d); if(s == "All Source"){ if(transformedDate >= d){ //console.log("is date expected?"+(transformedDate >= d)); tempEvents.push(item); } }else{ if(item["source"] == s){ if (transformedDate >= d){ tempEvents.push(item); } }else{ return; } } } }); console.log("tempEvents.length:"+tempEvents.length); return tempEvents; console.log("*****end filterLog function*****"); } $scope.filterHistory = function(s,d){ var tempHistories = []; $scope.baseHistories.forEach(function(history){ var hisDate = history["timeStr"]; var transformedDate = new Date(Date.parse(hisDate)); if(s == "All"){ if(transformedDate >= d){ //console.log("is date expected?"+(transformedDate >= d)); tempHistories.push(history); } }else{ if(history["typeStr"] == s){ if(transformedDate >= d){ tempHistories.push(history); } }else{ return; } } }); console.log("length of filtered history:"+tempHistories.length); return tempHistories; } /*Filter the maintain history page of log*/ $scope.transactionTypes = [ "All", "Firmware", "Configuration", "Hardware activity" ]; $scope.useFilter = false; $scope.selectedType = "All"; //$scope.tableFilter.Type = "All"; //$scope.selectedAllType = $scope.transactionTypes[0]; //$scope.myFilter = function(tran) { // if ($scope.tableFilter.Type == "All" || !$scope.tableFilter.Type) // return true; // else if($scope.tableFilter.Type == tran.Type) // return true; // else // return false; //}; $scope.selectAType = function(type){ console.log("type:"+type); if(type == "Hardware"){ $scope.selectedType = "Hardware Activity"; }else{ $scope.selectedType = type; } $scope.maintainHistories = $scope.filterHistory($scope.selectedType,$scope.hisExpectedDate); } /*checkbox setting for maintaince page*/ $scope.hasChecked = []; $scope.check = function(){ if($scope.hasChecked.length==$scope.maintainHistories.length){ var tmp = $scope.hasChecked.join(''); if(!tmp.indexOf('true') && !tmp.lastIndexOf('true') && !tmp.replace(/true/g,'') && $scope.isChecked)return; else{ if($scope.isChecked) checkAll(); else $scope.hasChecked = []; } }else checkAll(); }; var checkAll = function(){ $scope.hasChecked = []; for(var i in $scope.maintainHistories) $scope.hasChecked.push(true); }; $scope.testchk = function() { console.log("tttyyy\t"+JSON.stringify($scope.hasChecked)); } /*Event page's DlgPop Control */ //CustomizeTab control $scope.customizeTabInfo = { "Source": true, "EventID": true, "Date": true, "ServiceState": false, "Index": false, "Sequence": false }; $scope.showSequence = false; $scope.showServiceState = false; $scope.showIndexNum = false; $scope.clkCustomizeTabOK = function(){ console.log('save default customizeTabInfo.....'); $scope.showCustomizeTab = !$scope.showCustomizeTab; if ($scope.customizeTabInfo.ServiceState) { $scope.showServiceState = true; } else { $scope.showServiceState = false; } if ($scope.customizeTabInfo.Sequence) { $scope.showSequence = true; } else { $scope.showSequence = false; } if ($scope.customizeTabInfo.Index) { $scope.showIndexNum = true; } else { $scope.showIndexNum = false; } }; $scope.clkCustomizeTabCancel = function() { console.log('cancel customizeTabInfo dlgPop....'); $scope.showCustomizeTab = false; }; $scope.clkAuditCustomTabOK = function() { $scope.showAuditCustomizeTab = !$scope.showAuditCustomizeTab; if ($scope.customizeTabInfo.ServiceState) { $scope.showServiceState = true; } else { $scope.showServiceState = false; } if ($scope.customizeTabInfo.Sequence) { $scope.showSequence = true; } else { $scope.showSequence = false; } if ($scope.customizeTabInfo.Index) { $scope.showIndexNum = true; } else { $scope.showIndexNum = false; } }; $scope.clkAuditCustomTabCancel = function() { console.log('cancel customizeTabInfo dlgPop....'); $scope.showAuditCustomizeTab = false; }; $scope.customizeTabReset = function() { //need to be optimized if($scope.customizeTabInfo.Source || $scope.customizeTabInfo.EventID || $scope.customizeTabInfo.Date || $scope.customizeTabInfo.ServiceState || $scope.customizeTabInfo.Index ||$scope.customizeTabInfo.Sequence ) { $scope.customizeTabInfo.ServiceState = false; $scope.customizeTabInfo.Index = false; $scope.customizeTabInfo.Sequence = false; } else { $scope.customizeTabInfo.Source = true; $scope.customizeTabInfo.EventID = true; $scope.customizeTabInfo.Date = true; } }; /* Clear logs control*/ //Del maintain history page record /*var clkDelMaintainLog = function(index) { $scope.maintainHistories.splice(index-1, 1); };*/ $scope.delHistory = function (){ restClearMaintainHis.save({},{"Maintainance_ClearLogs":""},function(data){ if(data.return == 0){ $scope.maintainHistories = []; }else{ $scope.$emit('showErrMsgBox', data.return); } }, function(error){ $scope.$emit('showErrMsgBox', JSON.stringify(error)); }); }; $scope.hasContentToDel = function (){ var i; for(i=$scope.hasChecked.length;i--;i>0){ if($scope.hasChecked[i]){ console.log('has content to delete'); return true; } } //console.log('nothing to delete'); return false; }; //Del Event log record $scope.clkDelEventLog = function(index) { $scope.events.splice(index-1, 1); }; //Del Audit Log record $scope.clkDelAuditLog = function(index) { $scope.events.splice(index-1, 1); }; /*Fresh Ctrl */ //This function need to be improved $scope.showFishRefreshBtn = false; $scope.defTime=3 $scope.clkRefreshTab = function() { if($scope.showAuditLog){ restEventInfo.save({},{CEM_LogType:'1'},function(data) { console.log('loading audit information ...'); $scope.audits = data["items"]; $scope.baseAudits = $scope.audits.concat(); $scope.showFishRefreshBtn = true; if($scope.showFishRefreshBtn ) { var time= $timeout(function(){ $scope.showFishRefreshBtn = false; },1000); } else { $scope.stopFresh(); } },function(error){ alert("Error:"+JSON.stringify(error)); }); $('.audit-thumbnail').addClass('blueBorder'); $('.datePicker').datepicker('update', ''); $scope.auditSpecificDate = ""; $scope.auditExpectedDate = new Date('1969-01-01'); $scope.auditSource = "All Source"; }else{ restEventInfo.save({},{CEM_LogType:'0'},function(data) { console.log('loading event information ...'); $scope.events = data["items"]; $scope.baseEvents = $scope.events.concat(); console.log("number of events:"+$scope.events.length); $scope.showFishRefreshBtn = true; if($scope.showFishRefreshBtn ) { var time= $timeout(function(){ $scope.showFishRefreshBtn = false; },1000); } else { $scope.stopFresh(); } },function(error){ alert("Error:"+JSON.stringify(error)); }); $('.event-thumbnail').addClass('blueBorder'); $('.datePicker').datepicker('update', ''); $scope.specificDate = ""; $scope.expectedDate = new Date('1969-01-01'); $scope.source = "All Source"; } }; $scope.stopFresh = function() { if (angular.isDefined(time)) { $interval.cancel(time); time = undefined; } }; $scope.reloadRoute = function() { $route.reload(); }; //Time Ctrl $scope.clkTimeWidget = function() { $scope.showDateTimeSeting = !$scope.showDateTimeSeting; }; $scope.showSearchText = false; $scope.clkSearch = function() { $scope.showSearchText = !$scope.showSearchText ; }; /* $scope.showAuditSearchText = false; $scope.clkAuditSearch = function() { $scope.showAuditSearchText = !$scope.showAuditSearchText; }; */ $scope.clkOK = function() { console.log('save note data..' ); $scope.showCustomNote = false; }; $scope.clkCancel = function() { $scope.showCustomNote = false; }; /*Configure Alert Control*/ //init alert recipient var restRecipientAddEmail = cfgAlertRecipientService.restRecipientAddEmail(); var restRecipientModifyEmail = cfgAlertRecipientService.restRecipientModifyEmail(); var restRecipientDeleteEmail = cfgAlertRecipientService.restRecipientDeleteEmail(); var restRecipientAddSyslog = cfgAlertRecipientService.restRecipientAddSyslog(); var restRecipientModifySyslog = cfgAlertRecipientService.restRecipientModifySyslog(); var restGetSnmpSettingInfo = cfgAlertSNMPv3RecipientService.restGetSnmpSettingInfo(); var restGetAllUsers = cfgAlertSNMPv3RecipientService.restGetAllUsers(); var restSetSnmpSettings = cfgAlertSNMPv3RecipientService.restSetSnmpSettings(); var restSetSnmpTrap = cfgAlertSNMPv3RecipientService.restSetSnmpTrap(); //Select at least one event type $scope.criticalEvtsIndeterminate = false; $scope.showCriticalEvtsType = false; $scope.showAttentionEvtsType = false; $scope.showSystemEvtsType = false; $scope.showAuth = false; //init event type var initCrit = function(bool){ $scope.criticalChkInfo = { "temp" : bool, "volt" : bool, "power" : bool, "disk" : bool, "fan" : bool, "cpu" : bool, "memory" : bool , "hw_incomp" : bool, "redun_power" : bool, "other" : bool }; }; var initWarn = function(bool){ $scope.warnChkInfo = { "redun_power": bool, "temp": bool, "volt": bool, "power": bool, "fan": bool, "cpu": bool, "memory": bool, "other": bool }; }; var initInfo = function(bool){ $scope.systemChkInfo = { "remote_login": bool, "os_timeout": bool, "other": bool, "power_on": bool, "power_off": bool, "boot_fail": bool, "load_timeout": bool, "pfa": bool, "75full": bool, "net_change": bool, "all_audit": bool }; } var initEditCrit = function(bool){ $scope.editEmailReciModel.critical_temperature = bool; $scope.editEmailReciModel.critical_voltage = bool; $scope.editEmailReciModel.critical_power = bool; $scope.editEmailReciModel.critical_harddisk = bool; $scope.editEmailReciModel.critical_fan = bool; $scope.editEmailReciModel.critical_cpu = bool; $scope.editEmailReciModel.critical_memory = bool; $scope.editEmailReciModel.critical_hardware_incompatibility = bool; $scope.editEmailReciModel.critical_power_redundancy = bool; $scope.editEmailReciModel.critical_other = bool; }; var initEditWarn = function(bool){ $scope.editEmailReciModel.attention_power_redundancy = bool; $scope.editEmailReciModel.attention_temperature = bool; $scope.editEmailReciModel.attention_voltage = bool; $scope.editEmailReciModel.attention_power = bool; $scope.editEmailReciModel.attention_fan = bool; $scope.editEmailReciModel.attention_memory = bool; $scope.editEmailReciModel.attention_other = bool; }; var initEditInfo = function(bool){ $scope.editEmailReciModel.system_login = bool; $scope.editEmailReciModel.system_os_timeout = bool; $scope.editEmailReciModel.system_other = bool; $scope.editEmailReciModel.system_power = bool; $scope.editEmailReciModel.system_os_boot_fail = bool; $scope.editEmailReciModel.system_os_watchdog_timeout = bool; $scope.editEmailReciModel.system_pfa = bool; $scope.editEmailReciModel.system_event_log = bool; $scope.editEmailReciModel.system_network_change = bool; $scope.editEmailReciModel.all_audit_events = bool; }; initCrit(true); initWarn(true); initInfo(true); $scope.selMainCritical = function(){ if($scope.criticalChkInfo.xxxx) { $scope.criticalChkInfo.criticalTemperatureThresholdExceeded = true; $scope.criticalChkInfo.criticalVoltageThresholdExceeded = true; $scope.criticalChkInfo.criticalDriveFailure = true; $scope.criticalChkInfo.HardDiskDriveFailure = true; $scope.criticalChkInfo.FanFailure = true; $scope.criticalChkInfo.CPUFailure = true; $scope.criticalChkInfo.MemoryFailure = true; $scope.criticalChkInfo.HardwareIncompatibility = true; $scope.criticalChkInfo.Powerredundancyfailure = true; $scope.criticalChkInfo.Allothercriticalevents = true; } else { $scope.criticalChkInfo.criticalTemperatureThresholdExceeded = false; $scope.criticalChkInfo.criticalVoltageThresholdExceeded = false; $scope.criticalChkInfo.criticalDriveFailure = false; $scope.criticalChkInfo.HardDiskDriveFailure = false; $scope.criticalChkInfo.FanFailure = false; $scope.criticalChkInfo.CPUFailure = false; $scope.criticalChkInfo.MemoryFailure = false; $scope.criticalChkInfo.HardwareIncompatibility = false; $scope.criticalChkInfo.Powerredundancyfailure = false; $scope.criticalChkInfo.Allothercriticalevents = false; } }; /*alert receipient table control*/ $scope.id2del=''; $scope.id2edit=''; $scope.id2test=''; $scope.editEmailReciModel = {}; $scope.displayDelDiv = function(id) { if($scope.id2del != ''){ $scope.id2edit=''; $scope.id2test = ''; $scope.id2del = ''; }else{ $scope.id2edit=''; $scope.id2test = ''; $scope.id2del = id; } }; //input object and attributes you want to transform var numberToBoolean = function(obj, attrs){ angular.forEach(attrs, function(attr, index){ obj[attr] = !!obj[attr]; }); } $scope.testIcon = "www/images/event/test_icon_grey.png"; $scope.disableTest = false; $scope.displayEditDiv = function(id) { if($scope.id2edit != ''){ $scope.id2del=''; $scope.id2edit = ''; $scope.id2test=''; }else{ $scope.id2del=''; $scope.id2edit = id; $scope.id2test=''; var toBeEdit = $scope.recipients.filter(function(recip){ return (recip.index == id); }); $scope.editEmailReciModel = angular.copy(toBeEdit[0]); var attrs = ['status','include_log_in_email','enable_critical','critical_temperature','critical_voltage','critical_power','critical_harddisk','critical_fan', 'critical_cpu','critical_memory','critical_hardware_incompatibility','critical_power_redundancy','critical_other', 'enable_attention','attention_power_redundancy','attention_temperature','attention_voltage','attention_power', 'attention_fan','attention_cpu','attention_memory','attention_other','enable_system','system_login','system_os_timeout', 'system_other','system_power','system_os_boot_fail','system_os_watchdog_timeout','system_pfa','system_event_log','system_network_change','all_audit_events']; numberToBoolean($scope.editEmailReciModel,attrs); console.log("****editModel****:"+JSON.stringify($scope.editEmailReciModel)); } }; $scope.displayTestDiv = function(id) { if($scope.id2test != ''){ $scope.id2del=''; $scope.id2test = ''; $scope.id2edit=''; }else{ $scope.id2del=''; $scope.id2edit=''; $scope.id2test = id; } }; $scope.checkDel = function(id) { if($scope.id2del==id){ return true; }else{ return false; } }; $scope.checkEdit = function(id) { if($scope.id2edit==id){ return true; }else{ return false; } }; $scope.checkTest = function(id) { if($scope.id2test==id){ return true; }else{ return false; } }; $scope.removeItem = function (index) { restRecipientDeleteEmail.save({},{"entryIndex": index}, function(data){ if(data.return == 0){ getAlertRecip(); $scope.$emit('showErrMsgBox', "Saved successfully!"); } }); //$scope.recipients.splice(index-1, 1); }; $scope.testRecipient = function(index){ $scope.showTestingInfo = true; $scope.testingInfo = "Sending test..."; $scope.disableTest = true; $scope.testIcon = "www/images/event/ic_send test_blue600_18dp.png"; var payLoad = { "entryIndex": index }; cfgAlertRecipientService.restTestRecip().save({},payLoad,function(data){ if(data.return == 0){ $scope.disableTest = false; $scope.id2test = ''; $scope.testingInfo = "Send!"; $timeout(function(){ $scope.testingInfo = ""; $scope.testIcon = "www/images/event/test_icon_grey.png"; }, 10000); }else{ $scope.disableTest = false; $scope.testingInfo = ""; $scope.testIcon = "www/images/event/test_icon_grey.png"; $("#testPopDlg").modal(); } }, function(error){ $scope.disableTest = false; $scope.testingInfo = ""; $scope.testIcon = "www/images/event/test_icon_grey.png"; $("#testPopDlg").modal(); }); } $scope.id2EditUser = ''; $scope.id2DelUser = ''; $scope.displayEditUser = function(id, user){ if($scope.id2EditUser != ''){ $scope.id2EditUser = ''; $scope.id2DelUser = ''; }else{ $scope.ineditUser = true; $scope.userBeingEdit = angular.copy(user); $scope.id2EditUser = id; $scope.id2DelUser = ''; } }; $scope.displayDelUser = function(id){ if($scope.id2DelUser != ''){ $scope.id2EditUser = ''; $scope.id2DelUser = ''; }else{ $scope.id2EditUser = ''; $scope.id2DelUser = id; } } $scope.removeSNMPv3RecItem = function(index) { $scope.snmpv3Recipients.splice(index-1, 1); }; $scope.applyInEditRecip = function(){ $scope.id2edit = ''; var enaCritBitMap = $scope.editEmailReciModel.critical_temperature*1 | $scope.editEmailReciModel.critical_voltage*2 | $scope.editEmailReciModel.critical_power*4 | $scope.editEmailReciModel.critical_harddisk*8 | $scope.editEmailReciModel.critical_fan*16 | $scope.editEmailReciModel.critical_cpu*32 | $scope.editEmailReciModel.critical_memory*64 | $scope.editEmailReciModel.critical_hardware_incompatibility*128 | $scope.editEmailReciModel.critical_power_redundancy*256 | $scope.editEmailReciModel.critical_other*512; var enaWarnBitMap = $scope.editEmailReciModel.attention_power_redundancy*1 | $scope.editEmailReciModel.attention_temperature*2 | $scope.editEmailReciModel.attention_voltage*4 | $scope.editEmailReciModel.attention_power*8 | $scope.editEmailReciModel.attention_fan*16 | $scope.editEmailReciModel.attention_cpu*32 | $scope.editEmailReciModel.attention_memory*64 | $scope.editEmailReciModel.attention_other*128; var enaSysBitMap = $scope.editEmailReciModel.system_os_timeout*1 | $scope.editEmailReciModel.system_other*2 | $scope.editEmailReciModel.system_power*4 | $scope.editEmailReciModel.system_os_boot_fail*8 | $scope.editEmailReciModel.system_os_watchdog_timeout*16 | $scope.editEmailReciModel.system_pfa*32 | $scope.editEmailReciModel.system_event_log*64 | $scope.editEmailReciModel.system_network_change*128 | $scope.editEmailReciModel.all_audit_events*8388608; var jsonPayload = {}; jsonPayload.entryIndex = $scope.editEmailReciModel.index+''; jsonPayload.descName = $scope.editEmailReciModel.name+''; jsonPayload.emailAddr = $scope.editEmailReciModel.email_address+''; jsonPayload.sysLogAddr = $scope.editEmailReciModel.syslog_address+''; jsonPayload.enaCrit = $scope.editEmailReciModel.enable_critical * 1+''; jsonPayload.enaCritBitMap = enaCritBitMap+''; jsonPayload.enaWarn = $scope.editEmailReciModel.enable_attention * 1+''; jsonPayload.enaWarnBitMap = enaWarnBitMap+''; jsonPayload.enaSys = $scope.editEmailReciModel.enable_system * 1+''; jsonPayload.enaSysBitMap = enaSysBitMap+''; jsonPayload.includeLog = $scope.editEmailReciModel.include_log_in_email * 1+''; jsonPayload.entryDisable = $scope.editEmailReciModel.status * 1+''; if($scope.editEmailReciModel.email_address !== ""){ restRecipientModifyEmail.save({},jsonPayload, function(data){ if(data.return == 0){ angular.forEach($scope.recipients, function(recip, i){ if(recip.index == $scope.editEmailReciModel.index){ $scope.recipients[i] = angular.copy($scope.editEmailReciModel); } }); $scope.$emit('showErrMsgBox', "Saved successfully!"); } }); }else{ restRecipientModifySyslog.save({},jsonPayload,function(data){ if(data.return == 0){ angular.forEach($scope.recipients, function(recip, i){ if(recip.index == $scope.editEmailReciModel.index){ $scope.recipients[i] = angular.copy($scope.editEmailReciModel); } }); $scope.$emit('showErrMsgBox', "Saved successfully!"); } }); } } $scope.cancelInEditRecip = function(){ $scope.id2edit = ''; } /*clear log*/ /*$scope.clkClearLog = function(id) { if($scope.id2del==id){ return true; }else{ return false; } };*/ /*Filter the maintain page of log*/ $scope.transactionTypes = [ "All", "Firmware", "Configuration", "Hardware activity" ]; $scope.useFilter = false; $scope.tableFilter = {}; $scope.selected = $scope.transactionTypes[0]; $scope.myFilter = function(tran) { if ($scope.tableFilter.Type == "All" || !$scope.tableFilter.Type) return true; else if($scope.tableFilter.Type == tran.Type) return true; else return false; }; $scope.clkRefresh = function() { //alert('test refresh'); }; /* Time widget */ $scope.clkTimeWidget = function() { //alert('Time Test'); } $scope.clkCustomizeDate = function () { }; $scope.restoreChkSetting = function() { //alert('reset to Default'); }; $scope.clkOk = function() { $scope.showCustomizeTab = false; }; /*create Email Recipient page */ $scope.createEmail={}; var initEmailInfo = function(){ $scope.createEmail.newRecipientName=""; $scope.createEmail.newRecipientEmail=""; $scope.createEmail.smtpServer=""; $scope.createEmail.port="25"; $scope.createEmail.status=true; $scope.createEmail.enaCrit = true; $scope.createEmail.enaWarn = true; $scope.createEmail.enaSys = true; $scope.createEmail.includeLog = false; }; initEmailInfo(); var computeCrit = function(){ var bitMap = 0; angular.forEach($scope.criticalChkInfo, function(value, key){ var tranformedNum = 0; switch(key) { case "temp": tranformedNum = 1; break; case "volt": tranformedNum = 2; break; case "power": tranformedNum = 4; break; case "disk": tranformedNum = 8; break; case "fan": tranformedNum = 16; break; case "cpu": tranformedNum = 32; break; case "memory": tranformedNum = 64; break; case "hw_incomp": tranformedNum = 128; break; case "redun_power": tranformedNum = 256; break; case "other": tranformedNum = 512; break; } bitMap = bitMap | tranformedNum*value; }); return bitMap; }; var computeWarn = function(){ var bitMap = 0; angular.forEach($scope.warnChkInfo, function(value, key){ var tranformedNum = 0; switch(key) { case "redun_power": tranformedNum = 1; break; case "temp": tranformedNum = 2; break; case "volt": tranformedNum = 4; break; case "power": tranformedNum = 8; break; case "fan": tranformedNum = 16; break; case "cpu": tranformedNum = 32; break; case "memory": tranformedNum = 64; break; case "other": tranformedNum = 128; break; } bitMap = bitMap | tranformedNum*value; }); return bitMap; }; var computeInfor = function(){ var bitMap = 0; angular.forEach($scope.systemChkInfo, function(value, key){ var tranformedNum = 0; switch(key) { case "remote_login": tranformedNum = 1; break; case "os_timeout": tranformedNum = 2; break; case "other": tranformedNum = 4; break; case "power_on": tranformedNum = 8; break; case "power_off": tranformedNum = 16; break; case "boot_fail": tranformedNum = 32; break; case "load_timeout": tranformedNum = 64; break; case "pfa": tranformedNum = 128; break; case "75full": tranformedNum = 256; break; case "net_change": tranformedNum = 512; break; case "all_audit": tranformedNum = 8388608; break; } bitMap = bitMap | tranformedNum*value; }); return bitMap; } $scope.initAlertRecipientForEmail = function(){ console.log("lenght of info:"+$scope.criticalChkInfo.length); var enaCritBitMap = computeCrit(); var enaWarnBitMap = computeWarn(); var enaSysBitMap = computeInfor(); console.log("nums are"+enaCritBitMap+", "+enaWarnBitMap+", "+enaSysBitMap); //save //alert('Test Email Recipient'); var crit = $scope.createEmail.enaCrit?1:0; var warn = $scope.createEmail.enaWarn?1:0; var sys = $scope.createEmail.enaSys?1:0; var status = ""; if(typeof ($scope.createEmail.status) !== "boolean"){ status = parseInt($scope.createEmail.status); }else{ status = $scope.createEmail.status * 1; } console.log("stauts:"+ typeof($scope.createEmail.status)); var postLoad = {"entryIndex": parseInt($scope.helpIndexSelect.value)+'', "descName": $scope.createEmail.newRecipientName+'', "emailAddr": $scope.createEmail.newRecipientEmail+'', "enaCrit":crit+'', "enaCritBitMap":enaCritBitMap+'', "enaWarn":warn+'', "enaWarnBitMap": enaWarnBitMap+'', "enaSys": sys+'', "enaSysBitMap": enaSysBitMap+'', "includeLog": $scope.createEmail.includeLog * 1+'', "entryDisable": status+''}; restRecipientAddEmail.save(postLoad,function(data){ if(data.return == "0"){ initEmailInfo(); $scope.showAlertRecipients = true; $scope.showCreateEmailRecipient = false; $scope.showEventLog = false; $scope.showAuditLog = false; $scope.showMaintenanceHistory = false; $scope.showConfigureAlert = false; $scope.showSubCreateEmailRecipient = false; getAlertRecip(); $scope.$emit('showErrMsgBox', "Saved successfully!"); } }, function(error){ $scope.$emit('showErrMsgBox', error); }); }; /*syslog recipient page*/ $scope.createSyslog={}; $scope.createSyslog.iname=""; $scope.createSyslog.iemail=""; $scope.createSyslog.smtpServer=""; $scope.initAlertRecipientForSyslog = function(){ var enaCritBitMap = computeCrit(); var enaWarnBitMap = computeWarn(); var enaSysBitMap = computeInfor(); var crit = $scope.createEmail.enaCrit?1:0; var warn = $scope.createEmail.enaWarn?1:0; var sys = $scope.createEmail.enaSys?1:0; var status = ""; if(typeof ($scope.createEmail.status) !== "boolean"){ status = parseInt($scope.createEmail.status); }else{ status = $scope.createEmail.status * 1; } var port = parseInt($scope.createEmail.port); var postLoad = {"entryIndex": parseInt($scope.helpIndexSelect.value)+'', "descName": $scope.createEmail.newRecipientName+'', "hostName": $scope.createEmail.newRecipientEmail+'', "port": port+'', "enaCrit":crit+'', "enaCritBitMap":enaCritBitMap+'', "enaWarn":warn+'', "enaWarnBitMap": enaWarnBitMap+'', "enaSys": sys+'', "enaSysBitMap": enaSysBitMap+'', "includeLog": $scope.createEmail.includeLog * 1+'', "entryDisable":status+''}; console.log("postlOad:"+JSON.stringify(postLoad)); restRecipientAddSyslog.save({},postLoad, function(data){ if(data.return == 0){ initEmailInfo(); getAlertRecip(); $scope.$emit('showErrMsgBox', "Saved successfully!"); } }); $scope.showAlertRecipients = true; $scope.showCreateSyslogRecipient = false; $scope.showSubCreateSyslogRecipient = false; $scope.showEventLog = false; $scope.showAuditLog = false; $scope.showMaintenanceHistory = false; $scope.showConfigureAlert = false; console.log('all data save '); }; /*help index select*/ $scope.helpIndexSelect = {}; $scope.helpIndexSelect.map = { "1": "index1Value", "2": "index2Value", "3": "index3Value", "4": "index4Value", "5": "index5Value", "6": "index6Value", "7": "index7Value", "8": "index8Value", "9": "index9Value", "10": "index10Value", "11": "index11Value", "12": "index12Value" }; $scope.helpIndexSelect.value='1'; $scope.selhelpIndexChanged = function(value) { console.log(value); return false; }; /*select SNMPv3 USER*/ $scope.SNMPv3UserSelect = {}; $scope.SNMPv3UserSelect.map = { }; $scope.SNMPV3AuthProtocalMap = { 0: "None", 1: "MD5", 2: "SHA" }; $scope.SNMPV3PrivProMap = { 0: "None", 1: "DES", 2: "AES" }; $scope.selSNMPv3UserChanged = function(value) { console.log(value); return false; }; $scope.SNMPv3AuthPro={}; $scope.SNMPv3AuthPro.map = { "None": "NoneLabel", "HMAC-MD5": "HMAC-MD5Label", "HMAC-SHA" : "HMAC-SHALabel" }; $scope.SNMPv3AuthPro.value='HMAC-MD5'; $scope.selSNMPv3AuthProChanged = function(value) { console.log(value); return false; } $scope.showPasswordSetting = false; $scope.SNMPv3PrivacyPro={}; $scope.SNMPv3PrivacyPro.map = { "None": "NoneLabel", "AES": "AESLabel", "CBC - DES": "CBC-DESLabel" }; $scope.SNMPv3PrivacyPro.value="AES"; $scope.selSNMPv3PrivacyProChanged = function(value) { console.log(value); if(value == "CBC - DES") { $scope.showPasswordSetting = true; } else { $scope.showPasswordSetting = false; } return false; } $scope.initAlertRecipientForSNMPv3 = function(){ //save //alert('Test SNMPv3 Recipient'); console.log('save snmpv3 data'); var userId = ''; for(var i = 0; i< $scope.allUsers.length; i++){ var user = $scope.allUsers[i]; if(user['users_user_name'] == $scope.userBeingEdit['name']){ userId = user['users_user_id']; } } var payLoad = userId + ',' + $scope.userBeingEdit['name'] + ','+','+','+ ','+ $scope.userBeingEdit['use_an_auth_protocol'] +','+ $scope.userBeingEdit['auth_protocol']+',' + $scope.userBeingEdit['auth_protocol']+','+ $scope.userBeingEdit['privacy_protocol']+','+ $scope.userBeingEdit['privacy_password']+',' + $scope.userBeingEdit['access_type']+','+ $scope.userBeingEdit['access_address']; console.log("payload is:"+payLoad); $scope.showSubCreateSNMPv3Recipient = false; cfgAlertSNMPv3RecipientService.restSetSnmpV3User().save({},{"USER_UserModify": payLoad},function(data){ if(data.return == 0){ $scope.snmpv3Setting(); getSnmpV3Users(); }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } },function(error){ $scope.$emit('showErrMsgBox', "error:"+JSON.stringify(error)); }); //$scope.showSNMPv3AlertRecipients = !$scope.showSNMPv3AlertRecipients; $scope.showCreateSNMPv3Recipient = ! $scope.showCreateSNMPv3Recipient; $scope.showEventLog = false; $scope.showAuditLog = false; $scope.showMaintenanceHistory = false; $scope.showConfigureAlert = false; $scope.createEmail.iname=""; $scope.createEmail.iemail=""; }; var removeRepeatUser = function(){ var ids = []; for(var i = $scope.snmpv3Users.length-1; i>=0; i--){ if($scope.snmpv3Users[i]['name'] != ""){ ids.push($scope.snmpv3Users[i]['user_id']); } } for(var i = $scope.allUsers.length-1; i>=0; i--){ console.log("index of this id:"+ids.indexOf($scope.allUsers[i]['users_user_id'])); if(ids.indexOf($scope.allUsers[i]['users_user_id']) >= 0){ $scope.allUsers.remove($scope.allUsers[i]); } } } /*sub create email recipient setting (pop Dlg)*/ $scope.clkCreate = function(viewName) { if(viewName == 'subCreateEmailRecipient') { initEmailInfo(); $scope.showSubCreateEmailRecipient = !$scope.showSubCreateEmailRecipient; } if(viewName == 'subCreateSyslogRecipient'){ initEmailInfo(); $scope.showSubCreateSyslogRecipient = !$scope.showSubCreateSyslogRecipient; } if(viewName == 'subCreateSNMPv3Recipient'){ $scope.ineditUser = false; $scope.showSubCreateSNMPv3Recipient = ! $scope.showSubCreateSNMPv3Recipient; removeRepeatUser(); $scope.userBeingEdit = { "access": "", "access_address": "", "access_type": "", "auth_protocol": "", "name": "", "privacy_password": "", "privacy_protocol": "", "use_a_privacy_protocol": "0", "use_an_auth_protocol": "0", "user_id": "" }; $scope.userBeingEdit['name'] = $scope.allUsers[0]['users_user_name']; $scope.userBeingEdit['auth_protocol'] = 0; $scope.userBeingEdit['privacy_protocol'] = 0; $scope.userBeingEdit['privacy_protocol'] = 0; $scope.allUsers.forEach(function(item){ $scope.SNMPv3UserSelect.map[item['users_user_name']] = item['users_user_name']; }) console.log("selected map is :"+ JSON.stringify($scope.SNMPv3UserSelect.map)); } /*control sub smtpserver*/ if(viewName == 'subSMTPServer') { $scope.showSMTPServer = !$scope.showSMTPServer; $scope.showTestError = false; } if(viewName == 'retryAnDelay') { $scope.showRetryAndDelay = !$scope.showRetryAndDelay; } if(viewName == 'SNMPv3Settings') { $scope.showSNMPv3Setting = !$scope.showSNMPv3Setting; } }; $scope.subEmailRecipientApply = function() { $scope.showAlertRecipients = !$scope.showAlertRecipients; }; $scope.subSyslogRecipientApply = function() { $scope.showAlertRecipients = !$scope.showAlertRecipients; }; /*Create syslog and email in alert recipients page*/ $scope.createSysLog={}; $scope.createSysLog.newRecipientName=""; $scope.createSysLog.newRecipientEmail=""; $scope.createSysLog.smtpServer=""; $scope.createSysLog.Port="25"; $scope.createSysLog.Status="Enabled"; $scope.createSysLog.enaCrit = true; $scope.createSysLog.enaWarn = true; $scope.createSysLog.enaSys = true; $scope.clkCreateERecipientApply = function() { //alert('CreateERecipientApply'); console.log('save email data'); $scope.showSubCreateEmailRecipient = false; }; $scope.clkCreateSyslogRecipientApply = function() { console.log('save syslog data'); $scope.showSubCreateSyslogRecipient = false; }; $scope.clkCreateSnmpv3RecipientApply = function(){ console.log('save snmpv3 data'); var userId = ''; for(var i = 0; i< $scope.snmpv3Users.length; i++){ var user = $scope.snmpv3Users[i]; if(user['name'] == $scope.userBeingEdit['name']){ userId = user['user_id']; } } var payLoad = userId + ',' + $scope.userBeingEdit['name'] + ','+','+','+ ','+ $scope.userBeingEdit['use_an_auth_protocol'] +','+ $scope.userBeingEdit['auth_protocol']+',' + $scope.userBeingEdit['auth_protocol']+','+ $scope.userBeingEdit['privacy_protocol']+','+ $scope.userBeingEdit['privacy_password']+',' + $scope.userBeingEdit['access_type']+','+ $scope.userBeingEdit['access_address']; console.log("payload is:"+payLoad); $scope.showSubCreateSNMPv3Recipient = false; cfgAlertSNMPv3RecipientService.restSetSnmpV3User().save({},{"USER_UserModify": payLoad},function(data){ if(data.return == 0){ getSnmpV3Users(); $scope.id2EditUser = ''; $scope.$emit('showErrMsgBox', "Saved successfully"); }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } },function(error){ $scope.$emit('showErrMsgBox', "error:"+JSON.stringify(error)); }); }; $scope.removeUser = function(user){ var payLoad = user['user_id'] + ',' + user['name']; cfgAlertSNMPv3RecipientService.restSetSnmpV3User().save({},{"USER_UserDelete":payLoad}, function(data){ if(data.return == 0){ getSnmpV3Users(); $scope.id2DelUser = ''; }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } }), function(error){ $scope.$emit('showErrMsgBox', "error:"+JSON.stringify(error)); }; }; $scope.cancelDelUser = function(){ $scope.id2DelUser = ''; }; $scope.cancelCreateERecipientSeting = function(){ $scope.showSubCreateEmailRecipient = false; }; $scope.cancelCreateSyslogRecipientSeting = function(){ $scope.showSubCreateSyslogRecipient = false; }; $scope.cancelCreateSnmpv3RecipientSeting = function(){ $scope.showSubCreateSNMPv3Recipient = false; }; /*change smtp server setting*/ $scope.chgSmtpServer = function() { $scope.showSMTPServer = false; }; $scope.clkSmtpSrvCancelSetting = function() { $scope.showSMTPServer = false; }; /*smtp server*/ $scope.smtpServerInAlert = {}; $scope.showLoading = false; $scope.showConnected = false; var restGetSmtpServer = cfgSMTPServerService.restGetSmtpServer(); var restSetSmtpServer = cfgSMTPServerService.restSetSmtpServer(); var restTestSmtpServer = cfgSMTPServerService.restTestSmtpServer(); restGetSmtpServer.get(function(data){ $scope.smtpServerInAlert = data.items[0]; $scope.smtpServerInAlert.smtp_auth = ($scope.smtpServerInAlert.smtp_auth == 1); $scope.smtpServerInAlert.smtp_authmethod = $scope.smtpServerInAlert.smtp_authmethod == 1?'LOGIN':'CRAM-MD5'; }); $scope.testConnInAlert = function(){ //alert("data:"+JSON.stringify($scope.smtpServerInAlert)); var payLoad = { "host":$scope.smtpServerInAlert.smtp_host, "port":$scope.smtpServerInAlert.smtp_port }; $scope.showLoading = true; $scope.showConnected = false; restTestSmtpServer.save({},payLoad,function(data){ if(data.return == 0){ $scope.showLoading = false; $scope.showConnected = true; $timeout(function(){ $scope.showConnected = false; }, 1000); }else{ $scope.showLoading = false; $scope.showTestError = true; $scope.testErrorMessage = "Test failed, error code: " + data.return; } }); } $scope.applySmtpServer = function(){ var payLoad = { "SMTP_ServerName":$scope.smtpServerInAlert.smtp_host + '', "SMTP_ServerPort":$scope.smtpServerInAlert.smtp_port + '', "SMTP_SmtpAuth":$scope.smtpServerInAlert.smtp_auth*1 + '', "SMTP_Username":$scope.smtpServerInAlert.smtp_username + '', "SMTP_Password":$scope.smtpServerInAlert.smtp_password + '', "SMTP_AuthMethod":($scope.smtpServerInAlert.smtp_authmethod == 'LOGIN'?0:1) + '', "SMTP_Email":$scope.smtpServerInAlert.smtp_email + '' }; restSetSmtpServer.save({},payLoad, function(data){ if(data.return == 0){ $scope.$emit('showErrMsgBox', "Saved successfully!"); } }); } /*Retry and Delay Page Contrl */ var original_retry_limit = '5'; $scope.delay_between_entries = {}; $scope.delay_between_entries.map = { "30" : "0.5 minutes", "60" : "1 minutes", "120" : "2 minutes", "180" : "3 minutes", }; $scope.retryAndDelayTimeOnChange = function(){ $scope.delay_between_entries_method = $("#delayBetweenEntriesFuc").val(); $scope.delay_between_attempts_method = $("#delay_between_attempts").val(); }; $scope.delay_between_attempts = {}; $scope.delay_between_attempts.map = { "30" : "0.5 minutes", "60" : "1 minutes", "120" : "2 minutes", "180" : "3 minutes", }; var restGetNoteGlobalInfo = cfgAlertSNMPv3RecipientService.restGetNoteGlobalInfo(); restGetNoteGlobalInfo.get(function(data){ $scope.retry_limit = data["items"][0]["retry_limit"]; $scope.delay_between_entries.value = data["items"][0]["delay_between_entries"]; $scope.delay_between_attempts.value = data["items"][0]["delay_between_attempts"]; }); var restSetNoteGlobalInfo = cfgAlertSNMPv3RecipientService.restSetNoteGlobalInfo(); $scope.retryAndDelaySetting = function() { var retryInput = $("#retry_limit").val(); var payLoad = { "EVT_NotifyRetryLimit": parseInt(retryInput), "EVT_NotifyEntryDelay": parseInt($scope.delay_between_entries.value), "EVT_NotifyAttemptDelay": parseInt($scope.delay_between_attempts.value) }; restSetNoteGlobalInfo.save({}, payLoad, function(data){ if(data.return == 0){ alert("success"); } }); $scope.showRetryAndDelay = false; }; $scope.clkCancelRetrySetting = function() { $scope.showRetryAndDelay = false; }; $scope.snmpv3Setting = function() { var enaCritBitMap = computeCrit(); var enaWarnBitMap = computeWarn(); var enaSysBitMap = computeInfor(); var payLoadForCategory = { "SNMP_TrapsCriticalBitMap": enaCritBitMap, "SNMP_TrapsWarningBitMap": enaWarnBitMap, "SNMP_TrapsSystemBitMap": enaSysBitMap }; var payLoadForSetSnmp = { "IMM_Contact": $scope.snmpV3Setting.snmp_contact_person, "IMM_Location": $scope.snmpV3Setting.snmp_location, "SNMP_v3AgentEna": $scope.snmpV3Setting.snmp_v3_enabled * 1 + '', "SNMP_TrapsEna": $scope.snmpV3Setting.snmp_traps_enabled * 1 + '', "SNMP_TrapsCriticalEna": $scope.snmpV3Setting.snmp_traps_critical_enabled * 1 + '', "SNMP_TrapsWarningEna": $scope.snmpV3Setting.snmp_traps_attention_enabled * 1 + '', "SNMP_TrapsSystemEna": $scope.snmpV3Setting.snmp_traps_system_enabled * 1 + '' }; //var restSetSnmpSettings = cfgAlertSNMPv3RecipientService.restSetSnmpSettings(); //var restSetSnmpTrap = cfgAlertSNMPv3RecipientService.restSetSnmpTrap(); restSetSnmpSettings.save({},payLoadForSetSnmp, function(data){ if(data.return == 0){ restSetSnmpTrap.save({},payLoadForCategory, function(data){ if(data.return == 0){ $scope.$emit('showErrMsgBox', "Saved successfully!"); }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } },function(error){ $scope.$emit('showErrMsgBox', "error:"+JSON.stringify(error)); }); }else{ $scope.$emit('showErrMsgBox', "error:"+data.return); } },function(error){ $scope.$emit('showErrMsgBox', "error:"+JSON.stringify(error)); }); $scope.showSNMPv3Setting = false; }; $scope.clkSnmpv3Setting = function() { $scope.showSNMPv3Setting = false; }; var createEmailRecipientStatus = "Enabled"; $scope.onInputChange = function() { if(document.getElementById("StatusTypeEnable").checked ) { $scope.createEmailRecipientStatus = "Enabled"; } else{ $scope.createEmailRecipientStatus = "Disabled"; } if(document.getElementById("StatusTypeDisable").checked ) { $scope.createEmailRecipientStatus = "Disabled"; } else{ $scope.createEmailRecipientStatus = "Enabled"; } if(document.getElementById("includeEventLog").checked){ $scope.includeEventLog = true; } else { $scope.includeEventLog = false; } if(document.getElementById("enableReciAuth").checked) { $scope.enabledReciAuth = true; } else { $scope.enabledReciAuth = false; } }; $scope.clkCancelEmailRecipent = function(){ $scope.showCreateEmailRecipient = false; } $scope.clkCancelSyslogRecipent = function(){ $scope.showCreateSyslogRecipient = false; $scope.showSubCreateSyslogRecipient = false; } $scope.clkCacelSnmpRecipent = function(){ $scope.showCreateSNMPv3Recipient = false; } $scope.showPreviousDate = false; $scope.showSpecificDate = false; $scope.previousDate = ""; $scope.preViewName = ""; $scope.specificDate = ""; $scope.showAuditPreviousDate = false; $scope.showAuditSpecificDate = false; $scope.previousAuditDate = ""; $scope.preAuditViewName = ""; $scope.auditSpecificDate = ""; $scope.showHisPreviousDate = false; $scope.showHisSpecificDate = false; $scope.previousHisDate = ""; $scope.preHisViewName = ""; $scope.hisSpecificDate = ""; //$scope.$watch('specificDate',function(newValue,oldValue, scope){ // console.log("date did change and selcted date is:"); //}); //$scope.focusedOnDatePicker = function(){ // var datePicker = $('#pickADay'); // //alert("datePickier:"+datePicker); // datePicker.change(function(){ // console.log("selected date is:"+$scope.specificDate); // $scope.events = $scope.filterLog($scope.icons, $scope.source, $scope.specificDate); // }); //} //$scope.querySpecificDate = function(){ // console.log("date did change and selcted date is:"+$scope.specificDate); //} $scope.$on('dateChange',function(event, data){ $scope.specificDate = data; }); $scope.$watch('specificDate',function(n,o){ console.log("new value:"+n); console.log("type of date?:"+typeof n); if(n == ""){ return; } console.log("secons:"+Date.parse(n)); if($scope.showAuditLog){ $scope.auditExpectedDate = new Date(Date.parse(n)); console.log("isDate?:"+angular.isDate($scope.auditExpectedDate)); if(angular.isDate($scope.auditExpectedDate)){ $scope.audits = $scope.filterLog($scope.baseAudits,$scope.auditIcons, $scope.auditSource, $scope.auditExpectedDate); } }else{ $scope.expectedDate = new Date(Date.parse(n)); console.log("isDate?:"+angular.isDate($scope.expectedDate)); if(angular.isDate($scope.expectedDate)){ $scope.events = $scope.filterLog($scope.baseEvents,$scope.icons, $scope.source, $scope.expectedDate); } } $scope.expectedDate = new Date(Date.parse(n)); console.log("isDate?:"+angular.isDate($scope.expectedDate)); if(angular.isDate($scope.expectedDate)){ $scope.events = $scope.filterLog($scope.baseEvents,$scope.icons, $scope.source, $scope.expectedDate); } }); $scope.timeShowCtrl = function(viewName) { //if($("#dateUl").css("display") == "flex"){ // $("#dateUl").css("display",""); //}else{ // $("#dateUl").css("display","flex"); //} console.log("*****test time show ctl*****"); var today = new Date(); var milliseconds = today.getTime(); console.log("millsecons:"+milliseconds); if($scope.preAuditViewName == viewName){ $scope.showPreviousDate = !$scope.showPreviousDate; }else{ $scope.showPreviousDate = true; } $scope.preAuditViewName = viewName; if (viewName == 'allDate'){ $scope.showPreviousDate = false; $scope.showSpecificDate = false; $scope.expectedDate = new Date("1970,1,1"); } if (viewName == 'PreviousTwohours'){ $scope.previousDate = "Previous 2 Hours"; $scope.expectedDate.setTime(milliseconds - 2*3600*1000); } if (viewName == 'Pre24hours'){ $scope.previousDate = "Previous 24 Hours"; $scope.expectedDate.setTime(milliseconds - 24*3600*1000); } if (viewName == 'Pre7days'){ $scope.previousDate = "Previous 7 Days"; $scope.expectedDate.setTime(milliseconds - 7*24*3600*1000); } if (viewName == 'Pre30days'){ $scope.previousDate = "Previous 30 Days"; $scope.expectedDate.setTime(milliseconds - 30*24*3600*1000); }if (viewName != 'specificDate'){ $scope.showSpecificDate = false; }else{ $scope.showSpecificDate = !$scope.showSpecificDate; $scope.showPreviousDate = false; $scope.previousDate = "Specific Date"; } console.log("expectedDate:"+$scope.expectedDate); $scope.events = $scope.filterLog($scope.baseEvents,$scope.icons, $scope.source, $scope.expectedDate); console.log("*****end test time show ctl*****"); } $scope.timeAuditShowCtrl = function(viewName) { //if($("#dateUl").css("display") == "flex"){ // $("#dateUl").css("display",""); //}else{ // $("#dateUl").css("display","flex"); //} console.log("*****test time show ctl*****"); var today = new Date(); var milliseconds = today.getTime(); console.log("millsecons:"+milliseconds); if($scope.preAuditViewName == viewName){ $scope.showAuditPreviousDate = !$scope.showAuditPreviousDate; }else{ $scope.showAuditPreviousDate = true; } $scope.preAuditViewName = viewName; if (viewName == 'allDate'){ $scope.showAuditPreviousDate = false; $scope.showAuditSpecificDate = false; $scope.auditExpectedDate = new Date("1970,1,1"); } if (viewName == 'PreviousTwohours'){ $scope.previousAuditDate = "Previous 2 Hours"; $scope.auditExpectedDate.setTime(milliseconds - 2*3600*1000); } if (viewName == 'Pre24hours'){ $scope.previousAuditDate = "Previous 24 Hours"; $scope.auditExpectedDate.setTime(milliseconds - 24*3600*1000); } if (viewName == 'Pre7days'){ $scope.previousAuditDate = "Previous 7 Days"; $scope.auditExpectedDate.setTime(milliseconds - 7*24*3600*1000); } if (viewName == 'Pre30days'){ $scope.previousAuditDate = "Previous 30 Days"; $scope.auditExpectedDate.setTime(milliseconds - 30*24*3600*1000); }if (viewName != 'specificDate'){ $scope.showAuditSpecificDate = false; }else{ $scope.showAuditSpecificDate = !$scope.showAuditSpecificDate; $scope.showAuditPreviousDate = false; $scope.previousAuditDate = "Specific Date"; } console.log("expectedDate:"+$scope.auditExpectedDate); $scope.audits = $scope.filterLog($scope.baseAudits,$scope.auditIcons, $scope.auditSource, $scope.auditExpectedDate); console.log("*****end test time show ctl*****"); } $scope.timeShowHisCtrl = function(viewName) { //if($("#dateUl").css("display") == "flex"){ // $("#dateUl").css("display",""); //}else{ // $("#dateUl").css("display","flex"); //} console.log("*****test time show ctl*****"); var today = new Date(); var milliseconds = today.getTime(); console.log("millsecons:"+milliseconds); if($scope.preHisViewName == viewName){ $scope.showHisPreviousDate = !$scope.showHisPreviousDate; }else{ $scope.showHisPreviousDate = true; } $scope.preHisViewName = viewName; if (viewName == 'allDate'){ $scope.showHisPreviousDate = false; $scope.showHisSpecificDate = false; $scope.hisExpectedDate = new Date("1970,1,1"); } if (viewName == 'PreviousTwohours'){ $scope.previousHisDate = "Previous 2 Hours"; $scope.hisExpectedDate.setTime(milliseconds - 2*3600*1000); } if (viewName == 'Pre24hours'){ $scope.previousHisDate = "Previous 24 Hours"; $scope.hisExpectedDate.setTime(milliseconds - 24*3600*1000); } if (viewName == 'Pre7days'){ $scope.previousHisDate = "Previous 7 Days"; $scope.hisExpectedDate.setTime(milliseconds - 7*24*3600*1000); } if (viewName == 'Pre30days'){ $scope.previousHisDate = "Previous 30 Days"; $scope.hisExpectedDate.setTime(milliseconds - 30*24*3600*1000); }if (viewName != 'specificDate'){ $scope.showHisSpecificDate = false; }else{ $scope.showHisSpecificDate = !$scope.showHisSpecificDate; $scope.showHisPreviousDate = false; $scope.previousHisDate = "Specific Date"; } console.log("expectedDate:"+$scope.hisExpectedDate); $scope.maintainHistories = $scope.filterHistory($scope.selectedType,$scope.hisExpectedDate); console.log("*****end test time show ctl*****"); } /*radio control*/ $scope.eventStatusChecked=true; $scope.statusEnabled="Enable" $scope.checkStatusChg = function(radioValue) { console.log(radioValue); $scope.statusEnabled=radioValue; }; $scope.closeTip = function() { $('#myTip').alert('close'); }; $scope.onInputChange = function(){ console.log('saving changes'); }; // below function need to be optimized // may be removed // $scope.hasCheckedEvents = []; $scope.checkEvents = function(){ //if($scope.hasChecked.length==$scope.maintainHistories.length){ if($scope.hasCheckedEvents.length== $scope.events.length){ var tmp = $scope.hasCheckedEvents.join(''); if(!tmp.indexOf('true') && !tmp.lastIndexOf('true') && !tmp.replace(/true/g,'') && $scope.isChecked)return; else{ if($scope.isChecked) checkEventsAll(); else $scope.hasCheckedEvents = []; } }else checkEventsAll(); }; var checkEventsAll = function(){ $scope.hasCheckedEvents = []; for(var i in $scope.events) $scope.hasCheckedEvents.push(true); }; $scope.testchkEvent = function() { console.log("tttyyy\t"+JSON.stringify($scope.hasCheckedEvents)); } $scope.delEventHistory = function (){ var i; for(i=$scope.hasCheckedEvents.length;i--;i>0){ if($scope.hasCheckedEvents[i]){ //console.log('going to del\t'+i); $scope.events.splice(i, 1); } } //reset the range as null $scope.hasCheckedEvents =[]; }; $scope.hasEventContentToDel = function (){ var i; for(i=$scope.hasCheckedEvents.length;i--;i>0){ if($scope.hasCheckedEvents[i]){ console.log('has content to delete'); return true; } } //console.log('nothing to delete'); return false; }; $scope.hasCheckedAudits = []; $scope.checkAudits = function(){ if($scope.hasCheckedAudits.length == $scope.audits.length){ var tmp = $scope.hasCheckedAudits.join(''); if(!tmp.indexOf('true') && !tmp.lastIndexOf('true') && !tmp.replace(/true/g,'') && $scope.isChecked)return; else{ if($scope.isChecked) checkAuditsAll(); else $scope.hasCheckedAudits = []; } }else checkAuditsAll(); }; var checkAuditsAll = function(){ $scope.hasCheckedAudits = []; for(var i in $scope.audits) $scope.hasCheckedAudits.push(true); }; $scope.testchkAudit = function() { console.log("tttyyy\t"+JSON.stringify($scope.hasCheckedAudits)); } $scope.delAuditHistory = function (){ var i; for(i=$scope.hasCheckedAudits.length;i--;i>0){ if($scope.hasCheckedAudits[i]){ console.log('going to del\t'+i); $scope.audits.splice(i, 1); } } //reset the range as null $scope.hasCheckedAudits =[]; }; $scope.hasAuditContentToDel = function (){ var i; for(i=$scope.hasCheckedAudits.length;i--;i>0){ if($scope.hasCheckedAudits[i]){ console.log('has content to delete'); return true; } } //console.log('nothing to delete'); return false; }; var getSnmpV3Users = function(){ restGetSnmpSettingInfo.get(function(data){ $scope.Users = []; var item = data["items"][0]; var attrs = ['imm_services_disabled','snmp_security_exception','snmp_traps_enabled','snmp_traps_critical_enabled', 'snmp_traps_critical_cpu','snmp_traps_critical_drive','snmp_traps_critical_fan','snmp_traps_critical_hardware', 'snmp_traps_critical_memory','snmp_traps_critical_other','snmp_traps_critical_power','snmp_traps_critical_redundancy', 'snmp_traps_critical_temp','snmp_traps_critical_voltage','snmp_traps_attention_enabled','snmp_traps_attention_cpu', 'snmp_traps_attention_fan','snmp_traps_attention_memory','snmp_traps_attention_other','snmp_traps_attention_power', 'snmp_traps_attention_redundancy','snmp_traps_attention_temp','snmp_traps_attention_voltage','snmp_traps_system_enabled', 'snmp_traps_system_boot','snmp_traps_system_fault','snmp_traps_system_info','snmp_traps_system_log','snmp_traps_system_login', 'snmp_traps_system_network','snmp_traps_system_os','snmp_traps_system_power','snmp_traps_system_watchdog','snmp_v3_enabled']; numberToBoolean(item,attrs); $scope.criticalChkInfo.temp = item.snmp_traps_critical_temp; $scope.criticalChkInfo.volt = item.snmp_traps_critical_voltage; $scope.criticalChkInfo.power = item.snmp_traps_critical_drive; $scope.criticalChkInfo.disk = item.snmp_traps_critical_power; $scope.criticalChkInfo.fan = item.snmp_traps_critical_fan; $scope.criticalChkInfo.cpu = item.snmp_traps_critical_cpu; $scope.criticalChkInfo.memory = item.snmp_traps_critical_memory; $scope.criticalChkInfo.hw_incomp = item.snmp_traps_critical_hardware; $scope.criticalChkInfo.redun_power = item.snmp_traps_critical_redundancy; $scope.criticalChkInfo.other = item.snmp_traps_critical_other; $scope.warnChkInfo.redun_power = item.snmp_traps_attention_redundancy; $scope.warnChkInfo.temp = item.snmp_traps_attention_temp; $scope.warnChkInfo.volt = item.snmp_traps_attention_voltage; $scope.warnChkInfo.power = item.snmp_traps_attention_power; $scope.warnChkInfo.fan = item.snmp_traps_attention_fan; $scope.warnChkInfo.cpu = item.snmp_traps_attention_cpu; $scope.warnChkInfo.memory = item.snmp_traps_attention_memory; $scope.warnChkInfo.other = item.snmp_traps_attention_other; $scope.systemChkInfo.remote_login = item.snmp_traps_system_login; $scope.systemChkInfo.os_timeout = item.snmp_traps_system_os; $scope.systemChkInfo.other = item.snmp_traps_system_info; $scope.systemChkInfo.boot_fail = item.snmp_traps_system_boot; $scope.systemChkInfo.load_timeout = item.snmp_traps_system_watchdog; $scope.systemChkInfo.pfa = item.snmp_traps_system_power; $scope.systemChkInfo['75full'] = item.snmp_traps_system_log; $scope.systemChkInfo.net_change = item.snmp_traps_system_network; $scope.systemChkInfo.all_audit = item.snmp_traps_system_fault; $scope.snmpV3Setting.snmp_v3_enabled = item['snmp_v3_enabled']; $scope.snmpV3Setting.snmp_contact_person = item.snmp_contact_person; $scope.snmpV3Setting.snmp_location = item.snmp_location; $scope.snmpV3Setting.snmp_traps_enabled = item.snmp_traps_enabled; $scope.snmpV3Setting.snmp_traps_critical_enabled = item.snmp_traps_critical_enabled; $scope.snmpV3Setting.snmp_traps_attention_enabled = item.snmp_traps_attention_enabled; $scope.snmpV3Setting.snmp_traps_system_enabled = item.snmp_traps_system_enabled; $scope.snmpv3Users = item['snmp_local_users']; console.log("length of users:"+$scope.snmpv3Users.length); $scope.hasSNMPv3 = false; $scope.snmpv3Users.forEach(function(item){ if(item['name'] != ""){ $scope.Users.push(item['name']); $scope.hasSNMPv3 = true; }else{ } }); $scope.numOfUsers = $scope.Users.length; console.log("number of users:"+ $scope.numOfUsers); }); } getSnmpV3Users(); restGetAllUsers.get(function(data){ $scope.allUsers = data['items'][0]['users']; for(var i = $scope.allUsers.length-1; i>=0 ;i--){ if($scope.allUsers[i]['users_user_name'] == ""){ $scope.allUsers.remove($scope.allUsers[i]); } } }); $scope.chgMap = function(viewName) { $scope.showSearchText = false ; $scope.showCustomizeTab = false; $scope.query=""; $scope.showSequence = false; $scope.showServiceState = false; $scope.showIndexNum = false; //$scope.customizeTabInfo.ServiceState = false; //$scope.customizeTabInfo.Index = false; //$scope.customizeTabInfo.Sequence = false; $scope.showPreviousTwohours = false; $scope.showPreviousTwefourHours = false; $scope.showPreviousSevenDays = false; $scope.showPreviousThirtyDays = false; if (viewName == 'eventLog') { if ($scope.showEventLog) { //$scope.showEventLog = true; } else { $scope.showEventLog = true; $scope.showAuditLog = false; $scope.showMaintenanceHistory = false; $scope.showAlertRecipients = false; $scope.showSNMPv3AlertRecipients = false; } }; if (viewName == 'auditLog') { if ($scope.showAuditLog) { } else { $scope.showAuditLog = true; $scope.showEventLog = false; $scope.showMaintenanceHistory = false; $scope.showAlertRecipients = false; $scope.showSNMPv3AlertRecipients = false; } }; if (viewName == 'maintenanceHistory') { if ($scope.showMaintenanceHistory) { } else { $scope.showMaintenanceHistory = true; $scope.showEventLog = false; $scope.showAuditLog = false; $scope.showAlertRecipients = false; $scope.showSNMPv3AlertRecipients = false; } }; if(viewName == 'AlertRecipients'){ if($scope.showAlertRecipients){ }else{ $scope.showAlertRecipients = true; $scope.showMaintenanceHistory = false; $scope.showEventLog = false; $scope.showAuditLog = false; $scope.showSNMPv3AlertRecipients = false; } } //customize tab if (viewName == 'CustomizeTab') { $scope.showCustomizeTab = !$scope.showCustomizeTab; } if (viewName == 'CustomNote' ){ $scope.showCustomNote = !$scope.showCustomNote; }; if (viewName == 'auditCustomizeTab') { $scope.showAuditCustomizeTab = !$scope.showAuditCustomizeTab; }; //init alert configure opearation if(viewName == 'createEmailRecipient') { $scope.showCreateEmailRecipient = !$scope.showCreateEmailRecipient; }; if(viewName == 'createSyslogRecipient'){ $scope.showCreateSyslogRecipient = !$scope.showCreateSyslogRecipient; }; if(viewName == 'createSNMPv3Recipient') { $scope.showCreateSNMPv3Recipient = !$scope.showCreateSNMPv3Recipient; removeRepeatUser(); $scope.userBeingEdit = { "access": "", "access_address": "", "access_type": "", "auth_protocol": "", "name": "", "privacy_password": "", "privacy_protocol": "", "use_a_privacy_protocol": "0", "use_an_auth_protocol": "0", "user_id": "" }; console.log("user_name:"+$scope.allUsers[0]['users_user_name']); $scope.userBeingEdit['name'] = $scope.allUsers[0]['users_user_name']; $scope.userBeingEdit['auth_protocol'] = 0; $scope.userBeingEdit['privacy_protocol'] = 0; $scope.userBeingEdit['privacy_protocol'] = 0; $scope.allUsers.forEach(function(item){ $scope.SNMPv3UserSelect.map[item['users_user_name']] = item['users_user_name']; }) //if($scope.showCreateSNMPv3Recipient){ // for(var i = 0; i < $scope.snmpv3Users.length; i++){ // if($scope.snmpv3Users[i]['name'] != ""){ // $scope.userBeingEdit = angular.copy($scope.snmpv3Users[i]); // } // break; // } //} }; //critical event type if (viewName == 'criticalEvtsType') { $scope.showCriticalEvtsType = true; $scope.showAttentionEvtsType = false; $scope.showSystemEvtsType = false; if($("#criticalEvtsType").is(":checked")) { if($scope.id2edit == ''){ initCrit(true); }else{ initEditCrit(true); } //$("#showCriticalEvtsType").find("input[type='checkbox']").prop("checked","checked"); //var showCriticalEvtsType = $("#showCriticalEvtsType").find("input[type='checkbox']"); //showCriticalEvtsType[0].checked = true; } else { if($scope.id2edit == ''){ initCrit(false); }else{ initEditCrit(false); } //$("#showCriticalEvtsType").find("input[type='checkbox']").removeAttr("checked"); } }; //attention event type if (viewName == 'attentionEvtsType') { $scope.showAttentionEvtsType = true; $scope.showSystemEvtsType = false; $scope.showCriticalEvtsType = false; if($("#attentionEvtsType").is(":checked")) { if($scope.id2edit == ''){ initWarn(true); }else{ initEditWarn(true); } //$("#showAttentionEvtsType").find("input[type='checkbox']").prop("checked","checked"); } else { if($scope.id2edit == ''){ initWarn(false); }else{ initEditWarn(false); } //$("#showAttentionEvtsType").find("input[type='checkbox']").removeAttr("checked"); } }; //system event type if (viewName == 'systemEvtsType') { $scope.showSystemEvtsType = true; $scope.showCriticalEvtsType = false; $scope.showAttentionEvtsType = false; if($("#systemEvtsType").is(":checked")) { if($scope.id2edit == ''){ initInfo(true); }else{ initEditInfo(true); } //$("#showSystemEvtsType").find("input[type='checkbox']").prop("checked","checked"); } else { if($scope.id2edit == ''){ initInfo(false); }else{ initEditInfo(false); } //$("#showSystemEvtsType").find("input[type='checkbox']").removeAttr("checked"); } }; } } ]) //change map /*help text controller*/ .controller('helpPopCtrl', ['$scope', function($scope) { $("#eventPopOver1").popover({content: "Specify the index number in the command line interface for this alert receipient.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver2").popover({content: "Specify the index number in the command line<br> interface for this alert receipient.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver3").popover({content: "Specify the Authentication Protocol, either HMAC-MD5 or HMAC-SHA. These are hash algorithms used by the SNMP V3 security model for the authentication. The password for the Linux account will be used for authentication. <br><b>Full name of HMAC-MD5:</b> Hash-based Message Authentication Code - Message- Digest algorithm 5 <br><b>Full name of HMAC-SHA:</b> Hash-based Message Authentication Code - Secure Hash Algorithm",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver4").popover({content: "Data transfer between the SNMP client and the agent can be protected using encryption. The supported methods are DES and AES. Privacy protocol is valid only if the Authentication protocol is either HMAC-MD5 or HMAC-SHA.<br><b>Full name of AES :</b> Advanced Encryption Standard<br><b>Full name of CBC-DES:</b> Cipher Block Chaining - Data Encryption Standard",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver5").popover({content: "Use this field to specify whether you want to send traps to SNMPv3 trap receivers configured under 'Login Profiles' or to allow an SNMPv3 manager to send 'get' and 'set' requests to the SNMPv3 agent. <br>Note: To enable the SNMPv3 agent, the IMM contact and location must be specified.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver6").popover({content: "Specify the name and phone number of the person who should be contacted if there is a problem with this system.<br>You can enter a maximum of 47 characters in this field. Special characters & < > are not allowed.<br>Note: This field is the same as the Contact field in the Server Properties; General Settings page",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver7").popover({content: "Identify where this system has been installed. The information in this field, along with Room ID, Rack ID and Lowest U-postion (if provided) should be of sufficient detail to allow someone to quickly find the server when necessary for maintenance or other pupopses.<br><br>You can enter a maximum of 47 characters in this field.<br>Special characters ! ~ ` @ # $ % ^ & * ( ) / : ; \" ' , < > [ ] ? = | + are not allowed.<br><br>Note: This field is the same as the Locaction field in the Server Properties; General Settings page.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver8").popover({content: "The SNMP agent notifies the management station about events on the IMM using traps. The SNMP Alert settings are global for all SNMP traps.<br><br>You can configure SNMP to filter the events, based on type. Filtering can be based on Critical, Attention and System event types. Informational events are not filtered. System events may some times overlap with the Critial and Attention types.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver9").popover({content: "Specify the index number in the command line interface for this alert receipient.",trigger: 'manual'}) .on("mouseover", function() { console.log('mouse overing'); $(this).popover('show'); }) .on("mouseout", function() { console.log('mouse leaving...'); $(this).popover('hide'); }); $("#eventPopOver10").popover({content: "Specify the index number in the command line interface for this alert receipient.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver11").popover({content: "Specify the Authentication Protocol, either HMAC-MD5 or HMAC-SHA. These are hash algorithms used by the SNMP V3 security model for the authentication. The password for the Linux account will be used for authentication. <br><b>Full name of HMAC-MD5:</b> Hash-based Message Authentication Code - Message- Digest algorithm 5 <br><b>Full name of HMAC-SHA:</b> Hash-based Message Authentication Code - Secure Hash Algorithm",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver12").popover({content: "Data transfer between the SNMP client and the agent can be protected using encryption. The supported methods are DES and AES. Privacy protocol is valid only if the Authentication protocol is either HMAC-MD5 or HMAC-SHA.<br><b>Full name of AES :</b> Advanced Encryption Standard<br><b>Full name of CBC-DES:</b> Cipher Block Chaining - Data Encryption Standard",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver13").popover({content: "Specify the time interval (in minutes) that the IMM subsystem <br>will wait retries to send an alert.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver14").popover({content: "Specify the number of additional times that the IMM subsystem <br>will attempt to send an alert.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver15").popover({content: "Specify the time interval (in minutes) that the IMM subsystem <br>will wait before sending an alert to the next recipient in the list.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver16").popover({content: "Use this field to specify whether you want to send traps to SNMPv3 trap receivers configured under 'Login Profiles' or to allow an SNMPv3 manager to send 'get' and 'set' requests to the SNMPv3 agent. <br>Note: To enable the SNMPv3 agent, the IMM contact and location must be specified.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver17").popover({content: "Specify the name and phone number of the person who should be contacted if there is a problem with this system.<br>You can enter a maximum of 47 characters in this field. Special characters & < > are not allowed.<br>Note: This field is the same as the Contact field in the Server Properties; General Settings page",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver18").popover({content: "Identify where this system has been installed. The information in this field, along with Room ID, Rack ID and Lowest U-postion (if provided) should be of sufficient detail to allow someone to quickly find the server when necessary for maintenance or other pupopses.<br><br>You can enter a maximum of 47 characters in this field.<br>Special characters ! ~ ` @ # $ % ^ & * ( ) / : ; \" ' , < > [ ] ? = | + are not allowed.<br><br>Note: This field is the same as the Locaction field in the Server Properties; General Settings page.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); $("#eventPopOver19").popover({content: "The SNMP agent notifies the management station about events on the IMM using traps. The SNMP Alert settings are global for all SNMP traps.<br><br>You can configure SNMP to filter the events, based on type. Filtering can be based on Critical, Attention and System event types. Informational events are not filtered. System events may some times overlap with the Critial and Attention types.",trigger: 'manual'}) .on("mouseover", function() { $(this).popover('show'); }) .on("mouseout", function() { $(this).popover('hide'); }); } ]); <file_sep>/* Copyright 2016 Avocent Corporation and its affiliates. * All Rights Reserved. * * This is Example code, and is provided "as is". Its * functionality is intended to be re-written and refined * by a GUI design team. */ /******** Initialization Start **************************/ var mUsername; var mPassword; var mPort; var mIPAddress; var colorArgs = [1, 2, 3, 4, 7, 9, 12, 15, 18, 21, 23]; //array entries 0 - 3 are BW, 4 - 10 are color var colorsMax = colorArgs.length; var htmlViewer = null; var bLaunchViewer = false; var bLaunchVMedia = false; var sessionSharingTimeout = null; var sessionUserList = null; var bSessionReadonly = false; var bDragSettingDialog = false; var bDragChatDialog = false; var ptDragingDialogX; var ptDragingDialogY; var mediaDriveList = null; var mediaDriveMapped = null; var viewerWidth; var viewerHeight; var clientWidth; var clientHeight; var dialogTitle = 'HTML5 Viewer'; var html5ErrorFunc = null; var html5ErrorCode = null; var invData = []; var blockDVCColorMode=false; var fileBlobArray = []; var fileNameArray = []; var fileMapStateArray = []; /******** Initialization End **************************/ if (isMobileBrowser()) { window.addEventListener("orientationchange", fitToScreen, false); } else { window.addEventListener('resize', fitToScreen, false); } /** * Function is used to resize the canvas based on browser's size. * */ function fitToScreen() { var parentDiv = document.getElementById("canvasParentDiv"); viewerWidth = parentDiv.clientWidth; viewerHeight = parentDiv.clientHeight; if (htmlViewer !== null) { htmlViewer.setRPEmbeddedViewerSize(viewerWidth, viewerHeight); } } /** * * This function will be called after page is loaded. */ function loadLoginPopup() { /* console.log("connecting..."); // var x = location.hostname; // console.log('HostName::'+x); document.getElementById('login').style.display = 'block'; document.getElementById('content').style.display = 'block'; var elem = document.getElementsByName("touchOption"); elem[0].checked = true; loadSettingsTab(); document.getElementById("checkratio").checked = true; */ //Create Object for RPViewer htmlViewer = new RPViewer("kvmCanvas", viewerAPIErrorCallback); // document.getElementById('version').innerHTML = "Version " + htmlViewer.getRPVersion(); } /** * This function will be called to connect the viewer * */ function launchKVM() { console.log("connecting..."); if (html5ErrorCode !== null) { viewerAPIErrorCallback(html5ErrorFunc, html5ErrorCode); return; } var parentDiv = document.getElementById("canvasParentDiv"); viewerWidth = parentDiv.clientWidth; viewerHeight = parentDiv.clientHeight; document.getElementById('login').style.display = 'none'; sessionUserList = null; if (bLaunchViewer === false) { var tempUserName = document.getElementById("txtUserName").value; var tempPassword = document.getElementById("txtPassword").value; mPort = document.getElementById("txtPort").value; mIPAddress = document.getElementById("txtIPAddress").value; mUsername = tempUserName; mPassword = <PASSWORD>; //Configuration APIs /* The default timeout value is 2 seconds if this API is not used. For slower network connection, you can increase this value. */ htmlViewer.setRPWebSocketTimeout(2); htmlViewer.setRPCredential(tempUserName, tempPassword); htmlViewer.setRPServerConfiguration(mIPAddress, mPort); htmlViewer.setRPEmbeddedViewerSize(viewerWidth, viewerHeight); htmlViewer.setRPAllowSharingRequests(true); htmlViewer.setRPMouseInputSupport(true); htmlViewer.setRPTouchInputSupport(true); htmlViewer.setRPKeyboardInputSupport(true); htmlViewer.setRPDebugMode(true); htmlViewer.setRPMaintainAspectRatio(true); htmlViewer.setRPInitialBackgroundColor('burlywood'); htmlViewer.setRPInitialMessageColor('black'); htmlViewer.setRPVirtualKeyboardPosition(50,100); htmlViewer.setRPInitialMessage('Connecting Viewer...'); //Setting Callbacks htmlViewer.registerRPLoginResponseCallback(loginResponseCallback); // htmlViewer.registerRPSharingRequestCallback(sharingRequestCallback); htmlViewer.registerRPSharedRequestCancelCallback(sharingCancelRequestCallback); htmlViewer.registerRPExitViewerCallback(exitViewerCallback); htmlViewer.registerRPUserListChangeCallback(userListChangeCallback); htmlViewer.registerRPColorModeChangeCallback(reportColorModeChange); htmlViewer.registerRPChatMessageCallback(chatMessageCallback); htmlViewer.registerRPMouseAccelerationChangeCallback(mouseAccelerationCallback); htmlViewer.registerRPSessionReadOnlyCallback(sessionReadonlyCallback); htmlViewer.registerRPSessionTerminationCallback(sessionTermCallback); htmlViewer.registerRPVideoStoppedCallback(videoStoppedCallback); htmlViewer.registerRPLEDKeyStatusCallback(ledStatusCallback); htmlViewer.registerRPInventoryCallback(inventoryCallback); //htmlViewer.registerRPUserInteractionCallback(userInteractionCallback); htmlViewer.registerRPVMLoginResponseCallback(loginVMCallback); htmlViewer.registerRPVMSessionDisconnectCallback(disconnectVMCallback); htmlViewer.registerRPVMDeviceInfoUpdateCallback(infoVMDevicesCallback); htmlViewer.registerRPVMDeviceStatusUpdateCallback(statusVMDeviceCallback); //Connect Viewer htmlViewer.connectRPViewer(); bLaunchViewer = true; } else { bLaunchViewer = false; exitViewer(); } } /** * This function will be called to connect the virtual media * */ function launchVM() { if (htmlViewer != null) { if (bLaunchVMedia === false) { console.log('Launching VMedia ...'); var bNeedTempCredentials = true; var fileDiskElem = document.getElementById("fileDisk"); fileDiskElem.addEventListener("change", function(event) { var index = getComboIndex(); fileBlobArray[index] = event.target.files[0]; fileNameArray[index] = fileBlobArray[index].name; fileMapStateArray[index] = false; //set buttons here }, false); htmlViewer.setRPVMPort(mPort); htmlViewer.activateRPVMedia(bNeedTempCredentials); } else { var alertText = cleanup(true); if ( alertText ) { // if you have to warn about mapped drives give a chance for user to cancel. if (confirm(alertText)) CleanupCloseVMedia(); } else { // no drives mapped so just close vmedia. CleanupCloseVMedia(); } } } } function getComboIndex() { var x = document.getElementById("driveListCombo"); var index = parseInt(x.value); return index; } function CleanupCloseVMedia() { console.log('Closing VMedia ...'); htmlViewer.deactivateRPVMedia(); closeMediaDriveDialog(); mediaDriveList = null; for (var i=0; i<fileMapStateArray.length; i++) { fileMapStateArray[i] = false; } setDriveTypes(); bLaunchVMedia = false; setMediaDisplayStatus(bLaunchVMedia); } function MapDiskAction() { var index = getComboIndex(); var maptext = ''; var mappath = ''; if (fileBlobArray[index] == null) { alert('Please select a file first before mapping'); return; } // check fileName0 to verify extension; var partsFile = fileNameArray[index].split('.'); var mediaExtension = partsFile[partsFile.length - 1]; var bError = true; switch (mediaDriveList[index].deviceType) { case RPViewer.RP_MEDIA_REMOTE_TYPE.REMOTE_TYPE_REMOVABLE: case RPViewer.RP_MEDIA_REMOTE_TYPE.REMOTE_TYPE_FLOPPY: if (mediaExtension.toLowerCase() == "img") bError = false; break; case RPViewer.RP_MEDIA_REMOTE_TYPE.REMOTE_TYPE_CD_DVD: if (mediaExtension.toLowerCase() == "iso") bError = false; break; } if (bError) { alert("Invalid File Type!"); return; } // use fileBlob0 to map var bMappedMediaDrive = false; if (htmlViewer !== null) { htmlViewer.mapRPDevice(index, fileBlobArray[index]); fileMapStateArray[index] = true; } resetDriveDialog(); } function UnMapDiskAction() { var index = getComboIndex(); htmlViewer.unMapRPDevice(index); fileMapStateArray[index] = false; resetDriveDialog(); } function resetDriveDialog() { var index = getComboIndex(); if ( fileMapStateArray[index] ) { document.getElementById("DriveName2").innerHTML = getDriveNameByType(mediaDriveList[index].deviceType); document.getElementById("mappedDivDescr").innerHTML = fileNameArray[index] + "<br/>mapped -- Read Only" document.getElementById("MappedDiv").style.display = 'block'; document.getElementById("NotMappedDiv").style.display = 'none'; } else { // it's unmapped so I need to set it to unmapped document.getElementById("DriveName").innerHTML = getDriveNameByType(mediaDriveList[index].deviceType); document.getElementById("fileDisk").value = ""; fileBlobArray[index] = null; document.getElementById("MappedDiv").style.display = 'none'; document.getElementById("NotMappedDiv").style.display = 'block'; } } /** * Callback function for RPViewer API errors. * @param {type} errorFunctionName * @param {type} errorCode * */ function viewerAPIErrorCallback(errorFunctionName, errorCode) { console.log('viewerAPIErrorCallback::errorFunctionName::' + errorFunctionName + " errorCode::" + errorCode); html5ErrorFunc = errorFunctionName; html5ErrorCode = errorCode; if (errorCode === RPViewer.RP_API_ERROR.HTML5_NOT_SUPPORTED_BY_BROWSER) { alert("Your browser is not compatible with HTML5."); } else if (errorCode === RPViewer.RP_API_ERROR.WEBSOCKET_NOT_SUPPORTED_BY_BROWSER) { alert("Your browser doesn't support websocket."); } else if (errorCode === RPViewer.RP_API_ERROR.POPUP_BLOCKED) { alert("Turn off your pop-up blocker and try again!"); } else if (errorCode === RPViewer.RP_API_ERROR.INVALID_CANVAS_ID) { alert("Invalid Canvas ID!"); } else { alert('API Error! \n\nFunction Name:' + errorFunctionName + " \nError Code:" + errorCode); } } /** * Callback function for RPViewer user list change. * @param {type} userList * */ function userListChangeCallback(userList) { Logger.logDebug('myUserListChangeCallback No.of Users::' + userList.length); var i = 0; if (sessionUserList === null) {//if here, this is a new instance of a viewer if (userList.length === 1) { var chatMsgData = localStorage.getItem("VIEWER_CHAT_DATA"); if (chatMsgData === null) { var msg = userList[0].userName + ":" + userList[0].sessionID + " User has joined."; localStorage.setItem("VIEWER_CHAT_DATA", msg); addChatHistory(msg, true); } } else { for (i = 0; i < userList.length; i++) { var userRecord = userList[i]; if (userRecord.isCurrentUser === false) { var chatMsgData = localStorage.getItem("VIEWER_CHAT_DATA"); if (chatMsgData === null) { var msg = userList[i].userName + ":" + userList[i].sessionID + " User Has joined."; localStorage.setItem("VIEWER_CHAT_DATA", userList[i].userName + ":" + userList[i].sessionID + "User has Joined."); addChatHistory(msg, false); } break; } } } } else if (sessionUserList !== null) { //not a new viewer session if here. Logger.logDebug('myUserListChangeCallback userList.length::' + userList.length + " sessionUserList.length::" + sessionUserList.length); if (userList.length > sessionUserList.length)//Someone has joined. { for (i = 0; i < userList.length; i++) {//Search for new user var bFound = false; var userRecord = userList[i]; if (userRecord.isCurrentUser === false) //we know I am not the new user, so don't check "true". { var newUserId = userRecord.userID; var newSessionID = userRecord.sessionID; //Check this user Id is already in the list for (var j = 0; j < sessionUserList.length; j++) { var userOldRecord = sessionUserList[j]; if ((newUserId === userOldRecord.userID) && (newSessionID === userOldRecord.sessionID)) { bFound = true; Logger.logDebug('myUserListChangeCallback found Old user: ' + newUserId + " " + newSessionID + " Skipping to next."); break; } } if (bFound === true) continue; //check others in userList? } } if (bFound === false) { //This is the new user i--; var chatUserMsg = userList[i].userName + ":" + userList[i].sessionID + " User Has Joined."; Logger.logDebug('myUserListChangeCallback New user::' + chatUserMsg); var chatMsgData = localStorage.getItem("VIEWER_CHAT_DATA"); chatMsgData += "�" + chatUserMsg; localStorage.setItem("VIEWER_CHAT_DATA", chatMsgData); addChatHistory(chatUserMsg, false); } else { Logger.logDebug('myUserListChangeCallback *** ERROR: Expecting a new user and did not find one.'); } } else { //Someone has left for (i = 0; i < sessionUserList.length; i++) { var userOldRecord = sessionUserList[i]; if (userOldRecord.isCurrentUser === false) { var exisUserId = userOldRecord.userID; //Check this user still exists in uesrList var bFound = false; for (var j = 0; j < userList.length; j++) { var userRecord = userList[j]; if (exisUserId === userRecord.userID) { bFound = true; break; } } if (bFound === false) { var chatUserMsg = sessionUserList[i].userName + ":" + sessionUserList[i].sessionID + " User has left."; Logger.logDebug('myUserListChangeCallback ::' + chatUserMsg); var chatMsgData = localStorage.getItem("VIEWER_CHAT_DATA"); chatMsgData += chatUserMsg; localStorage.setItem("VIEWER_CHAT_DATA", chatMsgData); addChatHistory(chatUserMsg, false); break; } } } } } sessionUserList = userList; for (var i = 0; i < userList.length; i++) { var userRecord = userList[i]; console.log('actSession UserName:: ' + i + " " + userRecord.userName + " userID::" + userRecord.userID + " IPAddress:" + userRecord.ipAddress + " Current User:" + userRecord.isCurrentUser + " SessionId::" + userRecord.sessionID); } } /** * Callback function for login response * @param {type} loginStatus * */ function loginResponseCallback(loginStatus) { console.log('loginResponseCallback::' + loginStatus); if (loginStatus === RPViewer.RP_LOGIN_RESULT.LOGIN_SUCCESS) { document.getElementById("viewerButtons").style.display = 'inline'; return; } else if (loginStatus === RPViewer.RP_LOGIN_RESULT.LOGIN_INUSE) { console.log('another user is using session. sending sharing request'); var confirmMsg = "A session to this device already exists. Do you want to try to share this session?"; var ans = confirm(confirmMsg); // console.log('confirm ans..'+ans); htmlViewer.requestRPSharedMode(ans); return; } //shared session else { reportLoginStatus(loginStatus); //report status via user exposed routine. htmlViewer.closeRPViewerSession(); } } /** * Callback function for session read-only info update * @param {type} bReadOnly * */ function sessionReadonlyCallback(bReadOnly) { bSessionReadonly = bReadOnly; if (bReadOnly) { document.getElementById("macroFieldSet").style.display = 'none'; document.getElementById('keyboardTd').style.display = 'none'; alert('Read Only privilege granted.'); } } /** * Callback function for session termination. * @param {type} reason * */ function sessionTermCallback(reason) { console.log('onSessionTermination...' + reason); reportTerminationReason(reason, true); //report status via user exposed routine. htmlViewer.closeRPViewerSession(); } /** * Callback function to update message for video stopped reasons. * @param {type} reason * @param {type} xRes * @param {type} yRes * @param {type} colorDepth * @returns {String} */ function videoStoppedCallback(reason, xRes, yRes, colorDepth) { //Logger.logDebug('videoStoppedCallback...'+reason); var videoStoppedMsg; switch (reason) { case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_CALIBRATING: videoStoppedMsg = "Calibrating"; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_NO_SIGNAL: videoStoppedMsg = "No Signal"; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_OUT_OF_RANGE: videoStoppedMsg = "Out of Range"; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_PERMISSION_DENIED: case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_BLOCKED: videoStoppedMsg = "The remote vKVM feature\nhas been currently disabled\nby the local system administrator"; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_RESOLUTION_NOT_SUPPORTED: videoStoppedMsg = "Out of Range\nReason:Resolution Not Supported\nDetected Resolution:"; videoStoppedMsg += " " + xRes + "x" + yRes; break; case RPViewer.RP_VIDEO_STOPPED_REASON.VIDEO_CAPTURE_FAILED: videoStoppedMsg = "Out of Range\nReason:Video Capture Failure\nDetected Resolution:"; videoStoppedMsg += " " + xRes + "x" + yRes; videoStoppedMsg += "\n" + "Detected Color Depth:" + colorDepth + "bpp"; break; default: videoStoppedMsg = "No Signal"; break; } return videoStoppedMsg; } /** * Callback function for user interaction status update. * @param {type} userInteraction * */ function userInteractionCallback(userInteraction) { console.log('userInteractionCallback..userInteraction::' + userInteraction); } /** * Callback function to update keyborad LED (Caps,Num,Scroll) status. * @param {type} bCapsOn * @param {type} bNumOn * @param {type} bScrollOn * */ function ledStatusCallback(bCapsOn, bNumOn, bScrollOn) { console.log('ledStatusCallback..bCapsOn::' + bCapsOn + "bNumOn::" + bNumOn + " bScrollOn::" + bScrollOn); var capsElem = document.getElementById("capsStatusDiv"); var numElem = document.getElementById("numStatusDiv"); var ScrollElem = document.getElementById("scrollStatusDiv"); if (bCapsOn) { capsElem.className = "led-green"; } else { capsElem.className = "led-green-off"; } if (bNumOn) { numElem.className = "led-green"; } else { numElem.className = "led-green-off"; } if (bScrollOn) { ScrollElem.className = "led-green"; } else { ScrollElem.className = "led-green-off"; } } /** * Callback function for VMedia login response * @param {type} loginStatus * */ function loginVMCallback(loginStatus) { Logger.logDebug('loginVMCallback response::' + loginStatus); bLaunchVMedia = (loginStatus == RPViewer.RP_LOGIN_RESULT.LOGIN_SUCCESS); // report status via user exposed routine. if (! bLaunchVMedia) reportLoginStatus(loginStatus); setMediaDisplayStatus(bLaunchVMedia); } /** * Callback function for VMedia session diconnect * @param {type} reason * */ function disconnectVMCallback(reason) { Logger.logDebug('disconnectVMCallback response::' + reason); reportTerminationReason(reason, false); // shutdown all of vmedia CleanupCloseVMedia(); } /** * Callback function for VMedia device list change. * @param {type} deviceList * */ var bPerformingFinalCheckVMDevices = false; function infoVMDevicesCallback(deviceList) { Logger.logDebug('infoVMDevicesCallback No.of Devices::' + deviceList.length); // add devices to dropdown list // check the devices to see if i need to detach/ disconnect var count = 0; for (var i = 0; (i < deviceList.length); i++) { if (deviceList[i].deviceType != 0) count++; } // update the number of blobs if we need to while ( fileBlobArray.length < count ) { fileBlobArray.push(null); fileNameArray.push(null); fileMapStateArray.push(false); } if (count > 0) { mediaDriveList = deviceList; setDriveTypes(); } else { if ( bPerformingFinalCheckVMDevices ) return; bPerformingFinalCheckVMDevices = true; // some servers are slow to give the drivelist back tot he client, we'll wait 5 seconds and check again. setTimeout(function() { finalCheckVMDevices(); }, 5000); } } function finalCheckVMDevices() { if (mediaDriveList == null) { // possibly warn about detached vmedia here? } } var deviceList; function setDriveTypes() { var index = getComboIndex(); // saved index var deviceList = mediaDriveList; var DriveSelect = document.getElementById('driveListCombo'); removeOptions(DriveSelect); if (( deviceList == null ) || ( deviceList.length == 0)) { DriveSelect.options[DriveSelect.options.length] = new Option("No Drives", 0); return; } for (var i = 0; (i < deviceList.length); i++) { //deviceList[i].deviceType; //deviceList[i].deviceId; var Descr; Descr = getDriveNameByType(deviceList[i].deviceType); if ( fileMapStateArray[i] ) Descr += "- Mapped"; DriveSelect.options[DriveSelect.options.length] = new Option(Descr, deviceList[i].deviceId); if ( DriveSelect.options[DriveSelect.options.length-1].value == index) DriveSelect.options[DriveSelect.options.length-1].selected = true; } } function getDriveNameByType(type) { var Descr = ""; switch (type) { case RPViewer.RP_MEDIA_REMOTE_TYPE.REMOTE_TYPE_REMOVABLE: Descr = "Removable Disk"; break; case RPViewer.RP_MEDIA_REMOTE_TYPE.REMOTE_TYPE_CD_DVD: Descr = "CD/DVD"; break; case RPViewer.RP_MEDIA_REMOTE_TYPE.REMOTE_TYPE_FLOPPY: Descr = "Floppy Disk"; break; } return Descr; } function removeOptions(selectbox) { var i; for(i=selectbox.options.length-1;i>=0;i--) { selectbox.remove(i); } } /** * Callback function for VMedia device status change. * @param {type} deviceList * */ function statusVMDeviceCallback(deviceId, isMapped, statusRemote, statusLocal) { Logger.logDebug('statusVMDeviceCallback Device::' + deviceId + 'Status::' + statusRemote + 'Local::' + statusLocal); // display an error if ((statusRemote != RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_OK) || (statusLocal != RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_OK)) { if ((statusRemote == -1)&&(statusLocal == 0)) return; var msgError = "Unspecified error"; if ((statusRemote != RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_OK) && (statusRemote != RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_STATUS_UNKNOWN)) { switch (statusRemote) { case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_DEVICE_INVALID: msgError = "Command not supported"; break; case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_DEVICE_UNSUPPORTED: msgError = "Device not supported"; break; case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_DEVICE_DISCONNECTED: msgError = "Device not connected"; break; case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_DEVICE_DISABLED: msgError = "Drive disabled"; break; case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_DEVICE_ATTACHED: msgError = "Drive already attached"; break; case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_DEVICE_OPTION: msgError = "Unknown configuration option"; break; case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_DEVICE_ERROR: msgError = "Unknown cause"; break; case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_FAILED_REQUEST: msgError = "Request failed"; break; case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_FAILED_READ: msgError = "Read failed on device"; break; case RPViewer.RP_MEDIA_REMOTE_STATUS.REMOTE_FAILED_WRITE: msgError = "Write failed device"; break; } } if ((statusLocal != RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_OK) && (statusLocal != RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_STATUS_UNKNOWN)) { switch (statusLocal) { case RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_DRIVE_INVALID: msgError = "Invalid drive identifer"; break; case RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_DRIVE_UNKNOWN: msgError = "Unknown file type"; break; case RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_DRIVE_UNSUPPORTED: msgError = "File type is not supported"; break; case RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_DRIVE_ERROR: msgError = "Unknown file error"; break; case RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_FAILED_READ: msgError = "Failed to read file"; break; case RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_SIZE_EMPTY: msgError = "The file contains no data"; break; case RPViewer.RP_MEDIA_LOCAL_STATUS.LOCAL_SIZE_BIG: msgError = "The size of the selected file is greater than 2.8 MB."; break; } } alert(msgError + "!\n\nDevice has been unmapped."); htmlViewer.unMapRPDevice(deviceId); fileMapStateArray[deviceId] = false; } resetDriveDialog(); } /** * Function is used to display checked button * @returns {Boolean} */ function setMediaDisplayStatus(bActivated) { document.getElementById("btnVMedia").innerHTML = (bActivated ? "Deactivate" : "Activate" ); document.getElementById("driveListCombo").style.visibility = (bActivated ? "visible" : "hidden" ); document.getElementById("btnManage").style.visibility = (bActivated ? "visible" : "hidden" ); } /** * Callback function to update RPViewer inventory data. * @param {type} data * */ function inventoryCallback(data) { var jsonData = JSON.parse(data); var rootKey; invData.length = 0; for (var prop in jsonData) { if (typeof (jsonData[prop]) === 'object' && !(jsonData[prop] instanceof Array)) { rootKey = prop; getInvValues(jsonData, rootKey); } else { var propName = "jsonobj." + prop; var propValue = jsonData[prop]; invData.push({ name: propName, value: propValue }); //console.log(propName +" = "+ propValue); } } } /** * Function is used to push inventory data to an array * @param {type} json * @param {type} rootKey * */ function getInvValues(json, rootKey) { for (var key in json[rootKey]) { for (var key1 in json[rootKey][key]) { if (typeof json[rootKey][key][key1] === "object") { var arr = json[rootKey][key][key1]; for (var prop in arr) { if (typeof arr[prop] === "object") { for (var elem in arr[prop]) { var propName = "jsonobj." + rootKey + "." + key + "." + key1 + "." + prop + "." + elem; var propValue = arr[prop][elem]; invData.push({ name: propName, value: propValue }); // console.log("jsonobj."+rootKey+ "."+ key + "." + key1 + "."+prop + "."+ elem + " = "+arr[prop][elem]); } } else { var propName = "jsonobj." + rootKey + "." + key + "." + key1 + "." + prop; var propValue = arr[prop]; invData.push({ name: propName, value: propValue }); //console.log(propName+ " = "+propValue); } } } else { var propName = "jsonobj." + rootKey + "." + key + "." + key1; var propValue = json[rootKey][key][key1]; invData.push({ name: propName, value: propValue }); // console.log(propName + " == "+ propValue ); } } } } /** * * Function is used to display inventory data in a separate window. */ function showInventory() { if (invData.length === 0) { alert('Inventory data is not available.'); } else { window.open("inventory.html", "Inventory", "width=800,height=500,scrollbars=yes,left=200,top=200,resizable=yes"); } } /** * * Function is used allow user to choose local VMedia drive file. */ function chooseMediaDrive(data) { Logger.logDebug('chooseMediaDrive RemoteDrives::' + data.length); var objFile = document.getElementById("fileVMedia"); if (objFile != null) { // objFile.onchange = loadMediaDrive(data); objFile.addEventListener("change", loadMediaDrive, false); objFile.click(); } return; } /** * * Function is used load and map local VMedia drive file. */ function loadMediaDrive(evt) { var mediaFile = null; var mediaPath = null; var mediaDrive = null; var bMediaIMG = false; var bMediaISO = false; // get the chosen file var filesChoose = evt.target.files; if (filesChoose[0]) { var mediaFile = filesChoose[0]; mediaPath = mediaFile.mozFullPath; if (mediaFile.path) mediaPath = mediaFile.path + "\\" + mediaFile.name; else mediaPath = mediaFile.name; } // get and check the file extension var partsFile = mediaPath.split('.'); var mediaExtension = partsFile[partsFile.length - 1]; if (mediaExtension.toLowerCase() == "img") bMediaIMG = true; if (mediaExtension.toLowerCase() == "iso") bMediaISO = true; if (!bMediaIMG && !bMediaISO) { alert("Invalid File Type!\nPlease choose either an ISO or IMG file."); if (htmlViewer != null) htmlViewer.deactivateRPVMedia(); bLaunchVMedia = false; setMediaDisplayStatus(bLaunchVMedia); return; } Logger.logDebug('loadMediaDrive LocalPath:: "' + mediaPath + '" FileType:: "' + mediaExtension + '"'); // decide on which drive to map it to var deviceList = mediaDriveList; if (deviceList != null) { for (var i = 0; (i < deviceList.length) && (mediaDrive == null); i++) { var deviceMedia = deviceList[i]; if (! deviceMedia.isMapped) { if (deviceMedia.deviceType == RPViewer.RP_MEDIA_REMOTE_TYPE.REMOTE_TYPE_REMOVABLE) { if (bMediaIMG) mediaDrive = deviceMedia.deviceId; } if (deviceMedia.deviceType == RPViewer.RP_MEDIA_REMOTE_TYPE.REMOTE_TYPE_CD_DVD) { if (bMediaISO) mediaDrive = deviceMedia.deviceId; } if (deviceMedia.deviceType == RPViewer.RP_MEDIA_REMOTE_TYPE.REMOTE_TYPE_FLOPPY) { var maxSize = (2.88 * 1024 * 1024); var fileSize = mediaFile.size; if (bMediaIMG && (fileSize <= maxSize)) mediaDrive = deviceMedia.deviceId; } } } } if (mediaDrive == null) { alert("Could not find appropriate drive for mapping."); if (htmlViewer != null) htmlViewer.deactivateRPVMedia(); bLaunchVMedia = false; setMediaDisplayStatus(bLaunchVMedia); return; } // finally, map the drive if ((htmlViewer !== null) && !bMappedMediaDrive) { htmlViewer.mapRPDevice(mediaDrive, mediaFile); mediaDriveMapped = mediaDrive; bMappedMediaDrive = true; } if (! bMappedMediaDrive) { alert("Failed to map drive"); if (htmlViewer != null) htmlViewer.deactivateRPVMedia(); bLaunchVMedia = false; setMediaDisplayStatus(bLaunchVMedia); } } /** * * Function is used close the RPViewer. */ function exitViewer() { if (htmlViewer !== null) { if (bLaunchVMedia) { CleanupCloseVMedia(); } htmlViewer.closeRPViewerSession(); } } /** * * Callback function */ function exitViewerCallback() { //called on page unload, or indirectly from a disconnect button press. invData.length = 0; console.log('exitViewerCallback...'); bLaunchViewer = false; bLaunchVMedia = false; bSessionReadonly = false; //Close Chat window if already open closeChatDialog(); var chatTable = document.getElementById("messageTable"); chatTable.innerHTML = ''; sessionUserList = null; localStorage.removeItem("VIEWER_CHAT_DATA"); document.getElementById("settingsDiv").style.display = 'none'; document.getElementById("viewerButtons").style.display = 'none'; if (document.getElementById('keyboardTd').style.display === 'none') { document.getElementById('keyboardTd').style.display = 'block'; } document.getElementById("macroFieldSet").style.display = 'block'; addAllSettingsTabs(); loadLoginPopup(); } /** * * Function is used to build Settings dialog. */ function addAllSettingsTabs() { var parentDiv = document.getElementById("tabsList"); var scaleTab = document.getElementById("tabHeader_1"); var touchTab = document.getElementById("tabHeader_2"); if (touchTab === null) { touchTab = document.createElement("li"); touchTab.appendChild(document.createTextNode("Touch")); touchTab.setAttribute("id", "tabHeader_2"); } var mouseTab = document.getElementById("tabHeader_3"); if (mouseTab === null) { mouseTab = document.createElement("li"); mouseTab.appendChild(document.createTextNode("Mouse")); mouseTab.setAttribute("id", "tabHeader_3"); } var colorTab = document.getElementById("tabHeader_4"); if (colorTab === null) { colorTab = document.createElement("li"); colorTab.appendChild(document.createTextNode("Color Mode")); colorTab.setAttribute("id", "tabHeader_4"); } var perfTab = document.getElementById("tabHeader_5"); if (perfTab === null) { perfTab = document.createElement("li"); perfTab.appendChild(document.createTextNode("Performance")); perfTab.setAttribute("id", "tabHeader_5"); } while (parentDiv.firstChild) { parentDiv.removeChild(parentDiv.firstChild); } parentDiv.appendChild(scaleTab); parentDiv.appendChild(touchTab); parentDiv.appendChild(mouseTab); parentDiv.appendChild(colorTab); parentDiv.appendChild(perfTab); } /** * * Function is used to open Chat dialog */ function openChatDialog() { var elem = document.getElementById("chatDiv"); var chatText = document.getElementById('txtChat'); if (elem.style.display !== 'block') { var headerelem = document.getElementById("chatHeader"); headerelem.addEventListener('dragstart', drag_startChat, false); document.body.addEventListener('dragover', drag_overChat, false); document.body.addEventListener('drop', dropChat, false); elem.style.left = ((window.innerWidth / 2) - 100) + "px"; elem.style.top = ((window.innerHeight / 2) - 50) + "px"; elem.style.display = 'block'; headerelem.addEventListener('touchmove', function(event) { var elem = document.getElementById("chatDiv"); var touch = event.targetTouches[0]; // Place element where the finger is elem.style.left = touch.pageX + 'px'; elem.style.top = touch.pageY + 'px'; event.preventDefault(); }, false); if (htmlViewer !== null) { htmlViewer.setRPFocus(false); } } chatText.focus(); } /** * * Function is used to close the Chat dialog */ function closeChatDialog() { var elem = document.getElementById("chatDiv"); elem.style.display = 'none'; var headerelem = document.getElementById("chatHeader"); headerelem.removeEventListener('dragstart', drag_startChat, false); document.body.removeEventListener('dragover', drag_overChat, false); document.body.removeEventListener('drop', dropChat, false); if (htmlViewer !== null) { htmlViewer.setRPFocus(true); } } /** * * Function is used to send Chat message */ function sendChatMsg() { var chatText = document.getElementById('txtChat'); var msg = chatText.value; if (msg !== null && msg.length > 0) { htmlViewer.sendRPChatMessage(msg); } chatText.value = ""; chatText.focus(); } /** * Function is used to build row for Chat dialog * @param {type} message * @param {type} bCurrentUser * */ function addChatHistory(message, bCurrentUser) { console.log('add Chat Row....'); // Get a reference to the table var tableRef = document.getElementById("messageTable"); var rowCount = tableRef.rows.length; // Insert a row in the table at row index 0 var newRow = tableRef.insertRow(rowCount); // Insert a cell in the row at index 0 var newCell1 = newRow.insertCell(0); if (bCurrentUser) { newCell1.className = "odd-row"; } else { newCell1.className = "even-row"; } newCell1.style.width = "100%"; newCell1.innerHTML = message; var elem = document.getElementById("chatDiv"); if (elem.style.display === 'block') { var dataDiv = document.getElementById("chatDataDiv"); dataDiv.scrollTop = dataDiv.scrollHeight; } } /** * Callback function to update chat message. * @param {type} userName * @param {type} sessionId * @param {type} message * @param {type} bCurrentUser */ function chatMessageCallback(userName, sessionId, message, bCurrentUser) { if(message !== null && message.length>0) { message=message.replace(/</g, "&lt"); message=message.replace(/>/g, "&gt"); } var str = "<b>" + userName + ":" + sessionId + "</b> " + message; var chatMsgData = localStorage.getItem("VIEWER_CHAT_DATA"); chatMsgData += "�" + str; localStorage.setItem("VIEWER_CHAT_DATA", chatMsgData); addChatHistory(str, bCurrentUser); openChatDialog(); } /** * * Function is used to show RPViewer in full screen mode. */ function showFullScreen() { var bSupport = htmlViewer.showRPFullScreen(); if (bSupport === false) { alert("Your browser doesn't support full screen mode."); } else { fullScreen = true; } } /** * * Function is used to apply selected color mode from the dropdown list for DVC platform. */ function applyColorMode() { var x = document.getElementById("cboColorMode"); var value_x = parseInt(x.value); if (htmlViewer.getPlatformID() === 4)//Pilot4 { if (value_x > 5) { htmlViewer.setRPVideoColorMode(value_x, true); } else { htmlViewer.setRPVideoColorMode(value_x, false); } } else { if (value_x > 6) { htmlViewer.setRPVideoColorMode(value_x, true); } else { htmlViewer.setRPVideoColorMode(value_x, false); } } } /** * * Function is used to apply selected color from the slider for DVC platform. */ function applyColorQuality() { var x = document.getElementById("vqVperf"); var index_x = parseInt(x.value); if (index_x < colorsMax) { var value_x = colorArgs[index_x]; if (value_x > 6) { htmlViewer.setRPVideoColorMode(value_x, true); } else { htmlViewer.setRPVideoColorMode(value_x, false); } } else { Logger.logDebug('*** Color index too high: ' + index_x); } } /** * Function is used to determine the index of the selected macro. It * then makes a call to callMacro passing the appropriate index value. * */ function applyMacro() { var x = document.getElementById("cboMacro"); var macroIndex = x.selectedIndex; //this is a numerical index (from 0) var macroName = null; var macroLanguage = RPViewer.RP_VKEYBOARD_LANGUAGE.ENGLISH_EN; switch (macroIndex) { case 0: //Ctrl+Alt+Del macroName = "Ctrl+Alt+Del"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_DELETE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 1: //Alt-Tab macroName = "Alt+Tab"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_TAB; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 2: //Alt-Esc macroName = "Alt+Esc"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ESCAPE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 3: //Ctrl-Esc macroName = "Ctrl+Esc"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ESCAPE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 4: //Alt-Space macroName = "Alt+Space"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_SPACE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 5: //Alt-Enter macroName = "Alt+Enter"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ENTER; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 6: //Alt-Hyphen macroName = "Alt+Hyphen"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_SEPARATOR; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 7: //Alt-F4 macroName = "Alt+F4"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_F4; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 8: //Prt Scr macroName = "Prt Scr"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PRINTSCREEN; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 9: //Alt + PrintScreen macroName = "Alt+PrintScreen"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PRINTSCREEN; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 10: //F1 macroName = "F1"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_F1; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 11: //Pause macroName = "Pause"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PAUSE; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 12: //Tab macroName = "Tab"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_TAB; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 13: //Ctrl+Enter macroName = "Ctrl+Enter"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_CONTROL_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ENTER; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 14: //SysRq macroName = "SysRq"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PRINTSCREEN; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; case 15: //Alt+SysRq macroName = "Alt+SysRq"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_PRINTSCREEN; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_ALT_LEFT; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_BREAK; break; case 16: //Windows Start macroName = "Windows Start"; macroName += "," + macroLanguage; macroName += "," + RPViewer.RP_KEY_NAMES.KEY_WINDOWS_START; macroName += "," + RPViewer.RP_MACRO_CONSTANT.KEY_MAKE_AND_BREAK; break; } htmlViewer.sendRPMacro(macroName); } /** * * Function is used to change mouse acceleration of RPViewer. */ function applyAcceleration() { var elem = document.getElementsByName("mouseAccer"); if (elem !== null) { var val = -1; for (var i = 0; i < elem.length; i++) { if (elem[i].checked) { val = elem[i].value; break; } } htmlViewer.setRPMouseAccelerationMode(val); } } /** * Function is used to report login status. * @param {type} loginStatus * */ function reportLoginStatus(loginStatus) { //report login exception status caught in notifications.js. Reported //here to allow customized handling. 0 <= loginStatus <= 15 console.log('loginStatus::' + loginStatus); var message = null; var loginResult = RPViewer.RP_LOGIN_RESULT; switch (loginStatus) { case loginResult.LOGIN_INVALID_USER: case loginResult.LOGIN_INVALID_PASSWORD: message = "Login failed.\n\nInvalid User name or Password."; //message = ResourceManager.ConnectionDialog_LoginFailed_Invalid; break; case loginResult.LOGIN_DENIED: message = "Login denied"; //message = ResourceManager.ConnectionDialog_AccessDenied; break; case loginResult.LOGIN_FULL: message = "Login failed\n\nThe max number of session has been exceeded."; //message = ResourceManager.ConnectionDialog_NoChannelsAvailable; break; case loginResult.LOGIN_NOSHARE: message = "Sharing request has been denied."; //message = ResourceManager.ConnectionDialog_SharingDenied; break; case loginResult.LOGIN_CERTIFICATE_NOT_VERIFIED: message = "Failed to connect viewer. Certificate may not be verified."; break; case loginResult.LOGIN_CERTIFICATE_TIMEDOUT: message = "The session has timed out waiting for verification of the certificate.\nAll the connections will be closed."; break; case loginResult.LOGIN_WEBSOCKET_EXCEPTION: message = "Failed to connect viewer due to Websocket exception."; break; default: message = "Login failed."; //message = ResourceManager.ConnectionDialog_LoginFailed; break; } if (message != null) { alert(message); } } /** * Function is used to report RPViewer terminate reason. * @param {type} messageNum * */ function reportTerminationReason(messageNum, isViewer) { //report termination status caught in notifications.js. Reported //here to allow customized handling. Logger.logDebug('Termination Reason::' + messageNum); var shutdownReason = RPViewer.RP_SHUTDOWN_REASON; var reason; switch (messageNum) { case shutdownReason.SHUTDOWN_ADMIN: reason = "Administrator Disconnect"; break; case shutdownReason.SHUTDOWN_TIMEOUT: reason = "Exceeded Idle Time Out"; break; case shutdownReason.SHUTDOWN_WEBSOCKET: reason = "the network connection has been dropped"; break; case shutdownReason.SHUTDOWN_REBOOT: reason = "Appliance Reboot"; break; case shutdownReason.SHUTDOWN_UPGRADE: reason = "Pending DSRIQ Upgrade"; break; case shutdownReason.SHUTDOWN_PREEMPT: reason = "Local User Channel Premption"; break; case shutdownReason.SHUTDOWN_UNSHARE: reason = "Last Active User Disconnection"; break; case shutdownReason.SHUTDOWN_EXLUSIVE: reason = "Primary User Getting into Exclusive Mode"; break; default: reason = "Unknown Problem"; break; } var message = "Client has been shut down as a result of "; if (! isViewer) message = "Virtual Media has terminated as a result of "; message += reason + "."; alert(message); } /** * Function is used to change color mode based on color mode recevied from RPViewer. * @param {type} dvcColorMode * @param {type} dvcColorDepth * */ function reportColorModeChange(dvcColorMode, dvcColorDepth) { if (htmlViewer.getPlatformID() === 4) { reportDVCBlockColorModeChange(dvcColorMode,dvcColorDepth); return; } console.log('dvcColorMode:' + dvcColorMode + ' dvcColorDepth:' + dvcColorDepth); //the following is highly dependent upon the presence & layout of the "cboColorMode" selector DOM object. //the following is highly dependent upon the presence & layout of the "vqVperf" slider DOM object. var x = document.getElementById("cboColorMode"); var y = document.getElementById("vqVperf"); var colorDepth = RPViewer.RP_COLOR_DEPTH; if (dvcColorMode) { //x index is within 4 to 10 //y array entries 0 - 3 are BW, 4 - 10 are color switch (dvcColorDepth) { case colorDepth.COLOR_7_BIT: if (x !== null) x.options[4].selected = true; if (y !== null) y.value = "4"; break; case colorDepth.COLOR_9_BIT: if (x !== null) x.options[5].selected = true; if (y !== null) y.value = "5"; break; case colorDepth.COLOR_12_BIT: if (x !== null) x.options[6].selected = true; if (y !== null) y.value = "6"; break; case colorDepth.COLOR_18_BIT: if (x !== null) x.options[8].selected = true; if (y !== null) y.value = "8"; break; case colorDepth.COLOR_21_BIT: if (x !== null) x.options[9].selected = true; if (y !== null) y.value = "9"; break; case colorDepth.COLOR_23_BIT: if (x !== null) x.options[10].selected = true; if (y !== null) y.value = "10"; break; case colorDepth.COLOR_15_BIT: default: if (x !== null) x.options[7].selected = true; if (y !== null) y.value = "7"; } } else { //x index is within 0 - 3 //y array entries 0 - 3 are BW, 4 - 10 are color switch (dvcColorDepth) { case colorDepth.GRAY_SCALE_16_SHADES: if (x !== null) x.options[0].selected = true; if (y !== null) y.value = "0"; break; case colorDepth.GRAY_SCALE_32_SHADES: if (x !== null) x.options[1].selected = true; if (y !== null) y.value = "1"; break; case colorDepth.GRAY_SCALE_64_SHADES: if (x !== null) x.options[2].selected = true; if (y !== null) y.value = "2"; break; case colorDepth.GRAY_SCALE_128_SHADES: default: if (x !== null) x.options[3].selected = true; if (y !== null) y.value = "3"; } } } /** * Function is used to change color mode based on color mode recevied from RPViewer. * @param {type} dvcColorMode * @param {type} dvcColorDepth * */ function reportDVCBlockColorModeChange(dvcColorMode, dvcColorDepth) { console.log('dvcColorMode:' + dvcColorMode + ' dvcColorDepth:' + dvcColorDepth); if (blockDVCColorMode === false) { blockDVCColorMode = true; //Remove var select = document.getElementById("cboColorMode"); select.options.length=0; //Add select.options[0]=new Option("Grayscale 6 bit", "1"); select.options[1]=new Option("Grayscale 9 bit", "2"); select.options[2]=new Option("Grayscale 12 bit", "3"); select.options[3]=new Option("Grayscale 15 bit", "4"); select.options[4]=new Option("Color 6 bit", "6"); select.options[5]=new Option("Color 9 bit", "9"); select.options[6]=new Option("Color 12 bit", "12"); select.options[7]=new Option("Color 15 bit", "15"); select.options[8]=new Option("Color 18 bit", "18"); select.options[9]=new Option("Color 21 bit", "21"); select.options[10]=new Option("Color 23 bit", "23"); } //the following is highly dependent upon the presence & layout of the "cboColorMode" selector DOM object. //the following is highly dependent upon the presence & layout of the "vqVperf" slider DOM object. var x = document.getElementById("cboColorMode"); var y = document.getElementById("vqVperf"); var colorDepth = RPViewer.RP_COLOR_DEPTH_BLOCK_DVC; if (dvcColorMode) { //x index is within 4 to 10 //y array entries 0 - 3 are BW, 4 - 10 are color switch (dvcColorDepth) { case colorDepth.COLOR_6_BIT: if (x !== null) x.options[4].selected = true; if (y !== null) y.value = "4"; break; case colorDepth.COLOR_9_BIT: if (x !== null) x.options[5].selected = true; if (y !== null) y.value = "5"; break; case colorDepth.COLOR_12_BIT: if (x !== null) x.options[6].selected = true; if (y !== null) y.value = "6"; break; case colorDepth.COLOR_18_BIT: if (x !== null) x.options[8].selected = true; if (y !== null) y.value = "8"; break; case colorDepth.COLOR_21_BIT: if (x !== null) x.options[9].selected = true; if (y !== null) y.value = "9"; break; case colorDepth.COLOR_23_BIT: if (x !== null) x.options[10].selected = true; if (y !== null) y.value = "10"; break; case colorDepth.COLOR_15_BIT: default: if (x !== null) x.options[7].selected = true; if (y !== null) y.value = "7"; } } else { //x index is within 0 - 3 //y array entries 0 - 3 are BW, 4 - 10 are color switch (dvcColorDepth) { case colorDepth.GRAY_SCALE_6_BIT: if (x !== null) x.options[0].selected = true; if (y !== null) y.value = "0"; break; case colorDepth.GRAY_SCALE_9_BIT: if (x !== null) x.options[1].selected = true; if (y !== null) y.value = "1"; break; case colorDepth.GRAY_SCALE_12_BIT: if (x !== null) x.options[2].selected = true; if (y !== null) y.value = "2"; break; case colorDepth.GRAY_SCALE_15_BIT: default: if (x !== null) x.options[3].selected = true; if (y !== null) y.value = "3"; } } } /** * Callback function is used to update mouse acceleration value. * @param {type} val * */ function mouseAccelerationCallback(val) { var elem = document.getElementsByName("mouseAccer"); if (elem !== null) { for (var i = 0; i < elem.length; i++) { if (elem[i].value == val) { elem[i].checked = true; break; } } } } /** * * Function is used to handle sharing action. */ function sharingAction() { var elem = document.getElementById("sharedDialog"); elem.style.display = 'none'; clearTimeout(sessionSharingTimeout); var actionVal; var radioElems = document.getElementsByName("rdoAction"); if (radioElems[0].checked) { actionVal = RPViewer.RP_SESSION_SHARING.SHARING_ACCEPT; } else if (radioElems[1].checked) { actionVal = RPViewer.RP_SESSION_SHARING.SHARING_REJECT; } else { actionVal = RPViewer.RP_SESSION_SHARING.SHARING_PASSIVE; } htmlViewer.sendRPSharingResponse(actionVal); } /** * Close the sharing request dialog and * send SHARING_TIMEOUT if user is not responded within 30 seconds. * */ function sendSharingTimeout() { document.getElementById("sharedDialog").style.display = 'none'; sessionSharingTimeout = null; htmlViewer.sendRPSharingResponse(RPViewer.RP_SESSION_SHARING.SHARING_TIMEOUT); } /** * Callback function to report sharing request. * @param {type} userName * */ function sharingRequestCallback(userName) { htmlViewer.exitRPFullScreen(); console.log('sharingRequestCallback...userName::' + userName); sessionSharingTimeout = setTimeout("sendSharingTimeout()", 30000); var elem = document.getElementById("sharedDialog"); var msgElem = document.getElementById("pHeader"); msgElem.innerHTML = "A connection request has been received from user '" + userName + "'."; elem.style.left = ((window.innerWidth / 2) - 100) + "px"; elem.style.top = ((window.innerHeight / 2) - 100) + "px"; elem.style.display = 'block'; } /** * * Callback function to report sharing cancel request. */ function sharingCancelRequestCallback() { console.log('sharingCancelRequestCallback.....'); if (sessionSharingTimeout !== null) { clearTimeout(sessionSharingTimeout); sessionSharingTimeout = null; } document.getElementById("sharedDialog").style.display = 'none'; } /** * * Function is used to request refresh RPViewer */ function sendRefresh() { htmlViewer.requestRPRefresh(); } /** * * Function is used to request capture RPViewer screen shot. */ function captureScreenShot() { htmlViewer.requestRPCaptureScreenShot(); } /** * * Function is used to show virtual keyboard */ function showKeyboard() { if (htmlViewer.isRPVirtualKeyboardPoppedUp()) { htmlViewer.closeRPVirtualKeyboard(); } else { console.log('Keybord size...'+htmlViewer.getRPVirtualKeyboardSize()); htmlViewer.showRPVirtualKeyboard(RPViewer.RP_VKEYBOARD_LANGUAGE.ENGLISH_EN); } } /* CHINESE_ZH Simplified Chinese language DANISH_DA Danish language DUTCH_NL Dutch language ENGLISH_EN English language FRENCH_FR French language GERMAN_DE German language ITALIAN_IT Italian language JAPANESE_JA Japanese language PORTUGUESE_PT Continental Portuguese language PORTUGUESE_PT_BR Brazilian Portuguese language SPANISH_ES_ES Continental Spanish language SPANISH_ES_LA Latin American Spanish language */ /** * * Function is used to change relative touch position option */ function changeMouse() { var elem = document.getElementsByName("touchOption"); if (elem !== null) { if (elem[1].checked) //relative { htmlViewer.setRPSupportRelativeTouchPosition(true); } else { htmlViewer.setRPSupportRelativeTouchPosition(false); //Direct } } } /** * * Function is used to change aspect ratio status */ function changeRatio() { var elem = document.getElementById("checkratio"); if (elem !== null) { if (elem.checked) { htmlViewer.setRPMaintainAspectRatio(true); } else { htmlViewer.setRPMaintainAspectRatio(false); } } fitToScreen(); } /** * * Function is used to open Setting dialog */ function openSettings() { var elem = document.getElementById("settingsDiv"); if (elem.style.display === "block") { closeSettings(); } else { if (isTouchOS() === false) { var parentDiv = document.getElementById("tabsList"); var touchTab = document.getElementById("tabHeader_2"); if (parentDiv.contains(touchTab)) { parentDiv.removeChild(touchTab); } } if (htmlViewer.getPlatformID() === 4)//Pilot4 { //Remove DVC color depth and add block-DVC color depth var perfTab = document.getElementById("tabHeader_5"); if (parentDiv.contains(perfTab)) { parentDiv.removeChild(perfTab); } if (blockDVCColorMode === false) { blockDVCColorMode = true; //Remove var select = document.getElementById("cboColorMode"); select.options.length=0; //Add select.options[0]=new Option("Grayscale 6 bit", "1"); select.options[1]=new Option("Grayscale 9 bit", "2"); select.options[2]=new Option("Grayscale 12 bit", "3"); select.options[3]=new Option("Grayscale 15 bit", "4"); select.options[4]=new Option("Color 6 bit", "6"); select.options[5]=new Option("Color 9 bit", "9"); select.options[6]=new Option("Color 12 bit", "12"); select.options[7]=new Option("Color 15 bit", "15"); select.options[8]=new Option("Color 18 bit", "18"); select.options[9]=new Option("Color 21 bit", "21"); select.options[10]=new Option("Color 23 bit", "23"); } } if (htmlViewer.getPlatformID() === 3 || bSessionReadonly)//Pilot3 { var parentDiv = document.getElementById("tabsList"); if (bSessionReadonly) { var touchTab = document.getElementById("tabHeader_2"); if (parentDiv.contains(touchTab)) { parentDiv.removeChild(touchTab); } var mouseTab = document.getElementById("tabHeader_3"); if (parentDiv.contains(mouseTab)) { parentDiv.removeChild(mouseTab); } } var colorTab = document.getElementById("tabHeader_4"); if (parentDiv.contains(colorTab)) { parentDiv.removeChild(colorTab); } var perfTab = document.getElementById("tabHeader_5"); if (parentDiv.contains(perfTab)) { parentDiv.removeChild(perfTab); } } var headerelem = document.getElementById("settingsHeader"); headerelem.addEventListener('dragstart', drag_startSettings, false); document.body.addEventListener('dragover', drag_overSettings, false); document.body.addEventListener('drop', dropSettings, false); elem.style.left = ((window.innerWidth / 2) - 100) + "px"; elem.style.top = ((window.innerHeight / 2) - 100) + "px"; elem.style.display = 'block'; headerelem.addEventListener('touchmove', function(event) { var elem = document.getElementById("settingsDiv"); var touch = event.targetTouches[0]; // Place element where the finger is elem.style.left = touch.pageX + 'px'; elem.style.top = touch.pageY + 'px'; event.preventDefault(); }, false); } } /** * * Function is used to close the Settings dialog. */ function closeSettings() { var elem = document.getElementById("settingsDiv"); elem.style.display = 'none'; var headerelem = document.getElementById("settingsHeader"); headerelem.removeEventListener('dragstart', drag_startSettings, false); document.body.removeEventListener('dragover', drag_overSettings, false); document.body.removeEventListener('drop', dropSettings, false); } /** * Function is used to support Settings dialog dragging. * @param {type} event * */ function drag_startSettings(event) { bDragSettingDialog = true; var style = window.getComputedStyle(event.target, null); event.dataTransfer.setData("text/plain", (parseInt(style.getPropertyValue("left"), 10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - event.clientY)); ptDragingDialogX = event.clientX; ptDragingDialogY = event.clientY; } /** * Function is used to support Settings dialog dragging. * @param {type} event * @returns {Boolean} */ function drag_overSettings(event) { event.preventDefault(); return false; } /** * Function is used to support Settings dialog dragging. * @param {type} event * @returns {Boolean} */ function dropSettings(event) { if (bDragSettingDialog) { bDragSettingDialog = false; var elem = document.getElementById("settingsDiv"); var leftStr = elem.style.left; leftStr.trim(); if ((leftStr == null) || (leftStr == "")) leftStr = "-250"; // default for modal dialog else leftStr = leftStr.substring(0, leftStr.length - 2); var topStr = elem.style.top; topStr.trim(); topStr = topStr.substring(0, topStr.length - 2); elem.style.left = parseInt(leftStr) + (event.clientX - ptDragingDialogX) + "px"; elem.style.top = parseInt(topStr) + (event.clientY - ptDragingDialogY) + "px"; event.preventDefault(); return false; } } /** * Function is used to support Chat dialog dragging. * @param {type} event * */ function drag_startChat(event) { bDragChatDialog = true; var style = window.getComputedStyle(event.target, null); event.dataTransfer.setData("text/plain", (parseInt(style.getPropertyValue("left"), 10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"), 10) - event.clientY)); ptDragingDialogX = event.clientX; ptDragingDialogY = event.clientY; } /** * Function is used to support Chat dialog dragging. * @param {type} event * @returns {Boolean} */ function drag_overChat(event) { event.preventDefault(); return false; } /** * Function is used to support Chat dialog dragging. * @param {type} event * @returns {Boolean} */ function dropChat(event) { if (bDragChatDialog) { bDragChatDialog = false; var elem = document.getElementById("chatDiv"); var leftStr = elem.style.left; leftStr.trim(); if ((leftStr == null) || (leftStr == "")) leftStr = "-250"; // default for modal dialog else leftStr = leftStr.substring(0, leftStr.length - 2); var topStr = elem.style.top; topStr.trim(); topStr = topStr.substring(0, topStr.length - 2); elem.style.left = parseInt(leftStr) + (event.clientX - ptDragingDialogX) + "px"; elem.style.top = parseInt(topStr) + (event.clientY - ptDragingDialogY) + "px"; event.preventDefault(); return false; } } /** * * Function is used to load the Settings dialog. */ function loadSettingsTab() { // get tab container var container = document.getElementById("settingsDiv"); var tabcon = document.getElementById("contentDiv"); // set current tab var navitem = document.getElementById("tabHeader_1"); //store which tab we are on var ident = navitem.id.split("_")[1]; //alert(ident); navitem.parentNode.setAttribute("data-current", ident); //set current tab with class of activetabheader navitem.setAttribute("class", "tabActiveHeader"); //hide two tab contents we don't need var pages = tabcon.getElementsByTagName("div"); for (var i = 1; i < pages.length; i++) { pages.item(i).style.display = "none"; } //this adds click event to tabs var tabs = container.getElementsByTagName("li"); for (var i = 0; i < tabs.length; i++) { tabs[i].onclick = displaySettingsTab; } } /** * * Function is used to build the Settings dialog Tabs. */ function displaySettingsTab() { var current = this.parentNode.getAttribute("data-current"); //remove class of activetabheader and hide old contents document.getElementById("tabHeader_" + current).removeAttribute("class"); document.getElementById("tabpage_" + current).style.display = "none"; var ident = this.id.split("_")[1]; //add class of activetabheader to new active tab and show contents this.setAttribute("class", "tabActiveHeader"); document.getElementById("tabpage_" + ident).style.display = "block"; this.parentNode.setAttribute("data-current", ident); } /** * Function is used to check HTML5 local storage support * @returns {Boolean} */ function isSupportHTML5Storage() { try { window.localStorage.setItem('checkLocalStorage', true); window.localStorage.removeItem('checkLocalStorage'); return true; } catch (error) { return false; } } /** * Function is used to test whether the OS is Touch supported or not. * @returns {Boolean} */ function isTouchOS() { var touchOS = false; if ('ontouchstart' in window) { touchOS = true; } else if ("PointerEvent" in window && navigator.maxTouchPoints > 0) { touchOS = true; } return touchOS; } /** * Function is used to test whether the browser is Mobile browser or not. * @returns {Boolean} */ function isMobileBrowser() { if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ) { return true; } else { return false; } } //// BEGIN Virtual Media Dialog Functions /** * * Function is used to open media dialog */ function openMediaDriveDialog() { // disable the combo and manage button. document.getElementById("driveListCombo").disabled=true; document.getElementById("btnManage").disabled=true; var elem = document.getElementById("VirtualMediaDriveDiv"); if (elem.style.display !== 'block') { var headerelem = document.getElementById("VirtualMediaDriveHeader"); elem.style.left = ((window.innerWidth / 2) - 100) + "px"; elem.style.top = ((window.innerHeight / 2) - 50) + "px"; elem.style.display = 'block'; /*headerelem.addEventListener('touchmove', function(event) { var elem = document.getElementById("VirtualMediaDriveDiv"); var touch = event.targetTouches[0]; // Place element where the finger is elem.style.left = touch.pageX + 'px'; elem.style.top = touch.pageY + 'px'; event.preventDefault(); }, false); if (htmlViewer !== null) { htmlViewer.setRPFocus(false); }*/ resetDriveDialog(); } } /** * * Function is used to close the media dialog */ function closeMediaDriveDialog() { document.getElementById("driveListCombo").disabled=false; document.getElementById("btnManage").disabled=false; var elem = document.getElementById("VirtualMediaDriveDiv"); elem.style.display = 'none'; var headerelem = document.getElementById("VirtualMediaDriveHeader"); if (htmlViewer !== null) { htmlViewer.setRPFocus(true); } } //// END Virtual Media Dialog Functions /**** Virtual Media - end*****/ function cleanup(bVMedia) { var exitWarn; var mapCount = 0; for (var i=0; i<fileMapStateArray.length; i++) { if (fileMapStateArray[i]) mapCount++; } if (mapCount > 0) { if (bVMedia) exitWarn = "There are drives currently mapped in Virtual Media. Deactivating Virtual Media will unmap those drives. Do you wish to continue?"; else exitWarn = "There are drives currently mapped in Virtual Media. Closing the Viewer will unmap those drives. Do you wish to continue?"; } return exitWarn; } function DisconnectViewer() { var alertText = cleanup(false); if ( alertText ) { if (confirm(alertText)) exitViewer(); } else exitViewer(); }
39ea1c467f05197099fdb467a7a1d03aab7784f9
[ "JavaScript", "HTML" ]
33
JavaScript
biubiubiu865/biubiubiu865.github.io
a756aac2a898ba6dcc114450db14e2fe15efd87b
5b600f77339d63ba3169fe9a1262a666e8e174f5
refs/heads/main
<repo_name>webshunter/kasirtoko<file_sep>/database/migrations/2019_11_24_091841_create_accounting_akun_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAccountingAkunTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('AccountingAkun', function (Blueprint $table) { $table->bigIncrements('id'); $table->char('id_akun', 255); $table->char('nama_akun', 255); $table->char('golongan_akun', 255); $table->char('posisi_akun', 255); $table->char('keterangan_akun', 255); $table->char('perusahaan', 255); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('AccountingAkun'); } } <file_sep>/app/Http/Controllers/gugusController.php <?php namespace App\Http\Controllers; // panggil model use App\datatable; use App\createDatatable; use PDF; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; class gugusController extends Controller { private $table1 = 'data'; public function show() { // table create $datatabel = new createDatatable; $datatabel->location('halo'); $datatabel->table_name('tableku'); $datatabel->create_row(['no', 'nama depan', 'nama belakang', '#']); $show = $datatabel->create(); return view('index', ['datatable'=> $show]); } public function halo($action = 'show', $keyword = '') { // default order for get order from datatable if (isset($_POST['order'])): $setorder = $_POST['order']; else: $setorder = ''; endif; $data = new datatable; $data->action($action); $data->set_table($this->table1); if($action == 'show'){ $data->set_draw($_POST['draw']); $data->set_search($_POST['search']['value'], ['data1', 'data2']); $data->set_order_data(['id', 'data1', 'data2'], $setorder); $data->set_limit($_POST['start'], $_POST['length']); $data->set_table_show('id', ['data1', 'data2']); }elseif($action == 'delete'){ $query_del = $data->set_delete_query()->where('id', '=', $_POST['id']); $data->delete_data($query_del); }elseif($action == 'update'){ $data->get_key_update('id' ,$keyword); return view('update', ['data'=> $data->get_data_update()]); } $data->release(); } public function simpan(){ DB::table($this->table1)->insert([ ['data1' => $_POST['data1'], 'data2' => $_POST['data2']] ]); return redirect('pengeluaran'); } public function update() { DB::table($this->table1) ->where('id', '=', $_POST['id']) ->update( [ 'data1' => $_POST['data1'], 'data2' => $_POST['data2'] ] ); return redirect('pengeluaran'); } public function testPdf(){ $pdf = PDF::loadview('pdf.pegawai_pdf',['pegawai'=>"kosong"])->setPaper('a4', 'landscape'); return $pdf->download('laporan-pegawai.pdf'); } } <file_sep>/app/Http/Controllers/pesanan.php <?php namespace App\Http\Controllers; use App\gugusDatatable; use App\createDatatable; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class pesanan extends Controller { private $table1 = 'pesanan'; public function show() { // table create $datatabel = new createDatatable; $datatabel->location('toko/pesanan/data'); $datatabel->table_name('tableku'); $datatabel->create_row([ 'no','id pesanan', 'nama pemesan', 'alamat', 'tanggal diambil','action']); $datatabel->order_set('0,3,4,5'); $show = $datatabel->create(); return view('toko.pesanan.index', ['datatable'=> $show]); } public function pesanan($action = 'show', $keyword = '') { if ($action == "show") { if (isset($_POST['order'])): $setorder = $_POST['order']; else: $setorder = ''; endif; $datatable = new gugusDatatable; $datatable->datatable( [ "table" => $this->table1, "select" => [ "*" ], 'where' => [ ['perusahaan', '=', Session::get("toko-user")['nama_perusahaan']], ], 'limit' => [ 'start' => gugusDatatable::post('start'), 'end' => gugusDatatable::post('length') ], 'search' => [ 'value' => gugusDatatable::search(), 'row' => [ 'id_pesanan' ,'nama_pemesan' ,'tanggal_diambil' ] ], 'table-draw' => gugusDatatable::post('draw'), 'table-show' => [ 'key' => 'id', 'data' => [ 'id_pesanan' ,'nama_pemesan' ,'alamat_pemesan' ,'tanggal_diambil' ] ], "action" => "standart", 'order' => [ 'order-default' => ['tanggal_diambil', 'DESC'], 'order-data' => $setorder, 'order-option' => [ "1" => "id_pesanan", "2" => "nama_pemesan", ], ], ] ); $datatable->table_show(); }elseif ($action == "update") { $dataedit = DB::table($this->table1)->where('id', '=', $keyword)->get()[0]; return view("toko.pesanan.update", ['data'=> $dataedit]); }elseif ($action == "delete") { $dataedit = DB::table($this->table1)->where('id', '=', $_POST['id'])->delete(); } } public function simpan(){ DB::table($this->table1)->insert([ 'id_pesanan' => $_POST['id_pesanan'] ,'nama_pemesan' => $_POST['nama_pemesan'] ,'alamat_pemesan' => $_POST['alamat_pemesan'] ,'tanggal_diambil' => $_POST['tanggal_diambil'] ,'perusahaan' => Session::get("toko-user")['nama_perusahaan'] ,'created_at' => date("Y-m-d H:i:s") ]); return redirect('toko/pesanan/tambah_data/'.$_POST['id_pesanan']); } public function update() { DB::table($this->table1) ->where('id', '=', $_POST['id']) ->update( [ 'id_pesanan' => $_POST['id_pesanan'] ,'nama_pemesan' => $_POST['nama_pemesan'] ,'alamat_pemesan' => $_POST['alamat_pemesan'] ,'tanggal_diambil' => $_POST['tanggal_diambil'] , 'perusahaan' => Session::get("toko-user")['nama_perusahaan'] , 'updated_at' => date("Y-m-d H:i:s") ] ); return redirect('toko/pesanan/tambah_data/'.$_POST['id_pesanan']); } private $table2 = "data_pesanan"; public function tambah_data($id_pesanan){ Session::put("id-pesanan", $id_pesanan); $datatabel = new createDatatable; $datatabel->location('toko/pesanan/tambah_data/show_data'); $datatabel->table_name('tableku'); $datatabel->create_row([ 'no','nama barang', 'harga barang', 'tottal barang', 'harga total','action']); $datatabel->order_set('0,3,4,5'); $show = $datatabel->create(); return view('toko.pesanan.tambah_pesanan', ['datatable'=> $show, 'id_pesanan' => $id_pesanan]); } public function show_data($action = 'show', $keyword = ''){ if ($action == "show") { if (isset($_POST['order'])): $setorder = $_POST['order']; else: $setorder = ''; endif; $datatable = new gugusDatatable; $datatable->datatable( [ "table" => $this->table2, "select" => [ $this->table2 => ['id','id_pesanan', 'banyak_barang'] ,'stock_barang' => ['nama_barang'] , "harga_jual" => ['harga_per_satuan as harga'] ], 'where' => [ [$this->table2.'.perusahaan', '=', Session::get("toko-user")['nama_perusahaan']], [$this->table2.'.id_pesanan', '=', Session::get("id-pesanan")], ] ,'leftJoin' => [ "stock_barang" => [$this->table2.'.id_barang', '=', 'stock_barang.id'], "harga_jual" => [$this->table2.'.id_barang', '=', 'harga_jual.id_barang'], ] ,'limit' => [ 'start' => gugusDatatable::post('start'), 'end' => gugusDatatable::post('length') ], 'search' => [ 'value' => gugusDatatable::search(), 'row' => [ 'id_pesanan' ] ], 'table-draw' => gugusDatatable::post('draw'), 'table-show' => [ 'key' => 'id', 'data' => [ 'nama_barang' ,'harga' ,'banyak_barang' ,'harga * banyak_barang' ] ], "action" => "delete-only", 'order' => [ 'order-default' => [$this->table2.'.id', 'DESC'], 'order-data' => $setorder, 'order-option' => [ "1" => "id_pesanan", ], ], ] ); $datatable->table_show(); }elseif ($action == "delete") { $dataedit = DB::table($this->table2)->where('id', '=', $_POST['id'])->delete(); } } public function simpan_data(){ $simpan = DB::table($this->table2)->insert([ 'id_pesanan' => $_POST['id_pesanan'] ,'id_barang' => $_POST['id_barang'] ,'banyak_barang' => $_POST['banyak_barang'] ,'perusahaan' => Session::get("toko-user")['nama_perusahaan'] ,'created_at' => date("Y-m-d H:i:s") ]); } } <file_sep>/app/Http/Controllers/toko.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; class toko extends Controller { private $mydb = "usertoko"; public function dashboard() { return view('toko.dashboard.index'); } public function loginmenu() { return view('toko.login'); } public function login() { $cek = DB::table($this->mydb)->where('username', '=', $_POST['username'])->get(); $getdata = $cek[0]; if(Hash::check($_POST['password'], $getdata->password)){ Session::put("toko-user", [$getdata->username, "nama_perusahaan" => $getdata->nama_perusahaan]); } return redirect('toko'); } public function logout() { Session::forget('toko-user'); return redirect('toko'); } public function pendaftaranSimpan() { DB::table($this->mydb)->insert([ 'username' => $_POST['user'] , 'password' => <PASSWORD>($_POST['<PASSWORD>']) , 'nama_perusahaan' => $_POST['nama_usaha'] , 'created_at' => date('Y-m-d H:i:s') ]); Session::put("toko-user", ["username" => $_POST['user'], "nama_perusahaan" => $_POST['nama_usaha']]); return redirect('toko'); } } <file_sep>/app/gugusDatatable.php <?php namespace App; use Illuminate\Support\Facades\DB; use Illuminate\Database\Eloquent\Model; class gugusDatatable extends Model { private $query; private $limit; private $key; private $table_row; private $table_draw; private $table_id_edit; private $table_name; private $button_view; private $action; public function datatable($data = "") { $query = "SELECT "; if(isset($data['select'])){ if (!isset($data['leftJoin'])) { foreach ($data['select'] as $key => $value) { if ($key == 0) { $query .= $value; }else{ $query .= ','.$value; } } }else{ $number = 0; foreach ($data['select'] as $key => $value) { if ($number == 0) { foreach ($value as $num => $nilai) { if ($num == 0) { $query .= $key.'.'.$nilai; }else{ $query .= ','.$key.'.'.$nilai; } } }else{ foreach ($value as $num => $nilai) { $query .= ','.$key.'.'.$nilai; } } $number++; } } }else{ $query .= " * "; } $query .= " FROM "; $query .= " ".$data['table']." "; $this->table_name = $data['table']; if (isset($data['leftJoin'])) { foreach ($data['leftJoin'] as $key => $value) { $query .= " LEFT JOIN ".$key." ON ".$value[0]." ".$value[1]." ".$value[2].""; } } if ($data['where']) { $query .= " WHERE "; foreach ($data['where'] as $keys => $value) { if ($keys == 0) { $query .= $value[0].' '.$value[1].' "'.$value[2].'"'; }else{ $query .= ' AND '.$value[0].' '.$value[1].' "'.$value[2].'"'; } } } if (isset($data['search'])) { $nilai_pencarian = $data['search']['value']; $query .= "AND ("; foreach ($data['search']['row'] as $keys => $value) { if ($keys == 0) { $query .= $value.' LIKE "%'.$nilai_pencarian.'%"'; }else{ $query .= " OR ".$value.' LIKE "%'.$nilai_pencarian.'%"'; } } $query .= ") "; } if (isset($data['order'])) { if ($data['order']['order-data'] != "") { $order_condition = $data["order"]['order-data'][0]["dir"]; $order_column = $data['order']['order-data'][0]['column']; $order_by = ""; foreach ($data['order']['order-option'] as $keys => $value) { if ($keys == $order_column) { $order_by = $value; } } $query .= " ORDER BY ".$order_by." ".$order_condition." "; }else{ $query .= " ORDER BY ".$data['order']['order-default'][0]." ".$data['order']['order-default'][1]." "; } } if (isset($data['table-show'])) { $this->key = $data['table-show']['key']; $this->table_row = $data['table-show']['data']; } if (isset($data['table-draw'])) { $this->table_draw = $data['table-draw']; } if (isset($data['limit'])) { $this->limit = "LIMIT ".$data['limit']['start'].",".$data['limit']['end']; } if (isset($data['action'])) { $this->action = $data['action']; } $this->query = $query; } private function query_data() { return DB::select($this->query); } private function query_limit(){ return DB::select($this->query.$this->limit); } private function query_count(){ return count($this->query_data()); } private function buat_table(){ $arr = []; $theTable = $this->query_limit(); $show_table = $this->table_row; $key_id = $this->key; foreach($theTable as $key => $value){ $child = []; $child[] = $key + 1; foreach($show_table as $evelop => $variable){ $perkalian = " * "; if (preg_match("/{$perkalian}/i", $variable)) { $kali_data = explode($perkalian, $variable); $data1 = $kali_data[0]; $data1 = str_replace("Rp ", "", $value->$data1); $data1 = str_replace(".", "", $data1); $data2 = $kali_data[1]; $data2 = str_replace("Rp ", "", $value->$data2); $data2 = str_replace(".", "", $data2); $child[] = 'Rp '.number_format(($data1*$data2),2,',','.'); }else { $child[] = $value->$variable; } } if ($this->action == "standart") { $child[] = " <center> <button data-id='".$value->$key_id."' class='btn btn-success edit'>edit</button> <button data-id='".$value->$key_id."' class='btn btn-danger delete'>hapus</button> </center> "; }elseif ($this->action == "delete-only") { $child[] = " <center> <button data-id='".$value->$key_id."' class='btn btn-danger delete'>hapus</button> </center> "; } array_push($arr, $child); } return $arr; } public function query_dump(){ dump($this->query_limit()); echo($this->query_count()); } public function table_show(){ $r = array( "draw" => $this->table_draw, "recordsTotal" => intval( $this->query_count() ), "recordsFiltered" => intval( $this->query_count() ), "data" => $this->buat_table(), ); echo json_encode($r); } public static function post($data){ $nilai = ""; if (isset($_POST[$data])) { $nilai = $_POST[$data]; } return $nilai; } public static function search(){ $pencarian = ""; if (isset($_POST['search']['value'])) { $pencarian = $_POST['search']['value']; } return $pencarian; } } <file_sep>/app/gugus/make/controller.php <?php echo "ok bro";<file_sep>/README.md # kasirtoko aplikasi kasir toko online multi user, setiap orang dapat membuat tokonya sendiri, dibangun menggunakan laravel <file_sep>/app/Helpers/User.php <?php namespace App\Helpers; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Session; class User { private static $barCHartId; private static $BarLabels; private static $BarColor; private static $BarValue; public static function setBarChart($aa){ self::$barCHartId = $aa; } public static function BarLabels($ar){ $str = ""; foreach ($ar as $key => $value) { if ($key == 0) { $str .= '"'.$value.'"'; }else{ $str .= ', "'.$value.'"'; } } self::$BarLabels = $str; } public static function BarColor($condition, $data){ if ($condition == "all") { $color = ""; $bar = self::$BarLabels; $explodebar = explode(",", $bar); for ($i=0; $i < count($explodebar) ; $i++) { if ($i == 0) { $color .= '"'.$data.'"'; }else{ $color .= ',"'.$data.'"'; } } self::$BarColor = $color; }else{ $color = ""; foreach ($variable as $key => $value) { if ($key == 0) { $color = '"'.$value.'"'; }else{ $color .= ',"'.$value.'"'; } } self::$BarColor = $color; } } public static function BarValue($value){ $nilai = ""; foreach ($value as $key => $n) { if ($key == 0) { $nilai .= '"'.$n.'"'; }else{ $nilai .= ',"'.$n.'"'; } } self::$BarValue = $nilai; } private static function BarScript(){ return " <script> var BARCHARTHOME = $('#".self::$barCHartId."'); var barChartHome = new Chart(BARCHARTHOME, { type: 'bar', options: { scales: { xAxes: [{ display: false }], yAxes: [{ display: false }], }, legend: { display: false } }, data: { labels: [".self::$BarLabels."], datasets: [ { label: 'Data Set 1', backgroundColor: [".self::$BarColor."], borderColor: [".self::$BarColor."], borderWidth: 1, data: [".self::$BarValue."] } ] } }); </script> "; } private static function CreateCanvasBar() { return "<canvas id=".self::$barCHartId."></canvas>"; } public static function CreateBar(){ $aa = self::CreateCanvasBar(); $bb = self::BarScript(); return $aa.$bb; } public static function sum($arr){ return array_sum($arr); } public static function average($arr){ $sum = array_sum($arr); $average = $sum / count($arr); return $average; } private static $form_set_style; public static function formStyle($aa = "") { self::$form_set_style = $aa; } public static function formStart() { return ' <input type="hidden" name="_token" value="'.csrf_token().'" /> '; } public static function formInputText($name ,$nameClass, $placeholder="", $value=""){ return ' <div class="form-group"> <label for="'.$nameClass.'" class="form-control-label">'.$name.'</label> <input type="text" name="'.$nameClass.'" id="'.$nameClass.'" required placeholder="'.$placeholder.'" class="'.self::$form_set_style.'" value="'.$value.'"/> </div> '; } public static function formInputNumber($name ,$nameClass, $placeholder="", $value=""){ return ' <div class="form-group"> <label id="'.$nameClass.'" class="form-control-label">'.$name.'</label> <input type="number" name="'.$nameClass.'" id="'.$nameClass.'" required placeholder="'.$placeholder.'" class="'.self::$form_set_style.'" value="'.$value.'"/> </div> '; } public static function formInputCurrency($currency ,$name, $nameClass, $placeholder="", $value=""){ return ' <div class="form-group"> <label for="'.$nameClass.'" class="form-control-label">'.$name.'</label> <input type="text" name="'.$nameClass.'" id="'.$nameClass.'" required placeholder="'.$placeholder.'" class="'.self::$form_set_style.'" value="'.$value.'"/> </div> <script> $("#'.$nameClass.'").keyup(function(event) { // skip for arrow keys if (event.which >= 37 && event.which <= 40)return; // format rupiah $(this).val(function(index, value){ return "'.$currency.'"+value .replace(/\D/g,"") .replace(/\B(?=(\d{3})+(?!\d))/g,"."); }) }); </script> '; } public static function formInputHidden($nameClass, $value = '') { return ' <input type="hidden" name="'.$nameClass.'" id="'.$nameClass.'" value="'.$value.'"/> '; } public static function formInputDate($name, $nameClass, $placeholder="", $value=""){ return ' <div class="form-group"> <label for="'.$nameClass.'" class="form-control-label">'.$name.'</label> <input type="text" name="'.$nameClass.'" id="'.$nameClass.'" required placeholder="'.$placeholder.'" class="'. self::$form_set_style.'" value="'.$value.'"/> </div> <script> $("#'.$nameClass.'").datepicker({ uiLibrary: "bootstrap4" }); </script> '; } public static function backDate($aa) { $date = explode("-", $aa); $date = $date[1].'/'.$date[2].'/'.$date[0]; return $date; } // hellper khusus di teplate ini public static function SelectOptionFromDB($table, $value, $show, $golongan, $selected = "") { $table = DB::table($table) ->where('perusahaan', '=', Session::get('accounting-user')['nama_perusahaan']) ->where('golongan_akun', '=', $golongan) ->get(); $option = ""; foreach($table as $key => $nilai){ if($selected != "" && $nilai->$value == $selected){ $option .= "<option selected value='".$nilai->$value."'>".$nilai->$show."</option>"; }else{ $option .= "<option value='".$nilai->$value."'>".$nilai->$show."</option>"; } } return $option; } }<file_sep>/app/datatable.php <?php namespace App; use Illuminate\Support\Facades\DB; use Illuminate\Database\Eloquent\Model; class datatable extends Model { private $nama_table; private $limit_start; private $limit_end; private $table_search; private $table_search_config; private $table_draw; private $table_set_show; private $set_data_order; private $set_config_order; private $table_action; private $keyword_update; private $location_update; private $keys; private $table_set_show_key; public function set_table($aa){ $this->nama_table = $aa; } public function action($aa){ $this->table_action = $aa; } public function set_limit($start, $end){ $this->limit_start = $start; $this->limit_end = $end; } public function set_search($search, $data){ $this->table_search = $search; $this->table_search_config = $data; } public function set_table_show($key ,$value) { $this->table_set_show_key = $key; $this->table_set_show = $value; } public function set_draw($draw) { $this->table_draw = $draw; } public function location_update($aa) { $this->location_update = $aa; } private function search_configurasi(){ $parameter_search = $this->table_search; $getConfig = $this->table_search_config; $var = " WHERE ("; foreach($getConfig as $key => $value){ if($key == 0){ $var .= $value.' like "%'.$parameter_search.'%" '; }else{ $var .= ' OR '.$value.' like "%'.$parameter_search.'%" '; } } $var .= ')'; return $var; } public function set_order_data($data, $order) { $this->set_data_order = $data; $this->set_config_order = $order; } private $order_default = ""; public function order_default($by, $order) { $this->order_default = " ORDER BY ".$by." ".$order; } private function set_order(){ $arr = $this->set_data_order; $order = $this->set_config_order; if ($order != "") { $columnName = ""; foreach ($arr as $key => $nilaicolumn) { if ($key == $order[0]["column"]) { $columnName = $nilaicolumn; } } $columnOrder = $_POST["order"][0]["dir"]; $order = 'ORDER BY '.$columnName.' '.$columnOrder.' '; }else{ if($this->order_default == ""){ $order = ' ORDER BY id DESC '; }else{ $order = $this->order_default; } } return $order; } private function panggil_tabel(){ return DB::table($this->nama_table); } public function set_delete_query() { return $this->panggil_tabel(); } public function delete_data($aa) { return $aa->delete(); } private $table_condition; public function table_condition($kondisi = "", $action = "" ,$nilai = "") { if($kondisi == "" || $action == "" || $nilai == ""){ $this->table_condition = ""; }else{ $this->table_condition = " AND $kondisi $action '$nilai' "; } } public function get_key_update($oo ,$aa){ $this->keys = $oo; $this->keyword_update = $aa; } private function dapatkan_data_table(){ return DB::select('SELECT * FROM '.$this->nama_table.' '.$this->search_configurasi().$this->table_condition.' '.$this->set_order().' LIMIT '.$this->limit_start.','.$this->limit_end); } private function data_table_base() { return DB::select('SELECT * FROM '.$this->nama_table.' '.$this->search_configurasi().$this->table_condition.' '.$this->set_order()); } private function jumlah_tabel() { $data = $this->data_table_base(); return count($data); } private function buat_table(){ $arr = []; $theTable = $this->dapatkan_data_table(); $show_table = $this->table_set_show; $key_id = $this->table_set_show_key; foreach($theTable as $key => $value){ $child = []; $child[] = $key + 1; foreach($show_table as $evelop => $variable){ $child[] = $value->$variable; } $child[] = " <center> <button data-id='".$value->$key_id."' class='btn btn-success edit'>edit</button> <button data-id='".$value->$key_id."' class='btn btn-danger delete'>hapus</button> </center> "; array_push($arr, $child); } return $arr; } public function get_data_update() { $datarealaeseupdate = DB::select("SELECT * FROM ".$this->nama_table." WHERE ".$this->keys." = '".$this->keyword_update."'"); return $getdata = $datarealaeseupdate[0]; } public function release() { if($this->table_action == "show"){ if($this->jumlah_tabel() == 0){ $data = array(); }else{ $data = $this->buat_table(); } $r = array( "draw" => $this->table_draw, "recordsTotal" => intval( $this->jumlah_tabel() ), "recordsFiltered" => intval( $this->jumlah_tabel() ), "data" => $data ); echo json_encode($r); } } } <file_sep>/app/Http/Controllers/akun.php <?php namespace App\Http\Controllers; use App\gugusDatatable; use App\createDatatable; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class akun extends Controller { private $table1 = 'akun'; public function show() { // table create $datatabel = new createDatatable; $datatabel->location('toko/akun/data'); $datatabel->table_name('tableku'); $datatabel->create_row([ 'no', 'id akun', 'nama akun', 'created at','action']); $datatabel->order_set('0,3,4'); $show = $datatabel->create(); return view('toko.akun.index', ['datatable'=> $show]); } public function akun($action = 'show', $keyword = '') { if ($action == "show") { if (isset($_POST['order'])): $setorder = $_POST['order']; else: $setorder = ''; endif; $datatable = new gugusDatatable; $datatable->datatable( [ "table" => $this->table1, "select" => [ "*" ], 'where' => [ ['perusahaan', '=', Session::get("toko-user")['nama_perusahaan']], ], 'limit' => [ 'start' => gugusDatatable::post('start'), 'end' => gugusDatatable::post('length') ], 'search' => [ 'value' => gugusDatatable::search(), 'row' => [ 'id_akun' ,'nama_akun' ] ], 'table-draw' => gugusDatatable::post('draw'), 'table-show' => [ 'key' => 'id', 'data' => [ 'id_akun' ,'nama_akun' ,'created_at' ] ], "action" => "standart", 'order' => [ 'order-default' => ['id', 'DESC'], 'order-data' => $setorder, 'order-option' => [ "1" => "id_akun", "2" => "nama_akun", ], ], ] ); $datatable->table_show(); }elseif ($action == "update") { $dataedit = DB::table($this->table1)->where('id', '=', $keyword)->get()[0]; return view("toko.pesanan.update", ['data'=> $dataedit]); }elseif ($action == "delete") { $dataedit = DB::table($this->table1)->where('id', '=', $_POST['id'])->delete(); } } public function simpan(){ DB::table($this->table1)->insert([ 'id_akun' => $_POST['id_akun'] ,'nama_akun' => $_POST['nama_akun'] ,'perusahaan' => Session::get("toko-user")['nama_perusahaan'] ,'created_at' => date("Y-m-d H:i:s") ]); } } <file_sep>/database/migrations/2019_11_24_030013_create_user_accounting_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUserAccountingTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('userAccounting', function (Blueprint $table) { $table->bigIncrements('id'); $table->char('username', 255); $table->mediumtext('password'); $table->char('nama_perusahaan',255); $table->char('jenis_usaha',255); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('userAccounting'); } } <file_sep>/app/gugus/main.php <?php class main { public function make($action) { require_once __DIR__."/make/".$action.".php"; } }<file_sep>/app/gugusSpeedCode.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class gugusSpeedCode extends Model { // } <file_sep>/app/Helpers/MyForm.php <?php namespace App\Helpers; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Session; class MyForm { private static $db; private static $selectfromdb; public static function set_db($aa) { self::$db = $aa; } public static function set_select($aa) { self::$selectfromdb = $aa; } private static function set_option() { if(!isset(self::$selectfromdb["manual"])){ $data_kondisi = self::$selectfromdb["kondisi"]; $value = self::$selectfromdb["option"]["value"]; $text = self::$selectfromdb["option"]["text"]; $kondisi = $data_kondisi; $data = DB::table(self::$db) ->where($kondisi) ->get(); $option = ""; if(isset(self::$selectfromdb["selected"])){ foreach($data as $key => $nilai){ if(isset(self::$selectfromdb["key"])){ $keyselect = self::$selectfromdb["key"]; if(self::$selectfromdb["selected"] == $nilai->$keyselect){ $option .= "<option selected value='".$nilai->$value."'>".$nilai->$text."</option>"; }else{ $option .= "<option value='".$nilai->$value."'>".$nilai->$text."</option>"; } }else{ if(self::$selectfromdb["selected"] == $nilai->$value){ $option .= "<option selected value='".$nilai->$value."'>".$nilai->$text."</option>"; }else{ $option .= "<option value='".$nilai->$value."'>".$nilai->$text."</option>"; } } } }else{ foreach($data as $key => $nilai){ $option .= "<option value='".$nilai->$value."'>".$nilai->$text."</option>"; } } return $option; }else{ $data_manual = self::$selectfromdb["manual"]; $option = ""; if(isset(self::$selectfromdb["selected"])){ foreach($data_manual as $thekey => $nilai_data){ if(self::$selectfromdb["selected"] == $thekey){ $option .= "<option selected value='".$thekey."'>".$nilai_data."</option>"; }else{ $option .= "<option value='".$thekey."'>".$nilai_data."</option>"; } } }else{ foreach($data_manual as $thekey => $nilai_data){ $option .= "<option value='".$thekey."'>".$nilai_data."</option>"; } } return $option; } } private static function get_select_db(){ $data = self::$selectfromdb; $html = ' <div class="form-group"> <label for="'.$data['id'].'">'.$data['title'].'</label> <select required class="'.$data['class'].'" name="'.$data['name'].'" id="'.$data['id'].'"> <option value=""> -- pilih data -- </option> '.self::set_option().' </select> </div> '; return $html; } public static function print_select(){ echo self::get_select_db(); } public static function hidden($name, $value){ echo "<input type='hidden' name='".$name."' value='".$value."' />"; } public static function input($data) { $placeholder = ""; if(isset($data["placeholder"])){ $placeholder = "placeholder='".$data["placeholder"]."'"; } $class = ""; if(isset($data["class"])){ $class = "class='".$data["class"]."'"; } $input_auto_id = ""; $value_form = ""; if(isset($data['value'])){ if (!isset($data['auto-id'])) { $value_form = "value='".$data['value']."'"; }else{ $kondisi_db = ""; if (isset($data['kondisi'])) { foreach ($data['kondisi'] as $theKey => $nilaiData) { if ($theKey == 0) { $kondisi_db .= " WHERE ".$nilaiData[0]." ".$nilaiData[1]." '".$nilaiData[2]."' "; }else{ $kondisi_db .= " AND ".$nilaiData[0]." ".$nilaiData[1]." '".$nilaiData[2]."' "; } } } $data_input = DB::select("SELECT MAX(".$data['auto-id']['row'].") AS ".$data['auto-id']['row']." FROM ".self::$db.$kondisi_db)[0]; $the_row = $data['auto-id']['row']; $the_row_value = $data_input->$the_row; $the_row_value += 1; $the_row_len = strlen($the_row_value); $total_format = strlen($data['auto-id']['format']) - $the_row_len; $the_auto_id = ""; for($i= 0; $i < $total_format; $i++){ $the_auto_id .= "0"; } if ($data['value'] != "") { $the_auto_id = $data['value']; }else{ $the_auto_id .= $the_row_value; } // dump($data_input->$the_row); $value_form = "value='".$the_auto_id."' disabled"; $input_auto_id = "<input type='hidden' name='".$data['name']."' value='".$the_auto_id."' />"; } } $format_rupiah = ""; if(isset($data['currency'])){ $format_rupiah = ' <script> $("#'.$data['name'].'").keyup(function(event) { // skip for arrow keys if (event.which >= 37 && event.which <= 40)return; // format rupiah $(this).val(function(index, value){ return "'.$data['currency'].'"+value .replace(/\D/g,"") .replace(/\B(?=(\d{3})+(?!\d))/g,"."); }) }); </script> '; } $tag = ""; $tagend = ""; if(isset($data['tag'])){ $tag = ' <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"><i class="'.$data['tag'].'"></i></span> </div> '; $tagend = '</div>'; } $mask = ""; $maskscript = ""; if(isset($data['mask'])){ $mask = ' data-inputmask='."'".'"mask":"'.$data['mask'].'"'."'".' '; $maskscript = " <script> $('#".$data['name']."').inputmask() </script> "; } $info = ""; if(isset($data['info'])){ $info .= '<smal style="font-size:12px;display:block;color: #777; padding: 5px;">'.$data['info'].'</smal>'; } $autocomplete = ""; if (isset($data['autocomplete'])) { $autocomplete = "autocomplete='".$data['autocomplete']."'"; } $html = ' <div class="form-group"> <label for="'.$data['name'].'">'.$data['title'].'</label> '.$tag.' <input type="'.$data['type'].'" id="'.$data['name'].'" name="'.$data['name'].'" '.$mask.' '.$class.' '.$placeholder.' '.$value_form.' '.$autocomplete.' required /> '.$input_auto_id.' '.$info.' '.$maskscript.' '.$tagend.' </div> '.$format_rupiah.' '; echo $html; } public static function start($action, $method) { $html = ' <form action="'.url($action).'" method="'.$method.'"> <input type="hidden" name="_token" value="'.csrf_token().'" /> '; echo $html; } public static function end($data) { $html = ' <a href="'.url($data['back-url']).'" class="'.$data['back-button'].'"> <i class="fas fa-window-close"></i> close</a> <button id="'.$data['id-submit'].'" type="submit" class="'.$data['submit-button'].'"> <i class="fas fa-save"></i> Save</button> </form> '; echo $html; } }<file_sep>/app/Http/Controllers/stockBarang.php <?php namespace App\Http\Controllers; use App\gugusDatatable; use App\createDatatable; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class stockBarang extends Controller { private $table1 = 'stock_barang'; public function show() { // table create $datatabel = new createDatatable; $datatabel->location('toko/stock-barang/data'); $datatabel->table_name('tableku'); $datatabel->create_row(['no', 'id barang', 'nama barang','harga barang', 'total barang', 'tanggal beli', 'action']); $datatabel->order_set('0,3,4,5,6'); $show = $datatabel->create(); return view('toko.stock_barang.index', ['datatable'=> $show]); } public function stockBarang($action = 'show', $keyword = '') { if ($action == "show") { if (isset($_POST['order'])): $setorder = $_POST['order']; else: $setorder = ''; endif; $datatable = new gugusDatatable; $datatable->datatable( [ "table" => $this->table1, "select" => [ '*' ], 'where' => [ [$this->table1.'.perusahaan', '=', Session::get("toko-user")['nama_perusahaan']], ], 'limit' => [ 'start' => gugusDatatable::post('start'), 'end' => gugusDatatable::post('length') ], 'search' => [ 'value' => gugusDatatable::search(), 'row' => [ 'id_barang' ,'nama_barang' ,'harga_barang' ,'total_barang' ,'tanggal_beli' ] ], 'table-draw' => gugusDatatable::post('draw'), 'table-show' => [ 'key' => 'id', 'data' => [ 'id_barang' ,'nama_barang' ,'harga_barang' ,'total_barang' ,'tanggal_beli' ] ], "action" => "standart", 'order' => [ 'order-default' => ['id_barang', 'ASC'], 'order-data' => $setorder, 'order-option' => [ "1" => "id_barang", "2" => "nama_barang", ], ], ] ); $datatable->table_show(); }elseif ($action == "update") { $dataedit = DB::table($this->table1)->where('id', '=', $keyword)->get()[0]; return view("toko.stock_barang.update", ['data'=> $dataedit]); }elseif ($action == "delete") { $dataedit = DB::table($this->table1)->where('id', '=', $_POST['id'])->delete(); } } public function simpan(){ DB::table($this->table1)->insert([ 'id_barang' => $_POST['id_barang'] ,'nama_barang' => $_POST['nama_barang'] ,'harga_barang' => $_POST['harga_barang'] ,'total_barang' => $_POST['total_barang'] ,'tanggal_beli' => $_POST['tanggal_beli'] ,'perusahaan' => Session::get("toko-user")['nama_perusahaan'] ,'created_at' => date("Y-m-d H:i:s") ]); return redirect('toko/stock-barang'); } public function update() { DB::table($this->table1) ->where('id', '=', $_POST['id']) ->update( [ 'id_barang' => $_POST['id_barang'] ,'nama_barang' => $_POST['nama_barang'] ,'harga_barang' => $_POST['harga_barang'] ,'total_barang' => $_POST['total_barang'] ,'tanggal_beli' => $_POST['tanggal_beli'] , 'perusahaan' => Session::get("toko-user")['nama_perusahaan'] , 'updated_at' => date("Y-m-d H:i:s") ] ); return redirect('toko/stock-barang'); } } <file_sep>/app/Http/Controllers/transaksi.php <?php namespace App\Http\Controllers; use App\gugusDatatable; use App\createDatatable; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class transaksi extends Controller { private $table1 = 'transaksi'; public function show() { // table create $datatabel = new createDatatable; $datatabel->location('toko/transaksi/data'); $datatabel->table_name('tableku'); $datatabel->create_row(['no', 'id transaksi', 'tanggal transaksi', 'action']); $datatabel->order_set('0,2,3'); $show = $datatabel->create(); return view('toko.transaksi.index', ['datatable'=> $show]); } public function transaksi($action = 'show', $keyword = '') { if ($action == "show") { if (isset($_POST['order'])): $setorder = $_POST['order']; else: $setorder = ''; endif; $datatable = new gugusDatatable; $datatable->datatable( [ "table" => $this->table1, "select" => [ '*' ], 'where' => [ ['perusahaan', '=', Session::get("toko-user")['nama_perusahaan']], ], 'limit' => [ 'start' => gugusDatatable::post('start'), 'end' => gugusDatatable::post('length') ], 'search' => [ 'value' => gugusDatatable::search(), 'row' => [ 'id_transaksi' ] ], 'table-draw' => gugusDatatable::post('draw'), 'table-show' => [ 'key' => 'id', 'data' => [ 'id_transaksi' ,'created_at' ] ], "action" => "standart", 'order' => [ 'order-default' => ['id_transaksi', 'DESC'], 'order-data' => $setorder, 'order-option' => [ "1" => "id_transaksi", ], ], ] ); $datatable->table_show(); }elseif ($action == "update") { $dataedit = DB::table($this->table1)->where('id', '=', $keyword)->get()[0]; DB::table($this->table1)-> where('id', '=', $keyword) ->update([ 'id_transaksi' => $dataedit->id_transaksi ,'perusahaan' => Session::get("toko-user")['nama_perusahaan'] ,'updated_at' => date("Y-m-d H:i:s") ]); Session::put("id-transaksi", $dataedit->id_transaksi); return redirect('toko/transaksi/tambah_data'); }elseif ($action == "delete") { $dataedit = DB::table($this->table1)->where('id', '=', $_POST['id'])->delete(); } } public function tambah(){ $format = "00000000"; $getMaxData = DB::select("SELECT MAX(id_transaksi) as id_transaksi FROM ".$this->table1." WHERE perusahaan = '".Session::get("toko-user")['nama_perusahaan']."' ")[0]->id_transaksi; $getMaxData += 1; $lenFormat = strlen($format); $lenMaxData = strlen($getMaxData); $lenData = $lenFormat - $lenMaxData; $makeId = ""; for($i=0; $i < $lenData; $i++){ $makeId .= '0'; } $makeId .= $getMaxData; echo $makeId; DB::table($this->table1)->insert([ 'id_transaksi' => $makeId ,'perusahaan' => Session::get("toko-user")['nama_perusahaan'] ,'created_at' => date("Y-m-d H:i:s") ]); Session::put("id-transaksi", $makeId); return redirect('toko/transaksi/tambah_data'); } public function tambah_data(){ $datatabel = new createDatatable; $datatabel->location('toko/transaksi/tambah_data/show_data'); $datatabel->table_name('tableku'); $datatabel->create_row([ 'no','nama barang', 'harga barang', 'tottal barang', 'harga total','action']); $datatabel->order_set('0,3,4,5'); $show = $datatabel->create(); return view('toko.transaksi.tambah', ['datatable'=> $show, 'id_transaksi' => Session::get('id-transaksi')]); } public function simpan(){ DB::table($this->table1)->insert([ 'id_barang' => $_POST['id_barang'] ,'nama_barang' => $_POST['nama_barang'] ,'harga_barang' => $_POST['harga_barang'] ,'total_barang' => $_POST['total_barang'] ,'tanggal_beli' => $_POST['tanggal_beli'] ,'perusahaan' => Session::get("toko-user")['nama_perusahaan'] ,'created_at' => date("Y-m-d H:i:s") ]); return redirect('toko/stock-barang'); } public function update() { DB::table($this->table1) ->where('id', '=', $_POST['id']) ->update( [ 'id_barang' => $_POST['id_barang'] ,'nama_barang' => $_POST['nama_barang'] ,'harga_barang' => $_POST['harga_barang'] ,'total_barang' => $_POST['total_barang'] ,'tanggal_beli' => $_POST['tanggal_beli'] , 'perusahaan' => Session::get("toko-user")['nama_perusahaan'] , 'updated_at' => date("Y-m-d H:i:s") ] ); return redirect('toko/stock-barang'); } // ------------------------------------------------------------------------------// private $table2 = "data_transaksi"; public function show_data($action = 'show', $keyword = ''){ if ($action == "show") { if (isset($_POST['order'])): $setorder = $_POST['order']; else: $setorder = ''; endif; $datatable = new gugusDatatable; $datatable->datatable( [ "table" => $this->table2, "select" => [ $this->table2 => ['id','id_transaksi', 'banyak_barang'] ,'stock_barang' => ['nama_barang'] , "harga_jual" => ['harga_per_satuan as harga'] ], 'where' => [ [$this->table2.'.perusahaan', '=', Session::get("toko-user")['nama_perusahaan']], [$this->table2.'.id_transaksi', '=', Session::get("id-transaksi")], ] ,'leftJoin' => [ "stock_barang" => [$this->table2.'.id_barang', '=', 'stock_barang.id'], "harga_jual" => [$this->table2.'.id_barang', '=', 'harga_jual.id_barang'], ] ,'limit' => [ 'start' => gugusDatatable::post('start'), 'end' => gugusDatatable::post('length') ], 'search' => [ 'value' => gugusDatatable::search(), 'row' => [ 'id_transaksi' ] ], 'table-draw' => gugusDatatable::post('draw'), 'table-show' => [ 'key' => 'id', 'data' => [ 'nama_barang' ,'harga' ,'banyak_barang' ,'harga * banyak_barang' ] ], "action" => "delete-only", 'order' => [ 'order-default' => [$this->table2.'.id', 'DESC'], 'order-data' => $setorder, 'order-option' => [ "1" => "id_transaksi", ], ], ] ); $datatable->table_show(); }elseif ($action == "delete") { $dataedit = DB::table($this->table2)->where('id', '=', $_POST['id'])->delete(); } } public function simpan_data(){ $simpan = DB::table($this->table2)->insert([ 'id_transaksi' => $_POST['id_transaksi'] ,'id_barang' => $_POST['id_barang'] ,'banyak_barang' => $_POST['banyak_barang'] ,'perusahaan' => Session::get("toko-user")['nama_perusahaan'] ,'created_at' => date("Y-m-d H:i:s") ]); } } <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ // Route::get -> digunakan untuk method akses get only // Route::get('/', 'gugusController@index'); // Route::get -> digunakan untuk method akses post only // Route::get('/', 'gugusController@index'); Route::get('/', function () { return view('dashboard.dashboard'); }); // area accounting Route::get('toko/loginmenu', 'toko@loginmenu'); Route::get('toko/logout', 'toko@logout'); Route::match(['get', 'post'],'toko/login', 'toko@login'); Route::match(['get', 'post'],'toko/pendaftaran/simpan', 'toko@pendaftaranSimpan'); Route::get('toko/signup', function(){ return view('toko.signup'); }); // accounting dashboard Route::match(['get', 'post'],'toko', 'toko@dashboard')->middleware('cekstatus'); // accounting toko stock barang Route::match(['get', 'post'],'toko/stock-barang', 'stockBarang@show')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/stock-barang/data', 'stockBarang@stockBarang')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/stock-barang/data/{condition}', 'stockBarang@stockBarang')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/stock-barang/data/{condition}/{keyword}', 'stockBarang@stockBarang')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/stock-barang/simpan', 'stockBarang@simpan')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/stock-barang/update', 'stockBarang@update')->middleware('cekstatus'); Route::get('toko/stock-barang/tambah', function(){ return view('toko.stock_barang.tambah'); })->middleware('cekstatus'); // accounting akun barang Route::match(['get', 'post'],'toko/akun', 'akun@show')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/akun/data', 'akun@akun')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/akun/data/{condition}', 'akun@akun')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/akun/data/{condition}/{keyword}', 'akun@akun')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/akun/simpan', 'akun@simpan')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/akun/update', 'akun@update')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/akun/cek', 'akun@cek')->middleware('cekstatus'); Route::get('toko/akun/tambah', function(){ return view('toko.akun.tambah'); })->middleware('cekstatus'); // accounting harga-jual Route::match(['get', 'post'],'toko/harga-jual', 'hargaJual@show')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/harga-jual/data', 'hargaJual@hargaJual')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/harga-jual/data/{condition}', 'hargaJual@hargaJual')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/harga-jual/data/{condition}/{keyword}', 'hargaJual@hargaJual')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/harga-jual/simpan', 'hargaJual@simpan')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/harga-jual/update', 'hargaJual@update')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/harga-jual/cek', 'hargaJual@cek')->middleware('cekstatus'); Route::get('toko/harga-jual/tambah', function(){ return view('toko.harga_jual.tambah'); })->middleware('cekstatus'); // accounting pesanan Route::match(['get', 'post'],'toko/pesanan', 'pesanan@show')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/pesanan/data', 'pesanan@pesanan')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/pesanan/data/{condition}', 'pesanan@pesanan')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/pesanan/data/{condition}/{keyword}', 'pesanan@pesanan')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/pesanan/simpan', 'pesanan@simpan')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/pesanan/simpan_data', 'pesanan@simpan_data')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/pesanan/tambah_data/{condition1}', 'pesanan@tambah_data')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/pesanan/tambah_data/show_data/{condition1}', 'pesanan@show_data')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/pesanan/tambah_data/show_data/{condition1}', 'pesanan@show_data')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/pesanan/update', 'pesanan@update')->middleware('cekstatus'); Route::get('toko/pesanan/tambah', function(){ return view('toko.pesanan.tambah'); })->middleware('cekstatus'); // accounting pesanan Route::match(['get', 'post'],'toko/transaksi', 'transaksi@show')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/data', 'transaksi@transaksi')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/data/{condition}', 'transaksi@transaksi')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/data/{condition}/{keyword}', 'transaksi@transaksi')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/simpan', 'transaksi@simpan')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/simpan_data', 'transaksi@simpan_data')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/update', 'transaksi@update')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/tambah', 'transaksi@tambah')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/tambah_data', 'transaksi@tambah_data')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/tambah_data/show_data/{condition1}', 'transaksi@show_data')->middleware('cekstatus'); Route::match(['get', 'post'],'toko/transaksi/tambah_data/show_data/{condition1}', 'transaksi@show_data')->middleware('cekstatus');<file_sep>/gugus #!/usr/bin/env php <?php // argument $argument = $argv; unset($argument[0]); // root require_once __DIR__.'/app/gugus/main.php'; // action funtion $action = $argument[1]; unset($argument[1]); call_user_func_array(array("main", $action), $argument); <file_sep>/gugus.sql -- phpMyAdmin SQL Dump -- version 4.6.6deb5 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: 13 Des 2019 pada 09.40 -- Versi Server: 5.7.28-0ubuntu0.18.04.4 -- PHP Version: 7.2.24-0ubuntu0.18.04.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `gugus` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `akun` -- CREATE TABLE `akun` ( `id` int(11) NOT NULL, `id_akun` varchar(255) NOT NULL, `nama_akun` varchar(255) NOT NULL, `perusahaan` varchar(255) NOT NULL, `total_stock` int(11) NOT NULL DEFAULT '0', `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `akun` -- INSERT INTO `akun` (`id`, `id_akun`, `nama_akun`, `perusahaan`, `total_stock`, `created_at`, `updated_at`) VALUES (17, '00000001', 'Celana Pendek', 'Grap - Store', 4, '2019-12-11 21:43:44', '2019-12-12 04:43:44'), (18, '00000002', '<NAME>', 'Grap - Store', 7, '2019-12-11 21:44:00', '2019-12-12 04:44:00'), (19, '00000003', '<NAME>', 'Grap - Store', 0, '2019-12-11 21:44:16', '2019-12-12 04:44:16'), (20, '00000004', '<NAME>', 'Grap - Store', 0, '2019-12-11 21:44:25', '2019-12-12 04:44:25'), (21, '00000005', 'Jilbab', 'Grap - Store', 0, '2019-12-11 21:44:34', '2019-12-12 04:44:34'), (22, '00000006', '<NAME>', 'Grap - Store', 0, '2019-12-11 21:44:42', '2019-12-12 04:44:42'), (23, '00000007', '<NAME>', 'Grap - Store', 0, '2019-12-11 21:44:50', '2019-12-12 04:44:50'), (24, '00000008', '<NAME>', 'Grap - Store', 0, '2019-12-11 21:45:05', '2019-12-12 04:45:05'), (25, '00000009', 'Kaos Lengan Panjang', 'Grap - Store', 0, '2019-12-11 21:45:17', '2019-12-12 04:45:17'), (26, '00000010', 'Topi Base Ball', 'Grap - Store', 0, '2019-12-11 21:45:34', '2019-12-12 04:45:34'); -- -------------------------------------------------------- -- -- Struktur dari tabel `data_pesanan` -- CREATE TABLE `data_pesanan` ( `id` int(11) NOT NULL, `id_pesanan` varchar(255) NOT NULL, `id_barang` varchar(255) NOT NULL, `banyak_barang` int(11) NOT NULL, `perusahaan` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `data_pesanan` -- INSERT INTO `data_pesanan` (`id`, `id_pesanan`, `id_barang`, `banyak_barang`, `perusahaan`, `created_at`, `updated_at`) VALUES (1, '0000001', '00000001', 3, 'Grap - Store', '2019-12-12 15:50:28', '2019-12-12 22:50:28'), (2, '0000001', '00000002', 2, 'Grap - Store', '2019-12-12 15:50:38', '2019-12-12 22:50:38'); -- -------------------------------------------------------- -- -- Struktur dari tabel `data_transaksi` -- CREATE TABLE `data_transaksi` ( `id` int(11) NOT NULL, `id_transaksi` varchar(255) NOT NULL, `id_barang` varchar(255) NOT NULL, `banyak_barang` int(11) NOT NULL, `perusahaan` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `data_transaksi` -- INSERT INTO `data_transaksi` (`id`, `id_transaksi`, `id_barang`, `banyak_barang`, `perusahaan`, `created_at`, `updated_at`) VALUES (1, '00000001', '00000001', 2, 'Grap - Store', '2019-12-12 15:48:36', '2019-12-12 22:48:36'), (2, '00000001', '00000002', 1, 'Grap - Store', '2019-12-12 15:48:45', '2019-12-12 22:48:45'), (3, '00000001', '00000001', 1, 'Grap - Store', '2019-12-12 15:52:50', '2019-12-12 22:52:50'); -- -------------------------------------------------------- -- -- Struktur dari tabel `harga_jual` -- CREATE TABLE `harga_jual` ( `id` int(20) NOT NULL, `id_barang` int(255) NOT NULL, `harga_per_satuan` varchar(255) CHARACTER SET latin1 NOT NULL, `perusahaan` varchar(255) CHARACTER SET latin1 NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data untuk tabel `harga_jual` -- INSERT INTO `harga_jual` (`id`, `id_barang`, `harga_per_satuan`, `perusahaan`, `created_at`, `updated_at`) VALUES (6, 1, 'Rp 30.000', 'Grap - Store', '2019-12-11 23:15:27', '2019-12-11 23:18:01'), (7, 2, 'Rp 45.000', 'Grap - Store', '2019-12-12 15:48:15', '2019-12-12 22:48:15'); -- -------------------------------------------------------- -- -- Struktur dari tabel `pesanan` -- CREATE TABLE `pesanan` ( `id` int(20) NOT NULL, `id_pesanan` varchar(255) CHARACTER SET latin1 NOT NULL, `nama_pemesan` varchar(255) CHARACTER SET latin1 NOT NULL, `alamat_pemesan` text CHARACTER SET latin1 NOT NULL, `tanggal_diambil` date DEFAULT NULL, `lunas_tanggal` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `perusahaan` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data untuk tabel `pesanan` -- INSERT INTO `pesanan` (`id`, `id_pesanan`, `nama_pemesan`, `alamat_pemesan`, `tanggal_diambil`, `lunas_tanggal`, `perusahaan`, `created_at`, `updated_at`) VALUES (1, '0000001', 'Gugus', 'jl katu', '2019-12-20', '2019-12-12 22:50:18', 'Grap - Store', '2019-12-12 15:50:18', '2019-12-12 16:48:02'); -- -------------------------------------------------------- -- -- Struktur dari tabel `stock_barang` -- CREATE TABLE `stock_barang` ( `id` bigint(20) NOT NULL, `id_barang` varchar(255) NOT NULL, `harga_barang` varchar(255) NOT NULL, `harga_satuan` varchar(255) NOT NULL, `total_barang` int(255) DEFAULT NULL, `tanggal_beli` date DEFAULT NULL, `perusahaan` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `stock_barang` -- INSERT INTO `stock_barang` (`id`, `id_barang`, `harga_barang`, `harga_satuan`, `total_barang`, `tanggal_beli`, `perusahaan`, `created_at`, `updated_at`) VALUES (14, '00000001', 'Rp 200.000', 'Rp 20.000', 10, '2019-09-09', 'Grap - Store', '2019-12-11 23:04:04', '2019-12-12 06:04:04'), (15, '00000002', 'Rp 300.000', 'Rp 30.000', 10, '2019-11-10', 'Grap - Store', '2019-12-12 15:47:00', '2019-12-12 22:47:00'); -- -------------------------------------------------------- -- -- Struktur dari tabel `toko_akun` -- CREATE TABLE `toko_akun` ( `id` int(11) NOT NULL, `nama_akun` varchar(255) NOT NULL, `tanggal_input` varchar(20) NOT NULL, `tanggal_update` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data untuk tabel `toko_akun` -- INSERT INTO `toko_akun` (`id`, `nama_akun`, `tanggal_input`, `tanggal_update`) VALUES (3, 'Printer', '2019-11-22 07:41:58', ''); -- -------------------------------------------------------- -- -- Struktur dari tabel `transaksi` -- CREATE TABLE `transaksi` ( `id` int(11) NOT NULL, `id_transaksi` varchar(255) NOT NULL, `perusahaan` varchar(255) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `transaksi` -- INSERT INTO `transaksi` (`id`, `id_transaksi`, `perusahaan`, `created_at`, `updated_at`) VALUES (1, '00000001', 'Grap - Store', '2019-12-12 15:48:27', '2019-12-12 17:11:53'); -- -------------------------------------------------------- -- -- Struktur dari tabel `usertoko` -- CREATE TABLE `usertoko` ( `id` bigint(20) UNSIGNED NOT NULL, `username` char(255) COLLATE utf8_unicode_ci NOT NULL, `password` mediumtext COLLATE utf8_unicode_ci NOT NULL, `nama_perusahaan` char(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- -- Dumping data untuk tabel `usertoko` -- INSERT INTO `usertoko` (`id`, `username`, `password`, `nama_perusahaan`, `created_at`, `updated_at`) VALUES (1, 'Gugus', <PASSWORD>', 'Grap - Store', '2019-12-07 04:53:18', NULL); -- -- Indexes for dumped tables -- -- -- Indexes for table `akun` -- ALTER TABLE `akun` ADD PRIMARY KEY (`id`); -- -- Indexes for table `data_pesanan` -- ALTER TABLE `data_pesanan` ADD PRIMARY KEY (`id`); -- -- Indexes for table `data_transaksi` -- ALTER TABLE `data_transaksi` ADD PRIMARY KEY (`id`); -- -- Indexes for table `harga_jual` -- ALTER TABLE `harga_jual` ADD PRIMARY KEY (`id`); -- -- Indexes for table `pesanan` -- ALTER TABLE `pesanan` ADD PRIMARY KEY (`id`); -- -- Indexes for table `stock_barang` -- ALTER TABLE `stock_barang` ADD PRIMARY KEY (`id`); -- -- Indexes for table `toko_akun` -- ALTER TABLE `toko_akun` ADD PRIMARY KEY (`id`); -- -- Indexes for table `transaksi` -- ALTER TABLE `transaksi` ADD PRIMARY KEY (`id`); -- -- Indexes for table `usertoko` -- ALTER TABLE `usertoko` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `akun` -- ALTER TABLE `akun` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=27; -- -- AUTO_INCREMENT for table `data_pesanan` -- ALTER TABLE `data_pesanan` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `data_transaksi` -- ALTER TABLE `data_transaksi` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `harga_jual` -- ALTER TABLE `harga_jual` MODIFY `id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `pesanan` -- ALTER TABLE `pesanan` MODIFY `id` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `stock_barang` -- ALTER TABLE `stock_barang` MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; -- -- AUTO_INCREMENT for table `transaksi` -- ALTER TABLE `transaksi` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `usertoko` -- ALTER TABLE `usertoko` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
edb85ea673e9a37dd9b35a3c9946be3437821c16
[ "Markdown", "SQL", "PHP" ]
19
PHP
webshunter/kasirtoko
3d89b115c050a0fe659c7c2049b1d335463f445c
6e92c376feb2120d74bb5e6f1d2c5c4e3a1284aa
refs/heads/master
<repo_name>Hippu/pikkujoulu-countdown<file_sep>/js/christmas_robot.js var player; let tag = document.createElement('script'); tag.src = "https://www.youtube.com/player_api"; let firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); let loading_div = document.getElementById('loading-card'); const loading_ready = function() { loading_div.innerHTML = "<h1>PRESS TO GET HYPE</h1>" loading_div.addEventListener("click", start_the_shitshow); } const start_the_shitshow = function() { player.playVideo(); loading_div.innerHTML = "<h1>HYPE!</h1>" document.body.classList.add("scrolling"); setInterval(card_interval, 1000) document.getElementsByClassName('content')[0].classList.add('animated'); } const cards = card_switcher(); const card_interval = function() {cards.next()}; function* card_switcher() { let cards = document.getElementsByClassName("card"); let index = 0; let max = cards.length; while (1) { cards[(index % max)].classList.remove("current-card"); index++; cards[(index % max)].classList.add("current-card"); console.log(index % max); yield index; } } let screen_size = function () { if (window.matchMedia("(min-height: 720px)").matches) { return {"width": "1280px", "height": "720px"}; } else { return {"width": "320px", "height": "240px"}; } } function onYouTubePlayerAPIReady() { player = new YT.Player('christmas-robot', { height: screen_size().height, width: screen_size().width, videoId: 'q-43GXLnjTo', events: { 'onReady': loading_ready }, playerVars: { autoplay: 0, loop: 1, controls: 0, modestbranding: 1, showinfo: 0, playlist: 'q-43GXLnjTo' } }); }<file_sep>/js/countdown.js const Countdown = { init: function () { target = document.querySelector("#countdown"); target.textContent = Date.now(); window.requestAnimationFrame(Countdown.update); }, update: function () { let goalDate = moment("2017-12-02 15:00"); let deltaTime = goalDate.diff(moment()) let duration = moment.duration(deltaTime) target.innerHTML = '<h1>' + Math.floor(duration.asHours()) + ' h <br>' + duration.minutes() + ' m <br>' + duration.seconds() + ' s' + '</h1>'; window.requestAnimationFrame(Countdown.update); } } Countdown.init();<file_sep>/lib/christmas_robot.js 'use strict'; var player; var christmas_robot = function christmas_robot() { var tag = document.createElement('script'); tag.src = "https://www.youtube.com/player_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); }; var onYouTubePlayerAPIReady = function onYouTubePlayerAPIReady() { player = new YT.Player('christmas-robot', { height: "100%", width: "600px", videoId: 'q-43GXLnjTo', playerVars: { autoplay: 1, loop: 1, controls: 0, modestbranding: 1, showinfo: 0, playlist: 'q-43GXLnjTo' } }); }; christmas_robot();
8c51bfd2ab518285a321ab2b25980b1cd7565c4a
[ "JavaScript" ]
3
JavaScript
Hippu/pikkujoulu-countdown
e6fb2fa0b58cf4dedf2f59603fb6ef44e62abe7c
8efd6dd8252fbfbed0f34fc1c190b22775173742
refs/heads/master
<repo_name>yann-eugone/playlist-angularjs<file_sep>/app/scripts/artist/controllers/list.js 'use strict'; /** * @ngdoc function * @name app.artist.controllers:ArtistListCtrl * @description * # ArtistListCtrl * * todo */ angular.module('app.artist.controllers') .controller('ArtistListCtrl', ['$scope', '$routeParams', '$http', 'config', function ($scope, $routeParams, $http, config) { $http.get(config.routes.artists, {params: $routeParams}) .success(function (data) { $scope.artists = data._embedded.items; $scope.pagination = { page: data.page, pages: data.pages, total: data.total }; }) }]) ; <file_sep>/app/scripts/_controllers/homepage.js 'use strict'; /** * @ngdoc function * @name app.controllers:HomepageCtrl * @description * # HomepageCtrl * * todo */ angular.module('app.controllers') .controller('HomepageCtrl', ['$scope', function ($scope) { }]) ; <file_sep>/Makefile dependencies: npm install bower install run: grunt serve <file_sep>/app/scripts/_services/backend.js 'use strict'; /** * @ngdoc function * @name app.services:backend * @description * # backend * * todo */ angular.module('app.services') .factory('backend', ['$http', 'config', function ($http, config) { var getConfig = function () { $http.get(config.baseUrl) .success(function (data) { config.routes = {}; for (var route in data._links) { config.routes[route] = config.baseUrl + data._links[route].href; } }) ; }; return { getConfig: getConfig }; }]) ; <file_sep>/README.md # AngularJS Playlist Application This is a simple musical playlist application, built with : - [AngularJS](https://angularjs.org/) - [Yeoman](http://yeoman.io/) The application rely on a backend that need to be up and running : - [Playlist](https://github.com/yann-eugone/playlist) ## Using the app **Checkout it :** ``` git clone https://github.com/yann-eugone/playlist-angularjs.git && cd playlist-angularjs ``` **Install it :** ``` make ``` **Run it :** ``` make run ``` You are all set ! **Try it :** Browse to the application at [http://127.0.0.1:9000/](http://127.0.0.1:9000/). <file_sep>/app/scripts/app.js 'use strict'; /** * @ngdoc overview * @name app * @description * # app * * Main module of the application. */ angular .module('app.services', []) .constant('config', { baseUrl: 'http://localhost:8000' }) ; angular .module('app.controllers', []) ; angular .module('app.filters', []) ; // Artist angular .module('app.artist.controllers', []) .config(function ($routeProvider) { $routeProvider .when('/artists', { templateUrl: 'views/artist/list.html', controller: 'ArtistListCtrl' }) ; }) ; angular .module('app.artist.services', []) ; angular .module('app.artist', [ 'app.artist.controllers', 'app.artist.services' ]) ; angular .module('app', [ 'ngResource', 'ngRoute', 'app.controllers', 'app.services', 'app.filters', 'app.artist' ]) .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/homepage.html', controller: 'HomepageCtrl' }) //.when('/bands', { // templateUrl: 'views/band/list.html', // controller: 'BandsListCtrl' //}) //.when('/albums', { // templateUrl: 'views/album/list.html', // controller: 'AlbumsListCtrl' //}) //.when('/playlists', { // templateUrl: 'views/playlist/list.html', // controller: 'PlaylistsListCtrl' //}) .otherwise({ redirectTo: '/' }); }) .run(function (backend) { backend.getConfig(); }) ;
db2ded4382d7afe8901399826a608552843ace04
[ "JavaScript", "Makefile", "Markdown" ]
6
JavaScript
yann-eugone/playlist-angularjs
74f370327c04501f118a796b82d384866148ade1
0767d55a991f3051255f1292597a21dbc6fd987c
refs/heads/master
<file_sep>#!/usr/bin/python # -*- coding: latin-1 -*- import time from datetime import datetime, timedelta import os, sys from sikuli import * from random import* # Gera nomes e sobrenome randomicamente. def nome(): listaNomesMasculinos = ["Diogo","Enzo","Guilherme","Kauan","Luiz", "Martim","Murilo","Rodrigo","Samuel","Victor"] listaNomesFemininos = ["Agatha","Aline","Anna","Julia","Paula", "Raisa","Mariana", "Marina","Claudia","Neusa"] listaSobrenomes = ["Alves","Carvalho","Cunha","Pereira","Costa", "Dias","Azevedo","Araujo","Ribeiro","Cardoso", "Oliveira","Cavalcanti","Tula","Ferreira ","Rodrigues", "Goncalves","Dias","Oliveira","Alves","Araujo", "Azevedo","Barbosa","Cardoso ","Carvalho","Costa", "Cunha","Dias","Goncalves","Oliveira","Pereira", "Ribeiro","Rodrigues","Tula","Pecci","Nupe"] tipoGenero = choice(["MASCULINO","FEMININO"]) if (tipoGenero == "MASCULINO") : listaNomes = listaNomesMasculinos elif (tipoGenero == "FEMININO"): listaNomes = listaNomesFemininos strNome = choice(listaNomes) strSobrenome_01 = choice(listaSobrenomes) strSobrenome_02 = choice(listaSobrenomes) strNomeSobrenome = strNome + " " + strSobrenome_01 + " " + strSobrenome_02 return strNomeSobrenome # Retorna data no fomato "dd/mm/yyyy" usando como base os dias passados. def data(qtdDias): dataHoje = datetime.today() dataSolicitada = datetime.fromordinal(dataHoje.toordinal() + qtdDias) strData = dataSolicitada.strftime("%d/%m/%Y") return strData # Gera numero de telefone fixo de forma randomica contendo o prefixo "(019)32" randomicamente def telefoneFixo(): strNumeroTelefoneFixo = "(019)32" + str(randint(10,99)) + "-" + str(randint(1000,9999)) return strNumeroTelefoneFixo # Gera numero de celular fixo de forma randomica contendo o prefixo "(019)99" randomicamente def celular(): strNumeroCelular = "(019)99" + str(randint(10,99)) + "-" + str(randint(1000,9999)) return strNumeroCelular # Gera o endereco de email com base no nome gerado pela funcão "nome()" def email(strNome): strEmail = strNome.replace(" ",".") + "@" + choice(["gmail","hotmail","academia123"]) + ".com" return strEmail<file_sep>#!/usr/bin/python # -*- coding: latin-1 -*- import time import datetime import os, sys from sikuli import * from random import* import Uteis reload(Uteis) import Gerador reload(Gerador) def inclusao(): # Guarda a hora que a funcão foi iniciada, # posteriormente será usado para calcular o tempo que o processo levou. dataInicio = time.time() # Abertura de tela foi isolada em uma funcão, # posteriormente pode ser usada em outros processos. aberturaTelaDeCadastroInstrutor() # Atribuido a variavel "strNomeIntrutor" pois será usada como base para montar o endereco de email. strNomeIntrutor = Gerador.nome() paste(strNomeIntrutor) Uteis.tabOrder(2,2) paste(str(randint(100000, 999999))) Uteis.tabOrder(1,2) # A funcão "dropDown()" foi criada para a codificação ficar mais enxuta, # é passado o número de vezes que o comando "type(Key.DOWN)" é chamado # incluindo o tempo de espera entre um e outro. # É feita uma escolha randomica entre [1]C | [2]D | [3]E Uteis.dropDown(choice([1,2,3]),2) Uteis.tabOrder(1,2) #[1]"JM ASL" | [2]"JM ASL/AFF" | [3]"I ASL" | [4]"I ASL/AFF" Uteis.dropDown(choice([1,2,3,4]),2) Uteis.tabOrder(1,5) paste(Gerador.telefoneFixo()) Uteis.tabOrder(1,5) paste(Gerador.celular()) Uteis.tabOrder(1,5) # Gera o endereço de email com base no nome cadastrado. paste(Gerador.email(strNomeIntrutor)) Uteis.tabOrder(1,5) paste("Nota cadastro instrutores") wait(2) # Fecha tela de cadastro de instrutor. type('f', KeyModifier.CTRL) wait(2) while exists("barraSuperiorCadastroInstrutores.png"): print "[LOG] Aguardando abertura da tela ..." wait(1) type(Key.F3) Uteis.fechaTela() wait(5) return Uteis.delta(dataInicio, time.time()) def aberturaTelaDeCadastroInstrutor(): click(Pattern("botaoCadastroInstrutor.png").similar(0.90)) wait(3) while not exists("barraSuperiorSelecaoInstrutores.png"): print "[LOG] Aguardando abertura da tela ..." wait(1) type('n', KeyModifier.CTRL) while not exists("barraSuperiorCadastroInstrutores.png"): print "[LOG] Aguardando abertura da tela ..." wait(1) <file_sep>#!/usr/bin/python # -*- coding: latin-1 -*- import time import datetime import os, sys from sikuli import * import Uteis reload(Uteis) def userioLogin(): # Guarda a hora que a funcão foi iniciada, # posteriormente será usado para calcular o tempo que o processo levou. dataInicio = time.time() # Algumas constantes insoladas para facilitar o processo. strlogin = "SCA" strsenha = "SCA" strExecutaveSCA = "C:\Program Files (x86)\Para-quedismo\Sca\Sca.exe" # Inicializa a aplicacão. myApp = App(strExecutaveSCA) myApp.open() # Enquando não existir a imagem "telaLogin.png" aguarda 1 segundo. while not exists("telaLogin.png"): print "[LOG] Aguardando a abertura da tela de login." wait(1) print "[LOG] Tela de login aberta com sucesso." # Inclusão de login e senha. paste(strlogin) Uteis.tabOrder(1, 0.5) # A funcão "tabOrder()" foi criada para a codificacão ficar mais enxuta. paste(strsenha) Uteis.tabOrder(2, 0.5) type(Key.ENTER) # Após indicar o usuário e senha aguardar a abertura do sistema para prosseguir com o fluxo while not exists ("barraSuperiorTelaInicial.png"): print "[LOG] Aguardando a abertura da tela inicial do SCA." wait(1) print "[LOG] SCA aberto com sucesso." # Retornado o tempo que o processo levou para ser executado, # será utilizado posteriormente na classe "Relatorio.py" return Uteis.delta(dataInicio, time.time())<file_sep>#!/usr/bin/python # -*- coding: latin-1 -*- import os import time import datetime from random import* from sikuli import * # Indica o tempo que levou para executar certa operacão. def delta(dataInicio,dataFim): dataDelta = time.strftime("%M:%S",time.localtime(dataFim - dataInicio)) return dataDelta # A funcão "dropDown()" foi criada para a codificação ficar mais enxuta, # é passado o número de vezes que o comando "type(Key.DOWN)" é chamado # incluindo o tempo de espera entre um e outro. def dropDown(qtdDropDown, tmpWait): cont = 0 while (cont <= qtdDropDown): type(Key.DOWN) wait(tmpWait) cont = cont + 1 # A funcão "tabOrder()" foi criada para a codificacão ficar mais enxuta, # é passado o número de vezes que o comando "type(Key.TAB)" é chamado # incluindo o tempo de espera entre um e outro. def tabOrder(qtdTabOrder, tmpWait): cont = 1 while (cont <= qtdTabOrder): type(Key.TAB) wait(tmpWait) cont = cont + 1 # Fecha qualquer tela do sistema. def fechaTela(): print "[LOG] fechaTela()" type(Key.F4, KeyModifier.ALT) wait(2) # Fecha especificamente o sistema SCA # pois ele apresenta uma mensagem que deve ser validada. def fechaSCA(): print "[LOG] fechaSCA()" type(Key.F4, KeyModifier.ALT) wait(2) while not exists("telaSaidaSistema.png"): wait(1) type(Key.LEFT) type(Key.ENTER) wait(5)<file_sep>#!/usr/bin/python # -*- coding: latin-1 -*- import time import datetime import os, sys from sikuli import * myPath = os.path.dirname(getBundlePath()) myPath = myPath.replace("Fluxo/FluxoCadastroAluno.sikuli", "") myPath = myPath + "Biblioteca/" importPathLib = myPath.replace("/", "\\\\") if not importPathLib in sys.path: sys.path.append(importPathLib) # Import bibliotecas import Login reload(Login) import Uteis reload(Uteis) import CadastroInstrutor reload(CadastroInstrutor) import Relatorio reload(Relatorio) try: dctTempoExecucao = {} dctTempoExecucao['login'] = Login.userioLogin() dctTempoExecucao['cadastroInstrutor'] = CadastroInstrutor.inclusao() Uteis.fechaSCA() # Chamada do relatório HTML Relatorio.montaRelatorio(dctTempoExecucao,"SUCESSO") print "[Log] Processo executado com SUCESSO." except: dctTempoExecucao['login'] = "--" dctTempoExecucao['cadastroInstrutor'] = "--" # Chamada do relatório HTML Relatorio.montaRelatorio(dctTempoExecucao,"ERRO") print "[Log] Processo executado com ERRO."<file_sep>#!/usr/bin/python # -*- coding: latin-1 -*- import os, sys from sikuli import * # Monta relatório em HMTML usando o "Materialize CSS" def montaRelatorio(dctTempoExecucao,strStatus): arquivoHTML = open('C:\\GitHub\\Sikuli_SCA\\Arquivos\\RelatorioSikuli\\index.html','w') conteudoHTML = ( "<!DOCTYPE html>" + "\n" + "<html>" + "\n" + "<head>" + "\n" + "<meta charset="'"utf-8"'" />" + "\n" + "<link href="'"http://fonts.googleapis.com/icon?family=Material+ "\n" +Icons"'" rel="'"stylesheet"'">" + "\n" + "<link type="'"text/css"'" rel="'"stylesheet"'" href="'"css/materialize.min.css"'" media="'"screen,projection"'" />" + "\n" + "<title>Testes Automatizados</title>" + "\n" + "<meta name="'"viewport"'" content="'"width=device-width, initial-scale=1.0"'" />" + "\n" + "</head>" + "\n" + "<body>" + "\n" + "<header>" + "\n" + "<nav>" + "\n" + "<div class="'"nav-wrapper"'"><a href="'"index.html"'" class="'"brand-logo"'">[+] Relatorio SIKULI</a></div>" + "\n" + "</nav>" + "\n" + "</header>" + "\n" + "<div class="'"container"'">" + "\n" + "<p class="'"z-depth-5"'">" + "\n" + "<div class="'"card"'">" + "\n" + "<div class="'"card-content black-text"'">" + "\n" + "<table>" + "\n" + "<thead>" + "\n" + "<tr>" + "\n" + "<th>Processo</th>" + "\n" + "<th>Tempo</th>" + "\n" + "</tr>" + "\n" + "</thead>" + "\n" + "<tbody>" + "\n" + "<tr>" + "\n" + "<td>" + "Login : " + "</td>" + "\n" + "<td>" + dctTempoExecucao['login'] + "</td>" + "\n" + "</tr>" + "\n" + "<tr>" + "\n" + "<td>" + "Cadastro Instrutor : " + "</td>" + "\n" + "<td>" + dctTempoExecucao['cadastroInstrutor'] + "</td>" + "\n" + "</tr>" + "\n" + "</tbody>" + "\n" + "</table>" + "\n" + "</p>" + "\n" + "</div>" + "\n" + "</div>" + "\n" + #Status é passado como ferencia para indicar se o processo ocorreu com SUCESSO ou ERRO linhaStatus(strStatus) + "\n" + "</div>" + "\n" + "</body>" + "\n" + "</html>") arquivoHTML.write(conteudoHTML) arquivoHTML.close() wait(5) aberturaRelatorioChrome() # Gerada a linha que indica no HTML se o processo ocorreu com SUCESSO ou ERRO def linhaStatus(strStatus): if(strStatus=="SUCESSO"): strLinhaStatus = "<span class="'"new badge green"'">Processo efetuado com SUCESSO | </span>" elif(strStatus=="ERRO"): strLinhaStatus = "<span class="'"new badge red"'">Processo efetuado com ERRO | </span>" return strLinhaStatus # Chrome é aberto para exibir o relatório HTML. def aberturaRelatorioChrome(): strChrome = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" strCaminhoRelatorio = "C:/GitHub/Sikuli_SCA/Arquivos/RelatorioSikuli/index.html" #Inicializa o Chrome. myApp = App(strChrome) myApp.open() wait(5) # Insere o caminho na barra de endereco. type("t", Key.CTRL) paste(strCaminhoRelatorio) type(Key.ENTER) # Maximiza a tela. type(Key.F11) wait(20)<file_sep># Sikuli_SCA Projeto de automação de testes utilizando Sikuli IDE. ![Exemplo](ExemploExecuçãoFluxo.gif)
640c9b1f20e1e3ddb8482a7ec2e1924830cb59f2
[ "Markdown", "Python" ]
7
Python
victorcampos-mbciet/Sikuli_SCA-Phyton-
9a41b354f0b814fc0a112f7fd677ced0d03685ea
b4da5aaec35d0771d93f85cc84af17fa9454021d
refs/heads/master
<file_sep>window.onload = function(){ // Declaration of Variables var slidingPuzzle = document.getElementById("puzzlearea"); var tiles = slidingPuzzle.children; var targetbLeft = 0; var targetbTop = 0; var topAxis = 0; var leftAxis = 0; var eTop = 300; var eLeft = 300; var originalTop; var originalLeft; var shuffleTiles; var shuffles = []; var shuffleTimes = 1000; // Function enables the puzzle tiles to move function move_tiles(){ originalTop = parseInt(this.style.top); originalLeft = parseInt(this.style.left); if (originalTop == eTop && originalLeft == (eLeft-100) || originalTop == eTop && originalLeft == (eLeft+100) || originalTop == (eTop-100) && originalLeft == eLeft || originalTop == (eTop+100) && originalLeft == eLeft){ this.style.top = eTop + "px"; this.style.left = eLeft + "px"; eTop = originalTop; eLeft = originalLeft; } } // function which determines whether a tile can be moved function movable_tiles(){ originalTop = parseInt(this.style.top); originalLeft = parseInt(this.style.left);originalLeft if (originalTop == eTop && originalLeft == (eLeft-100) || originalTop == eTop && originalLeft == (eLeft+100) || originalTop == (eTop-100) && originalLeft == eLeft || originalTop == (eTop+100) && originalLeft == eLeft){ $(this).addClass('movablepiece'); } else{ $(this).removeClass("movablepiece"); } } // for loop which arranges the orginal list of numbers into a puzzle box format for(var i=0; i < tiles.length; i++){ tiles[i].className = "puzzlepiece"; tiles[i].style.top = topAxis + "px"; tiles[i].style.left = leftAxis + "px"; tiles[i].style.backgroundPosition = targetbLeft + "px " + targetbTop + "px"; tiles[i].onclick= move_tiles; tiles[i].onmouseover= movable_tiles; if(leftAxis < 300){ leftAxis = leftAxis + 100; targetbLeft = targetbLeft - 100; } else{ leftAxis = 0; targetbLeft = 0; topAxis = topAxis + 100; targetbTop = targetbTop - 100; } } // function which Shuffles the puzzle pieces upon selection of case function Shuffle(){ for(var c = 0; c < shuffleTimes; c++){ var pick = Math.floor (Math.random () * 4); switch(pick){ case 0: (get_tile_Style((eTop-100)+"px", eLeft+"px"))|| get_tile_Style((eTop+100)+"px", eLeft+"px"); originalTop = parseInt(shuffleTiles.style.top); originalLeft = parseInt(shuffleTiles.style.left); shuffleTiles.style.top = eTop + "px"; shuffleTiles.style.left = eLeft + "px"; eTop = originalTop; eLeft = originalLeft; break; case 1: (get_tile_Style(eTop+"px", (eLeft-100)+"px")) || get_tile_Style(eTop+"px", (eLeft + 100)+"px"); originalTop = parseInt(shuffleTiles.style.top); originalLeft = parseInt(shuffleTiles.style.left); shuffleTiles.style.top = eTop + "px"; shuffleTiles.style.left = eLeft + "px"; eTop = originalTop; eLeft = originalLeft; break; case 2: get_tile_Style((eTop+100)+"px", eLeft+"px") || (get_tile_Style((eTop-100)+"px", eLeft+"px")); originalTop = parseInt(shuffleTiles.style.top); originalLeft = parseInt(shuffleTiles.style.left); shuffleTiles.style.top = eTop + "px"; shuffleTiles.style.left = eLeft + "px"; eTop = originalTop; eLeft = originalLeft; break; default: get_tile_Style(eTop+"px", (eLeft + 100)+"px") || (get_tile_Style(eTop+"px", (eLeft-100)+"px")); originalTop = parseInt(shuffleTiles.style.top); originalLeft = parseInt(shuffleTiles.style.left); shuffleTiles.style.top = eTop + "px"; shuffleTiles.style.left = eLeft + "px"; eTop = originalTop; eLeft = originalLeft; break; } }} function get_tile_Style(top, left){ for(var i =0; i < tiles.length; i++){ if(tiles[i].style.top==top && tiles[i].style.left==left){ shuffleTiles = tiles[i]; return shuffleTiles; } } } document.getElementById("controls").onclick = Shuffle; }
55936cee3b2b7610a90f2d3db42b0c76d5298c09
[ "JavaScript" ]
1
JavaScript
MoniqueF17/info2180-project2
4372e3e3b180e0be48cf342086f242522230baec
5a130c3987ab055c1e0009948735285f991d9356
refs/heads/master
<repo_name>armandolezama/reto-poly<file_sep>/public/script.js //Este código tiene como objetivo presentar una simulación de televisiones para web. //Cada televisión cuenta con botones para controlarse y un sintonizador manual de canales //El sintonizador (control) sirve para ir a un canal en específico, configurado para respetar los límites de la tv const mainContainer = document.getElementById('main-container') //Esta es la conexión al tag html que contendrá las TV's let tvCollection = {} //Este objeto contendrá a todas las instancias de la clase 'Television' let tvButtons = {} //Se considera que la siguiente clase cumple con el concepto de abstracción de POO ya que, en un sólo modelo //engloba diversas funciones repetibles de un televisor. Como siguiente paso cada clase debería tener contenida en sí misma //el código en html que le corresponda a cada instancia de objetos class Television { constructor(model, manualCh, limit = 20, channel = 1){ this.model = document.getElementById(model) this.manualCh = document.getElementById(manualCh) this.turned = false this.channel = channel this.limit = limit } theChannel(){ this.model.innerHTML = ` <div class="screen"> <p class="ch-content">${this.channel}</p> </div>` } // async tuneIn(){ // await fetch().then().catch() // return img // } manualChannel(){ if(this.turned){ this.channel = this.manualCh.value if(this.channel > this.limit ){ this.channel = this.limit } else if (this.channel < 1){ this.channel = 1 } this.theChannel() } } plusChannel(){ if(this.turned){ this.channel += 1 if(this.channel > this.limit ){ this.channel = 1 } this.theChannel() } } lessChannel(){ if(this.turned){ this.channel -= 1 if(this.channel < 1){ this.channel = this.limit } this.theChannel() } } turnOff(){ this.turned = false this.model.innerHTML = `<div class="screen"><p class="ch-content">Apagado</p></div>` } turnOn(){ this.turned = true this.theChannel() } } //Al poder ser utilizada repetidas veces cumple con el concepto de polimorfismo de POO //yaa que cada objeto instanciado con esta clase posee sus propios atributos, sólo se ingresa //el id en html del televisor, y el id de su control, y automáticamente se accede a sus métodos //y propiedades let firstTV = new Television ('first-tv', 'first-manual') let secondTV = new Television ('second-tv', 'second-manual') let thirdTV = new Television ('third-tv', 'third-manual') //La siguiente función tiene como finalidad repetir la creación de televisiones y conectarlas inmediatamente con su nodo correspondiente //en HTML. Se utiliza la misma clase por lo que se recicla mucho código. function addTelevision(){ let numberofTv = Object.keys(tvCollection).length + 1; let tvName = `tvNumber${numberofTv}`; mainContainer.insertAdjacentHTML('beforeend', `<article class="tv-container"> <div id="tv-number-${numberofTv}" class="television"> <div id="screen-number-${numberofTv}" class="screen"><p class="ch-content">Apagado</p></div> </div> <div class="control"> <p>Aquí se encuentra el control para que cambie de canal</p> <div> <input id="manual-number-${numberofTv}" class="manualChn" id="" type="number" name="manualChn" value="" placeholder="Inserte el canal que desee sintonizar" required> <button id="manual-in-${numberofTv}" >Cambiar canal</button> </div> <div> <button id="off-${numberofTv}" class="off-btn">Apagar</button> <button id="on-${numberofTv}" class="on-btn">Encender</button> <button id="plus-${numberofTv}" class="plus-btn">+</button> <button id="less-${numberofTv}" class="less-btn">-</button> </div> </div> </article>`) tvCollection[tvName] = new Television (`tv-number-${numberofTv}`, `manual-number-${numberofTv}`) document.getElementById(`manual-in-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].manualChannel()}) document.getElementById(`off-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].turnOff()}) document.getElementById(`on-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].turnOn()}) document.getElementById(`plus-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].plusChannel()}) document.getElementById(`less-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].lessChannel()}) } //Para hacer un ejemplo práctico del concepto de herencia en POO se genera una nueva versión de Television. //Esta segunda clase aprovecha los atributos y los métodos de la anterior clase, y añade un nuevo método. //Este nuevo método permite añadir una "película" al televisor. class Television2 extends Television{ constructor(model, manualCh, vidScn, limit = 20, channel = 1){ super() this.model = document.getElementById(model) this.manualCh = document.getElementById(manualCh) this.vidScn = document.getElementById(vidScn) this.turned = false this.channel = channel this.limit = limit this.movie } playMovie(){ if(this.turned){ this.movie = this.vidScn.value this.model.innerHTML = ` <div class="screen2"> <p class="ch-content">${this.movie}</p> </div>` } } theChannel(){ this.model.innerHTML = ` <div class="screen2"> <p class="ch-content">${this.channel}</p> </div>` } turnOff(){ this.turned = false this.model.innerHTML = `<div class="screen2"><p class="ch-content">Apagado</p></div>` } } //Se tiene que reescribir la función addTelevision para volver compatible el nodo html de la nueva televisión con su clase. function addTelevision2(){ let numberofTv = Object.keys(tvCollection).length + 1; let tvName = `tvNumber${numberofTv}`; mainContainer.insertAdjacentHTML('beforeend', `<article class="tv-container2"> <div id="tv-number-${numberofTv}" class="television2"> <div id="screen-number-${numberofTv}" class="screen2"><p class="ch-content">Apagado</p></div> </div> <div class="control2"> <p>Aquí se encuentra el control para que cambie de canal</p> <div> <input id="manual-number-${numberofTv}" class="manualChn" id="" type="number" name="manualChn" value="" placeholder="Inserte el canal que desee sintonizar" required> <button id="manual-in-${numberofTv}" >Cambiar canal</button> </div> <div> <input id="manual-vid-${numberofTv}" class="manualChn" id="" type="text" name="manualChn" value="" placeholder="¿Qué película desea ver" required> <button id="manual-vid-in-${numberofTv}" >Ver película</button> </div> <div> <button id="off-${numberofTv}" class="off-btn">Apagar</button> <button id="on-${numberofTv}" class="on-btn">Encender</button> <button id="plus-${numberofTv}" class="plus-btn">+</button> <button id="less-${numberofTv}" class="less-btn">-</button> </div> </div> </article>`) tvCollection[tvName] = new Television2 (`tv-number-${numberofTv}`, `manual-number-${numberofTv}`,`manual-vid-${numberofTv}`) document.getElementById(`manual-in-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].manualChannel()}) document.getElementById(`off-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].turnOff()}) document.getElementById(`on-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].turnOn()}) document.getElementById(`plus-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].plusChannel()}) document.getElementById(`less-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].lessChannel()}) document.getElementById(`manual-vid-in-${numberofTv}`).addEventListener('click', ()=>{ tvCollection[tvName].playMovie()}) }
637e471cd8fa80ffcc7a9c02d9206cfd0bfa999a
[ "JavaScript" ]
1
JavaScript
armandolezama/reto-poly
5fad5d8d0474f5617ec2fe99f21c0335591710f9
45f5ba33562869a0175a88747403eb7ab9f81ce4
refs/heads/main
<repo_name>Magliari/Random_Forest<file_sep>/README.md # Random_Forest *Um projeto utilizado apenas para o estudo do algoritmo Random Forest, utilizando-se o R. Serão utilizadas duas bases de dados e dois scripts* A base de dados `census.csv` foi retirada do **UCI Machine Learning Repository**, a qual no mesmo possui o nome de **Adult Data Set**. Foram realizadas pequenas modificações na mesma. O objetivo de previsão na mesma é determinar se uma pessoa ganha mais de 50 mil por ano. O objetivo de previsão na base de dados `credit_data.csv` é determinar se o cliente pagou o empréstimo. Utilizando-se o algoritmo Random Forest foi possível encontrar uma precisão de **85,52%** na primeira base de dados e de **98,8%** na segunda. Nota-se que houve ganhos em relação ao algoritmo de Árvore de decisão, observar o repositório *Decision_Tree* disponível nesse perfil. <file_sep>/arvore_decisao_credit_data_random_forest.R base<-read.csv("credit_data.csv") base$clientid<- NULL summary(base) #Excluir os valores negativos base<-abs(base) #Excluir os valores faltantes base$age=ifelse(is.na(base$age),mean(base$age,na.rm = TRUE),base$age) #Encode da Classe base$default<-factor(base$default,levels = c(0,1)) #Dividir a base de dados em treinamento e teste library('caTools') set.seed(1) divisao<-sample.split(base$default,SplitRatio = 0.75) base_treinamento<-subset(base, divisao==TRUE) base_teste<-subset(base, divisao==FALSE) #Árvore de Decisão com Random Forest library(randomForest) classificador<-randomForest(x = base_treinamento[-4], y = base_treinamento$default, ntree = 10) previsoes<-predict(classificador,newdata = base_teste[-4]) matriz_confusao<-table(base_teste[,4],previsoes) #Precisão de 98,8% library(caret) confusionMatrix(matriz_confusao)
4d281b4da1bf24a00f0fa9a4f550efb5a791d749
[ "Markdown", "R" ]
2
Markdown
Magliari/Random_Forest
793da8ed6f8a57a13586c6ba78870db63d6261d4
6a3fd5c75f3d2537cd13c0800e72f28f872fae22
refs/heads/main
<file_sep>import { useState, useCallback } from "react"; export function useInput<T>( initialValue: T ): [T, (e?: React.ChangeEvent<HTMLInputElement>) => void] { const [value, setValue] = useState<T>(initialValue); const handler = useCallback((e) => { setValue(e.target.value); }, []); return [value, handler]; } <file_sep># 🌞 solar-todo ## 배포주소 https://pjainxido.github.io/solar-todo/ ## start ``` yarn yarn start ``` ## build & deploy ``` yarn build yarn depoly ``` ## 요구사항 ### 완성 및 기능추가 - [x] Todo List 현재시간 표시 - [x] Todo 버튼 클릭시 완료 가능 - [x] 완료목표일 기입, 입력항목 근처 입력가능하게 ux 구성(antd/date-picker 사용) - [x] 완료 목표일 렌더링 ### 예외사항 - todo text 미입력후 todo 생성시 알림 모달로 예외 표시 - 완료목표일(deadline) 입력시 현재 날짜보다 과거날짜 입력시 알림 모달로 예외 표시 ### 버그픽스 - 기존 id생성 로직으로 인해 id값이 중복되어 발생하는 문제들 수정 <file_sep>export const DATE_FORMAT = "YYYY-MM-DD"; export const STATE = { TODO: 0, INPROGRESS: 1, DONE: 2, };
56fd937d337c0206effb759cc41ff034beebf3b0
[ "Markdown", "TypeScript" ]
3
TypeScript
pjainxido/solar-todo
8d53780dd6c9796f367764cc2d9bc96b068b24e9
a85180a147caa65f4a3d42a73d51807fe3586d81
refs/heads/master
<repo_name>eugene2k/base-x-rs<file_sep>/benches/base.rs #[macro_use] extern crate bencher; extern crate rand; extern crate base_x; use bencher::Bencher; use base_x::{encode, decode, Alphabet}; fn random_input(size: usize) -> Vec<u8> { let mut v = vec![0; size]; for x in v.iter_mut() { *x = rand::random() } v } fn test_decode<A: Alphabet + Copy>(bench: &mut Bencher, alph: A) { let input = random_input(100); let out = encode(alph, &input); bench.iter(|| { decode(alph, &out).unwrap() }); } fn test_encode<A: Alphabet + Copy>(bench: &mut Bencher, alph: A) { let input = random_input(100); bench.iter(|| { encode(alph, &input) }); } // Actual benchmarks // Encode UTF-8 fn encode_base2(bench: &mut Bencher) { const ALPH: &'static str = "01"; test_encode(bench, ALPH); } fn encode_base16(bench: &mut Bencher) { const ALPH: &'static str = "0123456789abcdef"; test_encode(bench, ALPH); } fn encode_base58(bench: &mut Bencher) { const ALPH: &'static str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; test_encode(bench, ALPH); } // Decode UTF-8 fn decode_base2(bench: &mut Bencher) { const ALPH: &'static str = "01"; test_decode(bench, ALPH); } fn decode_base16(bench: &mut Bencher) { const ALPH: &'static str = "0123456789abcdef"; test_decode(bench, ALPH); } fn decode_base58(bench: &mut Bencher) { const ALPH: &'static str = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; test_decode(bench, ALPH); } benchmark_group!(benches, encode_base2, decode_base2, encode_base16, decode_base16, encode_base58, decode_base58 ); benchmark_main!(benches); <file_sep>/src/alphabet.rs use encoder::{AsciiEncoder, Utf8Encoder}; use decoder::{AsciiDecoder, Utf8Decoder}; use DecodeError; use std::ascii::AsciiExt; const INVALID_INDEX: u8 = 0xFF; pub trait Alphabet { fn encode(&self, input: &[u8]) -> String; fn decode(&self, input: &str) -> Result<Vec<u8>, DecodeError>; } impl<'a> Alphabet for &'a [u8] { #[inline(always)] fn encode(&self, input: &[u8]) -> String { AsciiEncoder::encode(*self, input) } #[inline(always)] fn decode(&self, input: &str) -> Result<Vec<u8>, DecodeError> { let mut lookup = [INVALID_INDEX; 256]; for (i, byte) in self.iter().enumerate() { lookup[*byte as usize] = i as u8; } AsciiDecoder::decode(*self, lookup, input) } } impl<'a> Alphabet for &'a str { #[inline(always)] fn encode(&self, input: &[u8]) -> String { if self.is_ascii() { return self.as_bytes().encode(input); } let alphabet: Vec<char> = self.chars().collect(); Utf8Encoder::encode(&alphabet, input) } #[inline(always)] fn decode(&self, input: &str) -> Result<Vec<u8>, DecodeError> { if self.is_ascii() { return self.as_bytes().decode(input); } let alphabet: Vec<char> = self.chars().collect(); Utf8Decoder::decode(&alphabet, input) } } <file_sep>/src/encoder.rs use bigint::BigUint; pub struct AsciiEncoder; pub struct Utf8Encoder; macro_rules! encode { ($alpha:ident, $input:ident) => ({ if $input.len() == 0 { return String::new(); } let base = $alpha.len() as u32; // Convert the input byte array to a BigUint let mut big = BigUint::from_bytes_be($input); let mut out = Vec::with_capacity($input.len()); // Find the highest power of `base` that fits in `u32` let big_pow = 32 / (32 - base.leading_zeros()); let big_base = base.pow(big_pow); 'fast: loop { // Instead of diving by `base`, we divide by the `big_base`, // giving us a bigger remainder that we can further subdivide // by the original `base`. This greatly (in case of base58 it's // a factor of 5) reduces the amount of divisions that need to // be done on BigUint, delegating the hard work to regular `u32` // operations, which are blazing fast. let mut big_rem = big.div_mod(big_base); if big.is_zero() { loop { out.push($alpha[(big_rem % base) as usize]); big_rem /= base; if big_rem == 0 { break 'fast; // teehee } } } else { for _ in 0..big_pow { out.push($alpha[(big_rem % base) as usize]); big_rem /= base; } } } let leaders = $input .iter() .take($input.len() - 1) .take_while(|i| **i == 0) .map(|_| $alpha[0]); out.extend(leaders); out }) } impl AsciiEncoder { #[inline(always)] pub fn encode(alphabet: &[u8], input: &[u8]) -> String { let mut out = encode!(alphabet, input); out.reverse(); String::from_utf8(out).expect("Alphabet must be ASCII") } } impl Utf8Encoder { #[inline(always)] pub fn encode(alphabet: &[char], input: &[u8]) -> String { let out = encode!(alphabet, input); out.iter().rev().map(|char| *char).collect() } } <file_sep>/src/decoder.rs use DecodeError; use bigint::BigUint; pub struct AsciiDecoder; pub struct Utf8Decoder; macro_rules! decode { ($alpha:ident, $input:ident, $iter:ident, $c:pat => $carry:expr) => ({ if $input.len() == 0 { return Ok(Vec::new()); } let base = $alpha.len() as u32; let mut big = BigUint::with_capacity(4); for $c in $input.$iter() { big.mul_add(base, $carry as u32); } let mut bytes = big.into_bytes_be(); let leader = $alpha[0]; let leaders = $input .$iter() .take_while(|byte| *byte == leader) .count(); for _ in 0..leaders { bytes.insert(0, 0); } Ok(bytes) }) } impl AsciiDecoder { #[inline(always)] pub fn decode(alphabet: &[u8], lookup: [u8; 256], input: &str) -> Result<Vec<u8>, DecodeError> { decode!( alphabet, input, bytes, c => match lookup[c as usize] { 0xFF => return Err(DecodeError), index => index } ) } } impl Utf8Decoder { #[inline(always)] pub fn decode(alphabet: &[char], input: &str) -> Result<Vec<u8>, DecodeError> { decode!( alphabet, input, chars, // Vector find is faster than HashMap even for Base58 c => alphabet .iter() .enumerate() .find(|&(_, ch)| *ch == c) .map(|(i, _)| i) .ok_or(DecodeError)? ) } }
50de2cd136f0d7b601ac7ae469cbe06b6e5c0e60
[ "Rust" ]
4
Rust
eugene2k/base-x-rs
64e2a9448475306309d8866217af5f1ce7da5f40
6bead0744bf8fc181a3df8917b3988a105c66149
refs/heads/master
<file_sep>package com.camille.clicker class Model ( var number: Int = 0 ) { fun increase(): Int { return ++number } }<file_sep>rootProject.name = "Clicker" include ':app' <file_sep>package com.camille.clicker import androidx.databinding.ObservableField class ViewModel ( var model: Model = Model(), val numberString: ObservableField<String> = ObservableField("0") ) { fun update() { model.increase() numberString.set(model.number.toString()) } }<file_sep>package com.camille.clicker import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import androidx.databinding.DataBindingUtil import com.camille.clicker.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.viewModel = ViewModel() findViewById<Button>(R.id.button).apply { this.setOnClickListener { binding.viewModel?.update() } } } }
98d6325d151e2fa6d470ead46028387c5c81b203
[ "Kotlin", "Gradle" ]
4
Kotlin
XDKomel/clickerMVVM
ce81eae85d4e44c23c5d5b60c3a6a36dfb589eae
bd2601e091fba3819d96d038b640dcb3daac2780
refs/heads/master
<file_sep># ProjectileSimulation Projectile simulation using jMonkeyEngine <file_sep>package com.sergeiyarema.simulation; import com.jme3.math.Vector3f; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import static com.sergeiyarema.simulation.DotParams.*; public class DotParamsTest { private static final DotParams dotParamsOriginal = new DotParams(new Vector3f(1f, 1f, 1f), 45.f, 10f, -3f, 9f); @Test public void copy() { DotParams dotParamsCopy = dotParamsOriginal.copy(); Assert.assertNotEquals(dotParamsOriginal.hashCode(), dotParamsCopy.hashCode()); // Really creates new object Assert.assertEquals(0, dotParamsCopy.compareTo(dotParamsOriginal)); // Same data } @Test public void getStartPos() { Assert.assertEquals(Vector3f.UNIT_XYZ, dotParamsOriginal.getStartPos()); } @Test public void setStartPos() { DotParams dotParamsCopy = dotParamsOriginal.copy(); Vector3f newPos = new Vector3f(10f, 10f, 10f); dotParamsCopy.setStartPos(newPos.clone()); Assert.assertEquals(newPos, dotParamsCopy.getStartPos()); } @Test public void get() { Assert.assertEquals(45f, dotParamsOriginal.get(START_ANGLE), 0.001); Assert.assertEquals(10f, dotParamsOriginal.get(START_SPEED), 0.001); Assert.assertEquals(-3f, dotParamsOriginal.get(GROUND_LEVEL), 0.001); Assert.assertEquals(9f, dotParamsOriginal.get(GRAVITY), 0.001); } @Rule public final ExpectedException exception = ExpectedException.none(); @Test public void getNotExistingParameter() { exception.expect(NullPointerException.class); dotParamsOriginal.get("NOT_EXISTING"); } @Test public void getChangeable() { Assert.assertEquals(45.f, dotParamsOriginal.getChangeable(START_ANGLE).getValue(), 0.001); Assert.assertEquals(10.f, dotParamsOriginal.getChangeable(START_SPEED).getValue(), 0.001); Assert.assertEquals(-3f, dotParamsOriginal.getChangeable(GROUND_LEVEL).getValue(), 0.001); Assert.assertEquals(9f, dotParamsOriginal.getChangeable(GRAVITY).getValue(), 0.001); } @Test public void getNotExistingChangeable() { exception.expect(NullPointerException.class); float not_existing = dotParamsOriginal.getChangeable("NOT_EXISTING").getValue(); } @Test public void set() { DotParams dotParamsCopy = dotParamsOriginal.copy(); dotParamsCopy.set(START_SPEED, 10f); dotParamsCopy.set(START_ANGLE, 10f); dotParamsCopy.set(GRAVITY, 10f); Assert.assertEquals(10f, dotParamsCopy.getChangeable(START_ANGLE).getValue(), 0.001); Assert.assertEquals(10f, dotParamsCopy.getChangeable(START_SPEED).getValue(), 0.001); Assert.assertEquals(10f, dotParamsCopy.getChangeable(GRAVITY).getValue(), 0.001); } @Test public void compareTo() { DotParams dotParamsA = dotParamsOriginal.copy(); DotParams dotParamsB = dotParamsOriginal.copy(); DotParams different = new DotParams(new Vector3f(0f, 0f, 0f), 45.f, 10f, -10f, 9f); Assert.assertNotEquals(0, different.compareTo(dotParamsA)); Assert.assertEquals(0, different.compareTo(different)); Assert.assertEquals(0, dotParamsA.compareTo(dotParamsA)); Assert.assertEquals(0, dotParamsA.compareTo(dotParamsB)); Assert.assertEquals(0, dotParamsB.compareTo(dotParamsA)); } @Test public void equals() { DotParams dotParamsA = dotParamsOriginal.copy(); DotParams dotParamsB = dotParamsOriginal.copy(); DotParams different = new DotParams(new Vector3f(0f, 0f, 0f), 45.f, 10f, -10f, 9f); Assert.assertTrue(dotParamsA.equals(dotParamsA)); Assert.assertTrue(dotParamsA.equals(dotParamsB)); Assert.assertFalse(dotParamsA.equals(different)); Assert.assertFalse(dotParamsA.equals(new Object())); } }<file_sep>package com.sergeiyarema.simulation; import com.jme3.math.Vector3f; import static com.sergeiyarema.simulation.DotParams.*; public class Trajectory { private Trajectory() { } public static Vector3f getCoords(DotParams params, float currentTime) { float x0 = params.getStartPos().x; float y0 = params.getStartPos().y; float z0 = params.getStartPos().z; float alpha = (float) Math.toRadians(params.get(START_ANGLE)); float vx = (float) (params.get(START_SPEED) * Math.cos(alpha)); float vy = (float) (params.get(START_SPEED) * Math.sin(alpha)); float x = currentTime * vx; float y = currentTime * vy - params.get(GRAVITY) * currentTime * currentTime / 2.f; return new Vector3f(x0 + x, y0 + y, z0); } public static Vector3f getCoordsFromXValue(DotParams params, float x) { float x0 = params.getStartPos().x; float y0 = params.getStartPos().y; float z0 = params.getStartPos().z; x = x - x0; float alpha = (float) Math.toRadians(params.get(START_ANGLE)); float v0 = params.get(START_SPEED); float g = params.get(GRAVITY); float y = (float) (x * Math.tan(alpha) - (g * x * x) / (2 * v0 * v0 * Math.cos(alpha) * Math.cos(alpha))); return new Vector3f(x0 + x, y0 + y, z0); } } <file_sep>rootProject.name = 'ProjectileSimulation' <file_sep>package com.sergeiyarema.simulation; import com.jme3.asset.AssetManager; public class GlobalAssets { private static AssetManager assetManager; private GlobalAssets() { } public static void innitAssets(AssetManager assetManager) { GlobalAssets.assetManager = assetManager; } public static AssetManager manager() { return assetManager; } } <file_sep>package com.sergeiyarema.simulation; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.sergeiyarema.misc.Copiable; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class DotParams implements Copiable<DotParams>, Comparable<DotParams> { public static final String GRAVITY = "Gravity"; public static final String START_ANGLE = "StartAngle"; public static final String START_SPEED = "StartSpeed"; public static final String GROUND_LEVEL = "GroundLevel"; public static final String RADIUS = "Radius"; public static final Vector2f ANGLE_LIMIT = new Vector2f(10f, 170f); public static final Vector2f SPEED_LIMIT = new Vector2f(0f, 200f); public static final Vector2f GRAVITY_LIMIT = new Vector2f(0.1f, 100f); private Map<String, ChangeableByDelta> mapping = new HashMap<>(); private Vector3f startPos; private DotParams() { } public DotParams(Vector3f startPos, float startAngle, float startSpeed, float groundLevel, float gravity) { this.startPos = startPos.clone(); set(START_ANGLE, startAngle).setBoundary(ANGLE_LIMIT); set(START_SPEED, startSpeed).setBoundary(SPEED_LIMIT); set(GRAVITY, gravity).setBoundary(GRAVITY_LIMIT); set(GROUND_LEVEL, groundLevel); set(RADIUS, 0.5f); } @Override public DotParams copy() { return new DotParams(startPos, get(START_ANGLE), get(START_SPEED), get(GROUND_LEVEL), get(GRAVITY)); } public Vector3f getStartPos() { return startPos; } public void setStartPos(Vector3f startPos) { this.startPos = startPos.clone(); } public float get(String valueName) { return getChangeable(valueName).getValue(); } public ChangeableByDelta getChangeable(String valueName) { return mapping.get(valueName); } public ChangeableByDelta set(String valueName, float newValue) { ChangeableByDelta newChangeable = mapping.get(valueName); if (newChangeable == null) { newChangeable = new ChangeableByDelta(); mapping.put(valueName, newChangeable); } newChangeable.setValue(newValue); return newChangeable; } @Override public int compareTo(DotParams dotParams) { if (this.hashCode() == dotParams.hashCode()) return 0; boolean mappingCheck = true; for (Map.Entry<String, ChangeableByDelta> entry : mapping.entrySet()) { if (dotParams.get(entry.getKey()) - entry.getValue().getValue() > 0.001) { mappingCheck = false; break; } } if (startPos.equals(dotParams.getStartPos()) && mappingCheck) return 0; else return -1; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DotParams dt = (DotParams) o; return (this.compareTo(dt) == 0); } @Override public int hashCode() { return Objects.hash(startPos, mapping); } }<file_sep>plugins { id 'java' id 'jacoco' id "org.sonarqube" version "2.7" } group 'ProjectileSimulation' version '1.0-SNAPSHOT' sourceCompatibility = 1.8 repositories { jcenter() mavenCentral() maven { url "http://dl.bintray.com/jmonkeyengine/org.jmonkeyengine" } } jacoco { toolVersion = "0.8.4" reportsDir = file("$buildDir/customJacocoReportDir") } jacocoTestReport { reports { xml.enabled false csv.enabled false html.destination file("${buildDir}/jacocoHtml") } } sonarqube { properties { property 'sonar.coverage.exclusions', "**/com/*/MainWindow" } } def jme3 = [v:'3.2.0-stable', g:'org.jmonkeyengine'] dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' compile "${jme3.g}:jme3-core:${jme3.v}" compile "${jme3.g}:jme3-bullet:${jme3.v}" compile "${jme3.g}:jme3-blender:${jme3.v}" compile "${jme3.g}:jme3-plugins:${jme3.v}" compile "${jme3.g}:jme3-jogg:${jme3.v}" compile "${jme3.g}:jme3-niftygui:${jme3.v}" compile "${jme3.g}:jme3-effects:${jme3.v}" compile "${jme3.g}:jme3-lwjgl3:${jme3.v}" compile "${jme3.g}:jme3-bullet-native:${jme3.v}" runtime "${jme3.g}:jme3-desktop:${jme3.v}" runtime "${jme3.g}:jme3-lwjgl3:${jme3.v}" } <file_sep>package com.sergeiyarema.simulation; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.math.Quaternion; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.shape.Cylinder; import static com.sergeiyarema.simulation.DotParams.RADIUS; import static com.sergeiyarema.simulation.DotParams.START_ANGLE; public class Cannon extends SimulationObject { public Cannon(DotParams dotParams, Node rootNode) { super(dotParams, rootNode); this.params = params.copy(); Material matGray = new Material(GlobalAssets.manager(), "Common/MatDefs/Misc/Unshaded.j3md"); matGray.setColor("Color", ColorRGBA.Gray); float radius = params.get(RADIUS) * 1.1f; float height = params.get(RADIUS) * 6f; geometry = new Geometry("Canon", new Cylinder(32, 32, radius, height, true)); geometry.setMaterial(matGray); geometry.move(params.getStartPos()); setAngle(params.get(START_ANGLE)); node.attachChild(geometry); } public void setAngle(float angle) { params.set(START_ANGLE, angle); Quaternion cameraAlign = new Quaternion(); cameraAlign.fromAngleAxis(FastMath.PI / 2.f, new Vector3f(0, 1, 0)); float radAngle = (float) Math.toRadians(angle); Quaternion angleSetter = new Quaternion(); angleSetter.fromAngleAxis(radAngle, new Vector3f(0, 0, 1)); geometry.setLocalRotation(angleSetter.mult(cameraAlign)); } }
81f72a8bf2234541cf6da97f53d8a0301793a28d
[ "Markdown", "Java", "Gradle" ]
8
Markdown
SergySanJj/ProjectileSimulation
a195c8c1a02933813c1d593d55af37ffe4d5169e
5ef30fc1846c8f1dcef64a9ae69b6ced90d5b58a
refs/heads/master
<file_sep>#do not forget that config.ru is vital to make rack -- the middleware which # handles http request and serving up a the page locally... work require './config/environment' run App
90fa5cc70513f6a2e5cf59099d78daae785a2176
[ "Ruby" ]
1
Ruby
haydenbetts/sinatra-basic-routes-lab-cb-gh-000
ecdfe8b0da1f59d0f908b661b131629c998d9796
046ed4b2c10c6d908edbca8496d581b1094c4421
refs/heads/master
<file_sep>$(document).ready(function() { /* TODO: * * 1. When the user clicks and drags on either of the resize targets, * the crop area should resize in an intuitive way. * * 2. When the user clicks and drags on the crop area but not on the * resize targets, the crop area should move in an intuitive way. * * 3. When the user clicks on the Crop! button, display a browser alert * that indicates the boundaries of the crop area, relative to the * container div (don't worry about the native size of the image). * * 4. You don't need to handle touch events. * * 5. You don't need to do anything more style-wise, we are only * interested in the functionality for this task. * * 6. You don't need to actually crop the image. Just alerting * the boundaries of the crop area is sufficient. */ // Initalize variable for mouse dragging var $mouseDown = false; var $dragCropArea = false; // Detect mouse down on either resize target $('.resize').on('mousedown', function() { $mouseDown = true; }); $('.resize').on('mouseup', function() { $mouseDown = false; }); $('.ne').on('mousemove', function(event) { if($mouseDown) { var width = event.pageX - $('.sw').offset().left - 20; $('.croparea').width(width); var height = $('.sw').offset().top + 20 - event.pageY; $('.croparea').height(height); $('.croparea').css('margin-top', (event.pageY - 28)); } }); $('.sw').on('mousemove', function(event) { if($mouseDown) { var width = $('.ne').offset().left + 20 - event.pageX; $('.croparea').width(width); $('.croparea').css('margin-left', event.pageX - 36); var height = event.pageY - $('.ne').offset().top - 20; $('.croparea').height(height); } }); $('.croparea').on('mousedown', function() { $dragCropArea = true; }); $('.croparea').on('mouseup', function() { $dragCropArea = false; }); $('.croparea').on('mousemove', function(event) { if($dragCropArea && !$mouseDown) { var marginLeft = Number($('.croparea').css('margin-left').slice(0, -2)) + event.originalEvent.movementX; $('.croparea').css('margin-left', marginLeft); var marginTop = Number($('.croparea').css('margin-top').slice(0, -2)) + event.originalEvent.movementY; $('.croparea').css('margin-top', marginTop); } }); $('.docrop').click(function() { var width = $('.ne').offset().left - $('.sw').offset().left; var height = $('.sw').offset().top - $('.ne').offset().top; alert('Cropping to width: ' + width + 'px, ' + 'and height: ' + height + 'px'); }); });<file_sep># README ### USE Open up simplecrop.html to crop a picture ![Crop screen cap](http://i.imgur.com/vMzX6UB.jpg)
46312f372f79264be5c00349108c77a25731751a
[ "JavaScript", "Markdown" ]
2
JavaScript
kweng2/image_resize
d439ac201db033e3d184b7e59ef77acf06752ca5
303d66b938cf3305431ec49c6e8dd0f3123ab6f5
refs/heads/master
<repo_name>hxl0131/mp<file_sep>/src/main/java/study/hxl/mp/MpApplication.java package study.hxl.mp; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class MpApplication { public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(MpApplication.class, args); String[] beanDefinitionNames = run.getBeanDefinitionNames(); for (String name : beanDefinitionNames) { System.out.println(name); } System.out.println("haha"); System.out.println("master test1"); System.out.println("hotfix test1"); System.out.println("test push"); System.out.println("test pull"); } } <file_sep>/src/main/java/study/hxl/mp/enums/AgeEnum.java package study.hxl.mp.enums; import com.baomidou.mybatisplus.annotation.IEnum; /** * @author hxl * @Date 2021-07-14 20:03 */ public enum AgeEnum implements IEnum<Integer> { ONE(1, "一年"), TWO(2, "两年"), THREE(3, "三年"); private int value; private String desc; AgeEnum(int value,String desc){ this.value = value; this.desc = desc; } @Override public Integer getValue() { return this.value; } }<file_sep>/src/test/java/study/hxl/mp/MpApplicationTests.java package study.hxl.mp; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import study.hxl.mp.bean.User; import study.hxl.mp.enums.AgeEnum; import study.hxl.mp.mapper.UserMapper; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @SpringBootTest class MpApplicationTests { @Autowired private UserMapper userMapper; @Test void contextLoads() { } @Test public void testInsert(){ // List<User> users = userMapper.selectList(null); // users.forEach(System.out::println); User user = new User(); user.setName("lala"); user.setAge(19); user.setEmail("<EMAIL>"); int insert = userMapper.insert(user); System.out.println(insert); } @Test public void testSelect(){ User user = userMapper.selectById(2); System.out.println(user); } @Test public void testUpdate(){ // User user = new User(); // user.setId(2L); // user.setEmail("<EMAIL>"); // userMapper.updateById(user); User user = new User(); //设置要更新的字段 user.setAge(20); user.setEmail("<EMAIL>"); QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name","Tom");//把数据库表中字段name的值为Tom的数据,更新为user int update = userMapper.update(user, wrapper); System.out.println(update); } @Test public void testUpdate2(){ UpdateWrapper<User> wrapper = new UpdateWrapper<>(); wrapper.set("age",21).set("u_email","<EMAIL>") //更新的字段 .eq("name","haha"); //更新的条件 int update = userMapper.update(null, wrapper); System.out.println(update); } @Test public void testDelete(){ //测试删除 //根据ID删除 // int result = userMapper.deleteById(9L); // System.out.println(result); // 根据wrapper条件删除 //用法1: // QueryWrapper<User> wrapper = new QueryWrapper<>(); // //条件之间隔着and // wrapper.eq("name","haha") // .eq("u_email","<EMAIL>"); //用法2:(推荐使用) User user = new User(); user.setName("lalala"); user.setAge(5); QueryWrapper<User> wrapper = new QueryWrapper<>(user); int delete = userMapper.delete(wrapper); System.out.println(delete); } @Test public void testDeleteByMap(){ Map<String,Object> map = new HashMap<>(); map.put("name","mary"); map.put("u_email","<EMAIL>"); //根据Map删除数据,多条件之间是and关系 int result = userMapper.deleteByMap(map); System.out.println(result); } @Test public void testDeleteBatchIds(){ //根据id批量删除 int delete = userMapper.deleteBatchIds(Arrays.asList(11, 12)); System.out.println(delete); } @Test public void testSelect2(){ //批量查询 List<User> users = userMapper.selectBatchIds(Arrays.asList(2L, 3L, 4L)); users.forEach(System.out::println); } @Test public void testSelectOne(){ QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name","Jack"); //若根据条件查询到的数据有多条,会报异常 User user = userMapper.selectOne(wrapper); System.out.println(user); } //根据条件查询数据的条数 @Test public void testSelectCount(){ QueryWrapper<User> wrapper = new QueryWrapper<>(); //条件可以是eq、gt(大于)、lt(小于)等... wrapper.lt("age","40"); Integer count = userMapper.selectCount(wrapper); System.out.println(count); } @Test public void testSelectList(){ QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("u_email","qq"); List<User> users = userMapper.selectList(wrapper); for (User user : users) { System.out.println(user); } } //分页查询 @Test public void testSelectPage(){ Page<User> page = new Page<>(1,2); QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.lt("age","40"); Page<User> userPage = userMapper.selectPage(page, wrapper); System.out.println("数据总条数:" + userPage.getTotal()); System.out.println("数据总页数:" + userPage.getPages()); System.out.println("当前页数:" + userPage.getCurrent()); List<User> records = userPage.getRecords(); records.forEach(System.out::println); } @Test public void testFindById(){ User user = userMapper.findById(2); System.out.println(user); } @Test public void testAllEq(){ Map<String,Object> params = new HashMap<>(); params.put("name","曹操"); params.put("age",90); params.put("u_email",null); QueryWrapper<User> wrapper = new QueryWrapper<>(); // SELECT id,name,age,u_email AS email FROM tb_user WHERE (u_email IS NULL AND name = ? AND age = ?) // wrapper.allEq(params); // SELECT id,name,age,u_email AS email FROM tb_user WHERE (name = ? AND age = ?) // wrapper.allEq(params,false); // SELECT id,name,age,u_email AS email FROM tb_user WHERE (age = ?) // 意思是,从map中传进来的条件,只有在这个lambda表达式中符合,返回true,才能作为sql的条件进行查询,相当于一个过滤器 wrapper.allEq( (k, v) -> (k.equals("age") || k.equals("id") ), params); List<User> users = this.userMapper.selectList(wrapper); for (User user : users) { System.out.println(user); } } @Test public void testOrderByAgeDesc(){ QueryWrapper<User> wrapper = new QueryWrapper<>(); //按年龄倒序排序 wrapper.orderByDesc("age"); List<User> users = userMapper.selectList(wrapper); for (User user : users) { System.out.println(user); } } @Test public void testOr(){ QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name","Jack").or().eq("age",24); // SELECT id,name,age,u_email AS email FROM tb_user WHERE (name = ? OR age = ?) List<User> users = userMapper.selectList(wrapper); for (User user : users) { System.out.println(user); } } @Test public void testSelectWithOut(){ QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name","Jack") .or() .eq("age",24) .select("id","name","u_email"); // SELECT id,name,u_email FROM tb_user WHERE (name = ? OR age = ?) List<User> users = userMapper.selectList(wrapper); for (User user : users) { System.out.println(user); } } @Test public void testFindAll(){ List<User> users = userMapper.findAll(); for (User user : users) { System.out.println(user); } } @Test public void testInsertWithFill(){ User user = new User(); user.setName("关于"); user.setAge(99); int insert = userMapper.insert(user); System.out.println(insert); } //测试逻辑删除 @Test public void testDeleteLogic(){ // int result = userMapper.deleteById(7L); // UPDATE tb_user SET deleted=1 WHERE id=? AND deleted=0 // System.out.println(result); User user = userMapper.selectById(7L); // SELECT id,name,age,u_email AS email,version,deleted FROM tb_user WHERE id=? AND deleted=0 System.out.println(user); } @Test public void testSelectByEnum(){ QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("create_age",AgeEnum.TWO); // SELECT id,name,age,u_email AS email,version,deleted,create_age FROM tb_user // WHERE deleted=0 AND (create_age = ?) List<User> users = userMapper.selectList(wrapper); for (User user : users) { System.out.println(user); } } @Test public void testhaha(){ System.out.println("haha"); } } <file_sep>/src/test/java/study/hxl/mp/TestMapperAR.java package study.hxl.mp; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import study.hxl.mp.bean.User; import study.hxl.mp.enums.AgeEnum; import java.util.List; /** * @author hxl * @Date 2021-07-14 12:24 */ @SpringBootTest public class TestMapperAR { @Test public void testSelectById(){ User user = new User(); user.setId(2L); User user1 = user.selectById(); System.out.println(user1); } @Test public void testInsert(){ User user = new User(); user.setName("刘备"); user.setAge(80); user.setEmail("<EMAIL>"); //调用AR的insert方法 boolean insert = user.insert(); System.out.println(insert); } @Test public void testUpdate(){ User user = new User(); user.setId(3L); user.setAge(69); boolean update = user.updateById(); System.out.println(update); } @Test public void testDelete(){ User user = new User(); boolean b = user.deleteById(6); System.out.println(b); } @Test public void testSelect(){ User user = new User(); QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.le("age",70); List<User> users = user.selectList(wrapper); for (User u : users) { System.out.println(u); } } @Test public void testUpdateVersion(){ User user = new User(); user.setId(3L); //先查到当前版本,再去修改 User userVersion = user.selectById(); user.setAge(69); //当前的版本信息 如果这个值和数据库中版本不一致,则更新失败 // user.setVersion(1L); // UPDATE tb_user SET age=69, version=2 WHERE id=3 AND version=1 user.setVersion(userVersion.getVersion()); boolean update = user.updateById(); System.out.println(update); } @Test public void testEnum(){ User user = new User(); user.setName("wahaha"); user.setAge(10); user.setEmail("<EMAIL>"); user.setCreateAge(AgeEnum.TWO);//枚举 boolean insert = user.insert(); System.out.println(insert); } }
1a9d85357f1dc619345be3d5bd4bf3595498ede8
[ "Java" ]
4
Java
hxl0131/mp
e78829ad5984e227d5db0a76f24f6c67f203f737
e163649b8effefe95e47ebb760956c065989c939
refs/heads/master
<file_sep>package com.sian0412.privatelocation; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import androidx.core.content.ContextCompat; import android.Manifest; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class Details extends AppCompatActivity { private TextView tvDetailsName,tvDetailsAddress,tvDetailsPhone,tvDetailsRemarkColumn; private ImageButton imgbtnMap,imgbtnPhone; private Intent intent; private String phoneNum; private Context context; private String TAG="Details"; private List<String> unPermissionList = new ArrayList<String>(); //申請未得到授權的許可權列表 private AlertDialog mPermissionDialog = null; private static final int REQUEST_CALL_PHONE = 102; private String mPackName ; private String[] permissionList = new String[]{ //申請的許可權列表 Manifest.permission.CALL_PHONE }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); mPackName = getPackageName(); context = this; findView(); loadDetails(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void findView() { tvDetailsName = (TextView)findViewById(R.id.tvDetailsName); tvDetailsAddress = (TextView)findViewById(R.id.tvDetailsAddress); tvDetailsPhone = (TextView)findViewById(R.id.tvDetailsPhone); tvDetailsRemarkColumn = (TextView)findViewById(R.id.tvDetailsRemarkColumn); imgbtnMap = (ImageButton)findViewById(R.id.imgbtnMap); imgbtnMap.setOnClickListener(clickListener); imgbtnPhone = (ImageButton)findViewById(R.id.imgbtnPhone); imgbtnPhone.setOnClickListener(clickListener); } private void loadDetails() { intent = getIntent(); String name = intent.getStringExtra("name"); String address = intent.getStringExtra("address"); String phone = intent.getStringExtra("phone"); String remark = intent.getStringExtra("remark"); tvDetailsName.setText(name); tvDetailsAddress.setText(address); tvDetailsPhone.setText(phone); tvDetailsRemarkColumn.setText(remark); } private View.OnClickListener clickListener = new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onClick(View v) { switch (v.getId()){ case R.id.imgbtnMap: if(tvDetailsAddress.getText().toString() == null || tvDetailsAddress.getText().toString().equals("")){ Toast.makeText(context,R.string.address,Toast.LENGTH_SHORT).show(); }else{ String url = "https://www.google.com.tw/maps/place/"+tvDetailsAddress.getText().toString(); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); } break; case R.id.imgbtnPhone: if(tvDetailsPhone.getText().toString() == null || tvDetailsPhone.getText().toString().equals("") ){ Toast.makeText(Details.this,R.string.phoneNumber,Toast.LENGTH_SHORT).show(); }else{ phoneNum = tvDetailsPhone.getText().toString(); // 檢查手機版本是否是 6.0(含)以上 if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){ checkPermission(); }else { // 已經是允許 或 6.0以下的版本,就可撥打電話 callPhone(); } } break; } } }; //許可權判斷和申請 @RequiresApi(api = Build.VERSION_CODES.M) public void checkPermission() { unPermissionList.clear(); for(int i=0;i<permissionList.length;i++){ if(ContextCompat.checkSelfPermission(this,permissionList[i])!= PackageManager.PERMISSION_GRANTED){ unPermissionList.add(permissionList[i]); } } if(unPermissionList.size()>0){ requestPermissions(permissionList,REQUEST_CALL_PHONE); Log.i(TAG,"check 有許可權未通過"); }else{ Log.i(TAG,"check 許可權都已經申請通過"); callPhone(); } } public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode,permissions,grantResults); boolean hasPermissionDismiss = false; if(REQUEST_CALL_PHONE == requestCode){ for(int i=0;i<grantResults.length;i++){ if(grantResults[i] == -1){ hasPermissionDismiss = true; Log.i(TAG,"有許可權沒被通過"); break; } } } if(hasPermissionDismiss){//如果有 沒有被允許的許可權 showPermissionDialog(); Log.e("showPermissionDialog","showPermissionDialog"); }else{ //許可權已經通過了 程式可以打開 Log.i(TAG,"onRequestPermissionsResult 都已經申請過"); } } private void showPermissionDialog() { Log.i(TAG,"mPackName"+mPackName); if(mPermissionDialog == null){ mPermissionDialog = new AlertDialog.Builder(this) .setMessage(R.string.no_Permission) .setPositiveButton(R.string.setting, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { cancelPermissionDialog(); Uri packageURI = Uri.parse("package:"+mPackName);//到設定裡面設定 Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,packageURI); startActivity(intent); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //關閉頁面或者其他操作 cancelPermissionDialog(); } }) .show(); } } private void cancelPermissionDialog() { mPermissionDialog.cancel(); } private void callPhone() { Intent intent = new Intent(Intent.ACTION_CALL); Uri data = Uri.parse("tel:" + phoneNum); intent.setData(data); startActivity(intent); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if(item.getItemId() == android.R.id.home){ finish(); } return super.onOptionsItemSelected(item); } }<file_sep># PrivateLocation 口袋名單 利用資料庫 保存自己常去地點 <file_sep>package com.sian0412.privatelocation; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.EditText; import android.widget.TextView; import java.lang.reflect.Field; public class AddLocation extends AppCompatActivity { private EditText etName, etAddress, etPhone, etRemarkColumn; private String name, address, phone, remarkColumn; private Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_location); findView(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void findView() { etName = (EditText) findViewById(R.id.etName); etAddress = (EditText) findViewById(R.id.etAddress); etPhone = (EditText) findViewById(R.id.etPhone); etRemarkColumn = (EditText) findViewById(R.id.etRemarkColumn); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.save_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if(item.getItemId() == android.R.id.home){ finish(); }else{ name = new String(etName.getText().toString().trim()); address = new String(etAddress.getText().toString().trim()); phone = String.valueOf(etPhone.getText().toString().trim()); remarkColumn = new String(etRemarkColumn.getText().toString().trim()); if(name == null || name.equals("")) { AlertDialog.Builder builder = new AlertDialog.Builder(AddLocation.this); builder.setMessage(R.string.restName); builder.setPositiveButton(R.string.ok, null); builder.show(); }else{ PacelableMethod(); } } return super.onOptionsItemSelected(item); } public void PacelableMethod() { LocationData locationData = new LocationData(); locationData.setName(name); locationData.setAddress(address); locationData.setPhone(phone); locationData.setRemarkColumn(remarkColumn); intent = getIntent(); intent.putExtra("locationData", locationData); setResult(RESULT_OK, intent); finish(); } }<file_sep>package com.sian0412.privatelocation; import android.os.Parcel; import android.os.Parcelable; public class LocationData implements Parcelable { public String name; public String address; public String phone; public String remarkColumn; public static final Creator<LocationData> CREATOR = new Creator<LocationData>() { @Override public LocationData createFromParcel(Parcel in) { LocationData mLocationData = new LocationData(); mLocationData.name = in.readString(); mLocationData.address = in.readString(); mLocationData.phone = in.readString(); mLocationData.remarkColumn = in.readString(); return mLocationData; } @Override public LocationData[] newArray(int size) { return new LocationData[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeString(address); dest.writeString(phone); dest.writeString(remarkColumn); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getRemarkColumn() { return remarkColumn; } public void setRemarkColumn(String remarkColumn) { this.remarkColumn = remarkColumn; } }
3ee68f6b0eff5fb296323f5704d3f0bb5aaab20e
[ "Markdown", "Java" ]
4
Java
Sian0412/PrivateLocation
752743221b25e17fa2eab352105a3a17e148ebeb
4d69d617134a79cba25519b3a477a028848ce320
refs/heads/master
<file_sep>// // Movie.cpp // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Getter & Setter ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- string getMovieName() - Returns Movie Title string getDirectorName() - Returns Director's name char getMovieType() - Returns Movie Genre int getReleaseYear() - Returns Released Year int getMovieStock() - Returns Movie DVD stock string getMovieDetails() - Returns string line of "Movie Name: " + movieName + " by " + directorName; bool Return() - Adds the movie stock for returning borrowed DVD bool borrow() - Subtracts the movie stock for borrowing DVD void addMovieStock() - Adds the movie stock, if the movie is already existed during the inserting movie data(Duplicated) ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Default Operator Overloads ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- If the new derived movie classes don't have the overrided operator overloads, these will be executed. ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- virtual bool operator <() virtual bool operator >() virtual bool operator !=() virtual bool operator ==() ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications - This class is the Abstract Class. It contains the core functions & key data that every child movie class requires. Assumption - Assuming that the movie data file is formatted in a given way by professor. */ // -------------------------------------------------------------------------------------------------------------------- #include <stdio.h> #include "Movie.h" using namespace std; /*-------------------Default Constructor--------------------------*/ // Describtion // - Constructs the object with default setting // // Preconditions: No parameters are passed in. // Postconditions: The data variables are set as default value. Movie::Movie() { movieName = ""; directorName = ""; movieType = 0; releaseYear = 0; movieStock = 0; fmovieStock = 0; }; // end of Default Constructor /*---------------------------------------------------------*/ /*------------------- Casting datas to Constructor --------------------------*/ // Describtion // - Constructs a object with the following parameters saved in to the data variables // // Preconditions: Character of movie genre, integer of movie stock, string of director name // string of movie title, and integer of released year are passed in as parameter. // Postconditions: The parameters are saved into the data variables by a given structure. Movie::Movie(char mType, int mStock, string dName, string mName, int relYear) { movieName = mName; directorName = dName; movieType = mType; releaseYear = relYear; movieStock = mStock; fmovieStock = movieStock; }; // end of Constructor /*---------------------------------------------------------*/ /*------------------- Virtual Destructor --------------------------*/ // Describtion // - Needed so movie data are deleted properly // // Preconditions: No parameters are passed in // Postconditions: Will be deleted by BST Movie::~Movie() { } // end of Destructor /*---------------------------------------------------------*/ /*-------------------getMovieName()--------------------------*/ // Describtion // - returns the Title of the movie // // Preconditions: No parameters are passed in // Postconditions: Returns the title of the movie string Movie::getMovieName() const { return this->movieName; } // end of getMovieName /*---------------------------------------------------------*/ /*-------------------getDirectorName()--------------------------*/ // Describtion // - returns the Director's name of the movie // // Preconditions: No parameters are passed in // Postconditions: Returns the Director's name string Movie::getDirectorName() const { return directorName; } // end of getMovieName /*---------------------------------------------------------*/ /*-------------------getMovieType()--------------------------*/ // Describtion // - returns the Movie genre // // Preconditions: No parameters are passed in // Postconditions: Returns the movie genre char Movie::getMovieType() const { return this->movieType; } // end of getMovieType /*---------------------------------------------------------*/ /*-------------------getReleaseYear()--------------------------*/ // Describtion // - returns the released year // // Preconditions: No parameters are passed in // Postconditions: Returns the released year int Movie::getReleaseYear() const { return this->releaseYear; } // end of getReleaseYear /*---------------------------------------------------------*/ /*-------------------getMovieStock()--------------------------*/ // Describtion // - returns the dvd stock of the movie // // Preconditions: No parameters are passed in // Postconditions: Returns the dvd stock of the movie int Movie::getMovieStock() const { return this->movieStock; } // end of getMovieStock /*---------------------------------------------------------*/ /*-------------------getMovieDetails()--------------------------*/ // Describtion // - returns string line of the following information listed below // // Preconditions: No parameters are passed in // Postconditions: Returns the movie title and director's name in string line string Movie::getMovieDetails() const { return "Movie Name: " + movieName + " by " + directorName; } // end of getMovieDetails /*---------------------------------------------------------*/ /*-------------------Return()--------------------------*/ // Describtion // - adds the movie stock for returning the borrowed dvd // // Preconditions: No parameters are passed in // Postconditions: If the movie stock is not negative, adds the stock for returning dvd. bool Movie::Return() { if (movieStock < fmovieStock) { movieStock++; return true; } else { cout << "MOVIE NOT FROM THE STORE" << endl; return false; } }; // end of addMovieStock /*---------------------------------------------------------*/ /*-------------------borrow()--------------------------*/ // Describtion // - subtracts the movie stock for borrowing dvd // // Preconditions: No parameters are passed in // Postconditions: If the movie stock is enough to rent it, subtracts the stock for borrowing dvd. bool Movie::borrow() { if (!(movieStock <= 0)) { movieStock--; return true; } else { cout << "TRANSACTION DENIED! " << movieName << " stock: " << movieStock << endl; return false; } }; // end of subtractMovieStock /*---------------------------------------------------------*/ /*-------------------addMovieStock()--------------------------*/ // Describtion // - adds movie stock if there is a duplicated one during the // inserting the movie data into the BST. // // Preconditions: The stock number is passed in as integer // Postconditions: Adds the movie stock and update. void Movie::addMovieStock(int stock) { movieStock += stock; }; // end of addMovieStock /*---------------------------------------------------------*/ /*-------------------operator <()--------------------------*/ // Describtion // - Compares by title of the movie and released year // // Preconditions: Address of the other movie object is passed in // Postconditions: Compares it by the movie title and the released year bool Movie::operator <(Movie& other) const { // checks general edge case if (other.getMovieName() == "") { return false; } else { // if Title is different // sort by Title if (movieName != other.getMovieName()) { if (this->movieName < other.getMovieName()) { return true; } else { return false; } } // if Title is identicle // then sort by released year else { if (releaseYear < other.getReleaseYear()) { return true; } else { return false; } } } return false; } // end of operator <() /*---------------------------------------------------------*/ /*-------------------operator >()--------------------------*/ // Describtion // - Compares by title of the movie and released year // // Preconditions: Address of the other movie object is passed in // Postconditions: Compares it by the movie title and the released year bool Movie::operator >(Movie& other) const { // checks general edge case if (other.getMovieName() == "") { return false; } else { // if Title is different // just sort by Title if (movieName != other.getMovieName()) { if (this->movieName > other.getMovieName()) { return true; } else { return false; } } // if Title is identicle // then sort by released year else { if (releaseYear > other.getReleaseYear()) { return true; } else { return false; } } } return false; } // end of operator <() /*---------------------------------------------------------*/ /*-------------------operator ==()--------------------------*/ // Describtion // - Compares by title of the movie and released year // // Preconditions: Address of the other movie object is passed in // Postconditions: Compares it by the movie title and the released year bool Movie::operator ==(Movie& other) const { // checks general edge case if (other.getMovieName() == "") { return false; } else { // Must check the Title and the released year // The movie may have same Title but different released year if (this->movieName == other.getMovieName() && this->releaseYear == other.getReleaseYear()) { return true; } else { return false; } } } // end of operator ==() /*---------------------------------------------------------*/ /*-------------------operator !=()--------------------------*/ // Describtion // - Compares by title of the movie and released year // // Preconditions: Address of the other movie object is passed in // Postconditions: Compares it by the movie title and the released year bool Movie::operator !=(Movie& other) const { // checks general edge case if (other.getMovieName() == "") { return false; } else { // compare the Title if (this->movieName != other.getMovieName()) { return true; } else { // if the Titles are identicle // , compare release year if (this->releaseYear != other.getReleaseYear()) { return true; } else { return false; } } } return false; } // end of operator !=() /*---------------------------------------------------------*/ <file_sep>const express = require('express'); const app = express(); const fetch = require('node-fetch'); const path = require('path'); const cookieParser = require('cookie-parser'); const logger = require('morgan'); const azure = require('azure-storage'); const AZURE_STORAGE_CONNECTION_STRING = 'your azure connection string'; app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // serve files from the public directory app.use(express.static('public')); // start the express web server listening on 8080 var port = normalizePort(process.env.PORT || '8081'); app.listen(port, () => { console.log('listening on 8081'); }); // Workers variables to communicate with Azure Storage let tableClient = azure.createTableService(AZURE_STORAGE_CONNECTION_STRING); let blobClient = azure.createBlobService(AZURE_STORAGE_CONNECTION_STRING); // serve the homepage app.get('/', (req, res) => { res.sendFile(__dirname + '/public/index.html'); }); // Reponse to the Query Button app.get('/query', (req, res) => { let reqObj = Object.keys(req.query); let reqArr = []; let tableQ = new azure.TableQuery(); if (reqObj.length == '2') { reqObj.forEach(k => { reqArr.push(req.query[k]); }); console.log(reqArr[0] + " " + reqArr[1]); tableQ = new azure.TableQuery().where('firstName == ? and lastName == ?', reqArr[0], reqArr[1]); } else if (reqObj.length == '1') { let objKey = reqObj[0].toString() let value = req.query[objKey]; if (reqObj[0].toString() == 'lastName') { tableQ = new azure.TableQuery().where('lastName == ?', value); } else { tableQ = new azure.TableQuery().where('firstName == ?', value); } } else { res.send('Incorrect query parameter(s)'); } tableClient.queryEntities('prog4table', tableQ, null, (error, result, response) => { if (!error) { let resEntries = result.entries; let outputArr = []; if (resEntries.length != 0) { resEntries.forEach(entry => { let outputs = {}; Object.keys(entry).forEach(k => { if (k !== ".metadata" && k !== 'PartitionKey' && k !== 'RowKey' && k !== 'Timestamp') { let prop = Object.getOwnPropertyDescriptor(entry, k); if (prop) { outputs[k] = prop.value["_"]; } } }) outputArr.push(outputs); }) res.send(outputArr); } else { res.send('No data found'); } } else { res.send("No data found"); } }) }); // Response to the Load Button app.get('/load', (req, res) => { // Fetch from given url let blobUrl = ''; fetch('https://s3-us-west-2.amazonaws.com/css490/input.txt', { method: 'GET'}) .then(urlResponse1 => { return urlResponse1.text(); }).then(urlResponse2 => { blobUrl = queryBlob(urlResponse2); console.log(blobUrl); }); // Fetch from my azure blob storage setTimeout(() => { fetch(blobUrl, { method: 'GET' }).then(blobResponse1 => { return blobResponse1.text(); }).then(blobResponse2 => { let sortedData = sortData(blobResponse2); entryBuilder(sortedData); res.send(sortedData); }); }, 3000); }); // Response to the Clear Button app.get('/clear', async (req, res) => { tableClient.deleteTable('prog4table', (error, response) => { if (error) { console.log("ERROR AT DELETING TABLE"); } }); blobClient.deleteBlob('program4inputs', 'textblob.txt', (error, response) => { if (!error) { res.status(200).send('Success all data deleted'); } else { console.log(response); res.status(404).send('No data to delete'); return; } }); }); // Add to blob storage function queryBlob(uploadInputs) { blobClient.createBlockBlobFromText('program4inputs', 'textblob.txt', uploadInputs, { contentSettings: { contentType: 'text/plain' } },function(error, result, response) { if (!error) { // file uploaded console.log('load successful'); } }); let url = blobClient.getUrl('program4inputs') + '/textblob.txt'; return url; } // Add entries to table function queryTable(uploadInput) { tableClient.createTableIfNotExists('prog4table', (error, result, response) => { if (!error) { console.log('table exist!'); tableClient.insertEntity('prog4table', uploadInput, (error, result, response) => { if (!error) { console.log('success add entry'); } else { console.log(response); } }); } else { console.log(response); } }); } //Create an entry that can be used to insert onto table storage function entryBuilder(inputData) { let entGen = azure.TableUtilities.entityGenerator; console.log(inputData); let lines = inputData.split('\n'); for (let i = 0; i < lines.length - 1; i++) { let lineArr = lines[i].split(' '); let jsonObj = { PartitionKey: entGen.String(lineArr[0] + lineArr[1]), RowKey: entGen.String(i.toString()) }; for (let j = 0; j < lineArr.length; j++) { if (lineArr[j].includes('=')) { let keyvalue = lineArr[j].split('='); if (keyvalue[0] != null && keyvalue[1] != null) { jsonObj[keyvalue[0]] = entGen.String(keyvalue[1]); } else if (lineArr[0] != null) { jsonObj[keyvalue[0]] = entGen.String(''); } } else if (j == 0) { jsonObj['lastName'] = entGen.String(lineArr[j]); } else if (j == 1) { jsonObj['firstName'] = entGen.String(lineArr[j]); } } queryTable(jsonObj); } } // Elimnates extra spaces function sortData(inputData) { let lines = inputData.split('\n'); let newString = ''; for (let i = 0; i < lines.length - 1; i++) { let newline = lines[i].replace(/\s+/g, ' ').trim(); newString += newline + '\n'; } console.log(newString); return newString; } function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } <file_sep>import java.util.*; public class SyncQueue { private Vector<QueueNode> tQueue; private final int MAXSIZE = 10; public SyncQueue() { tQueue = new Vector<QueueNode>(MAXSIZE); for (int i = 0; i < MAXSIZE; i++) { QueueNode tempNode = new QueueNode(); this.tQueue.add(i,tempNode); } } public SyncQueue(int max) { tQueue = new Vector<QueueNode>(max); for (int i = 0; i < max; i++) { QueueNode tempNode = new QueueNode(); this.tQueue.add(i,tempNode); } } public int enqueueAndSleep(int condi) { return this.tQueue.get(condi).sleep(); } public void dequeueAndWakeup(int condi) { this.dequeueAndWakeup(condi, 0); } public void dequeueAndWakeup(int condi, int tid) { this.tQueue.get(condi).wakeup(tid); } }<file_sep>// // DamaMovie.h // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Overriding Operator Overloads ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- The Drama is sorted by the Director's name and the Title of the movie. The comparisons are based on Director's name and the Title of the movie. ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- virtual bool operator <() virtual bool operator >() virtual bool operator !=() virtual bool operator ==() ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications - The DramaMovie class is a child class of the Movie class. It has the access to the parents class's public functions and protected data - When "cout <<," the first two information are one that used on sorting. Rest of the information will be printed inisde of the bracket. Assumption - Assuming that the movie data file is formatted in a given way by professor. */ // -------------------------------------------------------------------------------------------------------------------- #include"Movie.h" #ifndef DramaMovie_h #define DramaMovie_h class DramaMovie : public Movie { public: // Constructor & Destructor DramaMovie(); // default constructor DramaMovie(const char movieType, int movieStock, const string derName, const string movieName, int releaseYear); // data is set equal to parameter virtual ~DramaMovie(); // Operator Overloads bool operator <(DramaMovie& other) const; bool operator >(DramaMovie& other) const; bool operator ==(DramaMovie& other) const; bool operator !=(DramaMovie& other) const; friend ostream& operator <<(ostream& out, DramaMovie& other); private: }; #endif <file_sep>using System; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Collections.Generic; namespace HTTPGet { // Global Variables static class Global { public static HashSet<string> vistedURIs = new HashSet<string>(); public static Regex parser = new Regex("(?<=<a href=\")(.*?)(?=\")"); public static Stack<string> tempURIs = new Stack<string>(); public static Stack<string> vistedHTML = new Stack<string>(); public static bool run = true; } class Program { //Take care of uri that either trailing fowardslash or doesn't static bool trailingCheck(string current) { if(current[current.Length-1] == '/') { string temp = current.Substring(0, current.Length - 1); if (Global.vistedURIs.Contains(temp)) { return false; } else { return true; } } else { string temp = current; temp = temp.Insert(temp.Length, "/"); if (Global.vistedURIs.Contains(temp)) { return false; } else { return true; } } } //Goes through the html page and find the next uri static string crawl(string htmlContent) { // only crawl when the its a 200 respond Match mat = Global.parser.Match(htmlContent); string current = ""; while (mat.Success) { current = mat.Value.ToString(); if (current.Length > 4 && current.Substring(0,4) == "http" && (!Global.vistedURIs.Contains(current)) && trailingCheck(current)) { Global.vistedURIs.Add(current); Global.tempURIs.Push(current); return current; } else { mat = mat.NextMatch(); } } return current; } static string backTrack() { if(Global.tempURIs.Count != 0) { return Global.tempURIs.Pop(); } else { Global.run = false; return ""; } } //Main fuction static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Invalid Input"); return; } using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate })) { string currentURI = args[0]; int maxHops = Int32.Parse(args[1]); Console.WriteLine("Starting URI: " + args[0] + " Max Hops: " + args[1]); Global.vistedURIs.Add(currentURI); Global.tempURIs.Push(currentURI); string nextURI = currentURI; while (maxHops >= 0 && Global.run) { try { //Visiting website HttpResponseMessage response = client.GetAsync(nextURI).Result; string result = response.Content.ReadAsStringAsync().Result; Global.vistedHTML.Push(result); int status = (int)response.StatusCode; if(status == 200) { // Console.WriteLine(status); currentURI = nextURI; nextURI = crawl(result); if(nextURI == "") { nextURI = backTrack(); } Console.WriteLine(maxHops+ " NEXT URL: " + nextURI); maxHops--; } else if (status == 301) { // Console.WriteLine(status); nextURI = backTrack(); } else { Console.WriteLine(status); return; } } //404 expections catch (System.AggregateException) { Console.WriteLine("REDIRECTING"); nextURI = backTrack(); } } //Printing out the results while (Global.vistedHTML.Count > 0) { Console.WriteLine(Global.vistedHTML.Pop()); } foreach (var item in Global.vistedURIs) { Console.WriteLine(item); } } } } } <file_sep>- Please put Retriever on csslab1.uwb.edu and Server on csslab3.uwb.edu. - For the script to work effectively please keep the follow structure: mySubmissionFolder --> build.sh testRealServerScript.sh testServerScript.sh retrieverDir/ serverDir/ - The port number I used for the script is 1499 - Thankyou<file_sep><!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title><NAME> Homework 1</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <h1>Jun's Favorite Foods</h1> <h2>Pho</h2> <p>A vietnamese soup consisting of broth, rice noodles, herbs, and meat</p> <img src="./imgs/500px-Pho-Beef-Noodles-2008.jpg" alt="Trulli" width="500" height="333"> <br> <b> Recipes </b> <ul> <li>Preheat oven to 425 degrees F (220 degrees C). </li> <li>Place beef bones on a baking sheet and roast in the preheated oven until browned, about 1 hour.</li> <li>Place onion on a baking sheet and roast in the preheated oven until blackened and soft, about 45 minutes. </li> <li>Place bones, onion, ginger, salt, star anise, and fish sauce in a large stockpot and cover with 4 quarts of water. Bring to a boil and reduce heat to low. Simmer on low for 6 to 10 hours. Strain the broth into a saucepan and set aside. </li> <li>Place rice noodles in large bowl filled with room temperature water and allow to soak for 1 hour. Bring a large pot of water to a boil and after the noodles have soaked, place them in the boiling water for 1 minute. Bring stock to a simmer. </li> <li>Divide noodles among 4 serving bowls; top with sirloin, cilantro, and green onion. Pour hot broth over the top. Stir and let sit until the beef is partially cooked and no longer pink, 1 to 2 minutes. Serve with bean sprouts, Thai basil, lime wedges, hoisin sauce, and chile-garlic sauce on the side. </li> </ul> <br> <h3>Beef Noodle Soup</h3> <p>A noodle soup made of stewed or red braised beef, beef broth, vegetables and Chinese noodles</p> <img src="./imgs/beefnodle.jpeg" alt="Trulli" width="450" height="300"> <br> <i> Instructions </i> <ol> <li>Cut beef into larger chunks and then place in a large pot with enough cold water. Throw one spring onion and several ginger slices, bring to a boil and then pick the beef chunks out (so there will be no floating dirt on the meat and we can skip rinsing process.) Drain. </li> <li>Heat up around 2 tablespoons of oil in a deep stewing pot and fry doubanjiang for half minute over slow fire, then place garlic, ginger, leek onion and red onion in, fry until aromatic.</li> <li>Return cooked beef and stir for several minutes until the beef is slightly browned, place tomato wedges and add warm stock to cover all the content. Bring to boil and then slow down the fire and simmer for around 1 hour.</li> <li>Pick the beef out and strain the liquid to remove cooked vegetables and spices, add salt to taste (the soup can be slightly salty compare with common soups)and simmer for another 15-20 minutes.</li> <li>During this period, cook noodles according to package instructions. You can either serve wide noodles or thin noodles. Transfer noodles to serving bowl, pour in soup base and top with beef. Garnish chopped green onion and decorate with coriander.</li> </ol> <br> <h4>Ramen</h4> <p>is a Japanese dish consists of Chinese wheat noodles served in a meat or fish-based broth, often flavored with soy sauce or miso, and uses toppings such as sliced pork, nori, menma, and scallions</p> <img src="./imgs/500px-Shoyu_Ramen.jpg" alt="Trulli" width="400" height="266"> <br> <b> Recipes </b> <ul> <li>Roast the chicken wings. Arrange a rack in the middle of the oven and heat to 425°F. Place the chicken wings in a stovetop-safe roasting pan or casserole dish and roast until well-browned, about 30 minutes. Reduce the heat to 375°F, add the carrots and scallions, and stir to combine. Roast for 20 minutes more.</li> <li>Deglaze the roasting pan. Transfer the chicken and vegetables to a stockpot. Place the now-empty roasting pan on the stovetop over high heat. Add 2 cups of the water and, stirring and scraping vigorously with a heatproof or metal spoon, scrape up all the flavorful browned bits from the bottom of the pan. Bring to a boil, then carefully pour the mixture into the stockpot.</li> <li>Amp up the aromatics. Add the garlic, ginger, shiitakes, kombu, and remaining 8 cups of water to the pot and stir to combine. Bring just to a simmer over high heat — just a few bubbles around the edges.</li> <li>Simmer the broth. Reduce the heat as low as your stove will allow, add the soy sauce, and simmer uncovered, occasionally skimming the fat and scum that accumulates on the surface, until the chicken has fallen completely off the bone and the wing bones come apart easily, 3 to 3 1/2 hours.</li> <li>Strain the broth. Pour the broth through a fine-mesh strainer into a large bowl; discard the solids. Cool the broth to room temperature, then cover and refrigerate overnight. Before using, skim the fat off the surface and discard.</li> <li>Make the tare. Combine the soy sauce and mirin in a small airtight container, seal, and refrigerate until ready to use.</li> </ul> <br> <h5>Tacos</h5> <p>A traditional Mexican dish consisting of a small hand-sized corn or wheat tortilla topped with a filling.</p> <img src="./imgs/440px-001_Tacos_de_carnitas.jpg" alt="Trulli" width="350" height="233"> <br> <b> Instructions </b> <ol> <li>Fill the taco shells with 2 heaping tablespoons of taco meat. Top with desired taco toppings: shredded cheese, shredded lettuce, chopped tomatoes, diced red onion, taco sauce, sour cream, guacamole, etc.</li> <li>Add the beef to a large skillet over medium-high heat. Break the meat apart with a wooden spoon. Add the chili powder, cumin, salt, oregano, garlic powder, and pepper to the meat. Stir well. Cook until the meat is cooked through, about 6-8 minutes, stirring occasionally.</li> <li>Reduce the heat to medium. Add the tomato sauce and water. Stir to combine. Cook, stirring occasionally, for 7-8 minutes, until some of the liquid evaporates but the meat mixture is still a little saucy. Remove from the heat.</li> <li>Warm the taco shells according to their package directions.</li> </ol> <br> <h6>Hashbrown and Omlete</h6> <p>Popular American breakfast dish in which potatoes are pan-fried after being shredded, diced. Served with eggs</p> <img src="./imgs/southwest-hashbrown-omelet.jpg" alt="Trulli" width="300" height="200"> <br> <b> Recipes </b> <ul> <li> Shred potatoes into a large bowl filled with cold water. Stir until water is cloudy, drain, and cover potatoes again with fresh cold water. Stir again to dissolve excess starch. Drain potatoes well, pat dry with paper towels, and squeeze out any excess moisture.</li> <li> Heat clarified butter in a large non-stick pan over medium heat. Sprinkle shredded potatoes into the hot butter and season with salt, black pepper, cayenne pepper, and paprika.</li> <li>Cook potatoes until a brown crust forms on the bottom, about 5 minutes. Continue to cook and stir until potatoes are browned all over, about 5 more minutes.</li> </ul> </body> </html><file_sep>Notes: - I used the provided description file to run my generator script. - The result is not the same as the example provided due to the different arrangment of states. - The hardest part is the formating the generated .cpp file. - It was also difficult to compare/debug my solution with the example because the formating was all over the place. How to run: - Make sure the description file import fsm.py #import fsm - run description file #HOS.py<file_sep>//<NAME> //CSS432 //HW1 //10-11-2019 #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <string.h> #include <netinet/tcp.h> #include <stdio.h> #include <sys/uio.h> #include <pthread.h> #include <stdlib.h> #include <errno.h> //Global variables for the thread function const int BUFFSIZE = 1500; int repetition; //Takes in a void pointer to the File Descriptor, //the function's argument is where we will read and write the data to/from void* action(void* args) { //Casting the void pointer back to int pointer so we can deference to get the file descriptor int* sockPtr = (int*) args; char buffer[BUFFSIZE]; int count = 0; //Marking the amount of time to read the batch of data struct timeval timer, endTimer; gettimeofday(&timer, NULL); for ( int i = 0; i <= repetition; i++ ) { //This loop is to ensure we read all the data from client for ( int numberRead = 0; (numberRead += read(*sockPtr , buffer , BUFFSIZE - numberRead)) < BUFFSIZE; ++count); count++; } //Formating the time gettimeofday(&endTimer,NULL); long a = (endTimer.tv_sec - timer.tv_sec) * 1000000 + endTimer.tv_usec - timer.tv_usec; //Write back to client and print out information write(*sockPtr, &count , sizeof(int)); printf("Amount read: %d\n",count); printf("Lap-trip time: %d\n", a); close(*sockPtr); } int main(int argc, char **argv) { //Setting up the server repetition = atoi(argv[2]); int on = 1; int serSock, cliSock; struct sockaddr_in server, client; if((serSock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Error at Socket"); exit(-1); } server.sin_family = AF_INET; server.sin_port = htons(atoi(argv[1])); server.sin_addr.s_addr = INADDR_ANY; bzero(&server.sin_zero, 0); //Request the OS to release the socket once program finish running setsockopt(serSock, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(int)); if( bind(serSock,(struct sockaddr*)&server, sizeof(server)) == -1) { perror("Error at Bind"); exit(-1); } socklen_t len = sizeof(client); //Infinite loop because we want the server to continue to serve any client coming in while(1) { if((listen(serSock,5)) == -1) { perror("Error at Listen"); exit(-1); } printf("Listening\n"); if((cliSock = accept(serSock,(struct sockaddr*)&client, &len)) == -1) { perror("Error at Accept"); exit(-1); } printf("Connected to: %s\n",inet_ntoa(client.sin_addr)); //Create a new thread per client conncted to the server //The program will wait until all the threads finish excuting before closing pthread_t newthread; if((pthread_create(&newthread, NULL, action, &cliSock)) < 0) { perror("Error at pThread"); exit(-1); }; pthread_join(newthread, NULL); printf("\n"); } return 0; } <file_sep># <NAME> # CSS 436 Cloud Computing # 02-16-20 # ass3Backup.py - Take in folder name as an argument and make a backup to the cloud of the specified directory # to AWS and maintain the file structure import boto3 import logging from botocore.exceptions import ClientError import hashlib import os import sys import time # Global variables s3 = boto3.resource("s3") bucketName = "1950386css436prog3" regionName = "us-west-2" currentDir = "./" # Create bucket def makeBucket(bucket_name, region): try: s3_client = boto3.client('s3', region) location = {'LocationConstraint': region} s3_client.create_bucket(Bucket=bucket_name, CreateBucketConfiguration=location) except ClientError as e: logging.error(e) return False return True #Print out all the buckets in s3 def printAllBuckets(): for bucket in s3.buckets.all(): print("Bucket: ", bucket.name) print("--------") for key in bucket.objects.all(): print(key.key) print("") #Helper function for getLocalChecksum, return file.read() def readFile(fileName): with fileName: return fileName.read() #Get the checksum of the file passed in def getLocalChecksum(fileName): return hashlib.md5(readFile(open(fileName, "rb"))).hexdigest() # Local into the s3 bucket and find its checksum value stored as metadata def getS3Checksum(fileName): return(s3.Object(bucketName,fileName).get()["Metadata"]["sumvalue"]) # Main function that utitlize os.walk to backup files and folder into aws s3 def Backup(path): transfer = boto3.client("s3") for dirName, subdirList, fileList in os.walk(path): # print('Found directory: %s' % dirName) for fname in fileList: #Full path fullpath = os.path.join(dirName,fname) #key gets rid of the root ("./") directory key = fullpath #Get the check sum of the file we going to store in s3 checksumValue = getLocalChecksum(fullpath) # Only insert if s3 and local don't have matching files if (checkObjExists(key)): if (checksumValue != getS3Checksum(key)): print("Updating Backing up:", fname) transfer.upload_file(key, Key=key, ExtraArgs= {"Metadata":{"sumValue": checksumValue}}, Bucket=bucketName) else: print("Backing up:", fname) transfer.upload_file(key, Key=key, ExtraArgs= {"Metadata":{"sumValue": checksumValue}}, Bucket=bucketName) # Check if object exists def checkObjExists(key): try: s3.Object(bucketName, key).load() except ClientError as e: return False return True # Main Fuction if __name__ == "__main__": print("BACKING UP") try: s3.meta.client.head_bucket(Bucket=bucketName) print("Bucket %s Already Exists" % (bucketName)) except ClientError: if (makeBucket(bucketName, regionName)): print("Successful Creating Bucket: %s!!!" % (bucketName)) else: print("Unsuccessful Creating Bucket: %s... " % (bucketName)) path = sys.argv[1] Backup(path) # This might crash due to the time it takes for aws to create bucket and load objects if that's the case please run # it again or uncommon the sleepe timer during the first run. printAllBuckets() <file_sep>#include <iostream> #include "UdpSocket.h" #include "Timer.h" using namespace std; class udphw3 { public: int clientStopWait( UdpSocket &sock, const int max, int message[] ); int clientSlidingWindow( UdpSocket &sock, const int max, int message[], int windowSize ); void serverReliable( UdpSocket &sock, const int max, int message[] ); void serverEarlyRetrans( UdpSocket &sock, const int max, int message[], int windowSize ); };<file_sep>import sys import time import random from urllib import error from urllib import request # Store cmd line args url = sys.argv[1] rps = int(sys.argv[2]) jitter = float(sys.argv[3]) #calculate the range with the jitter #continue hit the server with different probabilities of requets while True: jitRps = random.randint(int(rps * (1 - jitter)), int(rps * (1 + jitter))) start = time.time() for i in range(jitRps): chance = random.randint(0, 100) try: if chance in range(0,25): request.urlopen(url + '/garabge', timeout= 10000) #404 elif chance in range(26, 51): request.urlopen(url + '/fail', timeout= 10000) #500 else: request.urlopen(url, timeout= 10000) #200 except error.HTTPError: continue time.sleep(1) <file_sep>#include "bintree.h" //------------------------- Defualt Constructor --------------------------------- // Initialize Tree // Preconditions: None // Postconditions: None BinTree::BinTree() { root = NULL; } //------------------------- Copy Constructor --------------------------------- // Initialize Tree and copy parameter's value // Preconditions: Parameter tree must not be empty // Postconditions: Same value as the parameter BinTree::BinTree(const BinTree& tree) { root = NULL; *this = tree; } //------------------------- Destructor --------------------------------- // Free up all allocated memories and remove tree // Preconditions: Parameter tree must not be empty // Postconditions: Tree must be empty BinTree::~BinTree() { if (root == NULL) { return; } else { this->makeEmpty(); } } //------------------------- isEmpty --------------------------------- // Check if tree is empty or not // Preconditions: None // Postconditions: None bool BinTree::isEmpty() const { if (root == NULL) { return true; } else { return false; } } //------------------------- findNode --------------------------------- // Search the tree to find the value given by parameter // Preconditions: Tree must not be empty // Postconditions: Holder will point to the value in the tree bool BinTree::findNode(NodeData& value, Node* node, Node*& holder) const { if (node == NULL) { return false; } else if (*node->data == value) { holder = node; return true; } else { return findNode(value, node->left, holder) || findNode(value, node->right, holder); } } //------------------------- operator!= --------------------------------- // Check two tree if there are equal or not // Preconditions: None // Postconditions: None bool BinTree::operator!=(const BinTree& otherTree) const { return !(*this == otherTree); } //------------------------- operator!= --------------------------------- // Check two tree if there are equal or not // Preconditions: None // Postconditions: None bool BinTree::operator==(const BinTree& otherTree) const { if (this->isEmpty() || otherTree.isEmpty()) { return false; } else if (this->isEmpty() || otherTree.isEmpty()) { return true; } else { return compareTree(root, otherTree.root); } } //------------------------- compareTree --------------------------------- // Check two tree if there are equal or not // Preconditions: None // Postconditions: None bool BinTree::compareTree(Node* node1, Node* node2) const { if ((node1 == NULL && node2 == NULL)) { return true; } else if ((node1 != NULL && node2 == NULL) || (node1 == NULL && node2 != NULL)) { return false; } else if (*node1->data == *node2->data) { return compareTree(node1->left, node2->left) && compareTree(node1->right, node2->right); } else { return false; } } //------------------------- operator= --------------------------------- // Assigning operator, copy the values of parameter to itself // Preconditions: Must not be the same tree // Postconditions: None BinTree& BinTree::operator=(const BinTree& otherTree) { if (*this != otherTree) { this->makeEmpty(); copyTree(otherTree.root); } return *this; } bool BinTree::copyTree(const Node* node) { if (node) { this->insert(node->data); copyTree(node->left); copyTree(node->right); return true; } else { return false; } } //------------------------- makeEmpty --------------------------------- // Empty out the whole tree and set root to null // Preconditions: None // Postconditions: None void BinTree::makeEmpty() { if (root != NULL) { makeEmptyHelper(root); } } void BinTree::makeEmptyHelper(Node* node) { if (node == NULL) { return; } makeEmptyHelper(node->left); makeEmptyHelper(node->right); delete node; root = NULL; } //------------------------- arrayToBSTree --------------------------------- // Store all the data in a array into an tree // Preconditions: Tree must be empty and array must not be empty // Postconditions: array must be empty void BinTree::arrayToBSTree(NodeData* arr[]) { if (root == NULL) { int n = countArraySize(arr); arrayToBSTreeHelper(root, 0, n - 1, arr); } else { this->isEmpty(); int n = countArraySize(arr); arrayToBSTreeHelper(root, 0, n - 1, arr); } } void BinTree::arrayToBSTreeHelper(Node* node, int begin, int end, NodeData* arr[]) { if (begin > end) { node = NULL; } else { int middle = (end + begin) / 2; insert(arr[middle]); arr[middle] = NULL; int firstEnd = middle - 1; int secondStart = middle + 1; arrayToBSTreeHelper(node, begin, firstEnd, arr); arrayToBSTreeHelper(node, secondStart, end, arr); } } //------------------------- countArraySize --------------------------------- // Count how many elements in the array // Preconditions: none // Postconditions: none int BinTree::countArraySize(NodeData* arr[]) { int count = 0; while (arr[count] != NULL) { count++; } return count; } //------------------------- bstreeToArray --------------------------------- // Store all the data in a tree into an array with inorder traversal // Preconditions: Array must be empty and Tree must not be empty // Postconditions: Tree must be empty void BinTree::bstreeToArray(NodeData* arr[]) { bstreeToArrayHelper(root, arr); makeEmpty(); } int BinTree::bstreeToArrayHelper(Node* node, NodeData* arr[]) { if (node != NULL) { int before = bstreeToArrayHelper(node->left, arr); NodeData* tempIns; tempIns = node->data; node->data = NULL; *(arr + before) = tempIns; tempIns = NULL; int newAdd = before + 1; int after = bstreeToArrayHelper(node->right, arr + newAdd); return 1 + after + before; } return 0; } //------------------------- getHeight --------------------------------- // Get the height of the a node // Preconditions: tree must not be negative // Postconditions: none int BinTree::getHeight(const NodeData& value) const { Node* current; NodeData v = value; if (this->findNode(v, root, current)) { return getHeightHelper(current); } else { return 0; } } int BinTree::getHeightHelper(Node*& node) const { if (node == NULL) { return 0; } else { return max(getHeightHelper(node->left), getHeightHelper(node->right)) + 1; } } //------------------------- retrieve --------------------------------- // Find the corrsponding node value and link it with parameter // Preconditions: tree must not be negative // Postconditions: parameter ptr will point to the node bool BinTree::retrieve(const NodeData& value, NodeData*& holder) { if (root != NULL) { return retrieveHelper(root, value, holder); } else { return false; } } bool BinTree::retrieveHelper(Node*& node, const NodeData& value, NodeData*& holder) { if (*node->data == value) { holder = node->data; return true; } else if (*node->data > value && node->left != NULL) { return retrieveHelper(node->left, value, holder); } else if (*node->data < value && node->right != NULL) { return retrieveHelper(node->right, value, holder); } else { return false; } } //------------------------- insert --------------------------------- // Insert the given value into the tree // Preconditions: No duplicates // Postconditions: value is inserted in the correct position bool BinTree::insert(NodeData* newData) { return insertHelper(root, newData); } bool BinTree::insertHelper(Node*& node, NodeData* newData) { if (node == NULL) { node = new Node(newData); return true; } else if (*node->data > * newData) { return insertHelper(node->left, newData); } else if (*node->data < *newData) { return insertHelper(node->right, newData); } else { return false; } } //------------------------- operator<< --------------------------------- // Print out the tree's value with inorder traversal // Preconditions: No duplicates // Postconditions: value is inserted in the correct position ostream& operator<<(ostream& out, const BinTree& tree) { tree.inorderHelper(tree.root); return out << endl; } void BinTree::inorderHelper(Node* node) const { if (node == NULL) { return; } inorderHelper(node->left); cout << *node->data << " "; inorderHelper(node->right); } //------------------------- displaySideways --------------------------------- // Displays a binary tree as though you are viewing it from the side; // hard coded displaying to standard output. // Preconditions: NONE // Postconditions: BinTree remains unchanged. void BinTree::displaySideways() const { sideways(root, 0); } //---------------------------- Sideways ------------------------------------- // Helper method for displaySideways // Preconditions: NONE // Postconditions: BinTree remains unchanged. void BinTree::sideways(Node* current, int level) const { if (current != NULL) { level++; sideways(current->right, level); // indent for readability, 4 spaces per depth level for (int i = level; i >= 0; i--) { cout << " "; } cout << *current->data << endl; // display information of object sideways(current->left, level); } } <file_sep>/* <NAME> CSS430 Shell.java */ #include<stdio.h> #include<stdlib.h> #include<sys/wait.h> #include<unistd.h> int main(int argc, char** argv) { //Creating file Descriptors and two pipes int fd[2]; int fd2[2]; pipe(fd); pipe(fd2); //Creating a new process pid1 = child pid_t pid1 = fork(); if (pid1 == 0) { //pid2 = grandchild pid_t pid2 = fork(); if(pid2 == 0) { //Redirect the standard output to pipe 2's write side dup2(fd2[1], STDOUT_FILENO); close(fd2[1]); close(fd2[0]); close(fd[1]); close(fd[0]); //Change this process to execute "ps" execlp("ps", "ps","-A",NULL); } else { //Child will wait for the grandchild pid_t wait(pid2); //Change the standard input to pipe 2's read side dup2(fd2[0], STDIN_FILENO); close(fd2[0]); close(fd2[1]); //Change the standard output to pipe 1's write side dup2(fd[1], STDOUT_FILENO); close(fd[1]); close(fd[0]); //Change this process to execute "grep" execlp("grep", "grep", argv[1], NULL); } } else { //The parent wait for the child pid_t wait(pid1); //Change the standard input to pipe 1's read side dup2(fd[0], STDIN_FILENO); close(fd[0]); close(fd[1]); close(fd2[0]); close(fd2[1]); //Change this process to execute "wc" execlp("wc", "wc","-l",NULL); } }<file_sep>//<NAME> //CSS432 //HW1 //10-11-2019 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/time.h> int main(int argc, char **argv) { //Arguments from commandline int PORT = atoi(argv[1]); int repetition = atoi(argv[2]); int NBUFF = atoi(argv[3]); int BUFFSIZE = atoi(argv[4]); char* serveIp = argv[5]; int type = atoi(argv[6]); //Establish the connection with server struct hostent* host = gethostbyname(argv[5]); struct sockaddr_in sendSockAddr; bzero((char*)& sendSockAddr, sizeof(sendSockAddr)); sendSockAddr.sin_family = AF_INET; sendSockAddr.sin_addr.s_addr = inet_addr( inet_ntoa( *(struct in_addr*)*host->h_addr_list )); sendSockAddr.sin_port = htons(PORT); int clientSd = socket(AF_INET, SOCK_STREAM, 0); if(connect(clientSd, (sockaddr*)&sendSockAddr,sizeof(sendSockAddr))) { perror("ERROR on connect"); exit(1); } //Once connection establish, marking the time of transmittion struct timeval begin, lap, finish; gettimeofday(&begin, NULL); char buffer [NBUFF][BUFFSIZE]; //Using loop to write big amount of data. Depending on the argument, //it will use different method of writing to the server for(int i = 0; i <= repetition; i++) { if(type == 1) { for ( int j = 0; j < NBUFF; j++ ) { write(clientSd, buffer[j], sizeof(buffer[j])); } } else if(type == 2) { struct iovec vector[NBUFF]; for ( int j = 0; j < NBUFF; j++ ) { vector[j].iov_base = buffer[j]; vector[j].iov_len = BUFFSIZE; } writev(clientSd, vector, NBUFF); } else if(type == 3) { write(clientSd, buffer, NBUFF *BUFFSIZE); } else { printf("ERROR on Input\n"); exit(-1); } } //Record the time of writing gettimeofday(&lap, NULL); //Server writing back and record the time int n; read(clientSd,&n,sizeof(int)); gettimeofday(&finish, NULL); //Formatting the output long lapn = (lap.tv_sec - begin.tv_sec) * 1000000 + lap.tv_usec - begin.tv_usec; long finishn = (finish.tv_sec - begin.tv_sec) * 1000000 + finish.tv_usec - begin.tv_usec; printf("Type: %d Lap: %d Finish: %d ",type,lapn,finishn); printf("Time Server Read: %d\n",n); return 0; }<file_sep>#! /bin/bash python3 ass3Backup.py testingObjects<file_sep>/* <NAME> CSS 436 Cloud Computing A program that takes in a city name as an arguement and will consume at least 2 RESTful API to make a meaningful report about the city. The program utilize an exponetial backoff mechanism when it fails to reach an API endpoint to ensure no crashing. */ using System; using System.Net.Http; using Newtonsoft.Json; using System.Threading; using System.Collections.Generic; namespace Program { public class ass2 { static void Main(string[] args) { //Data fields string city = System.Web.HttpUtility.UrlPathEncode(args[0]); string weatherURI = "http://api.openweathermap.org/"; string geoURI = "http://geodb-free-service.wirefreethought.com/"; //Try Catch to ensure failed api requests try { //Requesting Open Weather Map's api to get information regarding to the weather WeatherReport weatherDetails = JsonConvert.DeserializeObject<WeatherReport>(getCityInfo(city,"", weatherURI, 2)); Console.WriteLine("Weather Report of " + weatherDetails.name + " " + weatherDetails.sys.country); Console.WriteLine(" Coordinates: " + weatherDetails.coord.lat + ", " + weatherDetails.coord.lon); Console.WriteLine(" Weather: " + weatherDetails.weather[0].description); Console.WriteLine(" Temperature: " + ((int) ((weatherDetails.main.temp - 273.15) * 1.8 + 32)) + " degrees Fahrenhit"); Console.WriteLine(" Feels Like: " + ((int) ((weatherDetails.main.feels_like - 273.15) * 1.8 + 32)) + " degrees Fahrenhit"); Console.WriteLine(" Humidity: " + weatherDetails.main.humidity + "%"); Console.WriteLine(" Wind Speed: " + weatherDetails.wind.speed); //Requesting the GeoDB's API to the city's details RootObject cityDetails = JsonConvert.DeserializeObject<RootObject>(getCityInfo(city,"", geoURI, 0)); CityInfo cityInfo = cityDetails.data[0]; string latlon = getCoords(cityInfo); NearByCitiesList cityList = JsonConvert.DeserializeObject<NearByCitiesList>(getCityInfo(city, latlon, geoURI,1)); Console.WriteLine("Cities Near By " + weatherDetails.name + " " + weatherDetails.sys.country); for (int i = 1; i < cityList.data.Count; i++) { Console.WriteLine(" City " + i + ": " + cityList.data[i].name + " " + cityList.data[i].countryCode + ", distance from " + weatherDetails.name + " " + weatherDetails.sys.country + ": " + cityList.data[i].distance + " miles"); } Console.WriteLine(""); } catch (Newtonsoft.Json.JsonReaderException) { Console.WriteLine("NO DATA RETURN"); } catch (System.NullReferenceException) { Console.WriteLine("NO DATA RETURN"); } } // Return the full coordinates a city static string getCoords(CityInfo c) { string s = ""; string latlon = ""; if(c.longitude > 0) latlon = c.latitude.ToString(s) + "+" + c.longitude.ToString(s); else latlon = c.latitude.ToString(s) + c.longitude.ToString(s); return latlon; } // Return the result after an api call. Depending on the api number paramter, // it will return either OpenWeather or GeoDB results static string getCityInfo(string cityName, string coords, string uri, int apiNum) { int status = 0; for (int i = 0; i < 5; i++) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(uri); HttpResponseMessage response = new HttpResponseMessage(); int waitTimer = 1; string results = ""; // Call the city information API if (apiNum == 0) { response = client.GetAsync("v1/geo/cities?namePrefix=" + cityName).Result; results = response.Content.ReadAsStringAsync().Result; } // Call the nearby cities API else if (apiNum == 1) { response = client.GetAsync("v1/geo/locations/" + coords + "/nearbyCities?limit=5&offset=0&radius=100").Result; results = response.Content.ReadAsStringAsync().Result; } // Call the weather API else if (apiNum == 2) { response = client.GetAsync("data/2.5/weather?q=" + cityName + "&APPID=yourkey").Result; results = response.Content.ReadAsStringAsync().Result; } status = (int)response.StatusCode; if (status == 200) { return results; } else { waitTimer = backOff(waitTimer); } } Console.WriteLine(status + " FAILED API CALL AT: " + uri); return "NULL"; } // Return the total time waited, will put process to sleep // if the HTTP request is not 200 static int backOff(int time) { if(time > 30000) { return 0; } Thread.Sleep(time); Random rnd = new Random(); time *= 2; time += rnd.Next(500); return time; } } } // ----- Near By Cities ------ public class NearByCities { public int id { get; set; } public string wikiDataId { get; set; } public string type { get; set; } public string city { get; set; } public string name { get; set; } public string country { get; set; } public string countryCode { get; set; } public string region { get; set; } public string regionCode { get; set; } public double latitude { get; set; } public double longitude { get; set; } public double distance { get; set; } } public class Link { public string rel { get; set; } public string href { get; set; } } public class NearByCitiesList { public List<NearByCities> data { get; set; } public List<Link> links { get; set; } public Metadata metadata { get; set; } } // ----- GeoDB ------ public class CityInfo { public int id { get; set; } public string wikiDataId { get; set; } public string type { get; set; } public string city { get; set; } public string name { get; set; } public string country { get; set; } public string countryCode { get; set; } public string region { get; set; } public string regionCode { get; set; } public double latitude { get; set; } public double longitude { get; set; } } public class Metadata { public int currentOffset { get; set; } public int totalCount { get; set; } } public class RootObject { public List<CityInfo> data { get; set; } public Metadata metadata { get; set; } } // ----- openweatherapi ------ public class Coord { public double lon { get; set; } public double lat { get; set; } } public class Weather { public int id { get; set; } public string main { get; set; } public string description { get; set; } public string icon { get; set; } } public class Main { public double temp { get; set; } public double feels_like { get; set; } public double temp_min { get; set; } public double temp_max { get; set; } public int pressure { get; set; } public int humidity { get; set; } } public class Wind { public double speed { get; set; } public int deg { get; set; } } public class Rain { public double __invalid_name__1h { get; set; } } public class Clouds { public int all { get; set; } } public class Sys { public int type { get; set; } public int id { get; set; } public string country { get; set; } public int sunrise { get; set; } public int sunset { get; set; } } public class WeatherReport { public Coord coord { get; set; } public List<Weather> weather { get; set; } public string @base { get; set; } public Main main { get; set; } public int visibility { get; set; } public Wind wind { get; set; } public Rain rain { get; set; } public Clouds clouds { get; set; } public int dt { get; set; } public Sys sys { get; set; } public int timezone { get; set; } public int id { get; set; } public string name { get; set; } public int cod { get; set; } } <file_sep>import java.util.Vector; //Cache class to simulate the behavior of how main memory interact with secondary //to improve memory access by incorperating with enchacned seconad change algorithm public class Cache { //Data Fields private int blockSize; private int victimPage; private Vector<Page> cachePage; //Vector to hold all our pages //Cache Constructor public Cache(int blockSize, int cacheBlocks) { this.blockSize = blockSize; victimPage = 0; cachePage = new Vector<Page>(cacheBlocks); for (int i = 0; i < cacheBlocks; i++) { Page temp = new Page(blockSize); this.cachePage.add(temp); } } //Page struct/class to hold all the unqiue values such as reference bits and dirty bits private class Page { //begin at -1 indicate it is empty public int blockNum = -1; //Store the data of the page public byte [] pageData; //Used to deter if page should be swapped or not public boolean refBit = false; public boolean dirtyBit = false; //Constructor public Page(int size) { pageData = new byte[size]; blockNum = -1; refBit = false; dirtyBit = false; } } //This method will read into the buffer and look for the specified block id from the second memory. // If it found the block, then it will return true otherwise false which mean it is a page fault. public synchronized boolean read(int blockId, byte buffer[]) { //loop through the all the pages to a match to our paramter for (int i = 0; i < cachePage.size(); i++) { if(cachePage.get(i).blockNum == blockId) { System.arraycopy(cachePage.get(i).pageData, 0, buffer, 0, blockSize); cachePage.get(i).refBit = true; return true; } } //check for empty pages for (int i = 0; i < cachePage.size(); i++) { if(cachePage.get(i).blockNum == -1) { SysLib.rawread(blockId, cachePage.get(i).pageData); System.arraycopy(cachePage.get(i).pageData, 0, buffer, 0, blockSize); cachePage.get(i).refBit = true; cachePage.get(i).blockNum = blockId; return true; } } int vict = findVictim(); if( (cachePage.get(vict).dirtyBit == true) && (cachePage.get(vict).blockNum != -1) ) { SysLib.rawwrite(cachePage.get(vict).blockNum, cachePage.get(vict).pageData); cachePage.get(vict).dirtyBit = false; } SysLib.rawread(blockId, buffer); System.arraycopy(cachePage.get(vict).pageData, 0, buffer, 0, blockSize); cachePage.get(vict).refBit = true; cachePage.get(vict).blockNum = blockId; return true; } //find the index of a page that is ready to be swapped out private int findVictim() { //infite loop until we find a good match page while(true) { //loop through the pages and check each pages' reference bit and dirty bit for (int i = 1; i < cachePage.size(); i++) { int victIndex = (victimPage + i) % this.cachePage.size(); if( (cachePage.get(victIndex).refBit == false) && (cachePage.get(victIndex).dirtyBit == false) ) { return victIndex; } } for (int i = 1; i < cachePage.size(); i++) { int victIndex = (victimPage + i) % this.cachePage.size(); if ( (cachePage.get(victIndex).refBit == false) && (cachePage.get(victIndex).dirtyBit) ) { if (cachePage.get(victIndex).dirtyBit == true) { return victIndex; } } cachePage.get(victIndex).refBit = false; } } } //This method will search for the specific spots in the secondary memory and write data into it. public synchronized boolean write(int blockId, byte buffer[]) { //loop through the all the pages to a match to our paramter for (int i = 0; i < cachePage.size(); i++) { if (cachePage.get(i).blockNum == blockId) { System.arraycopy(buffer, 0, cachePage.get(i).pageData, 0, blockSize); cachePage.get(i).refBit = true; cachePage.get(i).dirtyBit = true; return true; } } for (int i = 0; i < cachePage.size(); i++) { if (cachePage.get(i).blockNum == -1) { System.arraycopy(buffer, 0, cachePage.get(i).pageData, 0, blockSize); cachePage.get(i).refBit = true; cachePage.get(i).blockNum = blockId; cachePage.get(i).dirtyBit = true; return true; } } //If we get to here then it means main memory are full, thus we need to swap out a page int vict = findVictim(); Page page = cachePage.get(vict); if (page.dirtyBit == true) { SysLib.rawwrite(cachePage.get(vict).blockNum, cachePage.get(vict).pageData); } System.arraycopy(buffer, 0, cachePage.get(vict).pageData, 0, blockSize); cachePage.get(vict).blockNum = blockId; cachePage.get(vict).refBit = true; cachePage.get(vict).dirtyBit = true; return false; } //Write data to disk, invoke right before shutting down public synchronized void sync() { for (int i = 0; i < cachePage.size(); i++) { if( (cachePage.get(i).dirtyBit == true) && (cachePage.get(i).blockNum != -1) ) { SysLib.rawwrite(cachePage.get(i).blockNum, cachePage.get(i).pageData); cachePage.get(i).dirtyBit = false; } } SysLib.sync(); } //Clean up the copies of block. use for testinng performance public synchronized void flush() { for (int i = 0; i < cachePage.size(); i++) { if( (cachePage.get(i).dirtyBit == true) && (cachePage.get(i).blockNum != -1) ) { SysLib.rawwrite(cachePage.get(i).blockNum, cachePage.get(i).pageData); cachePage.get(i).dirtyBit = false; } cachePage.get(i).refBit = false; cachePage.get(i).blockNum = -1; } SysLib.sync(); } }<file_sep>How to compile and run: - The assignment page only told us to include our write-up, hw3.cpp, udphw3.cpp, udphw3case4.cpp, and hw3case3.cpp - To able to run, the problem needs the provided code: Time.cpp, Time.h, UdpSocket.cpp, UdpSocket.cpp, - Please put those files inside directory: hw3 and hw3case4 (each directory require a copy!) - I noticed timeout time the assignment ask us to set (1500 user) is too long for any packet to drop for me, if you don't see any retransmission, please lower the time out time in udphw3.cpp and udphw3case4.cpp. This may vary from hardware to hardware. - Please enter these commands to compile and run: - hw3: (machine 1) $ g++ Time.cpp UdpSocket.cpp hw3.cpp udphw3.cpp -o hw3 (machine 1) $ ./hw3 (machine 2) $ ./hw3 127.0.0.1 #I used local network, if you use different ip address please make sure its local (machine 1 and 2) $ #enter test 1, 2, or 3 - hw3case4: (machine 1) $ g++ Time.cpp UdpSocket.cpp hw3case4.cpp udphw3case4.cpp -o hw3case4 (machine 1) $ ./hw3case4 (machine 2) $ ./hw3case4 127.0.0.1 #I used local network, if you use different ip address please make sure its local (machine 1 and 2) $ #Please enter test 4 only! <file_sep>// // HashTable.h // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Public Function ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- int hashFunction(int value) - resizes the Hash size void insert(Customer* c) - insert customer hashnode in the HashTable void display() - displays all the customer in the HashTable void remove() - removes the customer from HashTable bool contain(Customer* c) - checks if customer is saved bool retrieve(int id, Customer*& holder) - retrieves customer's data by pointing with holder bool getHistory(int id) - retrieves customer's history bool exist(int id) - checks if the customer exists ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications Assumption */ // -------------------------------------------------------------------------------------------------------------------- #ifndef HashTable_h #define HashTable_h #include<vector> #include<iomanip> #include "Customer.h" #include "Movie.h" #include "BST.h" struct HashNode { HashNode(Customer data, HashNode* next = NULL) { this->data = data; this->next = next; } Customer data; HashNode* next; }; class HashTable { public: // constructor & destructor HashTable(); // default constructor ~HashTable(); // destructor // public function int hashFunction(int value); // resizes the Hash size void insert(Customer* c); // insert customer hashnode in the HashTable void display(); // displays all the customer in the HashTable void remove(); // removes the customer from HashTable bool contain(Customer* c); // checks if customer is saved bool retrieve(int id, Customer*& holder); // retrieves customer's data by pointing with holder bool getHistory(int id); // retrieves customer's history bool exist(int id); // checks if the customer exists private: int size; int capacity; HashNode** elements; }; #endif <file_sep>// // HashTable.cpp // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------ ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Public Function ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- int hashFunction(int value) - resizes the Hash size void insert(Customer* c) - insert customer hashnode in the HashTable void display() - displays all the customer in the HashTable void remove() - removes the customer from HashTable bool contain(Customer* c) - checks if customer is saved bool retrieve(int id, Customer*& holder) - retrieves customer's data by pointing with holder bool getHistory(int id) - retrieves customer's history bool exist(int id) - checks if the customer exists ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications Assumption */ // -------------------------------------------------------------------------------------------------------------------- #include "HashTable.h" /*-------------------Constructor()--------------------------*/ // Description // Creates the hashtable class and set every value to 0 or NULL // // Preconditions: None // Postconditions: None HashTable::HashTable() { size = 0; capacity = 10; elements = new HashNode * [10](); } // end of Constructor /*---------------------------------------------------------*/ /*-------------------Destructor--------------------------*/ // Description // Deallocate all memory in heap // // Preconditions: Class is not empty // Postconditions: No memory leak HashTable::~HashTable() { if (size != 0) { this->remove(); } } // end of Destructor /*---------------------------------------------------------*/ /*-------------------hashFunction()--------------------------*/ // Description // Determine where in the hashtable the value will place in // // Preconditions: none // Postconditions: none int HashTable::hashFunction(int value) { return value % capacity; } // end of hashFunction /*---------------------------------------------------------*/ /*-------------------insert()--------------------------*/ // Description // Insert a value into the hashtable // // Preconditions: None // Postconditions: The value is sitting on the correct spot void HashTable::insert(Customer* c) { if (!this->contain(c)) { int spot = hashFunction(c->customerID); HashNode* newNode = new HashNode(*c); newNode->next = elements[spot]; elements[spot] = newNode; size++; } } // end of insert /*---------------------------------------------------------*/ /*-------------------display()--------------------------*/ // Description // Show all the values in the hashtable // // Preconditions: Hashtable must not be empty // Postconditions: None void HashTable::display() { for (int i = 0; i < capacity; i++) { cout << "[" << i << "]:"; HashNode* current = elements[i]; while (current != NULL) { cout << " -> " << setw(2) << current->data; current = current->next; } cout << " /" << endl; } cout << "size = " << size << endl; } // end of display /*---------------------------------------------------------*/ /*-------------------remove()--------------------------*/ // Description // Remove value from hashtable // // Preconditions: Hashtable must not be empty // Postconditions: No memory leak void HashTable::remove() { for (int i = 0; i < capacity; i++) { HashNode* current; while (elements[i] != NULL) { current = elements[i]; elements[i] = elements[i]->next; delete current; current = NULL; size--; } } delete elements; } // end of remove /*---------------------------------------------------------*/ /*-------------------contain()--------------------------*/ // Description // Check whether the value is inside the hashtable // // Preconditions: None // Postconditions: None bool HashTable::contain(Customer* c) { int spot = hashFunction(c->customerID); HashNode* current = elements[spot]; while (current != NULL) { if (current->data == *c) { return true; } current = current->next; } return false; } // end of contain /*---------------------------------------------------------*/ /*-------------------getHistory()--------------------------*/ // Describtion // Find the value and print out all its transaction history // // Preconditions: Must exist in the hashtable // Postconditions: None bool HashTable::getHistory(int id) { int spot = hashFunction(id); HashNode* current = elements[spot]; while (current != NULL) { if (current->data.customerID == id) { current->data.showRecords(); return true; } current = current->next; } return false; } // end of getHistory /*---------------------------------------------------------*/ /*-------------------exist()--------------------------*/ // Description // Check whether the value is inside the hashtable // // Preconditions: None // Postconditions: None bool HashTable::exist(int id) { int spot = hashFunction(id); HashNode* current = elements[spot]; while (current != NULL) { if (current->data.customerID == id) { return true; } current = current->next; } return false; } // end of exist /*---------------------------------------------------------*/ /*-------------------retrieve()--------------------------*/ // Describtion // Find the associate value and set it to the holder // // Preconditions: Value must exist in the hashtable // Postconditions: bool HashTable::retrieve(int id, Customer*& holder) { int spot = hashFunction(id); HashNode* current = elements[spot]; while (current != NULL) { if (current->data.customerID == id) { holder = &current->data; return true; } current = current->next; } return false; } // end of retrieve /*---------------------------------------------------------*/ <file_sep>I implement the solution with python and pure bash with little bit help from awk. At first Both solution had the same logic. Find all uniq artists, use that list to find their albums, and for each song print their path and attach html tags. My solution to generate the html file was very slow. It has to do with my solution constantly using find and locate the artists, albums, and songs. This was easier to implement because of bash utilities that get what i wanted without appling any logical checks. With my python solution, I use find <dirName>/ and piped into the python script. This solution was much faster in term of real life time. For the python script, I stored the input from find to a matrix. With the matrix holding all information, I was able to apply the same logic of find artist then album etc. This script was much heavier on the number of line side. Implementing the solution in python was much harder than bash because of my small experience with python and I don't have access to bash utilities. At first I wanted to do it in bash and perl, but perl end up being too diffcult to understand, so i switched to python. I do not know python much but the language is very straightfoward and the syntax are much easier to understand than perl. I already understood what I needed to do from the solution I did in bash, I just need to apply the same way with python. <file_sep>// // main.cpp // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications Assumption - Make sure the input file address is in correct format and correct name - Assuming that Movie Data file is fo - Assuming that the command data are formatted correctly. - For Inventory = I - For History = H (four digit account number) - For Borrow & Return = For Classic Movie - (B || R) (account number) (Media Type) (C) (Released Month) (Released Year) (Major Actor's First Name) (Major Actor's Last Name) = For Comedy Movie - (B || R) (account number) (Media Type) (F) (Movie Title), (Released Year) = For Drama Movie - (B || R) (account number) (Media Type) (D) (Director's Name), (Movie Title), */ // -------------------------------------------------------------------------------------------------------------------- #include <iostream> #include"Store.h" int main() { // Welcome to the Block Buster! Store blockbuster; string s; // Processing the Movie Data cout << "Please enter a Movie file: "; cin >> s; blockbuster.readMovieFile(s); // Processing the Customer data cout << "Please enter a Customer file: "; cin >> s; // Processing the Command data blockbuster.readCustomerFile(s); cout << "Please enter a Command file: "; cin >> s; blockbuster.readCommandFile(s); cout << endl; return 0; } <file_sep>#! /bin/bash #<NAME> #cd Music/ echo --Warm Up-- echo Total Tracks: "$(find . | grep .ogg | wc -l)" printf "\n" echo Total Artists: $(find . | grep .ogg | cut -d "/" -f3 | sort | uniq | wc -l) printf "\n" echo Multi-Genre Artists: find . | grep .ogg | cut -d "/" -f1-3 | cut -d "/" -f3 | uniq | sort | uniq -d printf "\n" echo Multi-Disk Alumbs: find . | grep disk | cut -d "/" -f4 | sort | uniq echo --Detailed Report-- printf "\n" echo Multi-Genre Artists: find . | grep .ogg | cut -d "/" -f2,3 | sort | uniq | cut -d "/" -f 2 | sort | uniq -d | while read artists do echo " " "$artists" find . | grep "$artists" | cut -d "/" -f 2 | sort | uniq | while read i do echo " " " " $i done done printf "\n" echo Multi-Disk Albums: find . | grep disk | cut -d "/" -f3 | sort | uniq | while read artists; do echo $artists find . | grep "$artists" | grep disk | cut -d "/" -f4 | sort | uniq | while read albums; do echo " " $albums done done printf "\n" echo Possible Duplicates Albums: find . | grep .ogg | cut -d "/" -f4 | uniq | sort | uniq -d | while read dAlbums do echo $dAlbums find . | grep "/$dAlbums" | cut -d "/" -f2,3 | sort | uniq | sed 's/\// /' | while read i do echo " " $i done done <file_sep>#!/bin/bash cd retrieverDir/ # 200 Ok ./retriever.out www.httpbin.org /get 80 # 300 Moved ./retriever.out www.google.com /gmail 80 # 400 Bad Request ./retriever.out www.abc.go.com %/ 80<file_sep>// // Store.h // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Public Function ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- bool readMovieFile(string fileName) - process movie data file bool readCustomerFile(string fileName) - process customer data file bool readCommandFile(string fileName) - process command data file void inventory() - checks inventory of dvds for movie ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications Assumption - Make sure the input file address is in correct format. - Assuming that the command data are formatted correctly. - For Inventory = I - For History = H (four digit account number) - For Borrow & Return = For Classic Movie - (B || R) (account number) (Media Type) (C) (Released Month) (Released Year) (Major Actor's First Name) (Major Actor's Last Name) = For Comedy Movie - (B || R) (account number) (Media Type) (F) (Movie Title), (Released Year) = For Drama Movie - (B || R) (account number) (Media Type) (D) (Director's Name), (Movie Title), */ // -------------------------------------------------------------------------------------------------------------------- #ifndef Store_h #define Store_h #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include "BST.h" #include "HashTable.h" #include "Customer.h" #include "Movie.h" #include"ClassicMovie.h" #include"ComedyMovie.h" #include"DramaMovie.h" using namespace std; class Store { public: // Constructor and Destructor Store(); // default constructor ~Store(); // destructor // public function bool readMovieFile(string fileName); // process movie data file bool readCustomerFile(string fileName); // process customer data file bool readCommandFile(string fileName); // process command data file void inventory(); // checks inventory of dvds for movie private: BST <ComedyMovie> comedyBST; BST <DramaMovie> dramaBST; BST <ClassicMovie> classicBST; HashTable accountTable; }; #endif <file_sep>import java.util.*; public class QueueNode { private Vector<Integer> tidQueue; public QueueNode() { this.tidQueue = new Vector<Integer>(); } public synchronized int sleep() { if(this.tidQueue.isEmpty()) { try { this.wait(); } catch (InterruptedException e) { SysLib.cerr("ERROR at QueueNode\n"); } } return this.tidQueue.remove(0); } public synchronized void wakeup(int tid) { this.tidQueue.add(tid); this.notify(); } }<file_sep>import sys #scan the file and put segements with corrsponding cookies def getData(fileName): cookiesDict = {} eachLine = [] splitLine = [] file = open(fileName) readLine = file.readlines() for line in readLine: if("evaluated:" in line): eachLine = line.split("==>") splitLine = eachLine[0].split(":") cookies = splitLine[-1].strip() segments = eachLine[-1].strip() cookiesDict[cookies] = segments return cookiesDict #get the cookies with empty segments def getEmptyCook(dataDict): result = [] for key, value in dataDict.items(): if(value == "[]"): result.append(key) return result #get the cookies with nonempty segments def getNonEmptyCook(dataDict): result = [] for key, value in dataDict.items(): if(value != "[]"): result.append(key) return result #Find the cookies that had their segments changed def differCook(dictA, dictB): rDict = {} for keyA, ValueA in dictA.items(): for KeyB, ValueB in dictB.items(): if(keyA == KeyB): A = ValueA.strip("[").strip("]").replace(" ","").split(",") B = ValueB.strip("[").strip("]").replace(" ","").split(",") tempList = [] for i in B: if i not in A and i != "": tempList.append(i) if tempList: rDict[keyA]= tempList return rDict #Find all the segments are added or removed def diffSeg(dataDict): rDict = {} for key in sorted(dataDict.keys()): for value in sorted(dataDict[key]): if value in rDict: rDict[value].append(key) else: rDict[value] = key.split() return rDict #Find the total amount of segments def getSegSize(dataDict): rSet = set() for value in baseDict.values(): seg = value.strip("[").strip("]").replace(" ","").split(",") for i in seg: rSet.add(i) return len(rSet) if __name__ == '__main__': #Parse the data from input baseDict = getData(sys.argv[1]) testDict = getData(sys.argv[2]) #Get the total, empty, and nonempty cookies nonEmptyBase = getNonEmptyCook(baseDict) emptyBase = getEmptyCook(baseDict) baseCookieSet = set(nonEmptyBase) nonEmptyTest = getNonEmptyCook(testDict) emptyTest = getEmptyCook(testDict) testCookieSet = set(nonEmptyTest) #Get the data for missing or added cookies totalSegBase = getSegSize(baseDict) missDict = differCook(testDict,baseDict) addDict = differCook(baseDict,testDict) #get the data for missing or added segments sAddDict = diffSeg(addDict) sMissDict = diffSeg(missDict) # #Print out the results print("Summary:") #Part 1: Total, empty, nonempty cookies print("total cookies in baseline = ",len(baseDict)) print("empty cookies in baseline = ",len(emptyBase)) print("non-empty cookies in baseline = ", len(nonEmptyBase),"\n") print("total cookies in text = ",len(testDict)) print("empty cookies in text = ",len(emptyTest)) #Part 2: nonempty cookes in baseline, test, both, and empty print("non-empty cookies in text = ",len(nonEmptyTest),"\n") baseOnly = len(baseCookieSet.difference(testCookieSet)) testOnly = len(testCookieSet.difference(baseCookieSet)) both = len(baseCookieSet.intersection(testCookieSet)) either = len(baseCookieSet.union(testCookieSet)) print("non-empty cookies in baseline only = ",baseOnly) print("non-empty cookies in test only = ", testOnly) print("non-empty cookies in both = ", both) print("non-empty cookies in either = ", either,"\n") #Part 3: segments and cookies changes print(("Cookies with added segments: %s/%s") % (len(addDict),len(baseDict))) for index, (key, value) in enumerate(sorted(addDict.items())): print(("%d\t%s\t%d\t%s") % (index, key, len(value), value)) print(("\nCookies with missing segments: %s/%s") % (len(missDict),len(baseDict))) for index, (key, value) in enumerate(sorted(missDict.items())): print(("%d\t%s\t%d\t%s") % (index, key, len(value), value)) print(("\nSegments with added cookies: %s/%s") % (len(sAddDict),totalSegBase)) for index, (key, value) in enumerate(sorted(sAddDict.items())): print(("%d\t%s\t%d\t%s") % (index,key, len(value),value)) print(("\nSegments with missing cookies: %s/%s") % (len(sMissDict),totalSegBase)) for index, (key, value) in enumerate(sorted(sMissDict.items())): print(("%d\t%s\t%d\t%s") % (index,key, len(value),value)) <file_sep># <NAME> # CSS 436 Cloud Computing # 02-16-20 # ass3Backup.py - Take in folder name as an argument and restore from the cloud the specified directory from AWS. The # directory structure of the files will be keep intact. import os import boto3 import sys from botocore.exceptions import ClientError import logging # Global variable bucketName = "1950386css436prog3" s3 = boto3.resource('s3') # Check if object exists def checkObjExists(key): try: s3.Object(bucketName, key).load() except ClientError as e: return False return True # Open up the bucket and using the module os to recursively tranverse and download the files def Restore(directoryName): bucket = s3.Bucket(bucketName) for obj in bucket.objects.filter(Prefix = directoryName): if not os.path.exists(os.path.dirname(obj.key)): os.makedirs(os.path.dirname(obj.key)) bucket.download_file(obj.key, obj.key) if __name__ == "__main__": # Check if bucket exists before restoring try: s3.meta.client.head_bucket(Bucket=bucketName) Restore(sys.argv[1]) except ClientError: print("BUCKET DOES NOT EXISTS") <file_sep>// ------------------------------------------------ polynomial.cpp ------------------------------------------------------- // <NAME> CSS343 Section A // Creation Date: 6/27/19 // Date of Last Modification: 7/1/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - Creating a ciricular doubly linked list that repsent a polynomial function // -------------------------------------------------------------------------------------------------------------------- // Specifiaction - The driver will take in a coefficiant and power and attach it our linked list // -------------------------------------------------------------------------------------------------------------------- #include "polymonial.h" // ------------------------------------Polynomial----------------------------------------------- // Description // Polynomial: Default constructer // precondition: Default constructor that takes no argument in the paramenter // [ostcondition: Initialize a dummy node that have no values and have the head pointer point to it // -------------------------------------------------------------------------------------------- Polynomial::Polynomial() { //Dummy Node Term* dummy = new Term(0.0,0); head = dummy; head->next = head; head->prev = head; size = 0; } //end of Polynomial() //Precondition: After main is finished running, the destrcutor will run //Postcondition: This destructor will free up all dynamic allocated memories Polynomial::Polynomial(const Polynomial& p) { Term* dummy = new Term(0.0, 0); head = dummy; head->next = head; head->prev = head; size = 0; *this = p; } //end of Polynomial(const Polynomial) // ------------------------------------~Polynomial----------------------------------------------- // Description // - ~Polynomial() : destructor, clears all the data from the objects at the end. // preconditions: no parameters needed. // postconditions: no parameters gets passed in. The destructor delets every objects until it is empty // -------------------------------------------------------------------------------------------- Polynomial::~Polynomial() { if (head != NULL) { while (size != 0) { this->remove(head->next); } remove(head); } } //end of ~Polynomial() // ------------------------------------degree----------------------------------------------- // Description // degree: Find the highest term's power // precondition: Take in no argument, but the list must contain // postcondition: Return the highest dregree of this polymonial function // -------------------------------------------------------------------------------------------- int Polynomial::degree() const { if (size != 0) { return head->next->power; } else { return head->power; } } //end of degree() // ------------------------------------coefficient----------------------------------------------- // Description // coefficient: Find the coefficiant of the term based on the power of the term // precondition: Take in a power related to a coefficenet // postcondition: Return the coefficient based on the power // -------------------------------------------------------------------------------------------- double Polynomial::coefficient(const int power) const { int tempSize = size; Term* current = head->next; while (tempSize != 0) { if (current->power == power) { return current->coeff; } current = current->next; } return 0.0; } //end of coefficient (const int power) const // ------------------------------------changeCoefficient----------------------------------------------- // Description // changeCoefficient: Change the coefficant of the term based on the given power // preconditions: Take in the double for coeff and int for power // postconditions: If the coefficient is zero, remove that term, but insert a new term if there is no corrsponding power // -------------------------------------------------------------------------------------------- bool Polynomial::changeCoefficient(const double newCoefficient, const int power) { Term* current = head; int tempSize = size; if (newCoefficient == 0) { current = head->next; while (tempSize != 0) { if (current->power == power) { this->remove(current); return true; } current = current->next; tempSize--; } return false; } else { while (tempSize != 0) { if (current->next->power == power) { current->next->coeff = newCoefficient; return true; } else if (current->next->power < power) { this->insert(current, newCoefficient, power); return true; } current = current->next; tempSize--; } this->insert(current, newCoefficient, power); return true; } return false; } //end of changeCoefficient(const double newCoefficient, const int power) // Arithmetic operators // ------------------------------------ operator+----------------------------------------------- // Description // - operator+ : Operator overload + adds the two Polynomial, 2nd polynomial from the 1st one. // preconditions: The &p is the value of the polynomials. // postconditions: The left side of the polynomial gets copied to the new object, and then return the object // -------------------------------------------------------------------------------------------- Polynomial Polynomial::operator+(const Polynomial& p) const { return Polynomial(*this) += p; } //end of operator+ // ------------------------------------ operator- ----------------------------------------------- // Description // operator- : Operator overload - subtracts the two Polynomials, 2nd polynomial from the 1st one. // preconditions: The &p is the value of the polynomials. // postconditions: The left side of the polynomial gets copied to the new object, and then return the object // -------------------------------------------------------------------------------------------- Polynomial Polynomial::operator-(const Polynomial& p) const { return Polynomial(*this) -= p; } //end of operator- // Boolean comparison operators // ------------------------------------operator=----------------------------------------------- // Description // operator ==: Overload the == operator to check if two objects are identicle. // preconditions: The operand's must contain values. // postconditions: Returns true if two objects are identicle. // -------------------------------------------------------------------------------------------- bool Polynomial::operator==(const Polynomial& p) const { Term* current = head->next; Term* otherCurrent = p.head->next; if (this->size != p.size) { return false; } else { for (int i = 0; i < size; i++) { if (current->coeff != otherCurrent->coeff || current->power != otherCurrent->power) { return false; } current = current->next; otherCurrent = otherCurrent->next; } return true; } } //end of operator== // ------------------------------------operator!= ----------------------------------------------- // Description // operator !=: Overload the != operator to check if two objects are unidenticle. // preconditions: The operand's must contain values. // postconditions: Returns true if two Polynomials are unidenticle. // -------------------------------------------------------------------------------------------- bool Polynomial::operator!=(const Polynomial& p) const { return (!(*this == p)); } //end of operator!= // Assignment operators // ------------------------------------operator= ----------------------------------------------- // Description // operator =: Overload the = operator to copy and assign objects // preconditions: The operand's must contain values // postconditions: Return the object with values copied from the parameter object // -------------------------------------------------------------------------------------------- Polynomial& Polynomial::operator=(const Polynomial& p) { if (*this != p) { while (size != 0) { this->remove(head->next); } Term* otherCurrent = p.head->next; for (int i = 0; i < p.size; i++) { this->changeCoefficient(otherCurrent->coeff, otherCurrent->power); otherCurrent= otherCurrent->next; } } return *this; } //end of operator= // ------------------------------------operator +=----------------------------------------------- // Description // operator +=: Overload the += operator to add and assign objects // preconditions: The operand's must contain values // postconditions: Return the object with values added from the parameter object // -------------------------------------------------------------------------------------------- Polynomial& Polynomial::operator+=(const Polynomial& p) { if (p.size == 0) { return *this; } else { Term* otherCurrent = p.head->next; for (int i = 0; i < p.size; i++) { Term* holder = NULL; { if (findTerm(otherCurrent->power, holder)) { this->changeCoefficient(otherCurrent->coeff + holder->coeff, otherCurrent->power); } else { this->changeCoefficient(otherCurrent->coeff, otherCurrent->power); } } otherCurrent = otherCurrent->next; } return *this; } } //end of operator += // ------------------------------------operator -=----------------------------------------------- // Description // operator -=: Overload the -= operator to subtract and assign objects // preconditions: The operand's must contain values // postconditions: Return the object with values subtracted from the parameter object // -------------------------------------------------------------------------------------------- Polynomial& Polynomial::operator-=(const Polynomial& p) { if (p.size == 0) { return *this; } else { Term* otherCurrent = p.head->next; for (int i = 0; i < p.size; i++) { Term* holder = NULL; { if (findTerm(otherCurrent->power, holder)) { this->changeCoefficient(holder->coeff - otherCurrent->coeff, otherCurrent->power); } else { this->changeCoefficient(-otherCurrent->coeff, otherCurrent->power); } } otherCurrent = otherCurrent->next; } return *this; } } //end of operator -= // ------------------------------------Operator <<----------------------------------------------- // Description // Operator <<: Overload the << operator to print out the all linked list's value // preconditions: The linked list must contain values in it // postconditions: All the values in linked list will be formated and printed out on console // -------------------------------------------------------------------------------------------- ostream& operator<<(ostream& output, const Polynomial& p) { Polynomial::Term* current = p.head->next; if (p.size != 0) { if (current->power == 1 && current->coeff == 1) { if (current->coeff < 0) { output << "-x"; current = current->next; } else { output << "x"; current = current->next; } } else if (current->power == 1) { output << current->coeff << "x"; current = current->next; } else if (current->power == 0) { output << current->coeff; current = current->next; } else { output << current->coeff << "x^" << current->power; current = current->next; } while (current != p.head) { if (current->coeff < 0) { if (current->power == 1 && current->coeff == 1) { output << "-x"; current = current->next; } else if (current->power == 1) { output << current->coeff << "x"; current = current->next; } else if (current->power == 0) { output << current->coeff; current = current->next; } else { output << current->coeff << "x^" << current->power; current = current->next; } } else { if (current->power == 1 && current->coeff == 1) { output << " + x"; current = current->next; } else if (current->power == 1) { output << " + " << current->coeff << "x"; current = current->next; } else if (current->power == 0) { output << " + " << current->coeff; current = current->next; } else { output << " + " << current->coeff << "x^" << current->power; current = current->next; } } } } return output; } //end of operator << // ------------------------------------insert----------------------------------------------- // Description // insert: Given a location and value, generate a new node and attach to the link list // preconditions: Parameter pointer must be pointing to a linked list with other nodes // postconditions: Return true if sucessfully insert a new node with given value // -------------------------------------------------------------------------------------------- bool Polynomial::insert(Term* pos, const double newCoefficient, const int power) { if (pos != NULL) { Term* temp = new Term(newCoefficient, power); temp->next = pos->next; temp->prev = pos; pos->next->prev = temp; pos->next = temp; size++; return true; } else { return false; } } //end of insert() // ------------------------------------remove----------------------------------------------- // Description // remove: Given a location, remove that node. Return true if sucessfully removed, return false if not. // preconditions: Parameter address must be point to a node on a linked list // postconditions: Deallocate the node by using delete and setting its pointer to NULL // -------------------------------------------------------------------------------------------- bool Polynomial::remove(Term* pos) { if (size == 0) { pos->next = NULL; pos->prev = NULL; // cout << "deleting" << pos->coeff << endl; delete pos; return true; } else { pos->prev->next = pos->next; pos->next->prev = pos->prev; pos->next = NULL; pos->prev = NULL; // cout << "deleting" << pos->coeff << endl; delete pos; size--; return true; } return false; } //end of remove() // ------------------------------------findTerm----------------------------------------------- // Description // findTerm: Given a value, find the location based on that value return true if found, return false if not found // preconditions: the pointer variable must NULL and value must be an int // postconditions: point the parameter pointer to the found address // -------------------------------------------------------------------------------------------- bool Polynomial::findTerm(int power, Term*& holder) { Term* current = head->next; for (int i = 0; i < size; i++) { if (current->power == power) { holder = current; return true; } current = current->next; } holder = NULL; return false; } //end of findTerm() <file_sep>How to run program: Run with my script: $ chmod u+x runBackup.sh $ ./runBackup.sh $ chmod u+x runRestore.sh $ ./runRestore.sh Run on the command line: $ python3 ass3Backup.py "directoryName" $ python3 ass3Restore.py "directoryName" <file_sep>// // Customer.h // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Getter ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- int& getCustomerID() - returns address of the customer ID; ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Public Function ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- void trackRecords() - Saves the customer's transaction void showRecords() - Displays the customer's transaction chronogical order. (Newest to oldest) ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Overriding Operator Overloads ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- friend ostream& operator <<(ostream& out, Customer& other) bool operator==(const Customer&) bool operator!=(const Customer&) ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications - The customer class stores customer information: ID, first name, last name, and transaction history Assumption - Assuming that the customer data file is formatted in a given way by professor. */ // -------------------------------------------------------------------------------------------------------------------- #ifndef Customer_h #define Customer_h #include<iostream> #include <stdio.h> #include<string> #include<vector> using namespace std; class Customer { public: // Constructor & Destructor Customer(); // default constructor Customer(int ID, string fName, string lName); // data is set equal to parameter ~Customer(); // destructor // Getter function int& getCustomerID(); // returns customer ID; // public function void trackRecords(string s); // Saves the customer's transaction void showRecords(); // Displays the customer's transaction chronogical order. (Newest to oldest) //operation overloads friend ostream& operator <<(ostream& out, Customer& other); bool operator==(const Customer&) const; bool operator!=(const Customer&) const; private: int customerID; // customer ID string firstName; // customer's first name string lastName; // customer's last name vector<string> records; friend class HashTable; // Stack or Map for saving the transaction History // The order needs to be "latest to oldest" }; #endif /* Customer_HEADER */ <file_sep>// ------------------------------------------------ graphl.cpp ------------------------------------------------------- // <NAME> CSS343 Section A // Creation Date: 7/29/19 // Date of Last Modification: 7/29/19 // -------------------------------------------------------------------------------------------------------------------- // Description - Detail implementation for graphl.cpp // -------------------------------------------------------------------------------------------------------------------- #include "graphl.h" // --------------------------GraphL------------------------------ // Description: Default constructor for Adjacent List based graph // Precondition: none // Postcondition: none // ----------------------------------------------------------------------- GraphL::GraphL() { size = 0; for (int i = 0; i < MAXNODES_L; i++) { adjList[i].visited = false; adjList[i].edgeHead = NULL; } } // --------------------------GraphL------------------------------ // Description: Destructor to free up all memories // Precondition: none // Postcondition: All memories are freed // ----------------------------------------------------------------------- GraphL::~GraphL() { removeEdges(); } // --------------------------buildGraph------------------------------ // Description: Read and create a graph from the file // Precondition: none // Postcondition: none // ----------------------------------------------------------------------- void GraphL::buildGraph(ifstream& input) { int fromNode = 0; int toNode = 0; input >> size; string s; getline(input, s); if (size > 0) { for (int i = 1; i <= size; i++) { getline(input, s); adjList[i].data = new NodeData(s); } while (!input.eof()) { input >> fromNode >> toNode; if (fromNode == 0 || toNode == 0) { break; } insertEdge(fromNode, toNode); } } } // --------------------------insertEdge------------------------------ // Description: buildGraph Helper that insert new node into the linkedlist chain // Precondition: none // Postcondition: none // ----------------------------------------------------------------------- void GraphL::insertEdge(const int fromNode, const int toNode) { if (fromNode > 0 && fromNode <= size && toNode > 0 && toNode <= size) { EdgeNode* node = new EdgeNode; node->adjGraphNode = toNode; node->nextEdge = adjList[fromNode].edgeHead; adjList[fromNode].edgeHead = node; } } // --------------------------removeEdge------------------------------ // Description: Helper function that remove all nodes from all lists // Precondition: Graph must contain elements/values // Postcondition: All allocated memories are cleared // ----------------------------------------------------------------------- void GraphL::removeEdges() { for (int i = 0; i <= size; i++) { adjList[i].visited = false; EdgeNode* deallocThis = adjList[i].edgeHead; while (deallocThis != NULL) { EdgeNode* saveNext = deallocThis->nextEdge; delete deallocThis; deallocThis = saveNext; } adjList[i].edgeHead = NULL; } size = 0; } // --------------------------displayGraph------------------------------ // Description: Display all the nodes and where they are connected // Precondition: none // Postcondition: none // ----------------------------------------------------------------------- void GraphL::displayGraph() { cout << "Graph:" << endl; for (int i = 1; i <= size; i++) { cout << "Node" << i << " "; cout << *adjList[i].data << endl; cout << endl; if (adjList[i].edgeHead == NULL) { cout << endl; } else { EdgeNode* current = adjList[i].edgeHead; while (current != NULL) { cout << " " << "edge" << " " << i << " " << current->adjGraphNode << endl; current = current->nextEdge; } } } } // --------------------------dephtFirstSearch------------------------------ // Description: Algorithm to traversal all through the nodes and edges // Precondition: Adjacnet list must not be empty // Postcondition: none // ----------------------------------------------------------------------- void GraphL::depthFirstSearch() { if (size != 0) { cout << "Depth First Search: "; for (int i = 1; i <= size; i++) { if (!adjList[i].visited) { dfsHelper(i); } } } cout << endl; } // --------------------------dfsHelper------------------------------ // Description: Helper function for dfs // Precondition: must be only called by the depthFirstSearch function with given index // Postcondition: none // ----------------------------------------------------------------------- void GraphL::dfsHelper(const int index) { cout << " " << index; adjList[index].visited = true; int n = 0; EdgeNode* current = adjList[index].edgeHead; while (current != NULL) { n = current->adjGraphNode; if (!adjList[n].visited) { dfsHelper(n); } current = current->nextEdge; } }<file_sep>How to run program: 1. dotnet restore 2. dotnet run "city name" OR #this script will build and run premade test cases $ chmod u+x ./build.sh $ ./build.sh Notes: - The program utilizes NewtonSoft.Json and System.Net.http - City names with spaces between must be in qoutes! - This program is build in Mac environment, if possible please run it on Mac! <file_sep>// // Store.cpp // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright � 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Public Function ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- bool readMovieFile(string fileName) - process movie data file bool readCustomerFile(string fileName) - process customer data file bool readCommandFile(string fileName) - process command data file void inventory() - checks inventory of dvds for movie ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications Assumption - Make sure the input file address is in correct format. */ // -------------------------------------------------------------------------------------------------------------------- #include "Store.h" /*-------------------Default Constructor--------------------------*/ // Describtion // - Constructs the object with default setting // // Preconditions: No parameters are passed in. // Postconditions: The data variables are set as default value. Store::Store() { comedyBST; dramaBST; classicBST; accountTable; } // end of Constructor /*---------------------------------------------------------*/ /*-------------------Destructor--------------------------*/ // Describtion // - needed to delete store object. // // Preconditions: No parameters are passed in. // Postconditions: Deletes the Store object Store::~Store() { } // end of Destructor /*---------------------------------------------------------*/ /*-------------------readMovieFile--------------------------*/ // Describtion // - Reads the movie data file, and retrieves the information. // the retrieved data are saved in to one of the data container // according to the movie genre // // Preconditions: name of the file is passed in // Postconditions: reads the line until the end of the file bool Store::readMovieFile(string fileName) { ifstream moviedata(fileName); // general edge case if (!moviedata) { cout << "File could not be opened." << endl; return false; } // reads till the end of file for (;;) { // data that are required to be retrieved from the file char type, comma; string directorName, skip, title, fname, lname; int stock, month, year; // always the first character of the line is the movie genre moviedata >> type >> comma; // break if it reach end of the file if (moviedata.eof()) { break; } // Classic Movie if (type == 'C') { moviedata >> stock >> comma; getline(moviedata, directorName, ','); getline(moviedata, title, ','); moviedata >> fname >> lname >> month >> year; // ------------------------------------------ // Here we can create memory of Classic Movie // and insert it into Classic Movie BST ClassicMovie cm(type, stock, directorName, title, fname, lname, month, year); classicBST.insert(cm); // ------------------------------------------ } // Drama Movie and Comedy Movie else if (type == 'D' || type == 'F') { moviedata >> stock >> comma; getline(moviedata, directorName, ','); getline(moviedata, title, ','); moviedata >> year; // ------------------------------------------ // Here we can create memory of Classic Movie // and insert it into Classic Movie BST if (type == 'F') { ComedyMovie fm(type, stock, directorName, title, year); comedyBST.insert(fm); } if (type == 'D') { DramaMovie dm(type, stock, directorName, title, year); dramaBST.insert(dm); } } else { // if the movie genre is not either C, F, or D, throw error code getline(moviedata, skip); cout << "------------------------------------------------------------------------------" << endl; cout << endl; cout << "Invalid input from Movie Data" << endl; cout << type << ", " << skip << endl; cout << "------------------------------------------------------------------------------" << endl; } } return true; } // end of readMovieFile /*---------------------------------------------------------*/ /*-------------------readCustomerFile--------------------------*/ // Describtion // - Reads the customer data file, and retrieves the information. // The retrieved data are saved in to customer object then saved into // the HashTable // // Preconditions: name of the file is passed in // Postconditions: reads the line until the end of the file bool Store::readCustomerFile(string fileName) { ifstream customerData(fileName); // first general edge case if (!customerData) { cout << "File could not be opened." << endl; return false; } // Processing the customers data in following order // Account Number, First Name, Last Name for (;;) { // Account Number, First Name, Last Name int accountNumber = 0; string firstName, lastName, skip; customerData >> accountNumber; // breaks if it reaches end of the file if (customerData.eof()) { break; } // if Account Number is less than 0, return false if (accountNumber < 0 && accountNumber > 9999) { getline(customerData, skip); } else { // ------------------------------------------ // Here we can insert into the HashTable // The customer data is followed by account number, last name and first name. customerData >> lastName >> firstName; Customer c(accountNumber, firstName, lastName); accountTable.insert(&c); // ------------------------------------------ } } return true; } // end of readCustomerFile /*---------------------------------------------------------*/ /*-------------------readCommandFile--------------------------*/ // Describtion // - Reads the Command data file, and retrieves the information. // The retrieved data are executed accordingly based on the command. // // Preconditions: name of the file is passed in // Postconditions: reads the line until the end of the file bool Store::readCommandFile(string fileName) { ifstream commandData(fileName); // first general edge case if (!commandData) { cout << "File could not be opened." << endl; return false; } // reads until the end of the file for (;;) { // These are the information we can retrieve from the command data file string command; int accountNumber; string skip; Customer* cHolder = NULL; // reads the first letter of the line, which is the command commandData >> command; // break if it reaches end of the file if (commandData.eof()) { break; } // Inventory for DvD stock if (command == "I") { cout << "Print current inventory of DVD stocks." << endl; this->inventory(); } // History, displays Customer's transaction else if (command == "H") { commandData >> accountNumber; if (accountNumber < 1000 || accountNumber > 9999 || accountTable.exist(accountNumber)) { cout << "Print the history of " << accountNumber << " customer." << endl; accountTable.getHistory(accountNumber); } else { cout << "ACCOUNT NOT FOUND: " << accountNumber << endl; } } // Borrow & Return else if (command == "B" || command == "R") { // These are the data required for the B & R command // Media Type, Movie Genre string mediaType, movieType; // Retrieving account number commandData >> accountNumber; // finding the customer if (accountNumber < 1000 || accountNumber > 9999 || accountTable.retrieve(accountNumber, cHolder)) { // getting media type // Only, D(DvD) is considered in this project commandData >> mediaType; if (mediaType == "D") { // getting movie genre commandData >> movieType; // Comedy Movie if (movieType == "F") { // getting information for comedy movie string title; int releaseYear; getline(commandData, title, ','); if (commandData >> releaseYear) { // this is for retrieving information ComedyMovie* fholder = NULL; // if movie is found, execute Borrow or Return based on the command if (comedyBST.retrieve(title, releaseYear, fholder)) { // if B, execute Borrow Dvd if (command == "B") { fholder->borrow(); } // if R, execute Return Dvd else if (command == "R") { fholder->Return(); } // Tracks customer's transaction // by sending string line cHolder->trackRecords(" " + command + " " + to_string(accountNumber) + " " + mediaType + " " + movieType + title + " " + to_string(releaseYear)); } else { // if the movie does not exist, throw an error cout << "NOT A VALID MOVIE TITLE: " << title << endl; } } else { cout << "INVALID INPUT" << endl; commandData.clear(); getline(commandData, skip); } } // if drama movie else if (movieType == "D") { // information required for Drama Movie string director, title; getline(commandData, director, ','); getline(commandData, title, ','); // for retrieving drama movie from data container DramaMovie* dHolder = NULL; // if movie exist if (dramaBST.retrieve(director, title, dHolder)) { // if B, execute borrow if (command == "B") { dHolder->borrow(); } // if R, execute Return else if (command == "R") { dHolder->Return(); } // saving customer's transaction history cHolder->trackRecords(" " + command + " " + to_string(accountNumber) + " " + mediaType + " " + movieType + title + director); } else { // if the movie does not exist throw an error code cout << "NOT A VALID MOVIE TITLE: " << title << endl; } } // if it's classic movie else if (movieType == "C") { // retrieving information required for Classic Movie int releaseMonth, releaseYear; string maFirstName, maLastName; if ((commandData >> releaseMonth >> releaseYear >> maFirstName >> maLastName)) { // for retrieving classic movie from the BST ClassicMovie* clHolder = NULL; ClassicMovie* clHolder2 = NULL; // if the movie exist if (classicBST.retrieve(maFirstName, maLastName, releaseMonth, releaseYear, clHolder)) { if (command == "B") { if (clHolder->getMovieStock() > 0) { clHolder->borrow(); cHolder->trackRecords(" " + command + " " + to_string(accountNumber) + " " + mediaType + " " + movieType + " " + maFirstName + " " + maLastName); } else if (classicBST.retrieveSame(maFirstName, maLastName, clHolder->getMovieName(), clHolder->getDirectorName(), releaseMonth, releaseYear, clHolder2)) { string yesno; cout << "No Stock of Movie `" << clHolder->getMovieName() << "' with '" << maFirstName << " " << maLastName << "', would you like the Movie `" << clHolder2->getMovieName() << "' with '" << clHolder2->getMaFirstName() << " " << clHolder2->getMaLastName() << "'? Enter YES or NO (All CAPS)" << endl; cin >> yesno; if (yesno == "YES") { clHolder2->borrow(); cHolder->trackRecords(" " + command + " " + to_string(accountNumber) + " " + mediaType + " " + movieType + " " + clHolder2->getMaFirstName() + " " + clHolder2->getMaLastName()); } } else { cout << "TRANSACTION DENIED! " << clHolder->getMovieName() << " stock: " << clHolder->getMovieStock() << endl; } } // if R, execute return else if (command == "R") { clHolder->Return(); cHolder->trackRecords(" " + command + " " + to_string(accountNumber) + " " + mediaType + " " + movieType + " " + maFirstName + " " + maLastName); } // save the transaction history } else { cout << "NOT A VALID MOVIE TITLE WITH ACTOR/ACTRESS: " << maFirstName << " " << maLastName << " " << releaseMonth << " " << releaseYear << endl; } } else { cout << "INVALID INPUT" << endl; commandData.clear(); getline(commandData, skip); } } else { cout << "The movie genre, " << movieType << ", does not exist" << endl; getline(commandData, skip); } } else { cout << "Currently, we only have DvD available" << endl; getline(commandData, skip); } } else { cout << "ACCOUNT NOT FOUND: " << accountNumber << endl; getline(commandData, skip); } } else { cout << "Command " << command << " is not available" << endl; getline(commandData, skip); } } return 0; } // end of readCommandFile /*---------------------------------------------------------*/ /*-------------------inventory--------------------------*/ // Describtion // - prints out the inventory of the entire movie stock // // Preconditions: No parameter is passed in // Postconditions: Execute the display function from each movie data container void Store::inventory() { cout << "\n****** Movie Inventory ******\n" << endl; cout << "**************************************************" << endl; cout << "Comedy Movie (Sorted by Title, then Released Year)" << endl; cout << "**************************************************\n" << endl; this->comedyBST.display(); cout << "********************************************" << endl; cout << "Drama Movie (Sorted by Director, then Title)" << endl; cout << "********************************************\n" << endl; this->dramaBST.display(); cout << "******************************************************************" << endl; cout << "Classic Movie (Sorted by Released Date(mm/yyyy), then Major Actor)" << endl; cout << "******************************************************************\n" << endl; this->classicBST.display(); } // end of inventory /*---------------------------------------------------------*/ <file_sep>#!/bin/bash mono ass1.exe http://courses.washington.edu/css502/dimpsey/ 5 mono ass1.exe http://www.washington.edu/ 5<file_sep>class Machine(object): def __init__(self, name): self._name = name self._header = "" self._footer = "" self._edges = [] self._states = [] self._uniqEvent = set() #use by state to get the edges def edge(self,name, next_state, action_string=''): self._edges.append((name, next_state, action_string)) self._uniqEvent.add(name) return self._edges[-1] #use a state with multple edges def edges(self, *argv): arr = [] for arg in argv: arr.append(self.edge(arg[0], arg[1])) return arr #store the name of the state, the action to get to next state, tuple of next [event, state] def state(self, name, action, edges = None): if edges is None: edges = [] self._states.append((name, action, edges)) def header(self, text): self._header = text def footer(self, text): self._footer = text def print_enum_states(self): print("enum State {") for i, state in enumerate(self._states): if (i != len(self._states) - 1): print(" ", state[0]+"_STATE,") else: print(" ", state[0]+"_STATE") print("};") def printStringToEvent(self): print('Event string_to_event(string event_string) {') for e in self._uniqEvent: print(' if (event_string == "%s") {return %s;}' % (e, e+'_EVENT')) print(' return INVALID_EVENT;\n}') def print_enum_edges(self): print("enum Event {") for e in self._uniqEvent: print(" ",e+"_EVENT,") s = "INVALID_EVENT" print(" ",s) print("};") def print_eventNames(self): print("const char * EVENT_NAMES[] = {") for i, e in enumerate(self._uniqEvent): if (i != len(self._uniqEvent) - 1): print(" \""+e+"\",") else: print(" \""+e+"\"") print("};") def print_event(self, event): print(" case ", event[0]+"_EVENT:") print(" ",event[2]) print(" state =", event[1]+"_STATE;") print(" break;") def print_state(self, state): print((" case %s:") % (state[0]+"_STATE")) print((" cerr << \"state %s\" << endl;") % (state[0])) print(" ",state[1]) print(" event = get_next_event();") print(" cerr << \"event \" << EVENT_NAMES[event] << endl;") print(" switch(event) {") for e in state[2]: self.print_event(e) print(" default:") print((" cerr << \"INVALID EVENT \" << event << \" in state %s\" << endl;") % (state[0])) print(" return -1;") print(" }") print(" break;") def print_body(self): print("Event get_next_event();") print() self.printStringToEvent() print(("int %s(State initial_state) {") % (self._name)) print(" State state = initial_state;") print(" Event event;") print(" while (true) {") print(" switch (state) {") for state in self._states: self.print_state(state) print(" }") print(" }") print("}") def gen(self): print(self._header) self.print_enum_states() self.print_enum_edges() self.print_eventNames() self.print_body() print(self._footer)<file_sep>#pragma #include "UdpSocket.h" #include "Timer.h" class udphw3case4 { public: int clientSlidingWindow( UdpSocket &sock, const int max, int message[], int windowSize ); void serverEarlyRetrans( UdpSocket &sock, const int max, int message[], int windowSize ,int dropChance); };<file_sep>// ------------------------------------------------ graphl.h ------------------------------------------------------- // <NAME> CSS343 Section A // Creation Date: 7/29/19 // Date of Last Modification: 7/29/19 // -------------------------------------------------------------------------------------------------------------------- // Description - Header files for graphL.h // -------------------------------------------------------------------------------------------------------------------- #ifndef _GRAPHL_H_ #define _GRAPHL_H_ #include "nodedata.h" #include <iostream> #include "iomanip" using namespace std; //Max values for edges and vertices int const MAXNODES_L = 100; class GraphL { public: //Constructor and Destructor GraphL(); ~GraphL(); //Main Functions void buildGraph(ifstream&); void insertEdge(const int src, const int dest); void removeEdges(); void displayGraph(); void dfsHelper(const int searchNode); //Helper function void depthFirstSearch(); private: //Data fields struct EdgeNode; struct GraphNode { EdgeNode* edgeHead; NodeData* data; bool visited; }; struct EdgeNode { int adjGraphNode; EdgeNode* nextEdge; }; GraphNode adjList[MAXNODES_L]; int size; }; #endif<file_sep>#! /bin/bash python3 ass3Restore.py testingObjects<file_sep>#! /bin/bash #set -x ARTIST=3 ALBUM=4 albumCount=0 echo "<html>" echo " <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />" echo "<body>" echo "<table border=\"1\">" echo " <tr>" echo " <th>Artist</th>" echo " <th>Album</th>" echo " <th>Tracks</th>" echo " </tr>" find Music/ | grep ogg | cut -d "/" -f3 | sort | uniq | while read artists; do albumCount=$(find Music/ | grep .ogg | grep "$artists" | sort | cut -d "/" -f$ALBUM | cut -d "/" -f4 | sort | uniq | wc -l) n=$albumCount find Music/ | grep .ogg | grep "$artists" | sort | cut -d "/" -f4 | cut -d "/" -f$ALBUM | sort | uniq | while read albums; do echo " <tr>" if [ $n == $albumCount ] then echo " <td rowspan=\"$albumCount\">"$artists"</td>" fi echo " <td>"$albums"</td>" echo " <td>" echo " <table border=\"0\">" find Music/ | grep "/$artists/$albums/" | grep .ogg | sort | while read line do echo " <tr><td><a href=\""$line"\">"$(echo $line | awk -F "/" '{print $NF}')"" done echo " </table>" echo " </td>" echo " </tr>" ((n--)) done done echo "</table>" echo "<body>"<file_sep>// // ClassicMovie.cpp // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Getter & Setter ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- string getMaFirstName() - returns Major Actor's First Name string getMaLastName() - returns Major Actor's Last Name int getReleaseMonth() - returns Released Month ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Overriding Operator Overloads ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- The Classic Movie is sorted by the released date( Month / Year) and name of the Major Actor in the movie The comparisons are based on the released date( Month / Year) and name of the Major Actor in the movie ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- virtual bool operator <() virtual bool operator >() virtual bool operator !=() virtual bool operator ==() ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications - The Classic Movie class is a child class of the Movie class. It has the access to the parents class's public functions and protected data - When "cout <<," the first two information are one that used on sorting. Rest of the information will be printed inisde of the bracket. Assumption - Assuming that the movie data file is formatted in a given way by professor. */ // -------------------------------------------------------------------------------------------------------------------- // #include <stdio.h> #include "ClassicMovie.h" /*-------------------Default Constructor--------------------------*/ // Describtion // - Constructs the object with default setting // // Preconditions: No parameters are passed in. // Postconditions: The data variables are set as default value. ClassicMovie::ClassicMovie() { movieName = ""; directorName = ""; movieType = 0; releaseYear = 0; movieStock = 0; } // end of Constructor /*---------------------------------------------------------*/ /*------------------- Casting datas to Constructor --------------------------*/ // Describtion // - Constructs a object with the following parameters saved in to the data variables // // Preconditions: Character of movie genre, integer of movie stock, string of director name // string of movie title, and integer of released year are passed in as parameter. // Postconditions: The parameters are saved into the data variables by a given structure. ClassicMovie::ClassicMovie(const char movieType, int movieStock, const string derName, const string movieName, const string majFname, const string majLname, int releaseMonth, int releaseYear) :Movie(movieType, movieStock, derName, movieName, releaseYear) { this->releaseMonth = releaseMonth; this->maFirtname = majFname; this->maLastname = majLname; }; // end of Constructor /*---------------------------------------------------------*/ /*------------------- Virtual Destructor --------------------------*/ // Describtion // - Needed so movie data are deleted properly // // Preconditions: No parameters are passed in // Postconditions: Will be deleted by BST ClassicMovie::~ClassicMovie() { // delete all the movie data // delete all the allocated memories } // end of Destructor /*---------------------------------------------------------*/ /*-------------------getMaFirstName()--------------------------*/ // Describtion // - returns Major Actor's First Name // // Preconditions: No parameters are passed in // Postconditions: returns Major Actor's first name string ClassicMovie::getMaFirstName() const { // Only the Classic Movie contains name of the major actor in the movie return this->maFirtname; } // end of getMaFirstName /*---------------------------------------------------------*/ /*-------------------getMaLastName()--------------------------*/ // Describtion // - returns Major Actor's Last Name // // Preconditions: No parameters are passed in // Postconditions: returns Major Actor's last name string ClassicMovie::getMaLastName() const { // Only the Classic Movie contains name of the major actor in the movie return this->maLastname; } // end of getMaLastName /*---------------------------------------------------------*/ /*-------------------getReleaseMonth()--------------------------*/ // Describtion // The classic movie contains released month in addition to released year. // - The function returns released month // // Preconditions: No parameters are passed in // Postconditions: returns released month of the movie int ClassicMovie::getReleaseMonth() const { // Only the Classic Movie contains released month return releaseMonth; } // end of getMovieType /*---------------------------------------------------------*/ /*-------------------operator <()--------------------------*/ // Describtion // - Compares by title of the Comedy movie and released year // // Preconditions: Address of the other Comedy movie object is passed in // Postconditions: Compares it by the Comedy movie title and the released year bool ClassicMovie::operator <(ClassicMovie& other) const { // checks general edge case if (other.releaseMonth == 0) { return false; } else { // compare the year of released date if (releaseYear != other.releaseYear) { if (this->releaseYear < other.releaseYear) { return true; } else { return false; } } else { // if release year is same // then compare by released month if (this->releaseMonth < other.releaseMonth) { return true; } else if (this->releaseMonth == other.releaseMonth) { // if released dates are identicle // then compare by major Actor's last name if (maFirtname < other.maFirtname) { return true; } else if(maFirtname == other.maFirtname) { if(maLastname < other.maLastname) { return true; } else { return false; } } else { return false; } } else { // the release date is bigger(recent) return false; } } } } // end of operator <() /*---------------------------------------------------------*/ /*-------------------operator >()--------------------------*/ // Describtion // - Compares by title of the Comedy movie and released year // // Preconditions: Address of the other Comedy movie object is passed in // Postconditions: Compares it by the Comedy movie title and the released year bool ClassicMovie::operator >(ClassicMovie& other) const { // checks general edge case if (other.releaseMonth == 0) { return false; } else { // compare the year of released date if (releaseYear != other.releaseYear) { if (this->releaseYear > other.releaseYear) { return true; } else { return false; } } else { // if release year is same // then compare by released month if (this->releaseMonth > other.releaseMonth) { return true; } else if (this->releaseMonth == other.releaseMonth) { // if released dates are identicle // then compare by major Actor's last name if (maFirtname > other.maFirtname) { return true; } else if(maFirtname == other.maFirtname) { if(maLastname > other.maLastname) { return true; } else { return false; } } else { return false; } } else { // the release date is bigger(recent) return false; } } } } // end of operator <() /*---------------------------------------------------------*/ /*-------------------operator ==()--------------------------*/ // Describtion // - Compares by title of the Comedy movie and released year // // Preconditions: Address of the other Comedy movie object is passed in // Postconditions: Compares it by the Comedy movie title and the released year bool ClassicMovie::operator ==(ClassicMovie& other) const { // checks general edge case if (other.releaseMonth == 0) { return false; } else { // Must check the release year, month, and Major actor's first name and last name if (this->releaseYear == other.releaseYear && this->releaseMonth == other.releaseMonth && this->maFirtname == other.maFirtname && this->maLastname == other.maLastname) { return true; } else return false; } } // end of operator ==() /*---------------------------------------------------------*/ /*-------------------operator !=()--------------------------*/ // Describtion // - Compares by title of the Comedy movie and released year // // Preconditions: Address of the other Comedy movie object is passed in // Postconditions: Compares it by the Comedy movie title and the released year bool ClassicMovie::operator !=(ClassicMovie& other) const { // checks general edge case if (other.releaseMonth == 0) { return false; } else { // if one of them is different return true if (this->releaseYear != other.releaseYear || this->releaseMonth != other.releaseMonth || this->maFirtname != other.maFirtname || this->maLastname != other.maLastname) { return true; } else return false; } } // end of operator !=() /*---------------------------------------------------------*/ /*-------------------operator<<()--------------------------*/ // Describtion // - Overloads the operator << // - When the object is casted with cout <<, the following line will be printed // // Preconditions: Ostream and ComedMovie object are passed in // Postconditions: Retrieves data information and print out in the order below ostream& operator<<(ostream& out, ClassicMovie& other) { out << "Released date: " << other.releaseMonth << " / " << other.releaseYear << " Major Actor: " << other.maFirtname << " " << other.maLastname << " ( Title: " << other.movieName << " Director:" << other.directorName << " Type: " << other.movieType << " **Stock: " << other.movieStock << " )" << endl; return out; } // end of operator<< /*---------------------------------------------------------*/ <file_sep>// ------------------------------------------------ graphm.cpp ------------------------------------------------------- // <NAME> CSS343 Section A // Creation Date: 7/29/19 // Date of Last Modification: 7/29/19 // -------------------------------------------------------------------------------------------------------------------- // Description - Detail implementation for graphM.cpp // -------------------------------------------------------------------------------------------------------------------- #include "graphm.h" // --------------------------GraphM------------------------------ // Description: Default constructor for Adjacent Matrix based graph // Precondition: none // Postcondition: all value set to false and max value // ----------------------------------------------------------------------- GraphM::GraphM() { size = 0; for (int i = 1; i < MAXNODES; i++) { for (int j = 1; j < MAXNODES; j++) { C[i][j] = MAX; T[i][j].dist = MAX; T[i][j].path = 0; T[i][j].visited = false; } } } // --------------------------buildGraph------------------------------ // Description: Read and create a graph from the file // Precondition: none // Postcondition: none // ----------------------------------------------------------------------- void GraphM::buildGraph(ifstream& file) { file >> size; string s; getline(file, s); for (int i = 1; i <= size; i++) { data[i].setData(file); } int fromNode, toNode, dist; while (file >> fromNode >> toNode >> dist) { if (fromNode == 0) { break; } C[fromNode][toNode] = dist; } } // --------------------------insertEdge------------------------------ // Description: Connect two vertex together // Precondition: Our graph must contain those vertices // Postcondition: The edge value is no longer max int // ----------------------------------------------------------------------- bool GraphM::insertEdge(int fromNode, int toNode, int dist) { if (fromNode <= size && toNode <= size) { this->T[fromNode][toNode].dist = dist; return true; } else { return false; } } // --------------------------removeEdge------------------------------ // Description: Remove the edge from two vertices // Precondition: Our graph must contain those vertices // Postcondition: The edge value between the two vertices are now max int // ----------------------------------------------------------------------- bool GraphM::removeEdge(int fromNode, int toNode) { if (fromNode <= size && toNode <= size) { this->T[fromNode][toNode].dist = MAX; return true; } else { return false; } } // --------------------------findShortestPath------------------------------ // Description: Using Dijkstra's algorithm to find the shortest path // Precondition: Vertices must exist // Postcondition: none // ----------------------------------------------------------------------- void GraphM::findShortestPath() { int v = 0; int cNode = 0; for (int source = 1; source <= size; source++) { T[source][source].dist = 0; for (int i = 1; i <= size; i++) { v = minDistance(source); T[source][v].visited = true; for (int w = 1; w <= size; w++) if (T[source][w].visited == false && C[v][w] != MAX && T[source][v].dist + C[v][w] < T[source][w].dist) { T[source][w].dist = T[source][v].dist + C[v][w]; T[source][w].path = v; } } } } // --------------------------minDistance------------------------------ // Description: Shortest Path helper // Precondition: none // Postcondition: none // ----------------------------------------------------------------------- int GraphM::minDistance(int source) { int v = 0; int min = MAX; for (int i = 1; i <= size; i++) if (T[source][i].visited == false && T[source][i].dist <= min) { min = T[source][i].dist; v = i; } return v; } // --------------------------displayAll------------------------------ // Description: Display all the shortest distance from all nodes and the path // Precondition: none // Postcondition: none // ------------------------------------------------------------------- void GraphM::displayAll() const { cout << "|Description |From Node |To Node |Dijikstra's" << " |Path" << endl; for (int i = 1; i < size + 1; i++) { cout << data[i] << endl; for (int j = 1; j < size + 1; j++) { if (T[i][j].dist > 0 && T[i][j].dist < MAX) { cout << " " << i << " " << j << " " << T[i][j].dist << " "; getPath(i, j); cout << endl; } else { cout << " " << i << " " << j << " " << "---" << endl; } } } cout << endl; } // --------------------------display------------------------------ // Description: Display the shortest distance between two given position // Precondition: Vertices must exist // Postcondition: none // ------------------------------------------------------------------- void GraphM::display(const int fromNode, const int toNode) const { if (T[fromNode][toNode].dist != MAX) { cout << " " << fromNode << " " << toNode << " "; cout << T[fromNode][toNode].dist << " "; getPath(fromNode, toNode); } else { cout << " " << fromNode << " " << toNode << " ---"; } getPathName(fromNode, toNode); cout << endl; } // --------------------------getPath------------------------------ // Description: Get the path that it takes to travel the shortest distance // Precondition: none // Postcondition: none // ----------------------------------------------------------------------- void GraphM::getPath(const int fromNode, const int toNode) const { if (fromNode != toNode && T[fromNode][toNode].path != 0) { getPath(fromNode, T[fromNode][toNode].path); } cout << toNode << " "; } // --------------------------getPathName------------------------------ // Description: Similiar to getPath, but print out the list of the path // Precondition: none // Postcondition: none // ----------------------------------------------------------------------- void GraphM::getPathName(const int fromNode, const int toNode) const { if (T[fromNode][toNode].dist != MAX) { getPathNameHelper(fromNode, toNode); cout << data[toNode] << endl; } } void GraphM::getPathNameHelper(const int fromNode, const int toNode) const { if (fromNode != toNode && T[fromNode][toNode].path != 0) { getPathNameHelper(fromNode, T[fromNode][toNode].path); } cout << data[T[fromNode][toNode].path] << endl; }<file_sep>#!/bin/bash dotnet restore dotnet run seattle dotnet run wuhan dotnet run london <file_sep>// // ComedyMovie.h // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group #5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Overriding Operator Overloads ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- The comedy is sorted by the Title of the movie and the released year. The comparisons are based on the movie title and the released year. ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- virtual bool operator <() virtual bool operator >() virtual bool operator !=() virtual bool operator ==() ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications - This class is a child class of the Movie class. It has the access to the parents class's public functions and protected data - When "cout <<," the first two information are one that used on sorting. Rest of the information will be printed inisde of the bracket. Assumption - Assuming that the movie data file is formatted in a given way by professor. */ // -------------------------------------------------------------------------------------------------------------------- #include"Movie.h" #ifndef ComedyMovie_h #define ComedyMovie_h class ComedyMovie : public Movie { public: // Constructor & Destructor ComedyMovie(); // Default Constructor ComedyMovie(const char movieType, int movieStock, const string derName, const string movieName, int releaseYear); // data is set equal to parameter virtual ~ComedyMovie(); // virtual destructor // Overriding Operator Overloads bool operator <(ComedyMovie& other) const; bool operator >(ComedyMovie& other) const; bool operator ==(ComedyMovie& other) const; bool operator !=(ComedyMovie& other) const; friend ostream& operator <<(ostream& out, ComedyMovie& other); private: }; #endif <file_sep>$(document).ready(function() { $("#butt1").click(function() { alert("Hey John!!!\nGazooks! It worked!"); }); $("#SpongGar").hover(function() { $(this).css("color", "white"); }, function() { $(this).css("color", "black"); }); $("#butters").hover(function () { $(this).html("THIS IS MY FAV OF THE FAVS"); }); $("#butt2").click(function () { $("#SpongGar").css("color", "white"); $("#conceded").css("color", "white"); $("#student").css("color", "white"); $("#butters").css("color", "white"); $("#simi").css("color", "white"); }); $("#butt3").click(function () { $("#SpongGar").css("color", "black"); $("#conceded").css("color", "black"); $("#student").css("color", "black"); $("#butters").css("color", "black"); $("#simi").css("color", "black"); }) }); <file_sep>// // Customer.cpp // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Getter ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- int& getCustomerID() - returns address of the customer ID; ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Public Function ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- void trackRecords() - Saves the customer's transaction void showRecords() - Displays the customer's transaction chronogical order. (Newest to oldest) ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Overriding Operator Overloads ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- friend ostream& operator <<(ostream& out, Customer& other) bool operator==(const Customer&) bool operator!=(const Customer&) ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications - The customer class stores customer information: ID, first name, last name, and transaction history Assumption - Assuming that the customer data file is formatted in a given way by professor. */ // -------------------------------------------------------------------------------------------------------------------- #include "Customer.h" /*-------------------Default Constructor--------------------------*/ // Describtion // - Constructs the object with default setting // // Preconditions: No parameters are passed in. // Postconditions: The data variables are set as default value. Customer::Customer() { customerID = 0; firstName = ""; lastName = ""; } // end of Constructor /*---------------------------------------------------------*/ /*------------------- Casting datas to Constructor --------------------------*/ // Describtion // - Constructs a object with the following parameters saved in to the data variables // // Preconditions: Character of movie genre, integer of movie stock, string of director name // string of movie title, and integer of released year are passed in as parameter. // Postconditions: The parameters are saved into the data variables by a given structure. Customer::Customer(int ID, string fName, string lName) { customerID = ID; firstName = fName; lastName = lName; } // end of Constructor /*---------------------------------------------------------*/ /*--------------------Destructor-----------------------*/ // Describtion // - needed so customer data can be deleted // // Preconditions: No parameters are passed in // Postconditions: Will be deleted from the Hash Table Customer::~Customer() { // delete all the Customer data } // end of Destructor /*---------------------------------------------------------*/ /*--------------------getCustomerID()-----------------------*/ // Describtion // - returns the customer ID number // // Preconditions: No parameters are passed in // Postconditions: Returns the address of the Customer ID int& Customer::getCustomerID() { int& ptr = customerID; return ptr; } // end of getCustomerID /*---------------------------------------------------------*/ /*--------------------trackRecords()-----------------------*/ // Describtion // - Saves the transaction history by pushing in string line // // Preconditions: string s, which it contains transation information, is passed in // Postconditions: push in the data into the transaction memory(vector<string>) void Customer::trackRecords(string s) { records.push_back(s); } // end of getCustomerID /*---------------------------------------------------------*/ /*--------------------showRecords()-----------------------*/ // Describtion // - Iteratively go through each elements in vector and prints out the data // // Preconditions: No parameters are passed in // Postconditions: prints out the data void Customer::showRecords() { if (records.empty()) { cout << "NO CUSTOMER HISTORY" << endl; } else { for (auto it = records.end()-1; it != records.begin()-1; it--) { cout << *it << endl; } } } // end of getCustomerID /*---------------------------------------------------------*/ /*--------------------operator==()-----------------------*/ // Describtion // - checks if the customer ID is identicle // // Preconditions: address of the customer object is passed in // Postconditions: returns true if the both customer ID are identicle bool Customer::operator==(const Customer& other) const { return customerID == other.customerID; } // end of operator== /*---------------------------------------------------------*/ /*--------------------operator!=()-----------------------*/ // Describtion // - checks if the customer ID is un-identicle // // Preconditions: address of the customer object is passed in // Postconditions: returns true if the both customer ID are un-identicle bool Customer::operator!=(const Customer& other) const { return customerID != other.customerID; } // end of operator!= /*---------------------------------------------------------*/ /*-------------------- operator <<()-----------------------*/ // Describtion // - prints out in a specific structure listed below // // Preconditions: ostream and the address of the customer object are passed in // Postconditions: returns ostream that is saved with the set of string line. ostream& operator <<(ostream& out, Customer& other) { return out << "Customer ID: " << other.customerID << " Name: " << other.firstName << " " << other.lastName; } // end of operator << /*---------------------------------------------------------*/ <file_sep>//<NAME> //CSS432 //HW2 //10-25-2019 #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> #include <netinet/tcp.h> #include <stdio.h> #include <sys/uio.h> #include <pthread.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sstream> #include <iostream> #include <vector> #include <fstream> using namespace std; //Global variables for HTTP responses const char* HTTP200 = "HTTP/1.1 200 OK\n"; const char* HTTP404 = "HTTP/1.1 404 Not Found\n"; const char* HTTP400 = "HTTP/1.1 400 Bad Request\n"; const char* HTTP401 = "HTTP/1.1 401 Unauthorized\n"; const char* HTTP403 = "HTTP/1.1 403 Forbidden\n"; const int BUFFSIZE = 1500; //Parse the request and place them into a vector with size of 2 //1. HTTP Request 2. File Name bool requestString(int fileDesc, vector<string>& vecStr) { string s = ""; char buffer[BUFFSIZE]; if(recv(fileDesc , buffer , BUFFSIZE , 0) < 0) { printf("ERROR At READ"); return false; } int len = strlen(buffer); //Read each character one by one to weed out the white space and special characters for (int i = 0; i < len; i++) { if (buffer[i] == ' ') { vecStr.push_back(s); s = ""; } else if ((buffer[i] == '\r' || buffer[i] == '\n')) { //\r\n\r\n signals the end of request if(buffer[i] == 'r' || buffer[i] == '\n') { vecStr.push_back(s); break; } } else { //Put the string together s += buffer[i]; } } return true; } //This is where we would take the request and respond bool requestCommand(int fileDesc, vector<string>& requestVector, char* buffer) { string httpReq = requestVector[0]; string fileReq = requestVector[1]; cout << httpReq << " " << fileReq << endl; //Accepting only GET request if( httpReq == "GET" && fileReq.size() < 20) { //Check for out of current directory if(fileReq.substr(0,2) == "..") { cout << HTTP403 << endl; send(fileDesc, HTTP403, strlen(HTTP403),0); return false; } //Check for unauthorize file else if(fileReq == "/SecretFile.html") { cout << HTTP401 << endl; send(fileDesc, HTTP401, strlen(HTTP401),0); return false; } else { string fileName = "." + fileReq; FILE* file; char c; file = fopen(fileName.c_str(), "r"); //Valid file request if(file != NULL) { while(1) { if(feof(file)) { break; } fread(buffer, 1000, 1, file); } fclose(file); cout << HTTP200 << endl; send(fileDesc, HTTP200, strlen(HTTP200),0); send(fileDesc, buffer, strlen(buffer), 0); return true; } //File must not found else if(file == NULL) { cout << HTTP404 << endl; send(fileDesc, HTTP404, strlen(HTTP404),0); return false; } } } //Bad Request else { cout << HTTP400 << endl; send(fileDesc, HTTP400, strlen(HTTP400),0); return false; } } //Takes in a void pointer to the File Descriptor, //the function's argument is where we will read and write the data to/from void* action(void* args) { //Casting the void pointer back to int pointer so we can deference to get the file descriptor int* sockPtr = (int*) args; vector<string> requestVector; requestString(*sockPtr, requestVector); char fileContent[BUFFSIZE] = {0}; requestCommand(*sockPtr, requestVector, fileContent); close(*sockPtr); } int main(int argc, char **argv) { //Setting up the server int on = 1; int serSock, cliSock; struct sockaddr_in server, client; if((serSock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("Error at Socket"); exit(-1); } server.sin_family = AF_INET; server.sin_port = htons(atoi(argv[1])); server.sin_addr.s_addr = INADDR_ANY; bzero(&server.sin_zero, 0); //Request the OS to release the socket once program finish running setsockopt(serSock, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(int)); if( bind(serSock,(struct sockaddr*)&server, sizeof(server)) == -1) { perror("Error at Bind"); exit(-1); } socklen_t len = sizeof(client); //Infinite loop because we want the server to continue to serve any client coming in while(1) { if((listen(serSock,5)) == -1) { perror("Error at Listen"); exit(-1); } printf("Listening\n"); if((cliSock = accept(serSock,(struct sockaddr*)&client, &len)) == -1) { perror("Error at Accept"); exit(-1); } printf("Connected to: %s\n",inet_ntoa(client.sin_addr)); //Create a new thread per client conncted to the server //The program will wait until all the threads finish excuting before closing pthread_t newthread; if((pthread_create(&newthread, NULL, action, &cliSock)) < 0) { perror("Error at pThread"); exit(-1); }; pthread_join(newthread, NULL); printf("\n"); } return 0; }<file_sep>// ------------------------------------------------ polynomial.h ------------------------------------------------------- // <NAME> CSS343 Section A // Creation Date: 6/27/19 // Date of Last Modification: 7/1/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - header file that will outline the main functions and fields of the circular doubly linked list // -------------------------------------------------------------------------------------------------------------------- // A Polynomial class #ifndef POLYNOMIAL_H #define POLYNOMIAL_H #include <iostream> #include <string> using namespace std; class Polynomial { //Overloaded <<: prints Cn * x^n + Cn-1 * X^n-1 + ... C1 * X + C0 friend ostream& operator<<(ostream& output, const Polynomial& p); // Constructor: the default is a 0-degree polynomial with 0.0 coefficient public: // Member functions Polynomial(); Polynomial(const Polynomial& p); ~Polynomial(); int degree() const; // returns the degree of a polynomial double coefficient(const int power) const; // returns the coefficient of the x^power term. bool changeCoefficient(const double newCoefficient, const int power); // replaces the coefficient of the x^power term // Arithmetic operators Polynomial operator+(const Polynomial& p) const; Polynomial operator-(const Polynomial& p) const; //// Boolean comparison operators bool operator==(const Polynomial& p) const; bool operator!=(const Polynomial& p) const; //// Assignment operators Polynomial& operator=(const Polynomial& p); Polynomial& operator+=(const Polynomial& p); Polynomial& operator-=(const Polynomial& p); private: struct Term { // a term on the sparce polynomial double coeff; // the coefficient of each term int power; // the degree of each term Term* prev; // a pointer to the previous higher term Term* next; // a pointer to the next lower term Term(double c = 0.0, int p = 0, Term * pr = NULL, Term * ne = NULL) { coeff = c; power = p; prev = pr; next = ne; } }; int size; // # terms in the sparce polynomial Term* head; // a pointer to the doubly-linked circular list of // sparce polynomial bool insert(Term* pos, const double newCoefficient, const int power); bool remove(Term* pos); // void print( const string& msg ) const; bool findTerm(int power, Term*& holder); }; #endif <file_sep>#include "bintree.h" #include <fstream> #include <iostream> using namespace std; const int ARRAYSIZE = 100; //global function prototypes void buildTree(BinTree&, ifstream&); void initArray(NodeData* []); int main() { ifstream infile("inputdata.txt"); if (!infile) { cout << "File could not be opened." << endl; return 1; } NodeData notND("not"); NodeData andND("and"); NodeData sssND("sss"); NodeData tttND("ttt"); NodeData osdoND("osdo"); NodeData sdaND("sda"); NodeData eeeND("eee"); NodeData mghND("mgh"); NodeData tND("t"); cout << "Testing for Node constructor: " << osdoND << endl; BinTree T, T2, dup; NodeData* ndArray[ARRAYSIZE]; initArray(ndArray); cout << "Initial data:" << endl << " "; buildTree(T, infile); // builds and displays initial data cout << endl; BinTree first(T); // test copy constructor dup = dup = T; // test operator=, self-assignment while (!infile.eof()) { cout << "----------------------- Testing for Inorder Output -----------------------" << endl; cout << "Tree Inorder:" << endl << T; // operator<< does endl T.displaySideways(); cout << "----------------------- Testing for Retrieve -----------------------" << endl; NodeData* p; // pointer of retrieved object bool found; // whether or not object was found in tree found = T.retrieve(andND, p); cout << "Retrieve --> and: " << (found ? "found" : "not found") << endl; found = T.retrieve(notND, p); cout << "Retrieve --> not: " << (found ? "found" : "not found") << endl; found = T.retrieve(sssND, p); cout << "Retrieve --> sss: " << (found ? "found" : "not found") << endl; cout << "----------------------- Testing for getHeight -----------------------" << endl; cout << "Height --> and: " << T.getHeight(andND) << endl; cout << "Height --> not: " << T.getHeight(notND) << endl; cout << "Height --> sss: " << T.getHeight(sssND) << endl; cout << "Height --> osodo: " << T.getHeight(osdoND) << endl; cout << "Height --> eee: " << T.getHeight(eeeND) << endl; cout << "Height --> t: " << T.getHeight(tND) << endl; cout << "----------------------- Testing for Comparable operator -----------------------" << endl; T2 = T; cout << "T == T2? " << (T == T2 ? "equal" : "not equal") << endl; cout << "T != first? " << (T != first ? "not equal" : "equal") << endl; cout << "T == dup? " << (T == dup ? "equal" : "not equal") << endl; dup = T; cout << "----------------------- Testing for BST to ARR and ARR to BST -----------------------" << endl; T.bstreeToArray(ndArray); T.arrayToBSTree(ndArray); T.displaySideways(); T.makeEmpty(); // empty out the tree initArray(ndArray); // empty out the array cout << "---------------------------------------------------------------"<< endl; cout << "Initial data:" << endl << " "; buildTree(T, infile); cout << endl; } return 0; } void buildTree(BinTree& T, ifstream& infile) { string s; for (;;) { infile >> s; cout << s << ' '; if (s == "$$") break; // at end of one line if (infile.eof()) break; // no more lines of data NodeData* ptr = new NodeData(s); // NodeData constructor takes string // would do a setData if there were more than a string bool success = T.insert(ptr); if (!success) delete ptr; // duplicate case, not inserted } } //------------------------------- initArray ---------------------------------- // initialize the array of NodeData* to NULL pointers void initArray(NodeData* ndArray[]) { for (int i = 0; i < ARRAYSIZE; i++) ndArray[i] = NULL; }<file_sep>Details: - To run the program please enter 'python3 asgn3.py testFileBase.txt testFile.txt' - The baseline file is arg 1 and test file is arg 2 - The log file provided was really big it that I gave up running it. Instead, i cut about 25,000 line and run it that way. - Then I made my own test file instead. This assignment was really long but it was fun. I was able to practice the python I learned in class. Using tricks like enumerate for auto counter and set - union,intersect,etc for finding the cookies in both and either. Unfortnately, I was caught up with other classes homework and work that I wasn't able to complete in time. Please forgive me. <file_sep>Notes: - asgm1.sh is my script. TestData is my sample data. Music is the data that was provided. TestDataOutput and MusicOutput are the output of using asgm1.sh - My sample data will have the script within the tarball. It is the exact same script, I placed it there for it to be a reference where the script need to be. - The Script might not able to excute. In that case, please chmod u+x asgm1.sh - All my solutions utilize the command 'find .', which mean the script I wrote must be inside of the Music directory along with the genre directories. - Another thing to look out for is that the directory structure for the script to run properly must be the same as the Music.tar (Music/Genre/Artist/Album/Disc(optional)/Songs). - Please run the script while your current directory is Music/ same with TestData(my sample data I created). Instructions: 1. Untar the my submission 2. Put the script in the director you want to run. (Ie mv asgm1.sh Music/ or TestData/) 3. Change the directory to where you put the script in. (cd Music) 4. Run the script<file_sep>// // DamaMovie.cpp // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Overriding Operator Overloads ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- The Drama is sorted by the Director's name and the Title of the movie. The comparisons are based on Director's name and the Title of the movie. ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- virtual bool operator <() virtual bool operator >() virtual bool operator !=() virtual bool operator ==() ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications - The DramaMovie class is a child class of the Movie class. It has the access to the parents class's public functions and protected data Assumption - Assuming that the movie data file is formatted in a given way by professor. */ // -------------------------------------------------------------------------------------------------------------------- #include "DramaMovie.h" #include <stdio.h> /*-------------------Default Constructor--------------------------*/ // Describtion // - Constructs the object with default setting // // Preconditions: No parameters are passed in. // Postconditions: The data variables are set as default value. DramaMovie::DramaMovie() { movieName = ""; directorName = ""; movieType = 0; releaseYear = 0; movieStock = 0; } // end of Constructor /*---------------------------------------------------------*/ /*------------------- Casting datas to Constructor --------------------------*/ // Describtion // - Constructs a object with the following parameters saved in to the data variables // // Preconditions: Character of movie genre, integer of movie stock, string of director name // string of movie title, and integer of released year are passed in as parameter. // Postconditions: The parameters are saved into the data variables by a given structure. DramaMovie::DramaMovie(const char movieType, int movieStock, const string derName, const string movieName, int releaseYear) :Movie(movieType, movieStock, derName, movieName, releaseYear) { }; // end of Constructor /*---------------------------------------------------------*/ /*------------------- Virtual Destructor --------------------------*/ // Describtion // - Needed so movie data are deleted properly // // Preconditions: No parameters are passed in // Postconditions: Will be deleted by BST DramaMovie::~DramaMovie() { // delete all the movie data // delete all the allocated memories } // end of Destructor /*---------------------------------------------------------*/ /*-------------------operator <()--------------------------*/ // Describtion // - Compares by title of the Comedy movie and released year // // Preconditions: Address of the other Comedy movie object is passed in // Postconditions: Compares it by the Comedy movie title and the released year bool DramaMovie::operator <(DramaMovie& other) const { // checks general edge case if (other.getMovieName() == "") { return false; } else { // Compares by director's name, then Title if (directorName != other.getDirectorName()) { if (this->directorName < other.getDirectorName()) { return true; } else { return false; } } // if Director's name is identicle // then sort by movie name(Title) else { if (movieName < other.getMovieName()) { return true; } else { return false; } } } return false; } // end of operator <() /*---------------------------------------------------------*/ /*-------------------operator >()--------------------------*/ // Describtion // - Compares by title of the Comedy movie and released year // // Preconditions: Address of the other Comedy movie object is passed in // Postconditions: Compares it by the Comedy movie title and the released year bool DramaMovie::operator >(DramaMovie& other) const { // checks general edge case if (other.getMovieName() == "") { return false; } else { // Compares by director's name, then Title if (directorName != other.getDirectorName()) { if (this->directorName > other.getDirectorName()) { return true; } else { return false; } } // if Director's name is identicle // then sort by movie name(Title) else { if (movieName > other.getMovieName()) { return true; } else { return false; } } } return false; } // end of operator >() /*---------------------------------------------------------*/ /*-------------------operator ==()--------------------------*/ // Describtion // - Compares by title of the Comedy movie and released year // // Preconditions: Address of the other Comedy movie object is passed in // Postconditions: Compares it by the Comedy movie title and the released year bool DramaMovie::operator ==(DramaMovie& other) const { // checks general edge case if (other.getMovieName() == "") { return false; } else { // Must check the Title and the released year // The movie may have same Title but different released year if (this->directorName == other.getDirectorName() && this->movieName == other.getMovieName()) { return true; } else { return false; } } } // end of operator ==() /*---------------------------------------------------------*/ /*-------------------operator !=()--------------------------*/ // Describtion // - Compares by title of the Comedy movie and released year // // Preconditions: Address of the other Comedy movie object is passed in // Postconditions: Compares it by the Comedy movie title and the released year bool DramaMovie::operator !=(DramaMovie& other) const { // checks general edge case if (other.getMovieName() == "") { return false; } else { // Compare director's name if (this->directorName != other.getDirectorName()) { return true; } else { // if Director's name is identicle // compare by movie name(Title) if (this->movieName != other.getMovieName()) { return true; } else { return false; } }; } } // end of operator !=() /*---------------------------------------------------------*/ /*-------------------operator<<()--------------------------*/ // Describtion // - Overloads the operator << // - When the object is casted with cout <<, the following line will be printed // // Preconditions: Ostream and ComedMovie object are passed in // Postconditions: Retrieves data information and print out in the order below ostream& operator<<(ostream& out, DramaMovie& other) { out << "Director: " << other.directorName << " Title: " << other.movieName << " (Type: " << other.movieType << " Release Year: " << other.releaseYear << " **Stock: " << other.movieStock << " )" << endl; return out; } // end of operator<<() /*---------------------------------------------------------*/ <file_sep>// ------------------------------------------------ TestDrive.cpp ------------------------------------------------------- // <NAME> CSS343 Section A // Creation Date: 6/27/19 // Date of Last Modification: 7/1/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - Driver to test every function of the circulary doubly linked list: polynomial // -------------------------------------------------------------------------------------------------------------------- #include"polymonial.h" int main() { Polynomial p1; p1.changeCoefficient(5, 1); p1.changeCoefficient(2, 4); p1.changeCoefficient(2.2, 2); p1.changeCoefficient(-3.8, 3); cout << "p1 = " << p1 << endl; p1.changeCoefficient(0, 2); cout << "Test for changeCoefficient(0,2), with p1: " << "p1 = " << p1 << endl; Polynomial p2; cout << "p2 = " << p2 << endl; cout << "Test for operator =, with p2 = p1: " << "p2 = " << p2 << endl; Polynomial p3 = p1 + p2; cout << "p3 = " << p3 << endl; cout << "Test for operator +, with p3 = p1 + p2: " << "p3 = " << p3 << endl;; Polynomial defaultPoly; cout << "Test for default constructor, with defaultPoly: " << defaultPoly << endl; Polynomial copy(p1); cout << "Test for copy consturctor, with copyPoly(p1): " << copy << endl; cout << "Test for coefficient function, with p1 coeff power 3: " << p1.coefficient(3) << endl; cout << "Test for coefficient function, with p1 coeff power 1: " << p1.coefficient(1) << endl; Polynomial p7; p7.changeCoefficient(10, 4); p7.changeCoefficient(3, 2); p7.changeCoefficient(-5, 1); p7.changeCoefficient(15, 9); cout << "Testing for degree function, with p1: " << p1.degree() << endl; cout << "Testing for degree function, with p7: " << p7.degree() << endl; p1 += p2; cout << "Testing for += operator, with p1 = p1 + p2: " << p1 << endl; Polynomial p4; p4.changeCoefficient(5, 5); p4.changeCoefficient(6, 6); p4.changeCoefficient(7, 7); Polynomial p5; p5.changeCoefficient(1, 5); p5.changeCoefficient(1, 6); p5.changeCoefficient(3, 7); p5.changeCoefficient(2, -2); cout << "p4:" << p4 << endl; cout << "p5:" << p5 << endl; p4 -= p5; cout << "Testing for -= operator, p4 = p4 - p5: " << p4 << endl; Polynomial p10; p10 = p5 - p4; cout << "Test for operator -, with p10 = p5 - p4: " << "p10 = " << p10 << endl;; cout << "Testing for == operator and operater !=, with p4 == p5: "; if (p5 == p4) { cout << "p4 and p5 are the same" << endl; } else { cout << "p4 and p5 are not the same" << endl; } return 0; } //pass in zero power<file_sep>// ------------------------------------------------ graphm.h ------------------------------------------------------- // <NAME> CSS343 Section A // Creation Date: 7/29/19 // Date of Last Modification: 7/29/19 // -------------------------------------------------------------------------------------------------------------------- // Description - Header files for graphM.h // -------------------------------------------------------------------------------------------------------------------- #ifndef GRAPHM_H #define GRAPHM_H #include"nodedata.h" #include <iostream> #include <climits> #include <string> #include <iomanip> using namespace std; //Max values for edges and vertices int const MAXNODES = 100; int const MAX = 99999; class GraphM { public: //Default constructor GraphM(); //Main Functions void buildGraph(ifstream& file); bool insertEdge(int fromNode, int toNode, int dist); bool removeEdge(int fromNode, int toNode); void findShortestPath(); void displayAll() const; void display(const int fromNode, const int toNode) const; private: //Data fields NodeData data[MAXNODES]; int C[MAXNODES][MAXNODES]; int size; struct TableType { bool visited; int dist; int path; }; //Helper Functions TableType T[MAXNODES][MAXNODES]; void getPath(const int fromNode, const int toNode) const; void getPathName(const int fromNode, const int toNode) const; void getPathNameHelper(const int fromNode, const int toNode) const; int minDistance(int source); }; #endif<file_sep>#!/bin/bash cd retrieverDir/ # 200 Ok ./retriever.out csslab3.uwb.edu /getThis.txt 1499 # 400 Bad Request ./retriever.out csslab3.uwb.edu /abcdefghijklmnopqrtsuvwxyz.txt 1499 # 401 Unauthorized ./retriever.out csslab3.uwb.edu ../getThis.txt 1499 # 403 Forbidden ./retriever.out csslab3.uwb.edu /SecretFile.html 1499 # 404 Not Found ./retriever.out csslab3.uwb.edu /getThis2.txt 1499 <file_sep>//<NAME> //CSS432 //HW2 //10-24-2019 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/time.h> #include <iostream> using namespace std; //Global variables const int BUFFSIZE = 1024; const char* FILENAME; int PORT; char* SERVERIP; //HTTP respond in ASCII //Return false if its not an OK reply //200 Ok = 146 //400 Bad Request = 148 //401 Unauthorized = 149 //403 Forbidden = 151 //404 Not Found = 152 bool processCode(int code) { if(code == 146) return true; else return false; } //Takes in the client's socket. Send out the request and recv the reply //If it is a Ok reply then open a file and right to it bool sendRequest(int fileDesc) { //Setting up the HTTP send message char sendM[BUFFSIZE] = {0}; char recvM[BUFFSIZE] = {0}; snprintf(sendM, BUFFSIZE, "GET %s " "HTTP/1.1\r\n" "HOST: %s \r\n\r\n", FILENAME, SERVERIP); printf("---------------------------------------\n"); printf("%s", sendM); //Send is sucessful then wait for a respond if( send(fileDesc, sendM, strlen(sendM), 0) > 0 ) { recv(fileDesc, recvM, BUFFSIZE, 0); int code = recvM[9] + recvM[10] + recvM[11]; printf("Return Message: %s", recvM); //Only write to file if respond was an OK respond if(processCode(code)) { string fn = FILENAME; const char* writeFILENAME = fn.substr(1,fn.length()).c_str(); FILE * fptr = fopen(writeFILENAME, "w"); if(fptr != NULL) { //fgets(recvM, strlen(recvM), fptr); fputs(recvM, fptr); fclose(fptr); return true; } return false; } } else { printf("ERROR AT WRITE\n"); return false; } close(fileDesc); } //Setup the socket and establish connection int main(int argc, char **argv) { //Arguments from commandline FILENAME = argv[2]; PORT = atoi(argv[3]); SERVERIP = argv[1]; //Setting up the data structures and variables struct hostent* host = gethostbyname(SERVERIP); struct sockaddr_in sendSockAddr; bzero((char*)& sendSockAddr, sizeof(sendSockAddr)); sendSockAddr.sin_family = AF_INET; sendSockAddr.sin_addr.s_addr = inet_addr( inet_ntoa( *(struct in_addr*)*host->h_addr_list )); sendSockAddr.sin_port = htons(PORT); int clientSd = socket(AF_INET, SOCK_STREAM, 0); //Establish the connection with server if(connect(clientSd, (sockaddr*)&sendSockAddr,sizeof(sendSockAddr))) { perror("ERROR on connect\n"); exit(1); } //Sending the requets if(sendRequest(clientSd)) { printf("Request Sucess\n\n"); printf("---------------------------------------\n"); } else { printf("Request Fail\n\n"); printf("---------------------------------------\n"); } return 0; }<file_sep>#ifndef BINTREE_H #define BINTREE_H #include<iostream> #include"nodedata.h" #include<algorithm> #include<string> #include<sstream> using namespace std; class BinTree { // you add class/method comments and assumptions friend ostream& operator<<(ostream& out, const BinTree& tree); public: //Constructor and Destructors BinTree(); BinTree(const BinTree& tree); ~BinTree(); //Main functons bool isEmpty() const; void makeEmpty(); BinTree& operator=(const BinTree& otherTree); bool operator==(const BinTree& otherTree) const; bool operator!=(const BinTree& otherTree) const; bool insert(NodeData* newNode); bool retrieve(const NodeData& value, NodeData*& holder); int getHeight(const NodeData& value) const; void bstreeToArray(NodeData* arr []); void arrayToBSTree(NodeData* arr []); void displaySideways() const; private: //Data Fields struct Node { NodeData* data; // pointer to data object Node* left; // left subtree pointer Node* right; // right subtree pointer Node(NodeData* nd = NULL, Node* l = NULL, Node* r = NULL) { data = nd; left = l; right = r; } }; Node* root; //Utility/helper functions int countArraySize(NodeData* arr[]); void arrayToBSTreeHelper(Node* node, int begin, int end, NodeData* arr[]); int bstreeToArrayHelper(Node* node, NodeData* arr[]); bool findNode(NodeData& value, Node* node, Node*& holder) const; bool compareTree(Node* node1, Node* node2) const; bool copyTree(const Node* node); void makeEmptyHelper(Node* node); int getHeightHelper(Node*& node) const; bool retrieveHelper(Node*& node, const NodeData& value, NodeData*& holder); bool insertHelper(Node*& node, NodeData* newData); void inorderHelper(Node* node) const; void sideways(Node* current, int level) const; }; #endif <file_sep>from urllib import request import sys import time #data field url = sys.argv[1] + "/stats" wait = int(sys.argv[3]) outputFile = "record.tsv" #Setup time to stop oneHour = 3600 startTime = time.time() #Keep reading the stats of website and record to file with open("record.tsv", "w") as file: while True: if (startTime == oneHour): break req = request.urlopen(url) data = req.read().decode('utf-8').split("\n") for line in data[:4]: store = line.split(": ")[1] file.write(store + "\t") file.write("\n") time.sleep(wait)<file_sep>To compile program, please run the bash script by: $ chmod u+x build.sh $ ./build.sh After, there should be an ass1.exe, please run with mono by: $ mono ass1.exe args1 args2 To run with prefined arugements, please run the "run.sh" script by: $ chmod u+x build.sh $ ./run.sh - The program is build on MacOS and tested on Windows and MacOS. - If possible please run on MacOS - Only dependency is System.Net.Http - The build.sh uses csc /r:System.Net.Http.dll - MUST include /r:System.Net.Http.dll to compile! - My dotnet --version: 3.1.100<file_sep>#! /bin/bash cd serverDir/ g++ -pthread -std=c++11 server.cpp -o server.out -g cd ../retrieverDir/ g++ -std=c++11 retriever.cpp -o retriever.out -g cd ../serverDir/ ./server.out 1499<file_sep>#pragma #include "udphw3.h" // Test2: client stop and wait message send ----------------------------------- int udphw3:: clientStopWait( UdpSocket &sock, const int max, int *message ) { //For loop, using i as our sequence number int count = 0; for (int i = 0; i < max; i++) { message[0] = i; sock.sendTo((char*)message, MSGSIZE); //Move foward if ack is equal to i if(sock.pollRecvFrom() > 0) { sock.recvFrom((char*) message, MSGSIZE); //Reset i back if ack does not match if(message[0] != i) { i--; count++; continue; } } else { //A incompaitable ack indicate a chance of packet lost //So we start the timer Timer t; t.start(); while(sock.pollRecvFrom() <= 0) { if(t.lap() > 1500) { break; } } //Only arrive here when there is a time out occurs if(t.lap() >= 1500) { i--; count++; continue; } } } return count; } // Test2: server stop and wait message send ----------------------------------- void udphw3:: serverReliable(UdpSocket &sock, const int max, int *message) { //For-loop to match the sequence number of the sender for(int i = 0; i < max; i++) { //This loop will enscapsulate the function until condition is met while(sock.pollRecvFrom() >= 0) { sock.recvFrom((char *) message, MSGSIZE); //Only break out of the loop if the sequence number matches if(message[0] == i) { //Only send back the correct ack sock.ackTo((char *) &i, sizeof(i)); break; } } } } // Test3: client sliding window ----------------------------------- int udphw3::clientSlidingWindow( UdpSocket &sock, const int max, int *message, int windowSize ) { //count to keep track of the amount we need to retransmit, //ack - keep track of the amount of already acked sequence #, //nonAcked - keep track of the amount of non yet acked sequence # int count = 0; int acked = 0; int nonAcked = 0; for (int i = 0; i < max; i++) { //Timer at the beginning to keep track all transmitted sequence number //It will reset everytime we get a new ack Timer t; t.start(); //Only transmit when below the window size limit if(nonAcked < windowSize) { message[0] = i; sock.sendTo((char*)message, MSGSIZE); //Keep track of the all our non ack sequence number nonAcked++; } //Trap state that allow us to wait for the correct ack number if(nonAcked == windowSize) //2 == 2 { while(true) { if (sock.pollRecvFrom() > 0) { //Leave the trap state if get the correct ack number sock.recvFrom((char *) message, MSGSIZE); if (message[0] == acked) { acked++; nonAcked--; break; } } if(t.lap() > 1500) { //collect the current sequence # and window size then rid of all already acknowledged sequence # //start again where the most recent acked sequence number count = count + (i + windowSize - acked); i = acked; nonAcked = 0; continue; } } } } return count; } // Test3: server sliding window ----------------------------------- void udphw3::serverEarlyRetrans(UdpSocket &sock, const int max, int *message, int windowSize) { //For-loop to match the sequence number of the sender for(int i = 0; i < max; i++) { //Only increment the sequence number if the sequence number matches sock.recvFrom((char *) message, MSGSIZE); if(message[0] == i) { sock.ackTo((char *) &i, sizeof(i)); } //Reset i as long the sequence number doesn't match else { i--; sock.ackTo((char *) &i, sizeof(i)); } } }<file_sep>// // BST.h // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Public Function ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- void insert(T& value) - inserts the Node that contains movie data bool retrieve(const string director, const string movieName, T*& holder) - retrieves the Drama movie data bool retrieve(const string movieTitle, const int releaseYear, T*& holder) - retrieves the Comedy movie data bool retrieve(const string maFname, const string maLname, const int releaseMonth, const int releaseYear, T*& holder) - retrieves the Classic movie data bool isEmpty() - checks if the BST is empty void deleteTree() - deletes all the existing leaves and the root void display() - displays all the leaves on the BST ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Helper Function ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- void insertHelper(T& value, Node<T>*& node) - Helper function for insert() bool retrieveHelper(const string director, const string movieName, T*& holder, Node<T>* node) - Helper function for retrieve() 1 bool retrieveHelper(const string movieTitle, const int releaseYear, T*& holder, Node<T>* node) - Helper function for retrieve() 2 bool retrieveHelper(const string maFname, const string maLname, const int releaseMonth, const int releaseYear, T*& holder, Node<T>* node) - Helper function for retrieve() 3 void displayHelper(Node<T>* current, int level) - Helper function for display() void deleteTreeHelper(Node<T>* node) - Helper function for deleteTree() ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications - The BST is the data container for all the movies(Comedy, Drama, and Classic). - It saves the movie in each node, and sort them by the given instruction below -comedy movies(ëFí)sorted by Title, then Year it release -dramas (ëDí) are sorted by Director, then Title -classics (ëCí)are sorted by Release date, then Majoractor Assumption - Assuming that the movie data file is formatted in a given way by professor. */ // -------------------------------------------------------------------------------------------------------------------- #ifndef BST_HEADER #define BST_HEADER #include<iostream> #include"Movie.h" using namespace std; // templatized Node // contains data, node pointer to left and right template<class T> struct Node { // casting the default setting Node(T m = NULL, Node* r = NULL, Node* l = NULL) { data = m; right = r; left = l; } T data; Node<T>* right; Node<T>* left; }; template<class T> class BST { public: // constructor & destructor BST(); // Default constructor ~BST(); // Destructor // public function void insert(T& value); // inserts the Node that contains movie data bool retrieve(const string director, const string movieName, T*& holder); // retrieves the Drama movie data bool retrieve(const string movieTitle, const int releaseYear, T*& holder); // retrieves the Comedy movie data bool retrieve(const string maFname, const string maLname, const int releaseMonth, const int releaseYear, T*& holder); // retrieves the Classic movie data bool retrieveSame(const string maFname, const string maLname, const string movieName, const string director, const int releaseMonth, const int releaseYear, T*& holder); bool isEmpty() const; // checks if the BST is empty void deleteTree(); // deletes all the existing leaves and the root void display() const; // displays all the leaves on the BST private: Node<T>* root; // root node void insertHelper(T& value, Node<T>*& node); // Helper function for insert() bool retrieveHelper(const string director, const string movieName, T*& holder, Node<T>* node); // Helper function for retrieve() 1 bool retrieveHelper(const string movieTitle, const int releaseYear, T*& holder, Node<T>* node); // Helper function for retrieve() 2 bool retrieveHelper(const string maFname, const string maLname, const int releaseMonth, const int releaseYear, T*& holder, Node<T>* node); // Helper function for retrieve() 3 bool retrieveSameHelper(const string maFname, const string maLname, const string movieName, const string director, const int releaseMonth, const int releaseYear, T*& holder, Node<T>* node); void displayHelper(Node<T>* current, int level) const; // Helper function for display() void deleteTreeHelper(Node<T>* node); // Helper function for deleteTree() }; /*-------------------Default Constructor--------------------------*/ // Describtion // - Constructs the object with default setting // // Preconditions: No parameters are passed in. // Postconditions: The data variables are set as default value. template<class T> BST<T>::BST() { root = NULL; } // end of Constructor /*---------------------------------------------------------*/ /*-------------------Destructor--------------------------*/ // Describtion // - execute deleteTree until the root is NULL // // Preconditions: No parameters are passed in. // Postconditions: Deletes the entire BST template<class T> BST<T>::~BST() { if (root != NULL) { deleteTree(); } } // end of Constructor /*---------------------------------------------------------*/ /*-------------------insert ()--------------------------*/ // Describtion // - gets the address of the node and insert them through // its helper function // // Preconditions: Address of the node value is passed in // Postconditions: Calls the helper function to insert it in sorted order template<class T> void BST<T>::insert(T& value) { return insertHelper(value, root); } // end of insert /*---------------------------------------------------------*/ /*-------------------insertHelper--------------------------*/ // Describtion // - Helper function for the insert() // // Preconditions: Address of the node value and the root are passed in // Postconditions: Finds the correct spot and insert the node template<class T> void BST<T>::insertHelper(T& value, Node<T>*& node) { // If the root is null, instanciate the node if (node == NULL) { node = new Node<T>(value); } // if the movie exists, add to the movie stock else if (node->data == value) { node->data.addMovieStock(value.getMovieStock()); } // if its smaller move left else if (node->data > value) { insertHelper(value, node->left); } // if its bigger move right else if (node->data < value) { insertHelper(value, node->right); } } // end of Constructor /*---------------------------------------------------------*/ /*------------------- Retriever for dramaMovies --------------------------*/ // Describtion // - find the movie, and retrieves the information & data // // Preconditions: string director's name, movie title, and movie holder are passed in // Postconditions: call the helper function with parameters passed in template<class T> bool BST<T>::retrieve(const string director, const string movieName, T*& holder) { // calls the helper function and return true if the movie is found return retrieveHelper(director, movieName, holder, root); } // end of retrieve /*---------------------------------------------------------*/ /*-------------------dramaMovies retrieveHelper--------------------------*/ // Describtion // - Travels BST root node to the very bottom // - if movie is found, point the holder to the movie node and returns true // // Preconditions: string director's name, movie title, movie holder, and the root node are passed in // Postconditions: Travels BST root node to the very bottom to find the movie in the data container template<class T> bool BST<T>::retrieveHelper(const string director, const string movieName, T*& holder, Node<T>* node) { // general edge case #1 if (node == NULL) { return false; } // if the movie exists, point the holder to the node, and return true else if ((node->data.getDirectorName() == director) && (node->data.getMovieName() == movieName)) { holder = reinterpret_cast<T*>(node); return true; } else { // else travel down to the end of the BST return retrieveHelper(director, movieName, holder, node->left) || retrieveHelper(director, movieName, holder, node->right); } // if nothing works, return false return false; } // end of retrieveHelper /*---------------------------------------------------------*/ /*-------------------Retriever for comedyMovies--------------------------*/ // Describtion // - find the movie, and retrieves the information & data // // Preconditions: string director's name, movie title, and movie holder are passed in // Postconditions: call the helper function with parameters passed in template<class T> bool BST<T>::retrieve(const string movieTitle, const int releaseYear, T*& holder) { return retrieveHelper(movieTitle, releaseYear, holder, root); } // end of retrieve /*---------------------------------------------------------*/ /*-------------------RetrieverHelper for comedyMovies--------------------------*/ // Describtion // - Travels BST root node to the very bottom // - if movie is found, point the holder to the movie node and returns true // // Preconditions: string director's name, movie title, movie holder, and the root node are passed in // Postconditions: Travels BST root node to the very bottom to find the movie in the data container template<class T> bool BST<T>::retrieveHelper(const string movieTitle, const int releaseYear, T*& holder, Node<T>* node) { if (node == NULL) { return false; } else if ((node->data.getMovieName() == movieTitle) && (node->data.getReleaseYear() == releaseYear)) { holder = reinterpret_cast<T*>(node); return true; } else { return retrieveHelper(movieTitle, releaseYear, holder, node->left) || retrieveHelper(movieTitle, releaseYear, holder, node->right); } return false; } // end of retrieveHelper /*---------------------------------------------------------*/ /*-------------------Retriever for classicMovies--------------------------*/ // Describtion // - find the movie, and retrieves the information & data // // Preconditions: string director's name, movie title, and movie holder are passed in // Postconditions: call the helper function with parameters passed in template<class T> bool BST<T>::retrieve(const string maFname, const string maLname, const int releaseMonth, const int releaseYear, T*& holder) { return retrieveHelper(maFname, maLname, releaseMonth, releaseYear, holder, root); } // end of retrieve /*---------------------------------------------------------*/ /*-------------------Default Constructor--------------------------*/ // Describtion // - Travels BST root node to the very bottom // - if movie is found, point the holder to the movie node and returns true // // Preconditions: string director's name, movie title, movie holder, and the root node are passed in // Postconditions: Travels BST root node to the very bottom to find the movie in the data container template<class T> bool BST<T>::retrieveHelper(const string maFname, const string maLname, const int releaseMonth, const int releaseYear, T*& holder, Node<T>* node) { if (node == NULL) { return false; } else if ((node->data.getMaFirstName() == maFname) && (node->data.getMaLastName() == maLname) && (node->data.getReleaseYear() == releaseYear) && node->data.getReleaseMonth() == releaseMonth) { holder = reinterpret_cast<T*>(node); return true; } else { return retrieveHelper(maFname, maLname, releaseMonth, releaseYear, holder, node->left) || retrieveHelper(maFname, maLname, releaseMonth, releaseYear, holder, node->right); } return false; } // end of retrieveHelper /*---------------------------------------------------------*/ //retriever for classicMovies template<class T> bool BST<T>::retrieveSame(const string maFname, const string maLname, const string movieName, const string director, const int releaseMonth, const int releaseYear, T*& holder) { return retrieveSameHelper(maFname, maLname, movieName, director, releaseMonth, releaseYear, holder, root); } template<class T> bool BST<T>::retrieveSameHelper(const string maFname, const string maLname, const string movieName, const string director, const int releaseMonth, const int releaseYear, T*& holder, Node<T>* node) { if (node == NULL) { return false; } else if ((node->data.getMovieName() == movieName) && (node->data.getDirectorName() == director) && (node->data.getReleaseYear() == releaseYear) && (node->data.getReleaseMonth() == releaseMonth) && (node->data.getMovieStock() > 0) && node->data.getMaFirstName() != maFname && node->data.getMaLastName() != maLname) { holder = reinterpret_cast<T*>(node); return true; } else { return retrieveSameHelper(maFname, maLname, movieName, director, releaseMonth, releaseYear, holder, node->left) || retrieveSameHelper(maFname, maLname, movieName, director, releaseMonth, releaseYear, holder, node->right); } return false; } /*-------------------isEmpty--------------------------*/ // Describtion // - Checks if the tree is empty or not // // Preconditions: No parameters are passed in. // Postconditions: Returns true if the root is empty template<class T> bool BST<T>::isEmpty() const { if (root != NULL) { return false; } else { return true; } } // end of Constructor /*---------------------------------------------------------*/ /*-------------------deleteTree() --------------------------*/ // Describtion // - delete the node, leaf, on the BST // // Preconditions: No parameters are passed in. // Postconditions: Calls the helper function with passing the root template<class T> void BST<T>::deleteTree() { if (root == NULL) { return; } else { deleteTreeHelper(root); } } // end of Constructor /*---------------------------------------------------------*/ /*-------------------deleteTreeHelper--------------------------*/ // Describtion // - Deletes all the nodes in the BST // // Preconditions: The node pointer is passed in(usually root) // Postconditions: The function deletes entire BST recursively template<class T> void BST<T>::deleteTreeHelper(Node<T>* node) { // stops the recursive calls if (node == NULL) { return; } // recursive call deleteTreeHelper(node->left); deleteTreeHelper(node->right); delete node; node = NULL; } // end of Constructor /*---------------------------------------------------------*/ /*-------------------display-------------------------*/ // Describtion // - Displays entire BST nodes by one by one // // Preconditions: No parameters are passed in. // Postconditions: The function calls the helper function with passing root node template<class T> void BST<T>::display() const { displayHelper(root, 0); } // end of Constructor /*---------------------------------------------------------*/ /*-------------------displayHelper--------------------------*/ // Describtion // - Displays the node data one by one (in-order) // // Preconditions: root node and the integer of level are passed in // Postconditions: The function recursively travel inorder and prints out the data template<class T> void BST<T>::displayHelper(Node<T>* node, int level) const { if (node != NULL) { // left root right = inorder traversal displayHelper(node->left, level); cout << (node->data) << endl; // display information of object displayHelper(node->right, level); } } // end of Constructor /*---------------------------------------------------------*/ #endif <file_sep>// // Movie.h // FinalProject // // Created by <NAME> and kwontaeyoung on 8/15/19. // Copyright © 2019 Jun.Zhen&Tae.Y.Kwon. All rights reserved. // // // ------------------------------------------------graphm.h ------------------------------------------------------- // <NAME> & <NAME>. Implementation Group#5.CSS 343A // // Date of Last Modification = 8/15/19 // -------------------------------------------------------------------------------------------------------------------- // Purpose - The purpose of this program is to practice & to implement designing program, class inheritence, HashTable, // and choosing data structures that are efficient in storing data- Movie information and customer information. /* ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Getter & Setter ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- string getMovieName() - Returns Movie Title string getDirectorName() - Returns Director's name char getMovieType() - Returns Movie Genre int getReleaseYear() - Returns Released Year int getMovieStock() - Returns Movie DVD stock string getMovieDetails() - Returns string line of "Movie Name: " + movieName + " by " + directorName; bool Return() - Adds the movie stock for returning borrowed DVD bool borrow() - Subtracts the movie stock for borrowing DVD void addMovieStock() - Adds the movie stock, if the movie is already existed during the inserting movie data(Duplicated) ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- Default Operator Overloads ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- If the new derived movie classes don't have the overrided operator overloads, these will be executed. ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- virtual bool operator <() virtual bool operator >() virtual bool operator !=() virtual bool operator ==() ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- ------- */ // -------------------------------------------------------------------------------------------------------------------- // Notes on specifications, special algorithms, and assumptions. /* Specifications - This class is the Abstract Class. It contains the core functions & key data that every child movie class requires. Assumption - Assuming that the movie data file is formatted in a given way by professor. */ // -------------------------------------------------------------------------------------------------------------------- #ifndef Movie_h #define Movie_h #include <iostream> using namespace std; class Movie { public: // Constructor & Destructor Movie(); // Default constructor Movie(char mType, int mStock, string dName, string mName, int relYear); // data is set equal to parameter virtual ~Movie(); // Virtual destructor // Getter Function string getMovieName()const; // returns Movie Title string getDirectorName()const; // returns Director's name char getMovieType()const; // returns Movie Genre int getReleaseYear()const; // returns Released Year int getMovieStock()const; // returns Movie DVD stock string getMovieDetails() const; // returns string line of "Movie Name: " + movieName + " by " + directorName; bool Return(); // adds the movie stock for returning borrowed DVD bool borrow(); // subtracts the movie stock for borrowing DVD // Setter Function void addMovieStock(int stock); // adds the movie stock, if the movie is already existed(Duplicated) // Default operator overloads // These will be used only if the new derived movie class doesn't have over-written operators virtual bool operator <(Movie& other) const; virtual bool operator >(Movie& other) const; virtual bool operator !=(Movie& other) const; virtual bool operator ==(Movie& other) const; protected: string movieName; // Movie Title string directorName; // Director's name of the movie char movieType; // Movie Genre int releaseYear; // Released Year of the movie int movieStock; // DvD Stock of the movie int fmovieStock; }; #endif <file_sep>#!/usr/bin/python3 import fileinput #parsing the data, #store the artist and it's album into a dict #Store all the information give by input into a matrix uniqArtistAlbum = dict() lineList = [] #{ 0: Music, 1: Genre, 2: Artist, 3: Album, 4: Song, 5: Song Path } parsedMatrix = [] for line in fileinput.input(): lineList = line.strip().split("/") if(len(lineList) == 5 and (lineList[len(lineList)-1][:-1] != "disk")): #get rid of lines that have no songs lineList.append(line.strip()) parsedMatrix.append(lineList) artist = lineList[2] album = [lineList[3]] if(artist in uniqArtistAlbum): if(lineList[3] not in uniqArtistAlbum[artist]): uniqArtistAlbum[artist].append(lineList[3]) else: uniqArtistAlbum[artist] = album elif(len(lineList) == 6): #get the line that have disks lineList.append(line.strip()) parsedMatrix.append(lineList) artist = lineList[2] album = [lineList[3]] if(artist in uniqArtistAlbum): if(lineList[3] not in uniqArtistAlbum[artist]): uniqArtistAlbum[artist].append(lineList[3]) else: uniqArtistAlbum[artist] = album #Generating the data for html print('<html>') print(' <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />') print('<body>') print('<table border=\"1">') print(' <tr>') print(' <th>Artist</th>') print(' <th>Album</th>') print(' <th>Tracks</th>') print(' </tr>') parsedMatrix.sort(key=lambda tup: (tup[2], tup[5])) #Loop each artist and search for album by that artist and print for artists in sorted(uniqArtistAlbum): uniqArtistAlbum[artists].sort() albCount = len(uniqArtistAlbum[artists]) n = albCount for albums in uniqArtistAlbum[artists]: print(' <tr>') if(n == albCount): #print rowspan header only for the first album print('%s%d%s%s%s' %(' <td rowspan=\"', albCount, '\">', artists, '</td>' )) print('%s%s%s' % (' <td>',albums,'</td>')) print('%s' % (' <td>')) print('%s' % (' <table border=\"0\">')) for i in range(0, len(parsedMatrix)): if(parsedMatrix[i][2] == artists and parsedMatrix[i][3] == albums ): songPath = parsedMatrix[i][len(parsedMatrix[i])-1] songName = parsedMatrix[i][len(parsedMatrix[i])-2] print ('%s%s%s%s%s%s' %(' <tr><td><a href=', '\"', songPath, '\">', songName, '</a><td></tr>')) print('%s' % (' </table>')) print('%s' % (' </td>')) print(' </tr>') n-=1 print('</table>') print('<body>')<file_sep>import matplotlib.pyplot as graph import sys from datetime import datetime #default values fileName = sys.argv[1] dt = 60 #if user provides a flag if (len(sys.argv) > 2) and sys.argv[2] == "--delta_t" : dt = int(sys.argv[3]) else: print("incorrect argv") sys.exit() #find the time interval of data from collector.py timeJump = [] with open(fileName) as file: for i, line in enumerate(file): if(i > 1): break lineList = line.split() timeJump.append(int(lineList[0])) print(i) interval = dt // (timeJump[1] - timeJump[0]) #get all the values basied on the interval timeList = [] list200 = [] list404 = [] list500 = [] with open(fileName) as file: for i, line in enumerate(file): if( (i % interval) == 0): lineList = line.split() timeList.append(int(lineList[0])) list500.append(int(lineList[1])) list200.append(int(lineList[2])) list404.append(int(lineList[3])) #getting the change per each interval timeline = [] new200 = [] new404 = [] new500 = [] for i in range(1, len(list200)): new200.append(list200[i] - list200[i-1]) new404.append(list404[i] - list404[i-1]) new500.append(list500[i] - list500[i-1]) timeline.append(timeList[i]) #setting the timeline for the graph for i, time in enumerate(timeline): date = datetime.fromtimestamp(int(time)) timeline[i] = str(date.hour) + ":" + str(date.minute) #plot the graph using pyplot fig = graph.figure() graph.plot(timeline, new200, label = '200s') graph.plot(timeline, new404, label = '404s') graph.plot(timeline, new500, label = '500s') graph.ylabel("RPS(%d minute rate)" % (dt // 60)) graph.xlabel('Time') graph.legend() graph.title("Time Server Requests Over an Hour") fig.savefig('graph.jpg') graph.show()<file_sep>#! /bin/bash csc /r:System.Net.Http.dll ass1.cs<file_sep>console.log("Client-side code running"); // Hanldes the Load button. Once clicked, load data from URL into my blob then from blob into Table const loadButton = document.getElementById("loadButt"); loadButton.addEventListener("click", function(e) { console.log("button was clicked"); fetch("/load", { method: "GET" }) .then(response => { return response.text(); }) .then(response => { let lines = response.split('\n'); let ul = document.createElement('ul'); document.getElementById('queryOut').appendChild(ul); for (let i = 0; i < lines.length - 1; i++) { let partElement = lines[i].split(" "); let elementText = partElement[0] + partElement[1] + '\'s data has been loaded'; let li = document.createElement('li'); ul.appendChild(li); li.innerHTML += elementText; } }); }); // Handles the Clear button. Once clicked, delete all data in Blob and Table const clearButton = document.getElementById("clearButt"); clearButton.addEventListener("click", function(e) { console.log("button was clicked"); fetch("/clear", { method: "GET" }) .then(response => { return response.text(); }) .then(response => { document.getElementById('queryOut').innerHTML = response; }); }); // Handles the Query button. Query Table Storage for information const queryButton = document.getElementById("queryButt"); const firstText = document.getElementById('firstName'); const lastText = document.getElementById('lastName'); queryButton.addEventListener("click", function(e) { let serverEndpoint = ''; if (firstText && firstText.value && lastText && lastText.value) { serverEndpoint = '/query?firstName=' + firstText.value + '&lastName=' + lastText.value; hitServer(serverEndpoint); } else if (firstText && firstText.value) { serverEndpoint = '/query?firstName=' + firstText.value; hitServer(serverEndpoint); } else if (lastText && lastText.value) { serverEndpoint = '/query?lastName=' + lastText.value; hitServer(serverEndpoint); } else { console.log("No input"); } }); // Helper Function for query button function hitServer(endpoint) { console.log(endpoint); fetch(endpoint, { method: "GET" }) .then(response => { return response.text(); }) .then(data => { let outputList = data.replace(/{|}|"|\[|\]/g,""); outputList = outputList.replace(/:/g, ' = ') outputList = outputList.replace(/,/g, ', ') outputList = outputList.replace(/lastName/g, '*lastName') let messlist = outputList.split('*'); let ul = document.createElement('ul'); document.getElementById('queryOut').appendChild(ul); console.log(messlist); messlist.forEach(line => { let li = document.createElement('li'); ul.appendChild(li); li.innerHTML += line; }) }); }<file_sep>#include "udphw3case4.h" // Test4: client sliding window (same as test 3 because only the retriever is dropping the packet) ----------------------------------- int udphw3case4::clientSlidingWindow( UdpSocket &sock, const int max, int *message, int windowSize ) { //count to keep track of the amount we need to retransmit, //ack - keep track of the amount of already acked sequence #, //nonAcked - keep track of the amount of non yet acked sequence # int count = 0; int acked = 0; int nonAcked = 0; for (int i = 0; i < max; i++) { //Timer at the beginning to keep track all transmitted sequence number //It will reset everytime we get a new ack Timer t; t.start(); //Only transmit when below the window size limit if(nonAcked < windowSize) { message[0] = i; sock.sendTo((char*)message, MSGSIZE); //Keep track of the all our non ack sequence number nonAcked++; } //Trap state that allow us to wait for the correct ack number if(nonAcked == windowSize) //2 == 2 { while(true) { if (sock.pollRecvFrom() > 0) { //Leave the trap state if get the correct ack number sock.recvFrom((char *) message, MSGSIZE); if (message[0] == acked) { acked++; nonAcked--; break; } } //Time out and collect the amount we need to retransmit if(t.lap() > 1500) { count = count + (i + windowSize - acked); i = acked; nonAcked = 0; continue; } } } } return count; } // Test4: server sliding window with drop ----------------------------------- void udphw3case4::serverEarlyRetrans(UdpSocket &sock, const int max, int *message, int windowSize, int dropChance) { //For-loop to match the sequence number of the sender for (int i = 0; i < max; i++) { //Trapping state to enusre we get the correct corresponading number while (true) { if (sock.pollRecvFrom() > 0) { int chance = rand() % 101; //Only drop the packet if we roll the chance lower than the drop chance if (dropChance > chance) { continue; } //This won't excute if we drop because of continue //By utltizing continue, we can skip transmitting back sock.recvFrom((char *) message, MSGSIZE); sock.ackTo((char *) &i, sizeof(i)); if (message[0] == i) { //Get out of the trap state and move onto the next sequence number break; } } } } }
f8736b96b8af3fec6bda6ecced7bf538ac39ddf1
[ "HTML", "JavaScript", "Java", "C#", "Text", "Python", "C++", "Shell" ]
69
C++
jpzhen/School-Homework
e46efbb9f5b4835af430177cf9c6d3631b97f29f
588184fe56d940553e75d9eb486701ed27e461a3
refs/heads/master
<repo_name>patelsoham/minimax<file_sep>/connect4.go package main import ( "fmt" "strconv" "strings" "time" ) const ( EMPTY = iota P1 = iota P2 = iota EMPTY_COLOR = "\033[1;37m%s\033[0m" //White P1_COLOR = "\033[1;31m%s\033[0m" //Red P2_COLOR = "\033[1;36m%s\033[0m" //Teal MAX = 2147483647 MIN = -2147483648 ) var colors = []string{EMPTY_COLOR, P1_COLOR, P2_COLOR} type BitBoard struct { boards []int64 //two 64 bit integers (longs) for each player's board rows, cols, heights int } type Board struct { board [][]int //height 0 @ row n-1, height 1 @ row n-2, ..., height n @ row 0. heights int //each columns height (can eventually be converted to int64-> byte per col) } func getBitBoard(rows int, cols int) *BitBoard { return &BitBoard{make([]int64, 2), rows, cols, 0} } func strToBitBoard(game_state string, sep string) *BitBoard { b := getBitBoard(6, 7) player := 1 moves := strings.Split(game_state, sep) fmt.Println(moves) for col := range moves { col_val, _ := strconv.ParseInt(moves[col], 10, 32) b.modBoard(int(col_val), player, 1) player ^= 3 } return b } func (b *BitBoard) copyBoard() *BitBoard { new_boards := make([]int64, 2) copy(new_boards, b.boards) new_heights := b.heights return &BitBoard{new_boards, b.rows, b.cols, new_heights} } func (b *BitBoard) modBoard(col int, player int, delta int) { cur_height := ((0xF << uint(col*4)) & b.heights) >> uint(col*4) if delta > 0 { b.boards[player>>1] ^= (1 << uint(cur_height+(col*7))) cur_height += delta } else { cur_height += delta b.boards[player>>1] ^= (1 << uint(cur_height+(col*7))) } if cur_height > b.rows || cur_height < 0 { fmt.Printf("Invalid Height at col %d: %d made by player %d. Must be at most %d\n", col, cur_height, player, b.rows) b.printBoard() b.getHeights() fmt.Println(movesAvailable(b.heights, b.rows, b.cols)) panic(cur_height) } b.heights &= ^(0xF << uint(col*4)) b.heights |= (cur_height << uint(col*4)) } //Took this optimization of hasWon from https://github.com/denkspuren/BitboardC4/blob/master/BitboardDesign.md func (b *BitBoard) hasWon(player int) bool { var directions = []uint{1, 7, 6, 8} cur_board := b.boards[player>>1] var masked_board int64 for i := range directions { masked_board = cur_board & (cur_board >> directions[i]) if (masked_board & (masked_board >> (2 * directions[i]))) != 0 { return true } } return false } func (b *BitBoard) gameState(depth int, player int) (int, int) { st := time.Now() if b.hasWon(P1) { incrementGameState(time.Now().Sub(st)) return MAX, P1 } else if b.hasWon(P2) { incrementGameState(time.Now().Sub(st)) return MIN, P2 } else if len(movesAvailable(b.heights, b.rows, b.cols)) == 0 { incrementGameState(time.Now().Sub(st)) return 0, 0 } else if depth == 0 { score := b.scoreBoard(player) incrementGameState(time.Now().Sub(st)) return score, player } incrementGameState(time.Now().Sub(st)) return -1, -1 } func (b *BitBoard) printBoard() { fmt.Printf("BitBoard\n") for i := b.rows - 1; i >= 0; i-- { for j := 0; j < b.cols; j++ { cur_cell_1 := ((((b.boards[0]) & (0xFF << uint(j*7))) >> uint(j*7)) >> uint(i)) & 1 cur_cell_2 := ((((b.boards[1]) & (0xFF << uint(j*7))) >> uint(j*7)) >> uint(i)) & 1 fmt.Printf(colors[cur_cell_1+(cur_cell_2*2)], "O ") } fmt.Printf("\n") } } func (b *BitBoard) getHeights() { fmt.Printf("Heights for each column \n") for i := 0; i < b.cols; i++ { fmt.Printf("%d ", ((0xF<<uint(i*4))&b.heights)>>uint(i*4)) } fmt.Printf("\n") } func countBits(n int64) int { count := 0 for n > 0 { n &= (n - 1) count++ } return count } func scoreWindow(window []int64, player int) int { score := 0 opp_player := player ^ 3 player_count := countBits(window[player>>1]) opp_player_count := countBits(window[opp_player>>1]) empty_count := 4 - player_count - opp_player_count if player_count == 4 { score += 100 } else if player_count == 3 && empty_count == 1 { score += 5 } else if player_count == 2 && empty_count == 2 { score += 2 } if opp_player_count == 3 && empty_count == 1 { score -= 4 } return score } // logic obtained from https://github.com/KeithGalli/Connect4-Python/ func (b *BitBoard) scoreBoard(player int) int { score := 0 opp_player := player ^ 3 center_board := (b.boards[player>>1] >> 21) & (0x7F) center_count := countBits(center_board) score += center_count * 3 // next we will score windows of 4 spots at a time in the rows, columns and diagonals to calculate our score windows := make([]int64, 2) // score rows for r := uint(0); r < 6; r++ { for c := uint(0); c < 4; c++ { curr_board_player := b.boards[player>>1] curr_board_opp := b.boards[opp_player>>1] bit_pos := (1 << (r + 7*c)) | (1 << (r + 7*(c+1))) | (1 << (r + 7*(c+2))) | (1 << (r + 7*(c+3))) curr_board_player &= int64(bit_pos) curr_board_opp &= int64(bit_pos) windows[player>>1] = curr_board_player windows[opp_player>>1] = curr_board_opp score += scoreWindow(windows, player) } } // score cols for c := uint(0); c < 7; c++ { for r := uint(0); r < 3; r++ { curr_board_player := b.boards[player>>1] curr_board_opp := b.boards[opp_player>>1] start := c * 7 bit_pos := (1 << (start + r)) | (1 << (start + r + 1)) | (1 << (start + r + 2)) | (1 << (start + r + 3)) curr_board_player &= int64(bit_pos) curr_board_opp &= int64(bit_pos) windows[player>>1] = curr_board_player windows[opp_player>>1] = curr_board_opp score += scoreWindow(windows, player) } } // score + diagonal for r := uint(0); r < 3; r++ { for c := uint(0); c < 4; c++ { curr_board_player := b.boards[player>>1] curr_board_opp := b.boards[opp_player>>1] start := r + c*7 bit_pos := (1 << (start)) | (1 << (start + 8*1)) | (1 << (start + 8*2)) | (1 << (start + 8*3)) curr_board_player &= int64(bit_pos) curr_board_opp &= int64(bit_pos) windows[player>>1] = curr_board_player windows[opp_player>>1] = curr_board_opp score += scoreWindow(windows, player) } } // score - diagonal for r := uint(0); r < 3; r++ { for c := uint(0); c < 4; c++ { curr_board_player := b.boards[player>>1] curr_board_opp := b.boards[opp_player>>1] start := 5 - r + c*7 bit_pos := (1 << (start)) | (1 << (start + 6*1)) | (1 << (start + 6*2)) | (1 << (start + 6*3)) curr_board_player &= int64(bit_pos) curr_board_opp &= int64(bit_pos) windows[player>>1] = curr_board_player windows[opp_player>>1] = curr_board_opp score += scoreWindow(windows, player) } } // player is the minimizer so we negate the score if player == P2 { score *= -1 } return score } func getBoard(row int, col int) *Board { arr := make([][]int, row) for i := range arr { arr[i] = make([]int, col) } return &Board{arr, 0} } func (b *Board) modBoard(col int, player int, delta int) { cur_height := ((0xF << uint(col*4)) & b.heights) >> uint(col*4) if delta > 0 { b.board[len(b.board)-cur_height-1][col] = player cur_height += delta } else { cur_height += delta b.board[len(b.board)-cur_height-1][col] = player } if cur_height > len(b.board) || cur_height < 0 { fmt.Printf("Invalid Height at col %d: %d\n", col, cur_height) panic(cur_height) } b.heights &= ^(0xF << uint(col*4)) b.heights |= (cur_height << uint(col*4)) } func (b *Board) hasWon(player int) bool { //Horizontal for c := 0; c < len(b.board[0])-3; c++ { for r := 0; r < len(b.board); r++ { if b.board[r][c] == player && b.board[r][c+1] == player && b.board[r][c+2] == player && b.board[r][c+3] == player { fmt.Println("horizontal win") return true } } } //Vertical for r := 0; r < len(b.board)-3; r++ { for c := 0; c < len(b.board[0]); c++ { if b.board[r][c] == player && b.board[r+1][c] == player && b.board[r+2][c] == player && b.board[r+3][c] == player { fmt.Println("vertical win") return true } } } //Ascending Diagonals (L->R), Descending Diagonals (R->L) for r := 3; r < len(b.board); r++ { for c := 0; c < len(b.board[0])-3; c++ { if b.board[r][c] == player && b.board[r-1][c+1] == player && b.board[r-2][c+2] == player && b.board[r-3][c+3] == player { fmt.Println("ascending diagonals") return true } } } //Descending Diagonals (L->R), Ascending Diagonals (R->L) for r := 0; r < len(b.board)-3; r++ { for c := 0; c < len(b.board[0])-3; c++ { if b.board[r][c] == player && b.board[r+1][c+1] == player && b.board[r+2][c+2] == player && b.board[r+3][c+3] == player { fmt.Println("descending diagonals") return true } } } return false } func (b *Board) gameState() (int, int) { if b.hasWon(P1) { return MAX, P1 } else if b.hasWon(P2) { return MIN, P2 } else if len(movesAvailable(b.heights, len(b.board), len(b.board[0]))) == 0 { return 0, 0 } return -1, -1 } func (b *Board) printBoard() { fmt.Printf("2D Array Board\n") for i := range b.board { for j := range b.board[i] { fmt.Printf(colors[b.board[i][j]], "O ") } fmt.Printf("\n") } fmt.Printf("Heights for each column \n") for i := 0; i < len(b.board[0]); i++ { fmt.Printf("%d ", ((0xF<<uint(i*4))&b.heights)>>uint(i*4)) } fmt.Printf("\n") } func movesAvailable(heights int, height_lim int, max_moves int) []int { //get slice of columns with spaces based on heights moves := make([]int, 0) for i := 0; i < max_moves; i++ { if ((0xF<<uint(i*4))&heights)>>uint(i*4) < height_lim { moves = append(moves, i) } } return moves } func max(a int, b int) int { if a > b { return a } else { return b } } func min(a int, b int) int { if a < b { return a } else { return b } } <file_sep>/README.md # Minimax Implementations of Sequential and Parallel Minimax and Minimax with Alpha-Beta Pruning in Golang. <file_sep>/sequential.go package main import ( "fmt" "math/rand" "time" ) var moves []int var count int64 = 0 var per_10_mil time.Duration var st time.Time func seq_minimax(b *BitBoard, player int, depth int) (int, int) { game_res, player_res := b.gameState(depth, player) if game_res != -1 || player_res != -1 { count += 1 return game_res, player_res } avail_moves := movesAvailable(b.heights, b.rows, b.cols) if player == P1 { opt_val := MIN opt_move := avail_moves[rand.Intn(len(avail_moves))] for i := range avail_moves { b.modBoard(avail_moves[i], player, 1) val, _ := seq_minimax(b, player^3, depth-1) b.modBoard(avail_moves[i], player, -1) if val > opt_val { opt_val = val opt_move = avail_moves[i] } } return opt_val, opt_move } else if player == P2 { opt_val := MAX opt_move := avail_moves[rand.Intn(len(avail_moves))] for i := range avail_moves { b.modBoard(avail_moves[i], player, 1) val, _ := seq_minimax(b, player^3, depth-1) b.modBoard(avail_moves[i], player, -1) if val < opt_val { opt_val = val opt_move = avail_moves[i] } } return opt_val, opt_move } else { fmt.Printf("Invalid player number %d\n", player) panic(player) } } func seq_minimax_ab(b *BitBoard, player int, alpha int, beta int, depth int) (int, int) { game_res, player_res := b.gameState(depth, player) if game_res != -1 || player_res != -1 { count += 1 return game_res, player_res } if player == P1 { opt_val := MIN avail_moves := movesAvailable(b.heights, b.rows, b.cols) opt_move := avail_moves[rand.Intn(len(avail_moves))] for i := range avail_moves { b.modBoard(avail_moves[i], player, 1) val, _ := seq_minimax_ab(b, player^3, alpha, beta, depth-1) b.modBoard(avail_moves[i], player, -1) if val > opt_val { opt_val = val opt_move = avail_moves[i] } alpha = max(alpha, opt_val) if beta <= alpha { return opt_val, opt_move } } moves = append(moves, opt_move) return opt_val, opt_move } else if player == P2 { opt_val := MAX avail_moves := movesAvailable(b.heights, b.rows, b.cols) opt_move := avail_moves[rand.Intn(len(avail_moves))] for i := range avail_moves { b.modBoard(avail_moves[i], player, 1) val, _ := seq_minimax_ab(b, player^3, alpha, beta, depth-1) b.modBoard(avail_moves[i], player, -1) if val < opt_val { opt_val = val opt_move = avail_moves[i] } beta = min(beta, opt_val) if beta <= alpha { return opt_val, opt_move } } return opt_val, opt_move } else { fmt.Printf("Invalid player number %d\n", player) panic(player) } } func seq(impl int, depth int, debug int) { board := getBitBoard(6, 7) st = time.Now() game_res, player_res, move, player := 0, 0, 0, 1 moves := make([]int, 0) if impl == SEQ { fmt.Printf("Sequential Ran\n") g1, g2 := board.gameState(MAX, player) for g1 == -1 && g2 == -1 { game_res, move = seq_minimax(board, player, depth) if debug == 1 { fmt.Printf("Move %d is placing in column %d by player %d with value %d\n", moves_count, move, player, game_res) } moves = append(moves, move) board.modBoard(move, player, 1) player ^= 3 moves_count += 1 g1, g2 = board.gameState(MAX, player) } game_res, player_res = board.gameState(MAX, player) } else if impl == SEQ_AB { fmt.Printf("Sequential_AB Ran\n") g1, g2 := board.gameState(MAX, player) for g1 == -1 && g2 == -1 { game_res, move = seq_minimax_ab(board, player, MIN, MAX, depth) if debug == 1 { fmt.Printf("Move %d is placing in column %d by player %d\n", moves_count, move, player) } moves = append(moves, move) board.modBoard(move, player, 1) player ^= 3 moves_count += 1 g1, g2 = board.gameState(MAX, player) } game_res, player_res = board.gameState(MAX, player) } fmt.Printf("Total Moves Required: %d\n", len(moves)) fmt.Println(moves) fmt.Printf("The game result %d for player %d. %d boards explored.\n", game_res, player_res, count) board.printBoard() } <file_sep>/Makefile GO = go BUILD = build RUN = run TARGET = minmax all: clean build run run: $(TARGET) ./$(TARGET) build: $(GO) $(BUILD) -o $(TARGET) *.go clean: rm -f *.o minmax<file_sep>/minmax.go package main import ( "flag" "fmt" "sync" "time" ) type benchmarks struct { endtoend time.Duration gameState time.Duration } var lock sync.Mutex func incrementGameState(toAdd time.Duration) { return // comment this line to calculate the amount time spent calculating the game state for metrics lock.Lock() metrics.gameState += toAdd lock.Unlock() } func getGameState() float64 { return metrics.gameState.Seconds() } var metrics benchmarks var moves_count int = 0 var debug int = 0 const ( SEQ = iota SEQ_AB = iota PARALLEL = iota PARALLEL_AB = iota NUM_IMPL = iota ) func main() { impl, depth, pdepth, ab_percent_sequential := 0, 0, 0, 0.0 metrics := benchmarks{0, 0} flag.IntVar(&impl, "i", 0, "which implementation to run: 0 = sequential, 1 = sequential_ab, 2 = parallel, 3 = parallel_ab") flag.IntVar(&depth, "d", 5, "max depth of algorithms") flag.IntVar(&pdepth, "pd", -1, "max depth computed in parallel") flag.IntVar(&debug, "debug", 0, "include debug printing") flag.Float64Var(&ab_percent_sequential, "ab", 0.5, "percentage of the parallel AB solution done in sequential") flag.Parse() if pdepth == -1 || pdepth > depth { pdepth = depth } fmt.Printf("impl: %d, depth: %d, pdepth: %d, PERCENT_SEQ: %.5f\n", impl, depth, pdepth, ab_percent_sequential) st := time.Now() switch { case impl < 2: seq(impl, depth, debug) case impl >= 2 && impl < NUM_IMPL: parallel(impl, depth, pdepth, ab_percent_sequential, debug) default: fmt.Println("Default case entered") } metrics.endtoend += time.Now().Sub(st) // print metrics fmt.Printf("End to End Time: %.5f\nGame State Computation Time: %.10f\n", metrics.endtoend.Seconds(), getGameState()) } <file_sep>/parallel.go package main import ( "fmt" "math/rand" "time" ) var PERCENT_SEQ float64 = 0.0 var PERCENT_PARALLEL float64 = 1 - PERCENT_SEQ type move struct { val int player int opt_move int col int } func parallel_minimax_chan(b *BitBoard, player int, depth int, pdepth int, col int, ret chan move) { game_res, player_res := b.gameState(depth, player) if game_res != -1 || player_res != -1 { count += 1 ret <- move{game_res, player_res, -1, col} return } avail_moves := movesAvailable(b.heights, b.rows, b.cols) if player == P1 { if pdepth == 0 { opt_val, opt_move := seq_minimax(b, player, depth) ret <- move{opt_val, player, opt_move, col} return } else { //launch goroutines and compute in parallel result := make(chan move) opt_val := MIN opt_move := avail_moves[rand.Intn(len(avail_moves))] for i := range avail_moves { nb := b.copyBoard() nb.modBoard(avail_moves[i], player, 1) go parallel_minimax_chan(nb, player^3, depth-1, pdepth-1, avail_moves[i], result) } for i := 0; i < len(avail_moves); i++ { cur_res := <-result if cur_res.val > opt_val { opt_val = cur_res.val opt_move = cur_res.col } else if cur_res.val == opt_val { opt_move = min(opt_move, cur_res.col) } } ret <- move{opt_val, player, opt_move, col} return } } else if player == P2 { if pdepth == 0 { opt_val, opt_move := seq_minimax(b, player, depth) ret <- move{opt_val, player, opt_move, col} return } else { //launch goroutines and compute in parallel result := make(chan move) opt_val := MAX opt_move := avail_moves[rand.Intn(len(avail_moves))] for i := range avail_moves { nb := b.copyBoard() nb.modBoard(avail_moves[i], player, 1) go parallel_minimax_chan(nb, player^3, depth-1, pdepth-1, avail_moves[i], result) } for i := 0; i < len(avail_moves); i++ { cur_res := <-result if cur_res.val < opt_val { opt_val = cur_res.val opt_move = cur_res.col } else if cur_res.val == opt_val { opt_move = min(opt_move, cur_res.col) } } ret <- move{opt_val, player, opt_move, col} return } } else { fmt.Printf("Invalid player number %d\n", player) panic(player) } } func parallel_minimax_chan_ab(b *BitBoard, player int, depth int, pdepth int, alpha int, beta int, col int, ret chan move, doReturn bool) move { game_res, player_res := b.gameState(depth, player) if game_res != -1 || player_res != -1 { count += 1 if !doReturn { ret <- move{game_res, player_res, -1, col} } return move{game_res, player_res, -1, col} } avail_moves := movesAvailable(b.heights, b.rows, b.cols) if player == P1 { if pdepth == 0 { opt_val, opt_move := seq_minimax_ab(b, player, alpha, beta, depth) if !doReturn { ret <- move{opt_val, player, opt_move, col} } return move{opt_val, player, opt_move, col} } else { opt_val := MIN opt_move := avail_moves[rand.Intn(len(avail_moves))] result := make(chan move) //compute percentage of tree sequentially to utilize alpha-beta pruning (principle variation search) for i := 0; i < int(PERCENT_SEQ*float64(len(avail_moves))); i++ { nb := b.copyBoard() nb.modBoard(avail_moves[i], player, 1) cur_result := parallel_minimax_chan_ab(nb, player^3, depth-1, pdepth-1, alpha, beta, avail_moves[i], result, true) if cur_result.val > opt_val { opt_val = cur_result.val opt_move = cur_result.col } else if cur_result.val == opt_val { opt_move = min(opt_move, cur_result.col) } alpha = max(alpha, opt_val) if beta <= alpha { if !doReturn { ret <- move{opt_val, player, opt_move, col} } return move{opt_val, player, opt_move, col} } } for i := int(PERCENT_SEQ * float64(len(avail_moves))); i < len(avail_moves); i++ { nb := b.copyBoard() nb.modBoard(avail_moves[i], player, 1) go parallel_minimax_chan_ab(nb, player^3, depth-1, pdepth-1, alpha, beta, avail_moves[i], result, false) } //Gather step for minimax for i := int(PERCENT_SEQ * float64(len(avail_moves))); i < len(avail_moves); i++ { cur_result := <-result if cur_result.val > opt_val { opt_val = cur_result.val opt_move = cur_result.col } else if cur_result.val == opt_val { opt_move = min(opt_move, cur_result.col) } alpha = max(alpha, opt_val) if beta <= alpha { if !doReturn { ret <- move{opt_val, player, opt_move, col} } return move{opt_val, player, opt_move, col} } } if !doReturn { ret <- move{opt_val, player, opt_move, col} } return move{opt_val, player, opt_move, col} } } else if player == P2 { if pdepth == 0 { opt_val, opt_move := seq_minimax_ab(b, player, alpha, beta, depth) if !doReturn { ret <- move{opt_val, player, opt_move, col} } return move{opt_val, player, opt_move, col} } else { opt_val := MAX opt_move := avail_moves[rand.Intn(len(avail_moves))] result := make(chan move) //compute percentage of tree sequentially to utilize alpha-beta pruning (principle variation search) //we don't need to make a copy of the board because the moves are done sequentially for i := 0; i < int(PERCENT_SEQ*float64(len(avail_moves))); i++ { nb := b.copyBoard() nb.modBoard(avail_moves[i], player, 1) cur_result := parallel_minimax_chan_ab(nb, player^3, depth-1, pdepth-1, alpha, beta, avail_moves[i], result, true) if cur_result.val < opt_val { opt_val = cur_result.val opt_move = cur_result.col } else if cur_result.val == opt_val { opt_move = min(opt_move, cur_result.col) } beta = min(beta, opt_val) if beta <= alpha { if !doReturn { ret <- move{opt_val, player, opt_move, col} } return move{opt_val, player, opt_move, col} } } for i := int(PERCENT_SEQ * float64(len(avail_moves))); i < len(avail_moves); i++ { nb := b.copyBoard() nb.modBoard(avail_moves[i], player, 1) go parallel_minimax_chan_ab(nb, player^3, depth-1, pdepth-1, alpha, beta, avail_moves[i], result, false) } for i := int(PERCENT_SEQ * float64(len(avail_moves))); i < len(avail_moves); i++ { cur_result := <-result if cur_result.val < opt_val { opt_val = cur_result.val opt_move = cur_result.col } else if cur_result.val == opt_val { opt_move = min(opt_move, cur_result.col) } beta = min(beta, opt_val) if beta <= alpha { if !doReturn { ret <- move{opt_val, player, opt_move, col} } return move{opt_val, player, opt_move, col} } } if !doReturn { ret <- move{opt_val, player, opt_move, col} } return move{opt_val, player, opt_move, col} } } else { fmt.Printf("Invalid player number %d\n", player) panic(player) } } func parallel(impl int, depth int, pdepth int, percent_ab float64, debug int) { board := getBitBoard(6, 7) game_res, player_res, cur_move, player := 0, 0, 0, 1 st = time.Now() moves := make([]int, 0) if impl == PARALLEL { fmt.Printf("Parallel Ran\n") ret := make(chan move) g1, g2 := board.gameState(MAX, player) for g1 == -1 && g2 == -1 { go parallel_minimax_chan(board, player, depth, pdepth, rand.Intn(7), ret) result := <-ret game_res, cur_move = result.val, result.opt_move if debug == 1 { fmt.Printf("Move %d is placing in column %d by player %d with value %d\n", moves_count, cur_move, player, game_res) } moves = append(moves, cur_move) board.modBoard(cur_move, player, 1) player ^= 3 moves_count += 1 g1, g2 = board.gameState(MAX, player) } game_res, player_res = board.gameState(MAX, player) } else if impl == PARALLEL_AB { fmt.Printf("Parallel_AB Ran\n") ret := make(chan move) PERCENT_SEQ = percent_ab PERCENT_PARALLEL = 1 - PERCENT_SEQ g1, g2 := board.gameState(MAX, player) for g1 == -1 && g2 == -1 { go parallel_minimax_chan_ab(board, player, depth, pdepth, MIN, MAX, rand.Intn(7), ret, false) result := <-ret game_res, cur_move = result.val, result.opt_move if debug == 1 { fmt.Printf("Move %d is placing in column %d by player %d\n", moves_count, cur_move, player) } moves = append(moves, cur_move) board.modBoard(cur_move, player, 1) player ^= 3 moves_count += 1 g1, g2 = board.gameState(MAX, player) } game_res, player_res = board.gameState(MAX, player) } fmt.Printf("Total Moves Required: %d\n", len(moves)) fmt.Println(moves) fmt.Printf("The game result %d for player %d. %d boards explored.\n", game_res, player_res, count) board.printBoard() }
d31939f2ffc40bba5a96b3d1c5778d6e73affece
[ "Markdown", "Go", "Makefile" ]
6
Go
patelsoham/minimax
ec61bf0ab33a817aaceb8263c386afe18b43b85e
4fb35977b05684dfa75379509a41ab21e5b1a4b7
refs/heads/master
<repo_name>JohnBart/Amaispedida<file_sep>/app/src/main/java/com/example/amaispedida/domain/Musica.java package com.example.amaispedida.domain; /** * Created by <NAME> on 12/07/2017. */ public class Musica { private String musica; private String compositor; public Musica() { } public Musica(String musica, String compositor) { this.musica = musica; this.compositor = compositor; } public String getMusica() { return musica; } public void setMusica(String musica) { this.musica = musica; } public String getCompositor() { return compositor; } public void setCompositor(String compositor) { this.compositor = compositor; } } <file_sep>/app/src/main/java/com/example/amaispedida/adapters/MusicaRecyclerViewAdapter.java package com.example.amaispedida.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.amaispedida.R; import com.example.amaispedida.domain.Musica; import java.util.List; /** * Created by <NAME> on 18/07/2017. */ public class MusicaRecyclerViewAdapter extends RecyclerView.Adapter<MusicaRecyclerViewAdapter.ViewHolder>{ private List<Musica> mList; private Context context; public MusicaRecyclerViewAdapter(List<Musica> mList, Context context) { this.mList = mList; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.musica_cardview, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder holder, int position) { Musica musica = mList.get(position); holder.musicaTextView.setText(musica.getMusica()); holder.compositorTextView.setText(musica.getCompositor()) ; } @Override public int getItemCount() { return mList.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ public TextView musicaTextView; public TextView compositorTextView; public ViewHolder(View itemView) { super(itemView); musicaTextView = (TextView) itemView.findViewById(R.id.musica_textview); compositorTextView = (TextView) itemView.findViewById(R.id.compositor_textview); } } } <file_sep>/app/src/main/java/com/example/amaispedida/domain/Evento.java package com.example.amaispedida.domain; import android.widget.ImageView; import android.widget.ListView; /** * Created by <NAME> on 11/07/2017. */ public class Evento { private Integer imagemArtista; private String nomeEvento; private String nomeArtista; private String generoMusical; private String localShow; private String data; private String hora; public Evento() { } public Evento(Integer imagemArtista, String nomeEvento, String nomeArtista, String generoMusical, String localShow, String data, String hora) { this.nomeEvento = nomeEvento; this.imagemArtista = imagemArtista; this.nomeArtista = nomeArtista; this.generoMusical = generoMusical; this.localShow = localShow; this.data = data; this.hora = hora; } public String getNomeEvento() { return nomeEvento; } public void setNomeEvento(String nomeEvento) { this.nomeEvento = nomeEvento; } public Integer getImagemArtista() { return imagemArtista; } public void setImagemArtista(Integer imagemArtista) { this.imagemArtista = imagemArtista; } public String getNomeArtista() { return nomeArtista; } public void setNomeArtista(String nomeArtista) { this.nomeArtista = nomeArtista; } public String getGeneroMusical() { return generoMusical; } public void setGeneroMusical(String generoMusical) { this.generoMusical = generoMusical; } public String getLocalShow() { return localShow; } public void setLocalShow(String localShow) { this.localShow = localShow; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getHora() { return hora; } public void setHora(String hora) { this.hora = hora; } }<file_sep>/app/src/main/java/com/example/amaispedida/interfaces/CadastroMusicaActivity.java package com.example.amaispedida.interfaces; 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.example.amaispedida.R; import com.example.amaispedida.database.DBController; import com.example.amaispedida.domain.Musica; public class CadastroMusicaActivity extends AppCompatActivity { DBController database; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastro_musica); database = new DBController(this); Button bt_salvar = (Button) findViewById(R.id.bt_salvar_musica_cadastro); bt_salvar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText ed_musica = (EditText) findViewById(R.id.ed_musica_cadastro_musica); EditText ed_compositor = (EditText) findViewById(R.id.ed_compositor_cadastro_musica); String musicast = ed_musica.getText().toString(); String compositorst = ed_compositor.getText().toString(); long id_artista = 1; if(musicast.isEmpty()||compositorst.isEmpty()){ alert("Campo em branco, favor preencher todo o formulário"); }else if(database.isMusicInDatabase(musicast, compositorst, id_artista)){ alert("Musica já cadastrada"); }else{ Musica musica = new Musica(); musica.setMusica(musicast); musica.setCompositor(compositorst); database.insertMusica(musica, id_artista); alert("Musica cadastrada"); } } }); } public void alert(String str){ Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } } <file_sep>/app/src/main/java/com/example/amaispedida/database/DBCreator.java package com.example.amaispedida.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by erick on 26/07/17. */ class DBCreator extends SQLiteOpenHelper { private static final String USERS_TABLE = "users"; private static final String EVENTS_TABLE = "events"; private static final String SONGS_TABLE = "songs"; private static final String TABLE_CREATE_USERS = "create table if not exists "+USERS_TABLE+"(" + "_id integer primary key autoincrement, " + "name text not null, login text not null, " + "password text not null, profile text not null);"; private static final String TABLE_CREATE_EVENTS = "create table if not exists "+EVENTS_TABLE+"(" + "_id_event integer primary key autoincrement, "+ "name_event text not null, id_artist integer, " + "name_artist text not null, music_style text not null," + " date text not null, hour text not null);"; private static final String TABLE_CREATE_MUSICS = "create table if not exists "+SONGS_TABLE+"(" + "_id_music integer primary key autoincrement, "+ "song text not null, composer text not null, " + "id_artist integer);"; //composer é o que compôs a musica, id_artist é o artista que cadastrou a musica no seu repertório DBCreator(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(TABLE_CREATE_USERS); sqLiteDatabase.execSQL(TABLE_CREATE_EVENTS); sqLiteDatabase.execSQL(TABLE_CREATE_MUSICS); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { sqLiteDatabase.execSQL("drop table if exists "+USERS_TABLE+";"); sqLiteDatabase.execSQL("drop table if exists "+EVENTS_TABLE+";"); sqLiteDatabase.execSQL("drop table if exists "+SONGS_TABLE+";"); onCreate(sqLiteDatabase); } } <file_sep>/app/src/main/java/com/example/amaispedida/interfaces/CadastroUserActivity.java package com.example.amaispedida.interfaces; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.Toast; import com.example.amaispedida.R; import com.example.amaispedida.database.DBController; import com.example.amaispedida.domain.User; /** * Created by <NAME> on 20/07/2017. */ public class CadastroUserActivity extends AppCompatActivity { //DatabaseHelper database = new DatabaseHelper(this); DBController database; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cadastro_user); database = new DBController(this); Button btsignup = (Button) findViewById(R.id.signup_button); btsignup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText name = (EditText) findViewById(R.id.name_input_edittext); EditText login = (EditText) findViewById(R.id.login_input_edittext); EditText password1 = (EditText) findViewById(R.id.password_input_edittext1); EditText password2 = (EditText) findViewById(R.id.password_input_edittext2); String namest = name.getText().toString(); String loginst = login.getText().toString(); String password1st = <PASSWORD>().<PASSWORD>(); String password2st = <PASSWORD>.getText().toString(); String profilest = null; RadioGroup profilerg = (RadioGroup) findViewById(R.id.profile_radiogroup); switch (profilerg.getCheckedRadioButtonId()){ case R.id.espectador_radiobutton: profilest = "espectador"; break; case R.id.musico_radiobutton: profilest = "musico"; break; } if(namest.isEmpty()||loginst.isEmpty()||password1st.isEmpty()||password2st.isEmpty()){ alert("Campo em branco, favor preencher todo o formulário"); }else if(database.isLoginInDatabase(loginst)){ alert("Login indisponivel, escolher outro"); } else if (!password1st.equals(password2st)) { alert("Senhas diferentes"); } else { User user = new User(); user.setName(namest); user.setLogin(loginst); user.setPassword(<PASSWORD>); user.setProfile(profilest); database.insertUser(user); alert("Usuário cadastrado"); } } }); } public void alert(String str){ Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); } } <file_sep>/README.txt # Amaispedida Projeto de disciplina Projeto tem por objetivo, utilizar elementos de programação da plataforma android para criar um APP que ira utilizar SQL com content provider para criar uma lista de musicas que ira compor o repertório de usuário músico, o usuário espectador poderá consultar esta lista e realizar o pedido para que o musico toque esta musica. Ao realizar a solicitação, o músico deve ser notificado do pedido. O que já foi implementado: ACTIVITYS solicitarMusicaActivity / EspectadorMainActivity / LoginActivity CadastrarShowActivity - SelecionarRepertorioActivity | \ / | MusicoMainActivity -- CadastrarMusicaRepertorioActivity | \ CadastroActivity ExecutarRepertorioActivity 1) LoginActivity - Efetua o login do usuário, com base em username(email) e senha. - Se o usuário não possuir cadastro, chama a CadastroActivity para efetuar o cadastro. - Dependendo do perfil de quem está realizando o login, chama EspectadorMainActivity ou MusicoMainActivity. 2) CadastroActivity - Usuário deve realizar cadastro fornecendo nome, e-mail e senha. - Deve selecionar atravez de um checkbox o tipo do perfil (musico ou espectador). 3) EspectadorMainActivity - Abre uma lista de cards, com os shows cadastrados e demais informações - pode vizualizar o repertório do artista, podenso solicitar musicas dentro de uma lista pré cadastrada ou cadastrar uma musica nova. 4) MusicoMainActivity - Possuí um menu de opção, onde pode optar por cadastrar um novo show, cadastrar as musicas do repertório e realizar o controle de musicas executadas/pedidas durante um show. 5) CadastrarShowActivity - Realiza o cadastro de um novo show, inserindo data, hora e local, alem de poder selecionar dentro da lista de músicas cadastradas do usuário como as do repertório daquele show (via SelecionarRepertorioActivity). 6) SelecionarRepertorioActivity - Seleciona dentro da lista de músicas cadastradas do usuário musico como as do repertório daquele show. 7) CadastrarMusicaRepertorioActivity - Cadastra dentro de uma lista uma nova música dentro do repertório do artistas (músicas que ele sabe tocar). 8) ExecutarRepertorioActivity - Acompanha a execução de um show pré cadastrado, o usuário musico visualiza as musicas cadastrada para tocar naquele show, podendo retirá -las após a execução, nesta tela tambem são exibidas as musicas solicitadas pelo usuário espectador. ADAPTERS 1) MusicaListViewAdapter 2) EventoListViewAdapter Classes de suporte 1)Evento: cria atributos para implementar a atividade evento. Utilizar Get and set para acessar e alterar as variaveis desta classe. 2)Musica: Iden a 1. RES 1) Colors: Contem a definição de cores do app, atentar para o uso correto seguindo padrão Matherial Design. <file_sep>/app/src/main/java/com/example/amaispedida/interfaces/MusicoMainActivity.java package com.example.amaispedida.interfaces; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.example.amaispedida.R; import com.example.amaispedida.database.DBController; import com.example.amaispedida.domain.User; public class MusicoMainActivity extends AppCompatActivity { DBController database; private User user = new User(); Button bt_cadastrar_musica; Button bt_consultar_musicas; Button bt_cadastrar_evento; Button bt_consultar_eventos; String id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_musico_main); database = new DBController(this); //Recuperando informação via intent id = getIntent().getStringExtra("id"); Toast.makeText(this, "O id desse caboco é: "+id, Toast.LENGTH_SHORT).show(); bt_cadastrar_musica = (Button) findViewById(R.id.bt_cadastrar_musica); bt_cadastrar_musica.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MusicoMainActivity.this, CadastroMusicaActivity.class); i.putExtra("id",user.getId() ); i.putExtra("name", user.getName()); startActivity(i); } }); bt_consultar_musicas = (Button) findViewById(R.id.bt_consultar_musicas); bt_consultar_musicas.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MusicoMainActivity.this, MusicasActivity.class); i.putExtra("id",user.getId() ); i.putExtra("name", user.getName()); startActivity(i); } }); bt_cadastrar_evento = (Button) findViewById(R.id.bt_cadastrar_evento); bt_cadastrar_evento.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MusicoMainActivity.this, CadastroEventoActivity.class); i.putExtra("id",user.getId() ); i.putExtra("name", user.getName()); startActivity(i); } }); bt_consultar_eventos = (Button) findViewById(R.id.bt_consultar_eventos); bt_consultar_eventos.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); } @Override public void onBackPressed() { //Ação tomada ao pressionar o botão voltar AlertDialog.Builder adb = new AlertDialog.Builder(this); adb.setMessage("Deseja realmente sair?"); adb.setNegativeButton("Não", null); adb.setPositiveButton("Sim", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); adb.show(); } } <file_sep>/app/src/main/java/com/example/amaispedida/database/DBController.java package com.example.amaispedida.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.example.amaispedida.domain.Evento; import com.example.amaispedida.domain.Musica; import com.example.amaispedida.domain.User; import java.util.ArrayList; /** * Created by erick on 26/07/17. */ public class DBController { private static final int DATABASE_VERSION = 2; private static final String DATABASE_NAME = "Contacts.db"; private SQLiteDatabase db; private DBCreator dbCreator; public DBController(Context context) { dbCreator = new DBCreator(context, DATABASE_NAME, null, DATABASE_VERSION); db = dbCreator.getWritableDatabase(); } /*--------------------------------Usuarios--------------------------------------*/ public Boolean isLoginInDatabase(String login){ db = dbCreator.getReadableDatabase(); Cursor cursor; cursor = db.rawQuery("select login from users", null); String a; Boolean b = false; if(cursor.moveToFirst()){ do{ a = cursor.getString(0); if(a.equals(login)){ b = true; break; } }while(cursor.moveToNext()); } db.close(); return b; } public long returnIdUser(String login){ db = dbCreator.getReadableDatabase(); Cursor cursor; cursor = db.rawQuery("select login, _id from users", null); String a; long b = 0; if(cursor.moveToFirst()){ do{ a = cursor.getString(0); if(a.equals(login)){ b = cursor.getLong(1); break; } }while(cursor.moveToNext()); } db.close(); return b; } public void insertUser(User s){ db = dbCreator.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", s.getName()); values.put("login", s.getLogin()); values.put("password", s.<PASSWORD>()); values.put("profile", s.getProfile()); db.insert("users", null, values); db.close(); } public String searchPass(String login){ db = dbCreator.getReadableDatabase(); Cursor cursor; cursor = db.rawQuery("select login, password from users", null); String a,b = "not found"; if(cursor.moveToFirst()){ do{ a = cursor.getString(0); if(a.equals(login)){ b = cursor.getString(1); break; } }while(cursor.moveToNext()); } db.close(); return b; } public String searchProfile(String login){ db = dbCreator.getReadableDatabase(); Cursor cursor = db.rawQuery("select login, profile from users", null); String a,b = null; if(cursor.moveToFirst()){ do{ a = cursor.getString(0); if(a.equals(login)){ b = cursor.getString(1); break; } }while(cursor.moveToNext()); } db.close(); return b; } /*--------------------------------Eventos--------------------------------------*/ public void insertEvento(Evento e, long id_artista){ db = dbCreator.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name_event", e.getNomeEvento()); values.put("id_artist", id_artista); values.put("name_artist", e.getNomeArtista()); values.put("music_style", e.getGeneroMusical()); values.put("date", e.getData()); values.put("hour", e.getHora()); db.insert("events", null, values); db.close(); } /*--------------------------------Musicas--------------------------------------*/ public Boolean isMusicInDatabase(String song, String composer, long id){ db = dbCreator.getReadableDatabase(); Cursor cursor; cursor = db.rawQuery("select song, composer, id_artist from songs", null); String a,b; long c; Boolean aux = false; if(cursor.moveToFirst()){ do{ a = cursor.getString(0); b = cursor.getString(1); c = cursor.getLong(2); if(a.equals(song)&&b.equals(composer)&&(c == id)){ aux = true; break; } }while(cursor.moveToNext()); } db.close(); return aux; } public void insertMusica(Musica m, long id_artista){ db = dbCreator.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("song", m.getMusica()); values.put("composer", m.getCompositor()); values.put("id_artist", id_artista); db.insert("songs", null, values); db.close(); } public ArrayList<Musica> returnMusicsFromArtist(long id){ db = dbCreator.getReadableDatabase(); Cursor cursor; cursor = db.rawQuery("select song, composer from songs where id_artist = "+id, null); ArrayList<Musica> mList = new ArrayList<Musica>(); Musica musica = new Musica(); if(cursor.moveToFirst()){ do{ musica.setMusica(cursor.getString(0)); musica.setCompositor(cursor.getString(1)); mList.add(musica); }while(cursor.moveToNext()); } db.close(); return mList; } public int countLinesFromTable(String table){ db = dbCreator.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from "+table, null); int i = cursor.getCount(); return i; } } <file_sep>/app/src/main/java/com/example/amaispedida/interfaces/EspectadorMainActivity.java package com.example.amaispedida.interfaces; import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.ImageView; import com.example.amaispedida.R; import com.example.amaispedida.adapters.EventoRecyclerViewAdapter; import com.example.amaispedida.domain.Evento; import java.util.ArrayList; import java.util.List; public class EspectadorMainActivity extends Activity { private RecyclerView recyclerView; private RecyclerView.Adapter adapter; private List<Evento> mList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_espectador_main); recyclerView = (RecyclerView) findViewById(R.id.recyclerView_evento); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); mList = new ArrayList<>(); Evento evento; evento = new Evento(R.drawable.homer_rock, "Show de Rock", "The Simpsons", "Rock", "Bar do More", "Sexta, 22 Junho", "21:00"); mList.add(evento); evento = new Evento(R.drawable.guns, "Rock in Rio", "Guns n Roses", "Hard Rock", "Maracanã", "Quarta, 19 Ago", "20:00"); mList.add(evento); evento = new Evento(R.drawable.acdc, "Monsters of Rock", "AC/DC", "Hard Rock", "Allianz Parque", "Domingo, 7 Set", "22:00"); mList.add(evento); adapter = new EventoRecyclerViewAdapter(mList, this); recyclerView.setAdapter(adapter); } } <file_sep>/app/src/main/java/com/example/amaispedida/interfaces/LoginActivity.java package com.example.amaispedida.interfaces; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.amaispedida.R; import com.example.amaispedida.database.DBController; public class LoginActivity extends AppCompatActivity { private TextView tName; private TextView tLogin; private TextView tPassword; private String name; private String login; private String password; Button bt_login; Button bt_signup; DBController database; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); database = new DBController(this); bt_login = (Button)findViewById(R.id.button_login); bt_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { TextView tLogin = (TextView) findViewById(R.id.login_editText); TextView tPassword = (TextView) findViewById(R.id.password_editText); String login = tLogin.getText().toString(); String password = tPassword.getText().toString(); String passAux = database.searchPass(login); if (password.equals(passAux)) { String profileAux = database.searchProfile(login); long id = database.returnIdUser(login); Intent intent; if (profileAux.equals("espectador")) { intent = new Intent(LoginActivity.this, EspectadorMainActivity.class); } else { intent = new Intent(LoginActivity.this, MusicoMainActivity.class); } intent.putExtra("id", id); startActivity(intent); finish(); } else { alert("Login ou senha não conferem"); } } } ); bt_signup = (Button) findViewById(R.id.button_signup); bt_signup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(LoginActivity.this, CadastroUserActivity.class); startActivity(i); } }); } private void alert(String s) { Toast.makeText(this, s, Toast.LENGTH_LONG).show(); } }
3ff057113cf01833d855f280d5760eb3dfad28e7
[ "Java", "Text" ]
11
Java
JohnBart/Amaispedida
60b267dbf3ebc8edb0e6815aa83a7ba4291fb610
9ff5cfa22540da6235f313eec4ac89962c6eef37
refs/heads/master
<repo_name>pauloalexcosta/codingground<file_sep>/py4WAS/README.md This folder contains simple examples of WAS administration via CLI, using python/jython. <file_sep>/py4WAS/addUserToConsole.py #!/usr/bin/python # -*- coding: iso-8859-15 -*- # import sys and os import sys, os, os.path #testar user iswas = os.getlogin() if iswas is 'was': print('yep, user correcto') else: print('nope, volta à casa de partida') # Testar se sys.argv é string ou ficheiro #userlist = sys.argv[1] #print('userlist') #if os.path.isfile(sys.argv[1]) == 'true': # print('é ficheiro') #else: # print('é user') userlist=sys.argv[1] try: with open(userlist) as f: print("É ficheiro...") except IOError as e: print("Erro: não é ficheiro")
86de2510f3d2b54c67a012253843267360797fc5
[ "Markdown", "Python" ]
2
Markdown
pauloalexcosta/codingground
ab89151791325ea90e1bbbfc59674f7f99436d26
8fd72e6629b45690b44f2043f7427a400e95a662
refs/heads/master
<repo_name>GitHub-JYB/MyApplication<file_sep>/app/src/main/java/com/example/admin_jyb/myapplication/MainActivity.java package com.example.admin_jyb.myapplication; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.view.View; import android.widget.ImageView; import android.widget.RemoteViews; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.NotificationTarget; import com.example.admin_jyb.myapplication.Base.ToolBarActivity; import com.example.mvp.Image.ImageLoader; public class MainActivity extends ToolBarActivity { private NotificationTarget notificationTarget; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void setTitle() { getToolbar().setTitle("主界面"); } @Override protected int getContentViewId() { return R.layout.activity_main; } @Override protected void initView() { ImageView imageView = (ImageView) findViewById(R.id.image_view); ImageLoader.Builder builder = new ImageLoader.Builder(); builder.with(getApplicationContext()).load("https://www.baidu.com/img/bd_logo1.png").into(imageView); new ImageLoader(builder).showImage(); final RemoteViews rv = new RemoteViews(getBaseContext().getPackageName(), R.layout.remoteview_notification); rv.setImageViewResource(R.id.remoteview_notification_icon, R.mipmap.ic_launcher); rv.setTextViewText(R.id.remoteview_notification_headline, "Headline"); rv.setTextViewText(R.id.remoteview_notification_short_message, "Short Message"); // build notification NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getBaseContext()) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Content Title") .setContentText("Content Text") .setContent(rv) .setPriority( NotificationCompat.PRIORITY_MIN); final Notification notification = mBuilder.build(); // set big content view for newer androids if (android.os.Build.VERSION.SDK_INT >= 16) { notification.bigContentView = rv; } NotificationManager mNotificationManager = (NotificationManager) getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(1, notification); notificationTarget = new NotificationTarget( getBaseContext(), rv, R.id.remoteview_notification_icon, notification, 1); Glide .with( getApplicationContext() ) // safer! .load( "https://www.baidu.com/img/bd_logo1.png" ) .asBitmap() .into( notificationTarget ); } public void click(View view){ Intent intent = new Intent(this, ShowActivity.class); startActivity(intent); } } <file_sep>/app/src/main/java/com/example/admin_jyb/myapplication/Base/ToolBarActivity.java package com.example.admin_jyb.myapplication.Base; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import com.example.admin_jyb.myapplication.R; import com.example.mvp.Base.statusActivity; import cn.sharesdk.framework.ShareSDK; import cn.sharesdk.onekeyshare.OnekeyShare; /** * Created by Admin-JYB on 2017/4/11. */ public abstract class ToolBarActivity extends statusActivity { private Toolbar mToolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ShareSDK.initSDK(this,"1d111dbe093b0"); mToolbar = (Toolbar) findViewById(R.id.toolbar); if (mToolbar != null){ //将toolbar显示到界面 setTitle(); setSupportActionBar(mToolbar); } } protected abstract void setTitle(); @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.toolbar,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.setting: showShare(); break; case android.R.id.home: finish(); break; } return super.onOptionsItemSelected(item); } @Override protected void onStart() { super.onStart(); if (getToolbar() != null && isShowBacking()){ //默认显示左上角的图标 getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } /** * 是否显示后退按键,默认显示,可在子类重写该方法 * @return */ protected boolean isShowBacking() { return true; } public Toolbar getToolbar() { return (Toolbar) findViewById(R.id.toolbar); } private void showShare() { ShareSDK.initSDK(this); OnekeyShare oks = new OnekeyShare(); //关闭sso授权 oks.disableSSOWhenAuthorize(); // title标题,印象笔记、邮箱、信息、微信、人人网和QQ空间等使用 oks.setTitle("标题"); // titleUrl是标题的网络链接,QQ和QQ空间等使用 oks.setTitleUrl("http://sharesdk.cn"); // text是分享文本,所有平台都需要这个字段 oks.setText("我是分享文本"); // imagePath是图片的本地路径,Linked-In以外的平台都支持此参数 //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片 // url仅在微信(包括好友和朋友圈)中使用 oks.setUrl("http://sharesdk.cn"); // comment是我对这条分享的评论,仅在人人网和QQ空间使用 oks.setComment("我是测试评论文本"); // site是分享此内容的网站名称,仅在QQ空间使用 oks.setSite(getString(R.string.app_name)); // siteUrl是分享此内容的网站地址,仅在QQ空间使用 oks.setSiteUrl("http://sharesdk.cn"); // 启动分享GUI oks.show(this); } } <file_sep>/mvp/src/main/java/com/example/mvp/Base/BaseActivity.java package com.example.mvp.Base; /** * Created by Admin-JYB on 2017/4/19. */ public abstract class BaseActivity extends superActivity implements BaseView{ @Override public void showLoading() { } @Override public void showError() { } @Override public void hideLoading() { } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // return checkBackAction() || super.onKeyDown(keyCode, event); // } // private boolean mFlag = false; // private long mTimeout = -1; // // /** // * 双击退出 // * @return // */ // private boolean checkBackAction() { // long time = 3000L;//判定时间间隔为3秒 // boolean flag = mFlag; // boolean timeout = (mTimeout == -1 || (System.currentTimeMillis() - mTimeout > time)); // if (mFlag && (mFlag != flag || timeout)){ // mTimeout = System.currentTimeMillis(); // ToastUtil.showShortToast("再点击一次回到桌面 "); // return true; // } // return !mFlag; // } } <file_sep>/app/src/main/java/com/example/admin_jyb/myapplication/View/ImageWithText.java package com.example.admin_jyb.myapplication.View; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.example.admin_jyb.myapplication.R; /** * Created by Admin-JYB on 2017/4/12. */ public class ImageWithText extends LinearLayout{ public ImageWithText(Context context) { super(context); } public ImageWithText(Context context, @Nullable AttributeSet attrs) { super(context, attrs); View view = LayoutInflater.from(context).inflate(R.layout.image_with_text, this, true); ImageButton btn = (ImageButton) view.findViewById(R.id.btn); TextView text = (TextView) view.findViewById(R.id.text); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ImageWithText); CharSequence text1 = typedArray.getText(R.styleable.ImageWithText_android_text); if (text != null)text.setText(text1); Drawable drawable = typedArray.getDrawable(R.styleable.ImageWithText_android_src); if (drawable != null)btn.setBackground(drawable); typedArray.recycle(); } } <file_sep>/app/src/main/java/com/example/admin_jyb/myapplication/Show/Bean/ShowModelImpl.java package com.example.admin_jyb.myapplication.Show.Bean; import com.example.admin_jyb.myapplication.Show.ShowContract; import com.example.mvp.Base.MvpListener; import com.example.mvp.Net.MyListener; import com.example.mvp.Net.OkHttp; import java.util.List; /** * Created by Admin-JYB on 2017/4/19. */ public class ShowModelImpl implements ShowContract.ShowModel { @Override public void loadData(String url, final MvpListener<List<ZhiHu.StoriesBean>> listener) { OkHttp.getIntance().get(url, ZhiHu.class, new MyListener<ZhiHu>() { @Override public void onSuccess(ZhiHu result) { listener.onSuccess(result.getStories()); } @Override public void onErroe(String errorMsg) { listener.onError(errorMsg); } }); } } <file_sep>/mvp/src/main/java/com/example/mvp/Base/statusActivity.java package com.example.mvp.Base; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.LinearLayout; import com.example.mvp.R; /** * Created by Admin-JYB on 2017/4/11. */ public abstract class statusActivity extends superActivity{ private View statusView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStatusColor(this,getResources().getColor(R.color.colorPrimary)); } protected void setStatusColor(Activity activity, int color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){ //设置状态栏透明 activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //生成一个状态栏大小的矩形 //添加statusView到布局中 ViewGroup decorView = (ViewGroup)activity.getWindow().getDecorView(); if (statusView != null){ decorView.removeView(statusView); } statusView = createStatusView(activity,color); decorView.addView(statusView); //设置根布局的参数 ViewGroup rootView = (ViewGroup) ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0); rootView.setFitsSystemWindows(true); rootView.setClipToPadding(true); } } /** * 生成一个状态栏大小的矩形 * * @param activity 需要设置的activity * @param color 状态条颜色 * @return 矩形状态条 */ private View createStatusView(Activity activity, int color) { //获得状态栏的高度 int resourcedId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android"); int statusHeight = activity.getResources().getDimensionPixelSize(resourcedId); //绘制一个和状态栏一样高的矩形 View statusView = new View(activity); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, statusHeight); statusView.setLayoutParams(params); statusView.setBackgroundColor(color); return statusView; } /** * 提供remove方法,在不需要状态栏时可以移除 */ public void removeView(Activity activity){ ViewGroup decorView = (ViewGroup)activity.getWindow().getDecorView(); if (statusView != null){ decorView.removeView(statusView); } } }
84e63a055050f692a96140dd1e50cd5284a9d009
[ "Java" ]
6
Java
GitHub-JYB/MyApplication
6e97f221a6da43165ba86c723bacfb36143bc72c
ed18495e1b9a909b9d941e8835a030155ff239c2
refs/heads/master
<file_sep>import { EditAnnouncementPage } from './../edit-announcement/edit-announcement'; import { Subscription } from 'rxjs/Subscription'; import { HomePage } from './../home/home'; import { NgForm } from '@angular/forms'; import { AngularFireDatabase } from 'angularfire2/database'; import { Component, OnDestroy } from '@angular/core'; import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular'; import { CommonProvider } from '../../providers/common'; @IonicPage() @Component({ selector: 'page-announcement', templateUrl: 'announcement.html', }) export class AnnouncementPage implements OnDestroy{ myDate= new Date().toISOString().substring(0,10); announcements; announcementsArray=[]; announcementSub: Subscription; constructor(public navCtrl: NavController, public navParams: NavParams, private afDB: AngularFireDatabase, private common: CommonProvider) { this.announcements = afDB.list('/announcements').snapshotChanges() .map( (changes) => { return changes.map( (data) => ({ key: data.payload.key, ...data.payload.val() }) ) } ); //extracting all the data from the observable and putting it in local array to be used this.announcementSub=this.announcements.subscribe( (data) => { this.announcementsArray = data; } ) } onSubmit(f: NgForm){ this.afDB.list('/announcements').push({title: f.value.title,description:f.value.description, date: this.myDate}); f.reset(); this.common.toastPop('Posted announcement','bottom').present(); } onRemoveAnnouncement(key: string){ this.afDB.object('/announcements/'+ key).remove(); this.common.toastPop('Removed announcement','bottom').present(); } onEditAnnouncement(announcement){ this.navCtrl.push(EditAnnouncementPage,announcement); } ngOnDestroy(){ this.announcementSub.unsubscribe(); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { CourtDatePage } from './courtdate'; @NgModule({ declarations: [ CourtDatePage, ], imports: [ IonicPageModule.forChild(CourtDatePage), ], }) export class CourtdatePageModule {} <file_sep>import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, ViewController } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-details-modal', templateUrl: 'details-modal.html', }) export class DetailsModalPage { reservationDetails; constructor(public navCtrl: NavController, public navParams: NavParams, private viewCtrl: ViewController) { this.reservationDetails=this.navParams.data; } onDismiss(){ this.viewCtrl.dismiss(); } } <file_sep>import { AngularFireDatabase } from 'angularfire2/database'; import { Subscription } from 'rxjs/Subscription'; import { AnnouncementPage } from './../pages/announcement/announcement'; import { CourtDatePage } from './../pages/courtdate/courtdate'; import { CommonProvider } from './../providers/common'; import { SigninPage } from './../pages/signin/signin'; import { Component, ViewChild } from '@angular/core'; import { Nav, Platform } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { AngularFireAuth } from 'angularfire2/auth'; import { HomePage } from '../pages/home/home'; import { ReservationHistoryPage } from '../pages/reservation-history/reservation-history'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; adminSub: Subscription; adminID: string; adminObject; pages: Array<{title: string, component: any}>; constructor(private afDB:AngularFireDatabase,public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen,private afAuth: AngularFireAuth, private common: CommonProvider) { this.initializeApp(); this.afAuth.authState.subscribe( (user) => { if(user){ this.adminSub=this.afDB.object('/admins/'+ user.uid).valueChanges() .subscribe( (adminName) => { this.adminObject= adminName; this.common.toastPop('Welcome, '+ this.adminObject.name, 'bottom').present(); } ) this.nav.setRoot(HomePage); this.common.setUser(user.uid,user.email); }else{ this.nav.setRoot(SigninPage); } } ) // used for an example of ngFor and navigation this.pages = [ { title: 'Reservation Requests', component: HomePage }, { title: 'View Courts', component: CourtDatePage }, { title: 'Post Announcement', component: AnnouncementPage }, { title: 'Reservation History', component: ReservationHistoryPage } ]; } initializeApp() { this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. this.statusBar.styleDefault(); this.splashScreen.hide(); }); } openPage(page) { // Reset the content nav to have just this page // we wouldn't want the back button to show in this scenario this.nav.setRoot(page.component); } onLogout(){ this.adminSub.unsubscribe(); this.afAuth.auth.signOut(); this.nav.setRoot(SigninPage); this.common.toastPop('Successfully logged out.', 'bottom').present(); } } <file_sep>import { Subscription } from 'rxjs/Subscription'; import { DetailsModalPage } from './../details-modal/details-modal'; import { AngularFireDatabase } from 'angularfire2/database'; import { Component, ViewChild, OnDestroy } from '@angular/core'; import { IonicPage, NavController, NavParams, ModalController } from 'ionic-angular'; @IonicPage() @Component({ selector: 'page-reservation-history', templateUrl: 'reservation-history.html', }) export class ReservationHistoryPage implements OnDestroy{ allReservation= []; searchedId: string; filteredArray=[]; reservationSub:Subscription; constructor(public navCtrl: NavController, public navParams: NavParams, private afDB: AngularFireDatabase, private modalCtrl: ModalController) { this.reservationSub=this.afDB.list('/reservation').snapshotChanges() .map( (changes) => { return changes.map( (data) => ({ key: data.payload.key, ...data.payload.val() }) ) } ).subscribe( (reservationStuff) => { this.allReservation= reservationStuff; this.filteredArray= this.allReservation; } ) } onViewDetails(reservation){ this.modalCtrl.create(DetailsModalPage,reservation).present(); } onInput(event){ if(this.searchedId !== ''){ // this.filteredArray= this.allReservation.filter(x=> x.reservationID.toString().startsWith(this.searchedId) !== -1); this.filteredArray= this.allReservation.filter(x=> x.reservationID.toString().substring(0,this.searchedId.length)=== this.searchedId); }else{ this.filteredArray= this.allReservation; } } onCancel(event){ } bodyListener(){ } ngOnDestroy(){ this.reservationSub.unsubscribe(); } } <file_sep>import { CommonProvider } from './../../providers/common'; import { Component, OnDestroy } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { AngularFireDatabase } from 'angularfire2/database'; import { Subscription } from 'rxjs/Subscription'; import { Reservation } from '../../models/reservation.model'; @IonicPage() @Component({ selector: 'page-courtlist', templateUrl: 'courtlist.html', }) export class CourtlistPage implements OnDestroy{ courtType: string; reservationFinal: Reservation; isBadminton=false; isSquash=false; isTakraw=false; isBasketball=false; isFootball=false; courtName:string; dateTime= { date:'', time:'' } reservationTimeRef$; reservationAfterChecking; RCArray= []; categoryKey:string; badmintonRef$; badmintonObservable; badminton2Sync=[]; squashRef$; squashObservable; squash2Sync=[]; takrawRef$; takrawObservable; takraw2Sync=[]; basketballRef$; basketballObservable; basketball2Sync=[]; footballRef$; footballObservable; football2Sync=[]; badmintonStatusUpdateRef$; squashStatusUpdateRef$; fee: number; badmintonRecentStatus=false; squashRecentStatus=false; takrawRecentStatus=false; basketballRecentStatus=false; footballRecentStatus=false; reservationTimeSub: Subscription; badmintonSub: Subscription; squashSub: Subscription; takrawSub: Subscription; basketballSub: Subscription; footballSub: Subscription; adminID; adminEmail; adminSub: Subscription; adminObject; constructor(private common:CommonProvider,public navCtrl: NavController, public navParams: NavParams, private afDB: AngularFireDatabase) { this.dateTime= this.navParams.get('dateTime'); console.log(this.dateTime); //get admin uid this.adminID=this.common.getUser(); this.adminEmail= this.common.getUserEmail(); console.log(this.adminID); let content = { email: this.adminEmail } this.afDB.object('/admins/'+ this.adminID).update(content); this.adminSub=this.afDB.object('/admins/'+ this.adminID).valueChanges() .subscribe( (adminName) => { this.adminObject= adminName; console.log(this.adminObject.name); } ) //retreving the reservation with the submitted date and time this.reservationTimeRef$= this.afDB.list('/reservationTimes/'+ this.dateTime.time + '/'+ this.dateTime.date); this.reservationAfterChecking = this.reservationTimeRef$.snapshotChanges() .map( (changes) => { return changes.map( (data) => ({ key: data.payload.key, ...data.payload.val() }) ) } ) // this.reservationAfterChecking.subscribe( // (data) => { // this.RCArray= data; // } // ) this.reservationTimeSub=this.reservationAfterChecking.subscribe( (data) => { this.RCArray= data; console.log(this.RCArray); this.RCArray.forEach( (check)=> { console.log(check.key); this.categoryKey=check.key; // problemmm (solved for now ) ( retreived the category on that date, now think about how to sync everything) this.badmintonRef$=this.afDB.list('/reservationTimes/'+ this.dateTime.time + '/'+ this.dateTime.date+'/'+ this.categoryKey+ '/category/0/courts'); this.badmintonObservable= this.badmintonRef$.valueChanges(); this.badmintonSub=this.badmintonObservable.subscribe( (badmintonStuff) => { this.badminton2Sync= badmintonStuff; } ) this.squashRef$=this.afDB.list('/reservationTimes/'+ this.dateTime.time + '/'+ this.dateTime.date+'/'+ this.categoryKey+ '/category/3/courts'); this.squashObservable= this.squashRef$.valueChanges(); this.squashSub=this.squashObservable.subscribe( (squashStuff) => { this.squash2Sync= squashStuff; } ) this.takrawRef$=this.afDB.list('/reservationTimes/'+ this.dateTime.time + '/'+ this.dateTime.date+'/'+ this.categoryKey+ '/category/4/courts'); this.takrawObservable= this.takrawRef$.valueChanges(); this.takrawSub=this.takrawObservable.subscribe( (takrawStuff) => { this.takraw2Sync= takrawStuff; console.log(this.takraw2Sync); } ) this.basketballRef$=this.afDB.list('/reservationTimes/'+ this.dateTime.time + '/'+ this.dateTime.date+'/'+ this.categoryKey+ '/category/1/courts'); this.basketballObservable= this.basketballRef$.valueChanges(); this.basketballSub=this.basketballObservable.subscribe( (basketballStuff) => { this.basketball2Sync= basketballStuff; } ) this.footballRef$=this.afDB.list('/reservationTimes/'+ this.dateTime.time + '/'+ this.dateTime.date+'/'+ this.categoryKey+ '/category/2/courts'); this.footballObservable= this.footballRef$.valueChanges(); this.footballSub=this.footballObservable.subscribe( (footballStuff) => { this.football2Sync= footballStuff; } ) } ) } ) } onChange(event){ // console.log(this.RCArray); if(event === 'badminton'){ this.isBadminton=true; this.isSquash=false; this.isTakraw=false; this.isBasketball=false; this.isFootball=false; this.squashRecentStatus= false; this.takrawRecentStatus= false; this.basketballRecentStatus= false; this.footballRecentStatus= false; }else if(event ==='squash'){ this.isBadminton=false; this.isSquash=true; this.isTakraw=false; this.isBasketball=false; this.isFootball=false; this.badmintonRecentStatus= false; this.takrawRecentStatus= false; this.basketballRecentStatus= false; this.footballRecentStatus= false; }else if(event ==='takraw'){ this.isBadminton=false; this.isSquash=false; this.isTakraw=true; this.isBasketball=false; this.isFootball=false; this.badmintonRecentStatus= false; this.squashRecentStatus= false; this.basketballRecentStatus= false; this.footballRecentStatus= false; }else if(event ==='basketball'){ this.isBadminton=false; this.isSquash=false; this.isTakraw=false; this.isBasketball=true; this.isFootball=false; this.badmintonRecentStatus= false; this.takrawRecentStatus= false; this.squashRecentStatus= false; this.footballRecentStatus= false; }else if(event ==='football'){ this.isBadminton=false; this.isSquash=false; this.isTakraw=false; this.isBasketball=false; this.isFootball=true; this.badmintonRecentStatus= false; this.takrawRecentStatus= false; this.basketballRecentStatus= false; this.squashRecentStatus= false; } else{ this.isBadminton=false; this.isSquash=false; this.isTakraw=false; this.isBasketball= false; this.isFootball= false; this.badmintonRecentStatus= false; this.squashRecentStatus=false; this.takrawRecentStatus= false; this.basketballRecentStatus= false; this.footballRecentStatus= false; } } onSelect(){ console.log(this.courtType); console.log(this.courtName); if(this.badmintonRecentStatus === true){ this.fee= 5; }else if(this.squashRecentStatus === true){ this.fee=3; }else if(this.takrawRecentStatus === true){ this.fee=4; }else if(this.basketballRecentStatus === true){ this.fee=7; }else if(this.footballRecentStatus === true){ this.fee=10; } // const reservationRef= this.afDB.list('reservation'); // reservationRef.push(this.reservationFinal); // this.navCtrl.push(ReserveDetailsPage,{courtType: this.courtType, courtName: this.courtName, dateTime: this.dateTime, fee: this.fee, approvedStatus: false, reservationKey: this.categoryKey, userName: this.userObject.name}); let randomID= Math.floor(Math.random() * 10000000000); this.reservationFinal=new Reservation(this.dateTime.date, this.dateTime.time, this.courtType, this.courtName, this.fee,true, true,'Admin',this.categoryKey,randomID, this.adminObject.name); const reservationRefForPush$= this.afDB.list('reservation'); reservationRefForPush$.push(this.reservationFinal); } onSelectCourt(courtName:string, bookedStatus){ this.courtName=courtName; if(bookedStatus==true){ this.badmintonRecentStatus= false; this.squashRecentStatus= false; this.takrawRecentStatus= false; this.basketballRecentStatus= false; this.footballRecentStatus= false; // console.log('badminton: ',this.badmintonRecentStatus); // console.log('squash:',this.squashRecentStatus); }else{ // console.log(this.courtName); // console.log(this.courtType); if(this.courtType=== 'badminton'){ this.badmintonRecentStatus= true; if(this.squashRecentStatus == true){ this.squashRecentStatus= false; }else if(this.takrawRecentStatus == true){ this.takrawRecentStatus= false; }else if(this.basketballRecentStatus == true){ this.basketballRecentStatus= false; }else if(this.footballRecentStatus == true){ this.footballRecentStatus= false; } // console.log('badminton: ',this.badmintonRecentStatus); // console.log('squash:',this.squashRecentStatus); }else if(this.courtType === 'squash'){ this.squashRecentStatus= true; if(this.badmintonRecentStatus == true){ this.badmintonRecentStatus= false; }else if(this.takrawRecentStatus == true){ this.takrawRecentStatus= false; }else if(this.basketballRecentStatus == true){ this.basketballRecentStatus= false; }else if(this.footballRecentStatus == true){ this.footballRecentStatus= false; } }else if(this.courtType === 'takraw'){ this.takrawRecentStatus= true; if(this.badmintonRecentStatus == true){ this.badmintonRecentStatus= false; }else if(this.squashRecentStatus == true){ this.squashRecentStatus= false; }else if(this.basketballRecentStatus == true){ this.basketballRecentStatus= false; }else if(this.footballRecentStatus == true){ this.footballRecentStatus= false; } } else if(this.courtType === 'basketball'){ this.basketballRecentStatus= true; if(this.badmintonRecentStatus == true){ this.badmintonRecentStatus= false; }else if(this.takrawRecentStatus == true){ this.takrawRecentStatus= false; }else if(this.squashRecentStatus == true){ this.squashRecentStatus= false; }else if(this.footballRecentStatus == true){ this.footballRecentStatus= false; } } else if(this.courtType === 'football'){ this.footballRecentStatus= true; if(this.badmintonRecentStatus == true){ this.badmintonRecentStatus= false; }else if(this.takrawRecentStatus == true){ this.takrawRecentStatus= false; }else if(this.basketballRecentStatus == true){ this.basketballRecentStatus= false; }else if(this.squashRecentStatus == true){ this.squashRecentStatus= false; } } } } ngOnDestroy(){ this.badmintonSub.unsubscribe(); this.squashSub.unsubscribe(); this.reservationTimeSub.unsubscribe(); this.takrawSub.unsubscribe(); this.basketballSub.unsubscribe(); this.footballSub.unsubscribe(); this.adminSub.unsubscribe(); } } <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { CourtlistPage } from './courtlist'; @NgModule({ declarations: [ CourtlistPage, ], imports: [ IonicPageModule.forChild(CourtlistPage), ], }) export class CourtlistPageModule {} <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { ReservationHistoryPage } from './reservation-history'; @NgModule({ declarations: [ ReservationHistoryPage, ], imports: [ IonicPageModule.forChild(ReservationHistoryPage), ], }) export class ReservationHistoryPageModule {} <file_sep>import { DetailsModalPage } from './../pages/details-modal/details-modal'; import { EditAnnouncementPage } from './../pages/edit-announcement/edit-announcement'; import { AnnouncementPage } from './../pages/announcement/announcement'; import { CourtDatePage } from './../pages/courtdate/courtdate'; import { CommonProvider } from './../providers/common'; import { SigninPage } from './../pages/signin/signin'; import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; import { MyApp } from './app.component'; import { HomePage } from '../pages/home/home'; import { AngularFireDatabaseModule, AngularFireDatabase } from 'angularfire2/database'; import { AngularFireModule } from 'angularfire2'; import { AngularFireAuthModule } from 'angularfire2/auth'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { CourtlistPage } from '../pages/courtlist/courtlist'; import { ReservationHistoryPage } from '../pages/reservation-history/reservation-history'; export const firebaseConfig = { apiKey: "<KEY>", authDomain: "angularfire-dummy.firebaseapp.com", databaseURL: "https://angularfire-dummy.firebaseio.com", projectId: "angularfire-dummy", storageBucket: "", messagingSenderId: "164158484108" }; @NgModule({ declarations: [ MyApp, HomePage, SigninPage, CourtDatePage, CourtlistPage, AnnouncementPage, EditAnnouncementPage, ReservationHistoryPage, DetailsModalPage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), AngularFireModule.initializeApp(firebaseConfig), AngularFireDatabaseModule, AngularFireAuthModule ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage, SigninPage, CourtDatePage, CourtlistPage, AnnouncementPage, EditAnnouncementPage, ReservationHistoryPage, DetailsModalPage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, CommonProvider ] }) export class AppModule {} <file_sep>import { NgModule } from '@angular/core'; import { IonicPageModule } from 'ionic-angular'; import { EditAnnouncementPage } from './edit-announcement'; @NgModule({ declarations: [ EditAnnouncementPage, ], imports: [ IonicPageModule.forChild(EditAnnouncementPage), ], }) export class EditAnnouncementPageModule {} <file_sep>import { AngularFireDatabase } from 'angularfire2/database'; import { CommonProvider } from './../../providers/common'; import { Component, ViewChild } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import { NgForm } from '@angular/forms'; @IonicPage() @Component({ selector: 'page-edit-announcement', templateUrl: 'edit-announcement.html', }) export class EditAnnouncementPage { announcementTitle; announcementDescription; announcementKey; aTitle: string; aDescrip: string; constructor(public navCtrl: NavController, public navParams: NavParams, private common: CommonProvider, private afDB: AngularFireDatabase) { this.announcementTitle= this.navParams.get('title'); this.announcementDescription= this.navParams.get('description'); this.announcementKey= this.navParams.get('key'); this.aTitle=this.announcementTitle; this.aDescrip= this.announcementDescription; } onEdit(){ this.afDB.object('/announcements/'+this.announcementKey).update({title: this.aTitle,description:this.aDescrip}); this.common.toastPop('Edited announcement','bottom').present(); this.navCtrl.pop(); } } <file_sep>import { Subscription } from 'rxjs/Subscription'; import { CommonProvider } from './../../providers/common'; import { AngularFireDatabase } from 'angularfire2/database'; import { Component, OnDestroy } from '@angular/core'; import { NavController, AlertController } from 'ionic-angular'; declare var jquery:any; declare var $ :any; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage implements OnDestroy{ reservationRef$; reservationObservable; reservationsArray =[]; filteredArray=[]; filteredArray1=[]; filteredArray2=[]; reservationTimeRef$; reservationAfterChecking; index:string; courtName:string; loading; searchedId:string; rejectReason: string; segment: string; reservationSub: Subscription; adminID: string; adminName:string; adminEmail:string; adminSub: Subscription; adminObject; constructor(public navCtrl: NavController, private afDB: AngularFireDatabase, private common: CommonProvider, private alertCtrl: AlertController) { this.segment="pending"; this.adminID=this.common.getUser(); this.adminEmail= this.common.getUserEmail(); console.log(this.adminID); let content = { email: this.adminEmail } this.afDB.object('/admins/'+ this.adminID).update(content); this.adminSub=this.afDB.object('/admins/'+ this.adminID).valueChanges() .subscribe( (adminName) => { this.adminObject= adminName; console.log(this.adminObject.name); } ) this.reservationRef$= this.afDB.list('reservation'); this.reservationObservable = this.reservationRef$.snapshotChanges() .map( (changes) => { return changes.map( (data) => ({ key: data.payload.key, ...data.payload.val() }) ) } ) this.reservationSub=this.reservationObservable.subscribe( (reservationStuff) =>{ this.reservationsArray= reservationStuff; this.filteredArray=this.reservationsArray.filter(x => (x.approvedStatus === false || x.paidStatus === false) && x.rejectedStatus=== undefined); this.filteredArray2=this.filteredArray; this.loading.dismiss(); } ) } onApprove(key: string, reservationKey:string, time:string, date:string, item:string, category:string, reservationID: number){ if(category==='badminton'){ this.index= '0'; if(item==='Badminton Court 1'){ this.courtName='bcourt1'; }else if(item ==='Badminton Court 2'){ this.courtName='bcourt2'; }else if(item ==='Badminton Court 3'){ this.courtName='bcourt3'; }else if(item ==='Badminton Court 4'){ this.courtName='bcourt4'; }else if(item ==='Badminton Court 5'){ this.courtName='bcourt5'; }else if(item ==='Badminton Court 6'){ this.courtName='bcourt6'; }else if(item ==='Badminton Court 7'){ this.courtName='bcourt7'; }else if(item ==='Badminton Court 8'){ this.courtName='bcourt8'; }else if(item ==='Badminton Court 9'){ this.courtName='bcourt9'; }else if(item ==='Badminton Court 10'){ this.courtName='bcourt9a'; }else if(item ==='Badminton Court 11'){ this.courtName='bcourt9b'; }else if(item ==='Badminton Court 12'){ this.courtName='bcourt9c'; } }else if(category ==='squash'){ this.index='3'; if(item==='Squash Court 1'){ this.courtName='scourt1'; }else if(item ==='Squash Court 2'){ this.courtName='scourt2'; } }else if(category ==='takraw'){ this.index='4'; if(item==='Sepak Takraw Court 1'){ this.courtName='stcourt1'; }else if(item ==='Sepak Takraw Court 2'){ this.courtName='stcourt2'; }else if(item ==='Sepak Takraw Court 3'){ this.courtName='stcourt3'; }else if(item ==='Sepak Takraw Court 4'){ this.courtName='stcourt4'; } }else if(category ==='basketball'){ this.index='1'; if(item==='Basketball Court 1'){ this.courtName='bbcourt1'; } }else if(category ==='football'){ this.index='2'; if(item==='Football Field'){ this.courtName='ffield'; } } this.afDB.object('/reservation/'+ key).update({approvedStatus: true, approvedBy: this.adminObject.name}); this.afDB.object('/reservationTimes/'+ time+'/'+date+'/'+reservationKey+'/category/'+this.index+'/courts/'+ this.courtName).update({isBooked: true}); this.common.toastPop('Approved request #'+ reservationID,'bottom').present(); this.searchedId=''; } ionViewDidLoad(){ this.loading=this.common.loadingSpinner('Loading'); this.loading.present(); } onReject(key: string, reservationID: number){ console.log('rejected'); this.alertCtrl.create({ title: 'What is the reason?', inputs: [ { name: 'reason', placeholder: 'Reason' } ], buttons: [ { text: 'Cancel', role:'cancel' }, { text: 'Confirm', handler: data => { this.rejectReason= data.reason; if(this.rejectReason != ""){ this.afDB.object('/reservation/'+ key).update({rejectedStatus: true, rejectedBy: this.adminObject.name, rejectedReason:this.rejectReason}); this.common.toastPop('Rejected request #'+ reservationID,'bottom').present(); }else{ this.common.toastPop('Please state your reason!','bottom').present(); } } } ] }).present(); // this.afDB.object('/reservation/'+ key).remove(); } onPaid(key :string, reservationID: string){ console.log('Paid'); this.afDB.object('/reservation/'+ key).update({paidStatus: true, payreceivedBy:this.adminObject.name}); this.common.toastPop('#'+reservationID + ' has paid','bottom').present(); this.searchedId=''; } onInput(event){ if(this.searchedId !== ''){ // this.filteredArray= this.allReservation.filter(x=> x.reservationID.toString().startsWith(this.searchedId) !== -1); this.filteredArray2= this.filteredArray.filter(x=> x.reservationID.toString().substring(0,this.searchedId.length)=== this.searchedId); }else{ this.filteredArray2= this.filteredArray; } } onCancel(){ } ngOnDestroy(){ this.reservationSub.unsubscribe(); this.adminSub.unsubscribe(); } // sendEmail(){ // $.ajax( // { // url: "https://api.mailgun.net/v3/juel.mydomain.com", // type:"POST", // username: 'key-485ec952f8804bded980eaf0d2e0925a', // password: '<PASSWORD>', // dataType: 'json', // data:{ // "html": `<h1>TITLE-HERE lololol</h1>`, // "subject":"Hello Ng <NAME>", // "from": "User<<EMAIL>>", // "to": "<EMAIL>" // }, // success:function(a,b,c){ // console.log( 'mail sent: ', b ); // }.bind(this), // error:function( xhr, status, errText ){console.log( 'mail sent failed: ', xhr.responseText );} // }) // } }
78629e33c83df8e1daec761f590f45eb4aa262d3
[ "TypeScript" ]
12
TypeScript
albusdunble1/sportAdmin
d78771bac6a1523288baeda05fbf84e664d8ba29
b1ebf20d3bbea564b287060afb3de76120cedb14
refs/heads/master
<file_sep>![banner](https://github.com/NBSChain/NBS-QML/blob/master/doc/banner.gif) [![GitHub issues](https://img.shields.io/github/issues/NBSChain/NBS-QML.svg)](https://github.com/NBSChain/NBS-QML/issues) [![GitHub forks](https://img.shields.io/github/forks/NBSChain/NBS-QML.svg)](https://github.com/NBSChain/NBS-QML/network) [![GitHub stars](https://img.shields.io/github/stars/NBSChain/NBS-QML.svg)](https://github.com/NBSChain/NBS-QML/stargazers) [![GitHub license](https://img.shields.io/github/license/NBSChain/NBS-QML.svg)](https://github.com/NBSChain/NBS-QML/blob/master/LICENSE) [![GitHub followers](https://img.shields.io/github/followers/espadrine.svg?style=social&label=Follow)](https://github.com/lamborqq?tab=following) [![Twitter Follow](https://img.shields.io/twitter/follow/espadrine.svg?style=social&label=Follow)](https://github.com/NBSChain/NBS-QML) # NBS QML C++ ![](https://img.shields.io/badge/Qt-5.11-blue.svg) ![](https://img.shields.io/badge/QtQuick-2.2-green.svg) ![](https://img.shields.io/badge/C++-red.svg) A Dapp application based on NBS Chain. ### 功能介绍 基于NBS去中心化服务实现 - IM即时通讯 - 文件上传 - 文件查询 - gRPC 协议实现 - ## 项目状态 [![Throughput Graph](https://graphs.waffle.io/NBSChain/NBS-QML/throughput.svg)](https://waffle.io/NBSChain/NBS-QML/metrics/throughput) [**`Project Issues dev`**](https://github.com/NBSChain/NBS-QML/issues) #### 技术 *** * 基于NBS公链开发,具有去中心化存储、通信服务 ## <NAME> 一套红黑色调UI ![](https://github.com/NBSChain/NBS-QML/blob/master/doc/NBS-operator.gif?raw=true) <file_sep>#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickView> #include <QQmlContext> #include <QOpenGLContext> #include <QDir> #include <QScreen> //#include "cpp/networkcontroller.h" /** * @file * @version 1.0 * @brief * @date 2018-08-16 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); const QString mainQmlApp = QStringLiteral("qrc:/UI/main.qml"); // QSurfaceFormat format; // if(QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGL){ // format.setVersion(3,2); // format.setProfile(QSurfaceFormat::CoreProfile); // } // format.setDepthBufferSize(24); // format.setStencilBufferSize(8); // format.setSamples(4); // QScreen *screen = app.screens()[0]; // int scrW = screen->size().width(); // int scrH = screen->size().height(); /* viewer */ // QQuickView viewer; // viewer.setFlags(Qt::FramelessWindowHint); // viewer.setColor(QColor(Qt::transparent)); // #ifdef Q_OS_WIN // QString extraImportPath(QStringLiteral("%1/../../../../%2")); // #else // QString extraImportPath(QStringLiteral("%1/../../../%2")); // #endif // viewer.engine()->addImportPath(extraImportPath.arg(QGuiApplication::applicationDirPath(), // QString::fromLatin1("qml"))); // NetworkController networkController; // viewer.rootContext()->setContextProperty("networkController",&networkController); // viewer.setFormat(format); // viewer.setResizeMode(QQuickView::SizeRootObjectToView); // viewer.setSource(QUrl(mainQmlApp)); // viewer.setPosition((scrW-viewer.width())/2,(scrH-viewer.height())/2);//居中显示 // viewer.show(); // viewer.rootContext()->setContextProperty("viewer",&viewer); // QObject::connect(viewer.engine(),SIGNAL(quit()),qApp,SLOT(quit())); /* main view settings */ // qmlRegisterType<NetworkController>("NbsIo",1,0,"NetworkController"); // QSurfaceFormat::setDefaultFormat(format); QQmlApplicationEngine engine; engine.load(QUrl(mainQmlApp)); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); } <file_sep>/** * @file CliApp * @version 1.0 * @brief * @date 2018-08-29 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QFontDatabase> #include <QDebug> /** * @author lanbery * @brief qMain * @param argc * @param argv * @return */ int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); //添加字体 int fontId = QFontDatabase :: addApplicationFont(":/Font/fontawesome-webfont.ttf"); QStringList fontFamilies = QFontDatabase :: applicationFontFamilies(fontId); qDebug() << "fontFamilies.size() " << fontFamilies.size(); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); // if (engine.rootObjects().isEmpty()) // return -1; return app.exec(); } <file_sep>#ifndef APPMODEL_H #define APPMODEL_H #include <QObject> class AppModel : public QObject { Q_OBJECT public: explicit AppModel(QObject *parent = 0); ~AppModel(); signals: public slots: }; #endif // APPMODEL_H <file_sep>/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt3D module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * 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. ** * Neither the name of The Qt Company Ltd 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 ** OWNER 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ .pragma library var SUN = 0; var MERCURY = 1; var VENUS = 2; var EARTH = 3; var MARS = 4; var JUPITER = 5; var SATURN = 6; var URANUS = 7; var NEPTUNE = 8; var NUM_SELECTABLE_PLANETS = 9; var MOON = 9; var SOLAR_SYSTEM = 100; function planetId(planetName) { switch (planetName) { case "Sun": return SUN case "Mercury": return MERCURY case "Venus": return VENUS case "Earth": return EARTH case "Mars": return MARS case "Jupiter": return JUPITER case "Saturn": return SATURN case "Uranus": return URANUS case "Neptune": return NEPTUNE case "NBS Chain Network": return SOLAR_SYSTEM } } function planetIndex(planetName) { switch (planetName) { case "Sun": return 0 case "Mercury": return 1 case "Venus": return 2 case "Earth": return 3 case "Mars": return 4 case "Jupiter": return 5 case "Saturn": return 6 case "Uranus": return 7 case "Neptune": return 8 case "NBS Chain Network": return 9 } } var planets = []; // Planet data info var solarDistance = 2600000; var saturnOuterRadius = 120.700; var uranusOuterRadius = 40; var auScale = 149597.870700; // AU in thousands of kilometers function loadPlanetData() { // Planet Data // radius - planet radius // tilt - planet axis angle // N1/2 - longitude of the ascending node // i1/2 - inclination to the ecliptic (plane of the Earth's orbit) // w1/2 - argument of perihelion // a1/2 - semi-major axis, or mean distance from Sun // e1/2 - eccentricity (0=circle, 0-1=ellipse, 1=parabola) // M1/2 - mean anomaly (0 at perihelion; increases uniformly with time) // period - sidereal rotation period // centerOfOrbit - the planet in the center of the orbit // (orbital elements based on http://www.stjarnhimlen.se/comp/ppcomp.html) var sun = { radius: 694.439, tilt: 63.87, period: 25.05, x: 0, y: 0, z: 0, roll: 0 }; planets.push(sun); var mercury = { radius: 2.433722, tilt: 0.04, N1: 48.3313, N2: 0.0000324587, i1: 7.0047, i2: 0.0000000500, w1: 29.1241, w2: 0.0000101444, a1: 0.387098, a2: 0, e1: 0.205635, e2: 0.000000000559, M1: 168.6562, M2: 4.0923344368, period: 58.646, x: 0, y: 0, z: 0, roll: 0, centerOfOrbit: SUN }; planets.push(mercury); var venus = { radius: 6.046079, tilt: 177.36, N1: 76.6799, N2: 0.0000246590, i1: 3.3946, i2: 0.0000000275, w1: 54.8910, w2: 0.0000138374, a1: 0.723330, a2: 0, e1: 0.006773, e2: -0.000000001302, M1: 48.0052, M2: 1.6021302244, period: 243.0185, x: 0, y: 0, z: 0, roll: 0, centerOfOrbit: SUN }; planets.push(venus); var earth = { radius: 6.371, tilt: 25.44, N1: 174.873, N2: 0, i1: 0.00005, i2: 0, w1: 102.94719, w2: 0, a1: 1, a2: 0, e1: 0.01671022, e2: 0, M1: 357.529, M2: 0.985608, period: 0.997, x: 0, y: 0, z: 0, roll: 0, centerOfOrbit: SUN }; planets.push(earth); var mars = { radius: 3.389372, tilt: 25.19, N1: 49.5574, N2: 0.0000211081, i1: 1.8497, i2: -0.0000000178, w1: 286.5016, w2: 0.0000292961, a1: 1.523688, a2: 0, e1: 0.093405, e2: 0.000000002516, M1: 18.6021, M2: 0.5240207766, period: 1.025957, x: 0, y: 0, z: 0, roll: 0, centerOfOrbit: SUN }; planets.push(mars); var jupiter = { radius: 71.41254, tilt: 3.13, N1: 100.4542, N2: 0.0000276854, i1: 1.3030, i2: -0.0000001557, w1: 273.8777, w2: 0.0000164505, a1: 5.20256, a2: 0, e1: 0.048498, e2: 0.000000004469, M1: 19.8950, M2: 0.0830853001, period: 0.4135, x: 0, y: 0, z: 0, roll: 0, centerOfOrbit: SUN }; planets.push(jupiter); var saturn = { radius: 60.19958, tilt: 26.73, N1: 113.6634, N2: 0.0000238980, i1: 2.4886, i2: -0.0000001081, w1: 339.3939, w2: 0.0000297661, a1: 9.55475, a2: 0, e1: 0.055546, e2: -0.000000009499, M1: 316.9670, M2: 0.0334442282, period: 0.4395, x: 0, y: 0, z: 0, roll: 0, centerOfOrbit: SUN }; planets.push(saturn); var uranus = { radius: 25.5286, tilt: 97.77, N1: 74.0005, N2: 0.000013978, i1: 0.7733, i2: 0.000000019, w1: 96.6612, w2: 0.000030565, a1: 19.18171, a2: -0.0000000155, e1: 0.047318, e2: 0.00000000745, M1: 142.5905, M2: 0.011725806, period: 0.71833, x: 0, y: 0, z: 0, roll: 0, centerOfOrbit: SUN }; planets.push(uranus); var neptune = { radius: 24.73859, tilt: 28.32, N1: 131.7806, N2: 0.000030173, i1: 1.7700, i2: -0.000000255, w1: 272.8461, w2: 0.000006027, a1: 30.05826, a2: 0.00000003313, e1: 0.008606, e2: 0.00000000215, M1: 260.2471, M2: 0.005995147, period: 0.6713, x: 0, y: 0, z: 0, roll: 0, centerOfOrbit: SUN }; planets.push(neptune); var moon = { radius: 1.5424, tilt: 28.32, N1: 125.1228, N2: -0.0529538083, i1: 5.1454, i2: 0, w1: 318.0634, w2: 0.1643573223, a1: 0.273, a2: 0, e1: 0.054900, e2: 0, M1: 115.3654, M2: 13.0649929509, period: 27.321582, x: 0, y: 0, z: 0, roll: 0, centerOfOrbit: EARTH }; planets.push(moon); return planets; } function getOuterRadius(planet) { var outerRadius = solarDistance; if (planet !== SOLAR_SYSTEM) { outerRadius = planets[planet]["radius"]; if (planet === SATURN) { outerRadius =+ saturnOuterRadius; } else if (planet === URANUS) { outerRadius =+ uranusOuterRadius; } else if (planet === SUN) { outerRadius = planets[planet]["radius"] / 100; } } return outerRadius; } <file_sep>![](https://github.com/NBSChain/NBS-QML/blob/master/HuracanRosso/images/bg.png?raw=true) # Huracan Rosso UI 基于Qt5.11开发,UI 主色由RossoMars(红) 和Nerohelene(黑)组成 ![](https://img.shields.io/badge/%E7%89%88%E6%9D%83%E8%AE%B8%E5%8F%AF-MIT-orange.svg) ![](https://img.shields.io/badge/Qt-5.11-blue.svg) ![](https://img.shields.io/badge/QtQuick-2.2-blue.svg) ![](https://img.shields.io/badge/VS-2017-blue.svg) [![GitHub license](https://img.shields.io/github/license/NBSChain/NBS-QML.svg)](https://github.com/NBSChain/NBS-QML/blob/master/LICENSE) [![GitHub issues](https://img.shields.io/github/issues/NBSChain/NBS-QML.svg)](https://github.com/NBSChain/NBS-QML/issues) ## project Status <file_sep>#include "animationhuracanbackgroup.h" #include <QLinearGradient> #include <QPainter> #include <QPropertyAnimation> #include <QtMath> #include <QDateTime> /** * @file AnimationHuracanBackgroup.cpp * @version 1.0 * @brief * @date 2018-09-02 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ AnimationHuracanBackgroup::AnimationHuracanBackgroup() { } <file_sep>/** * @file planets.js * @version 1.0 * @brief 星际文件系统JS * @date 2018-09-17 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ .pragma library var SUN = 0; var MERCURY = 1; var VENUS = 2; var EARTH = 3; var MARS = 4; var JUPITER = 5; var SATURN = 6; var URANUS = 7; var NEPTUNE = 8; var NUM_SELECTABLE_PLANETS = 9; var MOON = 9; var NBS_SYSTEM = 100; /** * 根据名称获取值 * @version 1.0 * @brief 选中函数 * @date 2018-09-17 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ function planetId(planetName) { switch(planetName){ case "SUN": return SUN; case "MERCURY": return MERCURY; case "VENUS": return VENUS; case "EARTH": return EARTH; case "MARS": return MARS; case "JUPITER": return JUPITER; case "SATURN": return SATURN; case "URANUS": return URANUS; case "NEPTUNE": return NEPTUNE; case "MOON": return MOON; case "NBS Chain": return NBS_SYSTEM; default: return NBS_SYSTEM; } } /** * @version 1.0 * @brief * @date 2018-09-17 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ function planetIndex(planetName){ switch(planetName){ case "SUN": return 0; case "MERCURY": return 1; case "VENUS": return 2; case "EARTH": return 3; case "MARS": return 4; case "JUPITER": return 5; case "SATURN": return 6; case "URANUS": return 7; case "NEPTUNE": return 8; case "MOON": return MOON; case "NBS Chain": return 100; default: return 100; } } var planets = []; var solarDistance = 2600000; var saturnOuterRadius = 120.700; var uranusOuterRadius = 40; var auScale = 149596.870700; //AU in /** * @version 1.0 * @brief 初始化星际图TODO * @date 2018-09-17 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ function loadPlanetData(){ var NbsChain = { radius:694.439, x:0,y:0,z:0,roll:0, } planets.push(NbsChain); } /** * @version 1.0 * @brief * @date 2018-09-17 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ function getOuterRadius(planet){ var outerRadius = solarDistance; if(planet !== solarDistance){ outerRadius = planets[planet]["radius"]; if(planet === SATURN){ outerRadius =+ saturnOuterRadius; }else if(planet === URANUS){ outerRadius =+ uranusOuterRadius; }else if(planet === SUN){ outerRadius = planets[planet]["radius"]/100; } } return outerRadius; } <file_sep>#ifndef ANIMATIONHURACANBACKGROUP_H #define ANIMATIONHURACANBACKGROUP_H #include <QQuickPaintedItem> #include <QSequentialAnimationGroup> /** * @file AnimationHuracanBackgroup.h * @version 1.0 * @brief * @date 2018-09-02 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ class AnimationHuracanBackgroup { //Q_OBJECT //Q_PROPERTY(double Value READ Value WRITE setValue) public: AnimationHuracanBackgroup(); }; #endif // ANIMATIONHURACANBACKGROUP_H <file_sep>/** * nbs-qml * @file canavs/planets * @version 1.0 * @brief * @date 2018-09-26 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ Qt.include("three.js") Qt.include("threex.planets.js") var SUN = 0; var MERCURY = 1; var VENUS = 2; var EARTH = 3; var MARS = 4; var JUPITER = 5; var SATURN = 6; var URANUS = 7; var NEPTUNE = 8; var NUM_SELECTABLE_PLANETS = 9; var MOON = 9; var SOLAR_SYSTEM = 100; var camera, scene, renderer; var planetCanvas, mouse, raycaster; var daysPerFrame; var daysPerFrameScale; var planetScale; var cameraDistance; var objects = []; // Planet objects var hitObjects = []; // Planet hit detection objects var planets = []; // Planet data info var commonGeometry; var hitGeometry; var solarDistance = 2600000; var saturnOuterRadius = 120.700; var uranusOuterRadius = 40; var qmlView; var oldFocusedPlanetPosition; var oldCameraPosition; var defaultCameraPosition; var y = 2000; var m = 1; var D = 1; // Time scale formula based on http://www.stjarnhimlen.se/comp/ppcomp.html var startD = 367 * y - 7 * (y + (m + 9) / 12) / 4 + 275 * m / 9 + D - 730530; var oldTimeD = startD; var currTimeD = startD; var auScale = 149597.870700; // AU in thousands of kilometers var focusedScaling = false; var focusedMinimumScale = 20; var actualScale; function initializeGL(canvas, eventSource, mainView) { if(qmlView)qmlView = null; planetCanvas = canvas; qmlView = mainView; camera = new THREE.PerspectiveCamera(45, canvas.width / canvas.height, 2500000, 20000000); defaultCameraPosition = new THREE.Vector3(solarDistance, solarDistance, solarDistance); camera.position.set(defaultCameraPosition.x, defaultCameraPosition.y, defaultCameraPosition.z); scene = new THREE.Scene(); var starSphere = THREEx.Planets.createStarfield(8500000); scene.add(starSphere); var light = new THREE.PointLight(0x777777, 2); light.position.set(0, 0, 0); scene.add(light); scene.add(new THREE.AmbientLight(0x111111)); //console.log("loadPlanetData start..."); loadPlanetData(); // console.log("loadPlanetData end..."); createPlanets(); // console.log("create Planets end..."); setScale(1200); camera.lookAt(objects[0].position); // look at the Sun raycaster = new THREE.Raycaster(); mouse = new THREE.Vector2(); renderer = new THREE.Canvas3DRenderer( { canvas: canvas, antialias: true, devicePixelRatio: canvas.devicePixelRatio }); renderer.setPixelRatio(canvas.devicePixelRatio); renderer.setSize(canvas.width, canvas.height); //! [5] eventSource.mouseDown.connect(onDocumentMouseDown); //! [5] } function loadPlanetData() { // Planet Data // radius - planet radius in millions of meters // tilt - planet axis angle // N1 N2 - longitude of the ascending node // i1 i2 - inclination to the ecliptic (plane of the Earth's orbit) // w1 w2 - argument of perihelion // a1 a2 - semi-major axis, or mean distance from Sun // e1 e2 - eccentricity (0=circle, 0-1=ellipse, 1=parabola) // M1 M2 - mean anomaly (0 at perihelion; increases uniformly with time) // period - sidereal rotation period // centerOfOrbit - the planet in the center of the orbit // (orbital elements based on http://www.stjarnhimlen.se/comp/ppcomp.html) var sun = { radius: 694.439, tilt: 63.87, period: 25.05 }; planets.push(sun); var mercury = { radius: 2.433722, tilt: 0.04, N1: 48.3313, N2: 0.0000324587, i1: 7.0047, i2: 0.0000000500, w1: 29.1241, w2: 0.0000101444, a1: 0.387098, a2: 0, e1: 0.205635, e2: 0.000000000559, M1: 168.6562, M2: 4.0923344368, period: 58.646, centerOfOrbit: SUN }; planets.push(mercury); var venus = { radius: 6.046079, tilt: 177.36, N1: 76.6799, N2: 0.0000246590, i1: 3.3946, i2: 0.0000000275, w1: 54.8910, w2: 0.0000138374, a1: 0.723330, a2: 0, e1: 0.006773, e2: -0.000000001302, M1: 48.0052, M2: 1.6021302244, period: 243.0185, centerOfOrbit: SUN }; planets.push(venus); var earth = { radius: 6.371, tilt: 25.44, N1: 174.873, N2: 0, i1: 0.00005, i2: 0, w1: 102.94719, w2: 0, a1: 1, a2: 0, e1: 0.01671022, e2: 0, M1: 357.529, M2: 0.985608, period: 0.997, centerOfOrbit: SUN }; planets.push(earth); var mars = { radius: 3.389372, tilt: 25.19, N1: 49.5574, N2: 0.0000211081, i1: 1.8497, i2: -0.0000000178, w1: 286.5016, w2: 0.0000292961, a1: 1.523688, a2: 0, e1: 0.093405, e2: 0.000000002516, M1: 18.6021, M2: 0.5240207766, period: 1.025957, centerOfOrbit: SUN }; planets.push(mars); var jupiter = { radius: 71.41254, tilt: 3.13, N1: 100.4542, N2: 0.0000276854, i1: 1.3030, i2: -0.0000001557, w1: 273.8777, w2: 0.0000164505, a1: 5.20256, a2: 0, e1: 0.048498, e2: 0.000000004469, M1: 19.8950, M2: 0.0830853001, period: 0.4135, centerOfOrbit: SUN }; planets.push(jupiter); var saturn = { radius: 60.19958, tilt: 26.73, N1: 113.6634, N2: 0.0000238980, i1: 2.4886, i2: -0.0000001081, w1: 339.3939, w2: 0.0000297661, a1: 9.55475, a2: 0, e1: 0.055546, e2: -0.000000009499, M1: 316.9670, M2: 0.0334442282, period: 0.4395, centerOfOrbit: SUN }; planets.push(saturn); var uranus = { radius: 25.5286, tilt: 97.77, N1: 74.0005, N2: 0.000013978, i1: 0.7733, i2: 0.000000019, w1: 96.6612, w2: 0.000030565, a1: 19.18171, a2: -0.0000000155, e1: 0.047318, e2: 0.00000000745, M1: 142.5905, M2: 0.011725806, period: 0.71833, centerOfOrbit: SUN }; planets.push(uranus); var neptune = { radius: 24.73859, tilt: 28.32, N1: 131.7806, N2: 0.000030173, i1: 1.7700, i2: -0.000000255, w1: 272.8461, w2: 0.000006027, a1: 30.05826, a2: 0.00000003313, e1: 0.008606, e2: 0.00000000215, M1: 260.2471, M2: 0.005995147, period: 0.6713, centerOfOrbit: SUN }; planets.push(neptune); var moon = { radius: 1.5424, tilt: 28.32, N1: 125.1228, N2: -0.0529538083, i1: 5.1454, i2: 0, w1: 318.0634, w2: 0.1643573223, a1: 0.273, a2: 0, e1: 0.054900, e2: 0, M1: 115.3654, M2: 13.0649929509, period: 27.321582, centerOfOrbit: EARTH }; planets.push(moon); } function createPlanets() { objects = []; console.log(commonGeometry) commonGeometry = new THREE.BufferGeometry().fromGeometry(new THREE.SphereGeometry(1, 64, 64)); hitGeometry = new THREE.BufferGeometry().fromGeometry(new THREE.SphereGeometry(1, 8, 8)); var ringSegments = 70; var mesh, innerRadius, outerRadius, ring; for (var i = 0; i < planets.length; i ++) { switch (i) { case SUN: mesh = createSun(planets[i]["radius"]); mesh.position.set(0, 0, 0); break; case MERCURY: mesh = createPlanet(planets[i]["radius"], 0.005, 'images/mercurymap.jpg', 'images/mercurybump.jpg'); break; case VENUS: mesh = createPlanet(planets[i]["radius"], 0.005, 'images/venusmap.jpg', 'images/venusbump.jpg'); break; case EARTH: mesh = createPlanet(planets[i]["radius"], 0.05, 'images/earthmap1k.jpg', 'images/earthbump1k.jpg', 'images/earthspec1k.jpg'); createEarthCloud(mesh); break; case MARS: mesh = createPlanet(planets[i]["radius"], 0.05, 'images/marsmap1k.jpg', 'images/marsbump1k.jpg'); break; case JUPITER: mesh = createPlanet(planets[i]["radius"], 0.02, 'images/jupitermap.jpg', 'images/jupitermap.jpg'); break; case SATURN: mesh = createPlanet(planets[i]["radius"], 0.05, 'images/saturnmap.jpg', 'images/saturnmap.jpg'); innerRadius = (planets[i]["radius"] + 6.630) / planets[i]["radius"]; outerRadius = (planets[i]["radius"] + saturnOuterRadius) / planets[i]["radius"]; ring = createRing(innerRadius, outerRadius, ringSegments, 'qrc:images/saturnringcolortrans.png'); ring.receiveShadow = true; ring.castShadow = true; mesh.add(ring); break; case URANUS: mesh = createPlanet(planets[i]["radius"], 0.05, 'images/uranusmap.jpg', 'images/uranusmap.jpg'); innerRadius = (planets[i]["radius"] + 2) / planets[i]["radius"]; outerRadius = (planets[i]["radius"] + uranusOuterRadius) / planets[i]["radius"]; ring = createRing(innerRadius, outerRadius, ringSegments, 'qrc:images/uranusringcolortrans.png'); ring.receiveShadow = true; ring.castShadow = true; mesh.add(ring); break; case NEPTUNE: mesh = createPlanet(planets[i]["radius"], 0.05, 'images/neptunemap.jpg', 'images/neptunemap.jpg'); break; case MOON: mesh = createPlanet(planets[i]["radius"], 0.05, 'images/moonmap1k.jpg', 'images/moonbump1k.jpg'); break; } objects.push(mesh); scene.add(mesh); // Create separate meshes for click detection var hitMesh = new THREE.Mesh(hitGeometry); hitMesh.visible = false; hitObjects.push(hitMesh); scene.add(hitMesh); } } function createSun(radius) { var textureLoader = new THREE.TextureLoader(); var texture = textureLoader.load('images/sunmap.jpg'); var material = new THREE.MeshBasicMaterial({ map: texture }); var mesh = new THREE.Mesh(commonGeometry, material); mesh.scale.set(radius, radius, radius); mesh.receiveShadow = false; mesh.castShadow = false; return mesh; } function createPlanet(radius, bumpMapScale, mapTexture, bumpTexture, specularTexture) { console.log("createPlanet...") var textureLoader = new THREE.TextureLoader(); var material = new THREE.MeshPhongMaterial({ map: textureLoader.load(mapTexture), bumpMap: textureLoader.load(bumpTexture), bumpScale: bumpMapScale }); console.log(textureLoader.load(mapTexture)); if (specularTexture) { material.specularMap = textureLoader.load(specularTexture); material.specular = new THREE.Color('grey'); material.shininess = 50.0; } else { material.shininess = 1.0; } var mesh = new THREE.Mesh(commonGeometry, material); mesh.scale.set(radius, radius, radius); return mesh; } function createEarthCloud(earthMesh) { var textureLoader = new THREE.TextureLoader(); var material = new THREE.MeshPhongMaterial({ map: textureLoader.load('images/earthcloudmapcolortrans.png'), side: THREE.BackSide, transparent: true, opacity: 0.8 }); var mesh = new THREE.Mesh(commonGeometry, material); var material2 = new THREE.MeshPhongMaterial({ map: textureLoader.load('images/earthcloudmapcolortrans.png'), side: THREE.FrontSide, transparent: true, opacity: 0.8 }); var mesh2 = new THREE.Mesh(commonGeometry, material2); mesh.scale.set(1.02, 1.02, 1.02); earthMesh.add(mesh); mesh2.scale.set(1.02, 1.02, 1.02); earthMesh.add(mesh2); } function createRing(radius, width, height, texture) { var textureLoader = new THREE.TextureLoader(); var geometry = new THREE.BufferGeometry().fromGeometry( new THREEx.Planets._RingGeometry(radius, width, height)); var material = new THREE.MeshPhongMaterial({ map: textureLoader.load(texture), side: THREE.DoubleSide, transparent: true, opacity: 0.8 }); material.map.minFilter = THREE.NearestFilter; var mesh = new THREE.Mesh(geometry, material); mesh.lookAt(new THREE.Vector3(0, 90, 0)); return mesh; } function createStarfield(radius) { var textureLoader = new THREE.TextureLoader(); var texture = textureLoader.load('images/galaxy_starfield.png'); console.log(texture); var material = new THREE.MeshBasicMaterial({ map: texture, side: THREE.BackSide }) var geometry = new THREE.BufferGeometry().fromGeometry(new THREE.SphereGeometry(radius, 32, 32)); var mesh = new THREE.Mesh(geometry, material) return mesh } function onResizeGL(canvas) { if (camera === undefined) return; camera.aspect = canvas.width / canvas.height; camera.updateProjectionMatrix(); renderer.setPixelRatio(canvas.devicePixelRatio); renderer.setSize(canvas.width, canvas.height); } function onSpeedChanged(value) { daysPerFrameScale = value; } function setScale(value, focused) { // Save actual scale in focus mode if (!focused) actualScale = value; // Limit minimum scaling in focus mode to avoid jitter caused by rounding errors if (value <= focusedMinimumScale && (focusedScaling || focused)) { planetScale = focusedMinimumScale; } else { planetScale = actualScale; } for (var i = 0; i < objects.length; i++) { var object = objects[i]; // first reset scale var radius = planets[i]["radius"]; object.scale.set(radius, radius, radius); if (i === SUN) { object.scale.multiplyScalar(planetScale / 100); } else { object.scale.multiplyScalar(planetScale); } hitObjects[i].scale.set(object.scale.x, object.scale.y, object.scale.z); } } function prepareFocusedPlanetAnimation() { oldCameraPosition = camera.position.clone(); var planet = SUN; if (qmlView.oldPlanet !== SOLAR_SYSTEM) planet = qmlView.oldPlanet; oldFocusedPlanetPosition = objects[planet].position.clone(); qmlView.oldPlanet = qmlView.focusedPlanet; if (qmlView.focusedPlanet !== SOLAR_SYSTEM && actualScale <= focusedMinimumScale) { // Limit minimum scaling in focus mode to avoid jitter caused by rounding errors planetScale = focusedMinimumScale; setScale(focusedMinimumScale, true); focusedScaling = true; } else if (focusedScaling === true) { // Restore normal scaling focusedScaling = false; setScale(actualScale); } calculateLookAtOffset(); calculateCameraOffset(); } function setCameraDistance(distance) { cameraDistance = distance; } function calculateLookAtOffset() { var offset = oldFocusedPlanetPosition.clone(); var planet = 0; if (qmlView.focusedPlanet !== SOLAR_SYSTEM) planet = qmlView.oldPlanet; var focusedPlanetPosition = objects[planet].position.clone(); offset.sub(focusedPlanetPosition); qmlView.xLookAtOffset = offset.x; qmlView.yLookAtOffset = offset.y; qmlView.zLookAtOffset = offset.z; } function calculateCameraOffset() { var offset = oldCameraPosition.clone(); var planet = 0; if (qmlView.focusedPlanet !== SOLAR_SYSTEM) planet = qmlView.focusedPlanet; var newCameraPosition = getNewCameraPosition(getOuterRadius(planet)); if (qmlView.focusedPlanet !== SUN) offset.sub(newCameraPosition); if (qmlView.focusedPlanet === SUN && qmlView.oldPlanet === SOLAR_SYSTEM) { qmlView.xCameraOffset = Math.abs(offset.x); qmlView.yCameraOffset = Math.abs(offset.y); qmlView.zCameraOffset = Math.abs(offset.z); } else { // from a planet to another qmlView.xCameraOffset = offset.x; qmlView.yCameraOffset = offset.y; qmlView.zCameraOffset = offset.z; } } function getNewCameraPosition( radius ) { var position; if (qmlView.focusedPlanet === SOLAR_SYSTEM) { position = defaultCameraPosition.clone(); position.multiplyScalar(cameraDistance); } else if (qmlView.focusedPlanet === SUN) { position = new THREE.Vector3(radius * planetScale * 2, radius * planetScale * 2, radius * planetScale * 2); position.multiplyScalar(cameraDistance); } else { var vec1 = objects[qmlView.focusedPlanet].position.clone(); var vec2 = new THREE.Vector3(0, 1, 0); vec1.normalize(); vec2.cross(vec1); vec2.multiplyScalar(radius * planetScale * cameraDistance * 4); vec2.add(objects[qmlView.focusedPlanet].position); vec1.set(0, radius * planetScale, 0); vec2.add(vec1); position = vec2; } return position; } function onDocumentMouseDown(x, y) { // Mouse selection for planets and Solar system, not for the Moon. // Intersection tests are done against a set of cruder hit objects instead of // actual planet meshes, as checking a lot of faces can be slow. mouse.set((x / planetCanvas.width) * 2 - 1, - (y / planetCanvas.height ) * 2 + 1); raycaster.setFromCamera(mouse, camera); var intersects = []; var i = 0; var objectCount = hitObjects.length - 1; // -1 excludes the moon, which is the last object while (i < objectCount) { // Update hitObject position var objectPos = objects[i].position; var hitObject = hitObjects[i]; hitObject.position.set(objectPos.x, objectPos.y, objectPos.z); hitObject.updateMatrixWorld(); hitObject.raycast( raycaster, intersects ); i++; } intersects.sort( raycaster.ascSort ); var selectedPlanet; if (intersects.length > 0) { var intersect = intersects[0]; i = 0; while (i < objectCount) { if (intersect.object === hitObjects[i]) { selectedPlanet = i; break; } i++; } if (selectedPlanet < NUM_SELECTABLE_PLANETS) { qmlView.focusedPlanet = selectedPlanet; // Limit minimum scaling in focus mode to avoid jitter caused by rounding errors if (actualScale <= focusedMinimumScale) { planetScale = focusedMinimumScale; setScale(focusedMinimumScale, true); } focusedScaling = true; } } else { qmlView.focusedPlanet = SOLAR_SYSTEM; // Restore normal scaling if (focusedScaling === true) { focusedScaling = false; setScale(actualScale); } } } function paintGL(canvas) { // console.log("paintGL"); // console.log(canvas); if (qmlView.focusedPlanet === SOLAR_SYSTEM) daysPerFrame = daysPerFrameScale * 10; else daysPerFrame = daysPerFrameScale * planets[qmlView.focusedPlanet]["period"] / 100; // Advance the time in days oldTimeD = currTimeD; currTimeD = currTimeD + daysPerFrame; var deltaTimeD = currTimeD - oldTimeD; // Position the planets orbiting the sun for (var i = 1; i < objects.length; i ++) { var object = objects[i]; var planet = planets[i]; // Bumpmaps of mercury, venus, jupiter and moon need special handling if (i == MERCURY || i == VENUS || i == JUPITER || i == MOON) object.material.bumpScale = 0.03 * planetScale; else object.material.bumpScale = 0.3 * planetScale; // Calculate the planet orbital elements from the current time in days var N = (planet["N1"] + planet["N2"] * currTimeD) * Math.PI / 180; var iPlanet = (planet["i1"] + planet["i2"] * currTimeD) * Math.PI / 180; var w = (planet["w1"] + planet["w2"] * currTimeD) * Math.PI / 180; var a = planet["a1"] + planet["a2"] * currTimeD; var e = planet["e1"] + planet["e2"] * currTimeD; var M = (planet["M1"] + planet["M2"] * currTimeD) * Math.PI / 180; var E = M + e * Math.sin(M) * (1.0 + e * Math.cos(M)); var xv = a * (Math.cos(E) - e); var yv = a * (Math.sqrt(1.0 - e * e) * Math.sin(E)); var v = Math.atan2(yv, xv); // Calculate the distance (radius) var r = Math.sqrt(xv * xv + yv * yv); // From http://www.davidcolarusso.com/astro/ // Modified to compensate for the right handed coordinate system of OpenGL var xh = r * (Math.cos(N) * Math.cos(v + w) - Math.sin(N) * Math.sin(v + w) * Math.cos(iPlanet)); var zh = -r * (Math.sin(N) * Math.cos(v + w) + Math.cos(N) * Math.sin(v + w) * Math.cos(iPlanet)); var yh = r * (Math.sin(w + v) * Math.sin(iPlanet)); // Apply the position offset from the center of orbit to the bodies var centerOfOrbit = objects[planet["centerOfOrbit"]]; object.position.set(centerOfOrbit.position.x + xh * auScale, centerOfOrbit.position.y + yh * auScale, centerOfOrbit.position.z + zh * auScale); // Calculate and apply the appropriate axis tilt to the bodies // and rotate them around the axis var radians = planet["tilt"] * Math.PI / 180; // tilt in radians object.rotation.order = 'ZXY'; object.rotation.x = 0; object.rotation.y += (deltaTimeD / planet["period"]) * 2 * Math.PI; object.rotation.z = radians; } // rotate the Sun var sun = objects[SUN]; sun.rotation.order = 'ZXY'; sun.rotation.x = 0; sun.rotation.y += (deltaTimeD / planets[SUN]["period"]) * 2 * Math.PI; sun.rotation.z = planets[SUN]["tilt"] * Math.PI / 180; // tilt in radians // calculate the outer radius of the focused item var outerRadius = getOuterRadius(qmlView.focusedPlanet); // get the appropriate near plane position for the camera and animate it with QML animations qmlView.cameraNear = outerRadius; camera.near = qmlView.cameraNear; camera.updateProjectionMatrix(); // Calculate and set camera position var cameraPosition = getNewCameraPosition(outerRadius); var cameraOffset = new THREE.Vector3(qmlView.xCameraOffset, qmlView.yCameraOffset, qmlView.zCameraOffset); cameraPosition.add(cameraOffset); camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z); // Calculate and set camera look-at point var lookAtPlanet = SUN; if (qmlView.focusedPlanet !== SOLAR_SYSTEM) lookAtPlanet = qmlView.focusedPlanet; var cameraLookAt = objects[lookAtPlanet].position.clone(); var lookAtOffset = new THREE.Vector3(qmlView.xLookAtOffset, qmlView.yLookAtOffset, qmlView.zLookAtOffset); cameraLookAt.add(lookAtOffset); camera.lookAt(cameraLookAt); // console.log(scene); // console.log(camera); // Render the scene renderer.render(scene, camera); } function getOuterRadius( planet ) { var outerRadius = solarDistance; if (planet !== SOLAR_SYSTEM) { outerRadius = planets[planet]["radius"]; if (planet === SATURN) { outerRadius =+ saturnOuterRadius; } else if (planet === URANUS) { outerRadius =+ uranusOuterRadius; } else if (planet === SUN) { outerRadius = planets[planet]["radius"] / 100; } } return outerRadius; } <file_sep>#include <QGuiApplication> #include <QQmlApplicationEngine> #include "./cpp/appmodel.h" #include <QScreen> int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); /* Developer Info */ QCoreApplication::setOrganizationName("NBS Chain"); QCoreApplication::setOrganizationDomain("nbsio.net"); QCoreApplication::setApplicationName("NBS Dapp"); QCoreApplication::setApplicationVersion("v0.0.1"); /* 分辨率处理 */ qreal refDpi = 216.; qreal refWidth = 1000.; qreal refHeigh = 618.; QRect rect = QGuiApplication::primaryScreen()->geometry(); qreal height = qMin(rect.height(),rect.width()); qreal width = qMax(rect.width(),rect.height()); qreal dpi = QGuiApplication::primaryScreen()->logicalDotsPerInch(); qreal dp2i = QGuiApplication::primaryScreen()->physicalDotsPerInch(); QString d = QGuiApplication::primaryScreen()->manufacturer(); QString d1 = QGuiApplication::primaryScreen()->name(); QString d12 = QGuiApplication::primaryScreen()->model(); qreal m_ratio = qMin(height/refHeigh,width/refWidth); qreal m_ratioFont = qMin(height*refDpi/(dpi*refHeigh),width*refDpi/(dpi*refWidth)); qmlRegisterType<AppModel>("NBSAppModel",1,0,"AppModel"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/UI/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); } <file_sep>#include "appmodel.h" #include <QtCore> /** * @file AppModel.cpp * @version 1.0 * @brief * @date 2018-09-05 * @author lanbery * @section LICENSE Copyright (c) 2018 - 2025 lanbery,NBS Chain Co. */ AppModel::AppModel(QObject *parent) : QObject(parent) { } /** * @brief AppModel::~AppModel */ AppModel::~AppModel(){ }
3ddd7a434fa7eff7a63e9f2f59b7d521251c0ca0
[ "Markdown", "JavaScript", "C++" ]
12
Markdown
lamborc/NBS-QML
fd7b14a332131ff1156aa378cb471f9988edbd40
05caf6f68aeedf3bab5a21cae4ef2ab3c867986e
refs/heads/master
<file_sep>import {UserType} from "../HW8"; type ActionsType = { type: 'sort', payload: 'up' } | { type: 'sort', payload: 'down' } | { type: 'check', payload: 18 } export const homeWorkReducer = (state: UserType[], action: ActionsType): UserType[] => { switch (action.type) { case 'sort': { if (action.payload === 'up') { return [...state.sort((a, b) => a.age - b.age)] } return [...state.sort((a, b) => b.age - a.age)] } case 'check': { return state.filter(el => el.age >= action.payload) } default: return state } }
e0f20fec83789d96a744fa7884bdb9cce4e66a32
[ "TypeScript" ]
1
TypeScript
bunin-av/custom_ig
6f0fb0293ffad92b4e8309911ccf2fd38c933419
b9e00fb8302f28d449937d00aa292caec2e583b3
refs/heads/master
<repo_name>blackbelt238/theRealIMDb<file_sep>/sql.java import java.sql.*; import java.io.FileWriter; import java.io.IOException; import java.lang.StringBuilder; /* * <NAME>, <NAME>, <NAME> * Deliverable 5 */ public class Sql { public static void main (String[] args) { try { //create connection to our database String url = "jdbc:msql://localhost:3306/Demo"; Connection conn = DriverManager.getConnection(url,"",""); //execute statement in database Statement stmt = conn.createStatement(); //create result sets for each query ResultSet q1; ResultSet q2; ResultSet q3; ResultSet q4; ResultSet q5; //string builders for writing to csv files StringBuilder saveStr1 = new StringBuilder(); StringBuilder saveStr2 = new StringBuilder(); StringBuilder saveStr3 = new StringBuilder(); StringBuilder saveStr4 = new StringBuilder(); StringBuilder saveStr5 = new StringBuilder(); //query one //to compare average ratings against the adult rating of titles q1 = stmt.executeQuery("SELECT T.isAdult, R.averageRating FROM TITLE T, RATING R, IS_RATED IR WHERE T.tconst = IR.tconst AND IR.rconst = R.rconst"); while ( q1.next() ) { //add boolean isAdult String adult = q1.getString("T.isAdult"); saveStr1.append(adult); saveStr1.append(","); //add average rating String averating = q1.getString("R.averageRating"); saveStr1.append(averating); saveStr1.append("\n"); } //query two //to compare start year, runtime, primary genre, and average rating q2 = stmt.executeQuery("SELECT G.genre, T.startYear, T.runtimeMinutes, R.averageRating FROM TITLE T, RATING R, IS_RATED IR, PRIMARY_GENRE G WHERE T.tconst = IR.tconst AND IR.rconst = R.rconst AND T.tconst = G.tconst AND T.runtimeMinutes IS NOT NULL AND T.startYear IS NOT NULL"); while ( q2.next() ) { //add genre String genre = q2.getString("G.genre"); saveStr2.append(genre); saveStr2.append(","); //add start year String year = q2.getString("T.startYear"); saveStr2.append(year); saveStr2.append(","); //add runtime in minutes String runtime = q2.getString("T.runtimeMinutes"); saveStr2.append(runtime); saveStr2.append(","); //add average rating String averating = q2.getString("R.averageRating"); saveStr2.append(averating); saveStr2.append("\n"); } //query three //to compare average rating and for Warcraft to make predictions given the average ratings for titles in the same genre as Warcraft q3 = stmt.executeQuery("SELECT R.averageRating, T.startYear, T.runtimeMinutes, G.genre FROM TITLE T, RATING R, IS_RATED IR, PRIMARY_GENRE G WHERE T.tconst = IR.tconst AND IR.rconst = R.rconst AND T.tconst = G.tconst AND T.runtimeMinutes IS NOT NULL AND T.startYear is NOT NULL"); while ( q3.next() ) { //add average rating String rating = q3.getString("R.averageRating"); saveStr3.append(rating); saveStr3.append(","); //add start year String year = q3.getString("T.startYear"); saveStr3.append(year); saveStr3.append(","); //add runtime String time = q3.getString("T.runtimeMinutes"); saveStr3.append(time); saveStr3.append(","); //add genre String genre = q3.getString("G.genre"); saveStr3.append(genre); saveStr2.append("\n"); } //query four //to compare runtime across different genres q4 = stmt.executeQuery("SELECT T.runtimeMinutes, G.genre FROM TITLE T, PRIMARY_GENRE G WHERE T.tconst = G.tconst"); while ( q4.next() ) { //add runtime in minutes String runtime = q4.getString("T.runtimeMinutes"); saveStr4.append(runtime); saveStr4.append(","); //add genre String genre = q4.getString("G.genre"); saveStr4.append(genre); saveStr4.append("\n"); } //query five //to compare average rating and number of titles for the star wars and star trek franchises q5 = stmt.executeQuery("SELECT R.averageRating, (T.primaryTitle LIKE '%_tar _ars%')+1 FROM TITLE T, RATING R, IS_RATED IR WHERE T.primaryTitle LIKE '%_tar _ars%' OR T.primaryTitle LIKE '%_tar _rek%' AND T.tconst = IR.tconst AND IR.rconst = R.rconst"); while ( q5.next() ) { //add average rating String aveRating = q5.getString("R.averageRating"); saveStr5.append(aveRating); saveStr5.append(","); //add primary title String count = q5.getString("T.primaryTitle"); saveStr5.append(count); saveStr5.append("\n"); } //close database connection conn.close(); //create file writers FileWriter filewrite1 = null; FileWriter filewrite2 = null; FileWriter filewrite3 = null; FileWriter filewrite4 = null; FileWriter filewrite5 = null; //try writing to .csv files try{ filewrite1 = new FileWriter("question1.csv"); filewrite1.append(saveStr1.toString()); System.out.println("Generated question1.csv"); filewrite2 = new FileWriter("question2.csv"); filewrite2.append(saveStr2.toString()); System.out.println("Generated question2.csv"); filewrite3 = new FileWriter("question3.csv"); filewrite3.append(saveStr3.toString()); System.out.println("Generated question3.csv"); filewrite4 = new FileWriter("question4.csv"); filewrite4.append(saveStr4.toString()); System.out.println("Generated question4.csv"); filewrite5 = new FileWriter("question5.csv"); filewrite5.append(saveStr5.toString()); System.out.println("Generated question5.csv"); } catch(Exception e){ System.out.println(e); } finally{ //try closing files try{ filewrite1.flush(); filewrite1.close(); filewrite2.flush(); filewrite2.close(); filewrite3.flush(); filewrite3.close(); filewrite4.flush(); filewrite4.close(); filewrite5.flush(); filewrite5.close(); } catch(IOException e){ System.out.println(e); } } } catch (Exception e) { System.err.println("Got an exception! "); System.err.println(e.getMessage()); } } } <file_sep>/README.md # theRealIMDb make movies great again
8e98ca1f3421d0ee968e0a63593d53f8ce33c584
[ "Markdown", "Java" ]
2
Java
blackbelt238/theRealIMDb
0fd3a598935941b4693458bbb6aa74a23e5ad862
48a2c6944f0182fb6218bb014861c8242f185124
refs/heads/master
<file_sep>export default class Cast { name: string; }; <file_sep>import CastSet from './casts'; export default { castSet: new CastSet() }; <file_sep>import Cast from './cast'; export default class CastSet { casts: Cast[]; constructor() { // TEMP this.casts = ['Kitchen', 'Living Room', 'All'].map(name => { let cast = new Cast(); cast.name = name; return cast; }); } } <file_sep># Cast Status TODO <file_sep>import * as express from 'express'; import * as http from 'http'; import * as SocketIO from 'socket.io' const app = express(); const server = http.createServer(app); const io = SocketIO(server); app.use(express.static(__dirname + '/../static')); io.on('connection', (socket : any) => { console.log('Something connected'); }); app.get('/api/casts', (req, res) => { res.json(['Kitchen', 'Living Room', 'All']); }); server.listen(3001, () => console.log("Listening on *:3001"));
806fea46c6de87d8cca44314f8fa4c537e4db90f
[ "Markdown", "TypeScript" ]
5
TypeScript
simontaylor81/CastStatus
bde589db47c996353ec20abf211c60cd237d3919
a69bd0887879d68b5bee33beb18c50bd3cbe3aa2
refs/heads/master
<repo_name>samuele3/imguix<file_sep>/Classes/imgui/CCImGuiLayer.cpp #include "CCImGuiLayer.h" #include "imgui.h" #include "imgui_impl_cocos2dx.h" #include "CCIMGUI.h" USING_NS_CC; void ImGuiLayer::createAndKeepOnTop() { // delay call, once. auto director = Director::getInstance(); director->getScheduler()->schedule([=](float dt) { std::string layerName = "ImGUILayer"; auto order = INT_MAX; auto layer = ImGuiLayer::create(); auto runningScene = Director::getInstance()->getRunningScene(); if (runningScene && !runningScene->getChildByName(layerName)) { runningScene->addChild(layer, INT_MAX, layerName); } auto e = Director::getInstance()->getEventDispatcher(); layer->detached = false; e->addCustomEventListener(Director::EVENT_BEFORE_SET_NEXT_SCENE, [&, layerName](EventCustom*){ layer = dynamic_cast<ImGuiLayer*>(Director::getInstance()->getRunningScene()->getChildByName(layerName)); if (layer) { layer->retain(); layer->removeFromParent(); layer->detached = true; } }); e->addCustomEventListener(Director::EVENT_AFTER_SET_NEXT_SCENE, [&, layer, layerName](EventCustom*){ if (layer && layer->detached) { Director::getInstance()->getRunningScene()->addChild(layer, order, layerName); layer->release(); layer->detached = false; } }); }, director, 0, 0, 0, false, "checkIMGUI"); } // on "init" you need to initialize your instance bool ImGuiLayer::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } #if COCOS2D_VERSION < 0x00040000 // init imgui setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_COLOR)); #endif // events auto listener = EventListenerTouchOneByOne::create(); listener->setSwallowTouches(true); listener->onTouchBegan = [](Touch* touch, Event*) -> bool { bool inImGuiWidgets = ImGui::IsAnyWindowHovered(); return inImGuiWidgets; }; getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); return true; } void ImGuiLayer::visit(cocos2d::Renderer *renderer, const cocos2d::Mat4 &parentTransform, uint32_t parentFlags) { Layer::visit(renderer, parentTransform, parentFlags); _command.init(_globalZOrder); _command.func = CC_CALLBACK_0(ImGuiLayer::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_command); } void ImGuiLayer::onDraw() { #if COCOS2D_VERSION < 0x00040000 getGLProgram()->use(); #endif // create frame ImGui_ImplCocos2dx_NewFrame(); // draw all gui CCIMGUI::getInstance()->updateImGUI(); #if COCOS2D_VERSION < 0x00040000 // rendering glUseProgram(0); #endif ImGui::Render(); ImGui_ImplCocos2dx_RenderDrawData(ImGui::GetDrawData()); } <file_sep>/Classes/HelloWorldScene.cpp #include "HelloWorldScene.h" #include "imgui/CCIMGUI.h" #include "svg/SVGSprite.h" #include "spine/spine.h" USING_NS_CC; using namespace spine; static bool show_test_window = true; static bool show_another_window = false; static ImVec4 clear_color = ImColor(114, 144, 154); HelloWorld::~HelloWorld() { if (_skeletonData) spSkeletonData_dispose(_skeletonData); if (_stateData) spAnimationStateData_dispose(_stateData); if (_attachmentLoader) spAttachmentLoader_dispose(_attachmentLoader); if (_atlas) spAtlas_dispose(_atlas); } Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } auto director = Director::getInstance(); auto size = director->getWinSize(); auto rootNode = Sprite::create("HelloWorld.png"); rootNode->setPosition(size.width/2, size.height/2); addChild(rootNode); auto listener = EventListenerTouchOneByOne::create(); listener->onTouchBegan = [](Touch* touch, Event*) -> bool { CCLOG("touch bg node"); return true; }; Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, rootNode); CCIMGUI::getInstance()->addImGUI([=](){ // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug" { static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float*)&clear_color); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } // 2. Show another simple window, this time using an explicit Begin/End pair if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiCond_FirstUseEver); ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello"); ImGui::End(); } // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver); ImGui::ShowDemoWindow(); } }, "demoid"); createSpineTest(); testSVG(); return true; } void HelloWorld::createSpineTest() { // Load the texture atlas. _atlas = spAtlas_createFromFile("spine/spineboy.atlas", 0); CCASSERT(_atlas, "Error reading atlas file."); // This attachment loader configures attachments with data needed for cocos2d-x rendering. // Do not dispose the attachment loader until the skeleton data is disposed! _attachmentLoader = (spAttachmentLoader*)Cocos2dAttachmentLoader_create(_atlas); // Load the skeleton data. spSkeletonJson* json = spSkeletonJson_createWithLoader(_attachmentLoader); json->scale = 0.6f; // Resizes skeleton data to 60% of the size it was in Spine. _skeletonData = spSkeletonJson_readSkeletonDataFile(json, "spine/spineboy-ess.json"); CCASSERT(_skeletonData, json->error ? json->error : "Error reading skeleton data file."); spSkeletonJson_dispose(json); // Setup mix times. _stateData = spAnimationStateData_create(_skeletonData); spAnimationStateData_setMixByName(_stateData, "walk", "jump", 0.2f); spAnimationStateData_setMixByName(_stateData, "jump", "run", 0.2f); int xMin = _contentSize.width * 0.10f, xMax = _contentSize.width * 0.90f; int yMin = 0, yMax = _contentSize.height * 0.7f; for (int i = 0; i < 50; i++) { // Each skeleton node shares the same atlas, skeleton data, and mix times. SkeletonAnimation* skeletonNode = SkeletonAnimation::createWithData(_skeletonData, false); skeletonNode->setAnimationStateData(_stateData); skeletonNode->setAnimation(0, "walk", true); skeletonNode->addAnimation(0, "jump", false, 3); skeletonNode->addAnimation(0, "run", true); skeletonNode->setPosition(Vec2( RandomHelper::random_int(xMin, xMax), RandomHelper::random_int(yMin, yMax) )); skeletonNode->setScale(0.8); addChild(skeletonNode); } } void HelloWorld::testSVG() { auto svgSprite = SVGSprite::create("res/tiger.svg"); svgSprite->setPosition(getContentSize() / 2); addChild(svgSprite); auto duration = 5.0f; auto moveSeq = Sequence::createWithTwoActions(MoveBy::create(duration, Vec2(200,200)), MoveBy::create(duration, Vec2(-200,-200))); svgSprite->runAction(RepeatForever::create(moveSeq)); auto scaleSeq = Sequence::createWithTwoActions(ScaleTo::create(duration, 3), ScaleTo::create(duration, 0.5)); svgSprite->runAction(RepeatForever::create(scaleSeq)); }
e5ca56e16ac3f91d34cd554e917d3deefed31ed7
[ "C++" ]
2
C++
samuele3/imguix
7f2e67f0e203202ac87552047e70ef01cbd73e01
5d133eff1382abc92d8fce69d425016181db6ffb
refs/heads/master
<repo_name>dibend/localweb<file_sep>/server.js var express = require('express'); var serveIndex = require('serve-index'); var morgan = require('morgan'); var fs = require('fs'); var http = require('http'); var https = require('https'); var compression = require('compression'); var config = require('./config'); var app = express(); app.use(compression()); app.use(morgan('":remote-addr",":date[web]",":method",":url",":status",":response-time ms"')); app.use(express.static(config.dir), serveIndex(config.dir, {'icons': true})); console.log('"ip","date","method","url","status","time"'); var sslKey = fs.readFileSync('ssl/localweb.key', 'utf8'); var sslCert = fs.readFileSync('ssl/localweb.crt', 'utf8'); var creds = { key: sslKey, cert: sslCert, }; http.createServer(app).listen(8080); https.createServer(creds, app).listen(8443); <file_sep>/README.md # Local Web Serves directory over HTTP & HTTPS ## Debian Install Install node.js if you haven't `curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -`<br> `sudo apt-get install -y nodejs` Clone this repo `git clone https://github.com/dibend/localweb.git` Install dependencies `cd localweb`<br> `npm install` Set folder to share in config.json `{ "dir": "/home/share" }` Create a folder named ssl and add ssl key and cert named localweb.key and localweb.crt `mkdir ssl`<br> `sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl/localweb.key -out ssl/localweb.crt` run `./start.sh` to start server
619cb331f7cdb893d9e91bf4e595305b93d18b81
[ "JavaScript", "Markdown" ]
2
JavaScript
dibend/localweb
aceea9b496bb19283411717508e3a9256ee1edf8
b22dfc436b897728a8745fa30c5edbb57a9014a0
refs/heads/master
<file_sep>#include <bits/stdc++.h> #include <unordered_map> using namespace std; // make function to compare array and count the matches component using unordered mapping int compareArray (unordered_multimap<string, int> strComponent, string query){ return (int)(strComponent.count(query)); // using count function in unordered multimap to lookup element with specific key } int main(){ int strSize, querySize; unordered_multimap<string, int> strComponent; vector<int> result; // make a dynamic array to save result cin >> strSize; // collecting string value for (int i=0; i<strSize; i++){ string tempString; cin >> tempString; // read the string value strComponent.insert(make_pair(tempString, 0)); // inserting the value to array with the key value } cin >> querySize; // collecting queries value for(int i=0; i<querySize; i++){ string tempQuery; cin >> tempQuery; // read the query component result.push_back(compareArray(strComponent, tempQuery)); // add new compared value to the tail of dynamic array } // print the result for (int i=0; i<result.size(); i++){ cout << result[i] << "\n"; } return 0; }<file_sep>#include <bits/stdc++.h> #include <queue> #include <vector> #include <utility> using namespace std; int knightlOnAChessboard(int n, int a, int b) { vector<vector<int>> cache(n, vector<int>(n, INT_MAX)); queue<pair<int,int>> que; que.push(make_pair(0,0)); cache[0][0] = 0; while(!que.empty()){ pair<int,int> currentPosition = que.front(); que.pop(); int counter = cache[currentPosition.first][currentPosition.second] + 1; vector<pair<int,int>> nextPosition = { make_pair(currentPosition.first + a, currentPosition.second + b), make_pair(currentPosition.first + a, currentPosition.second - b), make_pair(currentPosition.first - a, currentPosition.second + b), make_pair(currentPosition.first - a, currentPosition.second - b), make_pair(currentPosition.first + b, currentPosition.second + a), make_pair(currentPosition.first + b, currentPosition.second - a), make_pair(currentPosition.first - b, currentPosition.second + a), make_pair(currentPosition.first - b, currentPosition.second - a) }; for(int i = 0; i<nextPosition.size(); i++){ pair<int, int> temp = nextPosition[i]; int x = temp.first; int y = temp.second; if (x >= 0 && x <= n-1 && y >=0 && y <= n-1){ if(cache[x][y] > counter){ cache[x][y] = counter; que.push(make_pair(x,y)); } } } } if (cache[n-1][n-1] == INT_MAX) return -1; return cache[n-1][n-1]; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) fout << knightlOnAChessboard(n, i, j) << " "; fout << endl; } fout.close(); return 0; } <file_sep>#include <bits/stdc++.h> #include <iostream> #include <algorithm> #include <vector> using namespace std; char matrix[101][101]; int row, column, wandCount = 0; bool countLuck(int currentX, int currentY, int prevX=-1, int prevY=-1) { const int dx[]={1,-1,0,0}; const int dy[]={0,0,1,-1}; int nextX, nextY =0; bool flag=0; int cc=0; if (matrix[currentX][currentY] == '*') return 1; for (int i=0; i<4; i++){ nextX = currentX + dx[i]; nextY = currentY + dy[i]; if (!(nextX>=0 && nextY>=0 && nextX<column && nextY<row)) continue; if (nextX == prevX && nextY == prevY) continue; if (matrix[nextX][nextY] == 'X') continue; if (countLuck(nextX, nextY, currentX, currentY)) flag = 1; cc++; } if (flag==1 && cc>1) wandCount++; return flag; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string result; int x, y = 0; int t; cin >> t; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int t_itr = 0; t_itr < t; t_itr++) { cin >> column >> row; for (int i=0; i<column; i++){ for (int j=0; j<row; j++){ cin >> matrix[i][j]; if (matrix[i][j] == 'M'){ x = i; y = j; } } } int k; cin >> k; cin.ignore(numeric_limits<streamsize>::max(), '\n'); wandCount = 0; countLuck(x, y); if(wandCount == k) result = "Impressed"; else result = "Oops!"; fout << result << "\n"; } fout.close(); return 0; }<file_sep>#include <bits/stdc++.h> using namespace std; /**************************EDITABLE PART******************/ int maxMin(int k, vector<int> arr) { sort(arr.begin(), arr.end()); // sort array in ascending order int len = arr.size(); int min = arr.back() - arr.front(); // insert default minimum difference value // do iteration until last element that can a group consist of k element for (int i=0; i<len-k+1; i++){ if ((arr[i+k-1]-arr[i])<min) // check if difference of first and last element in group is smaller than previous value min=arr[i+k-1]-arr[i]; } return min; } /********************************************************/ int main() { ofstream fout(getenv("OUTPUT_PATH")); int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int k; cin >> k; cin.ignore(numeric_limits<streamsize>::max(), '\n'); vector<int> arr(n); for (int i = 0; i < n; i++) { int arr_item; cin >> arr_item; cin.ignore(numeric_limits<streamsize>::max(), '\n'); arr[i] = arr_item; } int result = maxMin(k, arr); fout << result << "\n"; fout.close(); return 0; } <file_sep>#include <bits/stdc++.h> #include <vector> #include <cstdio> using namespace std; int main() { int t; cin >> t; while (t--){ int n,k; cin >> n >> k; vector<int> arr(n); for(int i=0; i<n; i++){ cin >> arr[i]; } vector<int> dynamicP(k+1); dynamicP[0] = 1; for(int i=0; i < n; i++){ for (int j=arr[i]; j<=k; j++){ dynamicP[j]+=dynamicP[j-arr[i]]; } } int z = k; for(; (z>0)&&(!dynamicP[z]); z--); cout << z << endl; } return 0; } <file_sep>#include <bits/stdc++.h> #include <vector> #include <iostream> using namespace std; int main() { ofstream fout(getenv("OUTPUT_PATH")); int t; cin >> t; while (t--){ int n; cin >> n; int prices[n]; long profit = 0, maxPrice = 0; for (int i = 0; i < n; i++) cin >> prices[i]; for (int i=n-1; i>=0; i--){ if(prices[i] >= maxPrice){ maxPrice = prices[i]; } profit += maxPrice - prices[i]; } fout << profit << "\n"; } fout.close(); return 0; } <file_sep>/* struct node { int data; node* left; node* right; }; */ // inOrder traversal is Depth First Search (DFS) and read in left-root-right order void inOrder(node *root) { // check if tree is empty if (root == NULL) return; inOrder(root->left); // take the left branch and assign the leaf as the new root printf("%d ", root->data); // print the root value inOrder(root->right); // take the right branch and assign the leaf as the new root }<file_sep># Hacker-Rank Solved problem from HackerRank website ## Data Structures ### Array 1. [2D Array - DS](https://www.hackerrank.com/challenges/2d-array/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%201/Data%20Structures/Arrays/2D%20Array%20-%20DS/2d%20array%20hourglass.c) 2. [Sparse Array](https://www.hackerrank.com/challenges/sparse-arrays/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%201/Data%20Structures/Arrays/Sparse%20Arrays/sparse%20array.cpp) ### Tree 1. [Tree: PreOrder Traversal](https://www.hackerrank.com/challenges/tree-preorder-traversal/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%201/Data%20Structures/Trees/Tree%20-%20Preorder%20Traversal/preOrder%20Traversal.cpp) 2. [Tree: PostOrder Traversal](https://www.hackerrank.com/challenges/tree-postorder-traversal/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%201/Data%20Structures/Trees/Tree%20-%20Postorder%20Traversal/postOrder%20Traversal.cpp) 3. [Tree: InOrder Traversal](https://www.hackerrank.com/challenges/tree-inorder-traversal/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%201/Data%20Structures/Trees/Tree%20-%20Inorder%20Traversal/inOrder%20Traversal.cpp) 4. [Tree: Height of Binary](https://www.hackerrank.com/challenges/tree-height-of-a-binary-tree/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%201/Data%20Structures/Trees/Tree%20-%20Height%20of%20a%20Binary/Tree%20Height.cpp) 5. [Tree: Huffmann Decoding](https://www.hackerrank.com/challenges/tree-huffman-decoding/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%201/Data%20Structures/Trees/Tree%20-%20Huffman%20Decoding/Tree%20Huffman%20Decoding.cpp) 6. [Swap Nodes - Algo](https://www.hackerrank.com/challenges/swap-nodes-algo/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%201/Data%20Structures/Trees/Swap%20Nodes%20%5BAlgo%5D/Swap%20Nodes.cpp) ### Linked List 1. [Cycle Detection](https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Linked%20List/Cycle%20Detection/Cycle%20Detection.cpp) ### Stack 1. [Balanced Bracket](https://www.hackerrank.com/challenges/balanced-brackets/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Stack/Balanced%20Brackets/Balanced%20Brackets.cpp) 2. [Simple Text Editor](https://www.hackerrank.com/challenges/simple-text-editor/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Stack/Simple%20Text%20Editor/Simple%20Text%20Editor.cpp) 3. [Poisonous Plants](https://www.hackerrank.com/challenges/poisonous-plants/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Stack/Poisonous%20Plants/Poisonous%20Plants.cpp) 4. [Waiter](https://www.hackerrank.com/challenges/waiter/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Stack/Waiter/Waiter.cpp) ### Queue 1. [Queue Using Two Stacks](https://www.hackerrank.com/challenges/queue-using-two-stacks/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Queue/Queue%20Using%20Two%20Stacks/Queue%20Using%20Two%20Stacks.cpp) 2. [Truck Tour](https://www.hackerrank.com/challenges/truck-tour/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Queue/Truck%20Tour/Truck%20Tour.cpp) ### Heap 1. [Find The Running Median](https://www.hackerrank.com/challenges/find-the-running-median/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Heap/Find%20The%20Running%20Median/Find%20The%20Running%20Median.cpp) 2. [Minimum Average Waiting Time](https://www.hackerrank.com/challenges/minimum-average-waiting-time/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Heap/Minimum%20Average%20Waiting%20Time/Minimum%20Average%20Waiting%20Time.cpp) ## Algorithm ### Greedy 1. [Greedy Florist](https://www.hackerrank.com/challenges/greedy-florist/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Heap/Minimum%20Average%20Waiting%20Time/Minimum%20Average%20Waiting%20Time.cpp) 2. [Max Min](https://www.hackerrank.com/challenges/angry-children/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%202/Data%20Structures/Greedy/Max%20Min/Max%20Min.cpp) ### String 1. [Sherlock and Anagrams](https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%203/Algorithm/String/Sherlock%20and%20Anagrams/Sherlock%20and%20Anagrams.cpp) ### Search 1. [KnightL on Chessboard](https://www.hackerrank.com/challenges/knightl-on-chessboard/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%203/Algorithm/Search/KnightL%20on%20Chessboard/KnightL%20on%20Chessboard.cpp) 2. [Count Luck](https://www.hackerrank.com/challenges/count-luck/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%203/Algorithm/Search/Count%20Luck/Count%20Luck.cpp) ### Graph Theory 1. [Floyd : City of Blinding Lights](https://www.hackerrank.com/challenges/floyd-city-of-blinding-lights/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%203/Algorithm/Graph%20Theory/Floyd%20City%20of%20Blinding%20Lights/Floyd%20City%20of%20Blinding%20Lights.cpp) ### Dynamic Programming 1. [Stock Maximize](https://www.hackerrank.com/challenges/stockmax/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%203/Algorithm/Dynamic%20Programming/Stock%20Maximize/Stock%20Maximize.cpp) 2. [Unbounded Knapsack](https://www.hackerrank.com/challenges/unbounded-knapsack/problem) - [Solution](https://github.com/PranataSitepu/HackerRank/blob/master/Progress%203/Algorithm/Dynamic%20Programming/Unbounded%20Knapsack/Unbounded%20Knapsack.cpp) <file_sep>#include <cmath> #include <cstdio> #include <iostream> #include <algorithm> #include <stack> using namespace std; int main() { stack<int> stack1; // rear element stack stack<int> stack2; // front element stack int opNumber; int opSelect; cin >> opNumber; for(int i=0; i<opNumber; i++){ cin >> opSelect; // insert number to the back of queue if (opSelect == 1){ int enqueue; cin >> enqueue; stack1.push(enqueue); } else{ //move all element from the rear stack to front stack to flip the sequence if(stack2.empty()){ while(!stack1.empty()){ stack2.push(stack1.top()); stack1.pop(); } } if(!stack2.empty()){ // dequeue the first element from queue if(opSelect == 2) stack2.pop(); else // print the first element in the queue cout << stack2.top() << endl; } } } return 0; } <file_sep>#include <bits/stdc++.h> #include <iostream> #define INF 99999; using namespace std; int main() { int road_nodes; int road_edges; int source, destination, weight; int shortestDistance[401][401]; cin >> road_nodes >> road_edges; for(int i=0; i<=road_nodes; i++){ for(int j=0; j<=road_nodes; j++){ if(i==j) shortestDistance[i][j]=0; else shortestDistance[i][j]=INF; } } for (int i = 0; i < road_edges; i++) { cin >> source >> destination >> weight; shortestDistance[source][destination] = weight; } for(int i=0; i<=road_nodes; i++){ for(int j=0; j<=road_nodes; j++){ for(int k=0; k<=road_nodes; k++){ if(shortestDistance[j][i] + shortestDistance[i][k] < shortestDistance[j][k]) shortestDistance[j][k] = shortestDistance[j][i]+shortestDistance[i][k]; } } } int q; cin >> q; for (int q_itr = 0; q_itr < q; q_itr++) { int x, y; cin >> x >> y; if(shortestDistance[x][y] == 99999) cout << "-1" << endl; else cout << shortestDistance[x][y] << endl; } return 0; } <file_sep>#include <bits/stdc++.h> #include <vector> using namespace std; vector<string> split_string(string); // function to get the prime number from 2 to 10^4 vector<int> getPrime (){ vector<int> prime; int lower = 2; int upper = 10000; for (int i=lower; i<upper; i++){ bool isPrime = 0; for(int j=lower; j<=sqrt(i); j++){ if (i%j == 0) isPrime = 1; } if (isPrime == 0) prime.push_back(i); } return prime; } vector<int> waiter(vector<int> number, int q) { vector<int> result, strA, strB; int num; vector<int> prime = getPrime(); // assign all the prime number to array for (int i=0; i<q; i++){ int size = number.size(); for (int j=0; j<size; j++){ num = number.back(); // if the number is divisible by the prime number, store it to stack strB // if not, store it to stack strB if( num % prime[i] == 0 ){ strB.push_back(num); number.pop_back(); } else{ strA.push_back(num); number.pop_back(); } } number = strA; // do the iteration with number in the strA strA.clear(); // move the strB stack value to the result stack while (!strB.empty()){ result.push_back(strB.back()); strB.pop_back(); } } // if the strA stack not empty until all iteration, move it to result stack while (!number.empty()){ result.push_back(number.back()); number.pop_back(); } return result; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string nq_temp; getline(cin, nq_temp); vector<string> nq = split_string(nq_temp); int n = stoi(nq[0]); int q = stoi(nq[1]); string number_temp_temp; getline(cin, number_temp_temp); vector<string> number_temp = split_string(number_temp_temp); vector<int> number(n); for (int number_itr = 0; number_itr < n; number_itr++) { int number_item = stoi(number_temp[number_itr]); number[number_itr] = number_item; } vector<int> result = waiter(number, q); for (int result_itr = 0; result_itr < result.size(); result_itr++) { fout << result[result_itr]; if (result_itr != result.size() - 1) { fout << "\n"; } } fout << "\n"; fout.close(); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; } <file_sep>#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <stack> using namespace std; int main() { stack<string> textStack; int opNumber; int opSelect; string str; // use stack to store the previous element // use string as a dynamic array cin >> opNumber; for(int i=0; i<opNumber; i++){ cin >> opSelect; // check the selector // insert character if (opSelect == 1){ string insertStr; cin >> insertStr; textStack.push(str); // insert the previous str character to stack str = str + insertStr; // insert the new entered character to string } // delete n character else if (opSelect == 2){ int deleteStack; cin >> deleteStack; textStack.push(str); // insert the previous str character to stack str.erase(str.size() - deleteStack); // erase the string from n-th element to the end } // print n character else if (opSelect == 3){ int printStack; cin >> printStack; cout << str[printStack - 1] << endl; // print last n-th element from string } // reset to previous element else{ str = textStack.top(); // get the previous character from the stack textStack.pop(); // erase the last previous character } } return 0; } <file_sep>#include <bits/stdc++.h> #include <queue> #include <vector> #include <algorithm> #include <iostream> using namespace std; // make a new data type struct CustomerType{ int arrival, duration; }; // make a new type for sorting struct compare{ bool operator() (CustomerType &a, CustomerType &b){ return a.duration > b.duration; } }; // comparator a<b bool operator < (CustomerType a, CustomerType b){ return a.arrival < b.arrival; } int main() { int n; cin >> n; //make dynamic array to store customer arrival time and cook duration vector<CustomerType> customers; // make a sorted heap priority_queue<CustomerType, vector<CustomerType>, compare> minHeap; for (int i=0; i<n ;i++){ int a, d; cin >> a >> d; CustomerType listCustomer; listCustomer.arrival = a; listCustomer.duration = d; customers.push_back(listCustomer); } // sort the input customer data in ascending order sort(customers.begin(), customers.end()); long arrivalTime = 0; long waitingTime = 0; int i; int idx=0; while (true){ for (i=idx; i<n; i++){ // check if there is customer that arrive faster than previous arrival time if (customers[i].arrival <= arrivalTime){ minHeap.push(customers[i]); // insert faster customer to heap } else{ idx = i; // make the next cycle start from the last element checked break; } } if (i == n) idx = n; if(!minHeap.empty()){ CustomerType tmp = minHeap.top(); waitingTime += arrivalTime + tmp.duration - tmp.arrival; arrivalTime += tmp.duration; minHeap.pop(); } else{ // minHeap is empty // assign the customer arrival as the slowest arrival time if (idx != n) arrivalTime = customers[idx].arrival; } if (idx == n && minHeap.empty()) break; } cout << waitingTime/n << "\n"; return 0; }<file_sep>#include <bits/stdc++.h> #include <string> #include <algorithm> #include <map> using namespace std; // Complete the sherlockAndAnagrams function below. int sherlockAndAnagrams(string input) { int length = input.size(); map<string, int> m; m.clear(); for(int i=0; i<length; i++){ for(int j=1; j<length+1-i; j++){ string t = input.substr(i,j); sort(t.begin(), t.end()); m[t]++; } } int ans = 0; for(map<string, int>:: iterator itr = m.begin(); itr !=m.end(); itr++) ans += (long)(itr->second)*(itr->second-1)/2; return ans; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int q; cin >> q; cin.ignore(numeric_limits<streamsize>::max(), '\n'); for (int q_itr = 0; q_itr < q; q_itr++) { string s; getline(cin, s); int result = sherlockAndAnagrams(s); fout << result << "\n"; } fout.close(); return 0; }
6f153056895b52103c0ba9ac73bc4eb0e323746c
[ "Markdown", "C++" ]
14
C++
itsAstrid/HackerRank
9252537943448400b76c090405eab8faa0211181
999968979474a22a56215c3d3ef5595d488e5e6b
refs/heads/main
<file_sep><?php session_start(); include("config.php"); $id = $_GET['id']; $bi = $_GET['bi']; $stmt = $db->prepare("DELETE FROM coachbooking WHERE book_id LIKE ?"); $stmt->bind_param("s", $bi); $stmt->execute(); $stmt = $db->prepare("DELETE FROM userbooking WHERE user_id LIKE ? AND booking_id LIKE ?"); $stmt->bind_param("ss", $id, $bi); $stmt->execute(); $stmt = $db->prepare("DELETE FROM booking WHERE id LIKE ?"); $stmt->bind_param("s", $bi); $stmt->execute(); header("Location:./profile.php"); ?><file_sep><?php include("config.php"); $q = $_GET["q"]; $d = $_GET["d"]; $da = $_GET["da"]; $co = $_GET["co"]; $arr = []; $arr1 = []; $arr2 = []; $arr3 = []; $encoded; $da = "'".$da."'"; $counter = 0; $query = "SELECT ".$q.".id, ".$q.".court, ".$q.".timeInterval, TIME_TO_SEC(openinghours.open), TIME_TO_SEC(openinghours.close) FROM ".$q." INNER JOIN openinghours ON ".$q.".arena_id=openinghours.arena_id AND openinghours.weekday=".$d.";"; $query .= "SELECT ".$q.".id, TIME(booking.dateTimeStart) AS StartTime, TIME_TO_SEC(TIME(booking.dateTimeStart)) AS StartSec, userbooking.user_id FROM booking LEFT JOIN ".$q." ON booking.court_id = ".$q.".id LEFT JOIN userbooking ON userbooking.booking_id=booking.id WHERE booking.arena_id = ".$q.".arena_id AND DATE(booking.dateTimeStart) LIKE ".$da." ORDER BY ".$q.".id, StartTime;"; $query .= "SELECT TIME_TO_SEC(TIME(coachbooking.dateTimeStart)) AS StartSec, TIME_TO_SEC(TIME(coachbooking.dateTimeEnd)) AS EndSec, coachbooking.book_id FROM coachbooking WHERE coachbooking.coach_id = ".$co." AND DATE(coachbooking.dateTimeStart) LIKE ".$da." ORDER BY StartSec"; if($db->multi_query($query)) { do { if($result = $db->store_result()){ if ($counter == 0) { $i = 0; while($row = $result->fetch_row()) { $arr1[$i++] = array("Id"=>$row[0], "Name"=>$row[1], "Interval"=>$row[2], "Open"=>$row[3]/60, "Close"=>$row[4]/60); } $counter++; } else if ($counter == 1) { $i = 0; while($row = $result->fetch_row()) { $arr2[$i++] = array("Id"=>$row[0], "StartTime"=>$row[1], "StartMin"=>$row[2]/60, "Booker"=>$row[3]); } $counter++; } else { $i = 0; while($row = mysqli_fetch_row($result)) { $arr3[$i++] = array("Started"=>$row[0]/60, "Ended"=>$row[1]/60, "BookId"=>$row[2]); } } $result->free(); } } while ($db->more_results() && $db->next_result()); } $arr = array("sched"=>json_encode($arr1), "book"=>json_encode($arr2), "coa"=>json_encode($arr3)); $encoded = json_encode($arr); echo($encoded); ?><file_sep><?php include("config.php"); include("login_session.php"); if (! isset($_SESSION['loggedin']) || $_SESSION['loggedin'] != true){ header("Location: index.php"); } $username = $_SESSION["username"]; $sql = "SELECT * FROM users WHERE email = '$username'"; $result = $db->query($sql); $row = $result->fetch_assoc(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PadelBooker | Raise your rackets</title> <link rel="stylesheet" href="css/basic.css"> <link rel="stylesheet" href="css/footer.css"> <link rel="stylesheet" href="css/media.css"> <link rel="stylesheet" href="css/profile.css"> <?php if(isset($_SESSION['iscoach'])) { echo "<script src='javabois/coach.js'></script>"; echo "<script type='text/javascript'> var DAY = 0; </script>"; } ?> </head> <body onload="start()"> <div class="header"> <div class="container"> <div class="navbar"> <div class="logo"> <a href="index.php"><img src="images/logo1.png" height="150"></a> </div> <nav> <ul class="MenuItems" id="MenuItems"> <li><a href="index.php">Home</a></li> <li><a href="search.php">Book</a></li> <li><a href="<?php echo $drop_url; ?>"><?php echo $drop_name; ?></a></li> <li><a href="<?php echo $drop_admin_url; ?>"><?php echo $drop_admin; ?></a></li> </ul> </nav> <img src="images/menu.png" class="menu-icon" onclick="menutoggle()"> </div> <div class ="big-cont"> <div class="prof-box"> <div class ="box1"> <div class="child1"> <img src=<?php echo $row["imgurl"];?> > </div> <div class ="child2"> <p> Rank <?php echo $row["playrank"];?></p> </div> </div> <div class = "box2"> <div class =" child1"> <h2> <?php echo $row["firstname"] ." ". $row["lastname"];?></h2> </div> <div class =" child3"> <p> <?php echo $row["email"];?></p> </div> <div class =" child3"> <p><?php echo $row["phone"];?></p> </div> </div> </div> <div class ="bio"> <div class ="head"> <h2>Info</h2> </div> <div class= "content"> <p><?php echo $row["info"];?></p> </div> </div> <div class ="choice-box" > <div class =" choice first"> <a href="search.php" class="btn">Boka nu</a> </div> <div class ="choice"> <button class="btn" onclick="showform()">Redigera profil</button> </div> </div> <div class ="pinfo"> <div class="phead"> <p> Dina bokningar </p> </div> <div class="divider"></div> <div class="pbookings"> <div class ="pcol"> <div class ="pwhen"> <p><?php $qry = "SELECT users.email, booking.court_id, booking.courtname, TIME(booking.dateTimeStart) AS StartTime, DATE(booking.dateTimeStart) AS StartDate, TIME(booking.dateTimeEnd) AS EndTime, DATE(booking.dateTimeEnd) AS EndDate, arenas.name, userbooking.booking_id, users.id, coachbooking.coach_id FROM users LEFT JOIN userbooking ON users.id = userbooking.user_id LEFT JOIN booking ON userbooking.booking_id = booking.id LEFT JOIN arenas ON booking.arena_id = arenas.id LEFT JOIN coachbooking ON coachbooking.book_id = booking.id WHERE users.email = '$username' AND booking.court_id IS NOT NULL AND booking.dateTimeStart >= NOW() ORDER BY booking.dateTimeStart ASC"; if($res = mysqli_query($db, $qry)){ if(mysqli_num_rows($res) > 0){ echo "<table style='border-collapse: collapse;'>"; echo "<tr>"; echo "<th>Datum</th>"; echo "<th>Tid</th>"; echo "<th>Plats</th>"; echo "<th>Bana</th>"; echo "<th>Coach</th>"; echo "<th></th>"; echo "<th>Avboka</th>"; echo "</tr>"; while($lines = mysqli_fetch_array($res)){ echo "<tr style='height: 10px;'>"; echo "<td style='padding: 0 10px 0 0;'>" . $lines['StartDate'] . "</td>"; echo "<td style='padding: 0 10px 0 0;'>" . substr($lines['StartTime'],0,-3) . " - ". substr($lines['EndTime'],0,-3). "</td>"; echo "<td style='padding: 0 10px 0 0;'>" . $lines['name'] . "</td>"; echo "<td style='padding: 0 10px 0 0;'>" . $lines['courtname'] . "</td>"; if(!is_null($lines['coach_id'])){ echo "<td style='padding: 0 10px 0 0;'>" . 'JA' . "</td>"; } else{ echo "<td style='padding: 0 10px 0 0;'>" . 'NEJ' . "</td>"; } echo "<td style='padding: 0 10px 0 0;'>"."</td>"; echo "<td style='padding: 0 10px 0 0;'> <button type='button' class='btn' onclick='delbook("; echo $lines['id']; echo ","; echo $lines['booking_id']; echo ")'>X</button>"; echo "</tr>"; } echo "</table>"; mysqli_free_result($res); } else{ echo "Inga bokningar"; } } else{ echo "could not run $qry. " . mysqli_error($db); } ?> <script> function delbook(id, bi) { if(confirm("Sure you want to delete booking?")){ window.location.assign("deleteinfo.php?id="+ id + "&bi=" + bi); } } </script> </div> </div> </div> <div class="divider"></div> </div> </div> <div class="big-cont" id="formcontainer"> <form class="form-popup" enctype="multipart/form-data" action="updateinfo.php?id=<?php echo $row['id']?>" method="POST"> <div class ="manage-box"> <div class="row1"> <div class="col1"> <b>Namn</b> <b>Email</b> <b>Adress</b> <b>Rank</b> </div> <div class ="col1"> <input class="child2" type="text" id="fname" name="fname" value="<?php echo $row["firstname"]; ?>" required> <input class="child2" type="text" id="email" name="email" value="<?php echo $row["email"]; ?>" required> <input class="child2" type="text" id="adress" name="adress" value="<?php echo $row["street"];?>" placeholder="Street"> <input class="child2" type="number" id="playrank" name="playrank" value="<?php echo $row["playrank"]; ?>" placeholder="Rank"> </div> <div class ="col1"> <b>Efternamn</b> <b>Telenfonnr</b> <b>Postnr</b> </div> <div class ="col1"> <input class="child2" type="text" id="lname" name="lname" value="<?php echo $row["lastname"]; ?>" required> <input class="child2" type="text" id="phone" name="phone" value="<?php echo $row["phone"]; ?>" placeholder="Phone"> <input class="child2" type="text" id="zip" name="zip" value="<?php echo $row["zip"]; ?>" placeholder="Zip"> </div> </div> <div class="row2"> <br><b>Info</b> <br><textarea class="contentform" class="bio" type="text" id="info" name="info" placeholder="Bio"> <?php echo $row["info"];?> </textarea> </div> <div class="row2"> <p> Välj Profilbild </p> <input type="file" name="file"> </div> <br> <button type="submit" class="btn">Spara</button> </div> </form> </div> </div> </div> <div class="footer"> <div class="container"> <div class="row"> <div class="footer-col-1"> <h3>Download Our App</h3> <p>This app is for Apple and Android</p> <div class="app-logo"> <img src="images/download.png"> </div> </div> <div class="footer-col-2"> <img src="images/logo1.png"> </div> <div class="footer-col-3"> <h3>Useful Links</h3> <ul> <li><a href="<?php echo $url?>" style="color:gray;"><?php echo $menu_button?></a></li> <li><a href="./search.php" style="color:gray;">Book </a></li> </ul> </div> <div class="footer-col-4"> <h3>Follow us</h3> <ul> <li>Facebook</li> <li>Twitter</li> <li>Instagram</li> <li>Youtube</li> </ul> </div> </div> </div> </div> <script> //js for toggle menu var MenuItems = document.getElementById("MenuItems"); MenuItems.style.maxHeight = "0px"; function menutoggle(){ if(MenuItems.style.maxHeight == "0px"){ MenuItems.style.maxHeight = "200px" } else{ MenuItems.style.maxHeight = "0px" } } </script> <script type="text/javascript"> function start(){ document.getElementById("formcontainer").style.display = "none"; } function showform(){ document.getElementById("formcontainer").style.display = "block"; scrollTo(0,document.getElementById("formcontainer").offsetTop); } </script> </body> </html> <file_sep><?php session_start(); include("config.php"); $fname = $_POST['regfname']; $lname = $_POST['reglname']; $email = $_POST['regemail']; $password = $_POST['regpass']; $sql = "SELECT * FROM users WHERE email = '$email'"; $sqlresult = mysqli_query($db, $sql) or die (mysqli_error($db)); $result = mysqli_num_rows($sqlresult); if($result == 1){ $_SESSION['errors'] = array("Kontot existerar redan"); header("Location:account.php"); } else{ $sql = "INSERT INTO users (email, password, firstname, lastname) VALUES ('$email', password('$<PASSWORD>'), '$fname', '$lname')"; $result = mysqli_query($db, $sql) or die (mysqli_error($db)); header("Location:./index.php"); } ?><file_sep><?php /* Ajax search to get the arena results based on name, street, city or zipcode */ session_start(); include 'config.php'; $q = "%" .$_GET['q']. "%"; $sql = 'SELECT * from arenas WHERE "name" LIKE ? OR street LIKE ? OR city LIKE ? OR zip LIKE ? LIMIT 10'; if($stmt = mysqli_prepare($db, $sql)) { $stmt->bind_param("ssss", $q, $q, $q, $q); $stmt->execute(); $result = $stmt->get_result(); while($row = mysqli_fetch_array($result)){ $_SESSION['fs'] = true; echo '<a href="book.php?book='.$row["name"].'&did='.$row["dbname"].'&aid='.$row["id"].'""><div>'.$row["name"].', '.$row["street"].', '.$row["city"].'</div></a>'; } } else { echo "could not execute".mysqli_error($db); } ?> <file_sep><?php include("login_session.php"); if (!isset($_SESSION['fs'])) { header("Location:search.php"); } else { $_SESSION['book'] = $_GET['book']; $_SESSION['did'] = $_GET['did']; $_SESSION['aid'] = $_GET['aid']; unset($_SESSION['fs']); $_SESSION['bk'] = true; } $title = $_SESSION['book']; include ("coaches.php"); $did = "'".$_SESSION['did']."'"; $aID = $_SESSION['aid']; $who = 0; if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) { $who = $_SESSION['lid']; } $_SESSION['prev'] = $_SERVER['REQUEST_URI']; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PadelBooker | Raise your rackets</title> <link rel="stylesheet" href="css/basic.css"> <link rel="stylesheet" href="css/footer.css"> <link rel="stylesheet" href="css/accountPage.css"> <link rel="stylesheet" href="css/media.css"> <link rel="stylesheet" href="css/brands.css"> <link rel="stylesheet" href="css/bookingpage.css"> <script src="javabois/gitTableW.js"></script> <script type="text/javascript"> var DAY = 0; </script> </head> <body onload="giveTable(<?php echo $did ?>,DAY,<?php echo $who ?>,<?php echo $aID ?>)"> <div class="header"> <div class="container"> <div class="navbar"> <div class="logo"> <a href="index.php"><img src="images/logo1.png" height="150"></a> </div> <nav> <ul class="MenuItems" id="MenuItems"> <li><a href="index.php">Home</a></li> <li><a href="search.php">Book</a></li> <li><a href="<?php echo $drop_url; ?>"><?php echo $drop_name; ?></a></li> <li><a href ="<?php echo $drop_profile_url;?>"><?php echo $drop_profile;?></a></li> </ul> </nav> <img src="images/menu.png" class="menu-icon" onclick="menutoggle()"> </div> <div class ="big-cont"> <div class="book-cont"> <div class="arenaname"> <p> <?php echo $title ?> </p> </div> <div class="date-box"> <div class ="date-choise"> <div> <button onclick="giveTable(<?php echo $did ?>,(--DAY),<?php echo $who ?>,<?php echo $aID ?>)" class="btn next round" class="previous round" style="padding: 8px 16px; text-decoration: none; display: inline-block;">&#8249;</button> </div> <div class ="date" id="dboi"></div> <div> <button onclick="giveTable(<?php echo $did ?>,(++DAY),<?php echo $who ?>,<?php echo $aID ?>)" class="btn next round" style="padding: 8px 16px; text-decoration: none; display: inline-block;">&#8250;</button> </div> </div> </div> <div class="book-item"> <div class="bigboi" id="bigboi"></div> </div> </div> <div class="coaches"> <div class="mini-container"> <h3 style="text-align: center;">Tränare</h3> <?php coaches(); ?> </div> </div> </div> </div> </div> <div class="brands"> <div class="small-container"> <div class="rows"> <div class="col-5"> <img src="images/klarna.png"> </div> <div class="col-5"> <img src="images/visa.png"> </div> <div class="col-5"> <img src="images/mastercard.png"> </div> <div class="col-5"> <img src="images/bankid-logo.png"> </div> </div> </div> </div> <div class="footer"> <div class="container"> <div class="row"> <div class="footer-col-1"> <h3>Download Our App</h3> <p>This app is for Apple and Android</p> <div class="app-logo"> <img src="images/download.png"> </div> </div> <div class="footer-col-2"> <img src="images/logo1.png"> </div> <div class="footer-col-3"> <h3>Useful Links</h3> <ul> <li><a href="<?php echo $url?>" style="color:gray;"><?php echo $menu_button?></a></li> <li><a href="./search.php" style="color:gray;">Book </a></li> </ul> </div> <div class="footer-col-4"> <h3>Follow us</h3> <ul> <li>Facebook</li> <li>Twitter</li> <li>Instagram</li> <li>Youtube</li> </ul> </div> </div> </div> </div> <script> //js for toggle menu var MenuItems = document.getElementById("MenuItems"); MenuItems.style.maxHeight = "0px"; function menutoggle(){ if(MenuItems.style.maxHeight == "0px"){ MenuItems.style.maxHeight = "200px" } else{ MenuItems.style.maxHeight = "0px" } } </script> <script> function coachpage(coachid){ window.location.assign("./coachpage.php?coachid="+coachid); } </script> </body> </html> <file_sep><?php session_start(); if (! isset($_SESSION['loggedin']) || $_SESSION['loggedin'] != true){ $menu_button = "Sign in"; $url = "account.php"; $drop_name = "Sign in"; $drop_url = "account.php"; $drop_profile = ""; $drop_profile_url = ""; $drop_admin = ""; $drop_admin_url = ""; } else{ $menu_button = "My Profile"; $url = "profile.php"; $drop_profile = "Profile"; $drop_profile_url = "profile.php"; $drop_name = "Log out"; $drop_url = "logout.php"; if($_SESSION['admin'] == true){ $drop_admin = "Admin"; $drop_admin_url = "admin.php"; } else{ $drop_admin = ""; $drop_admin_url = ""; } } ?><file_sep><?php include("config.php"); include("ArenaSearch.php"); include("usersearch.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PadelBooker | Raise your rackets</title> <link rel="stylesheet" href="css/basic.css"> <link rel="stylesheet" href="css/footer.css"> <link rel="stylesheet" href="css/media.css"> <link rel="stylesheet" href="css/profile.css"> </head> <body> <div class="header"> <div class="container"> <div class="navbar"> <nav> <ul class="MenuItems" id="MenuItems"> <li><a href="index.php">Home</a></li> <li><a href="search.php">Book</a></li> </ul> </nav> <img src="images/menu.png" class="menu-icon" onclick="menutoggle()"> </div> </div> <p>Ta bort användare</p> <select name = "drop_2" id="drop_2"> Användare <option selected="selected">Användare</option> <?php usersearch(); ?> </select> <button onclick="RemoveUser()">Ta bort</button> <br> <br> <br> <p> Lägg till coach </p> <select name = "drop_3" id="drop_3"> <option value = " " selected="selected">Arena</option> <?php arenasearch(); ?> </select> <select name = "drop_4" id="drop_4"> Användare <option value = " " selected="selected">Användare</option> <?php usersearch(); ?> </select> <button onclick="AddCoach()">Lägg till</button> <br> <br> <br> <form method="POST" action="AddArena.php"> <p>Lägg till Arena</p> <input type="text" id="Arena" name="Arena" placeholder="Arenanamn" required> <input type="text" id="city" name="city" placeholder="Stad" required> <input type="text" id="street" name="street" placeholder="Adress" required> <input type="text" id="zip" name="zip" placeholder="Postnummer" required><br> Öppetider<br> Måndag <input type="time" id="open1" name="open1" required> - <input type="time" id="close1" name="close1" required><br> Tisdag <input type="time" id="open2" name="open2" required> - <input type="time" id="close2" name="close2" required><br> Onsdag <input type="time" id="open3" name="open3" required> - <input type="time" id="close3" name="close3" required><br> Torsdag <input type="time" id="open4" name="open4" required> - <input type="time" id="close4" name="close4" required><br> Fredag <input type="time" id="open5" name="open5" required> - <input type="time" id="close5" name="close5" required><br> Lördag <input type="time" id="open6" name="open6" required> - <input type="time" id="close6" name="close6" required><br> Söndag <input type="time" id="open0" name="open0" required> - <input type="time" id="close0" name="close0" required><br> <button type="submit">Lägg till</button> </form> <br> <br> <p>Lägg till bana</p> <select name = "arena_court" id="arena_court"> <option value = " " selected="selected">Arena</option> <?php arenasearch(); ?> </select> <input id="courtname" name="courtname" placeholder="Namn på ny bana..."></input> Bokningsintervall i timmar <select name="intervall" id="intervall"> <option value="1">1</option> <option value="1.5">1.5</option> <option value="2">2</option> </select> <button onclick="AddCourt()">Lägg till</button> <br> <br> <br> Ta bort arena <select name = "arena_remove" id="arena_remove"> <option value = " " selected="selected">Arena</option> <?php arenasearch(); ?> </select> <button onclick="RemoveArena()">Ta bort</button> <br> <br> <br> Ta bort bana <select name = "court_remove" id="court_remove" onchange="Findcourts()"> <option value = " " selected="selected">Arena</option> <?php dbnamesearch(); ?> </select> <select name="removecourt" id="removecourt"> </select> <button onclick="RemoveCourt()">Ta bort</button> <!---------- js for toggle menu-------> <script> var MenuItems = document.getElementById("MenuItems"); MenuItems.style.maxHeight = "0px"; function menutoggle(){ if(MenuItems.style.maxHeight == "0px"){ MenuItems.style.maxHeight = "200px" } else{ MenuItems.style.maxHeight = "0px" } } </script> <script> function RemoveUser(){ if(confirm("Är du säker på att du vill ta bort denna användare?")) e = document.getElementById("drop_2"); var id = e.options[e.selectedIndex].value; window.location.assign("./RemoveUser.php?id="+id); } function AddCoach(){ if(confirm("Vill du lägga till denna coach?")){ var e = document.getElementById("drop_3"); var arena_id = e.options[e.selectedIndex].value; var i = document.getElementById("drop_4"); var user_id = i.options[i.selectedIndex].value; window.location.assign("./AddCoach.php?id="+user_id+"&arena_id="+arena_id); } } function RemoveArena(){ if(confirm("Vill du ta bort arenan?")){ var e = document.getElementById("arena_remove"); var arena_id = e.options[e.selectedIndex].value; window.location.assign("./RemoveArena.php?id="+arena_id); } } function AddCourt(){ if(confirm("Vill du lägga till denna bana?")){ var e = document.getElementById("arena_court"); var id = e.options[e.selectedIndex].value; var court = document.getElementById("courtname").value; var i = document.getElementById("intervall"); var intervall = i.options[i.selectedIndex].value; window.location.assign("./AddCourt.php?id="+id+"&name="+court+"&intervall="+intervall); } } function Findcourts(){ var xmlhttp = new XMLHttpRequest(); var dbname; xmlhttp.onreadystatechange=function(){ document.getElementById("removecourt").innerHTML=this.responseText; console.log(this.responseText); } var e = document.getElementById("court_remove"); dbname = e.options[e.selectedIndex].value; xmlhttp.open("GET", "SearchCourt.php?dbname="+dbname, true); xmlhttp.send(); console.log(dbname); } function RemoveCourt(){ if(confirm("Vill du tha bort denna bana?")){ var e = document.getElementById("court_remove"); var dbname = e.options[e.selectedIndex].value; var i = document.getElementById("removecourt"); var courtid = i.options[i.selectedIndex].value window.location.assign("./RemoveCourt.php?dbname="+dbname+"&courtid="+courtid); } } </script> </body> </html> <file_sep><?php include("config.php"); $arenaname = $_POST['Arena']; $city = $_POST['city']; $street = $_POST['street']; $zip = $_POST['zip']; $open1 = $_POST['open1']; $close1 = $_POST['close1']; $open2 = $_POST['open2']; $close2 = $_POST['close2']; $open3 = $_POST['open3']; $close3 = $_POST['close3']; $open4 = $_POST['open4']; $close4 = $_POST['close4']; $open5 = $_POST['open5']; $close5 = $_POST['close5']; $open6 = $_POST['open6']; $close6 = $_POST['close6']; $open0 = $_POST['open0']; $close0 = $_POST['close0']; $dbname = preg_replace("/\s+/","", $arenaname); $dbname = preg_replace("/ä/","a", $dbname); $dbname = preg_replace("/å/","a", $dbname); $dbname = preg_replace("/ö/","o", $dbname); $stmt = $db->prepare("INSERT INTO arenas (name, street, city, zip, dbname) VALUES (?, ?, ?, ?, ?)"); $stmt->bind_param("sssss", $arenaname, $city, $street, $zip, $dbname); $stmt->execute(); $stmt2 = "create TABLE $dbname ( id INT AUTO_INCREMENT PRIMARY KEY, arena_id INT, court VARCHAR(50), timeInterval Longtext, FOREIGN KEY (arena_id) REFERENCES arenas(id) )"; $result = mysqli_query($db,$stmt2); $sql = "SELECT id FROM arenas WHERE name = '$arenaname'"; $result = mysqli_query($db,$sql); $sqlresult = mysqli_fetch_row($result); $sql = $sqlresult[0]; $time = "INSERT INTO openinghours (arena_id, weekday, open, close) VALUES('$sql',0, '$open0', '$close0')"; $time1 = "INSERT INTO openinghours (arena_id, weekday, open, close) VALUES('$sql',1, '$open6', '$close6')"; $time2 = "INSERT INTO openinghours (arena_id, weekday, open, close) VALUES('$sql',2, '$open5', '$close5')"; $time3 = "INSERT INTO openinghours (arena_id, weekday, open, close) VALUES('$sql',3, '$open4', '$close4')"; $time4 = "INSERT INTO openinghours (arena_id, weekday, open, close) VALUES('$sql',4, '$open3', '$close3')"; $time5 = "INSERT INTO openinghours (arena_id, weekday, open, close) VALUES('$sql',5, '$open2', '$close2')"; $time6 = "INSERT INTO openinghours (arena_id, weekday, open, close) VALUES('$sql',6, '$open1', '$close1')"; $result = mysqli_query($db, $time); $result = mysqli_query($db, $time1); $result = mysqli_query($db, $time2); $result = mysqli_query($db, $time3); $result = mysqli_query($db, $time4); $result = mysqli_query($db, $time5); $result = mysqli_query($db, $time6); header("Location:./admin.php"); ?><file_sep><?php include("config.php"); include("login_session.php"); if(!isset($_SESSION['prev'])) { $_SESSION['prev'] = '/project/index.php'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PadelBooker | Raise your rackets</title> <link rel="stylesheet" href="css/basic.css"> <link rel="stylesheet" href="css/footer.css"> <link rel="stylesheet" href="css/accountPage.css"> <link rel="stylesheet" href="css/media.css"> <link rel="stylesheet" href="css/brands.css"> </head> <body> <div class="header"> <div class="container"> <div class="navbar"> <div class="logo"> <a href="index.php"><img src="images/logo1.png" height="150"></a> </div> <nav> <ul class="MenuItems" id="MenuItems"> <li><a href="index.php">Home</a></li> <li><a href="search.php">Book</a></li> </ul> </nav> <img src="images/menu.png" class="menu-icon" onclick="menutoggle()"> </div> </div> <div class="container"> <div class="row"> <div class="col-2"> <img src="images/img1.png" width="100%"> </div> <div class="col-2"> <div class="form-container"> <div class="form-btn"> <span onclick="login()">Login</span> <span onclick="register()">Register</span> <hr id="Indicator"> </div> <?php if (isset($_SESSION['errors'])): ?> <br> <div class="form-errors"> <?php foreach($_SESSION['errors'] as $error): ?> <p style="color: red;"><?php echo $error ?></p> <?php endforeach; unset($_SESSION['errors']); ?> </div> <?php endif; ?> <form id="LoginForm" action="logprocess.php" method="POST"> <input type="text" id ="loguser" name="loguser" placeholder="Email" required> <input type="<PASSWORD>" id ="logpass" name="logpass" placeholder="<PASSWORD>" required> <button type="submit" id="btn" value="login" class="btn">Login</button> </form> <form id="RegForm" action="regprocess.php" method="POST"> <input type="text" id ="regfname" name="regfname" placeholder="Firstname" required> <input type="text" id ="reglname" name="reglname" placeholder="Lastname" required> <input type="text" id="regemail" name="regemail" placeholder="Email" required> <input type="<PASSWORD>" id ="regpass" name="regpass" placeholder="<PASSWORD>" required> <button type="submit" id="btn" value="register" class="btn">Register</button> </form> </div> </div> </div> </div> </div> <div class="footer"> <div class="container"> <div class="row"> <div class="footer-col-1"> <h3>Download Our App</h3> <p>This app is for Apple and Android</p> <div class="app-logo"> <img src="images/download.png"> </div> </div> <div class="footer-col-2"> <img src="images/logo1.png"> </div> <div class="footer-col-3"> <h3>Useful Links</h3> <ul> <li><a href="<?php echo $url?>" style="color:gray;"><?php echo $menu_button?></a></li> <li><a href="./search.php" style="color:gray;">Book </a></li> </ul> </div> <div class="footer-col-4"> <h3>Follow us</h3> <ul> <li>Facebook</li> <li>Twitter</li> <li>Instagram</li> <li>Youtube</li> </ul> </div> </div> </div> </div> <script> //js for toggle menu var MenuItems = document.getElementById("MenuItems"); MenuItems.style.maxHeight = "0px"; function menutoggle(){ if(MenuItems.style.maxHeight == "0px"){ MenuItems.style.maxHeight = "200px" } else{ MenuItems.style.maxHeight = "0px" } } </script> <script> //js for toggle form var LoginForm = document.getElementById("LoginForm"); var RegForm = document.getElementById("RegForm"); var Indicator = document.getElementById("Indicator"); function login(){ LoginForm.style.transform = "translateX(0px)"; RegForm.style.transform = "translateX(-300px)"; Indicator.style.transform = "translateX(0px)"; } function register(){ LoginForm.style.transform = "translateX(300px)"; RegForm.style.transform = "translateX(300px)"; Indicator.style.transform = "translateX(100px)"; } </script> </body> </html> <file_sep><?php function arenasearch(){ include("config.php"); $sql = "SELECT * FROM arenas"; $result = mysqli_query($db,$sql); while($drop_2 = mysqli_fetch_array($result)){ echo '<option value="'.$drop_2['id'].'">'.$drop_2['name'].'</option>'; } } function dbnamesearch(){ include("config.php"); $sql = "SELECT * FROM arenas"; $result = mysqli_query($db,$sql); while($drop_2 = mysqli_fetch_array($result)){ echo '<option value="'.$drop_2['dbname'].'">'.$drop_2['name'].'</option>'; } } ?><file_sep><?php include("config.php"); include("login_session.php"); $_SESSION['prev'] = $_SERVER['REQUEST_URI']; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PadelBooker | Raise your rackets</title> <link rel="stylesheet" href="css/basic.css"> <link rel="stylesheet" href="css/footer.css"> <link rel="stylesheet" href="css/accountPage.css"> <link rel="stylesheet" href="css/media.css"> <link rel="stylesheet" href="css/brands.css"> </head> <body> <div class="header"> <div class="container"> <div class="navbar"> <div> <a href="index.php"><img src="images/logo1.png" height="150"></a> </div> <nav> <ul class="MenuItems" id="MenuItems"> <li><a href="index.php">Home</a></li> <li><a href="search.php">Book</a></li> <li><a href="<?php echo $drop_url; ?>"><?php echo $drop_name; ?></a></li> <li><a href ="<?php echo $drop_profile_url;?>"><?php echo $drop_profile;?></a></li> <li><a href="<?php echo $drop_admin_url; ?>"><?php echo $drop_admin; ?></a></li> </ul> </nav> <img src="images/menu.png" class="menu-icon" onclick="menutoggle()"> </div> <div class="row"> <div class="col-2"> <h1>Padel Booker <br> Get Ready, ENJOY!</h1> <p>Grab your rackets and reserve your playtime, VAMOS!</p> <a href="search.php" class="btn">Book now &#8594</a> <a href="<?php echo $url; ?>" class="btn"><?php echo $menu_button; ?>&#8594</a> </div> <div class="col-2"> <img src="images/img1.png"> </div> </div> </div> </div> <div class="categories"> <div class="small-container"> <div class="row"> <div class="col-3"> <img src="images/imgpaddel1.jpg"> </div> <div class="col-3"> <img src="images/imgpaddel2.jpg"> </div> <div class="col-3"> <img src="images/imgpaddel3.jpg"> </div> </div> </div> </div> <div class="brands"> <div class="small-container"> <div class="row"> <div class="col-5"> <img src="images/klarna.png"> </div> <div class="col-5"> <img src="images/visa.png"> </div> <div class="col-5"> <img src="images/mastercard.png"> </div> <div class="col-5"> <img src="images/bankid-logo.png"> </div> </div> </div> </div> <div class="footer"> <div class="container"> <div class="row"> <div class="footer-col-1"> <h3>Download Our App</h3> <p>This app is for Apple and Android</p> <div class="app-logo"> <img src="images/download.png"> </div> </div> <div class="footer-col-2"> <img src="images/logo1.png"> </div> <div class="footer-col-3"> <h3>Useful Links</h3> <ul> <li><a href="<?php echo $url?>" style="color:gray;"><?php echo $menu_button?></a></li> <li><a href="./search.php" style="color:gray;">Book </a></li> </ul> </div> <div class="footer-col-4"> <h3>Follow us</h3> <ul> <li>Facebook</li> <li>Twitter</li> <li>Instagram</li> <li>Youtube</li> </ul> </div> </div> </div> </div> <script> //js for toggle menu var MenuItems = document.getElementById("MenuItems"); MenuItems.style.maxHeight = "0px"; function menutoggle(){ if(MenuItems.style.maxHeight == "0px"){ MenuItems.style.maxHeight = "200px" } else{ MenuItems.style.maxHeight = "0px" } } </script> </body> </html> <file_sep><?php session_start(); //databas connection include("config.php"); //Variabler som innehåller coach och admin id om det finns $_SESSION["coachid"] = ""; $_SESSION["admin"] = ""; ?> <?php //Kollar om vi lyckats koppla till databasen. if($db->connect_error) { die("Connection failed ".$db->connect_error); } //get value from post $username = $_POST['loguser']; $password = $_POST['logpass']; //Get values from db $result = $db->query("SELECT * FROM users WHERE email = '$username' AND password = password('$<PASSWORD>')") or die(mysqli_error("Failed to query database" )); $row = $result -> fetch_array(MYSQLI_NUM); $count = mysqli_num_rows($result); $level = $row[0]; $sql = "SELECT coach_id FROM coaches WHERE user_id = '$level'"; $result = mysqli_query($db, $sql); $sqlresult = mysqli_num_rows($result); //Kolla om det finns ett coach eller admin id kopplat till användaren if($sqlresult == 1){ $_SESSION['iscoach'] = true; } $sqlAdmin = "SELECT admin_id FROM admin WHERE user_id = '$level'"; $resultAdmin = mysqli_query($db, $sqlAdmin); $sqlresultAdmin = mysqli_num_rows($resultAdmin); if($sqlresultAdmin == 1){ $_SESSION['admin'] = true; } //control equal values if ($count == 1){ $_SESSION['username'] = $_POST['loguser']; $_SESSION['loggedin'] = true; $_SESSION['lid'] = $row[0]; header("Location:".$_SESSION['prev']); } else{ $_SESSION['errors'] = array("Your username or password was incorrect."); header("Location:account.php"); } ?><file_sep><?php include("config.php"); include("login_session.php"); $_SESSION['prev'] = $_SERVER['REQUEST_URI']; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PadelBooker | Raise your rackets</title> <link rel="stylesheet" href="css/basic.css"> <link rel="stylesheet" href="css/footer.css"> <link rel="stylesheet" href="css/accountPage.css"> <link rel="stylesheet" href="css/media.css"> </head> <body> <div class="header"> <div class="container" style="padding-bottom:16em;"> <div class="navbar"> <div class="logo"> <a href="index.php"><img src="images/logo1.png" height="150"></a> </div> <nav> <ul class="MenuItems" id="MenuItems"> <li><a href="index.php">Home</a></li> <li><a href="search.php">Book</a></li> <li><a href="<?php echo $drop_url; ?>"><?php echo $drop_name; ?></a></li> <li><a href ="<?php echo $drop_profile_url;?>"><?php echo $drop_profile;?></a></li> <li><a href="<?php echo $drop_admin_url; ?>"><?php echo $drop_admin; ?></a></li> </ul> </nav> <img src="images/menu.png" class="menu-icon" onclick="menutoggle()"> </div> <div class="row col-2"> <div class="col-2"> <h1>Hitta anläggningar och boka tid</h1> <div class="search-box"> <input type="text" placeholder="Search" onkeyup="showResult(this.value)"> <div id="livesearch"></div> </div> </div> </div> </div> </div> <div class="footer"> <div class="container"> <div class="row"> <div class="footer-col-1"> <h3>Download Our App</h3> <p>This app is for Apple and Android</p> <div class="app-logo"> <img src="images/download.png"> </div> </div> <div class="footer-col-2"> <img src="images/logo1.png"> </div> <div class="footer-col-3"> <h3>Useful Links</h3> <ul> <li><a href="<?php echo $url?>" style="color:gray;"><?php echo $menu_button?></a></li> <li><a href="./search.php" style="color:gray;">Book </a></li> </ul> </div> <div class="footer-col-4"> <h3>Follow us</h3> <ul> <li>Facebook</li> <li>Twitter</li> <li>Instagram</li> <li>Youtube</li> </ul> </div> </div> </div> </div> <script> //js for toggle menu var MenuItems = document.getElementById("MenuItems"); MenuItems.style.maxHeight = "0px"; function menutoggle(){ if(MenuItems.style.maxHeight == "0px"){ MenuItems.style.maxHeight = "200px" } else{ MenuItems.style.maxHeight = "0px" } } </script> <script type="text/javascript"> //livesearch with the help of javascript function showResult(str) { if (str.length==0) { document.getElementById("livesearch").innerHTML=""; document.getElementById("livesearch").style.border="0px"; return; } var xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (this.readyState==4 && this.status==200) { document.getElementById("livesearch").innerHTML=this.responseText; document.getElementById("livesearch").style.border="1px solid #A5ACB2"; } } xmlhttp.open("GET","backend-search.php?q="+str,true); xmlhttp.send(); } </script> </body> </html> <file_sep># Project Padel-booking This project is made by group 4. In Git the indentation looks really bad.. dont know why. Please download the zip to go through handsome code ;) <file_sep><?php include("config.php"); $arena_id = $_GET['id']; $courtname = $_GET['name']; $intervall = $_GET['intervall']; $sql = "SELECT dbname, id FROM arenas WHERE id = '$arena_id'"; $result = mysqli_query($db,$sql); $sqlresult = mysqli_fetch_row($result); $dbname = $sqlresult[0]; $id = $sqlresult[1]; if($intervall == 1){ $time = '60'; $string = "[{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]}]"; $sql = "INSERT INTO $dbname (arena_id, court, timeInterval) VALUES ('$id', '$courtname', '$string')"; $result = mysqli_query($db,$sql); header("Location:./admin.php"); } else if($intervall == 1.5){ $time = '90'; $string = "[{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]}]"; $sql = "INSERT INTO $dbname (arena_id, court, timeInterval) VALUES ('$id', '$courtname', '$string')"; $result = mysqli_query($db,$sql); header("Location:./admin.php"); } else{ $time = '120'; $string = "[{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]},{".'"'."day".'"'.":[$time]}]"; $sql = "INSERT INTO $dbname (arena_id, court, timeInterval) VALUES ('$id', '$courtname', '$string')"; $result = mysqli_query($db,$sql); header("Location:./admin.php"); } ?><file_sep><?php include("config.php"); $arenaid = $_GET['id']; $sql = "SELECT dbname FROM arenas WHERE id = '$arenaid'"; $result = mysqli_query($db,$sql); $sqlresult = mysqli_fetch_row($result); $dbname = $sqlresult[0]; $sql = "DELETE FROM openinghours WHERE arena_id = '$arenaid'"; $result = mysqli_query($db,$sql); $sql = "DELETE FROM arenas WHERE id = '$arenaid'"; $result = mysqli_query($db,$sql); $sql = "DROP TABLE $dbname"; $result = mysqli_query($db,$sql); header("Location:./admin.php"); ?><file_sep><?php include("config.php"); $id = $_GET['id']; $sql = "SELECT coach_id FROM coaches WHERE user_id = '$id'"; $result = mysqli_query($db,$sql); $row = mysqli_fetch_row($result); $coachid = $row[0]; $sql = "DELETE FROM coachinarena WHERE coach_id = '$coachid'"; $result = mysqli_query($db,$sql); $sql = "DELETE FROM coaches WHERE coach_id = '$coachid'"; $result = mysqli_query($db,$sql); $sql = "DELETE FROM userbooking WHERE user_id = '$id'"; $result = mysqli_query($db,$sql); $sql = "DELETE FROM users WHERE id = '$id'"; $result = mysqli_query($db,$sql); header("Location:./admin.php"); ?><file_sep><?php include("config.php"); $dbname = $_GET['dbname']; echo $dbname; $sql = "SELECT * FROM $dbname"; $result = mysqli_query($db,$sql); echo "<option value = ' ' selected='selected'>Bana</option>"; while($court = mysqli_fetch_array($result)){ echo '<option value="'.$court['id'].'">'.$court['id'].' '.$court['court'].'</option>'; } ?><file_sep><?php session_start(); include("config.php"); $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $phone = $_POST['phone']; $city = $_POST['city']; $street = $_POST['adress']; $zip = $_POST['zip']; $playrank = $_POST['playrank']; $bio = $_POST['info']; $id = $_GET['id']; $file = $_FILES['file']['name']; if($file == ""){ $stmt = $db->prepare("UPDATE users SET firstname=?,lastname=?,email=?,phone=?,street=?,city=?,zip=?,playrank=?,info=? WHERE id=?"); $stmt->bind_param("ssssssssss", $fname, $lname, $email, $phone, $street, $city, $zip, $playrank, $bio, $id); $stmt->execute(); $_SESSION["username"] = $email; header("Location:./profile.php"); echo "HEj"; } else{ $target_dir = "images/"; $target_file = $target_dir . basename($_FILES["file"]["name"]); $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); $extension_array = array("jpg","jpeg","png","gif"); if(in_array($imageFileType,$extension_array) ){ move_uploaded_file($_FILES['file']['tmp_name'],$target_file); } $stmt = $db->prepare("UPDATE users SET firstname=?,lastname=?,email=?,phone=?,street=?,city=?,zip=?,playrank=?,info=?,imgurl=? WHERE id=?"); $stmt->bind_param("sssssssssss", $fname, $lname, $email, $phone, $street, $city, $zip, $playrank, $bio, $target_file, $id); $stmt->execute(); $_SESSION["username"] = $email; header("Location:./profile.php"); } ?><file_sep><?php include("config.php"); $q = $_GET["q"]; $d = $_GET["d"]; $da = $_GET["da"]; $arr = []; $arr1 = []; $arr2 = []; $encoded; $da = "'".$da."'"; $counter = 0; $query = "SELECT ".$q.".id, ".$q.".court, ".$q.".timeInterval, TIME_TO_SEC(openinghours.open), TIME_TO_SEC(openinghours.close) FROM ".$q." INNER JOIN openinghours ON ".$q.".arena_id=openinghours.arena_id AND openinghours.weekday=".$d.";"; $query .= "SELECT ".$q.".id, TIME(booking.dateTimeStart) AS StartTime, TIME_TO_SEC(TIME(booking.dateTimeStart)) AS StartSec, userbooking.user_id FROM booking LEFT JOIN ".$q." ON booking.court_id = ".$q.".id LEFT JOIN userbooking ON userbooking.booking_id=booking.id WHERE booking.arena_id = ".$q.".arena_id AND DATE(booking.dateTimeStart) LIKE ".$da." ORDER BY ".$q.".id, StartTime"; if($db->multi_query($query)) { do { if($result = $db->store_result()){ if ($counter == 0) { $i = 0; while($row = $result->fetch_row()) { $arr1[$i++] = array("Id"=>$row[0], "Name"=>$row[1], "Interval"=>$row[2], "Open"=>$row[3]/60, "Close"=>$row[4]/60); } $counter++; } else { $i = 0; while($row = $result->fetch_row()) { $arr2[$i++] = array("Id"=>$row[0], "StartTime"=>$row[1], "StartMin"=>$row[2]/60, "Booker"=>$row[3]); } } $result->free(); } } while ($db->more_results() && $db->next_result()); } $arr = array("sched"=>json_encode($arr1), "book"=>json_encode($arr2)); $encoded = json_encode($arr); echo($encoded); ?><file_sep><?php session_start(); unset($_SESSION['username']); unset($_SESSION['loggedin']); if (isset($_SESSION['iscoach'])) { unset($_SESSION['iscoach']); } if (isset($_SESSION['admin'])) { unset($_SESSION['admin']); } header("Location:index.php"); ?><file_sep><?php include("config.php"); $dbname = $_GET['dbname']; $courtid = $_GET['courtid']; $sql = "DELETE FROM $dbname WHERE id = '$courtid'"; $result = mysqli_query($db,$sql); header("Location:./admin.php"); ?><file_sep><?php function coaches() { include("config.php"); $title = $_SESSION['book']; $arenafetch = "SELECT id FROM arenas WHERE name='$title'"; $result = mysqli_query($db,$arenafetch) or die(mysqli_error($db)); $arenaarray = []; $i=0; while($arenarow = mysqli_fetch_row($result)){ $arenaarray[$i++] = array("id"=>$arenarow[0]); } $id = $arenaarray[0]['id']; $sql = "SELECT * FROM users LEFT JOIN coaches ON coaches.user_id = users.id LEFT JOIN coachinarena ON coachinarena.coach_id = coaches.coach_id WHERE coachinarena.arena_id = ".$id; $result = mysqli_query($db,$sql) or die(mysqli_error($db)); $fullarray = []; $i = 0; $currentrow = 1; echo '<div class="rows">'; /* read coaches dynamically onto the webpage from the database */ while($row = mysqli_fetch_row($result)){ $fullarray[$i] = array("firstname"=>$row[3], "lastname"=>$row[4], "imgurl"=>$row[9], "coach_id"=>$row[13], "arena_id"=>$row[15]); $arraycount = count($fullarray); if($currentrow % 5 == 0){ echo '</div><div class="rows">'; } $imgurl = "imgurl"; $fullname = $fullarray[$i]['firstname']." ".$fullarray[$i]['lastname']; echo '<div class="column"> <img src="'; echo $fullarray[$i][$imgurl]; echo '" onclick="coachpage('; echo $fullarray[$i]['coach_id']; echo ')"> <div>'; echo $fullarray[$i]['firstname']; echo " "; echo $fullarray[$i]['lastname']; echo '</div> </div>'; $currentrow++; $i++; } echo '</div>'; } ?><file_sep><?php session_start(); include("config.php"); $user_id = $_GET['id']; $arena = $_GET['arena_id']; $sql = "INSERT INTO coaches(user_id) VALUES('$user_id')"; $result = mysqli_query($db, $sql) or die (mysqli_error($db)); $coach = "SELECT coach_id FROM coaches WHERE user_id = '$user_id'"; $result = mysqli_query($db, $coach) or die (mysqli_error($db)); $sqlresult = mysqli_fetch_row($result); $coach_id = $sqlresult[0]; $arenacoach = "INSERT INTO coachinarena (coach_id, arena_id) VALUES ('$coach_id', '$arena')"; $arenaresult = mysqli_query($db, $arenacoach) or die(mysqli_error($db)); header("Location:./admin.php"); ?><file_sep>-- phpMyAdmin SQL Dump -- version 5.0.3 -- https://www.phpmyadmin.net/ -- -- Värd: 127.0.0.1 -- Tid vid skapande: 03 nov 2020 kl 00:46 -- Serverversion: 10.4.14-MariaDB -- PHP-version: 7.4.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Databas: `padelbooking` -- -- -------------------------------------------------------- -- -- Tabellstruktur `admin` -- CREATE TABLE `admin` ( `admin_id` int(11) NOT NULL, `user_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `admin` -- INSERT INTO `admin` (`admin_id`, `user_id`) VALUES (1, 2); -- -------------------------------------------------------- -- -- Tabellstruktur `arenas` -- CREATE TABLE `arenas` ( `id` int(11) NOT NULL, `name` varchar(50) NOT NULL, `street` varchar(50) NOT NULL, `city` varchar(50) NOT NULL, `zip` varchar(10) NOT NULL, `dbname` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `arenas` -- INSERT INTO `arenas` (`id`, `name`, `street`, `city`, `zip`, `dbname`) VALUES (1, 'Bålsta Padelclub', ' Ullevivägen 2', 'Bålsta', '746 51', 'balstapadelclub'), (2, 'Järfälla Padel Club', 'Mjölnarvägen 1', 'Järfälla', '177 41', 'jarfallapadelclub'), (3, 'Västerås Padel Arena - Hälla', 'Stockholmsvägen 136', 'Västerås', '721 34', 'vasteraspadelarenahalla'), (4, 'Enköping Padel Arena', 'Sandgatan 24', 'Enköping', '749 35', 'enkopingpadelarena'), (5, 'Globen Padel', ' Arenaslingan 9', 'Johanneshov', '121 77', 'GlobenPadel'); -- -------------------------------------------------------- -- -- Tabellstruktur `balstapadelclub` -- CREATE TABLE `balstapadelclub` ( `id` int(11) NOT NULL, `arena_id` int(11) NOT NULL, `court` varchar(50) NOT NULL, `timeInterval` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `balstapadelclub` -- INSERT INTO `balstapadelclub` (`id`, `arena_id`, `court`, `timeInterval`) VALUES (1, 1, 'MTB AB', '[{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]}]'), (2, 1, 'Bäckarnas', '[{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]}]'), (3, 1, 'Padelpärras', '[{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]}]'), (4, 1, '746 AB', '[{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]}]'); -- -------------------------------------------------------- -- -- Tabellstruktur `booking` -- CREATE TABLE `booking` ( `id` int(11) NOT NULL, `arena_id` int(11) NOT NULL, `court_id` int(11) NOT NULL, `courtname` varchar(50) NOT NULL, `dateTimeStart` datetime NOT NULL, `dateTimeEnd` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `booking` -- INSERT INTO `booking` (`id`, `arena_id`, `court_id`, `courtname`, `dateTimeStart`, `dateTimeEnd`) VALUES (207, 1, 1, 'MTB AB', '2020-11-03 10:00:00', '2020-11-03 11:00:00'), (208, 1, 2, 'Bäckarnas', '2020-11-03 13:00:00', '2020-11-03 14:00:00'), (209, 1, 4, '746 AB', '2020-11-03 21:00:00', '2020-11-03 22:30:00'), (210, 1, 1, 'MTB AB', '2020-11-04 19:00:00', '2020-11-04 19:55:00'), (211, 1, 4, '746 AB', '2020-11-05 12:00:00', '2020-11-05 13:25:00'), (212, 5, 1, 'Tele 2', '2020-11-03 11:00:00', '2020-11-03 12:00:00'), (213, 1, 1, 'MTB AB', '2020-11-03 16:00:00', '2020-11-03 17:00:00'), (214, 1, 1, 'MTB AB', '2020-11-04 16:00:00', '2020-11-04 16:55:00'); -- -------------------------------------------------------- -- -- Tabellstruktur `coachbooking` -- CREATE TABLE `coachbooking` ( `book_id` int(11) DEFAULT NULL, `coach_id` int(11) NOT NULL, `dateTimeStart` datetime NOT NULL, `dateTimeEnd` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `coachbooking` -- INSERT INTO `coachbooking` (`book_id`, `coach_id`, `dateTimeStart`, `dateTimeEnd`) VALUES (207, 2, '2020-11-03 10:00:00', '2020-11-03 11:00:00'), (208, 2, '2020-11-03 13:00:00', '2020-11-03 14:00:00'), (209, 2, '2020-11-03 21:00:00', '2020-11-03 22:30:00'), (214, 3, '2020-11-04 16:00:00', '2020-11-04 16:55:00'), (210, 3, '2020-11-04 19:00:00', '2020-11-04 19:55:00'), (211, 3, '2020-11-05 12:00:00', '2020-11-05 13:25:00'); -- -------------------------------------------------------- -- -- Tabellstruktur `coaches` -- CREATE TABLE `coaches` ( `coach_id` int(11) NOT NULL, `user_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `coaches` -- INSERT INTO `coaches` (`coach_id`, `user_id`) VALUES (1, 1), (2, 3), (4, 2), (13, 8), (14, 4), (19, 1), (20, 1), (21, 1), (22, 1), (23, 1), (24, 10), (25, 10); -- -------------------------------------------------------- -- -- Tabellstruktur `coachinarena` -- CREATE TABLE `coachinarena` ( `coach_id` int(11) NOT NULL, `arena_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `coachinarena` -- INSERT INTO `coachinarena` (`coach_id`, `arena_id`) VALUES (1, 1), (1, 2), (1, 4), (2, 1), (4, 1), (13, 2), (14, 1), (24, 3), (24, 5); -- -------------------------------------------------------- -- -- Tabellstruktur `enkopingpadelarena` -- CREATE TABLE `enkopingpadelarena` ( `id` int(11) NOT NULL, `arena_id` int(11) NOT NULL, `court` varchar(50) NOT NULL, `timeInterval` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `enkopingpadelarena` -- INSERT INTO `enkopingpadelarena` (`id`, `arena_id`, `court`, `timeInterval`) VALUES (1, 4, 'Sparbanken i Enköping', '[{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]}]'), (2, 4, 'Clean Drink', '[{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]}]\r\n\r\n\r\n\r\n\r\n\r\n\r\n'), (3, 4, 'Infra Projektledning', '[{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]}]\r\n\r\n\r\n\r\n\r\n\r\n\r\n'), (4, 4, 'Combimix', '[{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]}]\r\n\r\n\r\n\r\n\r\n\r\n\r\n'); -- -------------------------------------------------------- -- -- Tabellstruktur `globenpadel` -- CREATE TABLE `globenpadel` ( `id` int(11) NOT NULL, `arena_id` int(11) DEFAULT NULL, `court` varchar(50) DEFAULT NULL, `timeInterval` longtext DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `globenpadel` -- INSERT INTO `globenpadel` (`id`, `arena_id`, `court`, `timeInterval`) VALUES (1, 5, 'Tele 2', '[{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]}]'), (2, 5, 'Swedbank', '[{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]}]'); -- -------------------------------------------------------- -- -- Tabellstruktur `jarfallapadelclub` -- CREATE TABLE `jarfallapadelclub` ( `id` int(11) NOT NULL, `arena_id` int(11) NOT NULL, `court` varchar(50) NOT NULL, `timeInterval` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `jarfallapadelclub` -- INSERT INTO `jarfallapadelclub` (`id`, `arena_id`, `court`, `timeInterval`) VALUES (1, 2, 'Centercourt', '[{\"day\":[90]},{\"day\":[60,90,90,90,90,90,90,90,90,90,90]},{\"day\":[60,90,90,90,90,90,90,90,90,90,90]},{\"day\":[60,90,90,90,90,90,90,90,90,90,90]},{\"day\":[60,90,90,90,90,90,90,90,90,90,90]},{\"day\":[60,90,90,90,90,90,90,90,90,90]},{\"day\":[90]}]'), (2, 2, 'Centercourt', '[{\"day\":[90]},{\"day\":[60,90,90,90,90,90,90,90,90,90,90]},{\"day\":[60,90,90,90,90,90,90,90,90,90,90]},{\"day\":[60,90,90,90,90,90,90,90,90,90,90]},{\"day\":[60,90,90,90,90,90,90,90,90,90,90]},{\"day\":[60,90,90,90,90,90,90,90,90,90]},{\"day\":[90]}]'), (3, 2, 'Court', '[{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]}]'), (4, 2, 'Court', '[{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]}]'), (5, 2, 'Court', '[{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]}]'), (6, 2, 'Court', '[{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]}]'), (7, 2, 'Court', '[{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]},{\"day\":[60]}]'); -- -------------------------------------------------------- -- -- Tabellstruktur `openinghours` -- CREATE TABLE `openinghours` ( `arena_id` int(11) NOT NULL, `weekday` int(11) NOT NULL, `open` time NOT NULL, `close` time NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `openinghours` -- INSERT INTO `openinghours` (`arena_id`, `weekday`, `open`, `close`) VALUES (1, 0, '06:00:00', '24:00:00'), (1, 1, '06:00:00', '24:00:00'), (1, 2, '06:00:00', '24:00:00'), (1, 3, '06:00:00', '24:00:00'), (1, 4, '06:00:00', '24:00:00'), (1, 5, '06:00:00', '24:00:00'), (1, 6, '06:00:00', '24:00:00'), (2, 0, '08:00:00', '23:00:00'), (2, 1, '07:00:00', '23:00:00'), (2, 2, '07:00:00', '23:00:00'), (2, 3, '07:00:00', '23:00:00'), (2, 4, '07:00:00', '23:00:00'), (2, 5, '07:00:00', '21:30:00'), (2, 6, '08:00:00', '19:00:00'), (3, 0, '06:00:00', '24:00:00'), (3, 1, '06:00:00', '24:00:00'), (3, 2, '06:00:00', '24:00:00'), (3, 3, '06:00:00', '24:00:00'), (3, 4, '06:00:00', '24:00:00'), (3, 5, '06:00:00', '24:00:00'), (3, 6, '06:00:00', '24:00:00'), (4, 0, '06:00:00', '23:00:00'), (4, 1, '06:00:00', '23:00:00'), (4, 2, '06:00:00', '23:00:00'), (4, 3, '06:00:00', '23:00:00'), (4, 4, '06:00:00', '23:00:00'), (4, 5, '06:00:00', '23:00:00'), (4, 6, '06:00:00', '23:00:00'), (5, 0, '08:00:00', '22:00:00'), (5, 1, '08:00:00', '20:00:00'), (5, 2, '07:00:00', '23:00:00'), (5, 3, '07:00:00', '23:00:00'), (5, 4, '07:00:00', '23:00:00'), (5, 5, '07:00:00', '23:00:00'), (5, 6, '07:00:00', '23:00:00'); -- -------------------------------------------------------- -- -- Tabellstruktur `userbooking` -- CREATE TABLE `userbooking` ( `user_id` int(11) NOT NULL, `booking_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `userbooking` -- INSERT INTO `userbooking` (`user_id`, `booking_id`) VALUES (2, 207), (2, 208), (2, 209), (2, 210), (2, 211), (5, 212), (5, 213), (5, 214); -- -------------------------------------------------------- -- -- Tabellstruktur `users` -- CREATE TABLE `users` ( `id` int(11) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(100) DEFAULT NULL, `firstname` varchar(50) DEFAULT NULL, `lastname` varchar(50) DEFAULT NULL, `street` varchar(50) NOT NULL, `city` varchar(50) NOT NULL, `zip` varchar(20) NOT NULL, `phone` varchar(20) NOT NULL, `imgurl` varchar(100) NOT NULL DEFAULT 'images/dummy.png', `info` varchar(500) NOT NULL, `playrank` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `users` -- INSERT INTO `users` (`id`, `email`, `password`, `firstname`, `lastname`, `street`, `city`, `zip`, `phone`, `imgurl`, `info`, `playrank`) VALUES (1, '<EMAIL>', <PASSWORD>', 'Rasmus', 'Selvander', 'Vänersborgsvägen 1B', 'Bålsta', '746 34', '0723979496', 'images/rs.jpg', 'Fun trainer', 10), (2, '<EMAIL>', <PASSWORD>', 'Tim', 'Dafteke', '', '', '', '', 'images/tränare3.jpg', ' ', 69), (3, '<EMAIL>', <PASSWORD>', 'Oskar', 'Renefalk', 'Vetevägen 1', '', '746', '', 'images/or.jpg', ' ', 2), (4, '<EMAIL>', '*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29', 'Gabriel', 'Kazai', '', '', '', '', 'images/tränare4.jpg', '', 0), (5, '<EMAIL>', '*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29', 'Pär', 'Jansson', 'Gäddan', '', '74691', '0700053100', 'images/tränare1.jpg', 'Likes to play padel on my spare time. Likes to google ', 9), (6, '<EMAIL>', '*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29', 'tester', 'tester', '', '', '', '0700053126', 'images/dummy.png', 'Likes to play padel on my spare time. Likes to google', 5), (8, '<EMAIL>', '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B', 'root', 'root', '', '', '000', '', 'images/dummy.png', 'test', 7), (10, '<EMAIL>', '*94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29', 'Albin', 'Lyckåsen', '', '', '', '', 'images/test.jpg', 'Best trainer i svedala ;)', 10), (12, '<EMAIL>', '*3D07E0D0A6AB1EB78DA1D222570ED89455FB7045', 'www', 'www', 'www', '', 'www', 'www', 'images/tränare4.jpg', ' testetteashryhewhshhrhhsh ', 9); -- -------------------------------------------------------- -- -- Tabellstruktur `vasteraspadelarenahalla` -- CREATE TABLE `vasteraspadelarenahalla` ( `id` int(11) NOT NULL, `arena_id` int(11) NOT NULL, `court` varchar(50) NOT NULL, `timeInterval` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumpning av Data i tabell `vasteraspadelarenahalla` -- INSERT INTO `vasteraspadelarenahalla` (`id`, `arena_id`, `court`, `timeInterval`) VALUES (1, 3, 'Alfaglas Centercourt', '[{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]}]'), (2, 3, 'Fastighetsbyrån', '[{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]}]'), (3, 3, 'Brunnby', '[{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]}]'), (4, 3, '<NAME>', '[{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]}]'), (5, 3, 'Putsarkungen', '[{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]},{\"day\":[90]}]'), (6, 3, 'VLT', '[{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]},{\"day\":[60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,120]}]'); -- -- Index för dumpade tabeller -- -- -- Index för tabell `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`admin_id`), ADD KEY `user_id` (`user_id`); -- -- Index för tabell `arenas` -- ALTER TABLE `arenas` ADD PRIMARY KEY (`id`,`name`,`city`); -- -- Index för tabell `balstapadelclub` -- ALTER TABLE `balstapadelclub` ADD PRIMARY KEY (`id`,`arena_id`) USING BTREE, ADD KEY `arena_id` (`arena_id`); -- -- Index för tabell `booking` -- ALTER TABLE `booking` ADD PRIMARY KEY (`id`) USING BTREE, ADD UNIQUE KEY `arena_id` (`arena_id`,`court_id`,`dateTimeStart`); -- -- Index för tabell `coachbooking` -- ALTER TABLE `coachbooking` ADD PRIMARY KEY (`coach_id`,`dateTimeStart`); -- -- Index för tabell `coaches` -- ALTER TABLE `coaches` ADD PRIMARY KEY (`coach_id`,`user_id`) USING BTREE, ADD KEY `user_id` (`user_id`) USING BTREE; -- -- Index för tabell `coachinarena` -- ALTER TABLE `coachinarena` ADD PRIMARY KEY (`coach_id`,`arena_id`), ADD KEY `arena_id` (`arena_id`); -- -- Index för tabell `enkopingpadelarena` -- ALTER TABLE `enkopingpadelarena` ADD PRIMARY KEY (`id`,`arena_id`), ADD KEY `arena_id` (`arena_id`); -- -- Index för tabell `globenpadel` -- ALTER TABLE `globenpadel` ADD PRIMARY KEY (`id`), ADD KEY `arena_id` (`arena_id`); -- -- Index för tabell `jarfallapadelclub` -- ALTER TABLE `jarfallapadelclub` ADD PRIMARY KEY (`id`,`arena_id`), ADD KEY `arena_id` (`arena_id`); -- -- Index för tabell `openinghours` -- ALTER TABLE `openinghours` ADD PRIMARY KEY (`arena_id`,`weekday`) USING BTREE; -- -- Index för tabell `userbooking` -- ALTER TABLE `userbooking` ADD PRIMARY KEY (`user_id`,`booking_id`), ADD KEY `booking_id` (`booking_id`) USING BTREE, ADD KEY `user_id` (`user_id`); -- -- Index för tabell `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`,`email`); -- -- Index för tabell `vasteraspadelarenahalla` -- ALTER TABLE `vasteraspadelarenahalla` ADD PRIMARY KEY (`id`,`arena_id`), ADD KEY `arena_id` (`arena_id`); -- -- AUTO_INCREMENT för dumpade tabeller -- -- -- AUTO_INCREMENT för tabell `admin` -- ALTER TABLE `admin` MODIFY `admin_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT för tabell `arenas` -- ALTER TABLE `arenas` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT för tabell `balstapadelclub` -- ALTER TABLE `balstapadelclub` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT för tabell `booking` -- ALTER TABLE `booking` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=215; -- -- AUTO_INCREMENT för tabell `coaches` -- ALTER TABLE `coaches` MODIFY `coach_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=26; -- -- AUTO_INCREMENT för tabell `enkopingpadelarena` -- ALTER TABLE `enkopingpadelarena` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT för tabell `globenpadel` -- ALTER TABLE `globenpadel` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT för tabell `jarfallapadelclub` -- ALTER TABLE `jarfallapadelclub` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT för tabell `users` -- ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT för tabell `vasteraspadelarenahalla` -- ALTER TABLE `vasteraspadelarenahalla` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- Restriktioner för dumpade tabeller -- -- -- Restriktioner för tabell `admin` -- ALTER TABLE `admin` ADD CONSTRAINT `admin_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Restriktioner för tabell `balstapadelclub` -- ALTER TABLE `balstapadelclub` ADD CONSTRAINT `balstapadelclub_ibfk_1` FOREIGN KEY (`arena_id`) REFERENCES `arenas` (`id`); -- -- Restriktioner för tabell `booking` -- ALTER TABLE `booking` ADD CONSTRAINT `booking_ibfk_1` FOREIGN KEY (`arena_id`) REFERENCES `arenas` (`id`), ADD CONSTRAINT `booking_ibfk_2` FOREIGN KEY (`arena_id`) REFERENCES `arenas` (`id`); -- -- Restriktioner för tabell `coaches` -- ALTER TABLE `coaches` ADD CONSTRAINT `coaches_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`), ADD CONSTRAINT `coaches_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `coaches_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE, ADD CONSTRAINT `coaches_ibfk_4` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Restriktioner för tabell `coachinarena` -- ALTER TABLE `coachinarena` ADD CONSTRAINT `coachinarena_ibfk_1` FOREIGN KEY (`coach_id`) REFERENCES `coaches` (`coach_id`), ADD CONSTRAINT `coachinarena_ibfk_2` FOREIGN KEY (`arena_id`) REFERENCES `arenas` (`id`), ADD CONSTRAINT `coachinarena_ibfk_3` FOREIGN KEY (`coach_id`) REFERENCES `coaches` (`coach_id`) ON DELETE CASCADE; -- -- Restriktioner för tabell `enkopingpadelarena` -- ALTER TABLE `enkopingpadelarena` ADD CONSTRAINT `enkopingpadelarena_ibfk_1` FOREIGN KEY (`arena_id`) REFERENCES `arenas` (`id`); -- -- Restriktioner för tabell `globenpadel` -- ALTER TABLE `globenpadel` ADD CONSTRAINT `globenpadel_ibfk_1` FOREIGN KEY (`arena_id`) REFERENCES `arenas` (`id`); -- -- Restriktioner för tabell `jarfallapadelclub` -- ALTER TABLE `jarfallapadelclub` ADD CONSTRAINT `jarfallapadelclub_ibfk_1` FOREIGN KEY (`arena_id`) REFERENCES `arenas` (`id`); -- -- Restriktioner för tabell `openinghours` -- ALTER TABLE `openinghours` ADD CONSTRAINT `openinghours_ibfk_1` FOREIGN KEY (`arena_id`) REFERENCES `arenas` (`id`); -- -- Restriktioner för tabell `userbooking` -- ALTER TABLE `userbooking` ADD CONSTRAINT `userbooking_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`), ADD CONSTRAINT `userbooking_ibfk_2` FOREIGN KEY (`booking_id`) REFERENCES `booking` (`id`), ADD CONSTRAINT `userbooking_ibfk_3` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`), ADD CONSTRAINT `userbooking_ibfk_4` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`), ADD CONSTRAINT `userbooking_ibfk_5` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`); -- -- Restriktioner för tabell `vasteraspadelarenahalla` -- ALTER TABLE `vasteraspadelarenahalla` ADD CONSTRAINT `vasteraspadelarenahalla_ibfk_1` FOREIGN KEY (`arena_id`) REFERENCES `arenas` (`id`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php function usersearch(){ include("config.php"); $sql = "SELECT * FROM users"; $result = mysqli_query($db,$sql); while($drop_u = mysqli_fetch_array($result)){ echo '<option value="'.$drop_u['id'].'"> '.$drop_u['id'].'. '.$drop_u['firstname'].' '.$drop_u['lastname'].'</option>'; } } ?><file_sep><?php session_start(); if (! isset($_SESSION['loggedin']) || $_SESSION['loggedin'] != true) { header("Location:account.php"); } else { include 'config.php'; $aid = $_GET['aid']; $cid = $_GET['cid']; $cname = $_GET['cname']; $dts = $_GET['dts']; $dte = $_GET['dte']; $uid = $_GET['uid']; $sql = "INSERT INTO booking (arena_id, court_id, courtname, dateTimeStart, dateTimeEnd) VALUES ('$aid', '$cid', '$cname', '$dts','$dte')"; $result = mysqli_query($db, $sql) or die (mysqli_error($db)); $sql= "SELECT id FROM booking WHERE arena_id='$aid' AND court_id='$cid' AND dateTimeStart='$dts'"; $result = $db->query("SELECT id FROM booking WHERE arena_id='$aid' AND court_id='$cid' AND dateTimeStart='$dts'"); $sqlresult = mysqli_fetch_row($result); $bookid = $sqlresult[0]; $sql = "INSERT INTO userbooking (user_id, booking_id) VALUES ('$uid', '$bookid')"; $result = mysqli_query($db,$sql); if (isset($_SESSION['iscoach'])) { $sql = "INSERT INTO coachbooking (book_id, coach_id, dateTimeStart, dateTimeEnd) VALUES ('$bookid', '$uid', '$dts', '$dte')"; } $result = mysqli_query($db,$sql); $sqlm = "SELECT name FROM arenas WHERE id = '$aid'"; $resultm = mysqli_query($db,$sqlm); $rowm = mysqli_fetch_row($resultm); $name = $rowm[0]; $message = "Din bokning för $dts till $dte på bana $cname i $name är nu konfirmerad, välkommen till $name"; $email = $_SESSION['username']; mail($email, "bokning",$message); header("location: profile.php"); } ?><file_sep><?php include("config.php"); include("login_session.php"); if (!isset($_SESSION['bk'])) { header("Location:search.php"); } else { unset($_SESSION['bk']); } $did = "'".$_SESSION['did']."'"; $aID = $_SESSION['aid']; $title = $_SESSION['book']; $coachid = $_GET['coachid']; $who = 0; if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) { $who = $_SESSION['lid']; } $sql = "SELECT * FROM users WHERE id = '$coachid'"; $result = mysqli_query($db, $sql); $row = $result->fetch_assoc(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Website | Shop Design</title> <link rel="stylesheet" href="css/basic.css"> <link rel="stylesheet" href="css/footer.css"> <link rel="stylesheet" href="css/accountPage.css"> <link rel="stylesheet" href="css/media.css"> <link rel="stylesheet" href="css/coachpage.css"> <link rel="stylesheet" href="css/bookingpage.css"> <script src="javabois/coachW.js"></script> <script type="text/javascript"> var DAY = 0; </script> </head> <body onload="giveTable(<?php echo $did ?>,DAY,<?php echo $who ?>,<?php echo $aID ?>,<?php echo $coachid ?>)"> <div class="header"> <div class="container" style="padding-bottom:16em;"> <div class="navbar"> <div class="logo"> <a href="index.php"><img src="images/logo1.png" height="150"></a> </div> <nav> <ul class="MenuItems" id="MenuItems"> <li><a href="index.php">Home</a></li> <li><a href="search.php">Book</a></li> <li><a href ="<?php echo $drop_url;?>"><?php echo $drop_name;?></a></li> <li><a href ="<?php echo $drop_profile_url;?>"><?php echo $drop_profile;?></a></li> </ul> </nav> <img src="images/menu.png" class="menu-icon" onclick="menutoggle()"> </div> <div class ="big-cont"> <div class="prof-box"> <div class ="box1"> <div class="child1"> <img src=<?php echo $row["imgurl"];?> > </div> <div class ="child2"> <h3>Rank <?php echo $row["playrank"];?></h3> </div> </div> <div class = "box2"> <div class =" child1"> <h2> <?php echo $row["firstname"] ." ". $row["lastname"];?></h2> </div> <div class =" child2"> <h3> Tränare </h3> </div> <div class =" child3"> <p> <?php echo $row["email"];?></p> </div> <div class =" child3"> <p><?php echo $row["phone"];?></p> </div> </div> </div> <div class ="bio"> <div class ="head"> <h2> Info </h2> </div> <div class= "content"> <p><?php echo $row["info"];?></p> </div> </div> <div class ="book-cont" style="width:100%;"> <div class="arenaname"> <p> <?php echo $title ?> </p> </div> <div class="date-box"> <div class ="date-choise"> <div> <button onclick="giveTable(<?php echo $did ?>,(--DAY),<?php echo $who ?>,<?php echo $aID ?>,<?php echo $coachid ?>)" class="btn next round" class="previous round" style="padding: 8px 16px; text-decoration: none; display: inline-block;">&#8249;</button> </div> <div class ="date" id="dboi"></div> <div> <button onclick="giveTable(<?php echo $did ?>,(++DAY),<?php echo $who ?>,<?php echo $aID ?>,<?php echo $coachid ?>)" class="btn next round" style="padding: 8px 16px; text-decoration: none; display: inline-block;">&#8250;</button> </div> </div> </div> <div class="book-item" id="booker"> </div> </div> </div> </div> </div> <div class="footer"> <div class="container"> <div class="row"> <div class="footer-col-1"> <h3>Download Our App</h3> <p>This app is for Apple and Android</p> <div class="app-logo"> <img src="images/download.png"> </div> </div> <div class="footer-col-2"> <img src="images/logo1.png"> </div> <div class="footer-col-3"> <h3>Useful Links</h3> <ul> <li><a href="<?php echo $url?>" style="color:gray;"><?php echo $menu_button?></a></li> <li><a href="./search.php" style="color:gray;">Book </a></li> </ul> </div> <div class="footer-col-4"> <h3>Follow us</h3> <ul> <li>Facebook</li> <li>Twitter</li> <li>Instagram</li> <li>Youtube</li> </ul> </div> </div> </div> </div> <script> //js for toggle menu var MenuItems = document.getElementById("MenuItems"); MenuItems.style.maxHeight = "0px"; function menutoggle(){ if(MenuItems.style.maxHeight == "0px"){ MenuItems.style.maxHeight = "200px" } else{ MenuItems.style.maxHeight = "0px" } } </script> </body> </html>
23c0632185abf65613d18c92e4b4725da94767b2
[ "Markdown", "SQL", "PHP" ]
29
PHP
rselvander/Project
9dc2f88d48960f79bef47818171f19f1e03a3609
e1f391413677dca30fbdcb9b5496d81970354414
refs/heads/master
<repo_name>laterne/app-sse-test<file_sep>/public/script.js var evtSource = new EventSource('sse'), list = document.getElementById('sselist') evtSource.onmessage = function(e) { var date = new Date(), time = date.toLocaleTimeString(); console.log(e.data, time) }
d8f5eb6232d9108fb27496514263b36c8135a908
[ "JavaScript" ]
1
JavaScript
laterne/app-sse-test
587fa984b0f2f326b045a75e907f5f5efeae0218
f7d153a830dff52b43889adfd463bf8e8e92df17
refs/heads/master
<repo_name>sert-uw/setup_android_project<file_sep>/setup.sh #!/bin/sh PROJECT_NAME="yourProjectName" mkdir $HOME/androidProjects cd $HOME/androidProjects git clone <EMAIL>:sert-uw/AndroidBaseProject.git $PROJECT_NAME cd $PROJECT_NAME git remote remove origin echo sdk.dir=$ANDROID_HOME > local.propeties git add local.propeties git commit -m "create local.propeties" FILE_NAME="$HOME/androidProjects/${PROJECT_NAME}/app/src/main/res/values/strings.xml" sed -i -e "s/AndroidBaseProject/${PROJECT_NAME}/g" $FILE_NAME git add $FILE_NAME git commit -m "change app name" ./gradlew build <file_sep>/Readme.md This shell script make new android project based on "<EMAIL>:sert-uw/AndroidBaseProject.git". If you use this, you should change PROJECT_NAME in setup.sh. After run, new android project exist $HOME/androidProjects. ## License [![Public Domain](http://i.creativecommons.org/p/mark/1.0/88x31.png)](http://creativecommons.org/publicdomain/mark/1.0/ "license") This work is free of known copyright restrictions.
150f5b784c39b865dbd157c078c6d2af94d5feb2
[ "Markdown", "Shell" ]
2
Shell
sert-uw/setup_android_project
8b9300c37ad3b4cc3deb71166cc9a3d73bb8aca9
564ecb362f7462395190952c9f96e83d9a9409e0
refs/heads/main
<repo_name>ionuts94/notekeeper<file_sep>/src/components/task/task.js import React, { useState } from 'react'; import { FaCheckSquare } from 'react-icons/fa'; import { FaMinusSquare } from 'react-icons/fa'; import './task.css'; const Task = ({ task, handleDoneTask, index, isDone, handleDeleteTask }) => { const [done, setDone] = useState(false); const setAsDone = () => { if(done === false) { setDone(true); handleDoneTask(index, true); } else { setDone(false); handleDoneTask(index, false); } } return( <div className="task-container"> <div className="task-details"> <h2 className={`${isDone ? 'markedAsDone' : null}`}>{ task }</h2> </div> <div className="task-controls"> <span onClick={ setAsDone } className={`${isDone ? 'checkedBtn' : null}`}> <FaCheckSquare /> </span> <span onClick={ () => handleDeleteTask(index) } className="deleteBtn"> <FaMinusSquare /> </span> </div> </div> ) } export default Task;<file_sep>/src/components/formInput/formInput.js import React from 'react'; import './formInput.css'; const FormInput = ({id, name, type, label, handleChange}) => { return( <div className="formInputContainer"> <div className="groupControls"> <input id={id} type={type} name={name} placeholder=" " onChange={ handleChange } /> <label className="labelForInput" htmlFor={id}>{ label }</label> </div> </div> ) } export default FormInput;<file_sep>/src/App.js import React, { useState, useEffect } from 'react'; import { Route, Switch } from 'react-router-dom'; import Homepage from './pages/homepage/homepage'; import SignInPage from './pages/signInPage/signInPage'; import RegisterPage from './pages/registerPage/registerPage'; import LoggedPage from './pages/loggedpage/loggedpage'; import firebase from './fiebase'; import './App.css'; function App() { const [isLoged, setIsLogged] = useState(false); const [userId, setUserId] = useState(''); const [userEmail, setUserEmail] = useState(''); const authListener = () => { firebase.auth().onAuthStateChanged(usr => { if(usr) { setUserId(usr.uid); setUserEmail(usr.email); setIsLogged(true); } else { setIsLogged(false); } }) } useEffect(() => { authListener(); }, [isLoged]) if(!isLoged) { return ( <div className="App"> <Switch> <Route path="/" exact component={ Homepage } /> <Route path="/signin" exact component={ () => <SignInPage /> } /> <Route path="/register" exact component={ () => <RegisterPage /> } /> </Switch> </div> ); } else { return( <div className="loggedPage"> <LoggedPage userId={ userId } userEmail={ userEmail } /> </div> ) } } export default App; <file_sep>/src/components/navBar/navBar.js import React from 'react'; import { useHistory } from 'react-router-dom'; import '../../pages/homepage/homepage.css'; import './navBar.css'; const NavBar = (props) => { const history = useHistory(); return( <div className="homepageComponent"> <div className="homepageNav"> <span className={props.active === 'home' ? 'activated' : null} onClick={ () => history.push('/') }>HOME</span> <span className={props.active === 'signin' ? 'activated' : null} onClick={ () => history.push('/signin') }>SIGN IN</span> <span className={props.active === 'register' ? 'activated' : null} onClick={ () => history.push('/register') }>REGISTER</span> </div> </div> ) } export default NavBar;<file_sep>/src/components/inputTask/inputTask.js import React from 'react'; import $ from 'jquery'; import './inputTask.css'; const InputTask = ( {handleInputChange, addToTotalTasks }) => { const addTask = () => { addToTotalTasks(); $('.taskInput').val(''); } return( <div className="inputTask-container"> <div className="groupInput"> <input className="taskInput" type="text" placeholder="new task" onChange={ handleInputChange } onKeyPress={(event) => { if(event.key === 'Enter') { addTask(); } }} /> <span className="addTaskBtn" onClick={ addTask }>⌐ </span> </div> </div> ) } export default InputTask;<file_sep>/src/fiebase.js import firebase from 'firebase'; import 'firebase/firestore'; const firebaseConfig = { apiKey: "<KEY>", authDomain: "keep-d511b.firebaseapp.com", projectId: "keep-d511b", storageBucket: "keep-d511b.appspot.com", messagingSenderId: "492495291456", appId: "1:492495291456:web:d9fa432b504480e9d8cba5", measurementId: "G-M29P9JT21D" }; firebase.initializeApp(firebaseConfig); export default firebase;<file_sep>/src/pages/homepage/homepage.js import React from 'react'; import NavBar from '../../components/navBar/navBar'; import Note1 from '../../asets/note2.png'; import Note2 from '../../asets/note2.png'; import Note3 from '../../asets/note2.png'; import './homepage.css'; const Homepage = (props) => { return( <div> <NavBar active={'home'} /> <div className="homepageComponent"> <div className="appDescritpion"> <h1>Overview</h1> <p> Capture ideas with your voice, add images to notes, check tasks off your to-do list, and much more. </p> <div className="noteImgContainer"> <span className="imgOne noteImgs"> <img id="imgOne" src={ Note1 } alt="sticker" /> </span> <span className="imgTwo noteImgs"> <img id="imgTwo" src={ Note2 } alt="sticker" /> </span> <span className="imgThree noteImgs"> <img id="imgThree" src={ Note3 } alt="sticker" /> </span> </div> </div> </div> </div> ); } export default Homepage;<file_sep>/src/pages/loggedpage/loggedpage.js import React, { useState, useEffect } from 'react'; import firebase from '../../fiebase'; import Note from '../../components/note/note' import './loggedpage.css'; const LoggedPage = ({ userId, userEmail }) => { const [loading, setLoading] = useState(false); const [rerender, setRerender] = useState(0); const [usersNotes, setUsersNotes] = useState([]); const handleSignOut = () => { firebase.auth().signOut() .catch(err => console.log(err)); } const getUsersNotes = async () => { setLoading(true); let notes = []; const db = firebase.firestore(); await db.collection('notes').where('userId', '==', `${userId}`).get() .then(doc => doc.docs.map(doc => notes.push(doc.data()))); setUsersNotes(notes); setLoading(false); } const createNewNote = async (e) => { e.preventDefault(); //check if there's an empty note on the board //get all notes from database first let notes = []; const db = firebase.firestore(); await db.collection('notes').where('userId', '==', `${userId}`).get() .then(doc => doc.docs.map(doc => notes.push(doc.data()))); let empty = false; notes.forEach(note => { if(note.tasks.length < 1) { empty = true; } }) if(empty){ alert("You already created an empty note."); } else { const randNoteId = Math.floor(Math.random() * 3000); let notes = [...usersNotes]; let noteDate = Date.now(); const today = new Date(noteDate); notes[notes.length] = { noteDate: today.toDateString(), userId: userId, noteId: randNoteId, tasks: [] } setUsersNotes(notes); } } const deleteNote = async (toBeDeleted) => { const db = firebase.firestore(); await db.collection("notes").doc(`${toBeDeleted}`).delete().then(() => { setRerender(rerender => rerender + 1); }).catch((error) => { console.error("Error removing document: ", error); }); } useEffect(() => { getUsersNotes(); }, [rerender]) if(loading) { return <h1 className="loading">Loading...</h1> } else { return( <div className="logged-page-container"> <div className="header"> <h1 className="greeting">Welcome, { userEmail } </h1> <h2 className="signOutBtn" onClick={ handleSignOut } >SIGN OUT</h2> <h1 className="greetingPhone">Welcome, { userEmail }</h1> </div> <div className="notes-number"> <h1>You currently have {usersNotes.length} notes </h1> <button onClick={ createNewNote } >Create note</button> </div> <div className="notes-container"> { usersNotes.map(note => <Note key={ note.noteId } noteId={ note.noteId } userId={ note.userId } noteDate={ note.noteDate } tasks={ note.tasks } deleteNote={ deleteNote } />) } </div> </div> ) } } export default LoggedPage;
95b216dff487ada7f7c191a9c613466c1f5cd052
[ "JavaScript" ]
8
JavaScript
ionuts94/notekeeper
23b6ec1cb34d3d9410f564daeafb4c5962db23cf
374dbc5adeab985cb97bf723435a7a32cff3bb72
refs/heads/main
<repo_name>GDevEngel/Dungeon-Escape<file_sep>/Assets/Scripts/Enemy/Skeleton.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Skeleton : Enemy, IDamageable { //config private float _damageCD = 0.5f; //global var private bool _canDamage = true; public int Health { get; set; } public override void Init() { base.Init(); Health = base.health; } public void Damage() { if (_canDamage == true) { _canDamage = false; Debug.Log(this.gameObject.name+" Damage()"); Health--; animator.SetTrigger("Hit"); animator.SetBool("InCombat", true); if (Health < 1) { animator.SetTrigger("Death"); isDead = true; //Destroy(this.gameObject, 1.5f); } else { StartCoroutine(ResetCanDamage()); } } } IEnumerator ResetCanDamage() { Debug.Log("reset dmg coroutine started"); yield return new WaitForSeconds(_damageCD); _canDamage = true; Debug.Log("reset dmg coroutine ended"); } }<file_sep>/Assets/Scripts/Player/PlayerAnimation.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerAnimation : MonoBehaviour { //handle private Animator _animator; private Animator _swordAnimator; private SpriteRenderer _swordEffect; // Start is called before the first frame update void Start() { _animator = GetComponentInChildren<Animator>(); if (_animator == null) { Debug.Log(this.gameObject.name + " animator is null"); } _swordAnimator = GameObject.Find("Sword Arc").GetComponent<Animator>(); _swordEffect = GameObject.Find("Sword Arc").GetComponent<SpriteRenderer>(); } public void Move(float speed) { _animator.SetFloat("Speed", Mathf.Abs(speed)); } public void Jumping(bool isJumping) { _animator.SetBool("Jumping", isJumping); } public void Attacking(bool FaceBack) { _animator.SetTrigger("Attack"); _swordAnimator.SetTrigger("Attack"); if (FaceBack) { _swordEffect.transform.localPosition = new Vector2(-0.29f, 0); } else { _swordEffect.transform.localPosition = new Vector2(0.29f, 0); } //_swordEffect.flipX = FaceBack; _swordEffect.flipY = FaceBack; } } <file_sep>/Assets/Scripts/Enemy/Enemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class Enemy : MonoBehaviour { [SerializeField] protected int health; [SerializeField] protected float speed; [SerializeField] protected int gems; [SerializeField] protected Transform pointA, pointB; [SerializeField] protected float alertDistance; //protected bool isHit = false; protected Transform target; protected Animator animator; protected SpriteRenderer spriteRenderer; protected Transform player; protected bool isDead = false; public virtual void Init() { animator = GetComponentInChildren<Animator>(); if (animator == null) { Debug.LogError(this.gameObject.name + ".animator is null"); } spriteRenderer = GetComponentInChildren<SpriteRenderer>(); if (spriteRenderer == null) { Debug.LogError(this.gameObject.name + ".renderer is null"); } player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>(); if (player == null) { Debug.LogError(this.gameObject.name+".player is null"); } target = pointB; } private void Start() { Init(); } public virtual void Update() { if (isDead == true) { return; } //face player if in combat mode if (animator.GetBool("InCombat") == true) { Vector2 direction = transform.position - player.position; if (direction.x > 0) { spriteRenderer.flipX = true; //transform.Rotate(0, 180f, 0); } else if (direction.x < 0) { spriteRenderer.flipX = false; } //if player moves away exit combat mode //Debug.Log(this.gameObject.name + " to player distance: " + Vector2.Distance(transform.position, player.position)); if (Vector2.Distance(transform.position, player.position) > alertDistance) { //isHit = false; animator.SetBool("InCombat", false); } } else if (Vector2.Distance(transform.position, player.position) < alertDistance) { animator.SetTrigger("Idle"); animator.SetBool("InCombat", true); } if (animator.GetCurrentAnimatorStateInfo(0).IsName("Idle") || animator.GetBool("InCombat") == true) { return; } Movement(); } public virtual void Movement() { if (target == pointA) { spriteRenderer.flipX = true; } else if (target == pointB) { spriteRenderer.flipX = false; } if (Vector2.Distance(transform.position, target.position) < 0.1f) { animator.SetTrigger("Idle"); //switch target if (target == pointA) { target = pointB; } else if (target == pointB) { target = pointA; } } if (animator.GetBool("InCombat") == false) { transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime); } } public virtual void Attack() { Debug.Log("My name is: " + this.gameObject.name); } } <file_sep>/Assets/Scripts/Enemy/Spider.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spider : Enemy, IDamageable { //handle [SerializeField] private GameObject AcidPrefab; //global var private bool _canDamage = true; public int Health { get; set; } public override void Init() { base.Init(); Health = base.health; } public void Damage() { if (_canDamage == true) { Health--; _canDamage = false; //animator.SetBool("InCombat", true); if (Health < 1) { animator.SetTrigger("Death"); isDead = true; //Destroy(this.gameObject, 1.5f); } } } public override void Movement() { //sit your ass down } public override void Attack() { Instantiate(AcidPrefab, transform.position, Quaternion.identity); } }<file_sep>/Assets/Scripts/Player/Player.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour, IDamageable { //handle private Rigidbody2D _rigidbody; [SerializeField] LayerMask _groundLayer; private PlayerAnimation _playerAnimation; private SpriteRenderer _playerRenderer; //config private float _speed = 2.5f; private float _jumpForce = 250f; private WaitForSeconds _jumpCDTime = new WaitForSeconds(0.3f); private float _distance = 0.8f; //from player to ground //global var private float _move; private bool _faceBack = false; private bool _jumpOffCD = true; public int Health { get; set; } // Start is called before the first frame update void Start() { _rigidbody = GetComponent<Rigidbody2D>(); if (_rigidbody == null) { Debug.Log(gameObject.name+".rigidbody is null"); } _playerAnimation = GetComponent<PlayerAnimation>(); if (_playerAnimation == null) { Debug.Log(gameObject.name + " PlayerAnimation is null"); } _playerRenderer = GetComponentInChildren<SpriteRenderer>(); if (_playerRenderer == null) { Debug.Log(this.gameObject.name + " SpriteRenderer is null"); } } // Update is called once per frame void Update() { CalculateMovement(); if (Input.GetButtonDown("Fire1")) { Attack(); } } private void CalculateMovement() { _move = (Input.GetAxisRaw("Horizontal")); Debug.Log("IsGrounded: " + IsGrounded()); if (IsGrounded() && Input.GetKeyDown(KeyCode.Space)) { _rigidbody.AddForce(new Vector2(0, _jumpForce)); //anim jumping _playerAnimation.Jumping(true); //jump cooldown check to prevent instant trigger of ground check raycast to end the jump anim StartCoroutine(JumpCD()); } _rigidbody.velocity = new Vector2(_move * _speed, _rigidbody.velocity.y); _playerAnimation.Move(_move); Flip(); } private void Flip() { if (_move > 0) { _playerRenderer.flipX = false; _faceBack = false; } else if (_move < 0) { _playerRenderer.flipX = true; _faceBack = true; } } private void Attack() { _playerAnimation.Attacking(_faceBack); } bool IsGrounded() { RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.down, _distance, _groundLayer); Debug.DrawRay(transform.position, Vector2.down * _distance, Color.green); if (hit) { if (_jumpOffCD == true) { //anim stop jumping _playerAnimation.Jumping(false); } return true; } else { return false; } } IEnumerator JumpCD() { _jumpOffCD = false; yield return _jumpCDTime; _jumpOffCD = true; } public void Damage() { Debug.Log(this.gameObject.name + " damage called"); //TODO cd system to prevent multiple hits Health--; if (Health < 1) { //TODO death anim } } } <file_sep>/Assets/Scripts/Enemy/AcidEffect.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class AcidEffect : MonoBehaviour { private float _speed = 3f; private float _destroyTimer = 5f; private void Start() { Destroy(this.gameObject, _destroyTimer); } private void Update() { transform.Translate(Vector2.right * _speed * Time.deltaTime); } private void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Player") { IDamageable player = other.GetComponent<IDamageable>(); if (player != null) { player.Damage(); } Destroy(this.gameObject); } } }
4346dec0be0c883daadc560b6a075b43ed2ff7e2
[ "C#" ]
6
C#
GDevEngel/Dungeon-Escape
81ae7bd5fc8f5fec604e3f97563c1a3df267b6f0
873255ef53202b3069ce7a38a4cf3e20fb3dada7
refs/heads/master
<repo_name>jcysewski/Star-Wars-Wiki<file_sep>/Star Wars App/Episode1.swift // // Episode1.swift // Star Wars App // // Created by jcysewski on 12/2/15. // Copyright © 2015 jcysewski. All rights reserved. // import UIKit class Episode1: UILabel { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ } <file_sep>/Star Wars App/SlotMachine.swift // // slotMachine.swift // Star Wars App // // Created by jcysewski on 12/3/15. // Copyright © 2015 jcysewski. All rights reserved. // import UIKit class SlotMachine: UIViewController { @IBOutlet weak var image1: UIImageView! @IBOutlet weak var image2: UIImageView! @IBOutlet weak var image3: UIImageView! var r2d2 : UIImage = UIImage(named: "R2D2")! var kyloRehn : UIImage = UIImage(named: "KyloRehn")! var falcon : UIImage = UIImage(named: "Falcon")! var c3po : UIImage = UIImage(named: "C3PO")! var chewie : UIImage = UIImage(named: "Chewbacca")! var tieFighter : UIImage = UIImage(named: "TieFighter")! var yoda : UIImage = UIImage(named: "Yoda")! var slotPics : [UIImage] = [] // array of UI images override func viewDidLoad() { super.viewDidLoad() slotPics = [r2d2, kyloRehn, falcon, c3po, chewie, yoda] } @IBAction func spinWheel(sender: UITapGestureRecognizer) { print("tapped") let randomPic1 = Int(arc4random_uniform(UInt32(slotPics.count))) //variable that randomly choose an Image from the array slotPics let randomPic2 = Int(arc4random_uniform(UInt32(slotPics.count))) let randomPic3 = Int(arc4random_uniform(UInt32(slotPics.count))) image1.image = slotPics[randomPic1] // sets the random picture to the Image Views on the story board image2.image = slotPics[randomPic2] image3.image = slotPics[randomPic3] if randomPic1 == randomPic2 && randomPic2 == randomPic3 //if statement to identify if you win { print("jackpot") jackpot() } } func jackpot() // when you win, an alert view pops up, and depending on the image that won, there is a different message. { if image1.image == falcon { let alert = UIAlertController(title: "Jackpot", message: "The Force is Strong With You Young Padawan", preferredStyle: UIAlertControllerStyle.Alert) let resestGame = UIAlertAction(title: "Play Again", style: UIAlertActionStyle.Default, handler: {sender in self.image1.image = self.falcon self.image2.image = self.falcon self.image3.image = self.falcon}) alert.addAction(resestGame) presentViewController(alert, animated: true, completion: nil) } if image1.image == kyloRehn { let alert = UIAlertController(title: "Jackpot", message: "The Dark Side is Calling for You", preferredStyle: UIAlertControllerStyle.Alert) let resestGame = UIAlertAction(title: "Play Again", style: UIAlertActionStyle.Default, handler: {sender in self.image1.image = self.kyloRehn self.image2.image = self.kyloRehn self.image3.image = self.kyloRehn}) alert.addAction(resestGame) presentViewController(alert, animated: true, completion: nil) } if image1.image == chewie { let alert = UIAlertController(title: "Jackpot", message: "Rrrrrrr-ghghghghgh (Chewie Growl)", preferredStyle: UIAlertControllerStyle.Alert) let resestGame = UIAlertAction(title: "Play Again", style: UIAlertActionStyle.Default, handler: {sender in self.image1.image = self.chewie self.image2.image = self.chewie self.image3.image = self.chewie}) alert.addAction(resestGame) presentViewController(alert, animated: true, completion: nil) } if image1.image == c3po { let alert = UIAlertController(title: "Jackpot", message: "This is not the droid you are looking for", preferredStyle: UIAlertControllerStyle.Alert) let resestGame = UIAlertAction(title: "Play Again", style: UIAlertActionStyle.Default, handler: {sender in self.image1.image = self.c3po self.image2.image = self.c3po self.image3.image = self.c3po}) alert.addAction(resestGame) presentViewController(alert, animated: true, completion: nil) } if image1.image == r2d2 { let alert = UIAlertController(title: "Jackpot", message: "Beep Boop Beep Boop Bop", preferredStyle: UIAlertControllerStyle.Alert) let resestGame = UIAlertAction(title: "Play Again", style: UIAlertActionStyle.Default, handler: {sender in self.image1.image = self.r2d2 self.image2.image = self.r2d2 self.image3.image = self.r2d2}) alert.addAction(resestGame) presentViewController(alert, animated: true, completion: nil) } if image1.image == tieFighter { let alert = UIAlertController(title: "Jackpot", message: "Rebel Scum", preferredStyle: UIAlertControllerStyle.Alert) let resestGame = UIAlertAction(title: "Play Again", style: UIAlertActionStyle.Default, handler: {sender in self.image1.image = self.tieFighter self.image2.image = self.tieFighter self.image3.image = self.tieFighter}) alert.addAction(resestGame) presentViewController(alert, animated: true, completion: nil) } if image1.image == yoda { let alert = UIAlertController(title: "Jackpot", message: "Succesful at Slot Machines, You Are", preferredStyle: UIAlertControllerStyle.Alert) let resestGame = UIAlertAction(title: "Play Again", style: UIAlertActionStyle.Default, handler: {sender in self.image1.image = self.yoda self.image2.image = self.yoda self.image3.image = self.yoda}) alert.addAction(resestGame) presentViewController(alert, animated: true, completion: nil) } } } <file_sep>/Star Wars App/ViewController.swift // // ViewController.swift // Star Wars App // // Created by jcysewski on 11/19/15. // Copyright © 2015 jcysewski. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "one" { let episode1View = segue.destinationViewController episode1View.title = "Episode I The Phantom Menace" } if segue.identifier == "two" { let episode2View = segue.destinationViewController episode2View.title = "Episode II Attack of the Clones" } if segue.identifier == "three" { let episode3View = segue.destinationViewController episode3View.title = "Episode III Revenge of the Sith" } if segue.identifier == "four" { let episode4View = segue.destinationViewController episode4View.title = "Episode IV A New Hope" } if segue.identifier == "five" { let episode5View = segue.destinationViewController episode5View.title = "Episode V The Empire Strikes Back" } if segue.identifier == "six" { let episode6View = segue.destinationViewController episode6View.title = "Episode VI Return of the Jedi" } if segue.identifier == "seven" { let episode7View = segue.destinationViewController episode7View.title = "Episode VII The Force Awakens" } if segue.identifier == "slotMachine" { let slotView = segue.destinationViewController slotView.title = "Slot Machine Game" } } }
24d5f4c65abc89a70d86cfe13993d89ed0eb7425
[ "Swift" ]
3
Swift
jcysewski/Star-Wars-Wiki
e6f49282dc4114013310ab36928b5cddfb2aff7e
7ddd4145faaf6aa842d16d13a713f1b92055f35b
refs/heads/master
<file_sep>package com.pageObject; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; public class AgentPage extends BasicSetUp{ protected final WebDriver driver; public AgentPage(WebDriver driver) throws Exception{ this.driver=driver; verifyPage(); } public void verifyPage() throws Exception{ try{ waitBetween(10); // wait.until(ExpectedConditions.elementToBeClickable(By.id("add_member"))); driver.findElement(By.id("add_member")); System.out.println("Agent Page Loaded @ "+ getDate()); writeText("Agent Page Loaded @ "+ getDate()); } catch(Exception e){ captureScreen("agent_page_error"); System.out.println("Error: Agent Page didn't Load @ "+ getDate()); writeText("Error: Agent Page didn't Load @ "+ getDate()); } } } <file_sep>package com.selenium.test; import java.io.IOException; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; public class Tests extends TestWeb { // Log in at call Center @Test public void testLogIn() throws Exception { writeText("============================"); writeText("Test Started @ " + getDate()); System.out.println("============================"); System.out.println("Test Started @ " + getDate()); try { waitBetween(); driver.get(baseUrl + ""); driver.findElement(By.id("j_username")).clear(); driver.findElement(By.id("j_username")).sendKeys(username); driver.findElement(By.id("j_password")).clear(); driver.findElement(By.id("j_password")).sendKeys(<PASSWORD>); driver.findElement(By.id("signin")).click(); try { driver.findElement(By.id("menu_home")); System.out.println("Login Succesful @ " + getDate()); writeText("Login Successful @ " + getDate()); } catch (Exception e){ captureScreen("login_error"); System.out.println("Error during Login @ " +getDate()); writeText("Error during Login @ " + getDate()); } } catch(Exception e){ captureScreen("page_load"); System.out.println(e); System.out.println("Error: Login Page didnot load @ " +getDate()); writeText("Error: Login Page didnot load @ " + getDate()); } System.out.println("LogIn test is completed @ "+ getDate()); writeText("LogIn test is completed @ "+getDate()); // addAgent("sachin" , "" , "", ""); testCCProfile(); } public void testCCProfile() throws Exception{ String oldpassword = "<PASSWORD>"; String newpassword = "<PASSWORD>"; String confirmnewpassword="<PASSWORD>"; // String email = "<EMAIL>"; // String fullname=""; // String address = ""; // String city=""; // String state=""; // String country=""; // String pincode=""; // String phone=""; // String timezone=""; // String language=""; // String curreny=""; try{ driver.findElement(By.id("PROFILE_SUBMENU")).click(); // Old Password driver.findElement(By.id("oldpassword")).clear(); driver.findElement(By.id("oldpassword")).sendKeys(<PASSWORD>); //New Password driver.findElement(By.id("password")).clear(); driver.findElement(By.id("password")).sendKeys(<PASSWORD>); // Confirm new Password driver.findElement(By.id("password0")).clear(); driver.findElement(By.id("password0")).sendKeys(<PASSWORD>); // driver.findElement(By.id("email")).clear(); // driver.findElement(By.id("email")).sendKeys(email); // driver.findElement(By.id("oldpassword")).clear(); // driver.findElement(By.id("oldpassword")).sendKeys(<PASSWORD>); // driver.findElement(By.id("contact_country")).sendKeys(country); // driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS); driver.findElement(By.id("updateprofile")).click(); // WebElement myDynamicElement = (new WebDriverWait(driver, 100)) // .until(new ExpectedCondition<WebElement>(){ // @Override // public WebElement apply(WebDriver d) { // return driver.findElement(By.xpath("/html/body/div/div[2]/div/span[2]")); // }}); try{ WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div/div[2]/div/span[2]"))); driver.findElement(By.xpath("/html/body/div/div[2]/div/span[2]")); System.out.println(driver.findElement(By.xpath("/html/body/div/div[2]/div/span[2]")).getText() + "@" + getDate()); writeText(driver.findElement(By.xpath("/html/body/div/div[2]/div/span[2]")).getText() + "@" + getDate()); } catch(Exception e){ captureScreen("profile_update"); System.out.println(driver.findElement(By.xpath("/html/body/div[3]/div[2]/div/div/span[2]")).getText()); writeText(driver.findElement(By.xpath("/html/body/div[3]/div[2]/div/div/span[2]")).getText()); writeText("Error: Profile can not be updated @ "+ getDate()); System.out.println("Error: Profile can not be updated @ "+ getDate()); } } catch(Exception e){ System.out.println("Some unexpected error durign testing:("); } // System.out.println("Its done! "); } public void addAgent(String agentName, String agentUserName, String agentPassword, String email) throws IOException{ try{ driver.findElement(By.id("menu_members")).click(); driver.findElement(By.id("add_member")).click(); driver.findElement(By.id("newmember_name")).sendKeys(agentName); driver.findElement(By.id("newuser_name")).sendKeys(agentUserName); driver.findElement(By.id("newmember_password")).sendKeys(agentPassword); driver.findElement(By.id("newmember_cpassword")).sendKeys(agentPassword); driver.findElement(By.id("newmember_add")).click(); try { WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("/html/body/div[3]/div[2]/table/tbody/tr/td/table[2]/tbody/tr[2]/td/table/tbody/tr/td[2]"))); System.out.println("AgentUserName:"+driver.findElement(By.xpath("/html/body/div[3]/div[2]/table/tbody/tr/td/table[2]/tbody/tr[2]/td/table/tbody/tr/td[2]")).getText() + "is added successfully @ " + getDate()); writeText("AgentUserName: '"+ driver.findElement(By.xpath("/html/body/div[3]/div[2]/table/tbody/tr/td/table[2]/tbody/tr[2]/td/table/tbody/tr/td[2]")).getText() + "' is added successfully @" + getDate()); } catch(Exception e){ captureScreen("add_agent_error"); System.out.println("Error: Agent is not added @" + getDate()); writeText("Error: Agent is not added @" + getDate()); } } catch(Exception e){ captureScreen("add_agent_error"); System.out.println("Error: Agent is not added @" + getDate()); writeText("Error: Agent is not added @" + getDate()); } } }
f4bc3c689209ae3abdcc02c94d88a2adf2012e25
[ "Java" ]
2
Java
sachin-singh/le.ccclogic
8221bd9c9aeb2b59bef7d6229b674be38e951738
664376b007e729930b820082b9d93014e7be0c6b
refs/heads/master
<file_sep>## Work-in-progress sample code for monitoring an Azure VM Currently mostly nonfunctional! Do not attempt to use this! <file_sep>from .vm_monitor import app<file_sep>from setuptools import setup setup( name='vm_monitor', packages=['vm_monitor'], include_package_data=True, install_requires=[ 'flask', 'azure>=2.0.0rc6', 'azure-mgmt-compute>=0.30.0rc6', 'azure-mgmt-network>=1.0.0rc1', 'pytz', 'tzlocal', ], )<file_sep>import datetime import os import sys from azure.common.credentials import ServicePrincipalCredentials from azure.mgmt.resource import ResourceManagementClient from azure.monitor import MonitorClient import pytz import tzlocal from flask import Flask, render_template app = Flask(__name__) app.config.from_object(__name__) # load config from this file # Load default config and override config from an environment variable app.config.update(dict( CLIENT_ID=os.environ['AZURE_CLIENT_ID'], CLIENT_SECRET=os.environ['AZURE_CLIENT_SECRET'], TENANT_ID=os.environ['AZURE_TENANT_ID'], SUBSCRIPTION_ID=os.environ['AZURE_SUBSCRIPTION_ID'] )) app.config.from_envvar('AZURE_VM_MONITOR_SETTINGS', silent=True) class AzureMonitor(object): def __init__(self, subscription_id, resource_group_name='azure-python-deployment-sample', vm_name='azure-deployment-sample-vm'): self.subscription_id = subscription_id self.resource_group_name = resource_group_name self.vm_name = vm_name self.resource_id = ( "subscriptions/{}/" "resourceGroups/{}/" "providers/Microsoft.Compute/virtualMachines/{}" ).format(self.subscription_id, self.resource_group_name, self.vm_name) credentials = ServicePrincipalCredentials( client_id=app.config['CLIENT_ID'], secret=app.config['CLIENT_SECRET'], tenant=app.config['TENANT_ID'], ) resource_client = ResourceManagementClient(credentials, self.subscription_id) resource_client.providers.register('Microsoft.Insights') self.client = MonitorClient(credentials, self.subscription_id) def show_metrics(self): # You can get the available metrics of this specific resource # Example of result for a VM: # Percentage CPU: id=Percentage CPU, unit=Unit.percent # Network In: id=Network In, unit=Unit.bytes # Network Out: id=Network Out, unit=Unit.bytes # Disk Read Bytes: id=Disk Read Bytes, unit=Unit.bytes # Disk Write Bytes: id=Disk Write Bytes, unit=Unit.bytes # Disk Read Operations/Sec: id=Disk Read Operations/Sec, unit=Unit.count_per_second # Disk Write Operations/Sec: id=Disk Write Operations/Sec, unit=Unit.count_per_second print('Available metrics for', self.subscription_id) for metric in self.client.metric_definitions.list(self.resource_id): # metric is an azure.monitor.models.MetricDefinition print("{}: id={}, unit={}".format( metric.name.localized_value, metric.name.value, metric.unit )) def get_metric_totals(self, metric_name='Network Out'): # Get a metric per hour for the last 24 hours. utc_now = pytz.utc.localize(datetime.datetime.utcnow()) tz_now = utc_now.astimezone(tzlocal.get_localzone()) end_of_this_hour = tz_now + datetime.timedelta(hours=1) end_time = end_of_this_hour.replace(minute=0, second=0, microsecond=0) start_time = end_time - datetime.timedelta(days=1) metric_filter = " and ".join([ "name.value eq '{}'".format(metric_name), "aggregationType eq 'Total'", "startTime eq {}".format(start_time.isoformat()), "endTime eq {}".format(end_time.isoformat()), "timeGrain eq duration'PT1H'", ]) return self.client.metrics.list( self.resource_id, filter=metric_filter, ) def show_metric_totals(metric_name='Network Out'): metrics_data = get_metric_totals(metric_name) print(start_time, '-', end_time) for item in metrics_data: # azure.monitor.models.Metric print("{} ({})".format(item.name.localized_value, item.unit.name)) for data in item.data: # azure.monitor.models.MetricData print("{}: {}".format(data.time_stamp, data.total)) @app.route('/') def display_metrics(): monitor = AzureMonitor(app.config['SUBSCRIPTION_ID']) return render_template('show_metrics.html', metrics=monitor.get_metric_totals()) if __name__ == '__main__': app.run(debug=True)
f033feb5f10c047536b10db6933f25226a99cc09
[ "Markdown", "Python" ]
4
Markdown
v-iam/azure-vm-monitor
4f6eabd697e727f92e3a2e996d9b077b44b79a6f
636e9a2b25f25de5deb99dc693972736377c48fb
refs/heads/master
<repo_name>ianicno/login-bootstrap<file_sep>/profile.php <?php ob_start(); session_start(); include_once 'dbconnect.php'; if (!isset($_SESSION['usr_id'])) // if the session is not set it will redirect to login.php { header('Location: login.php'); } ?> <!DOCTYPE html> <!--[if IE 8]> <html lang="en" class="ie8"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <head> <title><NAME> 201443500150</title> <!-- Meta --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Tugas Pemrograman Web 1"> <meta name="author" content="riandy"> <link rel="shortcut icon" href="assets/images/riandy.jpg"> <link href='https://fonts.googleapis.com/css?family=Roboto:400,500,400italic,300italic,300,500italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Global CSS --> <link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css"> <!-- Plugins CSS --> <link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.css"> <!-- Theme CSS --> <link id="theme-style" rel="stylesheet" href="assets/css/styles.css"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body style="background-image:url(assets/images/1.png)" > <!-- Navigation --> <nav class="navbar-default navbar-fixed-top" role="navigation"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="index.php">Beranda</a></li> <li><a href="profile.php">Profile</a></li> <?php if (isset($_SESSION['usr_id'])) { ?> <li><p class="navbar-text">Signed in as <?php echo $_SESSION['usr_name']; ?></p></li> <li><a href="logout.php">Log Out</a></li> <?php } else { ?> <li><a href="login.php">Login</a></li> <li><a href="register.php">Sign Up</a></li> <?php } ?> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <div class="wrapper"> <div class="sidebar-wrapper"> <div class="profile-container"> <img class="profile" src="assets/images/riandy.jpg" alt="" /> <h1 class="name"><NAME></h1> <h3 class="tagline">Internet Surfer </h3> </div><!--//profile-container--> <div class="contact-container container-block"> <h2 class="section-title">Kontak Saya</h2> <ul class="list-unstyled contact-list"> <li class="email"><i class="fa fa-envelope"></i><a href="mailto:<EMAIL>"><EMAIL></a></li> <li class="phone"><i class="fa fa-phone"></i><a href="tel:087 8888 33794">087 8888 33794</a></li> <li class="website"><i class="fa fa-globe"></i><a href="http://musicoloid.com" target="_blank">musicoloid.com</a></li> <li class="linkedin"><i class="fa fa-linkedin"></i><a href="#" target="_blank"><NAME></a></li> <li class="github"><i class="fa fa-github"></i><a href="https://github.com/ianicno" target="_blank">github.com/ianicno</a></li> <li class="twitter"><i class="fa fa-twitter"></i><a href="https://twitter.com/ri_andy" target="_blank">@ri_andy</a></li> <li class="twitter"><i class="fa fa-home"></i><a href="#" target="_blank">JL.Batu Ampar 3 Kramat Jati Jakarta Timur</a></li> </ul> </div><!--//contact-container--> </div><!--//sidebar-wrapper--> <div class="main-wrapper"> <section class="section summary-section"> <h2 class="section-title"><i class="fa fa-money"></i>MOTTO</h2> <div class="summary"> <p ><h3 align="center" ><i>"Money is The King , Management Is The Queen"</i></h3></p> </div><!--//summary--> </section><!--//section--> <section class="section experiences-section"> <h2 class="section-title"><i class="fa fa-briefcase"></i>Karir</h2> <div class="item"> <div class="meta"> <div class="upper-row"> <h3 class="job-title">halo-robotics.com</h3> <div class="time">2016 - Sekarang</div> </div><!--//upper-row--> <div class="company">PT.Halo Indah Permai</div> </div><!--//meta--> </div><!--//item--> <div class="item"> <div class="meta"> <div class="upper-row"> <h3 class="job-title">Berrypay.com</h3> <div class="time">2014 - 2015</div> </div><!--//upper-row--> <div class="company">PT.Berry Technology</div> </div><!--//meta--> </div><!--//item--> <div class="item"> <div class="meta"> <div class="upper-row"> <h3 class="job-title">Gramedia.com</h3> <div class="time">2012 - 2014</div> </div><!--//upper-row--> <div class="company">PT.Gramedia Asri Media</div> </div><!--//meta--> </div><!--//item--> </section><!--//section--> <section class="section experiences-section"> <h2 class="section-title"><i class="fa fa-user"></i>Pendidikan</h2> <div class="item"> <div class="meta"> <div class="upper-row"> <h3 class="job-title">Teknik Informatika</h3> <div class="time">2014 - 2018</div> </div><!--//upper-row--> <div class="company">Universitas Indraprasta PGRI</div> </div><!--//meta--> </div><!--//item--> <div class="item"> <div class="meta"> <div class="upper-row"> <h3 class="job-title">Teknik Audio Vidio</h3> <div class="time">2009 - 2012</div> </div><!--//upper-row--> <div class="company">SMKN 53 Jakarta </div> </div><!--//meta--> </div><!--//item--> </section><!--//section--> </div><!--//main-body--> </div> <br> <footer> <div class="text-center"> <div class="col-lg-12"> <p>Tugas Pemrograman Web 1 / X5A / riandy eka</p> </div> </div> </footer> <!-- Javascript --> <script type="text/javascript" src="assets/plugins/jquery-1.11.3.min.js"></script> <script type="text/javascript" src="assets/plugins/bootstrap/js/bootstrap.min.js"></script> <!-- custom js --> <script type="text/javascript" src="assets/js/main.js"></script> </body> </html> <file_sep>/index.php <?php session_start(); include_once 'dbconnect.php'; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- Bootstrap Core CSS --> <!-- Custom CSS --> <link href="assets/css/modern-business.css" rel="stylesheet"> <title><NAME> 201443500150</title> <!-- Meta --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Tugas Pemrograman Web 1"> <meta name="author" content="riandy"> <link rel="shortcut icon" href="assets/images/riandy.jpg"> <link href='https://fonts.googleapis.com/css?family=Roboto:400,500,400italic,300italic,300,500italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <!-- Global CSS --> <link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css"> <!-- Plugins CSS --> <link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.css"> <!-- Theme CSS --> <link id="theme-style" rel="stylesheet" href="assets/css/styles.css"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body style="background-image:url(assets/images/1.png)" > <!-- Navigation --> <nav class="navbar-default navbar-fixed-top" role="navigation"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li><a href="index.php">Beranda</a></li> <li><a href="profile.php">Profile</a></li> <?php if (isset($_SESSION['usr_id'])) { ?> <li><p class="navbar-text">Signed in as <?php echo $_SESSION['usr_name']; ?></p></li> <li><a href="logout.php">Log Out</a></li> <?php } else { ?> <li><a href="login.php">Login</a></li> <li><a href="register.php">Sign Up</a></li> <?php } ?> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <!-- Header Carousel --> <header id="myCarousel" class="carousel slide"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <div class="fill" style="background-image:url('assets/images/1.jpg');"></div> <div class="carousel-caption"> <h2><NAME></h2> </div> </div> <div class="item"> <div class="fill" style="background-image:url('assets/images/2.jpg');"></div> <div class="carousel-caption"> <h2>Internet Surfer</h2> </div> </div> <div class="item"> <div class="fill" style="background-image:url('assets/images/3.jpg');"></div> <div class="carousel-caption"> <h2>Professional Sleepyhead</h2> </div> </div> </div> <!-- Controls --> <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="icon-prev"></span> </a> <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="icon-next"></span> </a> </header> <!-- Page Content --> <div class="container"> <!-- Marketing Icons Section --> <div class="row"> <div class="col-lg-12"> <h1 class="container"> Selamat Datang Di Profile Saya </h1> </div> </div> <!-- /.row --> <!-- Features Section --> <div class="well"> <div class="row"> <div class="col-lg-12"> <h1 class="container"> </h1> </div> <div class="col-md-6"> <p>Mawar itu merah , Violet itu Biru:</p> <ul> <li>jangan main klarinet </li> <li>jangan pernah memainkan lampu senter dengan cepat, lampu senter itu dianggap undangan </li> <li> jangan berhenti menatap sekitar </li> <li> jangan makan keju, (bagaimana kalo yg kotak?) kotak tidak apa-apa </li> <li>jangan pake topi sombrero atau baju bodoh! atau sepatu merah! atau rok panjang! </li> <li>jangan pernah! selamanya jangan! selamanya jangan! jangan! menari dan berteriak seperti keraaaa!!!! </li> </ul> <p></p> </div> <div class="col-md-6"> <video width="550" height="300" controls> <source src="assets/images/bergerak.mp4" type="video/mp4"> </video> </div> </div> </div> <!-- /.row --> <hr> <!-- Call to Action Section --> <div class="well"> <div class="row"> <div class="col-md-8"> <p>Ayo dapatkan Profil saya Disini tinggal klik tombol disamping</p> </div> <div class="col-md-4"> <a class="btn btn-lg btn-default btn-block" href="guest.html">Dapatkan Profil Saya</a> </div> </div> </div> <hr> <!-- Footer --> <footer> <div class="text-center"> <div class="col-lg-12"> <p>Tugas Pemrograman Web 1 / X5A / riandy eka</p> </div> </div> </footer> </div> <!-- /.container --> <!-- jQuery --> <script src="assets/js/min/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="assets/js/min/bootstrap.min.js"></script> <!-- Script to Activate the Carousel --> <script> $('.carousel').carousel({ interval: 5000 //changes the speed }) </script> </body> </html>
a6208ea35273980ee0a9ca702965c0e407b8d7a9
[ "PHP" ]
2
PHP
ianicno/login-bootstrap
b40c4b5d74e9eb6735bec94b506fcb043e425c22
fb672cfd9fc8f4bb35c1082697e5cd59d2c3e53b
refs/heads/main
<repo_name>SiddharthShyniben/vscode-generator-code<file_sep>/generators/app/generate-command-ts .js /*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ const prompts = require("./prompts"); module.exports = { id: 'ext-command-ts', aliases: ['ts', 'command-ts'], name: 'New Extension (TypeScript)', insidersName: 'New Extension with Proposed API (TypeScript)', /** * @param {import('yeoman-generator')} generator * @param {Object} extensionConfig */ prompting: async (generator, extensionConfig) => { await prompts.askForExtensionDisplayName(generator, extensionConfig); await prompts.askForExtensionId(generator, extensionConfig); await prompts.askForExtensionDescription(generator, extensionConfig); await prompts.askForGit(generator, extensionConfig); await prompts.askForWebpack(generator, extensionConfig); await prompts.askForPackageManager(generator, extensionConfig); }, /** * @param {import('yeoman-generator')} generator * @param {Object} extensionConfig */ writing: (generator, extensionConfig) => { if (extensionConfig.webpack) { generator.fs.copy(generator.templatePath('vscode-webpack'), generator.destinationPath('.vscode')); } else { generator.fs.copy(generator.templatePath('vscode'), generator.destinationPath('.vscode')); } generator.fs.copy(generator.templatePath('src/test'), generator.destinationPath('src/test')); generator.fs.copyTpl(generator.templatePath('vscodeignore'), generator.destinationPath('.vscodeignore'), extensionConfig); if (extensionConfig.gitInit) { generator.fs.copy(generator.templatePath('gitignore'), generator.destinationPath('.gitignore')); } generator.fs.copyTpl(generator.templatePath('README.md'), generator.destinationPath('README.md'), extensionConfig); generator.fs.copyTpl(generator.templatePath('CHANGELOG.md'), generator.destinationPath('CHANGELOG.md'), extensionConfig); generator.fs.copyTpl(generator.templatePath('vsc-extension-quickstart.md'), generator.destinationPath('vsc-extension-quickstart.md'), extensionConfig); generator.fs.copyTpl(generator.templatePath('tsconfig.json'), generator.destinationPath('tsconfig.json'), extensionConfig); generator.fs.copyTpl(generator.templatePath('src/extension.ts'), generator.destinationPath('src/extension.ts'), extensionConfig); generator.fs.copyTpl(generator.templatePath('package.json'), generator.destinationPath('package.json'), extensionConfig); generator.fs.copy(generator.templatePath('.eslintrc.json'), generator.destinationPath('.eslintrc.json')); if (extensionConfig.pkgManager === 'yarn') { generator.fs.copyTpl(generator.templatePath('.yarnrc'), generator.destinationPath('.yarnrc'), extensionConfig); } if (extensionConfig.webpack) { generator.fs.copyTpl(generator.templatePath('webpack.config.js'), generator.destinationPath('webpack.config.js'), extensionConfig); } extensionConfig.installDependencies = true; extensionConfig.proposedAPI = extensionConfig.insiders; } } <file_sep>/generators/app/generate-web-update.js /*--------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ module.exports = { id: 'ext-web-update', aliases: ['web-update'], insidersName: 'Add Web bits to existing extension (TypeScript)', update: true, /** * @param {import('yeoman-generator')} generator * @param {Object} extensionConfig */ prompting: async (generator, extensionConfig) => { const pkgJSON = generator.fs.readJSON(generator.destinationPath('package.json')); if (!pkgJSON || !pkgJSON['engines'] || !pkgJSON['engines'].vscode) { generator.log(''); generator.log('Unable to find `package.json` in the current directory.'); generator.log('Please run the generator on the folder on an existing VSCode extension.'); throw new Error('No extension detected at ' + generator.destinationPath()); } extensionConfig.pkgJSON = pkgJSON; }, /** * @param {import('yeoman-generator')} generator * @param {Object} extensionConfig */ writing: (generator, extensionConfig) => { generator.log('To make this extension a web extension, the generator will add the following:'); generator.log('- A new main module `src/web/extension.ts` used when running in the web extension host.'); generator.log('- New webpack configuration file `build/web-extension.webpack.config.js`'); generator.log('- Updates to `package.json`:'); generator.log(' - new property `browser`: points to the packaged web main module.'); generator.log(' - new devDependencies: `webpack`, `webpack-cli` and `ts-loader`'); generator.log(' - new scripts: `compile-web`, `watch-web` and `package-web`'); extensionConfig.name = extensionConfig.pkgJSON.name; extensionConfig.displayName = extensionConfig.pkgJSON.displayName; const dependencyVersions = extensionConfig.dependencyVersions; generator.fs.extendJSON('package.json', { 'browser': './dist/web/extension.js', 'scripts': { "test-web": "node ./dist/web/test/runTest.js", "pretest-web": "npm run compile-web && tsc ./src/web/test/runTest.ts --outDir ./dist --rootDir ./src --target es6 --module commonjs", "compile-web": "webpack --config ./build/web-extension.webpack.config.js", "watch-web": "webpack --watch --config ./build/web-extension.webpack.config.js", "package-web": "webpack --mode production --devtool hidden-source-map --config ./build/web-extension.webpack.config.js", }, 'devDependencies': { 'ts-loader': dependencyVersions['ts-loader'], 'webpack': dependencyVersions['webpack'], 'webpack-cli': dependencyVersions['webpack-cli'], "@types/webpack-env": dependencyVersions['@types/webpack-env'], "assert": dependencyVersions['assert'], "process": dependencyVersions['process'] } }); generator.fs.copyTpl(generator.templatePath('src/web/extension.ts'), generator.destinationPath('src/web/extension.ts'), extensionConfig, {}); generator.fs.copy(generator.templatePath('src/web/test'), generator.destinationPath('src/web/test')); generator.fs.copyTpl(generator.templatePath('build/web-extension.webpack.config.js'), generator.destinationPath('build/web-extension.webpack.config.js'), extensionConfig); if (generator.fs.exists(generator.destinationPath('yarn.lock'))) { extensionConfig.pkgManager = 'yarn'; } else { extensionConfig.pkgManager = 'npm'; } extensionConfig.installDependencies = true; } } <file_sep>/generators/app/templates/ext-notebook-renderer/src/extension/sampleProvider.ts import * as vscode from 'vscode'; import { TextDecoder, TextEncoder } from "util"; /** * An ultra-minimal sample provider that lets the user type in JSON, and then * outputs JSON cells. */ interface RawNotebookData { cells: RawNotebookCell[] } interface RawNotebookCell { language: string; value: string; kind: vscode.NotebookCellKind; editable?: boolean; outputs: RawCellOutput[]; } interface RawCellOutput { mime: string; value: any; } export class SampleContentSerializer implements vscode.NotebookSerializer { public readonly label: string = 'My Sample Content Serializer'; /** * @inheritdoc */ public async deserializeNotebook(data: Uint8Array, token: vscode.CancellationToken): Promise<vscode.NotebookData> { var contents = new TextDecoder().decode(data); // convert to String to make JSON object // Read file contents let raw: RawNotebookData; try { raw = <RawNotebookData>JSON.parse(contents); } catch { raw = { cells: [] }; } // Create array of Notebook cells for the VS Code API from file contents const cells = raw.cells.map(item => new vscode.NotebookCellData( item.kind, item.value, item.language, item.outputs ? [new vscode.NotebookCellOutput(item.outputs.map(raw => new vscode.NotebookCellOutputItem(raw.mime, raw.value)))] : [], new vscode.NotebookCellMetadata() )); // Pass read and formatted Notebook Data to VS Code to display Notebook with saved cells return new vscode.NotebookData( cells, new vscode.NotebookDocumentMetadata() ); } /** * @inheritdoc */ public async serializeNotebook(data: vscode.NotebookData, token: vscode.CancellationToken): Promise<Uint8Array> { // function to take output renderer data to a format to save to the file function asRawOutput(cell: vscode.NotebookCellData): RawCellOutput[] { let result: RawCellOutput[] = []; for (let output of cell.outputs ?? []) { for (let item of output.outputs) { result.push({ mime: item.mime, value: item.value }); } } return result; } // Map the Notebook data into the format we want to save the Notebook data as let contents: RawNotebookData = { cells: []}; for (const cell of data.cells) { contents.cells.push({ kind: cell.kind, language: cell.languageId, value: cell.value, outputs: asRawOutput(cell) }); } // Give a string of all the data to save and VS Code will handle the rest return new TextEncoder().encode(JSON.stringify(contents)); } } export class SampleKernel { readonly id = 'test-notebook-renderer-kernel'; public readonly label = 'Sample Notebook Kernel'; readonly supportedLanguages = ['json']; private _executionOrder = 0; private readonly _controller: vscode.NotebookController; constructor() { this._controller = vscode.notebook.createNotebookController(this.id, 'test-notebook-renderer', this.label); this._controller.supportedLanguages = this.supportedLanguages; this._controller.hasExecutionOrder = true; this._controller.executeHandler = this._executeAll.bind(this); } dispose(): void { this._controller.dispose(); } private _executeAll(cells: vscode.NotebookCell[], _notebook: vscode.NotebookDocument, _controller: vscode.NotebookController): void { for (let cell of cells) { this._doExecution(cell); } } private async _doExecution(cell: vscode.NotebookCell): Promise<void> { const execution = this._controller.createNotebookCellExecutionTask(cell); execution.executionOrder = ++this._executionOrder; execution.start({ startTime: Date.now() }); const metadata = { startTime: Date.now() }; try { execution.replaceOutput([new vscode.NotebookCellOutput([ new vscode.NotebookCellOutputItem('application/json', JSON.parse(cell.document.getText())), ], metadata)]); execution.end({ success: true }); } catch (err) { execution.replaceOutput([new vscode.NotebookCellOutput([ new vscode.NotebookCellOutputItem('application/x.notebook.error-traceback', { ename: err instanceof Error && err.name || 'error', evalue: err instanceof Error && err.message || JSON.stringify(err, undefined, 4), traceback: [] }) ])]); execution.end({ success: false }); } } }
8440958ed1245a7cdcb2be9a7d83b2e3bb32889a
[ "JavaScript", "TypeScript" ]
3
JavaScript
SiddharthShyniben/vscode-generator-code
89332ca77bde2732468d6389edaf570c4a24fbd3
2b09d62d5ba58d5933e9e33388367c5df4a88984
refs/heads/master
<repo_name>cbedoy/Corona-Tracker<file_sep>/app/src/main/java/iambedoy/coronatracker/ServiceApi.kt package iambedoy.coronatracker import com.haroldadmin.cnradapter.NetworkResponse import iambedoy.coronatracker.dto.* import retrofit2.http.GET import retrofit2.http.Query /** * Corona Tracker * * Created by bedoy on 19/05/20. */ interface ServiceApi { @GET("/v2/countries") suspend fun getCountries(): NetworkResponse<List<Country>, Void> @GET("/v2/states") suspend fun getStates(): NetworkResponse<List<State>, Void> @GET("/v3/covid-19/jhucsse") suspend fun getJHUCountryState(): NetworkResponse<List<JHUCountryState>, Void> @GET("/v2/all") suspend fun getAll(): NetworkResponse<Global, String> @GET("/v3/covid-19/historical/all") suspend fun getHistorical(@Query("lastdays") lastDays: Int = 30) : NetworkResponse<Historical, Void> }<file_sep>/app/src/main/java/iambedoy/coronatracker/fragment/CountryDetailFragment.kt package iambedoy.coronatracker.fragment import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import iambedoy.coronatracker.R import iambedoy.coronatracker.fragment.CountryDetailFragment.ChartType.* import iambedoy.coronatracker.viewmodel.CountryDetailViewModel import kotlinx.android.synthetic.main.details_view.* import kotlinx.android.synthetic.main.fragment_country_detail.* import org.koin.android.ext.android.inject /** * Corona Tracker * * Created by bedoy on 25/03/20. */ class CountryDetailFragment : Fragment(){ private val viewModel by inject<CountryDetailViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_country_detail, container, false) } enum class ChartType{ Deaths, Recovered, Cases } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) details_container.visibility = View.VISIBLE chart_deaths.setNoDataText("Loading") chart_recovered.setNoDataText("Loading") chart_cases.setNoDataText("Loading") viewModel.historical.observe(viewLifecycleOwner, Observer { historical -> fillChart(historical.deaths, chart_deaths, Deaths) fillChart(historical.recovered, chart_recovered, Recovered) fillChart(historical.cases, chart_cases, Cases) }) viewModel.global.observe(viewLifecycleOwner, Observer { global -> details_container.visibility = View.VISIBLE cases_count_view.text = "${global.cases}" today_cases_count_view.text = "${global.todayCases}" deaths_count_view.text = "${global.deaths}" today_deaths_count_view.text = "${global.todayDeaths}" recovered_count_view.text = "${global.recovered}" active_count_view.text = "${global.active}" critical_count_view.text = "${global.critical}" }) } private fun fillChart(map: Map<String, Long>, chart: LineChart, type: ChartType) { val dataSource = map.entries.mapIndexed { index, entry -> Entry(index.toFloat(), entry.value.toFloat()) } val textColor = when(type){ Deaths -> ContextCompat.getColor(requireContext(), R.color.total_deaths_color) Recovered -> ContextCompat.getColor(requireContext(), R.color.recovered_color) Cases -> ContextCompat.getColor(requireContext(), R.color.total_cases_color) } val dataSet = LineDataSet(dataSource, type.toString()).apply { lineWidth = 0F circleRadius = 1F circleHoleRadius = 1f color = textColor circleColors = listOf(textColor) setDrawValues(false) } chart.xAxis.isEnabled = false chart.axisLeft.isEnabled = false chart.axisRight.isEnabled = false chart.legend.textSize = 18F chart.legend.textColor = textColor chart.setDrawBorders(false) //chart.setDrawGridBackground(false) chart.data = LineData(dataSet) chart.animateXY(1500, 1500) chart.notifyDataSetChanged() chart.invalidate() } }<file_sep>/README.MD # Corona-Tracker [![Build Status](https://travis-ci.com/cbedoy/Corona-Tracker.svg?branch=master)](https://travis-ci.com/cbedoy/Corona-Tracker) Inspired by: https://github.com/ahmadawais/corona-cli Track Corona Virus COVID19 cases with this Andriod Application. # How it looks <img width="240" alt="" src="https://github.com/cbedoy/Corona-Tracker/blob/master/demov2.png?raw=true"> # Android App - [<NAME>](https://www.linkedin.com/in/carlos-bedoy-34248187/) | Android Engineer # API - [NovelCOVID](https://github.com/NovelCOVID/API) | API ### Sources <ol> <li id="ref-1"> <a href="https://www.who.int/emergencies/diseases/novel-coronavirus-2019/situation-reports/" >Novel Coronavirus (2019-nCoV) situation reports</a > - <a href="https://www.who.int/">World Health Organization</a> (WHO) </li> <li id="ref-2"> <a href="https://www.cdc.gov/coronavirus/2019-ncov/cases-in-us.html" >2019 Novel Coronavirus (2019-nCoV) in the U.S.</a > -. <a href="https://www.cdc.gov/">U.S. Centers for Disease Control and Prevention</a> (CDC) </li> <li id="ref-3"> <a href="http://www.nhc.gov.cn/xcs/yqtb/list_gzbd.shtml">Outbreak Notification</a> - National Health Commission (NHC) of the People’s Republic of China </li> <li id="ref-4"> <a href="https://www.health.gov.au/health-topics/novel-coronavirus-2019-ncov">Novel coronavirus (2019-nCoV)</a> - Australian Government Department of Health </li> <li id="ref-5"> <a href="https://www.medrxiv.org/content/10.1101/2020.01.23.20018549v2" >Novel coronavirus 2019-nCoV: early estimation of epidemiological parameters and epidemic prediction</a > - <NAME>. Read et al, Jan. 23,2020. </li> <li id="ref-6"> <a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3524675" >Early Transmissibility Assessment of a Novel Coronavirus in Wuhan, China</a > - <NAME> and <NAME>, Harvard University - Computational Health Informatics Program - Posted: 24 Jan 2020 Last revised: 27 Jan 2020 </li> <li id="ref-7"> <a href="https://www.imperial.ac.uk/mrc-global-infectious-disease-analysis/news--wuhan-coronavirus/" >Report 3: Transmissibility of 2019-nCoV</a > - 25 January 2020 - Imperial College London‌ </li> <li id="ref-8"> <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3809029/" >Case fatality risk of influenza A(H1N1pdm09): a systematic review</a > - Epidemiology. Nov. 24, 2013 </li> <li id="ref-9"> <a href="https://www.thelancet.com/journals/lancet/article/PIIS0140-6736(20)30185-9/fulltext#tbl1" >A novel coronavirus outbreak of global health concern</a > - <NAME> et al. The Lancet. January 24, 2020 </li> <li id="ref-10"> <a href="https://www.cdc.gov/coronavirus/2019-ncov/about/symptoms.html" >Symptoms of Novel Coronavirus (2019-nCoV)</a > - CDC </li> <li id="ref-11"> <a href="https://www.aljazeera.com/news/2020/01/chinas-national-health-commission-news-conference-coronavirus-200126105935024.html" >China's National Health Commission news conference on coronavirus</a > - Al Jazeera. January 26, 2020 </li> <li id="ref-12"> <a href="https://www.reuters.com/article/us-china-health-who/wuhan-lockdown-unprecedented-shows-commitment-to-contain-virus-who-representative-in-china-idUSKBN1ZM1G9" >Wuhan lockdown 'unprecedented', shows commitment to contain virus: WHO representative in China</a > - Reuters. January 23, 2020 </li> <li id="ref-13"> <a href="https://www.who.int/news-room/detail/23-01-2020-statement-on-the-meeting-of-the-international-health-regulations-(2005)-emergency-committee-regarding-the-outbreak-of-novel-coronavirus-(2019-ncov)" >Statement on the meeting of the International Health Regulations (2005) Emergency Committee regarding the outbreak of novel coronavirus (2019-nCoV)</a > - WHO, January 23, 2020 </li> <li id="ref-14"> <a href="https://www.who.int/news-room/events/detail/2020/01/30/default-calendar/international-health-regulations-emergency-committee-on-novel-coronavirus-in-china" >International Health Regulations Emergency Committee on novel coronavirus in China</a > - WHO, January 30, 2020 </li> <li id="ref-15"> <a href="https://www.theonlinecitizen.com/2020/01/29/human-to-human-transmission-of-wuhan-virus-outside-of-china-confirmed-in-germany-japan-and-vietnam/" >Human-to-human transmission of Wuhan virus outside of China, confirmed in Germany, Japan and Vietnam</a > - The Online Citizen, Jan. 29, 2020 </li> <li id="ref-16"> <a href="https://www.pscp.tv/WHO/1OdJrqEvgaeGX">Who: "Live from Geneva on the new #coronavirus outbreak"</a> </li> <li id="ref-17"> <a href="https://www.cdc.gov/media/releases/2020/p0130-coronavirus-spread.html" >CDC Confirms Person-to-Person Spread of New Coronavirus in the United States</a > - CDC Press Release, Jan. 30, 2020 </li> <li id="ref-18"> <a href="https://www.gov.uk/government/news/cmo-confirms-cases-of-coronavirus-in-england" >CMO confirms cases of coronavirus in England</a > - CMO, UK, Jan. 31, 2020 </li> <li id="ref-19"> <a href="https://www.thelocal.fr/20200131/coronavirus-in-france-what-you-need-to-know" >Coronavirus in France: what you need to know</a > - The Local France, Jan. 31, 2020 </li> <li id="ref-20"> <a href="https://tass.com/society/1115101">First two persons infected with coronavirus identified in Russia</a> - Tass, Jan. 31, 2020 </li> <li id="ref-21"> <a href="https://onlinelibrary.wiley.com/doi/abs/10.1002/jmv.25689?af=R" >Updated understanding of the outbreak of 2019 novel coronavirus (2019nCoV) in Wuhan, China</a > - Journal of Medical Virology, Jan. 29, 2020 </li> <li id="ref-22"> <a href="https://www.medrxiv.org/content/10.1101/2020.01.27.20018952v1.full.pdf" >Estimating the effective reproduction number of the 2019-nCoV in China</a > - Zhidong Cao et al., Jan. 29, 2020 </li> <li id="ref-23"> <a href="https://www.sciencedirect.com/science/article/pii/S1201971220300539" >Preliminary estimation of the basic reproduction number of novel coronavirus (2019-nCoV) in China, from 2019 to 2020: A data-driven analysis in the early phase of the outbreak</a > - Jan. 30, 2020 </li> <li id="ref-24"> <a href="https://www.bbc.com/news/world-asia-china-51368873" >Coronavirus: Window of opportunity to act, World Health Organization says</a > - BBC, Feb,\. 4, 2020 </li> <li id="ref-25"> <a href="https://jamanetwork.com/journals/jama/fullarticle/2761044?guestAccessKey=<KEY>" >Clinical Characteristics of 138 Hospitalized Patients With 2019 Novel Coronavirus–Infected Pneumonia in Wuhan, China</a > - Wang et. al, JAMA, Feb. 7, 2020 </li> <li id="ref-26"> NovelCOVID API based on top of <a href="https://www.worldometers.info/coronavirus/">WorldMeter</a> </li> </li> <li id="ref-27"> Insipired by <a href="https://github.com/ahmadawais/corona-cli">Corona-cli</a> </li> </ol> <br> <file_sep>/app/src/main/java/iambedoy/coronatracker/viewmodel/CountryDetailViewModel.kt package iambedoy.coronatracker.viewmodel import androidx.lifecycle.ViewModel import iambedoy.coronatracker.repository.CoronaRepository class CountryDetailViewModel ( private val repository: CoronaRepository ): ViewModel(){ val historical = repository.requestAllHistorical() val global = repository.requestGlobal2() }<file_sep>/app/src/main/java/iambedoy/coronatracker/repository/CoronaRepository.kt package iambedoy.coronatracker.repository import androidx.lifecycle.LiveData import androidx.lifecycle.liveData import com.haroldadmin.cnradapter.NetworkResponse import iambedoy.coronatracker.Filter import iambedoy.coronatracker.Filter.* import iambedoy.coronatracker.ServiceApi import iambedoy.coronatracker.dto.Country import iambedoy.coronatracker.dto.Global import iambedoy.coronatracker.dto.Historical import iambedoy.coronatracker.dto.JHUCountryState import iambedoy.repository /** * Corona Tracker * * Created by bedoy on 22/03/20. */ class CoronaRepository(private val serviceApi: ServiceApi) { suspend fun requestGlobal(): Global?{ return when(val response = serviceApi.getAll()){ is NetworkResponse.Success -> response.body is NetworkResponse.NetworkError -> { response.error.printStackTrace() return null } is NetworkResponse.ServerError -> { response.toString() return null } is NetworkResponse.UnknownError -> { response.error.printStackTrace() return null } } } fun requestGlobal2() : LiveData<Global>{ return liveData { when(val response = serviceApi.getAll()){ is NetworkResponse.Success -> { emit(response.body) } } } } suspend fun requestCountries(filter: Filter = cases): List<Country> { return when(val response = serviceApi.getCountries()){ is NetworkResponse.Success -> { return response.body.sortedBy { when (filter) { cases -> { return@sortedBy it.cases } todayCases -> { return@sortedBy it.todayCases } deaths -> { return@sortedBy it.deaths } todayDeaths -> { return@sortedBy it.todayDeaths } recovered -> { return@sortedBy it.recovered } else -> return@sortedBy it.cases } }.reversed() } else -> emptyList() } } suspend fun requestJHUData(): Map<String, MutableList<JHUCountryState>> { val mapOf = sortedMapOf<String, MutableList<JHUCountryState>>() return when(val response = serviceApi.getJHUCountryState()){ is NetworkResponse.Success -> { response.body.forEach { val country = it.country ?: "" if (!mapOf.containsKey(country)){ val states = mutableListOf<JHUCountryState>() states.add(it) mapOf[country] = states }else{ mapOf[country]?.let { list -> list.add(it) mapOf.remove(country) mapOf[country] = list.sortedByDescending { item -> item.stats.confirmed }.toMutableList() } } } mapOf } else -> { emptyMap() } } } suspend fun requestJHUDataWithCountry(country: String = "Mexico"): Map<String, MutableList<JHUCountryState>> { return requestJHUData().toMutableMap().apply { val get = get(country) clear() set(country, get?: mutableListOf()) } } fun requestAllHistorical(): LiveData<Historical> { return liveData { when(val response = serviceApi.getHistorical(360)){ is NetworkResponse.Success -> { emit(response.body) } } } } }<file_sep>/app/src/main/java/iambedoy/coronatracker/dto/CountryInfo.kt package iambedoy.coronatracker.dto import com.squareup.moshi.Json /** * Corona Tracker * * Created by bedoy on 19/05/20. */ data class CountryInfo( @field:Json(name = "_id") val id: Long? = null, @field:Json(name = "iso2") val iso2: String? = null, @field:Json(name = "iso3") val iso3: String? = null, @field:Json(name = "lat") val lat: Double? = null, @field:Json(name = "long") val long: Double? = null, @field:Json(name = "flag") val flag: String? = null )<file_sep>/app/src/main/java/iambedoy/coronatracker/fragment/countries/CountryListFragment.kt package iambedoy.coronatracker.fragment.countries import android.os.Bundle import android.text.SpannableString import android.text.method.LinkMovementMethod import android.text.util.Linkify import android.view.* import android.widget.SearchView import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.xwray.groupie.GroupAdapter import com.xwray.groupie.kotlinandroidextensions.GroupieViewHolder import iambedoy.coronatracker.Filter import iambedoy.coronatracker.R import iambedoy.coronatracker.viewmodel.CoronaViewModel import iambedoy.px import kotlinx.android.synthetic.main.fragment_corona.* import org.koin.android.ext.android.inject /** * Corona Tracker * * Created by bedoy on 22/03/20. */ class CountryListFragment : Fragment(){ private val viewModel by inject<CoronaViewModel>() private val adapter = GroupAdapter<GroupieViewHolder>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.fragment_corona, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) common_recycler_view.layoutManager = LinearLayoutManager(context) common_recycler_view.adapter = adapter common_progress_bar.visibility = View.VISIBLE viewModel.items.observe(viewLifecycleOwner, Observer { items -> adapter.addAll(items) common_progress_bar.visibility = View.GONE }) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.main_menu, menu) (menu.findItem(R.id.action_search)?.actionView as? SearchView)?.apply { setOnQueryTextListener(object : SearchView.OnQueryTextListener{ override fun onQueryTextSubmit(query: String?): Boolean { onQuery(query) return true } override fun onQueryTextChange(query: String?): Boolean { onQuery(query) return true } }) } super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when(item.itemId){ R.id.action_info -> { activity?.let { AlertDialog.Builder(it).setView(messageText).show() } } R.id.action_filter_by_cases -> sortBy(Filter.cases) R.id.action_filter_by_deaths -> sortBy(Filter.deaths) R.id.action_filter_by_recovered -> sortBy(Filter.recovered) R.id.action_filter_by_today_cases -> sortBy(Filter.todayCases) R.id.action_filter_by_today_deaths -> sortBy(Filter.todayDeaths) } return super.onOptionsItemSelected(item) } override fun onResume() { super.onResume() viewModel.loadCountryList() } private fun sortBy(filter: Filter) { viewModel.loadCountryList(filter) } private fun onQuery(query: String?) { viewModel.filterCoronaListWithQuery(query = query?:"") } private val messageText by lazy { val textView = TextView(context) val spannableString = SpannableString( "- <NAME> | Android Engineer \n\n " + "https://www.linkedin.com/in/carlos-bedoy-34248187\n" + "http://cbedoy.github.io\n\n" + "Line by line, code by code, logic and syntax, my dream explodes." ) Linkify.addLinks(spannableString, Linkify.WEB_URLS); textView.text = spannableString textView.setPadding(16.px,16.px,16.px,16.px) context?.let { textView.setTextColor(ContextCompat.getColor(it, R.color.black_primary)) } textView.movementMethod = LinkMovementMethod.getInstance() textView } }<file_sep>/app/src/main/java/iambedoy/module.kt package iambedoy import com.haroldadmin.cnradapter.NetworkResponseAdapterFactory import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import iambedoy.coronatracker.ServiceApi import iambedoy.coronatracker.fragment.CountryDetailFragment import iambedoy.coronatracker.fragment.countries.CountryListFragment import iambedoy.coronatracker.fragment.CountryFragment import iambedoy.coronatracker.fragment.JHUListFragment import iambedoy.coronatracker.repository.CoronaRepository import iambedoy.coronatracker.viewmodel.CoronaViewModel import iambedoy.coronatracker.viewmodel.CountryDetailViewModel import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory /** * Corona Tracker * * Created by bedoy on 13/05/20. */ private val moshi = Moshi.Builder() //.add(XNullableAdapterFactory()) .add(KotlinJsonAdapterFactory()) //.add(TypesAdapterFactory()) .build() val retrofit: Retrofit = Retrofit.Builder() .baseUrl("https://disease.sh") .addCallAdapterFactory(NetworkResponseAdapterFactory()) .addConverterFactory(MoshiConverterFactory.create(moshi)) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() val repository = module { single { CoronaRepository(get()) } } val viewModel = module { factory { CoronaViewModel(get()) } factory { CountryDetailViewModel(get()) } } val service = module { single { retrofit.create(ServiceApi::class.java) } } val fragments = module { factory { CountryListFragment() } factory { JHUListFragment() } factory { CountryFragment() } factory { CountryDetailFragment() } } val injections = listOf(repository, viewModel, service, fragments)<file_sep>/app/src/main/java/iambedoy/extensions.kt package iambedoy import android.content.res.Resources import android.graphics.drawable.Drawable import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.content.ContextCompat import iambedoy.coronatracker.R import iambedoy.coronatracker.dto.Country /** * Corona Tracker * * Created by bedoy on 29/05/20. */ fun TextView.setCollapseExpand(collapsibleView: View, onCollapse: () -> Unit, onExpand: () -> Unit) { setCompoundDrawablesWithIntrinsicBounds(null, null, createDrawable(R.drawable.ic_action_expand), null) setOnClickListener { when (collapsibleView.visibility) { View.GONE -> { collapsibleView.visibility = View.VISIBLE setCompoundDrawablesWithIntrinsicBounds(null, null, createDrawable(R.drawable.ic_action_collapse), null) onExpand() } View.VISIBLE -> { collapsibleView.visibility = View.GONE setCompoundDrawablesWithIntrinsicBounds(null, null, createDrawable(R.drawable.ic_action_expand), null) onCollapse() } } } } fun View.createDrawable(resourceId : Int): Drawable? { return ContextCompat.getDrawable(context, resourceId) } fun ViewGroup.inflate(layoutId: Int): View { return LayoutInflater.from(context).inflate(layoutId, this, false) } fun TextView.setTotalCasesColor() = setTextColor(ContextCompat.getColor(context, R.color.total_cases_color)) fun TextView.setDeathsColor() = setTextColor(ContextCompat.getColor(context, R.color.total_deaths_color)) fun TextView.setPrimaryTextColor() = setTextColor(ContextCompat.getColor(context, R.color.black_primary)) fun View.totalCasesColor() = ContextCompat.getColor(context, R.color.total_cases_color) fun View.deathsColor() = ContextCompat.getColor(context, R.color.total_deaths_color) fun View.primaryTextColor() = ContextCompat.getColor(context, android.R.color.white) fun View.secondaryTextColor() = ContextCompat.getColor(context, android.R.color.white) val Int.dp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt() val Int.px: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt() fun Country.formattedCountry(view: View): SpannableString { val localCases = "$cases" val localName : String = country?:"" val localDeaths = "$deaths" return SpannableString("$localCases $localName ($localDeaths)").apply { setSpan(ForegroundColorSpan(view.totalCasesColor()), 0, localCases.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) setSpan(ForegroundColorSpan(view.primaryTextColor()), indexOf(localName), indexOf(localName) + localName.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) setSpan(ForegroundColorSpan(view.deathsColor()), lastIndexOf(localDeaths), lastIndexOf(localDeaths) + localDeaths.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } }<file_sep>/app/src/main/java/iambedoy/coronatracker/dto/State.kt package iambedoy.coronatracker.dto /** * Corona Tracker * * Created by bedoy on 28/05/20. */ data class State( val updated: Double = 0.0, val state: String? = null, val cases: Int = 0, val todayCases: Int = 0, val deaths: Int = 0, val todayDeaths: Int = 0, val active: Int = 0, val critical: Int = 0, val casesPerOneMillion: Double = 0.0, val deathsPerOneMillion: Double = 0.0, val tests: Int = 0, val testsPerOneMillion: Double = 0.0 )<file_sep>/app/src/main/java/iambedoy/coronatracker/fragment/countries/items/Items.kt package iambedoy.coronatracker.fragment.countries.items import android.view.View import android.widget.TextView import coil.api.load import com.xwray.groupie.kotlinandroidextensions.GroupieViewHolder import com.xwray.groupie.kotlinandroidextensions.Item import iambedoy.coronatracker.R import iambedoy.coronatracker.dto.Country import iambedoy.coronatracker.dto.Global import iambedoy.formattedCountry import iambedoy.setCollapseExpand import kotlinx.android.synthetic.main.country_cell.* import kotlinx.android.synthetic.main.details_view.* class CountryItem(private val country: Country) : Item(){ override fun bind(viewHolder: GroupieViewHolder, position: Int) { viewHolder.country_name_view.text = country.formattedCountry(viewHolder.itemView) viewHolder.country_name_view.setCollapseExpand(viewHolder.details_container, { }, { }) viewHolder.country_flag_view.load(country.countryInfo?.flag){ crossfade(true) } viewHolder.cases_count_view.text = "${country.cases}" viewHolder.today_cases_count_view.text = "${country.todayCases}" viewHolder.deaths_count_view.text = "${country.deaths}" viewHolder.today_deaths_count_view.text = "${country.todayDeaths}" viewHolder.recovered_count_view.text = "${country.recovered}" viewHolder.active_count_view.text = "${country.active}" viewHolder.critical_count_view.text = "${country.critical}" } override fun getLayout(): Int { return R.layout.country_cell } } class GlobalItem(private val global: Global) : Item(){ override fun bind(viewHolder: GroupieViewHolder, position: Int) { viewHolder.details_container.visibility = View.VISIBLE viewHolder.cases_count_view.text = "${global.cases}" viewHolder.today_cases_count_view.text = "${global.todayCases}" viewHolder.deaths_count_view.text = "${global.deaths}" viewHolder.today_deaths_count_view.text = "${global.todayDeaths}" viewHolder.recovered_count_view.text = "${global.recovered}" viewHolder.active_count_view.text = "${global.active}" viewHolder.critical_count_view.text = "${global.critical}" } override fun getLayout(): Int { return R.layout.global_cell } }<file_sep>/app/src/main/java/iambedoy/coronatracker/dto/Historical.kt package iambedoy.coronatracker.dto data class Historical( val cases: Map<String, Long> = emptyMap(), val deaths: Map<String, Long> = emptyMap(), val recovered: Map<String, Long> = emptyMap() )<file_sep>/app/src/main/java/iambedoy/coronatracker/dto/Global.kt package iambedoy.coronatracker.dto /** * Corona Tracker * * Created by bedoy on 29/05/20. */ data class Global( val updated: Double = 0.0, val cases: Long = 0, val todayCases: Long = 0, val deaths: Long = 0, val todayDeaths: Long = 0, val recovered:Long = 0, val active: Long = 0, val critical: Long = 0, val casesPerOneMillion: Double = 0.0, val deathsPerOneMillion: Double = 0.0, val tests: Long = 0, val testsPerOneMillion: Double = 0.0, val population: Long = 0 )<file_sep>/app/src/main/java/iambedoy/coronatracker/dto/JHUCountryState.kt package iambedoy.coronatracker.dto /** * Corona Tracker * * Created by bedoy on 28/05/20. */ data class JHUCountryState( val country: String? = null, val updatedAt : String? = null, val stats : Stats = Stats(), val province : String? = null )<file_sep>/app/src/main/java/iambedoy/coronatracker/fragment/JHUListFragment.kt package iambedoy.coronatracker.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.xwray.groupie.GroupAdapter import com.xwray.groupie.kotlinandroidextensions.GroupieViewHolder import iambedoy.coronatracker.R import iambedoy.coronatracker.viewmodel.CoronaViewModel import kotlinx.android.synthetic.main.fragment_corona.* import org.koin.android.ext.android.inject /** * Corona Tracker * * Created by bedoy on 28/05/20. */ class JHUListFragment : Fragment(){ private val adapter = GroupAdapter<GroupieViewHolder>() private val viewModel by inject<CoronaViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { setHasOptionsMenu(true) return inflater.inflate(R.layout.fragment_corona, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val linearLayoutManager = LinearLayoutManager(context) common_progress_bar.visibility = View.VISIBLE common_recycler_view.adapter = adapter common_recycler_view.layoutManager = linearLayoutManager common_recycler_view.isNestedScrollingEnabled = false //viewModel.states.observe(viewLifecycleOwner, Observer { countries -> // adapter.setDataSource(countries) // common_progress_bar.visibility = View.GONE //}) } override fun onResume() { super.onResume() viewModel.loadJHUData() } }<file_sep>/app/src/main/java/iambedoy/coronatracker/MainActivity.kt package iambedoy.coronatracker import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import iambedoy.coronatracker.fragment.CountryDetailFragment import iambedoy.coronatracker.fragment.countries.CountryListFragment import iambedoy.coronatracker.fragment.CountryFragment import iambedoy.coronatracker.fragment.JHUListFragment import kotlinx.android.synthetic.main.activity_main.* import org.koin.android.ext.android.inject class MainActivity : AppCompatActivity() { private val fragment by inject<CountryListFragment>() private val jhuListFragment by inject<JHUListFragment>() private val countryFragment by inject<CountryFragment>() private val detailFragment by inject<CountryDetailFragment>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) bottom_navigation.setOnNavigationItemSelectedListener { when(it.itemId){ R.id.action_countries -> showFragment(fragment) R.id.action_states -> showFragment(detailFragment) R.id.action_mex -> showFragment(countryFragment) } true } bottom_navigation.selectedItemId = R.id.action_states } private fun showFragment(fragment: Fragment){ supportFragmentManager.beginTransaction().replace(R.id.layout_container, fragment).commit() } } <file_sep>/app/src/main/java/iambedoy/CoronaTrackerApplication.kt package iambedoy import android.app.Application import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin import org.koin.dsl.koinApplication /** * Corona Tracker * * Created by bedoy on 19/05/20. */ class CoronaTrackerApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@CoronaTrackerApplication) modules(injections) } } }<file_sep>/app/src/main/java/iambedoy/coronatracker/dto/Country.kt package iambedoy.coronatracker.dto /** * Corona Tracker * * Created by bedoy on 19/05/20. */ data class Country( val countryInfo: CountryInfo?= null, val updated: Double = 0.0, val country: String? = null, val cases: Int = 0, val todayCases: Int = 0, val deaths: Int = 0, val todayDeaths: Int = 0, val recovered:Int = 0, val active: Int = 0, val critical: Int = 0, val casesPerOneMillion: Double = 0.0, val deathsPerOneMillion: Double = 0.0, val tests: Int = 0, val testsPerOneMillion: Double = 0.0, val population: Int = 0, val continent: String = "" )<file_sep>/app/src/main/java/iambedoy/coronatracker/Filter.kt package iambedoy.coronatracker /** * Corona Tracker * * Created by bedoy on 13/05/20. */ enum class Filter{ cases, todayCases, deaths, todayDeaths, recovered, active, critical, casesPerOneMillion, deathsPerOneMillion }<file_sep>/app/src/main/java/iambedoy/coronatracker/dto/Stats.kt package iambedoy.coronatracker.dto /** * Corona Tracker * * Created by bedoy on 28/05/20. */ data class Stats ( val confirmed : Int = 0, val deaths : Int = 0, val recovered : Int = 0 )<file_sep>/app/src/main/java/iambedoy/coronatracker/adapter/jhu/Items.kt package iambedoy.coronatracker.adapter.jhu import android.text.Spannable import android.text.SpannableString import android.text.style.ForegroundColorSpan import android.view.View import com.xwray.groupie.kotlinandroidextensions.GroupieViewHolder import com.xwray.groupie.kotlinandroidextensions.Item import iambedoy.coronatracker.R import iambedoy.coronatracker.dto.JHUCountryState import iambedoy.deathsColor import iambedoy.secondaryTextColor import iambedoy.totalCasesColor import kotlinx.android.synthetic.main.jhu_country_state_header.* import kotlinx.android.synthetic.main.jhu_country_state_item.* /** * Corona Tracker * * Created by bedoy on 29/05/20. */ class TitleItem(private val countryName: String) : Item(){ override fun bind(viewHolder: GroupieViewHolder, position: Int) { viewHolder.jhu_country_name.text = countryName } override fun getLayout(): Int { return R.layout.jhu_country_state_header } } class StateItem(private val countryState: JHUCountryState) : Item(){ override fun bind(viewHolder: GroupieViewHolder, position: Int) { viewHolder.jhu_state_name.text = countryState.format(viewHolder.containerView) } override fun getLayout(): Int { return R.layout.jhu_country_state_item } private fun JHUCountryState.format(containerView: View): SpannableString { val localCases = "${stats.confirmed}" val localName : String = province?:"" val localDeaths = "${stats.deaths}" return SpannableString("$localCases $localName ($localDeaths)").apply { setSpan(ForegroundColorSpan(containerView.totalCasesColor()), 0, localCases.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) setSpan(ForegroundColorSpan(containerView.secondaryTextColor()), indexOf(localName), indexOf(localName) + localName.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) setSpan(ForegroundColorSpan(containerView.deathsColor()), indexOf(localDeaths), indexOf(localDeaths) + localDeaths.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } }<file_sep>/app/src/main/java/iambedoy/coronatracker/viewmodel/CoronaViewModel.kt package iambedoy.coronatracker.viewmodel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.xwray.groupie.kotlinandroidextensions.Item import iambedoy.coronatracker.Filter import iambedoy.coronatracker.adapter.jhu.StateItem import iambedoy.coronatracker.dto.Country import iambedoy.coronatracker.dto.Global import iambedoy.coronatracker.dto.JHUCountryState import iambedoy.coronatracker.fragment.countries.items.CountryItem import iambedoy.coronatracker.fragment.countries.items.GlobalItem import iambedoy.coronatracker.repository.CoronaRepository import kotlinx.coroutines.* /** * Corona Tracker * * Created by bedoy on 22/03/20. */ class CoronaViewModel(private val repository: CoronaRepository) : ViewModel() { private val _items = MutableLiveData<List<Item>> () val items: LiveData<List<Item>> get() = _items private val _states = MutableLiveData<List<StateItem>>() val states : LiveData<List<StateItem>> get() = _states private val _loadingState = MutableLiveData<Boolean>() var loadingState : LiveData<Boolean> = _loadingState private val networkScope = CoroutineScope(Job() + Dispatchers.IO) private var _targetCountry = "" private var _dataSource : List<Country> = emptyList() set(value) { field = value _loadingState.postValue(false) } private var _jhuDataSource : Map<String, MutableList<JHUCountryState>> = emptyMap() set(value) { field = value _states.postValue(field[_targetCountry]?.map { StateItem(it) }) _loadingState.postValue(false) } private var _searching = false fun loadJHUData() { networkScope.launch { _loadingState.postValue(true) repository.requestJHUData().let { _jhuDataSource = it } } } fun loadJHUDataWithCountry(country: String) { networkScope.launch { _loadingState.postValue(true) _targetCountry = country repository.requestJHUDataWithCountry(country).let { _jhuDataSource = it } } } fun loadCountryList(filter: Filter = Filter.cases){ networkScope.launch { _loadingState.postValue(true) val globalRequest = async { repository.requestGlobal() } val countriesRequest = async { repository.requestCountries(filter) } _dataSource = countriesRequest.await() val mutableListOf = mutableListOf<Item>() globalRequest.await()?.let { mutableListOf.add(GlobalItem(it)) } _dataSource.map { mutableListOf.add(CountryItem(it)) } _items.postValue(mutableListOf) } } fun filterCoronaListWithQuery(query: String) { _searching = query.length > 1 if (_searching ){ networkScope.launch (Dispatchers.Main){ val filteredCountries = _dataSource.filter { it.country?.contains(query, ignoreCase = true) == true } //_countries.postValue(filteredCountries) } }else{ //_countries.postValue(_dataSource) } } }<file_sep>/app/src/main/java/iambedoy/coronatracker/dto/Coordinates.kt package iambedoy.coronatracker.dto /** * Corona Tracker * * Created by bedoy on 28/05/20. */ data class Coordinates ( val latitude : Double = 0.0, val longitude : Double = 0.0 )
cc55b4611bceb865a22bef024f8ee8ca762f9de4
[ "Markdown", "Kotlin" ]
23
Kotlin
cbedoy/Corona-Tracker
0e916f64d8caf7c84ae02d0ca33cff4c82879508
b92ae03b5239550cf013fe9a05743b04dc8e78fe
refs/heads/master
<repo_name>ktalens/project-1_SpaceInvaders<file_sep>/readme.md # Space Invaders: ### App Demo: https://ktalens.github.io/project-1_SpaceInvaders/ --- ## Concept: The user plays as the spaceman, battling incoming hoardes of aliens by shooting them with his/her laser. The user wins when they defeat all the aliens in the given level before any alien reaches the bottom of the screen. Shooting an alien with the laser will stop the alien's advancement towards the bottom of the screen, but if any alien reaches the bottom, the user loses one out of their 3 lives. If the user loses, he/she can play on at the current level until they eexpend all their lives- otherwise the user must start from level 1 again. If the user wins, he/she is able to advance to the next level. There are 4 levels built in, each one has increasingly difficult alien size, speed, quantities, and increasing speed of the user's lasergun to let them keep up with the increasing difficulty of the aliens. ## Technologies Used: * HTML * CSS * JavaScript ## Approach: #### Overview This project uses canvas to animate the gameboard and utilize the left and right arrow keys to allow the user to navigate, and the spacebar to shoot the obstacles. The game logic is based on a user playing against the computer. The computer generates objects that start on the opposite end of the gameboard and advance towards the user's fixed position on other end of the gameboard. The user eliminates each of the computers objects when the object he/she projects an object that will collide with the computer's objects (which causes the computer's object to stop advancing at the point of collision), and defeats the computer when there are no computer objects advancing. In gameplay, this looks like the computer's objects disappear from the board, since collision will halt the object's movement and also sets the object's heigh and width to 0. The user loses against the computer if any of the computer's objects advance far enough to reach the same plane on the y-axis as the user. The computer's levels include increasing object speed to give the user less time, decreasing in size to give the user a smaller target, increasing in space between each object to add difficulty when the user is aiming, and (if I get this to work) increased volume of obstacles generated, by adding in multiple rows at specific intervals of the level. The function checkLose will detect if the user or computer has won the level, and will display a message on the gameboard that the user has either won and may proceed to the next level, or has lost and must try again. All gameplay elements are generated on the canvas by using the same object class of SpaceCreature to create the user's gamepiece, the computer's advancing objects, and the user's bullet. The images for each item are first set into the HTML and hidden with a display of "none", then drawn into the gameboard when the render() function is invoked for each item. The level and mission sections give the user a heads up on the difficulty of the current level, and the scoring was just another added feature that counts the number of collisons that occur during gameplay. Ideally, it would be set to increase by higher increments based on the difficulty of each level. The "Lives" indicator was a stretch goal that I initially didn't get to a functional state, but the idea was to allow the user to re-attempt a level if he/she was defeated by the computer without having to restart from the very first level each time. If the user exceeds 3 losses to the computer, the user has to start at the first level again. There's a starting screen that will display instructions upon loading the page, and requires the user to view the page and click "got it" before starting gameplay so that the user understands the gaming controls. There is also a pause screen that stops the gameplay and the movement of the computer's objects so that the user can get some releif without having to lose the game. #### Stretch goals * Having the user's live be more dynamic by basing it off of the accumulated score and taking a number of points away from the score each time an alien gets past the user would allow for more flexibility for the user to stay alive and for a longer, more competitive flow of gameplay. The progress could then just be measured by how many levels the user is able to reach, instead of requiring 100% of the aliens to be killed each round. * Having levels auto-generate increasing difficulty using set increments rather than having level values hard-coded into the game * Adding sound-effects of the laser-shooting events, the collisions, and other little events would make it a lot more fun. ## Challenges: * The major challenges were figuring out the separation of the functions inside constantly refreshing game-loop, because some pieces would replicate unintentionally, and which functions needed to stay inside and regenerate on each frame. Examples of this are having the score increase by too high of an amount if the function that counted score were kept inside the game-loop. * Another challenge was figuring out the timer of when each new row of aliens would generate. * One other big challenge was working out the flow of the level progression, and being able to factor in the amount of lives left, giving the user 2nd or 3rd chances to beat a level (if there are lives left) without having to replay all the previous levels again, and getting the running tally of aliens kills required to reset each time a new level is presented so that win & lose logic would work correctly instead of counting an accumulation of all the past level-wins or level-deaths. <!-- explanations of the technologies used, the approach taken, installation instructions, unsolved problems, etc. --> <file_sep>/app.js var galaxy = document.getElementById("galaxy"); var ctx = galaxy.getContext("2d"); let gameHeight= getComputedStyle(galaxy)['height']; let gameWidth= getComputedStyle(galaxy)['width']; galaxy.setAttribute('height', gameHeight); galaxy.setAttribute('width', gameWidth); //CREATE SPACEGUYS var spaceCowboy; var cowboyImage =document.getElementById('cowboy-2'); var laserGun = []; let laserImage = document.getElementById('laser'); var hoardeOfAlienBugs = []; var deadAliens = []; var currentLevel = 0; var score = 0; var lives =3 var thisMany; var levels = [ { level: 'ONE', bugWidth: 80, bugSideMargin: 20, bugTopMargin: 10, bugHeight: 80, bugImage : document.getElementById('awkward-alien'), bugSpeed: 1, laserSpeed: 10, levelWin: false, rounds: 1, roundDelay: 4000 }, { level: 'TWO', bugWidth: 60, bugSideMargin: 80, bugTopMargin: 10, bugHeight: 60, bugImage : document.getElementById('pink-alien'), bugSpeed: 2, laserSpeed: 15, levelWin: false, rounds: 2, roundDelay: 3000 }, { level: 'THREE', bugWidth: 45, bugSideMargin: 50, bugTopMargin: 50, bugHeight: 50, bugImage : document.getElementById('green-alien'), bugSpeed: 2, laserSpeed: 30, levelWin: false, rounds: 4, roundDelay: 2000 }, { level: 'FOUR', bugWidth: 40, bugSideMargin: 100, bugTopMargin: 10, bugHeight: 30, bugImage : document.getElementById('ufo'), bugSpeed: 5, laserSpeed: 50, levelWin: false, rounds: 5, roundDelay: 1000 } ]; function SpaceCreatures(img,x,y,width,height) { this.img= img this.x = x this.y=y this.width = width this.height= height this.alive = true this.render = function () { ctx.drawImage(this.img, this.x, this.y, this.width, this.height) } }; function makeHoarde (howMany,level) { for (let i=0;i<howMany; i++) { let width = levels[level].bugWidth; let height = levels[level].bugHeight; let margin = levels[level].bugSideMargin; let img = levels[level].bugImage; let startingXpos = margin+((width+margin)*i) let startingYpos= levels[level].bugTopMargin; var alienBug = new SpaceCreatures(img, startingXpos, startingYpos, width, height); hoardeOfAlienBugs.push(alienBug) } }; const chargeOnward =() => { let speed=levels[currentLevel].bugSpeed; ctx.clearRect(0,0,galaxy.width,galaxy.height); for (i=0;i<hoardeOfAlienBugs.length; i++){ hoardeOfAlienBugs[i].render(); if (hoardeOfAlienBugs[i].alive === true && hoardeOfAlienBugs[i].y<=parseInt(gameHeight)) { hoardeOfAlienBugs[i].y +=speed; } } }; function moonWalk(e) { let stepSize= 50; let boundary = parseInt(gameWidth) if (e.keyCode === 39) { if(spaceCowboy.x+stepSize < boundary) { //MOVE RIGHT one step size if x + stepSize is less than gameWidth spaceCowboy.x += stepSize } else if (spaceCowboy.x+stepSize >= boundary && (spaceCowboy.x+spaceCowboy.width) <= boundary) { //MOVE RIGHT for the remaining size if x + stepSize is more than gameWidth but x is still inside gameWidth spaceCowboy.x += boundary-(spaceCowboy.x+spaceCowboy.width) } } else if (e.keyCode === 37) { if(spaceCowboy.x-stepSize>=0){ //MOVE LEFT one stepSize if x - stepSize > 0 spaceCowboy.x -= stepSize } else if (spaceCowboy.x-stepSize <0 && (spaceCowboy.x >= 0)) { //MOVE LEFT for the remaining size if x - stepSize will be negative but x is still greater than or equal to 0 spaceCowboy.x -= spaceCowboy.x } } }; function pewpew (e) { e.preventDefault(); switch (e.keyCode) { case (32): var plasmaBeam= new SpaceCreatures(laserImage,spaceCowboy.x+15,spaceCowboy.y-30,20,50); laserGun.push(plasmaBeam); } }; const plasmaBeamSpeed = () => { let beamSpeed = levels[currentLevel].laserSpeed for (i=0;i<laserGun.length;i++) { laserGun[i].render(); laserGun[i].y -= beamSpeed; if (laserGun[i].y <0) { laserGun.shift(); } } }; function detectHit () { if (laserGun.length > 0) { for (i=0; i<laserGun.length; i++) { if (laserGun[i].width > 0){ for (j=0; j<hoardeOfAlienBugs.length; j++) { if (laserGun[i].y <= hoardeOfAlienBugs[j].y+hoardeOfAlienBugs[j].height && laserGun[i].y >= hoardeOfAlienBugs[j].y && laserGun[i].x+5 >= hoardeOfAlienBugs[j].x && laserGun[i].x <= hoardeOfAlienBugs[j].x+hoardeOfAlienBugs[j].width) { hoardeOfAlienBugs[j].alive=false; hoardeOfAlienBugs[j].width = 0; hoardeOfAlienBugs[j].height=0; laserGun[i].height=0; laserGun[i].width=0; } } } } } }; const countDead =() => { for (i=0; i<hoardeOfAlienBugs.length; i++) { if (hoardeOfAlienBugs[i].alive === false) { while (deadAliens.includes(i)==false) { deadAliens.push(i); score ++ } } } return }; const checkLose = () => { for (i=0; i<hoardeOfAlienBugs.length; i++) { if (hoardeOfAlienBugs.length > 0 && deadAliens.length === hoardeOfAlienBugs.length) { ctx.strokeStyle = 'rgb(0, 238, 242)'; ctx.lineWidth = 3; ctx.strokeText('VICTORY! PROCEED TO NEXT LEVEL',parseInt(gameWidth)/10,parseInt(gameHeight)/2); ctx.font = '300% Verdana'; levels[currentLevel].levelWin = true; levelUp.style.opacity = 1; levelUp.disabled = false; } else if (hoardeOfAlienBugs.length > 0 && hoardeOfAlienBugs[i].y+hoardeOfAlienBugs[i].height >= parseInt(gameHeight)) { spaceCowboy.alive = false; ctx.strokeStyle = 'rgb(223, 32, 67)'; ctx.lineWidth = 3; ctx.strokeText('MISSION FAILED! TRY AGAIN :(',parseInt(gameWidth)/6,parseInt(gameHeight)/2); ctx.font = '300% Verdana'; levelUp.style.display='none'; start.innerText= 'TRY AGAIN'; start.style.display = 'inline'; } } }; // What needs to happen at every frame? //1.display score(number of aliens destroyed) //2. has the win condition been met? //3. has the lose condition been met? //4.render the remaining aliens down left or right one increment from the last position //5. display how many aliens have been eliminated in the running scoreboard //6.render hero //7.has a bullet been deployed (spacebar key:32) ? if yes, 7b.render hero bullet 7c. check collison function gameLoop(){ ctx.clearRect(0,0,galaxy.width,galaxy.height); chargeOnward(); plasmaBeamSpeed(); spaceCowboy.render(); level.textContent = levels[currentLevel].level; document.getElementById('lives').innerText = lives;//.length; detectHit(); document.getElementById('score').innerText = score; countDead(); checkLose(); document.getElementById('status').innerText = `Destroy the incoming hoarde of ${thisMany*levels[currentLevel].rounds} aliens`; if (lives === 0) { start.disabled = true; start.style.opacity = .4 } }; document.addEventListener('DOMContentLoaded', function() { spaceCowboy= new SpaceCreatures(cowboyImage, parseInt(gameWidth)/2,parseInt(gameHeight)-70,60,60); thisMany= Math.floor(parseInt(gameWidth)/(levels[currentLevel].bugWidth+levels[currentLevel].bugSideMargin)) document.addEventListener('keydown',moonWalk); document.addEventListener('keydown',pewpew); //SETTING A TIMER FOR 60 FRAMES PER SECOND var runGame = setInterval(gameLoop, 60); gotIt.addEventListener('click', function () { startScreen.style.display = 'none' }); start.addEventListener('click',function () { if (lives >= 0) { spaceCowboy.alive = true; hoardeOfAlienBugs.splice(score,(thisMany*levels[currentLevel].rounds)); makeHoarde(thisMany,currentLevel); start.style.display = 'none'; levelUp.style.display = 'inline'; levelUp.disabled = true; lives -= 1 } else if (lives = 0) { start.disabled = true } }); levelUp.addEventListener('click', function () { if (currentLevel<= 2) { currentLevel+=1; } thisMany= Math.floor(parseInt(gameWidth)/(levels[currentLevel].bugWidth+levels[currentLevel].bugSideMargin)); var hoardesOnHoardes = setInterval( function () { makeHoarde(thisMany,currentLevel); },levels[currentLevel].roundDelay); setTimeout( function() { clearInterval(hoardesOnHoardes) }, levels[currentLevel].roundDelay*levels[currentLevel].rounds ); levelUp.disabled = true; levelUp.style.opacity = .4; }); pause.addEventListener('click',function () { clearInterval(runGame); pauseScreen.style.display = "inline-flex"; } ); resume.addEventListener('click',function () { pauseScreen.style.display = "none"; runGame = setInterval(gameLoop, 60)}) } );
cb6368b767a9f3cfc805fd499493fba1696a9aec
[ "Markdown", "JavaScript" ]
2
Markdown
ktalens/project-1_SpaceInvaders
59969914277038b02c2693b4503391d3760fc9e7
e98704c2fea958e713f8e5146a01f975dd183463
refs/heads/master
<repo_name>shariff6/HAIR_SALON<file_sep>/src/main/java/Stylist.java import org.sql2o.*; import java.util.List; public class Stylist { private String name; private int age; private String idNumber; private String phoneNumber; private String email; private int clientCount; private int id; public Stylist(String name, int age, String idNumber, String phoneNumber, String email, int clientCount) { this.name = name; this.age = age; this.idNumber = idNumber; this.phoneNumber = phoneNumber; this.email = email; this.clientCount = clientCount; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setIdNumber(String idNumber) { this.idNumber = idNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public void setEmail(String email) { this.email = email; } public void setClientCount(int clientCount) { this.clientCount = clientCount; } public void setId(int id) { this.id = id; } public String getName() { return name; } public int getAge() { return age; } public String getIdNumber() { return idNumber; } public String getPhoneNumber() { return phoneNumber; } public String getEmail() { return email; } public int getClientCount() { return clientCount; } public int getId() { return id; } public static List<Stylist> all() { String sql = "SELECT id, name FROM stylists"; try(Connection con = DB.sql2o.open()) { return con.createQuery(sql).executeAndFetch(Stylist.class); } } @Override public boolean equals(Object otherStylist) { if (!(otherStylist instanceof Stylist)) { return false; } else { Stylist newStylist = (Stylist) otherStylist; return this.getName().equals(newStylist.getName()) && this.getId() == newStylist.getId(); } } public void save() { try(Connection con = DB.sql2o.open()) { String sql = "INSERT INTO stylists(name, age, idNumber, phoneNumber, email, clientCount) VALUES (:name, :age, :idNumber, :phoneNumber, :email, :clientCount)"; this.id = (int) con.createQuery(sql, true) .addParameter("name", this.name) .addParameter("age", this.age) .addParameter("phoneNumber", this.phoneNumber) .addParameter("idNumber", this.idNumber) .addParameter("email", this.email) .addParameter("clientCount", this.clientCount) .executeUpdate() .getKey(); } } public static Stylist find(int id) { try(Connection con = DB.sql2o.open()) { String sql = "SELECT * FROM stylists where id=:id"; Stylist stylist = con.createQuery(sql) .addParameter("id", id) .executeAndFetchFirst(Stylist.class); return stylist; } } public List<Client> getClients() { try(Connection con = DB.sql2o.open()) { String sql = "SELECT * FROM clients where stylistId=:id"; return con.createQuery(sql) .addParameter("id", this.id) .executeAndFetch(Client.class); } } public void delete() { try(Connection con = DB.sql2o.open()) { String sql = "DELETE FROM stylists WHERE id = :id;"; con.createQuery(sql) .addParameter("id", id) .executeUpdate(); } } } <file_sep>/README.md # Hair Salon An app for hair salons to help them keep track of stylists and clients. ## Getting Started ### Seeting Up the Database In PSQL: ``` CREATE DATABASE hair_salon; CREATE TABLE stylists (id serial PRIMARY KEY, name varchar,age int, varchar, phoneNumber varchar, email varchar, clientCount varchar); CREATE TABLE clients (id serial PRIMARY KEY, firstName varchar, lastName varchar,email varchar, phoneNumber varchar, stylistId int); ``` ### Running the Application the application can be run sing gradle , run ``` gradle run. ``` to get the application started on your local machine. ### Prerequisites ``` Java, Graddle, Maven, Heroku. ``` ## Running the tests Tests are run using gradle. From the root of the project directory run gradle test ## Authors * **<NAME>** ## License This project is licensed under the MIT License - see the [MIT LICENCE](https://opensource.org/licenses/MIT) file for details ## Website The web-application is available at [here](https://polar-chamber-91556.herokuapp.com/)
2fc78e9371dcb32d13db03ba9307df743a39d36d
[ "Markdown", "Java" ]
2
Java
shariff6/HAIR_SALON
b4a54a17ecd03963e3151bd534731a52762fbe8a
26abef5f4573157b9705b0a0066f39d08dc895c6
refs/heads/master
<repo_name>Prasanth-G/HackerRank<file_sep>/Python/Itertools.py ######itertools.product() ''' Sample Input 1 2 3 4 Sample Output (1, 3) (1, 4) (2, 3) (2, 4) ''' from itertools import product for each in list(product(map(int,input().split(" ")),map(int,input().split(" ")))): print(each,end = " ") ######itertools.permutations() ''' Sample Input HACK 2 Sample Output AC AH AK CA CH CK HA HC HK KA KC KH ''' from itertools import permutations w = input().split(" ") a = sorted(["".join(each) for each in permutations(w[0],int(w[1]))]) for each in a: print(each) ######itertools.combinations() ''' Sample Input HACK 2 Sample Output A C H K AC AH AK CH CK HK ''' from itertools import combinations w = input().split(" ") out = ["".join(each) for i in range(1,int(w[1])+1) for each in combinations(sorted(w[0]),i)] for each in sorted(sorted(out),key=len): print(each) ######itertools.combinations_with_replacement ''' Sample Input HACK 2 Sample Output AA AC AH AK CC CH CK HH HK KK ''' from itertools import combinations_with_replacement w = input().split(" ") for each in sorted(["".join(each) for each in combinations_with_replacement(sorted(w[0]),int(w[1]))]): print(each) ######compress the string ''' Sample Input 1222311 Sample Output (1, 1) (3, 2) (1, 3) (2, 1) ''' from itertools import groupby for i,j in groupby(input()): print("(%d, %d) "%(len(list(j)),int(i)),end="") ######iterables and iterators ''' Sample Input 4 a a c d 2 Sample Output 0.8333 Explanation All possible unordered tuples of length 2 comprising of indices from 1 to 4 are: (1,2),(1,3),(1,4),(2,3),(2,4),(3,4) Out of these 6 combinations, 5 of them contain either index 1 or index 2 which are the indices that contain the letter 'a'. Hence, the answer is 5/6. from itertools import combinations ''' n = int(input()) w = input().split(" ") c = int(input()) temp = list(combinations(w, c)) print(len(["0" for i in temp if 'a' in i])/len(temp)) ######Maximize it ''' Sample Input 3 1000 2 5 4 3 7 8 9 5 5 7 8 9 10 Sample Output 206 Explanation Picking 5 from the 1st list, 9 from the 2nd list and 10 from the 3rd list gives the maximum S value equal to (5^2 + 9^2 + 10^2)%1000 = 206 ''' import itertools m = list(map(int, input().split(" "))) out = 0 inp = [] for i in range(m[0]): inp.append(list(map(int, input().split(" ")))[1:]) g = 0 for each in itertools.product(*inp): temp = sum([x**2 for x in each])%m[1] if g < temp: g = temp print(g)<file_sep>/Python/Errors_and_Exceptions.py ######1.Exceptions ''' Sample Input 3 1 0 2 $ 3 1 Sample Output Error Code: integer division or modulo by zero Error Code: invalid literal for int() with base 10: '$' 3 ''' for i in range(int(input())): try: a, b = map(int, input().strip("\r").split(" ")) print(a//b) except ZeroDivisionError: print("Error Code: integer division or modulo by zero") except ValueError as e: print("Error Code:",e) ######2.Incorrect Regex ''' Sample Input 2 .*\+ .*+ Sample Output True False ''' import re for i in range(int(input())): try: re.compile(input()) print('True') except: print('False')<file_sep>/Regex/Assertions.py #1.Positive Lookahead ''' Write a regex that can match all occurrences of o followed immediately by oo in S. ''' Regex_Pattern = r'o(?=oo)' #2.Negative Lookahead ''' Write a regex which can match all characters which are not immediately followed by that same character. ''' Regex_Pattern = r"(.)(?!\1)" #3.Positive Lookbehind ''' Write a regex which can match all the occurences of digit which are immediately preceded by odd digit. ''' Regex_Pattern = r"(?<=[13579])\d" #4.Negative Lookbehind ''' Write a regex which can match all the occurences of characters which are not immediately preceded by vowels (a, e, i, u, o, A, E, I, O, U). ''' Regex_Pattern = r"(?<![aeiouAEIOU])." <file_sep>/Python/Classes.py ######1.Classes: Dealing with complex Numbers ''' Sample Input 2 1 5 6 Sample Output 7.00+7.00i -3.00-5.00i 4.00+17.00i 0.26-0.11i 2.24+0.00i 7.81+0.00i ''' class Complex(object): def __init__(self, real, imaginary): self.real = real self.imaginary = imaginary def __add__(self, no): return Complex(no.real+self.real, no.imaginary+self.imaginary) def __sub__(self, no): return Complex(self.real - no.real, self.imaginary - no.imaginary) def __mul__(self, no): return Complex(self.real*no.real - self.imaginary*no.imaginary, self.real*no.imaginary + self.imaginary*no.real) def __truediv__(self, no): m = Complex(self.real,self.imaginary)*Complex(no.real,-1 * no.imaginary) d = no.real**2 + no.imaginary**2 return Complex(m.real/d , m.imaginary/d ) def mod(self): return Complex(math.sqrt(self.real**2 + self.imaginary**2),0) def __str__(self): if self.imaginary == 0: result = "%.2f+0.00i" % (self.real) elif self.real == 0: if self.imaginary >= 0: result = "0.00+%.2fi" % (self.imaginary) else: result = "0.00-%.2fi" % (abs(self.imaginary)) elif self.imaginary > 0: result = "%.2f+%.2fi" % (self.real, self.imaginary) else: result = "%.2f-%.2fi" % (self.real, abs(self.imaginary)) return result ######2.Find the Torsional Angle ''' Sample Input 0 4 5 1 7 6 0 5 9 1 7 2 Sample Output 8.19 ''' class Points(object): def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __sub__(self, no): return Points(no.x - self.x, no.y - self.y, no.z - self.z) def dot(self, no): return self.x * no.x + self.y * no.y + self.z * no.z def cross(self, no): return Points(self.y*no.z - self.z*no.y, self.z*no.x - self.x*no.z, self.x*no.y - self.y*no.x) def absolute(self): return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5)<file_sep>/Python/XML.py ######XML 1- Find te Score ''' Input (stdin) 11 <feed xml:lang='en'> <title>HackerRank</title> <subtitle lang='en'>Programming challenges</subtitle> <link rel='alternate' type='text/html' href='http://hackerrank.com/'/> <updated>2013-12-25T12:00:00</updated> <entry> <author gender='male'>Harsh</author> <question type='hard'>XML 1</question> <description type='text'>This is related to XML parsing</description> </entry> </feed> Expected Output 8 ''' import sys import xml.etree.ElementTree as etree def get_attr_number(node): return len_child(root,node,len(node.attrib)) def len_child(root,node,s): if not len(list(node)): if root == node: return s return s+len(node.attrib) else: for child in node: s = len_child(root,child,s) return s if __name__ == '__main__': sys.stdin.readline() xml = sys.stdin.read() tree = etree.ElementTree(etree.fromstring(xml)) root = tree.getroot() print(get_attr_number(root)) ######2.XML2 - Find the Maximum Depth ''' Input (stdin) 11 <feed xml:lang='en'> <title>HackerRank</title> <subtitle lang='en'>Programming challenges</subtitle> <link rel='alternate' type='text/html' href='http://hackerrank.com/'/> <updated>2013-12-25T12:00:00</updated> <entry> <author gender='male'>Harsh</author> <question type='hard'>XML 1</question> <description type='text'>This is related to XML parsing</description> </entry> </feed> Expected Output 2 ''' import xml.etree.ElementTree as etree maxdepth = 0 def depth(elem, level): global maxdepth level = level + 1 if not len(list(elem)): if level > maxdepth: maxdepth = level else: for child in elem: depth(child,level) if __name__ == '__main__': n = int(input()) xml = "" for i in range(n): xml = xml + input() + "\n" tree = etree.ElementTree(etree.fromstring(xml)) depth(tree.getroot(), -1) print(maxdepth) <file_sep>/Regex/Backreferences.py #1.Matching Same text again & again ''' must be of length: 20 1st character: lowercase letter . 2nd character: word character . 3rd character: whitespace character . 4th character: non word character . 5th character: digit . 6th character: non digit . 7th character: uppercase letter . 8th character: letter (either lowercase or uppercase). 9th character: vowel (a, e, i , o , u, A, E, I, O or U). 10th character: non whitespace character . 11th character: should be same as 1st character . 12th character: should be same as 2nd character . 13th character: should be same as 3rd character . 14th character: should be same as 4th character . 15th character: should be same as 5th character . 16th character: should be same as 6th character . 17th character: should be same as 7th character . 18th character: should be same as 8th character . 19th character: should be same as 9th character . 20th character: should be same as 10th character . ''' Regex_Pattern = r'([a-z])(\w)(\s)(\W)(\d)(\D)([A-Z])([a-zA-Z])([AEOIUaeiou])(\S)\1\2\3\4\5\6\7\8\9\10' #2.Backreferences to Failed groups ''' S consists of 8 digits. S may have "-" separator such that string S gets divided in 4 parts, with each part having exactly two digits. (Eg. 12-34-56-78) ''' Regex_Pattern = r"^\d\d(-?)\d\d(\1)\d\d(\2)\d\d$" #3.Branch reset Groups - Perl ''' S consists of 8 digits. S must have "---", "-", "." or ":" separator such that string S gets divided in 4 parts, with each part having exactly two digits. S string must have exactly one kind of separator. Separators must have integers on both sides. ''' $Regex_Pattern = '^[0-9]{2}(?|(---)|(:)|(\.)|(-))[0-9]{2}\1[0-9]{2}\1[0-9]{2}$'; #4.Forward References - Perl ''' S consists of tic or tac. tic should not be immediate neighbour of itself. The first tic must occur only when tac has appeared at least twice before. ''' $Regex_Pattern = '^(tactactic)(tactic)*(tac)*$'; <file_sep>/Python/Built-Ins.py #######1.Zipped! ''' Sample Input 5 3 89 90 78 93 80 90 91 85 88 86 91 92 83 89 90.5 Sample Output 90.0 91.0 82.0 90.0 85.5 ''' ns, n = map(int, input().split(" ")) marks = [list(map(float, input().split(" "))) for i in range(n)] zipped = zip(*marks) print(*[ sum(each)/n for each in list(zipped)],sep='\n') #######2.Input() ''' Sample Input 1 4 #x and k x**3 + x**2 + x + 1 Sample Output True ''' x, k = map(int, raw_input().split()) print(input() == k) ######3.Python Evaluation ''' Sample input print(2 + 3) Sample Output 5 ''' eval(input()) ######4.Sort Data ''' Sample input 5 3 10 2 5 7 1 0 9 9 9 1 23 12 6 5 9 1 Sample Output 7 1 0 10 2 5 6 5 9 9 9 9 1 23 12 Explanation The table is sorted on the second attribute shown as K = 1 because it's 0-indexed. ''' n, m = map(int, input().split(' ')) L = [ list(map(int,input().split(' '))) for i in range(n)] k = int(input()) [print(("%d "*m)%tuple(each)) for each in sorted(L, key= lambda x: x[k])] ######5.All or Any ''' Sample input 5 12 9 61 5 14 Sample Output True ''' input() inp = input().split(" ") print(all([int(x) >= 0 for x in inp]) and any([list(reversed(x)) == list(x) for x in inp])) ######6.ginortS ''' Sample Input Sorting1234 Sample Output ginortS1324 Note: a) Using join, for or while anywhere in your code, even as substrings, will result in a score of 0. b) You can only use one sorted function in your code. A 0 score will be awarded for using sorted more than once. Hint: Success is not the key, but key is success. ''' import functools def val(a): if a.islower(): return ord(a) - ord('a') elif a.isupper(): return ord(a) - ord('A') + 26 elif a.isdigit(): if int(a)%2: return int(a) + 53 else: return int(a) + 63 print(functools.reduce(lambda x,y : x + y, sorted(input(), key=val)))<file_sep>/Python/Regex_and_Parsing.py ######1.Introduction to Regex Module ''' Sample input : 5 1.414 +.5486468 0.5.0 1+1.0 0 Sample output : True True False False False ''' import re for i in range(int(input())): print(bool(re.match("^[\+\-]?\d*\.\d+$",input()))) ######2.re.split() ''' Sample input : .172..16.52.207,172.16.52.117 Sample Output : 172 16 52 207 172 16 52 117 #print only the numbers ''' import re [ print(i) for i in re.split("[.,]",input()) if i] ######3.Group(), Groups() & Groupdict() ''' Sample Input : ..12345678910111213141516171820212223 Sample Output : 1 Explanation .. is the first repeating character, but it is not alphanumeric. 1 is the first (from left to right) alphanumeric repeating character of the string in the substring 111. ''' import re out = re.findall(r'([A-Za-z0-9])\1',input()) if out: print(out[0]) else: print(-1) ######4.Re.findall() & Re.finditer() ''' Sample Input : rabcdeefgyYhFjkIoomnpOeorteeeeet Sample Output : ee Ioo Oeo eeeee Explanation : ee is located between d consonant f and . Ioo is located between k consonant m and . Oeo is located between p consonant r and . eeeee is located between t consonant t and . ''' import re pattern = re.compile(r'[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm]*([AEIOUaeiou]+)[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm]') match = pattern.findall(input()) match = [each for each in match if len(each) >= 2] if match: print(*match, sep='\n') else: print("-1") ######5.Re.start() & Re.end() ''' Sample Input : aaadaa aa Sample Output : (0, 1) (1, 2) (4, 5) ''' import re s, k = input(), input() l = list(re.finditer('(?=('+ k +'))',s)) if l: for each in l: print((each.start(),each.end()+len(k)-1)) else: print((-1,-1)) ######6.Regex Substitution ''' Sample Input : 11 a = 1; b = input(); if a + b > 0 && a - b < 0: start() elif a*b > 10 || a/b < 1: stop() print set(list(a)) | set(list(b)) #Note do not change &&& or ||| or & or | #Only change those '&&' which have space on both sides. #Only change those '|| which have space on both sides. Sample Output : a = 1; b = input(); if a + b > 0 and a - b < 0: start() elif a*b > 10 or a/b < 1: stop() print set(list(a)) | set(list(b)) #Note do not change &&& or ||| or & or | #Only change those '&&' which have space on both sides. #Only change those '|| which have space on both sides. ''' import re import functools for i in range(int(input())): print(functools.reduce(lambda x,z: re.sub(z[0],z[1],x),[(r'(?<=\s)\|\|(?=\s)','or'), (r'(?<=\s)&&(?=\s)','and')], input())) ######7.Validating Roman Numerals ''' Sample Input : CDXXI Sample Output : True ''' import re print(bool(re.fullmatch(r'M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})',input()))) ######8.Validating Phone numbers ''' Sample Input : 2 9587456281 1252478965 Sample Output : YES NO ''' import re for i in range(int(input())): if re.fullmatch(r'[987][0-9]{9}',input()): print("YES") else: print("NO") ######9.Validating and Parsing email addresses ''' Sample Input : 2 DEXTER <<EMAIL>> VIRUS <virus!@variable.:p> Sample Output : DEXTER <<EMAIL>> Explanation : A valid email address meets the following criteria: => It's composed of a username, domain name, and extension assembled in this format: [email protected] => The username starts with an English alphabetical character, and any subsequent characters consist of one or more of the following: alphanumeric characters, -,., and _. => The domain and extension contain only English alphabetical characters. => The extension is 1,2,3 or characters in length. ''' import email.utils import re for i in range(int(input())): name, addr = email.utils.parseaddr(input()) if re.fullmatch(r'[a-zA-Z][\w\-\.]*@[a-zA-Z]+?\.[a-zA-Z]{0,3}', addr): print(email.utils.formataddr((name, addr))) ######10.Hex colour code ''' Sample Input : 11 #BED { color: #FfFdF8; background-color:#aef; font-size: 123px; background: -webkit-linear-gradient(top, #f9f9f9, #fff); } #Cab { background-color: #ABC; border: 2px dashed #fff; } Sample Output : #FfFdF8 #aef #f9f9f9 #fff #ABC #fff ''' import re for i in range(int(input())): line = input() if len(line) and line[0] != '#': output = re.findall('#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}',line) if output: print(*output,sep='\n') ######11.HTML parser - part 1 ''' Sample Input : 2 <html><head><title>HTML Parser - I</title></head> <body data-modal-target class='1'><h1>HackerRank</h1><br /></body></html> Sample Output : Start : html Start : head Start : title End : title End : head Start : body -> data-modal-target > None -> class > 1 Start : h1 End : h1 Empty : br End : body End : html ''' from html.parser import HTMLParser # create a subclass and override the handler methods class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print ("Start :", tag) self.print_(attrs) def handle_endtag(self, tag): print ("End :", tag) def handle_startendtag(self, tag, attrs): print ("Empty :", tag) self.print_(attrs) def print_(self,attrs): for each in attrs: print("-> %s > %s"%each) # instantiate the parser and fed it some HTML parser = MyHTMLParser() for i in range(int(input())): parser.feed(input()) ######12.HTML parser - part 2 ''' Sample Input : 4 <!--[if IE 9]>IE9-specific content <![endif]--> <div> Welcome to HackerRank</div> <!--[if IE 9]>IE9-specific content<![endif]--> Sample Output : >>> Multi-line Comment [if IE 9]>IE9-specific content <![endif] >>> Data Welcome to HackerRank >>> Single-line Comment [if IE 9]>IE9-specific content<![endif] ''' from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_comment(self, comment): l = comment.split('\n') if len(l) > 1: print(">>> Multi-line Comment") else: print(">>> Single-line Comment") print(*l, sep='\n') def handle_data(self, data): if data != '\n': print(">>> Data\n%s"%data) html = "" for i in range(int(input())): html += input().rstrip() html += '\n' parser = MyHTMLParser() parser.feed(html) parser.close() ######13.Detect HTML Tags, Attributes and Attribute Value ''' Sample Input : 9 <head> <title>HTML</title> </head> <object type="application/x-flash" data="your-file.swf" width="0" height="0"> <!-- <param name="movie" value="your-file.swf" /> --> <param name="quality" value="high"/> </object> Sample Output : head title object -> type > application/x-flash -> data > your-file.swf -> width > 0 -> height > 0 param -> name > quality -> value > high ''' from html.parser import HTMLParser class myhtmlparser(HTMLParser): def handle_starttag(self, tag, attrs): print(tag) self.print_(attrs) def handle_startendtag(self, tag, attrs): print(tag) self.print_(attrs) def print_(self, attrs): for each in attrs: print("-> %s > %s"%each) html = '' for i in range(int(input())): html = html + input() + '\n' htmlparser = myhtmlparser() htmlparser.feed(html) htmlparser.close() ######14.Validating UID ''' Sample Input : 2 B1CD102354 B1CDEF2354 Sample Output : Invalid Valid ''' import re print(*[ 'Valid ' if not re.search(r'([A-Z0-9a-z]).*\1', text) and re.search(r'[A-Z].*[A-Z]', text) and re.search(r'\d.*\d.*\d', text) and len(text) == 10 else 'Invalid' for text in [input() for i in range(int(input()))]], sep='\n') ######15.Validating Credit Card Numbers ''' Sample Input : 6 4123456789123456 5123-4567-8912-3456 61234-567-8912-3456 4123356789123456 5133-3367-8912-3456 5123 - 3567 - 8912 - 3456 Sample Output : Valid Valid Invalid Valid Invalid Invalid Explanation : A valid credit card from ABCD Bank has the following characteristics: ► It must start with a 4,5 or 6. ► It must contain exactly 16 digits. ► It must only consist of digits (0-9). ► It may have digits in groups of 4 , separated by one hyphen "-". ► It must NOT use any other separator like ' ' , '_', etc. ► It must NOT have 4 or more consecutive repeated digits. ''' import re print(*['Valid' if re.search(r'^[4-6][0-9]{3}\-{0,1}[0-9]{4}\-{0,1}[0-9]{4}\-{0,1}[0-9]{4}$',text) and not re.findall(r'([0-9])\1\1\1',''.join(text.split('-'))) else 'Invalid' for text in [input() for i in range(int(input()))]], sep='\n') ######16.Validating Postal Codes ''' Sample Input : 110000 Sample Output : False Explanation : A postal code P must be a number in the range of (100000, 999999). A postal code P must not contain more than one alternating repetitive digit pair. Alternating repetitive digits are digits which repeat immediately after the next digit. In other words, an alternating repetitive digit pair is formed by two equal digits that have just a single digit between them. ''' import re code = input() print(len(code) == 6 and code.isdigit() and len(re.findall(r'(?=([0-9])\d\1)', code)) <= 1) ######17.Matrix Script ''' Sample Input : 7 3 Tsi h%x i # sM $a #t% ir! Sample Output : This is Matrix# %! ''' import re def func(string): string = string.group(0) return ' '.join([string[0], string[-1]]) m, n = map(int, input().split()) l = [input() for i in range(m)] decoded_str = ''.join([ ''.join([each[i] for each in l]) for i in range(n)]) print(re.sub(r'\w[!@#$%& ]+\w', func, decoded_str)) <file_sep>/Python/Numpy.py 1.Arrays import numpy print(numpy.array(list(reversed( input().split() )), float)) 2.Shape and Reshape import numpy print(numpy.reshape( numpy.array(input().split(), int), (3,3))) 3.Transpose and Flatten import numpy m,n = map(int, input().split()) mat = [input().split() for i in range(m)] arr = numpy.array(mat, int) print(numpy.transpose(arr), arr.flatten(), sep='\n') 4.Concatenate import numpy m, n, p = map(int, input().split()) mat_list = list(map(lambda x: [input().split() for i in range(x)], [m,n])) print(numpy.concatenate(list(map(lambda x: numpy.array(x,int), mat_list)))) 5.Zeros and Ones import numpy n = list(map(int, input().split())) print(numpy.zeros(n, dtype=numpy.int)) print(numpy.ones(n, dtype=numpy.int)) 6.Eye and Identity import numpy m, n = map(int, input().split()) print(numpy.eye(m,n,0)) 7.Array Mathematics import numpy m, n = map(int, input().split()) A, B = map(lambda x: numpy.array(x,int),[[input().split() for i in range(m)] for i in range(2)]) print(A + B) print(A - B) print(A * B) print(A // B) print(A % B) print(A ** B) 8.Floor, ceil and Rint import numpy A = numpy.array(input().split(), float) print(numpy.floor(A), numpy.ceil(A), numpy.rint(A), sep='\n') 9.Sum and Prod import numpy m, n = map(int, input().split()) l = numpy.array([input().split() for i in range(m)], int) print(numpy.prod(numpy.sum(l,axis=0))) 10.Min and Max import numpy m, n = map(int, input().split()) l = numpy.array([input().split() for i in range(m)], int) print(numpy.max(numpy.min(l, axis=1))) 11.Mean, var and std import numpy m, n = map(int, input().split()) l = numpy.array([input().split() for i in range(m)], int) print(numpy.mean(l, axis=1)) print(numpy.var(l, axis=0)) print(numpy.std(l)) 12.Dot and Cross import numpy n = int(input()) A, B = [numpy.array([input().split() for i in range(n)], int) for i in range(2)] print(numpy.dot(A,B)) 13.Inner and Outer import numpy A, B = [numpy.array(input().split(), int) for i in range(2)] print(numpy.inner(A,B), numpy.outer(A,B), sep='\n') 14.Polynomials import numpy P = numpy.array(input().split(), float) print(numpy.polyval(P, int(input()))) 15.Linear Algebra import numpy A = numpy.array([input().split() for i in range(int(input()))], float) print(numpy.linalg.det(A))<file_sep>/Regex/Repetitions.py #1.Matching {x} Repetitions ''' S must be of length equal to 45. The first 40 characters should consist of letters(both lowercase and uppercase), or of even digits. The last 5 characters should consist of odd digits or whitespace characters ''' Regex_Pattern = r'^[A-Za-z02468]{40}[13579\s]{5}$' #2.Matching {x,y} Repetitions ''' S should begin with or digits. After that, S should have 3 or more letters (both lowercase and uppercase). Then S should end with up to 3 . symbol(s). You can end with 0 to 3 . symbol(s), inclusively. ''' Regex_Pattern = r'^\d{1,2}[a-zA-Z]{3,}\.{0,3}$' #3.Matching Zero or More Repetitions ''' S should begin with 2 or more digits. After that, S should have 0 or more lowercase letters. S should end with 0 or more uppercase letters ''' Regex_Pattern = r'^\d{2,}[a-z]*[A-Z]*$' #4.Matching One or More Repetitions ''' S should begin with or more digits. After that, S should have 1 or more uppercase letters. S should end with 1 or more lowercase letters. ''' Regex_Pattern = r'^\d+[A-Z]+[a-z]+$' #5.Matching Ending Items ''' S should consist of only lowercase and uppercase letters (no numbers or symbols). S should end in s. ''' Regex_Pattern = r'^[a-zA-Z]*s$' <file_sep>/Python/Date_and_Time.py ######1.Calendar Module ''' Sample Input 08 05 2015 Sample Output WEDNESDAY ''' from datetime import datetime print(datetime.strptime(input(),'%m %d %Y').strftime('%A').upper()) ######2.Time Delta ''' Sample Input 2 Sun 10 May 2015 13:54:36 -0700 Sun 10 May 2015 13:54:36 +0000 Sat 02 May 2015 19:54:36 +0530 Fri 01 May 2015 13:54:36 +0000 Sample Output 25200 #absolute difference in seconds 88200 ''' import datetime for i in range(int(input())): d = datetime.datetime.strptime(input(),"%a %d %b %Y %X %z") - datetime.datetime.strptime(input(),"%a %d %b %Y %X %z") print(abs(int(d.total_seconds())))<file_sep>/Python/Math.py ######1.Polar Coordinates ''' Sample Input 1+2j Sample Output 2.23606797749979 1.1071487177940904 ''' import cmath a = complex(input()) print(abs(a)) print(cmath.phase(a)) ######2.Find Angle MBC ''' Sample Input 10 10 Sample Output 45° ''' import math ab = int(input()) bc = int(input()) print("%d°"%round(math.degrees(math.acos(bc/math.sqrt(ab**2 + bc**2))))) ######3.Triangle Quest 2 ''' Sample Input 5 Sample Output 1 121 12321 1234321 123454321 ''' for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also print((10**i - 1)** 2//81) ######4.Mod Divmod ''' Sample Input 177 10 Sample Output 17 7 (17, 7) ''' a,b = divmod(int(input()),int(input())) print(a) print(b) print("(%d, %d)"%(a,b)) ######5.Power - Mod Power ''' Sample Input 3 4 5 Sample Output 81 1 ''' a,b = int(input()),int(input()) print(pow(a,b)) print(pow(a,b,int(input()))) ######6.Integer comes in All Sizes ''' Sample Input 9 29 7 27 Sample Output 4710194409608608369201743232 ''' print(int(input())**int(input()) + int(input())**int(input())) ######7.Triangle Quest ''' Sample Input 5 Sample Output 1 22 333 4444 ''' for i in range(1,int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also print ((10**i-1)//9 * i)<file_sep>/Python/Sets.py ######1.Introduction to Sets ''' Sample Input : 10 161 182 161 154 176 170 167 171 170 174 Sample Output : 169.375 Explanation : Here, set([154, 161, 167, 170, 171, 174, 176, 182]) is the set containing the distinct heights. Using the sum() and len() functions, we can compute the average. ''' def average(array): a = set(array) return sum(a)/len(a) ######2.No Idea! ''' Sample Input : 3 2 1 5 3 3 1 5 7 Sample Output : 1 Explanation : You gain 1 unit of happiness for elements 3 and 1 in set A. You lose 1 unit for 5 in set B. The element 7 in set B does not exist in the array so it is not included in the calculation. Hence, the total happiness is 2 - 1 = 1. ''' input() arr = [ int(each) for each in input().split(" ")] A = set([int(each) for each in input().split(" ")]) B = set([int(each) for each in input().split(" ")]) happiness = 0 for each in arr: if each in A: happiness = happiness + 1 elif each in B: happiness = happiness - 1 print(happiness) ######3.Symmetric Difference ''' Sample Input : 4 2 4 5 9 4 2 4 11 12 Sample Output : 5 9 11 12 ''' input() a = input().split(" ") input() b = input().split(" ") a = set(a) b = set(b) output = sorted([ int(each) for each in a.difference(b).union(b.difference(a)) ]) for each in output: print(each) ######4. Set.add() ''' Sample Input : 7 UK China USA France New Zealand UK France Sample Output : 5 Explanation : UK and France repeat twice. Hence, the total number of distinct country stamps is 5 (five). ''' print(len(set([input() for i in range(int(input()))]))) ######5. Set .discard(), .remove() & .pop() ''' Sample Input : 9 1 2 3 4 5 6 7 8 9 10 pop remove 9 discard 9 discard 8 remove 7 pop discard 6 remove 5 pop discard 5 Sample Output : 4 Explanation : After completing these 10 operations on the set([4]), we get set. Hence, the sum is 4. ''' n = int(input()) s = set(map(int, input().split())) for i in range(int(input())): temp = input().split(" ") if temp[0] == "pop": s.pop() elif temp[0] == "remove" or temp[0] == "discard": s.discard(int(temp[1])) print(sum(s)) ######6. Set .union() Operation ''' Sample Input : 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 Sample Output : 13 Explanation : Roll numbers of students who have at least one subscription: 1,2,3,4,5,6,7,8,9,10,11,21 and 55. Roll numbers: 1, 2, 3, 6 and 8 are in both sets so they are only counted once. Hence, the total is 13 students. ''' input() a = set(map(int,input().split(" "))) input() b = set(map(int,input().split(" "))) print(len(list(a.union(b)))) ######7. Set .intersection() Operation ''' Sample Input : 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 Sample Output : 5 Explanation : The roll numbers of students who have both subscriptions: 1,2,3,6 and 8. Hence, the total is 5 students. ''' input() a = set(map(int,input().split(" "))) input() b = set(map(int,input().split(" "))) print(len(list(a.intersection(b)))) ######8. Set .difference() Operation ''' Sample Input : 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 Sample Output : 4 Explanation : The roll numbers of students who only have English newspaper subscriptions are: 4, 5, 7 and 9. Hence, the total is 4 students. ''' input() a = set(map(int,input().split(" "))) input() b = set(map(int,input().split(" "))) print(len(list(a.difference(b)))) ######9. Set .symmetric_difference() Operation ''' Sample Input : 9 1 2 3 4 5 6 7 8 9 9 10 1 2 3 11 21 55 6 8 Sample Output : 8 ''' input() a = set(map(int,input().split(" "))) input() b = set(map(int,input().split(" "))) print(len(list(a.symmetric_difference(b)))) ######10. Set Mutations ''' Sample Input : 16 1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52 4 intersection_update 10 2 3 5 6 8 9 1 4 7 11 update 2 55 66 symmetric_difference_update 5 22 7 35 62 58 difference_update 7 11 22 35 55 58 62 66 Sample Output : 38 ''' input() s = set(map(int, input().split(" "))) for each in range(int(input())): temp = input().split(" ") if temp[0] == "intersection_update": s.intersection_update(set(map(int, input().split(" ")))) elif temp[0] == "update": s.update(set(map(int, input().split(" ")))) elif temp[0] == "symmetric_difference_update": s.symmetric_difference_update(set(map(int, input().split(" ")))) elif temp[0] == "difference_update": s.difference_update(set(map(int, input().split(" ")))) print(sum(s)) ######11. The Captain's Room ''' Sample Input : 5 1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2 Sample Output : 8 ''' n = int(input()) d = {} for each in input().split(" "): if each in d: d[each] = d[each] + 1 else: d[each] = 1 for each in d: if d[each] == 1: print(each) break ######12. Check Subset ''' Sample Input : 3 5 1 2 3 5 6 9 9 8 5 6 3 2 1 4 7 1 2 5 3 6 5 4 1 7 1 2 3 5 6 8 9 3 9 8 2 Sample Output : True False False Explanation : Set A = {1 2 3 5 6} Set B = {9 8 5 6 3 2 1 4 7} All the elements of set A are elements of set B. Hence, set A is a subset of set B. ''' for i in range(int(input())): #More than 4 lines will result in 0 score. Blank lines won't be counted. a = int(input()); A = set(input().split()) b = int(input()); B = set(input().split()) print(A.issubset(B)) ######13. Check Strict Superset ''' Sample Input : 1 2 3 4 5 6 7 8 9 10 11 12 23 45 84 78 2 1 2 3 4 5 100 11 12 Sample Output : False Explanation : Set A is the strict superset of the set ([1,2,3,4,5]) but not of the set ([100, 11, 12]) because 100 is not in set A. Hence, the output is False. ''' A = set(input().split()) is_ss = lambda x : x.issubset(A) and bool(A.difference(x)) print(all([ is_ss(set(input().split())) for i in range(int(input())) ]))<file_sep>/Python/Python_Functionals.py ######1.Map and Lambda Function ''' Sample Input 5 Sample Output [0, 1, 1, 8, 27] ''' cube = lambda x: x**3# complete the lambda function def fibonacci(n): x = -1 y = 1 fseries = [] temp = 0 for i in range(n): temp = x + y fseries.append(temp) x,y = y, temp return fseries ######2.Validating Email Addresses with a Filter ''' Sample Input 3 <EMAIL> <EMAIL> <EMAIL> Sample Output ['<EMAIL>', '<EMAIL>', '<EMAIL>'] ''' import re def fun(s): return bool(re.match("[\w-]+@[A-Za-z0-9]+\.\w{0,3}$",s))# return True if s is a valid email, else return False def filter_mail(emails): return list(filter(fun, emails)) if __name__ == '__main__': n = int(input()) emails = [] for _ in range(n): emails.append(input()) filtered_emails = filter_mail(emails) filtered_emails.sort() print(filtered_emails) ######3.Reduce Function ''' Sample Input 3 1 2 3 4 10 6 Sample Output 5 8 Explanation Required product is (1/2)*(3/4)*(10/6) = (5/8) ''' from fractions import Fraction from functools import reduce def product(fracs): t = Fraction(reduce(lambda x,y: x*y,fracs)) return t.numerator, t.denominator if __name__ == '__main__': fracs = [] for _ in range(int(input())): fracs.append(Fraction(*map(int, input().split()))) result = product(fracs) print(*result) <file_sep>/Python/Closures_and_Decorators.py ###Closure # Py violates Variable scoping :p ###Decoratos # A decorator is just a callable that takes a function as an argument #and returns a replacement function. # ######1.Standardize Mobile number using Decorators ''' Sample Input 3 07895462130 919875641230 9195969878 Sample Output +91 78954 62130 +91 91959 69878 +91 98756 41230 ''' def wrapper(f): def fun(l): l = ['+91 '+phone_no[-10:-5]+' '+phone_no[-5:] for phone_no in l] return f(l) return fun @wrapper def sort_phone(l): print(*sorted(l), sep='\n') if __name__ == '__main__': l = [input() for _ in range(int(input()))] sort_phone(l) ######2.Decorators 2 - Name Directory ''' Sample Input 3 <NAME> 20 M <NAME> 32 M <NAME> 30 F Sample Output Mr. <NAME> Ms. <NAME> Mr. <NAME> ''' import operator def person_lister(f): def inner(people): #people = sorted(people, key= operator.itemgetter(2)) #return f(people) return map(f, sorted(people, key=operator.itemgetter(2))) return inner @person_lister def name_format(person): return ("Mr. " if person[3] == "M" else "Ms. ") + person[0] + " " + person[1] if __name__ == '__main__': people = [input().split() for i in range(int(input()))] print(*name_format(people), sep='\n') <file_sep>/Regex/Grouping_and_Capturing.py #1.Matching Word Boundaries ''' You have a test String S. Your task is to write a regex which will match word starting with vowel (a,e,i,o, u, A, E, I , O or U). The matched word can be of any length. The matched word should consist of letters (lowercase and uppercase both) only. The matched word must start and end with a word boundary. ''' Regex_Pattern = r'\b[aeiouAEIOU][a-zA-Z]*\b' #2.Capturing & Non-Capturing Groups ''' You have a test String S. Your task is to write a regex which will match S with the following condition: S should have 3 or more consecutive repetitions of ok. ''' Regex_Pattern = r'okokok' #3.Alternative Matching ''' Given a test string, S, write a RegEx that matches S under the following conditions: S must start with Mr., Mrs., Ms., Dr. or Er.. The rest of the string must contain one or more English alphabetic letters (upper and lowercase). ''' Regex_Pattern = r'^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)([A-Za-z]+)$'<file_sep>/Python/Collections.py ######1.collection.Counter() ''' Sample Input 10 #no.of shoes 2 3 4 5 6 8 7 6 5 18 #shoes size 6 #no.of customers 6 55 #customer's size, price 6 45 6 55 4 40 18 60 10 50 Sample Output 200 ''' from collections import Counter input() size = Counter(map(int, input().split(" "))) amt = 0 for each in range(int(input())): i = list(map(int,input().split(" "))) if i[0] in size: size[i[0]] = size[i[0]] - 1 if not size[i[0]]: size.pop(i[0]) amt = amt + i[1] print(amt) ######2.DefaultDict Tutorial ''' Output M lines. The ith line should contain the 1-indexed positions of the occurrences of the ith word separated by spaces. Sample Input 5 2 #M, N a #M words a b a b a #N testcase b Sample Output 1 2 4 3 5 ''' from collections import defaultdict d = defaultdict(list) m, n = input().split(" ") count = 1 for i in range(int(m)): d[input()].append(count) count = count + 1 for i in range(int(n)): inp = input() if inp in d: for each in d[inp]: print(each,end=" ") print("") else: print(-1) ######3.Coolections.namedtuple() ''' Sample Input 5 ID MARKS NAME CLASS 1 97 Raymond 7 2 50 Steven 4 3 91 Adrian 9 4 72 Stewart 5 5 80 Peter 6 Sample Output 78.00 #average mark ''' from re import findall n = int(input()) index = findall("(\S+)\s",input()).index("MARKS") print(sum([int(findall("(\S+)\s",input())[index]) for i in range(n)])/n) ######4.collections.OrderedDict() ''' Sample Input 9 BANANA FRIES 12 POTATO CHIPS 30 APPLE JUICE 10 CANDY 5 APPLE JUICE 10 CANDY 5 CANDY 5 CANDY 5 POTATO CHIPS 30 Sample Output BANANA FRIES 12 #item_name, total price in order POTATO CHIPS 60 APPLE JUICE 20 CANDY 20 ''' from collections import OrderedDict import re output = OrderedDict() for i in range(int(input())): item = re.findall("(.+) (\d+)",input())[0] if item[0] in output: output[item[0]] = output[item[0]] + int(item[1]) else: output[item[0]] = int(item[1]) for each in output: print(each,output[each]) ######5.Word Order ''' Sample Input 4 bcdef abcdefg bcde bcdef Sample Output 3 #no.of occurrence in input order 2 1 1 ''' from collections import OrderedDict d = OrderedDict() for i in range(int(input())): word = input() if word in d: d[word] = d[word] + 1 else: d[word] = 1 print(len(d)) for each in d: print(d[each],end = " ") ######6.Collections.deque() #de = double ended ''' Sample Input 6 append 1 append 2 append 3 appendleft 4 pop popleft Sample Output 1 2 ''' from collections import deque d = deque() for i in range(int(input())): w = input().split(" ") w[0] = w[0].strip("\r") if w[0] == "append": d.append(w[1].rstrip("\r")) elif w[0] == "pop": d.pop() elif w[0] == "appendleft": d.appendleft(w[1].rstrip("\r")) elif w[0] == "popleft": d.popleft() for each in d: print(each,end=" ") ######7.Piling up! ''' Sample Input 2 6 4 3 2 1 3 4 3 1 3 2 Sample Output Yes No ''' from collections import deque import sys for i in range(int(input())): input() i = input().split(" ") temp = [ int(each) for each in i if each.strip("\n") ] sidelengths = deque(temp) prevlength = sys.maxsize output = "Yes" while len(sidelengths): if len(sidelengths) == 1 or sidelengths[0] < sidelengths[-1]: currlength = sidelengths.pop() else: currlength = sidelengths.popleft() if currlength > prevlength: output = "No" break prevlength = currlength print(output) ######8.Most common ''' Sample Input aabbbccde Sample Output b 3 a 2 c 2 ''' from collections import Counter c = Counter(input()) s = sorted(c) def val(each): return c[each] for each in sorted(s, key= val, reverse= True)[:3]: print(each,c[each])<file_sep>/Regex/Character_class.py #1.Matching Specific Characters Regex_Pattern = r'^[123][012][xs0][30Aa][xsu][\.,]$' #2.Excluding Specific Characters Regex_Pattern = r'^[^\d][^aeiou][^bcDF][^\s][^AEIOU][^\.,]$' #3.Matching Character Ranges Regex_Pattern = r'^[a-z][1-9][^a-z][^A-Z][A-Z]'
4409c145c83619e40d846020d10488e14e97fe41
[ "Python" ]
18
Python
Prasanth-G/HackerRank
5fd0432995547f7845e90fa190a0daabaab10cb4
0cb7b80d95957a792d0a90fef6eec41c58b893d5
refs/heads/master
<repo_name>odedmar/Git<file_sep>/carkyp/src/com/carkyp/controllers/domain/ServiceProvidedType.java package com.carkyp.controllers.domain; public class ServiceProvidedType { private String name; public final String getName() { return name; } public final void setName(String name) { this.name = name; } @Override public String toString() { return "ServiceProvidedType [name=" + name + "]"; } } <file_sep>/carkyp/src/com/carkyp/service/provideraccount/model/BusnessDetail.java package com.carkyp.service.provideraccount.model; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import com.carkyp.domain.Address; public class BusnessDetail { //@Email private String email; // @NotEmpty private String password; // @NotEmpty private String businessName; // @NotEmpty private String contactFirstName; // @NotEmpty private String contactLastName; // @NotEmpty private String phoneNumber; // @NotEmpty private Address address; public final String getEmail() { return email; } public final void setEmail(String email) { this.email = email; } public final String getPassword() { return password; } public final void setPassword(String password) { this.password = password; } public final String getBusinessName() { return businessName; } public final void setBusinessName(String businessName) { this.businessName = businessName; } public final String getContactFirstName() { return contactFirstName; } public final void setContactFirstName(String contactFirstName) { this.contactFirstName = contactFirstName; } public final String getContactLastName() { return contactLastName; } public final void setContactLastName(String contactLastName) { this.contactLastName = contactLastName; } public final String getPhoneNumber() { return phoneNumber; } public final void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public final Address getAddress() { return address; } public final void setAddress(Address address) { this.address = address; } @Override public String toString() { return "BusnessDetail [email=" + email + ", password=" + password + ", businessName=" + businessName + ", contactFirstName=" + contactFirstName + ", contactLastName=" + contactLastName + ", phoneNumber=" + phoneNumber + ", address=" + address + "]"; } } <file_sep>/hibernate/src/main/java/com/jpa/hibernate/PrivateCar.java package com.jpa.hibernate; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class PrivateCar extends Car { @Override public void setWeells(long weells) { this.weells = 4; } } <file_sep>/hibernate/src/main/java/com/jpa/hibernate/Car.java package com.jpa.hibernate; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; @Entity //This style normalized the in heritance @Inheritance(strategy=InheritanceType.JOINED) public class Car { @Id @GeneratedValue(strategy=GenerationType.TABLE) private int id; protected long lisense; protected long weells; protected int door; @Column(name = "MANUFACTURE_NAME") protected String manufacturerName; public long getLisense() { return lisense; } public void setLisense(long lisense) { this.lisense = lisense; } public long getWeells() { return weells; } public void setWeells(long weells) { this.weells = weells; } public int getDoor() { return door; } public void setDoor(int door) { this.door = door; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getManufacturerName() { return manufacturerName; } public void setManufacturerName(String manufacturerName) { this.manufacturerName = manufacturerName; } } <file_sep>/carkyp/src/MongoApp.java import static org.springframework.data.mongodb.core.query.Criteria.where; import static org.springframework.data.mongodb.core.query.Update.update; import static org.springframework.data.mongodb.core.query.Query.query; import static org.springframework.data.mongodb.core.aggregation.Aggregation.group; import static org.springframework.data.mongodb.core.aggregation.Aggregation.match; import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation; import static org.springframework.data.mongodb.core.aggregation.Aggregation.project; import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.apache.catalina.tribes.util.UUIDGenerator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; import org.springframework.data.mongodb.core.aggregation.MatchOperation; import org.springframework.data.mongodb.core.index.Index; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.CriteriaDefinition; import org.springframework.data.mongodb.core.query.Order; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import static org.springframework.data.mongodb.core.aggregation.Aggregation.*; import com.carkyp.UseRoleStatus; import com.carkyp.UserAccountStatus; import com.carkyp.domain.Role; import com.carkyp.domain.UserDetails; import com.carkyp.domain.UserProfile; import com.carkyp.domain.carReservation; import com.carkyp.service.UserService; import com.carkyp.serviceprovider.domain.ServiceProviderProfile; import com.mongodb.Mongo; import com.mongodb.WriteResult; public class MongoApp { // private static final Log log = LogFactory.getLog(MongoApp.class); public static void main(String[] args) throws Exception { // DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy"); // DateTime startdate= formatter.parseDateTime("01/01/1996"); // DateTime endDate = formatter.parseDateTime("01/06/1997"); // MongoOperations mongoOps = new MongoTemplate(new Mongo(), "carkyp"); mongoOps.findAndModify(new Query(new Criteria().andOperator( Criteria.where("id").is("5744bb66b6e3a3fa988aeec7"), Criteria.where("additionalPrice").elemMatch(Criteria.where("name").is("fff")) )),update("additionalPrice.$.price",10), ServiceProviderProfile.class); // System.out.println("print!!!!!!!! = " + p.get(0)); // // Query.query(Criteria.where("id").is("5744b915b6e37363f8f505a2"). // and("additionalPrice.name").is("fff")), // new Update().set("additionalPrice.price", "10"), ServiceProviderProfile.class); // ServiceProviderProfile p = mongoOps.findOne( // new Query( Criteria.where("_id").is("5744b915b6e37363f8f505a2")), // Criteria.where("additionalPrice").elemMatch(Criteria.where("additionalName").is("fff"))), // ServiceProviderProfile.class); // // new Update().set("price", "10"), // mongoOps.findOne( // Query.query(Criteria.where("_id").is("57381738b6e3d7c3db241ae5")) // ,ServiceProviderProfile.class); // new Update().set("additionalPrice.price", "10"), ServiceProviderProfile.class); // mongoOps.indexOps(UserProfile.class).ensureIndex(new Index().on("username",Order.ASCENDING)); /* Aggregation aggregation = newAggregation( unwind("priceDetails"), match(Criteria.where("priceDetails.serviceType").is("60000") .and("priceDetails.carBrand").is("ford") .and("priceDetails.carModel").is("Exploerer Tgi")), group("priceDetails.serviceType","priceDetails.carBrand","priceDetails.carModel").avg("priceDetails.price").as("avarage") .min("priceDetails.price").as("minPrice") .max("priceDetails.price").as("maxPrice")); // sort(Sort.Direction.ASC, previousOperation(), "brand") // ); AggregationResults<PriceSummary> groupResults = mongoOps.aggregate( aggregation, ServiceProviderProfile.class, PriceSummary.class); List salesReport = groupResults.getMappedResults(); System.out.println(salesReport); */ // mongoOps.indexOps(UserProfile.class).ensureIndex(new Index().on("username",Order.ASCENDING)); // Aggregation agg = newAggregation( // // unwind("careReservation"), // match(Criteria.where("careReservation.reservationDate").gte(startdate).lt(endDate).and("_id").is("<EMAIL>") // ), // project("careReservation.reservationDate","careReservation.clientDetail","careReservation.carDetail","careReservation.serviceType") // .and("providerId").previousOperation(), // // sort(Sort.Direction.DESC, "careReservation.reservationDate") // // ); // // AggregationResults<CarReservation> groupResults = mongoOps.aggregate(agg, ServiceProviderProfile.class, CarReservation.class); //List<CarReservation> result = groupResults.getMappedResults(); // //for(CarReservation n:result ) // System.out.println(n); //// List<Object> aggregationOperations = new ArrayList<>(); //// aggregationOperations.add(MatchOperation.(query(where("careReservation.reservationDate").gte(startdate).lt(endDate) //// .and("_id").is("markovich.odedgmail.com"))) //// ////// System.out.println(mongoOps.find(query(where("careReservation.reservationDate").gte(startdate).lt(endDate) ////// .and("_id").is("markovich.odedgmail.com")), ServiceProviderProfile.class)); //// // mongoOps.findOne(query(where("age").is(33)), ServiceProviderProfile.class); ////// System.out.println( mongoOps ////// .updateFirst( new Query(where("userDetail.emailaddress").is(ua.getUserDetail().getEmailaddress()).and("token").is(ua.getToken())) , ////// Update.update("status", UserAccountStatus.STATUS_APPROVED.name()),UserAccount.class)); ////// //// // // // mongoOps.dropCollection("person"); } }<file_sep>/carkyp/src/com/carkyp/service/provider/events/clientProfileRegistrationEvent.java package com.carkyp.service.provider.events; import java.util.TimeZone; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import scala.Immutable; import com.carkyp.domain.ClientProfile; import com.carkyp.domain.UserProfile; import com.carkyp.service.email.model.MailRequest; import com.carkyp.utilities.Clonner; public class clientProfileRegistrationEvent implements Immutable{ final private DateTime eventDate; final private ClientProfile clientProfile; final private MailRequest mailRequest; public clientProfileRegistrationEvent( ClientProfile clientProfile,MailRequest mailRequest){ eventDate = new DateTime(DateTimeZone.forTimeZone(TimeZone.getDefault())); this.clientProfile = Clonner.clone(clientProfile); this.mailRequest = Clonner.clone(mailRequest); } public final DateTime getEventDate() { return eventDate; } public final ClientProfile getClientProfile() { return Clonner.clone(clientProfile); } public final MailRequest getMailRequest() { return Clonner.clone(mailRequest); } }<file_sep>/carkyp/src/com/carkyp/serviceprovider/domain/BusinessFacilitiesInternal.java package com.carkyp.serviceprovider.domain; import org.springframework.data.annotation.Id; public class BusinessFacilitiesInternal { private String id; private String facilitiesName; public final String getId() { return id; } public final void setId(String id) { this.id = id; } public final String getFacilitiesName() { return facilitiesName; } public final void setFacilitiesName(String facilitiesName) { this.facilitiesName = facilitiesName; } } <file_sep>/carkyp/src/com/carkyp/serviceprovider/domain/BusinessOpenHour.java package com.carkyp.serviceprovider.domain; import java.util.List; public class BusinessOpenHour { private String startWeekDay; private String endWeekDay; private String startTime; private String endTime; public BusinessOpenHour(){} public BusinessOpenHour(String startWeekDay, String endWeekDay, String startTime, String endTime) { super(); this.startWeekDay = startWeekDay; this.endWeekDay = endWeekDay; this.startTime = startTime; this.endTime = endTime; } public final String getStartWeekDay() { return startWeekDay; } public final void setStartWeekDay(String startWeekDay) { this.startWeekDay = startWeekDay; } public final String getEndWeekDay() { return endWeekDay; } public final void setEndWeekDay(String endWeekDay) { this.endWeekDay = endWeekDay; } public final String getStartTime() { return startTime; } public final void setStartTime(String startTime) { this.startTime = startTime; } public final String getEndTime() { return endTime; } public final void setEndTime(String endTime) { this.endTime = endTime; } @Override public String toString() { return "BusinessOpenHour [startWeekDay=" + startWeekDay + ", endWeekDay=" + endWeekDay + ", startTime=" + startTime + ", endTime=" + endTime + "]"; } } <file_sep>/carkyp/src/com/carkyp/service/provider/events/ProviderAccountRegistrationEvent.java package com.carkyp.service.provider.events; import java.util.TimeZone; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import scala.Immutable; import com.carkyp.domain.UserProfile; import com.carkyp.service.email.model.MailRequest; import com.carkyp.serviceprovider.domain.BusinessAccount; import com.carkyp.serviceprovider.domain.ServiceProviderProfile; import com.carkyp.utilities.Clonner; public class ProviderAccountRegistrationEvent implements Immutable{ final private DateTime eventDate; final private ServiceProviderProfile serviceproviderProfile; final private MailRequest mailRequest; public ProviderAccountRegistrationEvent( ServiceProviderProfile providerProfile,MailRequest mailRequest){ eventDate = new DateTime(DateTimeZone.forTimeZone(TimeZone.getDefault())); this.serviceproviderProfile = Clonner.clone(providerProfile); this.mailRequest = Clonner.clone(mailRequest); } public final DateTime getEventDate() { return eventDate; } public final ServiceProviderProfile getServiceproviderProfile() { return serviceproviderProfile; } public final MailRequest getMailRequest() { return mailRequest; } @Override public String toString() { return "ProviderAccountRegistrationEvent [eventDate=" + eventDate + ", serviceproviderProfile=" + serviceproviderProfile + ", mailRequest=" + mailRequest + "]"; } }<file_sep>/carkyp/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>carkyp</groupId> <artifactId>carkyp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <build> <sourceDirectory>src</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-bom</artifactId> <version>1.10.43</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.maxmind.geoip2</groupId> <artifactId>geoip2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>4.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>4.0.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.2.3</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>uk.com.robust-it</groupId> <artifactId>cloning</artifactId> <version>1.8.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.2.Final</version> </dependency> <dependency> <groupId>org.glassfish</groupId> <artifactId>javax.el</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.9.1.RELEASE</version> </dependency> <dependency> <groupId>com.typesafe.akka</groupId> <artifactId>akka-actor_2.10</artifactId> <version>2.3.9</version> </dependency> </dependencies> </project><file_sep>/carkyp/src/com/carkyp/domain/RetriveCarReservation.java package com.carkyp.domain; import java.util.Date; import org.joda.time.DateTime; public class RetriveCarReservation { private String starDate; private String endDate; private String mailId; public final String getStarDate() { return starDate; } public final void setStarDate(String starDate) { this.starDate = starDate; } public final String getEndDate() { return endDate; } public final void setEndDate(String endDate) { this.endDate = endDate; } public final String getMailId() { return mailId; } public final void setMailId(String mailId) { this.mailId = mailId; } @Override public String toString() { return "RetriveCarReservation [starDate=" + starDate + ", endDate=" + endDate + ", mailId=" + mailId + "]"; } } <file_sep>/carkyp/src/com/carkyp/service/email/events/MailRequestEvent.java //package com.carkyp.service.email.events; // //import java.io.Serializable; //import java.util.TimeZone; // //import org.joda.time.DateTime; //import org.joda.time.DateTimeZone; // //import com.carkyp.service.email.model.MailRequest; //import com.carkyp.utilities.Clonner; // //import scala.Immutable; // // //public class MailRequestEvent implements Immutable{ // // final private DateTime eventDate; // final private MailRequest mail; // // public MailRequestEvent( MailRequest mail){ // eventDate = new DateTime(DateTimeZone.forTimeZone(TimeZone.getDefault())); // this.mail = Clonner.clone(mail); // } // // public final DateTime getEventDate() { // return eventDate; // } // // public final MailRequest getMail() { // return Clonner.clone(mail); // } // // //} <file_sep>/carkyp/src/com/carkyp/serviceprovider/domain/CarServiceType.java package com.carkyp.serviceprovider.domain; import java.util.List; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.annotation.Id; @Document public class CarServiceType { @Id private String Id; private String serviceName; public final String getId() { return Id; } public final void setId(String id) { Id = id; } public final String getServiceName() { return serviceName; } public final void setServiceName(String serviceName) { this.serviceName = serviceName; } @Override public String toString() { return "CarServiceType [Id=" + Id + ", serviceName=" + serviceName + "]"; } } <file_sep>/carkyp/src/carkyp.properties mail.confirmationUrl=http://localhost:8081/carkyp/rest/regitrationConfirm mail.subject=carKyp Registration Confirmation mail.sender=<EMAIL><file_sep>/Anangular-TUTExample/WebContent/js/appJQ.js $('#plist').ready(function(){ var p = $('#splace'); var offset=p.offset(); $('#plist').offset({ top: offset.top + 50, left: offset.left + 200 }); /* var plp = $('#plist'); var pp = plp.position(); alert('list top = ' + pp.top + 'list left = ' +pp.left); */ });<file_sep>/carkyp/src/com/carkyp/serviceprovider/domain/ServiceProviderTypeInternal.java package com.carkyp.serviceprovider.domain; import org.springframework.data.annotation.Id; public class ServiceProviderTypeInternal { private String id; private String name; public ServiceProviderTypeInternal(){} public final String getId() { return id; } public final void setId(String id) { this.id = id; } public final String getName() { return name; } public final void setName(String name) { this.name = name; } public ServiceProviderTypeInternal(String id, String name) { super(); this.id = id; this.name = name; } } <file_sep>/carkyp/src/com/carkyp/config/AppConfig.java package com.carkyp.config; import static com.carkyp.config.akka.SpringExtension.SpringExtProvider; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSenderImpl; //import static config.akka.SpringExtension.SpringExtProvider; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.aspectj.EnableSpringConfigured; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import akka.actor.ActorSystem; @EnableWebMvc @Configuration @PropertySource(value="classpath:carkyp.properties") @EnableSpringConfigured @ComponentScan(basePackages={"com.carkyp.controllers","com.carkyp.service","com.carkyp.useraccount.repository", "com.carkyp.admin.repositories"}) //@Import({ SecurityConfig.class }) public class AppConfig { @Autowired private ApplicationContext applicationContext; public AppConfig(){ System.out.println("AppConfig!!!!!!!!!!!!!!!!!!!!!"); } @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } /** * Actor system singleton for this application. */ @Bean (name="ActorSystem") public ActorSystem actorSystem() { System.out.println("system issssssssssssssssssssssssss" ); try { ActorSystem system = ActorSystem.create("AkkaJavaSpring"); System.out.println("system issssssssssssssssssssssssss2222222222" ); // initialize the application context in the Akka Spring Extension SpringExtProvider.get(system).initialize(applicationContext); return system; } catch (Exception e) { System.err.println("ActorSystem initialized exception: " + e); } System.err.println("no exception!!!!!!!!!!!!!!!!!!!!" ); return null; } }<file_sep>/carkyp/src/com/carkyp/useraccount/repository/ServiceProviderProfileRepositoryCustom.java package com.carkyp.useraccount.repository; import java.util.List; import com.carkyp.controllers.domain.CarReservationDetails; import com.carkyp.controllers.domain.PlateNumberdetails; import com.carkyp.controllers.domain.PriceDetailSummary; import com.carkyp.controllers.domain.PriceDetailSummaryQuery; import com.carkyp.domain.CarReservationObjects; import com.carkyp.domain.PriceDetail; import com.carkyp.domain.RetriveCarReservation; import com.carkyp.domain.UserProfile; import com.carkyp.domain.carReservation; import com.carkyp.service.provideraccount.model.AdditionallDetails; import com.carkyp.serviceprovider.domain.Additional; import com.carkyp.serviceprovider.domain.CarCareReservation; interface ServiceProviderProfileRepositoryCustom { public Boolean addCarReservation(carReservation carReservation); List<CarReservationDetails> retriveReservationDetails(RetriveCarReservation query); public Boolean updateCarDetails(PlateNumberdetails carDetail); public Boolean SetCarecarePriceDetail(PriceDetail priceDetail); public PriceDetailSummary getPriceDetailsSummery(PriceDetailSummaryQuery qury); public void setAdditionals(AdditionallDetails additional); public void updateAdditionals(AdditionallDetails additional); } <file_sep>/hibernate/src/main/java/com/jpa/hibernate/Subscriber.java package com.jpa.hibernate; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.hibernate.annotations.IndexColumn; @Entity @Table(name="SUBSCRIBER") public class Subscriber { @Id @SequenceGenerator(name = "sub_gen",sequenceName="sub_seq") @GeneratedValue(strategy=GenerationType.TABLE,generator="sub_gen") @Column(name="ID") private int id; @Column(name="SUBSCRIBER_NAME") private String name; @OneToMany(cascade=CascadeType.PERSIST) private Collection<Car> carList = new ArrayList<Car>(); public Collection<Car> getCarList() { return carList; } public void setCarList(Collection<Car> carList) { this.carList = carList; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/carkyp/src/com/carkyp/sequrity/config/MvcWebApplicationInitializer.java package com.carkyp.sequrity.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import com.caekyp.config.mongo.MongoConfig; import com.carkyp.config.AppConfig; //import config.mongo.MongoConfig; public class MvcWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { SecurityConfig.class, WebConfig.class ,AppConfig.class,MongoConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { // TODO Auto-generated method stub return null; } @Override protected String[] getServletMappings() { // TODO Auto-generated method stub return new String[] { "/" }; } // ... other overrides ... }<file_sep>/carkyp/src/com/carkyp/service/provideraccount/model/BusinessAccount.java package com.carkyp.service.provideraccount.model; import java.util.List; import org.hibernate.validator.constraints.NotEmpty; import com.carkyp.controllers.domain.ServiceProvidedBrand; import com.carkyp.serviceprovider.domain.BusinessInformation; import com.carkyp.serviceprovider.domain.BusinessOpenHour; public class BusinessAccount { private String Id; private BusnessDetail businessDetail; @NotEmpty private String serviceProvidrTypeId; @NotEmpty private List<String> serviceProvidedId; //@NotEmpty private BusinessInformation businessInformation; //@NotEmpty private BusinessOpenHour businessopenHour; @NotEmpty private List<String> businessFacilitiesname; @NotEmpty private List<ServiceProvidedBrand> serviceProvidedBrands; public BusinessAccount(){} public final String getId() { return Id; } public final void setId(String id) { Id = id; } public final BusnessDetail getBusinessDetail() { return businessDetail; } public final void setBusinessDetail(BusnessDetail businessDetail) { this.businessDetail = businessDetail; } public final BusinessInformation getBusinessInformation() { return businessInformation; } public final void setBusinessInformation(BusinessInformation businessInformation) { this.businessInformation = businessInformation; } public final BusinessOpenHour getBusinessopenHour() { return businessopenHour; } public final void setBusinessopenHour(BusinessOpenHour businessopenHour) { this.businessopenHour = businessopenHour; } public final List<String> getBusinessFacilitiesname() { return businessFacilitiesname; } public final void setBusinessFacilitiesname(List<String> businessFacilitiesname) { this.businessFacilitiesname = businessFacilitiesname; } public final List<ServiceProvidedBrand> getServiceProvidedBrands() { return serviceProvidedBrands; } public final void setServiceProvidedBrands( List<ServiceProvidedBrand> serviceProvidedBrands) { this.serviceProvidedBrands = serviceProvidedBrands; } public final String getServiceProvidrTypeId() { return serviceProvidrTypeId; } public final void setServiceProvidrTypeId(String serviceProvidrTypeId) { this.serviceProvidrTypeId = serviceProvidrTypeId; } public final List<String> getServiceProvidedId() { return serviceProvidedId; } public final void setServiceProvidedId(List<String> serviceProvidedId) { this.serviceProvidedId = serviceProvidedId; } @Override public String toString() { return "BusinessAccount [Id=" + Id + ", businessDetail=" + businessDetail + ", serviceProvidrTypeId=" + serviceProvidrTypeId + ", serviceProvidedId=" + serviceProvidedId + ", businessInformation=" + businessInformation + ", businessopenHour=" + businessopenHour + ", businessFacilitiesname=" + businessFacilitiesname + ", serviceProvidedBrands=" + serviceProvidedBrands + "]"; } } <file_sep>/carkyp/src/com/carkyp/serviceprovider/domain/OpenHour.java package com.carkyp.serviceprovider.domain; public class OpenHour { private String openhourday; private String endHourday; public final String getOpenhourday() { return openhourday; } public final void setOpenhourday(String openhourday) { this.openhourday = openhourday; } public final String getEndHourday() { return endHourday; } public final void setEndHourday(String endHourday) { this.endHourday = endHourday; } public OpenHour(String openhourday, String endHourday) { super(); this.openhourday = openhourday; this.endHourday = endHourday; } public OpenHour(){} } <file_sep>/carkyp/src/com/carkyp/sequrity/config/WebConfig.java //package sequrity.config; // //import org.springframework.beans.factory.annotation.Autowired; // //import org.springframework.context.annotation.*; //import org.springframework.security.config.annotation.authentication.builders.*; //import org.springframework.security.config.annotation.web.configuration.*; // //@EnableWebSecurity //public class SecurityConfig extends WebSecurityConfigurerAdapter { // // @Autowired // public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // // // auth // .inMemoryAuthentication() // .withUser("user").password("<PASSWORD>").roles("USER"); // } //} package com.carkyp.sequrity.config; import java.util.List; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.web.client.HttpMessageConverterExtractor; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter{ @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { // configurer.ignoreAcceptHeader(true).defaultContentType( // MediaType.APPLICATION_JSON); configurer.favorPathExtension(false). favorParameter(true). parameterName("mediaType"). ignoreAcceptHeader(true). useJaf(false). defaultContentType(MediaType.APPLICATION_JSON). mediaType("xml", MediaType.APPLICATION_XML). mediaType("json", MediaType.APPLICATION_JSON); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("/"); } }<file_sep>/carkyp/src/com/carkyp/controllers/domain/ServiceProvidedBrand.java package com.carkyp.controllers.domain; import org.springframework.data.mongodb.core.index.Indexed; public class ServiceProvidedBrand { private String brandGroup; private String seviceProvidedName; public final String getBrandGroup() { return brandGroup; } public final void setBrandGroup(String brandGroup) { this.brandGroup = brandGroup; } public final String getSeviceProvidedName() { return seviceProvidedName; } public final void setSeviceProvidedName(String seviceProvidedName) { this.seviceProvidedName = seviceProvidedName; } @Override public String toString() { return "ServiceProvidedBrand [brandGroup=" + brandGroup + ", seviceProvidedName=" + seviceProvidedName + "]"; } } <file_sep>/carkyp/src/com/carkyp/service/email/MailServiceActor.java //package com.carkyp.service.email; // //import org.springframework.beans.factory.annotation.Autowired; // // // // //import com.carkyp.service.email.events.MailRequestEvent; // //import akka.actor.ActorRef; //import akka.actor.Props; //import akka.actor.Terminated; //import akka.actor.UntypedActor; //import akka.actor.UntypedActorContext; // //public class MailServiceActor extends UntypedActor{ // // @Autowired // SendMailInterface sendMailService; // final ActorRef child = // getContext().actorOf(Props.create(SendMailServiceActor.class), "myChild"); // { // this.getContext().watch(child); // } // // ActorRef lastSender = getContext().system().deadLetters(); // // // @Override // public void onReceive(Object arg0) throws Exception { // if(arg0 instanceof MailRequestEvent){ // System.out.println("send mail in MailServiceActor!!!"); // child.tell(((MailRequestEvent) arg0).getMail(),getSelf() ); // }else if (arg0 instanceof Terminated) { // System.out.println("Termination recived!!!"); // final Terminated t = (Terminated) arg0; // if (t.getActor() == child) { // getContext().stop(child); // } // } // } // // @Override // public void preStart() throws Exception { // System.err.println("MailServiceActor preStart has called!!!!"+ System.currentTimeMillis()); // } // // public void preRestart(Throwable reason, scala.Option<Object> message) { // System.err.println("MailServiceActor preRestart has called!!!!"); // for (ActorRef each : getContext().getChildren()) { // getContext().unwatch(each); // getContext().stop(each); // } // postStop(); // } // // public void postRestart(Throwable reason) throws Exception { // System.err.println("MailServiceActor postRestart has called!!!!"); // preStart(); // } // // public void postStop() { // System.err.println("MailServiceActor postStop has called!!!!"); // } //} <file_sep>/carkyp/src/com/carkyp/admin/repositories/SreviceProviderTypeRepository.java package com.carkyp.admin.repositories; import org.springframework.data.mongodb.repository.MongoRepository; import com.carkyp.domain.UserProfile; import com.carkyp.serviceprovider.domain.ServiceProvided; import com.carkyp.serviceprovider.domain.SreviceProviderType; public interface SreviceProviderTypeRepository extends MongoRepository<SreviceProviderType, String>{ } <file_sep>/carkyp/src/com/carkyp/useraccount/repository/UserProfileRepositoryImpl.java package com.carkyp.useraccount.repository; import static org.springframework.data.mongodb.core.query.Criteria.where; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import com.carkyp.UserAccountStatus; import com.carkyp.domain.UserProfile; import com.mongodb.WriteResult; class UserProfileRepositoryImpl implements UserProfileRepositoryCustom { @Autowired private MongoTemplate mt; @Override public Boolean activateAccount(String tokeniD) { MongoOperations mongoOps = mt; WriteResult wr = mongoOps .updateFirst( new Query(where("token").is(tokeniD)) , Update.update("status", UserAccountStatus.STATUS_APPROVED.name()),UserProfile.class); if(wr.isUpdateOfExisting()) return Boolean.TRUE; return Boolean.FALSE; } } <file_sep>/carkyp/src/com/carkyp/serviceprovider/domain/PriceDetail.java package com.carkyp.serviceprovider.domain; public class PriceDetail { private String serviceType; private String carBrand; private String carModel; private Double price; public PriceDetail(){} public PriceDetail(String serviceType, String carBrand, String carModel, Double price) { super(); this.serviceType = serviceType; this.carBrand = carBrand; this.carModel = carModel; this.price = price; } public final String getServiceType() { return serviceType; } public final void setServiceType(String serviceType) { this.serviceType = serviceType; } public final String getCarBrand() { return carBrand; } public final void setCarBrand(String carBrand) { this.carBrand = carBrand; } public final String getCarModel() { return carModel; } public final void setCarModel(String carModel) { this.carModel = carModel; } public final Double getPrice() { return price; } public final void setPrice(Double price) { this.price = price; } @Override public String toString() { return "PriceDetail [serviceType=" + serviceType + ", carBrand=" + carBrand + ", carModel=" + carModel + ", Price=" + price + "]"; } } <file_sep>/carkyp/src/com/carkyp/service/ProviderService.java package com.carkyp.service; import java.awt.font.TextLayout.CaretPolicy; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import com.carkyp.controllers.domain.CarReservationDetails; import com.carkyp.controllers.domain.PlateNumberdetails; import com.carkyp.controllers.domain.PriceDetailSummary; import com.carkyp.controllers.domain.PriceDetailSummaryQuery; import com.carkyp.domain.CarReservationObjects; import com.carkyp.domain.PriceDetail; import com.carkyp.domain.RetriveCarReservation; import com.carkyp.domain.carReservation; import com.carkyp.service.provideraccount.model.AdditionallDetails; import com.carkyp.service.provideraccount.model.ServiceProviderDetails; import com.carkyp.serviceprovider.domain.ServiceProviderProfile; import com.carkyp.useraccount.repository.ServiceProviderProfileRepository; @Service public class ProviderService { @Autowired private ServiceProviderProfileRepository serviceProviderProfile; public void addCarReservation(carReservation reservation){ Assert.notNull(reservation); serviceProviderProfile.addCarReservation(reservation); } public List<CarReservationDetails> retriveCarReservationDetails(RetriveCarReservation reservation){ Assert.notNull(reservation); List<CarReservationDetails> reservationDetails= serviceProviderProfile.retriveReservationDetails(reservation); return reservationDetails; } public Boolean updateCarDetails(PlateNumberdetails carDetail) { Assert.notNull(carDetail); return serviceProviderProfile.updateCarDetails(carDetail); } public Boolean insertCarProviderPriceDetail(PriceDetail pricaDetaill){ Assert.notNull(pricaDetaill); return serviceProviderProfile.SetCarecarePriceDetail(pricaDetaill); } public PriceDetailSummary getPriceDetailSummery(PriceDetailSummaryQuery pricaDetaillSumQuey){ Assert.notNull(pricaDetaillSumQuey); return serviceProviderProfile.getPriceDetailsSummery(pricaDetaillSumQuey); } public void addAditinalPriceDetail(AdditionallDetails additionals){ Assert.notNull(additionals); serviceProviderProfile.setAdditionals(additionals); } public void updateAditinalPriceDetail(AdditionallDetails additionals){ Assert.notNull(additionals); serviceProviderProfile.updateAdditionals(additionals); } public ServiceProviderDetails retriveProviderInformation(String providerid){ ServiceProviderProfile providerProfile = serviceProviderProfile.findOne(providerid); ServiceProviderDetails providerDeatils = new ServiceProviderDetails(); providerDeatils.setEmail(providerProfile.getEmail()); providerDeatils.setAdditionalPrice(providerProfile.getAdditionalPrice()); providerDeatils.setBusinessAccount(providerProfile.getBusinessAccount()); providerDeatils.setCareReservation(providerProfile.getCareReservation()); providerDeatils.setPriceDetails(providerProfile.getPriceDetails()); return providerDeatils; } } <file_sep>/carkyp/src/com/carkyp/admin/repositories/BusinessFacilitiesRepository.java package com.carkyp.admin.repositories; import org.springframework.data.mongodb.repository.MongoRepository; import com.carkyp.serviceprovider.domain.BusinessFacilities; import com.carkyp.serviceprovider.domain.ServiceProvidedBrand; public interface BusinessFacilitiesRepository extends MongoRepository<BusinessFacilities, String>{ }<file_sep>/libraryModel/src/main/resources/application.properties spring.datasource.url=jdbc:mysql://localhost:3306/personLibrary spring.datasource.username=root spring.datasource.password=<PASSWORD> spring.datasource.driverClassName=com.mysql.jdbc.Driver<file_sep>/carkyp/src/com/carkyp/serviceprovider/domain/CarCareReservation.java package com.carkyp.serviceprovider.domain; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; public class CarCareReservation { private Clientdetail clientDetail; private DateTime reservationDate; private CarDetail carDetail; private List<Additional> additional; private PriceDetail priceDetail; private String serviceType; public CarCareReservation(){} public CarCareReservation(Clientdetail clientDetail, String reservationDate, CarDetail carDetail, List<Additional> additional, PriceDetail priceDetail) { super(); DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH"); this.reservationDate = formatter.parseDateTime(reservationDate); this.clientDetail = clientDetail; this.carDetail = carDetail; this.additional = additional; this.priceDetail = priceDetail; } public final Clientdetail getClientDetail() { return clientDetail; } public final void setClientDetail(Clientdetail clientDetail) { this.clientDetail = clientDetail; } public final DateTime getReservationDate() { return reservationDate; } public final void setReservationDate(String reservationDate) { DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm"); this.reservationDate = formatter.parseDateTime(reservationDate); } public final CarDetail getCarDetail() { return carDetail; } public final void setCarDetail(CarDetail carDetail) { this.carDetail = carDetail; } public final List<Additional> getAdditional() { return additional; } public final void setAdditional(List<Additional> additional) { this.additional = additional; } public final PriceDetail getPriceDetail() { return priceDetail; } public final void setPriceDetail(PriceDetail priceDetail) { this.priceDetail = priceDetail; } public final String getServiceType() { return serviceType; } public final void setServiceType(String serviceType) { this.serviceType = serviceType; } @Override public String toString() { return "CarCareReservation [clientDetail=" + clientDetail + ", reservationDate=" + reservationDate + ", carDetail=" + carDetail + ", additional=" + additional + ", priceDetail=" + priceDetail + "]"; } }
c5c6a8b9405e4886e357f5f01b538d58e4b40991
[ "JavaScript", "Java", "Maven POM", "INI" ]
32
Java
odedmar/Git
89384adf2512c735ccb0fd984a6c88d8ec91b2a8
c9866216a87303a6ba8731f5e5794559c0b5514c
refs/heads/master
<repo_name>Aviadh148/22-7-2019<file_sep>/Targil2/timectrl.js // also works // angular.module("myTimerApp").controller("timeCtrl", () => { alert("hello from time controller")}) //module.controller("timeCtrl", () => { alert("hello from time controller")}) module.controller("timeCtrl", TimeCtrl) // DI dependency injection - IOC function TimeCtrl($scope) { //alert("hello from time controller") $scope.time = Date.now() $scope.refresh = function(){ $scope.time = Date.now() } }<file_sep>/Targil1/personCtrl.js module.controller("personCtrl", PersonCtrl) // DI dependency injection - IOC function PersonCtrl($scope) { $scope.person = new Person('') $scope.name = '' $scope.age = '' $scope.password = '' $scope.gender = '' $scope.vehicle = '' $scope.bike = false } function PersonFunc(name, age, password, gender, vehicle, Bike) { this.name = name this.age = age this.password = <PASSWORD> this.gender = gender this.vehicle = vehicle this.Bike = Bike } class Person { constructor ({name, age, password, gender, vehicle, bike}) { this._name = name this._age = age this._password = password this._gender = gender this._vehicle = vehicle this._bike = bike this.toString = () => { const {_name, _age, _password, _gender, _vehicle, _bike} = this console.log(`name: ${_name} age: ${_age} password: ${_password} gender: ${_gender} vehicle: ${_vehicle} bike: ${_bike}`) } } set name (name) {this._name = name} get name () {return this._name} set age (age) {this._age = age} get age () {return this._age} set password (password) {this._password = password} get password () {return this._password} set gender (gender) {this._gender = gender} get gender () {return this._gender} set vehicle (vehicle) {this._vehicle = vehicle} get vehicle () {return this._vehicle} set bike (bike) {this._bike = bike} get bike () {return this._bike} } function getPerson(){ let gen= "Other" let isGender= document.getElementsByName("gender") for(let g in isGender){ if (isGender[g].checked){ gen= isGender[g].value } } const per= new Person( { "name": document.getElementById("name").value , "age": document.getElementById("age").value , "password": document.getElementById("password").value , "gender": gen ,// document.getElementsByName("gender").checked.value , "vehicle": document.getElementById("vehicle").value , "bike": document.getElementById("bike").checked }) per.toString() } // const person1 = {name : "Aviad" , age : 25 , password : "<PASSWORD>" , gender : "Male" , vehicle : "KIA" , bike : false} // const person2 = {name : "Tamar" , age : 26 , password : "<PASSWORD>" , gender : "Female" , vehicle : "KIA" , bike : false} // const per1 = new PersonFunc(person1) // const per2 = new Person(person1)
dc03280dc567229a23683bec0c23c5f8d007c330
[ "JavaScript" ]
2
JavaScript
Aviadh148/22-7-2019
3fcc0a91351d8fd82e1690aa389bd01b62872163
67ee15eb83ecb442a220ce0765e83e5b00fd526b
refs/heads/master
<repo_name>STAT545-UBC-hw-2018-19/hw07-RyanGao67<file_sep>/foofactors.Rcheck/00_pkg_src/foofactors/tests/testthat/testnewreorder.R context("my reorder") # test the newreorder r script test_that("expecataion for success", { # first create the orginal factors a1 <- newreorder(factor(c("abandon","bbq","cook"))) b1 <- newreorder(factor(c("1","2","3","4"))) c1 <- newreorder(factor(c("a","s","t","z"))) # the following is the expected factors a2 <-c("cook","bbq","abandon") b2 <- c("4","3","2","1") c2 <- c("z","t","s","a") # Test if the computed and expected is equal expect_equal(levels(a1),a2) expect_equal(levels(b1),b2) expect_equal(levels(c1),c2) }) <file_sep>/foofactors/README.Rmd --- output: md_document: variant: markdown_github --- <!-- README.md is generated from README.Rmd. Please edit that file --> ```{r, echo = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "README-" ) ``` **Note1: This is originally created by jennybc, you can find the original one [here](https://github.com/jennybc/foofactors)** **NOTE2: This is a toy package created for expository purposes. It is not meant to actually be useful. If you want a package for factor handling, please see [forcats](https://cran.r-project.org/package=forcats).** ### foofactors Factors are a very useful type of variable in R, but they can also drive you nuts. This package provides some helper functions for the care and feeding of factors. ### Installation ```{r installation, eval = FALSE} devtools::install_github("STAT545-UBC-students/hw07-RyanGao67/foofactor") ``` ### Package structure - R scripts for functions are under ["R"](./R) - Test scripts are under ["tests"](./tests) - HTML generated by vignettes is ["hello-foofactors.html"](./doc/hello-foofactors.html) ### Quick demo * Binding two factors via `fbind()`: ```{r} library(foofactors) a <- factor(c("character", "hits", "your", "eyeballs")) b <- factor(c("but", "integer", "where it", "counts")) ``` * Simply catenating two factors leads to a result that most don't expect. ```{r} c(a, b) ``` * The `fbind()` function glues two factors together and returns factor. ```{r} fbind(a, b) ``` * Often we want a table of frequencies for the levels of a factor. The base `table()` function returns an object of class `table`, which can be inconvenient for downstream work. Processing with `as.data.frame()` can be helpful but it's a bit clunky. ```{r} set.seed(1234) x <- factor(sample(letters[1:5], size = 100, replace = TRUE)) table(x) as.data.frame(table(x)) ``` * The `freq_out()` function returns a frequency table as a well-named `tbl_df`: ```{r} freq_out(x) ``` * `detect_factors()` * The `fdetect()` function checks if a factor is actually a character, it basicly checks that if a factor has repeated value in which case the factor can be considered as a character ```{r} # This is a factor factor <- factor(c("m","i","s","s","i","s")) # This is a character character <- factor(c("s", "t", "a")) # return TRUE if it is a factor detect_factors(factor) # return FALSE if it is a character detect_factors(character) ``` * `newreorder()` * The `newreorder()` function can reorder the levels of a factor in descending order. ```{r} # create a factor as an example f <- factor(c("a", "b", "c","d")) # the originally order: "a" "b" "c" "d" levels(f) # the reordered order "d" "c" "b" "a" levels(newreorder(f)) ``` * `newfactor()` Set levels of a factor to the order in which they appear in the data. * `newrev()` Set levels of a factor to the reversed order in which they appear in the data. ```{r} # create a factor as an example f <- factor(c("b", "a", "c")) # the originally order of level should be "b" "a" "c" levels(f) # the reset levels should be "b" "a" "c" levels(newfactor(f)) # the reversed levels should be "c" "a" "b" levels(newrev(f)) ``` * `dfwrite()`/`dfread()` Functions `dfwrite()` and `dfread()`: functions to write and read data frames to plain text delimited files while retaining factor levels ```{r} # The basic idea here is that I first introduce a data frame # Then I reorder the data # Then I write the data frame to a file # Then I read the data from the file # Then I compare the data that I created and the data that I fetched from the file dataframe <- data.frame( first = 1, second = 1:100, factor = sample(LETTERS[1:6], 10, replace = TRUE) ) dataframe$factor <- newreorder(dataframe$factor) dfwrite(dataframe, "./test_reorder.csv", "./levels_reorder.txt") fetched <- dfread("./test_reorder.csv", "./levels_reorder.txt") levels(fetched$factor) levels(dataframe$factor) ``` ## References - [Be the boss of your factors](https://www.stat.ubc.ca/~jenny/STAT545A/block08_bossYourFactors.html) <file_sep>/foofactors.Rcheck/tests/testthat/testnewfactors.R test_that("in original order", { # check if function newfactor return the correct order a <- c("s","t","a","z") b <- c("this","is","a","test") c <- c("1","2","3","4") #Set levels of a factor to the order in which they appear in the data. expect_equal(levels(newfactor(factor(a))), a) expect_equal(levels(newfactor(factor(b))), b) expect_equal(levels(newfactor(factor(c))), c) }) test_that("in reversed order", { # check if function newrev return the correct order a <- c("s","t","a","z") b <- c("this","is","a","test") c <- c("1","2","3","4") #Set levels of a factor to the reversed order in which they appear in the data. expect_equal(levels(newrev(factor(a))), c("z","a","t","s")) expect_equal(levels(newrev(factor(b))), c("test","a","is","this")) expect_equal(levels(newrev(factor(c))), c("4","3","2","1")) }) <file_sep>/foofactors/tests/testthat/test_freq_out.R context("frequency table for a factor") test_that("expectation for success", { expect_equal(freq_out(factor(mtcars$cyl))$n, c(11,7,14)) expect_equal(freq_out(factor(iris$Species))$n, c(50,50,50)) }) <file_sep>/foofactors.Rcheck/00_pkg_src/foofactors/R/newfactors.R #' @title Set the levels "as is" #' #' @description Set levels of a factor to the order in which they appear in the data. #' #' @usage #' newfactor(f) #' #' @param f a factor. #' #' @return #' a factor with levels in the order of f. #' If the input is not a factor, the function will raise an error #' #' @examples #' newfactor(factor(c("s", "t", "a"))) # Levels: s t a #' #' @export #' #' newfactor <- function(x){ if(!is.factor(x))stop('Please enter a factor!\n','You entered: ', class(x)[1]) return(factor(x, as.character(unique(x)))) } #' @title Set the levels reversed #' #' @description #' Set levels of a factor to the reversed order in which they appear in the data. #' #' @param f a factor #' #' @return a factor with levels in the reverse order appeared in x. #' @export #' #' @examples newrev(factor(c("s","t","a","t"))) newrev <- function(x){ if(!is.factor(x))stop('Please enter a factor!\n','You entered: ', class(x)[1]) return(factor(x, rev(as.character(unique(x))))) } <file_sep>/README.md TAT 545A Homework 07 Repo owned by Tian **Homework 07** Navigation of the repo: * Package `foofactor`: * You can take a look at the functions code and tests code in [foofactors directory](./foofactors) * A quick installation guide: `devtools::install_github("STAT545-UBC-students/hw07-RyanGao67/foofactors")' * For more details, please refer to its [README](./foofactors/README.md). <file_sep>/foofactors/R/newreorder.R #' @title descend a factor #' #' @description A new version of reorder that uses desc #' #' @usage newreorder(f) #' #' This function give you the ability to sort your factors in descending order. #' #' @param x a factor or a vector #' @return a factor #' #' @examples newreorder(factor(c("s","t","a"))) #' #' @export #' newreorder <- function(x){ # check if the input is factor if(!is.factor(x))stop('Please enter a factor!\n', 'You input a: ', class(x)[1]) # decend the factor return(stats::reorder(x, dplyr::desc(x))) } <file_sep>/foofactors/README.md <!-- README.md is generated from README.Rmd. Please edit that file --> **Note1: This is originally created by jennybc, you can find the original one [here](https://github.com/jennybc/foofactors)** **NOTE2: This is a toy package created for expository purposes. It is not meant to actually be useful. If you want a package for factor handling, please see [forcats](https://cran.r-project.org/package=forcats).** ### foofactors Factors are a very useful type of variable in R, but they can also drive you nuts. This package provides some helper functions for the care and feeding of factors. ### Installation ``` r devtools::install_github("STAT545-UBC-students/hw07-RyanGao67/foofactor") ``` ### Package structure - R scripts for functions are under [“R”](./R) - Test scripts are under [“tests”](./tests) - HTML generated by vignettes is [“hello-foofactors.html”](./doc/hello-foofactors.html) ### Quick demo - Binding two factors via `fbind()`: ``` r library(foofactors) a <- factor(c("character", "hits", "your", "eyeballs")) b <- factor(c("but", "integer", "where it", "counts")) ``` - Simply catenating two factors leads to a result that most don’t expect. ``` r c(a, b) #> [1] 1 3 4 2 1 3 4 2 ``` - The `fbind()` function glues two factors together and returns factor. ``` r fbind(a, b) #> [1] character hits your eyeballs but integer where it #> [8] counts #> Levels: but character counts eyeballs hits integer where it your ``` - Often we want a table of frequencies for the levels of a factor. The base `table()` function returns an object of class `table`, which can be inconvenient for downstream work. Processing with `as.data.frame()` can be helpful but it’s a bit clunky. ``` r set.seed(1234) x <- factor(sample(letters[1:5], size = 100, replace = TRUE)) table(x) #> x #> a b c d e #> 25 26 17 17 15 as.data.frame(table(x)) #> x Freq #> 1 a 25 #> 2 b 26 #> 3 c 17 #> 4 d 17 #> 5 e 15 ``` - The `freq_out()` function returns a frequency table as a well-named `tbl_df`: ``` r freq_out(x) #> # A tibble: 5 x 2 #> x n #> <fct> <int> #> 1 a 25 #> 2 b 26 #> 3 c 17 #> 4 d 17 #> 5 e 15 ``` - `detect_factors()` - The `fdetect()` function checks if a factor is actually a character, it basicly checks that if a factor has repeated value in which case the factor can be considered as a character ``` r # This is a factor factor <- factor(c("m","i","s","s","i","s")) # This is a character character <- factor(c("s", "t", "a")) # return TRUE if it is a factor detect_factors(factor) #> [1] TRUE # return FALSE if it is a character detect_factors(character) #> [1] FALSE ``` - `newreorder()` - The `newreorder()` function can reorder the levels of a factor in descending order. ``` r # create a factor as an example f <- factor(c("a", "b", "c","d")) # the originally order: "a" "b" "c" "d" levels(f) #> [1] "a" "b" "c" "d" # the reordered order "d" "c" "b" "a" levels(newreorder(f)) #> [1] "d" "c" "b" "a" ``` - `newfactor()` Set levels of a factor to the order in which they appear in the data. - `newrev()` Set levels of a factor to the reversed order in which they appear in the data. ``` r # create a factor as an example f <- factor(c("b", "a", "c")) # the originally order of level should be "b" "a" "c" levels(f) #> [1] "a" "b" "c" # the reset levels should be "b" "a" "c" levels(newfactor(f)) #> [1] "b" "a" "c" # the reversed levels should be "c" "a" "b" levels(newrev(f)) #> [1] "c" "a" "b" ``` - `dfwrite()`/`dfread()` Functions `dfwrite()` and `dfread()`: functions to write and read data frames to plain text delimited files while retaining factor levels ``` r # The basic idea here is that I first introduce a data frame # Then I reorder the data # Then I write the data frame to a file # Then I read the data from the file # Then I compare the data that I created and the data that I fetched from the file dataframe <- data.frame( first = 1, second = 1:100, factor = sample(LETTERS[1:6], 10, replace = TRUE) ) dataframe$factor <- newreorder(dataframe$factor) dfwrite(dataframe, "./test_reorder.csv", "./levels_reorder.txt") fetched <- dfread("./test_reorder.csv", "./levels_reorder.txt") #> Parsed with column specification: #> cols( #> first = col_integer(), #> second = col_integer(), #> factor = col_character() #> ) levels(fetched$factor) #> [1] "D" "C" "B" "A" levels(dataframe$factor) #> [1] "D" "C" "B" "A" ``` References ---------- - [Be the boss of your factors](https://www.stat.ubc.ca/~jenny/STAT545A/block08_bossYourFactors.html) <file_sep>/foofactors.Rcheck/foofactors-Ex.R pkgname <- "foofactors" source(file.path(R.home("share"), "R", "examples-header.R")) options(warn = 1) options(pager = "console") base::assign(".ExTimings", "foofactors-Ex.timings", pos = 'CheckExEnv') base::cat("name\tuser\tsystem\telapsed\n", file=base::get(".ExTimings", pos = 'CheckExEnv')) base::assign(".format_ptime", function(x) { if(!is.na(x[4L])) x[1L] <- x[1L] + x[4L] if(!is.na(x[5L])) x[2L] <- x[2L] + x[5L] options(OutDec = '.') format(x[1L:3L], digits = 7L) }, pos = 'CheckExEnv') ### * </HEADER> library('foofactors') base::assign(".oldSearch", base::search(), pos = 'CheckExEnv') base::assign(".old_wd", base::getwd(), pos = 'CheckExEnv') cleanEx() nameEx("detect_factors") ### * detect_factors flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: detect_factors ### Title: find if a factor is actually character ### Aliases: detect_factors ### ** Examples detect_factors(factor(c("a","b","a"))) # True detect_factors(factor(c("a","b","c"))) # False base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("detect_factors", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("fbind") ### * fbind flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: fbind ### Title: Bind two factors ### Aliases: fbind ### ** Examples fbind(iris$Species[c(1, 51, 101)], PlantGrowth$group[c(1, 11, 21)]) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("fbind", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("freq_out") ### * freq_out flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: freq_out ### Title: Make a frequency table for a factor ### Aliases: freq_out ### ** Examples freq_out(iris$Species) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("freq_out", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("newfactor") ### * newfactor flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: newfactor ### Title: Set the levels "as is" ### Aliases: newfactor ### ** Examples newfactor(factor(c("s", "t", "a"))) # Levels: s t a base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("newfactor", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("newreorder") ### * newreorder flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: newreorder ### Title: descend a factor ### Aliases: newreorder ### ** Examples newreorder(factor(c("s","t","a"))) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("newreorder", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") cleanEx() nameEx("newrev") ### * newrev flush(stderr()); flush(stdout()) base::assign(".ptime", proc.time(), pos = "CheckExEnv") ### Name: newrev ### Title: Set the levels reversed ### Aliases: newrev ### ** Examples newrev(factor(c("s","t","a","t"))) base::assign(".dptime", (proc.time() - get(".ptime", pos = "CheckExEnv")), pos = "CheckExEnv") base::cat("newrev", base::get(".format_ptime", pos = 'CheckExEnv')(get(".dptime", pos = "CheckExEnv")), "\n", file=base::get(".ExTimings", pos = 'CheckExEnv'), append=TRUE, sep="\t") ### * <FOOTER> ### cleanEx() options(digits = 7L) base::cat("Time elapsed: ", proc.time() - base::get("ptime", pos = 'CheckExEnv'),"\n") grDevices::dev.off() ### ### Local variables: *** ### mode: outline-minor *** ### outline-regexp: "\\(> \\)?### [*]+" *** ### End: *** quit('no') <file_sep>/foofactors/R/readandwrite.R #' @title write data frames to plain text delimited #' #' @description Write data frame to plain text delimited files #' #' @usage writedataframe(dataframe, file, level) #' #' @param dataframe is dataframe #' #' @param file indicates where is the dataframe #' #' @param level is where to store the file #' #' @export dfwrite <- function(dataframe, file, level=NA) { # make sure the input is a factor if (!is.data.frame(dataframe)) stop("Not a data frame ", class(dataframe)[1]) readr::write_csv(dataframe, file) # we need a default level if (is.na(level)) level <- paste0(dirname(file), "/", "levels.txt") dput(lapply(dataframe[names(Filter(is.factor, dataframe))], levels), level) } #' @title read data frames from plain text delimited #' #' @description read data frame from plain text delimited files #' #' @usage readdataframe(file, level) #' #' @param dataframe is dataframe #' #' @param level is where to store the file #' #' @export dfread <- function(file, level = NA) { # write data frame using read_csv() dataframe <- readr::read_csv(file) # check filename for levels if (is.na(level)) level <- paste0(dirname(file), "/", "levels.txt") for (i in seq_along(dget(level))) { # first convert columns to factor dataframe[[names(dget(level)[i])]] <- as.factor(dataframe[[names(dget(level)[i])]]) levels(dataframe[[names(dget(level)[i])]]) <- dget(level)[[i]] } dataframe } <file_sep>/foofactors.Rcheck/00_pkg_src/foofactors/R/readandwrite.R #' @title write data frames to plain text delimited #' #' @description Write data frame to plain text delimited files #' #' @usage writedataframe(dataframe, file, level) #' #' @param dataframe is dataframe #' #' @param file indicates where is the dataframe #' #' @param level is where to store the file #' #' @export dfwrite <- function(df, dffilename, lvfilename = NA) { # check if the input is a factor or not dfcheck <- function(x) { # check if the input is a data frame or not if (!is.data.frame(x)) { stop("Function requires a data frame instead of a ", class(x)[1]) } } # write data frame using write_csv() readr::write_csv(df, dffilename) # get names of columns of factors factor_cols <- names(Filter(is.factor, df)) # check filename for levels if (is.na(lvfilename)) { # use dirname() to get path of filename lvfilename <- paste0(dirname(dffilename), "/", "levels.txt") } # write levels to companion file # use lapply() and levels() to get levels of factor columns dput(lapply(df[factor_cols], levels), lvfilename) } #' @title read data frames from plain text delimited #' #' @description read data frame from plain text delimited files #' #' @usage readdataframe(file, level) #' #' @param dataframe is dataframe #' #' @param level is where to store the file #' #' @export dfread <- function(file, level) { # write data frame using read_csv() ret <- readr::read_csv(dffilename) # check filename for levels if (is.na(lvfilename)) { # use dirname() to get path of filename lvfilename <- paste0(dirname(dffilename), "/", "levels.txt") } # get levels from companion file lvs <- dget(lvfilename) # set levels of data frame for (i in seq_along(lvs)) { # first convert columns to factor ret[[names(lvs[i])]] <- as.factor(ret[[names(lvs[i])]]) # set levels levels(ret[[names(lvs[i])]]) <- lvs[[i]] } # return data frame return(ret) } <file_sep>/foofactors.Rcheck/00_pkg_src/foofactors/R/detect_factors.R #' find if a factor is actually character #' #' In order to check if a factor is a character,this function checks #' #' whether there are repeated value in the factor #' @param x a factor #' #' @usage #' detect_factors(f) #' #' @return boolean; \code{TRUE} if input is factor, #' \code{FALSE} if input is character #' @export #' #' @examples #' detect_factors(factor(c("a","b","a"))) # True #' detect_factors(factor(c("a","b","c"))) # False #' #' detect_factors <- function(x){ # check if the input is factor if(!is.factor(x))stop('Please enter a factor!\n','The input is: ', class(x)[1]) # If the length of input is not equal to unique ones return true return(length(unique(x)) != length(x)) } <file_sep>/foofactors/tests/testthat/test_read_write.R # The basic idea here is that I first introduce a data frame # Then I reorder the data # Then I write the data frame to a file # Then I read the data from the file # Then I compare the data that I created and the data that I fetched from the file test_that("Reorder factor of a data frame", { # first create the dataframe dataframe <- data.frame( first = 1, second = 1:100, factor = sample(LETTERS[1:6], 10, replace = TRUE) ) dataframe$factor <- newreorder(dataframe$factor) dfwrite(dataframe, "./test_reorder.csv", "./levels_reorder.txt") fetched <- dfread("./test_reorder.csv", "./levels_reorder.txt") expect_equal(levels(fetched$factor), levels(dataframe$factor)) }) <file_sep>/foofactors/vignettes/hello-foofactors.Rmd --- title: "stringsAsFactors = HELLNO" author: "<NAME>" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{stringsAsFactors = HELLNO} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- Factors are a very useful type of variable in R, but they can also drive you nuts. Especially the "stealth factor" that you think of as character. Can we soften some of their sharp edges? Binding two factors via `fbind()`: ```{r} library(foofactors) a <- factor(c("character", "hits", "your", "eyeballs")) b <- factor(c("but", "integer", "where it", "counts")) ``` Simply catenating two factors leads to a result that most don't expect. ```{r} c(a, b) ``` The `fbind()` function glues two factors together and returns factor. ```{r} fbind(a, b) ``` Often we want a table of frequencies for the levels of a factor. The base `table()` function returns an object of class `table`, which can be inconvenient for downstream work. Processing with `as.data.frame()` can be helpful but it's a bit clunky. ```{r} set.seed(1234) x <- factor(sample(letters[1:5], size = 100, replace = TRUE)) table(x) as.data.frame(table(x)) ``` The `freq_out()` function returns a frequency table as a well-named `tbl_df`: ```{r} freq_out(x) ``` * `detect_factors()` * The `fdetect()` function checks if a factor is actually a character, it basicly checks that if a factor has repeated value in which case the factor can be considered as a character ```{r} # This is a factor factor <- factor(c("m","i","s","s","i","s")) # This is a character character <- factor(c("s", "t", "a")) # return TRUE if it is a factor detect_factors(factor) # return FALSE if it is a character detect_factors(character) ``` * `newreorder()` * The `newreorder()` function can reorder the levels of a factor in descending order. ```{r} # create a factor as an example f <- factor(c("a", "b", "c","d")) # the originally order: "a" "b" "c" "d" levels(f) # the reordered order "d" "c" "b" "a" levels(newreorder(f)) ``` * `newfactor()` Set levels of a factor to the order in which they appear in the data. * `newrev()` Set levels of a factor to the reversed order in which they appear in the data. ```{r} # create a factor as an example f <- factor(c("b", "a", "c")) # the originally order of level should be "b" "a" "c" levels(f) # the reset levels should be "b" "a" "c" levels(newfactor(f)) # the reversed levels should be "c" "a" "b" levels(newrev(f)) ``` * `dfwrite()`/`dfread()` Functions `dfwrite()` and `dfread()`: functions to write and read data frames to plain text delimited files while retaining factor levels ```{r} # The basic idea here is that I first introduce a data frame # Then I reorder the data # Then I write the data frame to a file # Then I read the data from the file # Then I compare the data that I created and the data that I fetched from the file dataframe <- data.frame( first = 1, second = 1:100, factor = sample(LETTERS[1:6], 10, replace = TRUE) ) dataframe$factor <- newreorder(dataframe$factor) dfwrite(dataframe, "./test_reorder.csv", "./levels_reorder.txt") fetched <- dfread("./test_reorder.csv", "./levels_reorder.txt") levels(fetched$factor) levels(dataframe$factor) ``` ## References - [Be the boss of your factors](https://www.stat.ubc.ca/~jenny/STAT545A/block08_bossYourFactors.html)
b154dbb986f13847fc0572396cae6ad40ac0a521
[ "Markdown", "R", "RMarkdown" ]
14
R
STAT545-UBC-hw-2018-19/hw07-RyanGao67
dbbc141e78fb69ad449cc5a1deb130821e562201
a3cba17663ebfb68bb53770190ea1463042928b2
refs/heads/master
<repo_name>feiyeyuanye/Android-development-toolset<file_sep>/app/src/main/java/com/example/developmenttoolset/math/Macth.kt package com.example.developmenttoolset.math import java.lang.RuntimeException /** * 简化多个数比较时的 max() 嵌套 * 借助 vararg 关键字,它允许方法接收任意多个同等类型的参数。 */ //fun mMax(vararg nums:Int):Int{ // // 记录所有数中的最大值,并在一开始将它赋值成了整形范围的最小值。 // var maxNum = Int.MIN_VALUE // for (num in nums){ // maxNum = max(maxNum,num) // } // return maxNum //} /** * 上面的方法只能比较整型数字。 * 那如果想要比较浮点型或长整型数字,可以重载多个 mMax(),来接收不同类型的参数。 * 但在这里会使用一种更加巧妙的做法。 * ------------------------------------------------------------------------------------------ * Java 中规定,所有类型的数字都是可比较的,因为必须实现 Comparable 接口, * 这个规则在 Kotlin 中也同样成立。我们可借助泛型,将 mMax() 修改成接收任意多个实现 Comparable 接口 的参数。 * ------------------------------------------------------------------------------------------ * 这里将泛型 T 的上界指定成了 Comparable<T>,那么参数 T 就必然是 Comparable<T> 的子类型了。 * 现在不管是双精度浮点型、单精度浮点型,还是短整型、整型、长整型,只要是实现 Comparable 接口的子类型,此函数都支持获取它们的最大值。 */ fun <T:Comparable<T>> mMax(vararg nums:T):T{ if (nums.isEmpty()) throw RuntimeException("Params can not be empty") var maxNum = nums[0] for (num in nums){ if (num > maxNum){ maxNum = num } } return maxNum } fun <T:Comparable<T>> mMin(vararg nums:T):T{ if (nums.isEmpty()) throw RuntimeException("Params can not be empty") var minNum = nums[0] for (num in nums){ if (num < minNum){ minNum = num } } return minNum }<file_sep>/settings.gradle include ':app' rootProject.name='DevelopmentToolset' <file_sep>/app/src/main/java/com/example/developmenttoolset/utils/Reified.kt package com.example.developmenttoolset.utils import android.content.Context import android.content.Intent /** * 使用泛型实化来启动 Activity * --------------------------------------- * 使用方式: * startActivity<MainActivity>(context) */ /** * Intent 的第二个参数本该是一个具体的 Activity 的 Class 类型, * 但由于 T 已经是一个被实化的泛型了,因此这里可直接传入 T::class.java。 */ inline fun <reified T> startActivity(context: Context){ val intent = Intent(context,T::class.java) context.startActivity(intent) } /** * 增加了一个函数类型参数,并且它的函数类型是定义在 Intent 类当中的 */ inline fun <reified T> startActivity(context: Context,block:Intent.() ->Unit){ val intent = Intent(context,T::class.java) intent.block() context.startActivity(intent) }<file_sep>/app/src/main/java/com/example/developmenttoolset/view/Snackbar.kt package com.example.developmenttoolset.view import android.view.View import com.google.android.material.snackbar.Snackbar /** * 记得要添加依赖库:implementation 'com.google.android.material:material:1.1.0' * 将扩展函数添加到了 View 类中 */ //fun View.showSnackbar(text:String, duration:Int = Snackbar.LENGTH_SHORT){ // Snackbar.make(this,text,duration).show() //} // //fun View.showSnackbar(resId:Int, duration:Int = Snackbar.LENGTH_SHORT){ // Snackbar.make(this,resId,duration).show() //} /** * 通过高阶函数来添加对 setAction() 的支持 * 这里将新增的两个参数都设置成可为空的类型,并将默认值都设置为空,然后只有当两个参数都不为空时才去调用 Snackbar 的 setAction() 来设置额外的点击事件。 * 如果触发了点击事件,只需要调用函数类型参数将事件传递给外部的 Lambda 表达式即可。 */ fun View.showSnackbar(text:String, actionText:String? = null, duration:Int = Snackbar.LENGTH_SHORT, block:(() -> Unit)? = null){ val snackbar = Snackbar.make(this,text,duration) if (actionText != null && block != null){ snackbar.setAction(actionText){ block() } } snackbar.show() } fun View.showSnackbar(resId:Int, actionResId:Int? = null, duration:Int = Snackbar.LENGTH_SHORT, block:(() -> Unit)? = null){ val snackbar = Snackbar.make(this,resId,duration) if (actionResId != null && block != null){ snackbar.setAction(actionResId){ block() } } snackbar.show() }<file_sep>/app/src/main/java/com/example/developmenttoolset/toast/Toast.kt package com.example.developmenttoolset.toast import android.content.Context import android.widget.Toast import com.example.developmenttoolset.config.MyApplication import com.example.developmenttoolset.config.MyApplication.Companion.context /** * Toast 第二个参数是要显示的内容,可以传入字符串和字符串资源 id 两种类型, * 所以,可以给 String 和 Int 类各添加一个扩展函数。 */ //fun String.showToast(context: Context){ // Toast.makeText(context,this,Toast.LENGTH_SHORT).show() //} // //fun Int.showToast(context: Context){ // Toast.makeText(context,this,Toast.LENGTH_SHORT).show() //} /** * 指定 Toast 的显示时长 * 通过给函数设定参数默认值,当需要 Toast.LENGTH_LONG 时可直接传入。 */ fun String.showToast(context: Context,duration:Int = Toast.LENGTH_SHORT){ Toast.makeText(context,this,duration).show() } fun Int.showToast(context: Context,duration:Int = Toast.LENGTH_SHORT){ Toast.makeText(context,this,duration).show() } /** * 使用 MyApplication 提供的 context 来简化代码 */ fun String.showToast(duration:Int = Toast.LENGTH_SHORT){ Toast.makeText(context,this,duration).show() } fun Int.showToast(duration:Int = Toast.LENGTH_SHORT){ Toast.makeText(context,this,duration).show() }
2107f2c83eca2577fd872880cfe8b8a91164f1c5
[ "Kotlin", "Gradle" ]
5
Kotlin
feiyeyuanye/Android-development-toolset
c9e2c175fdc40636e72837879cbb4248777eac9b
ffab5fe61e1852227b20bff100d9810f07d1010e
refs/heads/master
<repo_name>Vinther901/Neutrino-Machine-Learning<file_sep>/legacy/Models/Model4.py from torch_geometric.nn import GINConv, SGConv, SAGPooling, GCNConv, GATConv, DNAConv import torch from torch_scatter import scatter_add, scatter_max, scatter_mean import torch.nn.functional as F class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = GCNConv(5,10) self.sagpool1 = SAGPooling(10,0.2,GCNConv) self.gatconv = GATConv(10,20,heads=3) self.nn = torch.nn.Sequential(torch.nn.Linear(60,30),torch.nn.ReLU(),torch.nn.Linear(30,3)) self.m = torch.nn.LogSoftmax(dim=1) def forward(self, data): x, edge_index = data.x, data.edge_index batch = data.batch x = self.conv1(x,edge_index) x, edge_index, _, batch, _, _ = self.sagpool1(x,edge_index,batch=batch) x = self.gatconv(x,edge_index) x = scatter_add(x,batch,dim=0) x = self.nn(x) return self.m(x)<file_sep>/Model_Loaders/Model_3.py def Load_model(name, args): from FunctionCollection import Loss_Functions, customModule import pytorch_lightning as pl from torch_geometric_temporal import nn from typing import Optional import torch from torch_scatter import scatter_sum, scatter_min, scatter_max from torch_scatter.utils import broadcast @torch.jit.script def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None, unbiased: bool = True) -> torch.Tensor: if out is not None: dim_size = out.size(dim) if dim < 0: dim = src.dim() + dim count_dim = dim if index.dim() <= dim: count_dim = index.dim() - 1 ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) count = scatter_sum(ones, index, count_dim, dim_size=dim_size) index = broadcast(index, src, dim) tmp = scatter_sum(src, index, dim, dim_size=dim_size) count = broadcast(count, tmp, dim).clamp(1) mean = tmp.div(count) var = (src - mean.gather(dim, index)) var = var * var var = scatter_sum(var, index, dim, out, dim_size) if unbiased: count = count.sub(1).clamp_(1) var = var.div(count) maximum = scatter_max(src, index, dim, out, dim_size)[0] minimum = scatter_min(src, index, dim, out, dim_size)[0] return torch.cat([mean,var,maximum,minimum],dim=1) N_edge_feats = args['N_edge_feats'] #6 N_dom_feats = args['N_dom_feats']#6 N_scatter_feats = 4 # N_targets = args['N_targets'] N_outputs = args['N_outputs'] N_metalayers = args['N_metalayers'] #10 N_hcs = args['N_hcs'] #32 #Possibly add (edge/node/global)_layers crit, y_post_processor, output_post_processor, cal_acc = Loss_Functions(name, args) likelihood_fitting = True if name[-4:] == 'NLLH' else False class Net(customModule): def __init__(self): super(Net, self).__init__(crit, y_post_processor, output_post_processor, cal_acc, likelihood_fitting, args) self.act = torch.nn.SiLU() self.hcs = N_hcs N_x_feats = N_dom_feats + N_scatter_feats*N_edge_feats N_u_feats = N_scatter_feats*N_x_feats self.x_encoder = torch.nn.Linear(N_x_feats,self.hcs) self.edge_attr_encoder = torch.nn.Linear(N_edge_feats,self.hcs) self.u_encoder = torch.nn.Linear(N_u_feats,self.hcs) class EdgeModel(torch.nn.Module): def __init__(self,hcs,act): super(EdgeModel, self).__init__() self.hcs = hcs self.act = act self.lins = torch.nn.ModuleList() for i in range(2): self.lins.append(torch.nn.Linear(4*self.hcs,4*self.hcs)) self.decoder = torch.nn.Linear(4*self.hcs,self.hcs) def forward(self, src, dest, edge_attr, u, batch): # x: [N, F_x], where N is the number of nodes. # src, dest: [E, F_x], where E is the number of edges. # edge_attr: [E, F_e] # edge_index: [2, E] with max entry N - 1. # u: [B, F_u], where B is the number of graphs. # batch: [N] with max entry B - 1. out = torch.cat([src, dest, edge_attr, u[batch]], dim=1) for lin in self.lins: out = self.act(lin(out)) return self.act(self.decoder(out)) class NodeModel(torch.nn.Module): def __init__(self,hcs,act): super(NodeModel, self).__init__() self.hcs = hcs self.act = act self.lins1 = torch.nn.ModuleList() for i in range(2): self.lins1.append(torch.nn.Linear(2*self.hcs,2*self.hcs)) self.lins2 = torch.nn.ModuleList() for i in range(2): self.lins2.append(torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,(2 + 2*N_scatter_feats)*self.hcs)) self.decoder = torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,self.hcs) def forward(self, x, edge_index, edge_attr, u, batch): row, col = edge_index out = torch.cat([x[row],edge_attr],dim=1) for lin in self.lins1: out = self.act(lin(out)) out = scatter_distribution(out,col,dim=0) #8*hcs out = torch.cat([x,out,u[batch]],dim=1) for lin in self.lins2: out = self.act(lin(out)) return self.act(self.decoder(out)) class GlobalModel(torch.nn.Module): def __init__(self,hcs,act): super(GlobalModel, self).__init__() self.hcs = hcs self.act = act self.lins1 = torch.nn.ModuleList() for i in range(2): self.lins1.append(torch.nn.Linear((1 + N_scatter_feats)*self.hcs,(1 + N_scatter_feats)*self.hcs)) self.decoder = torch.nn.Linear((1 + N_scatter_feats)*self.hcs,self.hcs) def forward(self, x, edge_index, edge_attr, u, batch): out = torch.cat([u,scatter_distribution(x,batch,dim=0)],dim=1) # 5*hcs for lin in self.lins1: out = self.act(lin(out)) return self.act(self.decoder(out)) self.tgcn_starter = nn.recurrent.temporalgcn.TGCN(N_x_feats,self.hcs) from torch_geometric.nn import MetaLayer self.ops = torch.nn.ModuleList() self.tgcns = torch.nn.ModuleList() for i in range(N_metalayers): self.ops.append(MetaLayer(EdgeModel(self.hcs,self.act), NodeModel(self.hcs,self.act), GlobalModel(self.hcs,self.act))) self.tgcns.append(nn.recurrent.temporalgcn.TGCN(self.hcs,self.hcs)) self.decoders = torch.nn.ModuleList() self.decoders.append(torch.nn.Linear((1+N_metalayers)*self.hcs + N_scatter_feats*self.hcs,10*self.hcs)) self.decoders.append(torch.nn.Linear(10*self.hcs,8*self.hcs)) self.decoders.append(torch.nn.Linear(8*self.hcs,6*self.hcs)) self.decoders.append(torch.nn.Linear(6*self.hcs,4*self.hcs)) self.decoders.append(torch.nn.Linear(4*self.hcs,2*self.hcs)) self.decoder = torch.nn.Linear(2*self.hcs,N_outputs) def forward(self,data): x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch x = torch.cat([x,scatter_distribution(edge_attr,edge_index[1],dim=0)],dim=1) u = torch.cat([scatter_distribution(x,batch,dim=0)],dim=1) time_sort = torch.argsort(x[:,1]) batch_time_sort = time_sort[torch.argsort(batch[time_sort])] time_edge_index = torch.cat([batch_time_sort[:-1].view(1,-1),batch_time_sort[1:].view(1,-1)],dim=0) graph_ids, graph_node_counts = batch.unique(return_counts=True) tmp_bool = torch.ones(time_edge_index.shape[1],dtype=bool) tmp_bool[(torch.cumsum(graph_node_counts,0) - 1)[:-1]] = False time_edge_index = time_edge_index[:,tmp_bool] time_edge_index = torch.cat([time_edge_index,time_edge_index.flip(0)],dim=1) time_edge_index = torch.cat([edge_index,time_edge_index],dim=1) h = self.tgcn_starter(x, time_edge_index) x = self.act(self.x_encoder(x)) edge_attr = self.act(self.edge_attr_encoder(edge_attr)) u = self.act(self.u_encoder(u)) out = u.clone() for i in range(N_metalayers): x, edge_attr, u = self.ops[i](x, edge_index, edge_attr, u, batch) h = self.act(self.tgcns[i](x, time_edge_index, H=h)) out = torch.cat([out,u.clone()],dim=1) out = torch.cat([out,scatter_distribution(h,batch,dim=0)],dim=1) for lin in self.decoders: out = self.act(lin(out)) out = self.decoder(out) return out return Net<file_sep>/legacy/split_data.py from torch_geometric.data import DataListLoader, InMemoryDataset import numpy as np import pandas as pd import os import torch def create_class_dataset(): class LoadDataset(InMemoryDataset): def __init__(self, root): super(LoadDataset, self).__init__(root) self.data, self.slices = torch.load(root+'/processed/processed') @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') def process(self): pass print('Loads data') dataset = LoadDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset') dataset_background = LoadDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/dataset_background') dataset.data.y = torch.tensor(np.zeros(300000),dtype=torch.int64) dataset.slices['y'] = torch.tensor(np.arange(300000+1)) dataset_background.data.y = torch.tensor(np.ones(dataset_background.len()),dtype=torch.int64) dataset_background.slices['y'] = torch.tensor(np.arange(dataset_background.len() + 1)) subsize = 30000 nu_e_ind = np.random.choice(np.arange(100000),subsize,replace=False).tolist() nu_t_ind = np.random.choice(np.arange(100000,200000),subsize,replace=False).tolist() nu_m_ind = np.random.choice(np.arange(200000,300000),subsize,replace=False).tolist() muon_ind = np.random.choice(np.arange(dataset_background.len()),3*subsize,replace=False).tolist() train_dataset = dataset[nu_e_ind] + dataset[nu_t_ind] + dataset[nu_m_ind] + dataset_background[muon_ind] test_ind_e = np.arange(100000)[pd.Series(np.arange(100000)).isin(nu_e_ind).apply(lambda x: not(x))].tolist() test_ind_t = np.arange(100000,200000)[pd.Series(np.arange(100000,200000)).isin(nu_t_ind).apply(lambda x: not(x))].tolist() test_ind_m = np.arange(200000,300000)[pd.Series(np.arange(200000,300000)).isin(nu_m_ind).apply(lambda x: not(x))].tolist() test_ind_muon = np.arange(dataset_background.len())[pd.Series(np.arange(dataset_background.len())).isin(muon_ind).apply(lambda x: not(x))].tolist() test_dataset = dataset[test_ind_e] + dataset[test_ind_t] + dataset[test_ind_m] + dataset_background[test_ind_muon] for train_list in DataListLoader(train_dataset,batch_size=len(train_dataset)): pass for test_list in DataListLoader(test_dataset,batch_size=len(test_dataset)): pass class MakeDataset(InMemoryDataset): def __init__(self, root,data_list,name): super(MakeDataset, self).__init__(root) self.data, self.slices = self.collate(data_list) torch.save((self.data,self.slices),root+'/'+name) @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') def process(self): pass MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',train_list,'train_class') MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',test_list,'test_class') def create_type_dataset(): class LoadDataset(InMemoryDataset): def __init__(self, root): super(LoadDataset, self).__init__(root) self.data, self.slices = torch.load(root+'/processed/processed') @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') def process(self): pass print('Loads data') dataset = LoadDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset') dataset.data.y = torch.tensor([np.zeros(100000),np.ones(100000),np.ones(100000)*2],dtype=torch.int64).view(-1) dataset.slices['y'] = torch.tensor(np.arange(300000+1)) dataset = dataset.shuffle() train_dataset = dataset[:200000] print(len(train_dataset)) test_dataset = dataset[200000:] for train_list in DataListLoader(train_dataset,batch_size=len(train_dataset)): pass for test_list in DataListLoader(test_dataset,batch_size=len(test_dataset)): pass class MakeDataset(InMemoryDataset): def __init__(self, root,data_list,name): super(MakeDataset, self).__init__(root) self.data, self.slices = self.collate(data_list) torch.save((self.data,self.slices),root+'/'+name) @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets') def process(self): pass MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',train_list,'train_type') MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',test_list,'test_type') def create_energy_dataset(): class LoadDataset(InMemoryDataset): def __init__(self, root): super(LoadDataset, self).__init__(root) self.data, self.slices = torch.load(root+'/processed/processed') @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') def process(self): pass print('Loads data') dataset = LoadDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset') dataset.data.y = dataset.data.y[::8] dataset.slices['y'] = torch.tensor(np.arange(300000+1)) dataset = dataset.shuffle() train_dataset = dataset[:200000] print(len(train_dataset)) test_dataset = dataset[200000:] for train_list in DataListLoader(train_dataset,batch_size=len(train_dataset)): pass for test_list in DataListLoader(test_dataset,batch_size=len(test_dataset)): pass class MakeDataset(InMemoryDataset): def __init__(self, root,data_list,name): super(MakeDataset, self).__init__(root) self.data, self.slices = self.collate(data_list) torch.save((self.data,self.slices),root+'/'+name) @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets') def process(self): pass MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',train_list,'train_energy') MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',test_list,'test_energy') def create_background_dataset(): class LoadDataset(InMemoryDataset): def __init__(self, root): super(LoadDataset, self).__init__(root) self.data, self.slices = torch.load(root+'/processed/processed') @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') def process(self): pass print('Loads data') dataset = LoadDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset') dataset_background = LoadDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/dataset_background') # dataset.data.y = torch.tensor(np.zeros(300000),dtype=torch.int64) # dataset.slices['y'] = torch.tensor(np.arange(300000+1)) # dataset_background.data.y = torch.tensor(np.ones(dataset_background.len()),dtype=torch.int64) # dataset_background.slices['y'] = torch.tensor(np.arange(dataset_background.len() + 1)) subsize = 30000 nu_e_ind = np.random.choice(np.arange(100000),subsize,replace=False).tolist() nu_t_ind = np.random.choice(np.arange(100000,200000),subsize,replace=False).tolist() nu_m_ind = np.random.choice(np.arange(200000,300000),subsize,replace=False).tolist() muon_ind = np.random.choice(np.arange(dataset_background.len()),3*subsize,replace=False).tolist() train_dataset = dataset[nu_t_ind] + dataset[nu_e_ind] + dataset[nu_m_ind] + dataset_background[muon_ind] test_ind_e = np.arange(100000)[pd.Series(np.arange(100000)).isin(nu_e_ind).apply(lambda x: not(x))].tolist() test_ind_t = np.arange(100000,200000)[pd.Series(np.arange(100000,200000)).isin(nu_t_ind).apply(lambda x: not(x))].tolist() test_ind_m = np.arange(200000,300000)[pd.Series(np.arange(200000,300000)).isin(nu_m_ind).apply(lambda x: not(x))].tolist() test_ind_muon = np.arange(dataset_background.len())[pd.Series(np.arange(dataset_background.len())).isin(muon_ind).apply(lambda x: not(x))].tolist() test_dataset = dataset[test_ind_t] + dataset[test_ind_e] + dataset[test_ind_m] + dataset_background[test_ind_muon] for train_list in DataListLoader(train_dataset,batch_size=len(train_dataset)): pass for test_list in DataListLoader(test_dataset,batch_size=len(test_dataset)): pass class MakeDataset(InMemoryDataset): def __init__(self, root,data_list,name): super(MakeDataset, self).__init__(root) self.data, self.slices = self.collate(data_list) torch.save((self.data,self.slices),root+'/'+name) @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') def process(self): pass MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',train_list,'t30k_e30k_m30k_muon90k') MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',test_list,'t70k_e70k_m70k_muon38730') def create_neutrino_dataset(): class LoadDataset(InMemoryDataset): def __init__(self, root): super(LoadDataset, self).__init__(root) self.data, self.slices = torch.load(root+'/processed/processed') @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') def process(self): pass print('Loads data') dataset = LoadDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset') subsize = 70000 nu_e_ind = np.random.choice(np.arange(100000),subsize,replace=False).tolist() nu_t_ind = np.random.choice(np.arange(100000,200000),subsize,replace=False).tolist() nu_m_ind = np.random.choice(np.arange(200000,300000),subsize,replace=False).tolist() train_dataset = dataset[nu_t_ind] + dataset[nu_e_ind] + dataset[nu_m_ind] test_ind_e = np.arange(100000)[pd.Series(np.arange(100000)).isin(nu_e_ind).apply(lambda x: not(x))].tolist() test_ind_t = np.arange(100000,200000)[pd.Series(np.arange(100000,200000)).isin(nu_t_ind).apply(lambda x: not(x))].tolist() test_ind_m = np.arange(200000,300000)[pd.Series(np.arange(200000,300000)).isin(nu_m_ind).apply(lambda x: not(x))].tolist() # test_ind_muon = np.arange(dataset_background.len())[pd.Series(np.arange(dataset_background.len())).isin(muon_ind).apply(lambda x: not(x))].tolist() test_dataset = dataset[test_ind_t] + dataset[test_ind_e] + dataset[test_ind_m] for train_list in DataListLoader(train_dataset,batch_size=len(train_dataset)): pass for test_list in DataListLoader(test_dataset,batch_size=len(test_dataset)): pass class MakeDataset(InMemoryDataset): def __init__(self, root,data_list,name): super(MakeDataset, self).__init__(root) self.data, self.slices = self.collate(data_list) torch.save((self.data,self.slices),root+'/'+name) @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets') def process(self): pass MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',train_list,'t70k_e70k_m70k') MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets',test_list,'t30k_e30k_m30k') <file_sep>/scripts/print_db.py from FunctionCollection import Print from sqlite3 import connect from os import path from pandas import read_sql # filename = r"dev_lvl7_mu_nu_e_classification_v003_unscaled.db" filename = r"dev_level2_mu_tau_e_muongun_classification_wnoise_unscaled.db" filepath = r"/groups/hep/pcs557/databases/dev_level2_mu_tau_e_muongun_classification_wnoise/data" # query = "SELECT COUNT(*), pid FROM truth GROUP BY pid" Print("Connecting to DB: {} ..".format(filename)) with connect(path.join(filepath,filename)) as con: cursor = con.cursor() # Execute custom query: try: Print("Trying to execute query: {} ..".format(query)) df = read_sql(query,con) print(df) except: pass # Print the tables and indices present in the SQLite main database Print("Selecting all from SQLite_master..") cursor.execute("select * from SQLite_master") Print("Calling fetchall..") tables = cursor.fetchall() Print("Listing tables and indices from main database:") print("="*50) for table in tables: print("Type of database object: %s"%(table[0])) print("Name of the database object: %s"%(table[1])) print("Table Name: %s"%(table[2])) print("Root page: %s"%(table[3])) print("SQL statement: %s"%(table[4])) print("="*50) # con.close()<file_sep>/scripts/test_env_and_gpu.py import torch print("is initialized: ", torch.cuda.is_initialized()) print("current device: ", torch.cuda.current_device()) print("device count: ", torch.cuda.device_count()) print("cuda available: ", torch.cuda.is_available()) print("device capability: ", torch.cuda.get_device_capability()) print("device name: ", torch.cuda.get_device_name()) with torch.cuda.device(1) as device: print("is initialized: ", torch.cuda.is_initialized()) print("current device: ", torch.cuda.current_device()) print("device capability: ", torch.cuda.get_device_capability()) print("device name: ", torch.cuda.get_device_name())<file_sep>/legacy/PlotEvent.py import matplotlib.pyplot as plt import pandas as pd import numpy as np from mpl_toolkits.mplot3d import Axes3D seq = pd.read_csv('data/sequential.csv') pos = seq[['dom_x','dom_y','dom_z']].drop_duplicates() fig = plt.figure() ax = fig.add_subplot(111,projection='3d') ax.scatter(pos.iloc[:,0],pos.iloc[:,1],pos.iloc[:,2],alpha=0.05) fig.show() events = seq['event_no'].unique() def plot(index): ax.cla() ax.scatter(pos.iloc[:,0],pos.iloc[:,1],pos.iloc[:,2],alpha=0.05) pos_event = seq.loc[seq['event_no'] == events[index]][['dom_x','dom_y','dom_z','dom_charge']] event = ax.scatter3D(pos_event['dom_x'],pos_event['dom_y'],pos_event['dom_z'],c=pos_event['dom_charge'],cmap='plasma') fig.canvas.draw()<file_sep>/Model_Loaders/Model_6.py def Load_model(name, args): from FunctionCollection import Loss_Functions, customModule, edge_feature_constructor import pytorch_lightning as pl from typing import Optional import torch from torch_scatter import scatter_sum, scatter_min, scatter_max from torch_scatter.utils import broadcast # from torch_geometric.nn import GATConv, FeaStConv @torch.jit.script def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None, unbiased: bool = True) -> torch.Tensor: if out is not None: dim_size = out.size(dim) if dim < 0: dim = src.dim() + dim count_dim = dim if index.dim() <= dim: count_dim = index.dim() - 1 ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) count = scatter_sum(ones, index, count_dim, dim_size=dim_size) index = broadcast(index, src, dim) tmp = scatter_sum(src, index, dim, dim_size=dim_size) count = broadcast(count, tmp, dim).clamp(1) mean = tmp.div(count) var = (src - mean.gather(dim, index)) var = var * var var = scatter_sum(var, index, dim, out, dim_size) if unbiased: count = count.sub(1).clamp_(1) var = var.div(count) maximum = scatter_max(src, index, dim, out, dim_size)[0] minimum = scatter_min(src, index, dim, out, dim_size)[0] return torch.cat([mean,var,maximum,minimum],dim=1) N_edge_feats = args['N_edge_feats'] #6 N_dom_feats = args['N_dom_feats']#6 N_scatter_feats = 4 # N_targets = args['N_targets'] N_outputs = args['N_outputs'] N_metalayers = args['N_metalayers'] #10 N_hcs = args['N_hcs'] #32 #Possibly add (edge/node/global)_layers crit, y_post_processor, output_post_processor, cal_acc = Loss_Functions(name, args) likelihood_fitting = True if name[-4:] == 'NLLH' else False class Net(customModule): def __init__(self): super(Net, self).__init__(crit, y_post_processor, output_post_processor, cal_acc, likelihood_fitting, args) self.act = torch.nn.SiLU() self.hcs = N_hcs N_x_feats = N_dom_feats + N_scatter_feats*N_edge_feats # N_u_feats = N_scatter_feats*N_x_feats self.x_encoder = torch.nn.Linear(N_x_feats,self.hcs) self.edge_attr_encoder = torch.nn.Linear(N_edge_feats,self.hcs) self.CoC_encoder = torch.nn.Linear(3+N_scatter_feats*N_x_feats,self.hcs) class EdgeModel(torch.nn.Module): def __init__(self,hcs,act): super(EdgeModel, self).__init__() self.hcs = hcs self.act = act self.lins = torch.nn.ModuleList() for i in range(2): self.lins.append(torch.nn.Linear(4*self.hcs,4*self.hcs)) self.decoder = torch.nn.Linear(4*self.hcs,self.hcs) def forward(self, src, dest, edge_attr, CoC, batch): # x: [N, F_x], where N is the number of nodes. # src, dest: [E, F_x], where E is the number of edges. # edge_attr: [E, F_e] # edge_index: [2, E] with max entry N - 1. # u: [B, F_u], where B is the number of graphs. # batch: [N] with max entry B - 1. out = torch.cat([src, dest, edge_attr, CoC[batch]], dim=1) for lin in self.lins: out = self.act(lin(out)) return self.act(self.decoder(out)) class NodeModel(torch.nn.Module): def __init__(self,hcs,act): super(NodeModel, self).__init__() self.hcs = hcs self.act = act self.lins1 = torch.nn.ModuleList() for i in range(2): self.lins1.append(torch.nn.Linear(2*self.hcs,2*self.hcs)) self.lins2 = torch.nn.ModuleList() for i in range(2): self.lins2.append(torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,(2 + 2*N_scatter_feats)*self.hcs)) self.decoder = torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,self.hcs) def forward(self, x, edge_index, edge_attr, CoC, batch): row, col = edge_index out = torch.cat([x[row],edge_attr],dim=1) for lin in self.lins1: out = self.act(lin(out)) out = scatter_distribution(out,col,dim=0) #8*hcs out = torch.cat([x,out,CoC[batch]],dim=1) for lin in self.lins2: out = self.act(lin(out)) return self.act(self.decoder(out)) class GlobalModel(torch.nn.Module): def __init__(self,hcs,act): super(GlobalModel, self).__init__() def forward(self, x, edge_index, edge_attr, CoC, batch): return CoC from torch_geometric.nn import MetaLayer self.ops = torch.nn.ModuleList() self.GRUCells = torch.nn.ModuleList() self.lins1 = torch.nn.ModuleList() self.lins2 = torch.nn.ModuleList() self.lins3 = torch.nn.ModuleList() for i in range(N_metalayers): self.ops.append(MetaLayer(EdgeModel(self.hcs,self.act), NodeModel(self.hcs,self.act), GlobalModel(self.hcs,self.act))) self.GRUCells.append( torch.nn.GRUCell(self.hcs*2 + 4 + N_x_feats,self.hcs) ) self.lins1.append( torch.nn.Linear((1+N_scatter_feats)*self.hcs,(1+N_scatter_feats)*self.hcs) ) self.lins2.append( torch.nn.Linear((1+N_scatter_feats)*self.hcs,self.hcs) ) self.lins3.append( torch.nn.Linear(2*self.hcs,self.hcs) ) self.decoders = torch.nn.ModuleList() self.decoders.append(torch.nn.Linear(self.hcs,self.hcs)) self.decoders.append(torch.nn.Linear(self.hcs,self.hcs)) self.decoder = torch.nn.Linear(self.hcs,N_outputs) def forward(self,data): x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch pos = x[:,-3:] x = torch.cat([x,scatter_distribution(edge_attr,edge_index[1],dim=0)],dim=1) CoC = scatter_sum( pos*x[:,0].view(-1,1), batch, dim=0) / scatter_sum(x[:,0].view(-1,1), batch, dim=0) CoC = torch.cat([CoC,scatter_distribution(x,batch,dim=0)],dim=1) CoC_edge_index = torch.cat([torch.arange(x.shape[0]).view(1,-1).type_as(batch),batch.view(1,-1)],dim=0) cart = pos[CoC_edge_index[0],-3:] - CoC[CoC_edge_index[1],:3] del pos rho = torch.norm(cart, p=2, dim=-1).view(-1, 1) rho_mask = rho.squeeze() != 0 cart[rho_mask] = cart[rho_mask] / rho[rho_mask] CoC_edge_attr = torch.cat([cart.type_as(x),rho.type_as(x),x[CoC_edge_index[0]]], dim=1) x = self.act(self.x_encoder(x)) edge_attr = self.act(self.edge_attr_encoder(edge_attr)) CoC = self.act(self.CoC_encoder(CoC)) # u = torch.zeros( (batch.max() + 1, self.hcs) ).type_as(x) h = torch.zeros( (x.shape[0], self.hcs) ).type_as(x) for i, op in enumerate(self.ops): x, edge_attr, CoC = op(x, edge_index, edge_attr, CoC, batch) h = self.act( self.GRUCells[i]( torch.cat([CoC[CoC_edge_index[1]], x[CoC_edge_index[0]], CoC_edge_attr], dim=1), h ) ) CoC = self.act( self.lins1[i]( torch.cat([CoC,scatter_distribution(h, batch, dim=0)],dim=1) ) ) CoC = self.act( self.lins2[i]( CoC ) ) h = self.act( self.GRUCells[i]( torch.cat([CoC[CoC_edge_index[1]], x[CoC_edge_index[0]], CoC_edge_attr], dim=1), h ) ) x = self.act( self.lins3[i]( torch.cat([x,h],dim=1) ) ) for lin in self.decoders: CoC = self.act(lin(CoC)) CoC = self.decoder(CoC) return CoC return Net<file_sep>/legacy/Models/Model11.py import torch from torch_scatter import scatter_std, scatter_mean N_edge_feats = 6#3 N_targets = 2 class Net11(torch.nn.Module): def __init__(self): super(Net11, self).__init__() self.act = torch.nn.SiLU() #SiLU is x/(1+exp(-x)) self.hcs = 32 N_x_feats = 5 + 2*N_edge_feats N_u_feats = 2*N_x_feats self.x_encoder = torch.nn.Linear(N_x_feats,self.hcs) self.edge_attr_encoder = torch.nn.Linear(N_edge_feats,self.hcs) self.u_encoder = torch.nn.Linear(N_u_feats,self.hcs) class EdgeModel(torch.nn.Module): def __init__(self,hcs,act): super(EdgeModel, self).__init__() self.hcs = hcs self.act = act self.lins = torch.nn.ModuleList() for i in range(2): self.lins.append(torch.nn.Linear(4*self.hcs,4*self.hcs)) self.decoder = torch.nn.Linear(4*self.hcs,self.hcs) def forward(self, src, dest, edge_attr, u, batch): # x: [N, F_x], where N is the number of nodes. # src, dest: [E, F_x], where E is the number of edges. # edge_attr: [E, F_e] # edge_index: [2, E] with max entry N - 1. # u: [B, F_u], where B is the number of graphs. # batch: [N] with max entry B - 1. out = torch.cat([src, dest, edge_attr, u[batch]], dim=1) for lin in self.lins: out = self.act(lin(out)) return self.act(self.decoder(out)) class NodeModel(torch.nn.Module): def __init__(self,hcs,act): super(NodeModel, self).__init__() self.hcs = hcs self.act = act self.lins1 = torch.nn.ModuleList() for i in range(2): self.lins1.append(torch.nn.Linear(2*self.hcs,2*self.hcs)) self.lins2 = torch.nn.ModuleList() for i in range(2): self.lins2.append(torch.nn.Linear(4*self.hcs,4*self.hcs)) self.decoder = torch.nn.Linear(4*self.hcs,self.hcs) def forward(self, x, edge_index, edge_attr, u, batch): row, col = edge_index out = torch.cat([x[row],edge_attr],dim=1) for lin in self.lins1: out = self.act(lin(out)) # out = torch.cat([scatter_mean(out,col,dim=0),torch.square(scatter_std(out,col,dim=0))],dim=1) #6*hcs out = scatter_mean(out,col,dim=0) #4*hcs out = torch.cat([x,out,u[batch]],dim=1) for lin in self.lins2: out = self.act(lin(out)) return self.act(self.decoder(out)) class GlobalModel(torch.nn.Module): def __init__(self,hcs,act): super(GlobalModel, self).__init__() self.hcs = hcs self.act = act self.lins1 = torch.nn.ModuleList() for i in range(2): self.lins1.append(torch.nn.Linear(2*self.hcs,2*self.hcs)) self.decoder = torch.nn.Linear(2*self.hcs,self.hcs) def forward(self, x, edge_index, edge_attr, u, batch): # out = torch.cat([u,scatter_mean(x,batch,dim=0),torch.square(scatter_std(x,batch,dim=0))],dim=1) # 3*hcs out = torch.cat([u,scatter_mean(x,batch,dim=0)],dim=1) # 2*hcs for lin in self.lins1: out = self.act(lin(out)) return self.act(self.decoder(out)) from torch_geometric.nn import MetaLayer self.ops = torch.nn.ModuleList() for i in range(10): self.ops.append(MetaLayer(EdgeModel(self.hcs,self.act), NodeModel(self.hcs,self.act), GlobalModel(self.hcs,self.act))) # self.rnn = torch.nn.LSTM(self.hcs,self.hcs,num_layers=1,batch_first=True) self.decoders = torch.nn.ModuleList() # for i in range(8,2,-2): # self.decoders.append(torch.nn.Linear(i*self.hcs,(i-2)*self.hcs)) self.decoders.append(torch.nn.Linear(10*self.hcs,2*self.hcs)) self.decoders2 = torch.nn.ModuleList() # for i in range(4,1,-1): # self.decoders2.append(torch.nn.Linear(i*self.hcs,(i-1)*self.hcs)) self.decoders2.append(torch.nn.Linear(4*self.hcs,1*self.hcs)) self.decoder = torch.nn.Linear(self.hcs,3) def forward(self,data): x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch # times = x[:,1].detach().clone() # x = torch.cuda.FloatTensor(self.scaler.transform(x.cpu())) x = torch.cat([x,scatter_mean(edge_attr,edge_index[1],dim=0),scatter_std(edge_attr,edge_index[1],dim=0)],dim=1) u = torch.cat([scatter_mean(x,batch,dim=0),scatter_std(x,batch,dim=0)],dim=1) x = self.act(self.x_encoder(x)) edge_attr = self.act(self.edge_attr_encoder(edge_attr)) # u = torch.cuda.FloatTensor(batch.max()+1,self.hcs).fill_(0) u = self.act(self.u_encoder(u)) for i, op in enumerate(self.ops): x, edge_attr, u = op(x, edge_index, edge_attr, u, batch) if i == 0: out = u else: out = torch.cat([out,u],dim=1) # graph_indices, graph_sizes = data.batch.unique(return_counts=True) # tmp = torch.zeros((graph_indices.max()+1,graph_sizes.max(),self.hcs)).to(device) # sort = torch.sort(graph_sizes,dim=0,descending=True).indices # reverse_sort = torch.sort(sort,dim=0).indices # for tmp_index, i in enumerate(graph_indices[sort]): # tmp_graph = x[data.batch==i] # tmp_times = times[data.batch==i] # tmp[tmp_index,:graph_sizes[i]] = tmp_graph[torch.sort(tmp_times,dim=0).indices] # tmp = torch.nn.utils.rnn.pack_padded_sequence(tmp,graph_sizes[sort].cpu(),batch_first=True,enforce_sorted=True) # tmp, (hn, cn) = self.rnn(tmp) # #Maybe add TCN? for lin in self.decoders: out = self.act(lin(out)) # out = torch.cat([out,cn[0,reverse_sort], # scatter_mean(torch.cat([x,scatter_mean(edge_attr,edge_index[1],dim=0)],dim=1),batch,dim=0)],dim=1) out = torch.cat([out,scatter_mean(torch.cat([x,scatter_mean(edge_attr,edge_index[1],dim=0)],dim=1),batch,dim=0)],dim=1) for lin in self.decoders2: out = self.act(lin(out)) return self.decoder(out) <file_sep>/legacy/Models/Model2.py from torch_geometric.nn import GINConv, SGConv import torch from torch_scatter import scatter_add import torch.nn.functional as F class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() nn1 = torch.nn.Sequential(torch.nn.Linear(5,30),torch.nn.ReLU()) nn2 = torch.nn.Sequential(torch.nn.Linear(30,30),torch.nn.ReLU()) self.nnconv1 = GINConv(nn1) self.sconv1 = SGConv(30,30,K=5) self.sconv2 = SGConv(30,30,K=5) self.nnconv2 = GINConv(nn2) self.nn = torch.nn.Linear(30,1) def forward(self, data): x, edge_index = data.x, data.edge_index x = self.nnconv1(x,edge_index) x = self.sconv1(x,edge_index) x = self.sconv2(x,edge_index) x = self.nnconv2(x,edge_index) x = scatter_add(x,data.batch,dim=0) return self.nn(x) # class Net(torch.nn.Module): # def __init__(self): # super(Net, self).__init__() # nn1 = torch.nn.Sequential(torch.nn.Linear(5,30),torch.nn.ReLU()) # nn2 = torch.nn.Sequential(torch.nn.Linear(30,30),torch.nn.ReLU()) # self.nnconv1 = GINConv(nn1) # self.sconv1 = SGConv(30,30,K=5) # self.sconv2 = SGConv(30,30,K=5) # self.nnconv2 = GINConv(nn2) # self.nn = torch.nn.Linear(30,2) # self.m = torch.nn.LogSoftmax(dim=1) # def forward(self, data): # x, edge_index = data.x, data.edge_index # x = self.nnconv1(x,edge_index) # x = self.sconv1(x,edge_index) # x = self.sconv2(x,edge_index) # x = self.nnconv2(x,edge_index) # # x = torch.nn.Dropout() # x = scatter_add(x,data.batch,dim=0) # x = self.nn(x) # return self.m(x)<file_sep>/copy_db.py import sqlite3 import pandas as pd from sqlite3 import Error import os def Print(statement): from time import localtime, strftime print("{} - {}".format(strftime("%H:%M:%S", localtime()),statement)) new_db = 'rasmus_classification_muon_1500k.db' new_path = r'C:\Users\jv97\Desktop\github\Neutrino-Machine-Learning\raw_data' old_db = 'rasmus_classification_muon_3neutrino_3mio.db' old_path = r'C:\Users\jv97\Desktop\github\Neutrino-Machine-Learning\raw_data' event_nos_query = "SELECT event_no FROM truth WHERE pid IN (-13,13)" old_con_path = 'file:' + os.path.join(old_path,old_db) + '?mode=ro' new_con_path = os.path.join(new_path,new_db) with sqlite3.connect(old_con_path,uri=True) as old_db: old_cursor = old_db.cursor() Print("Selecting all from SQLite_master..") old_cursor.execute("select * from SQLite_master") Print("Calling fetchall..") tables = old_cursor.fetchall() with sqlite3.connect(new_con_path) as new_db: new_cursor = new_db.cursor() for table in tables: SQL_statement = table[4] Print("Creating table: {}..".format(table[1])) new_cursor.execute(SQL_statement) Print("Getting event_nos for events to be copied..") event_nos = pd.read_sql(event_nos_query,old_db) event_nos = event_nos.values.reshape(-1) old_cursor.execute("ATTACH DATABASE ? AS new_db", (new_con_path,)) Print("Copying features..") query = f"INSERT INTO new_db.features SELECT * FROM features WHERE event_no IN {tuple(event_nos)}" old_cursor.execute(query) Print("Copying truths..") query = f"INSERT INTO new_db.truth SELECT * FROM truth WHERE event_no IN {tuple(event_nos)}" old_cursor.execute(query) old_db.commit() Print("DONE!")<file_sep>/Model_Loaders/Model_5.py def Load_model(name, args): from FunctionCollection import Loss_Functions, customModule import pytorch_lightning as pl from typing import Optional import torch from torch_scatter import scatter_sum, scatter_min, scatter_max from torch_scatter.utils import broadcast from torch_geometric.nn import GATConv, FeaStConv @torch.jit.script def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None, unbiased: bool = True) -> torch.Tensor: if out is not None: dim_size = out.size(dim) if dim < 0: dim = src.dim() + dim count_dim = dim if index.dim() <= dim: count_dim = index.dim() - 1 ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) count = scatter_sum(ones, index, count_dim, dim_size=dim_size) index = broadcast(index, src, dim) tmp = scatter_sum(src, index, dim, dim_size=dim_size) count = broadcast(count, tmp, dim).clamp(1) mean = tmp.div(count) src_minus_mean = (src - mean.gather(dim, index)) var = src_minus_mean * src_minus_mean var = scatter_sum(var, index, dim, out, dim_size) if unbiased: count = count.sub(1).clamp_(1) var = var.div(count) skew = src_minus_mean * src_minus_mean * src_minus_mean / (var.gather(dim,index) + 1e-7)**(1.5) kurtosis = (src_minus_mean * src_minus_mean * src_minus_mean * src_minus_mean) / (var * var + 1e-7).gather(dim,index) skew = scatter_sum(skew, index, dim ,out, dim_size) kurtosis = scatter_sum(kurtosis, index, dim, out, dim_size) skew = skew.div(count) kurtosis = kurtosis.div(count) maximum = scatter_max(src, index, dim, out, dim_size)[0] minimum = scatter_min(src, index, dim, out, dim_size)[0] return torch.cat([mean,var,skew,kurtosis,maximum,minimum],dim=1) N_edge_feats = args['N_edge_feats'] #6 N_dom_feats = args['N_dom_feats']#6 N_scatter_feats = 6 # N_targets = args['N_targets'] N_outputs = args['N_outputs'] N_metalayers = args['N_metalayers'] #10 N_hcs = args['N_hcs'] #32 #Possibly add (edge/node/global)_layers crit, y_post_processor, output_post_processor, cal_acc = Loss_Functions(name, args) likelihood_fitting = True if name[-4:] == 'NLLH' else False class Net(customModule): def __init__(self): super(Net, self).__init__(crit, y_post_processor, output_post_processor, cal_acc, likelihood_fitting, args) self.act = torch.nn.SiLU() self.hcs = N_hcs N_x_feats = N_dom_feats + N_scatter_feats*N_edge_feats N_u_feats = N_scatter_feats*N_x_feats self.x_encoder = torch.nn.Linear(N_x_feats,self.hcs) self.edge_attr_encoder = torch.nn.Linear(N_edge_feats,self.hcs) self.u_encoder = torch.nn.Linear(N_u_feats,self.hcs) class EdgeModel(torch.nn.Module): def __init__(self,hcs,act): super(EdgeModel, self).__init__() self.hcs = hcs self.act = act self.lins = torch.nn.ModuleList() for i in range(2): self.lins.append(torch.nn.Linear(4*self.hcs,4*self.hcs)) self.decoder = torch.nn.Linear(4*self.hcs,self.hcs) def forward(self, src, dest, edge_attr, u, batch): # x: [N, F_x], where N is the number of nodes. # src, dest: [E, F_x], where E is the number of edges. # edge_attr: [E, F_e] # edge_index: [2, E] with max entry N - 1. # u: [B, F_u], where B is the number of graphs. # batch: [N] with max entry B - 1. out = torch.cat([src, dest, edge_attr, u[batch]], dim=1) for lin in self.lins: out = self.act(lin(out)) return self.act(self.decoder(out)) class NodeModel(torch.nn.Module): def __init__(self,hcs,act): super(NodeModel, self).__init__() self.hcs = hcs self.act = act self.FeaStConv = FeaStConv( (2 + N_scatter_feats)*self.hcs, (2 + N_scatter_feats)*self.hcs, 1, False) self.decoder = torch.nn.Linear( (2 + N_scatter_feats)*self.hcs, self.hcs ) def forward(self, x, edge_index, edge_attr, u, batch): row, col = edge_index x = torch.cat([x,scatter_distribution(edge_attr, col, dim=0),u[batch]],dim=1) x = self.act(self.FeaStConv( x, edge_index)) x = self.act(self.decoder( x )) return x class GlobalModel(torch.nn.Module): def __init__(self,hcs,act): super(GlobalModel, self).__init__() self.hcs = hcs self.act = act self.lins1 = torch.nn.ModuleList() for i in range(2): self.lins1.append(torch.nn.Linear((1 + N_scatter_feats)*self.hcs,(1 + N_scatter_feats)*self.hcs)) self.decoder = torch.nn.Linear((1 + N_scatter_feats)*self.hcs,self.hcs) def forward(self, x, edge_index, edge_attr, u, batch): out = torch.cat([u,scatter_distribution(x,batch,dim=0)],dim=1) # 5*hcs for lin in self.lins1: out = self.act(lin(out)) return self.act(self.decoder(out)) from torch_geometric.nn import MetaLayer self.ops = torch.nn.ModuleList() for i in range(N_metalayers): self.ops.append(MetaLayer(EdgeModel(self.hcs,self.act), NodeModel(self.hcs,self.act), GlobalModel(self.hcs,self.act))) self.decoders = torch.nn.ModuleList() self.decoders.append(torch.nn.Linear((1+N_metalayers)*self.hcs + N_scatter_feats*N_x_feats,10*self.hcs)) self.decoders.append(torch.nn.Linear(10*self.hcs,8*self.hcs)) self.decoders.append(torch.nn.Linear(8*self.hcs,6*self.hcs)) self.decoders.append(torch.nn.Linear(6*self.hcs,4*self.hcs)) self.decoders.append(torch.nn.Linear(4*self.hcs,2*self.hcs)) self.decoder = torch.nn.Linear(2*self.hcs,N_outputs) def forward(self,data): x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch x = torch.cat([x,scatter_distribution(edge_attr,edge_index[1],dim=0)],dim=1) u = torch.cat([scatter_distribution(x,batch,dim=0)],dim=1) x0 = x.clone() x = self.act(self.x_encoder(x)) edge_attr = self.act(self.edge_attr_encoder(edge_attr)) u = self.act(self.u_encoder(u)) out = u.clone() for i, op in enumerate(self.ops): x, edge_attr, u = op(x, edge_index, edge_attr, u, batch) out = torch.cat([out,u.clone()],dim=1) out = torch.cat([out,scatter_distribution(x0,batch,dim=0)],dim=1) for lin in self.decoders: out = self.act(lin(out)) out = self.decoder(out) return out return Net # assert 'load' in args, "Specify bool 'load' in args, for loading a checkpoint" # if args['load']: # return Net # else: # return Net() # def Load_model(name, args): # from FunctionCollection import Loss_Functions # import pytorch_lightning as pl # from typing import Optional # import torch # from torch_scatter import scatter_sum, scatter_min, scatter_max # from torch_scatter.utils import broadcast # @torch.jit.script # def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, # out: Optional[torch.Tensor] = None, # dim_size: Optional[int] = None, # unbiased: bool = True) -> torch.Tensor: # if out is not None: # dim_size = out.size(dim) # if dim < 0: # dim = src.dim() + dim # count_dim = dim # if index.dim() <= dim: # count_dim = index.dim() - 1 # ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) # count = scatter_sum(ones, index, count_dim, dim_size=dim_size) # index = broadcast(index, src, dim) # tmp = scatter_sum(src, index, dim, dim_size=dim_size) # count = broadcast(count, tmp, dim).clamp(1) # mean = tmp.div(count) # var = (src - mean.gather(dim, index)) # var = var * var # var = scatter_sum(var, index, dim, out, dim_size) # if unbiased: # count = count.sub(1).clamp_(1) # var = var.div(count) # maximum = scatter_max(src, index, dim, out, dim_size)[0] # minimum = scatter_min(src, index, dim, out, dim_size)[0] # return torch.cat([mean,var,maximum,minimum],dim=1) # N_edge_feats = args['N_edge_feats'] #6 # N_dom_feats = args['N_dom_feats']#6 # N_scatter_feats = 4 # N_targets = args['N_targets'] # N_metalayers = args['N_metalayers'] #10 # N_hcs = args['N_hcs'] #32 # #Possibly add (edge/node/global)_layers # crit, y_post_processor, output_post_processor, cal_acc = Loss_Functions(name, args) # likelihood_fitting = True if name[-4:] == 'NLLH' else False # if args['wandb_activated']: # import wandb # class Net(pl.LightningModule): # def __init__(self): # super(Net, self).__init__() # self.crit = crit # self.y_post_processor = y_post_processor # self.output_post_processor = output_post_processor # self.cal_acc = cal_acc # self.likelihood_fitting = likelihood_fitting # self.act = torch.nn.SiLU() # self.hcs = N_hcs # N_x_feats = N_dom_feats + N_scatter_feats*N_edge_feats # N_u_feats = N_scatter_feats*N_x_feats # self.x_encoder = torch.nn.Linear(N_x_feats,self.hcs) # self.edge_attr_encoder = torch.nn.Linear(N_edge_feats,self.hcs) # self.u_encoder = torch.nn.Linear(N_u_feats,self.hcs) # class EdgeModel(torch.nn.Module): # def __init__(self,hcs,act): # super(EdgeModel, self).__init__() # self.hcs = hcs # self.act = act # self.lins = torch.nn.ModuleList() # for i in range(2): # self.lins.append(torch.nn.Linear(4*self.hcs,4*self.hcs)) # self.decoder = torch.nn.Linear(4*self.hcs,self.hcs) # def forward(self, src, dest, edge_attr, u, batch): # # x: [N, F_x], where N is the number of nodes. # # src, dest: [E, F_x], where E is the number of edges. # # edge_attr: [E, F_e] # # edge_index: [2, E] with max entry N - 1. # # u: [B, F_u], where B is the number of graphs. # # batch: [N] with max entry B - 1. # out = torch.cat([src, dest, edge_attr, u[batch]], dim=1) # for lin in self.lins: # out = self.act(lin(out)) # return self.act(self.decoder(out)) # class NodeModel(torch.nn.Module): # def __init__(self,hcs,act): # super(NodeModel, self).__init__() # self.hcs = hcs # self.act = act # self.lins1 = torch.nn.ModuleList() # for i in range(2): # self.lins1.append(torch.nn.Linear(2*self.hcs,2*self.hcs)) # self.lins2 = torch.nn.ModuleList() # for i in range(2): # self.lins2.append(torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,(2 + 2*N_scatter_feats)*self.hcs)) # self.decoder = torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,self.hcs) # def forward(self, x, edge_index, edge_attr, u, batch): # row, col = edge_index # out = torch.cat([x[row],edge_attr],dim=1) # for lin in self.lins1: # out = self.act(lin(out)) # out = scatter_distribution(out,col,dim=0) #8*hcs # out = torch.cat([x,out,u[batch]],dim=1) # for lin in self.lins2: # out = self.act(lin(out)) # return self.act(self.decoder(out)) # class GlobalModel(torch.nn.Module): # def __init__(self,hcs,act): # super(GlobalModel, self).__init__() # self.hcs = hcs # self.act = act # self.lins1 = torch.nn.ModuleList() # for i in range(2): # self.lins1.append(torch.nn.Linear((1 + N_scatter_feats)*self.hcs,(1 + N_scatter_feats)*self.hcs)) # self.decoder = torch.nn.Linear((1 + N_scatter_feats)*self.hcs,self.hcs) # def forward(self, x, edge_index, edge_attr, u, batch): # out = torch.cat([u,scatter_distribution(x,batch,dim=0)],dim=1) # 5*hcs # for lin in self.lins1: # out = self.act(lin(out)) # return self.act(self.decoder(out)) # from torch_geometric.nn import MetaLayer # self.ops = torch.nn.ModuleList() # for i in range(N_metalayers): # self.ops.append(MetaLayer(EdgeModel(self.hcs,self.act), NodeModel(self.hcs,self.act), GlobalModel(self.hcs,self.act))) # self.decoders = torch.nn.ModuleList() # self.decoders.append(torch.nn.Linear((1+N_metalayers)*self.hcs + N_scatter_feats*N_x_feats,10*self.hcs)) # self.decoders.append(torch.nn.Linear(10*self.hcs,8*self.hcs)) # self.decoders.append(torch.nn.Linear(8*self.hcs,6*self.hcs)) # self.decoders.append(torch.nn.Linear(6*self.hcs,4*self.hcs)) # self.decoders.append(torch.nn.Linear(4*self.hcs,2*self.hcs)) # self.decoder = torch.nn.Linear(2*self.hcs,N_targets) # def forward(self,data): # x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch # x = torch.cat([x,scatter_distribution(edge_attr,edge_index[1],dim=0)],dim=1) # u = torch.cat([scatter_distribution(x,batch,dim=0)],dim=1) # x0 = x.clone() # x = self.act(self.x_encoder(x)) # edge_attr = self.act(self.edge_attr_encoder(edge_attr)) # u = self.act(self.u_encoder(u)) # out = u.clone() # for i, op in enumerate(self.ops): # x, edge_attr, u = op(x, edge_index, edge_attr, u, batch) # out = torch.cat([out,u.clone()],dim=1) # out = torch.cat([out,scatter_distribution(x0,batch,dim=0)],dim=1) # for lin in self.decoders: # out = self.act(lin(out)) # out = self.decoder(out) # return out # def configure_optimizers(self): # from FunctionCollection import lambda_lr # optimizer = torch.optim.Adam(self.parameters(), lr=args['lr']) # scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda_lr) # return [optimizer], [scheduler] # def training_step(self, data, batch_idx): # label = self.y_post_processor(data.y) # if self.likelihood_fitting: # output, cov = self.output_post_processor( self(data) ) # loss = self.crit(output, cov, label) # else: # output = self.output_post_processor( self(data) ) # loss = self.crit(output, label) # acc = self.cal_acc(output, label) # if args['wandb_activated']: # wandb.log({"Train Loss": loss.item(), # "Train Acc": acc}) # return {'loss': loss} # def validation_step(self, data, batch_idx): # label = self.y_post_processor(data.y) # if self.likelihood_fitting: # output, cov = self.output_post_processor( self(data) ) # else: # output = self.output_post_processor( self(data) ) # acc = self.cal_acc(output, label) # if args['wandb_activated']: # wandb.log({"val_batch_acc": acc}) # return {'val_batch_acc': torch.tensor(acc,dtype=torch.float)} # def validation_epoch_end(self, outputs): # avg_acc = torch.stack([x['val_batch_acc'] for x in outputs]).mean() # if args['wandb_activated']: # wandb.log({"Val Acc": avg_acc}) # return {'Val Acc': avg_acc} # def test_step(self, data, batch_idx): # label = self.y_post_processor(data.y) # if self.likelihood_fitting: # output, cov = self.output_post_processor( self(data) ) # else: # output = self.output_post_processor( self(data) ) # acc = self.cal_acc(output, label) # if args['wandb_activated']: # wandb.log({"Test Acc": acc}) # return {'test_batch_acc': torch.tensor(acc,dtype=torch.float)} # def test_epoch_end(self, outputs): # avg_acc = torch.stack([x['test_batch_acc'] for x in outputs]).mean() # if args['wandb_activated']: # wandb.log({"Test Acc": avg_acc}) # return {'Test Acc': avg_acc} # return Net()<file_sep>/Model_Loaders/Model_23.py def Load_model(name, args): from FunctionCollection import Loss_Functions, customModule import pytorch_lightning as pl from typing import Optional import torch from torch_scatter import scatter_sum, scatter_min, scatter_max from torch_scatter.utils import broadcast @torch.jit.script def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None, unbiased: bool = True) -> torch.Tensor: if out is not None: dim_size = out.size(dim) if dim < 0: dim = src.dim() + dim count_dim = dim if index.dim() <= dim: count_dim = index.dim() - 1 ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) count = scatter_sum(ones, index, count_dim, dim_size=dim_size) index = broadcast(index, src, dim) tmp = scatter_sum(src, index, dim, dim_size=dim_size) summ = tmp.clone() count = broadcast(count, tmp, dim).clamp(1) mean = tmp.div(count) var = (src - mean.gather(dim, index)) var = var * var var = scatter_sum(var, index, dim, out, dim_size) if unbiased: count = count.sub(1).clamp_(1) var = var.div(count) maximum = scatter_max(src, index, dim, out, dim_size)[0] minimum = scatter_min(src, index, dim, out, dim_size)[0] return torch.cat([summ,mean,var,maximum,minimum],dim=1) N_edge_feats = args['N_edge_feats'] #6 N_dom_feats = args['N_dom_feats']#6 N_scatter_feats = 5 # N_targets = args['N_targets'] N_outputs = args['N_outputs'] N_metalayers = args['N_metalayers'] #10 N_hcs = args['N_hcs'] #32 print("if features = x, Charge should be at x[:,-5], time at x[:,-4] and pos at x[:,-3:]") assert N_dom_feats == len(args['features'].split(', ')) crit, y_post_processor, output_post_processor, cal_acc = Loss_Functions(name, args) likelihood_fitting = True if name[-4:] == 'NLLH' else False class Net(customModule): def __init__(self): super(Net, self).__init__(crit, y_post_processor, output_post_processor, cal_acc, likelihood_fitting, args) self.act = torch.nn.SiLU() self.hcs = N_hcs class MLP(torch.nn.Module): def __init__(self, hcs_list, act = self.act, clean_out = False): super(MLP, self).__init__() mlp = [] for i in range(1,len(hcs_list)): mlp.append(torch.nn.Linear(hcs_list[i-1], hcs_list[i])) mlp.append(torch.nn.BatchNorm1d(hcs_list[i])) mlp.append(act) if clean_out: self.mlp = torch.nn.Sequential(*mlp[:-2]) else: self.mlp = torch.nn.Sequential(*mlp) def forward(self, x): return self.mlp(x) class FullConv(torch.nn.Module): def __init__(self, hcs_in, hcs_out, act = self.act): super(FullConv, self).__init__() self.self_mlp = MLP([hcs_in,hcs_out]) self.msg_mlp = torch.nn.Sequential(torch.nn.Linear(2*hcs_in,hcs_out), act) self.msg_mlp2 = MLP([4*hcs_out,hcs_out]) def forward(self, x, graph_node_counts): li : List[int] = graph_node_counts.tolist() tmp = [] for tmp_x in x.split(li): tmp_x = torch.cat([tmp_x.unsqueeze(1) - tmp_x, tmp_x.unsqueeze(1) + tmp_x],dim=2) tmp_x = self.msg_mlp(tmp_x) tmp.append(torch.cat([tmp_x.mean(1),tmp_x.std(1),tmp_x.min(1)[0],tmp_x.max(1)[0]],dim=1)) return self.self_mlp(x) + self.msg_mlp2(torch.cat(tmp,0)) class scatter_norm(torch.nn.Module): def __init__(self, hcs): super(scatter_norm, self).__init__() self.batch_norm = torch.nn.BatchNorm1d(N_scatter_feats*hcs) def forward(self, x, batch): return self.batch_norm(scatter_distribution(x,batch,dim=0)) N_x_feats = N_dom_feats# + 4*(N_dom_feats + 1) N_CoC_feats = N_scatter_feats*N_x_feats + 3 self.scatter_norm = scatter_norm(N_x_feats) self.x_encoder = MLP([N_x_feats,self.hcs]) self.CoC_encoder = MLP([N_CoC_feats,self.hcs]) self.convs = torch.nn.ModuleList() self.scatter_norms = torch.nn.ModuleList() for _ in range(N_metalayers): self.convs.append(FullConv(self.hcs,self.hcs)) self.scatter_norms.append(scatter_norm(self.hcs)) self.decoder = MLP([(1+N_scatter_feats*N_metalayers)*self.hcs,self.hcs,N_outputs],clean_out=True) def forward(self,data): x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch ############### x = x.float() ############### CoC = scatter_sum( x[:,-3:]*x[:,-5].view(-1,1), batch, dim=0) / scatter_sum(x[:,-5].view(-1,1), batch, dim=0) CoC = torch.cat([CoC,self.scatter_norm(x,batch)],dim=1) x = self.x_encoder(x) CoC = self.CoC_encoder(CoC) graph_ids, graph_node_counts = batch.unique(return_counts=True) for conv, scatter_norm in zip(self.convs,self.scatter_norms): x = conv(x, graph_node_counts) CoC = torch.cat([CoC,scatter_norm(x, batch)],dim=1) CoC = self.decoder(CoC) return CoC return Net<file_sep>/Model_Loaders/Model_10.py def Load_model(name, args): from FunctionCollection import Loss_Functions, customModule, edge_feature_constructor import pytorch_lightning as pl from typing import Optional import torch from torch_scatter import scatter_sum, scatter_min, scatter_max from torch_scatter.utils import broadcast import torch.nn.functional as F @torch.jit.script def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None, unbiased: bool = True) -> torch.Tensor: if out is not None: dim_size = out.size(dim) if dim < 0: dim = src.dim() + dim count_dim = dim if index.dim() <= dim: count_dim = index.dim() - 1 ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) count = scatter_sum(ones, index, count_dim, dim_size=dim_size) index = broadcast(index, src, dim) tmp = scatter_sum(src, index, dim, dim_size=dim_size) count = broadcast(count, tmp, dim).clamp(1) mean = tmp.div(count) var = (src - mean.gather(dim, index)) var = var * var var = scatter_sum(var, index, dim, out, dim_size) if unbiased: count = count.sub(1).clamp_(1) var = var.div(count) maximum = scatter_max(src, index, dim, out, dim_size)[0] minimum = scatter_min(src, index, dim, out, dim_size)[0] return torch.cat([mean,var,maximum,minimum],dim=1) @torch.jit.script def x_feature_constructor(x, graph_node_counts): tmp = [] a : List[int] = graph_node_counts.tolist() for tmp_x in x.split(a): tmp_x = tmp_x.unsqueeze(1) - tmp_x cart = tmp_x[:,:,-3:] rho = torch.norm(cart, p=2, dim=-1).unsqueeze(2) rho_mask = rho.squeeze() != 0 cart[rho_mask] = cart[rho_mask] / rho[rho_mask] tmp_x = torch.cat([cart,rho,tmp_x[:,:,:-3]],dim=2) tmp.append(torch.cat([tmp_x.mean(1),tmp_x.std(1),tmp_x.min(1)[0],tmp_x.max(1)[0]],dim=1)) return torch.cat(tmp,0) @torch.jit.script def time_edge_indeces(t, batch: torch.Tensor): time_sort = torch.argsort(t) graph_ids, graph_node_counts = torch.unique(batch,return_counts=True) batch_time_sort = torch.cat( [time_sort[batch[time_sort] == i] for i in graph_ids] ) time_edge_index = torch.cat([batch_time_sort[:-1].view(1,-1),batch_time_sort[1:].view(1,-1)],dim=0) tmp_ind = (torch.cumsum(graph_node_counts,0) - 1)[:-1] li : List[int] = (tmp_ind + 1).tolist() time_edge_index[1,tmp_ind] = time_edge_index[0, [0] + li[:-1]] time_edge_index = torch.cat([time_edge_index, torch.cat([time_edge_index[1,-1].view(1,1), time_edge_index[0,(tmp_ind + 1)[-1]].view(1,1)])],dim=1) time_edge_index = time_edge_index[:,torch.argsort(time_edge_index[1])] return time_edge_index N_edge_feats = args['N_edge_feats'] #6 N_dom_feats = args['N_dom_feats']#6 N_scatter_feats = 4 N_outputs = args['N_outputs'] N_metalayers = args['N_metalayers'] #10 N_hcs = args['N_hcs'] #32 # p_dropout = args['dropout'] crit, y_post_processor, output_post_processor, cal_acc = Loss_Functions(name, args) likelihood_fitting = True if name[-4:] == 'NLLH' else False class Net(customModule): def __init__(self): super(Net, self).__init__(crit, y_post_processor, output_post_processor, cal_acc, likelihood_fitting, args) print("This model assumes Charge is at index 0 and position is the last three") self.act = torch.nn.SiLU() self.hcs = N_hcs # self.dropout = torch.nn.Dropout(p=p_dropout) class MLP(torch.nn.Module): def __init__(self, hcs_list, act = self.act, no_final_act = False): super(MLP, self).__init__() mlp = [] for i in range(1,len(hcs_list)): mlp.append(torch.nn.Linear(hcs_list[i-1], hcs_list[i])) mlp.append(torch.nn.BatchNorm1d(hcs_list[i])) mlp.append(act) if not no_final_act: self.mlp = torch.nn.Sequential(*mlp) else: self.mlp = torch.nn.Sequential(*mlp[:-1]) def forward(self, x): return self.mlp(x) class AttGNN(torch.nn.Module): def __init__(self, hcs_in, hcs_out, act = self.act): super(AttGNN, self).__init__() self.beta = torch.nn.Parameter(torch.ones(1)*20) self.query_mlp = MLP([hcs_in,hcs_in,hcs_out]) self.self_mlp = MLP([hcs_in,hcs_in,hcs_out]) self.msg_mlp = MLP([hcs_in,hcs_in,hcs_out]) def forward(self, x, graph_node_counts): li : List[int] = graph_node_counts.tolist() tmp = [] for tmp_x, msg in zip(self.query_mlp(x).split(li), self.msg_mlp(x).split(li)): att = F.normalize(tmp_x,p=2.,dim=1) att = torch.cdist(att,att) tmp.append(torch.matmul(F.softmax(self.beta*att,1),msg)) return self.self_mlp(x) + torch.cat(tmp,0) # att = [] # for tmp_x in x.split(graph_node_counts.tolist()): # tmp_x = F.normalize(tmp_x,p=2,dim=1) # tmp_x = torch.cdist(tmp_x,tmp_x) # att.append(F.softmax(self.beta*tmp_x,1)) # return self.self_mlp(x) + torch.matmul(torch.block_diag(*att), self.msg_mlp(x)) N_x_feats = N_dom_feats + 4*(N_dom_feats + 1) + 4 + 3 self.x_encoder = MLP([N_x_feats,self.hcs,self.hcs]) self.convs = torch.nn.ModuleList() for i in range(N_metalayers): self.convs.append(torch.jit.script(AttGNN(self.hcs,self.hcs))) self.decoder = MLP([N_scatter_feats*self.hcs,N_scatter_feats//2*self.hcs,self.hcs,N_outputs],no_final_act=True) def return_CoC_and_edge_attr(self, x, batch): pos = x[:,-3:] charge = x[:,0].view(-1,1) # Define central nodes at Center of Charge: CoC = scatter_sum( pos*charge, batch, dim=0) / scatter_sum(charge, batch, dim=0) # Define edge_attr for those edges: cart = pos - CoC[batch] rho = torch.norm(cart, p=2, dim=1).view(-1, 1) rho_mask = rho.squeeze() != 0 cart[rho_mask] = cart[rho_mask] / rho[rho_mask] CoC_edge_attr = torch.cat([cart.type_as(x),rho.type_as(x)], dim=1) return CoC, CoC_edge_attr def forward(self,data): x, batch = data.x.float(), data.batch graph_ids, graph_node_counts = batch.unique(return_counts=True) CoC, CoC_edge_attr = self.return_CoC_and_edge_attr(x, batch) x = torch.cat([x, x_feature_constructor(x,graph_node_counts), CoC_edge_attr, CoC[batch]],dim=1) x = self.x_encoder(x) for conv in self.convs: x = conv(x,graph_node_counts) return self.decoder(scatter_distribution(x,batch,dim=0)) return Net<file_sep>/legacy/Models/Model1.py import torch.nn.functional as F import torch from torch_geometric.nn import GCNConv from torch_scatter import scatter_mean class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = GCNConv(5, 5*6) self.conv2 = GCNConv(5*6, 8) def forward(self, data): x, edge_index = data.x, data.edge_index x = self.conv1(x, edge_index) x = F.relu(x) x = F.dropout(x, training=self.training) x = self.conv2(x, edge_index) return scatter_mean(x,data.batch,dim=0) #scatter_mean ensures output is independent of num_nodes<file_sep>/Model_Loaders/__init__.py #Model_1 is purely homemade GCN #Model_2 is investigation of TGCN, shows not too bad results, so: #Model_3 is a 'better' implementation #Model_4 is playing with another scatter_distribution function that returns skew and kurtosis instead of max, min #Model_5 FeaStConv #Model_7 Tried different stuff, firstly added a central node, with edges to/from all other nodes on which message passing is done through a GRUcell, this works nicely. I then tried removing the edge_attr_update and later the node_update, which both did not affect the accuracy. #(this is reflected in m71 on wandb) #(m72 is the same model but without any dependancy on pre-defined edge_indeces) #(m73 is then the same model but with feature_construction included) #(m732 is switching the concatenation when doing message pass the other way) #Model_9 is Model_7 but 'improved' with batchnormalization and perhaps skiplayer and so forth<file_sep>/Trainer.py # import json # exp_path = r"C:\Users\jv97\Desktop\github\Neutrino-Machine-Learning\args.json" # with open(exp_path) as file: # args = json.load(file) from argparse import ArgumentParser import numpy as np import matplotlib.pyplot as plt import torch import pandas as pd import time import wandb import pytorch_lightning as pl import sqlite3 import FunctionCollection as fc import importlib fc = importlib.reload(fc) import os path = r'C:\Users\jv97\Desktop\github\Neutrino-Machine-Learning' run_name = 'TEST_OscNext_AngleO_m17' args = {'N_edge_feats': 6, 'N_dom_feats': 7, 'N_targets': 2, 'N_outputs': 3, 'N_metalayers': 2, 'N_hcs': 64, 'diagonal_cov': True, 'wandb_activated': True, 'type': 'Spherical_NLLH', 'zenith': True, 'id': wandb.util.generate_id()[:4], 'eps': 1e-5, 'output_offset': [3.14,1.57], 'lr': 3e-3, 'batch_size': 512, 'filename': 'Nu_lvl7_1Mio_unscaled_SRT.db',#dev_level7_mu_e_tau_oscweight_000.db #rasmus_classification_muon_3neutrino_3mio.db #dev_level7_oscNext_IC86_003.db 'features': 'width, rqe, charge_log10, dom_time, dom_x, dom_y, dom_z',#'charge_log10, dom_time, width, rqe, dom_x, dom_y, dom_z', # SRTInIcePulses, 'targets': 'azimuth, zenith', 'TrTV': (0.9,0.999,1),#(0.025,0.995,1) 'SRT_clean': False } centers = pd.DataFrame({'charge_log10': [-0.033858], 'dom_time': [10700.0], 'dom_x': [0], 'dom_y': [0], 'dom_z': [0], 'width': [4.5], 'rqe': [1.175]}) scalers = pd.DataFrame({'charge_log10': [0.274158], 'dom_time': [2699.0], 'dom_x': [300], 'dom_y': [300], 'dom_z': [300], 'width': [3.5], 'rqe': [0.175]}) centers = centers[args['features'].split(', ')].values scalers = scalers[args['features'].split(', ')].values def x_transform(df): df = (df - centers)/scalers return torch.tensor(df.values) def y_transform(df): return torch.tensor(df.values) from typing import List @torch.jit.script def batch_transform(x,events: List[int]): tmp_x = x.unsqueeze(1) - x cart = tmp_x[:,:,-3:] rho = torch.norm(cart, p=2, dim=-1).unsqueeze(2) rho_mask = rho.squeeze() != 0 if rho_mask.sum() != 0: cart[rho_mask] = cart[rho_mask] / rho[rho_mask] tmp_x = torch.cat([cart,rho,tmp_x[:,:,:-3]],dim=2) return torch.cat([tmp_x.mean(1),tmp_x.std(1),tmp_x.min(1)[0],tmp_x.max(1)[0],x],dim=1) filepath = os.path.join(path,'raw_data') def return_trainer(ckpt = None): early_stop_callback = pl.callbacks.early_stopping.EarlyStopping(monitor='Val Acc', min_delta=0.00, patience=20, verbose=False, mode='min') checkpoint_callback = pl.callbacks.ModelCheckpoint(dirpath = path + '/checkpoints/' + run_name + '_' + args['id'], filename = '{epoch}-{Val Acc:.3f}', save_top_k = 1, verbose = True, monitor = 'Val Acc', mode = 'min', prefix = run_name) lr_logger = pl.callbacks.lr_monitor.LearningRateMonitor(logging_interval = 'epoch') from pytorch_lightning.loggers import WandbLogger wandb_logger = WandbLogger(name = run_name, project = 'Neutrino-Machine-Learning', id = run_name + '_' + args['id'], # id and version can be interchanged, depending on whether you want to initialize or resume save_dir = path) #Specify version as id if you want to resume a run. trainer = pl.Trainer(gpus=hparams.gpus, #-1 for all gpus min_epochs=1, max_epochs=50, auto_lr_find = False, # accelerator = 'ddp', auto_select_gpus = True, log_every_n_steps = 50, terminate_on_nan = True, num_sanity_val_steps = 0, callbacks=[early_stop_callback, checkpoint_callback, lr_logger], logger = wandb_logger if args['wandb_activated'] else False, default_root_dir = path) return trainer, wandb_logger def main(hparams): import Model_Loaders.Model_17 as M M = importlib.reload(M) Net = M.Load_model(args['type'],args) model = Net() trainer, wandb_logger = return_trainer() dataset = fc.custom_db_dataset(filepath = filepath, filename = args['filename'], features = args['features'], targets = args['targets'], TrTV = args['TrTV'], # event_nos = event_nos, x_transform = x_transform, y_transform = y_transform, batch_transform = batch_transform, shuffle = True, SRT_clean = args['SRT_clean'], # reweighter = ze_reweighter ) train_loader, test_loader, val_loader = dataset.return_dataloaders(batch_size=args['batch_size'],num_workers = 0) # lr_finder = trainer.tuner.lr_find(model,train_loader,val_loader,min_lr=1e-6,max_lr=5e-2,num_training=100,mode='exponential',early_stop_threshold=4) # fig = lr_finder.plot(True,True) # print(lr_finder.suggestion()) # fig.show() device = torch.device('cuda') model.to(device) for dat in train_loader: dat.to(device) model.training_step(dat,None) break print(model.log) if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('--gpus', default=None) hparams = parser.parse_args() main(hparams)<file_sep>/legacy/MergeDataBases.py import sqlite3 import pandas as pd # db_file_list = ['C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\raw_data\\120000_00.db', # 'C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\raw_data\\140000_00.db', # 'C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\raw_data\\160000_00.db'] # # scalar = pd.DataFrame() # # sequential = pd.DataFrame() # Possibly: Electron, Tau, Muon # for db_file in db_file_list: # # with sqlite3.connect(db_file) as con: # # query = 'select * from sequential' # MERGES ALL .db FILES TO TWO .csv FILES: # sequential = sequential.append(pd.read_sql(query, con)) # scalar.csv , sequential.csv # query = 'select * from scalar' # THESE ARE THEN WRITTEN TO DRIVE # scalar = scalar.append(pd.read_sql(query, con)) # # cursor = con.cursor() # # cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") # sequential.to_csv(r'C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\data\\sequential.csv') # scalar.to_csv(r'C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\data\\scalar.csv') # db_file_list = ['C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\raw_data\\139008_00.db'] # # scalar = pd.DataFrame() # # sequential = pd.DataFrame() # Possibly: cosmic background # for db_file in db_file_list: # # with sqlite3.connect(db_file) as con: # # query = 'select * from sequential' # MERGES ALL .db FILES TO TWO .csv FILES: # sequential = sequential.append(pd.read_sql(query, con)) # scalar.csv , sequential.csv # query = 'select * from scalar' # THESE ARE THEN WRITTEN TO DRIVE # scalar = scalar.append(pd.read_sql(query, con)) # # cursor = con.cursor() # # cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") # sequential.to_csv(r'C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\data\\sequential_background.csv') # scalar.to_csv(r'C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\data\\scalar_background.csv') db_file_list = ['C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\raw_data\\rasmus_classification_muon_3neutrino_3mio.db'] # scalar = pd.DataFrame() # sequential = pd.DataFrame() # Possibly: cosmic background for db_file in db_file_list: # with sqlite3.connect(db_file) as con: # query = 'select * from sequential' # MERGES ALL .db FILES TO TWO .csv FILES: sequential = sequential.append(pd.read_sql(query, con)) # scalar.csv , sequential.csv query = 'select * from scalar' # THESE ARE THEN WRITTEN TO DRIVE scalar = scalar.append(pd.read_sql(query, con)) # cursor = con.cursor() # cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") sequential.to_csv(r'C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\data\\seq_rasmus.csv') scalar.to_csv(r'C:\\Users\\jv97\\Desktop\\github\\Neutrino-Machine-Learning\\data\\scalar_rasmus.csv')<file_sep>/Model_Loaders/Model_8.py def Load_model(name, args): from FunctionCollection import Loss_Functions, customModule, edge_feature_constructor import pytorch_lightning as pl from typing import Optional import torch from torch_scatter import scatter_sum, scatter_min, scatter_max from torch_scatter.utils import broadcast @torch.jit.script def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None, unbiased: bool = True) -> torch.Tensor: if out is not None: dim_size = out.size(dim) if dim < 0: dim = src.dim() + dim count_dim = dim if index.dim() <= dim: count_dim = index.dim() - 1 ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) count = scatter_sum(ones, index, count_dim, dim_size=dim_size) index = broadcast(index, src, dim) tmp = scatter_sum(src, index, dim, dim_size=dim_size) count = broadcast(count, tmp, dim).clamp(1) mean = tmp.div(count) var = (src - mean.gather(dim, index)) var = var * var var = scatter_sum(var, index, dim, out, dim_size) if unbiased: count = count.sub(1).clamp_(1) var = var.div(count) maximum = scatter_max(src, index, dim, out, dim_size)[0] minimum = scatter_min(src, index, dim, out, dim_size)[0] return torch.cat([mean,var,maximum,minimum],dim=1) N_edge_feats = args['N_edge_feats'] #6 N_dom_feats = args['N_dom_feats']#6 N_scatter_feats = 4 # N_targets = args['N_targets'] N_outputs = args['N_outputs'] N_metalayers = args['N_metalayers'] #10 N_hcs = args['N_hcs'] #32 #Possibly add (edge/node/global)_layers crit, y_post_processor, output_post_processor, cal_acc = Loss_Functions(name, args) likelihood_fitting = True if name[-4:] == 'NLLH' else False class Net(customModule): def __init__(self): super(Net, self).__init__(crit, y_post_processor, output_post_processor, cal_acc, likelihood_fitting, args) self.act = torch.nn.SiLU() self.hcs = N_hcs N_x_feats = 2*N_dom_feats + N_edge_feats self.x_encoder = torch.nn.Linear(N_x_feats,self.hcs) # class Conversation(torch.nn.Module): # def __init__(self,hcs,act): # super(Conversation, self).__init__() # self.act = act # self.hcs = hcs # self.GRU = torch.nn.GRUCell(3*self.hcs,self.hcs) # self.lin_msg1 = torch.nn.Linear((1+N_scatter_feats)*self.hcs,self.hcs) # self.lin_msg2 = torch.nn.Linear((1+N_scatter_feats)*self.hcs,self.hcs) # def forward(self, x, edge_index, edge_attr, batch, h): # (frm, to) = edge_index # h = self.act( self.GRU( torch.cat([x[to],x[frm],edge_attr],dim=1), h ) ) # x = self.act( self.lin_msg1( torch.cat([x,scatter_distribution(h, to, dim=0)],dim=1) ) ) # h = self.act( self.GRU( torch.cat([x[frm],x[to],edge_attr],dim=1), h) ) # x = self.act( self.lin_msg2( torch.cat([x,scatter_distribution(h, frm, dim=0)],dim=1) ) ) # return x class GRUConv(torch.nn.Module): def __init__(self,hcs,act): super(GRUConv, self).__init__() self.hcs = hcs self.act = act self.GRU = torch.nn.GRUCell(self.hcs, self.hcs) self.lin = torch.nn.Linear(2*self.hcs, self.hcs) def forward(self, x, edge_index, edge_attr, batch, h): (frm, to) = edge_index h = self.act( self.GRU( x, h ) ) x = torch.cat([x,h[frm]], dim=1) x = self.act( self.lin( x ) ) return x self.GRUConvs = torch.nn.ModuleList() # self.ConvConvs = torch.nn.ModuleList() for i in range(N_metalayers): self.GRUConvs.append(GRUConv(self.hcs,self.act)) # self.ConvConvs.append(Conversation(self.hcs,self.act) self.decoders = torch.nn.ModuleList() self.decoders.append(torch.nn.Linear(4*self.hcs,self.hcs)) self.decoders.append(torch.nn.Linear(self.hcs,self.hcs)) self.decoder = torch.nn.Linear(self.hcs,N_outputs) def forward(self,data): x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch time_sort = torch.argsort(x[:,1]) graph_ids, graph_node_counts = batch.unique(return_counts=True) batch_time_sort = torch.cat( [time_sort[batch[time_sort] == i] for i in graph_ids] ) time_edge_index = torch.cat([batch_time_sort[:-1].view(1,-1),batch_time_sort[1:].view(1,-1)],dim=0) tmp_ind = (torch.cumsum(graph_node_counts,0) - 1)[:-1] time_edge_index[1,tmp_ind] = time_edge_index[0, [0] + (tmp_ind + 1).tolist()[:-1]] time_edge_index = torch.cat([time_edge_index, torch.cat([time_edge_index[1,-1].view(1,1), time_edge_index[0,(tmp_ind + 1)[-1]].view(1,1)])],dim=1) time_edge_index = time_edge_index[:,torch.argsort(time_edge_index[1])] edge_attr = edge_feature_constructor(x, time_edge_index) x = torch.cat([x,edge_attr,x[time_edge_index[0]]],dim=1) x = self.act(self.x_encoder(x)) h = torch.zeros( (x.shape[0], self.hcs) ).type_as(x) for i, conv in enumerate(self.GRUConvs): x = conv(x, time_edge_index, edge_attr, batch, h) out = scatter_distribution(x,batch,dim=0) for lin in self.decoders: out = self.act(lin(out)) out = self.decoder(out) return out return Net<file_sep>/legacy/Models/Model11_2.py from typing import Optional import torch from torch_scatter import scatter_sum, scatter_min, scatter_max from torch_scatter.utils import broadcast @torch.jit.script def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None, unbiased: bool = True) -> torch.Tensor: if out is not None: dim_size = out.size(dim) if dim < 0: dim = src.dim() + dim count_dim = dim if index.dim() <= dim: count_dim = index.dim() - 1 ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) count = scatter_sum(ones, index, count_dim, dim_size=dim_size) index = broadcast(index, src, dim) tmp = scatter_sum(src, index, dim, dim_size=dim_size) count = broadcast(count, tmp, dim).clamp(1) mean = tmp.div(count) var = (src - mean.gather(dim, index)) var = var * var var = scatter_sum(var, index, dim, out, dim_size) if unbiased: count = count.sub(1).clamp_(1) var = var.div(count) maximum = scatter_max(src, index, dim, out, dim_size)[0] minimum = scatter_min(src, index, dim, out, dim_size)[0] return torch.cat([mean,var,maximum,minimum],dim=1) N_edge_feats = 6 N_dom_feats = 6 N_scatter_feats = 4 N_targets = 1 class Net11(torch.nn.Module): def __init__(self): super(Net11, self).__init__() # self.act = torch.nn.LeakyReLU(negative_slope=0.05) self.act = torch.nn.SiLU() #SiLU is x/(1+exp(-x)) # self.ReLU = torch.nn.ReLU() # self.act = torch.nn.Tanh() self.hcs = 32 # self.sum_scaler = torch.nn.Parameter(torch.Tensor([1000])) # global scatter_distribution # scatter_distribution = scatter_distribution_wrapper(self.sum_scaler) # from sklearn.preprocessing import RobustScaler, MinMaxScaler # # self.scaler = RobustScaler(quantile_range=(5,95)) # self.scaler = MinMaxScaler() # self.scaler.fit(dataset.data.x) #Perhaps revise this N_x_feats = N_dom_feats + N_scatter_feats*N_edge_feats N_u_feats = N_scatter_feats*N_x_feats self.x_encoder = torch.nn.Linear(N_x_feats,self.hcs) self.edge_attr_encoder = torch.nn.Linear(N_edge_feats,self.hcs) self.u_encoder = torch.nn.Linear(N_u_feats,self.hcs) class EdgeModel(torch.nn.Module): def __init__(self,hcs,act): super(EdgeModel, self).__init__() self.hcs = hcs self.act = act self.lins = torch.nn.ModuleList() for i in range(2): self.lins.append(torch.nn.Linear(4*self.hcs,4*self.hcs)) self.decoder = torch.nn.Linear(4*self.hcs,self.hcs) def forward(self, src, dest, edge_attr, u, batch): # x: [N, F_x], where N is the number of nodes. # src, dest: [E, F_x], where E is the number of edges. # edge_attr: [E, F_e] # edge_index: [2, E] with max entry N - 1. # u: [B, F_u], where B is the number of graphs. # batch: [N] with max entry B - 1. out = torch.cat([src, dest, edge_attr, u[batch]], dim=1) for lin in self.lins: out = self.act(lin(out)) return self.act(self.decoder(out)) class NodeModel(torch.nn.Module): def __init__(self,hcs,act): super(NodeModel, self).__init__() self.hcs = hcs self.act = act self.lins1 = torch.nn.ModuleList() for i in range(2): self.lins1.append(torch.nn.Linear(2*self.hcs,2*self.hcs)) self.lins2 = torch.nn.ModuleList() for i in range(2): self.lins2.append(torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,(2 + 2*N_scatter_feats)*self.hcs)) self.decoder = torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,self.hcs) def forward(self, x, edge_index, edge_attr, u, batch): row, col = edge_index out = torch.cat([x[row],edge_attr],dim=1) for lin in self.lins1: out = self.act(lin(out)) # out = torch.cat([scatter_mean(out,col,dim=0),torch.square(scatter_std(out,col,dim=0))],dim=1) #6*hcs # out = scatter_mean(out,col,dim=0) #4*hcs out = scatter_distribution(out,col,dim=0) #8*hcs out = torch.cat([x,out,u[batch]],dim=1) for lin in self.lins2: out = self.act(lin(out)) return self.act(self.decoder(out)) class GlobalModel(torch.nn.Module): def __init__(self,hcs,act): super(GlobalModel, self).__init__() self.hcs = hcs self.act = act self.lins1 = torch.nn.ModuleList() for i in range(2): self.lins1.append(torch.nn.Linear((1 + N_scatter_feats)*self.hcs,(1 + N_scatter_feats)*self.hcs)) self.decoder = torch.nn.Linear((1 + N_scatter_feats)*self.hcs,self.hcs) def forward(self, x, edge_index, edge_attr, u, batch): # out = torch.cat([u,scatter_mean(x,batch,dim=0),torch.square(scatter_std(x,batch,dim=0))],dim=1) # 3*hcs # out = torch.cat([u,scatter_mean(x,batch,dim=0)],dim=1) # 2*hcs out = torch.cat([u,scatter_distribution(x,batch,dim=0)],dim=1) # 5*hcs for lin in self.lins1: out = self.act(lin(out)) return self.act(self.decoder(out)) from torch_geometric.nn import MetaLayer self.ops = torch.nn.ModuleList() num_metalayers = 10 for i in range(num_metalayers): self.ops.append(MetaLayer(EdgeModel(self.hcs,self.act), NodeModel(self.hcs,self.act), GlobalModel(self.hcs,self.act))) # self.rnn = torch.nn.LSTM(self.hcs,self.hcs,num_layers=1,batch_first=True) self.decoders = torch.nn.ModuleList() # for i in range(8,2,-2): # self.decoders.append(torch.nn.Linear(i*self.hcs,(i-2)*self.hcs)) self.decoders.append(torch.nn.Linear((1+num_metalayers)*self.hcs + N_scatter_feats*N_x_feats,10*self.hcs)) self.decoders.append(torch.nn.Linear(10*self.hcs,8*self.hcs)) self.decoders.append(torch.nn.Linear(8*self.hcs,6*self.hcs)) self.decoders.append(torch.nn.Linear(6*self.hcs,4*self.hcs)) self.decoders.append(torch.nn.Linear(4*self.hcs,2*self.hcs)) # self.decoders2 = torch.nn.ModuleList() # # for i in range(4,1,-1): # # self.decoders2.append(torch.nn.Linear(i*self.hcs,(i-1)*self.hcs)) # # self.decoders2.append(torch.nn.Linear((1 + N_scatter_feats*(1 + N_scatter_feats))*self.hcs,10*self.hcs)) # self.decoders2.append(torch.nn.Linear(N_scatter_feats*N_x_feats,10*self.hcs)) # self.decoders2.append(torch.nn.Linear(10*self.hcs,1*self.hcs)) self.decoder = torch.nn.Linear(2*self.hcs,2) def forward(self,data): x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch # times = x[:,1].detach().clone() # x = torch.cuda.FloatTensor(self.scaler.transform(x.cpu())) # x = torch.cat([x,scatter_mean(edge_attr,edge_index[1],dim=0),scatter_std(edge_attr,edge_index[1],dim=0)],dim=1) # u = torch.cat([scatter_mean(x,batch,dim=0),scatter_std(x,batch,dim=0)],dim=1) x = torch.cat([x,scatter_distribution(edge_attr,edge_index[1],dim=0)],dim=1) u = torch.cat([scatter_distribution(x,batch,dim=0)],dim=1) x0 = x.clone() x = self.act(self.x_encoder(x)) edge_attr = self.act(self.edge_attr_encoder(edge_attr)) # u = torch.cuda.FloatTensor(batch.max()+1,self.hcs).fill_(0) u = self.act(self.u_encoder(u)) out = u.clone() for i, op in enumerate(self.ops): x, edge_attr, u = op(x, edge_index, edge_attr, u, batch) out = torch.cat([out,u.clone()],dim=1) # graph_indices, graph_sizes = data.batch.unique(return_counts=True) # tmp = torch.zeros((graph_indices.max()+1,graph_sizes.max(),self.hcs)).to(device) # sort = torch.sort(graph_sizes,dim=0,descending=True).indices # reverse_sort = torch.sort(sort,dim=0).indices # for tmp_index, i in enumerate(graph_indices[sort]): # tmp_graph = x[data.batch==i] # tmp_times = times[data.batch==i] # tmp[tmp_index,:graph_sizes[i]] = tmp_graph[torch.sort(tmp_times,dim=0).indices] # tmp = torch.nn.utils.rnn.pack_padded_sequence(tmp,graph_sizes[sort].cpu(),batch_first=True,enforce_sorted=True) # tmp, (hn, cn) = self.rnn(tmp) # #Maybe add TCN? out = torch.cat([out,scatter_distribution(x0,batch,dim=0)],dim=1) for lin in self.decoders: out = self.act(lin(out)) # out = torch.cat([out,cn[0,reverse_sort], # scatter_mean(torch.cat([x,scatter_mean(edge_attr,edge_index[1],dim=0)],dim=1),batch,dim=0)],dim=1) # out = torch.cat([out,scatter_mean(torch.cat([x,scatter_mean(edge_attr,edge_index[1],dim=0)],dim=1),batch,dim=0)],dim=1) # out = torch.cat([out,scatter_distribution(torch.cat([x,scatter_distribution(edge_attr,edge_index[1],dim=0)],dim=1),batch,dim=0)],dim=1) # for lin in self.decoders2: # out = self.act(lin(out)) out = self.decoder(out) # out[:,1] = self.ReLU(out[:,1]) return out # ###FOR AZIMUTH: # out = self.decoder(out).unsqueeze(2) # cos = torch.cos(out[:,0]) # sin = torch.sin(out[:,0]) # # return torch.cat([cos,sin,sin*out[:,1],cos*out[:,1]],dim=1) # return torch.cat([cos,sin,out[:,1],out[:,2],out[:,2],out[:,3]],dim=1) # from typing import Optional # import torch # from torch_scatter import scatter_sum, scatter_min, scatter_max # from torch_scatter.utils import broadcast # @torch.jit.script # def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, # out: Optional[torch.Tensor] = None, # dim_size: Optional[int] = None, # unbiased: bool = True) -> torch.Tensor: # if out is not None: # dim_size = out.size(dim) # if dim < 0: # dim = src.dim() + dim # count_dim = dim # if index.dim() <= dim: # count_dim = index.dim() - 1 # ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) # count = scatter_sum(ones, index, count_dim, dim_size=dim_size) # index = broadcast(index, src, dim) # tmp = scatter_sum(src, index, dim, dim_size=dim_size) # count = broadcast(count, tmp, dim).clamp(1) # mean = tmp.div(count) # var = (src - mean.gather(dim, index)) # var = var * var # var = scatter_sum(var, index, dim, out, dim_size) # if unbiased: # count = count.sub(1).clamp_(1) # var = var.div(count) # maximum = scatter_max(src, index, dim, out, dim_size)[0] # minimum = scatter_min(src, index, dim, out, dim_size)[0] # return torch.cat([mean,var,maximum,minimum],dim=1) # N_edge_feats = 6 # N_dom_feats = 6 # N_scatter_feats = 4 # N_targets = 1 # class Net(torch.nn.Module): # def __init__(self): # super(Net, self).__init__() # self.act = torch.nn.SiLU() # self.hcs = 32 # N_x_feats = N_dom_feats + N_scatter_feats*N_edge_feats # N_u_feats = N_scatter_feats*N_x_feats # self.x_encoder = torch.nn.Linear(N_x_feats,self.hcs) # self.edge_attr_encoder = torch.nn.Linear(N_edge_feats,self.hcs) # self.u_encoder = torch.nn.Linear(N_u_feats,self.hcs) # class EdgeModel(torch.nn.Module): # def __init__(self,hcs,act): # super(EdgeModel, self).__init__() # self.hcs = hcs # self.act = act # self.lins = torch.nn.ModuleList() # for i in range(2): # self.lins.append(torch.nn.Linear(4*self.hcs,4*self.hcs)) # self.decoder = torch.nn.Linear(4*self.hcs,self.hcs) # def forward(self, src, dest, edge_attr, u, batch): # # x: [N, F_x], where N is the number of nodes. # # src, dest: [E, F_x], where E is the number of edges. # # edge_attr: [E, F_e] # # edge_index: [2, E] with max entry N - 1. # # u: [B, F_u], where B is the number of graphs. # # batch: [N] with max entry B - 1. # out = torch.cat([src, dest, edge_attr, u[batch]], dim=1) # for lin in self.lins: # out = self.act(lin(out)) # return self.act(self.decoder(out)) # class NodeModel(torch.nn.Module): # def __init__(self,hcs,act): # super(NodeModel, self).__init__() # self.hcs = hcs # self.act = act # self.lins1 = torch.nn.ModuleList() # for i in range(2): # self.lins1.append(torch.nn.Linear(2*self.hcs,2*self.hcs)) # self.lins2 = torch.nn.ModuleList() # for i in range(2): # self.lins2.append(torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,(2 + 2*N_scatter_feats)*self.hcs)) # self.decoder = torch.nn.Linear((2 + 2*N_scatter_feats)*self.hcs,self.hcs) # def forward(self, x, edge_index, edge_attr, u, batch): # row, col = edge_index # out = torch.cat([x[row],edge_attr],dim=1) # for lin in self.lins1: # out = self.act(lin(out)) # out = scatter_distribution(out,col,dim=0) #8*hcs # out = torch.cat([x,out,u[batch]],dim=1) # for lin in self.lins2: # out = self.act(lin(out)) # return self.act(self.decoder(out)) # class GlobalModel(torch.nn.Module): # def __init__(self,hcs,act): # super(GlobalModel, self).__init__() # self.hcs = hcs # self.act = act # self.lins1 = torch.nn.ModuleList() # for i in range(2): # self.lins1.append(torch.nn.Linear((1 + N_scatter_feats)*self.hcs,(1 + N_scatter_feats)*self.hcs)) # self.decoder = torch.nn.Linear((1 + N_scatter_feats)*self.hcs,self.hcs) # def forward(self, x, edge_index, edge_attr, u, batch): # out = torch.cat([u,scatter_distribution(x,batch,dim=0)],dim=1) # 5*hcs # for lin in self.lins1: # out = self.act(lin(out)) # return self.act(self.decoder(out)) # from torch_geometric.nn import MetaLayer # self.ops = torch.nn.ModuleList() # num_metalayers = 10 # for i in range(num_metalayers): # self.ops.append(MetaLayer(EdgeModel(self.hcs,self.act), NodeModel(self.hcs,self.act), GlobalModel(self.hcs,self.act))) # self.decoders = torch.nn.ModuleList() # self.decoders.append(torch.nn.Linear((1+num_metalayers)*self.hcs + N_scatter_feats*N_x_feats,10*self.hcs)) # self.decoders.append(torch.nn.Linear(10*self.hcs,8*self.hcs)) # self.decoders.append(torch.nn.Linear(8*self.hcs,6*self.hcs)) # self.decoders.append(torch.nn.Linear(6*self.hcs,4*self.hcs)) # self.decoders.append(torch.nn.Linear(4*self.hcs,2*self.hcs)) # self.decoder = torch.nn.Linear(2*self.hcs,2) # def forward(self,data): # x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch # x = torch.cat([x,scatter_distribution(edge_attr,edge_index[1],dim=0)],dim=1) # u = torch.cat([scatter_distribution(x,batch,dim=0)],dim=1) # x0 = x.clone() # x = self.act(self.x_encoder(x)) # edge_attr = self.act(self.edge_attr_encoder(edge_attr)) # u = self.act(self.u_encoder(u)) # out = u.clone() # for i, op in enumerate(self.ops): # x, edge_attr, u = op(x, edge_index, edge_attr, u, batch) # out = torch.cat([out,u.clone()],dim=1) # out = torch.cat([out,scatter_distribution(x0,batch,dim=0)],dim=1) # for lin in self.decoders: # out = self.act(lin(out)) # out = self.decoder(out) # return out<file_sep>/scripts/FunctionCollection.py ### perhaps 1 target constructor is enough? ### Is this visible? # def direction_target_constructor(dataset): # ##Offsetting with 2 because if I want positive values # x_dir = torch.tensor(tfs['truth']['direction_x'].inverse_transform(dataset.data.y.view(-1,10,1)[:,5]),dtype=torch.float) # y_dir = torch.tensor(tfs['truth']['direction_y'].inverse_transform(dataset.data.y.view(-1,10,1)[:,6]),dtype=torch.float) # z_dir = torch.tensor(tfs['truth']['direction_z'].inverse_transform(dataset.data.y.view(-1,10,1)[:,7]),dtype=torch.float) # dataset.data.y = torch.cat([x_dir,y_dir,z_dir],dim=1).flatten() # dataset.slices['y'] = np.arange(0,len(dataset.data.y)+1, 3) # return dataset # def theta_target_constructor(dataset): # tfs = pd.read_pickle(path+'/train_test_datasets/transformers.pkl') # dataset.data.y = torch.tensor(tfs['truth']['zenith'].inverse_transform(dataset.data.y.view(-1,10,1)[:,9]),dtype=torch.float).flatten() # dataset.slices['y'] = np.arange(0,len(dataset.data.y)+1,1) # return dataset # def energy_target_constructor(dataset): # tfs = pd.read_pickle(path+'/train_test_datasets/transformers.pkl') # dataset.data.y = torch.tensor(tfs['truth']['energy_log10'].inverse_transform(dataset.data.y.view(-1,10,1)[:,0]),dtype=torch.float).flatten() # dataset.slices['y'] = np.arange(0,len(dataset.data.y) + 1, 1) # return dataset # def E_theta_target_constructor(dataset): # tfs = pd.read_pickle(path+'/train_test_datasets/transformers.pkl') # energy = torch.tensor(tfs['truth']['energy_log10'].inverse_transform(dataset.data.y.view(-1,10,1)[:,0]),dtype=torch.float) # theta = torch.tensor(tfs['truth']['zenith'].inverse_transform(dataset.data.y.view(-1,10,1)[:,9]),dtype=torch.float) # dataset.data.y = torch.cat([energy,theta],dim=1).flatten() # dataset.slices['y'] = np.arange(0,len(dataset.data.y)+1,2) # return dataset # def periodic_target_constructor(dataset): # dataset.data.y = dataset.data.y.view(-1,10)[:,8:10].flatten() # tfs = pd.read_pickle(path+'/train_test_datasets/transformers.pkl') # az_ze = dataset.data.y.view(-1,2,1) # az = torch.tensor(tfs['truth']['azimuth'].inverse_transform(az_ze[:,0]),dtype=torch.float) # ze = torch.tensor(tfs['truth']['zenith'].inverse_transform(az_ze[:,1]),dtype=torch.float) #the range seems to be about [0,pi/2]?. Makes sense, Muons come from the atmosphere # dataset.data.y = torch.cat([az,ze],dim=1).flatten() # dataset.slices['y'] = np.arange(0,len(dataset.data.y)+1, 2) # return dataset def edge_feature_constructor(x, edge_index): (frm, to) = edge_index pos = x[:,-3:] cart = pos[frm] - pos[to] rho = torch.norm(cart, p=2, dim=-1).view(-1, 1) rho_mask = rho.squeeze() != 0 cart[rho_mask] = cart[rho_mask] / rho[rho_mask] #Time difference and charge ratio T_diff = x[to,1] - x[frm,1] Q_diff = x[to,0] - x[frm,0] edge_attr = torch.cat([cart.type_as(pos),rho,T_diff.view(-1,1),Q_diff.view(-1,1)], dim=1) return edge_attr def dataset_feature_constructor(dataset,transformer): #proper edge_index edge_ind = dataset.data.edge_index.clone() for i in range(dataset.__len__()): edge_ind[:,dataset.slices['edge_index'][i]:dataset.slices['edge_index'][i+1]] += dataset.slices['x'][i] dataset.data.x[:,-3:] /= 300 dataset.data.pos = dataset.data.x[:,-3:] dataset.data.edge_attr = edge_feature_constructor(dataset.data.x, edge_ind) dataset.slices['edge_attr'] = dataset.slices['edge_index'] return dataset # (row, col) = edge_ind # #Spherical # tfs = transformer # from math import pi as PI # import torch # pos = dataset.data.pos # cart = pos[row] - pos[col] # rho = torch.norm(cart, p=2, dim=-1).view(-1, 1) # # phi = torch.atan2(cart[..., 1], cart[..., 0]).view(-1, 1) # # phi = phi + (phi < 0).type_as(phi) * (2 * PI) # # theta = torch.acos(cart[..., 2] / rho.view(-1)).view(-1, 1) # # theta[rho == 0] = torch.zeros((rho == 0).sum()) # rho_mask = rho.squeeze() != 0 # cart[rho_mask] = cart[rho_mask] / rho[rho_mask] # #"Normalize rho" # rho = rho / 600 #leads to the interval ~[0,2.25].. atleast for muon_100k_set11_SRT # #normalize pos # dataset.data.pos = pos / 300 #leads to absolute sizes of ~1.5-2 # dataset.data.x[:,-3:] = dataset.data.pos # #Time difference and charge ratio # T_diff = dataset.data.x[col,1] - dataset.data.x[row,1] # Q_diff = dataset.data.x[col,0] - dataset.data.x[row,0] # dataset.data.edge_attr = torch.cat([cart.type_as(pos),rho,T_diff.view(-1,1),Q_diff.view(-1,1)], dim=-1) # dataset.slices['edge_attr'] = dataset.slices['edge_index'] return dataset def dataset_preparator(name, path, transformer, tc = None, fc = None, shuffle = True, TrTV_split = (1,0,0), batch_size = 512): from torch_geometric.data import DataLoader, InMemoryDataset, DataListLoader import torch from datetime import datetime transformer = transformer class LoadDataset(InMemoryDataset): def __init__(self, name, path=str(), reload_data = None): super(LoadDataset, self).__init__(path) if reload_data is not None: (self.data, self.slices) = reload_data else: self.data, self.slices = torch.load(path + '/' + name) @property def processed_file_names(self): return os.listdir(path) def reload(self): for data_list in DataListLoader(self,batch_size=self.__len__()): pass return LoadDataset(name=None, reload_data = self.collate(data_list)) print(f"{datetime.now()}: loading data..") dataset = LoadDataset(name,path) print(f"{datetime.now()}: executing target constructor..") if tc is not None: # tc is target constructor, callable dataset = tc(dataset,transformer) print(f"{datetime.now()}: executing feature constructor..") if fc is not None: # fc is feature constructor, callable dataset = fc(dataset,transformer) if shuffle: print(f"{datetime.now()}: shuffling dataset..") dataset = dataset.shuffle() length = dataset.__len__() print(f"{datetime.now()}: defining dataloaders..") train_loader = DataLoader(dataset[:int(length*TrTV_split[0])], batch_size, shuffle=True) if TrTV_split[0] != 0 else None test_loader = DataLoader(dataset[int(length*TrTV_split[0]):int(length*TrTV_split[1])], batch_size, shuffle=False) val_loader = DataLoader(dataset[int(length*TrTV_split[1]):int(length*TrTV_split[2])], batch_size, shuffle=False) print(f"{datetime.now()}: Done!") return dataset, train_loader, test_loader, val_loader def return_reco_truth(model,loader): from tqdm import tqdm from torch import no_grad, device from torch.cuda import empty_cache from numpy import array outputs = [] labels = [] model.eval() with no_grad(): progress_bar = tqdm(total=loader.__len__(), desc='Batch', position=0) for data in loader: data = data.to(device('cuda' if next(model.parameters()).device.type == 'cuda' else 'cpu')) outputs += model(data).tolist() labels += data.y.view(data.num_graphs,-1).tolist() del data progress_bar.update(1) empty_cache() return array(outputs), array(labels) def performance_plot(res, x, bins=10, zero_bounded=False): import matplotlib.pyplot as plt import numpy as np x = x.flatten() slices = np.linspace(x.min(),x.max(),bins + 1) print(slices,x.min(),x.max()) quantiles = np.zeros((bins,3)) xes = np.zeros(bins) for i in range(bins): mask = (x >= slices[i])&(x <= slices[i+1]) if zero_bounded: quantiles[i] = np.quantile(res[mask],(0,0.5,0.68)) else: quantiles[i] = np.quantile(res[mask],(0.25,0.5,0.75)) xes[i] = np.mean(x[mask]) fig, ax = plt.subplots(figsize=(10,7)) ax.errorbar(x = xes, y = quantiles[:,1], yerr = abs(quantiles[:,1] - quantiles[:,[0,2]].T),fmt='none') ax.plot(xes,quantiles[:,1],'k.') ax.set(xlim=(slices[0] - 0.5, slices[-1] + 0.5)) ax.hlines(0,slices[0],slices[-1]) ax_hist = ax.twinx() ax_hist.hist(x,bins=bins,histtype='step',color='grey') ax.set_zorder(ax_hist.get_zorder()+1) ax.patch.set_visible(False) plt.grid() fig.show() fig2, ax2 = plt.subplots(figsize=(10,7)) colors = ['r','w','r'] for i in range(quantiles.shape[1]): ax2.plot(xes,quantiles[:,i],f'{colors[i]}--') hist2d = ax2.hist2d(x,res,bins=200) ax2.set_ylim(np.quantile(res,(0.1,0.9))) fig2.colorbar(hist2d[-1],ax=ax2) plt.grid() fig2.show() return quantiles def lambda_lr(epoch,epoch_warmup=2,maximum=25,a=0.05,q=0.2): if epoch < epoch_warmup: return a**(1-epoch/epoch_warmup) elif epoch < maximum*epoch_warmup: return 1/(1 + (1/q-1)*(epoch/epoch_warmup - 1)/(maximum-1)) else: return q def Loss_Functions(name, args = None): ''' Returns the specified loss function, accompanied by the proper "shape modifiers", as defined by y_post_processor and output_post_processor ''' assert name in ['Gaussian_NLLH', 'Spherical_NLLH', 'Polar_NLLH', 'twice_Polar_NLLH', 'MSE', 'MSE+MAE', 'Cross_Entropy'] print("Remember all accuracies are positive and defined to go towards 0 in the optimal case.") def cos_diff_angle(azp,zep,azt,zet): from torch import sin, cos, abs term1 = abs(sin(zep))*cos(azp)*sin(zet)*cos(azt) term2 = abs(sin(zep))*sin(azp)*sin(zet)*sin(azt) term3 = cos(zep)*cos(zet) return term1 + term2 + term3 ############################################################################################################## if name == 'Gaussian_NLLH': from torch import mean, matmul, sub, inverse, logdet def Gaussian_NLLH(pred, cov, label): loss = mean( matmul( sub(label,pred).unsqueeze(1), matmul( inverse(cov), sub(label,pred).unsqueeze(2) ) ) + logdet(cov) ) return loss assert 'diagonal_cov' in args, "Specify bool of 'diagonal_cov' in the dictionary 'args'." assert 'N_targets' in args, "Specify 'N_targets' in the dictionary 'args'." def y_post_processor(y): return y.view(-1, args['N_targets']) if not args['diagonal_cov']: print("This might not be a proper implementation, yet, since the covariances are explicitly given.") def output_post_processor(output): from torch import tril_indices, zeros, square (row,col) = tril_indices(row=args['N_targets'], col=args['N_targets'], offset=-1) tmp = zeros( (output.shape[0],args['N_targets'],args['N_targets']) ).type_as(output) tmp[:, row, col] = output[:,2*args['N_targets']:] tmp[:, col, row] = output[:,2*args['N_targets']:] tmp[:,[i for i in range(args['N_targets'])],[i for i in range(args['N_targets'])]] = square(output[:,args['N_targets']:2*args['N_targets']]) return output[:,:args['N_targets']], tmp else: assert 'eps' in args, "Specify 'eps' in the dictionary 'args'." def output_post_processor(output): from torch import zeros, square tmp = zeros( (output.shape[0],args['N_targets'],args['N_targets']) ).type_as(output) tmp[:,[i for i in range(args['N_targets'])],[i for i in range(args['N_targets'])]] = square(output[:,args['N_targets']:2*args['N_targets']]) return output[:,:args['N_targets']], tmp + args['eps'] def cal_acc(pred,label): return (pred.view(-1) - label.view(-1)).float().abs().mean() return Gaussian_NLLH, y_post_processor, output_post_processor, cal_acc ############################################################################################################## ############################################################################################################## elif name == 'Spherical_NLLH': from torch import mean, cos, sin, abs, log, exp, square def Spherical_NLLH(pred, kappa, label, weight): azp = pred[:,0] #Azimuth prediction azt = label[:,0] #Azimuth target zep = pred[:,1] #Zenith prediction zet = label[:,1] #Zenith target s1 = sin( zet + azt - azp ) s2 = sin( zet - azt + azp ) c1 = cos( zet - zep ) c2 = cos( zet + zep ) cos_angle = 0.5*abs(sin(zep))*( s1 + s2 ) + 0.5*(c1 + c2) # cos_angle = cos_diff_angle(azp,zep,azt,zet) nlogC = - log(kappa) + kappa + log( 1 - exp( - 2 * kappa ) ) loss = mean( - kappa*cos_angle + nlogC ) return loss # assert 'N_targets' in args, "Specify 'N_targets' in the dictionary 'args'." def y_post_processor(y): return y.view(-1, 2) assert 'eps' in args, "Specify 'eps' in the dictionary 'args'." def output_post_processor(output): return output[:,:2] + torch.tensor(args['output_offset']).type_as(output), square(output[:,2]) + args['eps']#(square(output[:,2]) + args['eps'])**(-1) def cal_acc(pred,label): azp = pred[:,0] #Azimuth prediction azt = label[:,0] #Azimuth target zep = pred[:,1] #Zenith prediction zet = label[:,1] #Zenith target s1 = sin( zet + azt - azp ) s2 = sin( zet - azt + azp ) c1 = cos( zet - zep ) c2 = cos( zet + zep ) cos_angle = 0.5*abs(sin(zep))*( s1 + s2 ) + 0.5*(c1 + c2) # cos_angle = cos_diff_angle(azp,zep,azt,zet) return (1 - cos_angle.float()).mean() return Spherical_NLLH, y_post_processor, output_post_processor, cal_acc ############################################################################################################## ############################################################################################################## elif name == 'Polar_NLLH': from torch import mean, cos, multiply, sub, abs, log, exp, square def Polar_NLLH(pred, kappa, label): lnI0 = kappa + log(1 + exp(-2*kappa)) -0.25*log(1+0.25*square(kappa)) + log(1+0.24273*square(kappa)) - log(1+0.43023*square(kappa)) loss = mean( - multiply(kappa,cos(sub(label,pred))) + lnI0 ) return loss assert 'zenith' in args, "Specify the bool 'zenith' in the dictionary 'args'." def y_post_processor(y): return y if args['zenith']: def output_post_processor(output): return abs(output[:,0]), square(output[:,1]) else: def output_post_processor(output): return output[:,0], square(output[:,1]) def cal_acc(output,label): return (1 - cos(output - label).float()).mean() return Polar_NLLH, y_post_processor, output_post_processor, cal_acc ############################################################################################################## ############################################################################################################## elif name == 'twice_Polar_NLLH': from torch.nn.functional import relu from torch import mean, cos, sin, multiply, sub, abs, log, exp, square def twice_Polar_NLLH(pred, kappa, label, weight): lnI0_az = kappa[:,0] + log(1 + exp(-2*kappa[:,0])) -0.25*log(1+0.25*square(kappa[:,0])) + log(1+0.24273*square(kappa[:,0])) - log(1+0.43023*square(kappa[:,0])) lnI0_ze = kappa[:,1] + log(1 + exp(-2*kappa[:,1])) -0.25*log(1+0.25*square(kappa[:,1])) + log(1+0.24273*square(kappa[:,1])) - log(1+0.43023*square(kappa[:,1])) az_correction = 0#100*relu(abs(pred[:,0] - label[:,0]) - 3.14) if torch.is_tensor(weight): loss = mean(weight*( - multiply(kappa[:,0],cos(sub(label[:,0],pred[:,0]))) - multiply(kappa[:,1],cos(sub(label[:,1],abs(pred[:,1])))) + lnI0_az + lnI0_ze + az_correction))/weight.sum() else: loss = mean( - multiply(kappa[:,0],cos(sub(label[:,0],pred[:,0]))) - multiply(kappa[:,1],cos(sub(label[:,1],abs(pred[:,1])))) + lnI0_az + lnI0_ze + az_correction) return loss def y_post_processor(y): return y.view(-1, 2) def output_post_processor(output): return output[:,:2] + torch.tensor(args['output_offset']).type_as(output), square(output[:,2:]) + args['eps']#torch.cat([square(output[:,2]).view(-1,1), square(output[:,3]).view(-1,1)],dim=1) + args['eps'] def cal_acc(output,label): azp = output[:,0] #Azimuth prediction azt = label[:,0] #Azimuth target zep = output[:,1] #Zenith prediction zet = label[:,1] #Zenith target s1 = sin( zet + azt - azp ) s2 = sin( zet - azt + azp ) c1 = cos( zet - zep ) c2 = cos( zet + zep ) cos_angle = 0.5*abs(sin(zep))*( s1 + s2 ) + 0.5*(c1 + c2) # cos_angle = cos_diff_angle(azp,zep,azt,zet) return (1 - cos_angle.float()).mean() # return ((2 - cos(output[:,0] - label[:,0]).float() - cos(abs(output[:,1]) - label[:,1]).float())*0.5).mean().item() return twice_Polar_NLLH, y_post_processor, output_post_processor, cal_acc ############################################################################################################## ############################################################################################################## elif name == 'MSE': from torch import mean def MSE(output,label): loss = mean( (output - label)**2 ) return loss assert 'N_targets' in args, "Specify 'N_targets' in the dictionary 'args'." def y_post_processor(y): return y.view(-1, args['N_targets']) def output_post_processor(output): return output def cal_acc(output,label): return (output.view(-1) - label.view(-1)).float().abs().mean() return MSE, y_post_processor, output_post_processor, cal_acc ############################################################################################################## ############################################################################################################## elif name == 'MSE+MAE': from torch import mean, abs def MSE_MAE(output,label): loss = mean( (output - label)**2 + abs(output - label) ) return loss assert 'N_targets' in args, "Specify 'N_targets' in the dictionary 'args'." def y_post_processor(y): return y.view(-1, args['N_targets']) def output_post_processor(output): return output def cal_acc(output,label): return (output.view(-1) - label.view(-1)).float().abs().mean() return MSE_MAE, y_post_processor, output_post_processor, cal_acc ############################################################################################################## ############################################################################################################## elif name == 'Cross_Entropy': from torch.nn import CrossEntropyLoss def y_post_processor(y): return y def output_post_processor(output): return output def cal_acc(output,label): return 1 - output.argmax(dim=1).eq(label).float().mean() return CrossEntropyLoss(), y_post_processor, output_post_processor, cal_acc ############################################################################################################## # def train(model, loss_name, train_loader, val_loader, args): # crit, y_post_processor, output_post_processor, cal_acc = Loss_Functions(loss_name, args) # likelihood_fitting = True if loss_name[-4:] == 'NLLH' else False # val_len = val_loader.__len__(); best_acc = np.inf # model.train() # for data in train_loader: # data = data.to(args['device']) # label = y_post_processor(data.y) # optimizer.zero_grad() # if likelihood_fitting: # output, cov = output_post_processor( model(data) ) # loss = crit(output, cov, label) # else: # output = output_post_processor( model(data) ) # loss = crit(output, label) # loss.backward() # optimizer.step() # del data # acc = cal_acc(output,label) # if args['wandb_activated']: # wandb.log({"Train Loss": loss.item(), # "Train Acc": acc}) # torch.cuda.empty_cache() # model.eval() # with torch.no_grad() from pytorch_lightning import LightningModule import torch class customModule(LightningModule): def __init__(self, crit, y_post_processor, output_post_processor, cal_acc, likelihood_fitting, args): super(customModule, self).__init__() self.crit = crit self.y_post_processor = y_post_processor self.output_post_processor = output_post_processor self.cal_acc = cal_acc self.likelihood_fitting = likelihood_fitting self.lr = args['lr'] def forward(self,data): print("This should not print, then 'forward' in your model is not defined") return def configure_optimizers(self): from torch.optim import Adam from torch.optim.lr_scheduler import LambdaLR from FunctionCollection import lambda_lr optimizer = Adam(self.parameters(), lr=self.lr) scheduler = LambdaLR(optimizer, lambda_lr) return [optimizer], [scheduler] def training_step(self, data, batch_idx): try: weight = data.weight except: weight = None label = self.y_post_processor(data.y) if self.likelihood_fitting: output, cov = self.output_post_processor( self(data) ) loss = self.crit(output, cov, label, weight) else: output = self.output_post_processor( self(data) ) loss = self.crit(output, label, weight) acc = self.cal_acc(output, label) self.log("Train Loss", loss, on_step = True) self.log("Train Acc", acc, on_step = True) return {'loss': loss} def validation_step(self, data, batch_idx): label = self.y_post_processor(data.y) if self.likelihood_fitting: output, cov = self.output_post_processor( self(data) ) else: output = self.output_post_processor( self(data) ) acc = self.cal_acc(output, label) # self.log("val_batch_acc", acc, on_step = True) # self.log("Val Acc2", acc, on_epoch=True) return {'val_batch_acc': acc} def validation_epoch_end(self, outputs): avg_acc = torch.stack([x['val_batch_acc'] for x in outputs]).mean() self.log("Val Acc", avg_acc) # self.log("lr", self.lr) return #{'Val Acc': avg_acc} #It said it should not return anything \_(^^)_/ def test_step(self, data, batch_idx): label = self.y_post_processor(data.y) if self.likelihood_fitting: output, cov = self.output_post_processor( self(data) ) else: output = self.output_post_processor( self(data) ) acc = self.cal_acc(output, label) self.log("Test Acc", acc, on_step = True) return {'Test Acc': acc} # def test_epoch_end(self, outputs): # avg_acc = torch.stack([x['test_batch_acc'] for x in outputs]).mean() # self.log("Test Acc", avg_acc) # return #{'Test Acc': avg_acc} def edge_creators(iteration): if iteration == 1: from torch_geometric.transforms import KNNGraph return KNNGraph(loop=True) if iteration == 2: from torch_geometric.transforms import KNNGraph, ToUndirected, AddSelfLoops def edge_creator(dat): KNNGraph(k=5, loop=False, force_undirected = False)(dat) dat.adj_t = None ToUndirected()(dat) AddSelfLoops()(dat) dat.edge_index = dat.edge_index.flip(dims=[0]) return dat return edge_creator # if iteration == 3: ############################################################################################################## import sqlite3 import os import torch import numpy as np from pandas import read_sql from torch_geometric.data import Data, Batch import torch.utils.data class _RepeatSampler(object): """ Sampler that repeats forever. Args: sampler (Sampler) """ def __init__(self, sampler): self.sampler = sampler def __iter__(self): while True: yield from iter(self.sampler) class FastDataLoader(torch.utils.data.dataloader.DataLoader): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler)) self.iterator = super().__iter__() def __len__(self): return len(self.batch_sampler.sampler) def __iter__(self): for i in range(len(self)): yield next(self.iterator) class custom_db_dataset(torch.utils.data.Dataset): def __init__(self, filepath, filename, features, targets, TrTV, event_nos = None, x_transform = lambda x: torch.tensor(x.values), y_transform = lambda y: torch.tensor(y.values), batch_transform = lambda tmp_x, events: tmp_x, shuffle = False, SRT_clean = False, reweighter = None): self.filepath = filepath self.filename = filename self.features = features #Should be string of features, eg: "charge_log10, time, pulse_width, SRTInIcePulses, dom_x, dom_y, dom_z" self.targets = targets #Should be string of targets, eg: "azimuth, zenith, energy_log10" self.TrTV = TrTV #Should be cumulative sum of percentages for "Tr(ain)T(est)V(alidation)"" sets. # self.con = sqlite3.connect('file:'+os.path.join(self.filepath,self.filename+'?mode=ro'),uri=True) self.con_path = 'file:'+os.path.join(self.filepath,self.filename+'?mode=ro') self.x_transform = x_transform #should transform df to tensor self.y_transform = y_transform self.batch_transform = batch_transform self.shuffle = shuffle self.SRT_clean = SRT_clean self.reweighter = reweighter if isinstance(event_nos,type(None)): with sqlite3.connect(self.con_path,uri=True) as con: self.event_nos = np.asarray(read_sql("SELECT event_no FROM truth",con)).reshape(-1) else: self.event_nos = event_nos if self.shuffle: np.random.shuffle(self.event_nos) def __len__(self): """length method, number of events""" return len(self.event_nos) def __getitem__(self, index): if isinstance(index, int): return self.get_single(index) if isinstance(index, list): return self.get_list(index) def get_single(self,index): with sqlite3.connect(self.con_path,uri=True) as con: query = f"SELECT {self.features} FROM features WHERE event_no = {self.event_nos[index]}" if self.SRT_clean: query += " AND SRTInIcePulses = 1" x = self.x_transform(read_sql(query,con)) query = f"SELECT {self.targets} FROM truth WHERE event_no = {self.event_nos[index]}" y = self.y_transform(read_sql(query,con)) return Data(x=x, y=y) def get_list(self,index): with sqlite3.connect(self.con_path,uri=True) as con: query = f"SELECT event_no, {self.features} FROM features WHERE event_no IN {tuple(self.event_nos[index])}" if self.SRT_clean: query += " AND SRTInIcePulses = 1" events = read_sql(query, con) x = self.x_transform(events.iloc[:,1:]) query = f"SELECT {self.targets} FROM truth WHERE event_no IN {tuple(self.event_nos[index])}" y = self.y_transform(read_sql(query,con)) data_list = [] _, events = np.unique(events.event_no.values.flatten(), return_counts = True) events = events.tolist() for tmp_x, tmp_y in zip(torch.split(x, events), y): tmp_x = self.batch_transform(tmp_x,events) data_list.append(Data(x=tmp_x,y=tmp_y)) # return self.collate(data_list) return data_list def return_self(self,event_nos, extra_targets = ''): return custom_db_dataset(self.filepath, self.filename, self.features, self.targets + extra_targets, self.TrTV, event_nos, self.x_transform, self.y_transform, self.batch_transform, self.shuffle, self.SRT_clean, self.reweighter) def train(self): return self.return_self(self.event_nos[:int(self.TrTV[0]*self.__len__())]) def test(self, extra_targets = ''): return self.return_self(self.event_nos[int(self.TrTV[0]*self.__len__()):int(self.TrTV[1]*self.__len__())], extra_targets) def val(self): return self.return_self(self.event_nos[int(self.TrTV[1]*self.__len__()):int(self.TrTV[2]*self.__len__())]) def collate(self,batch): return Batch.from_data_list(batch) def return_dataloader(self, dataset, batch_size, shuffle = False, num_workers=0): from torch.utils.data import BatchSampler, DataLoader, SequentialSampler, RandomSampler def collate(batch): return Batch.from_data_list(batch[0]) if shuffle: sampler = BatchSampler(RandomSampler(dataset),batch_size=batch_size,drop_last=False) else: sampler = BatchSampler(SequentialSampler(dataset),batch_size=batch_size,drop_last=False) return DataLoader(dataset = dataset, collate_fn = collate, num_workers = num_workers, pin_memory = True, sampler = sampler) def return_dataloaders(self, batch_size, num_workers = 0): #Perhaps rewrite this using return_dataloader method from torch.utils.data import BatchSampler, DataLoader, SequentialSampler, RandomSampler if self.reweighter: N_targets = len(self.targets.split(', ')) def collate(batch): batch = Batch.from_data_list(batch[0]) batch.weight = self.reweighter(batch)#torch.tensor(self.reweighter.predict_weights(batch.y.view(-1,N_targets))).view(-1,1) return batch else: def collate(batch): return Batch.from_data_list(batch[0]) train_loader = DataLoader(dataset = self.train(), collate_fn = collate, num_workers = num_workers, # persistent_workers=True, pin_memory = True, sampler = BatchSampler(RandomSampler(self.train()), batch_size=batch_size, drop_last=False)) test_loader = DataLoader(dataset = self.test(extra_targets = ', energy_log10'), collate_fn = collate, num_workers = num_workers, # persistent_workers=True, pin_memory = True, sampler = BatchSampler(SequentialSampler(self.test(extra_targets = ', energy_log10')), batch_size=batch_size, drop_last=False)) val_loader = DataLoader(dataset = self.val(), collate_fn = collate, num_workers = num_workers, # persistent_workers=True, pin_memory = True, sampler = BatchSampler(RandomSampler(self.val()), batch_size=batch_size, drop_last=False)) return train_loader, test_loader, val_loader ############################################################################################################## import pytorch_lightning as pl def return_trainer(path, run_name, args, ckpt = None, patience = 7, max_epochs=50, log_every_n_steps=50): early_stop_callback = pl.callbacks.early_stopping.EarlyStopping(monitor='Val Acc', min_delta=0.00, patience=patience, verbose=False, mode='min') checkpoint_callback = pl.callbacks.ModelCheckpoint(dirpath = path + '/checkpoints/' + run_name + '_' + args['id'], filename = '{epoch}-{Val Acc:.3f}', save_top_k = 1, verbose = True, monitor = 'Val Acc', mode = 'min', prefix = run_name) lr_logger = pl.callbacks.lr_monitor.LearningRateMonitor(logging_interval = 'epoch') from pytorch_lightning.loggers import WandbLogger if ckpt != None: wandb_logger = WandbLogger(name = run_name, project = 'Neutrino-Machine-Learning', version = run_name + '_' + args['id'], # id and version can be interchanged, depending on whether you want to initialize or resume save_dir = path, sync_step = False) #Specify version as id if you want to resume a run. # wandb_logger.experiment.config.update(args) trainer = pl.Trainer(gpus=1, #-1 for all gpus min_epochs=1, max_epochs=max_epochs, auto_lr_find = False, auto_select_gpus = True, log_every_n_steps = log_every_n_steps, terminate_on_nan = True, num_sanity_val_steps = 0, callbacks=[early_stop_callback, checkpoint_callback, lr_logger] if args['wandb_activated'] else [early_stop_callback, checkpoint_callback], resume_from_checkpoint = path + '/checkpoints/' + run_name + '_' + args['id'] + '/' + ckpt, logger = wandb_logger if args['wandb_activated'] else False, default_root_dir = path) else: wandb_logger = WandbLogger(name = run_name, project = 'Neutrino-Machine-Learning', id = run_name + '_' + args['id'], # id and version can be interchanged, depending on whether you want to initialize or resume save_dir = path) #Specify version as id if you want to resume a run. trainer = pl.Trainer(gpus=1, #-1 for all gpus min_epochs=1, max_epochs=max_epochs, auto_lr_find = False, auto_select_gpus = True, log_every_n_steps = log_every_n_steps, terminate_on_nan = True, num_sanity_val_steps = 0, callbacks=[early_stop_callback, checkpoint_callback, lr_logger] if args['wandb_activated'] else [early_stop_callback, checkpoint_callback], logger = wandb_logger if args['wandb_activated'] else False, default_root_dir = path) return trainer, wandb_logger def Print(statement): from time import localtime, strftime print("{} - {}".format(strftime("%H:%M:%S", localtime()),statement)) # def prepare_dataset_from_sets(args,filepath): # Print("Loading sets..") # sets = pd.read_pickle(os.path.join(filepath,'meta/sets.pkl')) <file_sep>/legacy/Models/Model6.py from torch_geometric.nn import GINConv, SGConv, SAGPooling, GCNConv, GATConv, DNAConv import torch from torch_scatter import scatter_add, scatter_max, scatter_mean import torch.nn.functional as F # Taken from: https://github.com/rusty1s/pytorch_geometric/blob/master/examples/dna.py class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() in_channels = 5 hidden_channels = 30 self.hidden_channels = hidden_channels num_layers = 6 self.lin1 = torch.nn.Linear(in_channels,hidden_channels) self.DNAConvs = torch.nn.ModuleList() for i in range(num_layers): self.DNAConvs.append(DNAConv(hidden_channels,heads=3,groups=1,dropout=0)) self.lin2 = torch.nn.Linear(hidden_channels,1) def forward(self, data): x, edge_index = data.x, data.edge_index x = F.relu(self.lin1(x)) # x = F.dropout(x,p=0.5,training.self.training) x_all = x.view(-1,1,self.hidden_channels) for conv in self.DNAConvs: x = F.relu(conv(x_all,edge_index)) x = x.view(-1,1,self.hidden_channels) x_all = torch.cat([x_all,x],dim=1) x = x_all[:,-1] x = scatter_add(x,data.batch,dim=0) # x = F.dropout(x,p=0.5,training.self.training) x = self.lin2(x) return x<file_sep>/legacy/Model_Tester.py import matplotlib.pyplot as plt import numpy as np import os import torch from torch_geometric.data import DataLoader, InMemoryDataset import time import importlib from sklearn.metrics import roc_curve classifiers = ['energy','type','class'] classifying = classifiers[2] class LoadDataset(InMemoryDataset): def __init__(self, name, root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets'): super(LoadDataset, self).__init__(root) self.data, self.slices = torch.load(root + '/' + name) @property def processed_file_names(self): return os.listdir(root) print(f'Loading datasets for {classifying} prediction') train_dataset = LoadDataset(f'train_{classifying}') test_dataset = LoadDataset(f'test_{classifying}') train_loader = DataLoader(train_dataset, batch_size=64,shuffle=True) test_loader = DataLoader(test_dataset, batch_size=256) print('Loads model') #Define model: #The syntax is for model i: from Models.Model{i} import Net import Models.Model2 as Model Model = importlib.reload(Model) print(f'remember to double check that model is suitable for {classifying} prediction') if not torch.cuda.is_available(): print('CUDA not available') print(f'Memory before .to(device) {torch.cuda.memory_allocated()}') device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = Model.Net().to(device) # optimizer = torch.optim.Adam(model.parameters(), lr=0.0005) optimizer = torch.optim.Adam(model.parameters(), lr=0.0001) print(f'Memory after .to(device) {torch.cuda.memory_allocated()}') # #For loading existing model and optimizer parameters. # print('Loading existing model and optimizer states') # state = torch.load('Trained_Models/Model7_Class.pt') # model.load_state_dict(state['model_state_dict']) # optimizer.load_state_dict(state['optimizer_state_dict']) def save_model(name): torch.save({'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict()},'Trained_Models/'+name) print('Model saved') if classifying == classifiers[0]: #Energy prediction crit = torch.nn.MSELoss() def cal_acc(output,label): return (output.view(-1) - label).float().mean().item() elif classifying == classifiers[1]: #Type prediction crit = torch.nn.NLLLoss() def cal_acc(output,label): return output.argmax(dim=1).eq(label).float().mean().item() elif classifying == classifiers[2]: #Class prediction crit = torch.nn.NLLLoss() def cal_acc(output,label): return output.argmax(dim=1).eq(label).float().mean().item() batch_loss, batch_acc = [], [] def train(): model.train() for data in train_loader: data = data.to(device) label = data.y optimizer.zero_grad() output = model(data) del data loss = crit(output,label) loss.backward() optimizer.step() batch_loss.append(loss.item()) batch_acc.append(cal_acc(output,label)) torch.cuda.empty_cache() return def test(): acc = 0 model.eval() with torch.no_grad(): for data in test_loader: data = data.to(device) label = data.y output = model(data) del data acc += cal_acc(output,label) torch.cuda.empty_cache() return acc/test_loader.__len__() def ROC(): model.eval() scores = [] labels = [] with torch.no_grad(): for data in test_loader: label = data.y data = data.to(device) output = model(data) del data scores += output.cpu()[:,0].tolist() del output # print(torch.cuda.memory_allocated()) labels += label.cpu().tolist() torch.cuda.empty_cache() return scores, labels def epochs(i,mean_length=500): print('Begins training') t0 = time.time() for epoch in range(i): print(f'Epoch: {epoch}') train() mean_loss = np.mean(batch_loss[-mean_length:]) mean_acc = np.mean(batch_acc[-mean_length:]) std_acc = np.std(batch_acc[-mean_length:]) print(f'Mean of last {mean_length} batches; loss: {mean_loss}, acc: {mean_acc} +- {std_acc}') print(f'time since beginning: {time.time() - t0}') print('Done') def plot(): fig, ax = plt.subplots(nrows=2,sharex=True) ax[0].plot(batch_loss) ax[1].plot(batch_acc) fig.show() <file_sep>/debugger.py import numpy as np import matplotlib.pyplot as plt import torch import pandas as pd import time import wandb import pytorch_lightning as pl import FunctionCollection as fc import importlib fc = importlib.reload(fc) import os path = r'C:\Users\jv97\Desktop\github\Neutrino-Machine-Learning' run_name = 'test_angle_m10' args = {'N_edge_feats': 6, 'N_dom_feats': 7, 'N_targets': 2, 'N_outputs': 4, 'N_metalayers': 1, 'N_hcs': 64, 'diagonal_cov': True, 'wandb_activated': False, 'type': 'twice_Polar_NLLH', 'zenith': True, 'id': wandb.util.generate_id()[:4], 'eps': 0, 'lr': 8e-2, 'filename': 'rasmus_classification_muon_3neutrino_3mio.db',#dev_level7_mu_e_tau_oscweight_000.db #rasmus_classification_muon_3neutrino_3mio.db #dev_level7_oscNext_IC86_003.db 'features': 'charge_log10, time, pulse_width, SRTInIcePulses, dom_x, dom_y, dom_z', 'targets': 'azimuth, zenith', 'TrTV': (0.1,0.99,1)#(0.025,0.995,1) } # filepath = os.path.join(path,'raw_data/dev_level7_mu_e_tau_oscweight_000/data') filepath = os.path.join(path,'raw_data') tf = pd.read_pickle(r'C:\Users\jv97\Desktop\github\Neutrino-Machine-Learning\datasets\transformers.pkl') # tf = pd.read_pickle(r'C:\Users\jv97\Desktop\github\Neutrino-Machine-Learning\raw_data\dev_level7_mu_e_tau_oscweight_000\data\meta\transformers.pkl') event_nos = pd.read_pickle(r'C:\Users\jv97\Desktop\github\Neutrino-Machine-Learning\datasets\event_nos_500k_muon_set1.pkl').values.reshape(-1) def x_transform(df): pos = ['dom_x','dom_y','dom_z'] for col in pos: df[col] = tf['features'][col].inverse_transform(df[[col]]) df[pos] /= 300 return torch.tensor(df.values) def y_transform(df): for col in df.columns: df[col] = tf['truth'][col].inverse_transform(df[[col]]) return torch.tensor(df.values) # <EMAIL> # def x_transform(df): # df['charge_log10'] = (df['charge_log10'] - charge_center)/charge_scale # df['dom_time'] = (df['dom_time'] - time_center)/time_scale # df[['dom_x','dom_y','dom_z']] /= 300 # return torch.tensor(df.values) # #<EMAIL> # def y_transform(df): # return torch.tensor(df.values) dataset = fc.custom_db_dataset(filepath = filepath, filename = args['filename'], features = args['features'], targets = args['targets'], TrTV = args['TrTV'], # event_nos = event_nos, x_transform = x_transform, y_transform = y_transform, shuffle = True) train_loader, test_loader, val_loader = dataset.return_dataloaders(batch_size=512) #~0.6sec loading time pr. batch i = 0 start = time.time() for dat in train_loader: print(time.time() - start) start = time.time() i += 1 if i > 100: break<file_sep>/legacy/Model_Tester_Energy.py import matplotlib.pyplot as plt import numpy as np import os import torch from torch_geometric.data import DataLoader, InMemoryDataset import time import importlib #### For loading the dataset as a torch_geometric InMemoryDataset #### # The @properties should be unimportant for now, including process since the data is processed. def load_dataset(path='C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset'): class MakeDataset(InMemoryDataset): def __init__(self, root, transform=None, pre_transform=None): super(MakeDataset, self).__init__(root, transform, pre_transform) self.data, self.slices = torch.load(self.processed_paths[-1]) #Loads PROCESSED.file #perhaps check print(self.processed_paths) @property def raw_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/raw_data') @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') def process(self): pass print('Loads data') var = MakeDataset(root = path) return var dataset = load_dataset() #### ##### #### Changing target variables from 8 to Energy alone #### dataset.data.y = dataset.data.y[::8] dataset.slices['y'] = torch.tensor(np.arange(300000+1)) #### #### ####Look at subset #### # dataset = dataset[100000:] dataset = dataset.shuffle() train_dataset = dataset[:50000] val_dataset = dataset[50000:75000] test_dataset = dataset[75000:100000] # train_dataset = dataset[:200000] # val_dataset = dataset[200000:250000] # test_dataset = dataset[250000:] #### #### train_batch_size = 128 batch_size = 128 train_loader = DataLoader(train_dataset, batch_size=train_batch_size) val_loader = DataLoader(val_dataset, batch_size=batch_size) test_loader = DataLoader(test_dataset, batch_size=batch_size) print('Loads model') #Define model: # from Models.Model1 import Net #The syntax is for model i: from Models.Model{i} import Net import Models.Model2 as Model Model = importlib.reload(Model) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = Model.Net().to(device) optimizer = torch.optim.Adam(model.parameters(), lr=0.005) crit = torch.nn.MSELoss() #Loss function # #For loading existing model and optimizer parameters. print('Loading existing model and optimizer states') state = torch.load('Trained_Models/Model2_Energy.pt') model.load_state_dict(state['model_state_dict']) optimizer.load_state_dict(state['optimizer_state_dict']) def save_model(path): torch.save({'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict()},path) print('Model saved') train_size = train_dataset.__len__() def train(): model.train() train_loss = 0 for data in train_loader: data = data.to(device) label = data.y optimizer.zero_grad() output = model(data) del data loss = crit(output,label) loss.backward() optimizer.step() train_loss += loss torch.cuda.empty_cache() return train_loss/train_size test_size = test_dataset.__len__() def test(): model.eval() acc = 0 with torch.no_grad(): for data in test_loader: label = data.y data = data.to(device) output = model(data) del data acc += output.cpu().view(-1).dist(label) torch.cuda.empty_cache() return acc / test_size def epochs(i): t = time.time() for epoch in range(i): print(f'Epoch: {epoch}') err = train() acc = test() print(f'training error: {err.item()} testing accuracy: {acc.item()}') print(f'time since beginning: {time.time() - t}') print('Ready for training') # def train(): # model.train() # train_score = 0 # for data in train_loader: # label = data.y.to(device) # data = data.to(device) # optimizer.zero_grad() # output = model(data) # print(label.shape,output.shape) # train_score += (output.view(-1) - label)/label # loss = crit(output, label) # loss.backward() # optimizer.step() # train_score /= train_loader.__len__() # model.eval() # test_score = 0 # for data in test_loader: # label = data.y.to(device) # data = data.to(device) # output = model(data) # test_score += (output.view(-1) - label)/label # test_score /= test_loader.__len__() # return torch.mean(train_score,0).data.cpu().numpy(), torch.mean(test_score,0).data.cpu().numpy() # print('Begins training') # t = time.time() # train_scores, test_scores = [], [] # for epoch in range(5): # print(f'Epoch: {epoch}') # train_score, test_score = train() # train_scores.append(train_score) # test_scores.append(test_score) # print(f'time since beginning: {time.time() - t}') # print('Done') # #### plotting #### # labels = ['Energy','Time','x','y','z','dir_x','dir_y','dir_z'] # train_scores = np.array(train_scores) # test_scores = np.array(test_scores) # # fig, ax = plt.subplots(2,1) # # for feature,label in zip(range(8),labels): # # ax[0].plot(train_scores[:,feature],label=label) # # ax[1].plot(test_scores[:,feature],label=label) # # ax[0].set_title('Train Scores') # # ax[1].set_title('Test Scores') # # ax[0].legend(loc = 2,ncol = 4) # # # ax[1].legend() # fig, ax = plt.subplots(figsize = (16,8),nrows=4,ncols=2) # ax = ax.flatten() # for feature,label in zip(range(8),labels): # ax[feature].plot(train_scores[:,feature],c='k',label = label) # # ax[feature].plot(test_scores[:,feature],ls='--',c=ax[feature].get_lines()[0].get_color(),label = label) # ax[feature].plot(test_scores[:,feature],ls='--',c='r',label = label) # z_train = train_scores[-1,feature] # z_test = test_scores[-1,feature] # ax[feature].set_title(label+f' Final scores: Train = {z_train} Test = {z_test}') # print('plotting') # def zoom(axes,ZOOM): # for f,ax in enumerate(axes): # mini = min(train_scores[-1,f],test_scores[-1,f]) # maxi = max(train_scores[-1,f],test_scores[-1,f]) # ax.set_ylim(mini - ZOOM*(maxi-mini), maxi + ZOOM*(maxi-mini)) # fig.canvas.draw() # return # fig.tight_layout() # fig.show() # #### ####<file_sep>/performance_plot.py import pandas as pd import numpy as np import matplotlib.pyplot as plt def performance_plot(pred,true,Energies,ylim=None): fig, ax = plt.subplots(figsize=(10,7)) sort = np.argsort(Energies) Energies = Energies[sort] res = pred[sort] - true[sort] slices = np.arange(0,4.5,0.5) quantiles = np.zeros((len(slices) - 1,3)) xes = np.zeros(len(slices) - 1) for i in range(1,len(slices)): mask = (Energies > slices[i-1])&(Energies < slices[i]) quantiles[i-1] = np.quantile(res[mask],(0.25,0.5,0.75)) xes[i-1] = np.mean(Energies[mask]) ax.errorbar(x = xes, y = quantiles[:,1], yerr = abs(quantiles[:,1] - quantiles[:,[0,2]].T),fmt='none') ax.plot(xes,quantiles[:,1],'k.') ax.set(xlim=(-0.2,4.2),ylim=ylim) ax.hlines(0,0,4) plt.grid() fig.show() fig2, ax2 = plt.subplots(figsize=(10,7)) for i in range(quantiles.shape[1]): ax2.plot(xes,quantiles[:,i]) ax2.set(xlim=(-0.2,4.2),ylim=ylim) ax2.hlines(0,0,4) plt.grid() fig2.show() return quantiles<file_sep>/legacy/Models/__init__.py #Model1: First try #Model2: First selfmade, now used for .energy prediction acc: 0.0443 (?), 2_test_acc: 2.85, AUC: 0.948428 (class pred) #Model3: Model2 readjusted for classifying types #Model4: Improving Model3, perhaps total do over. AUC: 0.9164886 (class pred) #Model5: First attempt at DNAConv for type prediction #Model6: Model5 but for energy prediction test_acc: -1.11 (pred - true) #Model7: DNAConv for class prediction AUC: 0.916741 #Model8: DNAConv with Model2 AUC: 0.97 #Model9: "Ensemble" for energy prediction no sure minimum: ~ -1.44<file_sep>/legacy/GraphCreator.py import pandas as pd from torch_geometric.data import InMemoryDataset, Data import numpy as np import torch_geometric.transforms as T import torch from datetime import datetime import sqlite3 # filename = "rasmus_classification_muon_3neutrino_3mio.db" # db_path = "C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/raw_data/{}".format(filename) # destination = "C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/datasets" # particle = 'muon' #'muonNeutrino' #'3_neutrinos' #'muon' # save_filename = 'muon_set2' #'muonNeutrino_set1' #'neutrinos_set1' #'muon_set1' # event_nos = None # event_nos = pd.read_pickle(destination + '/event_nos_500k_muon_set1.pkl').iloc[:100000] #Select event_no only for muons: print('{}: Collecting event numbers..'.format(datetime.now())) if event_nos is None: subdivides = 100000 N = 2*subdivides if particle == 'muon': query = "SELECT event_no FROM truth WHERE pid = 13" with sqlite3.connect(str(db_path)) as con: event_nos = pd.read_sql(query,con) event_nos = event_nos.sample(N) elif particle == '3_neutrinos': query = "SELECT event_no FROM truth WHERE pid = 12" with sqlite3.connect(str(db_path)) as con: event_nos = pd.read_sql(query,con) event_nos_electron = event_nos.sample(N//3) query = "SELECT event_no FROM truth WHERE pid = 14" event_nos = pd.read_sql(query,con) event_nos_muon = event_nos.sample(N//3) query = "SELECT event_no FROM truth WHERE pid = 16" event_nos = pd.read_sql(query,con) event_nos_tau = event_nos.sample(N//3) event_nos = pd.concat([event_nos_electron,event_nos_muon,event_nos_tau],dim=0) elif particle == '2_neutrinos': query = "SELECT event_no FROM truth WHERE pid = 12" with sqlite3.connect(str(db_path)) as con: event_nos = pd.read_sql(query,con) event_nos_electron = event_nos.sample(N//2) query = "SELECT event_no FROM truth WHERE pid = 14" event_nos = pd.read_sql(query,con) event_nos_muon = event_nos.sample(N//2) event_nos = pd.concat([event_nos_electron,event_nos_muon],dim=0) elif particle == 'muonNeutrino': query = "SELECT event_no FROM truth WHERE pid = 14" with sqlite3.connect(str(db_path)) as con: event_nos = pd.read_sql(query,con) event_nos = event_nos.sample(N) event_nos.to_pickle(destination + '/' + 'event_nos_{}k_{}.pkl'.format(N//1000,save_filename)) print('{}: Saved relevant event numbers.. \nBeginning Graph creation..'.format(datetime.now())) else: with sqlite3.connect(str(db_path)) as con: subdivides = event_nos.shape[0] N = subdivides tfs = pd.read_pickle("C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/datasets/transformers.pkl") print("Remember, transformer is currently activated to inverse_transform position variables..") subset = 1 data_list = [] for i, event_no in enumerate(event_nos.values.flatten()): query = "SELECT charge_log10, time, dom_x, dom_y, dom_z FROM features WHERE event_no = {} AND SRTInIcePulses = 1".format(event_no) tmp_event = pd.read_sql(query,con) tmp_event = tmp_event.loc[tmp_event.SRTInIcePulses == 1] if tfs is not None: x_pos = torch.tensor(tfs['features']['dom_x'].inverse_transform(tmp_event[['dom_x']]),dtype=torch.float) y_pos = torch.tensor(tfs['features']['dom_y'].inverse_transform(tmp_event[['dom_y']]),dtype=torch.float) z_pos = torch.tensor(tfs['features']['dom_z'].inverse_transform(tmp_event[['dom_z']]),dtype=torch.float) x = torch.cat([torch.tensor(tmp_event[['charge_log10','time']].values,dtype=torch.float),x_pos,y_pos,z_pos],dim=1) pos = torch.cat([x_pos,y_pos,z_pos],dim=1) else: x = torch.tensor(tmp_event[['charge_log10','time','dom_x','dom_y','dom_z']].values,dtype=torch.float) #Features pos = torch.tensor(tmp_event[['dom_x','dom_y','dom_z']].values,dtype=torch.float) #Position query = "SELECT energy_log10, time, position_x, position_y, position_z, direction_x, direction_y, direction_z, azimuth, zenith FROM truth WHERE event_no = {}".format(event_no) y = pd.read_sql(query,con) y = torch.tensor(y.values,dtype=torch.float) #Target dat = Data(x=x,edge_index=None,edge_attr=None,y=y,pos=pos) # T.KNNGraph(loop=True)(dat) #defining edges by k-NN with k=6 !!! Make sure .pos is not scaled!!! ie. x,y,z -!-> ax,by,cz T.KNNGraph(k=6, loop=False, force_undirected = False)(dat) dat.adj_t = None T.ToUndirected()(dat) T.AddSelfLoops()(dat) (row, col) = dat.edge_index dat.edge_index = torch.stack([col,row],dim=0) data_list.append(dat) if (i+1) % subdivides == 0: data, slices = InMemoryDataset.collate(data_list) torch.save((data,slices), destination + '/{}k_{}{}.pt'.format(subdivides//1000,save_filename,subset)) subset += 1 data_list = [] #Does this free up the memory? if i % 500 == 0: print("{}: Completed {}/{}".format(datetime.now(),i,N)) if data_list != []: data, slices = InMemoryDataset.collate(data_list) torch.save((data,slices), destination + '/{}k_{}{}.pt'.format(subdivides//1000,save_filename,subset)) <file_sep>/Model_Loaders/Model_2.py def Load_model(name, args): from FunctionCollection import Loss_Functions, customModule import pytorch_lightning as pl from torch_geometric_temporal import nn from typing import Optional import torch from torch_scatter import scatter_sum, scatter_min, scatter_max from torch_scatter.utils import broadcast from torch_geometric.nn import GATConv @torch.jit.script def scatter_distribution(src: torch.Tensor, index: torch.Tensor, dim: int = -1, out: Optional[torch.Tensor] = None, dim_size: Optional[int] = None, unbiased: bool = True) -> torch.Tensor: if out is not None: dim_size = out.size(dim) if dim < 0: dim = src.dim() + dim count_dim = dim if index.dim() <= dim: count_dim = index.dim() - 1 ones = torch.ones(index.size(), dtype=src.dtype, device=src.device) count = scatter_sum(ones, index, count_dim, dim_size=dim_size) index = broadcast(index, src, dim) tmp = scatter_sum(src, index, dim, dim_size=dim_size) count = broadcast(count, tmp, dim).clamp(1) mean = tmp.div(count) var = (src - mean.gather(dim, index)) var = var * var var = scatter_sum(var, index, dim, out, dim_size) if unbiased: count = count.sub(1).clamp_(1) var = var.div(count) maximum = scatter_max(src, index, dim, out, dim_size)[0] minimum = scatter_min(src, index, dim, out, dim_size)[0] return torch.cat([mean,var,maximum,minimum],dim=1) N_edge_feats = args['N_edge_feats'] #6 N_dom_feats = args['N_dom_feats']#6 N_scatter_feats = 4 # N_targets = args['N_targets'] N_outputs = args['N_outputs'] N_metalayers = args['N_metalayers'] #10 N_hcs = args['N_hcs'] #32 #Possibly add (edge/node/global)_layers crit, y_post_processor, output_post_processor, cal_acc = Loss_Functions(name, args) likelihood_fitting = True if name[-4:] == 'NLLH' else False class Net(customModule): def __init__(self): super(Net, self).__init__(crit, y_post_processor, output_post_processor, cal_acc, likelihood_fitting, args) self.act = torch.nn.SiLU() self.hcs = N_hcs N_x_feats = N_dom_feats + N_scatter_feats*N_edge_feats self.x_encoder = torch.nn.Linear(N_x_feats,self.hcs) self.conv = nn.recurrent.temporalgcn.TGCN(self.hcs,self.hcs) self.decoder = torch.nn.Linear(self.hcs*4,N_outputs) self.GATConv = GATConv(self.hcs, self.hcs, 3, add_self_loops = False) def forward(self,data): x, edge_attr, edge_index, batch = data.x, data.edge_attr, data.edge_index, data.batch x = torch.cat([x,scatter_distribution(edge_attr,edge_index[1],dim=0)],dim=1) # x0 = x.clone() time_sort = torch.argsort(x[:,1]) batch_time_sort = time_sort[torch.argsort(batch[time_sort])] time_edge_index = torch.cat([batch_time_sort[:-1].view(1,-1),batch_time_sort[1:].view(1,-1)],dim=0) graph_ids, graph_node_counts = batch.unique(return_counts=True) tmp_bool = torch.ones(time_edge_index.shape[1],dtype=bool) tmp_bool[(torch.cumsum(graph_node_counts,0) - 1)[:-1]] = False time_edge_index = time_edge_index[:,tmp_bool] time_edge_index = torch.cat([time_edge_index,time_edge_index.flip(0)],dim=1) x = self.act(self.x_encoder(x)) x, (e, w) = self.GATConv(x, edge_index, return_attention_weights = True) return x, e, w print(x, e, w) h = self.act(self.conv(x, time_edge_index)) for i in range(N_metalayers): h = self.act(self.conv(x,time_edge_index,H=h)) x = scatter_distribution(h,batch,dim=0) x = self.decoder(x) return x return Net<file_sep>/GraphCreatorImproved.py import pandas as pd from torch_geometric.data import InMemoryDataset, Data import numpy as np import torch_geometric.transforms as T import torch from tqdm import tqdm import FunctionCollection as fc from datetime import datetime import sqlite3 filename = "rasmus_classification_muon_3neutrino_3mio.db" db_path = "C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/raw_data/{}".format(filename) destination = "C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/datasets" iteration = 3 edge_creator = fc.edge_creators(iteration) particle = 'stopped_muons' #2_neutrinos' #'muonNeutrino' #'3_neutrinos' #'muon' save_filename = 'stopped_muons_{}set2'.format(iteration)#'EMu_neutrinos_set2' #'muonNeutrino_set2' #'muon_set2' #'muonNeutrino_set1' #'neutrinos_set1' #'muon_set1' event_nos = None # event_nos = pd.read_pickle(destination + '/event_nos_500k_muon_set1.pkl').iloc[:100000] # event_nos = pd.read_pickle(destination + '/event_nos_0k_test.pkl') print('{}: Collecting event numbers..'.format(datetime.now())) if event_nos is None: subdivides = 200000 N = 1*subdivides if particle == 'muon': query = "SELECT event_no FROM truth WHERE pid = 13" with sqlite3.connect(str(db_path)) as con: event_nos = pd.read_sql(query,con) event_nos = event_nos.sample(N) elif particle == '3_neutrinos': query = "SELECT event_no FROM truth WHERE pid = 12" with sqlite3.connect(str(db_path)) as con: event_nos = pd.read_sql(query,con) event_nos_electron = event_nos.sample(N//3) query = "SELECT event_no FROM truth WHERE pid = 14" event_nos = pd.read_sql(query,con) event_nos_muon = event_nos.sample(N//3) query = "SELECT event_no FROM truth WHERE pid = 16" event_nos = pd.read_sql(query,con) event_nos_tau = event_nos.sample(N//3) event_nos = pd.concat([event_nos_electron,event_nos_muon,event_nos_tau],dim=0) elif particle == '2_neutrinos': query = "SELECT event_no FROM truth WHERE pid = 12" with sqlite3.connect(str(db_path)) as con: event_nos = pd.read_sql(query,con) event_nos_electron = event_nos.sample(N//2) query = "SELECT event_no FROM truth WHERE pid = 14" event_nos = pd.read_sql(query,con) event_nos_muon = event_nos.sample(N//2) event_nos = pd.concat([event_nos_electron,event_nos_muon],axis=0).sample(N) elif particle == 'muonNeutrino': query = "SELECT event_no FROM truth WHERE pid = 14" with sqlite3.connect(str(db_path)) as con: event_nos = pd.read_sql(query,con) event_nos = event_nos.sample(N) elif particle == 'stopped_muons': query = "SELECT event_no FROM truth WHERE pid IN (-13,13) AND stopped_muon = 1" with sqlite3.connect(str(db_path)) as con: event_nos_stopped = pd.read_sql(query,con).sample(N//2) query = "SELECT event_no FROM truth WHERE pid IN (-13,13) AND stopped_muon = 0" event_nos_not_stopped = pd.read_sql(query,con).sample(N//2) event_nos = pd.concat([event_nos_stopped,event_nos_not_stopped],axis=0).sample(N) event_nos.to_pickle(destination + '/' + 'event_nos_{}k_{}.pkl'.format(N//1000,save_filename)) print('{}: Saved relevant event numbers.. \nBeginning Graph creation..'.format(datetime.now())) else: with sqlite3.connect(str(db_path)) as con: subdivides = event_nos.shape[0] N = subdivides tfs = pd.read_pickle("C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/datasets/transformers.pkl") print("Remember, transformer is currently activated to inverse_transform position variables..") for subset in range(N//subdivides): event_no_subset = event_nos.iloc[subset*subdivides:(subset+1)*subdivides] query = "SELECT charge_log10, time, pulse_width, dom_x, dom_y, dom_z, event_no FROM features WHERE event_no IN {} and SRTInIcePulses = 1".format(tuple(event_no_subset.event_no)) events = pd.read_sql(query,con) print('{}: Events features extracted..'.format(datetime.now())) ####Important that position is the last 3, even for code not visible here################################################## if tfs is not None: print('{}: Inverse transforming..'.format(datetime.now())) x_pos = torch.tensor(tfs['features']['dom_x'].inverse_transform(events[['dom_x']]),dtype=torch.float) y_pos = torch.tensor(tfs['features']['dom_y'].inverse_transform(events[['dom_y']]),dtype=torch.float) z_pos = torch.tensor(tfs['features']['dom_z'].inverse_transform(events[['dom_z']]),dtype=torch.float) x = torch.cat([torch.tensor(events[['charge_log10','time','pulse_width']].values,dtype=torch.float),x_pos,y_pos,z_pos],dim=1) # pos = torch.cat([x_pos,y_pos,z_pos],dim=1) else: x = torch.tensor(events[['charge_log10','time','pulse_width','dom_x','dom_y','dom_z']].values,dtype=torch.float) #Features # pos = torch.tensor(events[['dom_x','dom_y','dom_z']].values,dtype=torch.float) #Position _, events = np.unique(events.event_no.values.flatten(), return_counts = True) query = "SELECT energy_log10, time, position_x, position_y, position_z, direction_x, direction_y, direction_z, azimuth, zenith, stopped_muon FROM truth WHERE event_no IN {}".format(tuple(event_no_subset.event_no)) y = pd.read_sql(query,con) print('{}: Events truths extracted..'.format(datetime.now())) y = torch.tensor(y.values,dtype=torch.float) #Target data_list = [] for tmp_x, tmp_y in tqdm(zip(torch.split(x, events.tolist()), y), total = subdivides): dat = Data(x=tmp_x,edge_index=None,edge_attr=None,y=tmp_y,pos=tmp_x[:,-3:]) dat = edge_creator(dat) data_list.append(dat) data, slices = InMemoryDataset.collate(data_list) torch.save((data,slices), destination + '/{}k_{}{}.pt'.format(subdivides//1000,save_filename,subset)) print('{}: File saved..'.format(datetime.now())) subset += 1 data_list = [] if data_list != []: data, slices = InMemoryDataset.collate(data_list) torch.save((data,slices), destination + '/{}k_{}{}.pt'.format(subdivides//1000,save_filename,subset)) <file_sep>/legacy/Models/Model9.py from torch_geometric.nn import GINConv, SGConv, SAGPooling, GCNConv, GATConv, DNAConv, ChebConv from torch_scatter import scatter_add, scatter_max, scatter_mean import torch.nn.functional as F import torch class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() self.hcs = 60 # Hidden channels # Model1 self.lin1 = torch.nn.Linear(5,self.hcs) self.model1 = torch.nn.ModuleList() for i in range(10): self.model1.append(GCNConv(self.hcs,self.hcs)) # self.lin11 = torch.nn.Linear(self.hcs*3,1) #add GATConv? # Model2 self.lin2 = torch.nn.Linear(5,self.hcs) self.model2 = torch.nn.ModuleList() for i in range(10): self.model2.append(GINConv(torch.nn.Sequential(torch.nn.Linear(self.hcs,self.hcs),torch.nn.Tanhshrink()))) # self.lin22 = torch.nn.Linear(self.hcs*3,1) # Model3 self.lin3 = torch.nn.Linear(5,self.hcs) self.ChebConv = ChebConv(self.hcs,self.hcs,10) # self.lin33 = torch.nn.Linear(self.hcs*3,1) # Model4 DNAConv # self.lin5 = torch.nn.Linear(5,self.hcs) # self.model4 = torch.nn.ModuleList() # for i in range(5): # Final self.linFinal = torch.nn.Linear(3*self.hcs*3,1) # input size = Number of models * 1 def forward(self, data): x1 = x2 = x3 = data.x edge_index = data.edge_index # Model1 x1 = F.leaky_relu(self.lin1(x1)) for conv in self.model1: x1 = conv(x1,edge_index) x1 = torch.cat([scatter_add(x1,data.batch,dim=0),scatter_mean(x1,data.batch,dim=0),scatter_max(x1,data.batch,dim=0)[0]],dim=1) # x1 = F.softmax(self.lin11(x1)) # Model2 x2 = F.leaky_relu(self.lin2(x2)) for conv in self.model2: x2 = conv(x2,edge_index) x2 = torch.cat([scatter_add(x2,data.batch,dim=0),scatter_mean(x2,data.batch,dim=0),scatter_max(x2,data.batch,dim=0)[0]],dim=1) # x2 = F.softmax(self.lin22(x2)) # Model3 x3 = F.leaky_relu(self.lin3(x3)) x3 = self.ChebConv(x3, edge_index) x3 = torch.cat([scatter_add(x3,data.batch,dim=0),scatter_mean(x3,data.batch,dim=0),scatter_max(x3,data.batch,dim=0)[0]],dim=1) # x3 = F.softmax(self.lin33(x3)) return F.log_softmax(self.linFinal(torch.cat([x1,x2,x3],dim=1)))<file_sep>/MoonAnalysis/FCMA.py import numpy as np from scipy.integrate import quad, quad_vec, romb from iminuit.util import make_func_code from iminuit import describe from tqdm import tqdm def sample(distribution,N): subsample = np.quantile(distribution,np.random.uniform(0,1,N)) return subsample def sample2d(df2d,N,noise=0.01): return df2d.sample(N,replace=True) + np.random.normal(0,noise,(N,2)) # def MCsample(func,xlims,ylims): def fan_out(x): N = x.shape[0] angles = np.random.random(N)*2*np.pi tmp = np.zeros((N,2,2)) sin = np.sin(angles) cos = np.cos(angles) tmp[:,0,0] = cos tmp[:,0,1] = -sin tmp[:,1,0] = sin tmp[:,1,1] = cos xy = np.hstack([x.reshape(N,1),np.zeros((N,1))]) return np.matmul(xy.reshape(N,1,2),tmp).reshape(N,2) def gauss(x,mu,sigma): x = np.asarray(x).reshape(-1,1) mu = np.expand_dims(mu,0) sigma = np.expand_dims(sigma,0) return np.exp(-0.5*((x-mu)/sigma)**2)/(sigma*np.sqrt(2*np.pi)) class integratedLH: def __init__(self, f): self.f = f self.func_code = make_func_code(describe(self.f)) def __call__(self, *par): return self.f(*par) def default_errordef(self): return 0.5 def log_gauss(x,mu,sigma,eps=1e-7): x = np.asarray(x).reshape(-1,1) mu = np.expand_dims(mu,0) sigma = np.expand_dims(sigma,0) return -0.5*((x-mu)/sigma)**2 - np.log(sigma*np.sqrt(2*np.pi)+eps) def return_losses_1d(mus,sigmas,lims): def LF1_1d(mu, sigma): return -quad(lambda x: log_gauss(x,mu,sigma)*(gauss(x,mus,sigmas).sum(1)),*lims)[0] def LF2_1d(mu,sigma): return -np.sum(np.log(quad_vec(lambda x: gauss(x,mu,sigma)*gauss(x,mus,sigmas),*lims)[0])) return LF1_1d, LF2_1d def gauss2d(x,y,mus,sigmas): xy = (np.vstack((x,y,)).T).reshape(-1,2,1) mus = mus.T.reshape(1,2,-1) sigmas = sigmas.reshape(1,-1) z_sqrd = (((xy - mus)/sigmas)**2).sum(1) return np.exp(-0.5*z_sqrd)/(2*np.pi*sigmas**2) # def log_gauss2d(x,y,mu_x,mu_y,sigma,eps=1e-7): # z_sqrd = ((x-mu_x)**2 + (y - mu_y)**2)/ sigma**2 # return -0.5*z_sqrd - np.log(2*np.pi*sigma**2 + eps) # def return_LF1_2d_and_P_2d(xy_reco,xy_sigma,lim): # def P_2d(x,y,mu_x,mu_y,sigma,f): # # z_sqrd = ((X.flatten()-mu_x)**2 + (Y.flatten() - mu_y)**2)/ sigma**2 # # P = 1/(4*int_lim**2 - f*sigma**2*2*np.pi)*(1 - f*np.exp(-0.5*z_sqrd)) # z_sqrd = ((x-mu_x)**2 + (y - mu_y)**2)/ sigma**2 # return 1/(4*lim**2 - f*sigma**2*2*np.pi)*(1 - f*np.exp(-0.5*z_sqrd))#np.log(1 - f*np.exp(-0.5*z_sqrd)/(2*np.pi*sigma**2)) # def LF1_2d(mu_x,mu_y,sigma,f): # return -dblquad(lambda x,y: np.log(P_2d(x,y,mu_x,mu_y,sigma,f))*(gauss2d(x,y,xy_reco,xy_sigma).sum(1)),-lim,lim,-lim,lim)[0] # return LF1_2d, P_2d def return_LF1_2d_and_P_2d(xy_reco, xy_sigma, N_samples, lim, subsample = 5000): assert np.log(N_samples - 1)/np.log(2)%1 == 0, "N_samples need to be of the form 2**k + 1" x_grid = np.linspace(-lim,lim,N_samples + 1) y_grid = x_grid.copy() X_grid, Y_grid = np.meshgrid(x_grid,y_grid) x = binc(x_grid) y = x.copy() X, Y = np.meshgrid(x,y) dx = (x[1:] - x[:-1]).mean() dy = (y[1:] - y[:-1]).mean() P_obs = np.zeros(N_samples**2) for i in tqdm(range(0,xy_reco.shape[0],subsample)): P_obs += gauss2d(X.flatten(),Y.flatten(),xy_reco[i:i+subsample],xy_sigma[i:i+subsample]).sum(1) def P_2d(x,y,mu_x,mu_y,sigma,f): z_sqrd = ((x-mu_x)**2 + (y - mu_y)**2)/ sigma**2 return 1/(4*lim**2 - f*sigma**2*2*np.pi)*(1 - f*np.exp(-0.5*z_sqrd)) def LF1_2d(mu_x,mu_y,sigma,f): P = np.log(P_2d(X.flatten(),Y.flatten(),mu_x,mu_y,sigma,f))*P_obs return -romb(romb(P.reshape(N_samples,N_samples,-1),dy,0),dx,0) return LF1_2d, P_2d, P_obs, (X_grid,Y_grid), (X,Y) def return_LF2_2d_and_P_2d(xy_reco, xy_sigma, lim): def P_2d(x,y,mu_x,mu_y,sigma,f): Print("Wrong normalization!") z_sqrd = ((x-mu_x)**2 + (y - mu_y)**2)/ sigma**2 return 1/(4*lim**2 - f*sigma**2*2*np.pi)*(1 - f*np.exp(-0.5*z_sqrd)) def LF2_2d(mu_x,mu_y,sigma,f): Print("Called") loss = -np.sum(np.log(quad_vec(lambda y: quad_vec(lambda x: P_2d(x,y,mu_x,mu_y,sigma,f)*(gauss2d(x,y,xy_reco,xy_sigma)),-lim,lim)[0],-lim,lim)[0])) Print("Returning Loss") return loss return LF2_2d, P_2d def binc(x): return 0.5*(x[1:] + x[:-1]) def Print(statement): from time import localtime, strftime print("{} - {}".format(strftime("%H:%M:%S", localtime()),statement)) <file_sep>/README.md # Neutrino-Machine-Learning Using Machine Learning on simulated IceCube data. ## Table of contents: 1. [ Data ](#data) * [ GraphCreator.py ](#GraphCreator) * [ GraphCreatorImproved.py ](#GraphCreatorImproved) * [ CreateTorchDataset.py ](#CreateTorchDataset) * [ MergeDataBases.py ](#MergeDataBases) * [ Mock_GraphCreator.ipynb ](#Mock_GraphCreator) 2. [ Model ](#Model) * [ Models (folder) ](#Models) * [ Trained_Models (folder) ](#Trained_Models) * [ Test_trained_models.ipynb ](#Test_trained_models) 3. [ Various ](#Various) * [ azimuth_normal_distribution.ipynb ](#azimuth_normal_distribution) * [ FunctionCollection.py ](#FunctionCollection) * [ Notes.ipynb ](#Notes) * [ Simulator ](#Simulator) * [ InvestigativeNotebook.ipynb ](#InvestigativeNotebook) <a name="data"></a> ## 1. Data This section covers the contents of the notebooks / python files which have anything to do with data manipulation and graph creation. <a name="GraphCreator"></a> ### GraphCreator Is a python file for creating graphs, given a set of event numbers. However, the inverse transforming and so forth is not parallelized, so a new 'better' file is the GraphCreatorImproved. <a name="GraphCreatorImproved"></a> ### GraphCreatorImproved This python file loads a bunch of events based on a set of event numbers and returns a dataset consisting of graphs. <a name="CreateTorchDataset"></a> ### CreateTorchDataset Was the first endition of a graph creating script, and is not optimal. <a name="MergeDataBases"></a> ### MergeDataBases Converts a DB file to a csv file. It is not really employed anymore. <a name="Mock_GraphCreator"></a> ### Mock_GraphCreator This notebook investigates the effects of the different functions that can define edges in a graph. <a name="Model"></a> ## 2. Model This section contains the scripts / notebooks that have anything to do with model training and testing and so forth. <a name="Models"></a> ### Models This is a folder containing a number of Pytorch models which have been tried and tested. <a name="Trained_Models"></a> ### Trained_Models This folder contains the weights and optimizer status for different trained models. <a name="Test_trained_models"></a> ### Test_trained_models There are numerous python files and notebooks which investigates the performance of a model. This endition is, however, the latest. But I will try to create a newer and more general .py file or notebook (work in progress).. <file_sep>/legacy/Model_Tester_Types.py import matplotlib.pyplot as plt import numpy as np import pandas as pd import os import torch from torch_geometric.data import DataLoader, InMemoryDataset import time import importlib from sklearn.dummy import DummyClassifier # #### For loading the dataset as a torch_geometric InMemoryDataset #### # #The @properties should be unimportant for now, including process since the data is processed. # class MakeDataset(InMemoryDataset): # def __init__(self, root, transform=None, pre_transform=None): # super(MakeDataset, self).__init__(root, transform, pre_transform) # # print(self.processed_paths) # self.data, self.slices = torch.load(self.processed_paths[-1]) #Loads PROCESSED.file # #perhaps check print(self.processed_paths) # @property # def raw_file_names(self): # return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/raw_data') # @property # def processed_file_names(self): # return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') # def process(self): # pass # print('Loads data') # dataset = MakeDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset') # dataset_background = MakeDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/dataset_background') # #### ##### # #### Changing target variables to one hot encoded (or not) neutrino type #### # #### or changing them to neutri8730no and have muons as background # #### It is important to remember to change the slicing as well as y# # # types = torch.tensor([np.zeros(100000),np.ones(100000),np.ones(100000)*2],dtype=torch.int64).reshape((1,-1)) # types = torch.tensor(np.zeros(300000),dtype=torch.int64) # dataset.data.y = types # dataset.slices['y'] = torch.tensor(np.arange(300000+1)) # dataset_background.data.y = torch.tensor(np.ones(dataset_background.len()),dtype=torch.int64) # dataset_background.slices['y'] = torch.tensor(np.arange(dataset_background.len() + 1)) # #### #### # ####Look at subset #### # subsize = 30000 # nu_e_ind = np.random.choice(np.arange(100000),subsize,replace=False).tolist() # nu_t_ind = np.random.choice(np.arange(100000,200000),subsize,replace=False).tolist() # nu_m_ind = np.random.choice(np.arange(200000,300000),subsize,replace=False).tolist() # muon_ind = np.random.choice(np.arange(dataset_background.len()),3*subsize,replace=False).tolist() # train_dataset = dataset[nu_e_ind] + dataset[nu_t_ind] + dataset[nu_m_ind] + dataset_background[muon_ind] # test_ind_e = np.arange(100000)[pd.Series(np.arange(100000)).isin(nu_e_ind).apply(lambda x: not(x))].tolist() # test_ind_t = np.arange(100000,200000)[pd.Series(np.arange(100000,200000)).isin(nu_e_ind).apply(lambda x: not(x))].tolist() # test_ind_m = np.arange(200000,300000)[pd.Series(np.arange(200000,300000)).isin(nu_e_ind).apply(lambda x: not(x))].tolist() # test_ind_muon = np.arange(dataset_background.len())[pd.Series(np.arange(dataset_background.len())).isin(nu_e_ind).apply(lambda x: not(x))].tolist() # test_dataset = dataset[test_ind_e] + dataset[test_ind_t] + dataset[test_ind_m] + dataset_background[test_ind_muon] # # train_dataset = dataset[:100000] + dataset[100000:200000] + dataset[200000:] + dataset_background # # dataset = dataset.shuffle() # # train_dataset = dataset[:200000] # # val_dataset = dataset[200000:250000] # # test_dataset = dataset[250000:] # #### #### class MakeDataset(InMemoryDataset): def __init__(self, root, dataset): super(MakeDataset, self).__init__(root) # print(self.processed_paths) self.data, self.slices = torch.load(root+'/' + dataset) @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/copy_dataset/processed') def process(self): pass train_dataset = MakeDataset('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/train_test_datasets','train_class') train_dataset = train_dataset.shuffle() batch_size = 64 train_loader = DataLoader(train_dataset, batch_size=batch_size,shuffle=True) # val_loader = DataLoader(val_dataset, batch_size=batch_size) # test_loader = DataLoader(test_dataset, batch_size=1024) #### predicting baseline classification def dummy_prediction(stratified_num = 20): dummy_clf1 = DummyClassifier(strategy="most_frequent") dummy_clf2 = DummyClassifier(strategy='stratified') target = dataset.data.y[train_dataset.indices()] empty_array = np.empty(train_dataset.__len__()) dummy_clf1.fit(empty_array,target) dummy_clf2.fit(empty_array,target) pred1 = dummy_clf1.score(empty_array,target) pred2 = np.asarray([dummy_clf2.score(empty_array,target) for i in range(stratified_num)]) print(f'Dummy predicter: most frequent: {pred1}, stratified: {pred2.mean()} +- {pred2.std()}') # dummy_prediction() #### print('Loads model') #Define model: #The syntax is for model i: from Models.Model{i} import Net import Models.Model7 as Model Model = importlib.reload(Model) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = Model.Net().to(device) optimizer = torch.optim.Adam(model.parameters(), lr=0.005) crit = torch.nn.NLLLoss() #Loss function # # #For loading existing model and optimizer parameters. # print('Loading existing model and optimizer states') # state = torch.load('Trained_Models/Model5_Class.pt') # model.load_state_dict(state['model_state_dict']) # optimizer.load_state_dict(state['optimizer_state_dict']) batch_loss, batch_acc = [], [] def train(): model.train() correct = 0 for data in train_loader: data = data.to(device) label = data.y optimizer.zero_grad() output = model(data) del data loss = crit(output, label) loss.backward() optimizer.step() batch_loss.append(loss.item()) acc = output.argmax(dim=1).eq(label).sum() batch_acc.append(acc.item()/batch_size) correct += acc torch.cuda.empty_cache() return loss.item(), (correct.float()/len(train_dataset)).item() print('ready for training') loss_list, acc_list = [], [] def epochs(i): print('Begins training') t = time.time() for epoch in range(i): print(f'Epoch: {epoch}') curr_loss,ratio = train() <<<<<<< HEAD loss_list.append(curr_loss.item()) ratio_list.append(ratio.item()) print(curr_loss.item(),ratio.item()) ======= print('Done') def test(): correct = 0 with torch.no_grad(): for data in test_loader: data = data.to(device) label = data.y output = model(data) del data correct += output.argmax(dim=1).eq(label).sum() torch.cuda.empty_cache() return (correct.float()/len(test_dataset)).item() def test_all(): model.eval() score_list = [] with torch.no_grad(): for data in train_loader: data = data.to(device) label = data.y output = model(data) del data score_list.append(output.tolist()) torch.cuda.empty_cache() return score_list<file_sep>/legacy/CreateTorchDataset.py import os from torch_geometric.data import InMemoryDataset, Data import pandas as pd import numpy as np import torch_geometric.transforms as T import torch #In memory was just about possible with 16gb Ram and nothing else running. #Consists of 5 input features dom_pos, dom_charge, dom_time #Node = dom, edges is generated by k-Nearest Neighbours, with k = 6 #Runtime was a couple of hours for all 300.000 events ### TO-DO; is it optimized? If not perhaps do that. # seq = pd.read_csv('data/sequential.csv') # scalar = pd.read_csv('data/scalar.csv') # class MyOwnDataset(InMemoryDataset): # def __init__(self, root, transform=None, pre_transform=None): # super(MyOwnDataset, self).__init__(root, transform, pre_transform) # self.data, self.slices = torch.load(self.processed_paths[0]) # @property # def raw_file_names(self): # return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/raw_data') # @property # def processed_file_names(self): # return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/dataset/processed') # def process(self): # if self.processed_file_names is not None: # return # else: # seq = pd.read_csv('data/sequential.csv') # scalar = pd.read_csv('data/scalar.csv') # data_list = [] # i = 0 # for index, sca in scalar.iterrows(): # tmp_event = seq.loc[seq['event_no'] == sca['event_no']] # x = torch.tensor(tmp_event[['dom_charge','dom_time','dom_x','dom_y','dom_z']].to_numpy(),dtype=torch.float) #Features # pos = torch.tensor(tmp_event[['dom_x','dom_y','dom_z']].to_numpy(),dtype=torch.float) #Position # y = torch.tensor(sca[sca.keys()[3:]].to_numpy(),dtype=torch.float) #Target # dat = Data(x=x,edge_index=None,edge_attr=None,y=y,pos=pos) # T.KNNGraph(loop=True)(dat) #defining edges by k-NN with k=6 # data_list.append(dat) # if i % 1000 == 0: # print(i) # i += 1 # if self.pre_filter is not None: # data_list = [data for data in data_list if self.pre_filter(data)] # if self.pre_transform is not None: # data_list = [self.pre_transform(data) for data in data_list] # data, slices = self.collate(data_list) # torch.save((data,slices), self.processed_paths[0]) # MyOwnDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/dataset') #Target variables are energy, time, xyz, directions xyz #Generating cosmic torch dataset: # seq_background = pd.read_csv('data/sequential_background.csv') # scalar_background = pd.read_csv('data/scalar_background.csv') class MyOwnDataset(InMemoryDataset): def __init__(self, root, transform=None, pre_transform=None): super(MyOwnDataset, self).__init__(root, transform, pre_transform) print(self.processed_paths) # self.data, self.slices = torch.load(self.processed_paths[-1]) @property def raw_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/raw_data') @property def processed_file_names(self): return os.listdir('C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/dataset_background') def process(self): seq_b = pd.read_csv('data/sequential_background.csv') scalar_b = pd.read_csv('data/scalar_background.csv') data_list = [] i = 0 for index, sca in scalar_b.iterrows(): tmp_event = seq_b.loc[seq_b['event_no'] == sca['event_no']] x = torch.tensor(tmp_event[['dom_charge','dom_time','dom_x','dom_y','dom_z']].to_numpy(),dtype=torch.float) #Features pos = torch.tensor(tmp_event[['dom_x','dom_y','dom_z']].to_numpy(),dtype=torch.float) #Position y = torch.tensor(sca[sca.keys()[2:]].to_numpy(),dtype=torch.float) #Target dat = Data(x=x,edge_index=None,edge_attr=None,y=y,pos=pos) T.KNNGraph(loop=True)(dat) #defining edges by k-NN with k=6 data_list.append(dat) if i % 1000 == 0: print(i) i += 1 if self.pre_filter is not None: data_list = [data for data in data_list if self.pre_filter(data)] if self.pre_transform is not None: data_list = [self.pre_transform(data) for data in data_list] # print(data_list) data, slices = self.collate(data_list) torch.save((data,slices), self.processed_paths[0]) # MyOwnDataset(root = 'C:/Users/jv97/Desktop/github/Neutrino-Machine-Learning/dataset_background') #Could be done without all this, but the collate method is nessecary and torch.save
7624f6bac9d3db9d5d35a33712c7d54b5936e763
[ "Markdown", "Python" ]
34
Python
Vinther901/Neutrino-Machine-Learning
b2b3187d55fa5c89b426897edded1654d9082c16
c5a7f2f857bb15726dcd1f33bc00900d59d624ec
refs/heads/main
<file_sep>import styled, { css } from 'styled-components' import media from 'styled-media-query' export const Wrapper = styled.div` ${({ theme }) => css` margin: ${theme.spacings.small} 0; `} ` export const Content = styled.div` ${({ theme }) => css` display: grid; gap: ${theme.spacings.xsmall}; grid-template-columns: repeat(2, 1fr); margin-top: ${theme.spacings.small}; ${media.greaterThan('medium')` grid-template-columns: repeat(3, 1fr); `} ${media.greaterThan('large')` grid-template-columns: repeat(6, 1fr); `} `} ` export const Block = styled.div`` export const Label = styled.h3` ${({ theme }) => css` font-size: ${theme.font.sizes.small}; font-weight: ${theme.font.light}; color: ${theme.colors.white}; `} ` export const Description = styled.p` ${({ theme }) => css` font-size: ${theme.font.sizes.medium}; font-weight: ${theme.font.bold}; color: ${theme.colors.white}; `} ` export const IconsWrapper = styled.div` ${({ theme }) => css` color: ${theme.colors.white}; `} ` export const Icon = styled.span` ${({ theme }) => css` margin-right: ${theme.spacings.xxsmall}; `} `
187e22bde5054c98dcd9703284c9a1c7a74cf174
[ "JavaScript" ]
1
JavaScript
Morpa/Won-Games-Client
12d5affb176141cb1b97383ba7d5d1b70f4ee1be
1f3d98a216bc5213c14b8dfc1b9614b3fe5f114c
refs/heads/master
<repo_name>marcelobh864/repMusicasSertanejas<file_sep>/paginabandas2.php <style> body{ background-color: #FFFAF0; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } #topo{background-color: #000000; width: 100%; height: 110px; } p.Ptopo{ text-decoration: none; color: #FF4500; font-style: italic; position: absolute; left: 3%; top: 1%; font-size: 31px; } a.retorno{ text-decoration: none; color: #FF4500; position: absolute; left: 80%; top: 12%; font-size: 18px; } #Tprincipal { position: absolute; left: 48%; top: 31%; height: 37%; width: 24%; margin-left: 10px; margin-right: 10px; } p.Pbiografia { position:absolute; top: 24%; left: 48%; margin-left: 10px; margin-right: 10px; } p.NomeS { position:absolute; top: 17%; left: 32%; margin-left: 10px; margin-right: 10px; font-weight: bold; font-size: 26px; } p.lbagenda { position:absolute; top: 73%; left: 48%; margin-left: 10px; margin-right: 10px; } p.SiteB { position:absolute; top: 73%; left: 13%; margin-left: 10px; margin-right: 10px; } p.RedeB { position:absolute; top: 82%; left: 13%; margin-left: 10px; margin-right: 10px; } p.ContadoB { position:absolute; top: 90%; left: 13%; margin-left: 10px; margin-right: 10px; } input.txtnomebanda { position:absolute; top: 35%; left: 12%; margin-left: 10px; margin-right: 10px; } #conteutomusica { position:absolute; top: 45%; left: 79%; margin-left: 10px; margin-right: 10px; } #Tsecundario { position:absolute; width: 24%; top: 81%; height: 14%; left: 48%; margin-left: 10px; margin-right: 10px; } label.lbagenda { position:absolute; top: 73%; left: 62%; margin-left: 10px; margin-right: 10px; } label.lbcontato{ position: absolute; left: 12%; top: 54%; margin-left: 10px; margin-right: 10px; } #imagem{ position: absolute; left: 14%; top: 31%; border-color:#000000; border-style: solid; border-width: 1px; height: 37%; width: 24%; } .op{ position:absolute; left:75%; top:31%; } table tr td { /* Toda a tabela com fundo creme */ background: #fff; overflow: hidden; border-collapse: collapse; text-align: center; } body { margin:0px; padding:0px; } </style> <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJAS</p> <a href="paginaconfiguracao2.php" class="retorno">Voltar tela anterior</a> </div> <p class="lbagenda">Abaixo é a agenda da banda: </p> <p class="Pbiografia">Biografia da banda ou cantor(a): </p> <?php require_once "conexmusi.php"; if(isset($_GET['id'])) { $id = $_GET['id']; $sql="SELECT * FROM bandas WHERE idbanda='$id'"; $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_assoc($result)) { echo "<div id='imagem'>"; echo "<img src='cantores/" .$row['fotobanda']."' width='100%' height='100%'>"; echo "</div>"; echo "<textarea cols=60 rows=29 id='Tprincipal'>". $row["biografiabanda"]."</textarea>"; echo "<textarea cols=60 rows=10 id='Tsecundario'>". $row["agendabanda"]."</textarea>"; echo "<p class='NomeS'>Nome da banda ou do cantor(a): ". $row["nomebanda"]."</p>"; echo "<p class='SiteB'>Site da banda ou do cantor(a):<br> ". $row["sitebanda"]."</p>"; echo "<p class='RedeB'>Rede social da banda ou do cantor(a):<br> ". $row["redesocialbanda"]."</p>"; echo "<p class='ContadoB'>Telefone de contado da banda ou do cantor(a): ". $row["telefonebanda"]."</p>"; } } else { echo "Erro!"; } ?> <table border="1" class="op"> <tr> <td width="280px">Musicas da banda </td> </tr> <?php if(isset($_GET['id'])) { require_once "conexmusi.php"; $id = $_GET['id']; $query = "SELECT codmusica, codbanda, nomemusica FROM musicas WHERE codbanda = $id"; $consultando = mysqli_query($con, $query); while($dado = mysqli_fetch_array($consultando)) { $idmusica = $dado['codmusica']; $codbanda = $dado['codbanda']; $name = $dado['nomemusica']; ?> <tr> <td width="280px"><?php echo "<a href='letrasmusicas.php?id=$id>$name</a><br/>";?></td> </tr> <?php } }?> </table> </body> </html><file_sep>/configuracoes.php <?php require_once "conexmusi.php"; if (isset($_POST['Salvar'])){ $NomeBanda = $_POST["Nbanda"]; $BiografiaBanda = $_POST["Bbanda"]; $AgendaBanda = $_POST["Bagenda"]; $SiteBanda = $_POST["Bsite"]; $RedeSocialBanda = $_POST["Bsite"]; $TelefoneBanda = $_POST["telbanda"]; $extensao = strtolower(substr($_FILES['fimage']['name'], - 4)); $novo_nome = md5(time()). $extensao; $imageFileType = strtolower(pathinfo($novo_nome,PATHINFO_EXTENSION)); if($imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg" || $imageFileType == "gif" ) { $diretorio = "cantores/"; move_uploaded_file($_FILES['fimage']['tmp_name'], $diretorio.$novo_nome); $sql_cod = "INSERT INTO bandas (idbanda, nomebanda, biografiabanda, fotobanda, agendabanda, sitebanda, redesocialbanda, telefonebanda) VALUES(null, '$NomeBanda', '$BiografiaBanda', '$novo_nome', '$AgendaBanda', '$SiteBanda', '$RedeSocialBanda', '$TelefoneBanda')"; if($res=mysqli_query($con,$sql_cod)){ $msg = "Arquivo enviado com sucesso!"; header('Location: configuracoes.php'); } else{ $msg = "Falha ao enviar arquivo."; } }else{ echo "Não dá para salvar à imagem!"; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> body{ background-color: #FFFAF0; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } #topo{background-color: #000000; width: 100%; height: 155px; } p.Ptopo{ text-decoration: none; color: #FF4500; font-style: italic; position: absolute; left: 3%; top: 2%; font-size: 36px; } a.retorno{ text-decoration: none; color: #FF4500; position: absolute; left: 80%; top: 15%; font-size: 20px; } #conteuto { position:absolute; width: 25%; top: 36%; height: 200px; left: 62%; margin-left: 10px; margin-right: 10px; } label.lbbiografia { position:absolute; top: 31%; left: 62%; margin-left: 10px; margin-right: 10px; } label.lbnomebanda { position:absolute; top: 31%; left: 12%; margin-left: 10px; margin-right: 10px; } input.txtnomebanda { position:absolute; top: 35%; left: 12%; margin-left: 10px; margin-right: 10px; } #conteutomusica { position:absolute; top: 45%; left: 79%; margin-left: 10px; margin-right: 10px; } #conteutoagenda { position:absolute; width: 25%; top: 78%; height: 100px; left: 62%; margin-left: 10px; margin-right: 10px; } label.lbagenda { position:absolute; top: 73%; left: 62%; margin-left: 10px; margin-right: 10px; } input.arquivo{ position: absolute; left: 33%; top: 73%; } label.lbfoto{ position: absolute; left: 33%; top: 31%; } label.lbsite{ position: absolute; left: 12%; top: 40%; margin-left: 10px; margin-right: 10px; } input.txtsite{ position: absolute; left: 12%; top: 48%; margin-left: 10px; margin-right: 10px; } label.lbcontato{ position: absolute; left: 12%; top: 54%; margin-left: 10px; margin-right: 10px; } input.txtcontato{ position: absolute; left: 12%; top: 62%; margin-left: 10px; margin-right: 10px; } #imagem{ position: absolute; left: 33%; top: 36%; border-color:#000000; border-style: solid; border-width: 1px; } label.lbsalvar{ width: 175px; position: absolute; left: 12%; top: 82%; margin-left: 10px; margin-right: 10px; } input.enviar{ width: 175px; position: absolute; left: 12%; top: 90%; margin-left: 10px; margin-right: 10px; } input.Limpar{ width: 175px; position: absolute; left: 12%; top: 76%; margin-left: 10px; margin-right: 10px; } label.lblimpar{ width: 175px; position: absolute; left: 12%; top: 68%; margin-left: 10px; margin-right: 10px; } body { margin:0px; padding:0px; } </style> <title></title> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJAS</p> <a href="paginaconfiguracao2.php" class="retorno">Voltar para tela anterior</a> </div> <form method="POST" name="Salvar" action="configuracoes.php" enctype="multipart/form-data"> <input type="file" required name="fimage" class="arquivo" onchange="showimage.call(this)"> <div id="imagem"> <img src="img/foto.jpg" id="fimage" height="195px" width="186px"> <!-- Com o comando style="display:none" igual no exemplo abaixo o campo da imagem fica limpo sem --> <!-- <img src="imagens/foto.jpg" style="display:none" id="image" height="125px" width="116px"> --> </div> <script type="text/javascript"> function showimage() { if(this.files && this.files[0]) { var obj = new FileReader(); obj.onload = function(data){ var image = document.getElementById("fimage"); image.src = data.target.result; image.style.display = "block"; } obj.readAsDataURL(this.files[0]); } } function redirecionar(){ window.location="configuracoes.php"; } </script> <label class="lbbiografia">Fale sobre a biografia da banda </label> <label class="lbnomebanda">Fale o nome da banda </label> <input class="txtnomebanda" type="text" required="" name="Nbanda"> <textarea id="conteuto" name="Bbanda" required="" placeholder="Fale sobre a biografia da banda ou do cantor(a):"></textarea> <label class="lbfoto"> Escolha a imagem da banda: </label> <label class="lbagenda">Fale sobre a agenda da banda </label> <textarea id="conteutoagenda" name="Bagenda" required="" placeholder="Fale sobre a agenda da banda ou do cantor(a):"></textarea> <label class="lbcontato">Escreva o o telefone de<br> contato da banda: </label> <input class="txtcontato" type="text" required="" name="telbanda"> <label class="lbsite">Escreva o link do site da<br> banda ou cantor(a): </label> <input class="txtsite" type="text" required="" name="Bsite"> <label class="lbsalvar"> Para salvar a matéria tecle o botão abaixo : </label> <input type="submit" name="Salvar" class="enviar" value="Cadastrar" > <label class="lblimpar"> Para limpar o formulario tecle no botão abaixo : </label> <input type="button" onclick="redirecionar()" class="Limpar" value="Limpar todos os campos"> </form> </body> </html><file_sep>/paginabandas.php <?php require_once "conexmusi.php"; session_start(); if(isset($_POST['Salvar'])) { $Cbanda=$_SESSION['CodBanda']; $sql_cod = "INSERT INTO curtidas (codigo, CodBanda) VALUES(null, '$Cbanda')"; if($res=mysqli_query($con,$sql_cod)){ $msg = "Arquivo enviado com sucesso!"; header('Location: paginabandas.php'); } } else { } ?> <style> body{ background-color: #FFFAF0; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } #topo{ background-color: #000000; width: 100%; height: 110px; } p.Ptopo{ text-decoration: none; color: #FF4500; font-style: italic; position: absolute; left: 3%; top: 1%; font-size: 31px; } a.retorno{ text-decoration: none; color: #FF4500; position: absolute; left: 80%; top: 12%; font-size: 18px; } #Tprincipal { position: absolute; left: 48%; top: 31%; height: 37%; width: 24%; margin-left: 10px; margin-right: 10px; } p.Pbiografia { position:absolute; top: 24%; left: 48%; margin-left: 10px; margin-right: 10px; } p.NomeS { position:absolute; top: 17%; left: 32%; margin-left: 10px; margin-right: 10px; font-weight: bold; font-size: 26px; } p.lbagenda { position:absolute; top: 73%; left: 48%; margin-left: 10px; margin-right: 10px; } p.SiteB { position:absolute; top: 70%; left: 13%; margin-left: 10px; margin-right: 10px; } p.RedeB { position:absolute; top: 79%; left: 13%; margin-left: 10px; margin-right: 10px; } p.ContadoB { position:absolute; top: 87%; left: 13%; margin-left: 10px; margin-right: 10px; } input.btcurtir { position:absolute; top: 94%; left: 13%; margin-left: 10px; margin-right: 10px; } p.total { position:absolute; top: 92%; left: 17%; margin-left: 10px; margin-right: 10px; } input.txtnomebanda { position:absolute; top: 35%; left: 12%; margin-left: 10px; margin-right: 10px; } #conteutomusica { position:absolute; top: 45%; left: 79%; margin-left: 10px; margin-right: 10px; } #Tsecundario { position:absolute; width: 24%; top: 81%; height: 14%; left: 48%; margin-left: 10px; margin-right: 10px; } label.lbagenda { position:absolute; top: 73%; left: 62%; margin-left: 10px; margin-right: 10px; } label.lbcontato{ position: absolute; left: 12%; top: 51%; margin-left: 10px; margin-right: 10px; } #imagem{ position: absolute; left: 14%; top: 31%; border-color:#000000; border-style: solid; border-width: 1px; height: 37%; width: 24%; } .op{ position:absolute; left:75%; top:31%; } table tr td { /* Toda a tabela com fundo creme */ background: #fff; overflow: hidden; border-collapse: collapse; text-align: center; } body { margin:0px; padding:0px; } </style> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJAS</p> <a href="index.php" class="retorno">Voltar tela anterior</a> </div> <p class="lbagenda">Abaixo é a agenda da banda: </p> <p class="Pbiografia">Biografia da banda ou cantor(a): </p> <form method="POST" name="Salvar" action="paginabandas.php"> <input type="submit" class="btcurtir" name="Salvar" value="curtir"> </form> <table border="1" class="op"> <tr> <td width="280px">Musicas da banda </td> </tr> <?php require_once "conexmusi.php"; if(isset($_GET['id'])){ $Cbanda=$_GET['id']; $_SESSION['CodBanda']=$Cbanda; $query = "SELECT codmusica, nomemusica FROM musicas WHERE codbanda = $Cbanda"; $consultando = mysqli_query($con, $query); while($dado = mysqli_fetch_array($consultando)) { $idmusica = $dado['codmusica']; $name = $dado['nomemusica']; ?> <tr> <td width="280px"><?php echo "<a href='letrasmusicas.php?id=$idmusica'>$name<br/>";?></td> </tr> <?php } $Cbanda=$_SESSION['CodBanda']; $sql="SELECT * FROM bandas WHERE idbanda='$Cbanda'"; $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_assoc($result)) { echo "<div id='imagem'>"; echo "<img src='cantores/" .$row['fotobanda']."' width='100%' height='100%'>"; echo "</div>"; echo "<textarea cols=60 rows=29 id='Tprincipal'>". $row["biografiabanda"]."</textarea>"; echo "<textarea cols=60 rows=10 id='Tsecundario'>". $row["agendabanda"]."</textarea>"; echo "<p class='NomeS'>Nome da banda ou do cantor(a): ". $row["nomebanda"]."</p>"; echo "<p class='SiteB'>Site da banda ou do cantor(a):<br> ". $row["sitebanda"]."</p>"; echo "<p class='RedeB'>Rede social da banda ou do cantor(a):<br> ". $row["redesocialbanda"]."</p>"; echo "<p class='ContadoB'>Telefone de contado da banda ou do cantor(a): ". $row["telefonebanda"]."</p>"; } $Cbanda=$_SESSION['CodBanda']; $query = "SELECT COUNT(CodBanda) AS TOTAL FROM curtidas WHERE CodBanda='$Cbanda'"; $result = mysqli_query($con, $query); $row = mysqli_fetch_assoc($result); echo "<p class='total'>Total de curtidas: ". $row['TOTAL']."</p>"; }else{ $Cbanda=$_SESSION['CodBanda']; $query = "SELECT codmusica, nomemusica FROM musicas WHERE codbanda = $Cbanda"; $consultando = mysqli_query($con, $query); while($dado = mysqli_fetch_array($consultando)) { $idmusica = $dado['codmusica']; $name = $dado['nomemusica']; ?> <tr> <td width="280px"><?php echo "<a href='letrasmusicas.php?id=$idmusica'>$name<br/>";?></td> </tr> <?php } $Cbanda=$_SESSION['CodBanda']; $sql="SELECT * FROM bandas WHERE idbanda='$Cbanda'"; $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_assoc($result)) { echo "<div id='imagem'>"; echo "<img src='cantores/" .$row['fotobanda']."' width='100%' height='100%'>"; echo "</div>"; echo "<textarea cols=60 rows=29 id='Tprincipal'>". $row["biografiabanda"]."</textarea>"; echo "<textarea cols=60 rows=10 id='Tsecundario'>". $row["agendabanda"]."</textarea>"; echo "<p class='NomeS'>Nome da banda ou do cantor(a): ". $row["nomebanda"]."</p>"; echo "<p class='SiteB'>Site da banda ou do cantor(a):<br> ". $row["sitebanda"]."</p>"; echo "<p class='RedeB'>Rede social da banda ou do cantor(a):<br> ". $row["redesocialbanda"]."</p>"; echo "<p class='ContadoB'>Telefone de contado da banda ou do cantor(a): ". $row["telefonebanda"]."</p>"; } $Cbanda=$_SESSION['CodBanda']; $query = "SELECT COUNT(CodBanda) AS TOTAL FROM curtidas WHERE CodBanda='$Cbanda'"; $result = mysqli_query($con, $query); $row = mysqli_fetch_assoc($result); echo "<p class='total'>Total de curtidas: ". $row['TOTAL']."</p>"; } ?> </table> </body> </html> <file_sep>/atualizar100.php <?php session_start(); require_once "conexao.php"; if (isset($_POST['Salvar'])){ $codigo = $_POST["codigo"]; $NomeBanda = $_POST["Nbanda"]; $BiografiaBanda = $_POST["Bbanda"]; $AgendaBanda = $_POST["Bagenda"]; $SiteBanda = $_POST["Bsite"]; $RedeSocialBanda = $_POST["Bsite"]; $TelefoneBanda = $_POST["telbanda"]; $extensao = strtolower(substr($_FILES['fimage']['name'], - 4)); $novo_nome = md5(time()). $extensao; $diretorio = "ImgMaterias/"; move_uploaded_file($_FILES['fimage']['tmp_name'], $diretorio.$novo_nome); $sql_cod = "UPDATE bandas SET nomebanda = $NomeBanda, biografiabanda = $BiografiaBanda, fotobanda = $novo_nome , agendabanda = $AgendaBanda, sitebanda = $SiteBanda, telefonebanda = $TelefoneBanda , WHERE idbanda = $codigo"; if($res=mysqli_query($con,$sql_cod)) { $msg = "Falha ao enviar arquivo."; } } ?> <!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> p.Pnome{position: absolute; left: 76px; top: 130px;} #image{border-color:#000; border-style: solid; border-width: 1px; position: absolute; top: 20px; left: 76px; height: 110px; width: 90px;} #imagebanco{border-color:#000000; border-style: solid; border-width: 1px; position: absolute; left: 270px; top: 140px; height: 205px; width: 196px;} #foto{border-color:#000000; border-style: solid; border-width: 1px; position: absolute; left: 490px; top: 140px; height: 205px; width: 196px;} textarea.Tprincipal{ position: absolute; left: 800px; top: 140px;} textarea.Tsecundario{ position: absolute; left: 270px; top: 440px;} a.retorno{text-decoration: none; color: #000000; position: absolute; left: 1120px; top: 45px;} h1.Ptopo{text-decoration: none; color: #000000; position: absolute; left: 272px; top: -22px; font-size: 52px; } p.Pnomemat{position: absolute; left: 76px; top: 270px;} p.NomeS{position: absolute; left: 76px; top: 220px;} input.arquivo{position: absolute; left: 490px; top: 405px; width: 120px;} label.Nimg{position: absolute; left: 490px; top: 360px; width: 280px;} label.Nimgatual{position: absolute; left: 270px; top: 360px; width: 220px;} label.lbsalvar{position: absolute; left: 70px; top: 358px; width: 220px;} input.enviar{position: absolute; left: 70px; top: 400px; } label.lblimpar{position: absolute; left: 70px; top:438px; width: 220px;} input.Limpar{position: absolute; left: 70px; top: 480px; } </style> </head> <body> <div id="topo"> <h1 class="Ptopo"> Caderno digital</h1> <a href="index.php" class="retorno">Voltar tela de login</a> </div> <?php require_once "conexao.php"; $user=$_SESSION["username"]; $senha=$_SESSION["<PASSWORD>"]; $sql = "SELECT Nome, foto FROM cadernocad WHERE login = '$user' AND senha = '$senha'"; $result = mysqli_query($con, $sql); while($row = mysqli_fetch_array($result)){ echo "<div id='image'>"; echo "<img src='load/" .$row['foto']."' width='100%' height='100%'>"; echo "</div>"; echo "<p class='Pnome'>Bem vindo(a)<br> ". $row["Nome"]."</p>"; } ?> <?php require_once "conexao.php"; $Matcod=$_SESSION["matcod"]; $usercpf=$_SESSION["cpfuser"]; $userusuario=$_SESSION["username"]; $consulta = "SELECT NomeMat FROM matprincipal WHERE codigo = '$Matcod' AND cpf = '$usercpf'"; $consultando = mysqli_query($con, $consulta); while($dado = mysqli_fetch_array($consultando)) { echo "<p class='Pnomemat'>Esse tópico está <br>relacionado com à <br>materia: ". $dado["NomeMat"]."</p>";} ?> <form method="POST" name="Salvar" action="Atualizar.php" enctype="multipart/form-data"> <?php require_once "conexao.php"; $Matcodprincipal=$_SESSION["CMAT"]; $Matcodsecundario=$_SESSION["matcod"]; $sql = "SELECT Nmateria, imagem, textoprinc, observacao1 FROM materias WHERE codmat = '$Matcodprincipal' AND codmatprinc = '$Matcodsecundario'"; $result = mysqli_query($con, $sql); while($row = mysqli_fetch_array($result)){ echo "<div id='imagebanco'>"; echo "<img src='ImgMaterias/" .$row['imagem']."' width='100%' height='100%'>"; echo "</div>"; echo "<textarea name='texto' cols=60 rows=30 class='Tprincipal'>". $row["textoprinc"]."</textarea>"; echo "<textarea name='exe1' cols=60 rows=10 class='Tsecundario'>". $row["observacao1"]."</textarea>"; echo "<p class='NomeS'>Esse tópico é o <br>tópico: ". $row["Nmateria"]."</p>"; } ?> <label class="Nimg">Se quiser escolha uma nova <br>imagem:</label> <label class="Nimgatual">Imagem atual:</label> <input type="file" required name="fimage" class="arquivo" onchange="showimage.call(this)"> <div id="foto"> <img src="imagens/foto.jpg" id="fimage" name="fimage" height="205px" width="196px"> <!-- Com o comando style="display:none" igual no exemplo abaixo o campo da imagem fica limpo sem --> <!-- <img src="imagens/foto.jpg" style="display:none" id="image" height="125px" width="116px"> --> </div> <script type="text/javascript"> function showimage() { if(this.files && this.files[0]) { var obj = new FileReader(); obj.onload = function(data){ var image = document.getElementById("fimage"); image.src = data.target.result; image.style.display = "block"; } obj.readAsDataURL(this.files[0]); } } function redirecionar(){ window.location="Atualizar.php"; } </script> <label class="lbsalvar"> Para atualizar a matéria <br>tecle o botão abaixo : </label> <input type="submit" name="Salvar" class="enviar" value="Atualizar" > <label class="lblimpar"> Para limpar o formulario <br>tecle no botão abaixo : </label> <input type="button" onclick="redirecionar()" class="Limpar" value="Limpar todos os campos"> </form> </body> </html><file_sep>/atualizainicial.php <!DOCTYPE html> <html> <head> <title></title> <meta charset="UTF-8"> <style> body{ background-color: #FFFAF0; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } #topo{background-color: #000000; width: 100%; height: 155px; } p.Ptopo{ text-decoration: none; color: #FF4500; font-style: italic; position: absolute; left: 3%; top: 2%; font-size: 36px; } body { margin:0px; padding:0px; } a.retorno{ text-decoration: none; color: #FF4500; position: absolute; left: 80%; top: 15%; font-size: 20px; } .tabela{ position:absolute; width: 30%; top: 36%; left: 47%; margin-left: 10px; margin-right: 10px; } label.lbcodigo{ position: absolute; left: 20%; top: 35%; margin-left: 10px; margin-right: 10px; } input.txtcodigo{ width: 80px; position: absolute; left: 20%; top: 41%; margin-left: 10px; margin-right: 10px; } label.lbsalvar{ position: absolute; left: 20%; top: 45%; margin-left: 10px; margin-right: 10px; } input.salvar{ width: 230px; position: absolute; left: 20%; top: 53%; margin-left: 10px; margin-right: 10px; } label.lbcodigoM{ position: absolute; left: 20%; top: 60%; margin-left: 10px; margin-right: 10px; } input.txtcodigoM{ width: 50px; position: absolute; left: 20%; top: 67%; margin-left: 10px; margin-right: 10px; } label.lbsalvarM{ position: absolute; left: 20%; top: 72%; margin-left: 10px; margin-right: 10px; } input.salvarM{ width: 230px; position: absolute; left: 20%; top: 80%; margin-left: 10px; margin-right: 10px; } </style> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJAS</p> <a href="paginaconfiguracao2.php" class="retorno">Voltar para tela anterior</a> </div> <!--<form method="POST" name="Salvar" action="atualizar.php" enctype="multipart/form-data"> <label class="lbcodigo">Escreva o codigo do cantor ou banda <br>do qual você deseja alterar</label> <input class="txtcodigo" type="text" required="" name="codigo"> <label class="lbsalvar"> Para fazer alguma alteração na banda <br>ou cantor(a) tecle o botão abaixo : </label> <input type="submit" name="Salvar" class="salvar" value="Alterar banda ou cantor(a)" > </form>--> <form method="POST" name="Salvar" action="atualizarM.php" enctype="multipart/form-data"> <label class="lbcodigo">Digite o codigo do cantor ou banda <br>que você deseja alterar alguma musica</label> <input class="txtcodigo" type="text" required="" name="codigo"> <label class="lbsalvar"> Para alterar alguma musica da banda <br>ou cantor(a) tecle o botão abaixo : </label> <input type="submit" name="Salvar" class="salvar" value="Alterar musica" > </form> <table border="1" class="tabela"> <tr> <td >Codigo da banda</td> <td>Nome da banda ou cantor(a)</td> </tr> <?php require_once "conexmusi.php"; $consulta = "SELECT idbanda, nomebanda FROM bandas"; $consultando = mysqli_query($con, $consulta); while($dado = mysqli_fetch_array($consultando)) { ?> <tr> <td width="200px"><?php echo $dado["idbanda"];?> </td> <td width="450px"><?php echo $dado["nomebanda"];?> </td> </tr> <?php } ?> </table> </body> </html> <!-- <form method="POST" name="Salvar" action="atualizarM.php" enctype="multipart/form-data"> <label class="lbcodigoM">Digite o codigo do cantor ou banda <br>que você deseja alterar alguma musica</label> <input class="txtcodigoM" type="text" required="" name="codigo"> <label class="lbsalvarM"> Para alterar alguma musica da banda <br>ou cantor(a) tecle o botão abaixo : </label> <input type="submit" name="Salvar" class="salvarM" value="Alterar musica" > </form>--><file_sep>/atualizarM.php <?php session_start(); require_once "conexmusi.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> body{ background-color: #FFFAF0; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } #topo{background-color: #000000; width: 100%; height: 110px; } p.Ptopo{ text-decoration: none; color: #FF4500; font-style: italic; position: absolute; left: 3%; top: 1%; font-size: 31px; } a.retorno{ text-decoration: none; color: #FF4500; position: absolute; left: 80%; top: 12%; font-size: 18px; } #Tprincipal { position: absolute; left: 68%; top: 31%; height: 37%; width: 24%; margin-left: 10px; margin-right: 10px; } p.Pbiografia { position:absolute; top: 24%; left: 68%; margin-left: 10px; margin-right: 10px; } p.NomeS { position:absolute; top: 17%; left: 32%; margin-left: 10px; margin-right: 10px; font-weight: bold; font-size: 26px; } p.codMus { position:absolute; top: 84%; left: 14%; margin-left: 10px; } input.txtcodigoM{ width: 80px; position: absolute; left: 22%; top: 90%; } #imagem{ position: absolute; left: 14%; top: 31%; border-color:#000000; border-style: solid; border-width: 1px; height: 52%; width: 23%; margin-left: 10px; margin-right: 10px; } .op{ position:absolute; left:52%; top:31%; margin-left: 10px; margin-right: 10px; } input.salvarM{ width: 310px; position: absolute; left: 15%; top: 94%; } table tr td { /* Toda a tabela com fundo creme */ background: #fff; overflow: hidden; border-collapse: collapse; text-align: center; } body { margin:0px; padding:0px; } </style> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJAS</p> <a href="atualizainicial.php" class="retorno">Voltar tela anterior</a> </div> <form method="POST" name="Salvar" action="AtualizarMusica.php"> <p class="codMus"> Digite o codigo da musica que você deseja alterar</p> <input class="txtcodigoM" type="text" required="" name="codigo"> <input type="submit" name="salvar1" class="salvarM" value="Alterar Musica" > </form> <table border="1" class="op"> <tr> <td width="150px">Codigo da Musicas </td> <td width="280px">Musicas da banda </td> </tr> <?php $id = $_POST['codigo']; $id2= $_POST['codigo']; $_SESSION['banda']=$id; if(isset($_POST['Salvar'])) { $query = "SELECT codmusica, nomemusica FROM musicas WHERE codbanda = $id2"; $consultando = mysqli_query($con, $query); while($dado = mysqli_fetch_array($consultando)) { $idmusica = $dado['codmusica']; $name = $dado['nomemusica']; ?> <tr> <td width="150px"><?php echo "$idmusica";?></td> <td width="280px"><?php echo "$name";?></td> </tr> <?php } }?> </table> <?php require_once "conexmusi.php"; $id = $_POST['codigo']; $_SESSION['GlobalBanda']=$id; $id2=$_SESSION["GlobalBanda"]; if(isset($_POST['Salvar'])) { $sql="SELECT musicas.nomemusica, musicas.letraMusica, bandas.nomebanda, bandas.fotobanda FROM musicas JOIN bandas ON bandas.idbanda = musicas.codbanda WHERE bandas.idbanda='$id2'"; $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_assoc($result)) { echo "<div id='imagem'>"; echo "<img src='cantores/" .$row['fotobanda']."' width='100%' height='100%'>"; echo "</div>"; echo "<p class='NomeS'>Nome da banda ou do cantor(a): ". $row["nomebanda"]."</p>"; } } else { echo "Erro!"; } ?> </body> </html> <file_sep>/AtualizarMusica.php <?php session_start(); require_once "conexmusi.php"; // chamando a primeira vez - carregando tela if(isset($_POST['codigo'])) { $id = $_POST['codigo']; $_SESSION['codigo'] = $_POST['codigo']; } // chamando 2 vez - salvando tela if (isset($_POST['salvar2'])) { $nome_musica = $_POST["exe1"]; $texto = $_POST["texto"]; $sql_cod = 'UPDATE musicas SET nomemusica = "'.$nome_musica.'", letraMusica = "'.$texto.'" WHERE codmusica = '.$_SESSION['codigo']; //var_dump($sql_cod); die; if(!$res=mysqli_query($con,$sql_cod)){ $msg = "Falha ao alterar."; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> body{ background-color: #FFFAF0; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } #topo{background-color: #000000; width: 100%; height: 110px; } p.Ptopo{ text-decoration: none; color: #FF4500; font-style: italic; position: absolute; left: 3%; top: 1%; font-size: 31px; } a.retorno{ text-decoration: none; color: #FF4500; position: absolute; left: 80%; top: 12%; font-size: 18px; } #Lmusica { position: absolute; left: 39%; top: 31%; height: 47%; width: 25%; margin-left: 10px; margin-right: 10px; } #Lmusica2 { position: absolute; left: 69%; top: 31%; height: 47%; width: 25%; margin-left: 10px; margin-right: 10px; } p.SiteB { position:absolute; top: 22%; left: 39%; margin-left: 10px; margin-right: 10px; font-weight: bold; } p.Nletra { position:absolute; top: 22%; left: 69%; margin-left: 10px; margin-right: 10px; font-weight: bold; } p.NomeS { position:absolute; top: 22%; left: 6%; margin-left: 10px; margin-right: 10px; font-weight: bold; } p.Nnome { position:absolute; top: 78%; left: 6%;; margin-left: 10px; margin-right: 10px; font-weight: bold; } input.NomeNovo { position:absolute; top: 88%; width: 374px; left: 6%; margin-left: 10px; margin-right: 10px; } input.Atualizar { position:absolute; top: 88%; width: 342px; left: 39%; margin-left: 10px; margin-right: 10px; } #imagem{ position: absolute; left: 7%; top: 31%; border-color:#000000; border-style: solid; border-width: 1px; height: 47%; width: 27%; } body { margin:0px; padding:0px; } </style> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJAS</p> <?php $id = $_GET['id']; echo "<a href='atualizainicial.php?id=$id' class='retorno'>Voltar tela de anterior</a>";?> </div> <p class="Nnome">Se quiser mudar o nome da musica escreva o novo <br>nome abaixo</p> <p class="Nletra">Se quiser mudar a letra da musica escreva a nova <br>letra abaixo</p> <form method="POST" name="Salvar2" action="AtualizarMusica.php"> <input type="text" class="NomeNovo" name="exe1"> <textarea cols="40" rows="54" id="Lmusica2" name="texto"></textarea> <input type="submit" class="Atualizar" name="salvar2" value="Atualizar"> </form> <?php $id=$_SESSION["GlobalBanda"]; $sql="SELECT musicas.nomemusica, musicas.letraMusica, bandas.nomebanda, bandas.fotobanda FROM musicas join bandas on bandas.idbanda = musicas.codbanda WHERE bandas.idbanda='$id'"; $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_assoc($result)) { echo "<div id='imagem'>"; echo "<img src='cantores/" .$row['fotobanda']."' width='100%' height='100%'>"; echo "</div>"; echo "<textarea cols=60 rows=29 id='Lmusica'>". $row["letraMusica"]."</textarea>"; echo "<p class='NomeS'>Nome da banda ou do cantor(a): ". $row["nomebanda"]."</p>"; echo "<p class='SiteB'>Nome atual da música: ". $row["nomemusica"]."</p>"; } ?> </body> </html><file_sep>/curtidas.php <?php require_once "conexmusi.php"; if (isset($_POST['Salvar'])){ $comentario= $_POST["salvarcomentario"]; $nomeusuario= $_POST["usuario"]; $sql_cod = "INSERT INTO comentario (CodComentario, NomeUsuario, Comentario) VALUES(null, '$nomeusuario', '$comentario')"; if($res=mysqli_query($con,$sql_cod)){ $msg = "Arquivo enviado com sucesso!"; header('Location: curtidas.php'); } else{ $msg = "Falha ao enviar arquivo."; } } ?> <style> body{ background-color: #FFFAF0; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } #topo{ position: fixed; top: 0px; z-index: 3; background-color: #000000; width: 100%; height: 110px; } p.Ptopo{ text-decoration: none; color: #FF4500; font-style: italic; position: absolute; left: 3%; top: 1%; font-size: 31px; } input.nome{ position:absolute; top: 45%; left: 21%; width: 270px; margin-left: -250px; margin-right: 10px; } input.btcomentar{ position:absolute; top: 50%; left: 21%; width: 270px; margin-left: -250px; margin-right: 10px; } textarea.txtcomentario{ position:absolute; top: 33%; left: 2%; margin-left: 10px; margin-right: 10px; } textarea.coment{ margin-top: 5px; } #idcoment{ position:absolute; top: 400px; left: 2%; margin-left: 10px; margin-right: 10px; } p.lbcomentario{ position:absolute; top: 23%; left: 2%; margin-left: 10px; margin-right: 10px; } p.lbnome{ position:absolute; top: 39%; left: 2%; margin-left: 10px; margin-right: 10px; } p.Ncomentario{ margin-top: 5px; } #comentarios{ top: 105px; position: relative; width: 270px; left: 37px; z-index: 2 } #principal{ top: 230px; left: -2px; position: relative; z-index: 1; } p.sorteio{ position:absolute; top: 24%; left: 77%; margin-left: 10px; margin-right: 10px; } p.NomeS{ position:absolute; top: 59%; left: 2%; margin-left: 10px; margin-right: 10px; } p.opinioes{ position:absolute; top: 47%; left: 77%; margin-left: 10px; margin-right: 10px; } a.retorno{ text-decoration: none; color: #FF4500; position: absolute; left: 80%; top: 12%; font-size: 18px; } textarea.coment{ margin-left: 5px; margin-bottom: 9px; max-height: 1000px; } .op{ position:absolute; left:30%; top:26%; } table tr td { /* Toda a tabela com fundo creme */ background: #fff; overflow: hidden; border-collapse: collapse; text-align: center; } body { margin:0px; padding:0px; } </style> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJAS</p> <a href="index.php" class="retorno">Voltar tela anterior</a> </div> <div> <table border="1" class="op"> <tr> <td width="100px">Colocação </td> <td width="300px">Nome da Banda </td> <td width="200px">Quantidade de curtidas </td> </tr> <?php require_once "conexmusi.php"; session_start(); $contador = 0; $query = "SELECT COUNT(c.CodBanda) AS 'Quantidade de curtidas', b.nomebanda AS 'Nomes das bandas' FROM curtidas c JOIN bandas b ON b.idbanda = c.codBanda GROUP by c.CodBanda ORDER BY COUNT(c.CodBanda) DESC"; $consultando = mysqli_query($con, $query); while($dado = mysqli_fetch_array($consultando)) { $cont = $dado['Quantidade de curtidas']; $name = $dado['Nomes das bandas']; $contador = $contador + 1; ?> <tr> <td width="100px"><?php echo "$contador";?>º</td> <td width="300px"><?php echo "$name<br/>";?></td> <td width="200px"><?php echo "$cont<br/>";?></td> </tr> <?php } ?> </table> </div> <div> <p class="lbcomentario">Deixe abaixo o seu comentario sobre <br>a banda se você quiser.</p> <p class="lbnome">Informe o seu nome abaixo:</p> <p class="sorteio">Para participar de sorteios de ingressos para ir em shows da sua banda predileta envie um e-mail para o <EMAIL>, deixando o seu whatssap e de um amigo seu e fale o nome da banda que você deseja assistir um show ao vivo.</p> <p class="opinioes">Sugestões, criticas e opiniões mande um e-mail para <EMAIL></p> <form action="curtidas.php" method="POST"> <textarea name="salvarcomentario" rows="3" cols="35" class="txtcomentario" required="" placeholder="Deixe o seu comentario sobre alguma banda"></textarea> <input type="text" name="usuario" required="" class="nome" > <input type="submit" class="btcomentar" required="" value="Comentar" name="Salvar"> </form> <?php require_once "conexmusi.php"; $sql = "SELECT NomeUsuario, Comentario FROM comentario"; $result = mysqli_query($con, $sql); while($row = mysqli_fetch_array($result)){ ?> <div id="principal"> <div id="comentarios"> <?php echo "<p class='Ncomentario'>Comentario do : ". $row["NomeUsuario"]."</p>"; echo "<textarea class='coment' cols=34 rows=4 >". $row["Comentario"]."</textarea><br>";?> </div> </div><?php } ?> </div> </body> </html><file_sep>/index.php <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> body{ background: url(img/fundo7.jpg); background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; margin:0px; padding:0px; /* height: auto; width: 100%; background-size:100%; background-repeat: no-repeat; Esse codigo que está comentado era para deixar a imagem responsiva só que teu certo nãom */ } #topo{ width: 100%; height: 110px; } p.Ptopo{ text-decoration: none; color: #000; font-style: italic; position: absolute; font-weight: bold; left: 3%; top: -1%; font-size: 30px; } a.retorno{ text-decoration: none; color: #000; font-weight: bold; position: absolute; left: 80%; top: 8%; font-size: 19px; } a.retorno2{ text-decoration: none; color: #000; font-weight: bold; position: absolute; left: 64%; top: 8%; font-size: 19px; } .op{ position:absolute; left:35%; top:25%; } table tr td { /* Toda a tabela com fundo creme */ background: #ffc; overflow: hidden; border-collapse: collapse; text-align: center; } .config{ color: #ffffff; position:absolute; text-decoration:none; left:50%; top:95%; } </style> <title></title> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJOS</p> <a href="curtidas.php" class="retorno2">Bandas mais curtidas</a> <a href="paginaconfiguracao2.php" class="retorno">Pagina Configurações</a> </div> <table border="1" class="op"> <tr> <td width="450px">Nome da Banda </td> </tr> <?php require_once "conexmusi.php"; session_start(); $query = "SELECT idbanda, nomebanda FROM bandas order by nomebanda"; $consultando = mysqli_query($con, $query); while($dado = mysqli_fetch_array($consultando)) { $id = $dado['idbanda']; $name = $dado['nomebanda']; ?> <tr> <td width="450px"><?php echo "<a href='paginabandas.php?id=$id'>$name</a><br/>";?></td> </tr> <?php } ?> </table> </body> </html><file_sep>/letrasmusicas.php <style> body{ background-color: #FFFAF0; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } #topo{background-color: #000000; width: 100%; height: 110px; } p.Ptopo{ text-decoration: none; color: #FF4500; font-style: italic; position: absolute; left: 3%; top: 1%; font-size: 31px; } a.retorno{ text-decoration: none; color: #FF4500; position: absolute; left: 80%; top: 12%; font-size: 18px; } #Lmusica { position: absolute; left: 55%; top: 38%; height: 54%; width: 30%; margin-left: 10px; margin-right: 10px; } p.SiteB { position:absolute; top: 28%; left: 62%; margin-left: 10px; margin-right: 10px; font-weight: bold; } p.NomeS { position:absolute; top: 28%; left: 17%; margin-left: 10px; margin-right: 10px; font-weight: bold; } #imagem{ position: absolute; left: 16%; top: 38%; border-color:#000000; border-style: solid; border-width: 1px; height: 54%; width: 30%; } body { margin:0px; padding:0px; } </style> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJAS</p> <a href="paginabandas.php" class='retorno'>Voltar tela de anterior</a> </div> <?php require_once "conexmusi.php"; if(isset($_GET['id'])) { $id = $_GET['id']; $sql="SELECT musicas.nomemusica, musicas.letraMusica, bandas.nomebanda, bandas.fotobanda FROM musicas inner join bandas on bandas.idbanda = musicas.codbanda WHERE codmusica='$id'"; $result = mysqli_query($con, $sql); while ($row = mysqli_fetch_assoc($result)) { echo "<div id='imagem'>"; echo "<img src='cantores/" .$row['fotobanda']."' width='100%' height='100%'>"; echo "</div>"; echo "<textarea cols=60 rows=29 id='Lmusica'>". $row["letraMusica"]."</textarea>"; echo "<p class='NomeS'>Nome da banda ou do cantor(a): ". $row["nomebanda"]."</p>"; echo "<p class='SiteB'>Nome da música: ". $row["nomemusica"]."</p>"; } } else { echo "Erro!"; } ?> </body> </html><file_sep>/configuracoesmusicas.php <?php require_once "conexmusi.php"; if (isset($_POST['Salvar'])){ $CodBanda = $_POST["codbanda"]; $NomeMusica = $_POST["Nmusica"]; $LetraMusica = $_POST["Lmusica"]; $sql_cod = "INSERT INTO musicas (codmusica, codbanda, nomemusica, letraMusica) VALUES(null, '$CodBanda', '$NomeMusica', '$LetraMusica')"; if($res=mysqli_query($con,$sql_cod)){ $msg = "Arquivo enviado com sucesso!"; header('Location: configuracoesmusicas.php'); } else{ $msg = "Falha ao enviar arquivo."; } } ?> <!DOCTYPE html> <html> <head> <title></title> <meta charset="UTF-8"> <style> body{ background-color: #FFFAF0; background-position: center center; background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } #topo{background-color: #000000; width: 100%; height: 155px; } p.Ptopo{ text-decoration: none; color: #FF4500; font-style: italic; position: absolute; left: 3%; top: 2%; font-size: 36px; } body { margin:0px; padding:0px; } a.retorno{ text-decoration: none; color: #FF4500; position: absolute; left: 80%; top: 15%; font-size: 20px; } label.lblmusica{ position: absolute; left: 70%; top: 36%; margin-left: 10px; margin-right: 10px; } #txtletraM{ position:absolute; width: 20%; top: 40%; height: 300px; left: 70%; margin-left: 10px; margin-right: 10px; } .tabela{ position:absolute; width: 30%; top: 36%; left: 31%; margin-left: 10px; margin-right: 10px; } label.lbNmusica{ position: absolute; left: 9%; top: 36%; margin-left: 10px; margin-right: 10px; } input.txtNmusica{ position: absolute; left: 9%; top: 44%; margin-left: 10px; margin-right: 10px; } label.lbcodigo{ position: absolute; left: 9%; top: 50%; margin-left: 10px; margin-right: 10px; } input.txtcodigo{ width: 50px; position: absolute; left: 14%; top: 56%; margin-left: 10px; margin-right: 10px; } label.lbsalvar{ width: 175px; position: absolute; left: 9%; top: 62%; margin-left: 10px; margin-right: 10px; } input.salvar{ width: 175px; position: absolute; left: 9%; top: 69%; margin-left: 10px; margin-right: 10px; } </style> </head> <body> <div id="topo"> <p class="Ptopo"> REPOSITORIO DE BANDAS E CANTORES SERTANEJAS</p> <a href="paginaconfiguracao2.php" class="retorno">Voltar para tela anterior</a> </div> <form method="POST" name="Salvar" action="configuracoesmusicas.php" enctype="multipart/form-data"> <label class="lblmusica">Insira abaixo a letra da musica </label> <textarea id="txtletraM" name="Lmusica" required="" placeholder="Insira a letra da musica:"></textarea> <label class="lbNmusica">Escreva abaixo o nome da musica<br> que você deseja salvar: </label> <input class="txtNmusica" type="text" required="" name="Nmusica"> <label class="lbcodigo">Escreva o codigo do cantor ou banda <br>do qual é a musica que você está<br> salvando: </label> <input class="txtcodigo" type="text" required="" name="codbanda"> <label class="lbsalvar"> Para salvar a matéria tecle o botão abaixo : </label> <input type="submit" name="Salvar" class="salvar" value="Cadastrar" > </form> <table border="1" class="tabela"> <tr> <td >Codigo da música </td> <td>Nome da música</td> </tr> <?php require_once "conexmusi.php"; $consulta = "SELECT idbanda, nomebanda FROM bandas"; $consultando = mysqli_query($con, $consulta); while($dado = mysqli_fetch_array($consultando)) { ?> <tr> <td width="200px"><?php echo $dado["idbanda"];?> </td> <td width="450px"><?php echo $dado["nomebanda"];?> </td> </tr> <?php } ?> </table> </body> </html>
d54f5c1cd834a952aee5bbab48fdb180008e2901
[ "PHP" ]
11
PHP
marcelobh864/repMusicasSertanejas
30473d8e089c7a548b35915ae541e7bbeed327ae
9ee722b509fce34bf35c3783c6d79ae47517c4ab
refs/heads/master
<repo_name>norsem4n/CSharpDemo15<file_sep>/CKarnasProgram16/Charter.cs /* Project: Homework 7 - Assignment Set 16 * Date: December 2020 * Last Modified: 12.11.2020 * Developed By: CGK * Class Name: Charter * Purpose: Showcases price and accommodations for different yacht charters */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CKarnasProgram16 { class Charter { #region"Properties" //5 instance properties (auto-implemented – public get and private set) public decimal CharterFee { get; private set; } public decimal CharterHours { get; private set; } public string CustomerName { get; private set; } public int YachtSize { get; private set; } public string YachtTypes { get; private set; } #endregion #region"Constructors" //instantiates object and set its customer name, yacht type, yacht size, and hours chartered using parameters //calls a private method (see below) to set the charter fee. public Charter(string customerName, string yachtType, int yachtSize, decimal hoursChartered) { CustomerName = customerName; CharterHours = hoursChartered; YachtSize = yachtSize; YachtTypes = yachtType; CharterFee = CalculateCharterFee(); } #endregion #region"Methods" //a private method to calculate and return the charter fee based on the rate table private decimal CalculateCharterFee() { decimal charterFee = 0; switch(YachtSize) { case 22: charterFee = 208 * CharterHours; break; case 24: charterFee = 283 * CharterHours; break; case 30: charterFee = 305 * CharterHours; break; case 32: charterFee = 397 * CharterHours; break; case 36: charterFee = 495 * CharterHours; break; case 38: charterFee = 546 * CharterHours; break; case 45: charterFee = 675 * CharterHours; break; } return charterFee; } #endregion } } <file_sep>/CKarnasProgram16/Form1.cs /* Project: Homework 7 - Assignment Set 16 * Date: December 2020 * Last Modified: 12.11.2020 * Developed By: CGK * Class Name: Form */ 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; using System.Globalization; namespace CKarnasProgram16 { public partial class Form1 : Form { public Form1() { InitializeComponent(); allChartersToolStripMenuItem.Enabled = false; numberOfChartersForYachtSIzeToolStripMenuItem.Enabled = false; chartersSummaryToolStripMenuItem.Enabled = false; exitToolStripMenuItem.Enabled = true; txtCustomer.Focus(); } //declare a class level variable for CharterManager private CharterManager aCharterManager; private void Module8Ex2_Load(object sender, EventArgs e) { //cboYachtType.SelectedIndex = -1; } private void btnAddCharter_Click(object sender, EventArgs e) { //validate customer name input data if (txtCustomer.Text == string.Empty) { MessageBox.Show("Enter Customer Name", "Missing Input", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //vaidate yacht type input data if (cboYachtType.SelectedItem == null) { MessageBox.Show("Select a yacht type", "Missing input", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //validate yacht size input data if (lboxYachtSize.SelectedItem == null) { MessageBox.Show("Select a yacht size", "Missing input", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //declare method level variables and assign values string customerName = txtCustomer.Text; string yachtType = cboYachtType.SelectedItem.ToString(); int yachtSize = Convert.ToInt32(lboxYachtSize.SelectedItem); decimal hoursChartered = Convert.ToDecimal(nudHours.Value); Charter aCharter = new Charter(customerName, yachtType, yachtSize, hoursChartered); //instantiates a YatchManager object(one time only; when the first charter is added) if (aCharterManager == null) { aCharterManager = new CharterManager(); } //calls the appropriate method on the YachtManager object to add the charter aCharterManager.AddCharter(customerName, yachtType, yachtSize, hoursChartered); //enables the three menu items within the Display menu allChartersToolStripMenuItem.Enabled = true; numberOfChartersForYachtSIzeToolStripMenuItem.Enabled = true; chartersSummaryToolStripMenuItem.Enabled = true; //disables tools btnAddCharter.Enabled = false; txtCustomer.Enabled = false; nudHours.Enabled = false; lboxYachtSize.Enabled = false; cboYachtType.Text = null; } private void allChartersToolStripMenuItem_Click(object sender, EventArgs e) { //display all charters Form3 aForm = new Form3(); aForm.charterManagerBindingSource.DataSource = aCharterManager; aForm.ShowDialog(); } private void numberOfChartersForYachtSIzeToolStripMenuItem_Click(object sender, EventArgs e) { //error message if size not selected if (lboxYachtSize.SelectedIndex == -1) { MessageBox.Show("Select a yacht size", "Missing input", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //once selected, give the number of charters in a message box int charterCount; charterCount = aCharterManager.GetCharterCount(Convert.ToInt32(lboxYachtSize.SelectedItem)); MessageBox.Show($"The number of charters for the {lboxYachtSize.SelectedItem} foot sized Yacht is {charterCount}", "Yacht Size Total Charters", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void chartersSummaryToolStripMenuItem_Click(object sender, EventArgs e) { Form4 aForm = new Form4(); //display lowest charter fee aForm.lblLowestFeeDisplay.Text = aCharterManager.FindLowestCharterFee().ToString("c"); //the total fees from all charters aForm.lblTotalFeeDisplay.Text = aCharterManager.GetTotalCharterFees().ToString("c"); //and the average fee of all the charters aForm.lblAvgFeeDisplay.Text = aCharterManager.GetAvgCharterFee().ToString("c"); aForm.charterManagerBindingSource.DataSource = aCharterManager; aForm.ShowDialog(); } private void addYachtTypeToolStripMenuItem_Click(object sender, EventArgs e) { if (cboYachtType.Text == string.Empty) { MessageBox.Show("Enter a new yacht type", "Missing input", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string newMember = cboYachtType.Text; //assign the new member to be added to a variable bool duplicate = false; // duplication indicator //a foreach loop to iterate through the items in the list and check for potential duplication foreach (string aItem in cboYachtType.Items) //for each item in the combo box { if (string.Equals(newMember, aItem, StringComparison.OrdinalIgnoreCase)) //ignoring case, compare each member in the list to the member to be added { duplicate = true; //if the member already exists in the list, set duplication indicator to true break; //break out of the loop } } if (duplicate) //if duplicate is true, new member is not added { MessageBox.Show("Yacht type already exits", "Well, this is awkward...", MessageBoxButtons.OK, MessageBoxIcon.Information); cboYachtType.Text = string.Empty; } else //otherwise, new member is added { TextInfo aTextInfo = new CultureInfo("en-US", false).TextInfo; //create a TextInfo object based on "en-US" culture newMember = aTextInfo.ToTitleCase(newMember); //change the name of the new member to be added to proper case cboYachtType.Items.Add(newMember); //add the new member to the list MessageBox.Show("New yacht type added", "Confirmed", MessageBoxButtons.OK, MessageBoxIcon.Information); cboYachtType.Text = string.Empty; } } private void removeYachtTypeToolStripMenuItem_Click(object sender, EventArgs e) { // validate yacht type input if (cboYachtType.Text == string.Empty) { MessageBox.Show("Enter a yacht type to remove", "Missing Input", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { cboYachtType.Items.RemoveAt(cboYachtType.SelectedIndex); //remove selected member from list MessageBox.Show("Yacht has been removed", "Confirmed", MessageBoxButtons.OK, MessageBoxIcon.Information); cboYachtType.Text = string.Empty; } } private void resetForNextCharterToolStripMenuItem_Click(object sender, EventArgs e) { //reset input controls txtCustomer.Clear(); btnAddCharter.Enabled = true; txtCustomer.Enabled = true; nudHours.Enabled = true; lboxYachtSize.Enabled = true; nudHours.Value = nudHours.Minimum; cboYachtType.SelectedIndex = -1; lboxYachtSize.SelectedIndex = -1; txtCustomer.Focus(); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } } } <file_sep>/CKarnasProgram16/CharterManager.cs /* Project: Homework 7 - Assignment Set 16 * Date: December 2020 * Last Modified: 12.11.2020 * Developed By: CGK * Class Name: CharterManager * Purpose: Manages selection criteria for Yacht Charters */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Globalization; namespace CKarnasProgram16 { class CharterManager { #region"Properties" //instance property (auto-implemented – public get and private set) public List<Charter> CharterList { get; private set; } #endregion #region"Constructors" //instantiates object and instantiates the List<Charter> collection public CharterManager() { CharterList = new List<Charter>(); } #endregion #region"Methods" //a method to a) instantiate a Charter object and add it to the List <Charter> collection public void AddCharter(string customerName, string yachtType, int yachtSize, decimal hoursChartered) { Charter aCharter = new Charter(customerName, yachtType, yachtSize, hoursChartered); CharterList.Add(aCharter); } //a method to find and return the lowest charter fee among all the charters public decimal FindLowestCharterFee() { // using LINQ (Method Syntax) //var lowest = CharterList.Min(f => f.CharterFee); //return lowest; decimal currentLowest = CharterList[0].CharterFee; foreach (Charter aCharter in CharterList) { if (aCharter.CharterFee < currentLowest) { currentLowest = aCharter.CharterFee; } } return currentLowest; } //a method to sum up and return the total fees from all the charters // using LINQ (Method Syntax) public decimal GetTotalCharterFees() { // using LINQ (Method Syntax) //decimal total = CharterList.Sum(f => f.CharterFee); //return total; decimal total = 0; foreach (Charter aCharter in CharterList) { total += aCharter.CharterFee; } return total; } //a method to calculate and return the average charter fee public decimal GetAvgCharterFee() { //using LINQ (Method Syntax) var average = CharterList.Average(f => f.CharterFee); return average; } //a method to count and return the number of charters for a specific yacht size public int GetCharterCount(int yachtSize) { //return CharterList.Count; //GetLength for an array int count = 0; foreach (Charter aCharter in CharterList) { if (aCharter.YachtSize == yachtSize) { ++count; } } return count; // using LINQ (Query syntax) //int count = (from aFood in FoodList // where aFood.FoodType == aGroup // select aFood).Count(); //return count; // using LINQ (Method Syntax) //int count = CharterList.Count(f => f.YachtSize == yachtSize); //return count; } #endregion } }
49fc5013e0f7e56410a4c9bacdd8cc1335250462
[ "C#" ]
3
C#
norsem4n/CSharpDemo15
f901064b06439e9a6a308d7c2f1c430e30486711
57fc97e19b334ca4e1b2fdd51245117440f416de
refs/heads/master
<file_sep> #define _CRT_SECURE_NO_WARNINGS #define _WINSOCK_DEPRECATED_NO_WARNINGS #define Q_SIZE 1000000 #define PKT_SIZE 1000 #define ALPHA 0.125 #define UPDATE_AVGRTT(x) (avgRTT = (1-ALPHA)*avgRTT + ALPHA*(x)) // sec #define ELAPSED_TIME(s,f) ((double)(f) - (s))/1000 #include <stdio.h> #include <stdlib.h> #include <winsock2.h> #include <process.h> #include <Windows.h> #include <string.h> #include <time.h> #pragma comment(lib, "ws2_32.lib") typedef clock_t data; // ms /*함수 선언*/ typedef struct queue { int head; int tail; int cnt; data ar[Q_SIZE]; }QUEUE; void enqueue(QUEUE *q, data x); data dequeue(QUEUE *q); int queue_empty(QUEUE* q); int queue_full(QUEUE* q); UINT WINAPI recThread_func(void* para); UINT WINAPI printThread_func(void* para); void incr_acksnum(); void half_sendingrate(); void incr_sendingrate(); void error_handle(char* message); BOOL try_connect(); /*변수 선언*/ HANDLE recThread, printThread; UINT recThreadID, printThreadID; WSADATA wsa_data; SOCKET sock; SOCKADDR_IN send_addr; // 공유 메모리 CRITICAL_SECTION cs_ack, cs_nack, cs_sdrate, cs_avrtt, cs_que; int acks_num; double sending_rate; // sec double avgRTT; QUEUE que; int nack_num; BOOL is_first_rtt = TRUE; int main(void) { que.cnt = 0; que.head = 0; que.tail = 0; InitializeCriticalSection(&cs_nack); // cs 생성 InitializeCriticalSection(&cs_ack); // cs 생성 InitializeCriticalSection(&cs_sdrate); // cs 생성 InitializeCriticalSection(&cs_avrtt); // cs 생성 InitializeCriticalSection(&cs_que); // cs 생성 printf("Input initial_sending_rate >>"); scanf("%lf", &sending_rate); // 소켓 라이브러리 초기화 if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0) error_handle("WSAStartup() errer!"); // 소켓 생성 sock = socket(PF_INET, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) error_handle("socket() error!"); memset(&send_addr, 0, sizeof(send_addr)); send_addr.sin_family = AF_INET; send_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); send_addr.sin_port = htons(12000); // UDP Connection if (!try_connect()) { printf("Receiver가 접속해 있지 않습니다. Receiver를 먼저 접속시켜주세요!\n"); return 0; } recThread = (HANDLE)_beginthreadex(NULL, 0, recThread_func, 0, 0, &recThreadID); printThread = (HANDLE)_beginthreadex(NULL, 0, printThread_func, 0, 0, &printThreadID); // print Thread /* send 메인 스레드*/ while (1) { int retval; clock_t _timer = clock(); while (ELAPSED_TIME(_timer, clock()) < (1/sending_rate)); // minimum RTT 동안 지연한다 char send_buf[PKT_SIZE + 1] = "."; enqueue(&que, clock()); retval = sendto(sock, send_buf, PKT_SIZE, 0, (SOCKADDR*)&send_addr, sizeof(send_addr)); // 패킷 전송 if (retval == SOCKET_ERROR) continue; } CloseHandle(recThread); CloseHandle(printThread); closesocket(sock); WSACleanup(); DeleteCriticalSection(&cs_nack); // cs 제거 DeleteCriticalSection(&cs_avrtt); // cs 제거 DeleteCriticalSection(&cs_ack); // cs 제거 DeleteCriticalSection(&cs_sdrate); // cs 제거 DeleteCriticalSection(&cs_que); // cs 제거 return 0; } void error_handle(char* message) { fputs(message, stderr); fputc('\n', stderr); exit(1); } void incr_sendingrate() { EnterCriticalSection(&cs_sdrate); // lock 획득 혹은 waiting sending_rate = sending_rate + 1.0/ sending_rate; LeaveCriticalSection(&cs_sdrate); // lock 반환 } void half_sendingrate() { EnterCriticalSection(&cs_sdrate); // lock 획득 혹은 waiting sending_rate = sending_rate / 2.0; LeaveCriticalSection(&cs_sdrate); // lock 반환 } void incr_nacknum() { EnterCriticalSection(&cs_nack); // lock 획득 혹은 waiting nack_num++; LeaveCriticalSection(&cs_nack); // lock 반환 } void incr_acksnum() { EnterCriticalSection(&cs_ack); // lock 획득 혹은 waiting acks_num++; LeaveCriticalSection(&cs_ack); // lock 반환 } int queue_full(QUEUE* q) { EnterCriticalSection(&cs_que); // lock 획득 혹은 waiting int ret = ((q->head + 1) % Q_SIZE == q->tail); LeaveCriticalSection(&cs_que); // lock 반환 return ret; } /* queue_empty( QUEUE) This function check whether the queue is empty. */ int queue_empty(QUEUE* q) { EnterCriticalSection(&cs_que); // lock 획득 혹은 waiting int ret = (q->head == q->tail); LeaveCriticalSection(&cs_que); // lock 반환 return ret; } /* enqueue( QUEUE *, int) insert a data into the queue */ void enqueue(QUEUE *q, data x) { EnterCriticalSection(&cs_que); // lock 획득 혹은 waiting if ((q->head + 1) % Q_SIZE == q->tail) { printf("the queue is full!\n"); return; } q->head = (q->head + 1) % Q_SIZE; q->ar[q->head] = x; q->cnt++; LeaveCriticalSection(&cs_que); // lock 반환 } data dequeue(QUEUE *q) { EnterCriticalSection(&cs_que); // lock 획득 혹은 waiting data ret; if (q->head == q->tail) { printf("the queue is empty!\n"); return 0; } q->tail = (q->tail + 1) % Q_SIZE; ret = q->ar[q->tail]; q->cnt--; LeaveCriticalSection(&cs_que); // lock 반환 return ret; } /* print 스레드 */ UINT WINAPI printThread_func(void* para) { clock_t _init, _start; _init = clock(); _start = clock(); while (1) { if (ELAPSED_TIME(_start, clock()) >= 2.0) { double good_put; double elapsed = ELAPSED_TIME(_init, clock()); EnterCriticalSection(&cs_nack); // lock 획득 혹은 waiting if (nack_num > 0) { half_sendingrate(); nack_num = 0; } LeaveCriticalSection(&cs_nack); // lock 반환 EnterCriticalSection(&cs_avrtt); // lock 획득 혹은 waiting printf("\n[%lf]Average RTT : %lf\n", elapsed, avgRTT); LeaveCriticalSection(&cs_avrtt); // lock 반환 EnterCriticalSection(&cs_sdrate); // lock 획득 혹은 waiting printf("[%lf]Sedning Rate : %lf pps\n", elapsed, sending_rate); LeaveCriticalSection(&cs_sdrate); // lock 반환 EnterCriticalSection(&cs_ack); // lock 획득 혹은 waiting good_put = acks_num / 2.0; // data 접근 코드 acks_num = 0; LeaveCriticalSection(&cs_ack); // lock 반환 printf("[%lf]Goodput : %lf pps\n\n", elapsed, good_put); _start = clock(); } } } /* recevie 스레드*/ UINT WINAPI recThread_func(void* para) { SOCKADDR_IN peer_addr; char rcv_buf[PKT_SIZE+1]; int retval; while (1) { int addrlen = sizeof(peer_addr); retval = recvfrom(sock, rcv_buf, PKT_SIZE, 0, (SOCKADDR*)&peer_addr, &addrlen); if (retval == SOCKET_ERROR) continue; // 다른 ip로부터 패킷 수신 if (memcmp(&peer_addr, &send_addr, sizeof(peer_addr))) continue; rcv_buf[retval] = '\0'; if (!strcmp(rcv_buf, "ACK")) { incr_sendingrate(); // 1.sending_rate를 증가시킨다 double sample_rtt = ELAPSED_TIME(dequeue(&que), clock()); if (is_first_rtt) { EnterCriticalSection(&cs_avrtt); // lock 획득 혹은 waiting avgRTT = sample_rtt; LeaveCriticalSection(&cs_avrtt); // lock 반환 is_first_rtt = FALSE; } else { EnterCriticalSection(&cs_avrtt); UPDATE_AVGRTT(sample_rtt); // 2. avg_RTT 업데이트 LeaveCriticalSection(&cs_avrtt); } incr_acksnum(); // 3. 2초 동안의 acks_num 증가 } else if (!strcmp(rcv_buf, "NACK")) { dequeue(&que); incr_nacknum(); } } } BOOL try_connect() { char send_buf[PKT_SIZE+1], rcv_buf[PKT_SIZE+1]; int retval, addrlen; strcpy(send_buf, "connect"); retval = sendto(sock, send_buf, (int)strlen(send_buf), 0, (SOCKADDR*)&send_addr, sizeof(send_addr)); if (retval == SOCKET_ERROR) return FALSE; addrlen = sizeof(send_addr); retval = recvfrom(sock, rcv_buf, PKT_SIZE, 0, (SOCKADDR*)&send_addr, &addrlen); if (retval == SOCKET_ERROR) return FALSE; rcv_buf[retval] = '\0'; if (!strcmp(rcv_buf, "accept")) return TRUE; else return FALSE; } <file_sep> #define _CRT_SECURE_NO_WARNINGS #define _WINSOCK_DEPRECATED_NO_WARNINGS #define PKT_SIZE 1000 #define TRUE 1 #define FALSE 0 #define ELAPSED_TIME(s,f) ((double)(f) - (s))/1000 #include <stdio.h> #include <stdlib.h> #include <winsock2.h> #include <process.h> #include <Windows.h> #include <string.h> #include <time.h> #pragma comment(lib, "ws2_32.lib") typedef SOCKADDR_IN data; // ms typedef int bool; typedef struct queue { int head; int tail; int cnt; data* ar; }QUEUE; /*함수 선언*/ UINT WINAPI connectThread_func(void* para); void error_handle(char* message); void enqueue(QUEUE *q, data x); data dequeue(QUEUE *q); int queue_empty(QUEUE* q); int queue_full(QUEUE* q); int get_qcnt(QUEUE *q); UINT WINAPI printThread_func(void* para); UINT WINAPI emulThread_func(void* para); void incr_ack_num(); /*변수 선언*/ HANDLE connectThread, emulThread, printThread; UINT connectThreadID, emulThreadID, printThreadID; WSADATA wsa_data; SOCKET sock, sock2; SOCKADDR_IN send_addr, send_addr2; // 공유 메모리 CRITICAL_SECTION cs_ack, cs_que; int acks_num; QUEUE que; double bottleneck_rate, minimum_rtt, half_minrtt; // sec int pps, bottolneck_qsize; int main(void) { int pps; que.cnt = 0; que.head = 0; que.tail = 0; InitializeCriticalSection(&cs_ack); // cs 생성 InitializeCriticalSection(&cs_que); // cs 생성 printf("Input minimum_RTT >>"); scanf("%lf", &minimum_rtt); half_minrtt = minimum_rtt/2; printf("Input bottleneck_link_rate >>"); scanf("%d", &pps); bottleneck_rate = (double)pps; printf("Input bottleneck_queue_size >>"); scanf("%d", &bottolneck_qsize); if (bottolneck_qsize == 1) bottolneck_qsize = 2; que.ar = (data*)malloc(bottolneck_qsize * sizeof(data)); // 큐 사이즈 결정 // 소켓 라이브러리 초기화 if (WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0) error_handle("WSAStartup() error!"); // 소켓 생성 sock = socket(PF_INET, SOCK_DGRAM, 0); sock2 = socket(PF_INET, SOCK_DGRAM, 0); if (sock == INVALID_SOCKET) error_handle("socket() error!"); // 어드레스 설정 memset(&send_addr, 0, sizeof(send_addr)); send_addr.sin_family = AF_INET; send_addr.sin_addr.s_addr = htonl(INADDR_ANY); send_addr.sin_port = htons(11000); memset(&send_addr2, 0, sizeof(send_addr2)); send_addr2.sin_family = AF_INET; send_addr2.sin_addr.s_addr = htonl(INADDR_ANY); send_addr2.sin_port = htons(12000); if (bind(sock, (SOCKADDR*)&send_addr, sizeof(send_addr)) == SOCKET_ERROR) error_handle("bind() error!"); if (bind(sock2, (SOCKADDR*)&send_addr2, sizeof(send_addr2)) == SOCKET_ERROR) error_handle("bind() error!"); emulThread = (HANDLE)_beginthreadex(NULL, 0, emulThread_func, 0, 0, &emulThreadID); printThread = (HANDLE)_beginthreadex(NULL, 0, printThread_func, 0, 0, &printThreadID); // print Thread connectThread = (HANDLE)_beginthreadex(NULL, 0, connectThread_func, 0, 0, &connectThreadID); int retval; clock_t _timer = clock(); // Recevie 메인 스레드 while (1) { if (ELAPSED_TIME(_timer, clock()) >= (1/bottleneck_rate)) { if (!queue_empty(&que)) { SOCKADDR_IN recv_addr = dequeue(&que); // bottleneck 큐에서 데이터를 꺼낸다 _timer = clock(); while (ELAPSED_TIME(_timer, clock()) < half_minrtt); // minimum RTT 동안 지연한다 char send_buf[PKT_SIZE + 1] = "ACK"; retval = sendto(sock, send_buf, (int)strlen(send_buf), 0, (SOCKADDR*)&recv_addr, sizeof(recv_addr)); if (retval == SOCKET_ERROR) continue; incr_ack_num(); } _timer = clock(); // 타이머 셋 } } CloseHandle(emulThread); CloseHandle(printThread); closesocket(sock); WSACleanup(); DeleteCriticalSection(&cs_ack); // cs 제거 DeleteCriticalSection(&cs_que); // cs 제거 return 0; } void incr_ack_num() { EnterCriticalSection(&cs_ack); // lock 획득 혹은 waiting acks_num++; LeaveCriticalSection(&cs_ack); // lock 반환 } void error_handle(char* message) { fputs(message, stderr); fputc('\n', stderr); exit(1); } int queue_full(QUEUE* q) { EnterCriticalSection(&cs_que); // lock 획득 혹은 waiting int ret = ((q->head + 1) % bottolneck_qsize == q->tail); LeaveCriticalSection(&cs_que); // lock 반환 return ret; } /* queue_empty( QUEUE) This function check whether the queue is empty. */ int queue_empty(QUEUE* q) { EnterCriticalSection(&cs_que); // lock 획득 혹은 waiting int ret = (q->head == q->tail); LeaveCriticalSection(&cs_que); // lock 반환 return ret; } /* enqueue( QUEUE *, int) insert a data into the queue */ void enqueue(QUEUE *q, data x) { EnterCriticalSection(&cs_que); // lock 획득 혹은 waiting if ((q->head + 1) % bottolneck_qsize == q->tail) { printf("the queue is full!\n"); return; } q->head = (q->head + 1) % bottolneck_qsize; q->ar[q->head] = x; q->cnt++; LeaveCriticalSection(&cs_que); // lock 반환 } int get_qcnt(QUEUE *q) { EnterCriticalSection(&cs_que); // lock 획득 혹은 waiting int ret = q->cnt; LeaveCriticalSection(&cs_que); // lock 반환 return ret; } data dequeue(QUEUE *q) { EnterCriticalSection(&cs_que); // lock 획득 혹은 waiting data ret; if (q->head == q->tail) { printf("the queue is empty!\n"); return send_addr; } q->tail = (q->tail + 1) % bottolneck_qsize; ret = q->ar[q->tail]; q->cnt--; LeaveCriticalSection(&cs_que); // lock 반환 return ret; } UINT WINAPI connectThread_func(void* para) { SOCKADDR_IN peer_addr; char rcv_buf[PKT_SIZE + 1]; int retval; while (1) { int addrlen = sizeof(peer_addr); retval = recvfrom(sock2, rcv_buf, PKT_SIZE, 0, (SOCKADDR*)&peer_addr, &addrlen); if (retval == SOCKET_ERROR) continue; if (retval == SOCKET_ERROR) continue; rcv_buf[retval] = '\0'; if (!strcmp(rcv_buf, "connect")) { char send_buf[PKT_SIZE + 1] = "accept"; retval = sendto(sock, send_buf, (int)strlen(send_buf), 0, (SOCKADDR*)&peer_addr, sizeof(peer_addr)); // sock으로 보내어 연결한다. if (retval == SOCKET_ERROR) continue; } } } UINT WINAPI emulThread_func(void* para) { SOCKADDR_IN peer_addr; char rcv_buf[PKT_SIZE + 1]; int retval; while (1) { int addrlen = sizeof(peer_addr); retval = recvfrom(sock, rcv_buf, PKT_SIZE, 0, (SOCKADDR*)&peer_addr, &addrlen); if (retval == SOCKET_ERROR) continue; clock_t _timer = clock(); while (ELAPSED_TIME(_timer, clock()) < half_minrtt); // minimum RTT 동안 지연한다 if (retval == SOCKET_ERROR) continue; rcv_buf[retval] = '\0'; // 큐가 꽉차면 수신한 peer_Addr로 NACK 즉시 회신 if (queue_full(&que)) { clock_t _timer = clock(); while (ELAPSED_TIME(_timer, clock()) < half_minrtt); // minimum RTT 동안 지연한다 char send_buf[PKT_SIZE + 1] = "NACK"; retval = sendto(sock, send_buf, (int)strlen(send_buf), 0, (SOCKADDR*)&peer_addr, sizeof(peer_addr)); if (retval == SOCKET_ERROR) continue; } else { enqueue(&que, peer_addr); } } } UINT WINAPI printThread_func(void* para) { clock_t _init, _timer; int t; int sum, qoc[20]; _init = clock(); _timer = clock(); t = 0; while (1) { if (ELAPSED_TIME(_timer, clock()) >= 0.1) { qoc[t] = get_qcnt(&que); t++; _timer = clock(); } if (t == 20) { double elapsed = ELAPSED_TIME(_init, clock()); EnterCriticalSection(&cs_ack); // lock 획득 혹은 waiting printf("\n[%lf]Receiving Rate : %lf pps\n", elapsed, acks_num / 2.0); acks_num = 0; LeaveCriticalSection(&cs_ack); // lock 반환 sum = 0; for (int i = 0; i < 20; i++) sum += qoc[i]; printf("[%lf]Average Queue Occupancy : %lf\n\n", elapsed, sum / 20.0); t = 0; } } }
5b321c0d8f2eaf111dc4432f6811fb3a49348eec
[ "C" ]
2
C
JungKiBeen/UDP-Server_Clint_RTT_Emulating
6097d7d55ba273af9de92ea5e0ee6767e5c9fe09
66e729c1c959c09785f3328e37e291d86d497b98
refs/heads/master
<repo_name>roroquentin/Sen-de-Gel<file_sep>/Sen de Gel/FeedViewController.swift // // FeedViewController.swift // <NAME> // // Created by <NAME> on 19.11.2019. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import Firebase import SDWebImage class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var userEmail = [String]() var userInfo = [String]() var userImageArray = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.delegate = self tableView.dataSource = self getData() } func getData(){ let fireStoreDatabase = Firestore.firestore() fireStoreDatabase.collection("İlanlar").order(by: "date", descending: true).addSnapshotListener { (snapshot, error) in if error != nil{ print(error?.localizedDescription) }else{ if snapshot?.isEmpty != true && snapshot != nil { self.userImageArray.removeAll(keepingCapacity: false) self.userInfo.removeAll(keepingCapacity: false) self.userEmail.removeAll(keepingCapacity: false) for document in snapshot!.documents { let documentID = document.documentID print(documentID) if let name = document.get("ilanVeren") as? String { self.userEmail.append(name) } if let info = document.get("ilanBilgi") as? String { self.userInfo.append(info) } if let imageUrl = document.get("imageUrl") as? String { self.userImageArray.append(imageUrl) } } self.tableView.reloadData() } } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return userEmail.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FeedCell cell.ilanBilgi.text = userInfo[indexPath.row] cell.userMail.text = userEmail[indexPath.row] cell.userImage.sd_setImage(with: URL(string: self.userImageArray[indexPath.row])) return cell } }
1d9b475e5980b8c1db0695694bea8132a3099f61
[ "Swift" ]
1
Swift
roroquentin/Sen-de-Gel
221057063cd7a080dc24cdd664627e105d5485b5
d24c754b740ccf7cede3345ba4302806f60d014d
refs/heads/main
<file_sep>let container = document.createElement('div'); container.className = "container"; document.querySelector("body").prepend(container); var arrays = []; async function fetchData() { var response = await fetch("https://rest-countries-api-techieegy.herokuapp.com/v1/all"); const data = await response.json(); console.log(data) data.forEach(country => { if (country.currencies && country.latlng) { let div = document.createElement('div'); div.className = country.name + " box"; document.querySelector('.container').appendChild(div); let country_name = document.createElement('p'); country_name.className = "country-name"; country_name.innerText = country.name; div.appendChild(country_name); let image = document.createElement('img'); image.className = "img"; image.src = country.flags[0]; div.appendChild(image); let capital = document.createElement('p'); capital.className = "capital"; capital.innerHTML = "Capital:<span>" + country.capital + "</span>"; div.appendChild(capital); let currency_name = document.createElement('p'); currency_name.innerHTML = "Currency-Name:<strong>" + country.currencies[0].name + "</strong>" div.appendChild(currency_name); let currency_code = document.createElement('p'); currency_code.innerHTML = "Currency-Code:<strong>" + country.currencies[0].code + "</strong>" div.appendChild(currency_code); let symbol = document.createElement('p'); symbol.innerHTML = "Currency-Symbol:<strong>" + country.currencies[0].symbol + "</strong>" div.appendChild(symbol); let country_code = document.createElement('p'); country_code.className = "country-code"; country_code.innerHTML = "Country Codes:<strong>" + country.alpha2Code + "," + country.alpha3Code + "</strong>"; div.appendChild(country_code); let region = document.createElement('p'); region.className = "region"; region.innerHTML = "Region:<strong>" + country.region + "</strong>"; div.appendChild(region); let latlong = document.createElement('p'); latlong.className = "latlong"; latlong.innerHTML = "Lat,Long:<strong>" + country.latlng[0] + "," + country.latlng[1] + "</strong>"; div.appendChild(latlong); arrays.push(country.name); } else { let div = document.createElement('div'); div.className = country.name + " box"; document.querySelector('.container').appendChild(div); let country_name = document.createElement('p'); country_name.className = "country-name"; country_name.innerText = country.name; div.appendChild(country_name); let image = document.createElement('img'); image.className = "img"; image.src = country.flags[0]; div.appendChild(image); let capital = document.createElement('p'); capital.className = "capital"; capital.innerHTML = "Capital:<span>" + country.capital + "</span>"; div.appendChild(capital); let currency_name = document.createElement('p'); currency_name.innerHTML = "Currency-Name:<strong>None</strong>" div.appendChild(currency_name); let currency_code = document.createElement('p'); currency_code.innerHTML = "Currency-Code:<strong>None</strong>" div.appendChild(currency_code); let symbol = document.createElement('p'); symbol.innerHTML = "Currency-Symbol:<strong>None</strong>" div.appendChild(symbol); let country_code = document.createElement('p'); country_code.className = "country-code"; country_code.innerHTML = "Country Codes:<strong>" + country.alpha2Code + "," + country.alpha3Code + "</strong>"; div.appendChild(country_code); let region = document.createElement('p'); region.className = "region"; region.innerHTML = "Region:<strong>" + country.region + "</strong>"; div.appendChild(region); let latlong = document.createElement('p'); latlong.className = "latlong"; latlong.innerHTML = "Lat,Long:<strong>None</strong>"; div.appendChild(latlong); } }); } fetchData();
92850fcd41599604d66c967de76101263e4d662b
[ "JavaScript" ]
1
JavaScript
ssg31598/API_techieeGY
b5991a14a3e869af4eb17b2f380b2d3918841344
049b3e4dd558e1810fd8c32547cc909b1e3c5d25
refs/heads/master
<repo_name>cigraphics/autoproxy4chrome<file_sep>/core/core.js var ProxyMode = "auto"; var defaultProxy = { rules: { singleProxy: { scheme: "socks5", host : "127.0.0.1", port : 7070 } } } var fallbackProxy = {}; // won't work, webRequest API is not ready yet function AutoProxy(reqst) { var proxyConfig = shouldProxy(reqst.url) ? defaultProxy : fallbackProxy; chrome.experimental.proxy.useCustomProxySettings(proxyConfig); } function shouldProxy(url) { if ( url.indexOf("twitter.com") > 0 ) return true; return false; } // test... chrome.experimental.webRequest.onBeforeRequest.addListener( function(reqst) { alert("Great! The long-awaited webRequest API finally ships!"); } ); // workaround... chrome.experimental.proxy.useCustomProxySettings( { autoDetect: false, pacScript: { url: "http://autoproxy2pac.appspot.com/pac/ssh-d" } } );
0554d1c53cd06d7ca5681041ec31fce25befd9af
[ "JavaScript" ]
1
JavaScript
cigraphics/autoproxy4chrome
ee1c7496b27516c09652881a9581f9eca3d29965
c2e66b0ba1654f31b034ec81c90ccaed607518c3
refs/heads/master
<repo_name>university-of-york/t4-extension<file_sep>/js/trigger.js // Trigger event in parent window (if loaded in iframe) // iFrame window doesn't have access to window.parent :( (function () { if (window.parent != window.top) { // We're deeper than one down - create custom event var event = new Event('frameLoaded'); // Dispatch the event. window.parent.dispatchEvent(event); } })();<file_sep>/js/buttons.js (function () { // get random name for iframe var id = setTimeout(function(){}); var iframeName = 'save-frame-'+id; // Find all the button wrappers (multiple IDs? Nice one, T4) var buttonWraps = document.querySelectorAll('#tab-button-dd-menu-wrap-top'); if (buttonWraps.length === 0) return; var contentDiv = document.getElementById('content'); var contentHeader = content.querySelector('h1'); // Create a context for form target var iframe = document.createElement('iframe'); iframe.name = iframeName; iframe.style.height = '0'; iframe.style.width = '0'; iframe.style.borderWidth = '0'; document.body.appendChild(iframe); // Listen for the event - not being fired from parent // window.addEventListener('frameLoaded', function (e) { // console.log('iFrame is ready!'); // }, false); iframe.onload = function() { // Add message from iframe var iframeBanner = iframe.contentDocument.getElementById('pres-message'); if (iframeBanner) { contentDiv.insertBefore(iframeBanner.cloneNode(true), contentHeader.nextSibling); } }; Array.prototype.forEach.call(buttonWraps, function(wrap, i){ var sampleDiv = wrap.children[0]; var divClone = sampleDiv.cloneNode(true); var saveButton = divClone.querySelectorAll('button'); if (saveButton.length === 0) return; var buttonText = saveButton[0].textContent.replace('Update', 'Save'); saveButton[0].textContent = buttonText; saveButton[0].addEventListener('click', function(e) { // Remove old banner var oldBanner = document.getElementById('pres-message'); if (oldBanner) { oldBanner.parentNode.removeChild(oldBanner); } // Set form action to open in iframe var parentForm = saveButton[0].closest('form'); parentForm.setAttribute('target', iframeName); return true; }); wrap.insertBefore(divClone, wrap.firstChild); }); })();
d4a2bb4a69992f89dc9f26ea3455e6c5518f2d73
[ "JavaScript" ]
2
JavaScript
university-of-york/t4-extension
9959d57f05aa22362d855ae11fcc7a3a0392304a
4653408a9f5113feae551056651448d48cc3982c
refs/heads/master
<repo_name>sfaverman/Employee-Management-Application<file_sep>/tbemployees.sql -- phpMyAdmin SQL Dump -- version 4.7.0 -- https://www.phpmyadmin.net/ -- -- Host: localhost:8889 -- Generation Time: Aug 10, 2019 at 04:47 AM -- Server version: 5.6.34-log -- PHP Version: 7.2.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `webd166` -- -- -------------------------------------------------------- -- -- Table structure for table `tbemployees` -- CREATE TABLE `tbemployees` ( `id` int(6) NOT NULL, `fullname` varchar(255) NOT NULL, `gender` varchar(255) NOT NULL, `title` varchar(255) NOT NULL, `hire_date` date NOT NULL, `comments` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbemployees` -- INSERT INTO `tbemployees` (`id`, `fullname`, `gender`, `title`, `hire_date`, `comments`) VALUES (1, '<NAME>', 'Female', 'Web Developer', '2019-06-09', 'Moved from San Diego.!'), (6, '<NAME>', 'Female', 'Supervisor', '2009-08-05', 'The best!!'), (7, '<NAME>', 'Female', 'Data Scientist II', '2016-08-15', 'MS from Chapman University!!!!!'), (8, 'Nicholas Malmud', 'Male', 'Intern', '2018-09-17', 'Welcome!!'), (9, '<NAME>', 'Male', 'Manager', '2011-05-07', 'Promoted last year!'), (10, '<NAME>', 'Male', 'Project Manager', '2000-10-18', ''); -- -- Indexes for dumped tables -- -- -- Indexes for table `tbemployees` -- ALTER TABLE `tbemployees` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbemployees` -- ALTER TABLE `tbemployees` MODIFY `id` int(6) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/login.php <?php session_start(); //Connect to database $dbh = new PDO("mysql:host=localhost:8889;dbname=webd166", 'root', 'root'); if(isset($_POST['submit']) && $_POST['submit'] == 'Log in'){ $username = $_POST['username']; $userpass = $_POST['password']; $checksql = $dbh->prepare("select password from tbadmin where username = '$username' "); $checksql->execute(); $row = $checksql->fetch(); $password = $row[0]; if (password_verify($userpass, $password)) { //echo 'Password is valid!'; $_SESSION['username'] = $username; $_SESSION['auth'] = '<PASSWORD>'; header ("Location: employee_mgmt.php"); } else { echo '<h4>Invalid password. Please try again.</h4>'; } // FOR this sample/demo userid: admin, password: <PASSWORD> } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> <link rel="stylesheet" href="css/main.css"> <style> h1 { text-align: center; } form { max-width: 400px; margin: 0 auto; } input { width: 97%; } </style> </head> <body> <h1>Welcome to CMS</h1> <form action="login.php" method="post"> <fieldset><legend>Please login</legend> Username: <input type="text" name="username"> Password: <input type = "<PASSWORD>" name="password"> <input type="submit" name="submit" value="Log in"> </fieldset> </form> </body> </html> <file_sep>/README.md # Employee-Management-Application PHP-Employee Management Application <file_sep>/employee_mgmt.php <?php ob_start(); session_start(); //var_dump($_SESSION); if ($_SESSION['auth'] != 'w<PASSWORD>'){ header ("Location: login.php"); } echo '<div id="top"> Welcome, <b>'.$_SESSION['username'].'</b>'; echo '<a href="logout.php">Log Out</a><br><br></div>'; //INSERT data from registration form into database //Connect to database $dbh = new PDO("mysql:host=localhost:8889;dbname=webd166", 'root', 'root'); //echo 'connected to webd166<br>'; $status = 'Register'; if (isset($_GET['deleteid'])) { $deleteid = $_GET['deleteid']; } if (isset($_GET['editid'])) { $editid = $_GET['editid'];} if (isset($deleteid)) { $delsql = $dbh->prepare("delete from tbemployees where id = '$deleteid';"); $delsql->execute(); //echo "<h4>Record Deleted for employeeid = $deleteid.</h4>"; } if (isset($_GET['viewid'])) { $viewid = $_GET['viewid']; // select a particular user by id $viewsql = $dbh->prepare("SELECT * FROM tbemployees WHERE id = '$viewid';"); $viewsql->execute(); $viewrow = $viewsql->fetch(); $disfullname = $viewrow[1]; $disgender = $viewrow[2]; $disemptitle = $viewrow[3]; $dishiredate = $viewrow[4]; $discomments = $viewrow[5]; //echo "$disfullname - $disgender - $dishiredate - $discomments"; } if (isset($_POST['submit']) && $_POST['submit'] == 'Register'){ //get the data and insert it!!! $fullname = $_POST['fullname']; $gender = $_POST['gender']; $emptitle = $_POST['emptitle']; $hiredate = $_POST['year'].'-'. $_POST['month'].'-'.$_POST['day']; $comments = $_POST['comments']; //tbemployees is a table name created in phpMyAdmin for databases webd166 $insert = $dbh->prepare("insert into tbemployees ( fullname,gender,title,hire_date,comments) values ( '$fullname','$gender','$emptitle','$hiredate','$comments')"); $insert->execute(); //print_r($insert->errorInfo()); echo "<h4>Record added for employee $fullname !</h4>"; } if (isset($_POST['submit']) && $_POST['submit'] == 'Update'){ //get the data and insert it!!! $fullname = $_POST['fullname']; $gender = $_POST['gender']; $emptitle = $_POST['emptitle']; $month = sprintf("%02d", $_POST['month']); $day = sprintf("%02d", $_POST['day']); $hiredate = $_POST['year'].'-'. $month.'-'.$day; $comments = $_POST['comments']; //tbemployees is a table in phpMyAdmin for databases webd166 $updatesql = $dbh->prepare("UPDATE tbemployees SET fullname = '$fullname', gender = '$gender', title = '$emptitle', hire_date = '$hiredate', comments = '$comments!' WHERE id = '$editid';"); $updatesql->execute(); //print_r($updatesql->errorInfo()); echo "<h4> Record Updated for $fullname!</h4>"; } if (isset($editid)) { $editsql = $dbh->prepare("select fullname, gender, title, hire_date, comments from tbemployees where id = '$editid'"); $editsql->execute(); $editrow = $editsql->fetch(); $upfullname = $editrow[0]; $upgender = $editrow[1]; $upemptitle = $editrow[2]; $upyear = substr($editrow[3],0,4); $upmonth = substr($editrow[3],5,2); $upday = substr($editrow[3],8,2); $upcomments = $editrow[4]; $status = 'Update'; //print_r($editsql->errorInfo()); echo '<br><a href="employee_mgmt.php"> Click to go back to add mode</a>'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Employee Management</title> <link rel="stylesheet" href="css/main.css"> </head> <body> <h1>List of Employees</h1> <section id="listEmps"> <?php //display records ... just the name $display = $dbh->prepare("SELECT id, fullname FROM tbemployees ORDER BY id DESC"); $display->execute(); while ($row = $display->fetch()){ //$fullname = $row['fullname']; or $id = $row[0]; $fullname = $row[1]; $details = ''; if (isset($viewid) && $fullname == $disfullname) { $details = $disgender.', '.$disemptitle.', '.$dishiredate.', '.$discomments; } echo '<span class="employeeName">'.$fullname.'</span> <a href="employee_mgmt.php?viewid='.$id. '">View</a> '. '<a href="employee_mgmt.php?deleteid='.$id. '">Delete</a> '. '<a href="employee_mgmt.php?editid='.$id. '">Edit</a><br>'; if ($details != '') echo '<div class="record">'.$details.'</div><br>'; } ?> </section> <!--need to prepopulate the inputs with the selected record if edit is clicked. --> <h1> <?php if (empty($editid)) { echo 'Add new employee'; } else { echo 'Edit selected employee'; } ?> </h1> <form action ="employee_mgmt.php? <?php echo $_SERVER['QUERY_STRING']; //it is $editid if edit ?>" method="POST"> <fieldset><legend>Employee Registration form</legend> <label for="fullname">Name:</label> <input type="text" name="fullname" id="fullname" value="<?php if (isset($upfullname)) {echo $upfullname;} ?>" required> <fieldset><legend>Gender:</legend> <ul> <!--<li> <p>Gender:</p> </li> --> <li> <label for="male"> Male <input type="radio" name="gender" id="male" value="Male" <?php if (isset($upgender) && $upgender == 'Male') { echo ' checked="checked" ';} ?>></label> </li> <li> <label for="female">Female <input type="radio" name="gender" value="Female" <?php if (isset($upgender) && $upgender == 'Female') { echo ' checked="checked" ';} ?>></label> </li> </ul> </fieldset> <label for="emptitle">Title:</label> <input type="text" name="emptitle" id="emptitle" value="<?php if (isset($upemptitle)) {echo $upemptitle;} ?>" required> <fieldset><legend>Hire Date:</legend> <!--<input type="text" name="hiredate" id="hiredate" value="<?php if (isset($upfullname)) {echo $uphiredate;} ?>" required>--> <?php $month = [ 1 =>'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; $days = range(1,31); $years = range(date('Y'), 1900); echo '<ul>'; echo '<li> <label for="month">Month</label> <select name="month" id="month">'; foreach ($month as $key => $value) { echo "<option value=\"$key\""; if (isset($upmonth) && $upmonth == sprintf("%02d", $key) ) {echo " selected=\"selected\"";}; echo ">$value</option>"; } echo '</select></li>'; echo '<li> <label for="day">Day</label> <select name="day" id="day">'; foreach ($days as $value) { echo "<option value=\"$value\""; if (isset($upday) && $upday == $value) {echo " selected=\"selected\"";}; echo ">$value</option>"; } echo '</select></li>'; echo '<li> <label for="month">Year</label> <select name="year" id="year">'; foreach ($years as $value) { echo "<option value=\"$value\""; if (isset($upyear) && $upyear == $value) {echo " selected=\"selected\"";}; echo ">$value</option>"; } echo '</select></li>'; echo '</ul>'; ?> </fieldset> <label for="comments">Comments:</label> <textarea name="comments" id="comments"><?php if (isset($upcomments)) {echo $upcomments;} ?></textarea> <input type="submit" name ="submit" value="<?php echo $status;?>"> </fieldset> </form> </body> </html>
4213535dbc9062f3a28a4a1ea3c45e49486cdab1
[ "Markdown", "SQL", "PHP" ]
4
SQL
sfaverman/Employee-Management-Application
ba43219f563072c4bbc14c2fa8dfdbc2c5abd00a
f5e4beca1bafdb90505064b53ba6c7adcbefb849
refs/heads/main
<repo_name>iwannabespace/LibraryAutomation<file_sep>/Source/RequestStream.hpp #ifndef REQUESTSTREAM_HPP #define REQUESTSTREAM_HPP #include <fstream> #include <utility> #include "Book.hpp" #include "Vector.hpp" class RequestStream { private: Vector<std::pair<Book, std::string>> requested_books; Vector<std::pair<Book, std::string>> approved_books; public: RequestStream(); void addRequestedBook(const std::pair<Book, std::string>& pair); void addApprovedBook(const std::pair<Book, std::string>& pair); bool removeRequestedBook(const std::string& id); bool removeApprovedBook(const std::string& id); bool isRequested(const std::string& id) const; bool isApprovedIdAndUserValid(const std::pair<std::string, std::string>& pair) const; Book getRequestedBookById(const std::string& id) const; Book getApprovedBookById(const std::string& id) const; int indexForRequestedBook(const std::string& id) const; int indexForApprovedBook(const std::string& id) const; Vector<std::pair<Book, std::string>> getRequestedBooks() const; Vector<std::pair<Book, std::string>> getApprovedBooks() const; private: void loadRequestedBooks(); void loadApprovedBooks(); void updateRequestedBooks() const; void updateApprovedBooks() const; }; #endif<file_sep>/Source/Automation.cpp #include "Automation.hpp" void Automation::Begin() { while (true) { if (GetCurrentState() == "None") FirstScreen(); if (GetCurrentState() == "Admin") MainScreenAdmin(); if (GetCurrentState() == "User") MainScreenUser(); } } void Automation::FirstScreen() { int choice; for (const std::string& option: FirstScreenOptions()) std::cout << option << std::endl; std::cout << " -> "; std::cin >> choice; switch(choice) { case 1: SignIn(); break; case 2: SignUp(); break; case 3: Exit(); break; default: break; } } void Automation::MainScreenAdmin() { int choice; for (const std::string& option: MainScreenOptionsFor_Admin()) std::cout << option << std::endl; std::cout << " -> "; std::cin >> choice; switch(choice) { case 1: AddBook(); break; case 2: RemoveBook(); break; case 3: EditBook(); break; case 4: Answer(); break; case 5: SearchById(); break; case 6: SearchByAuthor(); break; case 7: ListBooks(); break; case 8: ListLentBooks(); break; case 9: ListRequests(); break; case 10: LogOut(); break; default: break; } } void Automation::MainScreenUser() { int choice; for (const std::string& option: MainScreenOptionsFor_User()) std::cout << option << std::endl; std::cout << " -> "; std::cin >> choice; switch(choice) { case 1: RequestBook(); break; case 2: ReturnBook(); break; case 3: ReturnAllBooks(); break; case 4: ListRequestedBooks(); break; case 5: ListBorrowedBooks(); break; case 6: ListLibrary(); break; case 7: LogOut(); default: break; } } void Automation::SignIn() { std::fstream file; std::string type; std::string username, u_temp; std::string password, p_temp; int pos = 0; std::cout << "Type: "; std::cin.ignore(); std::getline(std::cin, type); std::cout << "Username: "; std::getline(std::cin, username); std::cout << "Password: "; std::getline(std::cin, password); if (string_lower(type) == "admin") { file.open("Data/Admin.txt", std::ios::in); std::getline(file, u_temp); std::getline(file, p_temp); if (username == u_temp) { if (password == <PASSWORD>) AlterStateAs("Admin"); else std::cout << "Invalid password!" << std::endl; } else std::cout << "Admin username is invalid!" << std::endl; file.close(); } else if (string_lower(type) == "user") { file.open("Data/Accounts.txt", std::ios::in); while (!file.eof()) { std::getline(file, u_temp); pos++; if (username == u_temp && pos % 2 != 0) { std::getline(file, p_temp); if (password == <PASSWORD>) { AlterStateAs("User"); SetCurrentUser(username); break; } else { std::cout << "Invalid password!" << std::endl; break; } } else if (file.eof() && username != u_temp) std::cout << "No username found!" << std::endl; } file.close(); } else std::cout << "Invalid type!" << std::endl << "Try: Admin or User" << std::endl; } void Automation::SignUp() { std::fstream file; std::string username; std::string password; std::cout << "Choose a username: "; std::cin.ignore(); std::getline(std::cin, username); std::cout << "Choose a password: "; std::getline(std::cin, password); if (is_username_unique(username)) { if (is_password_appropriate(password) == 1) { file.open("Data/Accounts.txt", std::ios::app); file << username << std::endl; file << password << std::endl; file.close(); std::cout << "Sign up successfull" << std::endl; } else if (is_password_appropriate(password) == 0) std::cout << "Password must contain at least one number!" << std::endl; else if (is_password_appropriate(password) == -1) std::cout << "Password must contain at least one upper case letter!" << std::endl; else if (is_password_appropriate(password) == -2) std::cout << "Password length must be between 8 - 20 characters!" << std::endl; } else std::cout << "Username is already in use!" << std::endl; } void Automation::Exit() { exit(0); } void Automation::AddBook() { Library library; std::string name, author; std::string id, publish_date; std::cout << "Name of the book: "; std::cin.ignore(); std::getline(std::cin, name); std::cout << "Author of the book: "; std::getline(std::cin, author); std::cout << "Id of the book: "; std::getline(std::cin, id); std::cout << "Publish date of the book: "; std::getline(std::cin, publish_date); library.addBook(Book(name, author, id, Date(publish_date))); std::cout << "Book successfully added!" << std::endl; } void Automation::RemoveBook() { Library library; std::string data; std::cout << "Id of the book: "; std::cin.ignore(); std::getline(std::cin, data); if (library.removeBook(data)) std::cout << "Book successfully removed!" << std::endl; else std::cout << "Id doesn't match with any book!" << std::endl; } void Automation::EditBook() { Library library; std::string id, which, data; std::cout << "Id of book: "; std::cin.ignore(); std::getline(std::cin, id); std::cout << "Which section of book: "; std::getline(std::cin, which); if (string_lower(which) == "name") { std::cout << "New name: "; std::getline(std::cin, data); if (library.editBook(id, data, 1)) std::cout << "Book edited successfully!" << std::endl; else std::cout << "Id doesn't match with any book!" << std::endl; } else if (string_lower(which) == "author") { std::cout << "New author: "; std::getline(std::cin, data); if (library.editBook(id, data, 2)) std::cout << "Book edited successfully!" << std::endl; else std::cout << "Id doesn't match with any book!" << std::endl; } else if (string_lower(which) == "id") { std::cout << "New id: "; std::getline(std::cin, data); if (library.editBook(id, data, 3)) std::cout << "Book edited successfully!" << std::endl; else std::cout << "Id doesn't match with any book!" << std::endl; } else if (string_lower(which) == "date") { std::cout << "New publish date: "; std::getline(std::cin, data); if (library.editBook(id, data, 4)) std::cout << "Book edited successfully!" << std::endl; else std::cout << "Id doesn't match with any book!" << std::endl; } else std::cout << "\"" << which << "\" named section doesn't exist!" << std::endl; } void Automation::Answer() { Library library; RequestStream stream; std::string id, answer; std::cout << "Id of book to be answered: "; std::cin.ignore(); std::getline(std::cin, id); if (stream.getRequestedBookById(id).getName().size() > 0) { std::cout << "Your reply: "; std::getline(std::cin, answer); if (string_lower(answer) == "approved") { stream.addApprovedBook(std::make_pair(stream.getRequestedBookById(id), get_requester_by_id(id))); stream.removeRequestedBook(id); library.removeBook(id); delete_request_from_requests_by_id(id); } else if (string_lower(answer) == "disapproved") { stream.removeRequestedBook(id); delete_request_from_requests_by_id(id); } else std::cout << "Invalid reply!" << std::endl; } else std::cout << "Book with id of " << id << " is not requested!" << std::endl; } void Automation::SearchById() { Library library; std::string data; std::cout << "Id for searching: "; std::cin.ignore(); std::getline(std::cin, data); if (library.searchById(data).getId().size() > 0) std::cout << library.searchById(data) << std::endl; else std::cout << "Id doesn't match with any book!" << std::endl; } void Automation::SearchByAuthor() { Library library; std::string data; std::cout << "Author for searching: "; std::cin.ignore(); std::getline(std::cin, data); library.searchByAuthor(data); } void Automation::ListBooks() { Library library; if (library.getBooks().Size() > 0) for (int i = 0; i < library.getBooks().Size(); i++) std::cout << "Book " << i + 1 << std::endl << library.getBooks()[i] << std::endl; else std::cout << "No book found!" << std::endl; } void Automation::ListRequests() { std::fstream file("Data/Requests.txt", std::ios::in); std::string data; int index; while (!file.eof()) { std::getline(file, data); if (data.size() > 0) std::cout << "Request: " << data << std::endl; } file.close(); } void Automation::ListLentBooks() { RequestStream stream; if (stream.getApprovedBooks().Size() > 0) for (int i = 0; i < stream.getApprovedBooks().Size(); i++) std::cout << "Lent book " << i + 1 << std::endl << stream.getApprovedBooks().Get(i).first << std::endl; else std::cout << "No book has been lent so far!" << std::endl; } void Automation::RequestBook() { Library library; RequestStream stream; std::fstream file("Data/Requests.txt", std::ios::app); std::string data; std::cout << "Id of book to be requested: "; std::cin.ignore(); std::getline(std::cin, data); if (library.isIdValid(data)) { if (!stream.isRequested(data)) { file << GetCurrentUser() << " " << data << std::endl; stream.addRequestedBook(std::make_pair(library.getById(data), GetCurrentUser())); std::cout << "Book requested successfully!" << std::endl; } else std::cout << "This book is already requested!" << std::endl; } else std::cout << "Id doesn't match with any books!" << std::endl; file.close(); } void Automation::ReturnBook() { Library library; RequestStream stream; std::string data, id; std::cout << "Id of book to be returned: "; std::cin.ignore(); std::getline(std::cin, id); if (stream.isApprovedIdAndUserValid(std::make_pair(id, GetCurrentUser()))) { library.addBook(stream.getApprovedBookById(id)); if (stream.removeApprovedBook(id)) std::cout << "Book returned successfully!" << std::endl; else std::cout << "Book couldn't be returned because of an unknown reason!" << std::endl; } else std::cout << "You don't owe the book!" << std::endl; } void Automation::ReturnAllBooks() { Library library; RequestStream stream; for (const std::pair<Book, std::string>& pair: stream.getApprovedBooks()) if (pair.second == GetCurrentUser()) { library.addBook(stream.getApprovedBookById(pair.first.getId())); stream.removeApprovedBook(pair.first.getId()); } std::cout << "All borrowed books are returned!" << std::endl; } void Automation::ListRequestedBooks() { Library library; RequestStream stream; if (stream.getRequestedBooks().Size() > 0) { for (int i = 0; i < stream.getRequestedBooks().Size(); i++) { if (stream.getRequestedBooks().Get(i).second == GetCurrentUser()) { std::cout << "Requested Book " << i + 1 << std::endl; std::cout << stream.getRequestedBooks().Get(i).first << std::endl; } } } else std::cout << "Request list is empty!" << std::endl; } void Automation::ListBorrowedBooks() { Library library; RequestStream stream; if (stream.getApprovedBooks().Size() > 0) { for (int i = 0; i < stream.getApprovedBooks().Size(); i++) { if (stream.getApprovedBooks().Get(i).second == GetCurrentUser()) { std::cout << "Borrowed Book " << i + 1 << std::endl; std::cout << stream.getApprovedBooks().Get(i).first << std::endl; } } } else std::cout << "No borrowed book found!" << std::endl; } void Automation::ListLibrary() { Library library; if (library.getBooks().Size() > 0) for (int i = 0; i < library.getBooks().Size(); i++) std::cout << "Library book " << i + 1 << std::endl << library.getBooks().Get(i) << std::endl; else std::cout << "Library has no books yet!" << std::endl; } void Automation::LogOut() { AlterStateAs("None"); SetCurrentUser(""); } void Automation::AlterStateAs(const std::string& state) { std::fstream file("Data/State.txt", std::ios::out); file << state; file.close(); } void Automation::SetCurrentUser(const std::string& username) { std::fstream file("Data/Current Account.txt", std::ios::out); file << username; file.close(); } std::string Automation::GetCurrentState() { std::fstream file("Data/State.txt", std::ios::in); std::string current_state; file >> current_state; file.close(); return current_state; } std::string Automation::GetCurrentUser() { std::fstream file("Data/Current Account.txt", std::ios::in); std::string current_user; file >> current_user; file.close(); return current_user; } Vector<std::string> Automation::FirstScreenOptions() { Vector<std::string> first_screen = { "(1) -> Sign in", "(2) -> Sign up", "(3) -> Exit" }; return first_screen; } Vector<std::string> Automation::MainScreenOptionsFor_Admin() { Vector<std::string> main_screen_for_admin = { "(1) -> Add Book", "(2) -> Remove Book", "(3) -> Edit Book", "(4) -> Answer a Request", "(5) -> Search Book by ID", "(6) -> Search Book by Author", "(7) -> List Books", "(8) -> List Lent Books", "(9) -> List Requests", "(10) -> Log out" }; return main_screen_for_admin; } Vector<std::string> Automation::MainScreenOptionsFor_User() { Vector<std::string> main_screen_for_user = { "(1) -> Request Book", "(2) -> Return Book", "(3) -> Return All Books", "(4) -> List Requested Books", "(5) -> List Borrowed Books", "(6) -> List All Books In Library", "(7) -> Logout", }; return main_screen_for_user; } void Automation::delete_request_from_requests_by_id(const std::string& id) { RequestStream stream; std::fstream file("Data/Requests.txt", std::ios::out); for (const std::pair<Book, std::string>& pair: stream.getRequestedBooks()) if (pair.first.getId() != id) file << pair.second << " " << pair.first.getId() << std::endl; } std::string Automation::get_requester_by_id(const std::string& id) { RequestStream stream; if (stream.getRequestedBookById(id).getName().size() > 0) return stream.getRequestedBooks().Get(stream.indexForRequestedBook(id)).second; else return std::string(); } bool Automation::is_username_unique(const std::string& username) { std::fstream file("Data/Accounts.txt", std::ios::in); std::string data; int pos = 0; while (!file.eof()) { std::getline(file, data); pos++; if (data == username && pos % 2 != 0) { file.close(); return false; } } file.close(); return true; } int Automation::is_password_appropriate(const std::string& password) { if (password.size() >= 8 && password.size() <= 20) { if (std::any_of(password.begin(), password.end(), isupper)) { if (std::any_of(password.begin(), password.end(), isdigit)) return 1; else return 0; } else return -1; } else return -2; } std::string Automation::string_lower(const std::string& str) { std::string temp = str; for (char& letter: temp) letter = tolower(letter); return temp; }<file_sep>/Source/Book.cpp #include "Book.hpp" Book::Book() :name(""), author(""), id(""), publish_date("") {} Book::Book(const std::string& name, const std::string& author, const std::string& id, Date publish_date) :name(name), author(author), id(id), publish_date(publish_date) {} Book::Book(const Book& book) { name = book.getName(); author = book.getAuthor(); id = book.getId(); publish_date = book.getPublish_Date(); } void Book::setName(const std::string& name) { this->name = name; } void Book::setAuthor(const std::string& author) { this->author = author; } void Book::setId(const std::string& id) { this->id = id; } void Book::setPublish_Date(const Date& publish_date) { this->publish_date = publish_date; } std::string Book::getName() const { return name; } std::string Book::getAuthor() const { return author; } std::string Book::getId() const { return id; } Date Book::getPublish_Date() const { return publish_date; } bool Book::operator==(const Book& book) const { return name == book.getName() && author == book.getAuthor() && id == book.getId() && publish_date == book.getPublish_Date(); } std::ostream& operator<<(std::ostream& os, const Book& book) { os << "Name: " << book.getName() << std::endl << "Author: " << book.getAuthor() << std::endl << "Id: " << book.getId() << std::endl << "Publish date: " << book.getPublish_Date(); return os; }<file_sep>/main.cpp #include <iostream> #include "Source/Automation.hpp" int main() { Automation::Begin(); return 0; }<file_sep>/Source/RequestStream.cpp #include "RequestStream.hpp" RequestStream::RequestStream() { loadRequestedBooks(); loadApprovedBooks(); } void RequestStream::addRequestedBook(const std::pair<Book, std::string>& pair) { requested_books.Push(pair); updateRequestedBooks(); } void RequestStream::addApprovedBook(const std::pair<Book, std::string>& pair) { approved_books.Push(pair); updateApprovedBooks(); } bool RequestStream::removeRequestedBook(const std::string& id) { for (const std::pair<Book, std::string>& pair: requested_books) if (pair.first.getId() == id) { requested_books.Remove(pair); updateRequestedBooks(); return true; } return false; } bool RequestStream::removeApprovedBook(const std::string& id) { for (const std::pair<Book, std::string>& pair: approved_books) if (pair.first.getId() == id) { approved_books.Remove(pair); updateApprovedBooks(); return true; } return false; } bool RequestStream::isRequested(const std::string& id) const { for (const std::pair<Book, std::string>& pair: requested_books) if (pair.first.getId() == id) return true; return false; } bool RequestStream::isApprovedIdAndUserValid(const std::pair<std::string, std::string>& pair) const { for (const std::pair<Book, std::string>& apprv: approved_books) if (apprv.first.getId() == pair.first && apprv.second == pair.second) return true; return false; } Book RequestStream::getRequestedBookById(const std::string& id) const { for (const std::pair<Book, std::string>& pair: requested_books) if (pair.first.getId() == id) return pair.first; return Book(); } Book RequestStream::getApprovedBookById(const std::string& id) const { for (const std::pair<Book, std::string>& pair: approved_books) if (pair.first.getId() == id) return pair.first; return Book(); } int RequestStream::indexForRequestedBook(const std::string& id) const { for (int i = 0; i < requested_books.Size(); i++) if (requested_books.Get(i).first.getId() == id) return i; return 0; } int RequestStream::indexForApprovedBook(const std::string& id) const { for (int i = 0; i < approved_books.Size(); i++) if (approved_books.Get(i).first.getId() == id) return i; return 0; } Vector<std::pair<Book, std::string>> RequestStream::getRequestedBooks() const { return requested_books; } Vector<std::pair<Book, std::string>> RequestStream::getApprovedBooks() const { return approved_books; } void RequestStream::loadRequestedBooks() { std::fstream file("Data/Requested Books.txt", std::ios::in); std::string infos[4]; std::string data; while (!file.eof()) { std::getline(file, data); if (data == "BEGIN") { std::getline(file, data); std::getline(file, infos[0]); std::getline(file, infos[1]); std::getline(file, infos[2]); std::getline(file, infos[3]); for (std::string& info: infos) if (isspace(info[info.size() - 1])) info.pop_back(); requested_books.Push(std::make_pair(Book(infos[0], infos[1], infos[2], Date(infos[3])), data)); } } file.close(); } void RequestStream::loadApprovedBooks() { std::fstream file("Data/Approved Books.txt", std::ios::in); std::string infos[4]; std::string data; while (!file.eof()) { std::getline(file, data); if (data == "BEGIN") { std::getline(file, data); std::getline(file, infos[0]); std::getline(file, infos[1]); std::getline(file, infos[2]); std::getline(file, infos[3]); for (std::string& info: infos) if (isspace(info[info.size() - 1])) info.pop_back(); approved_books.Push(std::make_pair(Book(infos[0], infos[1], infos[2], Date(infos[3])), data)); } } file.close(); } void RequestStream::updateRequestedBooks() const { std::fstream file("Data/Requested Books.txt", std::ios::out); for (const std::pair<Book, std::string>& pair: requested_books) { file << "BEGIN" << std::endl; file << pair.second << std::endl << pair.first.getName() << std::endl << pair.first.getAuthor() << std::endl << pair.first.getId() << std::endl << pair.first.getPublish_Date() << std::endl; file << "END" << std::endl; } file.close(); } void RequestStream::updateApprovedBooks() const { std::fstream file("Data/Approved Books.txt", std::ios::out); for (const std::pair<Book, std::string>& pair: approved_books) { file << "BEGIN" << std::endl; file << pair.second << std::endl << pair.first.getName() << std::endl << pair.first.getAuthor() << std::endl << pair.first.getId() << std::endl << pair.first.getPublish_Date() << std::endl; file << "END" << std::endl; } file.close(); }<file_sep>/Source/Vector.hpp #pragma once #include <iostream> #include <vector> #include <algorithm> #include <initializer_list> template<class T> class Vector; template<class U> std::ostream& operator<<(std::ostream& os, const Vector<U>& vec); template<class U> std::ostream& operator<<(std::ostream& os, const Vector<U*>& vec); template<class T> class Vector { private: T* elems; int size; int capacity; public: Vector(); Vector(std::size_t capacity); Vector(const Vector<T>& vec); Vector(std::initializer_list<T> init_list); ~Vector(); std::size_t Size() const; std::size_t Capacity() const; T& Get(std::size_t pos) const; T& operator[](std::size_t pos) const; Vector<T> operator+(const Vector<T>& vec) const; bool operator==(const Vector<T>& vec) const; bool operator!=(const Vector<T>& vec) const; void Push(const T& elem); void Remove(const T& elem); void Remove_At(std::size_t pos); void Sort() const; std::vector<T> ConvertTo_Std() const; public: T* begin() const; T* end() const; public: template<class U> friend std::ostream& operator<<(std::ostream& os, const Vector<U>& vec); template<class U> friend std::ostream& operator<<(std::ostream& os, const Vector<U*>& vec); private: void Allocate(); }; #include "Vector.cpp"<file_sep>/Source/Date.cpp #include "Date.hpp" Date::Date() :date("") {} Date::Date(const std::string& date) :date(date) {} Date::Date(const Date& date) { this->date = date.getDay() + "." + date.getMonth() + "." + date.getYear(); } void Date::setDate(const std::string& date) { this->date = date; } std::string Date::getDay() const { std::string day; day += date[0]; day += date[1]; return day; } std::string Date::getMonth() const { std::string month; month += date[3]; month += date[4]; return month; } std::string Date::getYear() const { std::string year; year += date[6]; year += date[7]; year += date[8]; year += date[9]; return year; } std::string Date::asString() const { return date; } bool Date::operator==(const Date& date) const { return this->date == date.asString(); } std::string Date::Now() { std::time_t now_time = std::time(0); std::tm* now = std::localtime(&now_time); std::string actual_now; if (std::to_string(now->tm_mday).size() < 2) actual_now += "0" + std::to_string(now->tm_mday) + "."; else actual_now += std::to_string(now->tm_mday) + "."; if (std::to_string(now->tm_mon + 1).size() < 2) actual_now += "0" + std::to_string(now->tm_mon + 1) + "."; else actual_now += std::to_string(now->tm_mon + 1) + "."; actual_now += std::to_string(now->tm_year + 1900); return actual_now; } std::ostream& operator<<(std::ostream& os, const Date& date) { os << date.date; return os; }<file_sep>/Source/Vector.cpp #include "Vector.hpp" template<class T> Vector<T>::Vector() :capacity(5), size(0) { elems = new T[capacity]; } template<class T> Vector<T>::Vector(std::size_t capacity) :capacity(capacity), size(0) { elems = new T[capacity]; } template<class T> Vector<T>::Vector(const Vector<T>& vec) :capacity(vec.Capacity()), size(vec.Size()) { elems = new T[capacity]; for (std::size_t i = 0; i < vec.Size(); i++) elems[i] = vec[i]; } template<class T> Vector<T>::Vector(std::initializer_list<T> init_list) :capacity(init_list.size() + 5), size(init_list.size()) { int pos = 0; elems = new T[capacity]; for (const T& elem: init_list) elems[pos++] = elem; } template<class T> Vector<T>::~Vector() { delete[] elems; } template<class T> std::size_t Vector<T>::Size() const { return size; } template<class T> std::size_t Vector<T>::Capacity() const { return capacity; } template<class T> T& Vector<T>::Get(std::size_t pos) const { if (pos >= size || pos < 0) throw std::string("Index out of bounds!"); else return elems[pos]; } template<class T> T& Vector<T>::operator[](std::size_t pos) const { if (pos >= size || pos < 0) throw std::string("Index out of bounds!"); else return elems[pos]; } template<class T> Vector<T> Vector<T>::operator+(const Vector<T>& vec) const { //Vector<T> temp = this; // or ... = *this ? Vector<T> temp(capacity); for (std::size_t i = 0; i < size; i++) temp.Push(elems[i]); for (std::size_t i = 0; i < vec.Size(); i++) temp.Push(vec[i]); return temp; } template<class T> bool Vector<T>::operator==(const Vector<T>& vec) const { for (std::size_t i = 0; i < vec.Size(); i++) if (vec[i] != elems[i]) return false; return true; } template<class T> bool Vector<T>::operator!=(const Vector<T>& vec) const { return !operator==(vec); } template<class T> void Vector<T>::Push(const T& elem) { if ((size + 1) <= capacity) elems[size++] = elem; else { Allocate(); elems[size++] = elem; } } template<class T> void Vector<T>::Remove(const T& elem) { int pos = 0; bool isAvailable = false; for (std::size_t i = 0; i < size; i++) if (elem == elems[i]) { pos = i; isAvailable = true; break; } if (isAvailable) { T temp[size - 1]; for (std::size_t i = 0, j = 0; j < size; i++, j++) { if (j != pos) temp[i] = elems[j]; else { i--; continue; } } delete[] elems; elems = new T[--size]; for (std::size_t i = 0; i < size; i++) elems[i] = temp[i]; } } template<class T> void Vector<T>::Remove_At(std::size_t pos) { T temp[size - 1]; for (std::size_t i = 0, j = 0; j < size; i++, j++) { if (j != pos) temp[i] = elems[j]; else { i--; continue; } } delete[] elems; elems = new T[--size]; for (std::size_t i = 0; i < size; i++) elems[i] = temp[i]; } template<class T> void Vector<T>::Sort() const { std::sort(this->begin(), this->end()); } template<class T> std::vector<T> Vector<T>::ConvertTo_Std() const { std::vector<T> std_v; for (int i = 0; i < size; i++) std_v.push_back(elems[i]); return std_v; } template<class T> T* Vector<T>::begin() const { return &elems[0]; } template<class T> T* Vector<T>::end() const { return &elems[size]; } template<class T> void Vector<T>::Allocate() { T temp[capacity]; for (std::size_t i = 0; i < capacity; i++) temp[i] = elems[i]; delete[] elems; elems = new T[capacity * 2]; for (std::size_t i = 0; i < capacity; i++) elems[i] = temp[i]; capacity *= 2; } template<class U> std::ostream& operator<<(std::ostream& os, const Vector<U>& vec) { os << "{ "; for (std::size_t i = 0; i < vec.Size(); i++) { os << vec[i]; if (i < vec.Size() - 1) os << ", "; } os << " }"; return os; } template<class U> std::ostream& operator<<(std::ostream& os, const Vector<U*>& vec) { os << "{ "; for (std::size_t i = 0; i < vec.Size(); i++) { os << *vec[i]; if (i < vec.Size() - 1) os << ", "; } os << " }"; return os; }<file_sep>/Source/Library.cpp #include "Library.hpp" Library::Library() { loadBooks(); } void Library::addBook(const Book& book) { books.Push(book); updateBooks(); } bool Library::removeBook(const std::string& id) { if (index(id) >= 0) { books.Remove(books.Get(index(id))); updateBooks(); return true; } else return false; } bool Library::editBook(const std::string& id, const std::string& data, int which) { switch(which) { case 1: if (index(id) >= 0) { books.Get(index(id)).setName(data); updateBooks(); return true; } else return false; break; case 2: if (index(id) >= 0) { books.Get(index(id)).setAuthor(data); updateBooks(); return true; } else return false; break; case 3: if (index(id) >= 0) { books.Get(index(id)).setId(data); updateBooks(); return true; } else return false; break; case 4: if (index(id) >= 0) { books.Get(index(id)).setPublish_Date(Date(data)); updateBooks(); return true; } else return false; break; default: return false; break; } } Book Library::searchById(const std::string& id) const { if (index(id) >= 0) return books.Get(index(id)); else return Book(); } void Library::searchByAuthor(const std::string& author) const { for (const Book& book: books) if (string_lower(book.getAuthor()) == string_lower(author)) std::cout << book << std::endl; } Vector<Book> Library::getBooks() const { return books; } Book Library::getById(const std::string& id) const { for (const Book& book: books) if (book.getId() == id) return book; return Book(); } bool Library::isIdValid(const std::string& id) const { for (const Book& book: books) if (book.getId() == id) return true; return false; } void Library::loadBooks() { std::fstream file("Data/Books.txt", std::ios::in); std::string infos[4]; std::string data; while (!file.eof()) { std::getline(file, data); if (data == "BEGIN") { std::getline(file, infos[0]); std::getline(file, infos[1]); std::getline(file, infos[2]); std::getline(file, infos[3]); for (std::string& info: infos) if (isspace(info[info.size() - 1])) info.pop_back(); books.Push(Book(infos[0], infos[1], infos[2], Date(infos[3]))); } } file.close(); } void Library::updateBooks() const { std::fstream file("Data/Books.txt", std::ios::out); for (const Book& book: books) { file << "BEGIN" << std::endl; file << book.getName() << std::endl << book.getAuthor() << std::endl << book.getId() << std::endl << book.getPublish_Date() << std::endl; file << "END" << std::endl; } file.close(); } int Library::index(const std::string& id) const { for (int i = 0; i < books.Size(); i++) if (books.Get(i).getId() == id) return i; return -1; } std::string Library::string_lower(const std::string& str) const { std::string temp = str; for (char& letter: temp) letter = tolower(letter); return temp; }<file_sep>/Source/Book.hpp #ifndef BOOK_HPP #define BOOK_HPP #include "Date.hpp" class Book { private: std::string name; std::string author; std::string id; Date publish_date; public: Book(); Book(const std::string& name, const std::string& author, const std::string& id, Date publish_date); Book(const Book& book); void setName(const std::string& name); void setAuthor(const std::string& author); void setId(const std::string& id); void setPublish_Date(const Date& publish_date); std::string getName() const; std::string getAuthor() const; std::string getId() const; Date getPublish_Date() const; bool operator==(const Book& book) const; public: friend std::ostream& operator<<(std::ostream& os, const Book& book); }; #endif<file_sep>/Source/Date.hpp #ifndef DATE_HPP #define DATE_HPP #include <iostream> #include <algorithm> #include <ctime> class Date { private: std::string date; public: Date(); Date(const std::string& date); Date(const Date& date); void setDate(const std::string& date); std::string getDay() const; std::string getMonth() const; std::string getYear() const; std::string asString() const; bool operator==(const Date& date) const; static std::string Now(); public: friend std::ostream& operator<<(std::ostream& os, const Date& date); }; #endif<file_sep>/Source/Automation.hpp #ifndef AUTOMATION_HPP #define AUTOMATION_HPP #include "Library.hpp" #include "RequestStream.hpp" class Automation { public: static void Begin(); private: static void FirstScreen(); static void MainScreenAdmin(); static void MainScreenUser(); static void SignIn(); static void SignUp(); static void Exit(); static void AddBook(); static void RemoveBook(); static void EditBook(); static void Answer(); static void SearchById(); static void SearchByAuthor(); static void ListBooks(); static void ListRequests(); static void ListLentBooks(); static void RequestBook(); static void ReturnBook(); static void ReturnAllBooks(); static void ListRequestedBooks(); static void ListBorrowedBooks(); static void ListLibrary(); static void LogOut(); static void AlterStateAs(const std::string& state); static void SetCurrentUser(const std::string& username); static std::string GetCurrentState(); static std::string GetCurrentUser(); static Vector<std::string> FirstScreenOptions(); static Vector<std::string> MainScreenOptionsFor_Admin(); static Vector<std::string> MainScreenOptionsFor_User(); private: static void delete_request_from_requests_by_id(const std::string& id); static std::string get_requester_by_id(const std::string& id); static bool is_username_unique(const std::string& username); static int is_password_appropriate(const std::string& password); static std::string string_lower(const std::string& str); }; #endif <file_sep>/Source/Library.hpp #ifndef LIBRARY_HPP #define LIBRARY_HPP #include <fstream> #include "Book.hpp" #include "Vector.hpp" class Library { private: Vector<Book> books; public: Library(); void addBook(const Book& book); bool removeBook(const std::string& id); bool editBook(const std::string& id, const std::string& data, int which); Book searchById(const std::string& id) const; void searchByAuthor(const std::string& author) const; Vector<Book> getBooks() const; Book getById(const std::string& id) const; bool isIdValid(const std::string& id) const; private: void loadBooks(); void updateBooks() const; int index(const std::string& id) const; std::string string_lower(const std::string& str) const; }; #endif
addefdafae7d54dfd7fad4f4a3f447e4aee4dbfe
[ "C++" ]
13
C++
iwannabespace/LibraryAutomation
90261312a7493f41016cc983a8096529512f25e2
cb6df1a706746477ac59e52d4a6d914ca208c9cb
refs/heads/main
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Weightlessness : MonoBehaviour { private Rigidbody rigidbody; private void Start() { rigidbody = GetComponent<Rigidbody>(); } private void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "ZeroGravityArea") { rigidbody.useGravity = false; } } private void OnTriggerExit(Collider other) { if (other.gameObject.tag == "ZeroGravityArea") { rigidbody.useGravity = true; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GoldCycle : MonoBehaviour { [SerializeField] private Text goldPerCycleText; [SerializeField] private Text goldCountText; [SerializeField] private UnitsScript Archangel; private Image Plug; private AudioSource Sound; public int goldMiningFactor; private int goldPerCycle; private float mining—ycleTime; public float Mining—ycleTime { set { mining—ycleTime = value; } } private int goldCount; public int GoldCount { set { goldCount = value; } get { return goldCount; } } private float currentTimeOn—ycle; public int CurrentTimeOn—ycle { set { currentTimeOn—ycle = value; } } void Start() { Plug = GetComponent<Image>(); Sound = GetComponent<AudioSource>(); } void Update() { goldPerCycle = goldMiningFactor * Archangel.Count; goldPerCycleText.text = goldPerCycle.ToString(); currentTimeOn—ycle += Time.deltaTime; if (currentTimeOn—ycle >= mining—ycleTime) { Sound.Play(); currentTimeOn—ycle = 0; goldCount = Mathf.Clamp((goldCount + goldPerCycle), 0, 9999); } goldCountText.text = goldCount.ToString(); Plug.fillAmount = currentTimeOn—ycle / mining—ycleTime; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UnitsScript : MonoBehaviour { [SerializeField] private Text unitsBar; [SerializeField] private RecruitingSctipt setMaxBool; public int[] CountMax = new int[4]; private int count; public int Count { set { count = value; } get { return count; } } private int townGradeForUnitsCount; public int TownGradeForUnitsCount { set { townGradeForUnitsCount = value; } get { return townGradeForUnitsCount; } } void Update() { if (Count == CountMax[TownGradeForUnitsCount]) { setMaxBool.MaxCount = true; } else { setMaxBool.MaxCount = false; } Count = Mathf.Clamp(Count, -1, CountMax[TownGradeForUnitsCount]); unitsBar.text = Count.ToString() + "/" + CountMax[TownGradeForUnitsCount].ToString(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RaidCycle : MonoBehaviour { [SerializeField] private Text enemiesCountText; [SerializeField] private UnitsScript Knights; private Image Plug; private AudioSource Sound; public int raidsDifficulty; private int safeCycles; public int SafeCycles { set { safeCycles = value; } get { return safeCycles; } } private float raid—ycleTime; public float Raid—ycleTime { set { raid—ycleTime = value; } } private int enemiesCount; public int EnemiesCount { set { enemiesCount = value; } get { return enemiesCount; } } private int raidsCount; public int RaidsCount { set { raidsCount = value; } get { return raidsCount; } } private float currentTimeOn—ycle; public float CurrentTimeOn—ycle { set { currentTimeOn—ycle = value; } } void Start() { Plug = GetComponent<Image>(); Sound = GetComponent<AudioSource>(); } void Update() { if (raidsCount < safeCycles) { enemiesCount = 0; } else { if (enemiesCount == 0) { enemiesCount = Random.Range(1, 6); } } enemiesCountText.text = enemiesCount.ToString(); currentTimeOn—ycle += Time.deltaTime; if (currentTimeOn—ycle >= raid—ycleTime) { if (enemiesCount != 0) { Sound.Play(); } Knights.Count -= enemiesCount; currentTimeOn—ycle = 0; enemiesCount = (int)Mathf.Round(++raidsCount / raidsDifficulty) * Random.Range(1, 6); } Plug.fillAmount = currentTimeOn—ycle / raid—ycleTime; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RelayRunner : MonoBehaviour { public float passDistance; [SerializeField] private Transform nextRunner; [SerializeField] private RelayRunner nextOnRunning; private Transform currentRunner; private bool run; public bool Run { set { run = value; } } void Start() { currentRunner = GetComponent<Transform>(); } void Update() { if (run) { if (Vector3.Distance(currentRunner.position, nextRunner.position) > passDistance) { currentRunner.LookAt(nextRunner.position); currentRunner.position = Vector3.MoveTowards(currentRunner.position, nextRunner.position, Time.deltaTime); } else { run = false; nextOnRunning.Run = true; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SuperCubeStriker : MonoBehaviour { [SerializeField] private float strikeForce; [SerializeField] private float moveToX; [SerializeField] private float moveToY; [SerializeField] private float moveToZ; private Transform transform; private Rigidbody rigidbody; void Start() { transform = GetComponent<Transform>(); rigidbody = GetComponent<Rigidbody>(); } private void FixedUpdate() { Vector3 movementVector = new Vector3(moveToX, moveToY, moveToZ); rigidbody.velocity = movementVector; } private void OnCollisionEnter(Collision target) { Vector3 strikeVector = (target.gameObject.transform.position - transform.position) * strikeForce; target.gameObject.GetComponent<Rigidbody>().AddForce(strikeVector, ForceMode.Impulse); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MainScript : MonoBehaviour { public Text firstPinStatus; private int firstPin = 0; public Text secondPinStatus; private int secondPin = 0; public Text thirdPinStatus; private int thirdPin = 0; private int gameDifficult = -1; private int playerTry = 30; [SerializeField] private GameObject firstScreen; [SerializeField] private GameObject secondScreen; private GameObject currentScreen; void Start() { firstScreen.SetActive(true); currentScreen = firstScreen; } // Update is called once per frame void Update() { if ( gameDifficult == -1) { return; } TimerScript.ActivateTimer(TimerScript.timeLimitOnDifficult); if (timer < 0) { onGameOver("Вы проиграли. Попробуйте еще раз!"); } if (playerTry == 0) { onGameOver("Вы проиграли. Попробуйте еще раз!"); } if ( (firstPin == 5) & (secondPin == 5) & (thirdPin == 5) ) { onGameOver("Вы выиграли! Попробуйте еще раз!"); } } public void ChangeState(GameObject state) { if (currentScreen != null) { currentScreen.SetActive(false); state.SetActive(true); currentScreen = state; } } private void onGeneratePinsValues() { firstPin = Random.Range(0, 10) + 1; secondPin = Random.Range(0, 10) + 1; thirdPin = Random.Range(0, 10) + 1; while (firstPin == 5) { firstPin = Random.Range(0, 10) + 1; } while (secondPin == 5) { secondPin = Random.Range(0, 10) + 1; } while (thirdPin == 5) { thirdPin = Random.Range(0, 10) + 1; } firstPinStatus.text = firstPin.ToString(); secondPinStatus.text = secondPin.ToString(); thirdPinStatus.text = thirdPin.ToString(); } private void onUseTool(int firstPoint, int secondPoint, int thirdPoint) { firstPin += firstPoint; if (firstPin > 10) { firstPin = 10; } if (firstPin < 1) { firstPin = 1; } firstPinStatus.text = firstPin.ToString(); secondPin += secondPoint; if (secondPin > 10) { secondPin = 10; } if (secondPin < 1) { secondPin = 1; } secondPinStatus.text = secondPin.ToString(); thirdPin += thirdPoint; if (thirdPin > 10) { thirdPin = 10; } if (thirdPin < 1) { thirdPin = 1; } thirdPinStatus.text = thirdPin.ToString(); if (gameDifficult == 1) { tryCounter.text = "Количество попыток: " + (--playerTry).ToString(); } } public void onUsePicklock() { onUseTool(1, -1, 0); } public void onUseProbe() { onUseTool(-1, 2, -1); } public void onUseHammer() { onUseTool(-1, 1, 1); } public void StartNewGame(int difficult, int limit) { onGeneratePinsValues() ; TimerScript.passTimer = Time.time; gameDifficult = difficult; timeLimitOnDifficult = limit; } private void onGameOver(string finalText) { gameDifficult = -1; playerTry = 30; ChangeState(firstScreen); gameResult.text = finalText; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TownGradeScript : MonoBehaviour { [SerializeField] private Text buttonText; [SerializeField] private Image buildingImage; [SerializeField] private Button buildingButton; [SerializeField] private GameObject buttonAsObject; [SerializeField] private Sprite[] townViewImage = new Sprite[4]; [SerializeField] private UnitsScript archangelsMax; [SerializeField] private UnitsScript knightsMax; [SerializeField] private GoldCycle playersGolds; private Image Plug; private AudioSource Sound; public int[] townGardeCost = new int[4]; public string buildingText; private int currentGarde; public int CurrentGarde { set { currentGarde = value; } get { return currentGarde; } } private float building—ycleTime; public float Building—ycleTime { set { building—ycleTime = value; } } private float currentTimeOn—ycle; public float CurrentTimeOn—ycle { set { currentTimeOn—ycle = value; } } private bool onProcess; public bool OnProcess { set { onProcess = value; } } void Start() { Plug = GetComponent<Image>(); Sound = GetComponent<AudioSource>(); } void Update() { if (onProcess) { buildingButton.interactable = false; currentTimeOn—ycle += Time.deltaTime; Plug.fillAmount = currentTimeOn—ycle / building—ycleTime; if (currentTimeOn—ycle >= building—ycleTime) { ++currentGarde; archangelsMax.TownGradeForUnitsCount = currentGarde; knightsMax.TownGradeForUnitsCount = currentGarde; currentTimeOn—ycle = 0; onProcess = false; Plug.fillAmount = 0; } } else { buttonText.text = buildingText + townGardeCost[currentGarde].ToString(); buildingImage.sprite = townViewImage[currentGarde]; if (currentGarde == ( townGardeCost.Length - 1)) { buttonAsObject.SetActive(false); return; } if (playersGolds.GoldCount >= townGardeCost[currentGarde]) { buildingButton.interactable = true; } else { buildingButton.interactable = false; } Plug.fillAmount = 0; } } public void OnBuilding() { onProcess = true; Sound.Play(); playersGolds.GoldCount -= townGardeCost[currentGarde]; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MainScript : MonoBehaviour { [SerializeField] private Text purposesGoldText; [SerializeField] private Text purposesGradeText; [SerializeField] private Text purposesArchangelCountText; [SerializeField] private Text purposesKnightCountCountText; [SerializeField] private Text purposesDefenseRaid; [SerializeField] private Image gameoverBackground; [SerializeField] private Sprite winSprite; [SerializeField] private Sprite loseSprite; [SerializeField] private AudioSource winSound; [SerializeField] private AudioSource loseSound; [SerializeField] private GameObject GameScreen; [SerializeField] private GameObject EndGameScreen; [SerializeField] private Text titleText; [SerializeField] private Text resultGoldText; [SerializeField] private Text resultGradeText; [SerializeField] private Text resultRaidsText; [SerializeField] private GoldCycle Gold; [SerializeField] private TownGradeScript TownGrade; [SerializeField] private UnitsScript Archangels; [SerializeField] private UnitsScript Knights; [SerializeField] private RaidCycle Raids; [SerializeField] private RecruitingSctipt ArchangelRecruiting; [SerializeField] private RecruitingSctipt KnightRecruiting; private int goldToWin; public int GoldToWin { set { goldToWin = value; } get { return goldToWin; } } private int townGradeToWin; public int TownGradeToWin { set { townGradeToWin = value; } get { return townGradeToWin; } } private int archangelCountToWin; public int ArchangelCountToWin { set { archangelCountToWin = value; } get { return archangelCountToWin; } } private int knightCountToWin; public int KnightCountToWin { set { knightCountToWin = value; } get { return knightCountToWin; } } private int raidArrivesToWin; public int RaidArrivesToWin { set { raidArrivesToWin = value; } get { return raidArrivesToWin; } } private bool onPlay; public bool OnPlay { set { onPlay = value; } get { return onPlay; } } void Start() { Time.timeScale = 0; } void Update() { if (onPlay == false) { return; } if (Knights.Count < 0) { GameOver(false); return; } else { if ((Gold.GoldCount >= goldToWin) & (TownGrade.CurrentGarde >= townGradeToWin) & (Archangels.Count >= ArchangelCountToWin) & (Knights.Count >= KnightCountToWin) & ((Raids.RaidsCount - Raids.SafeCycles) >= raidArrivesToWin)) { GameOver(true); return; } } } public void OnPause() { Time.timeScale = 0; purposesGoldText.text = Gold.GoldCount.ToString() + " / " + goldToWin.ToString(); purposesGradeText.text = TownGrade.CurrentGarde.ToString() + " / " + townGradeToWin.ToString(); purposesArchangelCountText.text = Archangels.Count.ToString() + " / " + ArchangelCountToWin.ToString(); purposesKnightCountCountText.text = Knights.Count.ToString() + " / " + KnightCountToWin.ToString(); purposesDefenseRaid.text = Mathf.Clamp((Raids.RaidsCount - Raids.SafeCycles), 0, Raids.RaidsCount).ToString() + " / " + raidArrivesToWin.ToString(); } public void On—ontinue() { Time.timeScale = 1; } public void GameOver(bool win) { Time.timeScale = 0; GameScreen.SetActive(false); EndGameScreen.SetActive(true); if (win) { winSound.Play(); gameoverBackground.sprite = winSprite; titleText.text = "¬Ż ÔÓŠŚšŤŽŤ!"; resultRaidsText.text = Mathf.Clamp((Raids.RaidsCount - Raids.SafeCycles), 0, Raids.RaidsCount).ToString(); } else { loseSound.Play(); gameoverBackground.sprite = loseSprite; titleText.text = "¬Ż ÔūÓŤ„ūŗŽŤ!"; resultRaidsText.text = Mathf.Clamp((Raids.RaidsCount - Raids.SafeCycles - 1), 0 , Raids.RaidsCount).ToString(); } resultGoldText.text = Gold.GoldCount.ToString(); resultGradeText.text = TownGrade.CurrentGarde.ToString(); Raids.RaidsCount = 0; ArchangelRecruiting.CurrentTimeOn—ycle = 0; ArchangelRecruiting.OnProcess = false; KnightRecruiting.CurrentTimeOn—ycle = 0; KnightRecruiting.OnProcess = false; TownGrade.CurrentTimeOn—ycle = 0; TownGrade.OnProcess = false; Gold.CurrentTimeOn—ycle = 0; Raids.CurrentTimeOn—ycle = 0; onPlay = false; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Factorial : MonoBehaviour { [SerializeField] private InputField numb; [SerializeField] private Text resultText; private long p = 1; private int i = 0; private int n = 0; private string factStr = ""; public void onFact() { if (int.TryParse(numb.text, out i)) { if (i == 0) { resultText.text = "0! = 1"; //Debug.Log("0! = 1"); return; } if (i < 0) { resultText.text = $"{i}! = \u221E"; //Debug.Log($"{i}! = \u221E"); return; } while (n != i) { p *= ++n; //Debug.Log(p); } resultText.text = $"{i}! = {p.ToString()}"; } else { resultText.text = "Введите целое число!"; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EasyModeButtonScript : MonoBehaviour { public void EasyMode() { MainScript.StartNewGame(0, 180); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Jumper : MonoBehaviour { [SerializeField] private float zone; [SerializeField] private float timeToJump; [SerializeField] private float jumpForce; [SerializeField] private LayerMask layer; private float currentTime; private void Start() { currentTime = timeToJump; } private void Update() { Collider[] colliders = Physics.OverlapSphere(transform.position, zone, layer); if (colliders.Length != 0) { currentTime -= Time.deltaTime; if (currentTime <= 0) { foreach (Collider collider in colliders) { collider.gameObject.GetComponent<Rigidbody>().AddForce(0, jumpForce, 0, ForceMode.Impulse); } currentTime = timeToJump; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sample : MonoBehaviour { bool num; void Start() { Debug.Log(num); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class HardModeButtonScript : MonoBehaviour { public void HardMode() { MainScript.StartNewGame(1, 120); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class AverageModeButtonScript : MonoBehaviour { public void AverageMode() { MainScript.StartNewGame(0, 120); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class EvenNumb : MonoBehaviour { [SerializeField] private Text resultText; private string numbStr = ""; private int n = 0; public void onFindNumb() { for (n = 2; n < 10; n+= 2) { //Debug.Log(n); numbStr += n.ToString() + " "; } resultText.text = numbStr; numbStr = ""; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Start : MonoBehaviour { [SerializeField] private RelayRunner firstRunner; public void OnStart() { firstRunner.Run = true; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class StartGameScript : MonoBehaviour { [SerializeField] private Slider startGold; [SerializeField] private Slider startTownGrade; [SerializeField] private Slider startArchangelCount; [SerializeField] private Slider startKnightCount; [SerializeField] private Slider recruiting—ycle; [SerializeField] private Slider mining—ycle; [SerializeField] private Slider raid—ycle; [SerializeField] private Slider safe—ycle; [SerializeField] private Slider goldToWin; [SerializeField] private Slider townGradeToWin; [SerializeField] private Slider archangelCountToWin; [SerializeField] private Slider knightCountToWin; [SerializeField] private Slider raidsArrived; [SerializeField] private GoldCycle goldStatus; [SerializeField] private RaidCycle raidStatus; [SerializeField] private UnitsScript Archangels; [SerializeField] private UnitsScript Knights; [SerializeField] private TownGradeScript TownGrade; [SerializeField] private RecruitingSctipt RecruitingOne; [SerializeField] private RecruitingSctipt RecruitingTwo; [SerializeField] private MainScript Purposes; public void StartNewGame() { Time.timeScale = 1; Purposes.OnPlay = true; goldStatus.Mining—ycleTime = mining—ycle.value; goldStatus.GoldCount = (int)startGold.value; raidStatus.Raid—ycleTime = raid—ycle.value; raidStatus.SafeCycles = (int)safe—ycle.value; Archangels.Count = (int)startArchangelCount.value; Archangels.TownGradeForUnitsCount = (int)startTownGrade.value; Knights.Count = (int)startKnightCount.value; Knights.TownGradeForUnitsCount = (int)startTownGrade.value; TownGrade.CurrentGarde = (int)startTownGrade.value; RecruitingOne.Recruiting—ycleTime = recruiting—ycle.value; RecruitingTwo.Recruiting—ycleTime = recruiting—ycle.value; TownGrade.Building—ycleTime = recruiting—ycle.value; Purposes.GoldToWin = (int)goldToWin.value; Purposes.TownGradeToWin = (int)townGradeToWin.value; Purposes.ArchangelCountToWin = (int)archangelCountToWin.value; Purposes.KnightCountToWin = (int)knightCountToWin.value; Purposes.RaidArrivesToWin = (int)raidsArrived.value; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Multiplication : MonoBehaviour { [SerializeField] private Text resultText; private int[,] mult = new int[11, 11]; private string multStr = ""; private int n = 0; private int m = 0; public void onMultiply() { for (n = 1; n < 11; ++n) { for (m = 1; m < 11; ++m) { mult[n, m] = n * m; //Debug.Log($"{n} x {m} = {mult[n, m]}"); multStr += $"{n} x {m} = {mult[n, m]} \r | \r"; } multStr += "\n *** \n"; } resultText.text = multStr; multStr = ""; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RecruitingSctipt : MonoBehaviour { [SerializeField] private RecruitingSctipt otherRecruiting; [SerializeField] private Text buttonText; [SerializeField] private Button recruitingButton; [SerializeField] private Image recruitingStatus; [SerializeField] private UnitsScript Unit; [SerializeField] private GoldCycle playersGolds; public int unitsCost; public string recruitingText; private AudioSource Sound; private bool maxCount = false; public bool MaxCount { set { maxCount = value; } } private float recruiting—ycleTime; public float Recruiting—ycleTime { set { recruiting—ycleTime = value; } } private float currentTimeOn—ycle; public float CurrentTimeOn—ycle { set { currentTimeOn—ycle = value; } } private bool onProcess; public bool OnProcess { set { onProcess = value; } } void Start() { buttonText.text = recruitingText + unitsCost.ToString(); Sound = GetComponent<AudioSource>(); } public void OnRecruiting() { onProcess = true; playersGolds.GoldCount -= unitsCost; } void Update() { if (maxCount) { recruitingButton.interactable = false; return; } if (onProcess) { recruitingButton.interactable = false; currentTimeOn—ycle += Time.deltaTime; recruitingStatus.fillAmount = currentTimeOn—ycle / recruiting—ycleTime; if (currentTimeOn—ycle >= recruiting—ycleTime) { Sound.Play(); ++Unit.Count; currentTimeOn—ycle = 0; onProcess = false; recruitingStatus.fillAmount = 0; } } else { if ((playersGolds.GoldCount >= unitsCost) & (otherRecruiting.onProcess == false)) { recruitingButton.interactable = true; } else { recruitingButton.interactable = false; } recruitingStatus.fillAmount = 0; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class MainScript : MonoBehaviour { [SerializeField] private GameObject firstScreen; [SerializeField] private GameObject secondScreen; [SerializeField] private InputField answField_1; [SerializeField] private InputField answField_2; [SerializeField] private InputField answField_3; [SerializeField] private InputField answField_4; [SerializeField] private InputField answField_5; [SerializeField] private InputField answField_6; [SerializeField] private InputField answField_7; [SerializeField] private InputField answField_8; [SerializeField] private InputField answField_9; [SerializeField] private InputField answField_10; [SerializeField] private Text ResultText; private GameObject currentScreen; int Q_nunber = 0; int Right = 0; int Fall = 0; void Start() { firstScreen.SetActive(true); currentScreen = firstScreen; } public void ChangeState(GameObject state) { if (currentScreen != null) { currentScreen.SetActive(false); state.SetActive(true); currentScreen = state; } } public void Answer() { ++Q_nunber; switch (Q_nunber) { case 1: if (answField_1.text == "Берлин") { ++Right; break; } else { ++Fall; break; } case 2: if ((answField_2.text == "Джоуль") ^ (answField_2.text == "Джоули") ^ (answField_2.text == "Дж")) { ++Right; break; } else { ++Fall; break; } case 3: if (answField_3.text == "Серебро") { ++Right; break; } else { ++Fall; break; } case 4: if (answField_4.text == "Амазонка") { ++Right; break; } else { ++Fall; break; } case 5: if (answField_5.text == "Хлорофилл") { ++Right; break; } else { ++Fall; break; } case 6: if ((answField_6.text == "Колибри") ^ (answField_6.text == "Колибри-пчёлка") ^ (answField_6.text == "Колибри-пчелка")) { ++Right; break; } else { ++Fall; break; } case 7: if ((answField_7.text == "3") ^ (answField_7.text == "Третьей") ^ (answField_7.text == "Третей")) { ++Right; break; } else { ++Fall; break; } case 8: if ((answField_8.text == "Скорости") ^ (answField_8.text == "Скорость")) { ++Right; break; } else { ++Fall; break; } case 9: if ((answField_9.text == "46") ^ (answField_9.text == "Сорок шесть")) { ++Right; break; } else { ++Fall; break; } case 10: if ((answField_10.text == "3") ^ (answField_10.text == "Три")) { ++Right; break; } else { ++Fall; break; } default: break; } } public void ShowRes() { ResultText.text = $"Правильных ответов: {Right.ToString()} \nНеправильных ответов: {Fall.ToString()}"; answField_1.text = ""; answField_2.text = ""; answField_3.text = ""; answField_4.text = ""; answField_5.text = ""; answField_6.text = ""; answField_7.text = ""; answField_8.text = ""; answField_9.text = ""; answField_10.text = ""; Q_nunber = 0; Right = 0; Fall = 0; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TimerScript : MonoBehaviour { public Text timerText; public Text gameResult; public Text tryCounter; public float timer = 0.00f; public float passTimer = 0.00f; public float timeLimitOnDifficult = 0.00f; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void ActivateTimer(float timeLimit) { timer = timeLimit - (Time.time - passTimer); timerText.text = "Таймер: " + Mathf.Round(timer).ToString(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class FirstStrike : MonoBehaviour { private void Start() { GetComponent<Rigidbody>().AddForce(-220, 0, 0, ForceMode.Impulse); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Explosion : MonoBehaviour { [SerializeField] private float explosionForce; [SerializeField] private float timeToExplosion; [SerializeField] private float radius; private AudioSource boomSound; private void Start() { boomSound = GetComponent<AudioSource>(); } private void Update() { timeToExplosion -= Time.deltaTime; if (timeToExplosion <= 0) { Boom(); timeToExplosion = 10; } } private void Boom() { Rigidbody[] blocks = FindObjectsOfType<Rigidbody>(); foreach (Rigidbody block in blocks) { float calculate = Vector3.Distance(transform.position, block.transform.position); if (calculate < radius) { Vector3 direction = block.transform.position - transform.position; block.AddForce(direction.normalized * explosionForce * (radius - calculate), ForceMode.Impulse); boomSound.Play(); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TextUpdater : MonoBehaviour { [SerializeField] private Text textElement; private Slider customizeElement; void Start() { customizeElement = GetComponent<Slider>(); } void Update() { textElement.text = customizeElement.value.ToString(); } }
3e8bf5641a89f1e281d03e517b3956c26e67290f
[ "C#" ]
25
C#
HonestsGames/Unity-Projects
2273cecc798b29bfdd350a39b32ef388925d9310
ac0ea4b5408f0672e8bd860c12eeef9ebde16354
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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise35 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ double xn = 1; double x = Double.parseDouble(JOptionPane.showInputDialog("Enter X: ")); int n = Integer.parseInt(JOptionPane.showInputDialog("Enter N: ")); if (n<=0){ JOptionPane.showMessageDialog(null,"N must be a positive integer."); } else{ for (int i = 0;i<n;i++){ xn = xn*x; } JOptionPane.showMessageDialog(null,x + " raised to the power " + n + " is: "+xn); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise04 { /** * @param args the command line arguments */ public static void main(String[] args) { //initialize the variables needed double sinx = 0.5236,cosx = 0.523,sum; //get the sine and cosine sinx = Math.sin(sinx); cosx = Math.cos(cosx); //gets the sum between cos2 and sin2 sum = Math.pow(sinx,2) + Math.pow(cosx,2); //prints the result JOptionPane.showMessageDialog(null,"Given the value: 0.5236\n" + "sine: " + sinx +"\n"+ "cosine: " + cosx +"\n"+ "sum: " + sum); } } <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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise40 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ double total,weight; System.out.println("Weight of Order: "); weight = Integer.parseInt(dataIn.readLine()); while(weight>0){ if(weight<=10){ total = 3.0; } else{ total = 3.0 +((weight-10)*0.25); } System.out.format("Shipping Cost:$%.2f",total); System.out.println("\nWeight of Order: "); weight = Integer.parseInt(dataIn.readLine()); } }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input! Try again."); } } } <file_sep># Java-Lab-Exercises Some Java Lab Excercises I did in school. For safekeeping purposes. <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 MaramotHLab1Activity01; /** * * @author <NAME> */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class MaramotHLab1Activity1Exercise13 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 13"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ //initializes the variables double armean; double harmean; //ask and reads the value of x and y System.out.println("Enter X: "); double x = Double.parseDouble(dataIn.readLine()); System.out.println("Enter Y: "); double y = Double.parseDouble(dataIn.readLine()); //Arithmetic Mean armean = (x + y)/2; //Harmonic Mean harmean = 2/(1/x + 1/y); //prints the result System.out.println("Arithmetic Mean: " + armean); System.out.println("Harmonic Mean: " + harmean); }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input. Try again."); } } }<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 activity102; /** * * @author <NAME> */ public class MaramotHLabAct102Exercise16 { /** * @param args the command line arguments */ public static void main(String[] args) { int[][] data = { {3, 2, 5}, {1, 4, 4, 8, 13}, {9, 1, 0, 2}, {0, 2, 6, 3, -1, -8} }; System.out.println("Exercise 16 --- Reversal of Elements in Each Row"); for ( int row=0; row < data.length; row++){ for ( int col=0; col < ((data[row].length)/2); col++){ int temp = data[row][col]; data[row][col]=data[row][data[row].length-1-col]; data[row][data[row].length-1-col]=temp; } } for ( int rows=0; rows < data.length; rows++){ for ( int cols=0; cols < data[rows].length; cols++) { System.out.print(data[rows][cols]+", "); } System.out.println(); } System.out.println(); } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise02 { /** * @param args the command line arguments */ public static void main(String[] args) { double[] value = new double [3]; double x[] = {0.0,2.0,4.0}; //when x = 0.0 value[0] = 3*(Math.pow(x[0],2))-8*x[0] + 4; //when x = 2.0 value[1] = 3*(Math.pow(x[1],2))-8*x[1] + 4; //when x = 4.0 value[2] = 3*(Math.pow(x[2],2))-8*x[2] + 4; /* The program takes the assigned value in variable x and substitutes it to the equation 3x^2 - 8x + 4 then prints the results */ JOptionPane.showMessageDialog(null,"Given: 3x^2-8x+4\n" + "At x = " + x[0] + ", the result is " +value[0] +"\n" + "At x = " + x[1] + ", the result is " +value[1] +"\n" + "At x = " + x[2] + ", the result is " +value[2]); } } <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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise21 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 21 --- Steam Engine Efficiency"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ //initializes the variable float efficiency; //gets the inputs needed System.out.println("Enter the air temperature: "); float Tair = Float.parseFloat(dataIn.readLine()); System.out.println("Enter the steam temperature: "); float Tsteam = Float.parseFloat(dataIn.readLine()); //if tsteam is less than 373K, no efficiency if(Tsteam<373){ efficiency = 0; System.out.println("Efficiency: " + efficiency); } else{ efficiency = 1 - Tair/Tsteam; System.out.println("Efficiency: " + efficiency); } }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input!Try again."); } } } <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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise33 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 33"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ float sum = 0,square = 0,avg,savg,avgSquare,SD; System.out.println("How many numbers of N are to follow: "); int N = Integer.parseInt(dataIn.readLine()); float[] n = new float [N]; for(int i = 0;i<N;i++){ System.out.println("Enter an integer: "); n[i] = Float.parseFloat(dataIn.readLine()); sum = sum + n[i]; square = square + n[i]*n[i]; } avg = sum/N; savg = (float) Math.pow(avg,2); avgSquare = square/N; SD = (float) Math.sqrt(avgSquare - savg); System.out.println("Standard Deviation is: "+SD); }catch(IOException | NumberFormatException | ArithmeticException e){ System.out.println("Invalid Input! Try again."); } } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise17 { /** * @param args the command line arguments */ public static void main(String[] args){ try{ //ask for the weight int cpounds = Integer.parseInt(JOptionPane.showInputDialog("Enter your pounds: ")); //checks whether the weight is qualified for heavyweight if(cpounds>=220 && cpounds<=280){ JOptionPane.showMessageDialog(null,"Your'e allowed in the contest!"); } else{ JOptionPane.showMessageDialog(null,"You're not allowed in the contest!"); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } }<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 activity102; /** * * @author <NAME> */ public class MaramotHLabAct102Exercise05 { /** * @param args the command line arguments */ public static void main ( String[] args ) { int[] val = {0, 1, 2, 3}; int temp; System.out.println("Exercise 5 --- Reverse Order"); System.out.println( "Original Array: " + val[0] + " " + val[1] + " " + val[2] + " " + val[3] ); temp = val[3]; val[3] = val[0]; val[0] = temp; temp = val[1]; val[1] = val[2]; val[2] = temp; System.out.println( "Reversed Array: " + val[0] + " " + val[1] + " " + val[2] + " " + val[3] ); } } <file_sep>compile.on.save=true user.properties.file=C:\\Users\\HAZEL\\AppData\\Roaming\\NetBeans\\8.0\\build.properties <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise08 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ //asks for the value of change int cents = Integer.parseInt(JOptionPane.showInputDialog("Enter the value of change: ")); //if change is less than or equal to zero, invalid input if(cents<=0){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } //takes the value of dollars and puts the remainder in cents int dollars = cents/100; cents = cents%100; //takes the value of quarters and puts the remainder in cents int quarters = cents/25; cents = cents%25; //takes the value of dime and puts the remainder in cents int dime = cents/10; cents = cents%10; //takes the value of nickels and puts the remainder in cents int nickel = cents/5; cents = cents%5; //prints the results JOptionPane.showMessageDialog(null,"Your change is: " + dollars + " dollar " + quarters + " quarters " + dime + " dime " + nickel +" nickel and " + cents +" cents." ); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } }<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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise39 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ int exit = 1,sumout=0,sumin=0,num; int low = Integer.parseInt(JOptionPane.showInputDialog("In-range Adder\n" + "Low end of range: ")); int high = Integer.parseInt(JOptionPane.showInputDialog("High end of range: ")); while(exit == 1){ num = Integer.parseInt(JOptionPane.showInputDialog("Enter data: ")); if(num>=low && num<=high){ sumin = sumin + num; } else{ sumout = sumout + num; } if(num == 0){ JOptionPane.showMessageDialog(null,"Sum of in range values: "+sumin + "\nSum of out of range values: "+ sumout); System.exit(0); } } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise18 { /** * @param args the command line arguments */ public static void main(String[] args){ try{ //initializes the variables double packa; double packb; //asks for prices and percent double pricea = Double.parseDouble(JOptionPane.showInputDialog("Price per pound package A: ")); double percenta = Double.parseDouble(JOptionPane.showInputDialog("Percent lean package A: ")); double priceb = Double.parseDouble(JOptionPane.showInputDialog("Price per pound package B: ")); double percentb = Double.parseDouble(JOptionPane.showInputDialog("Percent lean package B: ")); //takes the prices for pack a and b packa = pricea/(percenta*0.01); packb = priceb/(percentb*0.01); //prints the prices JOptionPane.showMessageDialog(null,"Package A cost per pound of lean: " + packa +"\nPackage B cost per pound of lean: " + packb); //comparison between pack a and b if (packa<packb && packa != packb){ JOptionPane.showMessageDialog(null,"Package A is the best value"); } else if (packa>packb && packa != packb){ JOptionPane.showMessageDialog(null,"Package B is the best value"); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> */ public class MaramotHLab1Activity1Exercise41 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ int width,height,area,exit=1; System.out.println("Computer Aided Design Program"); while(exit==1){ System.out.println("First corner X coordinate: "); int x1 = Integer.parseInt(dataIn.readLine()); System.out.println("First corner Y coordinate: "); int y1 = Integer.parseInt(dataIn.readLine()); System.out.println("Second corner X coordinate: "); int x2 = Integer.parseInt(dataIn.readLine()); System.out.println("Second corner Y coordinate: "); int y2 = Integer.parseInt(dataIn.readLine()); width = Math.abs(x1-x2); height = Math.abs(y1-y2); area = width*height; System.out.println("Width: " + width + " Height: " + height + " Area: " + area); if(width == 0 || height == 0){ System.exit(0); } } }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input! Try again."); } } } <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 MaramotHLab1Activity01; /** * * @author <NAME> */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class MaramotHLab1Activity1Exercise12 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 12"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ //initializes the logarithm double loga; //asks and reads the inputs System.out.println("Enter a double: "); double x = Double.parseDouble(dataIn.readLine()); //gets the logarithm loga = Math.log(x)/Math.log(2); //prints the results System.out.println("Base 2 log of " + x + " is " + loga ); }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input! Try again."); } } } <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 activity102; import java.io.IOException; import java.util.Arrays; /** * * @author <NAME> */ public class MaramotHLabAct102Exercise13 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main ( String[] args ) throws IOException{ int[][] data = { {3, 2, 5}, {1, 4, 4, 8, 13}, {9, 1, 0, 2}, {0, 2, 6, 3, -1, -8} }; int length = 0; System.out.println("Exercise 13 --- Sum of Each Column"); for (int row = 0; row < data.length; row++) { length = data[row].length; } int[] sums = new int[length]; Arrays.fill(sums, 0); for (int row = 0; row < data.length; row++) { for (int col = 0; col < data[row].length; col++) { sums[col] += data[row][col]; } } for (int i = 0; i < sums.length; i++) { System.out.println(sums[i]); } } }<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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise08 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 8 --- Correct Change"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ //asks for the value of change System.out.println("Enter the value of change: "); int cents = Integer.parseInt(dataIn.readLine()); //if change is less than or equal to zero, invalid input if(cents<=0){ System.out.println("Invalid Input! Try again."); } //takes the value of dollars and puts the remainder in cents int dollars = cents/100; cents = cents%100; //takes the value of quarters and puts the remainder in cents int quarters = cents/25; cents = cents%25; //takes the value of dime and puts the remainder in cents int dime = cents/10; cents = cents%10; //takes the value of nickels and puts the remainder in cents int nickel = cents/5; cents = cents%5; //prints the results System.out.println("Your change is: " + dollars + " dollar " + quarters + " quarters " + dime + " dime " + nickel +" nickel and " + cents +" cents." ); }catch(NumberFormatException e){ System.out.println("Invalid Input! Try again."); } } } <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 MaramotHLab1Activity01; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise37 { /** * @param args the command line arguments */ public static void main(String [] args) { //triangle for (int i=7;i>=0;i--) //determines the number of * to be printed { for (int k = 0; k <i; k++){ System.out.print(" "); //pine tree format } for (int j = 0;j!=(-2*i+(2*7+1));j++){ System.out.print("*"); //prints the * } System.out.println(""); } //square //for 4 spaces before the start of printing * System.out.print(" "); for(int i = 3; i <= 5; i++) { System.out.print("*"); } //for printing the next line System.out.println(""); //for 4 spaces before the start of printing * System.out.print(" "); //loop for printing the 3 * for(int i = 3; i <= 5; i++) { System.out.print("*"); } System.out.println(""); //for 4 spaces before the start of printing * System.out.print(" "); //loop for printing the 3 * for(int i = 3; i <= 5; i++) { System.out.print("*"); } System.out.println(""); } } <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 activity104; import java.awt.Component; import java.awt.HeadlessException; import javax.swing.*; /** * * @author <NAME> */ public class MaramotHAct104MyIfElse { /** * @param args the command line arguments */ public static void main(String[] args) { int q1, q2, q3, ave; try{ q1 = Integer.parseInt(JOptionPane.showInputDialog("Enter LQ1 : ")); q2 = Integer.parseInt(JOptionPane.showInputDialog("Enter LQ2 : ")); q3 = Integer.parseInt(JOptionPane.showInputDialog("Enter LQ3 : ")); ave = (q1+q2+q3)/3; String remarks; if(ave>=80 && ave<=100){ remarks ="Excellent"; }else if(ave>=60 && ave<80){ remarks = "Fail"; }else if(ave>=0 && ave<60){ remarks = "Fail"; }else{ remarks = "Illegal Grade"; } System.out.println("("+q1+" + "+q2+" + "+q3+" )/3 = "+ave); System.out.println(remarks); }catch(HeadlessException | NumberFormatException e){ JOptionPane.showMessageDialog(null,"Invalid Input!","Error!",JOptionPane.WARNING_MESSAGE); } } }<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 activity102; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab2Act102Exercise01 { /** * @param args the command line arguments */ public static void main ( String[] args ) { int sum; int[] val = {0, 1, 2, 3}; System.out.println("Exercise 1 --- Array Sum"); sum = val[0] + val[1] +val[2]; System.out.println( "Sum of all numbers = " + sum ); } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise11 { /** * @param args the command line arguments */ public static void main(String[] args){ try{ //initializes the variable double d; double g = 32.174; //ask for number of seconds double t = Double.parseDouble(JOptionPane.showInputDialog("Enter the number of seconds: ")); //gets the distance d = (g*Math.pow(t,2))/2; //prints the result JOptionPane.showMessageDialog(null,"Distance: " + d + " feet"); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise29 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ String inputString; int times; inputString = JOptionPane.showInputDialog("Enter a word: "); times = inputString.length(); for(int i = 0; i<times;i++){ System.out.println(inputString); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise14 { /** * @param args the command line arguments */ public static void main(String[] args){ try{ //asks for amount of purchases int cent = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount of purchases: ")); int discount; //checks whether the cent>100, a 10% discount will apply if (cent>1000){ discount = cent - (cent*10)/100; JOptionPane.showMessageDialog(null,"Discounted Price: " + discount); } //else, no discount else{ JOptionPane.showMessageDialog(null,"Discounted Price: 0"); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } }<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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise42 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); double bal = 1000, pay = 0, tpay = 0; int month = 0; double fpay; try{ System.out.println("Enter the monthly payments: "); pay = Double.parseDouble(dataIn.readLine()); }catch (IOException | NumberFormatException e) { System.out.println("Invalid Input! Try again."); } System.out.println(""); System.out.println("Begining Balance: "+bal); System.out.println("Monthly Interest: 1.25%"); System.out.println("Payment amount per month: "+pay+"\n"); bal = bal + (bal * (1.5 / 100)) - pay; while (bal > 0){ month++; tpay += pay; System.out.println("Month "+month+" \tbalance: "+bal+" \ttotal paymentss: "+tpay); bal = bal + (bal * (1.5 / 100)) - pay; } fpay= pay + bal; tpay += fpay; bal = 0; month++; System.out.println("Month "+month+" balance: "+bal+" total payments: "+tpay); System.out.println(); System.out.println("Final payments that will bring the balance to zero: "+fpay); } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise36 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ int nstar = Integer.parseInt(JOptionPane.showInputDialog("Initial number of stars: ")); for (int i = nstar; i >= 1; i--) { System.out.print("\n"); for (int a = 1; a <= i; a++) { System.out.print("*"); } } System.out.println(""); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise14 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 14 --- Discount Prices"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ //initializes the variables int discount; //asks for amount of purchases System.out.println("Enter the amount of purchases: "); int cent = Integer.parseInt(dataIn.readLine()); //checks whether the cent>100, a 10% discount will apply if (cent>1000){ discount = cent - cent*(10/100); System.out.println("Discounted Price: " + discount); } //else, no discount else{ System.out.println("Discounted Price: 0"); } }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input! Try again."); } } } <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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise31 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 31 --- Adding up Integers"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ int sum = 0; int no; System.out.println("How many integers will be added: "); no = Integer.parseInt(dataIn.readLine()); int[] integers = new int[no]; for(int i = 0; i<no;i++){ System.out.println("Enter an integer: "); integers[i] = Integer.parseInt(dataIn.readLine()); sum = sum + integers[i]; } System.out.println("The sum is " + sum); }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input! Try again."); } } } <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 activity104; import java.awt.HeadlessException; import javax.swing.*; /** * * @author <NAME> */ public class MaramotHAct104MyInput { /** * @param args the command line arguments */ public static void main(String[] args) { String name; try{ name = JOptionPane.showInputDialog("Enter name "); System.out.println("Hello "+name); String input; input = JOptionPane.showInputDialog("How old are you : "); int age, year; age = Integer.parseInt(input); year = 2019-age; System.out.println("You were born in "+year); }catch(HeadlessException | NumberFormatException e){ JOptionPane.showMessageDialog(null,"Invalid Input!","Error!",JOptionPane.WARNING_MESSAGE); } } }<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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise38 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ double miles, initial; System.out.println("Miles per Gallon Program"); System.out.println("Initial Miles: "); initial = Integer.parseInt(dataIn.readLine()); if(initial<=0){ System.out.println("bye"); } while (initial !=0){ System.out.println("Final Miles: "); double finals = Integer.parseInt(dataIn.readLine()); if(finals <= 0){ System.out.println("Invalid Input!Try again."); System.exit(0); } if(initial>finals){ System.out.println("Invalid Input!Try again."); System.exit(0); } System.out.println("Gallons: "); int gallons = Integer.parseInt(dataIn.readLine()); if(gallons <= 0){ System.out.println("Invalid Input!Try again."); System.exit(0); } miles = (finals - initial)/gallons; System.out.format("Miles per Gallon: %.1f",miles); System.out.println("\nInitial Miles: "); initial = Integer.parseInt(dataIn.readLine()); if(initial<=0){ System.out.println("bye"); } } }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input! Try again."); } } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise40 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ double total,weight; weight = Integer.parseInt(JOptionPane.showInputDialog("Weight of Order: ")); if (weight<=0){ JOptionPane.showMessageDialog(null,"bye"); } while(weight>0){ if(weight<=10){ total = 3.0; } else{ total = 3.0 +((weight-10)*0.25); } JOptionPane.showMessageDialog(null,"Shipping Cost:$" + total); weight = Integer.parseInt(JOptionPane.showInputDialog("\nWeight of Order: ")); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise38 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ double miles, initial; initial = Integer.parseInt(JOptionPane.showInputDialog("Miles per Gallon Program\n" + "Initial Miles: ")); if(initial<=0){ JOptionPane.showMessageDialog(null,"bye"); } while (initial !=0){ double finals = Integer.parseInt(JOptionPane.showInputDialog("Final Miles: ")); if(finals <= 0){ JOptionPane.showMessageDialog(null,"Invalid Input!Try again."); System.exit(0); } if(initial>finals){ JOptionPane.showMessageDialog(null,"Invalid Input!Try again."); System.exit(0); } int gallons = Integer.parseInt(JOptionPane.showInputDialog("Gallons: ")); if(gallons <= 0){ JOptionPane.showMessageDialog(null,"Invalid Input!Try again."); System.exit(0); } miles = (finals - initial)/gallons; JOptionPane.showMessageDialog(null,"Miles per Gallon: "+ miles); initial = Integer.parseInt(JOptionPane.showInputDialog("\nInitial Miles: ")); if(initial<=0){ JOptionPane.showMessageDialog(null,"bye"); } } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise24 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 24 --- Check Charge"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ //asks for checking and savings account System.out.println("Enter the amount of Checking Account in $: "); int checka = Integer.parseInt(dataIn.readLine()); System.out.println("Enter the amount of Savings Account in $: "); int savea = Integer.parseInt(dataIn.readLine()); //checks whether the savings or checking for service charge if (savea>1500 || checka>1000 ){ System.out.println("Service Charge: $0"); } else{ System.out.println("Service Charge: $0.15"); } }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input! Try again."); } } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise42 { /** * @param args the command line arguments */ public static void main(String[] args) { double bal = 1000, pay = 0, tpay = 0; int month = 0; double fpay; try{ pay = Double.parseDouble(JOptionPane.showInputDialog("Enter the monthly payments: ")); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } System.out.println(""); System.out.println("Begining Balance: "+bal); System.out.println("Monthly Interest: 1.25%"); System.out.println("Payment amount per month: "+pay+"\n"); bal = bal + (bal * (1.5 / 100)) - pay; while (bal > 0){ month++; tpay += pay; System.out.println("Month "+month+" \tbalance: "+bal+" \ttotal paymentss: "+tpay); bal = bal + (bal * (1.5 / 100)) - pay; } fpay= pay + bal; tpay += fpay; bal = 0; month++; System.out.println("Month "+month+" \tbalance: "+bal); JOptionPane.showMessageDialog(null,"total payments: "+tpay + "\nFinal payments that will bring the balance to zero: "+fpay); } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise33 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ float sum = 0,square = 0,avg,savg,avgSquare,SD; int N = Integer.parseInt(JOptionPane.showInputDialog("How many numbers of N are to follow: ")); float[] n = new float [N]; for(int i = 0;i<N;i++){ n[i] = Float.parseFloat(JOptionPane.showInputDialog("Enter an integer: ")); sum = sum + n[i]; square = square + n[i]*n[i]; } avg = sum/N; savg = (float) Math.pow(avg,2); avgSquare = square/N; SD = (float) Math.sqrt(avgSquare - savg); JOptionPane.showMessageDialog(null,"Standard Deviation is: "+SD); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise32 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 32"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ double sum = 0; System.out.println("Enter N: "); int n = Integer.parseInt(dataIn.readLine()); int[] divisor = new int[n+1]; for(int i =1;i<=n;i++){ divisor[i] = i; sum = sum + (1.0/divisor[i]); } System.out.println("Sum is: " + sum); }catch(IOException | NumberFormatException | ArithmeticException e){ System.out.println("Invalid Input! Try again."); } } } <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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise21 { /** * @param args the command line arguments */ public static void main(String[] args){ try{ //initializes the variable float efficiency; //gets the inputs needed float Tair = Float.parseFloat(JOptionPane.showInputDialog("Enter the air temperature: ")); float Tsteam = Float.parseFloat(JOptionPane.showInputDialog("Enter the steam temperature: ")); //if tsteam is less than 373K, no efficiency if(Tsteam<373){ efficiency = 0; JOptionPane.showMessageDialog(null,"Efficiency: " + efficiency); } else{ efficiency = 1 - Tair/Tsteam; JOptionPane.showMessageDialog(null,"Efficiency: " + efficiency); } }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 activity104; import javax.swing.*; /** * * @author <NAME> */ public class MaramotHAct104MyLoop { /** * @param args the command line arguments */ public static void main(String[] args) { String pword, pword2; pword = JOptionPane.showInputDialog("Register your password : "); JPasswordField varA = new JPasswordField(); String flag = "F"; do{ JOptionPane.showConfirmDialog(null, varA, "Enter your password : ",JOptionPane.OK_CANCEL_OPTION); pword2 = new String(varA.getPassword()); if(pword2.equalsIgnoreCase(pword)){ flag = "T"; System.out.println(" Congratulations, access granted !"); }else{ System.out.println(" ACCESS DENIED !"); } }while(flag.equals("F")); } }<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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise31 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ int sum = 0; int no; no = Integer.parseInt(JOptionPane.showInputDialog("How many integers will be added: ")); int[] integers = new int[no]; for(int i = 0; i<no;i++){ integers[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter an integer: ")); sum = sum + integers[i]; } JOptionPane.showMessageDialog(null,"The sum is " + sum); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 MaramotHLab1Activity01; /** * * @author <NAME> * BSCpE 5-5 */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class MaramotHLab1Activity1Exercise06 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 6 --- Area of a Circle"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ //Asking for the input radius System.out.println("Input the radius: "); int r = Integer.parseInt(dataIn.readLine()); //formula for area of circle double area = Math.pow(r,2)*Math.PI; //print the results System.out.println("The radius is: " + r + " The area is: " + area ); }catch(NumberFormatException e){ //if there is an invalid input System.out.println("Invalid Input! Try again."); } } }<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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise20 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 20 --- Internet Delicatessen"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ //initializes the variable double ship; double total; double rem; //ask for inputs needed System.out.println("Enter the item: "); String itemname = dataIn.readLine(); System.out.println("Enter the price: "); int price = Integer.parseInt(dataIn.readLine()); System.out.println("Overnight delivery (0==no, 1==yes)"); int deli = Integer.parseInt(dataIn.readLine()); //gets the price rem = price/100.00; //for less than 10 dollars if(rem<10){ ship = 2.0; switch(deli){ case 0: //for daytime delivery total = rem + ship; System.out.println(itemname +" " + rem); System.out.println("shipping " + ship); System.out.println("total: " + total); break; case 1: //for overnight delivery ship = ship + 5.00; total = rem + ship; System.out.println(itemname + " \t" + rem); System.out.println("shipping: " + ship); System.out.println("total: \t" + total); break; default: System.out.println("Invalid Input!"); break; } } //for more than 10 dollars else if(price>10){ ship = 3.0; switch(deli){ case 0: //for daytime total = rem + ship; System.out.println(itemname +" " + rem); System.out.println("shipping " + ship); System.out.println("total: " + total); break; case 1: //for overnight ship = ship + 5.00; total = rem + ship; System.out.println(itemname +" " + rem); System.out.println("shipping " + ship); System.out.println("total: " + total); break; default: System.out.println("Invalid Input!"); break; } } }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input! Try again. "); } } } <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 MaramotHLab1Activity01; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author <NAME> * BSCpE 5-5 */ public class MaramotHLab1Activity1Exercise30 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 30"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ System.out.println("Enter the first word: "); String first = dataIn.readLine(); System.out.println("Enter the second word: "); String second = dataIn.readLine(); int flength = first.length(); int slength = second.length(); int length = 30 - (flength + slength); System.out.print(first); for(int i = 0; i<length;i++){ System.out.print("."); } System.out.println(second); }catch(IOException | NumberFormatException e){ System.out.println("Invalid Input! Try again."); } } } <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 activity102; import java.io.IOException; /** * * @author <NAME> */ public class MaramotHLabAct102Exercise12 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main ( String[] args ) throws IOException{ int[][] data = { {3, 2, 5}, {1, 4, 4, 8, 13}, {9, 1, 0, 2}, {0, 2, 6, 3, -1, -8} }; int sum; System.out.println("Exercise 12 --- Sum of Each Row"); for ( int row=0; row < data.length; row++){ sum = 0; for ( int col=0; col < data[row].length; col++){ sum = sum + data[row][col]; } System.out.println(sum); } } }<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 activity103; /** * * @author <NAME> */ import javax.swing.*; public class MaramotHActivity103LabExercise44 { /** * @param args the command line arguments */ public static void main(String[] args) { try{ int x; float n= 1f; double sum=1.0,term=1.0; x=Integer.parseInt(JOptionPane.showInputDialog("Enter value for x : ")); while(term >= 1.0E-12) { term = term * ((float)x / n); sum = sum + term; System.out.println(" n : "+n+" term : "+term+" sum : "+sum); n++; } JOptionPane.showMessageDialog(null,"ex^ using sum + term = " + sum); JOptionPane.showMessageDialog(null,"e^x using Math.exp(x)= "+ Math.exp(x)); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } }<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 activity103; import javax.swing.JOptionPane; /** * * @author <NAME> */ public class MaramotHActivity103LabExercise10 { /** * @param args the command line arguments */ public static void main(String[] args){ try{ //asks for the input of kilowatt-hour in cents double cent = Double.parseDouble(JOptionPane.showInputDialog("Enter cost per kilowatt-hour in cents: ")); //asks for the input of kilowatt-hours used per year int kwhours = Integer.parseInt(JOptionPane.showInputDialog("Enter kilowatt-hours used per year: ")); //computes the amount of annual cost double amount = (cent*kwhours)/100; //prints the result JOptionPane.showMessageDialog(null,"Annual Cost: " + amount); }catch(Exception e){ JOptionPane.showMessageDialog(null,"Invalid Input! Try again.","Error!",JOptionPane.WARNING_MESSAGE); } } } <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 MaramotHLab1Activity01; /** * * @author <NAME> * BSCpE 5-5 */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class MaramotHLab1Activity1Exercise07 { /** * @param args the command line arguments * @throws java.io.IOException */ public static void main(String[] args) throws IOException { System.out.println("Exercise 7 --- Cents to Dollars"); BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); try{ //uses try - catch to prevent invalid inputs //initializes the variable for dollars int dollars; //reads the users input System.out.println("Enter the number of cents: "); int cents = Integer.parseInt(dataIn.readLine()); //if the value of cents is less than zero, the program prints "invalid input" if(cents <= 0){ System.out.println("Invalid Input! Try Again."); } //else the program proceeds on the conversion of cents to dollars else{ dollars = cents/100; cents = cents%100; System.out.println("That is " + dollars + " dollars and " +cents + " cents "); } }catch(NumberFormatException e){ //if the program catches an invalid input, the program stops here System.out.println("Invalid Input! Try Again."); } } } <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 activity102; /** * * @author <NAME> */ public class MaramotHLabAct102Exercise14 { /** * @param args the command line arguments */ public static void main(String[] args) { int[][] data = { {3, 2, 5}, {1, 4, 4, 8, 13}, {9, 1, 0, 2}, {0, 2, 6, 3, -1, -8} }; int sum,minimum = 0,maximum = 0; System.out.println("Exercise 14 --- Maximum and Minimum Elements"); for ( int row=0; row < data.length; row++){ for ( int col=0; col < data[row].length; col++){ if(data[row][col]>maximum){ maximum=data[row][col]; } else if(data[row][col]<minimum){ minimum = data[row][col]; } } } sum = minimum + maximum; System.out.println("The sum is: " + sum); } }<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 activity102; /** * * @author <NAME> */ public class MaramotHLabAct102Exercise03 { /** * @param args the command line arguments */ public static void main ( String[] args ) { int[] valA = { 13, -22, 82, 17}; int[] valB = {-12, 24, -79, -13}; int[] sum = {0,0,0,0}; System.out.println("Exercise 3 --- Three Arrays"); sum[0] = valA[0] + valB[0]; sum[1] = valA[1] + valB[1]; sum[2] = valA[2] + valB[2]; sum[3] = valA[3] + valB[3]; System.out.println( "sum: " + sum[0] + " " + sum[1] + " " + sum[2] + " " + sum[3] ); } }
c8795643be01677ba7f6a3f204b89aceba0ec177
[ "Markdown", "Java", "INI" ]
49
Java
halmaramot10/Java-Lab-Exercises
5c213969ea9826ebb2b78fd14579b4b503b5ffdf
d8135c9e7127385224dc213e2aaca0fcf46ac53e
refs/heads/master
<repo_name>gallopmark/simpletablayout<file_sep>/library/src/main/java/com/galloped/tablayout/TabLayout.java package com.galloped.tablayout; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.FloatRange; import androidx.annotation.Nullable; import com.galloped.tablayout.tab.Tab; import java.util.ArrayList; import java.util.List; /** * Created by gallop 2019/7/4 * Copyright (c) 2019 holike * tabLayout */ public class TabLayout extends LinearLayout { private int mTabWidth; private boolean isTabSpaceEqual; private int mIconWidth; //icon 长 private int mIconHeight; //icon 宽 private int mSelectedTextColor; //选中tab 文字颜色 private int mUnSelectTextColor; //未选中tab 文字颜色 private int mIconGravity; //icon 位置(left、top、right、bottom) private float mDrawablePadding; //icon 距离文字边距 private float mTextSize; // 文字大小 public static final int STYLE_NORMAL = 0; public static final int STYLE_ITALIC = 1; public static final int STYLE_BOLD = 2; public static final int STYLE_BOLD_ITALIC = 3; private int mTextStyle = -1; //文字Typeface private Typeface mTextTypeface, mSelectedTextTypeface, mUnSelectTextTypeface; private int mSelectedTextStyle = -1; //选中文字Typeface private int mUnSelectTextStyle = -1; //未选中文字Typeface private float mSelectedTextSize; //选中时文字大小 private float mUnSelectTextSize; //未选中时文字大小 private boolean isAnimEnabled; //是否需要动画 private int mAnimDuration; //动画持续时间 private float mAlphaStart; //动画开始时透明度 private boolean isReselectedAnimEnabled; //重复选中tab是否需要动画 private boolean isAnimRecycle = false; //切换到另一个tab是否取消上次动画 private ValueAnimator mValueAnimator; /*drawable gravity*/ public static final int ICON_LEFT = 0; public static final int ICON_TOP = 1; public static final int ICON_RIGHT = 2; public static final int ICON_BOTTOM = 3; private boolean isTabSetup = false; private List<Tab> mTabList = new ArrayList<>(); private int mCurrentTab; //当前选中tab位置 private OnTabSelectListener mOnTabSelectListener; public TabLayout(Context context) { this(context, null); } public TabLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TabLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setClipChildren(false); //tab超出父元素边界也显示 setOrientation(HORIZONTAL); setupAttrs(context, attrs); } private void setupAttrs(Context context, AttributeSet attrs) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TabLayout); final int tabWidth = ta.getDimensionPixelSize(R.styleable.TabLayout_tab_width, 0); final boolean isTabSpaceEqual = ta.getBoolean(R.styleable.TabLayout_tab_space_equal, true); setTabWidth(tabWidth); setTabSpaceEqual(isTabSpaceEqual); mIconWidth = ta.getDimensionPixelSize(R.styleable.TabLayout_tab_drawableWidth, 0); mIconHeight = ta.getDimensionPixelSize(R.styleable.TabLayout_tab_drawableHeight, 0); mSelectedTextColor = ta.getColor(R.styleable.TabLayout_tab_selectedTextColor, Color.parseColor("#222222")); mUnSelectTextColor = ta.getColor(R.styleable.TabLayout_tab_unSelectTextColor, Color.parseColor("#666666")); final int iconGravity = ta.getInt(R.styleable.TabLayout_tab_drawableGravity, ICON_TOP); setIconGravity(iconGravity); final float drawablePadding = ta.getDimension(R.styleable.TabLayout_tab_drawablePadding, Unit.dp2px(context, 4f)); setDrawablePadding(drawablePadding); final int textStyle = ta.getInt(R.styleable.TabLayout_tab_textStyle, -1); final int selectedTextStyle = ta.getInt(R.styleable.TabLayout_tab_selectedTextStyle, -1); final int unnSelectTextStyle = ta.getInt(R.styleable.TabLayout_tab_unSelectTextStyle, -1); setSelectTextStyle(selectedTextStyle); setUnSelectTextStyle(unnSelectTextStyle); setTextStyle(textStyle); final float textSize = ta.getDimension(R.styleable.TabLayout_tab_textSize, Unit.dp2px(context, 13f)); final float selectedTextSize = ta.getDimension(R.styleable.TabLayout_tab_selectedTextSize, 0); final float unSelectTextSize = ta.getDimension(R.styleable.TabLayout_tab_unSelectTextSize, 0); setSelectedTextSize(selectedTextSize); setUnSelectTextSize(unSelectTextSize); setTextSize(textSize); final boolean isAnimEnabled = ta.getBoolean(R.styleable.TabLayout_tab_animEnabled, true); setAnimEnabled(isAnimEnabled); /*动画持续时间默认1000*/ final int animDuration = ta.getInteger(R.styleable.TabLayout_tab_animDuration, 1000); setAnimDuration(animDuration); final boolean isReselectedAnimEnabled = ta.getBoolean(R.styleable.TabLayout_tab_reselectedAnimEnabled, false); setReselectedAnimEnabled(isReselectedAnimEnabled); final boolean isAnimRecycle = ta.getBoolean(R.styleable.TabLayout_tab_animIsRecycle, false); setAnimRecycle(isAnimRecycle); /*动画开始透明度默认0.2f*/ float alphaStart = ta.getFloat(R.styleable.TabLayout_tab_alphaStart, 0.2f); setAlphaStart(alphaStart); ta.recycle(); } /*设置tab数据源*/ public void setupTab(@Nullable List<Tab> tabList) { if (tabList == null || tabList.isEmpty()) return; this.mTabList.clear(); this.mTabList.addAll(tabList); if (!isTabSetup) { isTabSetup = true; } notifyDataSetChanged(); } /*刷新数据*/ public void notifyDataSetChanged() { if (isTabSetup) { this.removeAllViews(); for (int i = 0; i < mTabList.size(); i++) { TabTextView tabTextView = obtainTabView(i); addTab(i, tabTextView); } setCurrentTab(mCurrentTab); } } private TabTextView obtainTabView(int position) { TabTextView tvTab = new TabTextView(getContext()); tvTab.setTag(position); tvTab.setGravity(Gravity.CENTER); //文字居中 tvTab.setCompoundDrawablePadding((int) mDrawablePadding); return tvTab; } private void addTab(int i, TabTextView tabTextView) { final int position = (Integer) tabTextView.getTag(); tabTextView.setText(mTabList.get(i).getTabText()); tabTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mUnSelectTextSize); tabTextView.setTextColor(mUnSelectTextColor); if (mUnSelectTextTypeface != null) { tabTextView.setTypeface(mUnSelectTextTypeface); } Drawable unSelectDrawable = mTabList.get(i).getUnSelectDrawable(); setDrawable(tabTextView, unSelectDrawable); tabTextView.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { if (mCurrentTab != position) { setCurrentTab(position); if (mOnTabSelectListener != null) { mOnTabSelectListener.onTabSelect(position); } } else { if (isReselectedAnimEnabled) { startValueAnim(position); } if (mOnTabSelectListener != null) { mOnTabSelectListener.onTabReselect(position); } } } }); LayoutParams params = isTabSpaceEqual ? new LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f) : new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); if (mTabWidth > 0) { params = new LinearLayout.LayoutParams(mTabWidth, LayoutParams.MATCH_PARENT); } tabTextView.setLayoutParams(params); addView(tabTextView); } private void updateTabSelection(int position) { for (int i = 0; i < mTabList.size(); ++i) { final boolean isSelect = i == position; TextView tabView = (TextView) getChildAt(i); tabView.setTextSize(TypedValue.COMPLEX_UNIT_PX, isSelect ? mSelectedTextSize : mUnSelectTextSize); Drawable drawable = isSelect ? mTabList.get(i).getSelectedDrawable() : mTabList.get(i).getUnSelectDrawable(); setDrawable(tabView, drawable); tabView.setTextColor(isSelect ? mSelectedTextColor : mUnSelectTextColor); Typeface typeface = isSelect ? mSelectedTextTypeface : mUnSelectTextTypeface; if (typeface != null) { tabView.setTypeface(typeface); } } } private void setDrawable(TextView tabView, Drawable drawable) { if (mIconWidth > 0 && mIconHeight > 0 && drawable != null) { drawable.setBounds(0, 0, mIconWidth, mIconHeight); if (mIconGravity == ICON_LEFT) { //drawableLeft tabView.setCompoundDrawables(drawable, null, null, null); } else if (mIconGravity == ICON_TOP) { //drawableTop tabView.setCompoundDrawables(null, drawable, null, null); } else if (mIconGravity == ICON_RIGHT) { //drawableRight tabView.setCompoundDrawables(null, null, drawable, null); } else if (mIconGravity == ICON_BOTTOM) { //drawableBottom tabView.setCompoundDrawables(null, null, null, drawable); } } else { if (mIconGravity == ICON_LEFT) { //drawableLeft tabView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null); } else if (mIconGravity == ICON_TOP) { //drawableTop tabView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null); } else if (mIconGravity == ICON_RIGHT) { //drawableRight tabView.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null); } else if (mIconGravity == ICON_BOTTOM) { //drawableBottom tabView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable); } } } private void startValueAnim(int position) { if (isAnimEnabled) { final TextView tabView = (TextView) getChildAt(position); if (isAnimRecycle) { stopValueAnim(); } mValueAnimator = ValueAnimator.ofFloat(mAlphaStart, 1); mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { float alpha = (Float) valueAnimator.getAnimatedValue(); tabView.setAlpha(alpha); } }); mValueAnimator.setDuration(mAnimDuration).start(); } } private void stopValueAnim() { if (mValueAnimator != null) { mValueAnimator.cancel(); mValueAnimator = null; } } /*设置当前tab*/ public void setCurrentTab(int position) { if (position < 0 || position >= mTabList.size()) return; this.mCurrentTab = position; updateTabSelection(position); startValueAnim(position); } public void setTabWidth(int tabWidth) { this.mTabWidth = tabWidth; notifyDataSetChanged(); } public int getTabWidth() { return this.mTabWidth; } public void setTabSpaceEqual(boolean isTabSpaceEqual) { this.isTabSpaceEqual = isTabSpaceEqual; notifyDataSetChanged(); } public boolean isTabSpaceEqual() { return this.isTabSpaceEqual; } public int getIconWidth() { return mIconWidth; } public void setIconWidth(int iconWidth) { this.mIconWidth = iconWidth; notifyDataSetChanged(); } public int getIconHeight() { return mIconHeight; } public void setIconHeight(int iconHeight) { this.mIconHeight = iconHeight; notifyDataSetChanged(); } public int getSelectedTextColor() { return mSelectedTextColor; } public void setSelectedTextColor(int selectedTextColor) { this.mSelectedTextColor = selectedTextColor; notifyDataSetChanged(); } public int getUnSelectTextColor() { return mUnSelectTextColor; } public void setUnSelectTextColor(int unSelectTextColor) { this.mUnSelectTextColor = unSelectTextColor; notifyDataSetChanged(); } public int getIconGravity() { return mIconGravity; } public void setIconGravity(int iconGravity) { this.mIconGravity = iconGravity; notifyDataSetChanged(); } public float getDrawablePadding() { return mDrawablePadding; } public void setDrawablePadding(float drawablePadding) { this.mDrawablePadding = drawablePadding; notifyDataSetChanged(); } public float getTextSize() { return mTextSize; } public void setTextSize(float textSize) { this.mTextSize = textSize; if (mSelectedTextSize == 0) { //未设置选中tab的文字大小,默认取textSize值 mSelectedTextSize = mTextSize; } if (mUnSelectTextSize == 0) { //未设置未选中tab的文字大小,默认取textSize值 mUnSelectTextSize = mTextSize; } notifyDataSetChanged(); } public void setTextStyle(int textStyle) { this.mTextStyle = textStyle; setTextStyle(createTypeface(this.mTextStyle)); } @Nullable public Typeface createTypeface(int style) { Typeface typeface = null; if (style == STYLE_NORMAL) { typeface = Typeface.defaultFromStyle(Typeface.NORMAL); } else if (style == STYLE_BOLD) { typeface = Typeface.defaultFromStyle(Typeface.BOLD); } else if (style == STYLE_ITALIC) { typeface = Typeface.defaultFromStyle(Typeface.ITALIC); } else if (style == STYLE_BOLD_ITALIC) { typeface = Typeface.defaultFromStyle(Typeface.BOLD_ITALIC); } return typeface; } public int getTextStyle() { return mTextStyle; } public void setTextStyle(@Nullable Typeface typeface) { this.mTextTypeface = typeface; if (this.mTextTypeface != null) { if (mSelectedTextTypeface == null) { mSelectedTextTypeface = typeface; } if (mUnSelectTextTypeface == null) { mUnSelectTextTypeface = typeface; } } notifyDataSetChanged(); } @Nullable public Typeface getTextTypeface() { return this.mTextTypeface; } public void setSelectTextStyle(int selectTextStyle) { this.mSelectedTextStyle = selectTextStyle; setSelectTextStyle(createTypeface(this.mSelectedTextStyle)); } public int getSelectTextStyle() { return this.mSelectedTextStyle; } public void setSelectTextStyle(@Nullable Typeface selectTypeface) { this.mSelectedTextTypeface = selectTypeface; notifyDataSetChanged(); } @Nullable public Typeface getSelectTextTypeface() { return this.mSelectedTextTypeface; } public void setUnSelectTextStyle(int unSelectTextStyle) { this.mUnSelectTextStyle = unSelectTextStyle; setUnSelectTextStyle(createTypeface(this.mUnSelectTextStyle)); } public int getUnSelectTextStyle() { return this.mUnSelectTextStyle; } public void setUnSelectTextStyle(@Nullable Typeface unSelectTypeface) { this.mUnSelectTextTypeface = unSelectTypeface; notifyDataSetChanged(); } @Nullable public Typeface getUnSelectTextTypeface() { return this.mUnSelectTextTypeface; } public float getSelectedTextSize() { return mSelectedTextSize; } public void setSelectedTextSize(float selectedTextSize) { this.mSelectedTextSize = selectedTextSize; notifyDataSetChanged(); } public float getUnSelectTextSize() { return mUnSelectTextSize; } public void setUnSelectTextSize(float unSelectTextSize) { this.mUnSelectTextSize = unSelectTextSize; notifyDataSetChanged(); } public void setAnimEnabled(boolean animEnabled) { isAnimEnabled = animEnabled; } public void setAnimRecycle(boolean animRecycle) { isAnimRecycle = animRecycle; } public void setReselectedAnimEnabled(boolean reselectedAnimEnabled) { isReselectedAnimEnabled = reselectedAnimEnabled; } public int getAnimDuration() { return mAnimDuration; } public void setAnimDuration(int mAnimDuration) { this.mAnimDuration = mAnimDuration; } public float getAlphaStart() { return mAlphaStart; } public void setAlphaStart(@FloatRange(from = 0.0, to = 1.0) float alphaStart) { if (alphaStart > 1.0f) { alphaStart = 1.0f; } else if (alphaStart < 0.0f) { alphaStart = 0.0f; } this.mAlphaStart = alphaStart; } public void setOnTabSelectListener(OnTabSelectListener onTabSelectListener) { this.mOnTabSelectListener = onTabSelectListener; } public interface OnTabSelectListener { void onTabSelect(int position); void onTabReselect(int position); } }
db77d9aa39bc34c3fb3682f0cb53199c140eb343
[ "Java" ]
1
Java
gallopmark/simpletablayout
3e649053fec9f87207c3418bb285227ab7aa9df6
f070ebfb09a99a6aeb6b25f54489645a217424eb
refs/heads/main
<repo_name>zdurham/AdventOfCode_2020<file_sep>/day_1/main.go package main import ( "bufio" "fmt" "io/ioutil" "log" "os" "strconv" ) const NUM_TO_GET = 2020 func main() { file, err := os.Open("input.txt") if err != nil { log.Fatal(err) } defer file.Close() scanner := bufio.NewScanner(file) var numbers []int for scanner.Scan() { text := scanner.Text() num, _ := strconv.Atoi(text) numbers = append(numbers, num) } outer: for _, num := range numbers { for _, innerNum := range numbers { if innerNum != num { total := innerNum + num if total == NUM_TO_GET { multiplied := innerNum * num fmt.Printf("the answer is %d \n", multiplied) ioutil.WriteFile("answer.txt", []byte(strconv.Itoa(multiplied)), 0644) break outer } } } } } <file_sep>/day_2/main.go package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func check(e error) { if e != nil { panic(e) } } func main() { data := parsePasswordData() var partOneValid int var partTwoValid int for _, datum := range data { occurenceValid := checkLetterOccurence(datum.Letter, datum.Password, datum.Bounds.Lower, datum.Bounds.Upper) positionValid := checkPosition(datum.Letter, datum.Password, datum.Bounds.Lower, datum.Bounds.Upper) if occurenceValid { partOneValid++ } if positionValid { partTwoValid++ } } fmt.Printf("There are %d valid passwords by the old policy. \n", partOneValid) fmt.Printf("There are %d valid passwords by the new policy. \n", partTwoValid) } type bounds struct { Upper int Lower int } type passwordStruct struct { Letter string Password string Bounds bounds } func parsePasswordData() []passwordStruct { file, err := os.Open("input.txt") check(err) scanner := bufio.NewScanner(file) var data []passwordStruct for scanner.Scan() { passwordData := scanner.Text() splitData := strings.Split(passwordData, " ") lower, higher := parseNums(splitData[0]) letter := parseLetter(splitData[1]) data = append(data, passwordStruct{ Password: splitData[2], Letter: letter, Bounds: bounds{ Lower: lower, Upper: higher, }, }) } return data } func parseNums(occurenceRange string) (lower, upper int) { nums := strings.Split(occurenceRange, "-") lower, _ = strconv.Atoi(nums[0]) upper, _ = strconv.Atoi(nums[1]) return lower, upper } func parseLetter(input string) string { split := strings.Split(input, ":") return split[0] } func checkPosition(letter, password string, first, second int) bool { letters := strings.Split(password, "") numLetters := len(letters) positionOne := first - 1 positionTwo := second - 1 var firstInstance string var lastInstance string if positionOne >= 0 && positionOne < numLetters { firstInstance = letters[positionOne] } if positionTwo < numLetters { lastInstance = letters[positionTwo] } if firstInstance == letter && lastInstance != letter { return true } else if firstInstance != letter && lastInstance == letter { return true } else { return false } } func checkLetterOccurence(letter, password string, lower, upper int) bool { var counter int letters := strings.Split(password, "") for _, l := range letters { if l == letter { counter++ } } if counter >= lower && counter <= upper { return true } return false } <file_sep>/day_5/main_test.go package main import ( "fmt" "testing" ) func TestSeatID(t *testing.T) { var tests = []struct { letters string want float64 }{ {"BFFFBBFRRR", 567}, {"FFFBBBFRRR", 119}, {"BBFFBBFRLL", 820}, } for _, tt := range tests { testname := fmt.Sprintf("%s should yield %v", tt.letters, tt.want) t.Run(testname, func(t *testing.T) { got := GetSeatID(tt.letters) if got != tt.want { t.Errorf("got %v, but we want %v\n", got, tt.want) } }) } } <file_sep>/go.mod module github.com/zdurham/aoc_2020 go 1.13 <file_sep>/day_4/main.go package main import ( "fmt" "io/ioutil" "regexp" "strings" ) var validators = []*regexp.Regexp{ regexp.MustCompile(`(byr):(?:(19[2-9]\d|200[0-2])(?:\s|$))?`), regexp.MustCompile(`(iyr):(?:(201\d|2020)(?:\s|$))?`), regexp.MustCompile(`(eyr):(?:(202\d|2030)(?:\s|$))?`), regexp.MustCompile(`(hgt):(?:((?:1[5-8]\d|19[0-3])cm|(?:59|6\d|7[0-6])in)(?:\s|$))?`), regexp.MustCompile(`(hcl):(?:(#[\da-f]{6})(?:\s|$))?`), regexp.MustCompile(`(ecl):(?:(amb|blu|brn|gry|grn|hzl|oth)(?:\s|$))?`), regexp.MustCompile(`(pid):(?:(\d{9})(?:\s|$))?`), } func main() { file, _ := ioutil.ReadFile("input.txt") partOneValid, partTwoValid := 0, 0 for _, passport := range strings.Split(strings.TrimSpace(string(file)), "\n\n") { // track validity using ints, if invalid make it 0, so nothing added to above sums validOne, validTwo := 1, 1 for _, reg := range validators { match := reg.FindStringSubmatch(passport) if len(match) == 0 { // no match, both invalid cause they are missing out validOne, validTwo = 0, 0 } else if match[2] == "" { validTwo = 0 } else { fmt.Println(match) } } partOneValid, partTwoValid = partOneValid+validOne, partTwoValid+validTwo } fmt.Printf("There are %d valid passports by part 1.\nThere are %d valid passports by part 2 standards", partOneValid, partTwoValid) } <file_sep>/day_5/main.go package main import ( "fmt" "io/ioutil" "math" "sort" "strings" ) func main() { file, _ := ioutil.ReadFile("input.txt") lines := strings.Split(string(file), "\n") var biggestSeatID float64 var seatIDs []float64 for _, line := range lines { seatID := GetSeatID(line) seatIDs = append(seatIDs, seatID) if seatID > biggestSeatID { biggestSeatID = seatID } } mySeatID := FindMissingSeatID(seatIDs) fmt.Printf("The biggest seatID is %v.\nMy seat number is %v\n", biggestSeatID, mySeatID) } func FindMissingSeatID(seatIDs []float64) (mySeatID float64) { sort.Float64s(seatIDs) for i := range seatIDs { // make sure we aren't at the front or back of the list if i != 0 || (i > 0 && i != (len(seatIDs)-1)) { curr := seatIDs[i] last := seatIDs[i-1] if curr-last == 2 { mySeatID = curr - 1 break } } } return } func GetSeatID(letters string) float64 { firstSeven := strings.Join(strings.Split(letters, "")[0:7], "") lastThree := strings.Join(strings.Split(letters, "")[7:10], "") row := FindPosition(firstSeven, 127.0, 0.0) seat := FindPosition(lastThree, 7.0, 0) // seat ID is row times 8, plus the seat position return (row * 8) + seat } func FindPosition(letters string, upper, lower float64) float64 { var position float64 for i, letterByte := range strings.Split(letters, "") { letter := string(letterByte) midPoint := findMidpoint(upper, lower) // lower half if letter == "F" || letter == "L" { upper = midPoint } else if letter == "B" || letter == "R" { // upper half lower = midPoint } if i == len(letters)-1 { if letter == "F" || letter == "L" { position = midPoint } else { position = midPoint + 1 } } } return position } func findMidpoint(upper, lower float64) float64 { return math.Floor((upper + lower) / 2) } <file_sep>/day_3/main.go package main import ( "bufio" "fmt" "log" "os" ) type Steps struct { Right int Down int X int NumTrees int } func main() { file, err := os.Open("input.txt") if err != nil { log.Fatal(err) } steps := []Steps{ { X: 0, Right: 1, Down: 1, NumTrees: 0, }, { X: 0, Right: 3, Down: 1, NumTrees: 0, }, { X: 0, Right: 5, Down: 1, NumTrees: 0, }, { X: 0, Right: 7, Down: 1, NumTrees: 0, }, { X: 0, Right: 1, Down: 2, NumTrees: 0, }, } defer file.Close() scanner := bufio.NewScanner(file) var lineNum = 1 for scanner.Scan() { line := scanner.Text() for i := range steps { if (steps[i].Down == 2 && lineNum%2 != 0) || steps[i].Down == 1 { if line[steps[i].X%len(line)] == '#' { steps[i].NumTrees++ } steps[i].X += steps[i].Right } } lineNum++ } multiplied := steps[0].NumTrees for i, step := range steps { fmt.Printf("The number of trees was %d\n", step.NumTrees) if i > 0 { multiplied = multiplied * step.NumTrees } } fmt.Printf("The multipled count is %d\n", multiplied) }
871136a9aa054fe2a306674646f84b760500f680
[ "Go Module", "Go" ]
7
Go
zdurham/AdventOfCode_2020
4d8d2e5b6f8a89e7356efa36e77d783c19c814c6
aa4b5561793741612f07fee1d33c755e95118ac9
refs/heads/master
<file_sep># Refactoring legacy code LevelUp 2017 | ThoughtWorks Australia (Brisbane) ## Session pre-requisites - If you just want to watch: - none at all. - If you would like to follow along as we refactor: - Visual Studio (Community Edition is fine) - ReSharper. ## Our goal Our goal is to refactor this tiny-yet-terrible app so that it's well-factored, robust, testable and tested, and all within a brief tutorial session. # Will you be my friend? Here's what the app looks like: Round 0 of 3 What is your name? Andrew Hello, Andrew! Isn't it a lovely afternoon? Do you like cookies? true That's great! I like cookies, too! Round 1 of 3 What is your name? David Hello, David! Isn't it a lovely afternoon? Do you like cookies? true That's great! I like cookies, too! Round 2 of 3 What is your name? Tony Hello, Tony! Isn't it a lovely afternoon? Do you like cookies? true That's great! I like cookies, too! Round 3 of 3 What is your name? Michael Hello, Michael! Isn't it a lovely afternoon? Do you like cookies? false Get away from me, you sick person. Andrew is my friend David is my friend Tony is my friend Press any key to quit <file_sep>using System; using System.Collections.Generic; namespace LevelUp2017 { internal class Program { private static void Main(string[] args) { var myFriends = new List<string>(); for (var i = 0; i < 4; i++) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Round {i} of {3}"); Console.WriteLine("What is your name?"); Console.ForegroundColor = ConsoleColor.DarkGreen; var personName = Console.ReadLine(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"Hello, {personName}!"); Console.WriteLine($"Isn't it a lovely {(DateTime.Now.Hour < 12 ? "morning" : "afternoon")}?"); Console.WriteLine("Do you like cookies?"); Console.ForegroundColor = ConsoleColor.DarkGreen; var likesCookies = bool.Parse(Console.ReadLine()); if (likesCookies) { myFriends.Add(personName); Console.WriteLine("That's great! I like cookies, too!"); } else { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Get away from me, you sick person."); } Console.WriteLine(); } foreach (var friend in myFriends) { Console.WriteLine($"{friend} is my friend"); } Console.WriteLine("Press any key to quit"); Console.ReadKey(); } } }
4d262e23e28b04a8536999a2752aa8654315c542
[ "Markdown", "C#" ]
2
Markdown
uglybugger/LevelUp2017
b8d632a63d49dff714c55b0d5f0f4751d7c2f03b
10326fa17ab2998552d04547ccd6847424ff7088
refs/heads/master
<repo_name>paultro708/Kitty_Jump<file_sep>/Kitty_Jump/Kitty_Jump/main.cpp #include "stdafx.h" #include "Game.h" #include "GameOver.h" #include "Menu.h" //#include <typeinfo> int main() { RenderWindow window(VideoMode(WINDOW_SIZE.x, WINDOW_SIZE.y), WINDOW_TITLE); window.setVerticalSyncEnabled(true); window.setFramerateLimit(WINDOW_FRAME_LIMIT); window.setPosition({ 431, 0 }); srand(time(NULL)); Event event; shared_ptr <Assets> ptr_assets(new Assets()); State *state = NULL; GameOver *gameover = new GameOver(ptr_assets); Game *newgame = new Game(ptr_assets); Menu *menu = new Menu(ptr_assets); state = menu; while (window.isOpen()) { state->doTheLoop(event, window); switch (state->getStateType()) { case MENU: break; case GAME: { if (typeid(*state) == typeid(Menu)) { state->setStateType(MENU); //back to default state state = newgame; } else if (typeid(*state) == typeid(GameOver)) { state->setStateType(GAMEOVER); newgame->reset(); state = newgame; } } break; case GAMEOVER: { if (typeid(*state) == typeid(Game)) { int tmpScore = state->getScore(); state->setStateType(GAME); state = gameover; state->setScore(tmpScore); } } break; default: break; } //if (typeid(*state) == typeid(Menu)) //{ // if (state->play) // state = newgame; //} //else if (typeid(*state) == typeid(Game)) //{ // if (state->gameOver) // { // gameover = new GameOver(ptr_assets, state->getScore()); // state = gameover; // } //} //else if (typeid(*state) == typeid(GameOver)) //{ // if (state->play) // { // state->play = false; // newgame->reset(); // //newgame= new Game(ptr_assets); // state = newgame; // } //} } delete newgame, gameover, menu; _CrtDumpMemoryLeaks(); return 0; }<file_sep>/Kitty_Jump/Kitty_Jump/GameOver.h #pragma once #include "State.h" #include "Button.h" class GameOver : public State { public: GameOver(shared_ptr <Assets> ptr_assets); ~GameOver(); void doTheLoop(Event &event, RenderWindow &window); void checkEvents(Event &event, RenderWindow &window); void render(RenderWindow &window); private: Text textGameOver; Text textScore; Sprite backgroundSprite; Button playAgain; Button quit; }; <file_sep>/Kitty_Jump/Kitty_Jump/Kitty.h #pragma once #include "consts.h" #include "Assets.h" class Kitty { private: shared_ptr<Assets> assets; Vector2f kitty_pos; Sprite kitty_sprite; void checkCylinderEffect(); //chceck go outside the boards in width Vector2f getHorizontalOffset(); public: void reset(); DirectionX directX = None; Kitty(shared_ptr<Assets> ptr_assets); ~Kitty(); void move(Vector2f &deltaPos); Vector2f getPosition(); void setPosition(Vector2f newPos); void update(); void draw(RenderWindow &window); /* float getSpeedY(); void setSpeedY(float newSpeed);*/ // float getHorizontalOffset(); }; <file_sep>/Kitty_Jump/Kitty_Jump/stdafx.h #pragma once #include <random> #include <SFML/Graphics.hpp> #include <string> #include <iostream> #include <memory> #include <typeinfo> <file_sep>/Kitty_Jump/Kitty_Jump/Kitty.cpp #include "stdafx.h" #include "Kitty.h" void Kitty::reset() { this->kitty_pos = KITTY_INITIAL_POSITION; this->kitty_sprite.setTexture(assets->KITTY_RIGHT_TEXTURE); this->kitty_sprite.setPosition(KITTY_INITIAL_POSITION); this->directX = None; } Kitty::Kitty(shared_ptr<Assets> ptr_assets) { assets = ptr_assets; this->kitty_pos = KITTY_INITIAL_POSITION; this->kitty_sprite.setTexture(assets->KITTY_RIGHT_TEXTURE); this->kitty_sprite.setPosition(KITTY_INITIAL_POSITION); } Kitty::~Kitty() { } void Kitty::move(Vector2f & offset) { kitty_sprite.move(offset); kitty_pos += offset; } Vector2f Kitty::getPosition() { //return position; return kitty_pos; //return this->kitty_sprite.getPosition(); } void Kitty::setPosition(Vector2f newPos) { kitty_sprite.setPosition(newPos); } void Kitty::checkCylinderEffect() { if (getPosition().x >= WINDOW_SIZE.x) { kitty_pos.x = 0; setPosition(Vector2f(kitty_pos)); } if (getPosition().x <= -KITTY_SIZE.x) { kitty_pos.x = WINDOW_SIZE.x - KITTY_SIZE.x; setPosition(Vector2f(kitty_pos)); } } void Kitty::update() { checkCylinderEffect(); this->move(getHorizontalOffset()); this->kitty_pos += getHorizontalOffset(); this->kitty_pos = kitty_sprite.getPosition(); switch (directX) { case Right: this->kitty_sprite.setTexture(assets->KITTY_RIGHT_TEXTURE); break; case Left: this->kitty_sprite.setTexture(assets->KITTY_LEFT_TEXTURE); break; default: break; } } Vector2f Kitty::getHorizontalOffset() { float posX = 0; switch (directX) { case Right: posX += STEP; break; case Left: posX -= STEP; break; default: break; } //to do jumping mechanism return Vector2f(posX, 0); } void Kitty::draw(RenderWindow & window) { window.draw(this->kitty_sprite); } <file_sep>/Kitty_Jump/Kitty_Jump/Pause.h #pragma once #include "State.h" class Pause: public State { public: Pause(); ~Pause(); void doTheLoop(Event &event, RenderWindow &window); void checkEvents(Event &event, RenderWindow &window); void render(RenderWindow &window); View currentView; }; <file_sep>/Kitty_Jump/Kitty_Jump/Game.h #pragma once #include "State.h" #include "Kitty.h" #include "Platform.h" //#include <random> class Game : public State { public: Game(shared_ptr <Assets> ptr_assets); ~Game(); void doTheLoop(Event &event, RenderWindow &window); void checkEvents(Event &event, RenderWindow &window); void render(RenderWindow &window); void checkGameEnd(); void reset(); private: Text score; Sprite backgroundSprite; float dy; Kitty my_kitty; vector <Platform> Ptab; Platform tmpPlatform; void gen_platforms(); void update_platform(Vector2f &platformPos); void update_jumping(); void draw_platforms(RenderWindow &window); bool checkJumping(); Vector2f genRandomVectf(); //bool gamePaused; }; <file_sep>/Kitty_Jump/Kitty_Jump/State.h #pragma once #include "consts.h" #include "Assets.h" class State { public: State(); shared_ptr<Assets> assets; virtual ~State() {}; int getScore(); void setScore(const int newScore); void resetScore(); virtual void doTheLoop(Event &event, RenderWindow &window) = 0; virtual void checkEvents(Event &event, RenderWindow &window) = 0; virtual void render(RenderWindow &window) = 0; void setStateType(StateType newState); StateType getStateType(); int actualScore = 0; StateType stateType; }; <file_sep>/Kitty_Jump/Kitty_Jump/Button.h #pragma once #include "consts.h" #include "Assets.h" class Button { private: shared_ptr <Assets> assets; Sprite sprite; Text text; Vector2f position; bool is_mouseOn = false; bool is_click = false; void buttonClick(Event &event); public: Button(shared_ptr <Assets> ptr_assets, string txt, float posY); ~Button(); void draw(RenderWindow &window); void setPosition(Vector2f newPos); Vector2f getPosition(); void mouseOn(Vector2f &mousePosition); bool checkButtonClick(Event &event); };<file_sep>/Kitty_Jump/Kitty_Jump/Menu.cpp #include "stdafx.h" #include "Menu.h" Menu::Menu(shared_ptr <Assets> ptr_assets) : playButton(ptr_assets, "Play", 300), quitButton(ptr_assets, "Quit", 450) { setStateType(MENU); assets = ptr_assets; logo.setTexture(assets->LOGO_TEXT); background.setTexture(assets->BACKGROUND_TEXTURE); kitty.setTexture(assets->KITTY); kitty.setPosition( 100, WINDOW_SIZE.y - KITTY_SIZE.y); } Menu::~Menu() { } void Menu::doTheLoop(Event & event, RenderWindow & window) { this->checkEvents(event, window); this->render(window); } void Menu::checkEvents(Event & event, RenderWindow & window) { while (window.pollEvent(event)) { if ((event.type == Event::Closed)||getStateType()==QUIT) window.close(); } Vector2i mousePos = Mouse::getPosition(); playButton.mouseOn(Vector2f(mousePos)); if (playButton.checkButtonClick(event)) { setStateType(GAME); } quitButton.mouseOn(Vector2f(mousePos)); if (quitButton.checkButtonClick(event)) { setStateType(QUIT); window.close(); } } void Menu::render(RenderWindow & window) { window.clear(Color::White); window.draw(background); window.draw(logo); window.draw(kitty); playButton.draw(window); quitButton.draw(window); window.display(); }<file_sep>/Kitty_Jump/Kitty_Jump/Button.cpp #include "stdafx.h" #include "Button.h" void Button::mouseOn(Vector2f &mousePosition) { Sprite tmp = sprite; tmp.setOrigin(0, 0); Vector2f position = tmp.getPosition(); position.x += (BUTTON_SIZE.x / 2.0f + 100); position.y -= (BUTTON_SIZE.y / 2.0f - 50); FloatRect buttonBounds = FloatRect(position, BUTTON_SIZE); if (buttonBounds.contains(mousePosition)) { sprite.setTexture(assets->BUTTON_ACTIVE_TEXTURE); is_mouseOn = true; } else { sprite.setTexture(assets->BUTTON_TEXTURE); is_mouseOn = false; } } void Button::buttonClick(Event & event) { const Vector2i mousePosition(event.mouseButton.x, event.mouseButton.y); if (event.type == Event::MouseButtonReleased && event.mouseButton.button == Mouse::Left) { if (is_mouseOn) { is_click = true; } } else is_click = false; } Button::Button(shared_ptr<Assets> ptr_assets, string txt, float posY) { assets = ptr_assets; sprite.setTexture(assets->BUTTON_TEXTURE); text.setFont(assets->RAVIE); text.setString(txt); text.setFillColor(Color(0, 158, 242)); text.setCharacterSize(BUTTON_TEXT_SIZE); setPosition(Vector2f(WINDOW_SIZE.x / 2.0f, posY)); } Button::~Button() { } void Button::draw(RenderWindow & window) { window.draw(sprite); window.draw(text); } void Button::setPosition(Vector2f newPos) { //set centre origin FloatRect buttonRect = sprite.getLocalBounds(); sprite.setOrigin(sprite.getTextureRect().left + BUTTON_SIZE.x / 2.0f, sprite.getTextureRect().top + BUTTON_SIZE.y / 2.0f); sprite.setPosition(newPos); FloatRect textRect = text.getLocalBounds(); text.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f); text.setPosition({ newPos.x, newPos.y + 15 }); this->position = sprite.getPosition(); } Vector2f Button::getPosition() { return this->position; } bool Button::checkButtonClick(Event &event) { this->buttonClick(event); return is_click; } <file_sep>/Kitty_Jump/Kitty_Jump/Assets.h #pragma once #include "consts.h" class Assets { private: string loadTextureError = "Can not open the file\n"; string loadFontError = "Can not load font from file\n"; public: Assets(); ~Assets(); void addTexture(Texture &texture, const string &name); void addFont(Font &font, const string &name); Texture BACKGROUND_TEXTURE; Texture PLATFORM_TEXTURE; Texture KITTY_LEFT_TEXTURE; Texture KITTY_RIGHT_TEXTURE; Texture BUTTON_ACTIVE_TEXTURE; Texture BUTTON_TEXTURE; Texture LOGO_TEXT; Texture KITTY; Font RAVIE; }; <file_sep>/Kitty_Jump/Kitty_Jump/Pause.cpp #include "Pause.h" Pause::Pause() { } Pause::~Pause() { } void Pause::doTheLoop(Event & event, RenderWindow & window) { } void Pause::checkEvents(Event & event, RenderWindow & window) { } void Pause::render(RenderWindow & window) { } <file_sep>/Kitty_Jump/Kitty_Jump/Assets.cpp #include "stdafx.h" #include "Assets.h" Assets::Assets() { addTexture(this->BACKGROUND_TEXTURE, "images/background.png"); addTexture(KITTY_LEFT_TEXTURE, "images/kitty_left.png"); addTexture(KITTY_RIGHT_TEXTURE, "images/kitty_right.png"); addTexture(PLATFORM_TEXTURE, "images/platform.png"); addTexture(BUTTON_TEXTURE, "images/button.png"); addTexture(BUTTON_ACTIVE_TEXTURE, "images/button_active.png"); addTexture(KITTY, "images/kitty2.png"); addTexture(LOGO_TEXT, "images/logo_text.png"); addFont(RAVIE, "font/RAVIE.ttf"); } Assets::~Assets() { } void Assets::addTexture(Texture & texture, const string &name) { try { if (!texture.loadFromFile(name)) throw loadTextureError; } catch (string loadTextureError) { cerr << loadTextureError; exit(1); } } void Assets::addFont(Font & font, const string &name) { try { if (!font.loadFromFile(name)) throw loadFontError; } catch (string loadFontError) { cerr << loadFontError; exit(1); } } <file_sep>/Kitty_Jump/Kitty_Jump/Platform.cpp #include "stdafx.h" #include "Platform.h" void Platform::move(Vector2f & deltaPos) { plat_sprite.move(deltaPos); plat_pos += deltaPos; } Vector2f Platform::getPosition() { return this->plat_pos; } void Platform::setPosition(Vector2f & newPos) { plat_pos = newPos; plat_sprite.setPosition(newPos); } void Platform::draw(RenderWindow & window) { window.draw(this->plat_sprite); } Platform::Platform(shared_ptr<Assets> ptr_assets) { assets = ptr_assets; this->plat_pos = PLATFORM_INITIAL_POSITION; this->plat_sprite.setTexture(assets->PLATFORM_TEXTURE); this->plat_sprite.setPosition(plat_pos); } Platform::~Platform() { } <file_sep>/Kitty_Jump/Kitty_Jump/GameOver.cpp #include "stdafx.h" #include "GameOver.h" GameOver::GameOver(shared_ptr <Assets> ptr_assets) : playAgain(ptr_assets, "Play again", 320), quit(ptr_assets, "Quit", 450) { setStateType(GAMEOVER); assets = ptr_assets; textGameOver.setFont(assets->RAVIE); textGameOver.setString("Game Over!"); textGameOver.setCharacterSize(BUTTON_TEXT_SIZE); textGameOver.setFillColor(Color::Red); textGameOver.setStyle(Text::Bold); FloatRect textGameOverRect = textGameOver.getLocalBounds(); textGameOver.setOrigin(textGameOverRect.left + textGameOverRect.width / 2.0f, textGameOverRect.top + textGameOverRect.height / 2.0f); textGameOver.setPosition(Vector2f(WINDOW_SIZE.x / 2.0f, WINDOW_SIZE.y / 2.0f - 200)); backgroundSprite.setTexture(assets->BACKGROUND_TEXTURE); textScore.setFont(assets->RAVIE); textScore.setCharacterSize(SCORE_OVER_TEXT_SIZE); textScore.setFillColor(Color::Red); } GameOver::~GameOver() { } void GameOver::doTheLoop(Event & event, RenderWindow &window) { window.clear(Color::White); this->checkEvents(event, window); this->render(window); window.display(); } void GameOver::checkEvents(Event & event, RenderWindow &window) { while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } Vector2i mousePos = Mouse::getPosition(); playAgain.mouseOn(Vector2f(mousePos)); if (playAgain.checkButtonClick(event)) { cout << "Play again button clicked\n"; //play = true; setStateType(GAME); } quit.mouseOn(Vector2f(mousePos)); if (quit.checkButtonClick(event)) window.close(); } void GameOver::render(RenderWindow &window) { textScore.setString("Your score: " + to_string(actualScore)); FloatRect textScoreRect = textScore.getLocalBounds(); textScore.setOrigin(textScoreRect.left + textScoreRect.width / 2.0f, textScoreRect.top + textScoreRect.height / 2.0f); textScore.setPosition(Vector2f(WINDOW_SIZE.x / 2.0f, WINDOW_SIZE.y / 2.0f - 150)); window.draw(backgroundSprite); window.draw(textGameOver); window.draw(textScore); playAgain.draw(window); quit.draw(window); } <file_sep>/Kitty_Jump/Kitty_Jump/State.cpp #include "stdafx.h" #include "State.h" State::State() { } int State::getScore() { return this->actualScore; } void State::setScore(const int newScore) { this->actualScore = newScore; } void State::resetScore() { this->actualScore = 0; } void State::setStateType(StateType newState) { this->stateType = newState; } StateType State::getStateType() { return this->stateType; } <file_sep>/Kitty_Jump/Kitty_Jump/Game.cpp #include "stdafx.h" #include "Game.h" Game::Game(shared_ptr <Assets> ptr_assets) : my_kitty(ptr_assets), tmpPlatform(ptr_assets) { setStateType(GAME); assets = ptr_assets; backgroundSprite.setTexture(assets->BACKGROUND_TEXTURE); score.setFont(assets->RAVIE); score.setString("Score: " + to_string(actualScore)); score.setCharacterSize(16); score.setFillColor(Color::White); score.setPosition(Vector2f(0, 0)); gen_platforms(); //init one of platform under the kitty initial position to not over the game on start Ptab[0].setPosition(Vector2f(KITTY_INITIAL_POSITION.x - 20, KITTY_INITIAL_POSITION.y + 200)); dy = 0; } Game::~Game() { } void Game::doTheLoop(Event &event, RenderWindow &window) { this->checkEvents(event, window); if (getStateType() != PAUSE) { this->my_kitty.update(); this->update_jumping(); this->checkGameEnd(); } this->render(window); } void Game::checkEvents(Event & event, RenderWindow &window) { while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); } if (Keyboard::isKeyPressed(Keyboard::P)) { if (getStateType() == PAUSE) { setStateType(GAME); return; } else { setStateType(PAUSE); return; } } if (getStateType() != PAUSE) { if (event.type == Event::KeyPressed) switch (event.key.code) { case Keyboard::Left: my_kitty.directX = Left; break; case Keyboard::Right: my_kitty.directX = Right; break; default: my_kitty.directX = None; } if (event.type == sf::Event::KeyReleased) { switch (event.key.code) { case Keyboard::Left: my_kitty.directX = None; break; case Keyboard::Right: my_kitty.directX = None; break; default: break; } } } } void Game::render(RenderWindow &window) { window.clear(Color::White); window.draw(backgroundSprite); my_kitty.draw(window); draw_platforms(window); score.setString("Score: " + to_string(actualScore)); score.setPosition({ 0,0 }); window.draw(score); window.display(); } void Game::checkGameEnd() { if (my_kitty.getPosition().y + KITTY_SIZE.y > WINDOW_SIZE.y) { setStateType(GAMEOVER); } } void Game::reset() { dy = 0; setStateType(GAME); resetScore(); Ptab.clear(); gen_platforms(); my_kitty.reset(); //init one of platform under the kitty initial position to not over the game on start Ptab[0].setPosition(Vector2f(KITTY_INITIAL_POSITION.x - 20, KITTY_INITIAL_POSITION.y + 200)); } void Game::gen_platforms() { Vector2f pos; for (int i = 0; i < NUMBER_PLATFORMS; i++) { pos = genRandomVectf(); tmpPlatform.setPosition(pos); Ptab.push_back(tmpPlatform); } } void Game::update_platform(Vector2f &platformPos) { platformPos.y -= dy; if (platformPos.y > WINDOW_SIZE.y) // new platform on the top { platformPos.y = 0; platformPos.x = genRandomVectf().x; } } void Game::update_jumping() { dy += 0.2; //faliing Vector2f tmpKittyPos = my_kitty.getPosition(); tmpKittyPos.y += dy; Vector2f tmpPlatformPos; if (tmpKittyPos.y < MAX_KITTY_JUMP_HEIGHT) for (int i = 0; i < NUMBER_PLATFORMS; i++) { tmpKittyPos.y = MAX_KITTY_JUMP_HEIGHT; my_kitty.setPosition(tmpKittyPos); tmpPlatformPos = Ptab[i].getPosition(); update_platform(tmpPlatformPos); //moving down and generating platforms on the top Ptab[i].setPosition(tmpPlatformPos); } if (tmpKittyPos.y == MAX_KITTY_JUMP_HEIGHT && dy < (-2)) actualScore++; //detection jumping on the platform for (int i = 0; i < NUMBER_PLATFORMS; i++) { Vector2f tmpPlatformPos = Ptab[i].getPosition(); if (checkJumping() && dy > 0) { dy = -10; } } my_kitty.setPosition(tmpKittyPos); } void Game::draw_platforms(RenderWindow &window) { for (int i = 0; i < Ptab.size(); i++) { Ptab[i].draw(window); } } bool Game::checkJumping() { for (int i = 0; i < NUMBER_PLATFORMS; i++) { Vector2f platformPos = Ptab[i].getPosition(); Vector2f kittyPos = my_kitty.getPosition(); if (((kittyPos.y + KITTY_SIZE.y >= platformPos.y) //check vertical collision && (kittyPos.y + KITTY_SIZE.y <= platformPos.y + PLATFORM_SIZE.y) && (kittyPos.x + KITTY_RIGHT_BOUNDING_BOX >= platformPos.x) //check hozizontal && (kittyPos.x + KITTY_LEFT_BOUNDING_BOX - PLATFORM_SIZE.x <= platformPos.x))) // checking bounding box to detect jump with only kitty's paws, not at whole width of sprite { return true; } } return false; } Vector2f Game::genRandomVectf() { Vector2f pos; pos.x = rand() % (int)(WINDOW_SIZE.x - PLATFORM_SIZE.x); pos.y = rand() % (int)(WINDOW_SIZE.y - PLATFORM_SIZE.y); return pos; }<file_sep>/Kitty_Jump/Kitty_Jump/Platform.h #pragma once #include "consts.h" #include <random> #include "Assets.h" class Platform { private: Vector2f plat_pos; //position of platform shared_ptr<Assets> assets; Sprite plat_sprite; public: void move(Vector2f &deltaPos); Vector2f getPosition(); void setPosition(Vector2f &newPos); void draw(RenderWindow &window); Platform(shared_ptr<Assets> ptr_assets); ~Platform(); }; <file_sep>/Kitty_Jump/Kitty_Jump/consts.h #pragma once //#include <SFML/Graphics.hpp> //#include <string> //#include <iostream> //#include <memory> using namespace sf; using namespace std; static const Vector2u WINDOW_SIZE = { 500, 650 }; static const string WINDOW_TITLE = "Kitty Jump!"; static const unsigned WINDOW_FRAME_LIMIT = 60; static const Vector2f KITTY_SIZE = { 70,70 }; static const Vector2f KITTY_INITIAL_POSITION = 0.5f * (Vector2f(WINDOW_SIZE) - KITTY_SIZE); static const unsigned MAX_KITTY_JUMP_HEIGHT = 150.f; static const unsigned PLATFORM_DELTA_REFLECT = 22.f; static const Vector2f PLATFORM_SIZE = { 63, 14 }; static const unsigned NUMBER_PLATFORMS = 12; static const Vector2f PLATFORM_INITIAL_POSITION = { 0,0 }; // vector for checking //{ WINDOW_SIZE.x / 2.f, WINDOW_SIZE.y + KITTY_INITIAL_POSITION.y }; static const auto STEP = 6.f; const int KITTY_LEFT_BOUNDING_BOX = 25; const int KITTY_RIGHT_BOUNDING_BOX = 45; static const Vector2f BUTTON_SIZE = { 333,125 }; static const unsigned BUTTON_TEXT_SIZE = 45; static const unsigned SCORE_OVER_TEXT_SIZE = 35; enum DirectionX { None = 0, Left, Right }; enum StateType { MENU = 0, GAME, PAUSE, GAMEOVER, QUIT };<file_sep>/Kitty_Jump/Kitty_Jump/Menu.h #pragma once #include "State.h" #include "Button.h" class Menu : public State { private: Button playButton; Button quitButton; shared_ptr <Assets> assets; Sprite background; Sprite kitty; Sprite logo; public: Menu(shared_ptr <Assets> ptr_assets); ~Menu(); void doTheLoop(Event &event, RenderWindow &window); void checkEvents(Event &event, RenderWindow &window); void render(RenderWindow &window); };
447666cc676249c726c753a832419ca3e8f6c3a7
[ "C++" ]
21
C++
paultro708/Kitty_Jump
e449519cbde287505062f2291579bf2c1a4228a2
2224fce01edbb3dd4cb612ae844d0a84aa5528d0
refs/heads/master
<repo_name>dima4p/challenge_make_this_data_sortable<file_sep>/app/controllers/programming_languages_controller.rb # This is the main controller class ProgrammingLanguagesController < ApplicationController before_action :set_programming_language, only: [:show, :edit, :update, :destroy] # GET /programming_languages # GET /programming_languages.json def index words = params[:q] && Shellwords.split(params[:q]).map(&:squish) if words.present? @with = words.reject{|word| word.first == '-'} @without = words.select{|word| word.first == '-'}.map do |word| word[1..-1] end @programming_languages = ProgrammingLanguage.with(@with).without(@without) else @programming_languages = ProgrammingLanguage.ordered end end end <file_sep>/config/routes.rb Rails.application.routes.draw do resources :programming_languages, only: [:index] root 'programming_languages#index' end <file_sep>/README.md # This is a test project ## Ruby on Rails Developer Applicants Test To understand your coding ability and style, we have devised a simple practical coding test. We use this as a dicussion topic during interviews and may use it as a sample of your knowledge when presenting your profile to customers. #### Objective: * Make this data searchable ### #Minimum requirements: * Implementation must use Ruby on Rails, JavaScript and HTML (all three) * Search logic should be implemented in Ruby on Rails * A search for Lisp Common should match a programming language named "Common Lisp" * Your solution will be tested on a server running Ubuntu, Ruby 2.1 and Rails 4.2.0 * Deliver your solution as a zip or tar.gz file * We will unpack your solution and run it from our server #### Meriting: * Writing code with reusability in mind * Search match precision * Search results ordered by relevance * Support for exact matches, eg. Interpreted "<NAME>", which should match "BASIC", but not "Haskell" * Match in different fields, eg. Scripting Microsoft should return all scripting languages designed by "Microsoft" * Support for negative searches, eg. john -array, which should match "BASIC", "Haskell", "Lisp" and "S-Lang", but not "Chapel", "Fortran" or "S". * Solution elegance * Visual design #### Keep in mind: * Frameworks are allowed, but not required. ** If you use a framework, please do not include the framework code. Write instructions allowing us to install the framework by ourselves (and where to add your code). * Comments are VERY useful, they help us understand your thought process * This exercise is not meant to take more than a few hours * A readme file is encouraged ## Requirement * Ruby 2.1.6 * PostreSQL ## Assumptions * We assume that partial words should be compared ## Deploy Standard RoR application deploy. Do not forget to seed the database. ## TODO * Add checkbox `case (un)sensitive` * Add colorizing the found search words * Add design ;-) <file_sep>/spec/routing/programming_languages_routing_spec.rb require "rails_helper" RSpec.describe ProgrammingLanguagesController, type: :routing do describe "routing" do it "routes to #index" do expect(:get => "/programming_languages") .to route_to("programming_languages#index") end it "does not route to #new" do expect(:get => "/programming_languages/new") .not_to route_to("programming_languages#new") end it "does not route to #show" do expect(:get => "/programming_languages/1") .not_to route_to("programming_languages#show", :id => "1") end it "does not route to #edit" do expect(:get => "/programming_languages/1/edit") .not_to route_to("programming_languages#edit", :id => "1") end it "does not route to #create" do expect(:post => "/programming_languages") .not_to route_to("programming_languages#create") end it "does not route to #update via PUT" do expect(:put => "/programming_languages/1") .not_to route_to("programming_languages#update", :id => "1") end it "does not route to #update via PATCH" do expect(:patch => "/programming_languages/1") .not_to route_to("programming_languages#update", :id => "1") end it "does not route to #destroy" do expect(:delete => "/programming_languages/1") .not_to route_to("programming_languages#destroy", :id => "1") end end end <file_sep>/app/views/programming_languages/index.json.jbuilder json.array!(@programming_languages) do |programming_language| json.extract! programming_language, :id, :name, :language_type, :designed_by end <file_sep>/db/seeds.rb # 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) JSON.load(Rails.root.join 'db', 'seeds', 'data.json').each do |record| programming_language = ProgrammingLanguage.find_or_create_by name: record['Name'] programming_language.update( language_type: record['Type'].split(/, */), designed_by: record['Designed by'].split(/, */) ) end <file_sep>/spec/views/programming_languages/index.html.haml_spec.rb require 'rails_helper' describe "programming_languages/index", type: :view do before(:each) do @programming_language = create(:programming_language) assign(:programming_languages, [@programming_language, @programming_language]) end it "renders a list of programming_languages" do render # expect(rendered).to eq '' assert_select 'tr>td', text: @programming_language.name.to_s, count: 2 assert_select 'tr>td', text: @programming_language.language_type.to_sentence, count: 2 assert_select 'tr>td', text: @programming_language.designed_by.to_sentence, count: 2 end it 'renders a form for search' do render assert_select "form[action='#{programming_languages_path}'][method='get']" do assert_select 'input#q[name=?]', 'q' end end end <file_sep>/app/models/programming_language.rb # == Schema Information # # Table name: programming_languages # # id :integer not null, primary key # name :string # language_type :string default([]), is an Array # designed_by :string default([]), is an Array # created_at :datetime not null # updated_at :datetime not null # # Model ProgrammingLanguage defines the main model that keeps data # class ProgrammingLanguage < ActiveRecord::Base validates :name, presence: true scope :ordered, -> { order(:name) } # Selects the records containing given words case insensitive scope :with, -> words { return ordered if words.blank? words = Array.wrap(words).map(&:downcase).map do |word| sanitize_sql_like word end logger.debug "ProgrammingLanguage@#{__LINE__}.with #{words.inspect}" if logger.debug? cond = words.map do |word| "(#{[ "lower(name) LIKE '%#{word}%'", "(SELECT count(*) FROM unnest(language_type) AS a(t) WHERE lower(t) LIKE '%#{word}%') > 0", "(SELECT count(*) FROM unnest(designed_by) AS a(t) WHERE lower(t) LIKE '%#{word}%') > 0" ].join ' OR '})" end.join ' AND ' count = words.map do |word| [ "CASE WHEN lower(name) LIKE '%#{word}%' THEN 1 ELSE 0 END", "(SELECT count(*) FROM unnest(language_type) AS a(t) WHERE lower(t) LIKE '%#{word}%')", "(SELECT count(*) FROM unnest(designed_by) AS a(t) WHERE lower(t) LIKE '%#{word}%')" ] end.flatten.join(' + ') select("* , #{count} AS rate") .where(cond) .order('rate DESC') .order('name') } # Rejects the records containing given words case insensitive scope :without, -> words { logger.debug "ProgrammingLanguage@#{__LINE__}.without #{words.inspect}" if logger.debug? cond = Array.wrap(words).map(&:downcase).map do |word| word = sanitize_sql_like word [ "lower(name) NOT LIKE '%#{word}%'", "(SELECT count(*) FROM unnest(language_type) AS a(t) WHERE lower(t) LIKE '%#{word}%') = 0", "(SELECT count(*) FROM unnest(designed_by) AS a(t) WHERE lower(t) LIKE '%#{word}%') = 0" ] end.flatten.join ' AND ' where cond } end <file_sep>/spec/controllers/programming_languages_controller_spec.rb require 'spec_helper' describe ProgrammingLanguagesController, type: :controller do # This should return the minimal set of attributes required to create a valid # ProgrammingLanguage. As you add validations to ProgrammingLanguage, be sure to # adjust the attributes here as well. The list could not be empty. let(:valid_attributes) {FactoryGirl.build(:programming_language).attributes.slice *%w[name]} let(:invalid_attributes) do {name: ''} end # This should return the minimal set of values that should be in the session # in order to pass any filters (e.g. authentication) defined in # ProgrammingLanguagesController. Be sure to keep this updated too. let(:valid_session) { {} } describe "GET index" do it "assigns all programming_languages as @programming_languages" do programming_language = create :programming_language get :index, {}, valid_session expect(assigns(:programming_languages)).to be_kind_of(ActiveRecord::Relation) expect(assigns(:programming_languages)).to eq([programming_language]) end context 'when query is present' do let(:query) do {q: %q( one " two " ' two and a half ' -three )} end it 'assigns the positive words to @with removing extra spaced' do get :index, query, valid_session expect(assigns(:with)).to eq ['one', 'two', 'two and a half'] end it 'assigns the negative words to @without removing extra spaced' do get :index, query, valid_session expect(assigns(:without)).to eq ['three'] end it 'sends to ProgrammingLanguage :with and :without calls' do expect(ProgrammingLanguage).to receive(:with) .with(['one', 'two', 'two and a half']) {ProgrammingLanguage} expect(ProgrammingLanguage).to receive(:without) .with(['three']) {ProgrammingLanguage} get :index, query, valid_session end end end end <file_sep>/spec/models/programming_language_spec.rb # == Schema Information # # Table name: programming_languages # # id :integer not null, primary key # name :string # language_type :string default([]), is an Array # designed_by :string default([]), is an Array # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' describe ProgrammingLanguage, type: :model do subject { create :programming_language } it { should be_valid } it {should validate_presence_of :name} describe :class do describe :scopes do let(:ada) do create :programming_language, name: 'Ada', language_type: %w[Compiled Imperative], designed_by: ["<NAME>", "<NAME>"] end let(:ant) do create :programming_language, name: 'Ant', language_type: %w[Interpreted], designed_by: ["Jean Software Foundation"] end before :each do ant ada end describe :ordered do it 'orders the records by :name' do expect(ProgrammingLanguage.ordered).to eq ProgrammingLanguage.order(:name) end end # :ordered describe :with do it 'filters out the records that do not contain any of the given words case insensitive' do expect(ProgrammingLanguage.with(['ada']).map(&:id)) .to eq [ada.id] expect(ProgrammingLanguage.with(['compiled']).map(&:id)) .to eq [ada.id] expect(ProgrammingLanguage.with(['tucker']).map(&:id)) .to eq [ada.id] expect(ProgrammingLanguage.with(['O']).map(&:id)) .to eq [ada.id, ant.id] expect(ProgrammingLanguage.with(%w[Tucker Interpreted]).map(&:id)) .to eq [] end it 'orders the languages with the same rate by name' do expect(ProgrammingLanguage.with(['Jean']).map(&:rate)) .to eq [1, 1] expect(ProgrammingLanguage.with(['Jean']).map(&:id)) .to eq [ada.id, ant.id] end it 'returns the ordered collection if words are empty' do expect(ProgrammingLanguage.with([])) .to eq ProgrammingLanguage.order(:name) end end # :with describe :without do it 'filters out the records that contain any of the given words case insensitive' do expect(ProgrammingLanguage.without(['ada']).map(&:id)).to eq [ant.id] expect(ProgrammingLanguage.without(['compiled']).map(&:id)).to eq [ant.id] expect(ProgrammingLanguage.without(['tucker']).map(&:id)).to eq [ant.id] expect(ProgrammingLanguage.without(['O']).map(&:id)).to eq [] end it 'returns the original collection if words are empty' do expect(ProgrammingLanguage.ordered.without([])) .to eq ProgrammingLanguage.order(:name) end end # :without end # :scopes end # :class end <file_sep>/spec/views/programming_languages/index.json.jbuilder_spec.rb require 'rails_helper' describe "programming_languages/index.json.jbuilder", type: :view do before(:each) do @programming_language = create(:programming_language) assign :programming_languages, [@programming_language, @programming_language] end attributes = %w[ id name language_type designed_by ] it "renders a list of programming_languages as json with following attributes: #{attributes.join(', ')}" do render hash = MultiJson.load rendered expect(hash.first).to eq(hash = hash.last) expect(hash.keys.sort).to eq attributes.sort expected = @programming_language.attributes.slice *attributes expected = MultiJson.load MultiJson.dump expected expect(hash).to eq expected # expect(hash['id']).to eq @programming_language.id.to_s # expect(hash['name']).to eq @programming_language.name.to_s # expect(hash['language_type']).to eq @programming_language.language_type.to_s # expect(hash['designed_by']).to eq @programming_language.designed_by.to_s # expect(hash['url']).to eq programming_language_url(@programming_language, format: 'json') end end <file_sep>/spec/factories/programming_languages.rb # == Schema Information # # Table name: programming_languages # # id :integer not null, primary key # name :string # language_type :string default([]), is an Array # designed_by :string default([]), is an Array # created_at :datetime not null # updated_at :datetime not null # FactoryGirl.define do factory :programming_language do sequence(:name) {|n| "ProgrammingLanguage ##{n}" } sequence(:language_type) {|n| ["Type #{n}-1", "Type #{n}-2"] } sequence(:designed_by) {|n| ["Designed by #{n}-1", "Designed by #{n}-2"] } end end
62fea54b12a844d0f324ff0ce930cefcd6abea2b
[ "Markdown", "Ruby" ]
12
Ruby
dima4p/challenge_make_this_data_sortable
b4153f421afd1e4d70a59d4cdb0e1a1abbe09622
76e164da0904d46110af195b8ab45fb0e1de5952
refs/heads/master
<repo_name>OpenTaal/diacritic-removal<file_sep>/README.md # diacritic-removal This project provides definitions, scripts and documentation for removal of diacritics on characters for the Dutch language. However, the project is also useful for other languages. For all applications, also in Dutch, please review exactly what the implications are of using the files and software offered here. This functionality is also provided by certain software libraries. However, the definitions here can be used for making a simple implementation or can be for used for testing implementations. Examples of results obtained with diacritic removal are: * `café` → `cafe` * `reünie` → `reunie` * `enquête` → `enquete` Note that the list with definitions also holds mappings for characters in superscript and subscript to normal characters. These are also many-to-one mappings for letters and numerails. Therefore, `e` cannot be converted back to `ë`, because the `a` could also originate from `ê`. The same applies for `2` with respect to `₂` and `²`. For this reason the converting of subscript and superscript is not part of case casting. Examples for when this relates to the Dutch language are: * H₂O → H2O * CO₂-emissie → CO2-emissie * 16m² → 16m2 * HNO₃-oplossing → HNO3-oplossing In the examples above, 16m² is a type of sailing boat and not sixteen square meters, which is properly written as 16 m² with a space between the number and the unit. Even though in these example no ambiguity is created, converting back on the basis of only inspecting separate characters is not possible. The definitions are found in [diacritic-removal.tsv](diacritic-removal.tsv) and counter examples, of where nothing changes, are found in [non-diacritic-removal.tsv](non-diacritic-removal.tsv). Documentation of the mapping is found in [diacritic-removal.png](diacritic-removal.png). Generated regular expressions, for usage in for example sed, are found in [diacritic-removal.sed](diacritic-removal.sed). A reference implementation for Python with testing functionality is in [implementation.py](implementation.py). ![Diacritic removal](diacritic-removal.png?raw=true "Diacritic removal") <file_sep>/document.sh ./preprocess.py dot -Tpng diacritic-removal.gv -odiacritic-removal.png <file_sep>/preprocess.py #!/usr/bin/env python3 import unicodedata if __name__ == '__main__': unique_characters = [] src_nodes = [] dst_nodes = [] edges = [] regexes = [] gv_file = open('diacritic-removal.gv', 'w') sed_file = open('diacritic-removal.sed', 'w') gv_file.write('''digraph G { layout="twopi" ranksep=1.5 fontsize=32 label="Removal of diacritics" labelloc="c" node [shape="box" fontsize=24 ] ''') with open('diacritic-removal.tsv', 'r') as input_file: for line in input_file: if line != '\n' and line[0] != '#': (char_src, char_dst) = line[:-1].split(' ') if char_src not in unique_characters: unique_characters.append(char_src) if char_dst not in unique_characters: unique_characters.append(char_dst) if char_src in src_nodes: print('ERROR') exit(1) else: src_nodes.append(char_src) if char_dst not in dst_nodes: dst_nodes.append(char_dst) edge = '"{}" -> "{}"'.format(char_src, char_dst) if edge in edges: print('ERROR') exit(1) else: edges.append(edge) regex = 's/{}/{}/g'.format(char_src, char_dst) if regex in regexes: print('ERROR') exit(1) else: regexes.append(regex) for node in dst_nodes: gv_file.write('"{}" [label=<<b>{}</b><br/><font point-size="8">{}</font>> ]\n'.format(node, node, unicodedata.name( node).replace('LETTER ', 'LETTER_').replace(' ', '<br/>').replace('LETTER_', 'LETTER ').lower())) gv_file.write('''node [style="rounded" ] ''') for node in src_nodes: gv_file.write('"{}" [label=<<b>{}</b><br/><font point-size="8">{}</font>> ]\n'.format(node, node, unicodedata.name( node).replace('LETTER ', 'LETTER_').replace(' ', '<br/>').replace('LETTER_', 'LETTER ').lower())) for edge in edges: gv_file.write('{}\n'.format(edge)) gv_file.write('''} ''') for regex in regexes: sed_file.write('{}\n'.format(regex)) <file_sep>/implementation.py #!/usr/bin/env python3 from unicodedata import category, name, normalize def desc(char): return name(char).lower() def remove_diacritics(s): return ''.join(c for c in normalize('NFKD', s.replace('ø', 'o').replace('Ø', 'O').replace('⁻', '-').replace('₋', '-')) if category(c) != 'Mn') if __name__ == '__main__': with open('diacritic-removal.tsv', 'r') as input_file: for line in input_file: if line == '\n' or line[0] == '#': continue (char_src, char_dst) = line[:-1].split(' ') char = remove_diacritics(char_src) if char != char_dst: print('ERROR: character {} "{}"\t\tconverses to {} "{}" instead of {} "{}"'.format(char_src, desc(char_src), char, desc(char), char_dst, desc(char_dst))) exit(1) else: print('INFO: character {} "{}"\t\tconverses to {} "{}"'.format(char_src, desc(char_src), char_dst, desc(char_dst))) with open('non-diacritic-removal.tsv', 'r') as input_file: for line in input_file: if line == '\n' or line[0] == '#': continue (char_src, char_dst) = line[:-1].split(' ') char = remove_diacritics(char_src) if char != char_dst: print('ERROR: character {} "{}"\t\tconverses to {} "{}" instead of {} "{}"'.format(char_src, desc(char_src), char, desc(char), char_dst, desc(char_dst))) exit(1) else: print('INFO: character {} "{}"\t\tconverses to {} "{}"'.format(char_src, desc(char_src), char_dst, desc(char_dst)))
21590429df5722803bf2f4929d0c73db8281650f
[ "Markdown", "Python", "Shell" ]
4
Markdown
OpenTaal/diacritic-removal
7b32c0a2eb0749a1390c0ffa17aa1ed846230f92
43ee74e789e028f99a6db93db55c9f4d7df22e48
refs/heads/master
<repo_name>andylsr/Hellow_World<file_sep>/Hellow_World.php <?php echo "Heloow World!" ?>
0947864bd9ff77987859298ee0b6dae441fb640f
[ "PHP" ]
1
PHP
andylsr/Hellow_World
95fa43577e3b519df7fa9a214fb76eee8f74bf7b
3ec603c61d671d382cbe185bb7fd97681b7c99e2
refs/heads/master
<repo_name>shikhar267/jsp-and-servlet<file_sep>/sendRedirectEx/WEB-INF/classes/servlet2.java import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class servlet2 extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException { PrintWriter out=null; response.setContentType("text/html"); out=response.getWriter(); out.println("hye servlet 2"); out.println("<br><br>bye servlet 2"); out.println("</body></html>"); } }<file_sep>/contextAttributeClass/WEB-INF/classes/RequestAttribute1.java import javax.servlet.http.*; import javax.servlet.*; import java.io.*; import java.sql.*; public class RequestAttribute1 extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { PrintWriter out=null; response.setContentType("text/html"); out=response.getWriter(); out.println("hello first servlet </br>"); ServletContext context=getServletContext(); context.setAttribute("company","INCAPP"); RequestDispatcher rd=request.getRequestDispatcher("s2"); rd.include(request,response); } }<file_sep>/rmi/server/Sum.java import java.rmi.*; public interface Sum extends Remote{ public int sum(int x,int y) throws RemoteException; } <file_sep>/README.md In this course we include all the files starting from our first app till the final project. To complete this course you need ide(netbeans or eclipse) and database(oracle or mysql). First start from our very first project first app. <file_sep>/loginlogoutappSESSION&LISTENER/README.md # ADVANCE-JAVA # login-logout-app # login-logout-app <file_sep>/httpServletListener/WEB-INF/classes/FirstServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class FirstServlet extends HttpServlet{ public void service(HttpServletRequest request,HttpServletResponse response){ response.setContentType("text/html"); PrintWriter out=null; try{ out=response.getWriter(); String n=request.getParameter("uname"); out.print("welcome"+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); ServletContext ctx=getServletContext(); int t=(Integer)ctx.getAttribute("Total session"); int c=(Integer)ctx.getAttribute("Current session"); out.print("<br>total session="+t); out.print("<br>current session="+c); out.print("<br><a href='logout'>logout</a>"); out.close(); } catch(Exception ex) { out.print(""+ex); } } }<file_sep>/rmi/client/MyClient.java import java.rmi.*; public class MyClient{ public static void main(String args[]){ try{ Sum stub=(Sum)Naming.lookup("rmi://localhost:1099/rmi"); System.out.println(stub.sum(34,4)); } catch(Exception e){ e.printStackTrace();} } } <file_sep>/servletContextListener/WEB-INF/classes/GetDataFromDB.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class GetDataFromDB extends HttpServlet{ public void service(HttpServletRequest request,HttpServletResponse response){ response.setContentType("text/html"); PrintWriter out=null; try{ out=response.getWriter(); ServletContext ctx=getServletContext(); Statement st=(Statement)ctx.getAttribute("stmt"); ResultSet rs=st.executeQuery("select * from emp_info"); while(rs.next()){ out.print("<br> "+ rs.getString(1)+ " :" +rs.getString(2)); } } catch(Exception e) { out.print(e); } out.close(); } } <file_sep>/jdbc/WEB-INF/classes/jdbcex.java import javax.servlet.http.*; import java.io.*; import java.sql.*; public class jdbcex extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) { PrintWriter out=null; try{ //PrintWriter out=null; response.setContentType("text/html"); out=response.getWriter(); Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE","root","incapp"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from emp_info"); while(rs.next()) { out.print("<br>"+rs.getString(1)+" : "+rs.getString(2)+ " : "+rs.getInt(3)+ " : "+rs.getInt(4)); } } catch(Exception ex) { out.println("exception:"+ex); } out.println("</body></html>"); } } <file_sep>/loginlogoutappSESSION&LISTENERwithhitcounter/WEB-INF/classes/Listener.java import javax.servlet.http.*; import java.io.*; import javax.servlet.*; import java.sql.*; public class Listener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","testdb","incapp"); Statement st=con.createStatement(); ServletContext ctx=event.getServletContext(); ctx.setAttribute("dbCon",con); ctx.setAttribute("stmt",st); } catch(Exception ex){ System.out.println(ex); } } public void contextDestroyed(ServletContextEvent e){} }<file_sep>/jdbcassign/WEB-INF/classes/jdbcassign.java import javax.servlet.http.*; import java.io.*; import java.sql.*; public class jdbcassign extends HttpServlet { public void service(HttpServletRequest request,HttpServletResponse response) { PrintWriter out=null; try{ //PrintWriter out=null; response.setContentType("text/html"); out=response.getWriter(); String i=request.getParameter("ee"); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","testdb","incapp"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from emp_info where eid='" + i + "'"); while(rs.next()) { out.print("<br>"+rs.getString(1)+" : "+rs.getString(2)+ " : "+rs.getInt(3)+ " : "+rs.getInt(4)); } } catch(Exception ex) { out.println("exception:"+ex); } out.println("</body></html>"); } }
8dbc4c4496e44c0dcf3892a6ef2a152bd809e150
[ "Markdown", "Java" ]
11
Java
shikhar267/jsp-and-servlet
055e84a9ba4fba180f67fdb7fe1d4a79f789b198
779630dd8e45b37ab0878f20b2412698d18af8a3
refs/heads/master
<file_sep>package com.bolsadeideas.springboot.reactor.app.models.documents; import java.util.Date; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Document(collection = "productos") @Data @NoArgsConstructor @AllArgsConstructor public class Producto { @Id private String id; private String nombre; private Double precio; private Date createAt; public Producto(String nombre, Double precio) { this.nombre = nombre; this.precio = precio; } }
ea728b6092e191d22bd74316a2ad59ab1097ab8b
[ "Java" ]
1
Java
saul9402/spring-boot-webflux
a4202299bfdb7995f56d4e1a56795e8e94b1f574
0a9173466ede4e7368577a824e96a4792016704e
refs/heads/master
<file_sep><?php declare(strict_types=1); namespace Murder; use pocketmine\scheduler\PluginTask; class MurderTimer extends PluginTask { /** * @param int $tick */ public function onRun(int $tick) { if ($this->owner instanceof MurderMain){ foreach ($this->owner->getArenas() as $arena) { $arena->tick(); } } } }
134e4e2e9b5ac5c86b2b219354d4490d056b5fb7
[ "PHP" ]
1
PHP
ElektroPrinz/Murder-Mystery
d7d5cd312e6f1298c24f3758b8c97e44e46ea85f
f7bc65c636262fa2c18770c83ad1c879229bf6e8
refs/heads/master
<file_sep>import React from 'react' import { FaGithub, FaInstagram, FaLinkedin } from 'react-icons/fa' const data = [ { id: 1, icon: <FaGithub className='social-icon' />, url: 'https://github.com/thienry' }, { id: 2, icon: <FaInstagram className='social-icon' />, url: 'https://instagram.com/thienry' }, { id: 3, icon: <FaLinkedin className='social-icon' />, url: 'https://www.linkedin.com/in/thiagotechdev/' }, ] const links = data.map(link => { return ( <li key={link.id}> <a href={link.url} target="_blank" rel="noreferrer" className='social-link'> {link.icon} </a> </li> ) }) export default ({ styleClass }) => { return ( <ul className={`social-links ${styleClass ? styleClass : ''}`}> {links} </ul> ) }<file_sep>import React from 'react' import Title from '../layout/Title' import strengths from '../../constants/strengths' function Strengths() { return ( <section className="section bg-grey"> <Title title='Skills' /> <div className="section-center strengths-center"> {strengths.map(strength => { const { id, icon, title } = strength return ( <article key={id} className='strength'> {icon} <h4>{title}</h4> <div className="underline"></div> </article> ) })} </div> </section> ) } export default Strengths<file_sep>import React, { useState, useEffect } from 'react' import PropTypes from 'prop-types' import { useStaticQuery, graphql } from 'gatsby' import Navbar from './Navbar' import Sidebar from './Sidebar' import Footer from './Footer' import ScrollToTop from '../utils/ScrollToTop' const Layout = ({ children, styleNav, styleContainer, isActive }) => { const data = useStaticQuery(graphql` query SiteTitleQuery { site { siteMetadata { title } } } `) const [isOpen, setIsOpen] = useState(false) useEffect(() => { window.addEventListener('load', () => { const navScroll = document.querySelector('nav') const scrollTop = document.querySelector('.scroll-to') navScroll.classList.add('sticky', window.scrollY > 10) scrollTop.classList.add('scroll-to-top', window.scrollY > 700) }) window.addEventListener('scroll', () => { const navScroll = document.querySelector('nav') const scrollTop = document.querySelector('.scroll-to') navScroll.classList.toggle('sticky', window.scrollY > 0) scrollTop.classList.toggle('scroll-to-top', window.scrollY > 700) scrollTop.classList.toggle('scroll-fadeout', window.scrollY < 800) }) }, []) function toggleSidebar() { setIsOpen(!isOpen) } return ( <> <div id="top" className={`content ${styleContainer ? styleContainer : ''}`}> <Navbar isActive={isActive} styleNav={styleNav} toggleSidebar={toggleSidebar} siteTitle={data.site.siteMetadata.title} /> <Sidebar isOpen={isOpen} toggleSidebar={toggleSidebar} /> <main>{children}</main> </div> <ScrollToTop /> <Footer /> </> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout <file_sep><h1 align="center">Bem vindo à Thiagotec 👋</h1> <p> <img alt="Version" src="https://img.shields.io/badge/version-2.0.0-blue.svg?cacheSeconds=2592000" /> <a href="https://github.com/gatsbyjs/gatsby-starter-default/graphs/commit-activity" target="_blank"> <img alt="Maintenance" src="https://img.shields.io/badge/Maintained%3F-yes-green.svg" /> </a> <a href="#" target="_blank"> <img alt="License: MIT" src="https://img.shields.io/github/license/thienry/Thiagotec" /> </a> <a href="https://twitter.com/thienry" target="_blank"> <img alt="Twitter: thienry" src="https://img.shields.io/twitter/follow/thienry.svg?style=social" /> </a> </p> > A portfolio & blog personal app ### 🏠 [Homepage](https://thiagotec.com) ## Install ```sh yarn install ``` ## Usage ```sh yarn dev ``` ## Author 👤 **<NAME> <<EMAIL>>** * Website: http://thiagotec.com * Twitter: [@thienry](https://twitter.com/thienry) * Github: [@thienry](https://github.com/thienry) * LinkedIn: [@thiagotechdev](https://linkedin.com/in/thiagotechdev) ## 🤝 Contributing Contributions, issues and feature requests are welcome!<br />Feel free to check [issues page](https://github.com/thienry/thiagotec-2.0/issues). ## Show your support Give a ⭐️ if this project helped you! *** _This README was generated with ❤️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_<file_sep>import React from 'react' import { Link } from 'gatsby' import PropTypes from 'prop-types' import { FaAlignRight } from 'react-icons/fa' import PageLinks from '../../constants/links' function Navbar({ siteTitle, toggleSidebar, styleNav, isActive }) { return ( <nav className={`navbar ${styleNav ? styleNav : ''}`}> <div className="nav-center"> <div className="nav-header"> <h1 className='nav-title'> <Link to="/">{siteTitle}</Link> </h1> <button type='button' className='toggle-btn' onClick={toggleSidebar}> <FaAlignRight /> </button> </div> <PageLinks isActive={isActive} styleClass='nav-links' /> </div> </nav> ) } Navbar.propTypes = { siteTitle: PropTypes.string.isRequired, toggleSidebar: PropTypes.func.isRequired, } export default Navbar<file_sep>import React from 'react' import { Link } from 'gatsby' import Layout from '../components/layout/layout' import SEO from '../components/utils/seo' const NotFoundPage = () => ( <Layout styleContainer="page-container" styleNav='nav-bg-color'> <SEO title="404: Not found" description="Houston, we have a problem..." /> <main className="error-page"> <div className="error-container"> <h1>oops, parece que você está perdido...</h1> <Link to="/" className="btn">voltar para a home</Link> </div> </main> </Layout> ) export default NotFoundPage <file_sep>import React from 'react' import { useForm } from '../components/utils/hooks' import Layout from '../components/layout/layout' import SEO from '../components/utils/seo' function Contact() { function validateContactForm(values) { let errors = {} const strippedName = values.name.trim().replace(/<\/?[^>]+(>|$)/g, '') const strippedEmail = values.email.trim().replace(/<\/?[^>]+(>|$)/g, '') const strippedMessage = values.message.trim().replace(/<\/?[^>]+(>|$)/g, '') if (strippedName === '') errors.name = 'Por favor, preencha o campo nome.' if (strippedEmail === '') errors.email = 'Por favor, preencha o campo email.' if (strippedMessage === '') errors.message = 'Por favor, preencha o campo mensagem.' return errors } const { values, errors, onChange, onSubmit } = useForm({ name: '', email: '', message: '' }, validateContactForm) return ( <Layout styleContainer="page-container" styleNav='nav-bg-color'> <SEO title='Contato' description="Entre em contato" /> <section className="contact-page"> <article className="contact-form"> <h3>Entre em contato</h3> <form onSubmit={onSubmit} action="https://formspree.io/xnqgpwjp" method="POST"> <div className="form-group"> <input type="text" name="name" value={values.name} onChange={onChange} placeholder="nome" className="form-control" aria-label="name" /> {errors.name && (<span className="form-validation">{errors.name}</span>)} <input type="email" name="email" value={values.email} onChange={onChange} placeholder="email" className="form-control" aria-label="email" /> {errors.email && (<span className="form-validation">{errors.email}</span>)} <textarea name="message" rows="5" value={values.message} onChange={onChange} placeholder="Mensagem" className="form-control" aria-label="message" ></textarea> {errors.message && (<span className="form-validation">{errors.message}</span>)} </div> <button type="submit" className="submit-btn btn">Enviar</button> </form> </article> </section> </Layout> ) } export default Contact <file_sep>import React from 'react' import { Link } from 'gatsby' import PropTypes from 'prop-types' import Title from '../layout/Title' import Project from '../utils/Project' function Projects({ projects, title, showLink }) { return ( <section className="section projects"> <Title title={title} /> <div className="section-center projects-center"> {projects.map((project, idx) => ( <Project key={project.id} idx={idx} {...project} /> ))} </div> {showLink && ( <Link to="/projetos/" className="btn center-btn" activeClassName="nav-active"> projetos </Link> )} </section> ) } Projects.propTypes = { title: PropTypes.string.isRequired, } export default Projects<file_sep>import React from 'react' import { Link } from 'gatsby' import { FaChevronUp } from 'react-icons/fa' function ScrollToTop() { return ( <Link className="scroll-to" to="#top"> <FaChevronUp /> </Link> ) } export default ScrollToTop <file_sep>module.exports = { siteMetadata: { title: `ThiagoTec`, description: `A portfolio & blog personal site.`, author: `@thienry`, twitterUsername: "@thienry14", siteUrl: `https://thiagotec.com`, image: `/thiagotec.png` }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `Thiagotec`, short_name: `Thiagotec`, start_url: `/`, background_color: `#1f4068`, theme_color: `#1f4068`, display: `minimal-ui`, icon: `src/images/thiagotec.png`, // This path is relative to the root of the site. }, }, { resolve: `gatsby-source-strapi`, options: { apiURL: `https://thiagotec-api.herokuapp.com`, queryLimit: 1000, contentTypes: [`jobs`, `projects`, `blogs`], singleTypes: [`about`], } }, { resolve: `@el7cosmos/gatsby-plugin-prefetch-google-fonts`, options: { fonts: [ { family: `Roboto`, variants: [`400`, `700`] }, { family: `Open Sans` }, { family: `Poppins` } ] } }, { siteMetadata: { siteUrl: `https://thiagotec.com`, }, resolve: `gatsby-plugin-sitemap`, }, { resolve: `gatsby-plugin-disqus`, options: { shortname: `thiagotec-com-1` } }, { resolve: `gatsby-plugin-nprogress`, options: { // Setting a color is optional. color: `tomato`, // Disable the loading spinner. showSpinner: false, }, }, { resolve: `gatsby-plugin-google-analytics`, options: { // The property ID; the tracking code won't be generated without it trackingId: "UA-162098046-1", }, }, { resolve: `gatsby-plugin-google-adsense`, options: { publisherId: `pub-7506061554414091` }, }, { resolve: `gatsby-plugin-canonical-urls`, options: { siteUrl: `https://www.thiagotec.com`, }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline `gatsby-plugin-offline`, /*{ resolve: `gatsby-source-instagram`, options: { type: `user-profile`, username: `thienry`, }, }*/ ], } <file_sep>import React from 'react' import { graphql } from 'gatsby' import Layout from '../components/layout/layout' import SEO from '../components/utils/seo' import Projects from '../components/sections/Projects' function ProjectsPage({ data }) { const { allStrapiProjects: { nodes: projects } } = data return ( <Layout styleContainer="page-container" styleNav='nav-bg-color'> <SEO title='Projetos' description="Dá uma olhadinha nos meus projetos!" /> <section className="projects-page"> <Projects projects={projects} title='Projetos' /> </section> </Layout> ) } export const query = graphql` { allStrapiProjects { nodes { id name description github url image { childImageSharp { fluid { ...GatsbyImageSharpFluid } } } tech { id name } } } } ` export default ProjectsPage<file_sep>import React, { useState } from 'react' import { graphql, useStaticQuery } from 'gatsby' import { FaAngleDoubleRight } from 'react-icons/fa' import Title from '../layout/Title' const query = graphql` { allStrapiJobs(sort: {fields: strapiId}) { nodes { strapiId company role date description { id name } } } } ` function Jobs() { const data = useStaticQuery(query) const { allStrapiJobs: { nodes: jobs } } = data const [value, setValue] = useState(0) const { company, role, date, description } = jobs[value] return ( <section className="section jobs bg-white"> <Title title="Experiências" /> <div className="jobs-center"> <div className="btn-container"> {jobs.map((item, idx) => ( <button key={item.strapiId} onClick={() => setValue(idx)} className={`job-btn ${idx === value && "active-btn"}`} > {item.company} </button> ))} </div> <article className="job-info"> <h3>{role}</h3> <h4>{company}</h4> <p className="job-date">{date}</p> {description.map(item => ( <div className="job-desc" key={item.id}> <FaAngleDoubleRight className="job-icon" /> <p>{item.name}</p> </div> ))} </article> </div> </section> ) } export default Jobs
040c88bd0647a7c2b134f0e10b969cc0e149bcdd
[ "JavaScript", "Markdown" ]
12
JavaScript
thienry/thiagotec
516df4cc38c97a748eb41862e2a7a7b12fc944d5
63ffb2ca801f19d03bce7b5597e60a8c4bf1126b
refs/heads/master
<file_sep># Org1 chaincode id: fabcar:1e4ff6bbecf64ccc6ae6c9a8738827943da69de5b1e165762d9484b6134b1ebd # Org2 chaincode id: fabcar:22713a8d18b1e0d90252c918786dfe37afb919dad5ee5b6ee9568e8a170d50eb ORDERER_CA=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/msp/tlscacerts/tlsca.example.com-cert.pem microk8s.kubectl exec cliorg1 -- peer lifecycle chaincode \ install /opt/gopath/src/github.com/chaincode/packing/fabcar-org1.tar.tgz microk8s.kubectl exec cliorg2 -- peer lifecycle chaincode \ install /opt/gopath/src/github.com/chaincode/packing/fabcar-org2.tar.tgz microk8s.kubectl exec cliorg1 -- peer lifecycle chaincode approveformyorg \ --channelID tworgschannel --name fabcar --version 1.0 --init-required \ --package-id fabcar:1e4ff6bbecf64ccc6ae6c9a8738827943da69de5b1e165762d9484b6134b1ebd \ --sequence 1 -o orderer:7050 --tls --cafile $ORDERER_CA microk8s.kubectl exec cliorg2 -- peer lifecycle chaincode approveformyorg \ --channelID tworgschannel --name fabcar --version 1.0 --init-required \ --package-id fabcar:22713a8d18b1e0d90252c918786dfe37afb919dad5ee5b6ee9568e8a170d50eb \ --sequence 1 -o orderer:7050 --tls --cafile $ORDERER_CA microk8s.kubectl exec cliorg1 -- peer lifecycle chaincode commit -o orderer:7050 \ --channelID tworgschannel --name fabcar --version 1.0 --sequence 1 --init-required \ --tls --cafile $ORDERER_CA --peerAddresses peer0org1:7051 --tlsRootCertFiles \ /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt --peerAddresses peer0org2:7051 --tlsRootCertFiles \ /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt<file_sep>#!/bin/bash export FABRIC_CFG_PATH=${PWD} rm -fr crypto-config/* rm -fr config/* cryptogen generate --config=crypto-config.yaml configtxgen -profile OrgOrdererGenesis --channelID testchainid -outputBlock ./config/genesis.block configtxgen -profile TwoOrgsChannel -outputCreateChannelTx ./config/tworgschannel.tx -channelID tworgschannel configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./config/Org1MSPanchors.tx -channelID tworgschannel -asOrg Org1MSP configtxgen -profile TwoOrgsChannel -outputAnchorPeersUpdate ./config/Org2MSPanchors.tx -channelID tworgschannel -asOrg Org2MSP <file_sep>TWOORGSCHANNEL_TX=/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/channel-artifacts/tworgschannel.tx ORG1ANCHORPEER=/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/channel-artifacts/Org1MSPanchors.tx ORDERER_CA=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/msp/tlscacerts/tlsca.example.com-cert.pem microk8s.kubectl exec cliorg1 -- peer channel create \ -c tworgschannel -o orderer:7050 -f $TWOORGSCHANNEL_TX --tls \ --cafile $ORDERER_CA --outputBlock tworgschannel.block microk8s.kubectl exec cliorg1 -- peer channel update \ -c tworgschannel -o orderer:7050 -f $ORG1ANCHORPEER --tls --cafile $ORDERER_CA microk8s.kubectl exec cliorg1 -- peer channel join \ -o orderer:7050 -b tworgschannel.block --tls --cafile $ORDERER_CA #microk8s.kubectl exec cliorg1 -- env CORE_PEER_ADDRESS=peer1org1:7051; \ # peer channel join \ # -o orderer:7050 -b tworgschannel.block --tls --cafile $ORDERER_CA ORG2ANCHORPEER=/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/channel-artifacts/Org2MSPanchors.tx microk8s.kubectl exec cliorg2 -- peer channel update \ -c tworgschannel -o orderer:7050 -f $ORG2ANCHORPEER --tls --cafile $ORDERER_CA microk8s.kubectl exec cliorg2 -- peer channel fetch oldest tworgschannel.block \ -c tworgschannel -o orderer:7050 --tls --cafile $ORDERER_CA microk8s.kubectl exec cliorg2 -- peer channel join \ -o orderer:7050 -b tworgschannel.block --tls --cafile $ORDERER_CA
e4bfb3081d7dbf050639f4aa6d1f3857ea1872fd
[ "Shell" ]
3
Shell
mauricioxzaparoli/blockchain-network
a33a3979bc207d7811c5f8d65e1240aa9c6f04a8
2b6ea00a702480f88bcc36c8a0f4d8a956425178
refs/heads/master
<repo_name>MQTTCool/Docker<file_sep>/1.1/jre8/Dockerfile # Set the base image FROM openjdk:8-jre LABEL maintainer="Lightstreamer Server Development Team <<EMAIL>>" # Set environment variables to identify the right Lightstreamer version and edition ENV MQTTCOOL_VERSION 1_1_0_20180330 ENV MQTTCOOL_URL_DOWNLOAD http://www.lightstreamer.com/repo/distros/mqtt.cool_${MQTTCOOL_VERSION}.tar.gz # Install the required packages RUN set -ex; \ mkdir /mqtt.cool && cd /mqtt.cool \ # Import Lighstreamer's public key && gpg --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys <KEY> \ # Download the distribution from the Lightstreamer site, verify the signature, and unpack && curl -fSL -o mqtt.cool.tar.gz ${MQTTCOOL_URL_DOWNLOAD} \ && curl -fSL -o mqtt.cool.tar.gz.asc ${MQTTCOOL_URL_DOWNLOAD}.asc \ && gpg --batch --verify mqtt.cool.tar.gz.asc mqtt.cool.tar.gz \ && tar -xvf mqtt.cool.tar.gz --strip-components=1 \ # Replace the fictitious jdk path with the JAVA_HOME environment variable in the launch script file && sed -i -- 's/\/usr\/jdk1.8.0/$JAVA_HOME/' bin/unix-like/mc.sh \ # Addjust logging configurations in order to log only on standard output && sed -i -e 's/<appender-ref ref="LSDailyRolling" \/>/<appender-ref ref="LSConsole" \/>/' \ -e '/<logger name="LightstreamerLogger.init/,+2s/<appender-ref ref="LSConsole" \/>/<!-- <appender-ref ref="LSConsole" \/> -->/' \ -e '/<logger name="LightstreamerLogger.license/,+2s/<appender-ref ref="LSConsole" \/>/<!-- <appender-ref ref="LSConsole" \/> -->/' \ conf/lightstreamer_log_conf.xml \ && sed -i 's/<appender-ref ref="MQTTCoolRolling" \/>/<appender-ref ref="LSConsole" \/>/' mqtt_connectors/mqtt_master_connector_log_conf.xml \ # Finally, remove no longer needed files && rm mqtt.cool.tar.gz mqtt.cool.tar.gz.asc # Export TCP port 8080 EXPOSE 8080 # Set the final working dir WORKDIR /mqtt.cool/bin/unix-like # Start the server CMD ["./mc.sh", "run"] <file_sep>/build.sh #!/bin/bash VERSION=$1 if [ -z "$VERSION" ]; then echo "Please specify a version" exit 1 fi docker build ${VERSION} -t mqttcool/mqtt.cool:${VERSION} --no-cache docker tag mqttcool/mqtt.cool:${VERSION} mqttcool/mqtt.cool:latest docker push mqttcool/mqtt.cool:${VERSION} docker push mqttcool/mqtt.cool:latest <file_sep>/README.md # What is MQTT.Cool? MQTT.Cool is a gateway designed for boosting existing MQTT brokers by extending their native functionalities with new out-of-the-box cool features. For more information and related downloads for the MQTT.Cool server and MQTT.Cool related products, please visit [mqtt.cool](https://mqtt.cool). ![](https://github.com/MQTTCool/Docker/raw/master/logo.png) # How to use this image ## Up and Running Launch the container with the default configuration: ```console $ docker run --name mc-server -d -p 8080:8080 mqttcool/mqtt.cool ``` This will map port 8080 inside the container to port 8080 on local host. Then point your browser to `http://localhost:8080` and watch the Welcome page from which you can launch the Test Client, a handy tool for testing the interaction between the MQTT.Cool server and any external MQTT broker. Furthermore, you can be redirected to the source code examples available on [GitHub](http://github.com/MQTTCool). ## Custom settings It is possible to customize each aspect of the MQTT.Cool instance running into the container. For example, a specific configuration file may be supplied as follows: ```console $ docker run --name mc-server -v /path/to/my-mqtt_master_connector_conf.xml:/mqtt.cool/mqtt_connectors/mqtt_master_connector_conf.xml -d -p 8080:8080 mqttcool/mqtt.cool ``` In the same way, you could provide a custom logging configuration, maybe in this case also specifying a dedicated volume to ensure both the persistence of log files and better performance of the container: ```console $ docker run --name mc-server -v /path/to/my-mqtt_master_connector_log_conf.xml:/mqtt.cool/mqtt_connectors/mqtt_master_connector_conf.xml -v /path/to/logs:/mqtt.cool/logs -d -p 8080:8080 mqttcool/mqtt.cool ``` If you also change in your `my-mqtt_master_connector_log_conf.xml` file the default logging path from `../logs` to `/path/to/dest/logs`: ```console $ docker run --name mc-server -v /path/to/my-mqtt_master_connector_log_conf.xml:/mqtt.cool/mqtt_connectors/mqtt_master_connector_conf.xml -v /path/to/hosted/logs:/path/to/dest/logs -d -p 8080:8080 mqttcool/mqtt.cool ``` Alternatively, the above tasks can be executed by deriving a new image through a `Dockerfile` as the following: ```dockerfile FROM mqttcool/mqtt.cool # Please specify a COPY command only for the the required custom configuration files COPY my-mqtt_master_connector_conf.xml /mqtt.cool/mqtt_connectors/mqtt_master_connector_conf.xml COPY my-mqtt_master_connector_log_conf.xml /mqtt.cool/mqtt_connectors/mqtt_master_connector_log_conf.xml ``` where `my-mqtt_master_connector_conf.xml` and `my-mqtt_master_connector_log_conf.xml` are your custom configuration files, placed in the same directory as the Dockerfile. By simply running the command: ```console $ docker build -t my-mqttcool . ``` the new image will be built along with the provided files. After that, launch the container: ```console $ docker run --name mc-server -d -p 8080:8080 my-mqttcool ``` To get more detailed information on how to configure the MQTT.Cool server, please see the inline documentation in the `mqtt_master_connector_conf.xml` and `mqtt_master_connector_log_conf.xml` files you can find under the `mqtt_connectors` folder of the installation directory. ## Deployment of web server pages There might be some circumstances where you would like to provide custom pages for the internal web server of the MQTT.Cool server. Even in this case, it is possible to customize the container by employing the same techniques as above. For example, with the following command you will be able to fully replace the factory `pages` folder: ```console $ docker run --name mc-server -v /path/to/custom/pages:/mqtt.cool/pages -d -p 8080:8080 mqttcool/mqtt.cool ``` where `/path/to/custom/pages` is the path in your host machine containing the replacing web content files. ## License View [license information](https://get.mqtt.cool/server/1.2.0/Lightstreamer+Software+License+Agreement.pdf) for the software contained in this image.<file_sep>/2.1.0/Dockerfile # Set the base image FROM openjdk:11-jdk-slim-stretch LABEL maintainer="MQTT.Cool Server Development Team <<EMAIL>>" # Set environment variables to identify the right MQTT.Cool version and edition ENV MQTTCOOL_VERSION 2.1.0 ENV MQTTCOOL_URL_DOWNLOAD https://get.mqtt.cool/server/${MQTTCOOL_VERSION}/mqtt.cool-${MQTTCOOL_VERSION}.tar.gz # Install the required packages RUN set -ex; \ mkdir /mqtt.cool \ && cd /mqtt.cool \ && apt-get update \ && apt-get install -y --no-install-recommends gnupg dirmngr curl \ && rm -rf /var/lib/apt/lists/* \ # Import Lighstreamer's public key && gpg --batch --keyserver hkp://keyserver.ubuntu.com --recv-keys <KEY> \ # Download the distribution from the MQTT.Cool site, verify the signature, and unpack && curl -fSL -o mqtt.cool.tar.gz ${MQTTCOOL_URL_DOWNLOAD} \ && curl -fSL -o mqtt.cool.tar.gz.asc ${MQTTCOOL_URL_DOWNLOAD}.asc \ && gpg --batch --verify mqtt.cool.tar.gz.asc mqtt.cool.tar.gz \ && tar -xvf mqtt.cool.tar.gz --strip-components=1 \ # Replace the fictitious jdk path with the JAVA_HOME environment variable in the launch script file && sed -i -- 's/\/usr\/jdk-11/$JAVA_HOME/' bin/unix-like/mc.sh \ # Addjust logging configurations in order to log only to the standard output && sed -i -e 's/<appender-ref ref="LSDailyRolling" \/>/<appender-ref ref="LSConsole" \/>/' \ -e 's/<appender-ref ref="MQTTCoolRolling" \/>/<appender-ref ref="LSConsole" \/>/' \ -e '/<logger name="LightstreamerLogger.init/,+2s/<appender-ref ref="LSConsole" \/>/<!-- <appender-ref ref="LSConsole" \/> -->/' \ -e '/<logger name="LightstreamerLogger.license/,+2s/<appender-ref ref="LSConsole" \/>/<!-- <appender-ref ref="LSConsole" \/> -->/' \ conf/log_configuration.xml \ # Add new user and group && groupadd -r -g 10000 mqttcool \ && useradd --no-log-init -r -g mqttcool -u 10000 mqttcool \ # Change ownership of tye mqtt.cool folder && chown -R mqttcool:mqttcool ../mqtt.cool \ # Finally, remove no longer needed files && rm mqtt.cool.tar.gz mqtt.cool.tar.gz.asc \ && apt-get remove -y gnupg dirmngr curl USER mqttcool # Export TCP port 8080 EXPOSE 8080 # Set the final working dir WORKDIR /mqtt.cool/bin/unix-like # Start the server CMD ["./mc.sh", "run"]
d3e44d421acee8a56dc3c7feb2111f78b88b0f95
[ "Markdown", "Dockerfile", "Shell" ]
4
Dockerfile
MQTTCool/Docker
d670f6f9c3e822a2db3f9b27b42712bf6cc84ba8
96164fd0c7c3d8b52ab3bdc1063c6f31edeca7cf
refs/heads/main
<file_sep>import javax.swing.*; import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.util.LinkedList; import java.util.List; public class WuZiQi extends JPanel{ final static int heigth = 1000; final static int width = 1000; private static JLabel label; private List<Circle> circles = new LinkedList<Circle>(); public void addC(Circle circle) { circles.add(circle); this.repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.drawLine(50,50, 950,50); g.drawLine(950,50, 950,950); g.drawLine(50,50, 50,950); g.drawLine(50,950, 950,950); for(int i = 110; i <= 900; i = i + 60) { g.drawLine(i,50, i,950); g.drawLine(50, i, 950, i); } for(Circle c : circles) { c.draw(g); } //Cliker temp = new Cliker(); //frame.getContentPane().addMouseListener(temp); //super.addMouseListener(temp); } public static void main(String[] args) { // TODO Auto-generated method stub //JPanel panel = new JPanel(); JFrame frame = new JFrame(); WuZiQi k = new WuZiQi(); label = new JLabel("ChessGameVersion 2.0"); Cliker temp = new Cliker(k); frame.getContentPane().addMouseListener(temp); //CirclePanel temp = new CirclePanel(); //frame.setContentPane(temp); //temp.addMouseListener(new Cliker(temp)); frame.setTitle("Test"); frame.setSize(heigth, width); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.add(k); k.add(label); k.setBackground(Color.GRAY); //panel.add(test2); } }
edd24c18c204742bd6f9b8c6a0c470467ac59406
[ "Java" ]
1
Java
Kka1i/GomokuGame
9a633f753e95a6376bb37bc849a72bac70d21725
2edcdbeb0df43e89a3c5853a9883a8694b0d400b
refs/heads/master
<repo_name>kiritooshi/canvas-latex-type<file_sep>/README.md # canvas-latex-type # References https://github.com/CurriculumAssociates/canvas-latex <file_sep>/index.d.ts // Type definitions for canvaslatextype // Project: [LIBRARY_URL_HERE] // Definitions by: [YOUR_NAME_HERE] <[YOUR_URL_HERE]> // Definitions: https://github.com/borisyankov/DefinitelyTyped //export as namespace CanvasLatex; declare namespace CanvasLatex { export function init(latex: any, options: any): any; export function distanceToBaseline(): any; export function getBounds(): any; } declare module "canvas-latex-type" { export = CanvasLatex; //legacy ts module export } <file_sep>/index.js let CanvasLatex = require("./canvas-latex"); exports.init = init; exports.distanceToBaseline = distanceToBaseline; exports.getBounds = getBounds; let _widget; function init(latex = "", options = {}) { _widget = new CanvasLatex.default(latex, options); return _widget; } function distanceToBaseline() { return _widget.distanceToBaseline; } function getBounds() { return _widget.getBounds(); }
227e11e4123f8a0b01293baa17bb2eccc279a908
[ "Markdown", "TypeScript", "JavaScript" ]
3
Markdown
kiritooshi/canvas-latex-type
738aa984a9cfb3edd4336047b214d8c6c6449d4e
22bc397902ae79180ffad7edd42d850454ed9c87
refs/heads/master
<repo_name>MattWilki/ArisMacys<file_sep>/features/step_definitions/my_steps.rb rndo = rand(1..10000) Given(/^a user goes to Macys\.com$/) do @browser.goto "http://macys.com" end When(/^the user enters appropriate (.*) in the search box$/) do |content| @browser.text_field(:name => "keyword").set "#{content}" @browser.send_keys :enter end Then(/^it will return with (.*)$/) do |results| if @browser.text.include? "#{results}" else @browser.screenshot.save "MacysSearchBarTest#{rndo}.png" scenario.fail end end Given(/^the user goes to Macys\.com$/) do @browser.goto "http://Macys.com" end When(/^they begin typing appropriate (.*) in the search box$/) do |content| @browser.text_field(:name => "keyword").set "#{content}" sleep 1 end Then(/^they will be offer a dropdown of potential (.*)$/) do |results| if @browser.text.include? "#{results}" else scenario.fail end end Given(/^an user goes to Macys\.co$/) do @browser.goto "http://Macys.com" end And(/^they start typing appropriate content in the search box (.*)$/) do |arg| @browser.text_field(:name => "keyword").set "#{arg}" sleep 4 end When(/^they click in any of the (.*) drop down results$/) do |potential| @browser.div(:text => "#{potential}").when_present.click end Then(/^they will return appropriate results of (.*)$/) do |search| if @browser.text.include? "#{search}" else scenario.fail end end Given(/^user goes to Macys\.com$/) do @browser.goto "http://Macys.com" end When(/^the user inputs a value in the search box that is not in the system$/) do @browser.text_field(:name => "keyword").set "alodpnf" @browser.send_keys :enter end Then(/^they will get a result saying We found zero results for$/) do if @browser.text.include? "We found 0 results for" else scenario.fail end end<file_sep>/features/support/env.rb require 'cucumber' require 'watir-webdriver' Before do @browser = Watir::Browser.new :ff @browser.window.maximize end After do @browser.close end
a74f572b85dd0eda7678c7f96f6cfdfc5732b5b7
[ "Ruby" ]
2
Ruby
MattWilki/ArisMacys
9401aae7fee86eaf5b45dee192904c06e72f4ac7
4356206f2a8c787d705720ee9b75dfcc03614658
refs/heads/maindev
<file_sep>import React, { useState, useEffect } from 'react' import BlogHeader from './BlogHeader' import BlogList from './BlogList' const BlogHomePage = () => { const [isLoading, setIsLoading] = useState(true) // Replace set date et.c with set BlogPosts const [blogPosts, setBlogPosts] = useState([]) const imageUrl = 'images/blog/' // Arrange items by date - most recent first const sortPostsMostRecent = (array) => array.sort((a, b) => { const c = new Date(a.post_date) const d = new Date(b.post_date) return d - c }) useEffect(() => { const allBlogPostsURL = `https://josephfletcher.co.uk/blog-backend/api/blogposts` fetch(allBlogPostsURL, {}) .then((res) => res.json()) .then((response) => { setBlogPosts(sortPostsMostRecent(response)) setIsLoading(false) }) .catch((error) => console.log(error)) }, []) // Transact On The State // Functions return ( <> {!isLoading ? ( <> <BlogHeader blogArray={blogPosts[0]} imageUrl={imageUrl} /> <BlogList blogArray={blogPosts} imageUrl={imageUrl} /> </> ) : null} </> ) } export default BlogHomePage <file_sep>## Blog App - React Frontend The front end of a blogging app, displaying blogposts using React. Consists of two main pages, the front page displaying summary information for all blogposts, and an individual blogpost page showing the blogpost in full. Built using React and Bootstrap. Data comes from API located at http://josephlfletcher.co.uk/blog-backend/api/. Eslint and prettier are set up to ensure code meets acceptable standards. Live version hosted on AWS EC2 Instance, served using NginX at my personal domain [josephfletcher.co.uk](https://josephfletcher.co.uk/blog). ## Project Status This is the MVP. Need to add navbar and footer, and add functionality to sort blogposts by tag, date, and to search. ## Project Screen Shot(s) #### Example: ## Installation and Setup Instructions Clone down this repository. You will need `node` and `npm` installed globally on your machine. Installation: `npm install` To Start Server: `npm start` To Visit App: `http://localhost:3000/blog` ## Reflection This was a project I undertook while learning React. I set out to build a simple blog, that would display articles automatically as they are added, with minimal input when it comes to updating the layout. As such the aim is to allow the user/admin to select the header article, the 4 leading articles, and then the rest will load below. It dovetails with another main project I'm undertaking (essentialcoaching.co.uk) and the next step will be to add this front end to replace the current blog page on that project, and allow the client to update blogposts as and when they like. One of the main challenges, or areas that still needs to be addressed is that of security. Allowing the user to display formatted text in the main body means that currently I'm using the dangerouslySetInnerHTML property which can leave the site open to XSS attacks. Although in this situation, there is only a single user accessing the backend, and therefore the risk is low, a next step would be to make that part of the process more secure. Another challenge was getting the routing correct across the server and the static files as in testing I was hosting the react app at the localhost route, but then in production I switched it to /blog. It won't be a problem next time now I'm clear how it all works, and all the various places I need to update routes, but as a learning exercise it was very valuable. I chose to use the `create-react-app` boilerplate to minimize initial setup and invest more time in learning the fundamentals of how react works. In the next iteration I plan on starting from scratch and creating a `webpack.config.js` file to more fully understand the build process. <file_sep>import React, { useState, useEffect } from 'react' import { Link } from 'react-router-dom' import { DateTime } from 'luxon' const BlogDetailPage = ({ match, location }) => { const { params: { blogId }, } = match // Initialise the State const [isLoading, setIsLoading] = useState(true) const [blogPost, setBlogPosts] = useState([]) const imageUrl = 'images/blog/' useEffect(() => { if (location.transferData !== undefined) { setBlogPosts(location.transferData.blogData) setIsLoading(false) } else { const nodeBlogURL = 'https://josephfletcher.co.uk/blog-backend/api/blogpost' fetch(`${nodeBlogURL}/${blogId}`, {}) .then((res) => res.json()) .then((response) => { setBlogPosts(response) setIsLoading(false) }) .catch((error) => console.log(error)) } }, [location.transferData, blogId]) // Transact on State let tagList if (!isLoading) { tagList = blogPost.tags.map((tag) => tag.name) } return ( <> {!isLoading ? ( <> <div className="container-fluid p-3 p-md-4 mb-4 text-white rounded d-flex flex-column justify-content-center align-items-center"> <div className="h-100 col-lg-8 py-mid-4 d-flex flex-column align-items-start"> <h1 className="display-5 font-italic text-dark"> {blogPost.title} </h1> <div className="w-100 mt-auto d-flex flex-row justify-content-between"> <i style={{ color: '#f7882f' }} className=""> {blogPost.author.first_name} {blogPost.author.family_name} </i> <i className="text-muted mb-0"> {DateTime.fromISO(blogPost.post_date).toLocaleString( DateTime.DATE_MED )} </i> </div> <p className="lead text-dark my-3">{blogPost.summary}</p> </div> <div className="col-lg-8 d-flex justify-content-center"> <img className="py-md-3 w-75 h-auto bg-light rounded-circle mb-3" src={`${imageUrl}${blogPost.image_filename}`} alt="Generic placeholder" /> </div> <div className="order-md-0 col-lg-8 px-0 text-dark" dangerouslySetInnerHTML={{ __html: blogPost.body }} /> <div className="col-lg-8 pt-3 d-flex flex-column justify-content-between"> <i style={{ color: '#f7882f' }} className=""> Tags: {tagList.join(' / ')} </i> <Link className="w-100 my-3 text-muted text-left text-decoration-none" to={{ pathname: `/blog/`, }} > Back to Blog Home </Link> </div> </div> </> ) : null} </> ) } export default BlogDetailPage <file_sep>import React from 'react' import { Link } from 'react-router-dom' import { DateTime } from 'luxon' const FeaturedPost = ({ blogInfo, imageUrl }) => { const blogData = blogInfo const tagList = blogData.tags.map((tag) => tag.name) return ( <div className="col-md-6 mb-4"> <div className="row h-100 g-0 border rounded overflow-hidden flex-column shadow-sm h-md-250 position-relative justify-content-center align-items-center"> <div className="col px-4 py-3 d-flex flex-column position-static"> <img className="rounded-circle bg-white align-self-center mb-3" src={`${imageUrl}${blogData.image_filename}`} alt="Generic placeholder" width="150" height="150" /> <h3 className="mb-0 pb-3 text-center">{blogData.title}</h3> <p className="mb-0 pb-2">{blogData.summary}</p> <Link className="stretched-link pb-2 text-muted text-decoration-none" to={{ pathname: `/blog/${blogData._id}`, transferData: { blogData, image_url: imageUrl, }, }} > Read More... </Link> <div className="mt-auto d-flex flex-row justify-content-between"> <i className="">{tagList.join(' / ')}</i> <i className=""> {DateTime.fromISO(blogData.post_date).toLocaleString( DateTime.DATE_MED )} </i> </div> </div> </div> </div> ) } export default FeaturedPost <file_sep>import React, { useEffect } from 'react' import { BrowserRouter as Router, Route, useLocation } from 'react-router-dom' import BlogDetailPage from './BlogDetailPage' import BlogHomePage from './BlogHomePage' // Function below is added so that on longer blog posts the window doesn't remain scrolled down the screen when switching screens. function ScrollToTop() { const { pathname } = useLocation() useEffect(() => { window.scrollTo(0, 0) }, [pathname]) return null } const App = () => ( <> <Router> <ScrollToTop /> <Route exact path="/blog/" component={BlogHomePage} /> <Route path="/blog/:blogId" component={BlogDetailPage} /> </Router> </> ) export default App
063ee503464c6df34ad67d7db0dc3a08b6de4b18
[ "JavaScript", "Markdown" ]
5
JavaScript
jwpf100/node-blog-frontend
4154fc67c48952b8b02c048f8545621bedba3514
5b03f226d090fdc9a555e2180ef14c00eafbb735
refs/heads/master
<repo_name>LukeMoll/arnie<file_sep>/arnie.py import re import znc # type: ignore[import] import traceback class arnie(znc.Module): module_types = [znc.CModInfo.NetworkModule] description = "Makes bridged messages appear more natural" # Module hooks def OnLoad(self, sArgsi, sMessage): self.load_channels() self.load_nicks() return True regex = re.compile("^<(?:\x03" + r"\d{,2}(?:,\d{,2})?)?([a-z[\]`_^|{}\\][a-z0-9[\]`_^|{}\\]*)" + "\x0F> ?", re.IGNORECASE) def OnChanTextMessage(self, Message): try: if ( self.match_nick(Message.GetNick()) and self.match_channel(Message.GetChan()) ): t = self.split_message(Message) if t is not None: (nick, msgtext) = t Message.SetText(msgtext) Message.GetNick().SetNick(self.get_prefix() + nick + self.get_suffix()) except Exception as e: self.PutModule("An error occurred. Please include the following in your report:") self.PutModule(traceback.format_exc()) return znc.CONTINUE def OnModCommand(self, command): try: command = command.lower() tokens = re.split(r"\s", command) cmd_name = tokens[0] if cmd_name == "chan" or cmd_name =="channels": if len(tokens) < 2: self.PutModule(self.usage["channels"]) return True elif tokens[1] == "clear": self.clear_channels() return True # else: params = set(tokens[2:]) if tokens[1] == "add": self.add_channels(params) elif tokens[1] == "remove": self.remove_channels(params) else: self.PutModule(self.usage["channels"]) elif cmd_name == "nick" or cmd_name == "nicks": if len(tokens) < 2: self.PutModule(self.usage["nicks"]) return True elif tokens[1] == "clear": self.clear_nicks() return True # else: params = set(tokens[2:]) if tokens[1] == "add": self.add_nicks(params) elif tokens[1] == "remove": self.remove_nicks(params) else: self.PutModule(self.usage["nicks"]) elif cmd_name == "suffix": if len(tokens) < 2: self.PutModule(self.usage["suffix"]) return True elif tokens[1] == "set": self.set_suffix(" ".join(tokens[2:])) elif tokens[1] == "clear": self.set_suffix("") else: self.PutModule(self.usage["suffix"]) elif cmd_name == "prefix": if len(tokens) < 2: self.PutModule(self.usage["prefix"]) return True elif tokens[1] == "set": self.set_prefix(" ".join(tokens[2:])) elif tokens[1] == "clear": self.set_prefix("") else: self.PutModule(self.usage["prefix"]) elif cmd_name == "status": self.PutModule( "Prefix: {}".format(self.get_prefix()) if len(self.get_prefix()) > 0 else "Empty prefix" ) self.PutModule( "Suffix: {}".format(self.get_suffix()) if len(self.get_suffix()) > 0 else "Empty suffix" ) self.PutModule("Translating messages sent in:") self.PutModule(", ".join(self.channels)) self.PutModule("and sent by:") self.PutModule(", ".join(self.nicks)) elif cmd_name == "help": if len(tokens) == 1: self.PutModule("Available commands:") self.PutModule(", ".join(self.usage.keys())) self.PutModule("Use `help <command>` to get more information about a command") elif tokens[1] in self.usage: self.PutModule(self.usage[tokens[1]]) else: self.PutModule("No such command {}.".format(tokens[1])) else: self.PutModule("No such command!") return True except Exception as e: self.PutModule("An error occurred. Please include the following in your report:") self.PutModule(traceback.format_exc()) return True usage = { "channels": """(chan for short) channels add <channels>: Adds all of <channels> (space separated) to the channel allowlist. Arnie will only translate messages sent in channels from the channel whitelist. Channels must be preceeded by a #. channels remove <channels>: Removes all of <channels> from the allowlist. channels clear: Removes all channels from the allowlist. No messages will be translated if the allowlist is empty. """, "nicks": """(nick for short) nicks add <nicks>: Adds all of <nicks> (space separated) to the nick allowlist. Arnie will only translate messages sent by bots in the nick allowlist. nicks remove <nicks>: Removes all of <nicks> from the allowlist. nicks clear: Removes all nicks from the allowlist. No messages will be translated if the allowlist is empty. """, "prefix": """Appears before the username of the bridged user. prefix set <prefix>: Sets the prefix. prefix clear: Clears the prefix. """, "suffix": """Appears after the username of the bridged user. suffix set <suffix>: Sets the suffix. suffix clear: Clears the suffix. """, "status": "Shows information about Arnie (takes no arguments)." } # Helper functions def split_message(self, Message): text = Message.GetText() match = re.match(self.regex, text) if match is not None: nick = match.group(1) remaining_text = text[match.span()[1]:] return (nick, remaining_text) else: return None def match_nick(self, Nick): return Nick.GetNick().lower() in self.nicks def match_channel(self, Channel): return Channel.GetName().lower() in self.channels # Member accessors def load_nicks(self): try: self.nicks = set(self.nv['nicks'].split(",")) except KeyError: self.nicks = set() return self.nicks def add_nicks(self, nicks): nicks = {n.replace(",","") for n in nicks} self.nicks.update(nicks) self.nv['nicks'] = ",".join(self.nicks) def remove_nicks(self, nicks): nicks = {n.replace(",","") for n in nicks} self.nicks.difference_update(nicks) self.nv['nicks'] = ",".join(self.nicks) def clear_nicks(self): self.nv['nicks'] = "" self.nicks = set() def load_channels(self): try: self.channels = set(self.nv['channels'].split(",")) except KeyError: self.channels = set() return self.channels def add_channels(self, channels): channels = {c.replace(",","") for c in channels} self.channels.update(channels) self.nv['channels'] = ",".join(self.channels) def remove_channels(self, channels): channels = {c.replace(",","") for c in channels} self.channels.difference_update(channels) self.nv['channels'] = ",".join(self.channels) def clear_channels(self): self.nv['channels'] = "" self.channels = set() def get_suffix(self): try: return self.nv['suffix'] except KeyError: self.nv['suffix'] = "" return "" def set_suffix(self, suff): self.nv['suffix'] = suff def get_prefix(self): try: return self.nv['prefix'] except KeyError: self.nv['prefix'] = "" return "" def set_prefix(self, pref): self.nv['prefix'] = pref <file_sep>/README.md Arnie === Arnie is a plugin for the [ZNC] IRC bouncer. It takes messages bridged into IRC (eg. from Slack) that look like this: ``` ldm: @sdhand how about this ldm: four slices of bread ldm: put fillings on 2 of them ldm: and put the other 2 pieces of bread on top of the ones with fillings on ldm: how many sandwiches hackbot: <sdhand> ah, as in do you have a just a sandwich with extra bread hackbot: <sdhand> or a sandwich sandwich hackbot: <sdhand> it comes down to whether or not something can be both sandwich and filling ``` and makes them look more like this: ``` ldm: @sdhand how about this ldm: four slices of bread ldm: put fillings on 2 of them ldm: and put the other 2 pieces of bread on top of the ones with fillings on ldm: how many sandwiches sdhand: ah, as in do you have a just a sandwich with extra bread sdhand: or a sandwich sandwich sdhand: it comes down to whether or not something can be both sandwich and filling ``` You can set a prefix or suffix to distinguish between IRC users and bridged users. ``` ldm: no, put 2 pieces of bread on a plate ldm: put fillings on those 2 pieces of bread ldm: and put a piece of bread on top of each of them ldm: how many sandwiches is that sdhand[s]: ye I got it sdhand[s]: as I said, it comes down to whether or not you consider the inner sandwich sdhand[s]: to be filling for the outer 2 pieces of bread ``` It will only translate messages from specified channels and users, so you don't need to worry about it interfering with non-bridged IRC channels. It also doesn't affect the `log` module so your IRC logs will also be unaffected. ## Installation Installed [as any other](https://wiki.znc.in/Modules#Managing_Modules) ZNC module. Requires [modpython] to be loaded 1. Copy `arnie.py` to the `modules` directory of your ZNC installation 2. Run `/msg *status loadmod arnie` to load the module 3. Send `help` to `*arnie` to get started. ## Usage Full command help text is available by sending `help` to `*arnie`. [ZNC]: https://wiki.znc.in/ZNC "ZNC Wiki" [modpython]: https://wiki.znc.in/Modpython "modpython - ZNC Wiki"
58c8298a7adaaae2afcd29ddcd53725c490bb854
[ "Markdown", "Python" ]
2
Python
LukeMoll/arnie
1bd1ad14a4f456410de1a5b0b7626d100e9fb9ac
764dbd4805de692c86fd97e1b85f9d3abf583063
refs/heads/master
<repo_name>umarferrer/vagrant<file_sep>/scripts/mysql.sh apt-get update debconf-set-selections <<< 'mysql-server mysql-server/root_password password <PASSWORD>' debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password <PASSWORD>' apt-get install -y mysql-server mysql-client php5-mysql sed -i 's/;date\.timezone =/date\.timezone = Europe\/Paris/g' /etc/php5/apache2/php.ini sed -i 's/;date\.timezone =/date\.timezone = Europe\/Paris/g' /etc/php5/cli/php.ini<file_sep>/scripts/utils.sh apt-get update sudo apt-get install -y htop vim telnet git apache2<file_sep>/scripts/s2.sh if [ ! -f /var/www/composer.json ] then curl -sS https://getcomposer.org/installer | php mv composer.phar /usr/local/bin/composer composer create-project symfony/framework-standard-edition /var/www/tmp "2.5.*" mv /var/www/tmp/* /var/www && rmdir /var/www/tmp cd /var/www/ && composer require "phpunit/phpunit=*" cd /var/www/ && composer require "sebastian/phpcpd=*" cd /var/www/ && composer require "phing/phing=*" fi<file_sep>/scripts/vhost.sh PROJECT = $1 VHOST=$(cat <<EOF <VirtualHost *:80> DocumentRoot "/var/www/web" ServerName $1.local <Directory "/var/www/web"> AllowOverride None </Directory> </VirtualHost> EOF ) echo "${VHOST}" > /etc/apache2/sites-enabled/000-default sudo a2enmod rewrite sudo /etc/init.d/apache2 reload <file_sep>/scripts/php5.5.sh echo "deb http://packages.dotdeb.org wheezy all" > /etc/apt/sources.list.d/php55 echo "deb-src http://packages.dotdeb.org wheezy all" >> /etc/apt/sources.list.d/php55 echo "deb http://packages.dotdeb.org wheezy-php55 all" >> /etc/apt/sources.list.d/php55 echo "deb-src http://packages.dotdeb.org wheezy-php55 all" >> /etc/apt/sources.list.d/php55 wget http://www.dotdeb.org/dotdeb.gpg apt-key add dotdeb.gpg apt-get update apt-get install -y php5 php5-cli php5-intl php5-curl php5-mysql php5-gd php5-gmp php5-mcrypt php5-xdebug php5-memcached php5-imagick php5-intl <file_sep>/Vagrantfile # -*- mode: ruby -*- # vi: set ft=ruby : PROJECT_NAME = "otl" SERVER_IP = "192.168.40.10" hostname = "vaprobash.dev" server_memory = "2048" # MB FOLDER = "/var/www/#{PROJECT_NAME}" PORT = "8888" Vagrant.configure("2") do |config| config.vm.box = "chef/debian-7.4" config.vm.box_url = "http://vagrantcloud.com/chef/debian-7.4/version/1/provider/virtualbox.box" config.vm.hostname = hostname if Vagrant.has_plugin?("vagrant-proxyconf") config.proxy.http = "http://172.16.58.3:8080/" config.proxy.https = "http://172.16.58.3:8080/" config.proxy.no_proxy = "localhost,127.0.0.1,.example.com" end config.vm.network "forwarded_port", guest: 80, host: PORT config.vm.network :private_network, ip: SERVER_IP config.vm.synced_folder FOLDER, "/var/www", id: "core", :nfs => true, :mount_options => ['nolock,vers=3,udp,noatime'] config.vm.provider :virtualbox do |vb| vb.customize ["modifyvm", :id, "--memory", server_memory] vb.customize ["guestproperty", "set", :id, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold", 10000] end config.vm.provision "shell", path: "../default/scripts/utils.sh" config.vm.provision "shell", path: "../default/scripts/php5.5.sh" config.vm.provision "shell", path: "../default/scripts/vhost.sh", args: [PROJECT_NAME] config.vm.provision "shell", path: "../default/scripts/mysql.sh" #config.vm.provision "shell", path: "../default/scripts/s2.sh" config.vm.provision "shell", path: "../default/scripts/extra.sh" end<file_sep>/README.md vagrant ======= SET those two variables : PROJECT_NAME = "projectName" SERVER_IP = "192.168.40.10" add projectName.local to /etc/vhosts Enjoy<file_sep>/scripts/extra.sh sudo echo "xdebug.max_nesting_level=2000" >> /etc/php5/apache2/conf.d/20-xdebug.ini sudo service apache2 restart echo "" > /home/vagrant/.bash_profile #auto-complete symfony2 cd /home/vagrant git clone https://github.com/jaytaph/SFConsole.git cd SFConsole mv console_completion.sh ../.console_completion.sh cd .. rm -rf SFConsole sudo echo ". ~/.console_completion.sh" >> /home/vagrant/.bash_profile #Ssh connect redirect to /var/www sudo echo "cd /var/www" >> /home/vagrant/.bash_profile #Pretty shell sudo echo 'parse_git_branch() {' >> /home/vagrant/.bash_profile sudo echo "git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'" >> /home/vagrant/.bash_profile sudo echo '}' >> /home/vagrant/.bash_profile sudo echo 'export PS1="\e[33m\u\e[0m \e[34m\w\e[0m\e[33m\$(parse_git_branch)\e[34m $ "' >> /home/vagrant/.bash_profile
68e1cef85a23ed3a5bc23ed0b8b94e3b461c92f6
[ "Markdown", "Ruby", "Shell" ]
8
Shell
umarferrer/vagrant
cfc23d72630d160de5f476359766715b1dc52050
dfad9e4b2a33fe31b365181a9b8038afe58cabc7
refs/heads/master
<file_sep>package edu.tacoma.uw.ahanag22.take_a_note_on_android; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ShareActionProvider; ; import edu.tacoma.uw.ahanag22.take_a_note_on_android.Note.NoteContent; /** * class to implement web login activity functions */ public class WebLoginActivity extends AppCompatActivity implements NoteFragment.OnListFragmentInteractionListener { //shareAction provider to allow sharing private ShareActionProvider mShareActionProvider; /** * Create the instance of this activity with the instancestate * @param savedInstanceState instance state */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_login); getSupportFragmentManager().beginTransaction() .add(R.id.note_container, new NoteFragment()) .commit(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(view.getContext(), NoteTakingActivity.class); startActivity(i); } }); } //List fragment interaction for the notecontent @Override public void onListFragmentInteraction(NoteContent item) { NoteDetailFragment noteDetailFragment = new NoteDetailFragment(); Bundle args = new Bundle(); args.putSerializable(NoteDetailFragment.NOTE_ITEM_SELECTED, item); noteDetailFragment.setArguments(args); getSupportFragmentManager().beginTransaction() .replace(R.id.note_container, noteDetailFragment) .addToBackStack(null) .commit(); } public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.menu_logout, menu); return true; } //allows logout functionality @Override public boolean onOptionsItemSelected(MenuItem item) { SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.LOGIN_PREFS), Context.MODE_PRIVATE); sharedPreferences.edit().putBoolean(getString(R.string.LOGGEDIN), false) .commit(); Intent i = new Intent(this, new SignInActivity().getClass()); startActivity(i); finish(); return true; } } <file_sep>package edu.tacoma.uw.ahanag22.take_a_note_on_android.Note; /** * Created by anita on 5/30/2017. */ public class MyProperties { public static String userid = null; } <file_sep>package edu.tacoma.uw.ahanag22.take_a_note_on_android; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.net.URLEncoder; import edu.tacoma.uw.ahanag22.take_a_note_on_android.Note.EditNoteFragment; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link AddNoteFragment.NoteAddListner} interface * to handle interaction events. * Use the {@link AddNoteFragment#newInstance} factory method to * create an instance of this fragment. */ public class AddNoteFragment extends Fragment { // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; //add note url private final static String COURSE_ADD_URL = "http://takenote.x10host.com/addNote.php?"; /** * Edittext of noteid */ private EditText mNoteId; /** * Edittext of note description */ private EditText mNoteDesc; /** * Edittext of userid */ private String mUserId; /** * Note add listner to add note */ private NoteAddListner mListener; public AddNoteFragment() { } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment AddNoteFragment. */ public static AddNoteFragment newInstance(String param1, String param2) { AddNoteFragment fragment = new AddNoteFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } /** * Create the instance of this activity with the instancestate * @param savedInstanceState instance state */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.fragment_add_note, container, false); mNoteId = (EditText) v.findViewById(R.id.add_note_id); mUserId = SignInActivity.muserId; mNoteDesc = (EditText) v.findViewById(R.id.add_note_desc); Button addCourseButton = (Button) v.findViewById(R.id.save_button); addCourseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (TextUtils.isEmpty(mNoteId.getText().toString())) { Toast.makeText(v.getContext(), "Enter filename" , Toast.LENGTH_SHORT) .show(); mNoteId.requestFocus(); return; } String url = buildNoteUrl(v); mListener.addNote(url); } }); return v; } /** * Build the url for the note adding * * @param v view * @return string representation of the data */ private String buildNoteUrl(View v) { StringBuilder sb = new StringBuilder(COURSE_ADD_URL); try { String courseId = mNoteId.getText().toString(); sb.append("id="); sb.append(courseId); String courseShortDesc = mNoteDesc.getText().toString(); String userId = mUserId; sb.append("&userid="); sb.append(userId); sb.append("&longDesc="); sb.append(URLEncoder.encode(courseShortDesc, "UTF-8")); Log.i("AddNoteFragment", sb.toString()); } catch (Exception e) { Toast.makeText(v.getContext(), "Something wrong with the url" + e.getMessage(), Toast.LENGTH_LONG) .show(); } return sb.toString(); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof NoteAddListner) { mListener = (NoteAddListner) context; } else { throw new RuntimeException(context.toString() + " must implement CourseAddListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface NoteAddListner { void addNote(String url); } } <file_sep>package edu.tacoma.uw.ahanag22.take_a_note_on_android.Note; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import edu.tacoma.uw.ahanag22.take_a_note_on_android.SignInActivity; /** * Helper class for providing sample content for user interfaces created by * Android template wizards. * <p> * * @author <NAME> & <NAME> */ public class NoteContent implements Serializable { //id for the note column public static final String ID = "id"; //note description column or the note itself public static final String NOTE_DESC = "longDesc"; //userid column public static final String USER_ID = "userid"; //noteid as file name private String mNoteId; //description or written note private String mLongDesc; //user id to save id in the database with note private String mUserId; /** * Constructor to initialize the value * * @param id * @param noteDesc */ public NoteContent(String id, String userid, String noteDesc) { mUserId = userid; mNoteId = id; mLongDesc = noteDesc; } /** * Parses the json string, returns an error message if unsuccessful. * Returns note list if success. * * @param noteJson * @return reason or null if successful. */ public static String parseNoteJson(String noteJson, List<NoteContent> noteContentList) { String reason = null; if (noteJson != null && !noteJson.isEmpty()) { try { JSONArray arr = new JSONArray(noteJson); for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); NoteContent noteContent = new NoteContent(obj.getString(NoteContent.ID), obj.getString(NoteContent.USER_ID), obj.getString(NoteContent.NOTE_DESC)); noteContentList.add(noteContent); } } catch (JSONException e) { reason = "Unable to parse data, Reason: " + e.getMessage(); } } return reason; } /** * getter to get the id * * @return note id */ public String getId() { return mNoteId; } /** * getter to get the note * * @return note description */ public String getNoteDesc() { return mLongDesc; } /* *getter to get the user id * @return userid */ public String getUserId() { return mUserId; } public void setId(String theNoteId) { if (theNoteId.isEmpty()) { throw new IllegalArgumentException("file name is not given"); } this.mNoteId = theNoteId; } /* *set the user id * @param theUserId user's id */ public void setUserId(String theUserId) { if (theUserId.isEmpty()) { throw new IllegalArgumentException("userid is not valid"); } this.mUserId = theUserId; } //set the note description //@param theNoteDesc notedescription public void setNoteDesc(String theNoteDesc) { this.mLongDesc = theNoteDesc; } public void setmUserId(String theUserid) { this.mUserId = theUserid; } }
b8b6f7345eb242add38ff484b360ff38ead5cdee
[ "Java" ]
4
Java
anitapau/take_a-note
cf6c1f71eba79a19b03b56496932a46c997f7b40
5012a94fae4af766f3bdd3234b85285f41ffba7d
refs/heads/master
<file_sep>package kyu7; //http://www.codewars.com/kata/55b75fcf67e558d3750000a3 public class Block { public int width; public int length; public int height; public Block(int[] block) { this.width = block[0]; this.length = block[1]; this.height = block[2]; } public int getWidth() { return width; } public int getLength() { return length; } public int getHeight() { return height; } public int getVolume() { return width * length * height; } public int getSurfaceArea() { return (width * length * 2) + (width * height * 2) + (length * height * 2); } } <file_sep>package kyu7; //http://www.codewars.com/kata/559590633066759614000063 class MinMax { public static int[] minMax(int[] arr) { int[] result = new int[2]; java.util.Arrays.sort(arr); result[0] = arr[0]; if (arr.length < 2) { result[1] = arr[0]; } else { result[1] = arr[arr.length - 1]; } return result; } } <file_sep>package kyu7; //http://www.codewars.com/kata/55f2b110f61eb01779000053 import java.util.Arrays; public class Sum { public int GetSum(int a, int b) { if (a == b) { return a; } else { int[] container = new int[]{a, b}; Arrays.sort(container); int result = 0; while (container[0] <= container[1]) { result += container[0]; container[0] += 1; } return result; } } }<file_sep>package kyu6; //http://www.codewars.com/kata/560b8d7106ede725dd0000e2 public class BeforeAfterPrimes { public static long[] primeBefAft(long num) { long[] result = new long[2]; for (long i = num - 1; i > 1; i--) { if (isPrime(i)) { result[0] = i; break; } } for (long i = num + 1; i < Long.MAX_VALUE; i++) { if (isPrime(i)) { result[1] = i; break; } } return result; } public static boolean isPrime(long number) { for (long i = 2; i < number; i++) { if (number % i == 0) { return false; } } return true; } } <file_sep>package kyu7; //http://www.codewars.com/kata/566efcfbf521a3cfd2000056 public class FunReverse { public static String result; public static String funReverse(String s) { result = new StringBuilder(s).reverse().toString(); for (int i = 1; i < s.length(); i++) { result = (result.substring(0, i)) + (new StringBuilder(result.substring(i, result.length())).reverse().toString()); } return result; } }
08ff09c06c78f199aef92dd12962e253f9484f4f
[ "Java" ]
5
Java
moRhen/CodeWars
68310d4512624b6bfaebf0e76c3b42f511edd3e4
e0ae93beb2eecc801b0c48774fcb3d5ad241ba53
refs/heads/master
<repo_name>sergiotorresperez/FirebaseChat<file_sep>/app/src/main/java/com/garrapeta/firebasechat/ChatMessageViewHolder.kt package com.garrapeta.firebasechat import android.view.View import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class ChatMessageViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val messageText : TextView = itemView.findViewById(R.id.message_text) as TextView val messageUser : TextView = itemView.findViewById(R.id.message_user) as TextView val messageTime : TextView = itemView.findViewById(R.id.message_time) as TextView }<file_sep>/README.md # FirebaseChat Instant message chat based on Firebase real time db <file_sep>/app/src/main/java/com/garrapeta/firebasechat/ChatMessage.kt package com.garrapeta.firebasechat import java.util.* data class ChatMessage( val messageText: String? = null, val messageUser: String? = null, val messageTime: Long = Date().time )<file_sep>/app/src/main/java/com/garrapeta/firebasechat/ChatRoomActivity.kt package com.garrapeta.firebasechat import android.app.Activity import android.content.Intent import android.os.Bundle import android.text.format.DateFormat import android.util.Log import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.firebase.ui.auth.AuthUI import com.firebase.ui.database.FirebaseRecyclerAdapter import com.firebase.ui.database.FirebaseRecyclerOptions import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.ChildEventListener import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import kotlinx.android.synthetic.main.activity_chatroom.* class ChatRoomActivity : AppCompatActivity() { companion object { private const val SIGN_IN_REQUEST_CODE = 1234 private const val DATABASE_PATH = "chats" private const val TAG = "stp" } private lateinit var adapter: FirebaseRecyclerAdapter<ChatMessage, ChatMessageViewHolder> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chatroom) login() } private fun login() { if (FirebaseAuth.getInstance().currentUser == null) { // Start sign in/sign up activity startActivityForResult( AuthUI.getInstance() .createSignInIntentBuilder() .build(), SIGN_IN_REQUEST_CODE ) } else { // User is already signed in. Therefore, display // a welcome Toast Toast.makeText( this, "Welcome " + (FirebaseAuth.getInstance().currentUser?.displayName ?: " Unknown User"), Toast.LENGTH_LONG ).show() // Load chat room contents setupDatabaseActions() } } override fun onActivityResult( requestCode: Int, resultCode: Int, data: Intent? ) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == SIGN_IN_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { Toast.makeText( this, "Successfully signed in. Welcome!", Toast.LENGTH_LONG ).show() setupDatabaseActions() } else { Toast.makeText( this, "We couldn't sign you in. Please try again later.", Toast.LENGTH_LONG ).show() // Close the app finish() } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_chatroom, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.menu_sign_out) { AuthUI.getInstance().signOut(this) .addOnCompleteListener { Toast.makeText( this, "You have been signed out.", Toast.LENGTH_LONG ) .show() // Close activity finish() } } return true } private fun setupDatabaseActions() { bindListView() bindSendButton() } private fun bindListView() { Log.i(TAG, "Binding list view") val childEventListener = object : ChildEventListener { override fun onChildAdded(dataSnapshot: DataSnapshot, previousChildName: String?) { Log.d(TAG, "onChildAdded:" + dataSnapshot.key!! + dataSnapshot.value) } override fun onChildChanged(dataSnapshot: DataSnapshot, previousChildName: String?) { Log.d(TAG, "onChildChanged: ${dataSnapshot.key}") } override fun onChildRemoved(dataSnapshot: DataSnapshot) { Log.d(TAG, "onChildRemoved:" + dataSnapshot.key!!) } override fun onChildMoved(dataSnapshot: DataSnapshot, previousChildName: String?) { Log.d(TAG, "onChildMoved:" + dataSnapshot.key!!) } override fun onCancelled(databaseError: DatabaseError) { Log.w(TAG, "postComments:onCancelled", databaseError.toException()) } } FirebaseDatabase.getInstance() .reference .addChildEventListener(childEventListener) val query = FirebaseDatabase.getInstance() .reference .child(DATABASE_PATH) val options = FirebaseRecyclerOptions.Builder<ChatMessage>() .setQuery(query, ChatMessage::class.java) .setLifecycleOwner(this) .build() adapter = object : FirebaseRecyclerAdapter<ChatMessage, ChatMessageViewHolder>(options) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatMessageViewHolder { // Create a new instance of the ViewHolder, in this case we are using a custom // layout called R.layout.message for each item val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_message, parent, false) return ChatMessageViewHolder(view) } override fun onBindViewHolder(holder: ChatMessageViewHolder, position: Int, model: ChatMessage) { // Set their text holder.messageText.text = model.messageText holder.messageUser.text = model.messageUser // Format the date before showing it holder.messageTime.text = DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.messageTime) } override fun onDataChanged() { Log.i("stp", "onDataChanged. New itemCount: ${this.itemCount}") list_of_messages.scrollToPosition(adapter.itemCount - 1) } override fun onError(e: DatabaseError) { Log.e("stp", "error $e") Toast.makeText(this@ChatRoomActivity, "dsa", Toast.LENGTH_SHORT).show() } } list_of_messages.adapter = adapter list_of_messages.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this) } private fun bindSendButton() { fab.setOnClickListener { val messageText: ChatMessage? = FirebaseAuth.getInstance() .currentUser ?.displayName ?.let { name -> ChatMessage(input.text.toString(), name) } messageText?.let { // Read the input field and push a new instance // of ChatMessage to the Firebase database FirebaseDatabase.getInstance().reference .child(DATABASE_PATH) .push() .setValue(messageText) } // Clear the input input.setText("") } } }
bfed1ac53c9d756da9bd192efc3e1165da8c2bb5
[ "Markdown", "Kotlin" ]
4
Kotlin
sergiotorresperez/FirebaseChat
6c37711cce80c5f6289af6931ab94185b5f0e701
1390f60ebd80da72a9f34a328ba870e5e7729d84
refs/heads/master
<repo_name>starryexpanse/new-website<file_sep>/seweb/src/StickyNavHeader.js import React, { Component } from 'react'; import imgRivenSymbol3d from './img/RivenSymbol3D.png'; import './StickyNavHeader.css'; class StickyNavHeader extends Component { render() { const { props } = this; const backgroundTuple = [81, 49, 49]; const alpha = props.opacity * 0.9; const backgroundColor = `rgba(${backgroundTuple[0]}, ${backgroundTuple[1]}, ${backgroundTuple[2]}, ${alpha})`; return ( <header className="StickyNavHeader" style={{ backgroundColor }}> <div className="StickyNavHeader-section-left" style={{opacity: props.opacity}}> <div>About</div> <div>Gallery</div> <div>Team</div> </div> <div className="StickyNavHeader-logo-outlet" style={props.isLogoVisible ? {} : {visibility: 'hidden'}}> <div className="StickyNavHeader-logo-outline" /> <img className="StickyNavHeader-logo" src={imgRivenSymbol3d} style={{ height: props.logoHeight, transition: 'height 0.07s' }} /> <div className="StickyNavHeader-logo-backdrop" /> </div> <div className="StickyNavHeader-section-right" style={{opacity: props.opacity}}> <div>We're Hiring</div> <div>Contact</div> </div> </header> ); } } export default StickyNavHeader; <file_sep>/templategarden-syntaxis-h/js/main.js function main() { (function () { 'use strict'; // Hide .navbar first $(".navbar").hide(); Math.clamp = function(number, min, max) { return Math.max(min, Math.min(number, max)); } // Fade in .navbar, rotate intro image $(function () { var offset = 0; var c = $('.intro-button'); var ri = $('.rotate-img'); var ri3D = $('.rotate-img-3D'); var state = 0; ri3D.mouseover(function () { var st = $(window).scrollTop(); offset += 22; //console.log(st); if(st < 230) { var rotationStr = "rotate(" + ((st + offset)/1.5) + "deg)"; //var rotationStr3D = ri3D.css("transform") + " rotate(" + ((st + offset)/1.5) + "deg)"; //console.log("mouseover"); ri.css({ "transition": "transform 0.3s ease", "-webkit-transform": rotationStr, "-moz-transform": rotationStr, "transform": rotationStr }); ri3D.css({ "transition": "transform 0.3s ease", "-webkit-transform": rotationStr, "-moz-transform": rotationStr, "transform": rotationStr }); } //console.log("mouseover"); }); ri3D.mouseout(function () { var st = $(window).scrollTop(); offset -= 22; //console.log(st) if(st < 230) { var rotationStr = "rotate(" + ((st + offset)/1.5) + "deg)"; //var rotationStr3D = ri3D.css("transform") + " rotate(" + ((st + offset)/1.5) + "deg)"; //console.log("mouseout"); ri.css({ "transition": "transform 0.3s ease", "-webkit-transform": rotationStr, "-moz-transform": rotationStr, "transform": rotationStr }); ri3D.css({ "transition": "transform 0.3s ease", "-webkit-transform": rotationStr, "-moz-transform": rotationStr, "transform": rotationStr }); } //console.log("mouseout"); }); $(window).scroll(function () { var st = $(window).scrollTop(); var rTop = ri.offset().top - st; // set distance user needs to scroll before we fadeIn navbar if($(this).scrollTop() > 200) { $('.navbar').fadeIn(); } else { $('.navbar').fadeOut(); } //var n = -7 var top = $('.intro-body').height() / 2.68; //console.log(st + " : " + top); //if(rTop > n) { // Rotate intro image if($(window).scrollTop() < top) { // Rotate intro image //var newLoc = $(window).scrollTop(); //var diff = scrollLoc - newLoc; //rotation -= diff, scrollLoc = newLoc; state = 0; var rotation = Math.clamp(st, 0, 360); //console.log(rotation + offset); var rotationStr = "rotate(" + (rotation + offset) / (top / 180) + "deg)"; ri.css({ "transition": "none", "-webkit-transform": rotationStr, "-moz-transform": rotationStr, "transform": rotationStr, "opacity": 1 }); ri3D.css({ "transition": "none", "opacity": Math.clamp($(window).scrollTop()/100, 0, 1).toString(), "-webkit-transform": rotationStr, "-moz-transform": rotationStr, "transform": rotationStr, "position": "absolute", "top": "0", "transform-origin": "center" }); c.attr("href", "#about"); } //else if($(window).scrollTop() < 600 && rTop <= n) { // Scale intro image else if($(window).scrollTop() < 600 && $(window).scrollTop() >= top) { // Scale intro image //var newLoc = $(window).scrollTop(); //var diff = scrollLoc - newLoc; //rotation -= diff, scrollLoc = newLoc; var cssArr = {}; state = 1; rotation = 180; var max = 550; var fScale = 0.5; //((600-600.56)*-1)/1000 //(($(window).scrollTop()-(max + fScale))*-1)/1000 var scale = Math.clamp(((($(window).scrollTop()-550)-(max))*-1)/900, fScale, 1); var tStr = "rotate(" + rotation + "deg) scale(" + scale + ")"; cssArr["-webkit-transform"] = tStr, cssArr["-moz-transform"] = tStr, cssArr["transform"] = tStr, cssArr["position"] = "fixed", cssArr["top"] = "-103px", //cssArr["top"] = (top / -2.28).toString() + "px", cssArr["transform-origin"] = "bottom"; ri.css("opacity", 0.0); c.attr("href", "#page-top"); ri3D.css(cssArr); //console.log($(window).scrollTop() + " : " + scale); } else if($(window).scrollTop() > top && state < 2) { // Set intro image //var newLoc = $(window).scrollTop(); //var diff = scrollLoc - newLoc; //rotation -= diff, scrollLoc = newLoc; var cssArr = {}; state = 2; rotation = 180; var max = 550; var fScale = 0.5; //((600-600.56)*-1)/1000 //(($(window).scrollTop()-(max + fScale))*-1)/1000 var scale = 0.553333; var tStr = "rotate(" + rotation + "deg) scale(" + scale + ")"; cssArr["-webkit-transform"] = tStr, cssArr["-moz-transform"] = tStr, cssArr["transform"] = tStr, cssArr["position"] = "fixed", cssArr["top"] = "-103px", //cssArr["top"] = (top / -2.28).toString() + "px", cssArr["transform-origin"] = "bottom"; ri.css("opacity", 0.0); ri3D.css("opacity", 1.0); c.attr("href", "#page-top"); ri3D.css(cssArr); //console.log("blah"); } //console.log(rTop); //console.log(offset); //console.log(st); }); }); // Preloader */ $(window).load(function() { // will first fade out the loading animation $("#status").fadeOut("slow"); // will fade out the whole DIV that covers the website. $("#preloader").delay(500).fadeOut("slow").remove(); }) // Page scroll $('a.page-scroll').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top - 40 }, 900); return false; } } }); // Show Menu on Book $(window).bind('scroll', function() { var navHeight = $(window).height() - 100; if ($(window).scrollTop() > navHeight) { $('.navbar-default').addClass('on'); } else { $('.navbar-default').removeClass('on'); } }); $('body').scrollspy({ target: '.navbar-default', offset: 80 }) $(document).ready(function() { $("#testimonial").owlCarousel({ navigation : false, // Show next and prev buttons slideSpeed : 300, paginationSpeed : 400, singleItem:true }); }); // Gallery Isotope Filter $(window).load(function() { var $container = $('.gallery-items'); $container.isotope({ filter: '*', animationOptions: { duration: 750, easing: 'linear', queue: false } }); $('.cat a').click(function() { $('.cat .active').removeClass('active'); $(this).addClass('active'); var selector = $(this).attr('data-filter'); $container.isotope({ filter: selector, animationOptions: { duration: 750, easing: 'linear', queue: false } }); return false; }); }); // jQuery Parallax function initParallax() { $('#intro').parallax("100%", 0.3); $('#services').parallax("100%", 0.3); $('#aboutimg').parallax("100%", 0.3); $('#testimonials').parallax("100%", 0.1); } initParallax(); // Pretty Photo $("a[rel^='prettyPhoto']").prettyPhoto({ social_tools: false }); }()); } main();<file_sep>/seweb/src/SpinningLogo.js import React, { Component } from 'react'; import './StickyNavHeader.css'; import imgRivenSymbol3d from './img/RivenSymbol3D.png'; import { quadInOut } from 'eases'; class SpinningLogo extends Component { render() { const { props } = this; const progress = Math.min( Math.max(((props.spinningRange - props.distanceFromTop) / props.spinningRange), 0), 1 ); return ( <div style={{ ...props.style, position: 'relative' }}> <div style={{ position: 'absolute', top: -4, right: -3, left: -4, bottom: 0, border: '1px solid black', borderRadius: '100px' }}></div> <img src={imgRivenSymbol3d} style={{ transform: `rotate(${ 0.5 + quadInOut(progress) / 2 }turn)`, }} /> </div> ); } } export default SpinningLogo; <file_sep>/seweb/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import { ScrollProvider } from './ScrollProvider'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<ScrollProvider><App /></ScrollProvider>, document.getElementById('root')); registerServiceWorker();
59d00ccd0d9591b5105ae52c9a11837240badf81
[ "JavaScript" ]
4
JavaScript
starryexpanse/new-website
82ebcf8b81cd6c1ef0f5a240a4894a4624cdf122
05adcc07460c4c4f0391312e8245eb7495239f2c
refs/heads/main
<repo_name>optblocks/minicurso-sbpo2020-blockchain-supply-chain<file_sep>/supplychain.cs using Neo.SmartContract.Framework; using Neo.SmartContract.Framework.Services.Neo; using Neo.SmartContract.Framework.Services.System; using System; using System.ComponentModel; using System.Numerics; using Helper = Neo.SmartContract.Framework.Helper; namespace Neo.SmartContract { public class SupplyChainNFTs : Framework.SmartContract { [DisplayName("Transfer")] public static event Action<byte[], byte[], BigInteger, string, string> TransferNotify; [DisplayName("MintToken")] public static event Action<byte[], string, string> MintTokenNotify; [DisplayName("NotificaEvent")] public static event Action<byte[], BigInteger, string, string> NotificaEvent; private static StorageContext Context() => Storage.CurrentContext; private static readonly byte[] Prefix_TotalSupplyBA = new byte[] { 10 }; private static readonly byte[] Prefix_TokenOwnerBA = new byte[] { 11 }; private static readonly byte[] Prefix_TokenBalanceBA = new byte[] { 12 }; private static readonly byte[] Prefix_PropertiesBA = new byte[] { 13 }; private static readonly byte[] Prefix_TokensOfBA = new byte[] { 14 }; private const int TOKEN_DECIMALS = 8; private const int FACTOR = 100_000_000; private static readonly byte[] superAdmin = Helper.ToScriptHash("AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y"); public static Object Main(string operation, params object[] args) { if (operation == "mintNFT") return MintNFT((byte[])args[0],(byte[])args[1],(byte[])args[2]); if (operation == "transfer") return Transfer((byte[])args[0],(byte[])args[1],(BigInteger)args[2],(byte[])args[3],(byte[])args[4]); if (operation == "balanceOf") return BalanceOf((byte[])args[0],(byte[])args[1]); if (operation == "notifica") return Notifica((byte[])args[0],(byte[])args[1],(byte[])args[2]); return false; } public static bool MintNFT(byte[] tokenId, byte[] owner, byte[] historic) { if (!Runtime.CheckWitness(superAdmin)) return false; if (owner.Length != 20) throw new FormatException("The parameter 'owner' should be 20-byte address."); if (historic.Length > 2048) throw new FormatException("The length of 'properties' should be less than 2048."); byte[] key = Prefix_TokenOwnerBA.Concat(tokenId); StorageMap tokenOwnerMap = Storage.CurrentContext.CreateMap(key.AsString()); if (tokenOwnerMap.Get(owner) != null) return false; byte[] key2 = Prefix_TokensOfBA.Concat(owner); StorageMap tokenOfMap = Storage.CurrentContext.CreateMap(key2.AsString()); byte[] key3 = Prefix_PropertiesBA.Concat(tokenId); Storage.Put(Context(), key3, historic); tokenOwnerMap.Put(owner, owner); tokenOfMap.Put(tokenId, tokenId); var totalSupply = Storage.Get(Context(), Prefix_TotalSupplyBA); if (totalSupply is null) Storage.Put(Context(), Prefix_TotalSupplyBA, FACTOR); else Storage.Put(Context(), Prefix_TotalSupplyBA, totalSupply.ToBigInteger() + FACTOR); byte[] key4 = Prefix_TokenBalanceBA.Concat(owner); StorageMap tokenBalanceMap = Storage.CurrentContext.CreateMap(key4.AsString()); tokenBalanceMap.Put(tokenId, FACTOR); MintTokenNotify(owner, tokenId.AsString(), historic.AsString()); return true; } public static bool Transfer(byte[] from, byte[] to, BigInteger amount, byte[] tokenId, byte[] reason) { if (from.Length != 20 || to.Length != 20) throw new FormatException("The parameters 'from' and 'to' should be 20-byte addresses."); if (amount < 0 || amount > FACTOR) throw new FormatException("The parameters 'amount' is out of range."); if (!Runtime.CheckWitness(from)) return false; StorageMap fromTokenBalanceMap = Storage.CurrentContext.CreateMap(Prefix_TokenBalanceBA.Concat(from).AsString()); StorageMap toTokenBalanceMap = Storage.CurrentContext.CreateMap(Prefix_TokenBalanceBA.Concat(to).AsString()); StorageMap tokenOwnerMap = Storage.CurrentContext.CreateMap(Prefix_TokenOwnerBA.Concat(tokenId).AsString()); StorageMap fromTokensOfMap = Storage.CurrentContext.CreateMap(Prefix_TokensOfBA.Concat(from).AsString()); StorageMap toTokensOfMap = Storage.CurrentContext.CreateMap(Prefix_TokensOfBA.Concat(to).AsString()); var fromTokenBalance = fromTokenBalanceMap.Get(tokenId); if (fromTokenBalance == null || fromTokenBalance.ToBigInteger() < amount) return false; var fromNewBalance = fromTokenBalance.ToBigInteger() - amount; if (fromNewBalance == 0) { tokenOwnerMap.Delete(from); fromTokensOfMap.Delete(tokenId); } fromTokenBalanceMap.Put(tokenId, fromNewBalance); var toTokenBalance = toTokenBalanceMap.Get(tokenId); if (toTokenBalance is null && amount > 0) { tokenOwnerMap.Put(to, to); toTokenBalanceMap.Put(tokenId, amount); toTokensOfMap.Put(tokenId, tokenId); } else { toTokenBalanceMap.Put(tokenId, toTokenBalance.ToBigInteger() + amount); } // Notify TransferNotify(from, to, amount, tokenId.AsString(), reason.AsString()); return true; } public static BigInteger BalanceOf(byte[] owner, byte[] tokenid) { if (owner.Length != 20) throw new FormatException("The parameter 'owner' should be 20-byte address."); byte[] key = Prefix_TokenBalanceBA.Concat(owner); if (tokenid is null) { var iterator = Storage.Find(Context(), key.AsString()); BigInteger result = 0; while (iterator.Next()) result += iterator.Value.ToBigInteger(); return result; } else return Storage.CurrentContext.CreateMap(key.AsString()).Get(tokenid).ToBigInteger(); } public static bool Notifica(byte[] owner, byte[] tokenId, byte[] info) { if (owner.Length != 20) throw new FormatException("The parameter 'owner' should be 20-byte address."); if (!Runtime.CheckWitness(owner)) return false; StorageMap fromTokenBalanceMap = Storage.CurrentContext.CreateMap(Prefix_TokenBalanceBA.Concat(owner).AsString()); var fromTokenBalance = fromTokenBalanceMap.Get(tokenId); if (fromTokenBalance == null) { Runtime.Notify("Token not found for this owner"); return false; } NotificaEvent(owner, fromTokenBalance.ToBigInteger(), tokenId.AsString(), info.AsString()); return true; } } } <file_sep>/README.md # minicurso-sbpo2020-blockchain-supply-chain ## Readme for invoking the SupplyChain NFT contract ```cs 52eaab8b2aab608902c651912db34de36e7a2b0f = 0f2b7a6ee34db32d9151c6028960ab2a8babea52 = APLJBPhtRg2XLhtpxEHd6aRNL7YSLGH2ZL [{"type":7,"value":"mintNFT"},{"type":16,"value":[{"type":7,"value":"LAND1"},{"type":5,"value":"52eaab8b2aab608902c651912db34de36e7a2b0f"},{"type":7,"value":"Terra para plantio Caparao"}]}] [{"type":7,"value":"mintNFT"},{"type":16,"value":[{"type":7,"value":"LAND2"},{"type":5,"value":"52eaab8b2aab608902c651912db34de36e7a2b0f"},{"type":7,"value":"Terra para plantio Diamantina"}]}] [{"type":7,"value":"mintNFT"},{"type":16,"value":[{"type":7,"value":"LAND3"},{"type":5,"value":"52eaab8b2aab608902c651912db34de36e7a2b0f"},{"type":7,"value":"Terra para plantio Sul de Minas"}]}] b1761b44255107162d3c79680b81b4c8a5efc597 = 97c5efa5c8b4810b68793c2d16075125441b76b1 = AXxCjds5Fxy7VSrriDMbCrSRTxpRdvmLtx [{"type":7,"value":"mintNFT"},{"type":16,"value":[{"type":7,"value":"TRUCK1"},{"type":5,"value":"b1761b44255107162d3c79680b81b4c8a5efc597"},{"type":7,"value":"Caminhao para transporte certifacado"}]}] [{"type":7,"value":"mintNFT"},{"type":16,"value":[{"type":7,"value":"TRUCK1"},{"type":5,"value":"52eaab8b2aab608902c651912db34de36e7a2b0f"},{"type":7,"value":"Caminhao para transporte certifacado II"}]}] Resultado sera 100000000 [{"type":7,"value":"balanceOf"},{"type":16,"value":[{"type":5,"value":"52eaab8b2aab608902c651912db34de36e7a2b0f"},{"type":7,"value":"TRUCK1"}]}] Resultado sera 100000000 [{"type":7,"value":"balanceOf"},{"type":16,"value":[{"type":5,"value":"b1761b44255107162d3c79680b81b4c8a5efc597"},{"type":7,"value":"TRUCK1"}]}] Resultado sera 100000000 [{"type":7,"value":"balanceOf"},{"type":16,"value":[{"type":5,"value":"52eaab8b2aab608902c651912db34de36e7a2b0f"},{"type":7,"value":"LAND1"}]}] Resultado sera 0 [{"type":7,"value":"balanceOf"},{"type":16,"value":[{"type":5,"value":"b1761b44255107162d3c79680b81b4c8a5efc597"},{"type":7,"value":"LAND1"}]}] Chama por AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y - Resultado Nada, não passa verificação [{"type":7,"value":"notifica"},{"type":16,"value":[{"type":5,"value":"<KEY>"}, {"type":7,"value":"TRUCK1"}, {"type":7,"value":"Update TRUCK1 Allowed"}]}] Chama por AXxCjds5Fxy7VSrriDMbCrSRTxpRdvmLtx - Resultado Nada, não passa verificação ainda, pois nao podemos notificar um token do owner <KEY> com <KEY> [{"type":7,"value":"notifica"},{"type":16,"value":[{"type":5,"value":"<KEY>"}, {"type":7,"value":"TRUCK1"}, {"type":7,"value":"Update TRUCK1 Allowed"}]}] Chama por APLJBPhtRg2XLhtpxEHd6aRNL7YSLGH2ZL Token not found for this owner [{"type":7,"value":"notifica"},{"type":16,"value":[{"type":5,"value":"<KEY>"}, {"type":7,"value":"LAND11"}, {"type":7,"value":"Update TRUCK1 Allowed"}]}] Chama por APLJBPhtRg2XLhtpxEHd6aRNL7YSLGH2ZL Notificação status ok [{"type":7,"value":"notifica"},{"type":16,"value":[{"type":5,"value":"<KEY>"}, {"type":7,"value":"LAND1"}, {"type":7,"value":"Update TRUCK1 Allowed"}]}] Aqui nao avançamos na lógica, em criar uma lista que diz quais caminhões são permitidos (dentro do smart contract) Da maneira que está o exemplo, essa verificação é feita pelo fornecedor. Porem, conforme visto, toda operação segue certificada. Chama por AXxCjds5Fxy7VSrriDMbCrSRTxpRdvmLtx [{"type":7,"value":"notifica"},{"type":16,"value":[{"type":5,"value":"b1761b44255107162d3c79680b81b4c8a5efc597"}, {"type":7,"value":"TRUCK1"}, {"type":7,"value":"LAND1 100KG CAFÉ DO BOM EM COLETA"}]}] Chama por AXxCjds5Fxy7VSrriDMbCrSRTxpRdvmLtx [{"type":7,"value":"notifica"},{"type":16,"value":[{"type":5,"value":"b1761b44255107162d3c79680b81b4c8a5efc597"}, {"type":7,"value":"TRUCK1"}, {"type":7,"value":"LAND2 80KG CAFÉ DO BOM EM COLETA"}]}] Chama por AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y [{"type":7,"value":"mintNFT"},{"type":16,"value":[{"type":7,"value":"DIST1"},{"type":5,"value":"52eaab8b2aab608902c651912db34de36e7a2b0f"},{"type":7,"value":"ArmazemGourmet"}]}] Chama por APLJBPhtRg2XLhtpxEHd6aRNL7YSLGH2ZL [{"type":7,"value":"notifica"},{"type":16,"value":[{"type":5,"value":"<KEY>"}, {"type":7,"value":"DIST1"}, {"type":7,"value":"TRUCK1 CARGA RECEBIDA"}]}] TX ID a04a4e31295ab10a8fde4d2cd3264530c584d5d779b823baaf7c83c0866f0bd1 Chama por AK2nJJpJr6o664CWJKi1QRXjqeic2zRp8y [{"type":7,"value":"mintNFT"},{"type":16,"value":[{"type":7,"value":"CLI1"},{"type":5,"value":"<KEY>"},{"type":7,"value":"Cliente com referencia interna X"}]}] Chama por APLJBPhtRg2XLhtpxEHd6aRNL7YSLGH2ZL Attach 1 NEO pago ao Dono do contrato (Pelo Café) [{"type":7,"value":"notifica"},{"type":16,"value":[{"type":5,"value":"<KEY>"}, {"type":7,"value":"DIST1"}, {"type":7,"value":"CAFE PAGO 10 gramas expresso a04a4e31295ab10a8fde4d2cd3264530c584d5d779b823baaf7c83c0866f0bd1 "}]}] ```
079465412199c4960f50f687a901bccd66f9d0f9
[ "Markdown", "C#" ]
2
C#
optblocks/minicurso-sbpo2020-blockchain-supply-chain
c2be3d334d058c470d52d89e4ec3e1d83c9b4785
262d099ff075963bafed9a5478a41a1a02d7e7a5
refs/heads/master
<repo_name>tonilingardsson/Magento<file_sep>/wieg16-mvc-starter-kit/app/Models/RecipeModel.php <?php namespace App\Models; use App\Database; class RecipeModel extends Model { protected $table = 'recipes'; public function __construct(Database $db, array $modelData = []) { parent::__construct($db, $modelData); } }<file_sep>/wieg16-mvc-starter-kit/views/update.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>Mitt MVC-projekt/UPDATE</title> <!-- Bootstrap core CSS --> <link href="/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div id="navbar" class="navbar-collapse collapse"> <form class="navbar-form navbar-right"> <div class="form-group"> <input type="text" placeholder="Email" class="form-control"> </div> <div class="form-group"> <input type="<PASSWORD>" placeholder="<PASSWORD>" class="form-control"> </div> <button type="submit" class="btn btn-success">Sign in</button> </form> </div><!--/.navbar-collapse --> </div> </nav> <!-- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <div class="container"> <h1>Edit product</h1> <p>This is a template for a simple shop administration website. It includes a form callout. Use it as a online tool to modify product features to make the product more attractive for the customer.</p> <p><a class="btn btn-primary btn-lg" href="#update-product" role="button">Update! &raquo;</a></p> </div> </div> <div class="container"> <!-- Example row of columns --> <div class="row"> <div class="col-md-12"> <h2>Product form</h2> <form method="post" action="/update-product"> <input type="hidden" name="id" value="<?php echo $product['id'] ?>"> <div class="form-group"> <label for="exampleInputProduct">Product</label> <input type="text" value="<?php echo $product['product'] ?>" name="product" class="form-control" id="exampleInputProduct" placeholder="Product name"> </div> <div class="form-group"> <label for="exampleInputDescription">Description</label> <input type="text" value="<?php echo $product['description'] ?>" name="description" class="form-control" id="exampleInputDescription" placeholder="Description"> </div> <div class="form-group"> <label for="exampleInputPrice">Price</label> <input type="text" value="<?php echo $product['price'] ?>" name="price" class="form-control" id="exampleInputPrice" placeholder="Price"> </div> <div class="form-group"> <label for="exampleInputImage">Image</label> <input type="text" value="<?php echo $product['image'] ?>" name="image" class="form-control" id="exampleInputImage" placeholder="URL"> </div> <button type="submit" class="btn btn-default">Save changes</button> </form> </div> </div> <hr> <footer> <p>&copy; 2016 Company, Inc.</p> </footer> </div> <!-- /container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="/js/vendor/jquery-3.2.1.min.js"></script> <script src="/js/vendor/bootstrap.min.js"></script> </body> </html> <file_sep>/wieg16-mvc-starter-kit/app/Database.php <?php namespace App; use PDO; class Database { /** * @var PDO */ private $pdo; public function __construct(PDO $pdo) { $this->pdo = $pdo; } /** * @param integer $id * @return Model */ public function getById($table, $id) { $stm = $this->pdo->prepare('SELECT * FROM '.$table.' WHERE id = :id'); $stm->bindParam(':id', $id); $success = $stm->execute(); $row = $stm->fetch(PDO::FETCH_ASSOC); return ($success) ? $row : []; } public function getAll($table) { $stm = $this->pdo->prepare('SELECT * FROM '.$table); $success = $stm->execute(); $rows = $stm->fetchAll(PDO::FETCH_ASSOC); return ($success) ? $rows : []; } public function create($table, $data) { $columns = array_keys($data); $columnSql = implode(',', $columns); 'name,quantity,recipe_difficulty'; $bindingSql = ':'.implode(',:', $columns); ':name,:quantity,:recipe_difficulty'; $sql = "INSERT INTO $table ($columnSql) VALUES ($bindingSql)"; $stm = $this->pdo->prepare($sql); foreach ($data as $key => $value) { $stm->bindValue(':'.$key, $value); } $status = $stm->execute(); return ($status) ? $this->pdo->lastInsertId() : false; } /** * ÖVERKURS * * Skriv den här själv! * Titta på create för strukturidéer * Du kan binda parametrar precis som i create * Klura ut hur du skall sätt ihop rätt textsträng för x=y... * Implode kommer inte ta dig hela vägen den här gången * Kanske array_map eller foreach? */ public function update($table, $id, $data) { $columns = array_keys($data); ['name', 'description', 'price', 'url']; $columns = array_map(function($item) { return $item.'=:'.$item; }, $columns); // $columns efter ['name=:name', 'description=:description', 'price=:price', 'url=:url']; //implode: $bindingSql = implode( ',', $columns); $sql = "UPDATE $table SET $bindingSql WHERE id = :id"; $stm = $this->pdo->prepare($sql); $data['id'] = $id; foreach ($data as $key => $value) { $stm->bindValue(':'.$key, $value); } $status = $stm->execute(); return $status; } /** * Skriv den här själv! * Titta på getById för struktur */ public function delete($table, $id) { /** * Jag har skrivit det */ $stm = $this->pdo->prepare('DELETE FROM '.$table.' WHERE id = :id'); $stm->bindParam(':id', $id); $success = $stm->execute(); $row = $stm->fetch(PDO::FETCH_ASSOC); return ($success) ? $row : []; } }<file_sep>/wieg16-mvc-starter-kit/views/index.php <?php /* @var $products */ ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <meta name="description" content=""> <meta name="author" content=""> <link rel="icon" href="../../favicon.ico"> <title>Mitt MVC-projekt</title> <!-- Bootstrap core CSS --> <link href="/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet/less" type="text/css" href="/css/styles.less" /><!-- Added by Marcus --> </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Tonis MVC projekt</a> </div> <div id="navbar" class="navbar-collapse collapse"> <form class="navbar-form navbar-right"> <div class="form-group"> <input type="text" placeholder="Email" class="form-control"> </div> <div class="form-group"> <input type="password" placeholder="<PASSWORD>" class="form-control"> </div> <button type="submit" class="btn btn-success">Sign in</button> </form> </div><!--/.navbar-collapse --> </div> </nav> <!-- Main jumbotron for a primary marketing message or call to action --> <div class="jumbotron"> <div class="container"> <h1>Hello, world!</h1> <p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p> <p><a class="btn btn-primary btn-lg" href="/create" role="button">Add a product &raquo;</a></p> </div> </div> <div class="container"> <!-- Example row of columns --> <div class="row"> <table class="table table-striped"> <thead> <tr> <th>Product</th> <th>Description</th> <th>Price</th> <th>Image</th> <th></th> </tr> </thead> <tbody> <?php foreach ($products as $product): ?> <tr> <td><?= $product['product'] ?></td> <td><?= $product['description'] ?></td> <td><?= $product['price'] ?></td> <td><?= $product['image'] ?></td> <td><a class="btn btn-warning" href="/update?id=<?= $product['id'] ?>"><strong>Update</strong></a> <a class="btn btn-danger" href="/delete?id=<?= $product['id'] ?>"><strong>Delete</strong></a></td> </tr> <?php endforeach; ?> </tbody> </table> </div> <div class="row"> <div class="col-md-4"> <h2>Daft Punk</h2> <p>Buy it, use it, break it, fix it,<br> Trash it, change it, mail, upgrade it,<br> Charge it, point it, zoom it, press it,<br> Snap it, work it, quick, erase it,<br> Write it, cut it, paste it, save it,<br> Load it, check it, quick, rewrite it.</p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> <div class="col-md-4"> <h2>Technologic</h2> <p>Plug it, play it, burn it, rip it,<br> Drag and drop it, zip, unzip it,<br> Lock it, fill it, curl it, find it,<br> View it, code it, jam, unlock it,<br> Surf it, scroll it, pose it, click it </p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> <div class="col-md-4"> <h2>Lyrics</h2> <p> Cross it, crack it, twitch, update it,<br> Name it, read it, tune it, print it,<br> Scan it, send it, fax, rename it,<br> Touch it, bring it, pay it, watch it,<br> Turn it, leave it, stop, format it.</p> <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p> </div> </div> <hr> <footer> <p>&copy; 2017 <NAME>.</p> </footer> </div> <!-- /container --> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="/js/vendor/jquery-3.2.1.min.js"></script> <script src="/js/vendor/bootstrap.min.js"></script> <!-- script src="/js/vendor/less.js"></script><!-- Added by toni_luna --> </body> </html>
fb06be12bed512640901e273fa198091b9420095
[ "PHP" ]
4
PHP
tonilingardsson/Magento
049f4f5653f2caa94ad2187b8cb645636e8a33ae
d3f80b69f34bfd0949d937eb75adefe656af01ce
refs/heads/master
<file_sep>package com.tenpay.stockquote; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.omg.CORBA.PRIVATE_MEMBER; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.util.Xml; import android.view.Menu; import android.widget.TextView; public class StockItemQuoteActivity extends Activity { final static String QUERY_URL_START = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22"; final static String QUERY_URL_END = "%22)&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"; TextView quoteTextView; TextView daysLowTextView; TextView daysHighTextView; TextView yearLowTextView; TextView yearHighTextView; private static Handler handle = new Handler(){ @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stock_item_quote); quoteTextView = (TextView)findViewById(R.id.quoteTextView); daysLowTextView = (TextView)findViewById(R.id.dayLowTextView); daysHighTextView = (TextView)findViewById(R.id.daysHighTextView); yearLowTextView = (TextView)findViewById(R.id.yearLowTextView); yearHighTextView = (TextView)findViewById(R.id.yearHighTextView); Intent intent = getIntent(); String quote = intent.getStringExtra(MainActivity.STOCK_QUOTE); new AsyncTask<String, String, Entity>() { @Override protected Entity doInBackground(String... params) { Entity entity = new Entity(); entity.setQuote(params[0]); try { URL url = new URL(QUERY_URL_START + params[0] + QUERY_URL_END); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.connect(); InputStream inputStream = connection.getInputStream(); XmlPullParser parser = Xml.newPullParser(); parser.setInput(inputStream, null); parser.nextTag(); String name = parser.getName(); while(!"results".equals(name)){ parser.next(); if(parser.getEventType() == XmlPullParser.START_TAG){ name = parser.getName(); } } parser.nextTag(); parser.require(XmlPullParser.START_TAG, null, "quote"); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } name = parser.getName(); if ("DaysLow".equals(name)) { entity.setDaysLow(readText(parser)); } else if("DaysHigh".equals(name)){ entity.setDaysHigh(readText(parser)); }else if("YearLow".equals(name)){ entity.setYearLow(readText(parser)); }else if("YearHigh".equals(name)){ entity.setYearHigh(readText(parser)); }else{ skip(parser); } } } catch (Exception e) { Log.d("stack_quote", e.getMessage()); } return entity; } @Override protected void onPostExecute(Entity result) { daysLowTextView.setText(result.getDaysLow()); daysHighTextView.setText(result.getDaysHigh()); yearLowTextView.setText(result.getYearLow()); yearHighTextView.setText(result.getYearHigh()); quoteTextView.setText(result.getQuote()); } }.execute(quote); } private String readText(XmlPullParser parser) throws IOException, XmlPullParserException { String result = ""; if (parser.next() == XmlPullParser.TEXT) { result = parser.getText(); parser.nextTag(); } return result; } private void skip(XmlPullParser parser) throws XmlPullParserException, IOException { if (parser.getEventType() != XmlPullParser.START_TAG) { throw new IllegalStateException(); } int depth = 1; while (depth != 0) { switch (parser.next()) { case XmlPullParser.END_TAG: depth--; break; case XmlPullParser.START_TAG: depth++; break; } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.stock_item_quote, menu); return true; } } class Entity{ private String quote; private String daysLow; private String daysHigh; private String yearLow; private String yearHigh; public String getDaysLow() { return daysLow; } public void setDaysLow(String daysLow) { this.daysLow = daysLow; } public String getDaysHigh() { return daysHigh; } public void setDaysHigh(String daysHigh) { this.daysHigh = daysHigh; } public String getYearLow() { return yearLow; } public void setYearLow(String yearLow) { this.yearLow = yearLow; } public String getYearHigh() { return yearHigh; } public void setYearHigh(String yearHigh) { this.yearHigh = yearHigh; } public String getQuote() { return quote; } public void setQuote(String quote) { this.quote = quote; } }<file_sep>##My first android project ### function * xml parsing * multiple activity * stock quote picker
bf953ac33ed18ef53d062d9f4e56da9e0aa2a9f2
[ "Markdown", "Java" ]
2
Java
agileluo/stock_quote
de30a361dd916680bae2fc9e476a1f3b7d780dd7
df860e4cc899ec44a1b29a8809432b4c394c0b3b
refs/heads/master
<file_sep>package uploaddownload; import java.io.File; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.sikuli.script.Screen; public class sikulidownload { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("https://www.seleniumhq.org/"); driver.findElement(By.linkText("Download")).click(); driver.findElement(By.linkText("3.141.59")).click(); Thread.sleep(3000); Screen screen = new Screen(); screen.click("C:\\saveasbt.PNG"); Thread.sleep(3000); File file =new File("C:\\Users\\vamsi\\Downloads\\selenium-server-standalone-3.141.59.jar"); Thread.sleep(3000); if (file.exists()) { System.out.println("download"); } else { System.out.println("fail to download"); } Thread.sleep(3000); driver.quit(); } } <file_sep>package uploaddownload; import java.sql.Driver; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.GeckoDriverInfo; public class autoitdownload { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub WebDriver driver = new FirefoxDriver(); driver.manage().window().maximize(); driver.get("https://www.seleniumhq.org/"); driver.findElement(By.linkText("Download")).click(); driver.findElement(By.linkText("3.141.59")).click(); Runtime.getRuntime().exec("C:\\softwares\\download autoit.exe"); driver.quit(); } } <file_sep>package webdr; import org.openqa.selenium.By; import org.openqa.selenium.By.ById; import org.openqa.selenium.By.ByLinkText; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class navigations { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://en-gb.facebook.com/login/"); Thread.sleep(5000); System.out.println(driver.getTitle()); WebElement fblogin= driver.findElement(By.id("email")); fblogin.sendKeys("<PASSWORD>"); WebElement fbpassword= driver.findElement(By.name("pass")); fbpassword.sendKeys("<PASSWORD>"); driver.findElement(By.id("loginbutton")).click(); Thread.sleep(5000); WebElement lgout=driver.findElement(By.id("userNavigationLabel")); Thread.sleep(5000); Select select = new Select(lgout); select.selectByVisibleText("Log out"); driver.quit(); driver.quit(); } } <file_sep>$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("file:src/test/resources/features/login.feature"); formatter.feature({ "name": "login feature", "description": "", "keyword": "Feature" }); formatter.scenario({ "name": "login site for book a ticket", "description": "", "keyword": "Scenario", "tags": [ { "name": "@login" } ] }); formatter.step({ "name": "open broswerand enter url", "keyword": "Given " }); formatter.match({}); formatter.result({ "status": "undefined" }); formatter.step({ "name": "Enter username and password and click on sigin", "keyword": "When " }); formatter.match({}); formatter.result({ "status": "undefined" }); formatter.step({ "name": "user login into application", "keyword": "Then " }); formatter.match({}); formatter.result({ "status": "undefined" }); formatter.step({ "name": "user click on signoff", "keyword": "When " }); formatter.match({}); formatter.result({ "status": "undefined" }); formatter.step({ "name": "user logout from application", "keyword": "Then " }); formatter.match({}); formatter.result({ "status": "undefined" }); });<file_sep>[SuiteResult context=TestScript][SuiteResult context=test1]<file_sep>package apachepoi; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class FindNumberOfSheets { public static void main(String[] args) throws Exception { File file = new File("D:\\testdata1.xls"); FileInputStream inputstream = new FileInputStream(file); Workbook workbook = WorkbookFactory.create(inputstream); System.out.println(workbook.getNumberOfSheets()); // workbook.getSheet(null); //create new sheet in the name of gspran workbook.createSheet("gspran"); //remover sheet index 1 workbook.removeSheetAt(1); FileOutputStream outputstream = new FileOutputStream(file); workbook.write(outputstream); Thread.sleep(3000); workbook.close(); } }<file_sep>package webdr; import java.util.List; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class xpathcss { public static void main(String[] args) throws Exception { WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.apsrtconline.in/oprs-web/"); //find number of text fields List<WebElement> list=driver.findElements(By.xpath("//input[@type='text']")); System.out.println(list.size()); /* WebElement from =driver.findElement(By.id("fromPlaceName")); from.sendKeys("hyderabad"); Thread.sleep(5000); WebElement to = driver.findElement(By.name("destination")); to.sendKeys("vizianagaram"); to.click(); Thread.sleep(5000); driver.findElement(By.cssSelector("input[id='searchBtn']")).click(); Alert alert =driver.switchTo().alert(); Thread.sleep(3000); System.out.println(alert.getText()); Thread.sleep(3000); */ WebElement from = driver.findElement(By.id("fromPlaceName")); Actions action = new Actions(driver); action.sendKeys(from, "hyderabad").perform(); Thread.sleep(1000); action.sendKeys(Keys.ENTER).perform(); WebElement to = driver.findElement(By.id("toPlaceName")); action.sendKeys(to, "vij").perform(); Thread.sleep(2000); WebElement text =driver.findElement(By.linkText("VIJAYRAI")); action.click().perform(); Thread.sleep(3000); driver.quit(); driver.quit(); } } <file_sep>package webdr; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class facebooktest { public static void main(String[] args) throws Exception { WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://en-gb.facebook.com/login/"); WebElement username = driver.findElement(By.id("email")); username.sendKeys("9505078969"); Thread.sleep(5000); WebElement password = driver.findElement(By.id("pass")); password.sendKeys("<PASSWORD>"); Thread.sleep(5000); driver.findElement(By.id("loginbutton")).click(); Thread.sleep(5000); //driver.findElement(By.id("userNavigationLabel")).click(); driver.quit(); } } <file_sep>package tables; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class tableexample { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://datatables.net/"); //List<WebElement> element = driver.findElements(By.xpath("//table[@id='example']//tr")); //for(int index = 0;index<=10;index++) { WebElement element = driver.findElement(By.xpath("((//table[@id='example']//tr)[4]//td)[2]")); System.out.println(element.getText()); //System.out.println(element.size()); //System.out.println(driver.findElements(By.xpath("//table[@id='example']//tbody//tr")).size()); //WebElement table = driver.findElementS(By.xpath("//table[@id='example']//tbody//tr")); //System.out.println(table.getText()); //System.out.println(driver.findElements(By.xpath("//table[@id='example']//tr")).size()); Thread.sleep(2000); driver.quit(); } } <file_sep>package uploaddownload; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.sikuli.script.Screen; public class sikuliupload { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub /* WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.indeed.co.in/"); driver.findElement(By.xpath("//span[text()='Post your resume']")).click(); driver.findElement(By.xpath("//button[text()='Upload your resume']")).click(); Thread.sleep(3000); Screen screen = new Screen(); screen.type("D:\\resumegsp.docx"); screen.click("C:\\canclebt.PNG"); */ WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.indeed.co.in/"); driver.findElement(By.xpath("//span[text()='Post your resume']")).click(); driver.findElement(By.xpath("//button[text()='Upload your resume']")).click(); Thread.sleep(3000); Screen screen = new Screen(); //type in text filed screen.type("D:\\resumegsp.docx"); //clik button screen.click("C:\\openbt.PNG"); Thread.sleep(3000); driver.quit(); } } <file_sep>package uploaddownload; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class autoitupload { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS); driver.get("https://www.indeed.co.in/"); driver.findElement(By.xpath("//span[text()='Post your resume']")).click(); driver.findElement(By.xpath("//button[text()='Upload your resume']")).click(); Thread.sleep(3000); Runtime.getRuntime().exec("C:\\softwares\\auto2.exe"); Thread.sleep(10000); driver.quit(); } } <file_sep>package testNG; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class test2 { WebDriver driver = null; @BeforeTest public void openbrowser() { driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @Test public void login() { driver.get("http://newtours.demoaut.com/"); driver.findElement(By.name("userName")).sendKeys("mercury"); driver.findElement(By.name("password")).sendKeys("<PASSWORD>"); driver.findElement(By.name("login")).click(); } @Test(priority = 2,dependsOnMethods = "login") public void bookATicket() { driver.findElement(By.name("findFlights")).click(); driver.findElement(By.name("reserveFlights")).click(); driver.findElement(By.name("buyFlights")).click(); } @Test(priority = 3,dependsOnMethods = "login") public void logoff() { driver.findElement(By.linkText("SIGN-OFF")).click(); } @AfterTest public void closebrowser() throws Exception { Thread.sleep(3000); driver.quit(); } } <file_sep>package webdr; import java.awt.Desktop.Action; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class gmailTest1 { public static void main(String[] args) throws Exception { WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://accounts.google.com/ServiceLogin/identifier?service=mail&flowName=GlifWebSignIn&flowEntry=AddSession"); WebElement username = driver.findElement(By.id("identifierId")); username.sendKeys("<EMAIL>"); Thread.sleep(2000); driver.findElement(By.xpath("//span[text()='Next']")).click(); WebElement password = driver.findElement(By.name("password")); password.sendKeys("<PASSWORD>"); Thread.sleep(2000); driver.findElement(By.xpath("//span[text()='Next']")).click(); //Actions action = new Actions(driver); //action.sendKeys(username,"<EMAIL>") Thread.sleep(10000); // WebElement next1 = driver.findElement(By.xpath(); driver.quit(); } } <file_sep>package testNG; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.Test; public class hardAssert { @Test public void verifytitle() throws Exception { WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.google.com/"); String expectedname = "Google"; String actualname = driver.getTitle(); Assert.assertEquals(actualname, expectedname); Thread.sleep(5000); driver.quit(); } }
de1d85425cda93f6a017757177f52facac47b00f
[ "JavaScript", "Java", "INI" ]
14
Java
gspraneeth/framework
b8dd15894b96a171fa0eec71a1682880f4fc1871
a44312545e402c0151ccb60b101cbbf15c162d0b
refs/heads/master
<repo_name>meathill-lecture/date-picker<file_sep>/date-picker/app/date-picker.js /** * Created by realm on 2017/2/15. */ import $ from 'jquery'; import template from '../template/picker.hbs'; import calendar from '../template/calendar.hbs'; import EasyDate from './EasyDate'; import utils from './utils'; export default class DatePicker { /** * * @param target * @param {Object} options * @param {Boolean|null} options.confirm 是否有确认按钮 * @param {Boolean|null} options.scattered 是否选择单日 * @param {Boolean|null} options.multiple 是否可以选择多个日期 * @param {String|null} options.start 可选日期范围的起点,默认是今天 * @param {String|null} options.end 可选日期范围的终点,为空则没有,即用户可以选择任意时间 * @param {String|null} options.format 日期格式,默认为 `yyyy-mm-dd`,无大小写区分 */ constructor(target, options = {}) { this.target = target; this.range = utils.getRange(options); if ('multiple' in options) { options.confirm = options.multiple; } this.createElement(options); this.delegateEvent(options); this.setValue(target.val()); this.options = options; } createElement(options) { options = Object.assign({}, options); let today = options.today = new EasyDate(0, options); let start = options.start = options.start ? new EasyDate(options.start, options) : today; let end = options.end = options.end ? new EasyDate(options.end, options) : null; let current = start.clone(); current.setDate(1); let months = []; for (let i = 0; i< 2; i++) { // 默认画两个月 let month = DatePicker.createMonthObject(current, today, start, end); months.push(month); current.add('1m'); } options.months = months; let item = $(template(options)); item.appendTo(document.body); this.$el = item; this.lastMonth = current; setTimeout(() => { item.removeClass('out'); }, 10); } static createMonthObject(current, today, start, end) { return current.toObject(today, start, end); } confirm() { let value = this.$el.find('.select').map(function() { return $(this).data('date'); }).get(); this.target.val(value.join(',')); this.hide(); } delegateEvent(options) { this.$el .on('click', 'li:not(.disabled,.empty)', this.onClick.bind(this)) .on('click', '.tqb-dp-close-button', () => { this.$el.addClass('out'); }) .on('click', '.tqb-dp-confirm-button', () => { this.confirm(); }) .on('transitionend', () => { this.$el.toggleClass('hide', this.$el.hasClass('out')); }); this.$el.find('.tqb-dp-container').on('scroll', event => { let container = event.target; if (container.scrollHeight - container.scrollTop <= container.offsetHeight + 10) { let item = calendar(DatePicker.createMonthObject(this.lastMonth, options.today, options.start, options.end)); $(container).append(item); this.lastMonth.add('+1m'); } }); } setValue(value) { let values = value.split(','); values.forEach( value => { this.$el.find('[data-date="' + value + '"]').addClass('select'); }); } show() { let options = this.target.data(); let range = utils.getRange(options); if (range !== this.range) { this.$el.remove(); this.createElement(options); this.delegateEvent(options); this.setValue(this.target.val()); this.options = options; this.range = range; return; } this.$el.removeClass('hide'); setTimeout(() => { this.$el.removeClass('out'); }, 10); } hide() { this.$el.addClass('out'); } onClick(event) { let li = $(event.currentTarget); if (li.hasClass('select')) { li.removeClass('select'); return; } if (!this.options.multiple) { this.$el.find('.select').removeClass('select'); } li.addClass('select'); if (!this.options.confirm) { this.confirm(); } } }<file_sep>/date-picker/app/index.js const a = 1; const b = 2; const c = a + b; module.exports = {c};<file_sep>/sample/let-const.js /** * Created by meathill on 2017/5/25. */ let a = 1; for (let a = 0; a < 5; a++) { console.log(a); } console.log(a);<file_sep>/date-picker/app/utils.js /** * Created by realm on 2017/3/1. */ const toString = Object.prototype.toString; module.exports = { getRange(options) { let start = options.start || ''; let end = options.end || ''; return `${start}_${end}`; }, isString(obj) { return toString.call(obj) === '[object ' + name + ']'; } };<file_sep>/content.md <!-- title: date-picker-tutorail description: a full tutorail of date-picker --> ### 实战 # 手机日历组件 #### [@meathill](https://weibo.com/meathill/) <!-- page --> {{> author}} <!-- page --> ## 课程大纲 1. 项目启动 & 需求分析 2. npm & package.json 3. Stylus 4. 静态 HTML 开发 <!-- section --> 5. ES2015 简介 6. 使用 ES6 开发 JavaScript 7. 使用 Mocha + should.js + Babel 测试 <!-- .element: start="5" --> <!-- section --> 8. 搭建 Webpack + Babel 编译环境 9. 使用 Handlebars 处理模板 10. 完成 UI 开发和测试 11. 使用策略模式解决分支需求 <!-- .element: start="8" --> <!-- section --> 11. Gulp 打包 12. 配置 Webpack 适应不同环境的打包 13. 使用 Weinre 解决微信下的问题 <!-- .elment: start="11" --> <!-- section --> 14. 使用 GitHub Pages 搭建文档网站 15. 回顾,总结 <!-- .element: start="13" --> <!-- page --> ## 教学目标 通过学习本系列教程,可以了解现代化前端开发的方方面面: 1. 学会搭建开发环境,使用 Webpack、Babel、Stylus、Gulp 等工具 3. 了解测试驱动开发,学会写测试用例、自动化测试 4. 学会打包发布代码 5. 学会用 GitHub Pages 维护产品文档 6. 学会写类似的组件 <!-- page --> ## 第一讲 1. 项目启动 & 需求分析 2. 技术选型 3. 流程图 4. [实战] 初始化项目 5. [实战] 开发静态 HTML <!-- page --> ## 需求分析 <!-- section --> <div class="row"> <div class="col"> ![例子](./img/sample.png)<!-- .element: height="600" --> </div> <div class="col" markdown="1"> <ol> <li>开发一个日历控件</li> <li>主要在手机浏览器中使用,包括公众号</li> <li>点击日期输入框,弹出控件,选择日期,收起控件</li> <li>尽量独立,少依赖,少引入框架</li> <li>样式如图</li> </ol> </div> </div> <!-- section --> ### 通用规则 1. 今日用黄点标记 2. 不可选的日期为灰色 3. 打开关闭都需要动画 4. 周末用橙色标记 5. 可以指定某个日期为橙色(端午节、清明节等) 6. 向上滚屏可以自动增加下个月 7. 可以用参数配置 <!-- section --> ### 选择单日 1. 点击日期视为选中 2. 点击同一日期视为取消 3. 点击其它日期视为多选 4. 若自动提交,点够数量就提交 5. 不自动提交,右上角有提交按钮,点击后提交 <!-- section --> ### 选择多日 1. 第一次点击时,视为选择时间段的一端,第二次点击为选择另一端 2. 允许用户先选择终点,再选择起点 3. 若自动提交,第二次点击后,控件伴随着动画关闭 4. 不自动提交,第三次点击会清空之前的选择,并重新选择起点 <!-- page --> ## 技术选型 1. 开发效率 2. 使用效率 3. 维护成本 <!-- section --> ### jQuery 1. 事件代理 2. 创建 DOM 3. 简单的 DOM 操作 <!-- section --> ### 模板引擎 Handlebars 1. 预编译 2. 比较熟 <!-- section --> ### Stylus -> CSS 1. 使用预处理工具,方便开发 2. 简单方便快捷,基于 Node.js 3. 支持变量、函数、循环 4. 丰富的内建函数 <!-- section --> ### 语言 1. ES6 Class 2. Webpack + Babel 4. 完整的测试用例 <!-- section --> ### 提交物料 1. 最终文件 CSS、JS 各一个 2. 源代码 3. 使用文档 <!-- page --> ## 这套方案的优势 1. 使用比较简单,嵌入资源文件即可 2. 使用 jQuery,前后兼容性好,对方容易接手 3. 源代码保持最大的弹性,方便扩展开发 <!-- page --> ## 工作流程 1. 将事件绑定在 `<body>` 上 2. 配置信息使用 `data-*` 写在 `<input>` 上 3. 用户点击 `input[type=text].tqb-date-picker` 后 1. 如果此文本框尚无日历元素 2. 则生成一个元素并绑定 4. 弹出日历窗口 5. 用户点击后选中日期 <!-- section --> ![日历组件流程图](./img/flow.svg)<!-- .element: class="bg-w" --> <!-- page --> ## 开工!! <!-- page --> ## 0. 准备阶段 1. 安装 node.js 2. 安装 Stylus 3. [可选] 安装 [Live-server](http://tapiov.net/live-server/) <!-- section --> ### Live-server Live-server 是开发服务器,基于 Node 实现,能够实现自动刷新。 用法: ```bash live-server --port=8081 --host=localhost --ignore=styl ``` <!-- page --> ## 1. 初始化项目 <!-- section --> ### NPM Node Package Manager = Node 包管理工具 1. 管理依赖 2. 发布我们自己的包 3. 记录常用脚本 <!-- section --> ### package.json 此项目的配置信息,可被 `npm` 读取。 1. 版本、内容、作者等描述 2. 依赖:运行时依赖 & 开发时依赖 3. 可执行脚本 <!-- page --> ## 2. 配置 Stylus <!-- page --> ### 3. 开发静态 HTML <!-- page --> ### 实战:手机日历组件 第二讲 # ES6 & 测试 #### [@meathill](https://weibo.com/meathill/) <!-- page --> ## 课程大纲 1. ES2015(ES6)简介 2. 使用 ES6 开发 JavaScript 3. 使用 Mocha.js + Should.js 搭建测试环境 <!-- page --> ### 教学目标 ## 1. 了解 ES2015 1. `let` 和 `const` 2. 变量解构 3. 箭头函数 4. `Class` 5. `Module` 6. 模板字符串 <!-- page --> ## 2. 了解测试 1. 为什么要写测试? 2. 什么是单元测试?怎么写? 3. 怎么开始写测试? <!-- page --> ## 3. 测试驱动开发 #### [实战] <!-- page --> ## ES2015 / ES6 <!-- section --> ES = ECMAScript = 由 ECMA 国际(前身为欧洲计算机制造商协会)通过 ECMA-262标准化的脚本程序设计语言。 <!-- section --> * JavaScript 是 ECMAScript 的一种方言 * 浏览器中的 JavaScript 增加了 DOM 和 BOM * 目前 ES5 基本完成普及,主流浏览器部分或全部支持 ES6 <!-- section --> * ES5 = ES6 之前的规范 * ES6 = ES2015 * ES7 = ES2016 + ES2017 * ES8 = ES2018(讨论中) * ES9 = ES2019(征集想法中) <!-- page --> ## JavaScript 的历史 <!-- section --> ### 妾本出身贫寒家,未想尊威仪天下 1. 为校验表单而生 2. 只花了10天就设计出原型 3. 连名字都是山寨的…… <!-- section --> ### 江山代有才人出,各领风骚数百年 1. JScript 2. Flash,ActiveX 3. SilverLight,JavaFX <!-- section --> ### 天下逐鹿,终归秦属 1. ES3 大体上统一了 JavaScript 2. ES4 夭折 3. HTML5 获得浏览器之争的最终胜利 4. ES5 诞生 5. ES6 诞生 <!-- page --> > ES2015 增加了很多优秀的新特性,可以让我们开发出更强壮,更好维护的代码。 > 以后的开发,都应当以 ES2015 为基础。 <!-- page --> ## ES2015 新特性 <!-- page --> ### `let` & `const` 1. 声明变量 `let a = 1;` 2. 声明常量 `const B = 2;` 3. 块级作用域 [code](./sample/let-const.js) 4. 没有变量提升 [code](./sample/let-const-2.js) <!-- page --> ### 变量解构 Destructuring 按照一定模式,从数组和对象中提取值。 ```javascript // 解构数组 let [a, b, c] = [1, 2, 3]; // a = 1; // b = 2; // c = 3; ``` <!-- section --> 只要两边模式对照一致,可以有很多种拆法: ```javascript let [a, ...b] = [1, 2, 3, 4]; // a = 1 // b = [2, 3, 4] let [a, , b] = [1, 2, 3]; // a = 1 // b = 3 ``` <!-- section --> 解构对象 ```javascript let {a, b, c} = {a: 1, b: 2, c: 3}; // a = 1 // b = 2 // c = 3 // 解构对象只关注键名,不关注顺序 let {b, c, a} = {a: 1, b:2, c: 3}; // a = 1 // b = 2 // c = 3 ``` <!-- section --> 常见用法:函数返回多个值 ```javascript function sample() { return { a: 1, b: 2, c: 3 }; } let {a, b, c} = sample(); ``` <!-- section --> 常见用法:作为函数参数 ```javascript function sample({id, name, age, sex, height, photo}) { // do something } sample({ id: 1, name: 'meathill', age: 33, sex: MALE, height: 181, photo: './photo.jpg' }); ``` <!-- page --> ### 箭头函数 ```javascript let f1 = p1 => { // do something }; let f2 = p1 => p1 * 100; // 等价于 let f2 = p1 => { return p1 * 100; } let f3 = (p1, p2) => { // do something }; let f4 = ([p1, p2]) => { // do something } ``` * 箭头函数的 `this` 固定指向声明它的对象 <!-- page --> ### Class ```javascript class A { constructor() { // 构造函数 // 声明实例属性 this.var = ''; } method1() { } method2() { } } ``` <!-- section --> 几个常见的点: 1. 这里的类仍然是原型继承 2. `class` 关键词不存在变量提升 3. 子类构造函数里,必须 `super()` 之后才有 `this` <!-- page --> ### Module 终于有模块机制了! ```javascript // profile.js export let name = 'Meathill'; export let age = 33; export let weight = 100; // user.js import * as user from './profile' // user.name = 'Meathill'; // user.age = 33; // user.weight = 100; // 亦可使用解构方法 import {name, age, weight} from './profile' ``` <!-- section --> 默认值 ```javascript // profile.js export default 'Meathill'; export let age = 33; export let weight = 100; // user.js import anyname from './profile.js'; ``` <!-- page --> ### 模板字符串 ```javascript let name = 'Meathill'; let age = 33; let favor = 'Gakki'; alert(`Hi, I'm ${name},I'm ${age}, I like ${favor}`); // Hi, I'm Meathill, I'm 33, I like Gakki ``` 1. 支持运算符,如 `Hi, ${user.name}` `${a * 3}` 2. 支持换行 3. 尽量不要在里面使用复杂的运算 <!-- page --> ## 测试与单元测试 <!-- page --> ### 我对测试的态度 1. 开发人员必须了解测试 1. 测试用例 2. 边界条件 3. 回归测试 2. 开发人员应该自己写测试 1. 稳定质量 2. 方便重构 3. 提升开发效率 3. 不用追求测试覆盖率 <!-- section --> ### 单元测试 <!-- section --> ### 什么是单元测试? > 在计算机编程中,单元测试(英语:Unit Testing)又称为模块测试, 是针对程序模块(软件设计的最小单位)来进行正确性检验的测试工作。 程序单元是应用的最小可测试部件。 > [Wiki](https://zh.wikipedia.org/zh-hans/单元测试) <!-- section --> ### 怎么写单元测试? 以 Node.js 为例 ```javascript const assert = require('assert'); assert.equal(1, '1'); // 1 == '1' true ``` <!-- section --> 核心概念: 1. 断言 2. 边界条件 <!-- page --> ### 我以前没写过,现在要怎么开始? 1. 如果要重构,先写测试 2. 比较重要的操作,先写测试 3. 如果要修复 Bug,先写测试 > 总之,测试不嫌少,能写赶紧写。 <!-- page --> ## 测试驱动开发 1. Test Driven Development 2. 先想怎么用,而不是先想怎么写 3. 适用于前期规划项目 <!-- page --> ## 工具 * [Mocha.js](https://mochajs.org/) * [Should.js](https://shouldjs.github.io/) <!-- page --> ## Coding <!-- page --> ### 实战:手机日历组件 第三讲 # UI 开发 & 策略模式 #### [@meathill](https://weibo.com/meathill/) <!-- page --> ## 课程大纲 1. 使用 Webpack + Babel 搭建开发环境 2. 开发 UI 界面 3. 使用策略模式解决分支需求 <!-- page --> ### 教学目标 1. 学会搭建 Webpack + Babel 开发环境 2. 学会使用各种 Loader 解决问题 3. 学会开发本插件 4. 了解设计模式,学会使用策略模式 <!-- page --> ## Webpack Webpack 是一个打包工具,降低 Web 中加载资源的难度。 * [官网](https://doc.webpack-china.org/) * [文档](https://doc.webpack-china.org/configuration) * 当前版本:2.6.1 <!-- section --> ### 依赖管理的发展 1. 最早:所有资源静态引入 2. 接下来:AMD/CMD/CommonJS/Sea.js 3. 打包流出现:Browserify 4. 打包一切:Webpack <!-- section --> ![webpack 示意图](https://webpack.js.org/bf093af83ee5548ff10fef24927b7cd2.svg) <!-- page --> ## Babel Babel 是一个转译工具,将高版本的 JS 转译成低版本的 JS。亦可转译 JSX(React)。 * [官网](https://babeljs.io/) * [文档](https://babeljs.io/docs/setup/#installation) * 当前版本: * babel-core 6.24.1 * babel-loader 7.0.0 <!-- section --> ### Babel 入门 1. 配置文件 [.babelrc](http://babeljs.io/docs/usage/babelrc/) 2. 预设环境 [preset env](http://babeljs.io/docs/plugins/preset-env/) 3. 插件 <!-- page --> ## 配置环境 <!-- page --> ## Coding <!-- page --> ## 设计模式 > 可复用面向对象软件的基础 <!-- section --> 1. 面向对象 2. 提高代码的复用性和维护效率 3. 锦上添花 <!-- section --> ### 使用设计模式的正确姿势 1. 了解设计模式,暗记于心 2. 学习别人使用设计模式的方式、场景 3. 在合适的地方使用合适的模式 <!-- page --> ### JavaScript 中的设计模式 1. JS 有独特的语法,也有独特的实现模式 2. ES6 与 ES5 的实现模式也相差甚远 3. 不要照搬其它语言中的模式 <!-- page --> ### 策略模式 > 定义一系列算法,把它们一个个封装起来,并且使它们可相互替换。 1. 如果把所有可能用到的算法都写到一起,会使它变得巨大复杂难以维护 2. 不同的时候需要不同的算法,一个类里不应包含它不支持的方法 3. 新增同类型的需求时,增加算法和调整现有算法都会变得很困难 <!-- section --> 1. 所有策略的主要流程是一致的 2. 个别不一致的环节可以独立实现 3. 通常配合工厂类一起使用 <!-- page --> [回顾一下我们的需求](#/5/3) 1. 主要业务流程一致 2. 少数逻辑有区别: 1. 点击日期后的处理 2. 输出日期到文本框 3. 初始化日期的显示 这两个需求差异,很适合用策略模式来处理。 <!-- page --> ## 继续 Coding <!-- page --> ### 实战:手机日历组件 第四讲 # 用 Gulp 打包发布吧! #### [@meathill](https://weibo.com/meathill/) <!-- page --> ## 课程大纲 1. 为什么要后(批)处理? 2. 使用 Gulp 进行批处理 3. 使用 ESLint 工具进行代码审查 <!-- page --> ### 教学目标 1. 了解什么是批处理,学会选用批处理工具 2. 学会使用 Gulp 进行批处理 3. 学会打包组件 4. 学会用 ESLint 审查代码 <!-- page --> ## 为什么要批(后)处理? 1. Stylus => CSS 2. ES2015/ES2017 => ES5 3. node_modules => CDN 4. 图片压缩 5. 开发环境 => 生产环境 <!-- page --> 一些可能的抱怨: > 我直接写,写完直接 FTP 传上去多省事儿啊! > 遇到问题我登到 FTP 上改不就好了么? > 整这些乱七八糟的干嘛? <!-- page --> 真的是这样么? <!-- section --> ### “我直接写,写完直接 FTP 传上去多省事儿啊!” 1. 文件多,难以确定哪些需要上传 2. 无法区分开发环境与生产环境 3. HTML/CSS/JavaScript 天生的缺陷 <!-- section --> ### “遇到问题我登到 FTP 上改不就好了么?” 1. 版本管理的问题 2. 缓存的问题 <!-- page --> 结论: > 使用中间代码 + 后处理代表着先进生产力,可以提高开发、维护、部署效率,我们应该学习运用。 <!-- page --> ## Gulp 1. Ant => Grunt => Gulp / npm script 2. 速度快 3. 用法简单,没有历史包袱 <!-- page --> ```javascript const gulp = require('gulp'); const stylus = require('gulp-stylus'); const cleanCSS = require('gulp-clean-css'); gulp.task('stylus', () => { return gulp.src('./styl/screen.styl') .pipe(stylus()) .pipe(cleanCSS({ level: 2 })) .pipe(gulp.dest('dist/screen.css')); }); ``` <!-- page --> ### 批处理 ```javascript gulp.task('stylus', () => { // .... }); gulp.task('webpack', () => { // .... }); gulp.task('html', () => { // .... }); gulp.task('default', ['stylus', 'webpack', 'html']); ``` <!-- page --> ### 批处理顺序 ```javascript const sequence = require('run-sequence'); const del = require('del'); gulp.task('clear', () => { return del(['dist']); }); gulp.task('default', callback => { sequence( 'clear', ['other', 'task'], callback ); }) ``` <!-- section --> 任务完成的判定依据: 1. `callback()` 2. 返回 gulp 流 3. 返回 Promise 对象 <!-- page --> ## Coding! <!-- page --> ## 处理不同环境 1. 不同的配置 2. 适配不同平台 3. <!-- page --> ### `webpack.DefinePlugin` ```javascript const webpack = require('webpack'); module.exports = { .... plugins: [ new webpack.DefinePlugin({ DEBUG: false, VERSION: JSON.stringify('1.0.0'), SUPPORT_ANDROID: false }) ] }; ``` <!-- page --> ## Coding! <!-- page --> ## 自动化代码审查 1. 确保所有代码风格一致 2. 加强团队配合能力 <!-- page --> ### ESLint 1. 检查代码是否符合规范 2. 执行最重要,有没有分号不重要 <!-- section --> ## Coding! <!-- page --> ### [`pre-commit`](https://www.npmjs.com/package/pre-commit) 利用 Git pre-commit 钩子,检查代码,不合规不入库 <!-- section --> 现实中: 1. 从现在开始,先审查新代码 2. 如果重构,把重构的代码拿来一起审查 <!-- page --> ## Coding! <!-- page --> ## 总结 1. 现代化前端开发,我们会写很多中间代码,需要批处理将其转换成最终代码 2. 一些资源,也在此时进行处理 3. 打包输出不同环境下的代码 4. 代码入库之前要进行审查,保证规范执行 <!-- page --> ### 实战:手机日历组件 第五讲 # 模块管理/文档/发布 #### [@meathill](https://weibo.com/meathill/) <!-- page --> ### 前情回顾 [时光机](#/5/1) Note: 我有一个朋友创业,他们公司后端实力很强,前端就比较一般。但是他们是一家2C的公司,基于微信做业务,所以迫切需要提升 Web 的用户体验。他们当时需求一个好用的日期选择组件,但是市面上暂时不好找;而且他们还有一些个性化的需求,即使找到了组件他们的前端也改不动。 这是我的幸运,同时也是他们的不幸。 (点击链接)好了,这就是他们的需求:(复述需求) 我当时正好没工作,所以就接了这个活儿。活儿本身不复杂,我大约花了3~4个工作日就完成了,其中一天受困于一个诡异的 Bug。交付之后,朋友公司的前端小妹找到我,希望看看我的源码,学习一下。我当然就给她了,结果她看不明白,因为我使用了大量的工具,开发过程和传统的基于 jQuery 的开发很不一样。所以我就产生了做这样一个系列教程的想法,一方面有机会帮助很多人,另一方面将来内训也可以省去很多力气。 前面我已经进行了4次分享,讲了从项目启动需求分析到结构搭建、CSS 预处理、编译、模板、打包、自动化测试,等等。这是我们第五次,也是原定最后一次分享,这次分享,我的目标是: <!-- page --> ## 教学目标 1. 理解 JS 模块管理 2. 学会发布符合各种标准的代码 3. 学会发布 NPM 模块 4. 学会使用 GitHub Pages <!-- page --> ## 课程大纲 1. JavaScript 的模块管理 2. 三种主流模块模型的特点 3. 打包输出同时支持三种模型的代码 4. 将代码发布到 NPM 5. 制作文档 6. 将文档发布到 GitHub Pages Note: 为达到这个目标,今天的分享会分成这些章节。 <!-- page --> ## JavaScript 的模块管理 <!-- page --> ### 模块管理的起源 Note: 首先我们来了解一下模块管理的起源。可能有一些同学不很理解,尤其是一些接触过一定前端的后端同学。现代化的前端开发变得非常复杂,做任何一件事情几乎都要搭建好久的环境,这让很多习惯于抄起 jQuery 就是干的同学很不爽。 但是,这是有原因的。接下来我们来看看为什么。 <!-- section --> 程序员的基础行为准则: DRY = Don't Repeat Yourself 不要重复你自己。 Note: 作为一名程序员,我们应该谨记:Dont repeat yourself,不要重复你做过的工作。这一点非常重要。只有程序员才有这样的能力,自己创造工具,避免重复性的劳动;同时,作为程序员,也必须这样,才能避免自己的精力和时间被重复性工作浪费掉。 <!-- section --> 早年的前端开发: 1. 以全局使用为主 2. 以复制粘贴为主 <!-- section --> 1. DOM 结构发生变化,代码失效 2. 修改了某段代码,其它页面失效 3. 不同代码容易冲突 <!-- section --> 模块管理 = 使用写好的代码 好处: 1. 节省开发时间 2. 节省测试时间 3. 可以使用更小的粒度 4. 可以版本管理 <!-- page --> ### 模块管理的发展 <!-- section --> 最早: 1. AMD => require.js 2. CMD => sea.js 3. CommonJS => Node.js 4. 全局,命名空间 => jQuery,Lodash/Underscore <!-- section --> 接下来: 1. AMD vs CMD 2. Browserify 3. Webpack 4. UMD Note: Browserify 彻底的解决了 JS 模块管理问题。 Webpack 顺手解决了其它资源管理的问题。 <!-- section --> 最终胜出者:Webpack 优势: 1. 海量 NPM 资源 2. 打包所有资源,非常方便 <!-- page --> ## 现阶段的模块管理 <!-- page --> ### 全局 1. 基于全局,可以有简单的命名空间 2. 适用于羽量级项目 3. 快捷方便,寿命最长,支持最多 <!-- page --> ### CommonJS 1. `module.exports={}` 2. 支持广泛,资源丰富 3. 局部变量更方便 <!-- page --> ### ES6 Module 1. CommonJS 的取代者 2. 更严格,静态化,方便运行时优化 3. 支持 `export default` 4. 很容易转译成 CommonJS <!-- page --> ## Coding! <!-- page --> ## 将代码发布到 NPM 1. 方便复用代码 2. 方便管理依赖 3. 有机会为开发社区做出贡献 4. 好的项目在哪里都是加分项 Note: “不到长城非好汉”,相信前端同学也会有“不发NPM也遗憾”的想法。 <!-- page --> ### package.json 1. version 版本 2. main 入口 <!-- section --> ### .npmignore 1. 可以忽略,此时会使用 .gitignore 2. 如有,则忽略 .gitignore 3. 建议只包含必要的文件,或编译后的文件 <!-- page --> ## Coding! <!-- page --> ## 制作文档 1. 详细的文档非常必要 2. 好的文档对产品推广帮助巨大 3. 建议使用 markdown 维护文档 <!-- page --> ### Makrdown 的好处 1. 语法简单,结构和纯文本类似 2. 可以转换成 HTML,表现力丰富 3. 支持内嵌 HTML <!-- page --> ## Coding! <!-- page --> ## 使用 GitHub Pages ## 托管静态网站 1. GitHub Pages 是 GitHub 提供的免费的静态网站托管服务 2. 可以为任何仓库创建静态网站 3. 也可以为组织或个人创建静态网站 <!-- page --> ## Coding! <!-- page --> ## 友情提示 请对自己的作品负责! 1. 请确保你的作品可以正常工作 2. 请使用测试框架保障历史功能 3. 请建设友好全面的文档 <!-- page --> ### 实战:手机日历组件 第六讲 # 重构为 Vue 版本 #### [@meathill](https://weibo.com/meathill/) <!-- page --> {{> author}} <!-- page --> ## 教学目标 1. 知道什么是组件化,了解组件化的必要性 2. 了解 MVVM 与 DOM 操作之间的区别 3. 学会 Vue 的组件化实现 4. 学会将 jQuery 插件重构为 Vue 组件 Note: 去年春天,也就是我计划做这个系列教程的时候,如果你把教程看完,把里面介绍的知识点都学会,基本上已经是一个合格的前端工程师了。 但是前端技术发展就这么快,短短不到一年时间,Vue、React 已经取代 jQuery 之前的地位,现在几乎所有公司都把技术切到新架构上,前端工程化,工具复合使用是常规操作,随之而来的便是组件化。 所以,为了继续丰富大家的技术栈,便有了这次讲堂。 我希望通过这次讲堂,能够(复述) <!-- page --> ## 课程大纲 1. 什么是组件化?组件化的优势是什么? 2. 什么是 MVVM?MVVM 和操作 DOM 有何区别? 3. 基于 Vue 进行组件化开发 4. 重构日历选择组件 Note: 接下来,我计划按照这样的章节来讲解组件化的内容。 <!-- page --> ## 组件化 <!-- page --> 1. 组件 = 控件、jQuery 插件、组件 2. 组件化 = 把通用的功能,封装成特定形态的代码 3. 组件化的优势 1. 节省开发时间 2. 获取自己尚不具备的能力 Note: 组件化并非新生事物。作为程序员,我们很清楚 DRY 法则,即不要重复你自己之前做过的工作。当我们做好的一些功能后,自然希望把它们封装成固定的预制件,以备将来再次使用。在前端工具体系尚未成形之前,我们也有很多不同的组件,当时,我们称他们为控件,如果是基于 jQuery 开发的,我们一般会称其为 jQuery 插件。现在你在论坛上仍然能看到很多求插件的问题。所以今天我们讨论的组件,就等于控件插件组件之和,后面不会再特意区分。 这里我们给“组件化”下一个简单的定义。组件化,就是把通用的功能,封装特定形态的代码。这里,通用两个字的作用非常大,因为只有足够通用的代码,太有组件化的必要。比如,视频播放器、文件上传、幻灯片,等等。至于封装成什么形态,这要看我们的技术选型了。 组件化具备很多优势,我认为其中最有效的,一是节省开发时间,二是可以让开发者获取自己暂时还不具备的能力。这两个大家直接从字面上就可以理解,我就不展开讲了。 <!-- page --> ### 组件化的发展 1. Ctrl+C Ctrl+V 代码块 2. jQuery 插件(及其它插件体系) 3. Web Components 4. Browserify/Webpack 5. 新三大框架 Note: 组件化的发展,其实就是大家想方设法复用之前写过的代码。这个部分在上一讲也提过,首先我们复制粘贴代码的方式来复用代码。接下来,我们遭遇到各种各样的问题。于是,当时最通用最普及的jQuery就提出了自己的插件功能,一时间大家都以 jQuery 为基础来创建插件,与之同时,其他的几大基础类库也都提出了自己的插件体系,现在这些基础类库极其插件仍在为丰富的互联网体验服务。 接下来,有人提出了 Web Components 规范,这套规范包含自定义元素、Shadow DOM,HTML 模板,HTML import 几大模块。因为太过复杂,所以愿意支持它的开发商并不多,现在只有 Google 的 Polymer 库在努力实现。 再接下来,有了 Browserify 和 Webpack 以后,模块管理取得了长足的进步。尤其是使用 webpack,不仅可以方便的引用 JS,还可以方便的管理组件所需要的其他元素,比如 CSS、图片、字体、乃至音频视频。 这也为最后新三大框架(Vue、React、Angular)都把组件化作为基础架构铺平了道路。它们和组件化互相成就,现在,使用这三大框架基本上都要使用组件化,这是今天一直讲好的缘由。 <!-- page --> ## MVVM 框架 Note: 说完了组件化,我们再来聊聊 MVVM 框架。 <!-- page --> 1. MVVM 是一种 UI 框架 2. MVVM = Model + View + ViewModel 3. MVVM 讲究数据驱动,是目前最先进的 UI 框架 Note: 接下来会讲解 Model + View + ViewModel 的来历 <!-- page --> ### UI 的发展 1. MVC 2. MVP 3. MVVM <!-- section --> ### MVC ![MVC 示意图](https://camo.githubusercontent.com/17749aa6915f9bab027dddc91783c86ac0a2010c/68747470733a2f2f6865696d2e6966692e75696f2e6e6f2f253745747279677665722f7468656d65732f6d76632f4d56432d323030362e676966) <!-- section --> 1. 发明于1979年 2. **没有图形界面!** 3. 主要输入方式是键盘甚至纸带 Note: (讲解示意图) 比尔盖茨上大学时候,编程用的就是打孔带。 那个时候所谓的 View 就是计算结果,虽然有不同的显示方式,但和今天是完全不同的,没有抽象出来的“元件”概念,更不要提元件能够获知用户操作。 <!-- section --> ### MVP 1. 发明于 1996 年 2. 此时,图形界面取得巨大发展 3. 鼠标成为最常用的输入工具 4. 显示器可以显示更复杂的图形,开始有抽象的“元件” <!-- section --> ![MVP 示意图](https://camo.githubusercontent.com/c3dd0f9f77b116f5b5b4ce9fb82ac136a68664b3/687474703a2f2f7777322e73696e61696d672e636e2f6d773639302f34373465626633356777316570346f6b727a34716a6a32306f6d3065753430352e6a7067) <!-- section --> ### MVVM 1. 发表于 2005 年 2. 几乎都是图形界面 3. 标记语言大行其道 4. 以“双向绑定”为代表 <!-- section --> ![MVVM 示意图](https://camo.githubusercontent.com/2a09625439c430f360a770c80702f8df2c996156/687474703a2f2f7777332e73696e61696d672e636e2f6d773639302f34373465626633357477316476716e77786338746b6a2e6a7067) <!-- section --> 1. 大部分你能找到的介绍这三种模式的文章都是错的 2. 理解内在原因比较重要 3. 在服务器端编程,MVC/MVP 仍然是主流 Note: 正确的文章附在后面 <!-- page --> ### MVVM 和 jQuery 1. MVVM 由数据驱动,代表更高的抽象层次 2. 三大框架都基于 MVVM 3. MVVM 可以极大减少代码量 4. jQuery 仍然有价值,只不过大部分可用原生方法代替 <!-- page --> ## 为什么选择 Vue? Note: 这是社区里一个非常常见的问题。 <!-- section --> ### vs React React 优势: 1. 大厂背书 2. React Native React 劣势: 1. 丑陋的 JSX,反标准,反历史进程 2. 学习曲线陡峭 3. 夹带私货的黑历史 <!-- section --> ### vs Angular Angular 优势: 1. 大厂背书 2. Angular 1 曾经是事实标准 Angular 劣势 1. Angular 2 之后重写了 2. 学习曲线非常陡峭 3. TypeScript <!-- section --> ### 最终选择:Vue 1. 优秀的中文文档 2. 活跃的中文社区 3. 平缓的学习曲线 4. 富有美感的 API 设计 <!-- page --> ## Vue 的组件开发 <!-- section --> 我假定各位: 1. 看过前面几节课,清楚前端工具体系 2. 具备 Vue 基础 <!-- page --> ### 组件分类: 1. 功能组件,如播放器、幻灯片 2. 表单组件,如文件上传、日历 <!-- section --> ### 表单组件核心:`v-model` 1. 负责传入数据 2. 负责回收数据 <!-- page --> ### 渐进式升级 1. Vue 支持全局使用 2. 全局注册组件可以和 jQuery 混用 3. 不要着急,慢慢来,渐进式升级 <!-- page --> ## Coding! <!-- page --> ## 总结 1. 不再操作 DOM,只操作数据 2. 数据分为渲染用和逻辑用 3. `value` 拆成本地和外部 <!-- page --> ## 课后练习 1. 完成 RangeDatePicker 的重构 2. 把动画效果加回来 3. 使用 webpack 把所有资源放在一起 <!-- section --> 欢迎通过 PR 的方式提交作业: https://github.com/meathill-freelance/date-picker 我承诺会及时 review 代码。通过后,送 ¥100 以内的书。 <!-- page --> Q&A <!-- page --> 完整项目代码仓库: * [Github meathill-freelance/date-picker](https://github.com/meathill-freelance/date-picker) * [线上文档](https://meathill-freelance.github.io/date-picker/) <!-- page --> ## 参考阅读: <!-- section --> ### 工具篇 * [NPM](https://docs.npmjs.com/) * [Stylus](http://stylus-lang.com/) * [Babeljs](https://babeljs.io/) * [Mocha](https://mochajs.org/) * [Should.js](https://shouldjs.github.io/) * [Webpack](https://doc.webpack-china.org/) * [ESLint](http://eslint.org/) | [ESLint 中文](http://eslint.cn/docs/user-guide/configuring) <!-- section --> ### 工具使用篇 * [Using a package.json](https://docs.npmjs.com/getting-started/using-a-package.json) * [阮一峰 测试框架 Mocha 实例教程](http://www.ruanyifeng.com/blog/2015/12/a-mocha-tutorial-of-examples.html) * [Babel 设置](https://babeljs.io/docs/setup/#installation) * [Run npm scripts in a git pre-commit Hook](http://elijahmanor.com/npm-precommit-scripts/) <!-- section --> ### 知识篇 * [ES6](http://es6.ruanyifeng.com) * [Wiki ECMAScript](https://zh.wikipedia.org/wiki/ECMAScript) * [谈谈UI架构设计的演化](http://www.cnblogs.com/winter-cn/p/4285171.html) * [Vue 组件基础](https://cn.vuejs.org/v2/guide/components.html) * [Vue 单文件组件](https://cn.vuejs.org/v2/guide/single-file-components.html) <!-- section --> ### 图书篇 * [JavaScript 设计模式](https://www.amazon.cn/图书/dp/B00D6MT3LG/ref=sr_1_3?ie=UTF8&qid=1496569116&sr=8-3&keywords=javascript+设计模式) <!-- section --> ### Debug 篇 * [一个超级诡异的 iOS Safari `position: fixed` 失效问题](https://blog.meathill.com/tech/fe/css/a-super-weird-ios-safari-postion-fixed-issue.html) <file_sep>/date-picker/gulpfile.js /** * Created by meathill on 2017/6/16. */ const del = require('del'); const gulp = require('gulp'); const stylus = require('gulp-stylus'); const cleanCSS = require('gulp-clean-css'); const rename = require('gulp-rename'); const webpack = require('webpack'); const webpackStream = require('webpack-stream'); const sequence = require('run-sequence').use(gulp); const DOC = 'docs/'; gulp.task('clear', () => { return del([DOC]); }); gulp.task('stylus', () => { let toPath = DOC + 'css'; return gulp.src('./styl/tqb-date-picker.styl') .pipe(stylus()) .pipe(gulp.dest(toPath)) .pipe(rename('tqb-date-picker.min.css')) .pipe(cleanCSS({ level: 2 })) .pipe(gulp.dest(toPath)); }); gulp.task('webpack', () => { let toPath = DOC + 'js'; return gulp.src('./app/index.js') .pipe(webpackStream(require('./webpack.config.prod'), webpack)) .pipe(rename('tqb-date-picker.js')) .pipe(gulp.dest(toPath)) .pipe(rename('tqb-date-picker.min.js')) .pipe(gulp.dest(toPath)); }); gulp.task('default', callback => { sequence( 'clear', ['stylus', 'webpack'], callback ); });<file_sep>/date-picker/app/main.js /** * Created by Meathill on 2017/5/26. */ import $ from 'jquery'; import Factory from './Factory'; $('body').on('click', '.tqb-date-picker-input', event => { let target = $(event.currentTarget); let options = target.data(); let picker = options.tqbDatePicker; if (picker) { return picker.show(); } picker = Factory.createDatePicker(target, options); target.data('tqb-date-picker', picker); });<file_sep>/README.md # 实战组件开发——手机日历 ## [幻灯片地址](https://meathill-lecture.github.io/date-picker/) ## 直播间 1. [第一课:项目启动](https://segmentfault.com/l/1500000009095492) 2. [第二课:ES6与测试](https://segmentfault.com/l/1500000009212121) 3. [第三课:UI 开发与策略模式](https://segmentfault.com/l/1500000009095492) 4. [迪斯科:用 Gulp 打包发布吧!](https://segmentfault.com/l/1500000009385678) 5. [第五课:理解模块管理/制作文档/发布到NPM](https://segmentfault.com/l/1500000013760259) 开播时间:2018-04-05 20:00 6. [重构为 Vue 版本](https://segmentfault.com/l/1500000013760169) 开播时间 2018-04-30 20:00 -------- ## 内容简介 我已经在 SegmentFault 上开设四个话题,都是针对特定知识点进行讲解,我觉得是时候来场完整项目实战了!这次选择讲解开发一个主攻移动设备网页的日历选择控件,重点在于完整重现整个开发过程。学完整个课程的同学可以对现代化前端开发有更全面的理解。 现代化的前端开发不仅局限于 HTML、CSS、JavaScript,它包含很多内容,比如各种预处理工具、批处理工具、模板引擎、打包工具,还有调试、测试、版本管理、响应式、甚至文档建设等等。本系列教程会尽可能全面完整的呈现这一切。 注意,这里我用了“本系列”。是的,如此多的内容不可能放在一个课时里讲完,我会把它分成若干个课时,每次课讲解若干个知识点。我现在没有办法完全确定每次课的内容,所以我会每次更新大约两节课的内容。 因为课程内容包含完整的开发流程,所以欢迎各个级别的前端同学前来学习交流。不过最好事先对前端有所了解,能看懂 CSS 和 JavaScript。时间所限我没法逐个讲解 API 和命令。 计划分享的内容: 1. 项目启动 2. npm 工具使用 3. CSS 预处理工具 Stylus 4. CSS 动画 5. Webpack + Babel + ES6/ES2015 6. 模板 Handlebars 7. gulp 打包 8. 测试,自动化测试 10. 设计模式之策略模式 12. 利用 GitHub Pages 搭建静态网站 13. 使用 Webpack 打包到多平台 14. 重构为 Vue 组件 ## 范例代码 [./sample/](date-picker/) 每节课的代码会打相应的 tag。 [第一课](https://github.com/meathill-lecture/date-picker/tree/lesson1) ## 源项目地址 https://github.com/meathill-freelance/date-picker/ ## 协议 代码部分采用 [MIT](https://opensource.org/licenses/MIT) 进行许可。 [![知识共享许可协议](https://i.creativecommons.org/l/by/4.0/88x31.png)](http://creativecommons.org/licenses/by/4.0/) Slide 和文档部分采用 [CC4.0](http://creativecommons.org/licenses/by/4.0/) 进行许可<file_sep>/date-picker/webpack.config.js /** * Created by Meathill on 2017/5/26. */ const path = require('path'); const webpack = require('webpack'); /* global __dirname */ module.exports = { entry: { 'tqb-date-picker': './app/index.js' }, output: { filename: '[name].js', path: path.resolve(__dirname, 'dist'), library: 'tqbDatePicker', libraryTarget: 'umd', }, target: 'node', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: ['babel-loader', 'eslint-loader'] }, { test: /\.hbs$/, use: 'handlebars-loader' } ] }, externals: { 'jquery': 'jQuery' }, mode: 'development', watch: true, watchOptions: { ignored: /node_modules|dist|build|docs|css/, poll: 1000 }, plugins: [ new webpack.DefinePlugin({ DEBUG: true }) ] };<file_sep>/date-picker/test/easy-date-test.js /** * Created by Meathill on 2017/5/26. */ const should = require('should'); import EasyDate from '../app/EasyDate'; describe('EasyDate', () => { let date = new EasyDate('+1m'); describe('#new', () => { it('should create instance', () => { let some = date.toDate(); let today = new Date(); should(some.getFullYear()).aboveOrEqual(today.getFullYear()); should(some.getFullYear() - today.getFullYear()).belowOrEqual(1); if (today.getMonth() === 11) { should(some.getMonth()).equal(0); } else { should(some.getMonth() - today.getMonth()).equal(1); } }); }); });<file_sep>/date-picker/app/EasyDate.js /** * Created by Meathill on 2017/5/26. */ const METHODS = { m: 'Month', d: 'Date' }; const defaultFormat = 'yyyy-mm-dd'; export default class EasyDate { constructor(offset, options = {}) { this.format = options.format || defaultFormat; let date = EasyDate.isDate(offset, this.format); if (date) { this.base = new Date(date); return; } if (offset instanceof Date) { this.base = new Date(offset); return; } this.base = new Date(); this.base.setHours(0); this.base.setMinutes(0); this.base.setSeconds(0); this.add(offset); } add(offset) { offset = EasyDate.parse(offset); if (!offset) { return; } for (let key in offset) { if (offset.hasOwnProperty(key)) { let method = METHODS[key]; this.base[`set${method}`](this.base[`get${method}`]() + offset[key]); } } return this; } clone() { return new EasyDate(this.base, { format: this.format }); } getDay() { return this.base.getDay(); } getFirstDayOfThisMonth() { let date = this.clone(); date.setDate(1); return date.getDay(); } isSameMonth(date) { return this.base.getFullYear() === date.getFullYear() && this.base.getMonth() === date.getMonth(); } setDate(date) { this.base.setDate(date); } toDate() { return this.base; } toObject(today, start, end) { let month = this.base.getMonth(); return { year: this.base.getFullYear(), month: EasyDate.toDouble(month + 1), empty: this.getFirstDayOfThisMonth(), days: EasyDate.getDates(this.base, today, start, end, this.format) }; } toString() { return EasyDate.format(this.base, this.format); } static format(date, format) { return format .replace(/y+/gi, () => { return date.getFullYear(); }) .replace(/m+/gi, () => { return EasyDate.toDouble(date.getMonth() + 1); }) .replace(/d+/gi, () => { return EasyDate.toDouble(date.getDate()); }); } static getDates(date, today, start, end, format = defaultFormat) { let month = date.getMonth(); date = new Date(date); date.setDate(1); let dates = []; while (date.getMonth() === month) { let label = EasyDate.format(date, format); dates.push({ date: label.substr(0, 10), today: today && today.toString() === label, disabled: (start && label < start.toString()) || (end && label > end.toString()) }); date.setDate(date.getDate() + 1); } return dates; } static isDate(string, format) { format = format || defaultFormat; string = string.toString(); let pos = []; let regexps = [/d+/gi, /y+/gi, /m+/gi]; let origin = format; regexps.forEach( regexp => { format = format.replace(regexp, match => { pos.push(match.substr(0, 1)); return '(\\d{' + match.length + '})'; }); }); let regexp = new RegExp(`^${format}$`); let check = string.match(regexp); if (!check) { return check; } let result = { }; ['y', 'm', 'd'].forEach(key => { let regexp = new RegExp(`${key}+`, 'gi'); origin.replace(regexp, (match, i) => { result[key] = string.substr(i, match.length); }); }); return `${result.y}-${result.m}-${result.d}`; } static isLeapYear(year) { if (year % 100 === 0) { return year % 400 === 0; } return year % 4 === 0; } static parse(offset) { if (!offset) { return false; } offset = offset.toLowerCase(); let result = {}; offset.replace(/([+-]?\d+)([ymd])/g, (match, number, unit) => { result[unit] = Number(number); }); return result; } static toDouble(number) { return number > 9 ? number.toString() : ('0' + number); } }<file_sep>/sample/let-const-2.js /** * Created by meathill on 2017/5/25. */ console.log(a); var a = 1; console.log(a);<file_sep>/app/main.js var search = location.search; var query = {}; if (search) { search = search.substr(1); search = search.split('&'); for (var i = 0, len = search.length; i < len; i++) { var kv = search[i].split('='); if (!isNaN(kv[1])) { kv[1] = Number(kv[1]); } if (/^true|false$/i.test(kv[1])) { kv[1] = Boolean(kv[1]); } query[kv[0]] = kv[1]; } } Reveal.initialize({ history: true, controls: 'controls' in query ? query.controls : true, transition: query.transition || 'slide', dependencies: [ { src: './node_modules/marked/marked.min.js', condition: function () { return !!document.querySelector('[data-markdown]'); } }, { src: './node_modules/reveal.js/plugin/markdown/markdown.js', condition: function () { return !!document.querySelector('[data-markdown]'); } }, { src: './node_modules/reveal.js/plugin/highlight/highlight.js', async: true, callback: function () { hljs.initHighlightingOnLoad(); } } ] }); if (query.print) { var link = document.createElement( 'link' ); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = './node_modules/reveal.js/css/print/pdf.css'; document.getElementsByTagName( 'head' )[0].appendChild( link ); }
e3dab9abd3e6a4d280503f5360b537dade24e35c
[ "JavaScript", "Markdown" ]
13
JavaScript
meathill-lecture/date-picker
4d51ea8031c3a3cb6cfec5f7e70b5de6da5a405a
38344193b730759d4fc0a089944e3eda8d0ee4a5
refs/heads/master
<repo_name>kontained/box<file_sep>/Photobox/Photobox/Photobox.cs 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; using Emgu.CV; using Emgu.CV.Structure; using Emgu.Util; namespace Photobox { public partial class Photobox : Form { private Capture Frame = null; public Photobox() { InitializeComponent(); try { //initialize the camera Frame = new Capture(); //Frame.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, 1080); //Frame.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, 1920); //set the event handler Frame.ImageGrabbed += ProcessFrame; //start the stream Frame.Start(); } catch { MessageBox.Show("Error Creating Stream!"); } } private void ProcessFrame(object sender, EventArgs arg) { Image<Bgr, Byte> ImageFrame = Frame.RetrieveBgrFrame(); camPreview.Image = ImageFrame; } //saves the photo when the picture is clicked. private void camPreview_Click(object sender, EventArgs e) { Image<Bgr, Byte> ImageFrame = Frame.QueryFrame(); ImageFrame.Save("Photos\\.png"); } private void ReleaseData() { if (Frame != null) { Frame.Dispose(); } } } }
229a33650602e7e4f8268132f9be489b365ea17d
[ "C#" ]
1
C#
kontained/box
9eff5e3b4724a2a43f967e87845f60b62702dc8a
1deb07efa6453887e6bfc2481c1f923b0d36c153
refs/heads/master
<repo_name>hamishgibbs/Baidu_Web_Scraping<file_sep>/Ajax_Intercept #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 10 11:47:09 2020 @author: hamishgibbs """ from selenium import webdriver import time import bs4 as BeautifulSoup from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.options import Options import pandas as pd import os import datetime from multiprocessing import Pool from itertools import compress import numpy as np from selenium.webdriver.common.desired_capabilities import DesiredCapabilities #%% caps = DesiredCapabilities.CHROME caps['loggingPrefs'] = {'performance': 'ALL'} driver = webdriver.Chrome(desired_capabilities=caps) driver.get('https://stackoverflow.com/questions/52633697/selenium-python-how-to-capture-network-traffics-response') try: browser_log = driver.get_log('browser') driver.quit() except Exception as e: print(e) driver.quit() #%% def process_browser_log_entry(entry): response = json.loads(entry['message'])['message'] return response #%%<file_sep>/Ajax_Intercept.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 10 11:47:09 2020 @author: hamishgibbs """ from selenium import webdriver import time import bs4 as BeautifulSoup from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.options import Options import pandas as pd import os import datetime from multiprocessing import Pool from itertools import compress import numpy as np from browsermobproxy import Server from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import json from haralyzer import HarParser, HarPage #%% caps = DesiredCapabilities.CHROME caps['loggingPrefs'] = {'performance': 'ALL'} driver = webdriver.Chrome(desired_capabilities=caps) driver.get('https://stackoverflow.com/questions/52633697/selenium-python-how-to-capture-network-traffics-response') try: browser_log = driver.get_log('browser') driver.quit() except Exception as e: print(e) driver.quit() #%% def process_browser_log_entry(entry): response = json.loads(entry['message'])['message'] return response #%% ''' try to save HAR file - select all options on the site, then save HAR file, parse massive json response write everything into a bot class ''' server = Server("/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Baidu_Web_Scraping/browsermob-proxy-2.1.4/bin/browsermob-proxy", options={'port': 8090}) server.start() proxy = server.create_proxy() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--proxy-server={}".format(proxy.proxy)) driver = webdriver.Chrome(options=chrome_options) proxy.new_har("myhar") with open('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Request_Intercept/myhar.har', 'w') as har_file: json.dump(proxy.har, har_file) driver.get('https://sgwuhan.xose.net/') time.sleep(10) ok_btn = driver.find_element_by_xpath('//*[@id="okBtn"]') ok_btn.click() time.sleep(5) server.stop() driver.quit() #%% executable_path = '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Baidu_Web_Scraping/chromedriver' #initialize web driver driver = webdriver.Chrome(executable_path = executable_path) url = 'https://qianxi.baidu.com/' #let page load driver.get(url) time.sleep(10) #define buttons that are constant no matter the layout of the site city_name_drop_down = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[1]/div/div') date_drop_down = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[2]/div/div/div') incoming_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[3]/div/div[1]') outgoing_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[3]/div/div[2]') for i in range(0, len(city_name_xpaths)): city_xpath = city_name_xpaths[i] city_name_drop_down.click() time.sleep(0.5) try: city_button = driver.find_element_by_xpath(city_xpath) city_button.click() outgoing_button.click() time.sleep(0.5) incoming_button.click() time.sleep(0.5) for a in range(0, len(date_name_xpaths), 1): incoming_button.click() date_xpath = date_name_xpaths[a] date_drop_down.click() time.sleep(0.5) date_button = driver.find_element_by_xpath(date_xpath) date_button_soup = BeautifulSoup.BeautifulSoup(date_button.get_attribute('innerHTML'), 'html.parser') date_button_text = date_button_soup.getText().replace('-', '_') date_button.click() short_wait() city_panel_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[4]/div[1]/div/div[1]') province_panel_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[4]/div[1]/div/div[2]') #get city data province_panel_button.click() time.sleep(0.5) #get province data outgoing_button.click() time.sleep(0.5) #get province data province_panel_button.click() time.sleep(0.5) #get city data city_panel_button.click() time.sleep(0.5) except Exception as e: city_name_drop_down.click() print(e) #%% ''' Parse .har file ''' with open('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Request_Intercept/qianxi.baidu.com.har', 'r') as f: har_page = json.loads(f.read()) #%% hot_city_index = [] line_data_index = [] city_data_index = [] prov_data_index = [] for i, log_entry in enumerate(har_page['log']['entries']): #get hot city #get line data #get panel data #search for hot_city if str(log_entry).find('cen&b') > 0: hot_city_index.append(i) #line_data if str(log_entry).find('historycurve') > 0: line_data_index.append(i) #panel_data if str(log_entry).find('cityrank') > 0: city_data_index.append(i) if str(log_entry).find('provincerank') > 0: prov_data_index.append(i) print(len(str(log_entry))) #%% ''' to scrape panel data ''' panel_data = har_page['log']['entries'][panel_data_index[0]]['response']['content']['text'] first_parenth = panel_data.find('(') panel_data = panel_data[first_parenth+1:] panel_data = panel_data.replace(')', '') panel_data=json.loads(panel_data)['data']['list'] panel_df = pd.DataFrame(panel_data) print(panel_df) #%% ''' to scrape line data ''' line_data = har_page['log']['entries'][line_data_index[0]]['response']['content']['text'] first_parenth = line_data.find('(') line_data = line_data[first_parenth+1:] line_data = line_data.replace(')', '') line_data=json.loads(line_data)['data']['list'] line_df = pd.DataFrame(list(line_data.items())) print(line_df) #%% ''' to scrape hot city datan - looks like you get hot city info before each item ''' hc_data = har_page['log']['entries'][hot_city_index[0]]['response']['content']['text'] first_parenth = hc_data.find('(') hc_data = hc_data[first_parenth+1:] hc_data = hc_data.replace(')', '') hc_data=json.loads(hc_data)['current_city'] print(hc_data) #%% for i, log_entry in enumerate(har_page['log']['entries']): fn = '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Request_Intercept/data_download_test/' + str(i) + '.csv' #panel_data try: if str(log_entry).find('cityrank') > 0: panel_data = har_page['log']['entries'][i]['response']['content']['text'] first_parenth = panel_data.find('(') panel_data = panel_data[first_parenth+1:] panel_data = panel_data.replace(')', '') panel_data=json.loads(panel_data)['data']['list'] panel_df = pd.DataFrame(panel_data) panel_df.to_csv(fn) except Exception as e: print('city') print(har_page['log']['entries'][i]['response']['content']['text']) print(e) #panel_data try: if str(log_entry).find('provincerank') > 0: panel_data = har_page['log']['entries'][i]['response']['content']['text'] first_parenth = panel_data.find('(') panel_data = panel_data[first_parenth+1:] panel_data = panel_data.replace(')', '') panel_data=json.loads(panel_data)['data']['list'] panel_df = pd.DataFrame(panel_data) panel_df.to_csv(fn) except Exception as e: print('province') print(har_page['log']['entries'][i]['response']['content']['text']) print(e) #line_data try: if str(log_entry).find('historycurve') > 0: line_data = har_page['log']['entries'][i]['response']['content']['text'] first_parenth = line_data.find('(') line_data = line_data[first_parenth+1:] line_data = line_data.replace(')', '') line_data=json.loads(line_data)['data']['list'] line_df = pd.DataFrame(list(line_data.items())) line_df.to_csv(fn) except Exception as e: print('line') print(e) #search for hot_city try: #panel_data if str(log_entry).find('cen&b') > 0: hc_data = har_page['log']['entries'][i]['response']['content']['text'] first_parenth = hc_data.find('(') hc_data = hc_data[first_parenth+1:] hc_data = hc_data.replace(')', '') hc_data=json.loads(hc_data)['current_city'] hc_df = pd.DataFrame(list(hc_data.items())) hc_df.to_csv(fn) except Exception as e: print('hc') print(e) #%% def text_to_json(text): first_parenth = text.find('(') text = text[first_parenth+1:] text = text.replace(')', '') json_data=json.loads(text)['data']['list'] return(json_data) #%% ''' then: work sequentially- when encounter a hot city - make that data the new data - then parse panels and liens as approppriate -looks like you get a hot city df before each data file? - this would make things very easy ''' #%% #to_get_panel data har_page['log']['entries'][panel_data_index[0]]['response']['content']['text'] #%% #%% #for every city - name dropdown click #for lines #incoming #outgoing #for every date- #click incoming_button #city #province #click outgoing button #city #province ''' har structure - hot city line data in line data out panel in: city province panel out: city province next city ''' #haralyzer #idea - #click through every option, download one har file manually with chrome #use python to parse the har - for active city/ lines data etc.<file_sep>/rds_to_csv.R data = read_rds('/Users/hamishgibbs/Dropbox/nCov-2019/data_sources/mobility_data/china_prf_connectivity.rds') data connect = read_rds('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Connectivity/connectivity_draft.rds') connect image(connect) matrix(connect) connect %>% select(-date, -from) image(matrix(connect$`110100`)) image(matrix(connect[,3:length(connect)])) image(as.matrix(connect[,3:length(connect)]), col=rainbow(100)) rainbow(100) shp = read_rds('/Users/hamishgibbs/Dropbox/nCov-2019/data_sources/demographic_data/shp_pop.rds') shp = as_tibble(shp) %>% select(-geometry) shp write_csv(shp, '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Unique_URLs/shp_pop.csv') <file_sep>/json_to_geojson.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 10 09:49:24 2020 @author: hamishgibbs """ import json from geojson import Point, Feature, FeatureCollection, dump #%% path = '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/' in_fn = 'singapore_data.json' out_fn = 'singapore_data.geojson' raw = open(path + in_fn).read() #for UTF-8 encoded chinese characters: #else: json_data = json.loads(raw) features = [] for i, feature in enumerate(json_data['data']): try: point = Point((float(feature['lng']), float(feature['lat']))) feature = Feature(geometry=point, properties=feature) features.append(feature) except Exception as e: print(e) #%% with open(path + out_fn, 'w') as f: dump(FeatureCollection(features), f) <file_sep>/Network_Image.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 11 10:54:50 2020 @author: hamishgibbs """ import rpy2.robjects as robjects from rpy2.robjects import pandas2ri pandas2ri.activate() readRDS = robjects.r['readRDS'] df = readRDS('/Users/hamishgibbs/Dropbox/nCov-2019/data_sources/mobility_data/china_prf_connectivity.rds') df = pandas2ri.ri2py(df) #%% <file_sep>/average_travel.R pop = read_rds('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Connectivity/shp_pop.rds') pop data = read_rds('/Users/hamishgibbs/Dropbox/nCov-2019/data_sources/mobility_data/china_prf_connectivity.rds') data wuhan_code = as.character(pop[pop$PYNAME == 'Wuhan Shi', 'CNTY_CODE'])[1] for (i in 1:length(data$date)){ current_date = data$date[i] date_data = data[data$date == current_date,'data'][[1]][[1]] if (i == 1){ date_destinations = as.tibble(date_data[wuhan_code,]) %>% mutate(date = current_date) %>% mutate(location = colnames(date_data)) } else { dd_tmp = as.tibble(date_data[wuhan_code,]) %>% mutate(date = current_date) %>% mutate(location = colnames(date_data)) date_destinations = rbind(date_destinations, dd_tmp) } } average_flow = date_destinations %>% group_by(location) %>% summarize(average_flow = mean(value, na.rm=TRUE)) average_flow plot(average_flow$average_flow) <file_sep>/README.md # Baidu_Web_Scraping Scraping Baidu Web Mapping App: https://qianxi.baidu.com/ <file_sep>/Scrape.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 30 22:23:41 2020 @author: hamishgibbs """ from selenium import webdriver import time import bs4 as BeautifulSoup from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.chrome.options import Options import pandas as pd import os import datetime from multiprocessing import Pool from itertools import compress import numpy as np chrome_options = Options() chrome_options.add_argument("--headless") #%% ''' Script Overview: Web scraping of Baidu movement interactive web map Outputs: Line chart data outgoing/incoming for every date: Top destination/arrival details city & provincial ''' #helper functions to wait different periods def very_short_wait(): time.sleep(0.0000001) def short_wait(): time.sleep(1.5) def long_wait(): time.sleep(10) #function to return xpath of element identified in beautiful soup def xpath_soup(element): components = [] child = element if element.name else element.parent for parent in child.parents: siblings = parent.find_all(child.name, recursive=False) components.append( child.name if 1 == len(siblings) else '%s[%d]' % ( child.name, next(i for i, s in enumerate(siblings, 1) if s is child) ) ) child = parent components.reverse() return '/%s' % '/'.join(components) #function to scrape the data of the active side panel def scrape_panel_data(driver): panel_final_data = [] full_page_soup = BeautifulSoup.BeautifulSoup(driver.page_source, 'html.parser') panel_container = full_page_soup.find_all('div', attrs={'class': 'mgs-list'}) panel_data = panel_container[0].find_all('tr') for item in panel_data: item_data = item.find_all('td') if len(item_data) == 3: panel_final_data.append({'rank':item_data[0].getText(), 'place':item_data[1].getText(), 'percent':item_data[2].getText()}) panel_df = pd.DataFrame(panel_final_data) return(panel_df) def scrape_line_graph(driver): line_chart = driver.find_element_by_xpath('//*[@id="content"]/div/div[5]') line_chart_data = [] #chart data only appears one value at a time - hover over every item in the chart and get its value #hover over chart starting from left to 700 pixels R (steps of 20 px) #This offset is in relation to default chrome window - changing window/monitor size will result in incorrect data for xoffset in range(0, 700, 7): hover = ActionChains(driver).move_to_element_with_offset(line_chart, xoffset=xoffset, yoffset=150) hover.perform() time.sleep(0.001) #get the container holding the current data of the hovered point current_line_data_container = driver.find_element_by_xpath('//*[@id="content"]/div/div[5]/div[1]/div[2]') #extract value and date from hovered point line_data_soup = BeautifulSoup.BeautifulSoup(current_line_data_container.get_attribute('outerHTML'), 'html.parser') line_value_soup = line_data_soup.find_all('div') for line in line_value_soup: #try catch for any hovered points without data try: line = line.getText() text_location_2020 = line.find('今年迁徙规模指数: ') text_location_2019 = line.find('去年迁徙规模指数: ') #see if there is a 2020 data value: if text_location_2020 > 0: #if there is a 2020 value: extract date, 2020 value and 2019 value line_date = line[: text_location_2020] data_2020 = line[text_location_2020:text_location_2019] data_2019 = line[text_location_2019:] data_2020_value = data_2020.split(': ')[1] data_2019_value = data_2019.split(': ')[1] else: #if there is no 2020 value, extract date and 2019 value line_date = line[: text_location_2019] data_2019 = line[text_location_2019:] data_2020_value = '' data_2019_value = data_2019.split(': ')[1] except: continue line_chart_data.append({'date':line_date, '2019':data_2019_value, '2020':data_2020_value}) #reconcile numeric dates with chinese dates (recorded) td = (datetime.date.today() + datetime.timedelta(days=8)) - datetime.date(2020, 1, 1) line_date_labels = [] #correctly format numeric dates - this will error with leap year? for i in range(td.days + 1): line_date_label = str(datetime.date(2020, 1, 1) + datetime.timedelta(days=i)) line_date_label = line_date_label[5:] line_date_label = line_date_label.replace('-', '_') line_date_labels.append(line_date_label) #try to create dataframe from line date - if there is no data - return none try: line_df = pd.DataFrame(line_chart_data) line_df.drop_duplicates(inplace=True) line_df.reset_index(inplace=True) #correct an error where the last selected record becomes the first if the function used in succession if line_df.loc[0, '2020'] == '': line_df = line_df.drop(0, axis=0) line_df['date'] = line_date_labels line_df.reset_index(inplace=True) line_df = line_df.filter(['date', '2019', '2020']) return(line_df) except Exception as e: print(e) return(None) def scrape_both_line_charts(i): url = 'https://qianxi.baidu.com/' city_xpath = city_name_xpaths[i] #initialize web driver driver = webdriver.Chrome(executable_path = executable_path, chrome_options=chrome_options) #let page load driver.get(url) short_wait() #define buttons that are constant no matter the layout of the site city_name_drop_down = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[1]/div/div') incoming_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[3]/div/div[1]') outgoing_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[3]/div/div[2]') #click on city dropdown city_name_drop_down.click() short_wait() try: city_button = driver.find_element_by_xpath(city_xpath) city_button.click() short_wait() #make a directory with the city name current_download_directory = download_directory_all + city_names[i] os.mkdir(current_download_directory) outgoing_button.click() #line charts do not change for different date values #scrape outgoing line chart line_df = scrape_line_graph(driver) write_csv(line_df, current_download_directory + '/' + city_names[i] + '_line_outgoing.csv') incoming_button.click() short_wait() #scrape incoming line chart line_df = scrape_line_graph(driver) write_csv(line_df, current_download_directory + '/' + city_names[i] + '_line_incoming.csv') short_wait() driver.quit() except Exception as e: print(e) driver.quit() def scrape_panels(i, select_date_button_index = None): city_xpath = city_name_xpaths[i] #initialize web driver driver = webdriver.Chrome(executable_path = executable_path, chrome_options=chrome_options) #let page load driver.get(url) short_wait() #define buttons that are constant no matter the layout of the site city_name_drop_down = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[1]/div/div') date_drop_down = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[2]/div/div/div') incoming_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[3]/div/div[1]') outgoing_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[2]/div[3]/div/div[2]') #click on city dropdown city_name_drop_down.click() short_wait() #scrape for a subset of dates or all dates - date button index is the index of the date buttons to use (date names don't match up) if select_date_button_index == None: select_date_button_index = range(0, len(date_name_xpaths), 1) else: select_date_button_index = select_date_button_index city_button = driver.find_element_by_xpath(city_xpath) city_button.click() short_wait() #load data into existing directories (where lines have already been scraped) current_download_directory = download_directory_all + city_names[i] try: outgoing_button.click() for a in select_date_button_index: date_xpath = date_name_xpaths[a] date_drop_down.click() short_wait() #click on new date date_button = driver.find_element_by_xpath(date_xpath) date_button_soup = BeautifulSoup.BeautifulSoup(date_button.get_attribute('innerHTML'), 'html.parser') date_button_text = date_button_soup.getText().replace('-', '_') #make a directory for each date current_date_download_directory = current_download_directory + '/' + city_names[i] + '_' + date_button_text os.mkdir(current_date_download_directory) date_button.click() short_wait() city_panel_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[4]/div[1]/div/div[1]') province_panel_button = driver.find_element_by_xpath('//*[@id="content"]/div/div[4]/div[1]/div/div[2]') #parse outgoing cities panel panel_df = scrape_panel_data(driver) panel_df.to_csv(current_date_download_directory + '/' + city_names[i] + '_' + date_button_text + '_cities_outgoing.csv') #activate provinces panel province_panel_button.click() short_wait() #parse outgoing provinces panel panel_df = scrape_panel_data(driver) panel_df.to_csv(current_date_download_directory + '/' + city_names[i] + '_' + date_button_text + '_provinces_outgoing.csv') #reset cities panel city_panel_button.click() short_wait() #change to incoming trips incoming_button.click() short_wait() #parse incoming cities data panel_df = scrape_panel_data(driver) panel_df.to_csv(current_date_download_directory + '/' + city_names[i] + '_' + date_button_text + '_cities_incoming.csv') #activate provinces panel province_panel_button.click() short_wait() #parse incoming provinces panel_df = scrape_panel_data(driver) panel_df.to_csv(current_date_download_directory + '/' + city_names[i] + '_' + date_button_text + '_provinces_incoming.csv') #reset to cities panel city_panel_button.click() short_wait() #reset to outgoing for next date outgoing_button.click() short_wait() driver.quit() except Exception as e: print(e) driver.quit() def write_csv(df, file_name): if df is not None: df.to_csv(file_name) #%% ''' Initial website parse to extract static elements ''' #remember to install correct version of chrome driver executable (open chrome and inspect version) executable_path = '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Baidu_Web_Scraping/chromedriver' #url to be scraped url = 'https://qianxi.baidu.com/' #initialize web driver - not using a headless web browser to continue to monitor progress driver = webdriver.Chrome(executable_path = executable_path, chrome_options=chrome_options) #let page load driver.get(url) short_wait() #extract all html of page soup = BeautifulSoup.BeautifulSoup(driver.page_source, 'html.parser') driver.quit() #%% #get text and xpath of city name and dates stored in main dropdown lists city_name_elements = soup.find_all('a', attrs={'class': 'sel_city_name'}) city_name_xpaths = [xpath_soup(i) for i in city_name_elements] city_names = [i.getText() for i in city_name_elements] date_name_container = soup.find_all('ul', attrs={'class': 'hui-option-list'}) date_name_elements = date_name_container[0].find_all('li') date_name_xpaths = [xpath_soup(i) for i in date_name_elements] date_name_xpaths.reverse() date_names = [i.getText() for i in date_name_elements] date_names.reverse() date_names_sub = [i.replace('-', '_') for i in date_names] #%% ''' Using data from initial scrape, conduct full, systematic web scrape ''' download_directory_all = '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Scraped_Data/' #scrape line charts and then panels for each city city_index = list(range(0, len(city_name_xpaths), 1)) #%% ''' responding to error 10-02-2020: only scrape line names that haven't been scraped ''' scraped_names = os.listdir('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Scraped_Data') not_scraped_names = [city not in scraped_names for city in city_names] not_scraped_names_names = list(compress(city_names, not_scraped_names)) #%% not_scraped_names = list(np.where(not_scraped_names)[0]) #%% with Pool(3) as p: p.map(scrape_both_line_charts, not_scraped_names)#city_index) #%% with Pool(3) as p: p.map(scrape_panels, city_index) #%% #%% select_date_button_index = [29, 22, 15, 8] ''' intercept AJAX with line data write update to scrape only those dates that haven't been scraped ''' <file_sep>/request_urls.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Feb 11 14:58:39 2020 @author: hamishgibbs """ import pandas as pd import requests import json import os from datetime import datetime from datetime import timedelta #%% def daterange(date1, date2): for n in range(int ((date2 - date1).days)+1): yield date1 + timedelta(n) def create_request_url(datatype, geocode, date, direction='move_out'): ''' Parameters ---------- datatype : TYPE DESCRIPTION. geocode : TYPE DESCRIPTION. date : TYPE DESCRIPTION. direction : TYPE, optional DESCRIPTION. The default is 'move_out'. Returns ------- None. ''' return('https://huiyan.baidu.com/migration/' + datatype + '.jsonp?dt=city&id=' + str(geocode) + '&type=' + direction + '&date=' + str(date)) def text_to_df(text, data_type): ''' Parameters ---------- text : TYPE DESCRIPTION. Returns ------- None. ''' first_parenth = text.find('(') text = text[first_parenth+1:] text = text.replace(')', '') json_data = json.loads(text) if data_type in ['historycurve', 'internalflowhistory']: df = pd.DataFrame(list(json_data['data']['list'].items())) df.rename({0:'date', 1:'value'}, axis=1, inplace=True) if data_type in ['cityrank', 'provincerank']: df = pd.DataFrame(json_data['data']['list']) return(df) def make_filename(datatype, geocode, date, direction='move_out'): ''' Parameters ---------- datatype : TYPE DESCRIPTION. geocode : TYPE DESCRIPTION. date : TYPE DESCRIPTION. direction : TYPE, optional DESCRIPTION. The default is 'move_out'. Returns ------- None. ''' fn = '/' + str(geocode) + '_' + str(date) + '_' + direction + '_' + datatype + '.csv' return(fn) def scrape(datatype, geocode, date, direction='move_out'): ''' Returns ------- None. ''' url = create_request_url(datatype, geocode, date, direction) r = requests.get(url) try: data = text_to_df(r.text, data_type=datatype) fn = make_filename(datatype, geocode, date, direction) return(data, fn) except Exception as e: print(e) #%% geocodes = pd.read_csv('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Unique_URLs/shp_pop.csv') geocodes = list(geocodes['CNTY_CODE']) start_date = datetime.strptime('2020-01-01', '%Y-%M-%d') today = datetime.today() dates = [] for dt in [dt for dt in daterange(start_date, today)]: day = str(dt.day) month = str(dt.month) year = str(dt.year) if(len(day) == 1): day = '0' + day else: day = day if(len(month) == 1): month = '0' + month else: month = month dates.append(year + month + day) #%% data_types = ['cityrank', 'provincerank', 'historycurve', 'internalflowhistory'] #%% download_directory_all = '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Scraped_Data' for geocode in geocodes: try: current_download_directory = download_directory_all + '/' + str(geocode) os.mkdir(current_download_directory) except Exception as e: print(e, 'Cannot make download directory for ' + str(geocode)) pass try: s = scrape('historycurve', geocode, dates[0], 'move_out') s[0].to_csv(current_download_directory + s[1]) except Exception as e: print(e, 'No historycurve out for ' + str(geocode)) pass try: s = scrape('historycurve', geocode, dates[0], 'move_in') s[0].to_csv(current_download_directory + s[1]) except Exception as e: print(e, 'No historycurve in for ' + str(geocode)) pass try: s = scrape('internalflowhistory', geocode, dates[0], 'move_out') s[0].to_csv(current_download_directory + s[1]) except Exception as e: print(e, 'No internalflowhistory for ' + str(geocode)) pass for date in dates: try: date_directory = current_download_directory + '/' + str(date) os.mkdir(date_directory) except Exception as e: print(e, 'Cannot make date directory for ' + str(geocode)) pass try: s = scrape('cityrank', geocode, date, 'move_out') s[0].to_csv(date_directory + s[1]) except Exception as e: print(e, 'No cityrank out for ' + str(geocode)) pass try: s = scrape('provincerank', geocode, date, 'move_out') s[0].to_csv(date_directory + s[1]) except Exception as e: print(e, 'No provincerank out for ' + str(geocode)) pass try: s = scrape('cityrank', geocode, date, 'move_in') s[0].to_csv(date_directory + s[1]) except Exception as e: print(e, 'No cityrank in for ' + str(geocode)) pass try: s = scrape('provincerank', geocode, date, 'move_in') s[0].to_csv(date_directory + s[1]) except Exception as e: print(e, 'No provincerank in for ' + str(geocode)) pass #%% #test s = scrape('internalflowhistory', geocodes[0], dates[0], 'move_out') #%% url = create_request_url('internalflowhistory', geocodes[0], dates[0], 'move_out') r = requests.get(url) #%% ''' can you get more cities than they have on the site? start_city ''' partial = [350300, 350500, 371200, 610400, 650100, 652300] <file_sep>/Singapore_Extra_Geocode.R pacman::p_load(jsonlite, tidyverse, dplyr, geojsonio, leaflet, rgdal, broom, sf, viridis) extra_geo <- st_as_sf(geojson_read("/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_additional_geodata.geojson", what = "sp")) leaflet(sf) %>% addProviderTiles(providers$CartoDB.Positron) %>% addCircleMarkers(radius=4, color = ~pal(caseNo), stroke = FALSE, fillOpacity = 1, popup = paste("Case ID", sf$caseNo, "<br>", "Text Address:", sf$text_orig, "<br>", "Visit Type:", sf$type, "<br>"), clusterOptions = markerClusterOptions()) sing = st_as_sf(geojson_read('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_data_id.geojson', what = "sp")) sing pal <- colorNumeric( palette = "YlGnBu", domain = sing$case_id ) leaflet(sing) %>% addProviderTiles(providers$CartoDB.Positron) %>% addCircleMarkers(radius=4, color = ~pal(case_id), stroke = 1, fillOpacity = 0, popup = paste("Case ID", sing$case_id, "<br>", "Age:", sing$age, "<br>", "Gender:", sing$gender, "<br>", "From:", sing$from, "<br>", "Citizenship:", sing$citizenship, "<br>")) %>% addCircleMarkers(lng = st_coordinates(extra_geo)[,1], lat = st_coordinates(extra_geo)[,2], radius=4, color = ~pal(extra_geo$caseNo), stroke = FALSE, fillOpacity = 1, popup = paste("Case ID", extra_geo$caseNo, "<br>", "Text Address:", extra_geo$text_orig, "<br>", "Visit Type:", extra_geo$type, "<br>"), markerClusterOptions()) #make boundig boxes around extant of each traveller extra_geo_id = extra_geo %>% rename(case_id = caseNo) %>% select(case_id) sing_id = sing %>% select(case_id) combined_geo = rbind(sing_id, extra_geo_id) unique_ids = unique(combined_geo$case_id) i = 1 for (id in unique_ids){ filtered = combined_geo %>% filter(case_id == id) if (i == 1){ bbox_df = tibble(id=id, geometry=st_as_sfc(st_bbox(filtered$geometry))) }else{ bbox_df = rbind(bbox_df, tibble(id=id, geometry=st_as_sfc(st_bbox(filtered$geometry)))) } i = i + 1 } bbox_df = st_sf(case_id = bbox_df$id, geometry=bbox_df$geometry) bbox_df %>% ggplot() + geom_sf() leaflet(bbox_df) %>% addProviderTiles(providers$CartoDB.Positron) %>% addPolygons(color = "#444444", weight = 1, smoothFactor = 0.5, opacity = 1.0, fillOpacity = 0.5, fillColor = ~pal(case_id)) <file_sep>/json_to_geojson.R pacman::p_load(jsonlite, tidyverse, dplyr, geojsonio, leaflet, geojson_sf, rgdal, broom, sf) data = read_json('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_data.json') data geojson_list(data) file_to_geojson('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_data.json') geojson_json(data) geojson_json(data, lat = 'lat', lon = 'lng') cbndata = read_rds('/Users/hamishgibbs/Dropbox/nCov-2019/data_sources/case_data/CBNDATA_Scrape/cbndata_features.rds') cbndata %>% leaflet() %>% addTiles() %>% addCircleMarkers(radius=2, color = 'k', stroke = FALSE, fillOpacity = 1) leaflet(data = quakes[1:4,]) %>% addTiles() %>% addMarkers(~long, ~lat, icon = greenLeafIcon) cd_json = geojson_json(case_data) write_json(cd_json, '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/CDNDATA/case_data.geojson') st_write(case_data, '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/CDNDATA/cbndata_features.shp') geojson_sf('/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_data.geojson') sf <- geojson_sf(system.file("/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_data.geojson", package = "geojsonsf")) spdf <- geojson_read("/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_data.geojson", what = "sp") spdf sf = st_as_sf(spdf) sf %>% ggplot() + geom_sf() write_rds(sf, '/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_data.rds') sing = read_rds('/Users/hamishgibbs/Dropbox/nCov-2019/data_sources/case_data/Singapore_Scrape/singapore_data.rds') sing$visited <file_sep>/Geocode_Singapore.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 10 13:40:17 2020 @author: hamishgibbs """ import json import geopandas as gpd import geocoder import geopy import shapely import time #%% sing = gpd.read_file("/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_data.geojson") print(list(sing)) #%% sing['case_id'] = range(1, len(sing['stayed'])+1) #%% stayed_data = [] locator = geopy.Nominatim(user_agent="myGeocoder", timeout=30) prohib = ['Singapore'] for a, case_num in enumerate(sing['case_id']): stayed = sing.loc[a, 'stayed'] try: if stayed != '' and stayed not in prohib: location = locator.geocode(stayed + ", Singapore") stayed_data.append({'caseNo':case_num, 'text_orig':stayed, 'point':shapely.geometry.Point((location.longitude, location.latitude)), 'type':'stayed'}) print(stayed) except Exception as e: print(e) continue #%% print(stayed_data) #%% visited_data = [] prohib = ['China', 'Wuhan', 'Malaysia', 'Singapore', 'GP Clinic', 'No info by MOH', 'Jewel'] locator = geopy.Nominatim(user_agent="myGeocoder", timeout=30) for a, case_num in enumerate(sing['case_id']): visited = sing.loc[a, 'visited'] visited = visited.split(', ') for text in visited: if text != '' and text not in prohib: print(text) location = locator.geocode(text + ", Singapore") try: visited_data.append({'caseNo':case_num, 'text_orig':text, 'point':shapely.geometry.Point((location.longitude, location.latitude)), 'type':'visited'}) except Exception as e: print(e) continue #%% print(visited_data) #shiny quick plot all_confirmed_prf #%% visited_gpd = gpd.GeoDataFrame(pd.DataFrame(visited_data), geometry = 'point') stayed_gpd = gpd.GeoDataFrame(pd.DataFrame(stayed_data), geometry = 'point') all_gpd = pd.merge(visited_gpd, stayed_gpd, on=list(visited_gpd), how='outer') #%% all_gpd.to_file("/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_additional_geodata.geojson", driver='GeoJSON') sing.to_file("/Users/hamishgibbs/Documents/nCOV-2019/Web_Scraping/Singapore_Data/singapore_data_id.geojson", driver='GeoJSON')
b31a385c35adea0bdf7003ea29a3ca757c604149
[ "Markdown", "Python", "R" ]
12
Python
hamishgibbs/Baidu_Web_Scraping
7d3a8678024dd8b053643c884f600fecefa22d9a
4ace21658dd92fcf160911849998accd723d48e2
refs/heads/master
<file_sep>package com.yhkim.springsecuritypractice.config; import com.yhkim.springsecuritypractice.filter.JwtAuthenticationFilter; import com.yhkim.springsecuritypractice.provider.JwtTokenProvider; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { private final JwtTokenProvider jwtTokenProvider; @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity .httpBasic().disable() .csrf().disable(); httpSecurity .authorizeRequests() .antMatchers("/account/login").anonymous() .anyRequest().authenticated() .and() .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class); } } <file_sep>create table if not exists account ( uuid varchar(100) not null primary key, kakao_id int not null, kakao_nickname varchar(100) not null, kakao_email varchar(100) null, kakao_profile_image text not null ); create table if not exists area ( id int auto_increment primary key, sido varchar(50) not null, sigungu varchar(50) not null, map_x double not null, map_y double not null ); create table if not exists bike_road ( uuid varchar(100) not null primary key, name varchar(100) not null, images text not null, address varchar(100) not null, map_x double not null, map_y double not null, dong varchar(100) not null, description text not null, gpx varchar(100) null ); create table if not exists bike_road_bookmark_relation ( id int auto_increment primary key, bookmark varchar(100) not null, bikeroad_uuid varchar(100) not null ); create table if not exists course ( uuid varchar(100) not null primary key, name varchar(100) not null, dong varchar(100) not null, map_x double not null, map_y double not null, first_place_id int null, first_image varchar(100) null, first_name varchar(100) null, first_tag varchar(100) null, first_map_x double null, first_map_y double null, second_place_id int null, second_image varchar(100) null, second_name varchar(100) null, second_tag varchar(100) null, second_map_x double null, second_map_y double null, third_place_id int null, third_image varchar(100) null, third_name varchar(100) null, third_tag varchar(100) null, third_map_x double null, third_map_y double null, bikeroad varchar(100) not null ); create table if not exists bookmark ( uuid varchar(100) not null primary key, owner varchar(100) not null, name varchar(100) not null, image text null ); create table if not exists course_relation ( uuid varchar(100) not null primary key, course varchar(100) not null, place varchar(100) not null ); create table if not exists place_bookmark_relation ( id int auto_increment primary key, bookmark varchar(100) not null, place_id int not null, image text null, name varchar(100) not null, map_x double not null, map_y double not null, tag varchar(100) not null ); create table if not exists token ( uuid varchar(100) not null primary key, account varchar(100) not null, created_at mediumtext not null ); <file_sep>package com.yhkim.springsecuritypractice.provider; import com.yhkim.springsecuritypractice.exception.AccountException; import com.yhkim.springsecuritypractice.repository.entity.Account; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; public class AuthenticationAccount extends AbstractAuthenticationToken { private Account account; private final String jwtTokenStr; private Object credentials; public AuthenticationAccount(String jwtTokenStr) { super(null); this.jwtTokenStr = jwtTokenStr; this.credentials = null; } public AuthenticationAccount(Authentication auth, Account account) { super(null); this.jwtTokenStr = (String) auth.getPrincipal(); this.account = account; this.setAuthenticated(true); } // password @Override public Object getCredentials() { return this.credentials; } // id @Override public Object getPrincipal() { return this.jwtTokenStr; } public Account getAccount() throws AccountException { if (this.account == null) throw new AccountException(); return this.account; } } <file_sep>package com.yhkim.springsecuritypractice.service; import com.yhkim.springsecuritypractice.common.UuidUtils; import com.yhkim.springsecuritypractice.controller.dto.AccountDTO; import com.yhkim.springsecuritypractice.exception.WheelieException; import com.yhkim.springsecuritypractice.provider.JwtTokenProvider; import com.yhkim.springsecuritypractice.repository.AccountRepository; import com.yhkim.springsecuritypractice.repository.TokenRepository; import com.yhkim.springsecuritypractice.repository.entity.Account; import com.yhkim.springsecuritypractice.repository.entity.Token; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.Calendar; import java.util.Optional; @Service @RequiredArgsConstructor public class AccountService { private final AccountRepository accountRepository; private final TokenRepository tokenRepository; private final JwtTokenProvider jwtTokenProvider; public ResponseEntity<AccountDTO.LoginResponse> loginV2(AccountDTO.LoginRequest loginRequest) throws WheelieException { AccountDTO.LoginObject loginObject = AccountDTO.LoginObject.builder() .id(loginRequest.getId()) .nickname(loginRequest.getNickname()) .profileImageUrl(loginRequest.getProfileImageUrl()) .build(); Account account = Account.toAccountEntityFromLoginObject(loginObject); Optional<Account> optionalAccount = accountRepository.findByKakaoIdEquals(account.getKakaoId()); if (optionalAccount.isPresent()) { account = optionalAccount.get(); } else { accountRepository.save(account); } return ResponseEntity.ok(AccountDTO.LoginResponse.builder() .statusCode(HttpStatus.OK.value()) .token(accountV2ToJWT(account)) .build()); } public AccountDTO.MyData getMyData(Account user) throws WheelieException { return AccountDTO.MyData.builder() .nickname(user.getNickname()) .email(user.getEmail() == null ? "" : user.getEmail()) .profileImageUrl(user.getProfileImageUrl()) .build(); } private String accountV2ToJWT(Account account) { Token token = Token.builder() .uuid(UuidUtils.uuid()) .account(account.getUuid()) .createdAt(Long.toString(Calendar.getInstance().getTimeInMillis())) .build(); String JWT = jwtTokenProvider.makeJwtToken(token); Token verifiedToken = jwtTokenProvider.verifyToken(JWT); tokenRepository.saveAndFlush(verifiedToken); return JWT; } public Account findAccountByUuid(String uuid) throws UsernameNotFoundException { return accountRepository.findById(uuid) .orElseThrow(() -> new UsernameNotFoundException("no_user_found")); } } <file_sep>package com.yhkim.springsecuritypractice.repository; import com.yhkim.springsecuritypractice.repository.entity.Token; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface TokenRepository extends JpaRepository<Token, String> { boolean existsByUuidEqualsAndAccountEqualsAndCreatedAtEquals(String uuid, String account, String createdAt); } <file_sep>package com.yhkim.springsecuritypractice.aop; import com.yhkim.springsecuritypractice.exception.AccountException; import com.yhkim.springsecuritypractice.exception.WheelieException; import com.yhkim.springsecuritypractice.filter.JwtAuthenticationFilter; import com.yhkim.springsecuritypractice.provider.AuthenticationAccount; import com.yhkim.springsecuritypractice.repository.entity.Account; import com.yhkim.springsecuritypractice.service.AccountService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.Map; @Slf4j @Aspect @Component public class AccountAspect { @Around("execution(* com.yhkim.springsecuritypractice.controller.*.*(.., @com.yhkim.springsecuritypractice.annotations.WheelieAccount (*), ..)) && !@annotation(com.yhkim.springsecuritypractice.annotations.EscapeAccountAspect)") public Object checkToken(ProceedingJoinPoint point) throws Throwable { String controller = (String) point.getTarget().getClass().getSimpleName(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); Object inputParam = null; for (Object obj : point.getArgs()) { if (obj instanceof Map) { inputParam = obj; } } String path = request.getRequestURI(); int port = request.getRemotePort(); // TODO: X-Real-IP 로 nginx가 real addr 넘겨줌 String ipAddr = request.getRemoteAddr(); String method = request.getMethod(); String success = "Success"; // TODO: Request Method도 log!! log.info("#####################################################################################################"); log.info("# REQUEST | CONTROLLER = {} | METHOD = {} | PATH = {} | REMOTEADDR = {} | PORT = {} | IN_PARAMS = {}", controller, method, path, ipAddr, port, inputParam == null ? "": inputParam); log.info("#####################################################################################################"); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Account account = ((AuthenticationAccount) authentication).getAccount(); Object[] args = Arrays.stream(point.getArgs()) .map(data -> { if (data instanceof Account) { data = account; } return data; }).toArray(); Object returnValue = point.proceed(args); log.info("#####################################################################################################"); log.info("# RESPONSE | CONTROLLER = {} | METHOD = {} | PATH = {} | RESULT = {} | REMOTEADDR = {} | PORT = {} | IN_PARAMS = {}", controller, method, path, returnValue, ipAddr, port, inputParam == null ? "" : inputParam); log.info("#####################################################################################################"); return returnValue; } } <file_sep>package com.yhkim.springsecuritypractice.controller.dto; import lombok.*; @Getter @Setter @AllArgsConstructor public class AccountDTO { @Getter @Setter @AllArgsConstructor @NoArgsConstructor public static class LoginRequest extends LoginObject { private String digest; } @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor public static class LoginObject { private String nickname; private String id; private String profileImageUrl; } @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor public static class LoginResponse { private int statusCode; private String token; } @Getter public static class ChangeNickname { private String newNickname; } @Getter @Setter @Builder public static class MyData { private String nickname; private String email; private String profileImageUrl; } }
52709a72740b465639b1d0a93da7a48ebfecc6c9
[ "Java", "SQL" ]
7
Java
BranKein/Spring-Security-Practice
5e948020b10d0b507f97f1ff0ac2afbd2e5c4cd1
da8f93b9349494eb1be2988f3b76b282d8d89b35
refs/heads/master
<file_sep>require 'sinatra' require 'pry' require 'shotgun' require 'pg' def db_connection begin connection = PG.connect(dbname: "movies") yield(connection) ensure connection.close end end def get_actors db_connection do |conn| actors = conn.exec('SELECT id, name FROM actors ORDER BY name').to_a end end def get_actors_details(actor_id) db_connection do |conn| actor_details = conn.exec_params('SELECT actors.name, movies.id AS "movie_id", movies.title, cast_members.character FROM movies JOIN cast_members ON movies.id = cast_members.movie_id JOIN actors ON actors.id = cast_members.actor_id WHERE actors.id = ($1)',[actor_id]).to_a end end def get_movies db_connection do |conn| movies = conn.exec('SELECT movies.id, title, year, rating, genres.name AS "genre", studios.name AS "studio" FROM movies JOIN genres ON movies.genre_id = genres.id LEFT OUTER JOIN studios ON movies.studio_id = studios.id ORDER BY title').to_a end end def get_movie_details(movie_id) db_connection do |conn| movie_details = conn.exec_params('SELECT title, genres.name AS "genre", studios.name AS "studio", actors.id AS "actor_id", actors.name AS "actor", cast_members.character AS "role" FROM movies JOIN genres ON movies.genre_id = genres.id JOIN studios ON movies.studio_id = studios.id JOIN cast_members ON movies.id = cast_members.movie_id JOIN actors ON actors.id = cast_members.actor_id WHERE movies.id = ($1)', [movie_id]).to_a end end get "/movies" do erb :'movies/index', locals: {movies: get_movies} end get "/movies/:id" do movie_id = params[:id] erb :'movies/show', locals: {movie_details: get_movie_details(movie_id)} end get "/actors" do erb :'actors/index', locals: {actors: get_actors} end get "/actors/:id" do actor_id = params[:id] erb :'actors/show', locals: {actor_details: get_actors_details(actor_id)} end
4fe2eba4d69ba3d0de5295c01f0667f4befd36af
[ "Ruby" ]
1
Ruby
jamesacero/movie-catalog-deluxe
c5107e9f73834b47510457049d74f2f5435c557d
0807793d693151ae2a7011cc69f4714cf950955a
refs/heads/master
<file_sep><?php declare(strict_types=1); namespace DoctrineMigrations; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; /** * Auto-generated Migration: Please modify to your needs! */ final class Version20190131223837 extends AbstractMigration { public function up(Schema $schema) : void { // this up() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('CREATE TABLE spot (id INT AUTO_INCREMENT NOT NULL, role_id INT NOT NULL, event_id INT NOT NULL, user_id INT DEFAULT NULL, INDEX IDX_B9327A73D60322AC (role_id), INDEX IDX_B9327A7371F7E88B (event_id), INDEX IDX_B9327A73A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); $this->addSql('CREATE TABLE event (id INT AUTO_INCREMENT NOT NULL, title VARCHAR(255) NOT NULL, description VARCHAR(255) NOT NULL, location VARCHAR(255) NOT NULL, date_from DATE NOT NULL, date_to DATE NOT NULL, image VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); $this->addSql('CREATE TABLE role (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE = InnoDB'); $this->addSql('ALTER TABLE spot ADD CONSTRAINT FK_B9327A73D60322AC FOREIGN KEY (role_id) REFERENCES role (id)'); $this->addSql('ALTER TABLE spot ADD CONSTRAINT FK_B9327A7371F7E88B FOREIGN KEY (event_id) REFERENCES event (id)'); $this->addSql('ALTER TABLE spot ADD CONSTRAINT FK_B9327A73A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)'); } public function down(Schema $schema) : void { // this down() migration is auto-generated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.'); $this->addSql('ALTER TABLE spot DROP FOREIGN KEY FK_B9327A7371F7E88B'); $this->addSql('ALTER TABLE spot DROP FOREIGN KEY FK_B9327A73D60322AC'); $this->addSql('DROP TABLE spot'); $this->addSql('DROP TABLE event'); $this->addSql('DROP TABLE role'); } } <file_sep><?php namespace App\Repository; class UserEmailIsAlreadyConfirmed extends \Exception { } <file_sep><?php namespace App\Controller; use App\Entity\User; use App\Repository\UserDoesNotExist; use App\Repository\UserEmailIsAlreadyConfirmed; use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController as BaseAdminController; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Symfony\Component\HttpFoundation\RedirectResponse; class AdminController extends BaseAdminController { /** * @Security("has_role('ROLE_ADMIN')") * * @return RedirectResponse */ public function confirmAction(): RedirectResponse { $id = $this->request->query->get('id'); $userRepository = $this->em->getRepository(User::class); $user = $userRepository->findOneBy(['id' => $id]); try { $userRepository->confirmUserEmail($user->getConfirmationToken()); $this->addFlash('success', 'You have successfully confirmed an user'); } catch (UserDoesNotExist|UserEmailIsAlreadyConfirmed $e) { $this->addFlash('warning', 'User is already confirmed!'); } return $this->redirectToRoute('easyadmin', [ 'action' => 'list', 'entity' => $this->request->query->get('entity'), ]); } } <file_sep><?php namespace App\Repository; class UserDoesNotExist extends \Exception { } <file_sep>FROM debian:jessie RUN apt-get update && apt-get install --no-install-recommends -y locales \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* RUN locale-gen en_US.UTF-8 ENV LANG en_US.UTF-8 ENV LANGUAGE en_US:en ENV LC_ALL en_US.UTF-8 ENV MODULESDIR /root/nginx-modules ENV NGINX_VERSION 1.13.0 RUN apt-get update && apt-get -y install nginx wget build-essential zlib1g-dev libpcre3 libpcre3-dev libbz2-dev libssl-dev tar unzip --no-install-recommends && rm -r /var/lib/apt/lists/* RUN cd /root && wget http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz && tar xf nginx-${NGINX_VERSION}.tar.gz && rm -f nginx-${NGINX_VERSION}.tar.gz RUN mkdir -p /var/log/nginx/ && mkdir -p /etc/nginx/ && mkdir -p /usr/share/ && mkdir -p /var/lock/ RUN cd /root/nginx-${NGINX_VERSION} && ./configure --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/lock/nginx.lock --with-http_v2_module --with-http_ssl_module --user=www-data --group=www-data --with-ipv6 --with-http_stub_status_module --with-http_gzip_static_module --with-http_addition_module --with-http_realip_module --without-mail_pop3_module --without-mail_imap_module --without-mail_smtp_module RUN cd /root/nginx-${NGINX_VERSION} && make && make install && make clean RUN rm -R /root/* CMD ["nginx", "-g", "daemon off;"] HEALTHCHECK --interval=5m --timeout=3s CMD curl -f http://localhost/ || exit 1 # Add required nginx config ADD nginx.conf /etc/nginx/nginx.conf ADD symfony.conf /etc/nginx/sites-enabled WORKDIR /var/www/symfony <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\SpotRepository") */ class Spot { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @var Role * * @ORM\ManyToOne(targetEntity="App\Entity\Role") * @ORM\JoinColumn(nullable=false) */ private $role; /** * @var Event * * @ORM\ManyToOne(targetEntity="App\Entity\Event", inversedBy="spots") * @ORM\JoinColumn(nullable=false) */ private $event; /** * @var User * * @ORM\ManyToOne(targetEntity="App\Entity\User") */ private $user; // /** // * @ORM\Column(type="string", length=255) // */ // private $status; public function getId(): ?int { return $this->id; } public function isAvailable(): bool { return $this->user === null; } public function setStatus(string $status): self { $this->status = $status; return $this; } public function getRole(): ?Role { return $this->role; } public function setRole(?Role $role): self { $this->role = $role; return $this; } public function getEvent(): ?Event { return $this->event; } public function setEvent(?Event $event): self { $this->event = $event; return $this; } public function getUser(): ?User { return $this->user; } public function setUser(?User $user): self { $this->user = $user; return $this; } public function attemptToReserve(User $user): bool { if ($this->event->hasUser($user)) { return false; } $this->setUser($user); return true; } public function __toString(): string { return $this->role->getName(); } } <file_sep><?php namespace App\DataFixtures; use App\Entity\Event; use App\Entity\Role; use App\Entity\Spot; use App\Entity\User; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Common\Persistence\ObjectManager; use Ramsey\Uuid\Uuid; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; class EventFixtures extends Fixture { private const ROLES_TO_ADD = [ 'Captain', 'Driver', 'Cook', 'Hunter' ]; private const EVENTS_TO_ADD = [ [ 'name' => 'Night sailing in Mazury', 'description' => 'Sit est beatae adipisci. Deleniti et illum excepturi dolor. Et omnis nobis adipisci nulla est sapiente non nesciunt. Ducimus cumque commodi nostrum debitis reprehenderit magni ipsa. Reprehenderit dolor ut dolore ducimus voluptatem.', 'dateFrom' => '14.01.2019', 'dateTo' => '31.01.2019', 'location' => 'Mazury, Poland', 'spots' => [ ['role' => 'Driver'], ['role' => 'Captain'], ] ], [ 'name' => 'Weekend hunt in the forest of Białowieża', 'description' => 'Sit est beatae adipisci. Deleniti et illum excepturi dolor. Et omnis nobis adipisci nulla est sapiente non nesciunt. Ducimus cumque commodi nostrum debitis reprehenderit magni ipsa. Reprehenderit dolor ut dolore ducimus voluptatem.', 'dateFrom' => '01.02.2019', 'dateTo' => '04.02.2019', 'location' => 'Białowieża, Poland', 'spots' => [ ['role' => 'Driver'], ['role' => 'Cook'], ['role' => 'Hunter'], ['role' => 'Hunter'], ] ], ]; /** * @var UserPasswordEncoderInterface */ private $passwordEncoder; public function __construct(UserPasswordEncoderInterface $passwordEncoder) { $this->passwordEncoder = $passwordEncoder; } public function load(ObjectManager $manager) { $userIzabela = $this->createUser($manager); $roles = []; foreach (self::ROLES_TO_ADD as $roleName) { $role = new Role(); $role->setName($roleName); $manager->persist($role); $roles[$roleName] = $role; } foreach (self::EVENTS_TO_ADD as $eventToAdd) { $event = new Event(); $event->setOwner($userIzabela); $event->setTitle($eventToAdd['name']); $event->setDescription($eventToAdd['description']); $event->setDateFrom(new \DateTime($eventToAdd['dateFrom'])); $event->setDateTo(new \DateTime($eventToAdd['dateTo'])); $event->setLocation($eventToAdd['location']); foreach ($eventToAdd['spots'] as $spotToAdd) { $spot = new Spot(); $spot->setEvent($event); $spot->setRole($roles[$spotToAdd['role']]); $manager->persist($spot); $event->addSpot($spot); } $manager->persist($event); } $manager->flush(); } private function createUser(ObjectManager $manager): User { $user = new User(); $user->setName('Izabela'); $user->setEmail('<EMAIL>'); $password = $this->passwordEncoder->encodePassword($user, '<PASSWORD>'); $user->setPassword($password); $user->setRoles(['ROLE_ADMIN']); $user->setConfirmationToken(Uuid::uuid4()->toString()); $manager->persist($user); $manager->flush(); return $user; } } <file_sep><?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\EventRepository") */ class Event { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $title; /** * @ORM\Column(type="string", length=255) */ private $description; /** * @ORM\Column(type="string", length=255) */ private $location; /** * @ORM\Column(type="date") */ private $dateFrom; /** * @ORM\Column(type="date") */ private $dateTo; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $image; /** * @ORM\OneToMany(targetEntity="App\Entity\Spot", mappedBy="event", orphanRemoval=true) */ private $spots; /** * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="events") * @ORM\JoinColumn(nullable=false) */ private $owner; /** * @ORM\ManyToMany(targetEntity="App\Entity\Role") */ private $role; public function __construct() { $this->spots = new ArrayCollection(); $this->role = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getTitle(): ?string { return $this->title; } public function setTitle(string $title): self { $this->title = $title; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getLocation(): ?string { return $this->location; } public function setLocation(string $location): self { $this->location = $location; return $this; } public function getDateFrom(): ?\DateTimeInterface { return $this->dateFrom; } public function setDateFrom(\DateTimeInterface $dateFrom): self { $this->dateFrom = $dateFrom; return $this; } public function getDateTo(): ?\DateTimeInterface { return $this->dateTo; } public function setDateTo(\DateTimeInterface $dateTo): self { $this->dateTo = $dateTo; return $this; } public function getImage(): ?string { return $this->image; } public function setImage(?string $image): self { $this->image = $image; return $this; } /** * @return Collection|Spot[] */ public function getSpots(): Collection { return $this->spots; } public function addSpot(Spot $spot): self { if (!$this->spots->contains($spot)) { $this->spots[] = $spot; $spot->setEvent($this); } return $this; } public function removeSpot(Spot $spot): self { if ($this->spots->contains($spot)) { $this->spots->removeElement($spot); // set the owning side to null (unless already changed) if ($spot->getEvent() === $this) { $spot->setEvent(null); } } return $this; } public function hasUser(User $user): bool { foreach ($this->getSpots() as $spot) { if ($spot->getUser() === $user) { return true; } } return false; } public function getOwner(): ?User { return $this->owner; } public function setOwner(?User $owner): self { $this->owner = $owner; return $this; } /** * @return Collection|Role[] */ public function getRole(): Collection { return $this->role; } public function addRole(Role $role): self { if (!$this->role->contains($role)) { $this->role[] = $role; } return $this; } public function removeRole(Role $role): self { if ($this->role->contains($role)) { $this->role->removeElement($role); } return $this; } } <file_sep><?php namespace App\DataFixtures; use App\Entity\Category; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Common\Persistence\ObjectManager; class CategoryFixtures extends Fixture { public const CATEGORIES = [ 'Sport', 'Travel', 'Social', 'Business', 'Health' ]; public function load(ObjectManager $manager): void { foreach (self::CATEGORIES as $category) { $newCategory = new Category(); $newCategory->setName($category); $manager->persist($newCategory); } $manager->flush(); } } <file_sep><?php namespace App\Controller; use App\Entity\User; use App\Form\RegistrationFormType; use App\Notification\UserNotifier; use App\Repository\UserDoesNotExist; use App\Repository\UserEmailIsAlreadyConfirmed; use App\Repository\UserRepository; use App\Security\AppAuthenticator; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; use Symfony\Component\Security\Guard\GuardAuthenticatorHandler; class RegistrationController extends AbstractController { /** * @var UserRepository */ private $userRepository; /** * @var UserNotifier */ private $userNotifier; public function __construct(UserRepository $userRepository, UserNotifier $userNotifier) { $this->userRepository = $userRepository; $this->userNotifier = $userNotifier; } /** * @Route("/register", name="app_register") */ public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder, GuardAuthenticatorHandler $guardHandler, AppAuthenticator $authenticator): Response { // if authenticated if ($this->isGranted('ROLE_USER_NOT_CONFIRMED')) { return RedirectResponse::create('/'); } $user = new User(); $form = $this->createForm(RegistrationFormType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $user->setPassword( $passwordEncoder->encodePassword( $user, $form->get('password')->getData() ) ); $this->userRepository->register($user); $this->userNotifier->requestEmailConfirmation($user); $this->addFlash('success', 'You have been successfully registered. Confirm your email to use all of the features.'); return $guardHandler->authenticateUserAndHandleSuccess( $user, $request, $authenticator, 'main' ); } return $this->render('registration/register.html.twig', [ 'registrationForm' => $form->createView(), ]); } /** * @Route("/confirm-email/{confirmationToken}", name="app_confirm_email") */ public function confirmEmailAddress(string $confirmationToken): Response { try { $this->userRepository->confirmUserEmail($confirmationToken); $user = $this->userRepository->findOneBy(['confirmationToken' => $confirmationToken]); $this->userNotifier->greetUser($user); $this->addFlash('success', 'Your email has been confirmed! Feel free to use all of the features.'); } catch (UserDoesNotExist|UserEmailIsAlreadyConfirmed $e) { $this->addFlash('warning', $e->getMessage()); } return $this->redirect('/'); } } <file_sep>FROM php:7.2-fpm RUN apt-get update && apt-get install --no-install-recommends -y \ libmcrypt-dev \ libxml2-dev \ librabbitmq-dev \ libssh-dev \ python python-pip \ # required by Mcrypt Extension libicu-dev && \ # required by Intl Extension apt-get clean && \ rm -rf /var/lib/apt/lists/* RUN pecl install amqp apcu \ && docker-php-ext-enable amqp RUN echo "extension=apcu.so" > /usr/local/etc/php/conf.d/apcu.ini RUN docker-php-ext-install -j$(nproc) opcache pdo pdo_mysql intl sockets bcmath mbstring soap RUN echo "date.timezone = Europe/London" >> /usr/local/etc/php/php.ini # Install Composer RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer RUN echo "memory_limit = 1G;" > /usr/local/etc/php/php.ini && \ echo "error_reporting = E_ALL;" >> /usr/local/etc/php/php.ini && \ echo "date.timezone = Europe/London" >> /usr/local/etc/php/php.ini # xdebug RUN pecl install xdebug && \ docker-php-ext-enable xdebug RUN echo "error_reporting = E_ALL" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini && \ echo "display_startup_errors = On" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini && \ echo "display_errors = On" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini && \ echo "xdebug.remote_enable=1" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini && \ echo "xdebug.remote_autostart=1" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini && \ echo "xdebug.remote_connect_back=0" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini && \ echo "xdebug.idekey=PHPSTORM" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini && \ echo "xdebug.remote_host=host.docker.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini && \ echo "xdebug.remote_port=9001" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini RUN apt-get update \ && apt-get install --no-install-recommends -y libxml2-dev git \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* RUN docker-php-ext-install -j$(nproc) soap RUN mkdir /var/www/symfony WORKDIR /var/www/symfony <file_sep><?php namespace App\Repository; use App\Entity\Event; use App\Entity\Spot; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Symfony\Bridge\Doctrine\RegistryInterface; /** * @method Event|null find($id, $lockMode = null, $lockVersion = null) * @method Event|null findOneBy(array $criteria, array $orderBy = null) * @method Event[] findAll() * @method Event[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class EventRepository extends ServiceEntityRepository { public function __construct(RegistryInterface $registry) { parent::__construct($registry, Event::class); } public function findAllEventsByCategory(string $category = null): array { return $this->findBy([ ], [ 'dateFrom' => 'ASC' ]); } public function save(Spot $spot): void { $em = $this->getEntityManager(); $em->persist($spot); $em->flush(); } } <file_sep><?php namespace App\Notification; use App\Entity\User; use Twig\Environment; class UserNotifier { /** * @var \Swift_Mailer */ private $mailer; /** * @var Environment */ private $twigEnvironment; public function __construct(\Swift_Mailer $mailer, Environment $twigEnvironment) { $this->mailer = $mailer; $this->twigEnvironment = $twigEnvironment; } public function requestEmailConfirmation(User $user): void { $message = new \Swift_Message('Hello email'); $message->setFrom('<EMAIL>') ->setTo($user->getEmail()) ->setBody($this->twigEnvironment->render('email/confirmation.html.twig', ['user' => $user])); $this->mailer->send($message); } public function greetUser(User $user): void { $message = new \Swift_Message('Thank you for your registration'); $message->setFrom('<EMAIL>') ->setTo($user->getEmail()) ->setBody($this->twigEnvironment->render('email/thankyou.html.twig', ['user' => $user])); $this->mailer->send($message); } } <file_sep><?php namespace App\Repository; use App\Entity\User; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Ramsey\Uuid\Uuid; use Symfony\Bridge\Doctrine\RegistryInterface; /** * @method User|null find($id, $lockMode = null, $lockVersion = null) * @method User|null findOneBy(array $criteria, array $orderBy = null) * @method User[] findAll() * @method User[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class UserRepository extends ServiceEntityRepository { public function __construct(RegistryInterface $registry) { parent::__construct($registry, User::class); } private function save(User $user): void { $entityManager = $this->getEntityManager(); $entityManager->persist($user); $entityManager->flush(); } public function register(User $user): void { $user->setRoles(['ROLE_USER_NOT_CONFIRMED']); $user->setConfirmationToken(Uuid::uuid4()->toString()); $this->save($user); } /** * @param string $confirmationToken * * @throws UserDoesNotExist * @throws UserEmailIsAlreadyConfirmed */ public function confirmUserEmail(string $confirmationToken): void { $user = $this->findOneBy(['confirmationToken' => $confirmationToken]); if (!$user) { throw new UserDoesNotExist("There's no user for this token"); } if ($user->isConfirmed()) { throw new UserEmailIsAlreadyConfirmed('Your email is already confirmed.'); } $user->confirm(); $this->save($user); } } <file_sep><?php namespace App\Controller; use App\Entity\Event; use App\Entity\Spot; use App\Repository\CategoryRepository; use App\Repository\EventRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Response; class HomeController extends AbstractController { /** * @var CategoryRepository */ private $categoryRepository; /** * @var EventRepository */ private $eventRepository; public function __construct( CategoryRepository $categoryRepository, EventRepository $eventRepository ) { $this->categoryRepository = $categoryRepository; $this->eventRepository = $eventRepository; } public function indexAction($category = null): Response { return $this->render('home/dashboard.html.twig', [ 'categories' => $this->categoryRepository->findAllMainCategoriesWithCounts(), 'events' => $this->eventRepository->findAllEventsByCategory($category) ]); } public function eventAction(Event $event): Response { return $this->render('home/event.html.twig', [ 'event' => $event ]); } public function joinEventAction(Spot $spot): RedirectResponse { if (!$spot->isAvailable()) { $this->addFlash('warning', 'Sorry, but this spot is already occupied :c'); return $this->redirectToRoute('app_event', ['id' => $spot->getEvent()->getId()]); } if (!$spot->attemptToReserve($this->getUser())) { $this->addFlash('warning', 'Sorry! You\'re already in our team'); return $this->redirectToRoute('app_event', ['id' => $spot->getEvent()->getId()]); } $this->eventRepository->save($spot); $this->addFlash('success', 'Yaaay! You have teamed up!'); return $this->redirectToRoute('app_event', ['id' => $spot->getEvent()->getId()]); } }
c29593c1c928b99cd41fc261dfca45d0c114049d
[ "Dockerfile", "PHP" ]
15
PHP
gitzabela/TIN
edb097372f2664b939246097e87b8d5bb2b145ee
ffd595fc82bf815e1ef511bee0d9ce260b8c6265
refs/heads/master
<repo_name>bnslanuj/FBHackerCup<file_sep>/CookingtheBooks.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; int main() { int t,test; string str,a,b; cin>>test; for(t=1;t<=test;t++){ cin>>str; a=b=str; for(int i=0;i<str.size();i++) { for(int j=i+1;j<str.size();j++) { string temp=str; char c=temp[j]; if(i==0 && c=='0')continue; temp[j]=temp[i]; temp[i]=c; if(temp>a)a=temp; if(temp<b)b=temp; } } printf("Case #%d: %s %s\n",t,b.c_str(),a.c_str());} return 0; } <file_sep>/BalancedSmileys.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll unsigned long long #define mod 1000000007 using namespace std; int main() { int t,test; cin>>test; char ch,p; getchar(); for(t=1;t<=test;t++) { int s,f,o; s=f=o=0; p='p'; bool isDone=1; while((ch=getchar())!='\n') { if(ch=='(' && p==':') f++; if(ch==')' && p==':') s++; if(ch=='(') o++; else if(ch==')') { if(o) { o--; if(f>o) f=o; } else if(s) s--; else isDone=0; } p=ch; } if(o<=f && isDone) printf("Case #%d: YES\n",t); else printf("Case #%d: NO\n",t); //getchar(); } return 0; } <file_sep>/Squished_Status.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 4207849484 using namespace std; int main() { ll t,test,m,i,j,k,temp; cin>>test; string str; for(t=1;t<=test;t++) { cin>>m>>str; int l=str.size(); vector<vector<ll> >dp(l+1,vector<ll>(l+1,0)); for(i=1;i<=l;i++) { temp=atoi(str.substr(i-1,1).c_str()); if(temp>=1 && temp<=min(9LL,m)) dp[i][i]=1; } for(i=1;i<l;i++) { temp=atoi(str.substr(i-1,2).c_str()); if(temp/10>=1 && temp/10<=min(9LL,m)) dp[i][i+1]=dp[i+1][i+1]; if(temp>=10 && temp<=min(99LL,m)) dp[i][i+1]++; } for(i=1;i<l-1;i++) { temp=atoi(str.substr(i-1,3).c_str()); if(temp/100>=1 && temp/100<=min(9LL,m)) dp[i][i+2]=dp[i+1][i+2]; if(temp/10>=10 && temp/10<=min(99LL,m)) dp[i][i+2]+=dp[i+2][i+2]; if(temp>=100 && temp<=min(255LL,m)) dp[i][i+2]++; } for(k=4;k<=l;k++) { i=1;j=k; while(i<=l && j<=l) { temp=atoi(str.substr(i-1,3).c_str()); if(temp/100>=1 && temp/100<=min(9LL,m)) dp[i][j]=(dp[i][j]+dp[i+1][j])%mod; if(temp/10>=10 && temp/10<=min(99LL,m)) dp[i][j]=(dp[i][j]+dp[i+2][j])%mod; if(temp>=100 && temp<=min(255LL,m)) dp[i][j]=(dp[i][j]+dp[i+3][j])%mod; i++;j++; } } printf("Case #%lld: %lld\n",t,dp[1][l]); } } <file_sep>/CardGame.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; ll fact[10009]; ll invfact[10009]; ll raise(ll a,ll b) { if(b==0)return 1; ll val=raise(a,b/2); if(b&1) return (((val*val)%mod)*a)%mod; return (val*val)%mod; } void init() { fact[0]=invfact[0]=1; for(ll i=1;i<=10000;i++) fact[i]=(fact[i-1]*i)%mod; for(ll i=1;i<=10000;i++) invfact[i]=raise(fact[i],mod-2); return ; } ll ncr(ll n,ll r) { return (((fact[n]*invfact[r])%mod)*invfact[n-r])%mod; } ll v[10009]; int main() { init(); ll t,test,n,k; cin>>test; for(t=1;t<=test;t++) { cin>>n>>k; for(ll i=0;i<n;i++) cin>>v[i]; sort(v,v+n); ll ans=0; for(ll i=n-1;i>=k-1;i--) ans=(ans+(v[i]*ncr(i,k-1))%mod)%mod; printf("Case #%lld: %lld\n",t,ans); } return 0; } <file_sep>/ThePriceisCorrect.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; ll numRange(vector<ll> &arr, ll b, ll c) { if(arr.size()==0)return 0; vector<ll>cum(arr.size()+1,0); cum[1]=arr[0]; for(int i=2;i<=arr.size();i++) cum[i]=cum[i-1]+arr[i-1]; ll ans=0,low,high; low=high=1; for(int i=1;i<=arr.size();i++) { while(low<=arr.size() && cum[low]-cum[i-1]<b) low++; while(high<=arr.size() && cum[high]-cum[i-1]<=c) high++; high--; if(low<=high) ans+=(high-low+1); low=max(low,(ll)i+1); high=max(high,(ll)i+1); } return ans; } int main() { int t,test; cin>>test; ll n,p; for(t=1;t<=test;t++) { cin>>n>>p; vector<ll>v(n); for(int i=0;i<n;i++) cin>>v[i]; ll ans=numRange(v,1,p); printf("Case #%d: %lld\n",t,ans); } return 0; } <file_sep>/DoubleSquares.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; int main() { vector<ll>v; for(ll i=0;i<=50000;i++) v.push_back(i*i); ll n,c,x,nn; // freopen("double_squares.txt","r",stdin); //freopen("sout.txt", "w",stdout); cin>>nn; for(n=1;n<=nn;n++) { cin>>x; c=0; int i=0,j=v.size()-1; while(i<=j) { if(v[i]+v[j]==x) { c++; i++;j--; } else if(v[i]+v[j]<x) i++; else j--; } printf("Case #%d: %d\n",n,c); } return 0; } <file_sep>/Billboards.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; int main() { int test,t,w,h; char c; scanf("%d",&test); for(t=1;t<=test;t++) { scanf("%d%d",&w,&h); getchar(); vector<string>v; string str; while((c=getchar())!='\n') { if(c==' ') { v.push_back(str); str.clear(); } else str.push_back(c); } v.push_back(str); int ans=0; for(int i=min(w,h); i>=1; i--) { int pos=0,k=0,j,line=h/i; for(j=1;j<=line && k<v.size();) { if(pos+v[k].size()*i<=w) { pos+=v[k].size()*i+i; k++; } else { j++; pos=0; } } if(k==v.size()) { ans=i;break; } } printf("Case #%d: %d\n",t,ans); } return 0; } <file_sep>/CodingContestCreation.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; int main() { int t,test,n; scanf("%d",&test); for(t=1;t<=test;t++) { scanf("%d",&n); vector<int>arr(n+1,0); for(int i=0;i<n;i++) scanf("%d",&arr[i]); int c=0,curr=0,last=arr[0]-1; for(int i=0;i<n;) { if(arr[i]-last<=10 && arr[i]-last>0) { last=arr[i]; i++; } else { c++; last+=10; } curr++; if(curr==4) { curr=0; last=arr[i]-1; } } if(curr!=0) c+=(4-curr); printf("Case #%d: %d\n",t,c); } } <file_sep>/StudiousStudent.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; bool comp(string a,string b) { if(a+b<b+a)return 1; return 0; } int main() { int t,tt,m; cin>>tt; for(t=1;t<=tt;t++) { cin>>m; vector<string>str(m); for(int i=0;i<m;i++) cin>>str[i]; sort(str.begin(),str.end(),comp); string ans; for(int i=0;i<m;i++) ans+=str[i]; printf("Case #%d: ",t); cout<<ans<<endl; } return 0; } <file_sep>/HighSecurity.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; bool check(string str,int i) { if(str.size()==1 && str[0]=='.') return true; if(i==0 && str[i]=='.' && str[i+1]!='.') return true; if(i==str.size()-1 && str[str.size()-1]=='.' && str[str.size()-2]!='.') return true; if(str[i]=='.' && str[i-1]!='.' && str[i+1]!='.') return true; return false; } bool mark(string &str,int i) { if(str[i]=='.') { for(int j=i;j>=0 && str[j]=='.';j--) str[j]='X'; for(int j=i+1;j<str.size() && str[j]=='.';j++) str[j]='X'; return true; } return false; } int main() { int test,t,n; cin>>test; string str[2]; for(t=1;t<=test;t++) { cin>>n>>str[0]>>str[1]; int c=0; for(int i=0;i<n;i++) { if(str[0][i]=='.') { c++; while(i<n && str[0][i]=='.') i++; } } for(int i=0;i<n;i++) { if(str[1][i]=='.') { c++; while(i<n && str[1][i]=='.') i++; } } for(int i=0;i<n;i++) { if(check(str[0],i) && mark(str[1],i)) c--; } for(int i=0;i<n;i++) { if(check(str[1],i) && mark(str[0],i)) c--; } printf("Case #%d: %d\n",t,c); } return 0; } <file_sep>/Autocomplete.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; struct node { char c; struct node *next[26]; }; struct node* newNode(char c) { struct node *temp=(struct node*)malloc(sizeof(struct node)); temp->c=c; for(int i=0;i<26;i++) temp->next[i]=NULL; return temp; } int insert(struct node *root,string &str) { if(root==NULL)return -1; int c=1,ans=0; struct node *trav=root; for(int i=0;i<str.size();i++) { if(trav->next[str[i]-'a']==NULL) { if(ans==0) ans=c; trav->next[str[i]-'a']=newNode(str[i]); trav=trav->next[str[i]-'a']; } else { trav=trav->next[str[i]-'a']; c++; } } if(ans==0)return c-1; return ans; } int main() { int test,t,n; cin>>test; for(t=1;t<=test;t++) { cin>>n; string str; int ans=0; struct node *root=newNode('#'); for(int i=1;i<=n;i++) { cin>>str; ans+=insert(root,str); } printf("Case #%d: %d\n",t,ans); } } <file_sep>/LaserMaze.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; char mat[109][109]; bool visit[4][109][109]; bool danger[4][109][109]; int n,m; void init() { for(int i=0;i<=n;i++) { for(int j=0;j<=m;j++) { visit[0][i][j]=visit[1][i][j]=visit[2][i][j]=visit[3][i][j]=0; danger[0][i][j]=danger[1][i][j]=danger[2][i][j]=danger[3][i][j]=0; } } return ; } //up->0 right->1 down->2 left->3 void markDanger(int x,int y,int dir,int num) { if(dir==0) { for(int i=x-1;i>=0;i--) { if(mat[i][y]=='#' || mat[i][y]=='<' || mat[i][y]=='>' || mat[i][y]=='^' || mat[i][y]=='v') break; danger[num][i][y]=1; } } else if(dir==1) { for(int i=y+1;i<m;i++) { if(mat[x][i]=='#' || mat[x][i]=='<' || mat[x][i]=='>' || mat[x][i]=='^' || mat[x][i]=='v') break; danger[num][x][i]=1; } } else if(dir==2) { for(int i=x+1;i<n;i++) { if(mat[i][y]=='#' || mat[i][y]=='<' || mat[i][y]=='>' || mat[i][y]=='^' || mat[i][y]=='v') break; danger[num][i][y]=1; } } else { for(int i=y-1;i>=0;i--) { if(mat[x][i]=='#' || mat[x][i]=='<' || mat[x][i]=='>' || mat[x][i]=='^' || mat[x][i]=='v') break; danger[num][x][i]=1; } } } void preCompute() { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(mat[i][j]=='<') { markDanger(i,j,3,0); markDanger(i,j,0,1); markDanger(i,j,1,2); markDanger(i,j,2,3); } else if(mat[i][j]=='^') { markDanger(i,j,0,0); markDanger(i,j,1,1); markDanger(i,j,2,2); markDanger(i,j,3,3); } else if(mat[i][j]=='>') { markDanger(i,j,1,0); markDanger(i,j,2,1); markDanger(i,j,3,2); markDanger(i,j,0,3); } else if(mat[i][j]=='v') { markDanger(i,j,2,0); markDanger(i,j,3,1); markDanger(i,j,0,2); markDanger(i,j,1,3); } } } return ; } int dx[]={1,-1,0,0}; int dy[]={0,0,1,-1}; bool isValid(int x,int y) { if(x>=0 && y>=0 && x<n && y<m && (mat[x][y]=='.'||mat[x][y]=='S'||mat[x][y]=='G') ) return 1; return 0; } void print(int num) { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) printf("%d ",danger[num][i][j]); printf("\n"); } } int main() { int t,test; cin>>test; for(t=1;t<=test;t++) { cin>>n>>m; init(); for(int i=0;i<n;i++) cin>>mat[i]; preCompute(); queue<int>X,Y,S,N; for(int i=0;i<n;i++) for(int j=0;j<m;j++) { if(mat[i][j]=='S') { X.push(i); Y.push(j); S.push(0); N.push(0); visit[0][i][j]=1; } } int ans=INT_MAX; while(!X.empty()) { int currx=X.front(); int curry=Y.front(); int currs=S.front(); int num=N.front(); X.pop();Y.pop();S.pop();N.pop(); if(mat[currx][curry]=='G' && !danger[num][currx][curry]) { ans=currs;break; } for(int i=0;i<4;i++) { int x,y; x=currx+dx[i]; y=curry+dy[i]; if(isValid(x,y) && !danger[(num+1)%4][x][y] && !visit[(num+1)%4][x][y]) { visit[(num+1)%4][x][y]=1; X.push(x); Y.push(y); S.push(currs+1); N.push((num+1)%4); } } } if(ans==INT_MAX) printf("Case #%d: impossible\n",t); else printf("Case #%d: %d\n",t,ans); } return 0; } <file_sep>/Labelmaker.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; int main() { ll t,n,test; cin>>test; for(t=1;t<=test;t++) { string str; cin>>str>>n; string ans; while(n>0) { ll rem=n%str.size(); if(rem!=0) { rem--; n=n/str.size(); } else { rem=str.size()-1; n=n/str.size()-1; } ans=str[rem]+ans; } printf("Case #%d: %s\n",t,ans.c_str()); } return 0; } <file_sep>/BeautifulStrings.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll unsigned long long #define mod 1000000007 using namespace std; int main() { int t,test; cin>>test; getchar(); char c; for(t=1;t<=test;t++) { vector<int>v(26,0); while((c=getchar())!='\n') { if(c>='A'&&c<='Z') v[c-'A']++; if(c>='a'&&c<='z') v[c-'a']++; } sort(v.begin(),v.end()); int ans=0; for(int i=25,j=26;i>=0;i--,j--) ans+=v[i]*j; printf("Case #%d: %d\n",t,ans); } return 0; } <file_sep>/TurnontheLights.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; int arr[20][20]; int temp[20][20]; void toggle(int x,int y,int mat[][20],int r,int c) { mat[x][y]^=1; if(x-1>=1) mat[x-1][y]^=1; if(y-1>=1) mat[x][y-1]^=1; if(y+1<=c) mat[x][y+1]^=1; if(x+1<=r) mat[x+1][y]^=1; return ; } int main() { int t,tt,r,c; scanf("%d",&tt); for(t=1;t<=tt;t++) { scanf("%d%d",&r,&c); string str; for(int i=1;i<=r;i++) { cin>>str; for(int j=1;j<=c;j++) { if(str[j-1]=='X') arr[i][j]=1; else arr[i][j]=0; } } int ans=INT_MAX; for(int i=0;i<(1<<c);i++) { //make copy. for(int j=1;j<=r;j++) for(int k=1;k<=c;k++) temp[j][k]=arr[j][k]; int count=0; for(int j=1;j<=c;j++) { if(((1<<(j-1))&i) && temp[1][j]==0) { count++; toggle(1,j,temp,r,c); } else if(!((1<<(j-1))&i) && temp[1][j]) { count++; toggle(1,j,temp,r,c); } } for(int j=2;j<=r;j++) { for(int k=1;k<=c;k++) { if(temp[j-1][k]==0) { count++; toggle(j,k,temp,r,c); } } } bool isDone=1; for(int j=1;j<=c;j++) { if(temp[r][j]==0) { isDone=0;break; } } if(isDone) ans=min(ans,count); } if(ans==INT_MAX)ans=-1; printf("Case #%d: %d\n",t,ans); } return 0; } <file_sep>/NewYear'sResolution.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; int main() { int n,t,test,gp,gc,gf; cin>>test; for(t=1;t<=test;t++) { cin>>gp>>gc>>gf>>n; vector<int>p(n),c(n),f(n); for(int i=0;i<n;i++) cin>>p[i]>>c[i]>>f[i]; bool isDone=0; for(int i=1;i<(1<<n);i++) { int k,j,tc=0,tf=0,tp=0; j=i;k=0; while(j) { if(j&1) { tc+=c[k]; tf+=f[k]; tp+=p[k]; } j>>=1; k++; } if(tc==gc && tf==gf && tp==gp) { isDone=1;break; } } if(isDone) printf("Case #%d: yes\n",t); else printf("Case #%d: no\n",t); } return 0; } <file_sep>/FindtheMin.cpp #include<iostream> #include<cstdio> #include<cstdlib> #include<climits> #include<queue> #include<map> #include<stack> #include<vector> #include<ctime> #include<cstring> #include<algorithm> #include<set> #include <iomanip> #include<cmath> #define ll long long #define mod 1000000007 using namespace std; int main() { ll test,t,n,k,a,b,c,r; cin>>test; for(t=1;t<=test;t++) { cin>>n>>k>>a>>b>>c>>r; vector<ll>v(k); map<ll,ll>s,s1; map<ll,ll>::iterator it; v[0]=a; s1[a]++; for(ll i=1;i<k;i++) { v[i]=(b*v[i-1]+c)%r; s1[v[i]]++; } for(ll i=0;i<=k;i++) { if(s1.find(i)==s1.end()) s[i]++; } n=(n-k-1)%(k+1); ll ans; for(ll i=0;i<=n;i++) { it=s.begin(); ans=it->first; s.erase(it); it=s1.find(v[i]); it->second--; if(it->second==0) { s[it->first]++; s1.erase(it); } } printf("Case #%lld: %lld\n",t,ans); } return 0; }
98a593875425b378a9fda4fee1a823a017e2a7fa
[ "C++" ]
17
C++
bnslanuj/FBHackerCup
cd154d23c5b51203d99b581aeed6a4dcab728279
1006012afbc107b4706a10e51395c3d36fb9effa
refs/heads/master
<repo_name>onimenotsuki/medium-blog<file_sep>/src/pages/index.js import React, { Component } from 'react' import Layout from '../components/layout' const mediumLink = (username, uniqueSlug) => { const url = 'https://medium.com'; const permalink = encodeURIComponent(uniqueSlug); return `${url}/${username}/${permalink}`; } class IndexPage extends Component { constructor() { super() this.state = { payload: { posts: [], }, } } componentDidMount() { const username = 'edgar-talledos' fetch(`${process.env.API_URL}?username=${username}`) .then(res => res.json()) .then(({ payload }) => this.setState({ payload })) } componentWillUnmount() { this.setState({ payload: { posts: [] } }) } render() { const { payload: { posts } } = this.state; return ( <Layout> {posts.map(post => ( <div key={post.id} className="fl w-100 w-50-ns pa4" > <h1 className="f2 lh-title">{post.title}</h1> <p className="f3 lh-copy">{post.virtuals.subtitle}</p> <a className="link black dim" href={mediumLink('edgar-talledos', post.uniqueSlug)} > Leer más... </a> </div> ))} </Layout> ) } } export default IndexPage
d4f5a7451660b4d54c79afae7082399b9c82b1af
[ "JavaScript" ]
1
JavaScript
onimenotsuki/medium-blog
a974c8fa316ff75dd296c17ef7b93137b0f658a6
4fe95c3b867eed3ad7ac3d5928b55063af1e8622
refs/heads/master
<file_sep><?php namespace ylPay\interfaces; use ylPay\core\Container; /** * Interface Provider * @package ylPay\interfaces */ interface Provider { public function serviceProvider(Container $container); } <file_sep><?php namespace ylPay\functions\Alipay\Transfer; use ylPay\core\AliPayBaseClient; use ylPay\core\ylPayException; class fundTrans extends AliPayBaseClient { /** * 支付宝转账到个人支付宝 通过邮箱或手机号码指定收款支付宝账号 * B2C红包 * @throws ylPayException */ public function alipayFundTransUniTransfer() { // 添加公共参数 $params = [ 'app_id' => $this->app->app_id, 'method' => 'alipay.fund.trans.uni.transfer', 'format' => 'json', 'timestamp' => date("Y-m-d H:i:s"), 'charset' => 'UTF-8', 'app_cert_sn' => $this->app->alipay_app_cert, 'alipay_root_cert_sn' => $this->app->alipay_transfer_root_cert_sn ]; // 合并参数 $this->app->params = array_merge($this->app->params, $params); // 签名 $string_to_be_signed = $this->getSignContent($this->app->params); $this->app->params['sign'] = $this->sign($string_to_be_signed); $resp = $this->post(); $res = json_decode($resp, true); if ($res['alipay_fund_trans_uni_transfer_response']['code'] !== '10000') throw new ylPayException($res['alipay_fund_trans_uni_transfer_response']['sub_msg'], 400); return [ // 商户订单号 'out_biz_no' => $res['alipay_fund_trans_uni_transfer_response']['out_biz_no'], // 支付宝转账订单号 'order_id' => $res['alipay_fund_trans_uni_transfer_response']['order_id'], // 支付宝支付资金流水号 'pay_fund_order_id' => $res['alipay_fund_trans_uni_transfer_response']['pay_fund_order_id'], // 转账单据状态。 // SUCCESS:成功(对转账到银行卡的单据, 该状态可能变为退票[REFUND]状态); // FAIL:失败(具体失败原因请参见error_code以及fail_reason返回值); // DEALING:处理中; // REFUND:退票; 'status' => $res['alipay_fund_trans_uni_transfer_response']['status'], // trans_date 'trans_date' => $res['alipay_fund_trans_uni_transfer_response']['trans_date'] ]; } /** * 查询转账状态 * @return mixed * @throws ylPayException */ public function alipayFundTransCommonQuery() { // 添加公共参数 $params = [ 'app_id' => $this->app->app_id, 'method' => 'alipay.fund.trans.common.query', 'format' => 'json', 'timestamp' => date("Y-m-d H:i:s"), 'charset' => 'UTF-8', 'app_cert_sn' => $this->app->alipay_app_cert, 'alipay_root_cert_sn' => $this->app->alipay_transfer_root_cert_sn ]; // 合并参数 $this->app->params = array_merge($this->app->params, $params); // 签名 $string_to_be_signed = $this->getSignContent($this->app->params); $this->app->params['sign'] = $this->sign($string_to_be_signed); $resp = $this->post(); $res = json_decode($resp, true); if ($res['alipay_fund_trans_common_query_response']['code'] !== '10000') throw new ylPayException($res['alipay_fund_trans_common_query_response']['sub_msg'], 400); return $res['alipay_fund_trans_common_query_response']; } /** * 查询账号余额 * @return mixed * @throws ylPayException */ public function alipayFundAccountQuery() { // 添加公共参数 $params = [ 'app_id' => $this->app->app_id, 'method' => 'alipay.fund.account.query', 'format' => 'json', 'timestamp' => date("Y-m-d H:i:s"), 'charset' => 'UTF-8', 'app_cert_sn' => $this->app->alipay_app_cert, 'alipay_root_cert_sn' => $this->app->alipay_transfer_root_cert_sn, 'sign_type' => 'RSA2' ]; // 合并参数 $this->app->params = array_merge($this->app->params, $params); // 签名 $string_to_be_signed = $this->getSignContent($this->app->params); $this->app->params['sign'] = $this->sign($string_to_be_signed); $resp = $this->post(); $res = json_decode($resp, true); if ($res['alipay_fund_account_query_response']['code'] !== '10000') throw new ylPayException($res['alipay_fund_account_query_response']['sub_msg'], 400); return $res['alipay_fund_account_query_response']['available_amount']; } /** * 异步回调 校验app_id+校验seller_id+验签 * @return mixed * @throws ylPayException */ public function getAlipayNotifyResponse() { // 校验异步回调的app_id与设置的app_id是否一致 // if ($this->app->app_id != $this->app->params['app_id']) // throw new ylPayException("app_id不一致", 400); // 验签 $string_to_be_signed = $this->getSignContent(); // 将cert的支付宝公钥读取出来生成字符串赋值给alipay_rsa_public_key if (false === $this->verify($this->app->sign, $string_to_be_signed, $this->app->alipay_rsa_public_key, $this->app->sign_type)) throw new ylPayException("签验失败", 400); return $this->app->params; } } <file_sep><?php namespace ylPay\functions\PayPal; use ylPay\core\PayPalBaseClient; class Pay extends PayPalBaseClient { /** * 获取token * @return string */ public function getAccessToken(){ $this->base_url = $this->app->base_url . "/v1/oauth2/token"; $this->app->headers = [ "Content-type: application/x-www-form-urlencoded", 'Authorization: Basic ' . base64_encode($this->app->paypal_client . ":" . $this->app->paypal_secret) ]; $this->app->params = [ 'grant_type' => 'client_credentials' ]; $resp = $this->post(); $res = json_decode($resp, true); return $res['token_type'] . " " . $res['access_token']; } /** * 支付 * @return mixed */ public function checkoutOrders() { $this->base_url = $this->app->base_url . "/v2/checkout/orders"; $this->app->headers = [ "Content-type: application/json", 'Authorization: ' . $this->app->access_token ]; $resp = $this->post(); $res = json_decode($resp, true); $pay_url = null; if (isset($res["links"])) foreach ($res["links"] as $link) { if ($link["rel"] == "approve") { $pay_url = $link["href"]; break; } } return [$res['id'], $res['status'], $pay_url]; } /** * 查询订单状态 * @param $order_id * @return mixed * @throws \Exception */ public function showOrderDetails($order_id) { if (empty($order_id) || ! is_string($order_id)) throw new \Exception("invalid order id"); $this->base_url = $this->app->base_url . "/v2/checkout/orders/" . $order_id; $resp = $this->get(); $res = json_decode($resp, true); $purchase_units = $res['purchase_units'][0]; // intent = capture && status = created 订单创建尚未付款 // intent = capture && status = approved 订单创建已付款 // purchase_units['payments']['captures'][0]['status'] = REFUNDED 已退款 return [ $res['intent'], $res['status'], $purchase_units['reference_id'], isset($purchase_units['payments']['captures'][0]['id']) ? $purchase_units['payments']['captures'][0]['id'] : null, isset($purchase_units['amount']) ? $purchase_units['amount'] : null, isset($purchase_units['payee']) ? $purchase_units['payee'] : null, isset($purchase_units['shipping']) ? $purchase_units['shipping'] : null, isset($purchase_units['payments']) ? $purchase_units['payments'] : null ]; } /** * 修改订单信息 * @param $order_id * @return mixed * @throws \Exception */ public function updateOrder($order_id) { if (empty($order_id) || ! is_string($order_id)) throw new \Exception("invalid order id"); $this->base_url = $this->app->base_url . "/v2/checkout/orders/" . $order_id; $resp = $this->patch(); return json_decode($resp, true); } /** * 付款 必须创建订单+用户在paypal支付成功后 调用方可成功 * @param $order_id * @return array * @throws \Exception */ public function orderCapture($order_id) { if (empty($order_id) || ! is_string($order_id)) throw new \Exception("invalid order id"); $this->app->params = "{}"; $this->app->headers = [ "Content-type: application/json", 'Authorization: ' . $this->app->access_token ]; $this->base_url = $this->app->base_url . "/v2/checkout/orders/" . $order_id . "/capture"; $resp = $this->post(); $res = json_decode($resp, true); if (isset($res['name']) && $res['name'] == "UNPROCESSABLE_ENTITY" && isset($res['details']) && count($res['details']) > 0) { return [ null, null, $res['details'][0]['issue'] ]; } $purchase_units = $res['purchase_units'][0]; return [ $purchase_units['reference_id'], $purchase_units['payments']['captures'][0]['id'], $purchase_units['payments']['captures'][0]['status'] ]; } /** * 退款 * @param $order_id * @return mixed * @throws \Exception */ public function refund($order_id) { if (empty($order_id) || ! is_string($order_id)) throw new \Exception("invalid order id"); $this->base_url = $this->app->base_url . "/v2/payments/captures/" . $order_id . "/refund"; // $this->app->params = "{}"; $this->app->headers = [ "Content-type: application/json", 'Authorization: ' . $this->app->access_token ]; $resp = $this->post(); return json_decode($resp, true); } }<file_sep><?php namespace ylPay\core; class AliPayBaseClient { protected $app; public $base_url = 'http://gw.open.1688.com/openapi/'; public $url_info; protected $postData; public $res_url; public $mode = 'production'; public function __construct(Container $app) { $this->app = $app; } public function setMode($mode = '') { if (!empty($mode)) $this->mode = $mode; } private function characet($data, $targetCharset) { if (!empty($data)) { $fileType = 'UTF-8'; if (strcasecmp($fileType, $targetCharset) != 0) { $data = mb_convert_encoding($data, $targetCharset, $fileType); // $data = iconv($fileType, $targetCharset.'//IGNORE', $data); } } return $data; } /** * get 请求方式 * @return mixed * @throws ylPayException */ public function get(){ // $this->sign(); $file = $this->curlRequest($this->res_url,''); return json_decode($file,true); } /** * post 请求方式 * @return mixed * @throws ylPayException */ public function post(){ return $this->curlRequest(! empty($this->app->base_url) ? $this->app->base_url : $this->base_url, $this->app->params); } /** * 设置地址 * @param $api_name * @return $this */ public function setApi($api_name){ $this->url_info = $api_name; return $this; } /** * curl 请求 * @param $url * @param $post_fields * @param string $method * @return bool|string * @throws ylPayException */ public function curlRequest($url, $post_fields) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $postBodyString = ""; $encodeArray = Array(); $postMultipart = false; if (is_array($post_fields) && 0 < count($post_fields)) { foreach ($post_fields as $k => $v) { if ("@" != substr($v, 0, 1)) //判断是不是文件上传 { $postBodyString .= "$k=" . urlencode($this->characet($v, $this->app->charset)) . "&"; $encodeArray[$k] = $this->characet($v, $this->app->charset); } else //文件上传用multipart/form-data,否则用www-form-urlencoded { $postMultipart = true; $encodeArray[$k] = new \CURLFile(substr($v, 1)); } } unset ($k, $v); curl_setopt($ch, CURLOPT_POST, true); if ($postMultipart) { curl_setopt($ch, CURLOPT_POSTFIELDS, $encodeArray); } else { curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1)); } } if (!$postMultipart) { $headers = array('content-type: application/x-www-form-urlencoded;charset=' . $this->app->charset); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } $response = curl_exec($ch); if (curl_errno($ch)) { throw new ylPayException(curl_error($ch), 0); } else { $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (200 !== $httpStatusCode) { throw new ylPayException($response, $httpStatusCode); } } curl_close($ch); return $response; } /** * 检查字符串是否为空 * @param $value * @return bool */ public function checkEmpty($value) { if (!isset($value)) return true; if ($value === null) return true; if (trim($value) === "") return true; return false; } /** * 生成待签名字符串 * @return string */ public function getSignContent() { ksort($this->app->params); $string_to_be_signed = ""; $i = 0; foreach ($this->app->params as $k => $v) { if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) { if ($i == 0) { $string_to_be_signed .= "$k" . "=" . "$v"; } else { $string_to_be_signed .= "&" . "$k" . "=" . "$v"; } $i++; } } unset ($k, $v); return $string_to_be_signed; } /** * 签名 * @param string $data 待签名的数据 * @return string * @throws ylPayException */ public function sign($data) { try { if ($this->checkEmpty($this->app->alipay_rsa_private_key_path)) { $pri_key = $this->app->alipay_rsa_private_key; $res = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($pri_key, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----"; } else { $pri_key = file_get_contents($this->app->alipay_rsa_private_key_path); $res = openssl_get_privatekey($pri_key); } if ("RSA2" == $this->app->params['sign_type']) { openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256); } else { openssl_sign($data, $sign, $res); } if (!$this->checkEmpty($this->app->alipay_rsa_private_key_path)) { openssl_free_key($res); } $sign = base64_encode($sign); return $sign; } catch (\Exception $e) { throw new ylPayException('您使用的私钥格式错误,请检查RSA私钥配置', 400); } } /** * 验签 * @param $signature * @param $string_to_be_signed * @param string $rsa_public_key_path * @param string $sign_type * @return bool * @throws ylPayException */ protected function verify($signature, $string_to_be_signed, $rsa_public_key_path = '', $sign_type = 'RSA') { try { if ($this->checkEmpty($rsa_public_key_path) || ! file_exists($rsa_public_key_path)) { $pubKey = $this->app->alipay_rsa_public_key; $res = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($pubKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----"; } else { //读取公钥文件 $pubKey = file_get_contents($rsa_public_key_path); //转换为openssl格式密钥 $res = openssl_get_publickey($pubKey); } //调用openssl内置方法验签,返回bool值 if ("RSA2" == $sign_type) { $result = (openssl_verify($string_to_be_signed, base64_decode($signature), $res, OPENSSL_ALGO_SHA256) === 1); } else { $result = (openssl_verify($string_to_be_signed, base64_decode($signature), $res) === 1); } if (!$this->checkEmpty($rsa_public_key_path) && ! is_string($res)) { //释放资源 openssl_free_key($res); } return $result; } catch (\Exception $e) { throw new ylPayException('支付宝RSA公钥错误。请检查公钥文件格式是否正确', 400); } } /** * 填充算法 * @param string $source * @return string */ protected function addPKCS7Padding($source) { $source = trim($source); $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $pad = $block - (strlen($source) % $block); if ($pad <= $block) { $char = chr($pad); $source .= str_repeat($char, $pad); } return $source; } } <file_sep><?php namespace ylPay\provider; use ylPay\core\Container; use ylPay\functions\Alipay\Transfer\fundTrans; use ylPay\interfaces\Provider; /** * 支付宝转账 * Class AlipayTransferProvider * @package ylPay\provider */ class AlipayTransferProvider implements Provider { public function serviceProvider(Container $container) { // TODO: Implement serviceProvider() method. $container['alipay_transfer'] = function ($container){ return new fundTrans($container); }; } } <file_sep><?php namespace ylPay\functions\Alipay; use ylPay\core\AliPayBaseClient; use ylPay\core\ylPayException; /** * Class Pay * @package ylPay\functions\Alipay */ class Pay extends AliPayBaseClient { /** * wap支付 * @return string * @throws ylPayException */ public function alipayTradeWapPay() { // 添加公共参数 $params = [ 'app_id' => $this->app->app_id, 'method' => 'alipay.trade.wap.pay', 'format' => 'json', 'timestamp' => date("Y-m-d H:i:s"), 'charset' => 'UTF-8' ]; // 合并参数 $this->app->params = array_merge($this->app->params, $params); // 签名 $string_to_be_signed = $this->getSignContent(); $this->app->params['sign'] = $this->sign($string_to_be_signed); return $this->app->base_url . '?' . http_build_query($this->app->params); } /** * 支付宝app支付 * @return string * @throws ylPayException */ public function alipayTradeAppPay() { // 添加公共参数 $params = [ 'app_id' => $this->app->app_id, 'method' => 'alipay.trade.app.pay', 'format' => 'json', 'timestamp' => date("Y-m-d H:i:s"), 'charset' => 'UTF-8' ]; // 合并参数 $this->app->params = array_merge($this->app->params, $params); // 签名 $string_to_be_signed = $this->getSignContent(); $this->app->params['sign'] = $this->sign($string_to_be_signed); return http_build_query($this->app->params); } /** * 异步回调 校验app_id+校验seller_id+验签 * @return mixed * @throws ylPayException */ public function getAlipayNotifyResponse() { // 校验异步回调的app_id与设置的app_id是否一致 if ($this->app->app_id != $this->app->params['app_id']) throw new ylPayException("app_id不一致", 400); // 校验异步回调的seller_id与设置的seller_id是否一致 if ($this->app->alipay_seller_id != $this->app->params['seller_id']) throw new ylPayException("非法seller_id", 400); // 验签 $string_to_be_signed = $this->getSignContent(); if (false === $this->verify($this->app->sign, $string_to_be_signed, $this->app->alipay_rsa_public_key_path, $this->app->sign_type)) throw new ylPayException("签验失败", 400); return $this->app->params; } public function alipayTradeClose() { return $this; } } <file_sep><?php namespace ylPay; use ylPay\core\ContainerBase; use ylPay\provider\AlipayProvider; use ylPay\provider\AlipayTransferProvider; use ylPay\provider\PayPalProvider; class ylPay extends ContainerBase { public function __construct($parameters = []) { parent::__construct($parameters); } protected $provider = [ AlipayProvider::class, AlipayTransferProvider::class, PayPalProvider::class ]; } <file_sep><?php namespace ylPay\provider; use ylPay\core\Container; use ylPay\functions\PayPal\Pay; use ylPay\interfaces\Provider; class PayPalProvider implements Provider { public function serviceProvider(Container $container) { // TODO: Implement serviceProvider() method. $container['paypal'] = function ($container){ return new Pay($container); }; } }<file_sep><?php namespace ylPay\core; /** * Class ContainerBase * @package ylAlibaba\core */ class ContainerBase extends Container { protected $provider = []; public $params = []; public $headers = []; public $base_url; public $sign = ''; public $sign_type = ''; public $app_id = ''; public $alipay_rsa_private_key = ''; public $alipay_rsa_private_key_path = ''; public $alipay_rsa_public_key = ''; public $alipay_rsa_public_key_path = ''; public $alipay_seller_id = ''; public $charset = 'utf-8'; // public $alipay_version = "1.0"; // public $alipay_format = 'json'; // public $alipay_sign_type = 'RSA2'; // public $alipay_timestamp = ''; // public $alipay_sdk = "alipay-sdk-php-20200415"; // public $alipay_charset = 'utf-8'; public $alipay_transfer_rsa_private_key = ''; public $alipay_transfer_rsa_public_key = ''; public $alipay_app_cert = ''; public $alipay_transfer_cert_sn = ''; public $alipay_transfer_root_cert_sn = ''; public $alipay_root_cert_content = ''; public $app_secret = ''; public $access_token = ''; /** * paypal 参数 * @var string */ public $paypal_client = ""; public $paypal_secret = ""; /** * @param string $paypal_client */ public function setPaypalClient(string $paypal_client) { $this->paypal_client = $paypal_client; } /** * @param string $paypal_secret */ public function setPaypalSecret(string $paypal_secret) { $this->paypal_secret = $paypal_secret; } /** * @param string $access_token */ public function setAccessToken(string $access_token) { $this->access_token = $access_token; } public function __construct($params =array()) { $this->params = $params; $provider_callback = function ($provider) { $obj = new $provider; $this->serviceRegister($obj); }; //注册 array_walk($this->provider, $provider_callback); } public function __get($id) { return $this->offsetGet($id); } /** * @param mixed $base_url */ public function setBaseUrl($base_url) { $this->base_url = $base_url; } /** * @param string $app_id */ public function setAppId($app_id) { $this->app_id = $app_id; } /** * @param string $alipay_rsa_private_key */ public function setAlipayRsaPrivateKey($alipay_rsa_private_key) { $this->alipay_rsa_private_key = $alipay_rsa_private_key; } /** * @param string $alipay_rsa_public_key */ public function setAlipayRsaPublicKey($alipay_rsa_public_key) { $this->alipay_rsa_public_key = $alipay_rsa_public_key; } /** * @param string $alipay_rsa_private_key_path */ public function setAlipayRsaPrivateKeyPath($alipay_rsa_private_key_path) { $this->alipay_rsa_private_key_path = $alipay_rsa_private_key_path; } /** * @param string $alipay_rsa_public_key_path */ public function setAlipayRsaPublicKeyPath($alipay_rsa_public_key_path) { $this->alipay_rsa_public_key_path = $alipay_rsa_public_key_path; } /** * @param string $sign */ public function setSign($sign) { $this->sign = $sign; } /** * @param string $sign_type */ public function setSignType($sign_type) { $this->sign_type = $sign_type; } /** * @param string $alipay_seller_id */ public function setAlipaySellerId($alipay_seller_id) { $this->alipay_seller_id = $alipay_seller_id; } /* ------------------ 资金类接口所需的方法 ----------------------- */ protected function array2string($array) { $string = []; if ($array && is_array($array)) { foreach ($array as $key => $value) { $string[] = $key . '=' . $value; } } return implode(',', $string); } /** * 从证书中提取公钥 * @param $cert * @return mixed */ public function setTransferPublicKey($certPath) { $cert = file_get_contents($certPath); $ssl = openssl_x509_parse($cert); $this->alipay_transfer_cert_sn = md5(self::array2string(array_reverse($ssl['issuer'])) . $ssl['serialNumber']); } /** * 设置应用公钥 * @param $alipay_app_cert * @return string|string[] */ public function setAlipayAppCertSn($alipay_app_cert) { $cert = file_get_contents($alipay_app_cert); $ssl = openssl_x509_parse($cert); $this->alipay_app_cert = md5($this->array2string(array_reverse($ssl['issuer'])) . $ssl['serialNumber']); } /** * 设置根证书 * @param string $alipay_transfer_root_cert_sn */ public function setAlipayTransferRootCertSn($alipay_transfer_root_cert_sn) { $cert = file_get_contents($alipay_transfer_root_cert_sn); $this->alipay_root_cert_content = $cert; $array = explode("-----END CERTIFICATE-----", $cert); $this->alipay_transfer_root_cert_sn = null; for ($i = 0; $i < count($array) - 1; $i++) { $ssl[$i] = openssl_x509_parse($array[$i] . "-----END CERTIFICATE-----"); if(strpos($ssl[$i]['serialNumber'],'0x') === 0){ $ssl[$i]['serialNumber'] = $this->hex2dec($ssl[$i]['serialNumber']); } if ($ssl[$i]['signatureTypeLN'] == "sha1WithRSAEncryption" || $ssl[$i]['signatureTypeLN'] == "sha256WithRSAEncryption") { if ($this->alipay_transfer_root_cert_sn == null) { $this->alipay_transfer_root_cert_sn = md5($this->array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']); } else { $this->alipay_transfer_root_cert_sn = $this->alipay_transfer_root_cert_sn . "_" . md5($this->array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']); } } } } /** * 0x转高精度数字 * @param $hex * @return int|string */ protected function hex2dec($hex) { $dec = 0; $len = strlen($hex); for ($i = 1; $i <= $len; $i++) { $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i)))); } return round($dec,0); } } <file_sep><?php namespace ylPay\core; use Exception; class ylPayException extends Exception { } <file_sep><?php namespace ylPay\core; class PayPalBaseClient { protected $app; public $base_url = 'https://api-m.sandbox.paypal.com'; public $client = ""; public $secret = ""; public function __construct(Container $app) { $this->app = $app; // $this->log_path = } public function get() { return $this->curlRequest($this->base_url, "GET", '', $this->app->headers); } public function post() { var_dump(realpath(dirname(__FILE__))); return $this->curlRequest($this->base_url, "POST", $this->app->params, $this->app->headers); } public function patch() { return $this->curlRequest($this->base_url, "PATCH", $this->app->params, $this->app->headers); } /** * curl 请求 * @param $url * @param string $methods * @param string $post_fields * @param array $headers * @return bool|string * @throws ylPayException */ public function curlRequest($url, $method = "GET", $post_fields = "", $headers = []) { if (empty($url)) throw new \Exception("baseUrl不能为空"); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); $flag = 200; if ($method == 'PATCH') { array_push($headers, 'X-HTTP-Method-Override: ' . $method); $flag = 204; } else if ($method == 'POST') $flag = 201; curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); if (is_array($post_fields) && 0 < count($post_fields)) curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields)); else if (is_string($post_fields) && null !== json_decode($post_fields, true)) { curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); array_push($headers, 'Content-type: application/json'); } if (!empty($headers)) curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); $err_code = curl_errno($ch); if ($err_code) { throw new ylPayException($err_code, 0); } else { $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); var_dump($flag, $httpStatusCode); if ($httpStatusCode !== $flag) { // 日志记录错误信息 } // if ($httpStatusCode !== $flag) { // throw new ylPayException($response, $httpStatusCode); // } } curl_close($ch); return $response; } }<file_sep><?php namespace ylPay\provider; use ylPay\core\Container; use ylPay\functions\Alipay\Pay; use ylPay\interfaces\Provider; class AlipayProvider implements Provider { public function serviceProvider(Container $container) { // TODO: Implement serviceProvider() method. $container['alipay'] = function ($container){ return new Pay($container); }; } }
777ec9b26fab20881b4c7f3a2617a444b849b2f0
[ "PHP" ]
12
PHP
weaponhsu/ylPayOpen
3ac9646140fdb52f58d91d2d28a0b963b2c1b91b
dd872456d9bd7593a5dcccf2e310e9834e102fae
refs/heads/master
<file_sep># Golang skeleton for speedrun ## Useage 1. Clone repo 1. Change `main.go` line 25~29 (`TODO : Something code`). 1. Write test and response for `main_test.go` line 36~39 (`TODO: Add test cases.`). 1. Ready! Let's run `go test` ## Creater / Licenser [0Delta](https://github.com/0Delta) ## License These codes are licensed under CC0. [![CC0](http://i.creativecommons.org/p/zero/1.0/88x31.png "CC0")](http://creativecommons.org/publicdomain/zero/1.0/deed.ja) <file_sep>package main import ( "bufio" "fmt" "os" "strconv" "strings" ) var sc = bufio.NewScanner(os.Stdin) func getLine() string { if len(os.Args) < 2 { sc.Scan() return sc.Text() } return os.Args[len(os.Args)-1] } func main() { inp := getLine() sinp := strings.Split(inp, ",") // TODO : Something code sum := 0 for _, n := range sinp { m, _ := strconv.Atoi(n) sum += m } fmt.Print(sum) }
2609c5777894fcf3b537aa2c7d5aff0265cb461f
[ "Markdown", "Go" ]
2
Markdown
0Delta/GolangSkeletonForSpeedrun
9f64933c417e44fc5590de08460cd13ac595870d
a266d896fe8f5ad2a7ec27b186a82c0c5c3bb8be
refs/heads/master
<file_sep>module Plivo module XML class Speak < Element @nestables = [] @valid_attributes = %w[voice language loop] def initialize(body, attributes = {}) if !body raise PlivoXMLError, 'No text set for Speak' else body = HTMLEntities.new(:html4).encode(body, :decimal) end super(body, attributes) end end end end
2c4c2c0e0e539e919ae9e173f8e2013905e550ad
[ "Ruby" ]
1
Ruby
kunal-plivo/plivo-ruby
b1bc2a768616af94e35aefb9f13c23d388f73dc7
637cf081536e3a71bfb2a9cc79596d8572e5b1a2