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># <NAME> # Primer Ejercicio # 1. En una lista se reciben las notas de n estudiantes de un curso. Escriba una funci´on # notas(lista) que, considerando que la nota de aprobaci´on sea 70, obtenga en una lista: # (a) Cu´antos estudiantes aprobaron el curso. # (b) Cu´antos estudiantes reprobaron. # (c) El promedio de notas. def notas(lista): promedio = 0 cantidad = 0 aprobados = 0 aplazados = 0 for i in lista: if i < 70: aplazados += 1 promedio += i cantidad +=1 else: aprobados += 1 promedio += i cantidad += 1 return [round(promedio/cantidad),aprobados, aplazados] print(notas([10, 20, 25, 25, 30, 40, 100])) # Segundo Ejercicio # 2. Escriba una funci´on triangulo(lineas) que genere un tri´angulo de aster´ıscos con la siguiente forma: # ∗ # ∗ ∗ # ∗ ∗ ∗ # ∗ ∗ ∗ ∗ # ∗ ∗ ∗ ∗ ∗ # ∗ ∗ ∗ ∗ ∗ ∗ # donde el argumento de entrada lineas corresponda a la cantidad de l´ıneas que se desea # imprimir del tri´angulo. def triangulo(lineas): for i in range(lineas): print(" " * (lineas - i -1)+"*" * (2 * i + 1)) triangulo(6) <file_sep># 8. Utilizando el ciclo while, implemente una funci´on para computar la siguiente sumatoria def sumatoria_while(N, x): resultado = 0 n = -7 while(n <= N): resultado +=(x**n)/(n+x) # incrementar el indice n +=1 print("El resultado de la sumatoria es", resultado) sumatoria_while(5, 100) # 9. Utilizando el ciclo for, realice la multiplicacion de 2 vectores (listas de una dimension). # :c # 10. Utilizando el ciclo for, realice la suma de la diagonal y la antidiagonal de una matriz # cuadrada, e imprima ambos resultados. # :c # 11. Utilizando cualquier metodo iterativo, retorne la posicion del valor mas alto dentro de una matriz de numeros enteros. # Retorne el resultado utilizando la notacion # f ila, columna. def mayor_matriz(matriz): elemento_mayor = 0 # **** fila_mayor = 0 columna_mayor = 0 for fila in range(len(matriz)): for columna in range(len(matriz[fila])): # Evaluar si el elemento es mayor a elemento_mayor if matriz[fila][columna] > elemento_mayor: elemento_mayor = matriz[fila][columna] fila_mayor = fila columna_mayor = columna print("El elemento mayor es {} y esta en la posicion ({}, {})". format(elemento_mayor, fila_mayor, columna_mayor)) mayor_matriz([[1 ,2 , 3], [4, 5, 6],[7, 8, 9]]) # 12. Utilizando cualquier metodo iterativo, hacer una funcion que multiplique los elementos # de una lista. # :c # 13. Utilizando recursividad, hacer una funcion que reciba una lista de numeros y obtenga # otra solo con los numeros pares. # :c <file_sep>import tkinter ventana = tkinter.Tk() ventana.mainloop()<file_sep>#Tarea de recursividad de cola #<NAME>, <NAME> #1Escriba una funcion que reciba un numero (que debe ser entero) y retorne dos listas, #una con los dıgitos entre 0 y 4 y otra con los dıgitos entre 5 y 9. def lista_split(num): if(isinstance(num, int)): return lista_split_aux(num, [], []) else: print("El numero debe ser entero") def lista_split_aux(num, lista_0_4, lista_5_9): if (num==0): return lista_0_4, lista_5_9 else: digito = num%10 if (digito <=4): lista_0_4.append(digito) else: lista_5_9.append(digito) return lista_split_aux(num//10, lista_0_4, lista_5_9) #print(lista_split(123456789)) #2. Construya una funcion de nombre split(lista). Esta funcion toma una lista y la divide #en sublistas usando como punto de corte cada vez que aparezca un cero. def split(lista): if (isinstance(lista, list)): return split_aux(lista, [], []) else: return "Lista no valida" def split_aux(listas, lista_aux, resultado): if(listas==[]): resultado.append(lista_aux) return resultado elif(listas[0]!=0): lista_aux.append(listas[0]) return split_aux(listas[1:], lista_aux, resultado) else: resultado.append(lista_aux) return split_aux(listas[1:], [], resultado) #print(split([1,2,3,0,4,5,6,0,7,8,9])) #3. Escriba una funcion cambie todos(num) que reciba una numero entero y sustituya #todos los valores que aparezcan 2 o mas veces por un cero. def cambie_todos(num): if(isinstance(num, int)): return cambie_todos_aux(num, repetidos_aux(num, [], []), 0, 0) else: return "Introduzca numeros validos" def repetidos_aux(num, digitos, resultado): if(num == 0): if(digitos == []): return resultado elif(digitos[0] in digitos [1:]): if(digitos[0] in resultado): return repetidos_aux(num, digitos[1:], resultado) else: return repetidos_aux(num, digitos[1:], resultado + [digitos[0]]) else: return repetidos_aux(num, digitos[1:], resultado) else: digitos.append(num%10) return repetidos_aux(num//10, digitos, resultado) def cambie_todos_aux(num, contar, repetidos, resultado): if(num == 0): return resultado elif(num%10 in repetidos): return cambie_todos_aux(num//10, repetidos, contar +1, resultado) else: return cambie_todos_aux(num//10, repetidos, contar +1, resultado + (num%10)*10**contar) #print(cambie_todos(1223445677889)) #4. Escriba una funcion coincide(lista) que recibe una lista de numeros enteros e indique #si algun elemento de la lista coincide con la suma de todos los que le preceden: def coincide(lista): if isinstance(lista, list): return coincide_aux(lista, lista[0], 1) else: return -1 def coincide_aux(lista, r, i): print(r) if i == len(lista): return False elif r == lista[i]: return True else: r += lista[i] return coincide_aux(lista, r, i+1) #print(coincide([2,3,4,9,14])) <file_sep>#Se intentara adapatar el proyecto de diferentes puntos de vista import
cee845f473eedd8693b461b02f6d250e7d5339c9
[ "Python" ]
5
Python
Joseph1103/Proyecto_Taller
c185c841dc69f53eaf9d085e00c0d77a64f7d3ec
04cd2672b608f54c6eea9960a770b68dc1a2dbd3
refs/heads/master
<file_sep>#include"pthread_pool.h" static void*workpthread(void*arg); static void* adjustpthread(void*arg); pthread_pool_t *pthreadpool_create() { pthread_pool_t *pool=(pthread_pool_t *)malloc(sizeof(pthread_pool_t)); do{ if(pool==NULL) { perror("malloc"); break; } pool->queue=(task_t*)malloc(sizeof(task_t)*MAX_QUEUE); if(pool->queue==NULL) break; memset(pool->queue,0,sizeof(task_t)*MAX_QUEUE); pool->tid=(pthread_t*)malloc(sizeof(pthread_t)*MAX_PTHREAD); if(pool->tid==NULL) break; memset(pool->tid,0,sizeof(pthread_t)*MAX_PTHREAD); (*(int*)&pool->pthread_max)=MAX_PTHREAD; (*(int*)&pool->pthread_min)=MIN_PTHREAD; (*(int*)&pool->creat_count)=CREAT_COUNT; (*(int*)&pool->destory_count)=DESTORY_COUNT; pool->alive_count=MIN_PTHREAD; pool->work_count=0; pool->exit_count=0; (*(int*)&pool->queue_capacity)=MAX_QUEUE; pool->queue_size=0; pool->head=0; pool->tail=0; pool->shutdown=FALSE; if(pthread_mutex_init(&pool->lock,NULL)!=0|| pthread_mutex_init(&pool->work_lock,NULL)!=0|| pthread_cond_init(&pool->queue_not_full,NULL)!=0|| pthread_cond_init(&pool->queue_not_empty,NULL)!=0) { perror("pthread_init"); break; } int i; for( i=0;i<MIN_PTHREAD;i++) { pthread_create(&pool->tid[i],NULL,workpthread,pool); pthread_detach(pool->tid[i]); } pthread_create(&pool->adjusttid,NULL,adjustpthread,pool); pthread_detach(pool->adjusttid); return pool; //相当于goto语句 }while(0); pthreadpool_destory(pool); return NULL; } //工作线程的工作流程 void* workpthread(void*arg) { pthread_pool_t *pool=(pthread_pool_t*)arg; for(;;) { pthread_mutex_lock(&pool->lock); while(pool->queue_size==0&&!pool->shutdown) { printf("thread 0x%x is waiting\n",(unsigned int)pthread_self()); pthread_cond_wait(&pool->queue_not_empty,&pool->lock); if(pool->shutdown) { printf("thread 0x%x is exit\n",(unsigned int)pthread_self()); pthread_mutex_unlock(&pool->lock); pthread_exit(NULL); } ////如果有要销毁的线程,且当前存活的线程数大于最小的线程的存活数,让线程自己退出 if(pool->exit_count>0) { if(pool->alive_count>pool->pthread_min) { printf("thread 0x%x is exit\n",(unsigned int)pthread_self()); --pool->alive_count; //必须释放掉自己的锁 pthread_mutex_unlock(&pool->lock); pthread_exit(NULL); } } } task_t ta=pool->queue[pool->head]; pool->head=(pool->head+1)%pool->queue_capacity; --pool->queue_size; pthread_mutex_unlock(&pool->lock); /////////忙碌线程加1 pthread_mutex_lock(&pool->work_lock); ++pool->work_count; pthread_mutex_unlock(&pool->work_lock); ////////处理任务 printf("thread 0x%x is working\n",(unsigned int)pthread_self()); (*ta.function)(ta.arg); ////////通知添加任务的线程,队列已经不为满了 pthread_cond_broadcast(&pool->queue_not_full); /////////忙碌线程减1 pthread_mutex_lock(&pool->work_lock); --pool->work_count; pthread_mutex_unlock(&pool->work_lock); } pthread_exit(NULL); return NULL; } //管理线程的流程 void* adjustpthread(void*arg) { pthread_pool_t *pool=(pthread_pool_t*)arg; for(;;) { pthread_mutex_lock(&pool->lock); if(pool->shutdown) { pthread_mutex_unlock(&pool->lock); break; } int alive_count=pool->alive_count; int work_count=pool->alive_count; int queue_size=pool->queue_size; pthread_mutex_unlock(&pool->lock); if(queue_size>alive_count&&alive_count<pool->pthread_max) { int i=0; int j=0; pthread_mutex_lock(&pool->lock); for(i=0;pool->alive_count<pool->pthread_max&& j<pool->creat_count&& i<pool->pthread_max;i++) { if(pool->tid[i]==0||pthread_kill(pool->tid[i],0)) { pthread_create(&pool->tid[i],NULL,workpthread,(void*)pool); pthread_detach(pool->tid[i]); ++pool->alive_count; ++j; } } pthread_mutex_unlock(&pool->lock); } if(alive_count>pool->pthread_min&&3*pool->work_count<pool->alive_count) { pthread_mutex_lock(&pool->lock); pool->exit_count=pool->destory_count; pthread_mutex_unlock(&pool->lock); int i=0; for(i=0;i<pool->destory_count;i++) { pthread_cond_signal(&pool->queue_not_empty); } } } } //往线程池添加任务 int pthreadpool_addtask(pthread_pool_t *pool,task_t ta) { pthread_mutex_lock(&pool->lock); while(pool->queue_size==pool->queue_capacity) { printf("addtask thread 0x%x is waiting\n",(unsigned int)pthread_self()); pthread_cond_wait(&pool->queue_not_full,&pool->lock); } if(pool->shutdown) { pthread_mutex_unlock(&pool->lock); // pthread_exit(NULL); return -1; } printf("addtaskthread 0x%x is addtask\n",(unsigned int)pthread_self()); //free((pool->queue[pool->tail]).arg); (pool->queue[pool->tail]).arg=ta.arg; (pool->queue[pool->tail]).function=ta.function; pool->tail=(pool->tail+1)%pool->queue_capacity; ++pool->queue_size; pthread_mutex_unlock(&pool->lock); pthread_cond_signal(&pool->queue_not_empty); } int pthreadpool_destory(pthread_pool_t *pool) { if(pool==NULL) return -1; ///删除管理线程 pool->shutdown=TRUE; int i=0; for(i=0;i<pool->alive_count;++i) pthread_cond_broadcast(&pool->queue_not_empty); free(pool->queue); free(pool->tid); if(pool->tid) { pthread_mutex_lock(&pool->lock); pthread_mutex_destroy(&pool->lock); pthread_mutex_lock(&pool->work_lock); pthread_mutex_destroy(&pool->work_lock); pthread_cond_destroy(&pool->queue_not_full); pthread_cond_destroy(&pool->queue_not_empty); } free(pool); return 0; } <file_sep>test:test.c pthread_pool.c gcc -o$@ $^ -lpthread .PHONY:clean clean: rm -r test <file_sep>/************************************************************************* > File Name: out.c > Author: ma6174 > Mail: <EMAIL> > Created Time: 2018年07月05日 星期四 15时48分41秒 ************************************************************************/ #include<stdio.h> #include<string.h> #include<unistd.h> #include<stdlib.h> #include<fcntl.h> int main() { // int fd=open("error",O_WRONLY|O_CREAT,0666); char method[100]; // dup2(2,1); // write(fd,"call out.cgi",12); strcpy(method,getenv("METHOD")); // write(fd,method,strlen(method)); char buf[1024]={ 0 }; int first; int second; if(strcasecmp(method,"GET")==0) { perror("GET"); strcpy(buf,getenv("QUERY_STRING")); // write(fd,buf,strlen(buf)); } else { int count=atoi(getenv("CONTENT_LENGTH")); perror("%d",count); read(0,buf,count); } sscanf(buf,"first=%d&second=%d",&first,&second); int finally=first+second; printf("<html>\n<body>\n<p>first+second=%d\n</p>\n</body>\n</html>\n",finally); perror("cgi finally"); // write(fd,"cgi finally",11); // close(fd); } <file_sep>#include"pthread_pool.h" #include"handsocket.h" #define MAX_EVENTS 1024 int startup(int port) { int sock=socket(AF_INET,SOCK_STREAM,0); if(sock<0) { perror("socket"); } int opt=1; setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); struct sockaddr_in serveraddr; serveraddr.sin_family=AF_INET; serveraddr.sin_port=htons(port); serveraddr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sock,(struct sockaddr*)&serveraddr,sizeof(serveraddr))<0) { perror("bind"); exit(3); } if(listen(sock,5)<0) { perror("listen"); exit(4); } return sock; } static pthread_pool_t*pool=NULL; void handler(int arg) { pthreadpool_destory(pool); printf("process exit\n"); exit(0); } int main(int argc,char*argv[]) { // if(argc!=2) // { // printf("argc=%d\n",argc); // printf("usage:[%s] [%s]\n",argv[0],"port"); // // exit(1); // } struct sigaction act; act.sa_handler=handler; sigemptyset(&act.sa_mask); act.sa_flags=0; sigaction(SIGINT,&act,NULL); //创建一个监听套接字 int listen_socket=startup(9999); ////创建一个线程池 pool=pthreadpool_create(); //任务封装 task_t task; task.function=handle; struct sockaddr_in clientaddr; size_t len =sizeof(clientaddr); //////创建一个epool句柄 // int epfd=epoll_create(MAX_EVENTS); // struct epoll_event event; // event.events=EPOLLIN; // event.data.fd=listen_socket; // struct epoll_event retevents[MAX_EVENTS]; // epoll_ctl(epfd,EPOLL_CTL_ADD,listen_socket,&event); // for(;;){ // int count = epoll_wait(epfd,retevents,MAX_EVENTS,-1); // int i=0; // printf("read_count=%d\n",count); // for(;i<count;i++) // { // if(!retevents[i].events&EPOLLIN) // continue; // if(retevents[i].data.fd==listen_socket) // { // int client_socket=accept(listen_socket,(struct sockaddr*)&clientaddr,&len); // event.data.fd=client_socket; // event.events=EPOLLIN; // printf("Get a fd %d\n",retevents[i].data.fd); // epoll_ctl(epfd,EPOLL_CTL_ADD,client_socket,&event); // } // else // { // server_t *s=(server_t*)malloc(sizeof(server_t)); // s->efd=epfd; // s->socket=retevents[i].data.fd; // task.arg=(void*)s; // pthreadpool_addtask(pool,task); // printf("add a fd %d\n",retevents[i].data.fd); // } // } // // } for(;;) { int client_socket=accept(listen_socket,(struct sockaddr*)&clientaddr,&len); task.arg=(void*)client_socket; printf("Get a fd %d\n",client_socket); pthreadpool_addtask(pool,task); //printf("Get a fd %d\n",client_socket); //pthread_t tid; //pthread_create(&tid,NULL,handle,(void*)client_socket); //pthread_detach(tid);pthreadpool_addtask(pool,task); } return 0; } <file_sep>#ifndef HTTP_SERVER_H_ #define HTTP_SERVER_H_ #include<stdlib.h> #include<stdio.h> #include<unistd.h> #include<string.h> #include<pthread.h> #include<fcntl.h> #include<sys/socket.h> #include<sys/types.h> #include<netinet/in.h> #include<sys/stat.h> #include<sys/sendfile.h> #include<signal.h> #include<sys/epoll.h> #define MAX 1024 typedef struct { int efd; int socket; }server_t; int Getline(int socket,char*buf,int size); void clear_sock(int sock); void bad_request(const char*path,const char*errorstr,int sock); int excu_cgi(int socket,char*method,char*path,char*query_string); int echo_www(int sock,char*path,int size); void*handle(void*arg); #endif <file_sep>#include"handsocket.h" int Getline(int socket,char*buf,int size) { char c=0; int i=0; while(c!='\n'&&i<size-1) { if(recv(socket,&c,1,0)>0) { if(c=='\r') { if(recv(socket,&c,1,MSG_PEEK)>0) { if(c=='\n') recv(socket,&c,1,0); else c='\n'; } } buf[i++]=c; } else break; } buf[i]=0; printf("%s\n",buf); return i; } void clear_sock(int sock) { char buf[MAX]; for(;;) { int size=Getline(sock,buf,MAX-1); if(size==1&&strcmp(buf,"\n")==0) break; } // printf("clean finish\n"); } void bad_request(const char*path,const char*errorstr,int sock) { printf("call bad_request \n"); int fd=open(path,O_RDONLY); printf("path=%s\n",path); if(fd<0) { printf("open failer\n"); perror("open"); return ; } //响应报头加空行 // printf("响应报头加空行\n"); char line[MAX]; sprintf(line,"%s",errorstr); send(sock,line,strlen(line),0); const char*content_type="Content-Type:text/html;charset=utf-8\r\n"; send(sock,content_type,strlen(content_type),0); send(sock,"\r\n",2,0); struct stat st; if(fstat(fd,&st)<0) { printf("fstat failer \n"); perror("fstat"); return ; } int size =st.st_size; printf("%s size=%d\n",path,size); sendfile(sock,fd,0,size); close(fd); } void echo_errno(int code,int socket) { switch(code) { case 404: { bad_request("wwwroot/404.html","HTTP/1.0 404 Not found\r\n",socket); break; } case 503: bad_request("wwwroot/503.html","HTTP/1.0 503 Not found\r\n",socket); break; default: break; } } int excu_cgi(int socket,char*method,char*path,char*query_string) { // char Method[MAX]; char Content_Length[MAX>>3]; char buf[MAX]; int size=0; int content_length=-1; char Path[20]; // sprintf(Method,"METHOD=%s",method); if(strcasecmp(method,"POST")==0) { // strcpy(Method,"POST"); do { size=Getline(socket,buf,sizeof(buf)); if(strncmp(buf,"Content-Length: ",16)==0) { // 获得正文长度 content_length=atoi(buf+16); } }while(size!=1&&strcmp(buf,"\n")!=0); sprintf(Content_Length,"%d",content_length); } else { // strcpy(Method,"GET"); clear_sock(socket); printf("%s\n",query_string); // char Query[MAX]; // sprintf(Query,"%s",query_string); // putenv(Query); } int outfd[2]; int infd[2]; if(pipe(outfd)<0) { return 404; } if(pipe(infd)<0) { return 404; } char line[MAX]; sprintf(line,"HTTP/1.0 200 OK\n"); send(socket,line,strlen(line),0); const char*content_type="Content-Type:text/html;charset=utf-8\r\n"; send(socket,content_type,strlen(content_type),0); send(socket,"\r\n",2,0); pid_t pid=fork(); if(pid==0) { setenv("METHOD",method,1); // printf("%s\n",getenv("METHOD")); // printf("开辟子进程\n"); if(strcasecmp(method,"GET")==0) { setenv("QUERY_STRING",query_string,1); } else { setenv("CONTENT_LENGTH",Content_Length,1); printf("CONTENT_LENGTH=%s\n",Content_Length); } printf("path=%s\n",path); close(outfd[1]); close(infd[0]); dup2(outfd[0],0); dup2(infd[1],1); execl(path,path,NULL); perror("call cgi faile"); return 404; }else if(pid>0) { close(outfd[0]); close(infd[1]); int i=0; char c; if(strcasecmp(method,"POST")==0) { printf("content_length=%d\n",content_length); while(i<content_length) { recv(socket,&c,1,0); write(outfd[1],&c,1); // printf("%c",c); ++i; }} // printf("\n"); wait(NULL); // printf("read infd[0]\n"); // int k=0; while(read(infd[0],&c,1)>0) { // k++; send(socket,&c,1,0); // printf("%c",c); } close(outfd[1]); close(infd[0]); printf("excgi,ok\n"); }else { perror("fork"); return 404; } return 200; } int echo_www(int sock,char*path,int size) { printf("clear_sock start\n"); clear_sock(sock); printf("clear_sock end\n"); int fd=open(path,O_RDONLY); printf("文件的大小为:%d\n",size); //清理剩余报文信息,避免粘包问题 // printf("clean socket\n"); //发送响应报头 // printf("send http\n"); char line[MAX>>3]; sprintf(line,"HTTP/1.0 200 OK\n"); send(sock,line,strlen(line),0); const char*content_type="Content-Type:text/html;charset=utf-8\r\n"; send(sock,content_type,strlen(content_type),0); send(sock,"\n",1,0); // snedfile效率高,因为它少了从内核区向用户区拷贝,然后再从用户区拷贝到内核区 if(sendfile(sock,fd,0,size)<0) { printf("%s发送文件失败\n",path); return 404; } close(fd); return 200; } void*handle(void*arg) { // server_t *s=(server_t*)arg; // int socket=s->socket; // int efd=s->efd; int socket=(int)arg; char buf[MAX]; char method[MAX]; char url[MAX]; char path[MAX]; char* query_string=0; int cgi=0; int erroncode=200; //获得http的请求行 int size = Getline(socket,buf,sizeof(buf)); printf("size=%d buf=%s\n",size,buf); // if(size==0) // { // epoll_ctl(efd,EPOLL_CTL_DEL,socket,NULL); // printf("delete fd %d\n",socket); // goto end; // } // printf("size=%d\n",size); int i=0; int j=0; //从请求行解析出请求方法 while(buf[i]&&i<size) { if(isspace(buf[i])) { break; } method[j++]=buf[i++]; } method[j]=0; // printf("method=%s\n",method); while(i<size&&isspace(buf[i])) ++i; //获得url j=0; while(buf[i]&&i<size) { if(isspace(buf[i])) { break; } url[j++]=buf[i++]; } url[j]=0; // printf("url=%s\n",url); //判断请求方法 if(strcasecmp(method,"POST")==0) cgi=1; else if(strcasecmp(method,"GET")==0) { j=0; while(url[j]&&j<MAX) { if(url[j]=='?') { // printf("GET 方法带参数\n"); cgi=1; query_string=url+j+1; url[j]=0; break; } ++j; } // printf("path=%s\n",path); } else { erroncode=404; goto end; } sprintf(path,"wwwroot%s",url); //如果访问的是目录,就返回目录下的主页 if(path[strlen(path)-1]=='/') { strcat(path,"index.html"); } //判断path资源是否存在 struct stat state; if(stat(path,&state)<0) { printf("no file path=%s\n",path); printf("文件不存在\n"); clear_sock(socket); erroncode=404; goto end; } if(S_ISDIR(state.st_mode)) { strcat(path,"/index.html"); } else if(S_ISREG(state.st_mode)) { if((state.st_mode&S_IXUSR)||\ (state.st_mode&S_IXGRP)||(state.st_mode&S_IXOTH)) { cgi=1; } } else { } if(stat(path,&state)<0) { printf("no file path=%s\n",path); printf("文件不存在\n"); clear_sock(socket); erroncode=404; goto end; } printf("path=%s\n",path); if(cgi==1) { printf("call excu_cgi\n"); erroncode=excu_cgi(socket,method,path,query_string); } else { // printf("call echo_www\n"); erroncode=echo_www(socket,path,state.st_size); } end: if(erroncode!=200) { printf("call echo_errno\n"); echo_errno(erroncode,socket); } printf("send ok\n"); close(socket); return NULL; }
21ee9defc9f5717a67c5587eb279adc274177e46
[ "C", "Makefile" ]
6
C
cocealx/HTTP-Server
5fe590ab4249640c0f1a4befd5971aeca01c2a60
ecd85339fcf31a03795b297a045c087670c35e0f
refs/heads/master
<file_sep>week = input("weekdag? ") if (week.lower() == "maandag"): day = 1 elif (week.lower() == "dinsdag"): day = 2 elif (week.lower() == "woensdag"): day = 3 elif (week.lower() == "donderdag"): day = 4 elif (week.lower() == "vrijdag"): day = 5 elif (week.lower() == "zaterdag"): day = 6 elif (week.lower() == "zondag"): day = 7 else: print("Eyo das geen weekdag") alter = 1 while alter <= day: if alter== 1: naam = "maandag" if alter== 2: naam = "dinsdag" if alter== 3: naam = "woensdag" if alter== 4: naam = "donderdag" if alter== 5: naam = "vrijdag" if alter== 6: naam = "zaterdag" if alter== 7: naam = "zondag" print(naam) alter = alter + 1 <file_sep>i = 0 while i <= 11: print(str(i) + str("AM")) i = i + 1 p = 12 while p <= 23: print(str(p) + str("PM")) p = p + 1<file_sep>u = 1 while u != "quit": u = input("quit? ")<file_sep>u = 50 while u <= 1000: print(u) u = u + u<file_sep># name of student: # number of student: # purpose of program: # function of program: # structure of program: toPay = int(float(input('Amount to pay: '))* 100) #topay word berekend met een user input als een getal paid = int(float(input('Paid amount: ')) * 100) #paid word berekend met een user input als een getal change = paid - toPay #simpele som die een som maakt met de opgegeven waardes. if change > 0: #als uit de bovenstaande som 0 kwam word coinvalue 50 coinValue = 50 #coinvalue word gezet while change > 0 and coinValue > 0: #als change en coinvalue 0 zijn word het volgende herhaald nrCoins = change // coinValue # nrcoins = change gedeelt door (en naar beneden afgerond) coinvalue if nrCoins > 0: #als nrcoins dankzij de bovenstaande som 0 is... print('return maximal ', nrCoins, ' coins of ', coinValue, ' cents!' ) #word return maximal (met het uitgerekende nrcoins) coins of (de eerder gezette coinvalue) cents! geprint. nrCoinsReturned = int(input('How many coins of ' + str(coinValue) + ' cents did you return? ')) # het vraagt voor hoeveel coins je hebt teruggegeven change -= nrCoinsReturned * coinValue #coinvalue keer nrcoinsreturned min change word change. # comment on code below: het checked hoeveel van de verschillende coins je hebt teruggegeven. (samen met mijn really scuffed code) if coinValue == 500 coinValue = 300 elif coinValue == 300 coinValue = 200 elif coinValue == 200 coinValue = 50 elif coinValue == 50: coinValue = 20 elif coinValue == 20: coinValue = 10 elif coinValue == 10: coinValue = 5 elif coinValue == 5: coinValue = 2 elif coinValue == 2: coinValue = 1 else: coinValue = 0 if change > 0: #als change na dat alles nog steeds 0 is word er verteld hoeveel er moest worden betaald. print('Change not returned: ', str(change) + ' cents') else: print('done')
2adc215da449793202ad9a2d5caa7878818da7bb
[ "Python" ]
5
Python
BrianMourik/nogmaals
5b5ca09fbd1962824ce80ca85981deacda93b451
a3e1297f131b7a58e86b8952839fb5b143640e6b
refs/heads/master
<repo_name>martrs/pbkrtest<file_sep>/R/KR-linearAlgebra.R .spur<-function(U){ sum(diag(U)) } .orthComplement<-function(W) { ##orthogonal complement of <W>: <W>orth=<Worth> rW <- rankMatrix(W) Worth <- qr.Q(qr(cbind(W)), complete=TRUE)[,-c(1:rW), drop=FALSE] Worth } ## ## Old UHH-code below Completely obsolete ## ## .spurAB<-function(A,B){ ## sum(A*t.default(B)) ## } ## # if A eller B er symmetrisk så er trace(AB)=sum(A*B) ## .matrixNullSpace<-function(B,L) { ## ## find A such that <A>={Bb| b in Lb=0} ## if ( ncol(B) != ncol(L) ) { ## stop('Number of columns of B and L not equal \n') ## } ## A <- B %*% .orthComplement(t(L)) ## # makes columns of A orthonormal: ## A <- qr.Q(qr(A))[,1:rankMatrix(A)] ## A ## } ## .colSpaceCompare<-function(X1,X2) { ## ## X1 X2: matrices with the ssme number of rows ## ## results r (Ci column space of Xi) ## ## r=1 C1 < C2 ## ## r=2 C2 < C1 ## ## r=3 C1==C2 ## ## r=4 C1 intersect C2 NOTempty but neither the one contained in the other ## ## r=5 C1 intersect C2 = empty ## if (nrow(X1)!= nrow(X2)){ ## stop("\n number of rows of X1 and X2 must be equal") } ## r1 <-rankMatrix(X1) ## r2 <-rankMatrix(X2) ## r12<-rankMatrix(cbind(X1,X2)) ## r <- ## if (r12 <= pmax(r1,r2)) { ## if (r1==r2) 3 else { ## if (r1>r2) 2 else 1 ## } ## } else { ## if (r12==(r1+r2)) 5 else 4 ## } ## r ## } <file_sep>/R/KR-modcomp.R ## ########################################################################## ## #' @title F-test and degrees of freedom based on Kenward-Roger approximation #' #' @description An approximate F-test based on the Kenward-Roger approach. #' #' @name kr-modcomp #' ## ########################################################################## #' @details The model \code{object} must be fitted with restricted maximum #' likelihood (i.e. with \code{REML=TRUE}). If the object is fitted with #' maximum likelihood (i.e. with \code{REML=FALSE}) then the model is #' refitted with \code{REML=TRUE} before the p-values are calculated. Put #' differently, the user needs not worry about this issue. #' #' An F test is calculated according to the approach of Kenward and Roger #' (1997). The function works for linear mixed models fitted with the #' \code{lmer} function of the \pkg{lme4} package. Only models where the #' covariance structure is a sum of known matrices can be compared. #' #' The \code{largeModel} may be a model fitted with \code{lmer} either using #' \code{REML=TRUE} or \code{REML=FALSE}. The \code{smallModel} can be a model #' fitted with \code{lmer}. It must have the same covariance structure as #' \code{largeModel}. Furthermore, its linear space of expectation must be a #' subspace of the space for \code{largeModel}. The model \code{smallModel} #' can also be a restriction matrix \code{L} specifying the hypothesis \eqn{L #' \beta = L \beta_H}, where \eqn{L} is a \eqn{k \times p}{k X p} matrix and #' \eqn{\beta} is a \eqn{p} column vector the same length as #' \code{fixef(largeModel)}. #' #' The \eqn{\beta_H} is a \eqn{p} column vector. #' #' Notice: if you want to test a hypothesis \eqn{L \beta = c} with a \eqn{k} #' vector \eqn{c}, a suitable \eqn{\beta_H} is obtained via \eqn{\beta_H=L c} #' where \eqn{L_n} is a g-inverse of \eqn{L}. #' #' Notice: It cannot be guaranteed that the results agree with other #' implementations of the Kenward-Roger approach! #' #' @aliases KRmodcomp KRmodcomp.lmerMod KRmodcomp_internal KRmodcomp.mer #' @param largeModel An \code{lmer} model #' @param smallModel An \code{lmer} model or a restriction matrix #' @param betaH A number or a vector of the beta of the hypothesis, e.g. L #' beta=L betaH. betaH=0 if modelSmall is a model not a restriction matrix. #' @param details If larger than 0 some timing details are printed. #' @note This functionality is not thoroughly tested and should be used with #' care. Please do report bugs etc. #' #' @author <NAME> \email{<EMAIL>}, <NAME> #' \email{<EMAIL>} #' #' @seealso \code{\link{getKR}}, \code{\link{lmer}}, \code{\link{vcovAdj}}, #' \code{\link{PBmodcomp}} #' #' @references <NAME>, <NAME> (2014)., A Kenward-Roger #' Approximation and Parametric Bootstrap Methods for Tests in Linear Mixed #' Models - The R Package pbkrtest., Journal of Statistical Software, #' 58(10), 1-30., \url{http://www.jstatsoft.org/v59/i09/} #' #' <NAME>. and <NAME>. (1997), \emph{Small Sample Inference for #' Fixed Effects from Restricted Maximum Likelihood}, Biometrics 53: 983-997. #' #' @keywords models inference #' @examples #' #' (fmLarge <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)) #' ## removing Days #' (fmSmall <- lmer(Reaction ~ 1 + (Days|Subject), sleepstudy)) #' anova(fmLarge,fmSmall) #' KRmodcomp(fmLarge,fmSmall) #' #' ## The same test using a restriction matrix #' L <- cbind(0,1) #' KRmodcomp(fmLarge, L) #' #' ## Same example, but with independent intercept and slope effects: #' m.large <- lmer(Reaction ~ Days + (1|Subject) + (0+Days|Subject), data = sleepstudy) #' m.small <- lmer(Reaction ~ 1 + (1|Subject) + (0+Days|Subject), data = sleepstudy) #' anova(m.large, m.small) #' KRmodcomp(m.large, m.small) #' #' #' @export #' @rdname kr-modcomp KRmodcomp <- function(largeModel, smallModel,betaH=0, details=0){ UseMethod("KRmodcomp") } #' @export #' @rdname kr-modcomp KRmodcomp.lmerMod <- function(largeModel, smallModel, betaH=0, details=0) { ## 'smallModel' can either be an lmerMod (linear mixed) model or a restriction matrix L. w <- KRmodcomp_init(largeModel, smallModel, matrixOK = TRUE) if (w == -1) { stop('Models have either equal fixed mean stucture or are not nested') } else { if (w == 0){ ##stop('First given model is submodel of second; exchange the models\n') tmp <- largeModel largeModel <- smallModel smallModel <- tmp } } ## Refit large model with REML if necessary if (!(getME(largeModel, "is_REML"))){ largeModel <- update(largeModel,.~.,REML=TRUE) } ## All computations are based on 'largeModel' and the restriction matrix 'L' ## ------------------------------------------------------------------------- t0 <- proc.time() L <- .model2restrictionMatrix(largeModel, smallModel) PhiA <- vcovAdj(largeModel, details) stats <- .KR_adjust(PhiA, Phi=vcov(largeModel), L, beta=fixef(largeModel), betaH) stats <- lapply(stats, c) ## To get rid of all sorts of attributes ans <- .finalizeKR(stats) f.small <- if (.is.lmm(smallModel)){ .zzz <- formula(smallModel) attributes(.zzz) <- NULL .zzz } else { list(L=L, betaH=betaH) } f.large <- formula(largeModel) attributes(f.large) <- NULL ans$f.large <- f.large ans$f.small <- f.small ans$ctime <- (proc.time()-t0)[1] ans$L <- L ans } #' @rdname kr-modcomp KRmodcomp.mer <- KRmodcomp.lmerMod .finalizeKR <- function(stats){ test = list( Ftest = c(stat=stats$Fstat, ndf=stats$ndf, ddf=stats$ddf, F.scaling=stats$F.scaling, p.value=stats$p.value), FtestU = c(stat=stats$FstatU, ndf=stats$ndf, ddf=stats$ddf, F.scaling=NA, p.value=stats$p.valueU)) test <- as.data.frame(do.call(rbind, test)) test$ndf <- as.integer(test$ndf) ans <- list(test=test, type="F", aux=stats$aux, stats=stats) ## Notice: stats are carried to the output. They are used for get getKR function... class(ans)<-c("KRmodcomp") ans } KRmodcomp_internal <- function(largeModel, LL, betaH=0, details=0){ PhiA <- vcovAdj(largeModel, details) stats <- .KR_adjust(PhiA, Phi=vcov(largeModel), LL, beta=fixef(largeModel), betaH) stats <- lapply(stats, c) ## To get rid of all sorts of attributes ans <- .finalizeKR(stats) ans } ## -------------------------------------------------------------------- ## This is the function that calculates the Kenward-Roger approximation ## -------------------------------------------------------------------- .KR_adjust <- function(PhiA, Phi, L, beta, betaH){ Theta <- t(L) %*% solve( L %*% Phi %*% t(L), L) P <- attr( PhiA, "P" ) W <- attr( PhiA, "W" ) A1 <- A2 <- 0 ThetaPhi <- Theta %*% Phi n.ggamma <- length(P) for (ii in 1:n.ggamma) { for (jj in c(ii:n.ggamma)) { e <- ifelse(ii==jj, 1, 2) ui <- ThetaPhi %*% P[[ii]] %*% Phi uj <- ThetaPhi %*% P[[jj]] %*% Phi A1 <- A1 + e* W[ii,jj] * (.spur(ui) * .spur(uj)) A2 <- A2 + e* W[ii,jj] * sum(ui * t(uj)) } } q <- rankMatrix(L) B <- (1/(2*q)) * (A1+6*A2) g <- ( (q+1)*A1 - (q+4)*A2 ) / ((q+2)*A2) c1<- g/(3*q+ 2*(1-g)) c2<- (q-g) / (3*q + 2*(1-g)) c3<- (q+2-g) / ( 3*q+2*(1-g)) ## cat(sprintf("q=%i B=%f A1=%f A2=%f\n", q, B, A1, A2)) ## cat(sprintf("g=%f, c1=%f, c2=%f, c3=%f\n", g, c1, c2, c3)) ###orgDef: E<-1/(1-A2/q) ###orgDef: V<- 2/q * (1+c1*B) / ( (1-c2*B)^2 * (1-c3*B) ) ##EE <- 1/(1-A2/q) ##VV <- (2/q) * (1+c1*B) / ( (1-c2*B)^2 * (1-c3*B) ) EE <- 1 + (A2/q) VV <- (2/q)*(1+B) EEstar <- 1/(1-A2/q) VVstar <- (2/q)*((1+c1*B)/((1-c2*B)^2 * (1-c3*B))) ## cat(sprintf("EE=%f VV=%f EEstar=%f VVstar=%f\n", EE, VV, EEstar, VVstar)) V0<-1+c1*B V1<-1-c2*B V2<-1-c3*B V0<-ifelse(abs(V0)<1e-10,0,V0) ## cat(sprintf("V0=%f V1=%f V2=%f\n", V0, V1, V2)) ###orgDef: V<- 2/q* V0 /(V1^2*V2) ###orgDef: rho <- V/(2*E^2) rho <- 1/q * (.divZero(1-A2/q,V1))^2 * V0/V2 df2 <- 4 + (q+2)/ (q*rho-1) ## Here are the adjusted degrees of freedom. ###orgDef: F.scaling <- df2 /(E*(df2-2)) ###altCalc F.scaling<- df2 * .divZero(1-A2/q,df2-2,tol=1e-12) ## this does not work because df2-2 can be about 0.1 F.scaling <- ifelse( abs(df2 - 2) < 1e-2, 1 , df2 * (1 - A2 / q) / (df2 - 2)) ##cat(sprintf("KR: rho=%f, df2=%f F.scaling=%f\n", rho, df2, F.scaling)) ## Vector of auxilary values; just for checking etc... aux <- c(A1=A1, A2=A2, V0=V0, V1=V1, V2=V2, rho=rho, F.scaling=F.scaling) ### The F-statistic; scaled and unscaled betaDiff <- cbind( beta - betaH ) Wald <- as.numeric(t(betaDiff) %*% t(L) %*% solve(L %*% PhiA %*% t(L), L %*% betaDiff)) WaldU <- as.numeric(t(betaDiff) %*% t(L) %*% solve(L %*% Phi %*% t(L), L %*% betaDiff)) FstatU <- Wald/q pvalU <- pf(FstatU, df1=q, df2=df2, lower.tail=FALSE) Fstat <- F.scaling * FstatU pval <- pf(Fstat, df1=q, df2=df2, lower.tail=FALSE) stats<-list(ndf=q, ddf=df2, Fstat = Fstat, p.value=pval, F.scaling=F.scaling, FstatU = FstatU, p.valueU = pvalU, aux = aux) stats } .KRcommon <- function(x){ cat(sprintf("F-test with Kenward-Roger approximation; time: %.2f sec\n", x$ctime)) cat("large : ") print(x$f.large) if (inherits(x$f.small,"call")){ cat("small : ") print(x$f.small) } else { formSmall <- x$f.small cat("small : L beta = L betaH \n") cat('L=\n') print(formSmall$L) cat('betaH=\n') print(formSmall$betaH) } } #' @export print.KRmodcomp <- function(x, ...){ .KRcommon(x) FF.thresh <- 0.2 F.scale <- x$aux['F.scaling'] tab <- x$test if (max(F.scale)>FF.thresh){ printCoefmat(tab[1,,drop=FALSE], tst.ind=c(1,2,3), na.print='', has.Pvalue=TRUE) } else { printCoefmat(tab[2,,drop=FALSE], tst.ind=c(1,2,3), na.print='', has.Pvalue=TRUE) } return(invisible(x)) } #' @export summary.KRmodcomp <- function(object, ...){ .KRcommon(object) FF.thresh <- 0.2 F.scale <- object$aux['F.scaling'] tab <- object$test printCoefmat(tab, tst.ind=c(1,2,3), na.print='', has.Pvalue=TRUE) if (F.scale<0.2 & F.scale>0) { cat('Note: The scaling factor for the F-statistic is smaller than 0.2 \n') cat('The Unscaled statistic might be more reliable \n ') } else { if (F.scale<=0){ cat('Note: The scaling factor for the F-statistic is negative \n') cat('Use the Unscaled statistic instead. \n ') } } } #stats <- .KRmodcompPrimitive(largeModel, L, betaH, details) ## .KRmodcompPrimitive<-function(largeModel, L, betaH, details) { ## PhiA<-vcovAdj(largeModel, details) ## .KR_adjust(PhiA, Phi=vcov(largeModel), L, beta=fixef(largeModel), betaH ) ## } ### SHD addition: calculate bartlett correction and gamma approximation ### ## ## Bartlett correction - X2 distribution ## BCval <- 1 / EE ## BCstat <- BCval * Wald ## p.BC <- 1-pchisq(BCstat,df=q) ## # cat(sprintf("Wald=%f BCval=%f BC.stat=%f p.BC=%f\n", Wald, BCval, BCstat, p.BC)) ## ## Gamma distribution ## scale <- q*VV/EE ## shape <- EE^2/VV ## p.Ga <- 1-pgamma(Wald, shape=shape, scale=scale) ## # cat(sprintf("shape=%f scale=%f p.Ga=%f\n", shape, scale, p.Ga)) <file_sep>/R/KR-vcovAdj.R ################################################################################ #' #' @title Ajusted covariance matrix for linear mixed models according #' to Kenward and Roger #' @description Kenward and Roger (1997) describbe an improved small #' sample approximation to the covariance matrix estimate of the #' fixed parameters in a linear mixed model. #' @name kr-vcov #' ################################################################################ ## Implemented in Banff, august 2013; Søren Højsgaard #' @aliases vcovAdj vcovAdj.lmerMod vcovAdj_internal vcovAdj0 vcovAdj2 #' vcovAdj.mer LMM_Sigma_G get_SigmaG get_SigmaG.lmerMod get_SigmaG.mer #' #' @param object An \code{lmer} model #' @param details If larger than 0 some timing details are printed. #' @return \item{phiA}{the estimated covariance matrix, this has attributed P, a #' list of matrices used in \code{KR_adjust} and the estimated matrix W of #' the variances of the covariance parameters of the random effetcs} #' #' \item{SigmaG}{list: Sigma: the covariance matrix of Y; G: the G matrices that #' sum up to Sigma; n.ggamma: the number (called M in the article) of G #' matrices) } #' #' @note If $N$ is the number of observations, then the \code{vcovAdj()} #' function involves inversion of an $N x N$ matrix, so the computations can #' be relatively slow. #' @author <NAME> \email{<EMAIL>}, <NAME> #' \email{<EMAIL>} #' @seealso \code{\link{getKR}}, \code{\link{KRmodcomp}}, \code{\link{lmer}}, #' \code{\link{PBmodcomp}}, \code{\link{vcovAdj}} #' @references <NAME>, <NAME> (2014)., A Kenward-Roger #' Approximation and Parametric Bootstrap Methods for Tests in Linear Mixed #' Models - The R Package pbkrtest., Journal of Statistical Software, #' 58(10), 1-30., \url{http://www.jstatsoft.org/v59/i09/} #' #' <NAME>. and <NAME>. (1997), \emph{Small Sample Inference for #' Fixed Effects from Restricted Maximum Likelihood}, Biometrics 53: 983-997. #' #' @keywords inference models #' @examples #' #' fm1 <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy) #' class(fm1) #' #' ## Here the adjusted and unadjusted covariance matrices are identical, #' ## but that is not generally the case: #' #' v1 <- vcov(fm1) #' v2 <- vcovAdj(fm1, details=0) #' v2 / v1 #' #' ## For comparison, an alternative estimate of the variance-covariance #' ## matrix is based on parametric bootstrap (and this is easily #' ## parallelized): #' #' \dontrun{ #' nsim <- 100 #' sim <- simulate(fm.ml, nsim) #' B <- lapply(sim, function(newy) try(fixef(refit(fm.ml, newresp=newy)))) #' B <- do.call(rbind, B) #' v3 <- cov.wt(B)$cov #' v2/v1 #' v3/v1 #' } #' #' #' #' @export vcovAdj #' #' @rdname kr-vcov vcovAdj <- function(object, details=0){ UseMethod("vcovAdj") } #' @method vcovAdj lmerMod #' @rdname kr-vcov #' @export vcovAdj.lmerMod vcovAdj.lmerMod <- function(object, details=0){ if (!(getME(object, "is_REML"))) { object <- update(object, . ~ ., REML = TRUE) } Phi <- vcov(object) SigmaG <- get_SigmaG(object, details) X <- getME(object, "X") vcovAdj16_internal(Phi, SigmaG, X, details=details) } ## Needed to avoid emmeans choking. #' @export vcovAdj.lmerMod <- vcovAdj.lmerMod #' @method vcovAdj mer #' @rdname kr-vcov #' @export vcovAdj.mer <- vcovAdj.lmerMod ## ## For backward compatibility with bnlearn who calls methods and not generic functions... ## ## #' @method grain CPTspec ## #' @export grain.CPTspec ## grain.CPTspec <- grain.cpt_spec ## #' @rdname grain-main ## #' @export ## grain.CPTspec <- grain.cpt_spec .vcovAdj_internal <- function(Phi, SigmaG, X, details=0){ ##cat("vcovAdj_internal\n") ##SG<<-SigmaG DB <- details > 0 ## debugging only #print("HHHHHHHHHHHHHHH") #print(system.time({chol( forceSymmetric(SigmaG$Sigma) )})) #print(system.time({chol2inv( chol( forceSymmetric(SigmaG$Sigma) ) )})) ## print("HHHHHHHHHHHHHHH") ## Sig <- forceSymmetric( SigmaG$Sigma ) ## print("HHHHHHHHHHHHHHH") ## print(system.time({Sig.chol <- chol( Sig )})) ## print(system.time({chol2inv( Sig.chol )})) t0 <- proc.time() ## print("HHHHHHHHHHHHHHH") SigmaInv <- chol2inv( chol( forceSymmetric(SigmaG$Sigma) ) ) ## print("DONE --- HHHHHHHHHHHHHHH") if(DB){ cat(sprintf("Finding SigmaInv: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time() } ##print("iiiiiiiiiiiii") t0 <- proc.time() ## Finding, TT, HH, 00 n.ggamma <- SigmaG$n.ggamma TT <- SigmaInv %*% X HH <- OO <- vector("list", n.ggamma) for (ii in 1:n.ggamma) { .tmp <- SigmaG$G[[ii]] %*% SigmaInv HH[[ ii ]] <- .tmp OO[[ ii ]] <- .tmp %*% X } if(DB){cat(sprintf("Finding TT,HH,OO %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ## if(DB){ ## cat("HH:\n"); print(HH); HH <<- HH ## cat("OO:\n"); print(OO); OO <<- OO ## } ## Finding PP, QQ PP <- QQ <- NULL for (rr in 1:n.ggamma) { OrTrans <- t( OO[[ rr ]] ) PP <- c(PP, list(forceSymmetric( -1 * OrTrans %*% TT))) for (ss in rr:n.ggamma) { QQ <- c(QQ,list(OrTrans %*% SigmaInv %*% OO[[ss]] )) }} if(DB){cat(sprintf("Finding PP,QQ: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ## if(DB){ ## cat("PP:\n"); print(PP); PP2 <<- PP ## cat("QP:\n"); print(QQ); QQ2 <<- QQ ## } Ktrace <- matrix( NA, nrow=n.ggamma, ncol=n.ggamma ) for (rr in 1:n.ggamma) { HrTrans <- t( HH[[rr]] ) for (ss in rr:n.ggamma){ Ktrace[rr,ss] <- Ktrace[ss,rr]<- sum( HrTrans * HH[[ss]] ) }} if(DB){cat(sprintf("Finding Ktrace: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ## Finding information matrix IE2 <- matrix( NA, nrow=n.ggamma, ncol=n.ggamma ) for (ii in 1:n.ggamma) { Phi.P.ii <- Phi %*% PP[[ii]] for (jj in c(ii:n.ggamma)) { www <- .indexSymmat2vec( ii, jj, n.ggamma ) IE2[ii,jj]<- IE2[jj,ii] <- Ktrace[ii,jj] - 2 * sum(Phi*QQ[[ www ]]) + sum( Phi.P.ii * ( PP[[jj]] %*% Phi)) }} if(DB){cat(sprintf("Finding IE2: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} eigenIE2 <- eigen(IE2,only.values=TRUE)$values condi <- min(abs(eigenIE2)) WW <- if(condi>1e-10) forceSymmetric(2* solve(IE2)) else forceSymmetric(2* ginv(IE2)) ## print("vcovAdj") UU <- matrix(0, nrow=ncol(X), ncol=ncol(X)) ## print(UU) for (ii in 1:(n.ggamma-1)) { for (jj in c((ii+1):n.ggamma)) { www <- .indexSymmat2vec( ii, jj, n.ggamma ) UU <- UU + WW[ii,jj] * (QQ[[ www ]] - PP[[ii]] %*% Phi %*% PP[[jj]]) }} ## print(UU) UU <- UU + t(UU) ## UU <<- UU for (ii in 1:n.ggamma) { www <- .indexSymmat2vec( ii, ii, n.ggamma ) UU<- UU + WW[ii,ii] * (QQ[[ www ]] - PP[[ii]] %*% Phi %*% PP[[ii]]) } ## print(UU) GGAMMA <- Phi %*% UU %*% Phi PhiA <- Phi + 2 * GGAMMA attr(PhiA, "P") <-PP attr(PhiA, "W") <-WW attr(PhiA, "condi") <- condi PhiA } <file_sep>/R/PB-modcomp.R ########################################################## ### ### Bartlett corrected LRT ### ########################################################## #' @title Model comparison using parametric bootstrap methods. #' #' @description Model comparison of nested models using parametric bootstrap #' methods. Implemented for some commonly applied model types. #' #' @name pb-modcomp #' #' @details The model \code{object} must be fitted with maximum likelihood #' (i.e. with \code{REML=FALSE}). If the object is fitted with restricted #' maximum likelihood (i.e. with \code{REML=TRUE}) then the model is #' refitted with \code{REML=FALSE} before the p-values are calculated. Put #' differently, the user needs not worry about this issue. #' #' Under the fitted hypothesis (i.e. under the fitted small model) \code{nsim} #' samples of the likelihood ratio test statistic (LRT) are generetated. #' #' Then p-values are calculated as follows: #' #' LRT: Assuming that LRT has a chi-square distribution. #' #' PBtest: The fraction of simulated LRT-values that are larger or equal to the #' observed LRT value. #' #' Bartlett: A Bartlett correction is of LRT is calculated from the mean of the #' simulated LRT-values #' #' Gamma: The reference distribution of LRT is assumed to be a gamma #' distribution with mean and variance determined as the sample mean and sample #' variance of the simulated LRT-values. #' #' F: The LRT divided by the number of degrees of freedom is assumed to be #' F-distributed, where the denominator degrees of freedom are determined by #' matching the first moment of the reference distribution. #' #' @aliases PBmodcomp PBmodcomp.lm PBmodcomp.merMod getLRT getLRT.lm #' getLRT.merMod plot.XXmodcomp PBmodcomp.mer getLRT.mer #' @param largeModel A model object. Can be a linear mixed effects #' model or generalized linear mixed effects model (as fitted with #' \code{lmer()} and \code{glmer()} function in the \pkg{lme4} #' package) or a linear normal model or a generalized linear #' model. The \code{largeModel} must be larger than #' \code{smallModel} (see below). #' @param smallModel A model of the same type as \code{largeModel} or #' a restriction matrix. #' @param nsim The number of simulations to form the reference #' distribution. #' @param ref Vector containing samples from the reference #' distribution. If NULL, this vector will be generated using #' PBrefdist(). #' @param seed A seed that will be passed to the simulation of new #' datasets. #' @param h For sequential computing for bootstrap p-values: The #' number of extreme cases needed to generate before the sampling #' proces stops. #' @param cl A vector identifying a cluster; used for calculating the #' reference distribution using several cores. See examples below. #' @param details The amount of output produced. Mainly relevant for #' debugging purposes. #' @note It can happen that some values of the LRT statistic in the #' reference distribution are negative. When this happens one will #' see that the number of used samples (those where the LRT is #' positive) are reported (this number is smaller than the #' requested number of samples). #' #' In theory one can not have a negative value of the LRT statistic but in #' practice on can: We speculate that the reason is as follows: We simulate data #' under the small model and fit both the small and the large model to the #' simulated data. Therefore the large model represents - by definition - an #' overfit; the model has superfluous parameters in it. Therefore the fit of the #' two models will for some simulated datasets be very similar resulting in #' similar values of the log-likelihood. There is no guarantee that the the #' log-likelihood for the large model in practice always will be larger than for #' the small (convergence problems and other numerical issues can play a role #' here). #' #' To look further into the problem, one can use the \code{PBrefdist()} function #' for simulating the reference distribution (this reference distribution can be #' provided as input to \code{PBmodcomp()}). Inspection sometimes reveals that #' while many values are negative, they are numerically very small. In this case #' one may try to replace the negative values by a small positive value and then #' invoke \code{PBmodcomp()} to get some idea about how strong influence there #' is on the resulting p-values. (The p-values get smaller this way compared to #' the case when only the originally positive values are used). #' #' @author <NAME> \email{<EMAIL>} #' #' @seealso \code{\link{KRmodcomp}}, \code{\link{PBrefdist}} #' #' @references <NAME>, <NAME> (2014)., A Kenward-Roger #' Approximation and Parametric Bootstrap Methods for Tests in Linear Mixed #' Models - The R Package pbkrtest., Journal of Statistical Software, #' 58(10), 1-30., \url{http://www.jstatsoft.org/v59/i09/} #' @keywords models inference #' @examples #' #' data(beets, package="pbkrtest") #' head(beets) #' #' ## Linear mixed effects model: #' sug <- lmer(sugpct ~ block + sow + harvest + (1|block:harvest), #' data=beets, REML=FALSE) #' sug.h <- update(sug, .~. -harvest) #' sug.s <- update(sug, .~. -sow) #' #' anova(sug, sug.h) #' PBmodcomp(sug, sug.h, nsim=50, cl=1) #' anova(sug, sug.h) #' PBmodcomp(sug, sug.s, nsim=50, cl=1) #' #' ## Linear normal model: #' sug <- lm(sugpct ~ block + sow + harvest, data=beets) #' sug.h <- update(sug, .~. -harvest) #' sug.s <- update(sug, .~. -sow) #' #' anova(sug, sug.h) #' PBmodcomp(sug, sug.h, nsim=50, cl=1) #' anova(sug, sug.s) #' PBmodcomp(sug, sug.s, nsim=50, cl=1) #' #' ## Generalized linear model #' counts <- c(18,17,15,20,10,20,25,13,12) #' outcome <- gl(3,1,9) #' treatment <- gl(3,3) #' d.AD <- data.frame(treatment, outcome, counts) #' head(d.AD) #' glm.D93 <- glm(counts ~ outcome + treatment, family = poisson()) #' glm.D93.o <- update(glm.D93, .~. -outcome) #' glm.D93.t <- update(glm.D93, .~. -treatment) #' #' anova(glm.D93, glm.D93.o, test="Chisq") #' PBmodcomp(glm.D93, glm.D93.o, nsim=50, cl=1) #' anova(glm.D93, glm.D93.t, test="Chisq") #' PBmodcomp(glm.D93, glm.D93.t, nsim=50, cl=1) #' #' ## Generalized linear mixed model (it takes a while to fit these) #' \dontrun{ #' (gm1 <- glmer(cbind(incidence, size - incidence) ~ period + (1 | herd), #' data = cbpp, family = binomial)) #' (gm2 <- update(gm1, .~.-period)) #' anova(gm1, gm2) #' PBmodcomp(gm1, gm2, cl=2) #' } #' #' #' \dontrun{ #' (fmLarge <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)) #' ## removing Days #' (fmSmall <- lmer(Reaction ~ 1 + (Days|Subject), sleepstudy)) #' anova(fmLarge, fmSmall) #' PBmodcomp(fmLarge, fmSmall, cl=1) #' #' ## The same test using a restriction matrix #' L <- cbind(0,1) #' PBmodcomp(fmLarge, L, cl=1) #' #' ## Vanilla #' PBmodcomp(beet0, beet_no.harv, nsim=1000, cl=1) #' #' ## Simulate reference distribution separately: #' refdist <- PBrefdist(beet0, beet_no.harv, nsim=1000) #' PBmodcomp(beet0, beet_no.harv, ref=refdist, cl=1) #' #' ## Do computations with multiple processors: #' ## Number of cores: #' (nc <- detectCores()) #' ## Create clusters #' cl <- makeCluster(rep("localhost", nc)) #' #' ## Then do: #' PBmodcomp(beet0, beet_no.harv, cl=cl) #' #' ## Or in two steps: #' refdist <- PBrefdist(beet0, beet_no.harv, nsim=1000, cl=cl) #' PBmodcomp(beet0, beet_no.harv, ref=refdist) #' #' ## It is recommended to stop the clusters before quitting R: #' stopCluster(cl) #' } #' #' #' @export PBmodcomp #' @rdname pb-modcomp seqPBmodcomp <- function(largeModel, smallModel, h = 20, nsim = 1000, cl=1) { t.start <- proc.time() chunk.size <- 200 nchunk <- nsim %/% chunk.size LRTstat <- getLRT(largeModel, smallModel) ref <- NULL for (ii in 1:nchunk) { ref <- c(ref, PBrefdist(largeModel, smallModel, nsim = chunk.size, cl=cl)) n.extreme <- sum(ref > LRTstat["tobs"]) if (n.extreme >= h) break } ans <- PBmodcomp(largeModel, smallModel, ref = ref) ans$ctime <- (proc.time() - t.start)[3] ans } #' @export #' @rdname pb-modcomp PBmodcomp <- function(largeModel, smallModel, nsim=1000, ref=NULL, seed=NULL, cl=NULL, details=0){ UseMethod("PBmodcomp") } #' @export #' @rdname pb-modcomp PBmodcomp.merMod <- function(largeModel, smallModel, nsim=1000, ref=NULL, seed=NULL, cl=NULL, details=0){ ##cat("PBmodcomp.lmerMod\n") f.large <- formula(largeModel) attributes(f.large) <- NULL if (inherits(smallModel, c("Matrix", "matrix"))){ f.small <- smallModel smallModel <- restrictionMatrix2model(largeModel, smallModel) } else { f.small <- formula(smallModel) attributes(f.small) <- NULL } if (is.null(ref)){ ref <- PBrefdist(largeModel, smallModel, nsim=nsim, seed=seed, cl=cl, details=details) } ## samples <- attr(ref, "samples") ## if (!is.null(samples)){ ## nsim <- samples['nsim'] ## npos <- samples['npos'] ## } else { ## nsim <- length(ref) ## npos <- sum(ref>0) ## } LRTstat <- getLRT(largeModel, smallModel) ans <- .finalizePB(LRTstat, ref) .padPB( ans, LRTstat, ref, f.large, f.small) } #' @export PBmodcomp.mer <- PBmodcomp.merMod #' @export #' @rdname pb-modcomp PBmodcomp.lm <- function(largeModel, smallModel, nsim=1000, ref=NULL, seed=NULL, cl=NULL, details=0){ ok.fam <- c("binomial", "gaussian", "Gamma", "inverse.gaussian", "poisson") f.large <- formula(largeModel) attributes(f.large) <- NULL if (inherits(smallModel, c("Matrix", "matrix"))){ f.small <- smallModel smallModel <- restrictionMatrix2model(largeModel, smallModel) } else { f.small <- formula(smallModel) attributes(f.small) <- NULL } if (!all.equal((fam.l <- family(largeModel)), (fam.s <- family(smallModel)))) stop("Models do not have identical identical family\n") if (!(fam.l$family %in% ok.fam)){ stop(sprintf("family must be of type %s", toString(ok.fam))) } if (is.null(ref)){ ref <- PBrefdist(largeModel, smallModel, nsim=nsim, seed=seed, cl=cl, details=details) } LRTstat <- getLRT(largeModel, smallModel) ans <- .finalizePB(LRTstat, ref) .padPB( ans, LRTstat, ref, f.large, f.small) } .finalizePB <- function(LRTstat, ref){ tobs <- unname(LRTstat[1]) ndf <- unname(LRTstat[2]) refpos <- ref[ref>0] nsim <- length(ref) npos <- length(refpos) ##cat(sprintf("EE=%f VV=%f\n", EE, VV)) p.chi <- 1 - pchisq(tobs, df=ndf) ## Direct computation of tail probability n.extreme <- sum(tobs < refpos) p.PB <- (1+n.extreme) / (1+npos) test = list( LRT = c(stat=tobs, df=ndf, p.value=p.chi), PBtest = c(stat=tobs, df=NA, p.value=p.PB)) test <- as.data.frame(do.call(rbind, test)) ans <- list(test=test, type="X2test", samples=c(nsim=nsim, npos=npos), n.extreme=n.extreme, ctime=attr(ref,"ctime")) class(ans) <- c("PBmodcomp") ans } ### dot-functions below here .padPB <- function(ans, LRTstat, ref, f.large, f.small){ ans$LRTstat <- LRTstat ans$ref <- ref ans$f.large <- f.large ans$f.small <- f.small ans } .summarizePB <- function(LRTstat, ref){ tobs <- unname(LRTstat[1]) ndf <- unname(LRTstat[2]) refpos <- ref[ref>0] nsim <- length(ref) npos <- length(refpos) EE <- mean(refpos) VV <- var(refpos) ##cat(sprintf("EE=%f VV=%f\n", EE, VV)) p.chi <- 1-pchisq(tobs, df=ndf) ## Direct computation of tail probability n.extreme <- sum(tobs < refpos) ##p.PB <- n.extreme / npos p.PB <- (1+n.extreme) / (1+npos) p.PB.all <- (1+n.extreme) / (1+nsim) se <- round(sqrt(p.PB*(1-p.PB)/npos),4) ci <- round(c(-1.96, 1.96)*se + p.PB,4) ## Kernel density estimate ##dd <- density(ref) ##p.KD <- sum(dd$y[dd$x>=tobs])/sum(dd$y) ## Bartlett correction - X2 distribution BCstat <- ndf * tobs/EE ##cat(sprintf("BCval=%f\n", ndf/EE)) p.BC <- 1-pchisq(BCstat,df=ndf) ## Fit to gamma distribution scale <- VV/EE shape <- EE^2/VV p.Ga <- 1-pgamma(tobs, shape=shape, scale=scale) ## Fit T/d to F-distribution (1. moment) ## FIXME: Think the formula is 2*EE/(EE-1) ##ddf <- 2*EE/(EE-ndf) ddf <- 2*EE/(EE-1) Fobs <- tobs/ndf if (ddf>0) p.FF <- 1-pf(Fobs, df1=ndf, df2=ddf) else p.FF <- NA ## Fit T/d to F-distribution (1. AND 2. moment) ## EE2 <- EE/ndf ## VV2 <- VV/ndf^2 ## rho <- VV2/(2*EE2^2) ## ddf2 <- 4 + (ndf+2)/(rho*ndf-1) ## lam2 <- (ddf/EE2*(ddf-2)) ## Fobs2 <- lam2 * tobs/ndf ## if (ddf2>0) ## p.FF2 <- 1-pf(Fobs2, df1=ndf, df2=ddf2) ## else ## p.FF2 <- NA ## cat(sprintf("PB: EE=%f, ndf=%f VV=%f, ddf=%f\n", EE, ndf, VV, ddf)) test = list( LRT = c(stat=tobs, df=ndf, ddf=NA, p.value=p.chi), PBtest = c(stat=tobs, df=NA, ddf=NA, p.value=p.PB), Gamma = c(stat=tobs, df=NA, ddf=NA, p.value=p.Ga), Bartlett = c(stat=BCstat, df=ndf, ddf=NA, p.value=p.BC), F = c(stat=Fobs, df=ndf, ddf=ddf, p.value=p.FF) ) ## PBkd = c(stat=tobs, df=NA, ddf=NA, p.value=p.KD), ##F2 = c(stat=Fobs2, df=ndf, ddf=ddf2, p.value=p.FF2), #, #PBtest.all = c(stat=tobs, df=NA, ddf=NA, p.value=p.PB.all), #Bartlett.all = c(stat=BCstat.all, df=ndf, ddf=NA, p.value=p.BC.all) ##F2 = c(stat=Fobs2, df=ndf, p.value=p.FF2, ddf=ddf2) test <- as.data.frame(do.call(rbind, test)) ans <- list(test=test, type="X2test", moment = c(mean=EE, var=VV), samples= c(nsim=nsim, npos=npos), gamma = c(scale=scale, shape=shape), ref = ref, ci = ci, se = se, n.extreme = n.extreme, ctime = attr(ref, "ctime") ) class(ans) <- c("PBmodcomp") ans } ## rho <- VV/(2*EE^2) ## ddf2 <- (ndf*(4*rho+1) - 2)/(rho*ndf-1) ## lam2 <- (ddf/(ddf-2))/(EE/ndf) ## cat(sprintf("EE=%f, VV=%f, rho=%f, lam2=%f\n", ## EE, VV, rho, lam2)) ## ddf2 <- 4 + (ndf+2)/(rho*ndf-1) ## Fobs2 <- lam2 * tobs/ndf ## if (ddf2>0) ## p.FF2 <- 1-pf(Fobs2, df1=ndf, df2=ddf2) ## else ## p.FF2 <- NA ### ########################################################### ### ### Utilities ### ### ########################################################### .PBcommon <- function(x){ cat(sprintf("Bootstrap test; ")) if (!is.null((zz<- x$ctime))){ cat(sprintf("time: %.2f sec;", round(zz,2))) } if (!is.null((sam <- x$samples))){ cat(sprintf("samples: %d; extremes: %d;", sam[1], x$n.extreme)) } cat("\n") if (!is.null((sam <- x$samples))){ if (sam[2] < sam[1]){ cat(sprintf("Requested samples: %d Used samples: %d Extremes: %d\n", sam[1], sam[2], x$n.extreme)) } } if(!is.null(x$f.large)){ cat("large : "); print(x$f.large) cat("small : "); print(x$f.small) } } #' @export print.PBmodcomp <- function(x, ...){ .PBcommon(x) tab <- x$test printCoefmat(tab, tst.ind=1, na.print='', has.Pvalue=TRUE) return(invisible(x)) } #' @export summary.PBmodcomp <- function(object, ...){ ans <- .summarizePB(object$LRTstat, object$ref) ans$f.large <- object$f.large ans$f.small <- object$f.small class(ans) <- "summaryPB" ans } #' @export print.summaryPB <- function(x, ...){ .PBcommon(x) ans <- x$test printCoefmat(ans, tst.ind=1, na.print='', has.Pvalue=TRUE) cat("\n") ## ci <- x$ci ## cat(sprintf("95 pct CI for PBtest : [%s]\n", toString(ci))) ## mo <- x$moment ## cat(sprintf("Reference distribution : mean=%f var=%f\n", mo[1], mo[2])) ## ga <- x$gamma ## cat(sprintf("Gamma approximation : scale=%f shape=%f\n", ga[1], ga[2])) return(invisible(x)) } #' @export plot.PBmodcomp <- function(x, ...){ ref <-x$ref ndf <- x$test$df[1] u <-summary(x) ddf <-u$test['F','ddf'] EE <- mean(ref) VV <- var(ref) sc <- var(ref)/mean(ref) sh <- mean(ref)^2/var(ref) sc <- VV/EE sh <- EE^2/VV B <- ndf/EE # if ref is the null distr, so should A*ref follow a chisq(df=ndf) distribution upper <- 0.20 #tail.prob <- c(0.0001, 0.001, 0.01, 0.05, 0.10, 0.20, 0.5) tail.prob <-seq(0.001, upper, length.out = 1111) PBquant <- quantile(ref,1-tail.prob) ## tail prob for PB dist pLR <- pchisq(PBquant,df=ndf, lower.tail=FALSE) pF <- pf(PBquant/ndf,df1=ndf,df2=ddf, lower.tail=FALSE) pGamma <- pgamma(PBquant,scale=sc,shape=sh,lower.tail=FALSE) pBart <- pchisq(B*PBquant,df=ndf, lower.tail=FALSE) sym.vec <- c(2,4,5,6) lwd <- 2 plot(pLR~tail.prob,type='l', lwd=lwd, #log="xy", xlab='Nominal p-value',ylab='True p-value', xlim=c(1e-3, upper),ylim=c(1e-3, upper), col=sym.vec[1], lty=sym.vec[1]) lines(pF~tail.prob,lwd=lwd, col=sym.vec[2], lty=sym.vec[2]) lines(pBart~tail.prob,lwd=lwd, col=sym.vec[3], lty=sym.vec[3]) lines(pGamma~tail.prob,lwd=lwd, col=sym.vec[4], lty=sym.vec[4]) abline(c(0,1)) ZF <-bquote(paste("F(1,",.(round(ddf,2)),")")) Zgamma <-bquote(paste("gamma(scale=",.(round(sc,2)),", shape=", .(round(sh,2)),")" )) ZLRT <-bquote(paste(chi[.(ndf)]^2)) ZBart <-bquote(paste("Bartlett scaled ", chi[.(ndf)]^2)) legend(0.001,upper,legend=as.expression(c(ZLRT,ZF,ZBart,Zgamma)), lty=sym.vec,col=sym.vec,lwd=lwd) } #' @export as.data.frame.XXmodcomp <- function(x, row.names = NULL, optional = FALSE, ...){ as.data.frame(do.call(rbind, x[-c(1:3)])) } ## seqPBmodcomp2 <- ## function(largeModel, smallModel, h = 20, nsim = 1000, seed=NULL, cl=NULL) { ## t.start <- proc.time() ## simdata=simulate(smallModel, nsim=nsim, seed=seed) ## ref <- rep(NA, nsim) ## LRTstat <- getLRT(largeModel, smallModel) ## t.obs <- LRTstat["tobs"] ## count <- 0 ## n.extreme <- 0 ## for (i in 1:nsim){ ## count <- i ## yyy <- simdata[,i] ## sm2 <- refit(smallModel, newresp=yyy) ## lg2 <- refit(largeModel, newresp=yyy) ## t.sim <- 2 * (logLik(lg2, REML=FALSE) - logLik(sm2, REML=FALSE)) ## ref[i] <- t.sim ## if (t.sim >= t.obs) ## n.extreme <- n.extreme + 1 ## if (n.extreme >= h) ## break ## } ## ref <- ref[1:count] ## ans <- PBmodcomp(largeModel, smallModel, ref = ref) ## ans$ctime <- (proc.time() - t.start)[3] ## ans ## } ## plot.XXmodcomp <- function(x, ...){ ## test <- x$test ## tobs <- test$LRT['stat'] ## ref <- attr(x,"ref") ## rr <- range(ref) ## xx <- seq(rr[1],rr[2],0.1) ## dd <- density(ref) ## sc <- var(ref)/mean(ref) ## sh <- mean(ref)^2/var(ref) ## hist(ref, prob=TRUE,nclass=20, main="Reference distribution") ## abline(v=tobs) ## lines(dd, lty=2, col=2, lwd=2) ## lines(xx,dchisq(xx,df=test$LRT['df']), lty=3, col=3, lwd=2) ## lines(xx,dgamma(xx,scale=sc, shape=sh), lty=4, col=4, lwd=2) ## lines(xx,df(xx,df1=test$F['df'], df2=test$F['ddf']), lty=5, col=5, lwd=2) ## smartlegend(x = 'right', y = 'top', ## legend = c("kernel density", "chi-square", "gamma","F"), ## col = 2:5, lty = 2:5) ## } ## rho <- VV/(2*EE^2) ## ddf2 <- (ndf*(4*rho+1) - 2)/(rho*ndf-1) ## lam2 <- (ddf/(ddf-2))/(EE/ndf) ## cat(sprintf("EE=%f, VV=%f, rho=%f, lam2=%f\n", ## EE, VV, rho, lam2)) ## ddf2 <- 4 + (ndf+2)/(rho*ndf-1) ## Fobs2 <- lam2 * tobs/ndf ## if (ddf2>0) ## p.FF2 <- 1-pf(Fobs2, df1=ndf, df2=ddf2) ## else ## p.FF2 <- NA <file_sep>/R/KR-init-modcomp.R KRmodcomp_init <- function(m1, m2, matrixOK=FALSE){ UseMethod("KRmodcomp_init") } KRmodcomp_init.lmerMod <- function(m1, m2, matrixOK=FALSE) { ##comparison of the mean structures of the models ## it is tested for that (1) m1 is mer and (2) m2 is either mer or a matrix ## mers <- if (.is.lmm(m1) & (.is.lmm(m2) | is.matrix(m2) ) ) TRUE ## else FALSE mers <- (.is.lmm(m1) & (.is.lmm(m2) | is.matrix(m2))) if (!mers) { cat("Error in modcomp_init\n") cat(paste("either model ",substitute(m1), "\n is not a linear mixed of class mer(CRAN) or lmerMod (GitHub)\n \n",sep=' ')) cat(paste("or model ", substitute(m2),"\n is neither of that class nor a matrix",sep='')) stop() } ##checking matrixcOK is FALSE but m2 is a matrix if (!matrixOK & is.matrix(m2)) { cat ('Error in modcomp_init \n') cat (paste('matrixOK =FALSE but the second model: ', substitute(m2), '\n is specified via a restriction matrix \n \n',sep='')) stop() } Xlarge <- getME(m1, "X") rlarge <- rankMatrix(Xlarge) code <- if (.is.lmm(m2)){ Xsmall <- getME(m2,"X") rsmall <- rankMatrix(Xsmall) rboth <- rankMatrix(cbind(Xlarge, Xsmall)) if (rboth == pmax(rlarge, rsmall)) { if (rsmall < rlarge) { 1 } else { if (rsmall > rlarge) { 0 } else { -1 } } } else { -1 } } else { ##now model m2 is a restriction matrix if (rankMatrix(rbind(Xlarge,m2)) > rlarge) { -1 } else { 1 } } code } KRmodcomp_init.mer <- KRmodcomp_init.lmerMod <file_sep>/R/KR-Sigma-G2.R ## ############################################################################## ## ## LMM_Sigma_G: Returns VAR(Y) = Sigma and the G matrices ## ## Re-implemented in Banff, Canada, August 2013 by <NAME> ## ## ############################################################################## #' @export get_SigmaG <- function(object, details=0) { UseMethod("get_SigmaG") } #' @export get_SigmaG.lmerMod <- function(object, details=0) { .get_SigmaG( object, details ) } #' @export get_SigmaG.mer <- function(object, details=0) { LMM_Sigma_G( object, details ) } .get_SigmaG <- function(object, details=0) { DB <- details > 0 ## For debugging only if (!.is.lmm(object)) stop("'object' is not Gaussian linear mixed model") GGamma <- VarCorr(object) SS <- .shgetME( object ) ## Put covariance parameters for the random effects into a vector: ## Fixme: It is a bit ugly to throw everything into one long vector here; a list would be more elegant ggamma <- NULL for ( ii in 1:( SS$n.RT )) { Lii <- GGamma[[ii]] ggamma <- c(ggamma, Lii[ lower.tri( Lii, diag=TRUE ) ] ) } ggamma <- c( ggamma, sigma( object )^2 ) ## Extend ggamma by the residuals variance n.ggamma <- length(ggamma) ## Find G_r: G <- NULL Zt <- getME( object, "Zt" ) for (ss in 1:SS$n.RT) { ZZ <- .shget_Zt_group( ss, Zt, SS$Gp ) n.lev <- SS$n.lev.by.RT2[ ss ] ## ; cat(sprintf("n.lev=%i\n", n.lev)) Ig <- sparseMatrix(1:n.lev, 1:n.lev, x=1) for (rr in 1:SS$n.parm.by.RT[ ss ]) { ## This is takes care of the case where there is random regression and several matrices have to be constructed. ## FIXME: I am not sure this is correct if there is a random quadratic term. The '2' below looks suspicious. ii.jj <- .index2UpperTriEntry( rr, SS$n.comp.by.RT[ ss ] ) ##; cat("ii.jj:"); print(ii.jj) ii.jj <- unique(ii.jj) if (length(ii.jj)==1){ EE <- sparseMatrix(ii.jj, ii.jj, x=1, dims=rep(SS$n.comp.by.RT[ ss ], 2)) } else { EE <- sparseMatrix(ii.jj, ii.jj[2:1], dims=rep(SS$n.comp.by.RT[ ss ], 2)) } EE <- Ig %x% EE ## Kronecker product G <- c( G, list( t(ZZ) %*% EE %*% ZZ ) ) } } ## Extend by the indentity for the residual n.obs <- nrow(getME(object,'X')) G <- c( G, list(sparseMatrix(1:n.obs, 1:n.obs, x=1 )) ) Sigma <- ggamma[1] * G[[1]] for (ii in 2:n.ggamma) { Sigma <- Sigma + ggamma[ii] * G[[ii]] } SigmaG <- list(Sigma=Sigma, G=G, n.ggamma=n.ggamma) SigmaG } .shgetME <- function( object ){ Gp <- getME( object, "Gp" ) n.RT <- length( Gp ) - 1 ## Number of random terms ( i.e. of (|)'s ) n.lev.by.RT <- sapply(getME(object, "flist"), function(x) length(levels(x))) n.comp.by.RT <- .get.RT.dim.by.RT( object ) n.parm.by.RT <- (n.comp.by.RT + 1) * n.comp.by.RT / 2 n.RE.by.RT <- diff( Gp ) n.lev.by.RT2 <- n.RE.by.RT / n.comp.by.RT ## Same as n.lev.by.RT2 ??? list(Gp = Gp, ## group.index n.RT = n.RT, ## n.groupFac n.lev.by.RT = n.lev.by.RT, ## nn.groupFacLevelsNew n.comp.by.RT = n.comp.by.RT, ## nn.GGamma n.parm.by.RT = n.parm.by.RT, ## mm.GGamma n.RE.by.RT = n.RE.by.RT, ## ... Not returned before n.lev.by.RT2 = n.lev.by.RT2, ## nn.groupFacLevels n_rtrms = getME( object, "n_rtrms") ) } .getME.all <- function(obj) { nmME <- eval(formals(getME)$name) sapply(nmME, function(nm) try(getME(obj, nm)), simplify=FALSE) } ## Alternative to .get_Zt_group .shget_Zt_group <- function( ii.group, Zt, Gp, ... ){ zIndex.sub <- (Gp[ii.group]+1) : Gp[ii.group+1] ZZ <- Zt[ zIndex.sub , ] return(ZZ) } ## ## Modular implementation ## .get_GI_parms <- function( object ){ GGamma <- VarCorr(object) parmList <- lapply(GGamma, function(Lii){ Lii[ lower.tri( Lii, diag=TRUE ) ] }) parmList <- c( parmList, sigma( object )^2 ) parmList } .get_GI_matrices <- function( object ){ SS <- .shgetME( object ) Zt <- getME( object, "Zt" ) G <- NULL G <- vector("list", SS$n.RT+1) for (ss in 1:SS$n.RT) { ZZ <- .shget_Zt_group( ss, Zt, SS$Gp ) n.lev <- SS$n.lev.by.RT2[ ss ] ## ; cat(sprintf("n.lev=%i\n", n.lev)) Ig <- sparseMatrix(1:n.lev, 1:n.lev, x=1) UU <- vector("list", SS$n.parm.by.RT) for (rr in 1:SS$n.parm.by.RT[ ss ]) { ii.jj <- .index2UpperTriEntry( rr, SS$n.comp.by.RT[ ss ] ) ii.jj <- unique(ii.jj) if (length(ii.jj)==1){ EE <- sparseMatrix(ii.jj, ii.jj, x=1, dims=rep(SS$n.comp.by.RT[ ss ], 2)) } else { EE <- sparseMatrix(ii.jj, ii.jj[2:1], dims=rep(SS$n.comp.by.RT[ ss ], 2)) } EE <- Ig %x% EE ## Kronecker product UU[[ rr ]] <- t(ZZ) %*% EE %*% ZZ } G[[ ss ]] <- UU } n.obs <- nrow(getME(object,'X')) G[[ length( G ) ]] <- sparseMatrix(1:n.obs, 1:n.obs, x=1 ) G } <file_sep>/R/zzz-PB-anova-not-used.R ### ########################################################### ### ### PBanova ### ### ########################################################### ##.PBanova <- function(largeModel, smallModel=NULL, nsim=200, cl=NULL){ ## if (is.null(smallModel)){ ## fixef.name <- rev(attr(terms(largeModel),"term.labels")) ## ans1 <- list() ## ans2 <- list() ## ## for (kk in seq_along(fixef.name)){ ## dropped <- fixef.name[kk] ## newf <- as.formula(paste(".~.-", dropped)) ## smallModel <- update(largeModel, newf) ## #cat(sprintf("dropped: %s\n", dropped)) ## rr <- PBrefdist(largeModel, smallModel, nsim=nsim, cl=cl) ## ans1[[kk]] <- PBmodcomp(largeModel, smallModel, ref=rr) ## #ans2[[kk]] <- .FFmodcomp(largeModel, smallModel, ref=rr) ## largeModel <- smallModel ## } ## ## ans12 <- lapply(ans1, as.data.frame) ## ans22 <- lapply(ans2, as.data.frame) ## ## ans3 <- list() ## for (kk in seq_along(fixef.name)){ ## dropped <- fixef.name[kk] ## ans3[[kk]] <- ## rbind( ## cbind(term=dropped, test=rownames(ans12[[kk]]), ans12[[kk]],df2=NA), ## cbind(term=dropped, test=rownames(ans22[[kk]][2,,drop=FALSE]), ans22[[kk]][2,,drop=FALSE])) ## ## } ## ## ans3 <- rev(ans3) ## ans4 <- do.call(rbind, ans3) ## rownames(ans4) <- NULL ## ans4$p<-round(ans4$p,options("digits")$digits) ## ans4$tobs<-round(ans4$tobs,options("digits")$digits) ## ## ans4 ## } else { ## ## ## } ##} ## <file_sep>/R/modelCoercion.R ## FIXME: model2restrictionMatrix -> m2rm ## FIXME: restrictionMatrix2model -> rm2m ################################################################################ #' @title Conversion between a model object and a restriction matrix #' #' @description Testing a small model under a large model corresponds #' imposing restrictions on the model matrix of the larger model #' and these restrictions come in the form of a restriction #' matrix. These functions converts a model to a restriction #' matrix and vice versa. #' #' @name model-coerce ################################################################################ #' @aliases model2restrictionMatrix model2restrictionMatrix.lm #' model2restrictionMatrix.mer model2restrictionMatrix.merMod #' restrictionMatrix2model restrictionMatrix2model.lm #' restrictionMatrix2model.mer restrictionMatrix2model.merMod #' #' @param largeModel,smallModel Model objects of the same "type". Possible types #' are linear mixed effects models and linear models (including generalized #' linear models) #' @param LL A restriction matrix. #' @return \code{model2restrictionMatrix}: A restriction matrix. #' \code{restrictionMatrix2model}: A model object. #' @note That these functions are visible is a recent addition; minor changes #' may occur. #' @author <NAME> \email{<EMAIL>}, <NAME> #' \email{<EMAIL>} #' @seealso \code{\link{PBmodcomp}}, \code{\link{PBrefdist}}, #' \code{\link{KRmodcomp}} #' @references <NAME>, <NAME> (2014)., A Kenward-Roger #' Approximation and Parametric Bootstrap Methods for Tests in Linear Mixed #' Models - The R Package pbkrtest., Journal of Statistical Software, #' 58(10), 1-30., \url{http://www.jstatsoft.org/v59/i09/} #' @keywords utilities #' #' @examples #' library(pbkrtest) #' data("beets", package = "pbkrtest") #' sug <- lm(sugpct ~ block + sow + harvest, data=beets) #' sug.h <- update(sug, .~. - harvest) #' sug.s <- update(sug, .~. - sow) #' #' ## Construct restriction matrices from models #' L.h <- model2restrictionMatrix(sug, sug.h); L.h #' L.s <- model2restrictionMatrix(sug, sug.s); L.s #' #' ## Construct submodels from restriction matrices #' mod.h <- restrictionMatrix2model(sug, L.h); mod.h #' mod.s <- restrictionMatrix2model(sug, L.s); mod.s #' #' ## The models have the same fitted values #' plot(fitted(mod.h), fitted(sug.h)) #' plot(fitted(mod.s), fitted(sug.s)) #' ## and the same log likelihood #' logLik(mod.h) #' logLik(sug.h) #' logLik(mod.s) #' logLik(sug.s) #' #' @export model2restrictionMatrix #' @rdname model-coerce model2restrictionMatrix <- function (largeModel, smallModel) { UseMethod("model2restrictionMatrix") } #' @method model2restrictionMatrix merMod #' @export model2restrictionMatrix.merMod <- model2restrictionMatrix.mer <- function (largeModel, smallModel) { L <- if(is.matrix(smallModel)) { ## ensures that L is of full row rank: LL <- smallModel q <- rankMatrix(LL) if (q < nrow(LL) ){ t(qr.Q(qr(t(LL)))[,1:qr(LL)$rank]) } else { smallModel } } else { #smallModel is mer model .restrictionMatrixBA(getME(largeModel,'X'), getME(smallModel,'X')) } L<-.makeSparse(L) L } #' @method model2restrictionMatrix lm #' @export model2restrictionMatrix.lm <- function (largeModel, smallModel) { L <- if(is.matrix(smallModel)) { ## ensures that L is of full row rank: LL <- smallModel q <- rankMatrix(LL) if (q < nrow(LL) ){ t(qr.Q(qr(t(LL)))[,1:qr(LL)$rank]) } else { smallModel } } else { #smallModel is mer model .restrictionMatrixBA(model.matrix( largeModel ), model.matrix( smallModel )) } L<-.makeSparse(L) L } .formula2list <- function(form){ lhs <- form[[2]] tt <- terms(form) tl <- attr(tt, "term.labels") r.idx <- grep("\\|", tl) if (length(r.idx)){ rane <- paste("(", tl[r.idx], ")") f.idx <- (1:length(tl))[-r.idx] if (length(f.idx)) fixe <- tl[f.idx] else fixe <- NULL } else { rane <- NULL fixe <- tl } ans <- list(lhs=deparse(lhs), rhs.fix=fixe, rhs.ran=rane) ans } #' @rdname model-coerce #' @export restrictionMatrix2model <- function(largeModel, LL){ UseMethod("restrictionMatrix2model") } ## #' @rdname model-coerce #' @export restrictionMatrix2model.merMod <- restrictionMatrix2model.mer <- function(largeModel, LL){ XX.lg <- getME(largeModel, "X") form <- as.formula(formula(largeModel)) attributes(XX.lg)[-1] <- NULL XX.sm <- .restrictedModelMatrix(XX.lg, LL) ncX.sm <- ncol(XX.sm) colnames(XX.sm) <- paste(".X", 1:ncX.sm, sep='') rhs.fix2 <- paste(".X", 1:ncX.sm, sep='', collapse="+") fff <- .formula2list(form) new.formula <- as.formula(paste(fff$lhs, "~ -1+", rhs.fix2, "+", fff$rhs.ran)) new.data <- cbind(XX.sm, eval(largeModel@call$data)) ## ans <- lmer(eval(new.formula), data=new.data, REML=getME(largeModel, "is_REML")) ans <- update(largeModel, eval(new.formula), data=new.data) ans } ## #' @rdname model-coerce #' @export restrictionMatrix2model.lm <- function(largeModel, LL){ form <- as.formula(formula(largeModel)) XX.lg <- model.matrix(largeModel) attributes(XX.lg)[-1] <- NULL XX.sm <- zapsmall( .restrictedModelMatrix(XX.lg, LL) ) ncX.sm <- ncol(XX.sm) colnames(XX.sm) <- paste(".X", 1:ncX.sm, sep='') rhs.fix2 <- paste(".X", 1:ncX.sm, sep='', collapse="+") fff <- .formula2list(form) new.formula <- as.formula(paste(fff$lhs, "~ -1+", rhs.fix2)) new.data <- as.data.frame(cbind(XX.sm, eval(largeModel$model))) #print(new.data) ans <- update(largeModel, eval(new.formula), data=new.data) ans } .restrictedModelMatrix<-function(B,L) { ##cat("B:\n"); print(B); cat("L:\n"); print(L) ## find A such that <A>={Bb| b in Lb=0} ## if (!is.matrix(L)) ## L <- matrix(L, nrow=1) if ( !inherits(L, c("matrix", "Matrix")) ) L <- matrix(L, nrow=1) L <- as(L, "matrix") if ( ncol(B) != ncol(L) ) { print(c( ncol(B), ncol(L) )) stop('Number of columns of B and L not equal \n') } A <- B %*% .orthComplement(t(L)) A } .restrictionMatrixBA<-function(B,A) { ## <A> in <B> ## determine L such that <A>={Bb| b in Lb=0} d <- rankMatrix(cbind(A,B)) - rankMatrix(B) if (d > 0) { stop('Error: <A> not subspace of <B> \n') } Q <- qr.Q(qr(cbind(A,B))) Q2 <- Q[,(rankMatrix(A)+1):rankMatrix(B)] L <- t(Q2) %*% B ##make rows of L2 orthogonal L <-t(qr.Q(qr(t(L)))) L } .model2restrictionMatrix <- function (largeModel, smallModel) { L <- if(is.matrix(smallModel)) { ## ensures that L is of full row rank: LL <- smallModel q <- rankMatrix(LL) if (q < nrow(LL) ){ t(qr.Q(qr(t(LL)))[,1:qr(LL)$rank]) } else { smallModel } } else { #smallModel is mer model .restrictionMatrixBA(getME(largeModel,'X'), getME(smallModel,'X')) } L<-.makeSparse(L) L } <file_sep>/R/PB-refdist.R ### ########################################################### ### ### Computing of reference distribution; possibly in parallel ### ### ########################################################### #' @title Calculate reference distribution using parametric bootstrap #' #' @description Calculate reference distribution of likelihood ratio statistic #' in mixed effects models using parametric bootstrap #' #' @name pb-refdist #' #' @details The model \code{object} must be fitted with maximum likelihood #' (i.e. with \code{REML=FALSE}). If the object is fitted with restricted #' maximum likelihood (i.e. with \code{REML=TRUE}) then the model is #' refitted with \code{REML=FALSE} before the p-values are calculated. Put #' differently, the user needs not worry about this issue. #' #' The argument 'cl' (originally short for 'cluster') is used for #' controlling parallel computations. 'cl' can be NULL (default), #' positive integer or a list of clusters. #' #' #' Special care must be taken #' on Windows platforms (described below) but the general picture #' is this: #' #' The recommended way of controlling cl is to specify the #' component \code{pbcl} in options() with #' e.g. \code{options("pbcl"=4)}. #' #' If cl is NULL, the function will look at if the pbcl has been set #' in the options list with \code{getOption("pbcl")} #' #' If cl=N then N cores will be used in the computations. If cl is #' NULL then the function will look for #' #' #' @aliases PBrefdist PBrefdist.merMod PBrefdist.lm #' #' @param largeModel A linear mixed effects model as fitted with the #' \code{lmer()} function in the \pkg{lme4} package. This model muse be #' larger than \code{smallModel} (see below). #' @param smallModel A linear mixed effects model as fitted with the #' \code{lmer()} function in the \pkg{lme4} package. This model muse be #' smaller than \code{largeModel} (see above). #' @param nsim The number of simulations to form the reference distribution. #' @param seed Seed for the random number generation. #' #' @param cl Used for controlling parallel computations. See sections #' 'details' and 'examples' below. #' #' @param details The amount of output produced. Mainly relevant for debugging #' purposes. #' @return A numeric vector #' @author <NAME> \email{<EMAIL>} #' @seealso \code{\link{PBmodcomp}}, \code{\link{KRmodcomp}} #' @references <NAME>, <NAME> (2014)., A Kenward-Roger #' Approximation and Parametric Bootstrap Methods for Tests in Linear Mixed #' Models - The R Package pbkrtest., Journal of Statistical Software, #' 58(10), 1-30., \url{http://www.jstatsoft.org/v59/i09/} #' #' @keywords models inference #' @examples #' #' data(beets) #' head(beets) #' beet0 <- lmer(sugpct ~ block + sow + harvest + (1|block:harvest), data=beets, REML=FALSE) #' beet_no.harv <- update(beet0, . ~ . -harvest) #' rd <- PBrefdist(beet0, beet_no.harv, nsim=20, cl=1) #' rd #' \dontrun{ #' ## Note: Many more simulations must be made in practice. #' #' # Computations can be made in parallel using several processors: #' #' # 1: On OSs that fork processes (that is, not on windows): #' # -------------------------------------------------------- #' #' if (Sys.info()["sysname"] != "Windows"){ #' N <- 2 ## Or N <- parallel::detectCores() #' #' # N cores used in all calls to function in a session #' options("mc.cores"=N) #' rd <- PBrefdist(beet0, beet_no.harv, nsim=20) #' #' # N cores used just in one specific call (when cl is set, #' # options("mc.cores") is ignored): #' rd <- PBrefdist(beet0, beet_no.harv, nsim=20, cl=N) #' } #' #' # In fact, on Windows, the approach above also work but only when setting the #' # number of cores to 1 (so there is to parallel computing) #' #' # In all calls: #' # options("mc.cores"=1) #' # rd <- PBrefdist(beet0, beet_no.harv, nsim=20) #' # Just once #' # rd <- PBrefdist(beet0, beet_no.harv, nsim=20, cl=1) #' #' # 2. On all platforms (also on Windows) one can do #' # ------------------------------------------------ #' library(parallel) #' N <- 2 ## Or N <- detectCores() #' clus <- makeCluster(rep("localhost", N)) #' #' # In all calls in a session #' options("pb.cl"=clus) #' rd <- PBrefdist(beet0, beet_no.harv, nsim=20) #' #' # Just once: #' rd <- PBrefdist(beet0, beet_no.harv, nsim=20, cl=clus) #' stopCluster(clus) #' } #' @rdname pb-refdist #' @export PBrefdist <- function(largeModel, smallModel, nsim=1000, seed=NULL, cl=NULL, details=0){ UseMethod("PBrefdist") } #' @rdname pb-refdist #' @export PBrefdist.lm <- function(largeModel, smallModel, nsim=1000, seed=NULL, cl=NULL, details=0){ t0 <- proc.time() get_fun <- .get_refDist_lm ref <- .do_sampling(largeModel, smallModel, nsim, cl, get_fun, details) ref <- ref[ref>0] ctime <- (proc.time()-t0)[3] attr(ref,"ctime") <- ctime LRTstat <- getLRT(largeModel, smallModel) attr(ref, "stat") <- LRTstat attr(ref, "samples") <- c(nsim=nsim, npos=sum(ref > 0), n.extreme=sum(ref > LRTstat["tobs"]), pPB=(1 + sum(ref > LRTstat["tobs"])) / (1 + sum(ref > 0))) if (details>0) cat(sprintf("Reference distribution with %i samples; computing time: %5.2f secs. \n", length(ref), ctime)) ref } #' @rdname pb-refdist #' @export PBrefdist.merMod <- function(largeModel, smallModel, nsim=1000, seed=NULL, cl=NULL, details=0){ t0 <- proc.time() if (getME(smallModel, "is_REML")) smallModel <- update(smallModel, REML=FALSE) if (getME(largeModel, "is_REML")) largeModel <- update(largeModel, REML=FALSE) get_fun <- .get_refdist_merMod ref <- .do_sampling(largeModel, smallModel, nsim, cl, get_fun, details) LRTstat <- getLRT(largeModel, smallModel) ctime <- (proc.time()-t0)[3] attr(ref, "ctime") <- ctime attr(ref, "stat") <- LRTstat attr(ref, "samples") <- c(nsim=nsim, npos=sum(ref > 0), n.extreme=sum(ref > LRTstat["tobs"]), pPB=(1 + sum(ref > LRTstat["tobs"])) / (1 + sum(ref > 0))) if (details>0) cat(sprintf("Reference distribution with %5i samples; computing time: %5.2f secs. \n", length(ref), ctime)) ref } .get_refDist_lm <- function(lg, sm, nsim=20, seed=NULL, simdata=simulate(sm, nsim=nsim, seed=seed)){ ##simdata <- simulate(sm, nsim, seed=seed) ee <- new.env() ee$simdata <- simdata ff.lg <- update.formula(formula(lg),simdata[,ii]~.) ff.sm <- update.formula(formula(sm),simdata[,ii]~.) environment(ff.lg) <- environment(ff.sm) <- ee cl.lg <- getCall(lg) cl.sm <- getCall(sm) cl.lg$formula <- ff.lg cl.sm$formula <- ff.sm ref <- rep.int(NA, nsim) for (ii in 1:nsim){ ref[ii] <- 2 * (logLik(eval(cl.lg)) - logLik(eval(cl.sm))) } ref } .get_refdist_merMod <- function(lg, sm, nsim=20, seed=NULL, simdata=simulate(sm, nsim=nsim, seed=seed)){ #simdata <- simulate(sm, nsim=nsim, seed=seed) unname(unlist(lapply(simdata, function(yyy){ sm2 <- suppressMessages(refit(sm, newresp=yyy)) lg2 <- suppressMessages(refit(lg, newresp=yyy)) 2 * (logLik(lg2, REML=FALSE) - logLik(sm2, REML=FALSE)) }))) } .do_sampling <- function(largeModel, smallModel, nsim, cl, get_fun, details=0){ .cat <- function(b, ...) {if (b) cat(...)} dd <- details if (Sys.info()["sysname"] == "Windows"){ ##cat("We are on windows; setting cl=1\n") cl <- 1 } if (!is.null(cl)){ if (inherits(cl, "cluster") || (is.numeric(cl) && length(cl) == 1 && cl >= 1)){ .cat(dd>3, "valid 'cl' specified in call \n") } else stop("invalid 'cl' specified in call \n") } else { .cat(dd>3, "trying to retrieve 'cl' from options('pb.cl') ... \n") cl <- getOption("pb.cl") if (!is.null(cl)){ if (!inherits(cl, "cluster")) stop("option 'cl' set but is not a list of clusters\n") .cat(dd>3," got 'cl' from options; length(cl) = ", length(cl), "\n") } if (is.null(cl)){ .cat(dd>3, "trying to retrieve 'cl' from options('mc.cores')... \n") cl <- getOption("mc.cores") if (!is.null(cl)) .cat(dd>3," got 'cl' from options(mc.cores); cl = ", cl, "\n") } } if (is.null(cl)){ .cat(dd > 3, "cl can not be retrieved anywhere; setting cl=1\n") cl <- 1 } if (is.numeric(cl)){ if (!(length(cl) == 1 && cl >= 1)) stop("Invalid numeric cl\n") .cat(dd>3, "doing mclapply, cl = ", cl, "\n") nsim.cl <- nsim %/% cl ref <- unlist(mclapply(1:cl, function(i) {get_fun(largeModel, smallModel, nsim=nsim.cl)}, mc.cores=cl)) } else if (inherits(cl, "cluster")){ .cat(dd>3,"doing clusterCall, nclusters = ", length(cl), "\n") nsim.cl <- nsim %/% length(cl) clusterSetRNGStream(cl) ref <- unlist(clusterCall(cl, fun=get_fun, largeModel, smallModel, nsim=nsim.cl)) } else stop("Invalid 'cl'\n") } <file_sep>/R/namespace.R #' @import lme4 #' @importFrom MASS ginv #' @importFrom magrittr "%>%" #' @export "%>%" #' @importFrom parallel clusterCall clusterExport clusterSetRNGStream #' mclapply detectCores makeCluster #' #' @importClassesFrom Matrix Matrix #' @importFrom Matrix Matrix sparseMatrix rankMatrix #' @importMethodsFrom Matrix t isSymmetric "%*%" solve diag chol #' chol2inv forceSymmetric "*" #' #' @importFrom graphics abline legend lines plot #' @importFrom methods as is #' @importFrom stats as.formula family formula getCall logLik #' model.matrix pchisq pf pgamma printCoefmat quantile simulate #' terms update update.formula var vcov sigma #' .dumfunction_afterimportFrom <- function(){} #' @title pbkrtest internal #' @description pbkrtest internal #' @name internal-pbkrtest #' #' @aliases "%>%" NULL <file_sep>/R/KR-Sigma-G.R ## ############################################################################## ## ## LMM_Sigma_G: Returns VAR(Y) = Sigma and the G matrices ## ## ############################################################################## LMM_Sigma_G <- function(object, details=0) { DB <- details > 0 ## For debugging only if (!.is.lmm(object)) stop("'object' is not Gaussian linear mixed model") GGamma <- VarCorr(object) ## Indexing of the covariance matrix; ## this is somewhat technical and tedious Nindex <- .get_indices(object) ## number of random effects in each groupFac; note: residual error excluded! n.groupFac <- Nindex$n.groupFac ## the number of random effects for each grouping factor nn.groupFacLevels <- Nindex$nn.groupFacLevels ## size of the symmetric variance Gamma_i for reach groupFac nn.GGamma <- Nindex$nn.GGamma ## number of variance parameters of each GGamma_i mm.GGamma <- Nindex$mm.GGamma ## not sure what this is... group.index <- Nindex$group.index ## writing the covariance parameters for the random effects into a vector: ggamma <- NULL for ( ii in 1:(n.groupFac) ) { Lii <- GGamma[[ii]] nu <- ncol(Lii) ## Lii[lower.tri(Lii,diag=TRUE)= Lii[1,1],Lii[1,2],Lii[1,3]..Lii[1,nu], ## Lii[2,2], Lii[2,3] ... ggamma<-c(ggamma,Lii[lower.tri(Lii,diag=TRUE)]) } ## extend ggamma by the residuals variance such that everything random is included ggamma <- c( ggamma, sigma( object )^2 ) n.ggamma <- length(ggamma) ## Find G_r: Zt <- getME( object, "Zt" ) t0 <- proc.time() G <- NULL ##cat(sprintf("n.groupFac=%i\n", n.groupFac)) for (ss in 1:n.groupFac) { ZZ <- .get_Zt_group(ss, Zt, object) ##cat("ZZ\n"); print(ZZ) n.levels <- nn.groupFacLevels[ss] ##cat(sprintf("n.levels=%i\n", n.levels)) Ig <- sparseMatrix(1:n.levels, 1:n.levels, x=1) ##print(Ig) for (rr in 1:mm.GGamma[ss]) { ii.jj <- .indexVec2Symmat(rr,nn.GGamma[ss]) ##cat("ii.jj:"); print(ii.jj) ii.jj <- unique(ii.jj) if (length(ii.jj)==1){ EE <- sparseMatrix(ii.jj, ii.jj, x=1, dims=rep(nn.GGamma[ss],2)) } else { EE <- sparseMatrix(ii.jj, ii.jj[2:1], dims=rep(nn.GGamma[ss],2)) } ##cat("EE:\n");print(EE) EE <- Ig %x% EE ## Kronecker product G <- c( G, list( t(ZZ) %*% EE %*% ZZ ) ) } } ## Extend by the indentity for the residual nobs <- nrow(getME(object,'X')) G <- c( G, list(sparseMatrix(1:nobs, 1:nobs, x=1 )) ) if(DB){cat(sprintf("Finding G %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} Sigma <- ggamma[1] * G[[1]] for (ii in 2:n.ggamma) { Sigma <- Sigma + ggamma[ii] * G[[ii]] } if(DB){cat(sprintf("Finding Sigma: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} SigmaG <- list(Sigma=Sigma, G=G, n.ggamma=n.ggamma) SigmaG } .get_indices <-function(object) { ## ff = number of random effects terms (..|F1) + (..|F1) are group factors! ## without the residual variance output: list of several indices ## we need the number of random-term factors Gp <- getME(object,"Gp") ff <- length(Gp)-1 gg <- sapply(getME(object,"flist"), function(x)length(levels(x))) qq <- .get.RT.dim.by.RT( object ) ##; cat("qq:\n"); print(qq) ## number of variance parameters of each GGamma_i ss <- qq * (qq+1) / 2 ## numb of random effects per level of random-term-factor nn.groupFac <- diff(Gp) ##cat("nn.groupFac:\n"); print(nn.groupFac) ## number of levels for each random-term-factor; residual error here excluded! nn.groupFacLevels <- nn.groupFac / qq ## this is the number of random term factors, should possible get a more approriate name list(n.groupFac = ff, nn.groupFacLevelsNew = gg, # length of different grouping factors nn.groupFacLevels = nn.groupFacLevels, # vector of the numb. levels for each random-term-factor nn.GGamma = qq, mm.GGamma = ss, group.index = Gp) } .get_Zt_group <- function(ii.group, Zt, object) { ## ii.group : the index number of a grouping factor ## Zt : the transpose of the random factors design matrix Z ## object : A mer or lmerMod model ##output : submatrix of Zt belongig to grouping factor ii.group Nindex <- .get_indices(object) nn.groupFacLevels <- Nindex$nn.groupFacLevels nn.GGamma <- Nindex$nn.GGamma group.index <- Nindex$group.index .cc <- class(object) ## cat(".get_Zt_group\n"); ## print(group.index) ## print(ii.group) zIndex.sub <- if (.cc %in% "mer") { Nindex$group.index[ii.group]+ 1+c(0:(nn.GGamma[ii.group]-1))*nn.groupFacLevels[ii.group] + rep(0:(nn.groupFacLevels[ii.group]-1),each=nn.GGamma[ii.group]) } else { if (.cc %in% "lmerMod" ) { c((group.index[ii.group]+1) : group.index[ii.group+1]) } } ZZ <- Zt[ zIndex.sub , ] return(ZZ) } <file_sep>/R/KR-utils.R .makeSparse<-function(X) { X <- as.matrix( X ) w <- cbind( c(row(X)), c(col(X)), c(X)) w <- w[ abs( w[,3] ) > 1e-16, ,drop = FALSE] Y <- sparseMatrix( w[,1], w[,2], x=w[,3], dims=dim(X)) } ##if A is a N x N matrix A[i,j] ## and R=c(A[1,1],A[1,2]...A[1,n],A[2,1]..A[2,n],, A[n,n] ## A[i,j]=R[r] .ij2r<-function(i,j,N) (i-1)*N+j .indexSymmat2vec <- function(i,j,N) { ## S[i,j] symetric N times N matrix ## r the vector of upper triangular element in row major order: ## r= c(S[1,1],S[1,2]...,S[1,j], S[1,N], S[2,2],...S[N,N] ##Result: k: index of k-th element of r k <-if (i<=j) { (i-1)*(N-i/2)+j } else { (j-1)*(N-j/2)+i } } .indexVec2Symmat<-function(k,N) { ## inverse of indexSymmat2vec ## result: index pair (i,j) with i>=j ## k: element in the vector of upper triangular elements ## example: N=3: k=1 -> (1,1), k=2 -> (1,2), k=3 -> (1,3), k=4 -> (2,2) aa <- cumsum(N:1) aaLow <- c(0,aa[-length(aa)]) i <- which( aaLow<k & k<=aa) j <- k-N*i+N-i*(3-i)/2+i return( c(i,j) ) } .index2UpperTriEntry <- .indexVec2Symmat .divZero<-function(x, y, tol=1e-14){ ## ratio x/y is set to 1 if both |x| and |y| are below tol x.y <- if( abs(x)<tol & abs(y)<tol) { 1 } else { x/y } x.y } .is.lmm <- function(object) { ##if (class(object) %in% c("matrix","Matrix")){ if (inherits(object, c("matrix", "Matrix"))){ FALSE } else { lme4::isLMM(object) } } ## .is.lmm <- function(object) { ## ##checks whether object is ## ## - mer object AND ## ## - linear mixed model ## if (class(object) %in% "mer") { ## if (length(object@muEta)==0 ) ## TRUE ## else ## ## FALSE ## ## } else { ## ## FALSE ## ## } ## ## } <file_sep>/R/get_ddf_Lb.R #' @title Adjusted denomintor degress freedom for linear estimate for linear #' mixed model. #' #' @description Get adjusted denomintor degress freedom for testing Lb=0 in a #' linear mixed model where L is a restriction matrix. #' #' @name get_ddf_Lb #' #' @aliases get_Lb_ddf get_Lb_ddf.lmerMod Lb_ddf #' #' @param object A linear mixed model object. #' @param L A vector with the same length as \code{fixef(object)} or a matrix #' with the same number of columns as the length of \code{fixef(object)} #' @param V0,Vadj Unadjusted and adjusted covariance matrix for the fixed #' effects parameters. Undjusted covariance matrix is obtained with #' \code{vcov()} and adjusted with \code{vcovAdj()}. #' @return Adjusted degrees of freedom (adjusment made by a Kenward-Roger #' approximation). #' #' @author <NAME>, \email{<EMAIL>} #' @seealso \code{\link{KRmodcomp}}, \code{\link{vcovAdj}}, #' \code{\link{model2restrictionMatrix}}, #' \code{\link{restrictionMatrix2model}} #' @references <NAME>, <NAME> (2014)., A Kenward-Roger #' Approximation and Parametric Bootstrap Methods for Tests in Linear Mixed #' Models - The R Package pbkrtest., Journal of Statistical Software, #' 58(10), 1-30., \url{http://www.jstatsoft.org/v59/i09/} #' #' @keywords inference models #' @examples #' #' (fmLarge <- lmer(Reaction ~ Days + (Days|Subject), sleepstudy)) #' ## removing Days #' (fmSmall <- lmer(Reaction ~ 1 + (Days|Subject), sleepstudy)) #' anova(fmLarge,fmSmall) #' #' KRmodcomp(fmLarge, fmSmall) ## 17 denominator df's #' get_Lb_ddf(fmLarge, c(0,1)) ## 17 denominator df's #' #' # Notice: The restriction matrix L corresponding to the test above #' # can be found with #' L <- model2restrictionMatrix(fmLarge, fmSmall) #' L #' #' @export #' @rdname get_ddf_Lb get_Lb_ddf <- function(object, L){ UseMethod("get_Lb_ddf") } #' @export #' @rdname get_ddf_Lb get_Lb_ddf.lmerMod <- function(object, L){ Lb_ddf(L, vcov(object), vcovAdj(object)) } #' @export #' @rdname get_ddf_Lb Lb_ddf <- function(L, V0, Vadj) { if (!is.matrix(L)) L = matrix(L, nrow = 1) Theta <- t(L) %*% solve(L %*% V0 %*% t(L), L) P <- attr(Vadj, "P") W <- attr(Vadj, "W") A1 <- A2 <- 0 ThetaV0 <- Theta %*% V0 n.ggamma <- length(P) for (ii in 1:n.ggamma) { for (jj in c(ii:n.ggamma)) { e <- ifelse(ii == jj, 1, 2) ui <- ThetaV0 %*% P[[ii]] %*% V0 uj <- ThetaV0 %*% P[[jj]] %*% V0 A1 <- A1 + e * W[ii, jj] * (.spur(ui) * .spur(uj)) A2 <- A2 + e * W[ii, jj] * sum(ui * t(uj)) } } q <- nrow(L) # instead of finding rank B <- (1/(2 * q)) * (A1 + 6 * A2) g <- ((q + 1) * A1 - (q + 4) * A2)/((q + 2) * A2) c1 <- g/(3 * q + 2 * (1 - g)) c2 <- (q - g)/(3 * q + 2 * (1 - g)) c3 <- (q + 2 - g)/(3 * q + 2 * (1 - g)) EE <- 1 + (A2/q) VV <- (2/q) * (1 + B) EEstar <- 1/(1 - A2/q) VVstar <- (2/q) * ((1 + c1 * B)/((1 - c2 * B)^2 * (1 - c3 * B))) V0 <- 1 + c1 * B V1 <- 1 - c2 * B V2 <- 1 - c3 * B V0 <- ifelse(abs(V0) < 1e-10, 0, V0) rho <- 1/q * (.divZero(1 - A2/q, V1))^2 * V0/V2 df2 <- 4 + (q + 2)/(q * rho - 1) df2 } #' @rdname get_ddf_Lb #' @param Lcoef Linear contrast matrix get_ddf_Lb <- function(object, Lcoef){ UseMethod("get_ddf_Lb") } #' @rdname get_ddf_Lb get_ddf_Lb.lmerMod <- function(object, Lcoef){ ddf_Lb(vcovAdj(object), Lcoef, vcov(object)) } #' @rdname get_ddf_Lb #' @param VVa Adjusted covariance matrix #' @param VV0 Unadjusted covariance matrix #' @export ddf_Lb <- function(VVa, Lcoef, VV0=VVa){ .spur = function(U){ sum(diag(U)) } .divZero = function(x,y,tol=1e-14){ ## ratio x/y is set to 1 if both |x| and |y| are below tol x.y = if( abs(x)<tol & abs(y)<tol) {1} else x/y x.y } if (!is.matrix(Lcoef)) Lcoef = matrix(Lcoef, ncol = 1) vlb = sum(Lcoef * (VV0 %*% Lcoef)) Theta = Matrix(as.numeric(outer(Lcoef, Lcoef) / vlb), nrow=length(Lcoef)) P = attr(VVa, "P") W = attr(VVa, "W") A1 = A2 = 0 ThetaVV0 = Theta%*%VV0 n.ggamma = length(P) for (ii in 1:n.ggamma) { for (jj in c(ii:n.ggamma)) { e = ifelse(ii==jj, 1, 2) ui = ThetaVV0 %*% P[[ii]] %*% VV0 uj = ThetaVV0 %*% P[[jj]] %*% VV0 A1 = A1 + e* W[ii,jj] * (.spur(ui) * .spur(uj)) A2 = A2 + e* W[ii,jj] * sum(ui * t(uj)) }} ## substituted q = 1 in pbkrtest code and simplified B = (A1 + 6 * A2) / 2 g = (2 * A1 - 5 * A2) / (3 * A2) c1 = g/(3 + 2 * (1 - g)) c2 = (1 - g) / (3 + 2 * (1 - g)) c3 = (3 - g) / (3 + 2 * (1 - g)) EE = 1 + A2 VV = 2 * (1 + B) EEstar = 1/(1 - A2) VVstar = 2 * ((1 + c1 * B)/((1 - c2 * B)^2 * (1 - c3 * B))) V0 = 1 + c1 * B V1 = 1 - c2 * B V2 = 1 - c3 * B V0 = ifelse(abs(V0) < 1e-10, 0, V0) rho = (.divZero(1 - A2, V1))^2 * V0/V2 df2 = 4 + 3 / (rho - 1) ## cat(sprintf("Lcoef: %s\n", toString(Lcoef))) ## cat(sprintf("df2: %f\n", df2)) df2 } ## .get_ddf: Adapted from Russ Lenths 'lsmeans' package. ## Returns denom d.f. for testing lcoefs'beta = 0 where lcoefs is a vector # VVA is result of call to VVA = vcovAdj(object, 0) in pbkrtest package # VV is vcov(object) ## May not now be needed # lcoefs is contrast of interest # varlb is my already-computed value of lcoef' VV lcoef = est variance of lcoef'betahat ## .get_ddf <- function(VVa, VV0, Lcoef, varlb) { ## ## print(VVa); print(VV0) ## ## ss<<-list(VVa=VVa, VV0=VV0) ## .spur = function(U){ ## ##print(U) ## sum(diag(U)) ## } ## .divZero = function(x,y,tol=1e-14){ ## ## ratio x/y is set to 1 if both |x| and |y| are below tol ## x.y = if( abs(x)<tol & abs(y)<tol) {1} else x/y ## x.y ## } ## vlb = sum(Lcoef * (VV0 %*% Lcoef)) ## Theta = Matrix(as.numeric(outer(Lcoef, Lcoef) / vlb), nrow=length(Lcoef)) ## P = attr(VVa, "P") ## W = attr(VVa, "W") ## A1 = A2 = 0 ## ThetaVV0 = Theta%*%VV0 ## n.ggamma = length(P) ## for (ii in 1:n.ggamma) { ## for (jj in c(ii:n.ggamma)) { ## e = ifelse(ii==jj, 1, 2) ## ui = ThetaVV0 %*% P[[ii]] %*% VV0 ## uj = ThetaVV0 %*% P[[jj]] %*% VV0 ## A1 = A1 + e* W[ii,jj] * (.spur(ui) * .spur(uj)) ## A2 = A2 + e* W[ii,jj] * sum(ui * t(uj)) ## }} ## ## substituted q = 1 in pbkrtest code and simplified ## B = (A1 + 6 * A2) / 2 ## g = (2 * A1 - 5 * A2) / (3 * A2) ## c1 = g/(3 + 2 * (1 - g)) ## c2 = (1 - g) / (3 + 2 * (1 - g)) ## c3 = (3 - g) / (3 + 2 * (1 - g)) ## EE = 1 + A2 ## VV = 2 * (1 + B) ## EEstar = 1/(1 - A2) ## VVstar = 2 * ((1 + c1 * B)/((1 - c2 * B)^2 * (1 - c3 * B))) ## V0 = 1 + c1 * B ## V1 = 1 - c2 * B ## V2 = 1 - c3 * B ## V0 = ifelse(abs(V0) < 1e-10, 0, V0) ## rho = (.divZero(1 - A2, V1))^2 * V0/V2 ## df2 = 4 + 3 / (rho - 1) ## ## cat(sprintf("Lcoef: %s\n", toString(Lcoef))) ## ## cat(sprintf("df2: %f\n", df2)) ## df2 ## } <file_sep>/R/KR-vcovAdj16.R .vcovAdj16 <- function(object, details=0){ if (!(getME(object, "is_REML"))) { object <- update(object, . ~ ., REML = TRUE) } Phi <- vcov(object) SigmaG <- get_SigmaG( object, details ) X <- getME(object,"X") vcovAdj16_internal( Phi, SigmaG, X, details=details) } ## DENNE DUER IKKE; Løber ud for hukommelse... ## FIXME vcovAdj16_internal is the function being used by vcovAdj vcovAdj16_internal <- function(Phi, SigmaG, X, details=0){ # save(SigmaG, file="SigmaG.RData") # return(19) details=0 DB <- details > 0 ## debugging only t0 <- proc.time() ##Sigma <- SigmaG$Sigma n.ggamma <- SigmaG$n.ggamma M <- cbind(do.call(cbind, SigmaG$G), X) if(DB)cat(sprintf("dim(M) : %s\n", toString(dim(M)))) ## M can have many many columns if(DB)cat(sprintf("dim(SigmaG) : %s\n", toString(dim(SigmaG)))) if(DB){cat(sprintf("M etc: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ##SinvM <- solve(SigmaG$Sigma, M, sparse=TRUE) SinvM <- chol2inv(chol( forceSymmetric( SigmaG$Sigma ))) %*% M ##SigmaInv <- chol2inv( chol( forceSymmetric(SigmaG$Sigma) ) ) if(DB){cat(sprintf("SinvM etc: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} v <- c(rep(1:length(SigmaG$G), each=nrow(SinvM)), rep(length(SigmaG$G)+1, ncol(X))) idx <- lapply(unique.default(v), function(i) which(v==i)) SinvG <- lapply(idx, function(z) SinvM[,z]) ## List of SinvG1, SinvG2,... SinvGr, SinvX SinvX <- SinvG[[length(SinvG)]] ## Kaldes TT <NAME> SinvG[length(SinvG)] <- NULL ## Er HH^t if(DB){cat(sprintf("SinvG etc: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ##stat <<- list(SigmaG=SigmaG, X=X, M=M) OO <- lapply(1:n.ggamma, function(i) { SigmaG$G[[i]] %*% SinvX ## G_i \Sigma\inv X; n \times p }) if(DB){cat(sprintf("Finding OO: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} PP <- vector("list", n.ggamma) QQ <- vector("list", n.ggamma * (n.ggamma + 1) / 2 ) index <- 1 for (r in 1:n.ggamma) { OOt.r <- t( OO[[ r ]] ) #str(list("dim(OOt.r)"=dim(OOt.r), "dim(SinvX)"=dim(SinvX))) ##PP[[r]] <- forceSymmetric( -1 * OOt.r %*% SinvX) ## PP : p \times p PP[[r]] <- -1 * (OOt.r %*% SinvX) ## PP : p \times p for (s in r:n.ggamma) { QQ[[index]] <- OOt.r %*% ( SinvG[[s]] %*% SinvX ) index <- index + 1; } } ##stat16 <<- list(Phi=Phi, OO=OO, PP=PP,QQ=QQ) if(DB){cat(sprintf("Finding PP,QQ: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} Ktrace <- matrix( NA, nrow=n.ggamma, ncol=n.ggamma ) for (r in 1:n.ggamma) { HHr <- SinvG[[r]] for (s in r:n.ggamma){ Ktrace[r,s] <- Ktrace[s,r] <- sum( HHr * SinvG[[s]] ) }} if(DB){cat(sprintf("Finding Ktrace: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ## Finding information matrix IE2 <- matrix(0, nrow=n.ggamma, ncol=n.ggamma ) for (ii in 1:n.ggamma) { Phi.P.ii <- Phi %*% PP[[ii]] for (jj in c(ii:n.ggamma)) { www <- .indexSymmat2vec( ii, jj, n.ggamma ) IE2[ii,jj]<- IE2[jj,ii] <- Ktrace[ii,jj] - 2 * sum(Phi * QQ[[ www ]]) + sum( Phi.P.ii * ( PP[[jj]] %*% Phi)) }} if(DB){cat(sprintf("Finding IE2: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} eigenIE2 <- eigen( IE2, only.values=TRUE )$values condi <- min( abs( eigenIE2 ) ) WW <- if ( condi > 1e-10 ) forceSymmetric(2 * solve(IE2)) else forceSymmetric(2 * ginv(IE2)) ## print("vcovAdj") UU <- matrix(0, nrow=ncol(X), ncol=ncol(X)) ## print(UU) for (ii in 1:(n.ggamma-1)) { for (jj in c((ii+1):n.ggamma)) { www <- .indexSymmat2vec( ii, jj, n.ggamma ) UU <- UU + WW[ii,jj] * (QQ[[ www ]] - PP[[ii]] %*% Phi %*% PP[[jj]]) }} ## print(UU) UU <- UU + t(UU) for (ii in 1:n.ggamma) { www <- .indexSymmat2vec( ii, ii, n.ggamma ) UU <- UU + WW[ii,ii] * (QQ[[ www ]] - PP[[ii]] %*% Phi %*% PP[[ii]]) } if(DB){cat(sprintf("Finding UU: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ## print(UU) GGAMMA <- Phi %*% UU %*% Phi PhiA <- Phi + 2 * GGAMMA attr(PhiA, "P") <- PP attr(PhiA, "W") <- WW attr(PhiA, "condi") <- condi PhiA } ## Dette er en kopi af '2015' udgaven vcovAdj16_internal <- function(Phi, SigmaG, X, details=0){ details=0 DB <- details > 0 ## debugging only t0 <- proc.time() if (DB){ cat("vcovAdj16_internal\n") cat(sprintf("dim(X) : %s\n", toString(dim(X)))) print(class(X)) cat(sprintf("dim(Sigma) : %s\n", toString(dim(SigmaG$Sigma)))) print(class(SigmaG$Sigma)) } ##SigmaInv <- chol2inv( chol( forceSymmetric(SigmaG$Sigma) ) ) SigmaInv <- chol2inv( chol( forceSymmetric(as(SigmaG$Sigma, "matrix")))) ##SigmaInv <- as(SigmaInv, "dpoMatrix") if(DB){ cat(sprintf("Finding SigmaInv: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time() } #mat <<- list(SigmaG=SigmaG, SigmaInv=SigmaInv, X=X) t0 <- proc.time() ## Finding, TT, HH, 00 n.ggamma <- SigmaG$n.ggamma TT <- SigmaInv %*% X HH <- OO <- vector("list", n.ggamma) for (ii in 1:n.ggamma) { #.tmp <- SigmaG$G[[ii]] %*% SigmaInv #HH[[ ii ]] <- .tmp #OO[[ ii ]] <- .tmp %*% X HH[[ ii ]] <- SigmaG$G[[ii]] %*% SigmaInv OO[[ ii ]] <- HH[[ ii ]] %*% X } if(DB){cat(sprintf("Finding TT, HH, OO %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ## Finding PP, QQ PP <- QQ <- NULL for (rr in 1:n.ggamma) { OrTrans <- t( OO[[ rr ]] ) PP <- c(PP, list(forceSymmetric( -1 * OrTrans %*% TT))) for (ss in rr:n.ggamma) { QQ <- c(QQ, list(OrTrans %*% SigmaInv %*% OO[[ss]] )) }} if(DB){cat(sprintf("Finding PP,QQ: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ##stat15 <<- list(HH=HH, OO=OO, PP=PP, Phi=Phi, QQ=QQ) Ktrace <- matrix( NA, nrow=n.ggamma, ncol=n.ggamma ) for (rr in 1:n.ggamma) { HrTrans <- t( HH[[rr]] ) for (ss in rr:n.ggamma){ Ktrace[rr,ss] <- Ktrace[ss,rr]<- sum( HrTrans * HH[[ss]] ) }} if(DB){cat(sprintf("Finding Ktrace: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} ## Finding information matrix IE2 <- matrix( NA, nrow=n.ggamma, ncol=n.ggamma ) for (ii in 1:n.ggamma) { Phi.P.ii <- Phi %*% PP[[ii]] for (jj in c(ii:n.ggamma)) { www <- .indexSymmat2vec( ii, jj, n.ggamma ) IE2[ii,jj]<- IE2[jj,ii] <- Ktrace[ii,jj] - 2 * sum(Phi * QQ[[ www ]]) + sum( Phi.P.ii * ( PP[[jj]] %*% Phi)) }} if(DB){cat(sprintf("Finding IE2: %10.5f\n", (proc.time()-t0)[1] )); t0 <- proc.time()} eigenIE2 <- eigen(IE2, only.values=TRUE)$values condi <- min(abs(eigenIE2)) WW <- if (condi > 1e-10) forceSymmetric(2 * solve(IE2)) else forceSymmetric(2 * ginv(IE2)) ## print("vcovAdj") UU <- matrix(0, nrow=ncol(X), ncol=ncol(X)) ## print(UU) for (ii in 1:(n.ggamma-1)) { for (jj in c((ii + 1):n.ggamma)) { www <- .indexSymmat2vec( ii, jj, n.ggamma ) UU <- UU + WW[ii,jj] * (QQ[[ www ]] - PP[[ii]] %*% Phi %*% PP[[jj]]) }} ## print(UU) UU <- UU + t(UU) ## UU <<- UU for (ii in 1:n.ggamma) { www <- .indexSymmat2vec( ii, ii, n.ggamma ) UU<- UU + WW[ii, ii] * (QQ[[ www ]] - PP[[ii]] %*% Phi %*% PP[[ii]]) } ## print(UU) GGAMMA <- Phi %*% UU %*% Phi PhiA <- Phi + 2 * GGAMMA attr(PhiA, "P") <-PP attr(PhiA, "W") <-WW attr(PhiA, "condi") <- condi PhiA }
248f1a3f08038a8df1ad3d0f4d008fe00e47efae
[ "R" ]
14
R
martrs/pbkrtest
6ba04b9bbd13760fec1d9052013cc554595e6760
b7f17bf5aad5ad80780ed022d24b4052fed4d5ce
refs/heads/master
<repo_name>kupyna/JavaScriptCore_Lesson1<file_sep>/lesson1.js var name; var admin; name = "Василь"; admin = name; alert (admin);
e3c714962e2f84718d7c9ecd2990c7c4c51d13c9
[ "JavaScript" ]
1
JavaScript
kupyna/JavaScriptCore_Lesson1
eae5d450a27e080f93edc63d79209fa73954a291
02a07adaaac5c130642ff665acf44a70ccb556a9
refs/heads/master
<file_sep>import os, re, copy, traceback from random import randint os.system('cls') with open('a_raven.ascii', 'r') as intro: print intro.read() raw_input("Press ENTER to continue...") os.system('cls') weights = {'shape':7, 'size':6, 'inside':2, 'fill':7, 'above':4, 'overlaps':3, 'angle':6, 'left-of':4, 'horizontal-flip':6, 'vertical-flip':6} class Figure(object): def __init__(self,name): self.name = name self.properties = {} def __str__(self): out = "" for key, value in self.properties.iteritems(): out += key + ":" + value + "\r\n" return out str = __str__ __rep__=__str__ class Picture(object): def __init__(self): self.name = '' self.figure_list = {} def add_figure(self,figure): self.figure_list[figure.name] = figure def __str__(self): out = self.name + "\r\n" for key, value in self.figure_list.iteritems(): out += key + "\r\n" out += value.str() return out def parse_picture(lines, start, finish): picture = Picture() picture.name = lines[start][0] f = Figure(lines[start + 1][1]) for line in lines[start + 2 : finish + 1]: #print line[:-1] if line[:2] == "\t\t": stripped = line[2:].replace('\n','').replace('\r','') colon = stripped.find(':') #print "Adding Property " + "\"" + stripped + "\"" f.properties[stripped[:colon]] = stripped[colon + 1 :] else: #print "Saving Figure " + f.name + " to picture " + picture.name picture.add_figure(f) f = Figure(line[1]) return picture def weigh_figures_transformations(f1, f2): weight = 0 for p in f1.properties: if p in f2.properties: if f1.properties[p] == f2.properties[p]: weight += weights[p] else: weight -= weights[p] else: weight -= weights[p] return weight def two_dim_max(matrix): largest = -500 for i, v in enumerate(matrix): candidate = max(v) if candidate > largest: largest = candidate row = i column = v.index(largest) return row, column def relate_figures(weights,f1,f2): k1 = f1.figure_list.keys() k2 = f2.figure_list.keys() figures_relations = {} for figure in k1: figures_relations[figure] = '' while len(weights): relation = two_dim_max(weights) figures_relations[k1[relation[1]]] = k2[relation[0]] del(k1[relation[1]]) del(k2[relation[0]]) del(weights[relation[0]]) for index, val in enumerate(weights): del(weights[index][relation[1]]) return figures_relations def weigh_pictures_transformations(p1,p2): p1_figures = p1.figure_list.keys() p2_figures = p2.figure_list.keys() weights = [['' for x in p1_figures] for x in p2_figures] for col, col_name in enumerate(p1_figures): for row, row_name in enumerate(p2_figures): weights[row][col] = weigh_figures_transformations(p1.figure_list[p1_figures[col]], p2.figure_list[p2_figures[row]]) return weights def apply_transformations(p, template, relations): option = Picture() for old_figure_name, old_figure in p.figure_list.iteritems(): new_name = relations[old_figure_name] transformations = template[new_name] if transformations != 'figure_deleted': figure = Figure(new_name) for new_key, new_value in transformations.iteritems(): if new_value == 'same': #print old_figure.properties old_value = old_figure.properties[new_key] figure.properties[new_key] = old_value elif not new_value == 'deleted': figure.properties[new_key] = new_value option.add_figure(figure) return option def compare_figures(f1,f2): are_they_equal = True for p1, v1 in f1.properties.iteritems(): if p1 in f2.properties: if f2.properties[p1] == v1: are_they_equal &= True else: are_they_equal &= False else: are_they_equal &= False return 10 if are_they_equal else -10 def compare_pictures(p1,p2): weight = 0 for p1_name, f1 in p1.figure_list.iteritems(): for p2_name, f2 in p2.figure_list.iteritems(): f2_copy = copy.deepcopy(f2) weight += compare_figures(f1,f2) return weight solutions = [] corrects = [] for x in range(1,21): #Change this to (1,21) in final version print "Loading problem %02d..." % (x,) try: with open('Problems/2x1BasicProblem%02d.txt' % (x,), 'r') as p: lines = list(p) corrects.append(int(lines[2][0])) lines.append("\n,") # Parse pictures into Picture/Figure structures for index, line in enumerate(lines[3:]): if line[0] == 'A': index_a = index + 3 if line[0] == 'B': index_b = index + 3 if line[0] == 'C': index_c = index + 3 if line[0] == '1': index_s1 = index + 3 if line[0] == '2': index_s2 = index + 3 if line[0] == '3': index_s3 = index + 3 if line[0] == '4': index_s4 = index + 3 if line[0] == '5': index_s5 = index + 3 if line[0] == '6': index_s6 = index + 3 a = parse_picture(lines, index_a, index_b) b = parse_picture(lines, index_b, index_c) c = parse_picture(lines, index_c, index_s1) s1 = parse_picture(lines, index_s1, index_s2) s2 = parse_picture(lines, index_s2, index_s3) s3 = parse_picture(lines, index_s3, index_s4) s4 = parse_picture(lines, index_s4, index_s5) s5 = parse_picture(lines, index_s5, index_s6) s6 = parse_picture(lines, index_s6, len(lines)) #print a,b,c,s1,s2,s3,s4,s6 # Generate figure relations list between pictures A and B a_b_transformations_weights = weigh_pictures_transformations(a,b) a_b_figures_relations = relate_figures(a_b_transformations_weights,a,b) #print a_b_figures_relations # Generate transformation template transformations_template = {} for index, relation in enumerate(a_b_figures_relations.iteritems()): old = relation[0] new = relation[1] transformations_template[old] = {} if new in b.figure_list: for p, a_v in a.figure_list[old].properties.iteritems(): if p in b.figure_list[new].properties: b_v = b.figure_list[new].properties[p] if a_v == b_v: transformations_template[old][p] = 'same' else: transformations_template[old][p] = b_v else: transformations_template[old][p] = 'deleted' else: transformations_template[old] = 'figure_deleted' # Add 'added' properties to the transformation template for name, figure in b.figure_list.iteritems(): for p, v in figure.properties.iteritems(): if not p in transformations_template[name]: transformations_template[name][p] = v #print transformations_template # Generate figure relations list between pictures A and C a_c_transformations_weights = weigh_pictures_transformations(c,a) a_c_figures_relations = relate_figures(a_c_transformations_weights,c,a) #print a_c_figures_relations # Apply transformations template to C option = apply_transformations(c, transformations_template, a_c_figures_relations) #print option # Compare and weigh option with numbered possible solutions solution_weights = [] s = [s1,s2,s3,s4,s5,s6] for i, solution in enumerate(s): solution_weights.append(compare_pictures(option, solution)) #print solution_weights solutions.append(solution_weights.index(max(solution_weights))+1) except: print traceback.format_exc() solutions.append(randint(1,6)) print 'My Answers: ', solutions print 'Correct answers:', corrects total = 0 for s, c in zip(solutions, corrects): total += 1 if s==c else 0 print total, 'out of', len(solutions), 'correct'
c6047fa5044e8c31dc8ab99ca4b15bc85b483e87
[ "Python" ]
1
Python
rodolfosrg/the_raven
eb97ea4dc7bb7a33236a3d4ef95155c57f26be2a
5b3f1b87009066353926f3d51cf9eec018be5cef
refs/heads/main
<repo_name>Ariel0123/HeartDiseaseApp<file_sep>/HeartDiseaseApp/Views/SelectorView.swift // // SelectorView.swift // HeartDiseaseApp // // Created by <NAME> on 8/10/21. // import SwiftUI struct SelectorView: View { @Binding var nameField: String @Binding var value: String @State var selectedSex = "Select" var body: some View { HStack{ Text(nameField) .font(.headline) Divider() Menu(self.selectedSex) { Button("Female", action: setFemale) Button("Male", action: setMale) } .pickerStyle(MenuPickerStyle()) .frame(maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: .leading) } .padding(10) .background(Color.gray.opacity(0.1)) .cornerRadius(20) .frame(height: 30, alignment: .leading) .onChange(of: value, perform: { value in if value == "0"{ self.selectedSex = "Female" }else if value == "1"{ self.selectedSex = "Male" }else{ self.selectedSex = "Select" } }) } func setMale(){ self.value = "1" } func setFemale(){ self.value = "0" } } struct SelectorView_Previews: PreviewProvider { static var previews: some View { SelectorView(nameField: .constant(""), value: .constant("")) } } <file_sep>/HeartDiseaseApp/Utils/MessageWarning.swift // // MessageWarning.swift // HeartDiseaseApp // // Created by <NAME> on 8/10/21. // import Foundation enum MessageWarning: Error { case age case sex case cp case trestbps case chol case fbs case restecg case thalach case exang case oldpeak case slope case ca case thal case errorModel var message: String { switch self { case .age: return "The age field is empty or is an invalid input" case .sex: return "The sex field is empty" case .cp: return "The cp field is empty or is an invalid input" case .trestbps: return "The trestbps field is empty or is an invalid input" case .chol: return "The chol field is empty or is an invalid input" case .fbs: return "The fbs field is empty or is an invalid input" case .restecg: return "The restecg field is empty or is an invalid input" case .thalach: return "The thalach field is empty or is an invalid input" case .exang: return "The exang field is empty or is an invalid input" case .oldpeak: return "The oldpeak field is empty or is an invalid input" case .slope: return "The slope field is empty or is an invalid input" case .ca: return "The ca field is empty or is an invalid input" case .thal: return "The thal field is empty or is an invalid input" case .errorModel: return "Prediction error" } } } struct MessageModel: Identifiable { let id = UUID() let msg: String } class MessageService: ObservableObject{ @Published var msg: MessageModel? = nil } <file_sep>/README.md <h1>Heart disease app</h1> <p>The app uses a model trained with kaggle's heart disease dataset</p> <p>Dataset: <a href="https://www.kaggle.com/ronitf/heart-disease-uci">Heart disease</a></p> <file_sep>/HeartDiseaseApp/HeartDiseaseAppApp.swift // // HeartDiseaseAppApp.swift // HeartDiseaseApp // // Created by <NAME> on 8/10/21. // import SwiftUI @main struct HeartDiseaseAppApp: App { var body: some Scene { WindowGroup { MainView() } } } <file_sep>/HeartDiseaseApp/Views/MainView.swift // // MainView.swift // HeartDiseaseApp // // Created by <NAME> on 8/10/21. // import SwiftUI import CoreML struct MainView: View { @StateObject var heartService = HeartService() @StateObject var messageService = MessageService() @State var age = "" @State var sex = "" @State var cp = "" @State var trestbps = "" @State var chol = "" @State var fbs = "" @State var restecg = "" @State var thalach = "" @State var exang = "" @State var oldpeak = "" @State var slope = "" @State var ca = "" @State var thal = "" var body: some View { VStack(alignment: .leading) { Text("Heart Disease") .font(/*@START_MENU_TOKEN@*/.title/*@END_MENU_TOKEN@*/) .bold() .padding() VStack(spacing: 20){ HStack { TextFieldView(nameField: .constant("Age"), value: $age) //TextFieldView(nameField: .constant("Sex"), value: $sex) SelectorView(nameField: .constant("Sex"), value: $sex) } HStack { TextFieldView(nameField: .constant("Cp"), value: $cp) TextFieldView(nameField: .constant("Trestbps"), value: $trestbps) } HStack { TextFieldView(nameField: .constant("Chol"), value: $chol) TextFieldView(nameField: .constant("Fbs"), value: $fbs) } HStack { TextFieldView(nameField: .constant("Restecg"), value: $restecg) TextFieldView(nameField: .constant("Thalach"), value: $thalach) } HStack { TextFieldView(nameField: .constant("Exang"), value: $exang) TextFieldView(nameField: .constant("Oldpeak"), value: $oldpeak) } HStack { TextFieldView(nameField: .constant("Slope"), value: $slope) TextFieldView(nameField: .constant("Ca"), value: $ca) } HStack{ TextFieldView(nameField: .constant("Thal"), value: $thal) .frame(width: UIScreen.main.bounds.width/2-20, alignment: .leading) Spacer() } } .padding() HStack{ Button(action: { do{ try getResult() }catch{ print("error") } }, label: { Text("Predict") .frame(width: 150, height: 40, alignment: .center) }).background(Color.blue) .foregroundColor(.white) .font(.headline) .cornerRadius(25) Spacer() Button(action: { self.clearFields() }, label: { Text("Clear fields") .frame(width: 150, height: 40, alignment: .center) }).background(Color.orange) .foregroundColor(.white) .font(.headline) .cornerRadius(25) } .padding() if !heartService.result.isEmpty && !heartService.percentage.isEmpty{ ResultView(result: $heartService.result, percentage: $heartService.percentage) .padding(.horizontal) } Spacer() }.alert(item: $messageService.msg){ message in Alert(title: Text("Warning"), message: Text(message.msg)) } } func getResult() throws { do{ try validateFields() }catch MessageWarning.sex{ self.messageService.msg = MessageModel(msg: MessageWarning.sex.message) }catch MessageWarning.age{ self.messageService.msg = MessageModel(msg: MessageWarning.age.message) }catch MessageWarning.cp{ self.messageService.msg = MessageModel(msg: MessageWarning.cp.message) }catch MessageWarning.trestbps{ self.messageService.msg = MessageModel(msg: MessageWarning.trestbps.message) }catch MessageWarning.chol{ self.messageService.msg = MessageModel(msg: MessageWarning.chol.message) }catch MessageWarning.fbs{ self.messageService.msg = MessageModel(msg: MessageWarning.fbs.message) }catch MessageWarning.restecg{ self.messageService.msg = MessageModel(msg: MessageWarning.restecg.message) }catch MessageWarning.thalach{ self.messageService.msg = MessageModel(msg: MessageWarning.thalach.message) }catch MessageWarning.exang{ self.messageService.msg = MessageModel(msg: MessageWarning.exang.message) }catch MessageWarning.oldpeak{ self.messageService.msg = MessageModel(msg: MessageWarning.oldpeak.message) }catch MessageWarning.slope{ self.messageService.msg = MessageModel(msg: MessageWarning.slope.message) }catch MessageWarning.ca{ self.messageService.msg = MessageModel(msg: MessageWarning.ca.message) }catch MessageWarning.thal{ self.messageService.msg = MessageModel(msg: MessageWarning.thal.message) } } func validateFields() throws { if self.age.isEmpty || !self.age.isNumeric{ throw MessageWarning.age }else if self.sex.isEmpty{ throw MessageWarning.sex }else if self.cp.isEmpty || !self.cp.isNumeric{ throw MessageWarning.cp }else if self.trestbps.isEmpty || !self.trestbps.isNumeric{ throw MessageWarning.trestbps }else if self.chol.isEmpty || !self.chol.isNumeric{ throw MessageWarning.chol }else if self.fbs.isEmpty || !self.fbs.isNumeric{ throw MessageWarning.fbs }else if self.restecg.isEmpty || !self.restecg.isNumeric{ throw MessageWarning.restecg }else if self.thalach.isEmpty || !self.thalach.isNumeric{ throw MessageWarning.thalach } else if self.exang.isEmpty || !self.exang.isNumeric{ throw MessageWarning.exang } else if self.oldpeak.isEmpty || !self.oldpeak.isNumeric{ throw MessageWarning.oldpeak } else if self.slope.isEmpty || !self.slope.isNumeric{ throw MessageWarning.slope }else if self.ca.isEmpty || !self.ca.isNumeric{ throw MessageWarning.ca }else if self.thal.isEmpty || !self.thal.isNumeric{ throw MessageWarning.thal } else{ do{ try heartService.predictHeartDisease(age: self.age, sex: self.sex, cp: self.cp, trestbps: self.trestbps, chol: self.chol, fbs: self.fbs, restecg: self.restecg, thalach: self.thalach, exang: self.exang, oldpeak: self.oldpeak, slope: self.slope, ca: self.ca, thal: self.thal) }catch MessageWarning.errorModel{ self.messageService.msg = MessageModel(msg: MessageWarning.errorModel.message) } } } func clearFields(){ self.age = "" self.sex = "" self.cp = "" self.trestbps = "" self.chol = "" self.fbs = "" self.restecg = "" self.thalach = "" self.exang = "" self.oldpeak = "" self.slope = "" self.ca = "" self.thal = "" heartService.result = "" heartService.percentage = "" } } struct MainView_Previews: PreviewProvider { static var previews: some View { MainView() } } extension String { var isNumeric : Bool { if self.last == "."{ return false }else{ var onePoint = false for i in self { if i == "." && !onePoint{ onePoint = true }else if i == "." && onePoint{ return false } } } return true } } <file_sep>/HeartDiseaseApp/Views/ResultView.swift // // ResultView.swift // HeartDiseaseApp // // Created by <NAME> on 8/10/21. // import SwiftUI struct ResultView: View { @Binding var result: String @Binding var percentage: String var body: some View { VStack(alignment: .leading){ HStack{ Text("Result:") .font(.headline) Text(String(self.result)) } .padding(.bottom, 10) .frame(maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: .leading) HStack{ Text("Percentage:") .font(.headline) Text(self.percentage) } .frame(maxWidth: /*@START_MENU_TOKEN@*/.infinity/*@END_MENU_TOKEN@*/, alignment: .leading) } .padding() .background(Color.gray.opacity(0.1)) .cornerRadius(20) } } struct ResultView_Previews: PreviewProvider { static var previews: some View { ResultView(result: .constant(""), percentage: .constant("")) } } <file_sep>/HeartDiseaseApp/ViewModel/HeartService.swift import Combine import CoreML class HeartService: ObservableObject{ @Published var result = "" @Published var percentage = "" func predictHeartDisease(age: String, sex: String, cp: String, trestbps: String, chol: String, fbs: String, restecg: String, thalach: String, exang: String, oldpeak: String, slope: String, ca: String, thal: String) throws { do{ let config = MLModelConfiguration() let model = try heart(configuration: config) let marsHabitatPricerOutput = try model.prediction(age: Double(age)!, sex: Double(sex)!, cp: Double(cp)!, trestbps: Double(trestbps)!, chol: Double(chol)!, fbs: Double(fbs)!, restecg: Double(restecg)!, thalach: Double(thalach)!, exang: Double(exang)!, oldpeak: Double(oldpeak)!, slope: Double(slope)!, ca: Double(ca)!, thal: Double(thal)!) if marsHabitatPricerOutput.target == 1{ self.result = "Heart disease" self.percentage = String(format: "%.2f", marsHabitatPricerOutput.targetProbability[1]!) + " %" }else{ self.result = "No heart disease" self.percentage = String(format: "%.2f", marsHabitatPricerOutput.targetProbability[0]!) + " %" } }catch{ throw MessageWarning.errorModel } } } <file_sep>/HeartDiseaseApp/Views/TextFieldView.swift // // TextFieldView.swift // HeartDiseaseApp // // Created by <NAME> on 8/10/21. // import SwiftUI import Combine struct TextFieldView: View { @Binding var nameField: String @Binding var value: String var body: some View { HStack{ Text(nameField) .font(.headline) Divider() TextField("Enter value", text: $value) .keyboardType(.numberPad) .onReceive(Just(value)) { newValue in let filtered = newValue.filter { "0123456789.".contains($0) } if filtered != newValue{ self.value = filtered } } } .padding(10) .background(Color.gray.opacity(0.1)) .cornerRadius(20) .frame(height: 30, alignment: .leading) } } struct TextFieldView_Previews: PreviewProvider { static var previews: some View { TextFieldView(nameField: .constant(""), value: .constant("")) } }
151a2d86b9e1fc6a43ae6880267c660a8f784010
[ "Swift", "Markdown" ]
8
Swift
Ariel0123/HeartDiseaseApp
d6d1b8bebb5fa7c3dec1897dcd1c9a792e8d321a
5bce0d55414dc951ca2f52f2e83ec4ebea980bf3
refs/heads/main
<file_sep>using Microsoft.EntityFrameworkCore.Migrations; namespace Vehicles.API.Migrations { public partial class ModifyVehicleToVehicles : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Histories_Vehicle_VehicleId", table: "Histories"); migrationBuilder.DropForeignKey( name: "FK_Vehicle_AspNetUsers_UserId", table: "Vehicle"); migrationBuilder.DropForeignKey( name: "FK_Vehicle_Brands_BrandId", table: "Vehicle"); migrationBuilder.DropForeignKey( name: "FK_Vehicle_VehicleTypes_VehicleTypeId", table: "Vehicle"); migrationBuilder.DropForeignKey( name: "FK_VehiclePhotos_Vehicle_VehicleId", table: "VehiclePhotos"); migrationBuilder.DropPrimaryKey( name: "PK_Vehicle", table: "Vehicle"); migrationBuilder.RenameTable( name: "Vehicle", newName: "Vehicles"); migrationBuilder.RenameIndex( name: "IX_Vehicle_VehicleTypeId", table: "Vehicles", newName: "IX_Vehicles_VehicleTypeId"); migrationBuilder.RenameIndex( name: "IX_Vehicle_UserId", table: "Vehicles", newName: "IX_Vehicles_UserId"); migrationBuilder.RenameIndex( name: "IX_Vehicle_Plaque", table: "Vehicles", newName: "IX_Vehicles_Plaque"); migrationBuilder.RenameIndex( name: "IX_Vehicle_BrandId", table: "Vehicles", newName: "IX_Vehicles_BrandId"); migrationBuilder.AddPrimaryKey( name: "PK_Vehicles", table: "Vehicles", column: "Id"); migrationBuilder.AddForeignKey( name: "FK_Histories_Vehicles_VehicleId", table: "Histories", column: "VehicleId", principalTable: "Vehicles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_VehiclePhotos_Vehicles_VehicleId", table: "VehiclePhotos", column: "VehicleId", principalTable: "Vehicles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Vehicles_AspNetUsers_UserId", table: "Vehicles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Vehicles_Brands_BrandId", table: "Vehicles", column: "BrandId", principalTable: "Brands", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Vehicles_VehicleTypes_VehicleTypeId", table: "Vehicles", column: "VehicleTypeId", principalTable: "VehicleTypes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Histories_Vehicles_VehicleId", table: "Histories"); migrationBuilder.DropForeignKey( name: "FK_VehiclePhotos_Vehicles_VehicleId", table: "VehiclePhotos"); migrationBuilder.DropForeignKey( name: "FK_Vehicles_AspNetUsers_UserId", table: "Vehicles"); migrationBuilder.DropForeignKey( name: "FK_Vehicles_Brands_BrandId", table: "Vehicles"); migrationBuilder.DropForeignKey( name: "FK_Vehicles_VehicleTypes_VehicleTypeId", table: "Vehicles"); migrationBuilder.DropPrimaryKey( name: "PK_Vehicles", table: "Vehicles"); migrationBuilder.RenameTable( name: "Vehicles", newName: "Vehicle"); migrationBuilder.RenameIndex( name: "IX_Vehicles_VehicleTypeId", table: "Vehicle", newName: "IX_Vehicle_VehicleTypeId"); migrationBuilder.RenameIndex( name: "IX_Vehicles_UserId", table: "Vehicle", newName: "IX_Vehicle_UserId"); migrationBuilder.RenameIndex( name: "IX_Vehicles_Plaque", table: "Vehicle", newName: "IX_Vehicle_Plaque"); migrationBuilder.RenameIndex( name: "IX_Vehicles_BrandId", table: "Vehicle", newName: "IX_Vehicle_BrandId"); migrationBuilder.AddPrimaryKey( name: "PK_Vehicle", table: "Vehicle", column: "Id"); migrationBuilder.AddForeignKey( name: "FK_Histories_Vehicle_VehicleId", table: "Histories", column: "VehicleId", principalTable: "Vehicle", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Vehicle_AspNetUsers_UserId", table: "Vehicle", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Vehicle_Brands_BrandId", table: "Vehicle", column: "BrandId", principalTable: "Brands", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Vehicle_VehicleTypes_VehicleTypeId", table: "Vehicle", column: "VehicleTypeId", principalTable: "VehicleTypes", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_VehiclePhotos_Vehicle_VehicleId", table: "VehiclePhotos", column: "VehicleId", principalTable: "Vehicle", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } } }
7f2ef96371337f154d9cc39bd407c33ce9ee605d
[ "C#" ]
1
C#
jdbarrera89/Vehicles
b37ef88c9fabe373e83379915e6fc48cf163ee0d
67638f2c1a21a7e6d3741bfeeefa9dc0f5bd9280
refs/heads/master
<file_sep>// GraphZones - Optimization for hit-testing within a partitioned space // of rectangles. // // dx, dy - size of each zone // xMax - the max width of the space // Copyright (c) 2007 by <NAME> function GraphZones(dx, dy, xMax) { this.dx = dx; this.dy = dy; this.cols = Math.ceil(xMax/dx); this.zones = []; } GraphZones.prototype = { Zone: function(x, y) { var iZone = Math.floor(x/this.dx) + this.cols * Math.floor(y/this.dy); if (iZone < 0) return null; if (this.zones[iZone] == undefined) this.zones[iZone] = []; return this.zones[iZone]; }, Move: function (obj) { var zone = this.Zone(obj.x, obj.y); if (obj._zone) { if (obj._zone == zone) return; this.Remove(obj); } this.Add(obj, zone); }, Remove: function(obj) { if (!obj._zone) return; var zone = obj._zone; console.assert(obj == zone[obj._iSlot]); delete zone[obj._iSlot]; obj._zone = null; }, Add: function(obj, zone) { obj._zone = zone; // Re-use empty slots for (var iSlot = 0; iSlot < zone.length; iSlot++) { if (zone[iSlot] == undefined) { obj._iSlot = iSlot; zone[iSlot] = obj; return; } } obj._iSlot = zone.push(obj) - 1; }, ZonesAround: function(x, y, rad) { // Assume radius cannot span more than the 8 adjacent zones console.assert(rad < this.dx && rad < this.dy); var zones = []; rad = Math.floor(rad); for (var xT = x - rad; xT <= x + rad; xT += rad) for (var yT = y - rad; yT <= y + rad; yT += rad) { var zone = this.Zone(xT, yT); if (zone) zones.PushIfNew(zone); } return zones; }, ProcessCollisions: function(obj, fn) { var zones = this.ZonesAround(obj.x, obj.y, obj.r); // Bug: potential performance issue - use linked list to set add/delete instead of an array. for (var izone = 0; izone < zones.length; izone++) { var zone = zones[izone]; for (var iobj = 0; iobj < zone.length; iobj++) { var objOther = zone[iobj]; if (objOther == null || objOther == obj) continue; if (obj.FCollision(objOther)) fn(obj,objOther); } } } } <file_sep>// ------------------------------------------------------------ // slideshow.js // // History: // // Copyright 2004 by <NAME> (<EMAIL>) // // This file contains code for the generation of an interactive slideshow or // image gallery. It reads the contents of an embedded XML data island // and creates the DHTML needed to display the gallery. // See http://mckoss.com/jscript/slideshow for more information. // -----------------------------------------------------mck---- var cbSS = new CodeBase("slideshow.js"); SlideShow.DeriveFrom(Named); SlideShow.modeLand = 0; SlideShow.modePort = 1; SlideShow.modeFlip = 2; SlideShow.stRelVersion = "2004-05-27"; SlideShow.stSourceRoot = "http://coderats.com/"; SlideShow.stProductName = "The Image Gallery"; SlideShow.stAuthor = "CodeRats.com"; function SlideShow(xmlSS) { var ndT; var rgb; this.Named(); this.wc = new WindowControl(false); this.fDebug = false; var ndRoot= xmlSS.XMLDocument.documentElement; var sht = document.styleSheets(0); this.dzMargin = XMLAttrDef(ndRoot, "Margin", 10); this.dzThumb = XMLAttrDef(ndRoot, "ThumbSize", 40); this.dzBorder = XMLAttrDef(ndRoot, "Border", 2); var rgb = XMLAttrDef(ndRoot, "BorderColor", "white"); var stStyle = "border: " + this.dzBorder + " solid " + rgb + ";"; sht.addRule("IMG.Main" , stStyle); sht.addRule("IMG.Selected", stStyle); rgb = XMLAttrDef(ndRoot, "UnselectedColor", "black"); sht.addRule("IMG.Loaded" , "border: " + this.dzBorder + " solid " + rgb + ";"); rgb = XMLAttrDef(ndRoot, "ErrorColor", "red"); sht.addRule("IMG.Error", "border: " + this.dzBorder + " solid " + rgb + ";"); rgb = XMLAttrDef(ndRoot, "BackColor", "#3C3C3C"); sht.addRule("BODY", "background: " + rgb); rgb = XMLAttrDef(ndRoot, "TextColor", "white"); sht.addRule("BODY", "color: " + rgb + ";"); sht.addRule("A", "color: " + rgb + ";"); this.stFont = XMLAttrDef(ndRoot, "Font", "Verdana"); this.wFontSize = XMLAttrDef(ndRoot, "FontSize", 14); sht.addRule("BODY", "font-family: " + this.stFont + ";"); sht.addRule("BODY", "font-size: " + this.wFontSize + ";"); sht.addRule(".Title", "font-family:" + XMLAttrDef(ndRoot, "TitleFont", this.stFont) + ";"); sht.addRule(".Title", "font-size:" + XMLAttrDef(ndRoot, "TitleFontSize", this.wFontSize+4) + ";"); sht.addRule("DIV.Splash", "font-family:" + XMLAttrDef(ndRoot, "TitleFont", this.stFont) + ";"); sht.addRule(".DIV.Splash", "font-size:" + XMLAttrDef(ndRoot, "TitleFontSize", this.wFontSize+4) + ";"); this.dzThumbSpace = this.dzThumb + this.dzMargin + 2*this.dzBorder; sht.addRule("TD.Thumb", "width: " + this.dzThumbSpace + "px;"); sht.addRule("TD.Thumb", "height: " + this.dzThumbSpace + "px;"); sht.addRule("Table.ControlBar TD", "width: " + this.dzThumbSpace + "px;"); sht.addRule("Table.ControlBar TD", "height: " + this.dzThumbSpace + "px;"); var stT= XMLAttrDef(ndRoot, "SoundTrack"); if (stT) { this.sndBack = new Sound(stT); this.sndBack.fLoop = true; } this.secDelay = XMLAttrDef(ndRoot, "Delay", 7); ndT = ndRoot.selectSingleNode("./Title"); this.stTitle = StXMLContent(ndT); ndT = ndRoot.selectSingleNode("./Home"); this.stHome = XMLAttrDef(ndT, "HREF"); this.ptSizeDef = PtXMLSizeDef(ndRoot, new Point(640, 480)); this.stImageBase = XMLAttrDef(ndRoot, "ImageBase", ""); this.stThumbBase = XMLAttrDef(ndRoot, "ThumbBase", this.stImageBase); this.rgslide = new Array; var rgndSlides = ndRoot.selectNodes("./Slide"); var i; for (i = 0; i < rgndSlides.length; i++) this.rgslide[i] = new Slide(this, rgndSlides.item(i), i); this.cslides = this.rgslide.length; this.cslidesLoaded = 0; this.ccol = Math.ceil(Math.sqrt(this.cslides)); this.crw = Math.ceil(this.cslides/this.ccol); this.fLayout = false; this.timerPlay = new Timer(this.StNamed() + ".AutoAdvance();", this.secDelay * 1000); this.fPlay = XMLAttrDef(ndRoot, "AutoPlay", false); // Transition and image loading timer - check for loaded images each 1/10 sec this.timerTransition = new Timer(this.StNamed() + ".DoTransition();", 100); this.timerTransition.Active(true); this.fFirstSlide = false; this.fTransition = false; this.cslidesPre = 0; // Prevent text selection in the document - mainly want in divNav -but // this looks nicer everywhere too. document.onselectstart = new Function("return false;"); } function SlideShow.prototype.ToggleSplash() { if (this.cslides == 0) this.txtLoading.innerText = "No Slides!"; this.fSplashOn = !this.fSplashOn; this.txtLoading.style.visibility = this.fSplashOn ? "visible" : "hidden"; } function SlideShow.prototype.PlayMode(fPlay) { this.fPlay = fPlay; this.btnPlay.ButtonDown(fPlay); this.timerPlay.Active(fPlay); } function SlideShow.prototype.StUI() { var st = ""; if (this.sndBack) st += this.sndBack.StUI(); st += "<DIV class=Title " + this.StPartID("Title") + " NOWRAP></DIV>"; st += "<IMG class=Main " + this.StPartID("Main") + " SRC='" + cbSS.stPath + "images/blank.gif'>"; st += "<DIV class=Desc " + this.StPartID("DivDesc") + ">"; st += "<SPAN class=Title " + this.StPartID("DTitle") + "></SPAN>"; st += "<BR><SPAN class=Desc " + this.StPartID("Date") + "></SPAN>"; st += "<BR><BR><SPAN class=Desc " + this.StPartID("TxtDesc") + "></SPAN>"; st += "</DIV>"; st += "<DIV class=Nav " + this.StPartID("Nav") + ">"; // Control buttons st += "<TABLE class=ControlBar cellpadding=0 cellspacing=0><TR>"; if (this.stHome != undefined) { this.btnHome = new Button("Home", this.StNamed() + ".Home();", cbSS.stPath + "images/home-up.png", cbSS.stPath + "images/home-down.png", "Home Page"); this.btnHome.SetHeight(this.dzThumb); st += "<TD>"; st += this.btnHome.StUI(); st += "</TD>"; } if (this.sndBack) { this.btnSnd = new Button("Sound", this.StNamed() + ".SoundToggle();", cbSS.stPath + "images/sound-on.png", cbSS.stPath + "images/sound-off.png", "Sound On/Off"); this.btnSnd.fToggle = true; this.btnSnd.SetHeight(this.dzThumb); st += "<TD>"; st += this.btnSnd.StUI(); st += "</TD>"; } this.btnPrev = new Button("Prev", this.StNamed() + ".AdvanceClick(-1);", cbSS.stPath + "images/prev-up.png", cbSS.stPath + "images/prev-down.png", "Previous Image"); this.btnPrev.SetHeight(this.dzThumb); st += "<TD>"; st += this.btnPrev.StUI(); st += "</TD>"; this.btnNext = new Button("Next", this.StNamed() + ".AdvanceClick(1);", cbSS.stPath + "images/next-up.png", cbSS.stPath + "images/next-down.png", "Next Image"); this.btnNext.SetHeight(this.dzThumb); st += "<TD>"; st += this.btnNext.StUI(); st += "</TD>"; this.btnPlay = new Button("Play", this.StNamed() + ".PlayToggle();", cbSS.stPath + "images/play-up.png", cbSS.stPath + "images/play-down.png", "Play On/Off"); this.btnPlay.fToggle = true; this.btnPlay.SetHeight(this.dzThumb); st += "<TD>"; st += this.btnPlay.StUI(); st += "</TD>"; st += "</TR></TABLE>"; st += "<TABLE cellpadding=0 cellspacing=0>"; var islide = 0; var rw; var col; for (rw = 0; rw < this.crw; rw++) { st += "<TR>"; for (col = 0; col < this.ccol; col++) { st += "<TD class=Thumb>"; if (islide < this.cslides) st += this.rgslide[islide].StThumbUI(); st += "</TD>"; islide++; } st += "</TR>"; } st += "</TABLE></DIV>"; st += "<DIV " + this.StPartID("Credits") + " class=Credits NOWRAP>"; st += "Powered by <A HREF=" + SlideShow.stSourceRoot + ">" + SlideShow.stProductName + "</A>"; st += "&nbsp;<FONT SIZE=1>(Ver." + SlideShow.stRelVersion + ")</FONT>"; st += "</DIV>"; st += "<DIV " + this.StPartID("Splash") + "class=Splash>"; st += this.stTitle; st += "<BR><BR><SPAN " + this.StPartID("Loading") + ">Loading...</SPAN>" st += "</DIV>"; if (this.fDebug) { st += "<DIV " + this.StPartID("DivL") + " class=Debug></DIV>"; st += "<DIV " + this.StPartID("DivP") + " class=Debug></DIV>"; st += "<DIV " + this.StPartID("DivNavDebug") + " class=Debug></DIV>"; } return st; } // This function called after the page is loaded - but note that not all images may yet be loaded! function SlideShow.prototype.BindUI() { var islide; for (islide = 0; islide < this.cslides; islide++) this.rgslide[islide].BindUI(); if (this.stHome != undefined) this.btnHome.BindUI(); this.btnPrev.BindUI(); this.btnNext.BindUI(); this.btnPlay.BindUI(); if (this.sndBack) { this.sndBack.BindUI(); this.btnSnd.BindUI(); } this.txtTitle = this.BoundPart("Title"); this.imgMain = this.BoundPart("Main"); this.divDesc = this.BoundPart("DivDesc"); this.divNav = this.BoundPart("Nav"); this.divCredits = this.BoundPart("Credits"); this.txtDTitle = this.BoundPart("DTitle"); this.txtDate = this.BoundPart("Date"); this.txtDesc = this.BoundPart("TxtDesc"); this.divSplash = this.BoundPart("Splash"); this.txtLoading = this.BoundPart("Loading"); var rcSplash = RcAbsolute(this.divSplash); rcSplash.CenterOn(this.wc.rc.PtCenter()); PositionElt(this.divSplash, rcSplash.ptUL); this.divSplash.style.visibility = "visible"; this.timerSplash = new Timer(this.StNamed() + ".ToggleSplash();", 500); this.fSplashOn = true; this.timerSplash.Active(true); if (this.fDebug) { this.divL = this.BoundPart("DivL"); this.divP = this.BoundPart("DivP"); this.divNavDebug = this.BoundPart("DivNavDebug"); } this.txtTitle.innerHTML = this.stTitle; this.sm = new StatusMsg(); this.MakeCur(0); this.PlayMode(this.fPlay); } function SlideShow.prototype.WriteUI() { DW(this.StUI()); this.BindUI(); } function SlideShow.prototype.FThumbsLoaded() { for (islide = 0; islide < this.cslides; islide++) { var slide = this.rgslide[islide]; if (!slide.imgThumb.complete && !slide.fThumbError) { this.sm.SetStatus("thumb", "Loading thumbnail " + slide.stThumb); return false; } } this.sm.SetStatus("thumb"); return true; } // When a user selects a slide, we should turn off the auto-play mode function SlideShow.prototype.MakeCurClick(islide) { this.PlayMode(false); this.MakeCur(islide); } function SlideShow.prototype.MakeCur(islide) { var slide; if (this.cslides == 0) return; if (islide == this.islideCur) return; if (this.islideCur != null) { slide = this.rgslide[this.islideCur]; slide.fSel = false; slide.SetStatus(); } this.islideCur = islide; slide = this.rgslide[islide]; slide.fSel = true; slide.Preload(); slide.SetStatus(); this.fTransition = true; } function SlideShow.prototype.DoTransition() { if (!this.FThumbsLoaded()) return; if (!this.fTransition) { this.SpecLoad(); return; } var slide = this.rgslide[this.islideCur]; if (!slide.fLoaded) { this.sm.SetStatus("image", "Loading image " + slide.stSrc); return; } this.sm.SetStatus("image"); this.fTransition = false; // Start up background sound when we're ready to paint the screen if (this.sndBack && this.sndBack.fPlay == undefined) this.sndBack.Play(true); document.body.filters[0].apply(); if (!this.fLayout) this.Layout(); this.imgMain.src = slide.stSrc; this.txtDTitle.innerHTML = slide.stTitle; if (slide.stDate) this.txtDate.innerText = slide.stDate; else this.txtDate.innerText = ""; this.txtDesc.innerHTML = slide.stDesc; if (!this.fFirstSlide) { this.fFirstSlide = true; this.imgMain.style.display = "block"; this.divDesc.style.display = "block"; this.divNav.style.display = "block"; this.divCredits.style.display = "block"; this.txtTitle.style.visibility = "visible"; this.divSplash.style.visibility = "hidden"; this.timerSplash.Active(false); if (this.fDebug) { this.divL.style.display = "block"; this.divP.style.display = "block"; this.divNavDebug.style.display = "block"; } } this.PositionSlide(slide); document.body.filters[0].play(); } // We have some idle time - see if there is any speculative image loading we can do. function SlideShow.prototype.SpecLoad() { var islide; var slide; if (this.cslidesPre > 0 ||this.cslidesLoaded == this.cslides) return; islide = this.islideCur; if (islide == null) islide = 0; else islide = (islide + 1) % this.cslides; var islideDone = islide; var fFirst = true; while (fFirst || islide != islideDone) { fFirst = false; slide = this.rgslide[islide]; if (!slide.fLoaded) { slide.Preload(); break; } islide = (islide+1) % this.cslides; } } function SlideShow.prototype.AutoAdvance() { // Stop play mode when going from penultimate to ultimate slide if (this.islideCur == this.cslides - 2) { this.PlayMode(false); if (this.sndBack) this.sndBack.RampVolume(0, this.secDelay); } this.Advance(1); } function SlideShow.prototype.AdvanceClick(dislide) { this.PlayMode(false); this.Advance(dislide); } function SlideShow.prototype.Advance(dislide) { this.MakeCur((this.islideCur + dislide + this.cslides) % this.cslides); } function SlideShow.prototype.Home() { location = this.stHome; } function SlideShow.prototype.SoundToggle() { this.sndBack.Play(!this.sndBack.fPlay); } function SlideShow.prototype.PlayToggle() { if (!this.fPlay) this.Advance(1); this.PlayMode(!this.fPlay); } // ------------------------------------------------------------ // Layout the page parts // // Layout modes: // // Portrait layout (modePort): Nav box placed to the right of the image rect - bottom aligned. // Description placed above the Nav box. // Lanscape layout (modeLand): Nav box placed beneath the image rect - right aligned. // Description placed to the left of Nav box. // Flip layout (modeFlip): Nav box placed at lower right corner of union of portrait and lanscape // bounding rects. Descriptions are placed above Nav for portrait pics, and to the left of Nav // for landscape pics. // // Nifty 5-step (whew!) Layout Algorithm: // // 1 Compute bounding box of all portrait rects and landscape rects // 2 If we don't have a predominating orientation, try to fit the Nav box in the // lower right of the union of the Landscape and Portrait rects. If it fits, // (does not overlap either bounding rect) we use that. // 3 If all are Portrait (or all images fit within the Portrait bounding box), // then use Portrait mode. // EXCEPTION: if Portrait layout does not fit on the user's screen, BUT, // Landscape does - then use Landscape. // 4 Otherwise, if Portrait mode fits the screen, but not Landscape, use Portrait. // 5 Otherwise, use Landscape. // -----------------------------------------------------mck---- function SlideShow.prototype.Layout() { var dpt; var rcNavP; var rcNavL; var islide; var slide; this.ptSizeL = new Point(0,0); this.ptSizeP = new Point(0,0); for (islide = 0; islide < this.cslides; islide++) { slide = this.rgslide[islide]; if (slide.FLandscape()) this.ptSizeL.Max(slide.ptSize); else this.ptSizeP.Max(slide.ptSize); } // Position image and Show Title this.ptMain = new Point(this.dzMargin, this.dzMargin); PositionElt(this.txtTitle, this.ptMain); this.ptMain.Offset(0, this.txtTitle.offsetHeight + this.dzMargin/2); PositionElt(this.imgMain, this.ptMain); // Note: dom object size not available until it becomes visible (see MakeCur) // so we move it off screen and make it visible. Note that the Nav box has a built-in // margin on it's top and left sides. PositionElt(this.divNav, new Point(-1000,0)); this.divNav.style.display = "block"; this.rcNav = new Rect(new Point(0,0), PtSize(this.divNav)); this.divNav.style.display = "none"; Layout: { // Step 1. this.ptSizeL.Add(new Point(2*this.dzBorder, 2*this.dzBorder)); this.rcL = new Rect(new Point(0,0), this.ptSizeL); this.rcL.Add(this.ptMain); this.ptSizeP.Add(new Point(2*this.dzBorder, 2*this.dzBorder)); this.rcP = new Rect(new Point(0,0), this.ptSizeP); this.rcP.Add(this.ptMain); this.rcPL = this.rcP.Clone(); this.rcPL.Union(this.rcL); dpt = this.rcPL.ptLR.Clone(); dpt.Sub(this.rcNav.ptLR); this.rcNav.Add(dpt); // Step 2. if (!this.rcNav.FIntersect(this.rcL) && !this.rcNav.FIntersect(this.rcP)) { this.mode = SlideShow.modeFlip; break Layout; } // Step 3. rcNavP = this.rcNav.Clone() rcNavP.Offset(this.rcPL.ptLR.x - this.rcNav.ptUL.x, 0); rcNavL = this.rcNav.Clone(); rcNavL.Offset(0, this.rcPL.ptLR.y - this.rcNav.ptUL.y); if (this.rcP.FContainsRc(this.rcL)) { if (this.wc.FFitsScreen(rcNavL.ptLR) && !this.wc.FFitsScreen(rcNavP.ptLR)) { this.mode = SlideShow.modeLand; this.rcNav = rcNavL; break Layout; } this.mode = SlideShow.modePort; this.rcNav = rcNavP; break Layout; } // Step 4. if (this.wc.FFitsScreen(rcNavP.ptLR) && !this.wc.FFitsScreen(rcNavL.ptLR)) { this.mode = SlideShow.modePort; this.rcNav = rcNavP; break Layout; } // Step 5. this.mode = SlideShow.modeLand; this.rcNav = rcNavL; } // We set width and height to avoid resizing with window resizing SetEltRect(this.divNav, this.rcNav); if (this.fDebug) { SetEltRect(this.divL, this.rcL); SetEltRect(this.divP, this.rcP); SetEltRect(this.divNavDebug, this.rcNav); } this.fLayout = true; } function SlideShow.prototype.PositionSlide(slide) { SizeElt(this.imgMain, slide.ptSize); var ptDesc = this.ptMain.Clone(); ptDesc.Offset(0, slide.ptSize.y); var mode = this.mode; var rcDesc; if (mode == SlideShow.modeFlip) mode = slide.FLandscape() ? SlideShow.modeLand : SlideShow.modePort; if (mode == SlideShow.modePort) { rcDesc = new Rect(this.rcPL.ptUL, this.rcNav.PtUR()); rcDesc.ptUL.x += slide.ptSize.x + this.dzMargin; } else { rcDesc = new Rect(this.rcPL.ptUL, this.rcNav.PtLL()); rcDesc.ptUL.y += slide.ptSize.y + this.dzMargin; } SetEltRect(this.divDesc, rcDesc); if (mode == SlideShow.modePort) { // Measure the visible height of the description area to make sure it fits var ptSizeDesc = PtSize(this.divDesc); if (ptSizeDesc.y > rcDesc.Dy()) { rcDesc = new Rect(this.rcPL.ptUL, this.rcNav.PtLL()); rcDesc.ptUL.y += slide.ptSize.y + this.dzMargin; SetEltRect(this.divDesc, rcDesc); } } var ptCredits = this.rcNav.PtLL(); ptCredits.x = this.ptMain.x; ptCredits.y += this.dzMargin; var rcDescActual = RcAbsolute(this.divDesc); if (ptCredits.y < rcDescActual.ptLR.y + this.dzMargin) { ptCredits.y = rcDescActual.ptLR.y + this.dzMargin; } PositionElt(this.divCredits, ptCredits); } Slide.DeriveFrom(Named); function Slide(ss, nd, islide) { var ndT; this.Named(); this.ss = ss; this.islide = islide; this.fNoBase = XMLAttrDef(nd, "NoBase", false); var stSrc = XMLAttrDef(nd, "Src"); this.stSrc = stSrc if (!this.fNoBase) this.stSrc = StBaseURL(ss.stImageBase, this.stSrc); this.stThumb = XMLAttrDef(nd, "Thumb"); if (this.stThumb != undefined) { if (!this.fNoBase) this.stThumb = StBaseURL(ss.stThumbBase, this.stThumb); } else { this.stThumb = stSrc; if (!this.fNoBase) this.stThumb = StBaseURL(ss.stThumbBase, this.stThumb); var ichDot = this.stThumb.lastIndexOf("."); this.stThumb = this.stThumb.substring(0, ichDot) + "-T" + this.stThumb.substring(ichDot); } this.fLoaded = false; this.fError = false; this.fThumbError = false; ndT = nd.selectSingleNode("./Title"); this.stTitle = StXMLContent(ndT); if (this.stTitle == "") this.stTitle = this.stSrc.substring(0, this.stSrc.indexOf(".", 0)); ndT = nd.selectSingleNode("./Date"); this.stDate = StXMLContent(ndT); ndT = nd.selectSingleNode("./Desc"); this.stDesc = StXMLContent(ndT); this.ptSize = PtXMLSizeDef(nd, ss.ptSizeDef); } function Slide.prototype.StThumbUI() { var st = ""; st += "<IMG SRC=" + StAttrQuote(this.stThumb); st += " onmousedown=" + StAttrQuote(this.ss.StNamed() + ".MakeCurClick(" + this.islide + ");"); st += " " + this.StPartID("Thumb"); st += " TITLE=" + StAttrQuote(this.stTitle); st += ">"; return st; } function Slide.prototype.BindUI() { this.imgThumb = this.BoundPart("Thumb"); this.imgThumb.onerror = this.FnCallBack("ThumbError"); this.SetStatus(); } function Slide.prototype.ThumbError() { this.fThumbError = true; } function Slide.prototype.FLandscape() { return this.ptSize.x >= this.ptSize.y; } function Slide.prototype.Preload() { if (this.imgCache != undefined) return; this.imgCache = new Image(); this.imgCache.onload = this.FnCallBack("Loaded"); this.imgCache.onerror = this.FnCallBack("Error"); this.imgCache.src = this.stSrc; this.ss.cslidesPre++; } function Slide.prototype.Loaded() { this.fLoaded = true; this.ss.cslidesLoaded++; // Assume only one image is preloading at a time. this.ss.cslidesPre--; if (!this.fError) { // NOTE: If we find an incorrect image dimension in the slide show - we correct // it and re-layout the show. This may not be correct as the user may want a // scaled image in his show....maybe this code should go. // if (this.imgCache.width != this.ptSize.x || this.imgCache.height != this.ptSize.y) // { // this.ptSize = new Point(this.imgCache.width, this.imgCache.height); // this.ss.fLayout = false; // } } this.SetStatus(); } // Error loading an image. function Slide.prototype.Error() { this.fError = true; this.Loaded(); } function Slide.prototype.SetStatus() { var stClass = "Unloaded"; if (this.fLoaded) stClass = "Loaded"; if (this.fSel) stClass = "Selected"; if (this.fError) stClass = "Error"; this.imgThumb.className = stClass; } <file_sep> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta http-equiv="Content-Language" content="en-us"> <title>Koss Residence - February 2001</title> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> </head> <body style="font-family: Verdana"> <!--webbot bot="Include" U-Include="header.htm" TAG="BODY" startspan --> <table border="0" width="99%" height="112"> <tr> <td width="25%" height="106"> <p align="center"><a href="DesignWeb/images/ext03.jpg"> <img alt="ext03thmb.jpg (8851 bytes)" border="1" src="images/ext03thmb.jpg" width="128" height="96"></a></p> </td> <td width="44%" height="106"> <h1 align="center"><font face="Verdana"><a href="Default.htm">Koss Residence<br> Web</a></font></h1> </td> <td width="31%" height="106"> <p align="center"><a href="http://www.seanet.com/~harleyd/koss/images/ext02.jpg"><a href="DesignWeb/images/ext11.jpg"> <img alt="ext11thmb.jpg (8113 bytes)" border="1" src="images/ext11thmb.jpg" width="128" height="96"></a></p> </td> </tr> </table> <hr> <!--webbot bot="Include" endspan i-checksum="55442" --> <h3>February 2001</h3> <p>Pool roof and finishes.</p> <table border="0" width="100%"> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0009.JPG" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">February 3, 2001</p> <p align="left">Installing the Hardi-Plank on the ceiling of the pool room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0012.JPG" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">February 3, 2001</p> <p align="left">The house is beginning to look nearly finished with final stucco color and nearly complete cedar siding. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0013.JPG" width="350" height="466"></td> <td width="50%" valign="top"> <p align="right">February 3, 2001</p> <p align="left">The QuadWall roofing panels and assembly parts <i>finally</i> arrive (after being delayed by a factory fire). </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0015.JPG" width="350" height="466"></td> <td width="50%" valign="top"> <p align="right">February 3, 2001</p> <p align="left">The courtyard wall is tarped over in preparation for stucco application. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0027.JPG" width="350" height="466"></td> <td width="50%" valign="top"> <p align="right">February 13, 2000</p> <p align="left">Our interior doors are set up to be prepped in the dining room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20010301.JPG" width="350" height="371"></td> <td width="50%" valign="top"> <p align="right">February 13, 2001</p> <p align="left">Painted out speaker grills on the deck really blend in well with the stucco walls. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0031.JPG" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">February 13, 2001</p> <p align="left">Placing stone edging around the courtyard. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0054.JPG" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">February 14, 2001</p> <p align="left">Stucco application on the concrete courtyard wall. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0060.JPG" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">February 15, 2001</p> <p align="left">Pool QuadWall roof installation. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0067.JPG" width="350" height="466"></td> <td width="50%" valign="top"> <p align="right">February 15, 2001</p> <p align="left">Hard-plank boards outside the pool room deck.&nbsp; The ceiling pattern is the same inside and outside. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0068.JPG" width="350" height="466"></td> <td width="50%" valign="top"> <p align="right">February 15, 2001</p> <p align="left">...even under the stairs! </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0072.JPG" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">February 15, 2001</p> <p align="left">Stone detail - bathroom floor tile. </td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"> <p align="right">February 16, 2001</p> <p align="left">We get a big snowfall in Seattle (pictures from Bothell).</p> <p><img border="0" src="images/IMG_0078.JPG" width="350" height="262"><img border="0" src="images/IMG_0081.JPG" width="350" height="262"></td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0094.JPG" width="350" height="466"></td> <td width="50%" valign="top"> <p align="right">February 18, 2001</p> <p align="left">San Diego Zoo.... </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0161.JPG" width="350" height="466"></td> <td width="50%" valign="top"> <p align="right">February 27, 2001</p> <p align="left">The concrete drive is demolished. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0162.JPG" width="350" height="466"></td> <td width="50%" valign="top"> <p align="right">February 27, 2001</p> <p align="left">QuadWall roof installation complete. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/IMG_0166.JPG" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">February 27, 2001</p> <p align="left">Wiring the electrical &quot;closet&quot; behind the media room. </td> </tr> </table> </body> </html> <file_sep>// Persist JSCRIPT Objects to an XML formatted stream // that preserves datatypes and structure. function PersistContext() { this.Init(); // 0: Type-major // 1: Name-major with types // 2: Name-major with no types this.iStyle = 0; } PersistContext.idSerial = 0; PersistContext.prototype.Init = PCInit; function PCInit() { this.st = ""; this.rgstName = new Array; this.mapObjects = new Object; this.istName = 0; this.idSerial = PersistContext.idSerial++; } PersistContext.prototype.SetName = PCSetName; function PCSetName(stName) { this.rgstName[this.istName++] = stName; } PersistContext.prototype.StName = PCStName; function PCStName() { return this.rgstName[this.istName-1]; } PersistContext.prototype.PopName = PCPopName; function PCPopName() { this.istName--; } PersistContext.prototype.AddLine = PCAddLine; function PCAddLine(st) { //alert("AddLine: " + st); var ich; var ichMax = (this.istName-1) * 2; for (ich = 0; ich<ichMax; ich++) this.st += " "; this.st += st + "\r"; } PersistContext.prototype.StPath = PCStPath; function PCStPath() { var ist; var st = ""; for (ist = 0; ist < this.istName; ist++) { if (ist != 0) st += "."; st += this.rgstName[ist]; } return st; } PersistContext.prototype.PersistOpen = PCPersistOpen; function PCPersistOpen(obj) { var stType = this.StType(obj); var st = StBuildParam(PersistContext.rgstObjectOpen[this.iStyle], stType, this.StName()); this.AddLine(st); } PersistContext.prototype.PersistClose = PCPersistClose; function PCPersistClose(obj) { var stType = this.StType(obj); var st = StBuildParam(PersistContext.rgstObjectClose[this.iStyle], stType, this.StName()); this.AddLine(st); } PersistContext.prototype.StType = PCStType; function PCStType(obj) { var stType = typeof(obj); if (stType == "object") { switch (obj.constructor) { case Array: return "Array"; case Object: return "Object"; case Date: return "Date"; case Function: return "Function"; } stType = obj.constructor.toString(); stType = stType.substr(9, stType.indexOf("(")-9); } else { stType = stType.substr(0, 1).toUpperCase() + stType.substr(1); } return stType; } // Format for Type, Name, Value PersistContext.rgstValue = new Array( "<^1 Name=^2.a Value=^3.a/>", "<^2 Type=^1.a>^3</^2>", "<^2>^3</^2>"); // Format for Class, Name, [Ref] PersistContext.rgstObjectOpen = new Array( "<^1 Name=^2.a>", "<^2 Type=^1.a>", "<^2>"); PersistContext.rgstObjectClose = new Array( "</^1>", "</^2>", "</^2>"); PersistContext.rgstObjectRef = new Array( "<^1 Name=^2.a Ref=^3.a/>", "<^2 Ref=^3.a/>", "<^2 Ref=^3.a/>"); PersistContext.prototype.PersistValue = PCPersistValue; function PCPersistValue(stType, value) { this.AddLine(StBuildParam(PersistContext.rgstValue[this.iStyle], stType, this.StName(), value)); } function StAttribute(stAttr) { return "\"" + stAttr + "\""; } PersistContext.mapExcludeProps = new Object; PersistContext.mapExcludeProps.stPersistPath = true; PersistContext.mapExcludeProps.idSerial = true; Number.prototype.Persist = ScalarPersist; String.prototype.Persist = ScalarPersist; Boolean.prototype.Persist = ScalarPersist; function ScalarPersist(pc) { if (PersistContext.mapExcludeProps[pc.StName()]) return; pc.PersistValue(pc.StType(this.valueOf()), this.valueOf()); } Object.prototype.Persist = ObjectPersist; function ObjectPersist(pc) { var stType = pc.StType(this); if (stType == "Function") { return; } if (this.idSerial == pc.idSerial) { var st = StBuildParam(PersistContext.rgstObjectRef[pc.iStyle], stType, pc.StName(), this.stPersistPath); pc.AddLine(st); return; } this.idSerial = pc.idSerial; this.stPersistPath = pc.StPath(); pc.PersistOpen(this); for (prop in this) { pc.SetName(prop); this[prop].Persist(pc); pc.PopName(); } pc.PersistClose(this); } function StAttrQuote(st) { return '"' + StAttrQuoteInner(st) + '"'; } function StAttrQuoteInner(st) { st = st.toString(); st = st.replace(/&/g, '&amp;'); st = st.replace(/\"/g, '&quot;'); // " to fool LocStudio st = st.replace(/\r/g, '&#13;'); return st; } function StBuildParam(stPattern) { var re; var i; for (i = 1; i < StBuildParam.arguments.length; i++) { re = new RegExp("\\^" + i + "\.a", "g"); stPattern = stPattern.replace(re, StAttrQuote(StBuildParam.arguments[i])); re = new RegExp("\\^" + i, "g"); stPattern = stPattern.replace(re, StBuildParam.arguments[i]); } return stPattern; } // // Parsing XML to create objects PersistContext.prototype.ParseXML = PCParseXML; function PCParseXML(stXML) { this.doc = new ActiveXObject("Microsoft.XMLDOM"); var fParsed = this.doc.loadXML(stXML); if (!fParsed) { var pe = this.doc.parseError; var code = (pe.errorCode ^ 0x80000000) & 0xFFFFFFF; alert("Error in line " + pe.line + ": " + pe.reason + "(Error code: " + code.toString(16).toUpperCase() + ")"); return; } return this.ObjectNode(this.doc.documentElement); } PersistContext.prototype.StNameNode = PCStNameNode; function PCStNameNode(node) { if (this.iStyle == 0) return node.attributes.getNamedItem("Name").nodeValue; return node.baseName; } PersistContext.prototype.StTypeNode = PCStTypeNode; function PCStTypeNode(node) { if (this.iStyle == 0) return node.baseName; var stType = node.attributes.getNamedItem("Type").nodeValue; if (this.iStyle == 1) return stType; if (!stType) stType = "Object"; return stType; } PersistContext.prototype.StValueNode = PCStValueNode; function PCStValueNode(node) { var stValue; if (this.iStyle == 0) stValue = node.attributes.getNamedItem("Value").nodeValue; else stValue = node.nodeValue; switch (this.StTypeNode(node)) { case "Number": return parseFloat(stValue); case "Boolean": return stValue == "true"; } return stValue; } PersistContext.prototype.ObjectNode = PCObjectNode; function PCObjectNode(node) { var i; var nodes = node.childNodes; var obj; if (node.attributes.getNamedItem("Ref")) { obj = this.mapObjects[node.attributes.getNamedItem("Ref").nodeValue]; return obj; } for (i = 0; i < nodes.length; i++) { if (nodes(i).nodeType == 1) { if (!obj) { obj = eval("new " + this.StTypeNode(node)); this.SetName(this.StNameNode(node)); this.mapObjects[this.StPath()] = obj; } var objChild = this.ObjectNode(nodes(i)); obj[this.StNameNode(nodes(i))] = objChild; } } if (obj) { this.PopName(); return obj; } return this.StValueNode(node); } <file_sep>// ------------------------------------------------------------ // util.js // // Copyright, 2003-2004 by <NAME> (<EMAIL>) // // History: // // January 31, 2004 [mck] Added Point and Rect utilities for object positioning. // November 28, 2003 [mck] Copied base JScript utilities from object.js. // // This file contains utilities for enabling a richer object-oriented code in JScript // as well as helper functions for string processing, collections (Bag's), and absolute // positioned DHTML. // ------------------------------------------------------------ // Header template - copy me // -----------------------------------------------------mck---- var cbUtil = new CodeBase("util.js"); // ------------------------------------------------------------ // CodeBase - determine location of script file // -----------------------------------------------------mck---- function CodeBase(stScript) { var stPath; var ichFile; for (i = 0; i < document.scripts.length; i++) { stPath = document.scripts(i).src; ichFile = stPath.indexOf(stScript, 0); if (ichFile >= 0) { this.stPath = stPath.substring(0, ichFile); if (this.stPath.indexOf("http://") == 0) this.stDomain = this.stPath.substring(7); break; } } } function CodeBase.prototype.MailTag(stUser, stSubject) { var st = ""; st += "mailto:" + this.stDomain + "@" + stUser; if (stSubject != undefined) st += "?subject=" + stSubject; document.write("<A HREF=" + StAttrQuote(st) + ">"); } function CodeBase.prototype.IncludeScript(stFile) { document.write("<" + "SCRIPT SRC='" + this.stPath + stFile + "'></" + "SCRIPT>"); } function CodeBase.prototype.IncludeStyle(stFile) { document.createStyleSheet(this.stPath + stFile); } // ------------------------------------------------------------ // Object Orientation Functions // -----------------------------------------------------mck---- // Copy all base class methods that do not have a definition in the current // constructor prototype. Also add a prototype variable that references to // base class's constructor by name function Function.prototype.DeriveFrom(fnBase) { var prop; if (this == fnBase) { alert("Error - cannot derive from self"); return; } for (prop in fnBase.prototype) { if (typeof(fnBase.prototype[prop]) == "function" && !this.prototype[prop]) { this.prototype[prop] = fnBase.prototype[prop]; } } this.prototype[fnBase.StName()] = fnBase; } function Function.prototype.StName() { var st; st = this.toString(); st = st.substring(st.indexOf(" ")+1, st.indexOf("(")); return st; } // Give subclass access to parent's method, via Parent_Method() like call. function Function.prototype.Override(fnBase, stMethod) { this.prototype[fnBase.StName() + "_" + stMethod] = fnBase.prototype[stMethod]; } function Function.prototype.StParams() { var st; st = this.toString(); st = st.substring(st.indexOf("("), st.indexOf(")")+1); return st; } // ------------------------------------------------------------ // Named - Base class for jsavascript objects that need scriptable names // // Derive from the Named object for any object that you want to have a script-evalable name // (these are often needed in attributes added to browser elements for click events, timer callbacks etc.) // // e.g. // MyObj.DeriveFrom(Named); // function MyObj() // { // this.Named(); // ... // } // "<IMG onclick=" + StAttrQuote(this.StNamed() + ".Callback();") + ">" // -----------------------------------------------------mck---- Named.idNext = 0; Named.rg = new Array; function Named() { this.idNamed = Named.idNext++; Named.rg[this.idNamed] = this; } // Name for the JS object function Named.prototype.StNamed() { return "Named.rg[" + this.idNamed + "]"; } // Produce DHTML name for web component associated with this JS object function Named.prototype.StNamedPart(stPart, iPart) { var st; st = "NM_" + this.idNamed + "_" + stPart; if (iPart != undefined) st += "_" + iPart; return st; } function Named.prototype.StPartID(stPart, iPart) { return "ID=" + StAttrQuote(this.StNamedPart(stPart, iPart)); } function Named.prototype.BoundPart(stPart, iPart) { return eval(this.StNamedPart(stPart, iPart)); } function Named.prototype.FnCallBack(stFunc) { return new Function(this.StNamed() + "." + stFunc + "();"); } // ------------------------------------------------------------ // Misc and string quoting Functions // -----------------------------------------------------mck---- function NYI() { alert(NYI.caller.StName() + ": Not yet implemented"); } function StAttrQuote(st) { return '"' + StAttrQuoteInner(st) + '"'; } function StAttrQuoteInner(st) { st = st.toString(); st = st.replace(/&/g, '&amp;'); st = st.replace(/\"/g, '&quot;'); // editor confused about single quote " st = st.replace(/'/g, '&#39;'); // editor confused about single quote ' st = st.replace(/\r/g, '&#13;'); return st; } function DW(st) { document.write(st); } function Array.prototype.toString() { var i; var st = ""; st += "["; for (i = 0; i < this.length; i++) { if (i != 0) st += ", "; st += this[i].toString(); } st += "]"; return st; } function String.prototype.StRotate(iRot) { return this.substring(iRot) + this.substring(0, iRot); } function String.prototype.StReplace(stPat, stRep) { var st = ""; var ich = 0; var ichFind = this.indexOf(stPat, 0); while (ichFind >= 0) { st += this.substring(ich, ichFind) + stRep; ich = ichFind + stPat.length; ichFind = this.indexOf(stPat, ich); } st += this.substring(ich); return st; } function StHTML(st) { st = st.toString(); st = st.replace(/&/g, '&amp;'); st = st.replace(/</g, '&lt;'); st = st.replace(/>/g, '&gt;'); st = st.replace(/\n/g, '<br>'); st = st.replace(/ /g, '&nbsp;'); st = st.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;'); return st; } function StBaseURL(stBase, stURL) { if (stURL.indexOf("://", 0) < 0) stURL= stBase + stURL; return stURL; } // ------------------------------------------------------------ // BAG - Supports collections of objects and enumeration // -----------------------------------------------------mck---- Bag.idNext = 0; function Bag() { this.rg = new Array; this.stName = "Bag" + Bag.idNext++; this.idNext = 0; this.c = 0; } function Bag.prototype.Add(obj) { // Already a member of this bag if (obj[this.stName] != undefined) return; this.rg[this.idNext] = obj; obj[this.stName] = this.idNext; this.idNext++; this.c++; } function Bag.prototype.Remove(obj) { var id = obj[this.stName]; // Not in this bag if (id == undefined) return; this.rg[id] = undefined; this.c--; } function Bag.prototype.FMember(obj) { return obj[this.stName] != undefined; } // // IBag - Iterator for Bag's // function IBag(bag) { this.bag = bag; this.Init(); } function IBag.prototype.Init() { this.i = -1; } function IBag.prototype.FNext() { while (++this.i < this.bag.rg.length) { if (this.bag.rg[this.i] != undefined) return true; } return false; } function IBag.prototype.Obj() { if (this.i == -1) this.FNext(); return this.bag.rg[this.i]; } // ------------------------------------------------------------ // FileLoad - Allows reading files into JScript programs // -----------------------------------------------------mck---- FileLoad.DeriveFrom(Named); function FileLoad() { this.Named(); this.id = FileLoad.idNext++; FileLoad.rgfl[this.id] = this; } function FileLoad.prototype.StUI() { var st = ""; st += "<IFRAME "; st += "style=display:none "; st += this.StPartID("Frame"); st += " onload=" + StAttrQuote(this.StNamed() + ".Loaded(); "); st += "></IFRAME>"; return st; } function FileLoad.prototype.BindUI() { this.frData = this.BoundPart("Frame"); } function FileLoad.prototype.WriteUI() { DW(this.StUI()); this.BindUI(); } function FileLoad.prototype.GetFile(stFile, fnCallback) { this.frData.document.location = stFile; this.fnCallBack = fnCallback; this.fLoaded = false; } function FileLoad.prototype.Loaded() { this.fLoaded = true; if (this.fnCallBack != undefined) this.fnCallBack(this); } function FileLoad.prototype.StFile() { if (!this.fLoaded) return ""; return this.frData.document.body.innerText; } // ------------------------------------------------------------ // Geometrical and element positioning primitives // // Point - pt.x, pt.y // Rect - rc.ptUL, rc.ptLR // -----------------------------------------------------mck----// function Point(x, y) { this.x = x; this.y = y; } function Point.prototype.Clone() { return new Point(this.x, this.y); } function Point.Negate() { this.x = -this.x; this.y = -this.y; } function Point.prototype.Add(pt) { this.x += pt.x; this.y += pt.y; } function Point.prototype.Offset(dx, dy) { this.x += dx; this.y += dy; } function Point.prototype.Sub(pt) { this.x -= pt.x; this.y -= pt.y; } function Point.prototype.Min(pt) { this.x = Math.min(this.x, pt.x); this.y = Math.min(this.y, pt.y); } function Point.prototype.Max(pt) { this.x = Math.max(this.x, pt.x); this.y = Math.max(this.y, pt.y); } function Point.prototype.Mult(num) { this.x *= num; this.y *= num; } function Rect(ptUL, ptLR) { if (ptUL == undefined) this.ptUL = new Point(0,0); else this.ptUL = ptUL.Clone(); if (ptLR == undefined) ptLR = this.ptUL; this.ptLR = ptLR.Clone(); } function Rect.prototype.Clone() { return new Rect(this.ptUL, this.ptLR); } function Rect.prototype.Offset(dx, dy) { this.ptUL.Offset(dx, dy); this.ptLR.Offset(dx, dy); } function Rect.prototype.Add(ptD) { this.ptUL.Add(ptD); this.ptLR.Add(ptD); } function Rect.prototype.Union(rc) { this.ptUL.Min(rc.ptUL); this.ptLR.Max(rc.ptLR); } function Rect.prototype.BBox(pt) { this.ptUL.Min(pt); this.ptLR.Max(pt); } function Rect.prototype.PtCenter() { var ptCenter = this.ptUL.Clone(); ptCenter.Add(this.ptLR); ptCenter.Mult(1/2); return ptCenter; } function Rect.prototype.CenterOn(ptCenter) { var ptPos = ptCenter.Clone(); ptPos.Offset(-this.Dx()/2, -this.Dy()/2); ptPos.Sub(this.ptUL); this.Add(ptPos); } function Rect.prototype.PtSize() { var ptSize = this.ptLR.Clone(); ptSize.Sub(this.ptUL); return ptSize; } function Rect.prototype.Dx() { return this.ptLR.x - this.ptUL.x; } function Rect.prototype.Dy() { return this.ptLR.y - this.ptUL.y; } // Rectangles must include at least 1 pixel of OVERLAP to be considered intersecting // (not merely coincident on one edge). function Rect.prototype.FIntersect(rc) { return (FIntersectRange(this.ptUL.x, this.ptLR.x, rc.ptUL.x, rc.ptLR.x) && FIntersectRange(this.ptUL.y, this.ptLR.y, rc.ptUL.y, rc.ptLR.y)); } function Rect.prototype.FContainsPt(pt) { return (pt.x >= this.ptUL.x && pt.x <= this.ptLR.x && pt.y >= this.ptUL.y && pt.y <= this.ptLR.y); } function Rect.prototype.FContainsRc(rc) { return (this.FContainsPt(rc.ptUL) && this.FContainsPt(rc.ptLR)); } function FIntersectRange(x1Min, x1Max, x2Min, x2Max) { return x1Max > x2Min && x2Max > x1Min; } function Rect.prototype.PtUR() { return new Point(this.ptLR.x, this.ptUL.y); } function Rect.prototype.PtLL() { return new Point(this.ptUL.x, this.ptLR.y); } // Map to an interior portion of the rectangle - proportional to numX and numY [0..1] // for all points in the interior. function Rect.prototype.PtMap(numX, numY) { var dpt = this.ptLR.Clone(); dpt.Sub(this.ptUL); dpt.x *= numX; dpt.y *= numY; dpt.Add(this.ptUL); return dpt; } // Get absolute position on the page for the upper left of the element. function PtAbsolute(elt) { var pt = new Point(0,0); while (elt.offsetParent != null) { pt.x += elt.offsetLeft; pt.y += elt.offsetTop; elt = elt.offsetParent; } return pt; } // Return size of a DOM element in a Point function PtSize(elt) { return new Point(elt.offsetWidth, elt.offsetHeight); } // Return aboslute bounding rectangle for a DOM element function RcAbsolute(elt) { var rc = new Rect; rc.ptUL = PtAbsolute(elt); rc.ptLR = rc.ptUL.Clone(); rc.ptLR.Add(PtSize(elt)); return rc; } // Set DOM element absolution position function PositionElt(elt, pt) { // assumes elt.style.position = "absolute" elt.style.pixelLeft = pt.x; elt.style.pixelTop = pt.y; } // Set DOM element size function SizeElt(elt, pt) { if (pt.x != undefined) elt.style.pixelWidth = pt.x; if (pt.y != undefined) elt.style.pixelHeight = pt.y; } // Set DOM element Rect function SetEltRect(elt, rc) { PositionElt(elt, rc.ptUL); SizeElt(elt, rc.PtSize()); } // // Timer class supports periodic execution of a snippet of jscript code. // Timer.DeriveFrom(Named); function Timer(stCode, ms, obj) { this.Named(); this.stCode = stCode; this.ms = ms; this.obj = obj; this.iPing = 0; } function Timer.prototype.Ping() { if (this.obj) this.obj.Ping(); if (this.stCode) eval(this.stCode); } // Calling Active resets the timer so that next call to Ping will be in this.ms milliseconds from NOW function Timer.prototype.Active(fActive) { if (this.iTimer) { clearInterval(this.iTimer); this.iTimer = undefined; } if (fActive) this.iTimer = setInterval(this.StNamed() + ".Ping();", this.ms); } // ------------------------------------------------------------ // Button - creates on-screen UI for calling a function // -----------------------------------------------------mck---- Button.DeriveFrom(Named); function Button(stLabel, stCode, stImg1, stImg2, stTitle) { this.Named(); this.stLabel = stLabel; this.stCode = stCode; this.fText = (stImg1 == undefined); this.stImg1 = stImg1; this.stImg2 = stImg2; this.stTitle = stTitle; this.fToggle = false; this.fCapture = false; this.fAlpha = stImg1 && stImg1.indexOf(".png", 0) > 0; if (this.fAlpha) { // Load the images so we can get the width/height this.img1 = new Image(); this.img1.onload = this.FnCallBack("ImgLoaded"); this.fLoaded = false; this.img1.src = stImg1; if (this.stImg2) { this.img2 = new Image(); this.img2.src = stImg2; } } } function Button.prototype.SetHeight(dy) { this.dyTarget = dy; } function Button.prototype.StUI() { var st = ""; if (this.fText) { st += "<INPUT " + this.StPartID("Button") + " TYPE=Button class=TextButton Value=" + StAttrQuote(this.stLabel); if (this.stTitle != undefined) st += " TITLE=" + StAttrQuote(this.stTitle); st += " onclick=" + StAttrQuote(this.stCode) + ">"; return st; } st += "<IMG " + this.StPartID("Button") + " class=ImgButton SRC="; if (this.fAlpha) { st += StAttrQuote(cbUtil.stPath + "images/blank.gif"); } else st += StAttrQuote(this.stImg1); if (this.stTitle != undefined) st += " TITLE=" + StAttrQuote(this.stTitle); st += ">"; return st; } function Button.prototype.BindUI() { this.btn = this.BoundPart("Button"); if (!this.fText) { this.btn.onmousedown = this.FnCallBack("MouseDown"); this.btn.onmousemove = this.FnCallBack("MouseMove"); this.btn.onmouseup = this.FnCallBack("MouseUp"); this.btn.onlosecapture = this.FnCallBack("LoseCapture"); } this.SizeButton(); this.ButtonDown(false); } function Button.prototype.SizeButton() { if (!this.fLoaded || this.btn == undefined) return; var wScale = 1.0; if (this.dyTarget != undefined) wScale = this.dyTarget/this.img1.height; this.btn.style.pixelWidth = this.img1.width * wScale; this.btn.style.pixelHeight = this.img1.height * wScale; } function Button.prototype.ImgLoaded() { this.fLoaded = true; this.SizeButton(); } function Button.prototype.ButtonDown(fDown) { if (fDown == this.fDown) return; this.fDown = fDown; if (this.fText) return; var stImg = (fDown && this.stImg2) ? this.stImg2 : this.stImg1; if (this.fAlpha) { var st = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + StAttrQuote(stImg) + ", sizingMethod=scale)"; this.btn.style.filter = st; } else this.btn.src = stImg; } function Button.prototype.MouseDown() { this.fCapture = true; this.btn.setCapture(); this.rc = RcAbsolute(this.btn); this.ptMouse = new Point(0,0); this.fDownCap = this.fDown; this.ButtonDown(!this.fDownCap); } function Button.prototype.MouseMove() { if (!this.fCapture) return; this.ptMouse.x = event.clientX; this.ptMouse.y = event.clientY; this.ButtonDown(this.rc.FContainsPt(this.ptMouse) ^ this.fDownCap); } function Button.prototype.LoseCapture() { this.fCapture = false; this.ButtonDown(this.fDownCap); } function Button.prototype.MouseUp() { if (this.fDown == this.fDownCap) { document.releaseCapture(); return; } if (this.fToggle) this.fDownCap = !this.fDownCap; document.releaseCapture(); eval(this.stCode); } // ------------------------------------------------------------ // XML Utility functions // // Used for reading XML data islands // -----------------------------------------------------mck---- // Collect the text of all enclosed child nodes function StXMLContent(nd) { var i; var st = ""; if (!nd) return st; for (i = 0; i < nd.childNodes.length; i++) { st += nd.childNodes.item(i).xml; } return st; } // Read an attribute from a node, and provide a default value for a missing attribute // fNum=undefined/false: Treat as string // fNum=true: Treat as (floating point) number // fNum=2: Treat as Boolean! function XMLAttrDef(nd, stAttr, def) { if (!nd) return def; var stValue = nd.getAttribute(stAttr); if (stValue == undefined) return def; if (typeof(def) == "boolean") { var f; stValue = stValue.toUpperCase(); f = stValue == "TRUE" || stValue == "ON" || stValue == "YES"; return f; } if (typeof(def) == "number") return parseFloat(stValue); return stValue; } function PtXMLSizeDef(nd, ptDef, stPrefix) { if (stPrefix == undefined) stPrefix = ""; var ptSize = new Point(XMLAttrDef(nd, stPrefix + "Width", ptDef.x), XMLAttrDef(nd, stPrefix + "Height", ptDef.y)); return ptSize; } // ------------------------------------------------------------ // Object dump routines (for debugging) // -----------------------------------------------------mck---- var DumpCtx = new Object; DumpCtx.iDepth = 0; DumpCtx.iDepthMax = 3; DumpCtx.fProto = false; function Object.prototype.StDump() { var st = ""; var cProps = 0; var prop; if (DumpCtx.iDepth > DumpCtx.iDepthMax) { st += " '" + this.toString() + "'"; return st; } if (this.constructor == undefined) return "ActiveX Control"; DumpCtx.iDepth++; // All own properties for (prop in this) { if (this.hasOwnProperty(prop)) { st += StDumpVar(prop, this[prop]); cProps++; } } DumpCtx.iDepth--; if (cProps == 0) return ""; return st; } function StDumpVar(stVar, value) { var st = "\n"; for (i = 0 ; i < DumpCtx.iDepth; i++) st += " "; st += stVar + ": " ; if (value == undefined) { st += "UNDEFINED"; } else if (typeof(value) == "object") { if (value.constructor != undefined) st += value.StDump(); else st += "ActiveX Control"; } else if (typeof(value) == "function") { stT = value.toString(); st += stT.substring(0, stT.indexOf("(")); } else st += value.toString(); return st; } // Dump the properties of a DHTML element by enumerating all properties function StDumpAttrs(nd) { var i; var st = ""; var attr; for (i = 0; i < nd.attributes.length; i++) { attr = nd.attributes(i); if (attr.nodeValue != null && attr.nodeValue != "") st += attr.nodeName + ": " + attr.nodeValue + "\n"; } return st; } function WindowControl(fResize) { this.Refresh(); // Moving the window causes some (brief) flashing - allow use of defaults this.Calibrate(fResize); // Subtract for scroll and status bars too this.ptMaxVisSize = new Point(screen.availWidth - this.ptControls.x, screen.availHeight - this.ptControls.y); } function WindowControl.prototype.Refresh() { this.ptUL = new Point(window.screenLeft, window.screenTop); this.ptWindowSize = new Point(document.body.clientWidth, document.body.clientHeight); this.rc = new Rect(undefined, this.ptWindowSize); } // Temporarily move the window to the origin, so I can get the dimensions of the controls // around the window (to ultimately compute the max visible area in the window. function WindowControl.prototype.Calibrate(fResize) { if (fResize) { var ptULStart = new Point(window.screenLeft, window.screenTop); window.moveTo(0,0); ptULStart.Sub(this.ptUL); window.moveBy(ptULStart.x, ptULStart.y); this.ptControls = this.ptUL.Clone(); } else { this.ptControls = new Point(4, 121); } this.ptControls.x += 12; this.ptControls.y += 16; } function WindowControl.prototype.FFitsScreen(ptSize) { return ptSize.x <= this.ptMaxVisSize.x && ptSize.y <= this.ptMaxVisSize.y; } function WindowControl.prototype.FFitsWindow(ptSize) { this.Refresh(); return ptSize.x <= this.ptWindowSize.x && ptSize.y <= this.ptWindowSize.y; } function WindowControl.prototype.SizeTo(ptSize) { var pt = ptSize.Clone(); pt.Add(this.ptControls); window.resizeTo(pt.x, pt.y); } // ------------------------------------------------------------ // Sound -Allows for control of sound files // -----------------------------------------------------mck---- Sound.DeriveFrom(Named) function Sound(stSrc) { this.Named(); this.stSrc = stSrc; this.vol = 100; this.fLoop = false; this.timer = new Timer(undefined, 300, this); } function Sound.prototype.StUI() { var st = ""; // Note: Media Player Version 9 class ID here. // May want to switch to older version that had a CODEBASE supported parameter for // auto-download. // CLASSID="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" // CODEBASE="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" st += "<OBJECT style='display:none;' " + this.StPartID("Player"); st += " CLASSID='CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6'>" st += " <PARAM NAME=URL VALUE=" + StAttrQuote(this.stSrc) + ">"; st += " <PARAM NAME=autoStart VALUE=false>"; st += "</OBJECT>"; return st; } function Sound.prototype.BindUI() { this.player = this.BoundPart("Player"); this.player.settings.volume=100; if (this.fLoop) this.player.settings.setMode("loop", true); } // Set sound volume to ramp (linearly) to new volume [0..100] over time given (sec). function Sound.prototype.RampVolume(vol, sec) { var msNow = new Date().getTime(); this.msStart = msNow; this.msEnd = msNow + sec*1000; this.volStart = this.vol; this.volEnd = vol; this.timer.Active(true); } function Sound.prototype.Mute(fMute) { this.player.settings.mute = fMute; } function Sound.prototype.Play(fPlay) { this.fPlay = fPlay; if (fPlay) this.player.controls.play(); else this.player.controls.pause(); } function Sound.prototype.Ping() { var msNow = new Date().getTime(); var volNew = NumProportion(msNow, this.msStart, this.msEnd, this.volStart, this.volEnd); this.player.settings.volume = volNew; if (msNow > this.msEnd) this.timer.Active(false); } // ------------------------------------------------------------ // NumProportion - Return a scaled value where source range is mapped // to an output range (linear interpolation). // -----------------------------------------------------mck---- function NumProportion(numIn, numInMin, numInMax, numOutMin, numOutMax) { var num; if (numIn <= numInMin) return numOutMin; if (numIn >= numInMax) return numOutMax; num = (numIn - numInMin) * (numOutMax-numOutMin) / (numInMax-numInMin) + numOutMin; return num; } // ------------------------------------------------------------ // StatusMsg - Handle mutliple levels of status messages being displayed // to the user. To have status displayed in a DHTML element, pass in the // element as an arugment. Othewise, the status bar is used. // // Each status message belongs in a "slot" - any key can be used. Each slot // can contain one text string. All slots are concatenated together to display // the user-visible status message. // -----------------------------------------------------mck---- function StatusMsg(txtStat) { this.txtStat = txtStat; this.mpStatus = new Array; } function StatusMsg.prototype.SetStatus(stSlot, stMsg) { if (stMsg == null || stMsg == undefined) this.mpStatus[stSlot] = undefined; else this.mpStatus[stSlot] = stMsg; this.Display(); } function StatusMsg.prototype.StDisplay() { var st = ""; var stSlot; for (stSlot in this.mpStatus) { if (!this.mpStatus.hasOwnProperty(stSlot)) continue; if (this.mpStatus[stSlot] != undefined) st += this.mpStatus[stSlot] + " "; } return st; } function StatusMsg.prototype.Display() { var st = this.StDisplay(); if (this.txtStat != undefined) this.txtStat.innerText = st; else status = st; } <file_sep><!DOCTYPE HTML PUBLIC "-//W3O/DTD HTML//EN"> <html> <head> <title>Basic Logo Commands</title> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="FORMATTER" content="Vermeer FrontPage 1.0"> </head> <body bgcolor="#FFFFFF"> <h1><img src="images/rtree.gif" align="baseline" width="135" height="112">LOGO Programming <a href="OldDefault.htm"><img src="images/mikeface.gif" align="baseline" border="0" width="100" height="141"></a></h1> <hr noshade> <h1><em>Basic Commands</em></h1> <p align="center"><!-- ------------------------- --> <!-- START OF CONVERTED OUTPUT --> <!-- ------------------------- --> <Table border> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+5> <TD ALIGN="left"><B> Command </B></TD> <TD ALIGN="left"><B> What it does </B></TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> FD 100 </TD> <TD ALIGN="left"> Move the turtle forward 100 steps. </TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> RT 90 </TD> <TD ALIGN="left"> Turn the turtle to the right 90º. </TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> LT 90 </TD> <TD ALIGN="left"> Turn the turtle to the left 90º. </TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> BK 100 </TD> <TD ALIGN="left"> Move the turtle backwards 100 steps. </TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> PU </TD> <TD ALIGN="left"> Pick the turtle's pen up off the paper. </TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> PD </TD> <TD ALIGN="left"> Put the turtles pen back down on the paper. </TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> CS </TD> <TD ALIGN="left"> Clear the screen and start over. </TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> HT </TD> <TD ALIGN="left"> Hide the turtle (triangle). </TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> ST </TD> <TD ALIGN="left"> Show the turtle (triangle). </TD> </FONT></TR> <TR VALIGN="bottom"><FONT FACE="Arial" SIZE=+2> <TD ALIGN="center"> REPEAT 3 [...] </TD> <TD ALIGN="left"> Repeat the commands 3 times. </TD> </FONT></TR> </Table> <!-- ------------------------- --> <!-- END OF CONVERTED OUTPUT --> <!-- ------------------------- --> <hr noshade> <address> Comments or questions? Send me <a href="mailto:<EMAIL>"> mail</a>.<br> Copyright &#169; 1996, <NAME>.<br> &#160;&#160;<br> Last revised: February 25, 1996 </address> </body> </html> <file_sep><html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta name="GENERATOR" content="Microsoft FrontPage 5.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>BlueScream</title> </head> <body style="font-family: Verdana"> <h1 align="center"><font color="#0000FF">BlueScream</font></h1> <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="AutoNumber1"> <tr> <td width="50%" valign="top"> <img src="images/final.jpg" width="390" height="268"></td> <td width="50%"> <p align="center"><a href="http://web.mit.edu/6.270">MIT 6.270 Competition</a><br> January 2001<br> <br> <i><a href="masters.mht">Masters of the Universe</a></i><br> <br> <b> Microsoft Team:<br> </b> <NAME> ('99)<br> <NAME> ('94)<br> <NAME> ('83)<br> <NAME><br> <NAME></p> <p align="center"><i><font size="2">Web page by <a href="mailto:<EMAIL>">Mike Koss</a></font></i></p> <p>&nbsp;</td> </tr> </table> <p align="left">The organizers of MIT's 6.270 invited Microsoft to participate in this year's robot competition as a corporate sponsor.&nbsp; This gave us about two weeks before we had to fly to Boston, and another 5 days in the lab on campus before the day of the final competition.</p> <p align="left">We were able to demonstrate correct orientation and effective ball stealing (getting balls from the opponents side of the table and bringing them to our own side) in the lab; but we failed to do as well in the lighting conditions during the competitions.&nbsp; I'd attribute this to running out of time to work the bugs out of the software - we didn't really stabilize our hardware platform and were making changes so late that we were not able to adapt and debug completely.</p> <p align="left">But we did have fun making a <i>placebo</i> program which we ran during contest day.&nbsp; Our placebo would spin around, whack it's gate on the table, and pop wheelies.&nbsp; Unfortunately (but hilariously), by placing our batteries in a spot conducive to wheelies, we also made our robot very likely to fall over on it's back; which it did in each of the demos in front of an audience.</p> <table border="0" width="100%"> <tr> <td width="50%" valign="top"><img src="images/fried%20batteries.jpg" width="279" height="270"></td> <td width="50%" valign="top"> <p align="right">Friday, January 12, 2001</p> <p>We received our box of robot parts.&nbsp; Unfortunately, some of the (high current) batteries got loose in shipping and shorted out.&nbsp; Luckily, it only charred some batteries and didn't burn up the whole box!</td> </tr> <tr> <td width="50%" valign="top"><img src="images/IMG_0058.JPG" width="350" height="262"></td> <td width="50%" valign="top">Ya-Bing, Fei and Kevin at one of our evening work sessions before going to Boston.</td> </tr> <tr> <td width="50%" valign="top"><img src="images/IMG_0061.JPG" width="350" height="450"></td> <td width="50%" valign="top">Kevin built a lot of the electronics and sensors used by our robot.</td> </tr> <tr> <td width="50%" valign="top"><img src="images/IMG_0064.JPG" width="350" height="467"></td> <td width="50%" valign="top">Fei works on the base of our robot.</td> </tr> <tr> <td width="50%" valign="top"><img src="images/IMG_0063.JPG" width="350" height="262"></td> <td width="50%" valign="top">An early version of BlueScream (at Microsoft).</td> </tr> <tr> <td width="50%" valign="top"><img src="images/IMG_0105.JPG" width="350" height="262"></td> <td width="50%" valign="top">BlueScream as it appeared just before our trip to Boston.</td> </tr> <tr> <td width="50%" valign="top"><img border="0" src="images/IMG_0086.JPG" width="350" height="466"></td> <td width="50%" valign="top">Chris builds our the left-hand gear train to match the design of the right.</td> </tr> <tr> <td width="50%" valign="top"><img src="images/scope.jpg" width="350" height="262"></td> <td width="50%" valign="top">I put a scope on the motor speed control outputs to see what a &quot;low speed&quot; wave form looked like.</td> </tr> <tr> <td width="50%" valign="top"><img src="images/IMG_0101.JPG" width="350" height="226"></td> <td width="50%" valign="top">Kevin and I at work at Microsoft.</td> </tr> <tr> <td width="50%" valign="top"></td> <td width="50%" valign="top"></td> </tr> <tr> <td width="50%" valign="top"><img src="images/IMG_0171.JPG" width="350" height="231"></td> <td width="50%" valign="top">Prototype servo control for an add-on gate.&nbsp; We decided that we needed to have a gate to capture balls rather than rely on being able to scoop them up in a smooth motion.</td> </tr> <tr> <td width="50%" valign="top"><img src="images/IMG_0167.JPG" width="350" height="186"></td> <td width="50%" valign="top">Close up of servo mounting.</td> </tr> <tr> <td width="50%" valign="top"><img src="images/flash%2045.jpg" width="175" height="131"><img src="images/flash%2090.jpg" width="175" height="131"></td> <td width="50%" valign="top">These picture demonstrate the relative contrast of the two board colors.&nbsp; The picture on the left is taken at a 45 degree angle to the board surface.&nbsp; The one on the right is taken looking straight down at the surface. <p>Note that reflection from the flash reduces the contrast between the blue and white sides of the boards noticeably; this is the reason we positioned our look-down sensor and illuminator at an angle to the table rather than have it look straight down at the table.</td> </tr> <tr> <td width="50%" valign="top"></td> <td width="50%" valign="top"></td> </tr> </table> <p align="left"> We programmed the robot in <i>Interactive C</i>.&nbsp; Click <a href="proto3.c">here</a> to download the final version we used in the competition.</p> <p align="left"> This is the <a href="http://groups.yahoo.com/group/MS6270">eGroups site</a> contains an archive our email amongst ourselves and with the 6.270 coordinators.</p> <p align="left"> Some more pictures from the <a href="lab.htm">lab</a>.</p> <p align="left"> &nbsp;</p> <p align="left">&nbsp;</p> <p align="left"> &nbsp;</p> <p align="left"> &nbsp;</p> <p align="left"> &nbsp;</p> <p align="left">&nbsp;</p> <p align="left"> &nbsp;</p> <p align="left"> &nbsp;</p> <p align="left">&nbsp;</p> <p align="left"> &nbsp;</p> <p align="left"> &nbsp;</p> <p align="left">&nbsp;</p> <p align="left"> &nbsp;</p> <p align="left"> &nbsp;</p> <p align="left"> &nbsp;</p> <p align="left">&nbsp;</p> <p align="center">&nbsp;</p> </body> </html><file_sep>// GeekWeek.js // // History: // April 6, 2003 [mck] - Add Lighting and Controllers // March 30, 2003 [mck] - Created // Copyright, 2003 by <NAME> (<EMAIL>) // WTStage - Wild Tangent stage object // Data types: // // Hungarian: // drv - Wild Tangent Crontrol Wrapper // obj - Wild Tanget Object wrapper - base class // cube - WT Cube model wrapper // cam - WT Camera wrapper // lgt - Light // mod - WT Model wrapper // grp - WT Group wrapper // cmd - Command line helper object // v3 - 3D point/vector // pt - 2D point // rc - 2D rectangle (2 points) // ctr - Controller // rgb - Array of 3 color elements // snd - Sound // WildTangent Driver Objects // wt - Driver ActiveX Control // wts - Stage // wto - Object/Model/Group // wtg - Group // wta - Actor // wtc - Camera // wtl - Light // wtac - WTAudioClip // wtci - WT Collision Info // Copy all base class methods that do not have a definition in the current // constructor prototype. Also add a prototype variable that references to // base class's constructor by name (this used to use a single name, clsParent // but that does not work for classes nested more than 2 deep). // // Note: subclassing function other than the constructor not currently supported // Need to add way of calling the base class functions directly; maybe with a naming // convention of "Base_Func". function Function.prototype.DeriveFrom(fnBase) { var prop; if (this == fnBase) { alert("Error - cannot derive from self"); return; } for (prop in fnBase.prototype) { if (typeof(fnBase.prototype[prop]) == "function" && !this.prototype[prop]) { this.prototype[prop] = fnBase.prototype[prop]; } } this.prototype[fnBase.StName()] = fnBase; } function Function.prototype.StName() { var st; st = this.toString(); st = st.substring(st.indexOf(" ")+1, st.indexOf("(")) return st; } // // Give subclass access to parent's method. function Function.prototype.Override(fnBase, stMethod) { this.prototype[fnBase.StName() + "_" + stMethod] = fnBase.prototype[stMethod]; } function Function.prototype.StParams() { var st; st = this.toString(); st = st.substring(st.indexOf("("), st.indexOf(")")+1); return st; } function NYI() { alert(NYI.caller.StName() + ": Not yet implemented"); } // // WTDriver - Wild Tanget top level object ("Web Driver") // WTDriver.idNext = 0; // Id for next constructed driver object WTDriver.rgdrv = new Array; // Array of all driver objects created WTDriver.drvCur; // The "active" driver function WTDriver(cmd, dx, dy) { if (!dx) dx = 800; if (!dy) dy = 480; this.rc = new Rect(0, 0, dx, dy); // Control size this.cmd = cmd; this.id = WTDriver.idNext++; WTDriver.rgdrv[this.id] = this; this.stVarName = "WTDriver.rgdrv["+this.id+"]"; this.bgobj = new Bag; // All objects added to stage this.bgcam = new Bag; // Cameras - are also in bgobj this.bgsnd = new Bag; // Sounds this.bgctr = new Bag; // Object controllers that need callback per frame render this.rgobjCache = new Object; // File-object cache (bitmaps, models) this.fCollideDebug = true; // On-screen collision debugging this.stDir = "Models/"; // Default directory for files WTDriver.drvCur = this; } function WTDriver.prototype.Select() { WTDriver.drvCur = this; } function WTDriver.prototype.StUI() { var st = ""; this.stControl = "wt" + this.id; st += "<OBJECT id="+this.stControl+" classid=CLSID:FA13A9FA-CA9B-11D2-9780-00104B242EA3"; st += " width="+this.rc.Dx() +" height="+this.rc.Dy(); st += " CODEBASE=http://www.wildtangent.com/install/wdriver/generic/wtwdinst.cab#version=3,0,0,0>"; st += "</OBJECT>"; st += "<script>"+this.stVarName+".wt = " + this.stControl + ";</script>"; st += this.StEvent("Render"); st += this.StEvent("Keyboard"); st += this.StEvent("Mouse"); st += "<SCRIPT>" + this.stVarName + ".Init();</SCRIPT>"; return st; } function WTDriver.prototype.Init() { var wt = this.wt; // turn on version functionality wt.designedForVersion("3.0"); this.Select(); // Create a stage and camera this.wts = wt.createStage(); // Stage // Top level group contains all user objects this.wtgTop = wt.createGroup(); this.wts.addObject(this.wtgTop); this.Reset(); wt.setNotifyMouseEvent(1); // 1 specifies no mouse picking wt.setNotifyRenderEvent(true); wt.setNotifyKeyboardEvent(true); wt.start(); } function WTDriver.prototype.Reset() { this.wCollide = 0; // Default no collisions with created objects this.wCollideNext = 1; this.objCollide = null; this.modCollide = undefined; this.Empty(); } // // Create standard test environment with (controllable) camera, light, and background. // function WTDriver.prototype.TestEnv() { var cam = new Camera(); cam.MoveTo(0,0,-300); new SlewController(cam, "Camera"); this.SetBackColor([240, 230, 140]); // Khaki var lgt = new Light; lgt.SetColor([100,100,100]); lgt = new Light(3); lgt.Turn(-45); } function WTDriver.prototype.SetBackColor(rgb) { this.wts.setBGColor(rgb[0], rgb[1], rgb[2]); } // TODO: Can I do this directly - so I don't need the name of the object? function WTDriver.prototype.StEvent(stEvent) { var st = ""; st += "<script FOR=" + this.stControl + " EVENT=WT" + stEvent + "Event(evt)>"; st += " " + this.stVarName + ".Do" + stEvent + "(evt);"; st += "</script>"; return st; } function WTDriver.prototype.Empty() { var ibag; ibag = new IBag(this.bgctr); while (ibag.FNext()) ibag.Obj().Remove(); ibag = new IBag(this.bgobj); while (ibag.FNext()) ibag.Obj().Remove(); ibag = new IBag(this.bgsnd); while (ibag.FNext()) ibag.Obj().Remove(); } function SetCollisionCallback(obj) { WTDriver.drvCur.objCollide = obj; if (!obj) { WTDriver.drvCur.wCollide = 0; return; } WTDriver.drvCur.wCollide = WTDriver.drvCur.wCollideNext; WTDriver.drvCur.wCollideNext <<= 1; } function WTDriver.prototype.AddObject(obj) { if (obj.wto != undefined) { this.wtgTop.addObject(obj.wto); obj.wto.setCollisionMask(this.wCollide); if (obj.wto.getUserData() == null && obj.drv.objCollide) obj.wto.setUserData(obj.drv.objCollide); } this.bgobj.Add(obj); } function WTDriver.prototype.RemoveObject(obj) { if (obj.wto != undefined) this.wtgTop.removeObject(obj.wto); this.bgobj.Remove(obj); } function WTDriver.prototype.AddCamera(cam) { this.bgcam.Add(cam); this.ArrangeCameras(); } function WTDriver.prototype.RemoveCamera(cam) { this.bgcam.Remove(cam); this.ArrangeCameras(); } function WTDriver.prototype.ArrangeCameras() { var ccam = this.bgcam.c; if (ccam == 0) return; var ccol = Math.ceil(Math.sqrt(ccam)); var crw = Math.ceil(ccam/ccol); var irw; var icol; var dx; var dxMax = this.rc.Dx(); var rc = new Rect(0,0,0,0); var dy = this.rc.Dy()/crw; rc.pt1.y = 0; rc.pt2.y = dy; ibag = new IBag(this.bgcam); var crwT = crw; for (irw = 0; irw < crw; irw++) { ccol = Math.ceil(ccam/crwT); dx = dxMax / ccol; rc.pt1.x = 0; rc.pt2.x = dx; for (icol = 0; icol < ccol; icol++) { ibag.FNext(); ibag.Obj().SetViewRect(rc); rc.pt1.x += dx; rc.pt2.x += dx; } ccam -= ccol; crwT--; rc.pt1.y += dy; rc.pt2.y += dy; } } function WTDriver.prototype.AddSound(snd) { this.bgsnd.Add(snd); } function WTDriver.prototype.RemoveSound(snd) { this.bgsnd.Remove(snd); } function WTDriver.prototype.AddController(ctr) { if (this.divControllers && ctr.FHasUI()) { var st = ""; st += "<DIV id=divCtr" + ctr.id + "><B>"+ctr.stName+":</B><BR>"; st += ctr.StUI(this.cmd) + "<BR></DIV>"; this.divControllers.insertAdjacentHTML("beforeEnd", st); ctr.BindDOM(); ctr.divParent = eval("divCtr" + ctr.id); } this.bgctr.Add(ctr); } function WTDriver.prototype.RemoveController(ctr) { if (ctr.divParent != undefined) ctr.divParent.removeNode(true); this.bgctr.Remove(ctr); } function WTDriver.prototype.BMFromCache(stFile, rgbKey) { var bm = this.rgobjCache[stFile]; if (!bm) { bm = this.wt.createBitmap(this.stDir + stFile); if (rgbKey) bm.setColorKey(rgbKey[0], rgbKey[1], rgbKey[2]); this.rgobjCache[stFile] = bm; } return bm; } function WTDriver.prototype.DoRender(wevt) { var ibag; var obj; var msInterval = wevt.getInterval(); var msTime = wevt.getTime(); // Performance problem? Object allocation in render loop. ibag = new IBag(this.bgctr); while (ibag.FNext()) { obj = ibag.Obj(); if (obj.DoRender && !obj.fSuspend) obj.DoRender(msInterval, msTime); } } function WTDriver.prototype.DoKeyboard(wevt) { ibag = new IBag(this.bgctr); while (ibag.FNext()) { obj = ibag.Obj(); if (obj.DoKey && !obj.fSuspend) obj.DoKey(wevt.getKey(), wevt.getKeyState()); } } function WTDriver.prototype.DoMouse(wevt) { } // // Obj - Base object for Wild Tangent graphical objects // function Obj(stType) { this.drv = WTDriver.drvCur; } function Obj.prototype.Remove() { this.drv.RemoveObject(this); } // Replace and object that was removed from the stage function Obj.prototype.Add() { this.drv.AddObject(this); } // Not sure how collisions will be affected by invisible objects... function Obj.prototype.SetVisible(fVis) { this.wto.setVisible(fVis); } function Obj.prototype.Spin(deg) { if (deg == undefined) this.wto.setConstantRotation(Math.random()*2-1,Math.random()*2-1,Math.random()*2-1,Math.random()*180+20); else this.wto.setConstantRotation(0,1,0, deg); } function Obj.prototype.SetColor(rgb, part) { if (this.wtoI == undefined) return; if (part == undefined) this.wtoI.setColor(rgb[0], rgb[1], rgb[2]); } function Obj.prototype.SetTexture(stFile, rgb, uRep, vRep) { if (this.wtoI == undefined) return; var bm = this.drv.BMFromCache(stFile, rgb) if (uRep != undefined) { this.wtoI.setTextureRect("", 0, 0, uRep, vRep); } this.wtoI.setTexture(bm); } function Obj.prototype.SetOpacity(w) { if (this.wtoI == undefined) return; this.wtoI.setOpacity(w); } function Obj.prototype.MoveTo(x, y, z) { this.wto.setPosition(x, y, z); } function Obj.prototype.Move(dx, dy, dz) { var pos = this.wto.getPosition(); this.wto.setPosition(pos.getX() + dx, pos.getY()+dy, pos.getZ()+dz); } function Obj.prototype.GetPos(fWorld) { if (fWorld) return new V3(this.wto.getAbsolutePosition()); return new V3(this.wto.getPosition()); } function Obj.prototype.SetPos(v3) { this.MoveTo(v3.x, v3.y, v3.z); } function Obj.prototype.Forward(dz) { this.wto.moveBy(0,0,dz); } // Clockwise (from above) turn in X-Z plane function Obj.prototype.Turn(deg) { this.wto.setRotation(0,1,0, deg); } function Obj.prototype.Tip(deg) { this.wto.setRotation(1,0,0, deg); } function Obj.prototype.SetOrientation(x,y,z, xUp, yUp, zUp) { this.wto.setOrientationVector(x,y,z, xUp,yUp,zUp); } // Direction in X-Z plane; Z axis is 0, X axis is 90. function Obj.prototype.SetDir(deg) { this.SetOrientation(Math.sin(deg*Math.PI/180), 0, Math.cos(deg*Math.PI/180), 0, 1, 0); } function Obj.prototype.GetOrient(fWorld) { if (fWorld) return new V3(this.wto.getAbsoluteOrientationVector()); return new V3(this.wto.getOrientationVector()); } function Obj.prototype.GetDir(fWorld) { var v3 = this.GetOrient(fWorld); var deg; deg = Math.acos(v3.z) * 180/Math.PI; if (v3.x < 0) deg = 360 - deg; return deg; } function Obj.prototype.Scale(rx, ry, rz) { if (ry == undefined) { ry = rz = rx; } this.wto.setScale(rx, ry, rz); } function Obj.prototype.AbsoluteScale(rx, ry, rz) { if (ry == undefined) { ry = rz = rx; } this.wto.setAbsoluteScale(rx, ry, rz); } function Obj.prototype.LookAt(obj) { if (obj) this.wto.setLookAt(obj.wto); else this.wto.unsetLookAt(); } // Check for collisions with any objects within the extents of the current object // and for a given distance Forward (or Backward). function Obj.prototype.TestCollision(dz, mask) { var w3d; var dzSelf; if (mask == undefined) mask = ~this.wto.getCollisionMask(); dzSelf = dz < 0 ? -100 : 100; dz += dzSelf; var wtci = this.wto.checkCollision(0,20,dz, true, mask, 1); if (!wtci) return null; ci = new Object; ci.wtci = wtci; ci.dzTotal = wtci.getImpactDistance(); ci.dzSafe = ci.dzTotal - dzSelf; ci.wtoHit = wtci.getHitObject(); ci.posNew = new V3(wtci.getNewPosition()); if (ci.wtoHit.getUserData()) ci.objCallback = ci.wtoHit.getUserData(); if (obj.drv.fCollideDebug) { // Create marker on first use if (this.drv.modCollide == undefined) { this.drv.modCollide = new Sphere(20); this.drv.modCollide.SetColor([255,0,0]); } this.drv.modCollide.SetPos(ci.posNew); } return ci; } // Only called by derived classes function Obj.prototype.CreateObjInternal(wtoI) { this.Obj(); this.wtoI = wtoI; this.wto = this.drv.wt.createGroup(); this.wto.attach(this.wtoI); this.drv.AddObject(this); } // // Graphic objects derived from Obj: // Box // Cube // Sphere // Plane // Model // Text3D // Camera // Group // Light Box.DeriveFrom(Obj); function Box(dx, dy, dz) { this.CreateObjInternal(WTDriver.drvCur.wt.createBox(dx, dy, dz)); } Sphere.DeriveFrom(Obj); function Sphere(dx, sides) { if (dx == undefined) dx = 100; if (sides == undefined) sides = 18; this.CreateObjInternal(WTDriver.drvCur.wt.createSphere(dx, sides)); } Cube.DeriveFrom(Box); function Cube(dx) { if (dx == undefined) dx = 100; this.Box(dx, dx, dx); } Plane.DeriveFrom(Obj) function Plane(dx, dy, stTexture, rgb, uRep, vRep) { if (dx == undefined) dx = 100; if (dy == undefined) dy = 100; this.CreateObjInternal(WTDriver.drvCur.wt.createPlane(dx, dy, true)); if (stTexture != undefined) this.SetTexture(stTexture, rgb, uRep, vRep); } Model.DeriveFrom(Obj); function Model(stFile) { this.CreateObjInternal(WTDriver.drvCur.wt.createModel(WTDriver.drvCur.stDir + stFile + ".wt")); } Text3D.DeriveFrom(Obj); function Text3D(stText, wScale) { var wto; this.Obj(); if (stText == undefined) stText = "<NAME>"; if (wScale == undefined) wScale = 0.3; wto = this.drv.wt.createString3D(); wto.setCollisionMask(this.drv.wCollide); wto.setTextFace("Comic Sans MS, Verdana", 0); wto.setText(stText); wto.setScale(wScale, wScale, wScale/5); this.wtoI = wto; this.wto = this.drv.wt.createGroup(); this.wto.addObject(wto); CenterExtent(this.wtoI); this.drv.AddObject(this); } function Text3D.prototype.SetColor(rgb) { this.wtoI.setColor(rgb[0], rgb[1], rgb[2], 255); } function Text3D.prototype.SetTexture(stFile, rgb) { var bm = this.drv.BMFromCache(stFile, rgb) this.wtoI.setTexture(bm, 3); } Group.DeriveFrom(Obj); function Group() { this.Obj(); this.rgobj = new Array; this.wto = this.drv.wt.createGroup(); for (i = 0; i < Group.arguments.length; i++) { this.AddObject(Group.arguments[i]); } this.drv.AddObject(this); } function Group.prototype.SetTexture(stFile, rgb, xRep, yRep) { var i; for (i in this.rgobj) rgobj[i].SetTexture(stFile, rgb, xRep, yRep); } function Group.prototype.AddObject(obj) { this.rgobj.push(obj); this.wto.addObject(obj.wto); } Camera.DeriveFrom(Obj); function Camera() { this.Obj(); this.wto = this.drv.wts.createCamera(); this.wto.setClipping(10000); // Increase from 5,000 to 10,000 default this.rc = this.drv.rc.Clone(); this.drv.AddObject(this); this.drv.AddCamera(this); } function Camera.prototype.SetViewRect(rc) { this.rc = rc; this.wto.setViewRect(rc.pt1.x, rc.pt1.y, rc.Dx(), rc.Dy()); } function Camera.prototype.Remove() { this.wto.suspend(); this.drv.RemoveCamera(this); this.drv.RemoveObject(this); } Light.DeriveFrom(Obj); function Light(wType) { if (wType == undefined) wType = 0; // Ambient default this.Obj(); this.wtoI = this.drv.wt.createLight(wType); this.wto = this.wtoI; this.drv.AddObject(this); } function Sound(stFile, fLoop, wVolume) { this.drv = WTDriver.drvCur; this.wtac = this.drv.wt.createAudioClip(this.drv.stDir + stFile + ".wwv"); this.wLoop = 0; if (fLoop) this.wLoop = 1; this.drv.AddSound(this); } function Sound.prototype.Play() { this.wtac.start(this.wLoop); } function Sound.prototype.Stop() { this.wtac.stop(); } // Volume between 0..127 function Sound.prototype.Volume(wVolume) { this.wtac.setVolume(wVolume); } function Sound.prototype.Remove() { this.Stop(); this.drv.RemoveSound(this); } // // Controllers - Handle runtime dynamics and key events // function Controller(obj) { this.SetObj(obj); this.Suspend(false); this.drv.AddController(this); } function Controller.prototype.SetObj(obj) { this.obj = obj; this.drv = WTDriver.drvCur; } function Controller.prototype.Remove() { this.drv.RemoveController(this); } function Controller.prototype.Suspend(fSuspend) { this.fSuspend = fSuspend; } function Controller.prototype.SetLifetime(msLifetime) { this.msLifetime = msLifetime; } function Controller.prototype.DoRender(msInterval, msTime) { this.msTime = msTime; if (this.msLifetime) { if (!this.msLimit) { this.msStart = msTime; this.msLimit = msTime + this.msLifetime; } if (msTime >= this.msLimit) { this.Suspend(true); this.fFinal = true; } } } function Controller.prototype.Proportion(w1, w2) { return WProportion(this.msTime, this.msStart, this.msLimit, w1, w2); } function WProportion(w, w1, w2, w3, w4) { return (w-w1)/(w2-w1)*(w4-w3)+w3; } function Controller.prototype.FHasUI() { return false; } SlewController.DeriveFrom(Controller); // Standard movement and turn rates SlewController.dsUI = 100; SlewController.ddegUI = 45; // 45 degrees per second SlewController.idNext = 0; SlewController.rgctr = new Array; function SlewController(obj, stName) { this.stName = stName; this.id = SlewController.idNext++; SlewController.rgctr[this.id] = this; this.stVarName = "SlewController.rgctr["+this.id+"]"; this.Controller(obj); this.fQuiet = false; this.dv = new V3(0,0,0); this.ddeg = 0; this.dist = 0; } SlewController.Override(Controller, "DoRender"); function SlewController.prototype.DoRender(msInterval, msTime) { this.Controller_DoRender(msInterval, msTime); var s = msInterval / 1000; this.obj.Move(this.dv.x * s, this.dv.y *s, this.dv.z * s); this.obj.Turn(this.ddeg * s); this.obj.Forward(this.dist * s); if (this.txtLoc) { this.txtLoc.innerHTML = "Pos: " + this.obj.GetPos() + "<BR>Orient: " +this.obj.GetOrient(); } } function SlewController.prototype.FHasUI() { return true; } function SlewController.prototype.StUI(cmd) { var st = ""; var dS = SlewController.dsUI; this.stLocName = "spanSC" + this.id; st += this.StVarPair(cmd, "X", "dv.x", dS); st += this.StVarPair(cmd, "Y", "dv.y", dS); st += this.StVarPair(cmd, "Z", "dv.z", dS); st += "<BR>"; st += this.StVarPair(cmd, "Dir", "ddeg", SlewController.ddegUI); st += this.StVarPair(cmd, "Fwd", "dist", dS); st += "<BR><SPAN id=" + this.stLocName + "></SPAN>"; return st; } function SlewController.prototype.StVarSet(stVar, w) { return this.stVarName + "." + stVar + " = " + w + ";"; } function SlewController.prototype.StVarPair(cmd, stLabel, stVar, dS) { var st =""; st += cmd.StButton("+" + stLabel, this.StVarSet(stVar, dS), this.StVarSet(stVar, 0), this.fQuiet); st += cmd.StButton("-" + stLabel, this.StVarSet(stVar, -dS), this.StVarSet(stVar, 0), this.fQuiet); st += "&nbsp;"; return st; } function SlewController.prototype.BindDOM() { this.txtLoc = eval(this.stLocName); } function SlewController.prototype.WriteUI(cmd) { document.write(this.StUI(cmd)); this.BindDOM(); } // // CBController - Callback Controller. Calls object methods for keys and rendering: // obj.DoKey(ch, fDown) - keys are mapped from stKeys to corresponding letter in stMap // obj.DoRender(msInterval, msTime) - returns string to display in controller well // CBController.DeriveFrom(Controller); CBController.idNext = 0; CBController.rgctr = new Array; function CBController(obj, stName, stKeys, stMap) { this.stName = stName; this.id = CBController.idNext++; CBController.rgctr[this.id] = this; this.stVarName = "CBController.rgctr["+this.id+"]"; this.stKeys = stKeys; this.stMap = stMap; this.Controller(obj); } CBController.Override(Controller, "DoRender"); function CBController.prototype.DoRender(msInterval, msTime) { this.Controller_DoRender(msInterval, msTime); if (!this.obj.DoRender) return; var st = this.obj.DoRender(msInterval, msTime); // if (this.txtLoc && st != undefined) // this.txtLoc.innerHTML = st; } function CBController.prototype.DoKey(key, fDown) { if (this.obj.DoKey == undefined) return; var ch = String.fromCharCode(key); var ich = this.stKeys.indexOf(ch); if (ich >= 0) { this.obj.DoKey(this.stMap.charAt(ich), fDown); } } function CBController.prototype.FHasUI() { return this.stName != undefined; } function CBController.prototype.StUI(cmd) { var st = ""; this.stLocName = "spanCB" + this.id; st += "Keys: " + this.stKeys; // st += "<BR><SPAN id=" + this.stLocName + "></SPAN>"; return st; } function CBController.prototype.BindDOM() { // if (this.stLocName != undefined) // this.txtLoc = eval(this.stLocName); } function CBController.prototype.WriteUI(cmd) { document.write(this.StUI(cmd)); this.BindDOM(); } function Math.Round(n, cdec) { var nMult = Math.pow(10, cdec); n = Math.round(n*nMult); return n / nMult; } function Math.Rad(deg) { return deg * Math.PI / 180; } function V3() { // One - argument assume WT3Vector3D if (V3.arguments.length == 1) { var wt3 = V3.arguments[0]; this.x = wt3.getX(); this.y = wt3.getY(); this.z = wt3.getZ(); return; } this.x = V3.arguments[0]; this.y = V3.arguments[1]; this.z = V3.arguments[2]; } function V3.prototype.toString() { return "[" + Math.Round(this.x, 2) + ", " + Math.Round(this.y, 2) + ", " + Math.Round(this.z, 2) + "]"; } function V3.prototype.Add(v) { this.x += v.x; this.y += v.y; this.z += v.z; } function V3.prototype.Sub(v) { this.x -= v.x; this.y -= v.y; this.z -= v.z; } function V3.prototype.Scale(w) { this.x *= w; this.y *= w; this.z *= w; } function Point(x, y) { this.x = x; this.y = y; } function Point.prototype.Clone() { var pt = new Point(this.x, this.y); return pt; } function Rect(x1, y1, x2, y2) { if (Rect.arguments.length == 2) { this.pt1 = x1.Clone(); this.pt2 = y1.Clone(); return; } this.pt1 = new Point(x1, y1); this.pt2 = new Point(x2, y2); } function Rect.prototype.Clone() { var rc = new Rect(this.pt1, this.pt2); return rc; } function Rect.prototype.Dx() { return this.pt2.x - this.pt1.x; } function Rect.prototype.Dy() { return this.pt2.y - this.pt1.y; } function CenterExtent(wto) { var vMin = new V3(wto.getGeometryExtents(false, true)); var vMax = new V3(wto.getGeometryExtents(true, true)); vMin.Add(vMax); vMin.Scale(-1/2); wto.setPosition(vMin.x, vMin.y, vMin.z); } // Encode string so it will display in an HTML document function StHTML(st) { st = st.toString(); st = st.replace(/&/g, '&amp;'); st = st.replace(/</g, '&lt;'); st = st.replace(/>/g, '&gt;'); st = st.replace(/\n/g, '<br>'); st = st.replace(/ /g, '&nbsp;'); st = st.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;'); return st; } function StAttrQuote(st) { return '"' + StAttrQuoteInner(st) + '"'; } function StAttrQuoteInner(st) { st = st.toString(); st = st.replace(/&/g, '&amp;'); st = st.replace(/\"/g, '&quot;'); st = st.replace(/'/g, '&#39;'); st = st.replace(/\r/g, '&#13;'); return st; } // // Command - Command line UI and history // Command.idNext = 0; Command.rgcmd = new Array; g = new Object; // Place to hang eval-ed definitions! function Command(dx) { if (!dx) dx = 640; this.dx = dx; this.id = Command.idNext++; Command.rgcmd[this.id] = this; this.stVarName = "Command.rgcmd["+this.id+"]"; } function Command.prototype.StCmdLineUI() { var st = ""; this.stLineName = "txtCmd" + this.id; st += "<INPUT TYPE=Text id="+this.stLineName +" style=width:640 "; st += "onkeypress='" + this.stVarName + ".CmdChar();'" st += ">"; st += "<INPUT TYPE=Button VALUE=Execute "; st += "onClick='" + this.stVarName + ".ExecCmdLine();'>"; return st; } function Command.prototype.StHistoryUI(dy) { var st = ""; if (!dy) dy = 100; this.dyHist = dy; this.stHistName = "txtCmdHist" + this.id; st += "<TEXTAREA id=" + this.stHistName + " style='width:" + this.dx + ";height:" + this.dyHist; st += "'></TEXTAREA>"; return st; } function Command.prototype.StCodeUI(dy) { var st = ""; if (!dy) dy = 600; this.dyCode = dy; this.stCodeName = "txtCmdCode" + this.id; st += "<TABLE><TR><TD>"; st += "<TEXTAREA id=" + this.stCodeName + " style='width:" + this.dx + ";height:" + this.dyCode + "' "; st += "onkeydown='" + this.stVarName + ".CodeChar();' " st += "></TEXTAREA>"; st += "</TD><TD>"; st += "<INPUT TYPE=Button VALUE='Run Code' "; st += "onClick='" + this.stVarName + ".EvalCode();'>"; st += "</TD></TR></TABLE>"; return st; } function Command.prototype.WriteUI() { document.write("<SPAN class=lblCmd>Command Line:<SPAN><BR>"); document.write(this.StCmdLineUI()); document.write("<BR><SPAN class=lblCmd>Command History:<SPAN><BR>"); document.write(this.StHistoryUI()); document.write("<BR><SPAN class=lblCmd>Code:<SPAN><BR>"); document.write(this.StCodeUI()); this.BindDOM(); } // Extract variables pointing to the DOM UI elements for the command line and history. function Command.prototype.BindDOM() { this.txtCmd = eval(this.stLineName); this.txtHistory = eval(this.stHistName); this.txtCode = eval(this.stCodeName); } function Command.prototype.DoCommand(stCmd, fQuiet) { eval(stCmd); if (fQuiet == undefined) fQuiet = false; if (this.txtHistory != undefined && !fQuiet) { var stHist = this.txtHistory.innerText; var ich = stHist.indexOf(stCmd); if (ich < 0) { this.txtHistory.insertAdjacentText("beforeEnd", stCmd + "\n"); } } } function Command.prototype.CmdChar() { if (event.keyCode == 13) { this.ExecCmdLine(); event.returnValue = false; } } function Command.prototype.CodeChar() { switch (event.keyCode) { case 9: var sel = document.selection.createRange(); sel.text = " "; event.returnValue = false; break; } } function Command.prototype.ExecCmdLine() { this.DoCommand(this.txtCmd.value); this.txtCmd.select(); } function Command.prototype.EvalCode() { eval(this.txtCode.value); } function Command.prototype.StDoCmdAttr(stCmd, fQuiet) { if (fQuiet == undefined) fQuiet = false; return StAttrQuote(this.stVarName + ".DoCommand(\"" + stCmd + "\", " + fQuiet + ");"); } function Command.prototype.StButton(stLabel, stCmd, stCmdUp, fQuiet) { st = ""; st += "<INPUT TYPE=Button style=margin:2 Value=" + StAttrQuote(stLabel); if (stCmdUp == undefined || stCmdUp == "") { st += " onClick=" + this.StDoCmdAttr(stCmd, fQuiet); } else { // BUG: Command needs to capture the mouse in order to ensure getting the onmouseup event - user // can drag out and then relealse. onmouseenter and onmouseleave are not substitute st += " onmousedown=" + this.StDoCmdAttr(stCmd, fQuiet); st += " onmouseup=" + this.StDoCmdAttr(stCmdUp, fQuiet); } st += ">"; return st; } function DW(st) { document.write(st); } // // Debug object function Debug() { } function Debug.prototype.StUI() { var st = ""; st += "<DIV><B>dbg.Trace: </B><SPAN id=txtTrace></SPAN></DIV>"; st += "<BR><B>Object Dump:</B><DIV id=divDumpObj></DIV>"; return st; } function Debug.prototype.Trace(st) { var stCaller = ""; if (Debug.prototype.Trace.caller) stCaller = Debug.prototype.Trace.caller.StName(); if (stCaller != "") stCaller = "[" + stCaller + "] "; txtTrace.innerText = stCaller + st; } function Debug.prototype.DumpObj(obj) { var st = ""; if (obj) st = StDumpObj("Dump " + obj.constructor.StName() + " Object", obj); divDumpObj.innerHTML = st; } // // BAG - Object collections // Bag.idNext = 0; function Bag() { this.rg = new Array; this.stName = "Bag" + Bag.idNext++; this.idNext = 0; this.c = 0; } function Bag.prototype.Add(obj) { // Already a member of this bag if (obj[this.stName] != undefined) return; this.rg[this.idNext] = obj; obj[this.stName] = this.idNext; this.idNext++; this.c++; } function Bag.prototype.Remove(obj) { var id = obj[this.stName]; // Not in this bag if (id == undefined) return; this.rg[id] = undefined; this.c--; } function Bag.prototype.FMember(obj) { return obj[this.stName] != undefined; } // // IBag - Iterator for Bag's // function IBag(bag) { this.bag = bag; this.Init(); } function IBag.prototype.Init() { this.i = -1; } function IBag.prototype.FNext() { while (++this.i < this.bag.rg.length) { if (this.bag.rg[this.i] != undefined) return true; } return false; } function IBag.prototype.Obj() { if (this.i == -1) this.FNext(); return this.bag.rg[this.i]; } // // Object dump routines // StDumpObj.iDepth = 0; StDumpObj.iDepthMax = 1; StDumpObj.fProto = false; function StDumpObj(stName, obj) { var st = ""; var cProps = 0; var prop; if (StDumpObj.iDepth > StDumpObj.iDepthMax) { st += "..."; return st; } if (obj.constructor == undefined) return "ActiveX Control"; StDumpObj.iDepth++; st += "<TABLE class=doTable BORDER=1 CELLPADDING=4>\n"; if (stName != "") { st += "<TR><TD class=doTitle colspan=2>" st += stName; st += "</TD></TR>\n"; } // All own properties for (prop in obj) { if (obj.hasOwnProperty(prop)) { st += StDumpVar(prop, obj[prop]); cProps++; } } var stoProto = new StOnce("<TR><TD class=doProto colspan=2>prototype properties</TD></TR>\n"); // Don't recurse on a prototype objects constructor // since it can point back to ourselves again (no loops!) if (obj.constructor.prototype != obj) { st += stoProto.St(); st += StDumpVar("constructor", obj.constructor); cProps++; } if (StDumpObj.fProto) { // All properties contained in prototypes for (prop in obj) { if (!obj.hasOwnProperty(prop)) { st += stoProto.St(); st += StDumpVar(prop, obj[prop]); cProps++; } } } st += "</TABLE>" StDumpObj.iDepth--; if (cProps == 0) return ""; return st; } // StOnce.St() will return contained string ONE TIME when called - and empty string on all successive calls. function StOnce(st) { this.st = st; this.fOnce = false; } function StOnce.prototype.St() { if (!this.fOnce) { this.fOnce = true; return this.st } return ""; } function StDumpVar(stVar, value) { var st = ""; st += "<TR><TD class=doName>"; st += stVar; st += "</TD><TD class=doValue>"; if (value == undefined) { st += "&lt;UNDEFINED&gt;"; } else if (typeof(value) == "object") { st += StDumpObj("", value); } else if (typeof(value) == "function") { stT = value.toString(); st += StHTML(stT.substring(0, stT.indexOf("("))); st += StDumpObj("prototype", value.prototype); } else st += StHTML(value); st += "</TD></TR>\n"; return st; } function StHTML(st) { st = st.toString(); st = st.replace(/&/g, '&amp;'); st = st.replace(/</g, '&lt;'); st = st.replace(/>/g, '&gt;'); st = st.replace(/\n/g, '<br>'); st = st.replace(/ /g, '&nbsp;'); st = st.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;'); return st; } <file_sep>int fBallRelease = 0; /* Move recording buffer */ int xRec[100]; int yRec[100]; int iRecNext = 0; /* Move index buffer */ int rgirecMin[10]; int rgirecMax[10]; void main() { Setup(); MainMenu(); } int func; int funcLast; void MainMenu() { func = -1; while (!stop_button()) { funcLast = func; func = ScaleKnob(1, 27); if (FDispMenu(1, "Calibrate Lookdown")) CalibrateLookdown(); if (FDispMenu(2, "Compete!")) Compete(); if (FDispMenu(3, "Placebo")) Placebo(); if (FDispMenu(4, "Dance!")) Chop(10); if (FDispMenu(5, "Calibrate Soft")) CalibrateSoft(); if (FDispMenu(6, "Calibrate Hard")) CalibrateHard(); if (FDispMenu(7, "Speed Calibration")) CalibrateSpeed(); if (FDispMenu(8, "Lookdown Test")) LookdownTest(); if (FDispMenu(9, "Orientation")) Orient(); if (FDispMenu(10, "Straight 1000")) Move(1000,1000); if (FDispMenu(11, "Left 90 Soft")) Soft(90, 1); if (FDispMenu(12, "Left 90 Hard")) Hard(90); if (FDispMenu(13, "Find Line")) FindLine(); if (FDispMenu(14, "Line Follow")) LineFollower(); if (FDispMenu(15, "Record")) RecordMove(WSetting("Record move", 0, 9)); if (FDispMenu(16, "Playback")) PlayMove(WSetting("Play move", 0, 9)); /* hbtest.c functions */ if (FDispMenu(17, "Servo Test")) ServoTest(); if (FDispMenu(18, "Calibrate Gate")) CalibrateGate(); if (FDispMenu(19, "Soft Turn Test")) SoftTest(); if (FDispMenu(20, "Hard Turn Test")) HardTest(); if (FDispMenu(21, "Spin Test!")) Spinner(); if (FDispMenu(22, "Shake Test!")) Shaker(); if (FDispMenu(23, "Bump Test")) BumpTest(); if (FDispMenu(24, "Test Motors")) testmotors(); if (FDispMenu(25, "Test Digitals")) testdigitals(); if (FDispMenu(26, "Test Analogs")) testanalogs(); if (FDispMenu(27, "Assert Enable")) AssertEnable(); } } #define START_LIGHT_PORT 4 void Compete() { int i; ir_transmit_off(); fAssertEnable = YesNo("Debug"); kill_process(ipMotor); if (YesNo("Start Light")) start_machine(START_LIGHT_PORT); ipMotor = start_process(MotorDriver()); CompeteInit(0); Orient(); while (1) { FindLine(); CollectBalls(); /* BUG: We don't really know if we have a ball here */ DumpBall(); ReturnForMore(); } printf("C1"); } void ReturnForMore() { while (1) { Lookdown(); if (iSight == 2-iMe) { break; } Move(700, 700); if (fBlocked) Unbind(); Hard(45); if (fBlocked) Unbind(); } } void CollectBalls() { Hard(90); Move(-80,-80); Move(30, 30); Gate(0); fBallRelease = 1; Move(500, 500); pwrMax = 60; Move(-10, -10); Gate(1); fBallRelease = 0; msleep(250L); Move(-20, -20); pwrMax = 100; Move(-600,-600); msleep(250L); Move(80, 80); Hard(110); Move(-200,-200); Move(700, 700); } void DumpBall() { DebugStop("Dump Ball"); while (1) { Lookdown(); if (iSight == iMe) { DebugStop("Dumping"); fBallRelease = 1; Gate(0); Hard(-70); msleep(1000L); if (fBlocked) Unbind(); Move(-200,-200); Move(50, 50); Hard(-90); fBallRelease = 0; fBall = 0; break; } Move(300, 300); if (fBlocked) { if (rgfBlock[3]) Hard(-10); else Hard(10); } } } int rgiside[] = {0,0,0,2,0,2,2,2}; int rgdir[] = {2, 3, 1, 0, 0, 1, 3, 2}; int iMe; int dirOrient; void Orient() { int i; Lookdown(); i = rgiTable[0] * 4 + rgiTable[1] * 2 + rgiTable[2]; Assert((i & 1) == 0, "O4"); i >>= 1; iMe = rgiside[i]; dirOrient = rgdir[i]; printf("I: %d Side: %d Dir: %d\n", i, iMe, dirOrient); if (fAssertEnable) StartPress(); if (dirOrient == 0) { Move(-150, -150); Hard(-180); } if (dirOrient == 1) { Hard(80); Move(200,200); } if (dirOrient == 3) { Soft(-20, 0); Soft(-70, 1); Move(200,200); } if (fAssertEnable) StartPress(); } void Unbind() { fForce = 1; if (rgfBlock[0] || rgfBlock[1]) Move(15, 15); else Move(-15, -15); fForce = 0; } persistent int fAssertEnable = 0; void Assert(int f, char st[]) { if (!fAssertEnable || f) return; beep();beep();beep(); printf("Assert failed: %s\n", st); StartPress(); } void AssertEnable() { fAssertEnable = WSetting("Assert", 0, 1); } int FDispMenu(int funcSel, char stMenu[]) { if (func != funcSel) return 0; if (start_button() && func == funcLast) { while (start_button()); func = -1; return 1; } if (func != funcLast) printf("%s\n", stMenu); return 0; } void NYI() { beep(); printf("NYI\n"); sleep(2.0); } void CalibrateSoft() { CalibrateTurn(0, rgcSoft); } void CalibrateHard() { CalibrateTurn(1, rgcHard); } void CalibrateTurn(int fHard, int rgc[]) { int i; int fContinue = 1; while (fContinue) { i = WSetting("Left 90's", 1, 4); rgc[i] = CalibrateSetting(rgc[i], "Ticks"); if (fHard) Move(-rgc[i], rgc[i]); else { Move(0, rgc[i]); Move(200, 200); StartPress(); Move(rgc[i], 0); } Move(200, 200); fContinue = YesNo("Continue"); } } int CalibrateSetting(int w, char st[]) { printf("%s: %d\n", st, w); StartPress(); w = WSetting(st, MultDiv(w, 80, 100), MultDiv(w, 120, 100)); return w; } int YesNo(char st[]) { printf("%s? (Start=Y, Stop=N):\n", st); while (1) { if (start_button()) {while (start_button()); return 1;} if (stop_button()) {while (stop_button()); return 0;} } } int WSetting(char st[], int wMin, int wMax) { int wSet; int wSetLast = -1; while (!start_button()) { wSet = ScaleKnob(wMin, wMax); if (wSet != wSetLast) { wSetLast = wSet; printf("%s: %d\n", st, wSet); } } while (start_button()); return wSet; } int ScaleKnob(int wMin, int wMax) { return MultDiv(knob(), wMax-wMin, 255) + wMin; } int MultDiv(int w1, int w2, int w3) { return (int) ((float) w1 * (float) w2/ (float) w3); } int WProportion(int wIn, int wInMin, int wInMax, int wOutMin, int wOutMax) { int w; if (wIn <= wInMin) return wOutMin; if (wIn >= wInMax) return wOutMax; w = MultDiv(wIn - wInMin, wOutMax-wOutMin, wInMax-wInMin) + wOutMin; return w; } void DebugStop(char st[]) { if (!fAssertEnable) return; PromptFor(st); } void PromptFor(char st[]) { printf("Press Start: %s\n", st); StartPress(); } void StartPress() { beep();beep();beep(); while (!start_button()); while (start_button()); } int ipMotor; void Setup() { alloff(); enable_encoder(0); enable_encoder(1); CompeteInit(1); } void CompeteInit(int fPre) { enable_servos(); Gate(0); if (fPre) { sleep(0.25); disable_servos(); } fBall = 0; ipMotor = start_process(MotorDriver()); } int fStalled; int fStalling; int fForce = 0; int fBall = 0; long msStall; int cL; int cR; int cLLast; int cRLast; void InitEncoders() { reset_encoder(0); reset_encoder(1); fStalled = 0; fBlocked = 0; cL = -10; cR = -10; } int sgn(int w) { if (w < 0) return -1; if (w > 0) return 1; return 0; } /* Bumper order RR, LR, RF, LF */ int fBlocked; int rgfBump[4]; int rgibumpMotor[4] = {1, 0, 1, 0}; int rgibumpSgn[4] = {-1, -1, 1, 1}; int rgfBlock[4]; /* 5 ticks per second - at full power - is a stalled condition */ int cStalled = 5; void ReadEncoders() { int i; cLLast = cL; cRLast = cR; cL = read_encoder(0); cR = read_encoder(1); /* Stalled motors */ if (cL == cLLast && cR == cRLast) { if (!fStalling) msStall = mseconds() + 250L; fStalling = 1; } else fStalling = 0; if (fStalling && mseconds() >= msStall) { printf("Stall!\n"); beep();beep(); fStalled = 1; } /* Read bump sensors and do block detection */ fBlocked = 0; for (i = 0; i < 4; i++) { rgfBump[i] = digital(i+12); if (rgfBump[i] && sgn(rgpwr[rgibumpMotor[i]]) == rgibumpSgn[i]) { fBlocked = 1; rgfBlock[i] = 1; } else rgfBlock[i] = 0; } if (digital(10)) fBall = 1; } int pwrMax = 100; void Move(int cLMax, int cRMax) { int sL; int sR; float tL; float tR; float tMax; int sLSet; int sRSet; long ms; long msLimit; printf("Move: %d, %d\n", cLMax, cRMax); if (fAssertEnable) StartPress(); msLimit = mseconds() + 2000L; InitEncoders(); if (cLMax < 0) { cLMax = -cLMax; sL = -pwrMax; } else sL = pwrMax; if (cRMax < 0) { cRMax = -cRMax; sR = -pwrMax; } else sR = pwrMax; while (cL < cLMax || cR < cRMax) { if (stop_button()) break; ReadEncoders(); if (FBallCapture()) break; if (fStalled || fBlocked) { if (!fForce) { beep();beep();beep(); printf("Abort Move\n"); break; } ms = mseconds(); if (ms >= msLimit) { beep();beep();beep(); printf("Time out\n"); break; } } if (cL >= cLMax) sL = 0; if (cR >= cRMax) sR = 0; /* printf("L: %d, R: %d\n", cL, cR); */ tL = Parametric(cL, cLMax); tR = Parametric(cR, cRMax); sRSet = sR; sLSet = sL; /* BUG: Can need less than 3/4 speed - also need not retart balanced motors when both can track the same! */ if (tL > tR) sLSet = sL*3/4; else sRSet = sR*3/4; SetMotors(sLSet, sRSet); } SetMotors(0,0); } /* forward/back speeds ticks per sec - under load? */ int rgSpeed[2] = {25, 29}; /* Measure ticks per second */ void CalibrateSpeed() { long msStart; long msEnd; int cForward; int cBack; int cTicks = 500; int i; int fServo; for (fServo = 0; fServo < 2; fServo++) { if (fServo) { enable_servos(); Gate(0); printf("Servo: "); } else printf("No Servo: "); for (i = 0; i < 2; i++) { msStart = mseconds(); Move(cTicks,cTicks); msEnd = mseconds(); rgSpeed[i] = MultDiv(100, 1000, (int) (msEnd - msStart)); printf("%d ", rgSpeed[i]); cTicks = -cTicks; sleep(1.0); } if (fServo) disable_servos(); printf("\n"); StartPress(); } } /* persistent int c360Soft = 630; persistent int c360Hard = 270; */ /* Turn calibration - 0, 90, 180, 270, 360 */ persistent int rgcHard[5] = {0, 65, 144, 230, 310}; persistent int rgcSoft[5] = {0, 135, 300, 480, 644}; /* + Left, -Right */ void Hard(int deg) { int c; c = InterpolateTicks(deg, rgcHard); Move(-c, c); } int rgSLeft[] = {-1, 0, 0, 1}; int rgSRight[] = {0, 1, -1, 0}; void Soft(int deg, int fForward) { int i; int c; i = fForward; if (deg < 0) { i += 2; deg = -deg; } c = InterpolateTicks(deg, rgcSoft); Move(rgSLeft[i] * c, rgSRight[i] * c); } int InterpolateTicks(int deg, int rgcTicks[]) { int fNeg = 0; int c; int icBase; int iTurns; if (deg < 0) { fNeg = 1; deg = -deg; } iTurns = deg/360; deg = deg % 360; icBase = deg/90; c = WProportion(deg, icBase*90, (icBase+1)*90, rgcTicks[icBase], rgcTicks[icBase+1]) + iTurns * rgcTicks[4]; if (fNeg) c = -c; return c; } void SoftTest() { PromptFor("LF"); Soft(45, 1); PromptFor("LB"); Soft(45, 0); PromptFor("RF"); Soft(-45, 1); PromptFor("RB"); Soft(-45, 0); } void HardTest() { int deg; int degT; int fNeg; for (deg = 90; deg < 360; deg++) for (fNeg = 0; fNeg < 2; fNeg++) { degT = deg; if (fNeg) degT = -deg; printf("Hard %d\n", degT); Hard(degT); } } void BumpTest() { while (1) { Soft(360, 1); BumpStatus(); Soft(360, 0); BumpStatus(); Soft(-360, 1); BumpStatus(); Soft(-360, 0); BumpStatus(); } } void BumpStatus() { int i; printf("Blocked: %d ", fBlocked); for (i = 0; i < 4; i++) { printf("%d ", rgfBlock[i]); } printf("\n"); StartPress(); } /* Motor power (left/right) */ int rgpwr[2] = {0,0}; int rgpwrSet[2] = {0,0}; int rgMotor[4] = {0, 2, 1, 3}; int rgsgnMotor[4] = {1, -1, 1, -1}; /* Control 4 motors - ganged 2 on each side */ void SetMotors(int pwrL, int pwrR) { rgpwrSet[0] = pwrL; rgpwrSet[1] = pwrR; } void MotorDriver() { int i; int j; while (1) { for (i = 0; i < 2; i++) { if (rgpwr[i] != rgpwrSet[i]) { /* Instantaneous power reductions */ /* if (rgpwrSet[i] < rgpwr[i]) */ rgpwr[i] = rgpwrSet[i]; /* else rgpwr[i] = (3* rgpwr[i] + rgpwrSet[i])/4; */ for (j = 0; j < 2; j++) motor(rgMotor[2*i+j], rgpwr[i] * rgsgnMotor[2*i+j]); } } msleep(25L); } } float Parametric(int x, int xMax) { if (xMax == 0) return 1.0; return (float) x / (float) xMax; } int wLD; int iSight; #define iBlack 0 #define iMid 1 #define iWhite 2 int rgwTable[3]; int rgwWhite[3]; int rgwBlack[3]; int rgwTableMid[3] = {24, 15, 14}; int rgiTable[3]; persistent int wBlack = 30; persistent int wWhite = 230; persistent int wSlop = 40; persistent int wMid = 105; void FindLine() { int iCur; int iProc; int wInit; DebugStop("Find Line Start"); Lookdown(); iCur = iSight; wInit = wLD; iProc = start_process(Move(1000,1000)); while (iSight == iCur && !fBlocked && !fStalled && !fBall) { printf("FindLine: %d\n", iSight); defer(); Lookdown(); } printf("I:%d, B:%d S:%d\n", iSight, fBlocked, fStalled); kill_process(iProc); SetMotors(0,0); if (fBlocked || fStalled) Unbind(); } int pwrTrackMin = 16; int pwrTrackMax = 60; #define degSeek 1 /* Assume starting well aligned to line (black on left, white on right). If we leave the iMid region - we return (and set fLoseTrack) */ void LineFollower() { int pwrLeft; int pwrRight; InitEncoders(); while (!fStalled && !fBlocked) { Lookdown(); pwrLeft = WProportion(wLD, wBlack, wWhite, pwrTrackMax, pwrTrackMin); pwrRight = WProportion(wLD, wBlack, wWhite, pwrTrackMin, pwrTrackMax); printf("Follow: %d - %d\n", pwrRight, pwrLeft); SetMotors(pwrLeft, pwrRight); ReadEncoders(); } SetMotors(0,0); } void CalibrateLookdown() { int i; PromptFor("Over white"); Lookdown(); wWhite = wLD; for (i = 0; i < 3; i++) rgwWhite[i] = rgwTable[i]; PromptFor("Over black"); Lookdown(); for (i = 0; i < 3; i++) rgwBlack[i] = rgwTable[i]; wBlack = wLD; wSlop = (wWhite - wBlack)/5; wMid = (wWhite + wBlack)/2; for (i = 0; i < 3; i++) rgwTableMid[i] = (rgwWhite[i] + rgwBlack[i])/2; printf("%d, %d (%d slop)\n", wBlack, wWhite, wSlop); StartPress(); for (i = 0; i < 3; i++) printf("%d-%d ", rgwWhite[i], rgwBlack[i]); printf("\n"); StartPress(); } void LookdownTest() { int cErr = 0; int cLook = 0; while (!stop_button()) { cLook++; Lookdown(); if (wLD < 10) { cErr++; } printf("iSight: %d wLD: %d [0-%d:%d-255] Low: %d\n", iSight, wLD, wBlack+wSlop, wWhite-wSlop, cErr); } while (stop_button()); } int Lookdown() { int wAmb; int i; wAmb = analog(4); DownLight(1); wLD = wAmb - analog(4); DownLight(0); if (wLD <= wBlack + wSlop) iSight = iBlack; else if (wLD >= wWhite - wSlop) iSight = iWhite; else iSight = iMid; for (i = 0; i < 3; i++) { rgwTable[i] = analog(16+i); if (rgwTable[i] < rgwTableMid[i]) rgiTable[i] = iWhite; else rgiTable[i] = iBlack; } } void DownLight(int fOn) { motor(4, fOn * 100); } /* Move recorder routines */ void RecordMove(int iirec) { /* Note we don't reclaim buffer when over-recording */ rgirecMin[iirec] = iRecNext; Recorder(); rgirecMax[iirec] = iRecNext; } void PlayMove(int iirec) { Playback(rgirecMin[iirec], rgirecMax[iirec]); } void Recorder() { while (YesNo("Record next")) { if (iRecNext >= 100) { printf("Buffer Full\n"); return;} xRec[iRecNext] = read_encoder(0); yRec[iRecNext] = read_encoder(1); iRecNext++; } } void Playback(int iMin, int iMax) { int i; for (i = iMin; i < iMax; i++) Move(xRec[i], yRec[i]); } void ServoTest() { int pos; enable_servos(); ServoRange(); disable_servos(); } void ServoRange() { int pos; int portServ = 0; while (!stop_button()) { if (start_button()) { portServ = 1 - portServ; while (start_button()); } pos = ScaleKnob(30, 3960); printf("Servo: %d\n", pos); servo(portServ, pos); } while (stop_button()); } void CalibrateGate() { int i; PromptFor("Disengage Gate"); enable_servos(); Gate(0); PromptFor("Re-engage at top"); printf("Testing..."); for (i = 3; i >= 0; i--) { printf("%d", i); sleep(1.0); } printf("\n"); for (i = 0; i < 5; i++) { Gate(1); sleep(5.0); Gate(0); sleep(1.0); } disable_servos(); } int fGateDown; int rgcGate[4] = {2233, 939, 1586, 2927}; /* Straight up, and horizontal settings */ int rgcAngle[4] = {2819, 1031, 970, 2896}; void Gate(int fDown) { int i; for (i = 0; i < 2; i++) { servo(i, rgcGate[i*2 + fDown]); } fGateDown = fDown; } void GatePos(int deg) { int i; for (i = 0; i < 2; i++) { servo(i, WProportion(deg, 0, 90, rgcAngle[2*i], rgcAngle[2*i+1])); } } int FBallCapture() { if (fBall && !fBallRelease && !fGateDown) { Gate(1); return 1; } return 0; } void Spinner() { int i; int deg; deg = WSetting("Degrees", 10, 360); for (i = 0; i < 10; i++) { Hard(deg); Hard(-deg); } } void Shaker() { int i; int dist; int ms; dist = WSetting("Clicks", 1, 100); ms = WSetting("Pause (ms)", 0, 1000); for (i = 0; i < 10; i++) { Move(dist, dist); if (ms) msleep((long) ms); Move(-dist, -dist); if (ms) msleep((long) ms); } } void Placebo() { int i; ir_transmit_off(); fAssertEnable = YesNo("Debug"); kill_process(ipMotor); if (YesNo("Start Light")) start_machine(START_LIGHT_PORT); ipMotor = start_process(MotorDriver()); CompeteInit(0); Orient(); FindLine(); while (1) { Hard(90); Move(-100, -100); Move(80, 80); Hard(90); Move(-200, -200); msleep(1000L); Chop(3); Move(50, 50); Wheelie(); } } void Chop(int iMax) { int i; for (i = 0; i < iMax; i++) { GatePos(0); Move(5, 5); GatePos(90); Move(-5, -5); } } void Wheelie() { GatePos(90); Move(60,60); GatePos(0); Move(-40, -40); Move(1000, 1000); msleep(1000L); Unbind(); } <file_sep>// ------------------------------------------------------------ // util.js // // Copyright, 2003-2004 by <NAME> (<EMAIL>) // // History: // // January 31, 2004 [mck] Added Point and Rect utilities for object positioning. // November 28, 2003 [mck] Copied base JScript utilities from object.js. // // This file contains utilities for enabling a richer object-oriented code in JScript // as well as helper functions for string processing, collections (Bag's), and absolute // positioned DHTML. // ------------------------------------------------------------ // Header template - copy me // -----------------------------------------------------mck---- var cbUtil = new CodeBase("util.js"); // ------------------------------------------------------------ // CodeBase - determine location of script file // -----------------------------------------------------mck---- function CodeBase(stScript) { var stPath; var ichFile; for (i = 0; i < document.scripts.length; i++) { stPath = document.scripts(i).src; ichFile = stPath.indexOf(stScript, 0); if (ichFile >= 0) { this.stPath = stPath.substring(0, ichFile); if (this.stPath.indexOf("http://") == 0) this.stDomain = this.stPath.substring(7); break; } } } function CodeBase.prototype.StIncludeScript(stFile) { var st = ""; st += "<" + "SCRIPT SRC=" + StAttrQuote(this.stPath + stFile); st += "></" + "SCRIPT>"; return st; } function CodeBase.prototype.IncludeScript(stFile) { document.write(this.StIncludeScript(stFile)); } function CodeBase.prototype.IncludeStyle(stFile) { document.createStyleSheet(this.stPath + stFile); } // ------------------------------------------------------------ // Object Orientation Functions // -----------------------------------------------------mck---- // Copy all base class methods that do not have a definition in the current // constructor prototype. Also add a prototype variable that references to // base class's constructor by name function Function.prototype.DeriveFrom(fnBase) { var prop; if (this == fnBase) { alert("Error - cannot derive from self"); return; } for (prop in fnBase.prototype) { if (typeof(fnBase.prototype[prop]) == "function" && !this.prototype[prop]) { this.prototype[prop] = fnBase.prototype[prop]; } } this.prototype[fnBase.StName()] = fnBase; } function Function.prototype.StName() { var st; st = this.toString(); st = st.substring(st.indexOf(" ")+1, st.indexOf("(")); return st; } // Give subclass access to parent's method, via Parent_Method() like call. function Function.prototype.Override(fnBase, stMethod) { this.prototype[fnBase.StName() + "_" + stMethod] = fnBase.prototype[stMethod]; } function Function.prototype.StParams() { var st; st = this.toString(); st = st.substring(st.indexOf("("), st.indexOf(")")+1); return st; } // ------------------------------------------------------------ // Named - Base class for jsavascript objects that need scriptable names // // Derive from the Named object for any object that you want to have a script-evalable name // (these are often needed in attributes added to browser elements for click events, timer callbacks etc.) // // e.g. // MyObj.DeriveFrom(Named); // function MyObj() // { // this.Named(); // ... // } // "<IMG onclick=" + StAttrQuote(this.StNamed() + ".Callback();") + ">" // -----------------------------------------------------mck---- Named.idNext = 0; Named.rg = new Array; function Named() { this.idNamed = Named.idNext++; Named.rg[this.idNamed] = this; } // Name for the JS object function Named.prototype.StNamed() { return "Named.rg[" + this.idNamed + "]"; } // Produce DHTML name for web component associated with this JS object function Named.prototype.StNamedPart(stPart, iPart) { var st; st = "NM_" + this.idNamed + "_" + stPart; if (iPart != undefined) st += "_" + iPart; return st; } function Named.prototype.StPartID(stPart, iPart) { return "ID=" + StAttrQuote(this.StNamedPart(stPart, iPart)); } function Named.prototype.BoundPart(stPart, iPart) { return eval(this.StNamedPart(stPart, iPart)); } function Named.prototype.FnCallBack(stFunc) { return new Function(this.StNamed() + "." + stFunc + "();"); } // ------------------------------------------------------------ // Misc and string quoting Functions // -----------------------------------------------------mck---- function NYI() { alert(NYI.caller.StName() + ": Not yet implemented"); } function StAttrQuote(st) { return '"' + StAttrQuoteInner(st) + '"'; } function StAttrQuoteInner(st) { st = st.toString(); st = st.replace(/&/g, '&amp;'); st = st.replace(/\"/g, '&quot;'); // editor confused about single quote " st = st.replace(/'/g, '&#39;'); // editor confused about single quote ' st = st.replace(/\r/g, '&#13;'); return st; } function DW(st) { document.write(st); } function Array.prototype.toString() { var i; var st = ""; st += "["; for (i = 0; i < this.length; i++) { if (i != 0) st += ", "; st += this[i].toString(); } st += "]"; return st; } function String.prototype.StRotate(iRot) { return this.substring(iRot) + this.substring(0, iRot); } function String.prototype.StReplace(stPat, stRep) { var st = ""; var ich = 0; var ichFind = this.indexOf(stPat, 0); while (ichFind >= 0) { st += this.substring(ich, ichFind) + stRep; ich = ichFind + stPat.length; ichFind = this.indexOf(stPat, ich); } st += this.substring(ich); return st; } function StHTML(st) { st = st.toString(); st = st.replace(/&/g, '&amp;'); st = st.replace(/</g, '&lt;'); st = st.replace(/>/g, '&gt;'); st = st.replace(/\n/g, '<br>'); st = st.replace(/ /g, '&nbsp;'); st = st.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;'); return st; } function StBaseURL(stBase, stURL) { if (stURL.indexOf("://", 0) < 0) stURL= stBase + stURL; return stURL; } function MailLink(stDomain, stUser, stName, stSubject) { var st = ""; st += "mailto:" + stDomain + "@" + stUser; if (stSubject != undefined) st += "?subject=" + stSubject; document.write("<A HREF=" + StAttrQuote(st) + ">" + stName + "</A>"); } function URLNav(stOther) { var stURL = stOther; if (stURL == undefined) stURL = document.location.href; this.mpParam = new Object; var ich = stURL.indexOf("?"); if (ich == -1) ich = stURL.length; this.stBase = stURL.substring(0, ich); while (ich < stURL.length) { ich++; ichVar = stURL.indexOf("=", ich); ichEnd = stURL .indexOf("&", ich); if (ichEnd == -1) ichEnd = stURL.length; if (ichVar != -1) { var stParam = stURL.substring(ich, ichVar); stParam = decodeURIComponent(stParam); var stValue = stURL.substring(ichVar+1, ichEnd); stValue = decodeURIComponent(stValue); this.SetParam(stParam, stValue); } ich = ichEnd; } } function URLNav.prototype.StParam(stParam) { return this.mpParam[stParam]; } function URLNav.prototype.SetParam(stParam, stValue) { this.mpParam[stParam] = stValue; } function URLNav.prototype.StURL() { var stURL = this.stBase; var fFirst = true; for (stParam in this.mpParam) { if (!this.mpParam.hasOwnProperty(stParam)) continue; stURL += fFirst ? "?" : "&"; fFirst = false; stURL += encodeURIComponent(stParam) + "=" + encodeURIComponent(this.StParam(stParam)); } return stURL; } // ------------------------------------------------------------ // BAG - Supports collections of objects and enumeration // -----------------------------------------------------mck---- Bag.idNext = 0; function Bag() { this.rg = new Array; this.stName = "Bag" + Bag.idNext++; this.idNext = 0; this.c = 0; } function Bag.prototype.Add(obj) { // Already a member of this bag if (obj[this.stName] != undefined) return; this.rg[this.idNext] = obj; obj[this.stName] = this.idNext; this.idNext++; this.c++; } function Bag.prototype.Remove(obj) { var id = obj[this.stName]; // Not in this bag if (id == undefined) return; this.rg[id] = undefined; this.c--; } function Bag.prototype.FMember(obj) { return obj[this.stName] != undefined; } // // IBag - Iterator for Bag's // function IBag(bag) { this.bag = bag; this.Init(); } function IBag.prototype.Init() { this.i = -1; } function IBag.prototype.FNext() { while (++this.i < this.bag.rg.length) { if (this.bag.rg[this.i] != undefined) return true; } return false; } function IBag.prototype.Obj() { if (this.i == -1) this.FNext(); return this.bag.rg[this.i]; } // ------------------------------------------------------------ // FileLoad - Allows reading files into JScript programs // -----------------------------------------------------mck---- FileLoad.DeriveFrom(Named); function FileLoad() { this.Named(); this.id = FileLoad.idNext++; FileLoad.rgfl[this.id] = this; } function FileLoad.prototype.StUI() { var st = ""; st += "<IFRAME "; st += "style=display:none "; st += this.StPartID("Frame"); st += " onload=" + StAttrQuote(this.StNamed() + ".Loaded(); "); st += "></IFRAME>"; return st; } function FileLoad.prototype.BindUI() { this.frData = this.BoundPart("Frame"); } function FileLoad.prototype.WriteUI() { DW(this.StUI()); this.BindUI(); } function FileLoad.prototype.GetFile(stFile, fnCallback) { this.frData.document.location = stFile; this.fnCallBack = fnCallback; this.fLoaded = false; } function FileLoad.prototype.Loaded() { this.fLoaded = true; if (this.fnCallBack != undefined) this.fnCallBack(this); } function FileLoad.prototype.StFile() { if (!this.fLoaded) return ""; return this.frData.document.body.innerText; } // ------------------------------------------------------------ // Geometrical and element positioning primitives // // Point - pt.x, pt.y // Rect - rc.ptUL, rc.ptLR // -----------------------------------------------------mck----// function Point(x, y) { this.x = x; this.y = y; } function Point.prototype.FEqual(pt) { return (this.x == pt.x && this.y == pt.y); } function Point.prototype.FLEThan(pt) { return this.x <= pt.x && this.y <= pt.y; } function Point.prototype.Clone() { return new Point(this.x, this.y); } function Point.prototype.Negate() { this.x = -this.x; this.y = -this.y; } function Point.prototype.Floor() { this.x = Math.floor(this.x); this.y = Math.floor(this.y); } function Point.prototype.Add(pt) { this.x += pt.x; this.y += pt.y; } function Point.prototype.Offset(dx, dy) { this.x += dx; this.y += dy; } function Point.prototype.Sub(pt) { this.x -= pt.x; this.y -= pt.y; } function Point.prototype.Min(pt) { this.x = Math.min(this.x, pt.x); this.y = Math.min(this.y, pt.y); } function Point.prototype.Max(pt) { this.x = Math.max(this.x, pt.x); this.y = Math.max(this.y, pt.y); } function Point.prototype.Mult(num) { this.x *= num; this.y *= num; } // Return the max scale factor that keeps each dimension less than or equal // to a target size. function Point.prototype.ScaleTo(ptT) { return Math.min(ptT.x / this.x, ptT.y / this.y); } function Rect(ptUL, ptLR) { if (ptUL == undefined) this.ptUL = new Point(0,0); else this.ptUL = ptUL.Clone(); if (ptLR == undefined) ptLR = this.ptUL; this.ptLR = ptLR.Clone(); } function Rect.prototype.Clone() { return new Rect(this.ptUL, this.ptLR); } function Rect.prototype.Offset(dx, dy) { this.ptUL.Offset(dx, dy); this.ptLR.Offset(dx, dy); } function Rect.prototype.Add(ptD) { this.ptUL.Add(ptD); this.ptLR.Add(ptD); } function Rect.prototype.Sub(ptD) { this.ptUL.Sub(ptD); this.ptLR.Sub(ptD); } function Rect.prototype.Union(rc) { this.ptUL.Min(rc.ptUL); this.ptLR.Max(rc.ptLR); } function Rect.prototype.BBox(pt) { this.ptUL.Min(pt); this.ptLR.Max(pt); } function Rect.prototype.PtCenter() { var ptCenter = this.ptUL.Clone(); ptCenter.Add(this.ptLR); ptCenter.Mult(1/2); return ptCenter; } function Rect.prototype.CenterOn(ptCenter) { this.MoveTo(ptCenter, this.PtCenter()); } // Move the rectangle so that the upper left corner (OR the given source point) // is reposition to the Target location. function Rect.prototype.MoveTo(ptTarget, ptSrc) { var pt; pt = ptTarget.Clone(); if (!ptSrc) pt.Sub(this.ptUL); else pt.Sub(ptSrc); this.Add(pt); } function Rect.prototype.PtSize() { var ptSize = this.ptLR.Clone(); ptSize.Sub(this.ptUL); return ptSize; } function Rect.prototype.Dx() { return this.ptLR.x - this.ptUL.x; } function Rect.prototype.Dy() { return this.ptLR.y - this.ptUL.y; } // Rectangles must include at least 1 pixel of OVERLAP to be considered intersecting // (not merely coincident on one edge). function Rect.prototype.FIntersect(rc) { return (FIntersectRange(this.ptUL.x, this.ptLR.x, rc.ptUL.x, rc.ptLR.x) && FIntersectRange(this.ptUL.y, this.ptLR.y, rc.ptUL.y, rc.ptLR.y)); } function Rect.prototype.FContainsPt(pt) { return (pt.x >= this.ptUL.x && pt.x <= this.ptLR.x && pt.y >= this.ptUL.y && pt.y <= this.ptLR.y); } function Rect.prototype.FContainsRc(rc) { return (this.FContainsPt(rc.ptUL) && this.FContainsPt(rc.ptLR)); } function FIntersectRange(x1Min, x1Max, x2Min, x2Max) { return x1Max > x2Min && x2Max > x1Min; } function Rect.prototype.PtUR() { return new Point(this.ptLR.x, this.ptUL.y); } function Rect.prototype.PtLL() { return new Point(this.ptUL.x, this.ptLR.y); } // Map to an interior portion of the rectangle - proportional to numX and numY [0..1] // for all points in the interior. function Rect.prototype.PtMap(numX, numY) { var dpt = this.ptLR.Clone(); dpt.Sub(this.ptUL); dpt.x *= numX; dpt.y *= numY; dpt.Add(this.ptUL); return dpt; } // Get absolute position on the page for the upper left of the element. function PtAbsolute(elt) { var pt = new Point(0,0); while (elt.offsetParent != null) { pt.x += elt.offsetLeft; pt.y += elt.offsetTop; elt = elt.offsetParent; } return pt; } // Return size of a DOM element in a Point - includes borders, but not margins function PtSize(elt) { return new Point(elt.offsetWidth, elt.offsetHeight); } // Return aboslute bounding rectangle for a DOM element function RcAbsolute(elt) { var rc = new Rect; rc.ptUL = PtAbsolute(elt); rc.ptLR = rc.ptUL.Clone(); rc.ptLR.Add(PtSize(elt)); return rc; } // Set DOM element absolution position function PositionElt(elt, pt) { // assumes elt.style.position = "absolute" elt.style.pixelLeft = pt.x; elt.style.pixelTop = pt.y; } // Set DOM element size function SizeElt(elt, pt) { if (pt.x != undefined) elt.style.pixelWidth = pt.x; if (pt.y != undefined) elt.style.pixelHeight = pt.y; } // Set DOM element Rect function SetEltRect(elt, rc) { PositionElt(elt, rc.ptUL); SizeElt(elt, rc.PtSize()); } // // Timer class supports periodic execution of a snippet of jscript code. // Timer.DeriveFrom(Named); function Timer(fnCallBack, ms, fOneShot) { this.Named(); this.ms = ms; this.fnCallBack = fnCallBack; this.iPing = 0; this.fOneShot = fOneShot; } function Timer.prototype.Ping() { if (this.fOneShot) this.Active(false); this.fnCallBack(); } // Calling Active resets the timer so that next call to Ping will be in this.ms milliseconds from NOW function Timer.prototype.Active(fActive) { if (this.iTimer) { clearInterval(this.iTimer); this.iTimer = undefined; } if (fActive) this.iTimer = setInterval(this.StNamed() + ".Ping();", this.ms); } function Timer.prototype.FActive() { return this.iTimer != undefined; } // ------------------------------------------------------------ // Button - creates on-screen UI for calling a function // -----------------------------------------------------mck---- Button.DeriveFrom(Named); function Button(stLabel, stCode, stImg1, stImg2, stTitle) { this.Named(); this.stLabel = stLabel; this.stCode = stCode; this.fText = (stImg1 == undefined); this.stImg1 = stImg1; this.stImg2 = stImg2; this.stTitle = stTitle; this.fToggle = false; this.fCapture = false; this.fAlpha = stImg1 && stImg1.indexOf(".png", 0) > 0; if (this.fAlpha) { // Load the images so we can get the width/height this.img1 = new Image(); this.img1.onload = this.FnCallBack("ImgLoaded"); this.fLoaded = false; this.img1.src = stImg1; if (this.stImg2) { this.img2 = new Image(); this.img2.src = stImg2; } } } function Button.prototype.SetHeight(dy) { this.dyTarget = dy; } function Button.prototype.StUI() { var st = ""; if (this.fText) { st += "<INPUT " + this.StPartID("Button") + " TYPE=Button class=TextButton Value=" + StAttrQuote(this.stLabel); if (this.stTitle != undefined) st += " TITLE=" + StAttrQuote(this.stTitle); st += " onclick=" + StAttrQuote(this.stCode) + ">"; return st; } st += "<IMG " + this.StPartID("Button") + " class=ImgButton SRC="; if (this.fAlpha) { st += StAttrQuote(cbUtil.stPath + "images/blank.gif"); } else st += StAttrQuote(this.stImg1); if (this.stTitle != undefined) st += " TITLE=" + StAttrQuote(this.stTitle); st += ">"; return st; } function Button.prototype.BindUI() { this.btn = this.BoundPart("Button"); if (!this.fText) { this.btn.onmousedown = this.FnCallBack("MouseDown"); this.btn.onmousemove = this.FnCallBack("MouseMove"); this.btn.onmouseup = this.FnCallBack("MouseUp"); // Bug: The order of events leading to the ondblclick event is onmousedown, onmouseup, onclick, // onmouseup, and then ondblclick - we still have a bug since we do not get the second mouse // down that we don't paint the button in the down position - but we do execture the second command // on the double click message. this.btn.ondblclick = this.FnCallBack("DoubleClick"); this.btn.onlosecapture = this.FnCallBack("LoseCapture"); } this.SizeButton(); this.ButtonDown(false); } function Button.prototype.SizeButton() { if (!this.fLoaded || this.btn == undefined) return; var wScale = 1.0; if (this.dyTarget != undefined) wScale = this.dyTarget/this.img1.height; this.btn.style.pixelWidth = this.img1.width * wScale; this.btn.style.pixelHeight = this.img1.height * wScale; } function Button.prototype.ImgLoaded() { this.fLoaded = true; this.SizeButton(); } function Button.prototype.ButtonDown(fDown) { if (fDown == this.fDown) return; this.fDown = fDown; if (this.fText) return; var stImg = (fDown && this.stImg2) ? this.stImg2 : this.stImg1; if (this.fAlpha) { var st = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=" + StAttrQuote(stImg) + ", sizingMethod=scale)"; this.btn.style.filter = st; } else this.btn.src = stImg; } function Button.prototype.MouseDown() { this.fCapture = true; this.rc = RcAbsolute(this.btn); this.btn.setCapture(); this.ptMouse = new Point(0,0); this.fDownCap = this.fDown; this.ButtonDown(!this.fDownCap); } function Button.prototype.MouseMove() { if (!this.fCapture) return; // Convert window coordinates to document coordinates this.ptMouse.x = event.clientX + document.body.scrollLeft; this.ptMouse.y = event.clientY + document.body.scrollTop; this.ButtonDown(this.rc.FContainsPt(this.ptMouse) ^ this.fDownCap); } function Button.prototype.LoseCapture() { this.fCapture = false; this.ButtonDown(this.fDownCap); } function Button.prototype.MouseUp() { if (this.fDown == this.fDownCap) { document.releaseCapture(); return; } if (this.fToggle) this.fDownCap = !this.fDownCap; document.releaseCapture(); eval(this.stCode); } function Button.prototype.DoubleClick() { eval(this.stCode); } // ------------------------------------------------------------ // XML Utility functions // // Used for reading XML data islands // -----------------------------------------------------mck---- function XMLFromURL(stURL) { var xml = new ActiveXObject("Msxml2.DOMDocument"); xml.async = false; xml.resolveExternals = false; xml.load(stURL); return xml; } function StXMLError(xml) { var stError = ""; var err = xml.parseError; if (err.errCode != 0) { stError += "Parse Error in XML line number " + err.line + " (character " + err.linepos + "):\n"; if (err.url) stError += "File: " + err.url + "\n"; stError += "\n"; stError += err.srcText.substr(0, err.linepos-1); stError += "/\\"; stError += err.srcText.substr(err.linepos-1); stError += "\n\n" + err.reason; } return stError; } // Collect the text of all enclosed child nodes function StXMLContent(nd) { var i; var st = ""; if (!nd) return st; for (i = 0; i < nd.childNodes.length; i++) { st += nd.childNodes.item(i).xml; } return st; } // Read an attribute from a node, and provide a default value for a missing attribute // fNum=undefined/false: Treat as string // fNum=true: Treat as (floating point) number // fNum=2: Treat as Boolean! function XMLAttrDef(nd, stAttr, def) { if (!nd) return def; var stValue = nd.getAttribute(stAttr); if (stValue == undefined) return def; if (typeof(def) == "boolean") { var f; stValue = stValue.toUpperCase(); f = stValue == "TRUE" || stValue == "ON" || stValue == "YES"; return f; } if (typeof(def) == "number") return parseFloat(stValue); return stValue; } function PtXMLSizeDef(nd, ptDef, stPrefix) { if (stPrefix == undefined) stPrefix = ""; var ptSize = new Point(XMLAttrDef(nd, stPrefix + "Width", ptDef.x), XMLAttrDef(nd, stPrefix + "Height", ptDef.y)); return ptSize; } // ------------------------------------------------------------ // Object dump routines (for debugging) // -----------------------------------------------------mck---- var DumpCtx = new Object; DumpCtx.iDepth = 0; DumpCtx.iDepthMax = 3; DumpCtx.fProto = false; function Object.prototype.StDump() { var st = ""; var cProps = 0; var prop; if (DumpCtx.iDepth > DumpCtx.iDepthMax) { st += " '" + this.toString() + "'"; return st; } if (this.constructor == undefined) return "ActiveX Control"; DumpCtx.iDepth++; // All own properties for (prop in this) { if (this.hasOwnProperty(prop)) { st += StDumpVar(prop, this[prop]); cProps++; } } DumpCtx.iDepth--; if (cProps == 0) return ""; return st; } function StDumpVar(stVar, value) { var st = "\n"; for (i = 1 ; i < DumpCtx.iDepth; i++) st += " "; st += stVar + ": " ; if (value == undefined) { st += "UNDEFINED"; } else if (typeof(value) == "object") { if (value.constructor != undefined) st += value.StDump(); else st += "ActiveX Control"; } else if (typeof(value) == "function") { stT = value.toString(); st += stT.substring(0, stT.indexOf("(")); } else st += value.toString(); return st; } // Dump the properties of a DHTML element by enumerating all properties function StDumpAttrs(nd) { var i; var st = ""; var attr; for (i = 0; i < nd.attributes.length; i++) { attr = nd.attributes(i); if (attr.nodeValue != null && attr.nodeValue != "") st += attr.nodeName + ": " + attr.nodeValue + "\n"; } return st; } // ------------------------------------------------------------ // Window Control - window manipulation and sizing functions // -----------------------------------------------------mck---- WindowControl.DeriveFrom(Named); function WindowControl(wnd, fRecalibrate) { this.fInitializing = true; this.Named(); if (fRecalibrate == undefined) fRecalibrate = false; this.fRecalibrate = fRecalibrate; this.wnd = wnd ? wnd : window; this.ptScreen = new Point(screen.availWidth, screen.availHeight); this.rcScreen = new Rect(undefined, this.ptScreen); this.wnd.onresize = this.FnCallBack("Resize"); this.Refresh(); this.Calibrate(); this.fInitializing = false; } function WindowControl.prototype.Resize() { this.Refresh(); if (this.fnResize) this.fnResize(); } function WindowControl.prototype.Refresh() { this.ptUL = new Point(this.wnd.screenLeft, this.wnd.screenTop); this.ptClientSize = new Point(document.body.clientWidth, document.body.clientHeight); this.ptScroll = new Point(this.wnd.document.body.scrollLeft, this.wnd.document.body.scrollTop); this.rcClient = new Rect(undefined, this.ptClientSize); this.rcOnScreen = this.rcClient.Clone(); this.rcClient.Add(this.ptScroll); this.rcOnScreen.Add(this.ptUL); } // Use Win XP SP2 minimal window as standard control assumptions WindowControl.ptOffset = new Point(4, 30); WindowControl.ptControls = new Point(12, 38); // Temporarily move and resize the window, so I can get the dimensions of the controls // around the window (to ultimately compute the max visible area in the window). We // guess first at values for ptOffset and ptControls - if we're right, the window will not // in fact move at all (if it does move/size, we correct our guess). function WindowControl.prototype.Calibrate() { var rcScreenSav = this.rcOnScreen.Clone(); var fRecalSav = this.fRecalibrate; // Guess includes title bar, menu bar, address bar, google toolbar, status bar, and vertical scroll bar this.ptOffset = WindowControl.ptOffset.Clone(); this.ptControls = WindowControl.ptControls.Clone(); if (this.fRecalibrate) { this.fRecalibrate = false; // Move the window to the original to see how but ptOffset is (title bar, toolbar, etc). var ptULStart = this.ptUL.Clone(); this.MoveTo(ptULStart); ptULStart.Sub(this.ptUL); this.ptOffset.Sub(ptULStart); var ptClientStart = this.ptClientSize; this.SizeTo(this.ptClientSize); ptClientStart.Sub(this.ptClientSize); this.ptControls.Add(ptClientStart); // Save new default assumptions WindowControl.ptOffset = this.ptOffset.Clone(); WindowControl.ptControls = this.ptControls.Clone(); // alert("ptOffset: " + this.ptOffset.StDump() + "\nptControls:" + this.ptControls.StDump()); this.SetRc(rcScreenSav); } this.ptMaxVisSize = this.ptScreen.Clone(); this.ptMaxVisSize.Sub(this.ptControls); this.fRecalibrate = fRecalSav; } function WindowControl.prototype.FFitsScreen(ptSize) { return ptSize.FLEThan(this.ptMaxVisSize); } function WindowControl.prototype.FFitsWindow(ptSize) { this.Refresh(); return ptSize.FLEThan(this.ptClientSize); } // Resize the client area to the desired size (takes into account the total window size) function WindowControl.prototype.SizeTo(ptSize) { var ptOrig = ptSize.Clone(); ptOrig.Floor(); var pt = ptOrig.Clone(); pt.Add(this.ptControls); // Early mouse clicks make this line cause an exception??? try { this.wnd.resizeTo(pt.x, pt.y); } catch (e) {} this.Refresh(); // If a feature of the window has changed - our calibration may be wrong - try one recalibration // to see if the adjustment can be made. if (!ptOrig.FEqual(this.ptClientSize) && this.fRecalibrate) { this.fRecalibrate = false; this.Calibrate(); this.SizeTo(ptSize); this.fRecalibrate = true; } } // Moves the UL of the client area to the given screen point (takes into account offset between client area and top left of window) function WindowControl.prototype.MoveTo(ptMove) { var ptOrig = ptMove.Clone(); ptOrig.Floor(); var ptT = ptOrig.Clone(); ptT.Sub(this.ptOffset); // Early mouse clicks make this line cause an exception??? try { this.wnd.moveTo(ptT.x, ptT.y); } catch (e) {} this.Refresh(); // If a feature of the window has changed - our calibration may be wrong - try one recalibration // to see if the adjustment can be made. if (!ptOrig.FEqual(this.ptUL) && this.fRecalibrate) { this.fRecalibrate = false; this.Calibrate(); this.MoveTo(ptMove); this.fRecalibrate = true; } } function WindowControl.prototype.ScrollTo(pt) { this.wnd.scrollTo(pt.x, pt.y); this.Refresh(); } function WindowControl.prototype.SetRc(rc) { this.MoveTo(rc.ptUL); this.SizeTo(rc.PtSize()); } function WindowControl.prototype.PtToScreen(pt) { pt.Sub(this.ptScroll); pt.Add(this.ptUL); } // ------------------------------------------------------------ // Sound -Allows for control of sound files // -----------------------------------------------------mck---- Sound.DeriveFrom(Named) Sound.psStopped = 1; Sound.psPaused = 2; Sound.psPlaying = 3; Sound.psMediaEnded = 8; function Sound(stSrc, fnEndMedia) { this.Named(); this.stSrc = stSrc; this.fLoading = false; this.vol = 100; this.fLoop = false; this.timer = new Timer(this.FnCallBack("Ping"), 300); this.fnEndMedia = fnEndMedia; } function Sound.prototype.StUI() { var st = ""; // Note: Media Player Version 9 class ID here. // May want to switch to older version that had a CODEBASE supported parameter for // auto-download. // CLASSID="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" // CODEBASE="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" // Hiding the player is subtle. I tried style display:none, but that was not working in IE 6.0 on Windows ME. // Setting WIDTH and HEIGHT to 0 shrink the play to a single pixel on the screen - left as a backup. // PARAM tag uiMode=invisible will turn off the display in all versions // (I had to remove display:none as it was causing old version to not play audio st += "<OBJECT WIDTH=0 HEIGHT=0 " + this.StPartID("Player"); st += " CLASSID='CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6'>" st += " <PARAM NAME=autoStart VALUE=false>"; st += " <PARAM NAME=uiMode VALUE=invisible>"; st += "</OBJECT>"; st += "<SCRIPT FOR=" + this.StNamedPart("Player") + " EVENT='PlayStateChange(state)'>"; st += this.StNamed() + ".StateChange(state);"; st += "</SCRIPT>"; return st; } function Sound.prototype.BindUI() { this.player = this.BoundPart("Player"); this.SetVolume(100); if (this.fLoop) this.player.settings.setMode("loop", true); this.player.controls.pause(); this.fPlay = false; } function Sound.prototype.StateChange(state) { // Play can be paused in a race condition. We tell the player to pause, but it's not started playing yet. // So here, we detect starting to play when we're not supposed to be, and again pause the player. if (state == Sound.psPlaying && !this.fPlay) this.player.controls.pause(); // On "media end", alert call-back that we're done playing if (state == Sound.psMediaEnded && this.fPlay && !this.fLoop) { this.fPlay = false; if (this.fnEndMedia) this.fnEndMedia(); } } // Set sound volume to ramp (linearly) to new volume [0..100] over time given (sec). function Sound.prototype.RampVolume(vol, sec, fnCallback) { var msNow = new Date().getTime(); this.msStart = msNow; this.msEnd = msNow + sec*1000; this.volStart = this.vol; this.volEnd = vol; this.fnCallback = fnCallback; this.timer.Active(true); } function Sound.prototype.Mute(fMute) { this.player.settings.mute = fMute; } function Sound.prototype.Load() { if (this.fLoading) return this.fLoading = true; // This old code only supported by WMP 9.0 and higher - use player.URL (supported by 7.0 and higher) // this.media = this.player.newMedia(this.stSrc); // this.player.currentMedia = this.media; this.player.URL = this.stSrc; } function Sound.prototype.Play(fPlay) { // Without this line, repeated called to Play(true) were causing sporadic stuttering // of the audio playback (due to repeated calls to controls.play!) if (fPlay == this.fPlay) return; this.fPlay = fPlay; if (fPlay) { this.Load(); this.player.controls.play(); } else { this.player.controls.pause(); } } function Sound.prototype.FPlaying() { var state = this.player.playState; return state == Sound.psPlaying; } function Sound.prototype.SetVolume(volNew) { this.player.settings.volume = volNew; } function Sound.prototype.Ping() { var msNow = new Date().getTime(); var volNew = NumProportion(msNow, this.msStart, this.msEnd, this.volStart, this.volEnd); this.SetVolume(volNew); if (msNow > this.msEnd) { this.timer.Active(false); if (this.fnCallback) this.fnCallback(); } } // ------------------------------------------------------------ // NumProportion - Return a scaled value where source range is mapped // to an output range (linear interpolation). // -----------------------------------------------------mck---- function NumProportion(numIn, numInMin, numInMax, numOutMin, numOutMax) { var num; if (numIn <= numInMin) return numOutMin; if (numIn >= numInMax) return numOutMax; num = (numIn - numInMin) * (numOutMax-numOutMin) / (numInMax-numInMin) + numOutMin; return num; } // ------------------------------------------------------------ // StatusMsg - Handle mutliple levels of status messages being displayed // to the user. To have status displayed in a DHTML element, pass in the // element as an arugment. Othewise, the status bar is used. // // Each status message belongs in a "slot" - any key can be used. Each slot // can contain one text string. All slots are concatenated together to display // the user-visible status message. // -----------------------------------------------------mck---- function StatusMsg(txtStat) { this.txtStat = txtStat; this.mpStatus = new Object; this.stLast = ""; } function StatusMsg.prototype.SetStatus(stSlot, stMsg) { if (stMsg == null || stMsg == undefined || (typeof(stMsg) == "string" && stMsg == "")) this.mpStatus[stSlot] = undefined; else this.mpStatus[stSlot] = stMsg; this.Display(); } function StatusMsg.prototype.StDisplay() { var st = ""; var stSlot; for (stSlot in this.mpStatus) { if (!this.mpStatus.hasOwnProperty(stSlot)) continue; if (this.mpStatus[stSlot] != undefined) { if (st != "") st += " - "; st += stSlot + ": " + this.mpStatus[stSlot]; } } return st; } function StatusMsg.prototype.Display() { var st = this.StDisplay(); if (this.txtStat != undefined) this.txtStat.innerText = st; else { if (this.stLast != st) status = st; } this.stLast = st; } // ------------------------------------------------------------ // DragController - Class enables a web document to be scrolled "by hand" // -----------------------------------------------------mck---- DragController.DeriveFrom(Named); function DragController(obj) { this.Named(); this.obj = obj; obj.style.cursor = "move"; this.fDown = false; this.fThrow = false; obj.onmousedown = this.FnCallBack("MouseDown"); obj.onmousemove = this.FnCallBack("MouseMove"); obj.onmouseup = this.FnCallBack("MouseUp"); obj.onkeydown = this.FnCallBack("KeyDown"); this.msIdle = 1; this.friction = 0.97; this.tm = new Timer(this.FnCallBack("Idle"), this.msIdle); } function DragController.prototype.Throw(fThrow) { if (this.fThrow == fThrow) return; this.fThrow = fThrow; this.tm.Active(fThrow); } function DragController.prototype.Idle() { scrollBy(this.dx, this.dy); this.dx *= this.friction; this.dy *= this.friction; if (Math.abs(this.dx) < 1 && Math.abs(this.dy) < 1) this.Throw(false); } function DragController.prototype.MouseDown() { if (event.srcElement.tagName.toUpperCase() == "AREA") { return; } this.obj.setCapture(); this.fDown = true; this.Throw(false); this.RecordMouse(true); } function DragController.prototype.MouseMove() { if (!this.fDown) return; // Bug - we somehow got a mousedown and no mouseup if (event.button == 0) { this.MouseUp(); return; } this.RecordMouse(false); scrollBy(this.dx, this.dy); } function DragController.prototype.RecordMouse(fInit) { if (fInit) { this.dx = this.dy = 0; } else { this.dx = this.x - event.clientX; this.dy = this.y - event.clientY; } this.x = event.clientX; this.y = event.clientY; } function DragController.prototype.MouseUp() { this.obj.releaseCapture(); this.fDown = false; this.Throw(true); } function DragController.prototype.KeyDown() { var dx = 0; var dy = 0; switch (event.keyCode) { // left arrow case 37: dx = -5; break; // right arrow case 39: dx = 5; break; // up arrow case 38: dy = -5; break; // down arrow case 40: dy = 5; break; // page up case 33: dy = -10; break; // page down case 34: dy = 10; break; default: if (this.fnKey) this.fnKey(); return; } event.returnValue = false; if (!this.fDown && !this.fThrow) { this.dx = dx; this.dy = dy; this.Throw(true); return; } if (this.fThrow) { this.dx += dx; this.dy += dy; } } <file_sep>// // Solution adapted from manual solving techniques of <NAME> - <EMAIL> // // Copyright 2003, <NAME> (<EMAIL>) function FLee(ml) { this.ml = ml; } function FLee.prototype.Move(st) { this.ml.AppendMoves(st); this.perm = this.perm.ApplyMoves(st); } function FLee.prototype.Solve(perm) { var mv = this.ml.OpenBlock("Frank Lee Solution"); this.perm = perm; this.SolveUPieces(); // this.SolveMEdges(); // this.LastUPiece(); // this.LastMEdge(); mv.Close(); } FLee.rgUCubes = ["UFL", "UF", "URF", "UL", "UR", "ULB", "UB", "UBR"]; function FLee.prototype.SolveUPieces() { var i; var mtRoot = new MoveTree(this.perm, "", FLee.UScore); var mv = this.ml.OpenBlock("Solve U Face - save one corner"); while (mtRoot.cScore < 3) { alert("Best " + mtRoot.cScore + " with " + mtRoot.stMoves + "(" + MoveTree.c + ")"); var cLevel = 0; do { mtRoot.Expand(); cLevel++; alert("Level: " + cLevel); mtBest = mtRoot.MTBest(); } while (mtBest.cScore <= mtRoot.cScore); mtRoot = mtBest; } this.Move(mtRoot.stMoves); mv.Close(); } function FLee.UScore(perm) { var cScoreBest = 0; var i, j; for (j = 0; j < 4; j++) { var cCorners = 0; var cScore = 0; for (i = 0; i < FLee.rgUCubes.length; i++) { var stCube = FLee.rgUCubes[i]; if (perm.Map(stCube) == stCube) { if (stCube.length == 3) { cCorners++; if (cCorners < 4) cScore++; } else cScore++; } } if (cScore > cScoreBest) cScoreBest = cScore; perm = perm.ApplyMoves("u"); } return cScoreBest; } MoveTree.c = 0; function MoveTree(perm, stMoves, fnScore) { this.perm = perm; this.fnScore = fnScore; this.stMoves = stMoves; this.cScore = fnScore(perm); this.rgmtChild = new Array; ++MoveTree.c; } function MoveTree.prototype.Expand() { var i; var stMoves = "lrdufbLRDUFBxyzXYZ"; if (this.rgmtChild.length == 0) { for (i = 0; i < stMoves.length; i++) { ch = stMoves.charAt(i); if (this.stMoves.charAt(this.stMoves.length-1) == ChangeCase(ch)) continue; var perm = this.perm.ApplyMoves(ch); mt = new MoveTree(perm, this.stMoves + ch, this.fnScore); this.rgmtChild.push(mt); } return; } for (i = 0; i < this.rgmtChild.length; i++) this.rgmtChild[i].Expand(); } function MoveTree.prototype.MTBest() { var i; var mtBest = this; for (i = 0; i < this.rgmtChild.length; i++) { var mt = this.rgmtChild[i].MTBest(); if (mt.cScore > mtBest.cScore) mtBest = mt; } return mtBest; } <file_sep> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta http-equiv="Content-Language" content="en-us"> <title>Koss Residence - April 2000</title> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> </head> <body style="font-family: Verdana"> <!--webbot bot="Include" U-Include="header.htm" TAG="BODY" startspan --> <table border="0" width="99%" height="112"> <tr> <td width="25%" height="106"> <p align="center"><a href="DesignWeb/images/ext03.jpg"> <img alt="ext03thmb.jpg (8851 bytes)" border="1" src="images/ext03thmb.jpg" width="128" height="96"></a></p> </td> <td width="44%" height="106"> <h1 align="center"><font face="Verdana"><a href="Default.htm">Koss Residence<br> Web</a></font></h1> </td> <td width="31%" height="106"> <p align="center"><a href="http://www.seanet.com/~harleyd/koss/images/ext02.jpg"><a href="DesignWeb/images/ext11.jpg"> <img alt="ext11thmb.jpg (8113 bytes)" border="1" src="images/ext11thmb.jpg" width="128" height="96"></a></p> </td> </tr> </table> <hr> <!--webbot bot="Include" endspan i-checksum="55442" --> <h3>April 2000</h3> <p>April is a big month for framing.&nbsp; The second floor of the main house is getting framed and the concrete beam gets formed and poured. </p> <table border="0" width="100%"> <tr> <td width="100%" align="center" valign="top" colspan="2"> <p align="right">April 1, 2000</p> <p align="left">View from across Cozy Cove...our house is flanked on the left my Richard McAniff's site (now just lawn and a trailer), and on the right by the Coles' house.</p> <p><img border="0" src="images/2000058.jpg" width="800" height="349"></p> </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000049.jpg" width="320" height="255"></td> <td width="50%" valign="top"> <p align="right">April 3, 2000</p> <p align="left">Look - it's a crow! </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000410.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">April 3, 2000</p> <p align="left">The east pool wall.&nbsp; You can see the concrete pillars on which the beam and stairs will rest. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000411.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">April 7, 2000</p> <p align="left">Kitchen ceiling joist go up. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000412.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">April 7, 2000</p> <p align="left">From the dining room ... a great day to be working outside! </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000413.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">April 7, 2000</p> <p align="left">We &quot;arborize&quot; some rhododendrons - opening up some views to the lake. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000050.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">April 7, 2000</p> <p align="left">Steel moment frame at dining room and master bedroom.&nbsp; </td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"> <p align="right">April 7, 2000</p> <p align="left">Job site as seen from <NAME>'s property.&nbsp; Richard's kitchen window mock-up is at the right.&nbsp; Click on image below for full size panorama (359K).</p> <p align="center"><a href="images/2000-04-07%20Job%20Site%20Pan.JPG"><img border="0" src="images/2000051.jpg" width="800" height="172"></a></td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000052.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">April 16, 2000</p> <p align="left">Deb's project room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000053.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">April 16, 2000</p> <p align="left">Kitchen (with dining room behind) as seen from living room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000054.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">April 16, 2000</p> <p align="left">Pool room west wall. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000055.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">April 16, 2000</p> <p align="left">Forms and scaffolding for concrete beam.&nbsp; This beam is probably one of the trickiest parts of the concrete work.&nbsp; Both the face and the bottom of the beam have a 210' radius curve; the resulting bottom edge of the beam is the intersection of two 210' cylinders.&nbsp; </p> <p align="left">We're also forming clear plastic strips into the concrete as control joints to minimize any cracking of the concrete over time.&nbsp; We have the option of either leaving the plastic strips in place (and trimming them) or pulling them out completely. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000056.jpg" width="320" height="283"></td> <td width="50%" valign="top"> <p align="right">April 18, 2000</p> <p align="left">We have some flooring on the second floor.&nbsp; Kent and John (architects) are shown here in the master bedroom discussing the upper deck construction. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000057.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">April 19, 2000</p> <p align="left">Phil (framer) standing in front of the north living room wall. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000059.jpg" width="320" height="239"></td> <td width="50%" valign="top"> <p align="right">April 26, 2000</p> <p align="left">Paul uses a man-lift to put up the north living room wall. </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> </table> <p>&nbsp;</p> <p>&nbsp; </p> </body> </html> <file_sep><html> <head> <meta name="GENERATOR" content="Microsoft FrontPage 6.0"> <title>Caribbean Cruise 1999</title> <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> </script> <script type="text/javascript"> _uacct = "UA-177353-1"; urchinTracker(); </script> <meta name="Microsoft Theme" content="global 101, default"> <meta name="Microsoft Border" content="tl, default"> </head> <body background="_themes/global/glotextb.gif" bgcolor="#CCFFFF" text="#000051" link="#336699" vlink="#669999" alink="#3399CC"><!--msnavigation--><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td><!--mstheme--><font face="arial, helvetica"> <p align="center"><font size="6"><strong><img src="_derived/index.htm_cmp_global100_bnr.gif" width="600" height="60" border="0" alt="Caribbean Cruise 1999"></strong></font><br> </p> <p align="center">&nbsp;</p> <!--mstheme--></font></td></tr><!--msnavigation--></table><!--msnavigation--><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td valign="top" width="1%"><!--mstheme--><font face="arial, helvetica"> <!--mstheme--></font></td><td valign="top" width="24"></td><!--msnavigation--><td valign="top"><!--mstheme--><font face="arial, helvetica"> <h1 align="center"><!--mstheme--><font face="Trebuchet MS, Arial, Helvetica"><!--mstheme--><b><font face="Verdana">Caribbean Cruise 1999</font><!--mstheme--></font><!--mstheme--></b></h1> <!--mstheme--></font><table border="0" width="100%"> <tr> <td width="46%" valign="top"><!--mstheme--><font face="arial, helvetica"><img src="images/Itinerary.jpg" alt="Itinerary.jpg (10737 bytes)" WIDTH="290" HEIGHT="191"><!--mstheme--></font></td> <td width="54%" valign="top"><!--mstheme--><font face="arial, helvetica"><font face="Verdana">In February of 1999, we took a one week cruise in the Caribbean on <a href="http://www.rccl.com">The Enchantment of the Seas</a>.</font><p><font face="Verdana">We had been cruising once before - about 10 years ago.&nbsp; But these ships have become quite a bit larger.&nbsp; Ours carried 1000 passengers and 400 crew members.&nbsp; And they are building even larger ships today.</font><!--mstheme--></font></td> </tr> </table><!--mstheme--><font face="arial, helvetica"> <p align="left"><font face="Verdana">This is the first vacation we've taken a friend of Chris's with us.&nbsp; Sean and Chris had their own cabin and got a real sampling of adult freedoms; the ship is a relatively safe self-contained environment so we felt safe letting them explore on their own.&nbsp; One night we said goodnight to the boys and went to bed - they promised they'd be back in their cabin by midnight; but they were on their own.</font></p> <!--mstheme--></font><table border="0" width="100%"> <tr> <td width="50%" valign="top"><!--mstheme--><font face="arial, helvetica"><p align="center"><img id="imgFull" src="images/Tulum1.jpg" WIDTH="297" HEIGHT="223"><font face="Verdana"><br> Most of the time we just enjoyed the environment of the ship.&nbsp; But we had some fun excursions as well.&nbsp; Here Chris and Sean pose in front of the Mayan ruins of Tulum.</font><!--mstheme--></font></td> <td width="50%" valign="top"><!--mstheme--><font face="arial, helvetica"><p align="center"><img id="imgFull" src="images/Tulum2.jpg" WIDTH="339" HEIGHT="254"><br> <font face="Verdana">The ruins are built above rocky cliffs overlooking the sea.&nbsp; You can climb up on one of the lookout towers and look out to sea.&nbsp; It's breathtaking.</font><!--mstheme--></font></td> </tr> </table><!--mstheme--><font face="arial, helvetica"> <p>&nbsp;</p> <!--mstheme--></font><table border="0" width="100%"> <tr> <td width="50%" valign="top"><!--mstheme--><font face="arial, helvetica"><p align="center"><img src="images/Francis.JPG" alt="Francis.JPG (25385 bytes)" WIDTH="240" HEIGHT="320"><font face="Verdana"><br> When we weren't on an excursion, we were most often <em>eating</em>!&nbsp; Francis, our beverage waiter learned the boy's favorite drinks and had them ready at the table before we even sat down.</font><!--mstheme--></font></td> <td width="50%" valign="top"><!--mstheme--><font face="arial, helvetica"><font face="Verdana"><p align="center"></font><img src="images/Orkun.JPG" alt="Orkun.JPG (17438 bytes)" WIDTH="240" HEIGHT="320"><font face="Verdana"><br> Orkun, our table waiter was a wild man - very funny.&nbsp; Here he dances for us holding an Italian flag during one of the many theme-nights in the dinning room.</font><!--mstheme--></font></td> </tr> <tr> <td width="50%" valign="top"><!--mstheme--><font face="arial, helvetica"><p align="center"><img id="imgFull" src="images/ianork.jpg" WIDTH="334" HEIGHT="251"><br> <font face="Verdana">Orkun hams it up with our cocktail waiter - Ian.</font><!--mstheme--></font></td> <td width="50%" valign="top"><!--mstheme--><font face="arial, helvetica"><p align="center"><img id="imgFull" src="images/jands.jpg" WIDTH="280" HEIGHT="210"><font face="Verdana"><br> Our dining partners - Jane, Steve,...</font><!--mstheme--></font></td> </tr> <tr> <td width="50%" valign="top"><!--mstheme--><font face="arial, helvetica"><font face="Verdana"><p align="center"><img id="imgFull" src="images/mike.jpg" width="195" height="260"><br> Mike, ...</font><!--mstheme--></font></td> <td width="50%" valign="top"><!--mstheme--><font face="arial, helvetica"><font face="Verdana"><p align="center"><img id="imgFull" src="images/matt.jpg" WIDTH="307" HEIGHT="230"><br> and Matt.</font><!--mstheme--></font></td> </tr> </table><!--mstheme--><font face="arial, helvetica"> <p>&nbsp;</p> <!--mstheme--></font><table border="0" width="100%"> <tr> <td width="37" valign="top"><!--mstheme--><font face="arial, helvetica"><img id="imgFull" src="images/ballast.jpg" WIDTH="275" HEIGHT="206"><!--mstheme--></font></td> <td width="63%" valign="top"><!--mstheme--><font face="arial, helvetica"><font face="Verdana">On a tour of the ship's bridge I was amazed to see how many of the ship's systems are controlled by off-the-shelf PC's! &nbsp; Here's a screen from the ballast control system.&nbsp; They carry spare machines in case one fails.&nbsp; I did note, however, that the fire control system was controlled by a Sun Microsystems machine...no doubt they felt it more reliable than Windows '95!</font><!--mstheme--></font></td> </tr> </table><!--mstheme--><font face="arial, helvetica"> <p>&nbsp;</p> <!--mstheme--></font><table border="0" width="100%"> <tr> <td width="50%" valign="top" align="center"><!--mstheme--><font face="arial, helvetica"><font face="Verdana"><img id="imgFull" src="images/ourroom.jpg" WIDTH="275" HEIGHT="206"><br> Our Room</font><!--mstheme--></font></td> <td width="50%" valign="top" align="center"><!--mstheme--><font face="arial, helvetica"><img id="imgFull" src="images/boysroom.jpg" WIDTH="275" HEIGHT="206"><br> <font face="Verdana">The Boy's Room</font><!--mstheme--></font></td> </tr> <tr> <td width="50%" valign="top" align="center"><!--mstheme--><font face="arial, helvetica"><font face="Verdana"><img id="imgFull" src="images/gator.jpg" WIDTH="276" HEIGHT="207"><br> Sean holds a gator in Miami</font><!--mstheme--></font></td> <td width="50%" valign="top" align="center"><!--mstheme--><font face="arial, helvetica"><!--mstheme--></font></td> </tr> <tr> <td width="50%" valign="top" align="center"><!--mstheme--><font face="arial, helvetica"><!--mstheme--></font></td> <td width="50%" valign="top" align="center"><!--mstheme--><font face="arial, helvetica"><!--mstheme--></font></td> </tr> </table><!--mstheme--><font face="arial, helvetica"> <p>&nbsp;</p> <!--mstheme--></font><table border="0" width="100%"> <tr> <td width="50%" valign="top" align="center"><!--mstheme--><font face="arial, helvetica"><font face="Verdana"><img src="images/Sean_on_Railing.JPG" alt="Sean on Railing.JPG (15902 bytes)" WIDTH="320" HEIGHT="240"><br> Sean takes a trip on the railing...</font><!--mstheme--></font></td> <td width="50%" valign="top" align="center"><!--mstheme--><font face="arial, helvetica"><font face="Verdana"><img src="images/Chris_Falling.JPG" alt="Chris Falling.JPG (13921 bytes)" WIDTH="320" HEIGHT="240"><br> Chris takes a trip <em>off</em> the railing!</font><!--mstheme--></font></td> </tr> </table><!--mstheme--><font face="arial, helvetica"> <p align="center">&nbsp;</p> <p align="left">&nbsp;</p> <p align="center"></p> <!--mstheme--></font><!--msnavigation--></td></tr><!--msnavigation--></table></body> </html> <file_sep><!DOCTYPE HTML PUBLIC "-//W3O/DTD HTML//EN"> <html> <head> <title>Fun with REPEAT</title> <meta name="GENERATOR" content="Microsoft FrontPage 6.0"> <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> </script> <script type="text/javascript"> _uacct = "UA-177353-1"; urchinTracker(); </script> </head> <body bgcolor="#FFFFFF"> <h1><img src="images/rtree.gif" align="baseline" width="135" height="112">LOGO Programming <a href="OldDefault.htm"><img src="images/mikeface.gif" align="baseline" border="0" width="100" height="141"></a></h1> <hr noshade> <h1><em>Fun with Repeat</em></h1> <p>You can have fun with the REPEAT command just by changing three numbers!</p> <p></p> <p><em><img src="images/repeat1.gif" align="bottom" width="500" height="273"></em></p> <p>Which three numbers make your favorite drawing?</p> <blockquote> <h3>CS REPEAT __ [FD ___ RT ___]</h3> </blockquote> <p>Try this! What does it draw?</p> <blockquote> <h3>CS REPEAT 100 [FD 10 RT REPCOUNT]</h3> </blockquote> <hr noshade> <address> Comments or questions? Send me <a href="mailto:<EMAIL>"> mail</a>.<br> Copyright &#169; 1996, <NAME>.<br> &#160;&#160;<br> Last revised: February 25, 1996 </address> </body> </html> <file_sep>// Intialize iteration helpers var i; Sudoku.typeRow = 1; Sudoku.typeCol = 2; Sudoku.typeBlock = 3; function Sudoku() { var i; this.rgcells = new Array; this.rgcellRows = new Array; this.rgcellCols = new Array; this.rgcellBlocks = new Array; for (i = 0; i < 9; i++) { this.rgcellRows[i] = new Array; this.rgcellRows[i].stName = "Row " + Sudoku.StNameRowCol(i, undefined); this.rgcellRows[i].type = Sudoku.typeRow; this.rgcellCols[i] = new Array; this.rgcellCols[i].stName = "Column " + Sudoku.StNameRowCol(undefined, i); this.rgcellCols[i].type = Sudoku.typeCol; this.rgcellBlocks[i] = new Array; this.rgcellBlocks[i].stName = "Block " + (i+1); this.rgcellBlocks[i].type = Sudoku.typeBlock; } for (i = 0; i < 81; i++) new Cell(this, i); this.numSet = 0; this.fPageBreak = false; this.nPass = 1; this.cCost = 0; this.fIllegal = false; this.fInitDisplay = false; this.fSilent = false; // Actions queue this.rgact = new Array; this.iactCur = 0; } Sudoku.prototype.Cell = function(row, col) { return this.rgcells[row * 9 + col]; } Sudoku.prototype.FindSingle = function(rgcell) { var num; var icell; var rgcnum; rgcnum = Sudoku.Incidence(rgcell); for (num = 1; num <=9; num++) { if (rgcnum[num] != 1) continue; for (icell = 0; icell < rgcell.length; icell++) { var cell = rgcell[icell]; if (cell.num != undefined || !cell.rgNum[num]) continue; this.Action(Action.aSet, cell, num, rgcell.stName, 9); break; } } } Sudoku.prototype.FindPairs = function(rgcell) { var i; var j; var cell; var cell2; var rgcnum; var num; var num2; var num3; rgcnum = Sudoku.Incidence(rgcell); // Look for two cells that are the only two to contain values, num, and num2. // If found, remove all other possible values from those cells. for (num = 1; num <= 9; num++) { if (rgcnum[num] != 2) continue; NextNum: for (num2 = num+1; num2 <= 9; num2++) { if (rgcnum[num2] != 2) continue; // Look for cells that have both these values for (i = 0; i < rgcell.length; i++) { cell = rgcell[i]; if (cell.num || !cell.rgNum[num] || !cell.rgNum[num2]) continue; for (j = i+1; j < rgcell.length; j++) { cell2 = rgcell[j]; if (cell2.num || !cell2.rgNum[num] || !cell2.rgNum[num2]) continue; // First remove any other possible values from those cells. for (num3 = 1; num3 <= 9; num3++) { if (num3 == num || num3 == num2) continue; var stNote = "pair " + num + "/" + num2 + " at " + cell.StName() + "/" + cell2.StName(); this.Action(Action.aExclude, cell, num3, stNote, 9); this.Action(Action.aExclude, cell2, num3, stNote, 9); } // Next, remove any redundant values of the pair if (cell.Row() == cell2.Row()) this.ExcludePairsPart(cell.row, cell, cell2); if (cell.Col() == cell2.Col()) this.ExcludePairsPart(cell.col, cell, cell2); if (cell.Block() == cell2.Block()) this.ExcludePairsPart(cell.block, cell, cell2); // No need to consider num,num2 again. rgcnum[num] = undefined; rgcnum[num2] = undefined; break NextNum; } } } } } // Colinears are cells that lie in a row or column AND are contained within a single block. // // If the cells in a block that can be a given value are all in a row, then we can exclude that number // from the rest of the row (outside the block). // Conversly, if all the cells that can be a given value in a row, are contained in a single block, then // we can exclude that number from the rest of the cells in the block. Sudoku.prototype.FindColinears = function(rgcell, num) { var cell; var i; var rgcellMatch = new Array; var fMatchRow; var fMatchCol; for (i = 0; i < rgcell.length; i++) { cell = rgcell[i]; if (cell.num != undefined || !cell.rgNum[num]) continue; rgcellMatch.push(cell); if (rgcellMatch.length == 1) continue; if (cell.Block() != rgcellMatch[0].Block()) return; if (rgcellMatch.length == 2) { fMatchRow = cell.Row() == rgcellMatch[0].Row(); fMatchCol = cell.Col() == rgcellMatch[0].Col(); if (!fMatchRow && !fMatchCol) return; continue; } if (fMatchRow && cell.Row() != rgcellMatch[0].Row()) return; if (fMatchCol && cell.Col() != rgcellMatch[0].Col()); return; } if (rgcellMatch.length < 2) return; var rgcellExclude; var stNote; if (rgcell.type == Sudoku.typeBlock) { // If we found a co-linear in a block scan, we can remove all the other values in this row(column). stNote = "value " + num + " only in block " + (rgcellMatch[0].Block()+1); if (fMatchRow) rgcellExclude = rgcellMatch[0].row; else rgcellExclude = rgcellMatch[0].col; } else { // Found co-linear in a row/column scan. Remove all other values from this block stNote = "value " + num + " must be in " + (fMatchRow ? "Row " + Sudoku.StNameRowCol(rgcellMatch[0].Row(), undefined) : "Column " + Sudoku.StNameRowCol(undefined, rgcellMatch[0].Col())); rgcellExclude = rgcellMatch[0].block; } for (i = 0; i < rgcellExclude.length; i++) { cell = rgcellExclude[i]; if (cell.num != undefined || !cell.rgNum[num]) continue; if (cell.InCells(rgcell)) continue; this.Action(Action.aExclude, cell, num, stNote, 9); } } // Catch up any outstanding commands, and then display the board. Sudoku.prototype.ExecDisplay = function(fDisplayBoard) { var stPre; var st = ""; var stChunk = ""; var fChunky = false; this.fProgress = false; if (this.iactCur < this.rgact.length) { st += "<BR/><B>Pass " + this.nPass + "</B>: "; stPre = ""; for (; this.iactCur < this.rgact.length; this.iactCur++) { var act = this.rgact[this.iactCur]; if (act.DoIt()) { if (act.a == Action.aHeading) { if (fChunky) st += stChunk; fChunky = false; stChunk = ""; stPre = "<BR/>"; } stChunk += stPre + act.StDisplay(); this.cCost += act.cCost; if (act.a == Action.aHeading) stPre = ": "; else { stPre = ", "; this.fProgress = true; fChunky = true; } } } if (fChunky) st += stChunk; st += " <I>(Total Cost = " + this.cCost + "</I>)"; } if (this.fProgress) { if (!this.fSilent) DW(st); this.nPass++; } if (fDisplayBoard && !this.fSilent && (this.fInitDisplay || this.fProgress)) DW(this.StDisplay()); this.fInitDisplay = false; this.fPageBreak = true; } Sudoku.prototype.Solve = function() { this.fInitDisplay = true; this.ExecDisplay(true); SolveLoop: while (this.numSet != 81) { if (this.fIllegal) return; do { this.ScanConstraints(); this.ExecDisplay(false); if (this.fIllegal) { this.fInitDisplay = true; break SolveLoop; } } while (this.fProgress); if (this.numSet == 81) { this.fInitDisplay = true; break SolveLoop; } // Find pairs this.Heading("Pairs"); var x; for (x = 0; x < 9; x++) { this.FindPairs(this.rgcellRows[x]); this.FindPairs(this.rgcellCols[x]); this.FindPairs(this.rgcellBlocks[x]); } // Remove co-linear numbers. this.Heading("Co-Linears"); var num; for (num = 1; num <= 9; num++) { for (x = 0; x < 9; x++) { this.FindColinears(this.rgcellRows[x], num); this.FindColinears(this.rgcellCols[x], num); this.FindColinears(this.rgcellBlocks[x], num); } } this.ExecDisplay(true); if (this.fIllegal) { this.fInitDisplay = true; break SolveLoop; } // Try backtracking solution if we get stuck with straight forward methods if (!this.fProgress) { if (!this.Guess()) break SolveLoop; this.ExecDisplay(true); } } this.ExecDisplay(true); } // Guess at a cell value. Sudoku.prototype.Guess = function() { var icell; for (icell = 0; icell < 81; icell++) { var cell = this.rgcells[icell]; if (cell.cnumPossible != 2) continue; var num; var num1 = undefined; var num2 = undefined; for (num = 1; num <= 9; num++) { if (!cell.rgNum[num]) continue; if (!num1) { num1 = num; continue; } num2 = num; break; } if (this.TryGuess(cell, num1, num2) || this.TryGuess(cell, num2, num1)) return true; return false; } return false; } Sudoku.prototype.TryGuess = function(cell, num1, num2) { var sudT = new Sudoku(); sudT.fSilent = true; sudT.Copy(this); sudT.DoSet([[cell.Row()+1, cell.Col()+1, num1]]); sudT.Solve(); if (sudT.numSet == 81) { this.Action(Action.aSet, cell, num1, "Guessing " + num1 + " will solve.", 0); return true; } if (sudT.fIllegal) { this.Action(Action.aSet, cell, num2, "Value of " + num1 + " is impossible.", sudT.cCost); return true; } return false; } Sudoku.prototype.Copy = function(sudSrc) { var icell; var cellSrc; var cellDst; this.numSet = sudSrc.numSet; this.fIllegal = sudSrc.fIllegal; for (icell = 0; icell < 81; icell++) { cellSrc = sudSrc.rgcells[icell]; cellDst = this.rgcells[icell]; cellDst.Copy(cellSrc); } } Sudoku.prototype.Action = function(a, cell, num, stNote, cCost) { this.rgact.push(new Action(a, cell, num, stNote, cCost)); if (a != Action.aHeading) this.fProgress = true; } Sudoku.prototype.Heading = function(stNote) { this.Action(Action.aHeading, null, null, stNote); } Sudoku.prototype.Illegal = function(stNote) { this.Action(Action.aError, null, null, stNote); this.fIllegal = true; } Sudoku.prototype.ScanConstraints = function() { var cell; var i; var x; // Look for cells that have been constrained to a single value. for (i = 0; i < 81; i++) { cell = this.rgcells[i]; if (cell.cnumPossible == 1) { for (num = 1; num <= 9; num++) { if (cell.rgNum[num]) { this.Action(Action.aSet, cell, num, undefined, 1); break; } } } } // Look for the only cell in a row/col/block that can be a particular value. for (x = 0; x < 9; x++) { this.FindSingle(this.rgcellRows[x]); this.FindSingle(this.rgcellCols[x]); this.FindSingle(this.rgcellBlocks[x]); } } // Input: [[rw, col, num], ... ] (1-based coordinates here) Sudoku.prototype.DoSet = function(rgset) { var iset; var set; var cell; for (iset = 0; iset < rgset.length; iset++) { set = rgset[iset]; cell = this.Cell(set[0]-1, set[1]-1); if (cell.num == set[2]) continue; if (cell.num != undefined) { alert("Error: " + cell.StName() + " can't be set to " + set[2] + " (already " + cell.num + ")"); continue; } cell.Set(set[2]); } } Sudoku.prototype.ExcludePairsPart = function(rgcell, cell1, cell2) { var i; var cell; for (i = 0; i < rgcell.length; i++) { cell = rgcell[i]; if (cell == cell1 || cell == cell2) continue; this.Action(Action.aExclude, cell, cell1.num, "pairs", 1); this.Action(Action.aExclude, cell, cell2.num, "pairs", 1); } } Sudoku.Incidence = function(rgcell) { var cell; var rgcnum = new Array(9); for (num = 1; num <= 9; num++) rgcnum[num] = 0; // Count the incidence of all digits in the block for (i = 0; i < rgcell.length; i++) { cell = rgcell[i]; if (cell.num) continue; for (num = 1; num <= 9; num++) if (cell.rgNum[num]) rgcnum[num]++; } return rgcnum; } Sudoku.ExcludeCells = function(rgcell, num) { var icell; for (icell = 0; icell < rgcell.length; icell++) { rgcell[icell].Exclude(num); } } Sudoku.prototype.StDisplay = function() { var st; var row; var col; var num; st = ""; st += "<TABLE "; if (this.fPageBreak) st += "style='page-break-before: always;' "; st += "class='Sud' CELLPADDING=0 CELLSPACING=0>"; st += "<TR><TH class='Sud'>" + this.numSet + "</TH>"; for (col = 0; col < 9; col++) { if (col != 0 && (col % 3 == 0)) st += "<TH class='Spacer'></TH>"; st += "<TH class='Sud'>" + Sudoku.StNameRowCol(undefined, col) + "</TH>"; } for (row = 0; row < 9; row++) { if (row != 0 && (row % 3 == 0)) { st += "<TR>"; st += "<TH class='Spacer'></TH>"; for (col = 0; col < 9 + 3 -1; col++) st += "<TD class='Spacer'></TD>"; st += "</TR>"; } st += "<TR>"; st += "<TH class='Sud'>" + Sudoku.StNameRowCol(row, undefined) + "</TH>"; for (col = 0; col < 9; col++) { if (col != 0 && (col % 3 == 0)) st += "<TD class='Spacer'></TD>"; st += "\n<TD class='Cell'>"; cell = this.Cell(row, col); if (cell.num != undefined) st += cell.num; else { st += "<TABLE class='Int' CELLSPACING=0 CELLPADDING=0>" for (num = 1; num <= 9; num++) { if ((num-1)%3 == 0) st += "<TR>"; st += "<TD "; if (!cell.rgNum[num]) st += "class='Excluded'>&nbsp;</TD>"; else st += ">"+ num+ "</TD>"; if ((num-1)%3 == (3-1)) st += "</TR>"; } st += "</TABLE>"; } } st += "</TR>"; } st += "</TABLE>"; return st; } Sudoku.StNameRowCol = function(row, col) { var st = ""; if (col != undefined) st += String.fromCharCode(col + "A".charCodeAt(0)); if (row != undefined) st += (row+1); return st; } function Cell(sud, i) { var num; this.sud = sud; this.i = i; sud.rgcells.push(this); this.row = sud.rgcellRows[this.Row()]; this.col = sud.rgcellCols[this.Col()]; this.block = sud.rgcellBlocks[this.Block()]; this.row.push(this); this.col.push(this); this.block.push(this); this.i = i; this.rgNum = new Array(9); for (num = 1; num <= 9; num++) this.rgNum[num] = true; this.num = undefined; this.cnumPossible = 9; } Cell.prototype.Copy = function(cellSrc) { var num; for (num = 1; num <= 9; num++) this.rgNum[num] = cellSrc.rgNum[num]; this.num = cellSrc.num; this.cnumPossible = cellSrc.cnumPossible; } Cell.prototype.Row = function() { return Math.floor(this.i/9); } Cell.prototype.Col = function() { return this.i % 9; } Cell.prototype.StName = function() { return Sudoku.StNameRowCol(this.Row(), this.Col()); } Cell.prototype.Block = function() { return Math.floor(this.Row()/3) * 3 + Math.floor(this.Col()/3); } Cell.prototype.Set = function(num) { if (this.num) { if (num == this.num) return false; this.sud.Illegal("Cell " + this.StName() + " can't be set to " + num + " (from " + this.num + ")."); return false; } if (!this.rgNum[num]) { this.sud.Illegal("Cell " + this.StName() + " can't be set to " + num + " (not legal)."); return false; } this.num = num; this.cnumPossible = 0; this.sud.numSet++; Sudoku.ExcludeCells(this.row, num); Sudoku.ExcludeCells(this.col, num); Sudoku.ExcludeCells(this.block, num); return true; } Cell.prototype.Exclude = function(num) { if (this.num != undefined) return false; if (this.rgNum[num]) { this.rgNum[num] = false; this.cnumPossible--; if (this.cnumPossible == 0) this.sud.Illegal("No possible values for cell " + this.StName()); return true; } return false; } Cell.prototype.InCells = function(rgcell) { var i; for (i = 0; i < rgcell.length; i++) { if (this == rgcell[i]) return true; } return false; } Action.aHeading = 0; Action.aSet = 1; Action.aExclude = 2; Action.aError = 3; function Action(a, cell, num, stNote, cCost) { if (cCost == undefined) cCost = 0; this.a = a; this.cell = cell; this.num = num; this.stNote = stNote; this.cCost = cCost; } Action.prototype.StDisplay = function() { var st = ""; switch (this.a) { case Action.aError: st += "<B>Error: " + this.stNote + "</B>"; return st; case Action.aHeading: st += "<B>" + this.stNote + "</B>"; return st; case Action.aSet: st += this.cell.StName() + " = " + this.num; break; case Action.aExclude: st += this.cell.StName() + " != " + this.num; break; } if (this.stNote) st += " (" + this.stNote + ")"; return st; } Action.prototype.DoIt = function() { switch (this.a) { case Action.aSet: return(this.cell.Set(this.num)); case Action.aExclude: return(this.cell.Exclude(this.num)); } return true; } <file_sep> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta http-equiv="Content-Language" content="en-us"> <title>Koss Residence - June 2000</title> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> </head> <body style="font-family: Verdana"> <!--webbot bot="Include" U-Include="header.htm" TAG="BODY" startspan --> <table border="0" width="99%" height="112"> <tr> <td width="25%" height="106"> <p align="center"><a href="DesignWeb/images/ext03.jpg"> <img alt="ext03thmb.jpg (8851 bytes)" border="1" src="images/ext03thmb.jpg" width="128" height="96"></a></p> </td> <td width="44%" height="106"> <h1 align="center"><font face="Verdana"><a href="Default.htm">Koss Residence<br> Web</a></font></h1> </td> <td width="31%" height="106"> <p align="center"><a href="http://www.seanet.com/~harleyd/koss/images/ext02.jpg"><a href="DesignWeb/images/ext11.jpg"> <img alt="ext11thmb.jpg (8113 bytes)" border="1" src="images/ext11thmb.jpg" width="128" height="96"></a></p> </td> </tr> </table> <hr> <!--webbot bot="Include" endspan i-checksum="55442" --> <h3>June 2000</h3> <p>Framing and concrete work are completed on the main house. The pool steel is in place and shot-crete is blown in.&nbsp; Next door, <NAME>'s project gets underway. </p> <table border="0" width="100%"> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000082.jpg" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">June 2, 2000</p> <p align="left">Building a platform over the pool so we don't have to use scaffolding. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/P6020018.JPG" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">June 2, 2000</p> <p align="left">Good view of the &quot;rain chute&quot; in the front courtyard. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000083.jpg" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">June 7, 2000</p> <p align="left">Our stage is available for square dances, clog dancing, and concerts.&nbsp; Please make arrangements at <a href="mailto:<EMAIL>"><EMAIL></a>. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/P6100051.JPG" width="350" height="193"></td> <td width="50%" valign="top"> <p align="right">June 10, 2000</p> <p align="left">Project site from the lake. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000084.jpg" width="350" height="418"></td> <td width="50%" valign="top"> <p align="right">June 13, 2000</p> <p align="left">The culverts for our kayak storage tubes arrives on site.&nbsp; Getting ready here to poor concrete floors before setting them in place. </td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2">3, 2, 1, ..... Blast Off! <p><img border="0" src="images/P6130060.JPG" width="500" height="320"></td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"> <p align="right">June 15, 2000</p> <p align="left">Design inspiration for our house.&nbsp; I'm going to have to have a little talk with <NAME> to understand what he's trying to imply.&nbsp; We're also going to have to order a water fountain - it looks really natural there.</p> <p><img border="0" src="images/2000085.jpg" align="left" width="350" height="251"><img border="0" src="images/2000086.jpg" width="350" height="206"></td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/keys.jpg" width="350" height="448"></td> <td width="50%" valign="top"> <p align="right">June 16, 2000</p> <p align="left">Last night all my keys dropped out of my pack and into the lake ... in 10 feet of murky lake water.</p> <p align="left">But I'm happy to report that I was able to recover them this morning.&nbsp; They look fine - but they smell a little funny. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/P6210094.JPG" width="350" height="262"></td> <td width="50%" valign="top"> <p align="right">June 21, 2000</p> <p align="left">Steel for the pool enclosure begins to go up. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/P6210154.JPG" width="350" height="398"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> </table> </body> </html> <file_sep> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta http-equiv="Content-Language" content="en-us"> <title>Koss Residence - May 2000</title> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> </head> <body style="font-family: Verdana"> <!--webbot bot="Include" U-Include="header.htm" TAG="BODY" startspan --> <table border="0" width="99%" height="112"> <tr> <td width="25%" height="106"> <p align="center"><a href="DesignWeb/images/ext03.jpg"> <img alt="ext03thmb.jpg (8851 bytes)" border="1" src="images/ext03thmb.jpg" width="128" height="96"></a></p> </td> <td width="44%" height="106"> <h1 align="center"><font face="Verdana"><a href="Default.htm">Koss Residence<br> Web</a></font></h1> </td> <td width="31%" height="106"> <p align="center"><a href="http://www.seanet.com/~harleyd/koss/images/ext02.jpg"><a href="DesignWeb/images/ext11.jpg"> <img alt="ext11thmb.jpg (8113 bytes)" border="1" src="images/ext11thmb.jpg" width="128" height="96"></a></p> </td> </tr> </table> <hr> <!--webbot bot="Include" endspan i-checksum="55442" --> <h3>May 2000</h3> <p>Framing and concrete work are completed on the main house. The pool steel is in place and shot-crete is blown in.&nbsp; Next door, <NAME>'s project gets underway. </p> <table border="0" width="100%"> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000060.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 2, 2000</p> <p align="left">Excavation begins next door. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000061.jpg" width="320" height="267"></td> <td width="50%" valign="top"> <p align="right">May 2, 2000</p> <p align="left">Ray (project manager for both projects), Doug (next-door supervisor), and <NAME>. have a discussion on Doug's elaborate &quot;construction porch&quot;. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000062.jpg" width="320" height="239"></td> <td width="50%" valign="top"> <p align="right">May 2, 2000</p> <p align="left">Waterproofing and drain for walkway and &quot;water-feature&quot; in courtyard. </td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"> <p align="right">May 2, 2000</p> <p align="left">Beam is stripped - but still supported by scaffolding.</p> <p><img border="0" src="images/2000063.jpg" width="640" height="480"></td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000064.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 3, 2000</p> <p align="left">Beginning framing on Chris's bedroom and guest bedroom. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000065.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 3, 2000</p> <p align="left">View from guest bedroom. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000066.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 3, 2000</p> <p align="left">House from the dock. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000067.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 5, 2000</p> <p align="left">Guest and Chris bedroom framing. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000068.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 5, 2000</p> <p align="left">Living room ceiling joists. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000069.jpg" width="320" height="212"></td> <td width="50%" valign="top"> <p align="right">May 12, 2000</p> <p align="left">Lunch spread for our &quot;topping-out&quot; party.&nbsp; The house is all framed now! </td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"><img border="0" src="images/2000070.jpg" width="640" height="480"></td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000510.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 12, 2000</p> <p align="left">Pipes coming into the mechanical room for the pool equipment. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000511.jpg" width="320" height="421"></td> <td width="50%" valign="top"> <p align="right">May 12, 2000</p> <p align="left">Climbing the rafters in Chris's room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/kd1.jpg" width="320" height="426"> <p><img border="0" src="images/kd2.jpg" width="320" height="240"></p> <p><img border="0" src="images/kd3.jpg" width="297" height="279"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">While cleaning up the site, we found a Killdeer (<i><a href="http://encarta.msn.com/find/Concise.asp?z=1&amp;pg=2&amp;ti=761556918">Charadrius vociferus</a>)</i> nest.&nbsp; <NAME> carefully marked out the area with paint and boards.&nbsp; Even though we had some big machinery just a few feet from the nest, the parents did not give up on it and the babies hatched on May 25th.</p> <p align="center">&nbsp;</p> <p align="center"><img border="0" src="images/kd4.jpg" width="185" height="133"></p> <p align="center"><img border="0" src="images/kd5.jpg" width="351" height="255"></p> <p align="center"><img border="0" src="images/kd6.jpg" width="266" height="402"> </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000072.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">North-west corner of the house (study on main floor, guest room and Chris's room above). </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000073.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">The &quot;super-highway&quot;.&nbsp; We have room for two lanes of traffic in our north setback - great access to the lake if we decide to bring a drive down (current plan is grass and plantings only). </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000512.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">The study has a south-facing glass wall into the courtyard.&nbsp; The center section will hold an operable sliding glass door. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000513.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">View from just inside the front door, looking along the main first-floor hallway to the north.&nbsp; The stairs at the end lead up to the guest bedroom and Chris's room.&nbsp; When the house is complete, there will be a &quot;bridge&quot; spanning the space on the second floor. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000514.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">View from the front entrance.&nbsp; This is our &quot;entry-hall&quot;.&nbsp; The stairway to the second floor that is here now is temporary - the final stair is build from steel stringers and will connect into the second floor bridge. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000515.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">Dining room (facing south). </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000516.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">This won't be a view you'll normally be able to see.&nbsp; I'm standing on top of scaffolding at the east end of the living room, looking back to the west. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000517.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">Site cleanup (Killdeer nest is visible just behind the loader's cab). </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000518.jpg" width="320" height="426"> <p><img border="0" src="images/20000524.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">North living room wall.&nbsp; The opening at the bottom is for a fireplace.&nbsp; The slot above will bring reflected light into the living room.&nbsp; The final product will look something like the computer generated image below (from the <a href="images/fireplace.jpg">Design Web</a>).</p> <p align="center"><img src="images/fireplace.jpg" width="286" height="439"> </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000519.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">North end of pool room has concrete block-outs for ventilation and diving board plinth. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000520.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">Chris's bedroom window. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000521.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">Spa plumbing. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000071.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">Pool steel and piping in place. </td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"><img border="0" src="images/20000523.jpg" width="640" height="480"></td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="1" src="images/20000525.jpg" width="320" height="211"><br> <img border="1" src="images/20000527.jpg" width="320" height="149"><br> <img border="1" src="images/20000529.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">A couple of boats from the &quot;marina&quot; at the south end of Cozy Cove. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000526.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">Excavation progress on Richard's lot. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000528.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">Scaffolding from beam is gone. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000530.jpg" width="320" height="187"> <p><img border="0" src="images/20000531.jpg" width="320" height="154"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">More fun toys.&nbsp; The top one reminds me the Flintstone's car! </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000532.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 17, 2000</p> <p align="left">We haven't done anything here yet - this is how the driveway looks now.&nbsp; It's taken quite a beating with dump trucks and other heave vehicles running over it these last six months. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000533.jpg" width="320" height="217"></td> <td width="50%" valign="top"> <p align="right">May 18, 2000</p> <p align="left">Chris in the media room.&nbsp; The movie screen will descend from ceiling at the far end of the room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000534.jpg" width="320" height="275"></td> <td width="50%" valign="top"> <p align="right">May 18, 2000</p> <p align="left">Barb and Steve bring their new boat (<i>Andante</i>) to our dock to take us on a cruise.&nbsp; Happily, she <i>fits</i> in our dock slip - but only just.</p> <p align="left">Click on the image below to see the full size image of the Seattle skyline from Lake Union (167K bytes).</p> <p align="center"><a href="images/p5190142.jpg"><img border="0" src="images/20000537.jpg" width="320" height="240"></a> </td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"><img border="0" src="images/20000535.jpg" width="640" height="480"> <p><img border="0" src="images/20000536.jpg" width="640" height="366"></td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000539.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 23, 2000</p> <p align="left"><a href="http://www.spunstrand.com/main.html">Spunstrand</a> ductwork installation at north pool wall. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000540.jpg" width="320" height="265"> <p><img border="0" src="images/20000541.jpg" width="320" height="297"></td> <td width="50%" valign="top"> <p align="right">May 23, 2000</p> <p align="left">Chris is thrilled to receive his <a href="http://www.krekowjennings.com/">Krekow Jennings</a> customized hard hat.</p> <p align="center"><img alt="pig2.jpg (2536 bytes)" src="images/pig3.jpg" width="110" height="74"></p> <p align="center">&nbsp; </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000076.jpg" width="320" height="240"> <p><img border="0" src="images/2000074.jpg" width="320" height="426"></p> <p><img border="0" src="images/2000075.jpg" width="320" height="268"></td> <td width="50%" valign="top"> <p align="right">May 24, 2000</p> <p align="left">Now that the steel and plumbing are complete in the pool, it has to be filled with concrete.&nbsp; Concrete (or <a href="http://scrpa.com/shotcrete.html">shotcrete</a>) is sprayed through a hose under 500 lbs of air pressure.&nbsp; It takes over 90 yards of concrete to finish the job (which all has to be complete in one day for structural integrity)...it was a <i>very</i> long day getting this done.</p> <p align="center"><img border="0" src="images/2000077.jpg" width="170" height="94"> </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000078.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 24, 2000</p> <p align="left">Spunstrand in place (and Easter-Egg'ed). </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000079.jpg" width="320" height="224"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left">Here I am, swimming in the deep end (some might say <i>I'm off the deep end</i>). </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000080.jpg" width="320" height="274"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left">Kent and Mike inspect the spa wall. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000081.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left">Mock-up of pool ceiling.&nbsp; We're using <a href="http://www.eco-products.com/siding.htm">HardiPlank</a> boards (in the final installation they'll be stained/painted - here they are untreated) over a layer of Tectum wall panel (<a href="http://www.tectum.com/">Tectum</a> makes a sound absorbing material that looks like shredded wheat or compressed string).</p> <p align="left">Protruding through the ceiling we have an array of custom-made light fixtures that use a low-voltage bulb behind a solid hemisphere of cast glass. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000545.jpg" width="320" height="170"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left">Stone samples for the pool deck.&nbsp; We're using a variegated blue stone in a running bond pattern.&nbsp; The large (and thicker) pieces will be used as coping around the pool. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000542.jpg" width="320" height="296"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left"><b>Contest: </b>Explain this image.&nbsp; What is it, and what's special about it? </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000543.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left">Rhododendrons in bloom along our south property line. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000544.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left">The &quot;front&quot; yard is cleaned up. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000546.jpg" width="320" height="199"> <p><img border="0" src="images/20000547.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left">Concrete stairs coming off of the deck. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000548.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left">Concrete-closet under the deck. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000549.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">May 25, 2000</p> <p align="left">Spa filled with concrete. </td> </tr> </table> <p>&nbsp;</p> <p>&nbsp; </p> </body> </html> <file_sep>// Statistics gathering and display function Stats(eltParent, rg) { this.eltParent = eltParent; this.mp = {}; for (var i = 0; i < rg.length; i++) new Stat(this, rg[i]); } Stats.prototype = { Sample: function(stName, value, fSpark) { var stat = this.mp[stName]; if (!stat) stat = new Stat(this, stName, fSpark); stat.Sample(value); }, Update: function() { for (var prop in this.mp) this.mp[prop].Update(); }, Reset: function() { for (var prop in this.mp) this.mp[prop].Reset(); }, } // Stats.protoype Stat.dxSpark = 400; Stat.dySpark = 100; function Stat(stats, stName, fSpark) { this.stats = stats; this.stName = stName; this.fSpark = fSpark; this.Reset(); this.SetMode("VNAXC"); stats.eltParent.appendChild(document.createTextNode(stName + ": ")); this.spn = document.createElement("span"); stats.eltParent.appendChild(this.spn); stats.eltParent.appendChild(document.createElement("BR")); if (fSpark) { this.rgv = []; this.xSpark = 0; this.yMin = 0; this.yMax = 1; this.canvas = document.createElement("canvas"); this.canvas.setAttribute("height", Stat.dySpark); this.canvas.setAttribute("width", Stat.dxSpark); this.ctx = this.canvas.getContext("2d"); stats.eltParent.appendChild(this.canvas); stats.eltParent.appendChild(document.createElement("BR")); } stats.mp[this.stName] = this; } Stat.prototype = { SetMode: function(mode) { this.mode = mode; }, Reset: function() { this.value = undefined; this.c = 0; this.sum = 0; }, Sample: function(value) { // BUG: Should allow for "missing" values - but for now, just // skip. if (value == Infinity || value == undefined) return; this.c++; this.value = value; this.sum += value; if (this.c == 1) { this.min = value; this.max = value; return; } if (value < this.min) this.min = value; if (value > this.max) this.max = value; }, Update: function() { if (this.c == 0) { this.spn.textContent = "N/A"; return; } var st = ""; if (this.c == 1 && this.mode.indexOf("V") != -1) st += this.value.toFixed(1); var stSep = " "; if (this.c > 1) { if (this.mode.indexOf("A") != -1) { st += stSep + (this.sum/this.c).toFixed(1); stSep = " ["; } else stSep = "["; if (this.mode.indexOf("N") != -1) { st += stSep + this.min.toFixed(1); stSep = " "; } if (this.mode.indexOf("X") != -1) st += stSep + this.max.toFixed(1); stSep = "] "; if (this.mode.indexOf("C") != -1) { st += stSep + "of " + this.c; stSep = ""; } st += stSep; } this.spn.textContent = st; if (this.fSpark) { var value = this.c > 1 ? this.sum/this.c : this.value; this.rgv[this.xSpark++] = value; if (value > this.yMax) this.yMax = value; if (value < this.yMin) this.yMin = value; if (this.xSpark >= Stat.dxSpark) this.xSpark = 0; this.ctx.strokeStyle = "black"; this.ctx.clearRect(0, 0, Stat.dxSpark, Stat.dySpark); this.ctx.strokeRect(0, 0, Stat.dxSpark, Stat.dySpark); var xFirst = this.xSpark == this.rgv.length ? 0 : this.xSpark + 1; if (xFirst == Stat.dxSpark) xFirst = 0; var scale = Stat.dySpark/(this.yMax-this.yMin); this.ctx.beginPath(); var xDraw = 0; this.ctx.moveTo(xDraw++, (this.rgv[xFirst]-this.yMin)*scale); for (var x = xFirst+1; x != this.xSpark; x++) { if (x == Stat.dxSpark) { x = -1; continue; } this.ctx.lineTo(xDraw++, Stat.dySpark - (this.rgv[x]-this.yMin)*scale); } this.ctx.stroke(); } }, } // Stat.prototype <file_sep>// Evolution Game/Simulation // // Copyright (c) 2007 by <NAME> and <NAME> Evo.AttrLimits = {rFemale: 1, rRepro: 1, rOffspring: 1, fullthresh: 100, prChangeDir: 1}; function Evo(options) { this.options = { EnergyFract: 0.00, // Ambient energy fraction/day per mesh grid EnergyConst: 40, // Additional ambient energy per mesh grid StartEnergy: 100, // Organism's starting energy StartDensity: 6, // Number of organisms per mesh square to start MeshStartEnergy: 100, // Starting ambient energy level MaxAge: 4000, // Probility of death as ratio of MaxAge MeshSize: 50, // Mes size dxWorld: 300, // World size dyWorld: 300, StatsUpdateRate: 1, // Number of Days between refresh GradientUpdateRate: 1, // Gradient update display rate heritable : { // Default organism heritable traits speed: 1, size: 1, offspringnum: 10, // The number of children reproduced preysize: 0.5, fullthresh: 100, rFemale: 0.5, // Proportion of offspring that are female rRepro: 0.1, // Proportion of maxenergy needed to reproduce rOffspring: 0.5, // Proportion of energy that can be given to offspring Gestation: 10, // Interval a female must wait to reproduce again FertileAge: 10, // Number of days before female is fertile prChangeDir: 0.1, // Probability of changing direction each day }, }; Extend(this.options, options); this.oldestOrg = null; this.msLast = new Date(); this.gen = 0; this.orgLoopDir = 0; this.organisms = []; this.mpCauses = {}; this.gz = new GraphZones(25, 25, this.options.dxWorld); // The visible stage into which the simulation is displayed this.canvasWorld = document.createElement("canvas"); this.canvasWorld.setAttribute("width", this.options.dxWorld); this.canvasWorld.setAttribute("height", this.options.dyWorld); this.canvasWorld.globalCompositeOperation = "xor"; this.ctx = this.canvasWorld.getContext("2d"); // Offscreen canvas for the drawing of static creatures this.canvasStatic = document.createElement("canvas"); this.canvasStatic.setAttribute("width", this.options.dxWorld); this.canvasStatic.setAttribute("height", this.options.dyWorld); this.ctxStatic = this.canvasStatic.getContext("2d"); this.ctxStatic.globalCompositeOperation = "xor"; this.canvasEnergy = document.createElement("canvas"); this.canvasEnergy.setAttribute("width", this.options.dxWorld); this.canvasEnergy.setAttribute("height", this.options.dyWorld); this.ctxEnergy = this.canvasEnergy.getContext("2d"); this.mesh = new Mesh(this.options.MeshSize, this.options.MeshSize, this.options.dxWorld, this.options.dyWorld, {Gradient: true}); this.mesh.SetPly("energy", [0x7A, 0xD6, 0xD9], [0xF9, 0xFF, 0x1D], 100); var self = this; this.mesh.EnumPoints("energy", function (pt, x, y) { pt.value = self.options.MeshStartEnergy; } ); } Evo.prototype = { Init: function(stWorld, stStats) { this.divWorld = document.getElementById(stWorld); this.divWorld.appendChild(this.canvasWorld); if (this.options.DebugCanvas) { this.divWorld.appendChild(this.canvasStatic); this.divWorld.appendChild(this.canvasEnergy); } this.divStats = document.getElementById(stStats); this.btnPause = document.createElement("input"); with (this.btnPause) { type = "button"; value = "Pause"; onclick = this.PauseToggle.FnCallback(this); } this.divStats.appendChild(this.btnPause); this.divStats.appendChild(document.createElement("br")); this.stats = new Stats(this.divStats, ["Day"]); this.mesh.options.stats = this.stats; var cOrg = this.options.StartDensity*(this.mesh.colMax-1)*(this.mesh.rwMax-1); for (var i = 0; i < cOrg; i++) this.AddOrganism(); this.PauseToggle(); return this; }, AddOrganism: function(orgMother, orgFather, energy) { var org = new Organism(this, orgMother, orgFather, energy); this.organisms.push(org); return org; }, UpdateCatch: function() { try { this.Update(); } catch (e) { console.log(e); } }, Update: function() { if (this.fInUpdate) return; this.fInUpdate = true; //alternates direction of enumeration to be "fair" to young and old, alike. if(this.orgLoopDir == 0) { for (var i = 0; i < this.organisms.length; i++) this.organisms[i].Update(this); this.orgLoopDir == 1; } else { for (var i = 0; i < this.organisms.length; i++) this.organisms[this.organisms.length-i].Update(this); this.orgLoopDir == 0; } this.ProcessCollisions(); this.GarbageCollect(); var msNew = new Date(); var ms = msNew - this.msLast; this.msLast = msNew; this.stats.Sample("FPS", 1000/ms, true); if (this.gen % this.options.StatsUpdateRate == 0) { this.Survey(); this.stats.Update(); this.stats.Reset(); if (this.organisms.length == 0) this.PauseToggle(); } var self = this; this.mesh.EnumPoints("energy", function (pt, x, y) { if (x == 0 || y == 0 || x == self.options.dxWorld || y == self.options.dyWorld) return; pt.value += (100-pt.value)*self.options.EnergyFract + self.options.EnergyConst; if (pt.value > 100) pt.value = 100; self.stats.Sample("field energy", pt.value); }); if (this.gen % this.options.GradientUpdateRate == 0) this.mesh.DrawGradient("energy", this.ctxEnergy); this.ctx.drawImage(this.canvasEnergy, 0, 0); this.ctx.drawImage(this.canvasStatic, 0, 0); this.DrawAll(); this.gen++; this.fInUpdate = false; }, PauseToggle: function() { if (this.timer) { clearInterval(this.timer); delete this.timer; return; } this.timer = window.setInterval(this.UpdateCatch.FnCallback(this), 10); }, Survey: function() { var cStatic = 0; var cFemale = 0; var cTotal = this.organisms.length; this.stats.Sample("Day", this.gen); this.stats.Sample("Organisms", this.organisms.length, true); for (var i = 0; i < cTotal; i++) { var org = this.organisms[i]; this.stats.Sample("Size", org.h.size); this.stats.Sample("Prey size", org.h.preysize); this.stats.Sample("Energy", org.energy); console.assertBreak(org.energy > 0); this.stats.Sample("Metabolism", org.dailyenergy); this.stats.Sample("Max Energy", org.h.maxenergy); this.stats.Sample("growtimer", org.growtimer); this.stats.Sample("Offspring", org.h.offspringnum); this.stats.Sample("Max Speed", org.h.speed); this.stats.Sample("Current Speed", org.currentspeed); this.stats.Sample("Move threshold", org.h.fullthresh); this.stats.Sample("Age", org.age); this.stats.Sample("Generation", org.gen); this.stats.Sample("Female Repro (%)", 100*org.h.rFemale); this.stats.Sample("Req Repro Energy (%)", 100*org.h.rRepro); this.stats.Sample("Energy Offspring (%)", 100*org.h.rOffspring); this.stats.Sample("Gestation", org.h.Gestation); this.stats.Sample("Fertile Age", org.h.FertileAge); this.stats.Sample("Change Dir (%)", 100*org.h.prChangeDir); if (org.currentspeed == 0) cStatic++; if (org.gender == 0) cFemale++; } this.stats.Sample("Static", cStatic); this.stats.Sample("Females (%)", 100*cFemale/cTotal, true); }, GarbageCollect: function() { for (var i = this.organisms.length-1; i >= 0; i--) { var org = this.organisms[i]; if (org.fDead) { if (this.mpCauses[org.cause] == undefined) this.mpCauses[org.cause] = 0; this.mpCauses[org.cause]++; // Remove dead creature from the static canvas if (org.xStatic != undefined) org.DrawCtx(this.ctxStatic); this.stats.Sample("Life Span", org.age); delete this.organisms[i]; this.organisms.splice(i, 1); this.gz.Remove(org); } } for (var prop in this.mpCauses) { this.stats.Sample("Death by " + prop, this.mpCauses[prop], true); this.mpCauses[prop] = 0; } }, DrawAll: function() { for (var i = 0; i < this.organisms.length; i++) this.organisms[i].Draw(); }, ProcessCollisions: function() { var phase = this.gen % 5; for (var i = 0; i < this.organisms.length; i++) { var org = this.organisms[i]; if ((org.id % 5) == phase) this.gz.ProcessCollisions(org, this.CollisionFound.FnCallback(this)); } }, CollisionFound: function(org1, org2) { org1.fCollision = true; org2.fCollision = true; if (Math.abs(org1.h.size - org2.h.size) < 0.25 && org1.gender != org2.gender) { if (org1.growtimer == 0 && org2.growtimer == 0) { if (org1.gender == 0) org1.Reproduce(org2); else org2.Reproduce(org1); } return; } if(org1.h.preysize >= org2.h.size) org1.Eat(org2); else if (org2.h.preysize >= org1.h.size) org2.Eat(org1); }, } // Evo.prototype Organism.idNext = 0; function Organism(evo, orgMother, orgFather, energy) { this.evo = evo; this.h = {}; if (orgMother) { Combine(this.h, orgMother.h, orgFather.h); // Mutations are common and extensive for (var prop in this.h) this.h[prop] *= (0.75 + Math.random()*0.5); this.h.preysize = Math.min(this.h.preysize, this.h.size); for (var prop in Evo.AttrLimits) { if (this.h[prop] > Evo.AttrLimits[prop]) this.h[prop] = Evo.AttrLimits[prop]; } this.gen = Math.max(orgMother.gen, orgFather.gen)+1; this.x = orgMother.x+Math.RandomInt(10)-5; this.y = orgMother.y+Math.RandomInt(10)-5; this.growtimer = this.h.FertileAge; this.energy = energy; } else { Extend(this.h, this.evo.options.heritable); this.gen = 0; this.x = Math.RandomInt(this.evo.options.dxWorld); this.y = Math.RandomInt(this.evo.options.dyWorld); this.growtimer = 0; this.energy = this.evo.options.StartEnergy; } // Calc radius only needed on creation this.r = Math.round(Math.sqrt(this.h.size * 5)); if (this.r > 50) this.r = 50; this.id = Organism.idNext++; // Female == 0, Male == 1 this.gender = Math.random() < this.h.rFemale ? 0 : 1; this.age = 0; this.fDead = false; this.currentspeed = this.h.speed; this.NewDir(); this.EnergyUpdate(); this.evo.stats.Sample("Birth energy", this.energy); } Organism.prototype = { EnergyUpdate: function() { // Energy requirements this.h.maxenergy = this.h.size*100; this.dailyenergy = Math.pow(this.currentspeed, 2) + Math.pow(this.h.size,2); if (this.dailyenergy < 1) this.dailyenergy = 1; this.energy = Math.min(this.energy, this.h.maxenergy); this.energy -= this.dailyenergy; // You're dead with no energy - or, with increasing probability as you // approach MaxAge. if (this.energy < 1) { this.fDead = true; this.cause = "starvation"; } if (Math.random() < this.age/this.evo.options.MaxAge) { this.fDead = true; this.cause = "random"; } }, NewDir: function() { this.dir = Math.random()*2*Math.PI; this.dx = this.currentspeed * Math.cos(this.dir); this.dy = this.currentspeed * Math.sin(this.dir); }, Draw: function() { if (this.fDead) return; if (this.xStatic) { if (this.xStatic == this.x && this.yStatic == this.y) return; var xSav = this.x; var ySav = this.y; this.x = this.xStatic; this.y = this.yStatic; delete this.xStatic; delete this.yStatic; this.DrawCtx(this.evo.ctxStatic); this.x = xSav; this.y = ySav; } var ctx = this.evo.ctx; // HACK: Canvas is not erasing partially off left edge - so we // choose not to cache those static organisms hanging off the left // edge. if (this.currentspeed == 0 && this.x > this.r) { // Canvas does not draw fractional coordinates deterministicly - so we get // imperfect erasure. Ensur that coordinates are integer when the org // becomes static. this.x = Math.floor(this.x); this.y = Math.floor(this.y); this.xStatic = this.x; this.yStatic = this.y; ctx = this.evo.ctxStatic; } this.DrawCtx(ctx); }, DrawCtx: function(ctx) { ctx.beginPath(); if (this.fCollision) ctx.fillStyle = "red"; else if (this.energy > this.h.rRepro * this.h.maxenergy && this.growtimer == 0) ctx.fillStyle = this.gender == 0 ? "purple" : "blue"; else ctx.fillStyle = "gray"; // ctx.lineWidth = 0; // ctx.arc(this.x, this.y, this.r, 0, Math.PI*2, false); // ctx.closePath(); ctx.fillRect(this.x - this.r, this.y - this.r, 2*this.r, 2*this.r); // ctx.fill(); }, Update: function() { this.x = this.x + this.dx; this.y = this.y + this.dy; this.age++; if(Math.RandomInt(100) == 0) this.NewDir(); this.x = (this.x + this.evo.options.dxWorld) % this.evo.options.dxWorld; this.y = (this.y + this.evo.options.dyWorld) % this.evo.options.dyWorld; console.assert(this.x >= 0 && this.y >= 0); this.evo.gz.Move(this); this.fCollision = false; this.growtimer = Math.max(0, this.growtimer-1); var eAppetite = Math.max(0, this.h.maxenergy - this.energy); var info = this.evo.mesh.GetPtInfo("energy", this.x, this.y); eAppetite = Math.min(info.valTri, eAppetite); if (eAppetite >= 1) { var eEat = this.evo.mesh.AddValue("energy", this.x, this.y, -eAppetite, info); console.assertBreak(eEat <= 0); this.evo.stats.Sample("Eat Amount", -eEat, true); this.energy -= eEat; } if (this.currentspeed > 0 && this.gender == 0 && info.valTri > eAppetite + this.h.fullthresh) { this.currentspeed = 0; this.NewDir(); } else if (this.currentspeed <= 0 && info.valTri < eAppetite + this.h.fullthresh) { this.currentspeed = this.h.speed; this.NewDir(); } if (this.currentspeed > 0 && Math.random() < this.h.prChangeDir) this.NewDir(); this.EnergyUpdate(); }, Eat: function(prey) { console.assert(this != prey); this.energy += prey.energy; prey.energy = 0; prey.fDead = true; prey.cause = "predation"; this.evo.stats.Sample("eaten size", prey.h.size); this.evo.stats.Sample("eater size", this.h.size); }, Reproduce: function(male) { if (this.energy > this.h.maxenergy*this.h.rRepro && this.growtimer == 0) { var availenergy = this.energy * this.h.rOffspring; this.energy -= availenergy; console.assert(this.energy >= 0); this.growtimer = this.h.Gestation; var cOffspring = Math.round(this.h.offspringnum); for (var i = 0; i < cOffspring; i++) this.evo.AddOrganism(this, male, availenergy / cOffspring); this.EnergyUpdate(); } }, FCollision: function(orgOther) { if (this.id > orgOther.id) return false; var rad = orgOther.r + this.r; var dist = Math.sqrt(Math.pow(orgOther.x - this.x, 2) + Math.pow(orgOther.y - this.y, 2)); return (dist < rad); } } // Organism.prototype <file_sep> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> </head> <body> <p>Our current living room sofa:</p> <p><img src="images/livingroom%20sofa.jpg" width="350" height="262"></p> <p>Living room chair:</p> <p><img border="0" src="images/livingroom%20chair.jpg" width="350" height="466"></p> <p>This is my office chair - mine is covered in leather.<br> <i>RJones (Dallas - 214-951-0091)<br> Remington </i><i>#2432 with 25/75 Foam/Down Fill.<br> 32&quot; W x 33&quot; D x 31&quot; H, 16 1/2 &quot; Seat Height</i></p> <p><img border="0" src="images/Office_Chair.jpg" width="350" height="324"></p> <p>We have two of these chairs at home:</p> <p><img border="0" src="images/black%20chair.jpg" width="350" height="376"></p> <p>And this is an end table we have at home.</p> <p><img border="0" src="images/end%20table.jpg" width="350" height="355"></p> <p>&nbsp;</p> </body> </html> <file_sep> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta http-equiv="Content-Language" content="en-us"> <title>Koss Residence</title> <meta name="GENERATOR" content="Microsoft FrontPage 6.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> <script src="http://www.google-analytics.com/urchin.js" type="text/javascript"> </script> <script type="text/javascript"> _uacct = "UA-177353-1"; urchinTracker(); </script> <script> var fUseDHTML = (navigator.appVersion.indexOf("MSIE") != -1); function Refresh() { // window.navigate(window.location.href); } var tm = 0; function InitUpdateTimer() { if (fUseDHTML) { tm = setInterval(UpdateTime, 1000); GetNextUpdateTime(); } } var dateNext = new Date; var dtimeInterval = 15*60*1000; var dtimeLag = 5*60*1000; function GetNextUpdateTime() { var date = new Date; date.setTime(date.getTime() - dtimeLag); dateNext.setTime(Math.ceil(date.getTime()/dtimeInterval)*dtimeInterval + dtimeLag); } function UpdateTime() { var date = new Date; var stMerid; var dtick = dateNext.getTime() - date.getTime(); if (dtick < 0) { if (AutoRefresh.checked) Refresh(); } var hr = date.getHours(); if (hr < 12) stMerid = "am"; else stMerid = "pm"; if (hr == 0) hr = 12; if (hr > 12) hr -= 12; TimeNow.innerText = hr + ":" + Digits2(date.getMinutes()) + " " + stMerid; if (dtick >= 0) { var secs = Math.floor(dtick/1000); var min = Math.floor(secs/60); secs = secs % 60; TimeRemaining.innerText = min + ":" + Digits2(secs); } // Move-in Countdown timer ... sorry, <NAME>! MoveCounter.innerText = StCountdown(new Date(2001, 5, 15, 17)); } function Digits2(num) { if (num >= 10) return num; return "0" + num; } function StCountdown(dtFuture) { var dtNow = new Date(); var msDiff = dtFuture.getTime() - dtNow.getTime(); if (msDiff < 0) return("Complete!"); var msSec = 1000; var msMinute = msSec*60; var msHour = msMinute*60; var msDay = msHour * 24; var days = Math.floor(msDiff/msDay); msDiff %= msDay; var hrs = Math.floor(msDiff/msHour); msDiff %= msHour; var min = Math.floor(msDiff/msMinute); msDiff %= msMinute; var sec = Math.floor(msDiff/msSec); return(days + " days " + hrs + " hours " + min + " minutes " + sec + " seconds"); } </script> </head> <body onload="InitUpdateTimer();" style="font-family: Verdana"> <!--webbot bot="Include" U-Include="header.htm" TAG="BODY" startspan --> <table border="0" width="99%" height="112"> <tr> <td width="25%" height="106"> <p align="center"><a href="DesignWeb/images/ext03.jpg"> <img alt="ext03thmb.jpg (8851 bytes)" border="1" src="images/ext03thmb.jpg" width="128" height="96"></a></p> </td> <td width="44%" height="106"> <h1 align="center"><font face="Verdana"><a href="Default.htm">Koss Residence<br> Web</a></font></h1> </td> <td width="31%" height="106"> <p align="center"><a href="http://www.seanet.com/~harleyd/koss/images/ext02.jpg"><a href="DesignWeb/images/ext11.jpg"> <img alt="ext11thmb.jpg (8113 bytes)" border="1" src="images/ext11thmb.jpg" width="128" height="96"></a></p> </td> </tr> </table> <hr> <!--webbot bot="Include" endspan i-checksum="55442" --><table border="0" width="100%"> <tr> <td width="100%" valign="top" colspan="2"></td> </tr> <tr> <td width="25%" valign="top"> <img border="1" src="images/Ground%20Breaking.JPG" align="left" hspace="4" vspace="4" width="144" height="255"></td> <td width="75%" valign="top"><b>Ground-Breaking Ceremony<br> </b> October 22, 1999 <p>We officially broke ground on our new house construction project.&nbsp; The architects hosted a ground breaking ceremony at the property that (foggy) Friday.&nbsp; We hope to move in around <strike> May</strike> June 2001.</p> <p>We now have a firm move-in scheduled for 5 pm on June 15, 2001.</p> <p><b>Countdown Timer: <SPAN ID=MoveCounter>...</SPAN></b></p> <p><font face="Verdana">Visit our </font><font face="Verdana"> <a href="DesignWeb">Design Web</a> for computerized images of the house design.</font> <p><font face="Verdana">If you're working on this project (or if you're a friend or family member and would like to notified as I update this site), I'd like to invite you to visit the <a href="http://communities.msn.com/KossResidence">Koss Residence Community</a> web site.&nbsp;</font></td> </tr> </table> <table border="0" width="100%"> <tr> <td width="25%" valign="top"><b>View from Yarrow Point</b><br> November, 2000 <p align="center">&nbsp;</td> <td width="75%" valign="top"><img border="1" src="images/yphouse2.jpg" width="500" height="292"> </td> </tr> <tr> <td width="25%" valign="top">September, 2001</td> <td width="75%" valign="top"><img border="1" src="images/houseflag.jpg" width="500" height="375"></td> </tr> <tr> <td width="50%" valign="top"> <h3>Web Cam out of Service</h3> <p><font size="1">We've gotten far enough along in the project that the web-cams were getting in the way of construction - so we've had to take them down.</font></p> <p><font size="1">I plan to update the site with a movie made from all the web cam images.</font></p> <p><font size="1"><i><font face="Verdana">Our friends are building a home in Australia - you can visit their <a href="http://www.noorinya.com/">web cam</a> to get your fix of construction web cam viewing.</font></i><script> if (fUseDHTML) { var st = "<input type=checkbox ID=AutoRefresh checked>Automatic Page Refresh"; st += "<br><i>Time now: <SPAN ID=TimeNow>00:00</SPAN>&nbsp;-&nbsp;next update in <SPAN ID=TimeRemaining>00:00</SPAN></I>"; document.write(st); } </script> </font></p> <p><i><a href="WebCamCycler.htm"><font size="1">Web Cam Image Cycler</font></a></i></td> <td width="50%" valign="top"><font face="Verdana"> <IMG SRC="images/trailer.jpg" width="320" height="240"> </font></td> </tr> </table> <hr> <h3>Construction Pictures</h3> <table border="0" width="100%"> <tr> <td width="31%" valign="top"><a href="199911.htm">November, 1999</a></td> <td width="69%">Excavation.</td> </tr> <tr> <td width="31%" valign="top"><a href="199912.htm">December 1999</a></td> <td width="69%">Site work.</td> </tr> <tr> <td width="31%" valign="top"><a href="200001.htm">January 2000</a></td> <td width="69%">Footings poured, wall layout begins.</td> </tr> <tr> <td width="31%" valign="top"><a href="200002.htm">February 2000</a></td> <td width="69%">Concrete walls and slabs poured, guest house framing, steel erection.</td> </tr> <tr> <td width="31%" valign="top"><a href="200003.htm">March 2000</a></td> <td width="69%">More concrete and framing.&nbsp; Electrical and plumbing.</td> </tr> <tr> <td width="31%" valign="top"><a href="200004.htm">April 2000</a></td> <td width="69%">Framing and concrete beam.</td> </tr> <tr> <td width="31%" valign="top"><a href="200005.htm">May 2000</a></td> <td width="69%">Framing and concrete complete!&nbsp; Pool concrete finished.&nbsp; Plumbing and electrical start.&nbsp; <i>Charadrius vociferus</i> nest.</td> </tr> <tr> <td width="31%" valign="top"><a href="200006.htm">June 2000</a></td> <td width="69%">HVAC, electrical, kayak storage, key recovery.</td> </tr> <tr> <td width="31%" valign="top"><a href="200007.htm">July 2000</a></td> <td width="69%">Pool steel enclosure.</td> </tr> <tr> <td width="31%" valign="top"><a href="200008.htm">August 2000</a></td> <td width="69%">Aerial photographs, roofing, duct work, home automation wiring.</td> </tr> <tr> <td width="31%" valign="top"><a href="200009.htm">September 2000</a></td> <td width="69%">Lakefront retaining wall, lawn, courtyard wall, pool ceiling steel, pool windows</td> </tr> <tr> <td width="31%" valign="top"><a href="200010.htm">October 2000</a></td> <td width="69%">Lakefront patio, entry walkway/arcade, stucco sample, deck waterproofing, fireplace wall, theater framing, leaf art.</td> </tr> <tr> <td width="31%" valign="top"><a href="200011.htm">November 2000</a></td> <td width="69%">Courtyard stone and pond, </td> </tr> <tr> <td width="31%" valign="top"><a href="200012.htm">December 2000</a></td> <td width="69%">Wallboard, insulation, 2nd-floor bridge and stairs</td> </tr> <tr> <td width="31%" valign="top"><a href="200101.htm">January 2001</a></td> <td width="69%">Stucco and siding.</td> </tr> <tr> <td width="31%" valign="top"><a href="200102.htm">February 2001</a></td> <td width="69%">Pool roof, hardi-plank and pool finishes.</td> </tr> <tr> <td width="31%" valign="top"><a href="200103.htm">March 2001</a></td> <td width="69%">Pool tile and stone, flooring, driveway.</td> </tr> <tr> <td width="31%" valign="top">April 2001</td> <td width="69%"></td> </tr> <tr> <td width="31%" valign="top">May 2001</td> <td width="69%"></td> </tr> <tr> <td width="31%" valign="top">June 2001</td> <td width="69%">Move in!&nbsp; See <a href="http://mckoss.com/kossres/ArchPics/">Completed House Pictures</a>.</td> </tr> </table> &nbsp; <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="AutoNumber1" height="249"> <tr> <td width="20%" valign="top" height="213">General Contractor</td> <td width="80%" valign="top" height="213"> <a href="http://www.krekowjennings.com/"> <img border="0" src="images/kji.jpg" width="234" height="193"></a><br clear="ALL"> &nbsp;</td> </tr> <tr> <td width="20%" valign="top" height="18">Architect</td> <td width="80%" valign="top" height="18"><a href="http://www.r-b-f.com/"> rohleder | borges | fleming</a><p><a href="http://www.r-b-f.com/"> <img border="0" src="images/ext03thmb.jpg" width="128" height="96"></a></td> </tr> <tr> <td width="20%" valign="top" height="18"></td> <td width="80%" valign="top" height="18"></td> </tr> </table> <p>&nbsp;</p> <p>Visitors: <img border="0" src="http://fastcounter.bcentral.com/fastcounter?2412502+4825011"></p> </body </body> </html><file_sep><html> <head> <meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252"> <meta NAME="GENERATOR" CONTENT="Microsoft FrontPage 3.0"> <title>Christmas Letter 1998</title> </head> <body LINK="#0000FF" background="images/xmastree.jpg"> <dir> <dir> <font FACE="Comic Sans MS" SIZE="4"><p align="right">Christmas, 1998</p> <dir> <p>Merry Christmas!</p> </font><font SIZE="1"><p></font><font size="3"><img SRC="images/chrishat.jpg" WIDTH="192" HEIGHT="256" align="left" hspace="8" vspace="8"></font><font FACE="Comic Sans MS" size="3">This has been an interesting year for us. We&#146;ve done quite a bit of travelling together. In the spring, we went spent a <a href="http://mckoss.com/italy98">week in Italy</a>. We started in Rome, but spent the bulk of our time in Florence. We all enjoyed the art, architecture, and perhaps most of all, the food (especially Italian gelatto). We took several trips by train &#150; everything from the high-speed pendulum train to &quot;locals&quot; between small towns.</p> <p>Mike started weight lifting and hiking in preparation for a climb up Mt. Rainier. He made it to the summit &#150; but only just barely (climbing from sea level to over 14,000 ft. in one day gave him a nasty case of altitude sickness). For more details visit http://mckoss.com.</p> <p>In the summer, we went back to Oklahoma City for Mike&#146;s 20<sup>th</sup> high school reunion and then accompanied his father to Newberry, Michigan for his 40<sup>th</sup>. Chris and Debbie got to see Manastique Lake and the cabin where Mike was born.</p> <p>On his free weekends, Mike built Chris a &quot;<a href="http://mckoss.com/platformhouse">tree-house</a>&quot; this summer. Actually, since we have no trees, he had to build it on stilts. It stands 10 feet in the air, has a shake roof, a balcony and even electricity!</p> <p>Chris went to three sports camps this summer (basketball, baseball, and roller hockey) before starting at a new school this year. He started 5<sup>th</sup> grade at Overlake. He will be at this new school through high school. He&#146;s really enjoying it. Not only does he love his teachers, he&#146;s really enjoyed taking math, social studies and Latin. He&#146;s also started playing (drums) in the school band. He played in his first band concert in December.</p> <p><img SRC="images/plathouse.jpg" WIDTH="192" HEIGHT="144" align="right" hspace="8" vspace="8">Mike did a lot of business travelling this year, recruiting for Microsoft in Pittsburgh and twice to MIT/Boston, and then a week-long visit to Tokyo in December to interview customers (through an interpreter!).</p> <p>In September, we decided to look for waterfront property to build a new house. We were fortunate to find a really great lot on Lake Washington. There is no house on the site, so we are working with an architect now to design our new home. We expect to finish design by this summer and start construction in the fall. It&#146;s exciting and a bit scary. We should be able to move in around December 2000!</font><font FACE="Comic Sans MS" SIZE="1"></p> <table border="0" width="100%"> <tr> <td width="50%"></td> <td width="50%"><font FACE="Comic Sans MS" SIZE="4"><p align="left">Love to all,<br> <a href="http://mckoss.com/">Mike</a>, Deb, and <NAME></font></td> </tr> </table> </dir> </font><blockquote> <p>&nbsp;</p> </blockquote> <font FACE="Comic Sans MS" SIZE="4"> </dir> </dir> </font> </body> </html> <file_sep>var dc; function InitScroller() { new DragController(document.body); } DragController.prototype.Idle = DCIdle; function DCIdle() { if (this.fThrow) { window.scrollBy(this.dx, this.dy); this.dx *= this.friction; this.dy *= this.friction; if (Math.abs(this.dx) < 1 && Math.abs(this.dy) < 1) this.fThrow = false; } } function DragController(obj) { dc = this; this.obj = obj; obj.style.cursor = "hand"; this.fDown = false; this.fThrow = false; obj.onmousedown = new Function("dc.MouseDown();"); obj.onmousemove = new Function("dc.MouseMove();"); obj.onmouseup = new Function("dc.MouseUp();"); obj.onkeydown = new Function("dc.KeyDown();"); this.msIdle = 1; this.friction = 0.97; this.tm = window.setInterval("dc.Idle();", this.msIdle); } DragController.prototype.MouseDown = DCMouseDown; function DCMouseDown() { if (window.event.srcElement.tagName.toUpperCase() == "AREA") { return; } this.obj.setCapture(); this.fDown = true; this.fThrow = false; this.RecordMouse(true); } DragController.prototype.MouseMove = DCMouseMove; function DCMouseMove() { if (!this.fDown) return; // Bug - we somehow got a mousedown and no mouseup if (window.event.button == 0) { this.MouseUp(); return; } this.RecordMouse(false); window.scrollBy(this.dx, this.dy); } DragController.prototype.RecordMouse = DCRecordMouse; function DCRecordMouse(fInit) { if (fInit) { this.dx = this.dy = 0; } else { this.dx = this.x - window.event.clientX; this.dy = this.y - window.event.clientY; } this.x = window.event.clientX; this.y = window.event.clientY; } DragController.prototype.MouseUp = DCMouseUp; function DCMouseUp() { this.obj.releaseCapture(); this.fDown = false; this.fThrow = true; } DragController.prototype.KeyDown = DCKeyDown; function DCKeyDown() { var dx = 0; var dy = 0; switch (window.event.keyCode) { // left arrow case 37: dx = -5; break; // right arrow case 39: dx = 5; break; // up arrow case 38: dy = -5; break; // down arrow case 40: dy = 5; break; // page up case 33: dy = -10; break; // page down case 34: dy = 10; break; default: return; } window.event.returnValue = false; if (!this.fDown && !this.fThrow) { this.dx = dx; this.dy = dy; this.fThrow = true; return; } if (this.fThrow) { this.dx += dx; this.dy += dy; } } <file_sep> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <meta http-equiv="Content-Language" content="en-us"> <title>Koss Residence - March 2000</title> <meta name="GENERATOR" content="Microsoft FrontPage 4.0"> <meta name="ProgId" content="FrontPage.Editor.Document"> </head> <body style="font-family: Verdana"> <!--webbot bot="Include" U-Include="header.htm" TAG="BODY" startspan --> <table border="0" width="99%" height="112"> <tr> <td width="25%" height="106"> <p align="center"><a href="DesignWeb/images/ext03.jpg"> <img alt="ext03thmb.jpg (8851 bytes)" border="1" src="images/ext03thmb.jpg" width="128" height="96"></a></p> </td> <td width="44%" height="106"> <h1 align="center"><font face="Verdana"><a href="Default.htm">Koss Residence<br> Web</a></font></h1> </td> <td width="31%" height="106"> <p align="center"><a href="http://www.seanet.com/~harleyd/koss/images/ext02.jpg"><a href="DesignWeb/images/ext11.jpg"> <img alt="ext11thmb.jpg (8113 bytes)" border="1" src="images/ext11thmb.jpg" width="128" height="96"></a></p> </td> </tr> </table> <hr> <!--webbot bot="Include" endspan i-checksum="55442" --> <h3>March 2000</h3> <p>In March we got more concrete in place around the pool walls, guest house, garage slab, and under the study.&nbsp; The most visible progress was made in framing; the media room walls and ceiling got completely framed, and the first floor framing started to go up. </p> <table border="0" width="100%"> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000032.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">March 8, 2000</p> <p align="left">Waterproofing installed around the exterior walls. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000033.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">March 10, 2000</p> <p align="left">Electrical and plumbing conduit from the utility trench to the main house. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000319.jpg" width="320" height="420"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">Looks like Lee is having fun moving material around the site. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000034.jpg" width="320" height="302"></td> <td width="50%" valign="top"> <p align="right">March 15, 2000</p> <p align="left">Electrical and plumbing penetrations into the main house mechanical room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000318.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">March 15, 2000</p> <p align="left">Forms for the last of the media room walls. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000320.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">March 21, 2000</p> <p align="left">Putting up walls in the media room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000036.jpg" width="295" height="379"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">Craning the dehumidifier into the mechanical room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000035.jpg" width="320" height="225"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">The guest house garage now serves as office as storage area.&nbsp; We're down to 2 trailers on the site. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000037.jpg" width="320" height="239"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">Steel in the living room wall is craned into place and welded to vertical steel posts.</p> <p align="center">&nbsp; </td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"><img border="0" src="images/2000038.jpg" align="top" width="280" height="205"> <img border="0" src="images/20000315.jpg" width="240" height="352"></td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000039.jpg" align="top" width="320" height="240"> <p><img border="0" src="images/20000317.jpg" width="240" height="407"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">Form at the east pool wall.</p> <p align="left">&nbsp; </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000040.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">Ceiling framing complete in the media room.&nbsp; The high area is under the dining room floor - the lower part is under the deck. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000310.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">West end of media room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000311.jpg" width="320" height="231"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">Walls went up today on the first floor.&nbsp; This view is looking south through the living room wall. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000312.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">Tip up of the wall at the front of the house stands 20' high. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000314.jpg" width="320" height="300"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">The second monolithic wall on the main floor - extends through the stairwell from the basement through the second floor. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/20000316.jpg" width="320" height="212"></td> <td width="50%" valign="top"> <p align="right">March 24, 2000</p> <p align="left">View across Cozy Cove to Rao's place. </td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"> <p align="right">March 24, 2000</p> <p align="left">A stiched panorama of the water-side of the house.</td> </tr> <tr> <td width="100%" align="center" valign="top" colspan="2"><img border="0" src="images/20000321.jpg" width="500" height="234"></td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000041.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">March 25, 2000</p> <p align="left">Framing for Kitchen (pantry and powder room layout visible on the floor). </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000042.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">March 25, 2000</p> <p align="left">Filling trench at front door. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000043.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">March 28, 2000</p> <p align="left">Mike tests the load-bearing capacity of the library foundation walls. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000044.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">March 31, 2000</p> <p align="left">Paul scares me - putting up scaffolding to build the front wall of the living room. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000045.jpg" width="320" height="240"></td> <td width="50%" valign="top"> <p align="right">March 31, 2000</p> <p align="left">View from the dock - progress as of end of March.&nbsp; The Coles house is on the right. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000046.jpg" width="320" height="195"></td> <td width="50%" valign="top"> <p align="right">March 31, 2000</p> <p align="left">Siding the garage.&nbsp; Front door is at the left side of this picture. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000047.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">March 31, 2000</p> <p align="left">Looking down into the kitchen and entry hall.&nbsp; That's the pantry in the center of the picture. </td> </tr> <tr> <td width="50%" align="center" valign="top"><img border="0" src="images/2000048.jpg" width="320" height="426"></td> <td width="50%" valign="top"> <p align="right">March 31, 2000</p> <p align="left">Dining room (as seen from scaffolding). </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> <tr> <td width="50%" align="center" valign="top"></td> <td width="50%" valign="top"> </td> </tr> </table> <p>&nbsp;</p> <p>&nbsp; </p> </body> </html>
e2795043a57e6a61d28b7228ebf5b4e44904cd8e
[ "JavaScript", "C", "HTML" ]
24
JavaScript
mckoss/original-mckoss.com
80a42315df04adb3f708739e25079570cd6cbbca
89a2df35b6a3bb3e832e4bf50110ce6732ca4dba
refs/heads/master
<file_sep># _*_ coding:utf-8 _*_ import urllib.request from tkinter import * def get_screen_size(window): return window.winfo_screenwidth(), window.winfo_screenheight() def get_window_size(window): return window.winfo_reqwidth(), window.winfo_reqheight() def center_window(root1, width, height): screenwidth = root1.winfo_screenwidth() screenheight = root1.winfo_screenheight() size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) root1.geometry(size) def send_sms(): phone = entry_phone.get() url = "https://www.daoyuanketang.com/api/sendmobilecode?mobile=" + phone user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " \ "Chrome/70.0.3538.77 Safari/537.36" headers = {"User_Agent": user_agent, 'Accept': 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip, deflate, br', 'clientType': 'web'} print(url) req = urllib.request.Request(url, headers=headers) response = urllib.request.urlopen(req) html = response.read().decode('utf-8') print(html) def btnClick(): if entry_phone.get() == "": textLabel['text'] = "请输入手机号" return if len(entry_phone.get()) != 11: textLabel['text'] = "手机号不正确" return textLabel['text'] = "即将向:" + str(entry_phone.get()) + "发送短信" # send_sms() root = Tk(className="短信轰炸机v1.0", ) # 设置窗体大小 center_window(root, 500, 340) root.maxsize(600, 400) root.minsize(300, 240) # 手机号 text_phone = Label(root, text='手机号', justify=LEFT, padx=10) text_phone.pack(side=TOP) # 输入框 entry_phone = Entry(root, width=30, bg="white", fg="black") entry_phone.pack(side=TOP) # 提示信息 textLabel = Label(root, text='提示显示', justify=LEFT, padx=10) textLabel.pack(side=TOP) # 提示画布 cv = Canvas(root, bg='white', height="200", relief=RAISED) # 创建一个矩形,坐标为(10,10,110,110) cv.create_rectangle(10, 10, 50, 50) cv.create_text(100, 50, text="FishC") cv.pack() # 按钮 btn = Button(root) btn['text'] = '点击发送' btn['command'] = btnClick btn.pack(side=BOTTOM) mainloop()
e4b9713d94c5c78717708e04422b79b94124ed5a
[ "Python" ]
1
Python
Pig-Tong/sms_bomber
c3805d1259e5f421b28e420c904f254d17a622c3
dd6b17c9f680a6a9b14b075979ffd44857b05be5
refs/heads/master
<repo_name>OleksandrPavlyshch/speed_task<file_sep>/source/elements/scroll-to/scroll-to.js // 'use strict'; // (function () { // var $scrollLinks = $('.logo, .header_menu-list_item-link') // , $htmlBody = $('html, body') // , $body = $('body') // , topBlockId = '#hero' // , menuShowClass = 'is-menu-show' // , $header = $('header'); // $scrollLinks.on('click', function(event) { // event.preventDefault(); // var $this = $(this) // , link = $this.attr("href") // , section = $body.find(link) // , headerHeight = (link !== topBlockId) ? $header.height() : 0; // if(section.length){ // $htmlBody.animate({scrollTop: section.offset().top - headerHeight}, 1000); // console.log(menuShowClass, headerHeight); // $body.removeClass(menuShowClass); // return; // } // }); // })();<file_sep>/source/elements/menu/menu.js 'use strict'; (function () { var $body = $('body') , $menuButton = $('.toggle-menu-button') , menuShowClass = 'is-menu-show' , menuClass = '.toggle-menu-button'; $menuButton.on('click', function() { $body.toggleClass(menuShowClass); }); $(document).click( function(event){ if( $(event.target).closest(menuClass).length ) return; $body.removeClass(menuShowClass); // event.stopPropagation(); }); $(document).ready(function($) { $('.header_menu').ddscrollSpy({ scrolltopoffset: -50 , scrollduration: 1000 , highlightclass: 'active' }); }); })();
6b0bac2cd91d06e707d87bb095e70dcf48ae4004
[ "JavaScript" ]
2
JavaScript
OleksandrPavlyshch/speed_task
839c1c9c63be780ce21cc3590959ac3724571228
19852a8987431ee4ec6296507e513e7ae1b8160f
refs/heads/master
<file_sep>print("Hello laloran")
dd20cc04aa95b4b5887bb4bb351fb763d90818ae
[ "Python" ]
1
Python
laloran/Mydir
b878b97c3647e897bf980743724e623b1582264f
fe28efc9a9bd5497c3db8de1dae0f6d2c1ec7430
refs/heads/main
<repo_name>PradeepPrasanthS/Inventory<file_sep>/app/src/main/java/com/pradeep/inventory/ui/LoginActivity.kt package com.pradeep.inventory.ui import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.View import android.widget.EditText import android.widget.Toast import com.pradeep.inventory.R class LoginActivity : Activity() { private lateinit var emailEdit: EditText private lateinit var passwordEdit: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) emailEdit = findViewById(R.id.email) passwordEdit = findViewById(R.id.password) } fun login(view: View) { val email = emailEdit.text.toString() val password = <PASSWORD>() if(email == "<EMAIL>" && password == "<PASSWORD>") { val intent = Intent(this, MainActivity::class.java) startActivity(intent) } else { Toast.makeText(this, "Invalid login credentials", Toast.LENGTH_SHORT).show() } } }<file_sep>/app/src/main/java/com/pradeep/inventory/adapter/LoadsAdapter.kt package com.pradeep.inventory.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.recyclerview.widget.RecyclerView import com.pradeep.inventory.R class LoadsAdapter: RecyclerView.Adapter<LoadsAdapter.LoadsListHolder>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): LoadsListHolder { val inflatedView = parent.inflate(R.layout.loads_layout, false) return LoadsListHolder(inflatedView) } override fun onBindViewHolder( holder: LoadsListHolder, position: Int ) { } private fun ViewGroup.inflate(@LayoutRes layoutRes: Int, attachToRoot: Boolean = false): View { return LayoutInflater.from(context).inflate(layoutRes, this, attachToRoot) } override fun getItemCount(): Int { return 6 } class LoadsListHolder(v: View) : RecyclerView.ViewHolder(v) { } }<file_sep>/app/src/main/java/com/pradeep/inventory/ui/LoadsFragment.kt package com.pradeep.inventory.ui import android.graphics.Color import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.FloatingActionButton import com.pradeep.inventory.R import com.pradeep.inventory.adapter.LoadsAdapter class LoadsFragment : Fragment() { private lateinit var adapter: LoadsAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val root = inflater.inflate(R.layout.fragment_loads, container, false) setHasOptionsMenu(true) root.findViewById<FloatingActionButton>(R.id.fab).setColorFilter(Color.WHITE) val loadsList = root.findViewById<RecyclerView>(R.id.loadsList) val layoutManager = LinearLayoutManager(activity) loadsList.layoutManager = layoutManager adapter = LoadsAdapter() loadsList.adapter = adapter return root } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { activity?.menuInflater?.inflate(R.menu.loads_menu, menu) } }<file_sep>/README.md # Inventory The app which can show the list of inventories with a beautiful UI
35e3fe197a49ab67249726a83a605c93f9f6308f
[ "Markdown", "Kotlin" ]
4
Kotlin
PradeepPrasanthS/Inventory
b4f777d0966ca85e93e21d8510c07c220e008c0b
7f66acb8fd85b56e15b997b47488b27fe1975e71
refs/heads/master
<file_sep>require "./sass_compiler" Sass.compile(["test.scss"])
f258e58328165944c37e931a35dbd425d9ff989f
[ "Ruby" ]
1
Ruby
encours/font-awesome-test
3162b73b3c94ba32b243e00168fc8b06ace214d4
57a35b1367be8a9986d39d19d5edd7d4b65109ad
refs/heads/8.x-1.x
<file_sep><?php /** * @file * Contains \Drupal\bigmenu\MenuSliceFormController. */ namespace Drupal\bigmenu; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\AlertCommand; use Drupal\Core\Menu\MenuTreeParameters; use Drupal\menu_link_content\Entity\MenuLinkContent; class MenuSliceFormController extends MenuFormController { /** * @var \Drupal\menu_link\MenuLinkInterface */ protected $menuLink; protected function prepareEntity() { $this->menuLink = $this->getRequest()->attributes->get('menu_link'); } /** * @param array $form * @param \Drupal\Core\Form\FormStateInterface $form_state * @param int $depth * @return array */ protected function buildOverviewForm(array &$form, \Drupal\Core\Form\FormState $form_state, $depth = 1) { // Ensure that menu_overview_form_submit() knows the parents of this form // section. if (!$form_state->has('menu_overview_form_parents')) { $form_state->set('menu_overview_form_parents', []); } $form['#attached']['library'][] = 'menu_ui/drupal.menu_ui.adminforms'; // 'edit_bigmenu' == $this->operation $tree_params = new MenuTreeParameters(); $tree_params->setMaxDepth($depth); $tree = $this->menuTree->load($this->entity->id(), $tree_params); // We indicate that a menu administrator is running the menu access check. $this->getRequest()->attributes->set('_menu_admin', TRUE); $manipulators = array( array('callable' => 'menu.default_tree_manipulators:checkAccess'), array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'), ); $tree = $this->menuTree->transform($tree, $manipulators); $this->getRequest()->attributes->set('_menu_admin', FALSE); // Determine the delta; the number of weights to be made available. $count = function(array $tree) { $sum = function ($carry, MenuLinkTreeElement $item) { return $carry + $item->count(); }; return array_reduce($tree, $sum); }; // Tree maximum or 50. $delta = max($count($tree), 50); $form['links'] = array( '#type' => 'table', '#theme' => 'table__menu_overview', '#header' => array( $this->t('Menu link'), array( 'data' => $this->t('Enabled'), 'class' => array('checkbox'), ), $this->t('Weight'), array( 'data' => $this->t('Operations'), 'colspan' => 3, ), ), '#attributes' => array( 'id' => 'menu-overview', ), '#tabledrag' => array( array( 'action' => 'match', 'relationship' => 'parent', 'group' => 'menu-parent', 'subgroup' => 'menu-parent', 'source' => 'menu-id', 'hidden' => TRUE, 'limit' => \Drupal::menuTree()->maxDepth() - 1, ), array( 'action' => 'order', 'relationship' => 'sibling', 'group' => 'menu-weight', ), ), ); // No Links available (Empty menu) $form['links']['#empty'] = $this->t('There are no menu links yet. <a href=":url">Add link</a>.', [ ':url' => $this->url('entity.menu.add_link_form', ['menu' => $this->entity->id()], [ 'query' => ['destination' => $this->entity->url('edit-form')], ]), ]); $links = $this->buildOverviewTreeForm($tree, $delta); foreach (Element::children($links) as $id) { if (isset($links[$id]['#item'])) { $element = $links[$id]; $form['links'][$id]['#item'] = $element['#item']; // TableDrag: Mark the table row as draggable. $form['links'][$id]['#attributes'] = $element['#attributes']; $form['links'][$id]['#attributes']['class'][] = 'draggable'; $form['links'][$id]['#item'] = $element['#item']; // TableDrag: Sort the table row according to its existing/configured weight. $form['links'][$id]['#weight'] = $element['#item']->link->getWeight(); // Add special classes to be used for tabledrag.js. $element['parent']['#attributes']['class'] = array('menu-parent'); $element['weight']['#attributes']['class'] = array('menu-weight'); $element['id']['#attributes']['class'] = array('menu-id'); $form['links'][$id]['title'] = array( array( '#theme' => 'indentation', '#size' => $element['#item']->depth - 1, ), $element['title'], ); $strings = array( '!show_children' => t('Show children'), '%count' => 123, '!tooltip' => t('Click to expand and show child items'), ); $text = strtr('+ !show_children (%count)', $strings); $mlid = (int)$links[$id]['#item']->link->getMetaData()['entity_id']; /* * Show-more-Link with Ajax. */ $url = Url::fromRoute( 'bigmenu.menu_link', array('menu' => 'main', 'menu_link' => $mlid) ); $url->setOption('attributes', array('class' => 'use-ajax')); $link_generator = \Drupal::service('link_generator'); $indicator = $link_generator->generate($text, $url); $form['links'][$id]['enabled'] = $element['enabled']; $form['links'][$id]['enabled']['#wrapper_attributes']['class'] = array('checkbox', 'menu-enabled'); $form['links'][$id]['weight'] = $element['weight']; // Operations (dropbutton) column. $form['links'][$id]['operations'] = $element['operations']; // Menulink $form['links'][$id]['id'] = $element['id']; // MenuLink Parent $form['links'][$id]['parent'] = $element['parent']; // Title with Show more link. $form['links'][$id]['title'][] = array('#markup'=>'<br />'.$indicator); } } return $form; } /** * Overrides Drupal\Core\Entity\EntityFormController::form(). */ public function form(array $form, \Drupal\Core\Form\FormState &$form_state) { $menu = $this->entity; $menuLink = $this->menuLink; $trigger = $form_state->getTriggeringElement(); $halt = 'halt'; // Add menu links administration form for existing menus. if (!$menu->isNew() || $menu->isLocked()) { // Form API supports constructing and validating self-contained sections // within forms, but does not allow to handle the form section's submission // equally separated yet. Therefore, we use a $form_state key to point to // the parents of the form section. // @see self::submitOverviewForm() // $form_state['menu_overview_form_parents'] = array('links'); $form['links'] = array(); return $this->maxDepthbuildOverviewForm($form['links'], $form_state, 2); } return $form; } /** * @param array $form * @param array $form_state * @param int $depth * @return array */ protected function maxDepthbuildOverviewForm(array &$form, FormStateInterface $form_state, $depth = 1) { // Ensure that menu_overview_form_submit() knows the parents of this form // section. $form['#tree'] = TRUE; $form['#theme'] = 'menu_overview_form'; //$form_state += array('menu_overview_form_parents' => array()); $form['#attached']['css'] = array(drupal_get_path('module', 'menu') . '/css/menu.admin.css'); $menu_tree = \Drupal::menuTree(); $menu_tree_parameters = new MenuTreeParameters(); $menu_tree_parameters->minDepth = 0; $menu_tree_parameters->maxDepth = $depth; $test = MenuLinkContent::load($this->menuLink)->getPluginId(); $menu_tree_parameters->setRoot($test); $tree = \Drupal::menuTree()->load( $this->entity->getOriginalId(), $menu_tree_parameters ); $m_tree = $this->buildOverviewTreeForm($tree); $form = array_merge($form, $m_tree); $form = $this->buildOverviewTreeForm($tree); $form['#empty_text'] = t('There are no menu links yet. <a href="@link">Add link</a>.', array('@link' => url('admin/structure/menu/manage/' . $this->entity->id() . '/add'))); return $form; } } <file_sep><?php /** * @file * Administrative page callbacks for bigmenu module. * * Large amounts copied from menu.admin.inc * * @author Dan (dman) Morrison <EMAIL> * @author Adam (acbramley) Bramley <EMAIL> * @version 2012 */ /** * We re-use as much of the core menu rendering tools as possible. */ module_load_include('inc', 'menu', 'menu.admin'); function bigmenu_overview_form($form, &$form_state, $menu, $depth = 1) { global $menu_admin; $p_depth = 'p' . (string)((int)$depth + 3); $sql = " SELECT m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.title, m.title_callback, m.title_arguments, m.type, m.description, ml.* FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path WHERE ml.menu_name = :menu_name AND $p_depth = 0 ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC"; $result = db_query($sql, array(':menu_name' => $menu['menu_name']), array('fetch' => PDO::FETCH_ASSOC)); $links = array(); foreach ($result as $item) { $links[] = $item; } $tree = menu_tree_data($links); $node_links = array(); menu_tree_collect_node_links($tree, $node_links); // We indicate that a menu administrator is running the menu access check. $menu_admin = TRUE; menu_tree_check_access($tree, $node_links); $menu_admin = FALSE; // If the user doesn't have the permission to use big menu, use core's form $new_form = user_access('use bigmenu') ? _bigmenu_overview_tree_form($tree) : _menu_overview_tree_form($tree); $cached_mlids = bigmenu_get_cached_mlids($form_state); $new_form = array_merge($new_form, $cached_mlids); $new_form['#menu'] = $menu; if (element_children($new_form)) { $new_form['submit'] = array( '#type' => 'submit', '#value' => t('Save configuration'), ); } else { $new_form['#empty_text'] = array('#markup' => t('There are no menu items yet.')); } return $new_form; } /** * Get the menu items that have already been expanded to merge in with the form during it's construction * @param $form_state * @return array - The previously cached mlids, including those from expanded parents */ function bigmenu_get_cached_mlids($form_state) { $cached_mlids = array(); if (!empty($form_state) && !empty($form_state['rebuild_info']) && !empty($form_state['rebuild_info']['copy'])) { $form_build_id = $form_state['rebuild_info']['copy']['#build_id']; $cached_form = form_get_cache($form_build_id, $form_state); if (!empty($cached_form)) { // We have previously expanded one of the menu items so extract the items that were in the cached form // so that we can add them to the form that is being built now. foreach ($cached_form as $key => $value) { $matches = array(); if (preg_match('/mlid:([0-9]*)/', $key, $matches)) { $cached_mlids[$key] = $value; } } } } return $cached_mlids; } /** * Form for editing the immediate children of the given menu item id * * Invoked by menu callback or by json request * * @return FAPI form. */ function bigmenu_slice_form($form, &$form_state, $menu, $menu_link, $depth = 2) { // DB lookup the children of this item global $menu_admin; $p_depth = 'p' . $menu_link['depth']; $sql = " SELECT m.load_functions, m.to_arg_functions, m.access_callback, m.access_arguments, m.page_callback, m.page_arguments, m.title, m.title_callback, m.title_arguments, m.type, m.description, ml.* FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path WHERE ml.menu_name = :menu_name AND " . check_plain($p_depth) . " = :mlid ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC"; $result = db_query($sql, array(':menu_name' => $menu['menu_name'], ':mlid' => $menu_link['mlid']), array('fetch' => PDO::FETCH_ASSOC)); $links = array(); foreach ($result as $item) { $links[] = $item; } $tree = menu_tree_data($links); $node_links = array(); menu_tree_collect_node_links($tree, $node_links); // We indicate that a menu administrator is running the menu access check. $menu_admin = TRUE; menu_tree_check_access($tree, $node_links); $menu_admin = FALSE; // When doing a slice, don't show the actual parent link item, just the children foreach ($tree as $ix => $data) { $tree[$ix]['link'] = array(); } // (there was only one, but I didn't know its name) $form = _bigmenu_overview_tree_form($tree, $depth); $form['#theme'] = 'bigmenu_overview_form'; $form['#menu'] = $menu; if (element_children($form)) { $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array( '#type' => 'submit', '#value' => t('Save configuration'), ); } else { $form['#empty_text'] = array('#markup' => t('There are no menu items yet.')); } return $form; } /** * Return a submenu slice form in json format * Menu callback, invoked by AJAX * * Drupals form cache would not allow me to insert arbitrary fields into a form * without letting the server know about it. */ function bigmenu_slice_form_js($menu, $menu_link, $form_id, $form_build_id) { $depth = variable_get('bigmenu_depth', 1); $form_state = form_state_defaults(); $old_form = drupal_get_form('bigmenu_slice_form', $menu, $menu_link, $depth); $output = drupal_render($old_form); // This returns data to the browser immediately. drupal_json_output(array('status' => TRUE, 'data' => $output)); // After that we will do the slower job of updating the form cache. // Reload the bigmenu_overview_form, with the same args (the menu name) as before, $args = array($menu); $form_state['build_info']['args'] = $args; $form_state['values'] = array(); $form_state['rebuild_info']['copy']['#build_id'] = $form_build_id; drupal_rebuild_form($form_id, $form_state, array('#build_id' => $form_build_id)); exit; } /** * Theme the menu overview form into a table. * * A stub to core. No need to change anything. It just adds an extra js file and * passes it through. * * @ingroup themeable */ function theme_bigmenu_overview_form($form) { drupal_add_js(drupal_get_path('module', 'bigmenu') . '/bigmenu.js'); drupal_add_css(drupal_get_path('module', 'bigmenu') . '/bigmenu.css'); return theme('menu_overview_form', $form); } /** * A stub to core */ function bigmenu_overview_form_submit($form, &$form_state) { return menu_overview_form_submit($form, $form_state); } /** * Admin settings form. */ function bigmenu_settings($form, &$form_state) { $form['bigmenu_settings'] = array( '#type' => 'fieldset', '#title' => t('Settings'), ); $form['bigmenu_settings']['bigmenu_depth'] = array( '#type' => 'select', '#title' => t('Big Menu Depth'), '#description' => t('This setting controls how many levels are generated at a time when showing children of a menu item.'), '#required' => TRUE, '#default_value' => variable_get('bigmenu_depth', 1), '#options' => array(1 => '1', 2 => '2', 3 => '3'), ); return system_settings_form($form); } <file_sep>/** * @file add AJAX loading to the manu admin screen * * @author dman <EMAIL> */ (function ($) { Drupal.behaviors.bigmenu = { attach: function(context) { // Add click actions to all the child indicators // The bigmenu-processed class will mark that we don't want to attach this behavior twice. $('form#bigmenu-overview-form .bigmenu-childindictor').not('.bigmenu-processed') .addClass('bigmenu-processed') .click( function(event){ // Don't let the normal href_ click happen event.stopPropagation(); // jquery 1.3+ var parentRow = $(this).parents('tr').get(); // Find the mlid of the cell we are in. var mlid = $('.menu-mlid', parentRow).val(); // If children have been generated already, just show them again. if ($(parentRow).hasClass("bigmenu-generated") && $(parentRow).hasClass("bigmenu-collapsed")) { $('.childOf-' + mlid).css('display', ''); // Indicate we are expanded now $(parentRow) .removeClass('bigmenu-collapsed') .addClass('bigmenu-expanded'); $('.hide-show', parentRow).html('Hide children'); return false; } // Prevent double-clicks if ($(parentRow).hasClass("bigmenu-processing")) { return; } // Set throbber, and indicate we are busy $(parentRow).addClass("bigmenu-processing"); // We either expand or contract, depending on current status if ($(parentRow).hasClass("bigmenu-collapsed")) { // Fetch submenu and expand // This clicked item has the href call we need to make built in // just add 'js' to the end var url = $(this).attr('href') + '/js'; // ALSO, to deal with Drupal form API form cache, add the form build ID // so the background process can update the known fields var form = $('.menu-mlid', parentRow).attr('form') form_id = $('input[name="form_id"]', form).val(); form_build_id = $('input[name="form_build_id"]', form).val(); url += "/" + form_id + "/" + form_build_id // Make an ajax call for the child items. $.ajax({ dataType: 'json', url: url, success: function(data, textStatus, XMLHttpRequest) { //data = jQuery.parseJson(data); if (data.status) { // Shift the rows into this form. var new_form = $(data.data); // Add each tr in the retrieved form after the parent row // Tag the added rows so we can find and collapse them later var previousRow = parentRow; $('tr', new_form).each(function(index) { if ($('th', this).length == 0) { $(this).addClass('childOf-' + mlid) .css('opacity', 0.2) //.fadeTo(0, 0.5).css('opacity', 0.1) $(previousRow).after(this) // TODO - an animation of some sort - tr,td cannot set height however previousRow = this } }); $('.childOf-' + mlid) .animate({opacity:'1'}, 1500) // don't use fadeIn because tht acts odd on table elements // Attach any required behaviors to the table // thus, the further child expanders, and the tabledrag again. // tabledrag doesn't like running twice, so we have to remove some evidence $('#menu-overview').removeClass('tabledrag-processed'); $('#menu-overview .tabledrag-handle').remove(); // Remove the weight toggle widget as it will be added in again with AJAX. $('.tabledrag-toggle-weight-wrapper').remove(); Drupal.attachBehaviors(); // Remove tabledrag warning, otherwise it will duplicate for each set of children we show. Drupal.theme.tableDragChangedWarning = function () { return ''; }; // Indicate we are expanded now $(parentRow) .removeClass('bigmenu-collapsed') .addClass('bigmenu-expanded'); $('.hide-show', parentRow).html('Hide children'); } else { // Failure... alert(Drupal.t('AJAX error fetching submenu.')); //$('.bigmenu-childindictor', $(parentRow)).remove(); } // Finished processing, whether success or failure $(parentRow) .removeClass('bigmenu-processing') }, error: function(XMLHttpRequest, textStatus, errorThrown) { // Failure... alert(Drupal.t('Error fetching submenu: @error', { '@error': textStatus })); } }); } else { // This item was already expanded, so a click means it should close. // That means hide the kids $('.childOf-' + mlid).css('display', 'none'); // Indicate we are closed now $(parentRow) .removeClass('bigmenu-processing') .removeClass('bigmenu-expanded') .addClass('bigmenu-collapsed') .addClass('bigmenu-generated') $('.hide-show', parentRow).html('Show children'); } return false; } ); } }; })(jQuery); <file_sep><?php /** * @file * Contains \Drupal\bigmenu\MenuFormController. */ namespace Drupal\bigmenu; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\HtmlCommand; use Drupal\menu_ui\MenuForm as DefaultMenuFormController; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Menu\MenuLinkTreeElement; use Drupal\Core\Menu\MenuTreeParameters; use Drupal\Core\Render\Element; /** * Class MenuFormController * @package Drupal\bigmenu */ class MenuFormController extends DefaultMenuFormController { /** * @param array $form * @param \Drupal\Core\Form\FormStateInterface $form_state * @param int $depth * @return array */ protected function buildOverviewForm(array &$form, FormStateInterface $form_state, $depth = 1) { // Ensure that menu_overview_form_submit() knows the parents of this form // section. if (!$form_state->has('menu_overview_form_parents')) { $form_state->set('menu_overview_form_parents', []); } // Use Menu UI adminforms $form['#attached']['library'][] = 'menu_ui/drupal.menu_ui.adminforms'; // 'edit_bigmenu' == $this->operation $tree_params = new MenuTreeParameters(); $tree_params->setMaxDepth($depth); $tree = $this->menuTree->load($this->entity->id(), $tree_params); // We indicate that a menu administrator is running the menu access check. $this->getRequest()->attributes->set('_menu_admin', TRUE); $manipulators = array( array('callable' => 'menu.default_tree_manipulators:checkAccess'), array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'), ); $tree = $this->menuTree->transform($tree, $manipulators); $this->getRequest()->attributes->set('_menu_admin', FALSE); // Determine the delta; the number of weights to be made available. $count = function (array $tree) { $sum = function ($carry, MenuLinkTreeElement $item) { return $carry + $item->count(); }; return array_reduce($tree, $sum); }; // Tree maximum or 50. $delta = max($count($tree), 50); $form['links'] = array( '#type' => 'table', '#theme' => 'table__menu_overview', '#header' => array( $this->t('Menu link'), array( 'data' => $this->t('Enabled'), 'class' => array('checkbox'), ), $this->t('Weight'), array( 'data' => $this->t('Operations'), 'colspan' => 3, ), ), '#attributes' => array( 'id' => 'menu-overview', ), '#tabledrag' => array( array( 'action' => 'match', 'relationship' => 'parent', 'group' => 'menu-parent', 'subgroup' => 'menu-parent', 'source' => 'menu-id', 'hidden' => TRUE, 'limit' => \Drupal::menuTree()->maxDepth() - 1, ), array( 'action' => 'order', 'relationship' => 'sibling', 'group' => 'menu-weight', ), ), ); // No Links available (Empty menu) $form['links']['#empty'] = $this->t('There are no menu links yet. <a href=":url">Add link</a>.', [ ':url' => $this->url('entity.menu.add_link_form', ['menu' => $this->entity->id()], [ 'query' => ['destination' => $this->entity->url('edit-form')], ]), ]); $links = $this->buildOverviewTreeForm($tree, $delta); foreach (Element::children($links) as $id) { if (isset($links[$id]['#item'])) { $element = $links[$id]; $form['links'][$id]['#item'] = $element['#item']; // TableDrag: Mark the table row as draggable. $form['links'][$id]['#attributes'] = $element['#attributes']; $form['links'][$id]['#attributes']['class'][] = 'draggable'; $form['links'][$id]['#item'] = $element['#item']; // TableDrag: Sort the table row according to its existing/configured weight. $form['links'][$id]['#weight'] = $element['#item']->link->getWeight(); // Add special classes to be used for tabledrag.js. $element['parent']['#attributes']['class'] = array('menu-parent'); $element['weight']['#attributes']['class'] = array('menu-weight'); $element['id']['#attributes']['class'] = array('menu-id'); $form['links'][$id]['title'] = array( array( '#theme' => 'indentation', '#size' => $element['#item']->depth - 1, ), $element['title'], ); $mlid = (int)$links[$id]['#item']->link->getMetaData()['entity_id']; $form['links'][$id]['enabled'] = $element['enabled']; $form['links'][$id]['enabled']['#wrapper_attributes']['class'] = array( 'checkbox', 'menu-enabled' ); $form['links'][$id]['weight'] = $element['weight']; // Operations (dropbutton) column. $form['links'][$id]['operations'] = $element['operations']; $form['links'][$id]['#id'] = $element['id']; $form['links'][$id]['parent'] = $element['parent']; if ($form['links'][$id]['#item']->hasChildren) { $form['links'][$id]['title'][] = array( '#type' => 'big_menu_button', '#title' => t('Show Children'), '#value' => $mlid, '#name' => $mlid, '#attributes' => array('mlid' => $mlid), '#url' => '#', '#description' => t('Show children'), '#ajax' => array( // Function to call when event on form element triggered. 'callback' => array($this, 'bigmenu_ajax_callback'), // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'. 'effect' => 'fade', // Javascript event to trigger Ajax. Currently for: 'onchange'. 'event' => 'click', 'progress' => array( // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'. 'type' => 'throbber', // Message to show along progress graphic. Default: 'Please wait...'. 'message' => NULL, ), ), ); } } } return $form; } /** * @param array $form * @param array $form_state * @return AjaxResponse */ public function bigmenu_ajax_callback(array &$form, array &$form_state) { $elem = $form_state->getTriggeringElement(); $menuLinkId = $elem['#attributes']['mlid']; $params = new MenuTreeParameters(); $params->setRoot($menuLinkId); $menu_link = \Drupal::entityTypeManager()->getStorage('menu_link_content')->load($menuLinkId); // Instantiate an AjaxResponse Object to return. $ajax_response = new AjaxResponse(); // Add a command to execute on form, jQuery .html() replaces content between tags. // In this case, we replace the desription with wheter the username was found or not. $ajax_response->addCommand(new HtmlCommand('form#menu-edit-bigmenu-form', $this->buildOverviewForm($form, $form_state, 15))); // Return the AjaxResponse Object. return $ajax_response; } }
f9c2ed5b5cb2b1a80aa8db536ffb3333224b5c18
[ "JavaScript", "PHP" ]
4
PHP
patrickfweston/bigmenu
0a2e5adffc67893ae8c806c7d3270cfd51d33574
470f663af1748d2061fdc31501adbcf2e80e9f61
refs/heads/master
<repo_name>alexSp84/EsameFSESpinelli<file_sep>/app/src/main/java/com/example/amministratore/esamefsespinelli/RubricaActivity.java package com.example.amministratore.esamefsespinelli; import android.content.Context; import android.content.DialogInterface; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import java.util.ArrayList; public class RubricaActivity extends AppCompatActivity { private RecyclerView contactRecyclerView; private ContactsAdapter contactAdapter; private RecyclerView.LayoutManager contactLayoutManager; private FloatingActionButton addContactBtn; private ArrayList<Contact> cDataset; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rubrica); contactRecyclerView = findViewById(R.id.my_recycler_view); addContactBtn = (FloatingActionButton) findViewById(R.id.action_btn); contactRecyclerView.setHasFixedSize(true); contactLayoutManager = new LinearLayoutManager(this); contactRecyclerView.setLayoutManager(contactLayoutManager); cDataset = new ArrayList<>(); contactAdapter = new ContactsAdapter(cDataset, this); contactRecyclerView.setAdapter(contactAdapter); addContactBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialog(); } }); } private void showAlertDialog() { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); View dialogView = (View) LayoutInflater.from(this).inflate(R.layout.dialog_contact, null); alertBuilder.setView(dialogView); alertBuilder.setTitle(R.string.dialog_contact_title); final EditText nameEdTxt = dialogView.findViewById(R.id.name_ed_txt); final EditText phoneEdTxt = dialogView.findViewById(R.id.phone_ed_txt); alertBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String name = nameEdTxt.getText().toString(); String phone = phoneEdTxt.getText().toString(); if(name.length() != 0 && phone.length() != 0) { Contact contact = new Contact(name, phone); contactAdapter.addContact(contact); } } }); alertBuilder.setNegativeButton(R.string.annulla, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alertBuilder.show(); } } <file_sep>/app/src/main/java/com/example/amministratore/esamefsespinelli/MainActivity.java package com.example.amministratore.esamefsespinelli; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText emailEd, passwordEd; Button buttonLogin, buttonRubrica; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); emailEd = (EditText) findViewById(R.id.email_ed); passwordEd = (EditText) findViewById(R.id.password_ed); buttonLogin = (Button) findViewById(R.id.login); buttonRubrica = findViewById(R.id.rubrica); buttonLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String email = emailEd.getText().toString(); String password = passwordEd.getText().toString(); if(login(email,password)){ Intent accessOk = new Intent(MainActivity.this, SecondActivity.class); accessOk.putExtra("email", email); startActivity(accessOk); } } }); buttonRubrica.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent openRubrica = new Intent(MainActivity.this, RubricaActivity.class); startActivity(openRubrica); } }); } public boolean login(String email, String password){ if (!isValidEmail(email)) { Toast.makeText(MainActivity.this, R.string.noemail, Toast.LENGTH_LONG).show(); } else if (password.length() < 6) { Toast.makeText(MainActivity.this, R.string.nopassword, Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, R.string.success, Toast.LENGTH_LONG).show(); return true; } return false; } public static boolean isValidEmail(CharSequence target) { return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches(); } }
41de5f67d640b872cd871652ae77c55dc29eafd1
[ "Java" ]
2
Java
alexSp84/EsameFSESpinelli
cf6e6aa327c6e725291f41ce89cbc26c053ca156
611078fdfef986f4b07b30c3c454536463243f69
refs/heads/master
<repo_name>heitinder/Heitinder<file_sep>/mustache/datatable_start.mustache.html {{! the row containing the create new and the filter box}} <div class="row"> {{! Add entity link }} <div class="col-ms-3"> {{#createLabel}} <div class="form-group"> <a id="add_entity_link" href="{{createHref}}" class="btn btn-primary btn-full">{{createLabel}}</a> </div> {{/createLabel}} </div> {{! Filter entities link }} <div class="col-ms-9"> <form class="form-inline text-right cp-datatable-filter"> {{#includeFilters}} <div class="form-group"> <label class="sr-only" for="filter">Filter Field</label> <select id="filter" name="filter" class="form-control"> {{#filters}} <option value="{{value}}">{{name}}</option> {{/filters}} </select> </div> {{/includeFilters}} <div class="form-group"> <label class="sr-only" for="filterValue">Filter Value</label> <input type="text" class="form-control required" maxlength="20" id="filterValue" placeholder="{{searchInputPlaceholder}}"> </div> <div class="form-group"> <button id="filter_entity_submit" type="submit" class="btn btn-primary btn-full" disabled> <span class="glyphicon glyphicon-arrow-right" aria-hidden="true"></span> </button> </div> </form> </div> </div> <div class="row"> <div class="col-md-12 cp-filter-criteria" id="cp-filter-criteria"></div> </div> {{! row containing the datatable component}} <div class="row"> <div class="col-ms-12 cp-datatable"> <table id="{{id}}" class="display responsive no-wrap dt-bootstrap" cellspacing="0" width="100%"></table> </div> </div> <file_sep>/datatable/filter.js var $ = require('jquery'), FilterCriteria; FilterCriteria = function () {}; FilterCriteria.prototype.init = function (table, filters) { this.table = table; this.filters = filters; this.el = { _filterForm : $('.cp-datatable-filter'), _filterSubmit : $('#filter_entity_submit'), _filterValue : $('#filterValue'), _filterOption : $('#filter'), _filterCriteria : $('#cp-filter-criteria') } this.bind(); }; FilterCriteria.prototype.bind = function(){ var _view = this, _searchText; //Enable form and bind search event _view.el._filterForm .prop('disabled', false) .on('submit', function(e){ e.preventDefault(); if(_view.el._filterValue.val().trim() && _view.el._filterOption.val()){ _view.add(_view); } }); //Enable submit button on data _view.el._filterValue .on('keyup change', function () { _searchText = $(this).val().trim(); if(_searchText.length >= 1){ _view.el._filterSubmit.addClass('btn-primary').removeAttr('disabled'); }else{ _view.el._filterSubmit.prop('disabled', true).removeClass('btn-primary').removeClass('disabled'); } }); //Attach remove criteria event _view.el._filterCriteria .on('click', '.filter-criteria .close', function(e){ e.preventDefault(); $(this).parent().hide().remove(); _view.remove(_view, $(this).parent().data('col')); }); } FilterCriteria.prototype.template = function(options){ //Criteria HTML var html = "<div class='filter-criteria' data-col='"+options.column+"' data-val='"+options.searchText+"' >"; html += "<button type='button' class='close' aria-label='Close'>"; html += "<span aria-hidden='true'>&times;</span>"; html += "</button>"; html += "<span class='field-name' >"+options.title+":</span><span class='field-value'>"+options.searchText+"</span>"; html += "</div>"; return html; } FilterCriteria.prototype.add = function (_view) { var _searchText, _searchOption; _searchText = _view.el._filterValue.val().trim(); _searchOption = _view.el._filterOption.val(); if (_view.filters[_searchOption] && _searchText) { _view.filters[_searchOption].text = _searchText; //Filter datatable _view.table .column(_view.filters[_searchOption].col) .search(_searchText) .draw(); //Add criteria and disable search input _view.el._filterCriteria.show().append(function(){ _view.el._filterValue.val(''); _view.el._filterOption.val(''); _view.el._filterOption.children("option[value=" + _searchOption + "]").prop('disabled', true); return _view.template({ column: _searchOption, searchText : _searchText, title: _searchOption }); }); } else { _view.table .search('').columns().search('').draw(); } } FilterCriteria.prototype.remove = function (_view, column) { _view.table.search('').columns(_view.filters[column].col).search('').draw(); _view.el._filterOption.children("option[value=" + column + "]").removeAttr('disabled'); } module.exports.FilterCriteria = FilterCriteria;<file_sep>/datatable/index.js var $ = require( 'jquery' ); /*require('datatables.net' ); require('datatables.net-responsive' ); require('datatables.net-responsive-bs'); require('datatables.net-dt/css/jquery.dataTables.css' ); require('datatables.net-responsive-bs/css/responsive.bootstrap.css'); require('./index.scss');*/ $.extend($.fn.dataTable.defaults, { rowId: 'id', stripeClasses:[], lengthChange: false, info: false, responsive: true, filter:true }); module.exports = { }; <file_sep>/dependancies/dateutil.js /** * This js file consists date & time conversion related functions * Author : u408471 * Date : 2/13/2016 */ function formatUTCDate(date) { var dt = date.getUTCDate(); var month = date.getUTCMonth()+1; var year = date.getUTCFullYear(); var hour = date.getUTCHours(); var min = date.getUTCMinutes(); var am = 'AM'; if(hour >= 12){ am = 'PM'; hour = hour - 12; } if(hour == 0){ hour = 12; } if(year < 2000){ year = year + 100; } return (((month < 10 ? '0':'') + month) + "/" + (( dt < 10 ? '0':'')+dt) + "/" + year + " " +((hour < 10?'0':'')+hour) + ":" + (min<10?'0':'') + min + " " +am) ; } function formatDate(date) { var dt = date.getDate(); var month = date.getMonth()+1; var year = date.getFullYear(); var hour = date.getHours(); var min = date.getMinutes(); var am = 'AM'; if(year < 2000){ year = year + 100; } if(hour >= 12){ am = 'PM'; hour = hour - 12; } if(hour == 0){ hour = 12; } return (((month < 10 ? '0':'') + month) + "/" + (( dt < 10 ? '0':'')+dt) + "/" + year + " " +((hour < 10?'0':'')+hour) + ":" + (min<10?'0':'') + min + " " +am) ; } function isDST(t) { //t is the date object to check, returns true if daylight saving time is in effect. var jan = new Date(t.getFullYear(),0,1); var jul = new Date(t.getFullYear(),6,1); return Math.max(jan.getTimezoneOffset(),jul.getTimezoneOffset()) == t.getTimezoneOffset(); } function getUTCDate(ipdate, ipzone){ if(ipzone == null){ ipzone = 'PST'; } var dateStr = ipdate.split(' '); if(dateStr.length > 3){ ipdate = dateStr[0]+' '+dateStr[1]+' '+dateStr[2]; } var date = validateYear(new Date(ipdate)); var zoneoffset = getOffset(ipzone,date); var diffoffset = date.getTimezoneOffset() - zoneoffset; var dt = new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes()-diffoffset); return formatUTCDate(dt); } function getUTCDateinZone(utcdate, ipzone){ if(ipzone == null){ ipzone = 'PST'; } var utcDt = validateYear(new Date(utcdate)); var zoneoffset = getOffset(ipzone,utcDt); var zonedate = new Date(utcDt.getFullYear(),utcDt.getMonth(),utcDt.getDate(),utcDt.getHours(),utcDt.getMinutes()-zoneoffset); return formatDate(zonedate); } function getOffset(ipzone,ipDate){ var zoneoffset; if(MASTER_TIMEZONE == null){ $.ajax({ type: "GET", url: baseURLCompany+'timezones', dataType:'JSON', async:false, success:function(data){ if(data.success == true) { sessionStorage.setItem("timezones", JSON.stringify(data.result)); MASTER_TIMEZONE = data.result; } } }); } $.each(MASTER_TIMEZONE, function(index, element) { if(ipzone == element.timezoneCode){ zoneoffset = element.offset; //alert(isDST(ipDate)); if(!isDST(ipDate) && (ipzone == "EST" || ipzone == "CST" || ipzone == "PST")){ zoneoffset = zoneoffset - 60; } } }); return zoneoffset; } function getcompanyTimezone(companyid){ var companytimezone = "PST"; if(COMPANY_TIMEZONE != null){ var companyzones = jQuery.parseJSON(COMPANY_TIMEZONE); $.each(companyzones, function(index, element) { if(companyid == element.companyId){ companytimezone = element.timeZone; } }); } return companytimezone; } function getfacilityTimezone(facilityid){ var facilitytimezone = "PST"; if(FACILITY_TIMEZONE != null){ var facilityzones = jQuery.parseJSON(FACILITY_TIMEZONE); $.each(facilityzones, function(index, element) { if(facilityid == element.facilityId){ facilitytimezone = element.timeZone; } }); } return facilitytimezone; } function validateCurrentDate(ipdate,ipzone){ var flag = true; var currdate = new Date(); var currentUtcdate = new Date(currdate.getUTCFullYear(),currdate.getUTCMonth(),currdate.getUTCDate(),currdate.getUTCHours(),currdate.getUTCMinutes()); var inputDate = validateYear(new Date(ipdate)); if(Date.parse(inputDate) < Date.parse(currentUtcdate)){ flag = false; } return flag; } function getLoyaltyEndDate(ipdate,ipzone){ var dateStr = ipdate.split(' '); if(dateStr.length > 3){ ipdate = dateStr[0]+' '+dateStr[1]+' '+dateStr[2]; } var date = validateYear(new Date(ipdate)); var zoneoffset = getOffset(ipzone,date); var diffoffset = date.getTimezoneOffset() - zoneoffset; var dt = new Date(date.getFullYear()+300,date.getMonth(),date.getDate(),date.getHours(),date.getMinutes()-diffoffset); return formatUTCDate(dt); } function validateSaveDates(ipStartdt,ipEnddt){ var flag = true; var currentUtcdate = formatUTCDate(new Date()); var stdate = validateYear(new Date(ipStartdt)); var eddate = validateYear(new Date(ipEnddt)); var curdate = new Date(currentUtcdate); if(stdate < curdate){ showAlert("Start Date & Time should be later than Current Date & Time",false,'Error',null); flag = false; } if(eddate < curdate){ showAlert("End Date & Time should be later than Start Date & Time",false,'Error',null); flag = false; } if(eddate <= stdate){ showAlert("End date should be later than Start date",false,'Error',null); flag = false; } return flag; } function validateEditDates(ipStartdt,ipEnddt){ var flag = true; var currentUtcdate = formatUTCDate(new Date()); var stdate = validateYear(new Date(ipStartdt)); var eddate = validateYear(new Date(ipEnddt)); var curdate = new Date(currentUtcdate); if(eddate < curdate){ showAlert("End Date & Time should be later than Start Date & Time",false,'Error',null); flag = false; } if(eddate < stdate){ showAlert("End date should be later than Start date",false,'Error',null); flag = false; } return flag; } function validateLoyaltyPgmDate(ipStartdt){ var flag = true; var currentUtcdate = formatUTCDate(new Date()); var stdate = validateYear(new Date(ipStartdt)); var curdate = validateYear(new Date(currentUtcdate)); if(stdate < curdate){ showAlert("Start Date & Time should be later than Current Date & Time",false,'Error',null); flag = false; } return flag; } function validateYear(ipdate){ if(ipdate.getFullYear() < 2000){ ipdate.setFullYear(ipdate.getFullYear() + 100); } return ipdate; }
96b3bfabb00f2bc526e1f51ebb0675c107748ab8
[ "JavaScript", "HTML" ]
4
HTML
heitinder/Heitinder
bc54b8aba1ad0efa56487e2f524b25be825ef863
fbbde51d74bc659fed745625955c1f85e89b1073
refs/heads/master
<repo_name>Nagisachan/OS-Lab3-56070501053<file_sep>/fifo.c #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]){ int numberOfJob; int *noJob; int *timeArrive; int *timeUse; int *turnaroundTime; int *responseTime; float sumTimeUsed = 0; float sumTurnaroundTime = 0; float sumResponseTime = 0; FILE* file = fopen (argv[1], "r"); int i = 0; fscanf (file, "%d", &numberOfJob); noJob = (int*)malloc(numberOfJob*sizeof(int)); timeArrive = (int*)malloc(numberOfJob*sizeof(int)); timeUse = (int*)malloc(numberOfJob*sizeof(int)); responseTime = (int*)malloc(numberOfJob*sizeof(int)); turnaroundTime = (int*)malloc(numberOfJob*sizeof(int)); for(i=0;i<numberOfJob;i++){ fscanf(file,"%d %d %d",&noJob[i],&timeArrive[i],&timeUse[i]); } printf("No of Job = %d\n",numberOfJob); for(i=0;i<numberOfJob;i++){ printf("%d %d %d\n",noJob[i],timeArrive[i],timeUse[i]); } responseTime[0] = 0; turnaroundTime[0] = responseTime[0] + timeUse[0]; int systemTimeUsed = turnaroundTime[0]; for(i=1;i<numberOfJob;i++) { if(systemTimeUsed < timeArrive[i]) { responseTime[i] = 0; systemTimeUsed += timeArrive[i] + timeUse[i]; } else { responseTime[i] = systemTimeUsed - timeArrive[i]; systemTimeUsed += timeUse[i]; } turnaroundTime[i] = responseTime[i] + timeUse[i]; } for(i=0;i<numberOfJob;i++) { sumResponseTime += responseTime[i]; sumTimeUsed += timeUse[i]; sumTurnaroundTime += turnaroundTime[i]; printf("responseTime = %d\n", responseTime[i]); printf("timeUsed = %d\n", timeUse[i]); printf("turnaroundTime = %d\n\n", turnaroundTime[i]); } printf("avgResponseTime = %.2f\n", sumResponseTime/5); printf("avgTimeUsed = %.2f\n", sumTimeUsed/5); printf("avgTurnaroundTime = %.2f\n", sumTurnaroundTime/5); fclose (file); } <file_sep>/round roubin.c #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]){ int numberOfJob; int *noJob; int *timeArrive; int *timeUse; int *rt; FILE* file = fopen (argv[1], "r"); int i = 0; fscanf (file, "%d", &numberOfJob); noJob = (int*)malloc(numberOfJob*sizeof(int)); timeArrive = (int*)malloc(numberOfJob*sizeof(int)); timeUse = (int*)malloc(numberOfJob*sizeof(int)); rt = (int*)malloc(numberOfJob*sizeof(int)); for(i=0;i<numberOfJob;i++){ fscanf(file,"%d %d %d",&noJob[i],&timeArrive[i],&timeUse[i]); } printf("No of Job = %d\n",numberOfJob); for(i=0;i<numberOfJob;i++){ printf("%d %d %d\n",noJob[i],timeArrive[i],timeUse[i]); } int j=0,n = numberOfJob,time,remain = numberOfJob,flag=0; int ts = 2; //time slice int sum_wait=0,sum_turnaround=0; //at = arrive time, bt = burst time, rt = current time in each node int ganttP[50],ganttStartTime[50]; for(i=0;i<n;i++) { rt[i]=timeUse[i]; } printf("\n\nProcess\t|Turnaround time|waiting time\n\n"); for(time=0,i=0;remain!=0;) { if(rt[i]<=ts && rt[i]>0) { ganttP[j]=i+1; ganttStartTime[j++]=time; time+=rt[i]; rt[i]=0; flag=1; } else if(rt[i]>0) { ganttP[j]=i+1; ganttStartTime[j++]=time; rt[i]-=ts; time+=ts; } if(rt[i]==0 && flag==1) { remain--; printf("P[%d]\t|\t%d\t|\t%d\n",i+1,time-timeArrive[i],time-timeArrive[i]-timeUse[i]); sum_wait+=time-timeArrive[i]-timeUse[i]; sum_turnaround+=time-timeArrive[i]; flag=0; } if(i==n-1) i=0; else if(timeArrive[i+1]<=time) i++; } printf("\nAvg sum_wait = %f\n",sum_wait*1.0/n); printf("Avg sum_turnaround = %f",sum_turnaround*1.0/n); printf("\n\n"); for(i=0;i<j;i++) { printf("(P[%d],%d) ",ganttP[i],ganttStartTime[i]); } printf("\n"); fclose (file); }<file_sep>/input.c #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]){ int numberOfJob; int *noJob; int *timeArrive; int *timeUse; FILE* file = fopen (argv[1], "r"); int i = 0; fscanf (file, "%d", &numberOfJob); noJob = (int*)malloc(numberOfJob*sizeof(int)); timeArrive = (int*)malloc(numberOfJob*sizeof(int)); timeUse = (int*)malloc(numberOfJob*sizeof(int)); for(i=0;i<numberOfJob;i++){ fscanf(file,"%d %d %d",&noJob[i],&timeArrive[i],&timeUse[i]); } printf("No of Job = %d\n",numberOfJob); for(i=0;i<numberOfJob,i++){ printf("%d %d %d\n",noJob[i],timeArrive[i],timeUse[i]); } fclose (file); }<file_sep>/README.md # OS-Lab3-56070501053 Lab3 is using FIFO and RR The example of FIFO and RR use in Linux
4bc71ce6b6319b611fc8af6ec01258ebdeddd90e
[ "Markdown", "C" ]
4
C
Nagisachan/OS-Lab3-56070501053
e76f4b4f400b07ff0d15beb5c0b829ba35883903
3d08e5645844f9576ae052ff905d26cca900351c
refs/heads/main
<repo_name>ardaayvatas/Java-OOP-Exercises<file_sep>/Flight/src/Expense.java public interface Expense { double computeExpense(); } <file_sep>/Product/src/Product.java import java.util.Scanner; import javax.swing.JOptionPane; public class Product implements Payable{ public int id; private String brand; private String model; private int stock; private String isShippingFree; static int productCount = 0; String str; Scanner sc = new Scanner(System.in); CategoryForProducts category; public Product(){ str = JOptionPane.showInputDialog("ID:"); //System.out.printf("%s\n", "ID:"); //str= sc.nextLine(); //System.out.printf("%s\n", "ID:"); //str= sc.nextLine(); setId(Integer.parseInt(str)); str = JOptionPane.showInputDialog("Brand:"); //System.out.printf("%s\n", "Brand:"); setBrand(str); //System.out.printf("%s\n", "Model:"); str = JOptionPane.showInputDialog("Model:"); setModel(str); //System.out.printf("%s\n", "Free Shipping(y/n):"); str = JOptionPane.showInputDialog("Free Shipping(y/n):"); setShipping(str); str = JOptionPane.showInputDialog("Stock:"); //System.out.printf("%s\n", "Stock:"); setStock(Integer.parseInt(str)); productCount++; category=CategoryForProducts.SERVICE; } void displayProductInfo(){ JOptionPane.showMessageDialog(null,"id:"+id+"\n"+"brand:"+brand+"\n"+"model:"+model+"\n"+"stock:"+stock+"\n"+"category:"+category+" with starting price of "+category.getPrice()+"\n"+"shipping:"+isShippingFree+"\n","Display Product Info",JOptionPane.INFORMATION_MESSAGE); /*System.out.println("id:"+id+"\n"+ "brand:"+brand+"\n"+ "model:"+model+"\n"+ "stock:"+stock+"\n"+ "category:"+category+" with starting price of "+category.getPrice()+"\n"+ "shipping:"+isShippingFree+"\n");*/ } public void setId(int Id) { this.id = Id; } public int getId() { return this.id; } public void setStock(int Stock) { this.stock = Stock; } public int getStock() { return this.stock; } public void setBrand(String Brand) { this.brand = Brand; } public String getBrand() { return this.brand; } public void setModel(String Model) { this.model = Model; } public String getModel() { return this.model; } public void setShipping(String shipping) { this.isShippingFree = shipping; } public String getShipping() { return this.isShippingFree; } public Product(CategoryForProducts cat){ this(); this.category = cat; } public double calculatePayment() { double productpay=0; if(category.getPrice()== "$1000") { productpay=1000; } else if(category.getPrice()== "$500") { productpay=500; } else if(category.getPrice()== "$100") { productpay=100; } else if(category.getPrice()== "$200") { productpay=200; } else if(category.getPrice()== "$20") { productpay=20; } if(isShippingFree.equals("n")) { productpay=productpay+10; } return productpay; } } <file_sep>/Flight/src/Flight.java import java.util.Scanner; import java.util.InputMismatchException; public abstract class Flight implements Expense,Comparable<Flight>{ int flightNo; Datetime departureTime; Datetime arrivalTime; String originCity; String destinationCity; int maxLoadOfPlane; int flightDistance; double distanceRate; int flightPrice; boolean loopcontinueforflightno=true; boolean loopcontinueformaxLoadOfPlane=true; public Flight(){ Scanner sc=new Scanner(System.in); System.out.println(); //System.out.printf("Enter the flight no: "); do { try { System.out.printf("Enter the flight no: "); flightNo=sc.nextInt(); sc.nextLine(); loopcontinueforflightno=false; } catch(InputMismatchException inputMismatchException) { System.err.println("Flight no cannot be a String"); sc.nextLine(); } }while(loopcontinueforflightno); //flightNo=sc.nextInt(); //sc.nextLine(); System.out.printf("Enter the Departure Time;"); System.out.println(); departureTime= new Datetime(); System.out.printf("Enter the Arrival Time;"); System.out.println(); arrivalTime= new Datetime(); System.out.printf("Enter the Origin City: "); originCity=sc.nextLine(); System.out.printf("Enter the Destination City: "); destinationCity=sc.nextLine(); do { try { System.out.printf("Enter the Max Load: "); maxLoadOfPlane=sc.nextInt(); sc.nextLine(); loopcontinueformaxLoadOfPlane=false; } catch(InputMismatchException inputMismatchException) { System.err.println("Max Load cannot be a String"); sc.nextLine(); } }while(loopcontinueformaxLoadOfPlane); //System.out.printf("Enter the Max Load: "); //maxLoadOfPlane=sc.nextInt(); //sc.nextLine(); } public int getflightNo() { return flightNo; } public String getoriginCity() { return originCity; } public void displayFlightInformation() { System.out.println("Flight(no: "+flightNo+") "+"from "+originCity+" to "+destinationCity+" departs at "+departureTime.toString()+" and lands at \n"+arrivalTime.toString()+" with duration of "+calculateDuration()+" hour(s)"); System.out.println(); } public String getdestinationCity() { return destinationCity; } public String toStringofcities() { return "from" +originCity+" to "+destinationCity; } public int calculateDuration() { if(arrivalTime.day==departureTime.day) { return arrivalTime.hour-departureTime.hour; } else return ((arrivalTime.day-departureTime.day)*24)+arrivalTime.hour-departureTime.hour; } public abstract double computeExpense(); public int compareTo(Flight fl) { int startdateyeartomonth,flstartdateyeartomonth,startdateextra,flstartdateextra; startdateyeartomonth=(departureTime.year*12)+departureTime.month; flstartdateyeartomonth=(fl.departureTime.year*12)+fl.departureTime.month; startdateextra=(departureTime.day*24*60)+(departureTime.hour*60)+departureTime.minute; flstartdateextra=(fl.departureTime.day*24*60)+(fl.departureTime.hour*60)+fl.departureTime.minute; if(startdateyeartomonth==flstartdateyeartomonth) { if(startdateextra==flstartdateextra) return 0; else if(startdateextra>flstartdateextra) return 1; else return 0; } else if(startdateyeartomonth>flstartdateyeartomonth) { return 1; } else return -1; } }<file_sep>/Product/src/Employee.java import java.util.Scanner; import java.util.InputMismatchException; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.regex.PatternSyntaxException; import javax.swing.JOptionPane; abstract class Employee implements Payable,Comparable <Employee>{ int id; String name; String department="Tech"; Date startDate; double insuranceRate; String str; Scanner sc = new Scanner(System.in); boolean loopcontroller=true; String s; Employee(){ str = JOptionPane.showInputDialog("ID:"); //System.out.printf("%s\n", "ID:"); //str= sc.nextLine(); id =Integer.parseInt(str); do { try { name = JOptionPane.showInputDialog("Enter name"); //System.out.printf("%s\n", "Enter name"); //name = sc.nextLine(); s=name; if(s.matches("^[a-zA-Z ]+$")) { loopcontroller=false; } else { throw new InputMismatchException(); } } catch(InputMismatchException inputmismatchexception){ JOptionPane.showMessageDialog(null, "Name cannot any numbers!","Error",JOptionPane.ERROR_MESSAGE); //System.err.println("Name cannot contain any numbers!"); } }while(loopcontroller); startDate = new Date(); } public Employee(String department){ this(); this.department=department; } public void displayEmployeeInfo(){ System.out.println("ID: "+id+"\n"+ "Name: "+name+"\n"+ "Department: "+department+"\n"+ startDate.toString()+"\n"); } public abstract double calculatePayment(); public int compareTo(Employee em) { int startdateyeartomonth,emstartdateyeartomonth,startdateextra,emstartdateextra; startdateyeartomonth=(startDate.year*12)+startDate.month; emstartdateyeartomonth=(em.startDate.year*12)+em.startDate.month; startdateextra=(startDate.day*24*60)+(startDate.hour*60)+startDate.minute; emstartdateextra=(em.startDate.day*24*60)+(em.startDate.hour*60)+em.startDate.minute; if(startdateyeartomonth==emstartdateyeartomonth) { if(startdateextra==emstartdateextra) return 0; else if(startdateextra>emstartdateextra) return 1; else return 0; } else if(startdateyeartomonth>emstartdateyeartomonth) { return 1; } else return -1; } } <file_sep>/README.md # Java-OOP-Exercises Object Oriented Programming exercises by using Java <file_sep>/Product/src/Date.java import java.util.Scanner; import javax.swing.JOptionPane; public class Date { int day; int month; int year; int hour; int minute; String str; Scanner sc = new Scanner(System.in); public Date(){ str = JOptionPane.showInputDialog("Enter day:"); //System.out.println("Enter day:"); //str= sc.nextLine(); day =Integer.parseInt(str); str = JOptionPane.showInputDialog("Enter month:"); //System.out.println("Enter month:"); //str= sc.nextLine(); month =Integer.parseInt(str); str = JOptionPane.showInputDialog("Enter year:"); //System.out.println("Enter year:"); //str= sc.nextLine(); year =Integer.parseInt(str); str = JOptionPane.showInputDialog("Enter hour:"); //System.out.println("Enter hour:"); //str= sc.nextLine(); hour =Integer.parseInt(str); str = JOptionPane.showInputDialog("Enter minute:"); //System.out.println("Enter minute:"); //str= sc.nextLine(); minute =Integer.parseInt(str); } public String toString() { return String.format("Start Date: %02d/%02d/%02d %02d:%02d",day,month,year,hour,minute); } } <file_sep>/Product/src/HourlyEmployee.java import java.util.Scanner; import javax.swing.JOptionPane; public class HourlyEmployee extends Employee{ int workHour; double payment; HourlyEmployee(){ super(); Scanner sc=new Scanner(System.in); str = JOptionPane.showInputDialog("Payment:"); //System.out.println("Payment:"); payment=Double.parseDouble(str); str = JOptionPane.showInputDialog("Work Hours:"); workHour=Integer.parseInt(str); //System.out.println("Work Hours:"); //workHour=sc.nextInt(); //sc.nextLine(); } @Override public void displayEmployeeInfo() { JOptionPane.showMessageDialog(null, "ID: "+id+"\n"+"Name: "+name+"\n"+"Department: "+department+"\n"+startDate.toString()+"\n"+"Work hours :"+workHour+"\n"+"Daily Payment: "+calculatePayment()+"\n","Hourly Employee Info",JOptionPane.INFORMATION_MESSAGE); //System.out.println("ID: "+id+"\n"+ // "Name: "+name+"\n"+ //"Department: "+department+"\n"+ //startDate.toString()+"\n"+ //"Work hours: "+ workHour+"\n"+ //"Daily payment: "+calculatePayment()+"\n"); } public double calculatePayment() { if(department.equals("Tech")) { insuranceRate=20; } else if(department.equals("Finance")) { insuranceRate=10; } else { insuranceRate=5; } return (workHour*payment)+(workHour*payment*insuranceRate/100); } } <file_sep>/Flight/src/CheckInCounter.java import java.util.Locale; import java.util.Scanner; public class CheckInCounter extends Staff{ int overTimeHours; double overTimeRate; public CheckInCounter() { super(); Scanner sc=new Scanner(System.in); sc.useLocale(Locale.US); System.out.println("overTimeHours:"); overTimeHours=sc.nextInt(); sc.nextLine(); System.out.println("overTimeRate:"); overTimeRate=sc.nextDouble(); sc.nextLine(); } public double computeExpense() { return Salary+(overTimeRate*overTimeHours); } } <file_sep>/Flight/src/Ticket.java import java.util.Scanner; public class Ticket implements Expense{ int ticketNo; Flight flight; int passengerinfo; String seat; String clas; public Ticket(int ticketNo,Flight flight) { Scanner sc=new Scanner(System.in); System.out.println("Enter your Passenger Information;"); System.out.println("ID:"); passengerinfo=sc.nextInt(); sc.nextLine(); System.out.printf("Enter your Seat number: "); seat=sc.nextLine(); System.out.printf("Enter your Class: "); clas=sc.nextLine(); this.ticketNo=ticketNo; System.out.printf("Your ticket no is: "+ ticketNo); System.out.println(); System.out.println(); this.flight=flight; } public double computeExpense() { return 0; } } <file_sep>/Flight/src/Datetime.java import java.util.InputMismatchException; import java.util.Scanner; public class Datetime { int day; int month; int year; int hour; int minute; boolean loopcontinueforday=true; boolean loopcontinueformonth=true; boolean loopcontinueforyear=true; boolean loopcontinueforhour=true; boolean loopcontinueforminute=true; public Datetime() { Scanner sc=new Scanner(System.in); do { try { System.out.printf("Year: "); year=sc.nextInt(); sc.nextLine(); loopcontinueforyear=false; } catch(InputMismatchException inputMismatchException) { System.err.println("Year cannot be a String"); sc.nextLine(); } }while(loopcontinueforyear); //System.out.printf("Year: "); //year=sc.nextInt(); //sc.nextLine(); do { try { System.out.printf("Month: "); month=sc.nextInt(); sc.nextLine(); loopcontinueformonth=false; } catch(InputMismatchException inputMismatchException) { System.err.println("Month cannot be a String"); sc.nextLine(); } }while(loopcontinueformonth); //System.out.printf("Month: "); //month=sc.nextInt(); //sc.nextLine(); do { try { System.out.printf("Day: "); day=sc.nextInt(); sc.nextLine(); loopcontinueforday=false; } catch(InputMismatchException inputMismatchException) { System.err.println("Day cannot be a String"); sc.nextLine(); } }while(loopcontinueforday); //System.out.printf("Day: "); //day=sc.nextInt(); //sc.nextLine(); do { try { System.out.printf("Hour: "); hour=sc.nextInt(); sc.nextLine(); loopcontinueforhour=false; } catch(InputMismatchException inputMismatchException) { System.err.println("Hour cannot be a String"); sc.nextLine(); } }while(loopcontinueforhour); //System.out.printf("Hour: "); //hour=sc.nextInt(); //sc.nextLine(); do { try { System.out.printf("Minute: "); minute=sc.nextInt(); sc.nextLine(); loopcontinueforminute=false; } catch(InputMismatchException inputMismatchException) { System.err.println("Minute cannot be a String"); sc.nextLine(); } }while(loopcontinueforminute); //System.out.printf("Minute: "); //minute=sc.nextInt(); //sc.nextLine(); } public String toString() { return String.format("%02d/%02d/%02d %02d:%02d:00",day,month,year,hour,minute); } } <file_sep>/Product/src/Main.java import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import javax.swing.JOptionPane; public class Main { public static void main(String args[]) { ArrayList<Payable> pay = new ArrayList<Payable>(); Scanner sc = new Scanner(System.in); int choice; String department; CategoryForProducts cat; String str; int Cindex=0,idno,idcheck=0,productidno=0; Customer[] CustomerArray= new Customer[10]; int subchoice; ArrayList<Employee> elfordate = new ArrayList<Employee>(); ArrayList<Employee> elforname = new ArrayList<Employee>(); HashMap<Customer,ArrayList<Product>> mymap = new HashMap <Customer,ArrayList<Product>>(); while(true) { str =JOptionPane.showInputDialog("1. Create a new Product \n" +"2. Create a new Product with Category \n" +"3. Create a new Employee \n" +"4. Create a new Employee with department \n" +"5. Display Product information \n" +"6. Display Employee information \n" +"7. Display number of Products \n" +"8. Calculate Total Payment \n" +"9. Create a Customer \n" +"10. Buy Products \n" +"11. Display Customer Information \n" +"0.Exit\n"); /*System.out.println("1. Create a new Product \n" +"2. Create a new Product with Category \n" +"3. Create a new Employee \n" +"4. Create a new Employee with department \n" +"5. Display Product information \n" +"6. Display Employee information \n" +"7. Display number of Products \n" +"8. Calculate Total Payment \n" +"9. Create a Customer \n" +"10. Buy Products \n" +"11. Display Customer Information \n" +"0.Exit");*/ //str= sc.nextLine(); choice =Integer.parseInt(str); if(choice == 0) { sc.close(); break; } else if(choice == 1) { pay.add(new Product()); } else if(choice == 2) { String categoryselect = JOptionPane.showInputDialog("Enter Category:"); //System.out.println("Enter Category:"); //String categoryselect = sc.nextLine(); categoryselect=categoryselect.toUpperCase(); cat=CategoryForProducts.valueOf(categoryselect); pay.add(new Product(cat)); } else if(choice == 3) { str = JOptionPane.showInputDialog("1. Create a new Full Time Employee \n" +"2. Create a new Hourly Employee"); //System.out.println("1.Create a new Full Time Employee \n" // +"2.Create a new Hourly Employee"); //str= sc.nextLine(); subchoice =Integer.parseInt(str); if(subchoice==1) { pay.add(new FullTimeEmployee()); } else if(subchoice==2) { pay.add(new HourlyEmployee()); } } else if(choice == 4) { str = JOptionPane.showInputDialog("1.Create a new Full Time Employee \n"+"2.Create a new Hourly Employee \n"); //System.out.println("1.Create a new Full Time Employee \n" // +"2.Create a new Hourly Employee \n"); //str= sc.nextLine(); subchoice =Integer.parseInt(str); if(subchoice==1) { department = JOptionPane.showInputDialog("Department:"); //System.out.println("Department:"); //department=sc.nextLine(); pay.add(new FullTimeEmployee()); if(pay.get(pay.size()-1) instanceof FullTimeEmployee) { FullTimeEmployee fte=(FullTimeEmployee) pay.get(pay.size()-1); fte.department=department; } } else if(subchoice==2) { department = JOptionPane.showInputDialog("Department:"); //System.out.println("Department:"); //department=sc.nextLine(); pay.add(new HourlyEmployee()); if(pay.get(pay.size()-1) instanceof HourlyEmployee) { HourlyEmployee he=(HourlyEmployee) pay.get(pay.size()-1); he.department=department; } } } else if(choice == 5) { String x = JOptionPane.showInputDialog("Enter product id"); //System.out.println("Enter product id"); //int id = sc.nextInt(); //sc.nextLine(); int id=Integer.parseInt(x); boolean found = false; for (int i=0; i<=pay.size(); i++) { if (pay.get(i) != null){ if(pay.get(i) instanceof Product) { Product p= (Product) pay.get(i); if(p.getId()== id) { found = true; p.displayProductInfo(); break; } } } } if(!found) System.out.println("Product with the given id is not found."); } else if(choice == 6) { //System.out.println("1.Sorted by start date"); //System.out.println("2.Sorted by name"); str = JOptionPane.showInputDialog("1.Sorted by start date \n" +"2.Sorted by name"); //subchoice = sc.nextInt(); //sc.nextLine(); subchoice = Integer.parseInt(str); if(subchoice==1) { for (int i = 0; i<=pay.size()-1; i++) { if (pay.get(i) != null) { if(pay.get(i) instanceof Employee) { Employee e=(Employee) pay.get(i); elfordate.add(e); } } } Collections.sort(elfordate); for(Employee em:elfordate) { em.displayEmployeeInfo(); } } else if(subchoice==2) { for (int i = 0; i<=pay.size()-1; i++) { if (pay.get(i) != null) { if(pay.get(i) instanceof Employee) { Employee e=(Employee) pay.get(i); elforname.add(e); } } } NameCompare nameC= new NameCompare(); Collections.sort(elforname, nameC); for(Employee em:elforname) { em.displayEmployeeInfo(); } } } else if(choice == 7) { JOptionPane.showMessageDialog(null, "Number of Products:"+Product.productCount,"Display Number of Products",JOptionPane.INFORMATION_MESSAGE); //System.out.println("Number of Products:"+Product.productCount); } else if(choice == 8) { double totalpayment=0; for (int i = 0; i<=pay.size()-1; i++) { if(pay.get(i) != null) { if(pay.get(i) instanceof Product) { Product p = (Product) pay.get(i); totalpayment=totalpayment+p.calculatePayment(); } else if(pay.get(i) instanceof FullTimeEmployee) { FullTimeEmployee fte = (FullTimeEmployee) pay.get(i); totalpayment=totalpayment + fte.calculatePayment(); } else if(pay.get(i) instanceof HourlyEmployee) { HourlyEmployee he=(HourlyEmployee) pay.get(i); totalpayment=totalpayment+he.calculatePayment(); } } } JOptionPane.showMessageDialog(null, "Total Payment:"+totalpayment,"Display Total Payment",JOptionPane.INFORMATION_MESSAGE); //System.out.println("Total Payment:"+totalpayment+"\n"); } else if(choice == 9) { CustomerArray[Cindex] = new Customer(); mymap.put(CustomerArray[Cindex], CustomerArray[Cindex].shoppingCart); Cindex++; } else if(choice == 10) { productidno=0; while(productidno!=-1) { //System.out.println("Enter customer id"); str = JOptionPane.showInputDialog("Enter customer id\n"); //idno=sc.nextInt(); //sc.nextLine(); idno= Integer.parseInt(str); for(Customer e:mymap.keySet()) { if(e.id== idno) { idcheck=1; //System.out.println("Enter product id that you want to buy"); str = JOptionPane.showInputDialog("Enter product id that you want to buy"); //productidno=sc.nextInt(); //sc.nextLine(); productidno=Integer.parseInt(str); while(productidno!=-1) { for (int x=0; x<=pay.size()-1; x++) { if (pay.get(x) != null){ if(pay.get(x) instanceof Product) { Product p= (Product) pay.get(x); if(p.getId()== productidno) { e.shoppingCart.add(p); //System.out.println("Product with "+productidno+" is added to cart"); JOptionPane.showMessageDialog(null,"Product with "+productidno+" is added to cart","ADDED",JOptionPane.INFORMATION_MESSAGE); break; } else if(x==pay.size()-1 && p.getId()!=productidno) { //System.out.println("Product with the given id is not found"); JOptionPane.showMessageDialog(null,"Product with the given id is not found","NOT FOUND",JOptionPane.WARNING_MESSAGE); } } } } //System.out.println("Enter product id that you want to buy"); str = JOptionPane.showInputDialog("Enter product id that you want to buy"); //productidno=sc.nextInt(); //sc.nextLine(); productidno=Integer.parseInt(str); } if(productidno==-1) { break; } } } if(idcheck==0) { //System.out.println("Customer with the given id is not found"); JOptionPane.showMessageDialog(null,"Customer with the given id is not found","NOT FOUND",JOptionPane.WARNING_MESSAGE); } } } else if(choice == 11) { for(Customer cus:mymap.keySet()) { cus.DisplayCustomerInfo(); } } } } } <file_sep>/Flight/src/ThreeLegFlight.java import java.util.Locale; import java.util.Scanner; public class ThreeLegFlight extends TwoLegFlight { Datetime ThreeLegDeparturetime; Datetime ThreeLegArrivaltime; String ThreeLegDestinationCity; int thirdTimeZoneDifference; int thirdflightDistance; double thirddistanceRate; int thirdflightPrice; ThreeLegFlight(){ super(); Scanner sc=new Scanner(System.in); sc.useLocale(Locale.US); System.out.println("Enter the third Departure Time;"); ThreeLegDeparturetime = new Datetime(); System.out.println("Enter the third Arrival Time;"); ThreeLegArrivaltime = new Datetime(); System.out.printf("Enter the third Destination City : "); ThreeLegDestinationCity = sc.nextLine(); System.out.printf("Enter the Time Zone Difference: "); thirdTimeZoneDifference=sc.nextInt(); sc.nextLine(); System.out.printf("Enter the Flight Distance: "); thirdflightDistance=sc.nextInt(); sc.nextLine(); System.out.printf("Enter the Distance Rate: "); thirddistanceRate=sc.nextDouble(); sc.nextLine(); System.out.printf("Enter the Flight Price: "); thirdflightPrice=sc.nextInt(); sc.nextLine(); System.out.println(""); } @Override public String toStringofcities() { return String.format("from %s to %s ", super.getoriginCity(),ThreeLegDestinationCity); } @Override public void displayFlightInformation() { System.out.println("Flight(no: "+getflightNo()+") "+toStringofcities()+" departs at "+departureTime.toString()+" and lands at \n"+ThreeLegArrivaltime.toString()+" with duration of "+calculateDuration()+" hour(s)"); System.out.println(""); } @Override public int calculateDuration() { if(ThreeLegArrivaltime.day==ThreeLegDeparturetime.day) { return ThreeLegArrivaltime.hour-ThreeLegDeparturetime.hour+super.calculateDuration()+thirdTimeZoneDifference; } else return ((ThreeLegArrivaltime.day-ThreeLegDeparturetime.day)*24)+ThreeLegArrivaltime.hour-ThreeLegDeparturetime.hour+super.calculateDuration()+thirdTimeZoneDifference; } public double computeExpense() { return super.computeExpense()+thirdflightPrice-(thirdflightDistance*thirddistanceRate); } }
e5df652ef72e2226bd4050dbad527f9770fc8920
[ "Markdown", "Java" ]
12
Java
ardaayvatas/Java-OOP-Exercises
114548d2dbbfc195aec8d58ee114e456d9ca1d72
d4be08b2b4b584e996c6ec49894705b5bd0934b7
refs/heads/master
<file_sep># -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "hiking" s.version = "0.1.0" s.author = "<NAME>" s.email = "<EMAIL>" s.summary = "A tiny xpath application written with the camping microframework." s.description = "A tiny xpath application written with the camping microframework that is used to test out xpath statements." s.homepage = "http://ebot.github.com/hiking" s.add_dependency 'camping', '= 1.5.0' s.files = %w(README bin/go_hiking public/hiking.rb test/test_hiking.rb) s.executables = ["go_hiking"] s.require_paths = ["public"] end<file_sep>#!/usr/bin/env ruby require 'camping' require "rexml/document" include REXML Camping.goes :Hiking module Hiking::Controllers class Index < R '/' def get @xml = input.xml @xpath = input.xpath unless @xml == nil doc = Document.new input.xml @results = XPath.match doc, input.xpath else @xml = "<test>\r\n<item number=\"1\">First Item</item>\r\n</test>" end render :index end def post get end end class Style < R '/style.css' def get @headers["Content-Type"] = "text/css; charset=utf-8" @body = %{ body { background-color: black; color: white; font-family: Courier New; font-size: small; } h1 { color: green; font-size: 175%; margin: 0; padding: 10px; border-bottom: solid 1px white; } div.content { padding: 10px 0px 0px 10px; } h2 { color: green; font-size: 150%; border-bottom: solid 1px white; width: 250px; } strong { color: yellow; font-size: 115% } input, textarea, button { border: solid 1px white; background-color: #4B4B4B; color: white; } button {cursor: pointer;} a { color:white; text-decoration:underline; } a:link { color:white; text-decoration:underline; } a:visited { color:white; text-decoration:underline; } a:active { color:white; text-decoration:none; } a:hover { color:yellow; text-decoration: underline; } div.footer { padding: 5px 0px 5px 10px; margin-top: 5px; border-top: solid 1px gray; text-align: center; font-style: italic; font-size: 90%; color: lightgray; clear: both; } div.results { float: right; margin-top: -20px; margin-right: 20px; display: inline; } * html div.results { margin-top: -3px; } div.query_form { float: left; width: 800px; } } end end end module Hiking::Views def layout html do head do title 'Hiking - An XPATH Interpreter' link :rel => 'stylesheet', :type => 'text/css', :href => '/style.css', :media => 'screen' end body do h1.header 'Hiking - An XPATH Interpreter' div.content do self << yield end div.footer do p do span 'Created by ' a(:href => 'http://edbotz.us') {'<NAME>'} span ' with ' a(:href => 'http://camping.rubyforge.org/') {'Camping'} span ' on JUN 03 2008.' end end end end end def index div.query_form do form :action => '/', :method => 'post', :name => 'query' do fieldset do p do strong 'XPATH Statement: ' br input :type => 'text', :name => 'xpath', :id => 'xpath', :size => '108', :value => @xpath span ' ' button(:type => 'submit') {'Query'} end p do strong 'XML: ' br textarea @xml, :name => 'xml', :id => 'xml', :rows => '15', :cols => '90' end end end end div.results do h2 'Results: ' textarea @results, :name => 'results', :id => 'results', :rows => '19', :cols => '30' end script <<-END, :language => "JavaScript1.2" document.getElementById('xpath').focus(); END end end<file_sep>#!/usr/bin/env ruby require 'rubygems' require 'hiking' require 'webrick/httpserver' require 'camping/webrick' puts '' puts '** Start your hike down the xpath at http://localhost:5501 **' puts '** End your hike down the xpath with Ctrl+C **' puts '' s = WEBrick::HTTPServer.new :BindAddress => "0.0.0.0", :Port => 5501 s.mount "/", WEBrick::CampingHandler, Hiking # This lets Ctrl+C shut down your server trap(:INT) do s.shutdown end s.start<file_sep>require 'rubygems' require 'mosquito' require File.dirname(__FILE__) + "/../public/hiking" class TestHiking < Camping::WebTest test_xml = '<test><item number="1">First Item</item></test>' test "should get index" do get assert_response :success assert_match_body %r{&lt;test&gt;\r\n&lt;item number=\"1\"&gt;First Item&lt;/item&gt;\r\n&lt;/test&gt;} end test "should parse xml" do post '/', :xml => test_xml, :xpath => "/test/item/@number", :body => "Body" assert_response :success assert_match_body %r{<textarea name=\"results\" cols=\"30\" rows=\"19\" id=\"results\">1</textarea>} end end
6234e8e7d14b093ef511f9deeff607a36d067f38
[ "Ruby" ]
4
Ruby
ebot/hiking
4a103c750917725fc489aafd56216dd9542e0f2c
6371321b9fc8452997b8a7d428d29e2f05f9083b
refs/heads/master
<file_sep>using System; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using Microsoft.AspNetCore.Http; // Your Dojodachi should start with 20 happiness, 20 fullness, 50 energy, and 3 meals.[X] // After every button press, display a message showing how the Dojodachi reacted // Feeding your Dojodachi costs 1 meal and gains a random amount of fullness between 5 and 10 // (you cannot feed your Dojodachi if you do not have meals) // Playing with your Dojodachi costs 5 energy and gains a random amount of happiness between 5 and 10 // Every time you play with or feed your dojodachi there should be a 25% chance that it won't like it. Energy or meals will still decrease, but happiness and fullness won't change. // Working costs 5 energy and earns between 1 and 3 meals // Sleeping earns 15 energy and decreases fullness and happiness each by 5 // If energy, fullness, and happiness are all raised to over 100, you win! a restart button should be displayed. // If fullness or happiness ever drop to 0, you lose, and a restart button should be displayed. namespace DojoDachi { public class HomeController : Controller { // Requests // localhost:5000/ // [Route("")] [HttpGet("")] // can combine these two lines into one public ViewResult Index() { HttpContext.Session.SetInt32("fullness", 20); HttpContext.Session.SetInt32("happiness", 20); HttpContext.Session.SetInt32("meals", 3); HttpContext.Session.SetInt32("energy", 50); ViewBag.Action = "Hi Dojodachi, what do you want to do!?"; ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); ViewBag.Img = Url.Content("~/img/Dojodachi.jpg"); return View(); } [HttpPost("feed")] public IActionResult Feed(int min, int max) { if(HttpContext.Session.GetInt32("meals") < 1) { string cannot = "Not enough meals! Work to earn some meals first!"; ViewBag.Cannot = cannot; ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } else { int? meals = HttpContext.Session.GetInt32("meals"); meals -= 1; HttpContext.Session.SetInt32("meals", (int)meals); ViewBag.StatTwo = "-1 meal"; Random rand = new Random(); int chance = rand.Next(0, 101); if (chance > 25) { string Feed = "You fed your Dojodachi"; ViewBag.Action = Feed; int? fullness = HttpContext.Session.GetInt32("fullness"); int fed = rand.Next(min, max); fullness += fed; ViewBag.StatOne = $"+{fed} fullness"; HttpContext.Session.SetInt32("fullness", (int)fullness); ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } else { string notlike = "Your Dojodachi didn't like that food! No gain to fullness!"; ViewBag.NotLike = notlike; ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } } } [HttpPost("play")] public IActionResult Play(int min, int max) { if(HttpContext.Session.GetInt32("energy") < 1) { string cannot = "Dojodachi is tired! Sleep to recharge energy!"; ViewBag.Cannot = cannot; ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } else { int? energy = HttpContext.Session.GetInt32("energy"); energy -= 5; if(energy < 0) { energy = 0; } HttpContext.Session.SetInt32("energy", (int)energy); ViewBag.StatTwo = "-5 energy"; Random rand = new Random(); int chance = rand.Next(0, 101); if (chance > 25) { string Play = "You played with your Dojodachi!"; ViewBag.Action = Play; int? happiness = HttpContext.Session.GetInt32("happiness"); int play = rand.Next(min, max); happiness += play; ViewBag.StatOne = $"+{play} happiness"; HttpContext.Session.SetInt32("happiness", (int)happiness); ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } else { string notlike = "Your Dojodachi didn't like that game! No gain to Happiness!"; ViewBag.NotLike = notlike; ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } } } [HttpPost("work")] public IActionResult Work(int min, int max) { if(HttpContext.Session.GetInt32("energy") < 1) { string cannot = "Dojodachi is tired! Sleep to recharge energy!"; ViewBag.Cannot = cannot; ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } else { Random rand = new Random(); string Work = "You sent your Dojodachi to work!"; ViewBag.Action = Work; int? energy = HttpContext.Session.GetInt32("energy"); energy -= 5; if(energy < 0) { energy = 0; } int? meals = HttpContext.Session.GetInt32("meals"); int work = rand.Next(min, max); meals += work; ViewBag.StatOne = $"+{work} meals"; ViewBag.StatTwo = "-5 energy"; HttpContext.Session.SetInt32("meals", (int)meals); HttpContext.Session.SetInt32("energy", (int)energy); ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } } [HttpPost("sleep")] public IActionResult Sleep() { if(HttpContext.Session.GetInt32("happiness") < 1 && HttpContext.Session.GetInt32("fullness") < 1) { string cannot = "Dojodachi is unhappy and hungry! Feed and make your Dojodachi happier to sleep!"; ViewBag.Cannot = cannot; ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } if(HttpContext.Session.GetInt32("happiness") < 1) { string cannot = "Dojodachi is unhappy! Make your Dojodachi happier to sleep!"; ViewBag.Cannot = cannot; ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } if(HttpContext.Session.GetInt32("fullness") < 1) { string cannot = "Dojodachi is hungry! Feed your Dojodachi to sleep!"; ViewBag.Cannot = cannot; ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } else { string sleep = "Your Dojodachi went to sleep!"; ViewBag.Action = sleep; int? energy = HttpContext.Session.GetInt32("energy"); energy += 15; if(energy > 100) { energy = 100; } int? happiness = HttpContext.Session.GetInt32("happiness"); int? fullness = HttpContext.Session.GetInt32("fullness"); happiness -= 5; fullness -= 5; if(happiness < 0) { happiness = 0; } if(fullness < 0) { fullness = 0; } ViewBag.StatOne = $"+15 energy"; ViewBag.StatTwo = "-5 happiness -5 fullness"; HttpContext.Session.SetInt32("energy", (int)energy); HttpContext.Session.SetInt32("happiness", (int)happiness); HttpContext.Session.SetInt32("fullness", (int)fullness); ViewBag.Fullness = HttpContext.Session.GetInt32("fullness"); ViewBag.Happiness = HttpContext.Session.GetInt32("happiness"); ViewBag.Meals = HttpContext.Session.GetInt32("meals"); ViewBag.Energy = HttpContext.Session.GetInt32("energy"); return View("Index"); } } [HttpPost("restart")] public RedirectToActionResult Restart() { HttpContext.Session.Clear(); return RedirectToAction ("Index"); } } }
3de9d2eb0c48637b38b0848653181166567b39a3
[ "C#" ]
1
C#
ParkerLBrown/DojoDachi
df384d8ddacfb6b3aa4304b2f0206a2b9fc9e7d6
b8037afac7b6626bef1d3e46bcac1157d032e362
refs/heads/master
<repo_name>BegaDavor/test17092018<file_sep>/src/zadatak3/Test.java package zadatak3; public class Test { public static void main(String[] args) { int[] niz = {2, 4, 1, 5, 3}; MyArray array = new MyArray(niz); System.out.println("Najmanji: " + array.getSmallestElement()); System.out.println("Najveci: " + array.getLargestElement()); System.out.println("Suma: " + array.sumAllElements()); System.out.print("Elementi: "); array.printAllElements(); } } <file_sep>/src/zadatak2/Racunar.java package zadatak2; public class Racunar { // atributi private double kolicinaRAMa; private double kapacitetHD; private double brzinaProcesora; private double dijagonalaMonitora; private double nabavnaCijena; // kontruktori public Racunar(double kolicinaRAMa, double kapacitetHD, double brzinaProcesora, double dijagonalaMonitora, double nabavnaCijena) { this.kolicinaRAMa = kolicinaRAMa; this.kapacitetHD = kapacitetHD; this.brzinaProcesora = brzinaProcesora; this.dijagonalaMonitora = dijagonalaMonitora; this.nabavnaCijena = nabavnaCijena; } // getters and setters public double getKolicinaRAMa() { return kolicinaRAMa; } public double getKapacitetHD() { return kapacitetHD; } public double getBrzinaProcesora() { return brzinaProcesora; } public double getDijagonalaMonitora() { return dijagonalaMonitora; } public double getNabavnaCijena() { return nabavnaCijena; } public void setKolicinaRAMa(double kolicinaRAMa) { this.kolicinaRAMa = kolicinaRAMa; } public void setKapacitetHD(double kapacitetHD) { this.kapacitetHD = kapacitetHD; } public void setBrzinaProcesora(double brzinaProcesora) { this.brzinaProcesora = brzinaProcesora; } public void setDijagonalaMonitora(double dijagonalaMonitora) { this.dijagonalaMonitora = dijagonalaMonitora; } public void setNabavnaCijena(double nabavnaCijena) { this.nabavnaCijena = nabavnaCijena; } // metode public double izracunajCijenu() { double cijena = getNabavnaCijena() + getNabavnaCijena()*0.1; return cijena; } } <file_sep>/src/zadatak2/Laptop.java package zadatak2; public class Laptop extends Racunar{ //atributi private int trajanjeBaterije; //konstruktori public Laptop(double kolicinaRAMa, double kapacitetHD, double brzinaProcesora, double dijagonalaMonitora, double nabavnaCijena, int trajanjeBaterije) { super(kolicinaRAMa, kapacitetHD, brzinaProcesora, dijagonalaMonitora, nabavnaCijena); this.trajanjeBaterije = trajanjeBaterije; } // getters and setters public int getTrajanjeBaterije() { return trajanjeBaterije; } public void setTrajanjeBaterije(int trajanjeBaterije) { this.trajanjeBaterije = trajanjeBaterije; } // metode @Override public double izracunajCijenu() { double cijena = getNabavnaCijena() + getNabavnaCijena()*0.15; return cijena; } } <file_sep>/README.md # test17092018 Test od 17.9.2018. sa BILD-IT obuke.
07fece06c97de7862c47c4a93480bdcafaff2e24
[ "Markdown", "Java" ]
4
Java
BegaDavor/test17092018
82c5147bf32b14beed1fc7a2d11b11e078dbf235
214e17b8d78709c3a73a69c6446f2e151c18c776
refs/heads/main
<file_sep># Some topology configuration information and commands # hostnames RTA = 'RTA' RTB = 'RTB' RTC = 'RTC' PC2 = 'pc2' PC1 = 'pc1' valid_hosts = {RTA, RTB, RTC} rta_profile = { 'hostname': RTA, 'ip': '172.16.0.2', 'password': '<PASSWORD>' } rtb_profile = { 'hostname': RTB, 'ip': '172.16.0.3', 'password': '<PASSWORD>' } rtc_profile = { 'hostname': RTC, 'ip': '172.16.0.4', 'password': '<PASSWORD>' } pc1_profile = { 'hostname': PC1, 'ip': '192.168.3.2', 'password': '<PASSWORD>' } pc2_profile = { 'hostname': PC2, 'ip': '10.0.0.11', 'password': '<PASSWORD>' } router_profiles = [rta_profile, rtb_profile, rtc_profile] # commands to be executed on RTA _commands_rta = [ 'configure terminal', 'interface f0/0', 'ip address 192.168.3.1 255.255.255.0', 'no shutdown', 'interface s0/0/0', 'ip address 192.168.1.1 255.255.255.252', 'no shutdown', 'exit', 'ip route 192.168.1.32 255.255.255.224 192.168.1.2', 'exit', 'exit' ] # commands to be executed on RTB _commands_rtb = [ "configure terminal", "interface f0/0", "ip address 10.0.0.1 255.0.0.0", "no shutdown", "interface s0/0/0", "ip address 192.168.1.2 255.255.255.252", "no shutdown", "clock rate 9600", 'exit', 'ip route 0.0.0.0 0.0.0.0 192.168.1.1', 'ip nat inside source static 10.0.0.2 192.168.1.34', 'ip nat inside source static 10.0.0.11 192.168.1.35', 'interface f0/0', 'ip nat inside', 'interface s0/0/0', 'ip nat outside', 'exit', 'exit', 'exit' ] # commands to be executed on RTC _commands_rtc = [ 'configure terminal', 'interface f0/0', 'ip address 10.0.0.2 255.0.0.0', 'no shutdown', 'exit', 'ip route 0.0.0.0 0.0.0.0 10.0.0.1', 'exit', 'exit' ] commands = { RTA: _commands_rta, RTB: _commands_rtb, RTC: _commands_rtc } test_commands = { RTB: [ ('show ip nat translations', b'192.168.1.35') ], PC2: [ ('ping 192.168.3.2', '(0% 丢失)'.encode('gbk')) ], PC1: [ ('ping 10.0.0.0', '(100% 丢失)'.encode('gbk')), ('ping 192.168.1.35', '(0% 丢失)'.encode('gbk')), ] } <file_sep>from collections import namedtuple from flask import Flask, request, session from flask_cors import CORS import topology as tp from telnet import RouterTelnetConnection, config_router, run_test, run_pc_test app = Flask(__name__) app.secret_key = b'_<KEY> CORS(app, supports_credentials=True) ResultMessage = namedtuple('ResultMessage', ['success', 'errMessage']) TestResult = namedtuple('TestResult', ['success', 'message']) @app.route('/connect', methods=['GET']) def connect_telnet(): hostname = request.args.get('hostname') ip_add = request.args.get('ipAdd') password = request.args.get('password') # validate parameters if hostname is None or ip_add is None or password is None: return ResultMessage(False, 'incompleteParams') if hostname not in tp.valid_hosts: return ResultMessage(False, 'invalidHostname') # test connection telnet = RouterTelnetConnection(hostname, ip_add, password) connect_result = telnet.test_connection() if connect_result == 'success': session[hostname] = telnet.profiles return ResultMessage(True, '')._asdict() else: return ResultMessage(False, connect_result)._asdict() @app.route('/autoConfig') def do_configuration(): # config each router by telnet for router_profile in tp.router_profiles: result = config_router(router_profile['hostname'], router_profile) if result != 'success': return ResultMessage(False, result)._asdict() return ResultMessage(True, '')._asdict() @app.route('/testResult') def do_test(): # return NAT table of RTB nat_test = run_test(tp.RTB, tp.rtb_profile) # run test of pc1 and pc2 pc1_test = run_pc_test(tp.PC1, tp.pc1_profile) pc2_test = run_pc_test(tp.PC2, tp.pc2_profile) return [TestResult(*result)._asdict() for result in [nat_test, pc1_test, pc2_test]] if __name__ == '__main__': app.run(host='0.0.0.0') <file_sep>def config_router(hostname, router_info): return 'success' def run_test(hostname, router_info): return 'success', ['Nothing to show'] # noinspection PyMethodMayBeStatic class RouterTelnetConnection: def __init__(self, hostname, ip, password): self.hostname = hostname self.ip = ip self.password = <PASSWORD> def test_connection(self): return 'success', None @property def profiles(self): return { 'hostname': self.hostname, 'ip': self.ip, 'password': <PASSWORD> } def execute_commands(self, commands): return 'success', ['Nothing to show'] class PCTelnetConnection: def __init__(self, hostname, ip, password): self.hostname = hostname self.ip = ip self.password = <PASSWORD> <file_sep># network-backend ## 接口说明 - 连接 telnet ```json url: "/connect", params: { "hostname": "RTA|RTB|RTC", "ipAdd": "172.16.0.1", "password": "<PASSWORD>" }, result: { "success": true, "errMessage": "ipErr|invalidPasswd" } ``` - 前端请求一定要和 "RTA|RTB|RTC" 中的一个匹配。 - `ipErr` 表示地址有问题, `invalidPasswd` 表示密码有问题。 - 一键执行配置 ```json url: "/autoConfig", result: { "success": true, "errMessage": "hostIncomplete|ipErr|invalidPasswd|" } ``` - `hostIncomplete` 表示没有给所有的路由器都输入相应的 telnet 地址和密码。 - 获取测试结果 ```json url: "/testResult", result: [{ "success": true, "message": "" }] ``` ## 依赖 - python 3.7 - flask<file_sep>import time from telnetlib import Telnet from typing import Callable, Any import topology as tp def config_router(hostname, router_info): target = RouterTelnetConnection(hostname, router_info['ip'], router_info['password']) return target.execute_commands(tp.commands[hostname]) def run_test(hostname, router_info): target = RouterTelnetConnection(hostname, router_info['ip'], router_info['password']) return _execute_test(target) def run_pc_test(hostname, pc_info): target = PCTelnetConnection(hostname, pc_info['ip'], pc_info['password']) return _execute_test(target) def _execute_test(target_telnet_connection): exec_result = target_telnet_connection.execute_tests(tp.test_commands[target_telnet_connection.hostname]) print(exec_result) if exec_result == 'invalidPasswd' or exec_result == 'ipErr': return False, exec_result return exec_result def _input_to_telnet(command: str): return command.encode('ascii') + b'\r\n' class PCTelnetConnection: def __init__(self, hostname, ip, password): self.hostname = hostname self.ip = ip self.password = <PASSWORD> def _connect(self, func: Callable[[Any], Any] = lambda x: 'success'): try: with Telnet(self.ip) as tn: # try to login tn.read_until(b'login:', timeout=5) tn.write(_input_to_telnet(self.hostname)) tn.read_until(b'password', timeout=5) tn.write(_input_to_telnet(self.password)) time.sleep(0.1) # if password is wrong, telnet will request the user retype it result = tn.read_until(b'login:', timeout=1) print(result) if b'login:' in result: return 'invalidPasswd' elif b'>' in result: # execute user defined function return func(tn) else: return result except (TimeoutError, ConnectionRefusedError): return 'ipErr' def execute_tests(self, test_commands): def execute(tn): telnet_output = [] test_result = True for command, expected in test_commands: tn.write(_input_to_telnet(command)) if expected is not None: # read messages from telnet and test them with expected string time.sleep(0.1) response = tn.read_until(expected, timeout=5) response += tn.read_eager() if expected not in response: test_result = False telnet_output.append(response.decode('gbk')) return test_result, telnet_output return self._connect(execute) class RouterTelnetConnection: def __init__(self, hostname, ip, password): self.hostname = hostname self.ip = ip self.password = <PASSWORD> def _connect(self, func: Callable[[Any], Any] = lambda x: 'success', enabled=False): try: with Telnet(self.ip) as tn: tn.read_until(b'Password:', timeout=2) tn.write(_input_to_telnet(self.password)) time.sleep(0.5) # if password is wrong, telnet will request the user retype it result = tn.read_until(b'Password:', timeout=2) if b'Password:' in result: return '<PASSWORD>' elif b'>' in result: if enabled: # enter enable mode tn.write(_input_to_telnet('enable')) tn.read_until(b'Password', timeout=2) tn.write(_input_to_telnet('123456')) # execute user defined function return func(tn) except (TimeoutError, ConnectionRefusedError): return 'ipErr' def test_connection(self): return self._connect() @property def profiles(self): return { 'hostname': self.hostname, 'ip': self.ip, 'password': self.password } def execute_commands(self, commands): def execute(tn): for command in commands: tn.write(_input_to_telnet(command)) time.sleep(0.1) response = tn.read_eager() print(response) return 'success' return self._connect(execute, enabled=True) def execute_tests(self, test_commands): def execute(tn): telnet_output = [] test_result = True for command, expected in test_commands: tn.write(_input_to_telnet(command)) if expected is not None: # read messages from telnet and test them with expected string response = tn.read_until(expected, timeout=5) response += tn.read_eager() if expected not in response: test_result = False telnet_output.append(response.decode('ascii')) return test_result, telnet_output return self._connect(execute, enabled=True)
98565e968e09e923ba18977454305c9445528db4
[ "Markdown", "Python" ]
5
Python
nju-computer-network-2020/network-backend
b4ba147760dd896d7e65efe770ca3849fea5fd4d
f706402f4d0c1571ff192ab1ce11311a948164eb
refs/heads/master
<file_sep># -* coding: utf-8 from __future__ import print_function from src.evaluate import evaluate_class from src.DB import Database from skimage.feature import daisy from skimage import color from six.moves import cPickle import numpy as np import scipy.misc import math import os n_slice = 2 n_orient = 8 step = 10 radius = 30 rings = 2 histograms = 6 h_type = 'region' d_type = 'd1' depth = 3 R = (rings * histograms + 1) * n_orient ''' MMAP depth depthNone, daisy-region-n_slice2-n_orient8-step10-radius30-rings2-histograms6, distance=d1, MMAP 0.162806083971 depth100, daisy-region-n_slice2-n_orient8-step10-radius30-rings2-histograms6, distance=d1, MMAP 0.269333190731 depth30, daisy-region-n_slice2-n_orient8-step10-radius30-rings2-histograms6, distance=d1, MMAP 0.388199474789 depth10, daisy-region-n_slice2-n_orient8-step10-radius30-rings2-histograms6, distance=d1, MMAP 0.468182738095 depth5, daisy-region-n_slice2-n_orient8-step10-radius30-rings2-histograms6, distance=d1, MMAP 0.497688888889 depth3, daisy-region-n_slice2-n_orient8-step10-radius30-rings2-histograms6, distance=d1, MMAP 0.499833333333 depth1, daisy-region-n_slice2-n_orient8-step10-radius30-rings2-histograms6, distance=d1, MMAP 0.448 (exps below use depth=None) d_type daisy-global-n_orient8-step180-radius58-rings2-histograms6, distance=d1, MMAP 0.101883969577 daisy-global-n_orient8-step180-radius58-rings2-histograms6, distance=cosine, MMAP 0.104779921854 h_type daisy-global-n_orient8-step10-radius30-rings2-histograms6, distance=d1, MMAP 0.157738278588 daisy-region-n_slice2-n_orient8-step10-radius30-rings2-histograms6, distance=d1, MMAP 0.162806083971 ''' # cache dir cache_dir = 'cache' if not os.path.exists(cache_dir): os.makedirs(cache_dir) class Daisy(object): def histogram(self, input, type=h_type, n_slice=n_slice, normalize=True): ''' count img histogram arguments input : a path to a image or a numpy.ndarray type : 'global' means count the histogram for whole image 'region' means count the histogram for regions in images, then concatanate all of them n_slice : work when type equals to 'region', height & width will equally sliced into N slices normalize: normalize output histogram return type == 'global' a numpy array with size R type == 'region' a numpy array with size n_slice * n_slice * R #R = (rings * histograms + 1) * n_orient# ''' if isinstance(input, np.ndarray): # examinate input type img = input.copy() else: img = scipy.misc.imread(input, mode='RGB') height, width, channel = img.shape P = math.ceil((height - radius*2) / step) Q = math.ceil((width - radius*2) / step) assert P > 0 and Q > 0, "input image size need to pass this check" if type == 'global': hist = self._daisy(img) elif type == 'region': hist = np.zeros((n_slice, n_slice, R)) h_silce = np.around(np.linspace(0, height, n_slice+1, endpoint=True)).astype(int) w_slice = np.around(np.linspace(0, width, n_slice+1, endpoint=True)).astype(int) for hs in range(len(h_silce)-1): for ws in range(len(w_slice)-1): img_r = img[h_silce[hs]:h_silce[hs+1], w_slice[ws]:w_slice[ws+1]] # slice img to regions hist[hs][ws] = self._daisy(img_r) if normalize: hist /= np.sum(hist) return hist.flatten() def _daisy(self, img, normalize=True): image = color.rgb2gray(img) descs = daisy(image, step=step, radius=radius, rings=rings, histograms=histograms, orientations=n_orient) descs = descs.reshape(-1, R) # shape=(N, R) hist = np.mean(descs, axis=0) # shape=(R,) if normalize: hist = np.array(hist) / np.sum(hist) return hist def make_samples(self, db, verbose=True): if h_type == 'global': sample_cache = "daisy-{}-n_orient{}-step{}-radius{}-rings{}-histograms{}".format(h_type, n_orient, step, radius, rings, histograms) elif h_type == 'region': sample_cache = "daisy-{}-n_slice{}-n_orient{}-step{}-radius{}-rings{}-histograms{}".format(h_type, n_slice, n_orient, step, radius, rings, histograms) try: samples = cPickle.load(open(os.path.join(cache_dir, sample_cache), "rb", True)) for sample in samples: sample['hist'] /= np.sum(sample['hist']) # normalize if verbose: print("Using cache..., config=%s, distance=%s, depth=%s" % (sample_cache, d_type, depth)) except: if verbose: print("Counting histogram..., config=%s, distance=%s, depth=%s" % (sample_cache, d_type, depth)) samples = [] data = db.get_data() for d in data.itertuples(): d_img, d_cls = getattr(d, "img"), getattr(d, "cls") d_hist = self.histogram(d_img, type=h_type, n_slice=n_slice) samples.append({ 'img': d_img, 'cls': d_cls, 'hist': d_hist }) cPickle.dump(samples, open(os.path.join(cache_dir, sample_cache), "wb", True)) return samples if __name__ == "__main__": db = Database() # evaluate database APs = evaluate_class(db, f_class=Daisy, d_type=d_type, depth=depth) cls_MAPs = [] for cls, cls_APs in APs.items(): MAP = np.mean(cls_APs) print("Class {}, MAP {}".format(cls, MAP)) cls_MAPs.append(MAP) print("MMAP", np.mean(cls_MAPs)) <file_sep># -*- coding: utf-8 -*- # from __future__ import print_function from src.evaluate import distance, evaluate_class from src.DB import Database from six.moves import cPickle import numpy as np import scipy.misc import itertools import os # configs for histogram n_bin = 12 # histogram bins n_slice = 3 # slice image h_type = 'region' # global or region d_type = 'd1' # distance type depth = 1 # retrieved depth, set to None will count the ap for whole database ''' MMAP depth depthNone, region,bin12,slice3, distance=d1, MMAP 0.273745840034 depth100, region,bin12,slice3, distance=d1, MMAP 0.406007856783 depth30, region,bin12,slice3, distance=d1, MMAP 0.516738512679 depth10, region,bin12,slice3, distance=d1, MMAP 0.614047666604 depth5, region,bin12,slice3, distance=d1, MMAP 0.650125 depth3, region,bin12,slice3, distance=d1, MMAP 0.657166666667 depth1, region,bin12,slice3, distance=d1, MMAP 0.62 (exps below use depth=None) d_type global,bin6,d1,MMAP 0.242345913685 global,bin6,cosine,MMAP 0.184176505586 n_bin region,bin10,slice4,d1,MMAP 0.269872790396 region,bin12,slice4,d1,MMAP 0.271520862017 region,bin6,slcie3,d1,MMAP 0.262819311357 region,bin12,slice3,d1,MMAP 0.273745840034 n_slice region,bin12,slice2,d1,MMAP 0.266076627332 region,bin12,slice3,d1,MMAP 0.273745840034 region,bin12,slice4,d1,MMAP 0.271520862017 region,bin14,slice3,d1,MMAP 0.272386552594 region,bin14,slice5,d1,MMAP 0.266877181379 region,bin16,slice3,d1,MMAP 0.273716788003 region,bin16,slice4,d1,MMAP 0.272221031804 region,bin16,slice8,d1,MMAP 0.253823360098 h_type region,bin4,slice2,d1,MMAP 0.23358615622 global,bin4,d1,MMAP 0.229125435746 ''' # cache dir cache_dir = 'cache' if not os.path.exists(cache_dir): os.makedirs(cache_dir) class Color(object): def histogram(self, input, n_bin=n_bin, type=h_type, n_slice=n_slice, normalize=True): ''' count img color histogram arguments input : a path to a image or a numpy.ndarray n_bin : number of bins for each channel type : 'global' means count the histogram for whole image 'region' means count the histogram for regions in images, then concatanate all of them n_slice : work when type equals to 'region', height & width will equally sliced into N slices normalize: normalize output histogram return type == 'global' a numpy array with size n_bin ** channel type == 'region' a numpy array with size n_slice * n_slice * (n_bin ** channel) ''' if isinstance(input, np.ndarray): # examinate input type img = input.copy() else: img = scipy.misc.imread(input, mode='RGB') height, width, channel = img.shape bins = np.linspace(0, 256, n_bin+1, endpoint=True) # slice bins equally for each channel if type == 'global': hist = self._count_hist(img, n_bin, bins, channel) elif type == 'region': hist = np.zeros((n_slice, n_slice, n_bin ** channel)) h_silce = np.around(np.linspace(0, height, n_slice+1, endpoint=True)).astype(int) w_slice = np.around(np.linspace(0, width, n_slice+1, endpoint=True)).astype(int) for hs in range(len(h_silce)-1): for ws in range(len(w_slice)-1): img_r = img[h_silce[hs]:h_silce[hs+1], w_slice[ws]:w_slice[ws+1]] # slice img to regions hist[hs][ws] = self._count_hist(img_r, n_bin, bins, channel) if normalize: hist /= np.sum(hist) return hist.flatten() def _count_hist(self, input, n_bin, bins, channel): img = input.copy() bins_idx = {key: idx for idx, key in enumerate(itertools.product(np.arange(n_bin), repeat=channel))} # permutation of bins hist = np.zeros(n_bin ** channel) # cluster every pixels for idx in range(len(bins)-1): img[(input >= bins[idx]) & (input < bins[idx+1])] = idx # add pixels into bins height, width, _ = img.shape for h in range(height): for w in range(width): b_idx = bins_idx[tuple(img[h, w])] hist[b_idx] += 1 return hist def make_samples(self, db, verbose=True): if h_type == 'global': sample_cache = "histogram_cache-{}-n_bin{}".format(h_type, n_bin) elif h_type == 'region': sample_cache = "histogram_cache-{}-n_bin{}-n_slice{}".format(h_type, n_bin, n_slice) try: samples = cPickle.load(open(os.path.join(cache_dir, sample_cache), "rb", True)) if verbose: print("Using cache..., config=%s, distance=%s, depth=%s" % (sample_cache, d_type, depth)) except: if verbose: print("Counting histogram..., config=%s, distance=%s, depth=%s" % (sample_cache, d_type, depth)) samples = [] data = db.get_data() for d in data.itertuples(): d_img, d_cls = getattr(d, "img"), getattr(d, "cls") d_hist = self.histogram(d_img, type=h_type, n_bin=n_bin, n_slice=n_slice) samples.append({ 'img': d_img, 'cls': d_cls, 'hist': d_hist }) cPickle.dump(samples, open(os.path.join(cache_dir, sample_cache), "wb", True)) return samples if __name__ == "__main__": db = Database() data = db.get_data() color = Color() # test normalize hist = color.histogram(data.ix[0, 0], type='global') assert hist.sum() - 1 < 1e-9, "normalize false" # test histogram bins def sigmoid(z): a = 1.0 / (1.0 + np.exp(-1. * z)) return a np.random.seed(0) IMG = sigmoid(np.random.randn(2, 2, 3)) * 255 IMG = IMG.astype(int) hist = color.histogram(IMG, type='global', n_bin=4) assert np.equal(np.where(hist > 0)[0], np.array([37, 43, 58, 61])).all(), "global histogram implement failed" hist = color.histogram(IMG, type='region', n_bin=4, n_slice=2) assert np.equal(np.where(hist > 0)[0], np.array([58, 125, 165, 235])).all(), "region histogram implement failed" # examinate distance np.random.seed(1) IMG = sigmoid(np.random.randn(4, 4, 3)) * 255 IMG = IMG.astype(int) hist = color.histogram(IMG, type='region', n_bin=4, n_slice=2) IMG2 = sigmoid(np.random.randn(4, 4, 3)) * 255 IMG2 = IMG2.astype(int) hist2 = color.histogram(IMG2, type='region', n_bin=4, n_slice=2) assert distance(hist, hist2, d_type='d1') == 2, "d1 implement failed" assert distance(hist, hist2, d_type='d2-norm') == 2, "d2 implement failed" # evaluate database APs = evaluate_class(db, f_class=Color, d_type=d_type, depth=depth) cls_MAPs = [] for cls, cls_APs in APs.items(): MAP = np.mean(cls_APs) print("Class {}, MAP {}".format(cls, MAP)) cls_MAPs.append(MAP) print("MMAP", np.mean(cls_MAPs)) <file_sep># -*- coding: utf-8 -*- from __future__ import print_function from src.evaluate import evaluate_class from src.DB import Database from src.color import Color from src.daisy import Daisy from src.edge import Edge from src.gabor import Gabor from src.HOG import HOG from src.vggnet import VGGNetFeat from src.resnet import ResNetFeat from sklearn.random_projection import johnson_lindenstrauss_min_dim from sklearn import random_projection import numpy as np import itertools import os feat_pools = ['color', 'daisy', 'edge', 'gabor', 'hog', 'vgg', 'res'] keep_rate = 0.25 project_type = 'sparse' # result dir result_dir = 'result' if not os.path.exists(result_dir): os.makedirs(result_dir) class RandomProjection(object): def __init__(self, features, keep_rate=keep_rate, project_type=project_type): assert len(features) > 0, "need to give at least one feature!" self.features = features self.keep_rate = keep_rate self.project_type = project_type self.samples = None def make_samples(self, db, verbose=False): if verbose: print("Use features {}, {} RandomProject, keep {}".format(" & ".join(self.features), self.project_type, self.keep_rate)) if self.samples == None: feats = [] for f_class in self.features: feats.append(self._get_feat(db, f_class)) samples = self._concat_feat(db, feats) samples, _ = self._rp(samples) self.samples = samples # cache the result return self.samples def check_random_projection(self): ''' check if current smaple can fit to random project return a boolean ''' if self.samples == None: feats = [] for f_class in self.features: feats.append(self._get_feat(db, f_class)) samples = self._concat_feat(db, feats) samples, flag = self._rp(samples) self.samples = samples # cache the result return True if flag else False def _get_feat(self, db, f_class): if f_class == 'color': f_c = Color() elif f_class == 'daisy': f_c = Daisy() elif f_class == 'edge': f_c = Edge() elif f_class == 'gabor': f_c = Gabor() elif f_class == 'hog': f_c = HOG() elif f_class == 'vgg': f_c = VGGNetFeat() elif f_class == 'res': f_c = ResNetFeat() return f_c.make_samples(db, verbose=False) def _concat_feat(self, db, feats): samples = feats[0] delete_idx = [] for idx in range(len(samples)): for feat in feats[1:]: feat = self._to_dict(feat) key = samples[idx]['img'] if key not in feat: delete_idx.append(idx) continue assert feat[key]['cls'] == samples[idx]['cls'] samples[idx]['hist'] = np.append(samples[idx]['hist'], feat[key]['hist']) for d_idx in sorted(set(delete_idx), reverse=True): del samples[d_idx] if delete_idx != []: print("Ignore %d samples" % len(set(delete_idx))) return samples def _to_dict(self, feat): ret = {} for f in feat: ret[f['img']] = { 'cls': f['cls'], 'hist': f['hist'] } return ret def _rp(self, samples): feats = np.array([s['hist'] for s in samples]) eps = self._get_eps(n_samples=feats.shape[0], n_dims=feats.shape[1]) if eps == -1: import warnings warnings.warn( "Can't fit to random projection with keep_rate {}\n".format(self.keep_rate), RuntimeWarning ) return samples, False if self.project_type == 'gaussian': transformer = random_projection.GaussianRandomProjection(eps=eps) elif self.project_type == 'sparse': transformer = random_projection.SparseRandomProjection(eps=eps) feats = transformer.fit_transform(feats) assert feats.shape[0] == len(samples) for idx in range(len(samples)): samples[idx]['hist'] = feats[idx] return samples, True def _get_eps(self, n_samples, n_dims, n_slice=int(1e4)): new_dim = n_dims * self.keep_rate for i in range(1, n_slice): eps = i / n_slice jl_dim = johnson_lindenstrauss_min_dim(n_samples=n_samples, eps=eps) if jl_dim <= new_dim: print("rate %.3f, n_dims %d, new_dim %d, dims error rate: %.4f" % (self.keep_rate, n_dims, jl_dim, ((new_dim-jl_dim) / new_dim)) ) return eps return -1 def evaluate_feats(db, N, feat_pools=feat_pools, keep_rate=keep_rate, project_type=project_type, d_type='d1', depths=[None, 300, 200, 100, 50, 30, 10, 5, 3, 1]): result = open(os.path.join(result_dir, 'feature_reduction-{}-keep{}-{}-{}feats.csv'.format(project_type, keep_rate, d_type, N)), 'w') for i in range(N): result.write("feat{},".format(i)) result.write("depth,distance,MMAP") combinations = itertools.combinations(feat_pools, N) for combination in combinations: fusion = RandomProjection(features=list(combination), keep_rate=keep_rate, project_type=project_type) if fusion.check_random_projection(): for d in depths: APs = evaluate_class(db, f_instance=fusion, d_type=d_type, depth=d) cls_MAPs = [] for cls, cls_APs in APs.items(): MAP = np.mean(cls_APs) cls_MAPs.append(MAP) r = "{},{},{},{}".format(",".join(combination), d, d_type, np.mean(cls_MAPs)) print(r) result.write('\n'+r) print() result.close() if __name__ == "__main__": db = Database() # evaluate features single-wise evaluate_feats(db, N=1, d_type='d1', keep_rate=keep_rate, project_type=project_type) # evaluate features double-wise evaluate_feats(db, N=2, d_type='d1', keep_rate=keep_rate, project_type=project_type) # evaluate features triple-wise evaluate_feats(db, N=3, d_type='d1', keep_rate=keep_rate, project_type=project_type) # evaluate features quadra-wise evaluate_feats(db, N=4, d_type='d1', keep_rate=keep_rate, project_type=project_type) # evaluate features penta-wise evaluate_feats(db, N=5, d_type='d1', keep_rate=keep_rate, project_type=project_type) # evaluate features hexa-wise evaluate_feats(db, N=6, d_type='d1', keep_rate=keep_rate, project_type=project_type) # evaluate features hepta-wise evaluate_feats(db, N=7, d_type='d1', keep_rate=keep_rate, project_type=project_type) # evaluate color feature d_type = 'd1' depth = 30 fusion = RandomProjection(features=['color'], keep_rate=keep_rate, project_type=project_type) APs = evaluate_class(db, f_instance=fusion, d_type=d_type, depth=depth) cls_MAPs = [] for cls, cls_APs in APs.items(): MAP = np.mean(cls_APs) print("Class {}, MAP {}".format(cls, MAP)) cls_MAPs.append(MAP) print("MMAP", np.mean(cls_MAPs)) <file_sep># -*- coding: utf-8 -*- from __future__ import print_function from src.evaluate import * from src.DB import Database from skimage.filters import gabor_kernel from skimage import color from scipy import ndimage as ndi import multiprocessing from six.moves import cPickle import numpy as np import scipy.misc import os theta = 4 frequency = (0.1, 0.5, 0.8) sigma = (1, 3, 5) bandwidth = (0.3, 0.7, 1) n_slice = 2 h_type = 'global' d_type = 'cosine' depth = 1 ''' MMAP depth depthNone, global-theta4-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.141136758233 depth100, global-theta4-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.216985780572 depth30, global-theta4-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.310063286599 depth10, global-theta4-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.3847025 depth5, global-theta4-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.400002777778 depth3, global-theta4-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.398166666667 depth1, global-theta4-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.334 (exps below use depth=None) _power gabor-global-theta4-frequency(0.1, 0.5, 0.8)-sigma(0.05, 0.25)-bandwidthNone, distance=cosine, MMAP 0.0821975313939 gabor-global-theta6-frequency(0.1, 0.5)-sigma(1, 3)-bandwidth(0.5, 1), distance=cosine, MMAP 0.139570979988 gabor-global-theta6-frequency(0.1, 0.8)-sigma(1, 3)-bandwidth(0.7, 1), distance=cosine, MMAP 0.139554792177 gabor-global-theta8-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.140947344315 gabor-global-theta6-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.139914401079 gabor-global-theta4-frequency(0.1, 0.5, 0.8)-sigma(1, 3, 5)-bandwidth(0.3, 0.7, 1), distance=cosine, MMAP 0.141136758233 gabor-global-theta4-frequency(0.1, 0.5, 1)-sigma(0.25, 1)-bandwidth(0.5, 1), distance=cosine, MMAP 0.120351804156 ''' def make_gabor_kernel(theta, frequency, sigma, bandwidth): kernels = [] for t in range(theta): t = t / float(theta) * np.pi for f in frequency: if sigma: for s in sigma: kernel = gabor_kernel(f, theta=t, sigma_x=s, sigma_y=s) kernels.append(kernel) if bandwidth: for b in bandwidth: kernel = gabor_kernel(f, theta=t, bandwidth=b) kernels.append(kernel) return kernels gabor_kernels = make_gabor_kernel(theta, frequency, sigma, bandwidth) if sigma and not bandwidth: assert len(gabor_kernels) == theta * len(frequency) * len(sigma), "kernel nums error in make_gabor_kernel()" elif not sigma and bandwidth: assert len(gabor_kernels) == theta * len(frequency) * len(bandwidth), "kernel nums error in make_gabor_kernel()" elif sigma and bandwidth: assert len(gabor_kernels) == theta * len(frequency) * (len(sigma) + len(bandwidth)), "kernel nums error in make_gabor_kernel()" elif not sigma and not bandwidth: assert len(gabor_kernels) == theta * len(frequency), "kernel nums error in make_gabor_kernel()" # cache dir cache_dir = 'cache' if not os.path.exists(cache_dir): os.makedirs(cache_dir) class Gabor(object): def gabor_histogram(self, input, type=h_type, n_slice=n_slice, normalize=True): ''' count img histogram arguments input : a path to a image or a numpy.ndarray type : 'global' means count the histogram for whole image 'region' means count the histogram for regions in images, then concatanate all of them n_slice : work when type equals to 'region', height & width will equally sliced into N slices normalize: normalize output histogram return type == 'global' a numpy array with size len(gabor_kernels) type == 'region' a numpy array with size len(gabor_kernels) * n_slice * n_slice ''' if isinstance(input, np.ndarray): # examinate input type img = input.copy() else: img = scipy.misc.imread(input, mode='RGB') height, width, channel = img.shape if type == 'global': hist = self._gabor(img, kernels=gabor_kernels) elif type == 'region': hist = np.zeros((n_slice, n_slice, len(gabor_kernels))) h_silce = np.around(np.linspace(0, height, n_slice+1, endpoint=True)).astype(int) w_slice = np.around(np.linspace(0, width, n_slice+1, endpoint=True)).astype(int) for hs in range(len(h_silce)-1): for ws in range(len(w_slice)-1): img_r = img[h_silce[hs]:h_silce[hs+1], w_slice[ws]:w_slice[ws+1]] # slice img to regions hist[hs][ws] = self._gabor(img_r, kernels=gabor_kernels) if normalize: hist /= np.sum(hist) return hist.flatten() def _feats(self, image, kernel): ''' arguments image : ndarray of the image kernel: a gabor kernel return a ndarray whose shape is (2, ) ''' feats = np.zeros(2, dtype=np.double) filtered = ndi.convolve(image, np.real(kernel), mode='wrap') feats[0] = filtered.mean() feats[1] = filtered.var() return feats def _power(self, image, kernel): ''' arguments image : ndarray of the image kernel: a gabor kernel return a ndarray whose shape is (2, ) ''' image = (image - image.mean()) / image.std() # Normalize images for better comparison. f_img = np.sqrt(ndi.convolve(image, np.real(kernel), mode='wrap')**2 + ndi.convolve(image, np.imag(kernel), mode='wrap')**2) feats = np.zeros(2, dtype=np.double) feats[0] = f_img.mean() feats[1] = f_img.var() return feats def _gabor(self, image, kernels=make_gabor_kernel(theta, frequency, sigma, bandwidth), normalize=True): pool = multiprocessing.Pool(processes=multiprocessing.cpu_count()) img = color.rgb2gray(image) results = [] feat_fn = self._power for kernel in kernels: results.append(pool.apply_async(self._worker, (img, kernel, feat_fn))) pool.close() pool.join() hist = np.array([res.get() for res in results]) if normalize: hist = hist / np.sum(hist, axis=0) return hist.T.flatten() def _worker(self, img, kernel, feat_fn): try: ret = feat_fn(img, kernel) except: print("return zero") ret = np.zeros(2) return ret def make_samples(self, db, verbose=True): if h_type == 'global': sample_cache = "gabor-{}-theta{}-frequency{}-sigma{}-bandwidth{}".format(h_type, theta, frequency, sigma, bandwidth) elif h_type == 'region': sample_cache = "gabor-{}-n_slice{}-theta{}-frequency{}-sigma{}-bandwidth{}".format(h_type, n_slice, theta, frequency, sigma, bandwidth) try: samples = cPickle.load(open(os.path.join(cache_dir, sample_cache), "rb", True)) for sample in samples: sample['hist'] /= np.sum(sample['hist']) # normalize if verbose: print("Using cache..., config=%s, distance=%s, depth=%s" % (sample_cache, d_type, depth)) except: if verbose: print("Counting histogram..., config=%s, distance=%s, depth=%s" % (sample_cache, d_type, depth)) samples = [] data = db.get_data() for d in data.itertuples(): d_img, d_cls = getattr(d, "img"), getattr(d, "cls") d_hist = self.gabor_histogram(d_img, type=h_type, n_slice=n_slice) samples.append({ 'img': d_img, 'cls': d_cls, 'hist': d_hist }) cPickle.dump(samples, open(os.path.join(cache_dir, sample_cache), "wb", True)) return samples if __name__ == "__main__": db = Database() # evaluate database APs = evaluate_class(db, f_class=Gabor, d_type=d_type, depth=depth) cls_MAPs = [] for cls, cls_APs in APs.items(): MAP = np.mean(cls_APs) print("Class {}, MAP {}".format(cls, MAP)) cls_MAPs.append(MAP) print("MMAP", np.mean(cls_MAPs)) <file_sep># 2020DIGIX-AI-competition <file_sep># -*- coding: utf-8 -*- from __future__ import print_function from src.evaluate import infer from src.DB import Database from src.color import Color from src.daisy import Daisy from src.edge import Edge from src.gabor import Gabor from src.HOG import HOG from src.vggnet import VGGNetFeat from src.resnet import ResNetFeat depth = 5 d_type = 'd1' query_idx = 0 if __name__ == '__main__': db = Database() # retrieve by color method = Color() samples = method.make_samples(db) query = samples[query_idx] _, result = infer(query, samples=samples, depth=depth, d_type=d_type) print(result) # retrieve by daisy method = Daisy() samples = method.make_samples(db) query = samples[query_idx] _, result = infer(query, samples=samples, depth=depth, d_type=d_type) print(result) # retrieve by edge method = Edge() samples = method.make_samples(db) query = samples[query_idx] _, result = infer(query, samples=samples, depth=depth, d_type=d_type) print(result) # retrieve by gabor method = Gabor() samples = method.make_samples(db) query = samples[query_idx] _, result = infer(query, samples=samples, depth=depth, d_type=d_type) print(result) # retrieve by HOG method = HOG() samples = method.make_samples(db) query = samples[query_idx] _, result = infer(query, samples=samples, depth=depth, d_type=d_type) print(result) # retrieve by VGG method = VGGNetFeat() samples = method.make_samples(db) query = samples[query_idx] _, result = infer(query, samples=samples, depth=depth, d_type=d_type) print(result) # retrieve by resnet method = ResNetFeat() samples = method.make_samples(db) query = samples[query_idx] _, result = infer(query, samples=samples, depth=depth, d_type=d_type) print(result) <file_sep># -*- coding: utf-8 -*- from __future__ import print_function from src.evaluate import evaluate_class from src.DB import Database from src.color import Color from src.daisy import Daisy from src.edge import Edge from src.gabor import Gabor from src.HOG import HOG from src.vggnet import VGGNetFeat from src.resnet import ResNetFeat import numpy as np import itertools import os d_type = 'd1' depth = 30 feat_pools = ['color', 'daisy', 'edge', 'gabor', 'hog', 'vgg', 'res'] # result dir result_dir = 'result' if not os.path.exists(result_dir): os.makedirs(result_dir) class FeatureFusion(object): def __init__(self, features): assert len(features) > 1, "need to fuse more than one feature!" self.features = features self.samples = None def make_samples(self, db, verbose=False): if verbose: print("Use features {}".format(" & ".join(self.features))) if self.samples == None: feats = [] for f_class in self.features: feats.append(self._get_feat(db, f_class)) samples = self._concat_feat(db, feats) self.samples = samples # cache the result return self.samples def _get_feat(self, db, f_class): if f_class == 'color': f_c = Color() elif f_class == 'daisy': f_c = Daisy() elif f_class == 'edge': f_c = Edge() elif f_class == 'gabor': f_c = Gabor() elif f_class == 'hog': f_c = HOG() elif f_class == 'vgg': f_c = VGGNetFeat() elif f_class == 'res': f_c = ResNetFeat() return f_c.make_samples(db, verbose=False) def _concat_feat(self, db, feats): samples = feats[0] delete_idx = [] for idx in range(len(samples)): for feat in feats[1:]: feat = self._to_dict(feat) key = samples[idx]['img'] if key not in feat: delete_idx.append(idx) continue assert feat[key]['cls'] == samples[idx]['cls'] samples[idx]['hist'] = np.append(samples[idx]['hist'], feat[key]['hist']) for d_idx in sorted(set(delete_idx), reverse=True): del samples[d_idx] if delete_idx != []: print("Ignore %d samples" % len(set(delete_idx))) return samples def _to_dict(self, feat): ret = {} for f in feat: ret[f['img']] = { 'cls': f['cls'], 'hist': f['hist'] } return ret def evaluate_feats(db, N, feat_pools=feat_pools, d_type='d1', depths=[None, 300, 200, 100, 50, 30, 10, 5, 3, 1]): result = open(os.path.join(result_dir, 'feature_fusion-{}-{}feats.csv'.format(d_type, N)), 'w') for i in range(N): result.write("feat{},".format(i)) result.write("depth,distance,MMAP") combinations = itertools.combinations(feat_pools, N) for combination in combinations: fusion = FeatureFusion(features=list(combination)) for d in depths: APs = evaluate_class(db, f_instance=fusion, d_type=d_type, depth=d) cls_MAPs = [] for cls, cls_APs in APs.items(): MAP = np.mean(cls_APs) cls_MAPs.append(MAP) r = "{},{},{},{}".format(",".join(combination), d, d_type, np.mean(cls_MAPs)) print(r) result.write('\n'+r) print() result.close() if __name__ == "__main__": db = Database() # evaluate features double-wise evaluate_feats(db, N=2, d_type='d1') # evaluate features triple-wise evaluate_feats(db, N=3, d_type='d1') # evaluate features quadra-wise evaluate_feats(db, N=4, d_type='d1') # evaluate features penta-wise evaluate_feats(db, N=5, d_type='d1') # evaluate features hexa-wise evaluate_feats(db, N=6, d_type='d1') # evaluate features hepta-wise evaluate_feats(db, N=7, d_type='d1') # evaluate database fusion = FeatureFusion(features=['color', 'daisy']) APs = evaluate_class(db, f_instance=fusion, d_type=d_type, depth=depth) cls_MAPs = [] for cls, cls_APs in APs.items(): MAP = np.mean(cls_APs) print("Class {}, MAP {}".format(cls, MAP)) cls_MAPs.append(MAP) print("MMAP", np.mean(cls_MAPs))
4bfa5e8925ce8170ec6d1c541979b956f2cdde61
[ "Markdown", "Python" ]
7
Python
YulongLee/2020DIGIX-AI--competition
d16020303c00a9179c9083fa4533305a9f1cb4f2
0d352b89c226fe78dad0c523d5524960154a8ac6
refs/heads/master
<repo_name>Shichisan/object_oriented<file_sep>/test/app-03.rb # frozen_string_literal: true # Diameterizableのロールの担い手を作る class DiameterDouble def diameter 10 end end class GearTest < MiniTest::Unit::TestCase def test_calculates_gear_inches gear = Gear.new( chainring: 52, cog: 11, wheel: DiameterDouble.new ) assert_in_delta(47.27, gear.gear_inches, 0.01) end end <file_sep>/duck-typing/trip-03.rb # frozen_string_literal: true class Trip attr_reader :bicycles, :customers, :vehicle def prepare preparers preparers.each { |preparer| preparer.prepare_trip(self)} end end # すべてのpreparerは、'prepare_trip' に応答するダック class Mechanic def prepare_trip trip trip.bicycles.each { |bicycle| prepare_bicycle(bicycle) } end end class TripCoordinator def prepare_trip trip trip.customers.each { |customer| buy_food(customer) } end end class Driver def prepare_trip trip vehicle = trip.vehicle gas_up(vehicle) fill_water_tank(vehicle) end end <file_sep>/test/app-02.rb # frozen_string_literal: true class Gear attr_reader :chainring, :cog, :wheel def initialize(args) @chainring = args[:chainring] @cog = args[:cog] @wheel = args[:wheel] end def gear_inches # wheel 変数内のオブジェクトが # Diameterizable ロールを担う ratio * wheel.diameter end def ratio chainring / cog.to_f end end class GearTest < Minitest::Unit::TestCase def test_calculates_gear_inches gear = Gear.new( chainring: 52, cog: 11, wheel: Wheel.new(26, 1.5) ) assert_in_delta(137.1, gear.gear_inches, 0.01 ) end end <file_sep>/manage_dependencies/bicycle-21.rb # frozen_string_literal: true class Gear attr_reader :chainring, :cog, :wheel def initialize(chainring, cog) @chainring = chainring @cog = cog @wheel = wheel end def gear_inches ratio * wheel.diameter end end # ここでは引数を正しい順番で渡さないといけない Gear.new( 52, 11, Wheel.new(26, 1.5) ).gear_inches # ------------------固定されたパラメーターの代わりに、ハッシュを受け取るようにする----------------------- class Gear attr_reader :chainring, :cog, :wheel def initialize(args) @chainring = args[:chainring] @cog = args[:cog] @wheel = args[:wheel] end def gear_inches ratio * wheel.diameter end end Gear.new( chainring: 52, cog: 11, wheel: Wheel.new(26, 1.5) ).gear_inches # テクニックとして、安定性の高い引数は固定順で受け入れ、安定性の低い引数は、オプションハッシュで受け取るようにする # ------------------明示的にデフォルト値を設定する------------------- class Gear attr_reader :chainring, :cog, :wheel def initialize(args) @chainring = args[:chainring] || 40 @cog = args[:cog] || 18 @wheel = args[:wheel] end def gear_inches ratio * wheel.diameter end end # ------------------------------fetchメソッドでデフォルト値を設定する-------------------------------- class Gear attr_reader :chainring, :cog, :wheel def initialize(args) # fetchメソッドのほうが、キーがハッシュに無いときのみ第2引数を利用するように機能させることができる @chainring = args.fetch(:chainring, 40) @cog = args.fetch(:cog, 18) @wheel = args[:wheel] end def gear_inches ratio * wheel.diameter end end # ------------------------------独立したラッパーメソッドにデフォルト値を代入する-------------------------------- class Gear attr_reader :chainring, :cog, :wheel def initialize(args) # デフォルト値が単純な数字や文字列以上のものであるときは、defaultsメソッドを実装しましょう args = defaults.merge(args) @chainring = args[:chainring] @cog = args[:cog] @wheel = args[:wheel] end def gear_inches ratio * wheel.diameter end def defaults { chainring: 40, cog: 18 } end end <file_sep>/inheritance/bicycle-01.rb # frozen_string_literal: true class Bicycle attr_reader :size, :tape_color def initialize(args) @size = args.fetch(:size) @tape_color = args.fetch(:tape_color) end # すべての自転車はデフォ値として、同じタイヤサイズとチェーンサイズを持つ def spares { chain: '10-speed', tire_size: '23', tape_color: 'tape_color' } end # 他にもメソッドたくさん end bike = Bicycle.new( size: 'M', tape_color: 'red' ) bike.size bike.spares <file_sep>/single_responsibility/obscuring_references.rb # frozen_string_literal: true class ObscuringReferences attr_reader :data def initialize(data) @data = data end def diameters # 0 is rim, 1 is tire data.collect { |cell| cell[0] + (cell[1] * 2) } end end # リムとタイヤのサイズ(ここではミリメートル!)の2次元配列 @data = [[622, 20], [622, 23], [559, 30], [559, 40]] # この状態だと、diametersメソッドは、直径を計算する方法だけ知っているわけではない # 配列のどこを見ればリムとタイヤがあるかまで知っている # また配列の構造に依存している # リムが[0]にあるという知識は複製されるものではなく、ただ一箇所に把握されるべき <file_sep>/test/double-01.rb # frozen_string_literal: true class WheelTest < MiniTest::Unit::TestCase def setup @wheel = Wheel.new(26, 1.5) end def test_implements_the_diameterizable_interface assert_respond_to(@wheel, :width) end def test_calculates_diameter end end # -------------------------------------------------------------------- module DiameterizableInterfaceTest def test_implements_the_diameterizable_interface assert_respond_to(@object, :width) end end class WheelTest < MiniTest::Unit::TestCase include DiameterizableInterfaceTest def setup @wheel = @object = Wheel.new(26, 1.5) end def test_calculates_diameter end end class DiameterDouble def diameter 10 end end # 該当のtest double が、このテストが期待する # インターフェースを守ることを証明する class DiameterDoubleTest < MiniTest::Unit::TestCase include DiameterizableInterfaceTest def setup @object = DiameterDouble.new end end class GearTest < MiniTest::Unit::TestCase def test_calculates_gear_inches gear = Gear.new( chainring: 52, cog: 11, wheel: DiameterDouble.new ) assert_in_delta(47.27, gear.gear_inches, 0.01) end end class DiameterDouble def width 10 end end <file_sep>/inheritance/spares-trap.rb # frozen_string_literal: true class RecumbentBike < Bicycle attr_reader :flag # initialize時にsuperを送っていないことにより、弊害が生じる def initialize(args) @flag = args[:flag] end def spares super.merge({ flag: flag }) end def default_chain '9-speed' end def default_tire_size '28' end end bent = RecumbentBike.new( flag: 'tall and orange' ) bent.spares # -> { # tire_size: nil, <- 初期化されていない # chain: nil, # flag: 'tall and orange' # } <file_sep>/manage_dependencies/bicycle-01.rb # frozen_string_literal: true class Gear attr_reader :chainring, :cog, :rim, :tire def initialize(chainring, cog, rim, tire) @chainring = chainring @cog = cog @rim = rim @tire = tire end def gear_inches # 依存関係その1 # GearはWheelという名前のクラスが存在することを予想している # 依存関係その2 # GearはWheelのインスタンスがdiameterに応答すること予想している # 依存関係その3 # Gearは、Wheel.newにrimとtireが必要なことを知っている # 依存関係その4 # GearはWheel.newの最初の引数がrimで、2番目の引数がtireである必要があることを知っている # 明示的なクラスをメソッドの深いところでハードコーディングしていると、このメソッドは、Wheelのインスタンスの直径しか測らないという意図に見える ratio * Wheel.new(rim, tire).diameter end def ratio chainring / cog.to_f end end class Wheel attr_reader :rim, :tire def initialize(rim, tire) @rim = rim @tire = tire end def diameter rim + (tire * 2) end def circumference diameter * Math::PI end end puts Gear.new(52, 11, 26, 1.5).gear_inches <file_sep>/duck-typing/trip-01.rb # frozen_string_literal: true class Trip attr_reader :bicycles, :customers, :vehicle # この mechanic 引数はどんなクラスのものでもよい def prepare mechanic mechanic.prepare_bicycles(bicycles) end end # このクラスのインスタンスを渡すことになったとしても動作する class Mechanic def prepare_bicycles bicycles bicycles.each { |bicycle| prepare_bicycle(bicycle) } end def prepare_bicycle bicycle # ... end end <file_sep>/manage_dependencies/bicycle-11.rb # frozen_string_literal: true class Gear attr_reader :chainring, :cog, :rim, :tire def initialize(chainring, cog, rim, tire) @chainring = chainring @cog = cog # 外部から依存オブジェクトを注入できないくらい制約が強い場合、Wheelのインスタンス作成をせめてGearクラス内で隔離する # ただしGearが作られるとき、Wheelの無条件で作られることに注意が必要 @wheel = Wheel.new(rim, tire) end def gear_inches ratio * wheel.diameter end end # ------------------------------------------------- class Gear attr_reader :chainring, :cog, :rim, :tire # 依然として、rimとtireを初期化時の引数として使うことに変わりはないし、 # Wheelインスタンスも、独自に内部で作成している def initialize(chainring, cog, rim, tire) @chainring = chainring @cog = cog @rim = rim @tire = tire end def gear_inches ratio * wheel.diameter end def wheel @wheel ||= Wheel.new(rim, tire) end end # --------------------------------- class Gear attr_reader :chainring, :cog, :rim, :tire def initialize(chainring, cog, rim, tire) @chainring = chainring @cog = cog @rim = rim @tire = tire end # 外部的な依存を取り除き、専用のメソッド内にカプセル化すること def gear_inches # 何行か恐ろしい計算がある # wheel.diameterからdiameterに変更することにより、メッセージはselfに送るものだけになった foo = some_intermediate_result * diameter # 何行か恐ろしい計算がある end def diameter wheel.diameter end def wheel @wheel ||= Wheel.new(rim, tire) end end <file_sep>/duck-typing/duck-type-discover.rb # frozen_string_literal: true # クラスで分岐するcase文は、未発見のダックタイプである可能性が高い class Trip attr_reader :bicycles, :customers, :vehicle def prepare preparers preparers.each { |preparer| case preparer when Mechanic preparer.prepare_bicycles(bicycles) when TripCoordinator preparer.buy_food(customers) when Driver preparer.gas_up(vehicle) preparer.fill_water_tank(vehicle) end } end end # kind_of? と is_a? は未発見のダックタイプの可能性がある if preparer.kind_of?(Mechanic) preparer.prepare_bicycles(bicycles) elsif preparer.kind_of?(TripCoordinator) preparer.buy_food(customers) elsif preparer.kind_of?(Driver) preparer.gas_up(vehicle) preparer.fill_water_tank(vehicle) end # respond_to? は未発見のダックタイプの可能性がある if preparer.respond_to?(:prepare_bicycles) preparer.prepare_bicycles(bicycles) elsif preparer.respond_to?((:buy_food) preparer.buy_food(customers) elsif preparer.kind_of?(Driver) preparer.gas_up(vehicle) preparer.fill_water_tank(vehicle) end <file_sep>/composition/bicycle-06.rb # frozen_string_literal: true require 'ostruct' module PartsFactory def self.build(config, part_class = Part, parts_class = Parts) parts_class.new( config.collect { |part_config| create_part(part_config) } ) end def self.create_part(part_config) OpenStruct.new( name: part_config[0], description: part_config[1], needs_spare: part_config.fetch(2, true) ) end end require 'forwardable' class Parts extend Forwardable def_delegators :@parts, :size, :each include Enumerable def initialize(parts) @parts = parts end def spares select { |part| part.needs_spare } end end class Part attr_reader :name, :description, :needs_spare def initialize(args) @name = args[:name] @description = args[:description] @needs_spare = args.fetch(:needs_spare, true) end end mountain_config = [ ['chain', '10-speed'], ['tire_size', '2.1'], ['front_shock', 'Manitou', false], ['rear_shock', 'Fox'] ] mountain_parts = PartsFactory.build(mountain_config) <file_sep>/sharing_role_behavior_in_module/schedule-01.rb # frozen_string_literal: true class Schedule def scheduled?(schedulable, start_date, end_date) puts "This #{schedulable.class}" + " is not scheduled\n" + " between #{start_date} and #{end_date}" end end class Bicycle attr_reader :schedule, :size, :chain, :tire_size # Scheduleを注入し、初期値を設定する def initialize(args={}) @schedule = args[:schedule] || Schedule.new end # 与えられた期間(現在はBicycleに固有)の間、 # bicycleが利用可能であればtrueを返す def schedulable?(start_date, end_date) !scheduled?(start_date - lead_days, end_date) end # scheduleの答えを返す def scheduled?(start_date, end_date) schedule.scheduled?(self, start_date, end_date) end # bicycleがスケジュール可能となるまでの # 準備期間を返す def lead_days 1 end end require 'date' starting = Date.parse("2015/09/04") ending = Date.parse("2015/09/10") b = Bicycle.new b.schedulable?(starting, ending) <file_sep>/single_responsibility/bicycle-03.rb # frozen_string_literal: true class Gear def initialize(chainring, cog) @chainring = chainring @cog = cog end def ratio # 破滅への道 @chainring / @cog.to_f end end # インスタンス変数は、常にアクセサメソッドで包み、直接参照しないようにしましょう # 単一責任のクラスを作るためには、オブジェクトの持つデータではなく、振る舞いに依存させるべき class Gear ## ここでアクセサメソッドを利用して、変数を隠蔽します attr_reader :chainring, :cog def initialize(chainring, cog) @chainring = chainring @cog = cog end def ratio chainring / cog.to_f end end <file_sep>/manage_dependencies/some_framework_gear.rb # frozen_string_literal: true # Gearが外部インターフェースの一部の場合 module SomeFramework class Gear attr_reader :chainring, :cog, :wheel def initialize(chainring, cog, wheel) @chainring = chainring @cog = cog @wheel = wheel end end end # 外部のインターフェースをラップし、自身を変更から守る # このクラスの唯一の目的が、ほかのクラスのインスタンスの作成であること # このようなオブジェクトに「ファクトリー」という名前を付けている module GearWrapper class Gear def self.gear(args) SomeFramework::Gear.new( args[:chainring], args[:cog], args[:wheel] ) end end end # 引数を持つハッシュを渡すことでGearのインスタンスを作成できるようになった GearWrapper.gear( chainring: 52, cog: 11, wheel: Wheel.new(26, 1.5) ).gear_inches
224770b1f1c8b8c8d4af5d50fea72da80bd49e15
[ "Ruby" ]
16
Ruby
Shichisan/object_oriented
6ce71cd5a0bb4b9c67c8a655f808e13030eab36f
a3420275929a443d0d9ff41169760ad90cff440a
refs/heads/master
<repo_name>Tomizuahir/Lab-Prog.-I<file_sep>/TP_2_Cascara/funciones.c #include <stdio.h> #include <stdlib.h> #include "funciones.h" int obtenerEspacioLibre(EPersona lista[],int tamLista) { int idLibre=-1; for(int i=0;i<tamLista;i++) { if(lista[i].estado==0) { idLibre=i; break; } } return idLibre; } int buscarPorDni(EPersona lista[], int dni,int tamLista) { int idDNI=-1; for(int i=0;i<tamLista;i++) { if(lista[i].estado==1 && lista[i].dni==dni) { idDNI=i; } } return idDNI; } <file_sep>/validaciones.c #include <stdio.h> #include <stdlib.h> #include <string.h> //Codigo extraido del video https://www.youtube.com/watch?v=OW1TqB6Xzdw de CODE UTN FRA int esNumerico(char str[]){ int i=0; while(str[i]!='\0'){ if(str[i]<'0' || str[i]>'9') return 0; i++; } return 1; } //Codigo extraido del video https://www.youtube.com/watch?v=OW1TqB6Xzdw de CODE UTN FRA int esSoloLetras(char str[]){ int i=0; while(str[i]!='\0'){ if((str[i]!=' ') && (str[i]<'a' || str[i]>'z') && (str[i]<'A' || str[i]>'Z')) return 0; i++; } return 1; } //REVISAR ESTA MAL Codigo extraido del video https://www.youtube.com/watch?v=OW1TqB6Xzdw de CODE UTN FRA int esAlfaNumerico(char str[]){ int i=0; while(str[i]!='\0'){ if((str[i]!=' ') && (str[i]<'a' || str[i]>'z') && (str[i]<'A' || str[i]>'Z') && (str[i]<'0' || str[i]>'9')) return 0; i++; } return 1; } //Codigo extraido del video https://www.youtube.com/watch?v=OW1TqB6Xzdw de CODE UTN FRA int esTelefono(char str[]){ int i=0; int contadorGuiones=0; while(str[i]!='\0'){ if((str[i]!=' ') && (str[i]!='-') && (str[i]<'0' || str[i]>'9')) return 0; if(str[i]=='-') contadorGuiones++; i++; } if(contadorGuiones==0 || contadorGuiones==2) return 1; return 0; } <file_sep>/funciones_ABM.h #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct{ char nombre[50]; int edad; short int estado; int dni; }EPersona; /** \brief Devuelve la primera posicion del array de estructuras que se encuentra lugar libre para Altas (debe contener un campo "ESTADO") * * \param lista[] Array de estructuras a analizar * \param tamLista Cantidad de elementos del array de estructuras * \return -1-No hay lugar libre,<Otro valor>-Posicion libre del array de estructuras * */ int obtenerEspacioLibre(EPersona[],int); /** \brief Lista en consola los datos de personas en alta en el sistema (debe contener un campo "ESTADO") * * \param lista[] Array de estructuras de la base de datos * \param tamLista Cantidad de elementos del array de estructura * */ void mostrarLista(EPersona[],int); /** \brief Inicializa el array de la base de datos, indicando que todos son espacios libres * * \param lista[] Array de estructuras de base de datos * \param tamLista Cantidad de elementos del array * */ void inicializarDatos(EPersona[],int); /** \brief Comprueba si un array para un ABM tiene todos los espacios sin altas * * \param lista[] Array de estructuras * \param tamLista Cantidad de elementos del array de estructuras * \return 0-Array con altas, 1-Array sin altas * */ int arrayVacio(EPersona[],int); <file_sep>/ordenamiento.c //Metodo de ordenamiento de vectores de la burbuja para numeros void ordenamientoBurbujaNumeros(int nums1[],int tam_nums,int ascend){ int i,j,aux; for(i=0;i<tam_nums-1;i++){ for(j=i+1;j<tam_nums;j++){ if((ascend!=0 && nums1[i]>nums1[j]) || (ascend==0 && nums1[i]<nums1[j])){ aux=nums1[i]; nums1[i]=nums1[j]; nums1[j]=aux; } } } } <file_sep>/Clase 09.10.2017/Memoria Dinamica I/main.c #include <stdio.h> #include <stdlib.h> int main() { int* vec;//Definimos un puntero int* aux;//Puntero auxiliar para evitar perder valores de memoria si la redimension del vector resultara nula vec=(int*)malloc(5*sizeof(int));/*Asigna memoria dinamica al puntero. malloc(cantidad de bytes de memoria a reservar) Si no se consigue memoria devuelve NULL, caso contrario, devuelve la direccion de memoria en donde comienza el vector.*/ if(vec==NULL){ printf("No se consiguio memoria."); exit(1); //Termina el programa. } for(int i=0;i<5;i++){ printf("Ingrese un numero: "); scanf("%d",(vec+i)); } for(int i=0;i<5;i++){ printf("%d",*(vec+i)); } printf("\n"); /*realloc (vector puntero a redimensionar, cantidad de bytes de memoria a reservar). /*Devuelve NULL si no consigue,caso contrario devuelve la direccion de memoria*/ aux=(int*)realloc(vec,10*sizeof(int)); if(aux!=NULL){ //Si se consiguio memoria para realloc, le copiamos el auxiliar. vec=aux; } /*for(int i=5;i<10;i++){ printf("%d",*(vec+i)); } printf("\n"); for(int i=0;i<10;i++){ printf("%d",*(vec+1)); } printf("\n");*/ free(vec);//Libera la memoria que ocupaba vec(aun cuando el programa este cerrado, se debe liberar porque es espacio que queda ocupado. return 0; } <file_sep>/Arrays/Arrays - Ej.2/main.c #include <stdio.h> #include <stdlib.h> int main() { char palabra[5]; for(int i=0;i<5;i++) { printf("Ingrese solo vocales: "); fflush(stdin); scanf("%c",&palabra[i]); while(palabra[i]!='A' && palabra[i]!='E' && palabra[i]!='I' && palabra[i]!='O' && palabra[i]!='U' && palabra[i]!='a' && palabra[i]!='e' && palabra[i]!='i' && palabra[i]!='o' && palabra[i]!='u') { printf("Error: Ingrese solo vocales: "); fflush(stdin); scanf("%c",&palabra[i]); } } for(int i=0;i<5;i++) { printf("%c",palabra[i]); } printf("\n"); system("pause"); return 0; } <file_sep>/Arrays/Ejercicios/Matrices Ej.2/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> //Tiene errores char db_nombres[20][32], db_sexo[20]; int db_edad[20], db_id[20]; int main() { for (int i=0; i<20;i++) { db_id[i]=i; printf("Ingrese sexo para ID %d: ",db_id[i]); fflush(stdin); scanf("%c",&db_sexo[i]); while(toupper(db_sexo[i])!='F' && toupper(db_sexo[i])!='M') { printf("ERROR > Ingrese sexo para ID %d: ",db_id[i]); fflush(stdin); scanf("%c",&db_sexo[i]); } printf("Ingrese edad para ID %d: ",db_id[i]); scanf("%d",&db_edad[i]); while(db_edad[i]<0 || db_edad[i]>110) { printf("ERROR > Ingrese edad para ID %d: ",db_id[i]); scanf("%d",&db_edad[i]); } printf("Ingrese nombre para ID %d: ",db_id[i]); gets(db_nombres[i]); while(strlen(db_nombres[i])<5) { printf("Ingrese nombre para ID %d: ",db_id[i]); gets(db_nombres[i]); } } } <file_sep>/funciones_ABM.c //SE DEBE ADAPTAR EL CODIGO int obtenerEspacioLibre(EPersona lista[],int tamLista){ //Flag de elemento libre encontrado int idLibre=-1; //Recorre todo el array en busqueda, si encuentra lugar guarda en que posicion for(int i=0;i<tamLista;i++){ if(lista[i].estado==0){ idLibre=i; break; } } return idLibre; } //SE DEBE ADAPTAR EL CODIGO void mostrarLista(EPersona lista[],int tamLista) { //Auxiliar para swapeo en el burbujeo de nombres EPersona aux_pers; //Burbujeo (ordenamiento) de array por nombre for(int i=0;i<tamLista-1;i++){ if(lista[i].estado!=1){ continue; } for(int j=i+1;j<tamLista;j++){ if(lista[j].estado!=1){ continue; } if(strcmp(lista[i].nombre,lista[j].nombre)>0){ aux_pers=lista[i]; lista[i]=lista[j]; lista[j]=aux_pers; } } } //Si el array tiene altas muestra todas, por orden alfabetico por nombre, sino notifica que el array no tiene altas if(arrayVacio(lista,tamLista)!=1){ for(int i=0;i<tamLista;i++){ if(lista[i].estado==1){ printf("DNI: %d NOMBRE: %s EDAD: %d\n",lista[i].dni,lista[i].nombre,lista[i].edad); //MODIFICAR SEGUN USO } } } else{ printf("La base de datos no tiene altas activas para mostrar.\n"); } } //SE DEBE ADAPTAR EL CODIGO void inicializarDatos(EPersona lista[],int tamLista) { //Inicializa todo el array como espacio libre para admitir altas for(int i=0;i<tamLista;i++){ lista[i].estado=0; } } //SE DEBE ADAPTAR EL CODIGO int arrayVacio(EPersona lista[],int tamLista) { //Flag, indica si la cadena esta vacia int cad_vacia=1; //Recorremos todo el array buscando algun alta activa for(int i=0;i<tamLista;i++){ //Si encontramos un alta activa, marcamos el flag y no seguimos buscando mas elementos if(lista[i].estado==1){ cad_vacia=0; break; } } //Segun corresponda, devolvemos 1 si el array no tiene altas, sino devolvemos 0 return cad_vacia; } <file_sep>/Estructuras/Ejercicios/ABM - BD Relacional/main.c #include <stdio.h> #include <stdlib.h> void hardcodearProgramadores(eProgramador[],int); typedef struct { int idProg; char nombre[64]; int cat; int proyecto; float sueldo; int cant_hs; }eProgramador; typedef struct { int id; char descripcion; int pago_hora; }eCategoria; int main() { } void hardcodearProgramadores(eProgramador listaProg[],int tamListaProg) { listaProg[0]={0,"ANA",0,} } <file_sep>/TP_1_Cascara/funciones.c float Sumar(float op1, float op2) { op1+=op2; return op1; } float Restar(float op1, float op2) { op1-=op2; return op1; } float Dividir(float op1, float op2) { if(op2!=0) { op1/=op2; } else { op2=1; printf("DIVIDIR: Error matematico. No se admite la division por cero. Resultado incorrecto.\n"); } return op1; } float Multiplicar(float op1, float op2) { op1*=op2; return op1; } int Factorial(int N) { int fact=1; if(N>=1) { for(int i=N;i>1;i--) { fact*=i; } } else { N=1; printf("FACTORIAL: Error matematico. No se admiten factoriales de numeros no naturales. Resultado incorrecto.\n"); } return fact; } <file_sep>/Manipulacion de Ficheros 13.10.2017/main.c #include <stdio.h> #include <stdlib.h> int main() { int num=20; float flot=2.2; char nombre[]={"HOLA"}; FILE* f;//Debemos crear una estructura FILE con puntero a la misma para manipular archivos f=fopen("Prueba.txt","a");/*fopen abre archivos, argumento primero es ruta,nombre y extension. Argumento segundo, el modo de apertura. w-escritura caracteres, wb-escritura binaria a-append de archivos agrega contenido r-lectura caracteres rb-lectura binario*/ if(f==NULL)//Si el puntero contiene NULL es porque ocurrio un error al intentar manipular el archivo { printf("ERROR > No se pudo escribir el archivo."); exit(1); } fprintf(f,"\n%d",num);/*fprintf casi identico al printf pero para archivos. Primer argumento es el puntero al archivo que se esta trabajando. Segundo argumento es el texto o datos de variables en cuestion.*/ fprintf(f,"\n%f",flot);/*fprintf casi identico al printf pero para archivos. Primer argumento es el puntero al archivo que se esta trabajando. Segundo argumento es el texto o datos de variables en cuestion.*/ fprintf(f,"\n%s",nombre); printf("Escritura correcta del archivo. Se cerrara el programa."); fclose(f);//Los archivos deben cerrarse cuando no se utilizan. Para esto funcion fclose y puntero al archivo como argumento. return 0; } <file_sep>/TP_2_Cascara/main.c //Hacer modulares los procesos de cada opcion //Hacer modulares las validaciones de datos //Hacer opciones de 2 a 4 #include <stdio.h> #include <stdlib.h> #include <string.h> #include "funciones.h" #define TAM_LISTA 20 void Hardcodeo(EPersona[],int); void Listar(EPersona[],int); int main() { char seguir='s';//Respuesta del menu principal para volver al menu o salir del programa int opcion=0;//Opcion seleccionada del menu int aux_num;//Variable auxiliar para numeros enteros char aux_cad[512];//Variable auxiliar para cadenas de caracteres int id_actual;//Elemento actual en el que trabaja el dato al que hacerle ABM en el array de estructuras //Definir un array de estructuras de 20 elementos para el tipo EPersona EPersona dPersona[20]; Hardcodeo(dPersona,TAM_LISTA); //Menu principal while(seguir=='s') { printf("MENU PRINCIPAL:\n\n"); printf("1- Agregar persona\n"); printf("2- Borrar persona\n"); printf("3- Imprimir lista ordenada por nombre\n"); printf("4- Imprimir grafico de edades\n"); printf("--------------------------------------\n"); printf("5- Salir\n\n"); printf("Opcion elegida: "); //Ingresar la opcion elegida scanf("%d",&opcion); //Validar opcion seleccionada while(opcion<1 || opcion>5) { printf("ERROR Opcion no valida. Elija una opcion: "); scanf("%d",&opcion); } //Borrar consola system("cls"); //Ejecutar instrucciones de la opcion seleccionada anteriormente switch(opcion) { //Opcion 1 case 1: //Busca el primer indice con espacio libre para guardar el alta a ingresar id_actual=obtenerEspacioLibre(dPersona,TAM_LISTA); //Si encontramos un indice libre en el array de estructuras, pedimos los datos del alta a ingresar if(id_actual!=-1) { //Solicita DNI y lo guarda en el indice, campo DNI printf("ALTA DE DATOS:\n\n"); printf("DNI: "); scanf("%d",&dPersona[id_actual].dni); //Valida el DNI ingresado while(dPersona[id_actual].dni<1000000) { printf("ERROR, dato no valido. Ingresar desde 1000000 sin puntos. DNI: "); scanf("%d",&dPersona[id_actual].dni); } //Comprobar si ya existe el dni aux_num=buscarPorDni(dPersona,dPersona[id_actual].dni,TAM_LISTA); printf("AUX: %d\n",aux_num); //Si el DNI ya existe no nos permite guardar mas datos ni registrar el alta if(aux_num!=-1) { printf("El DNI ya existe.\n"); } //Si el DNI no fue encontrado en el array, nos pide datos y permite registrar el alta else { printf("El DNI no fue ingresado anteriormente.\n"); //Pide nombre y lo guarda en el elemento libre del array printf("Nombre: "); fflush(stdin); gets(dPersona[id_actual].nombre); //Valida el nombre ingresado while(strlen(dPersona[id_actual].nombre)<3) { printf("ERROR, dato no valido. Ingrese al menos 3 caracteres. Nombre: "); fflush(stdin); gets(dPersona[id_actual].nombre); } //Pide la edad printf("Edad: "); scanf("%d",&dPersona[id_actual].edad); //Valida la edad while(dPersona[id_actual].edad<0 || dPersona[id_actual].edad>120) { printf("ERROR, dato no valido. Ingresar desde 0 hasta 120. EDAD: "); scanf("%d",&dPersona[id_actual].edad); } //Marca la bandera de esta estructura para no sobrescribir los datos en un futuro ingreso dPersona[id_actual].estado=1; } //Si el indice libre devuelto es -1, no ha espacio y no nos dejara ingresar datos. } else { printf("No hay espacio libre para guardar esta entrada.\n"); } break; //Opcion 2 case 2: break; //Opcion 3 case 3: Listar(dPersona,TAM_LISTA); break; //Opcion 4 case 4: break; //Opcion 5 case 5: seguir = 'n'; break; } } //Retornar estado de ejecucion return 0; } void Hardcodeo(EPersona lista[],int tamLista) { for(int i=0;i<tamLista;i++) { lista[i].estado=0; } } void Listar(EPersona lista[],int tamLista) { for(int i=0;i<tamLista;i++) { printf("ID: %d DNI: %d NOMBRE: %s EDAD: %d ESTADO: %d\n",i,lista[i].dni,lista[i].nombre,lista[i].edad,lista[i].estado); } } <file_sep>/Arrays/Arrays Ej.1/main.c #include <stdio.h> #include <stdlib.h> int main() { //Vector de 10 elementos, numero ingresado a buscar y la bandera de haberlo hallado int numeros[]={10,20,30,40,50,60,70,80,90,100}, unum, flag_num; //Nos pregunta que numero queremos ingresar para la busqueda printf("Ingrese numero que desea buscar en el array: "); scanf("%d",&unum); //Borra la pantalla system("cls"); //Bandera que indica si encontramos el resultado. Comienza con resultado negativo. flag_num=0; //Buscamos en todos los elementos del vector, o hasta que el numero a buscar sea hayado por lo menos una vez for(int i=0;i<10;i++) { //Si el numero a buscar esta en el vector, marcamos la bandera, avisamos haberlo encontrado y salimos de la iteracion inmediatamente if(numeros[i]==unum) { flag_num=1; printf("El numero %d fue encontrado al menos una vez. Posicion: %d.\n",unum,i+1); break; } } //En caso de haber recorrido todos los elementos del vector sin encontrar el numero, avisamos que no se encuentra en el array. if(flag_num==0) { printf("El numero %d no existe dentro del array.\n",unum); } //Pausa en la consola. system("pause"); return 0; } <file_sep>/Estructuras/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> #define TAM 5 typedef struct { int legajo; char nombre[50]; int edad; float peso; char sintoma[50]; }ePaciente; void generarDatos(ePaciente[], int); void mostrarPaciente(ePaciente); void mostrarTodosLosPacientes(ePaciente[], int); void mostrarPacientesSintoma(ePaciente[], int, char[]); void cargarPacientes(ePaciente[], int); void ordenarPacientes(ePaciente[], int, int); int main() { ePaciente listaPacientes[TAM]; //cargarPacientes(listaPacientes, TAM); generarDatos(listaPacientes, TAM); ordenarPacientesNombre(listaPacientes, TAM, 0); mostrarPacientesSintoma(listaPacientes, TAM, "dolor De Cabeza"); mostrarTodosLosPacientes(listaPacientes, TAM); return 0; } void mostrarTodosLosPacientes(ePaciente lista[], int tam) { system("cls"); for(int i=0; i<tam; i++) { mostrarPaciente(lista[i]); } } void mostrarPaciente(ePaciente paciente) { printf("%d--%s--%d--%f--%s\n", paciente.legajo,paciente.nombre, paciente.edad, paciente.peso, paciente.sintoma); } void cargarPacientes(ePaciente lista[], int cantidad) { for(int i=0; i<TAM; i++) { system("cls"); printf("Ingrese legajo: "); scanf("%d", &lista[i].legajo); printf("Ingrese nombre: "); fflush(stdin); gets(lista[i].nombre); printf("Ingrese edad: "); scanf("%d", &lista[i].edad); printf("Ingrese peso: "); scanf("%f", &lista[i].peso); printf("Ingrese sintoma: "); fflush(stdin); gets(lista[i].sintoma); } } void ordenarPacientesNombre(ePaciente pacientes[], int cantidad, int ascendente) { ePaciente aux_paciente; for(int i=0; i<cantidad-1; i++) { for(int j=i+1; j<cantidad; j++) { if(ascendente==0) { if(stricmp(pacientes[i].nombre,pacientes[j].nombre)>0) { aux_paciente=pacientes[i]; pacientes[i]=pacientes[j]; pacientes[j]=aux_paciente; } } else { if(stricmp(pacientes[i].nombre,pacientes[j].nombre)<0) { aux_paciente=pacientes[i]; pacientes[i]=pacientes[j]; pacientes[j]=aux_paciente; } } } } } void mostrarPacientesSintoma(ePaciente lista_pacientes[], int tam, char sint_paciente[]) { system("cls"); for(int i=0;i<tam;i++) { if(stricmp(lista_pacientes[i].sintoma,sint_paciente)==0) { mostrarPaciente(lista_pacientes[i]); } } } void generarDatos(ePaciente lista_pacientes[], int tam) { for(int i=0;i<tam;i++) { strcpy(lista_pacientes[i].nombre, "Nombre"); lista_pacientes[i].edad=10; lista_pacientes[i].legajo=i; lista_pacientes[i].peso=10; } strcpy(lista_pacientes[0].sintoma, "Dolor de panza"); strcpy(lista_pacientes[1].sintoma, "Dolor de cabeza"); strcpy(lista_pacientes[2].sintoma, "Dolor de panza"); strcpy(lista_pacientes[3].sintoma, "Dolor de cabeza"); strcpy(lista_pacientes[4].sintoma, "Dolor de panza"); } <file_sep>/Clase 09.10.2017/Memoria Dinamica II/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ int cant; char *nombre; char auxcad[50]; printf("Ingrese nombre: "); gets(auxcad); cant=strlen(auxcad); nombre=(char*)malloc((cant+1)*sizeof(char)); if(nombre!=NULL){ strcpy(nombre,auxcad); } return 0; } <file_sep>/Estadisticas.h /** \brief Grafica en la consola una estadistica * * \param lista[] Array de estructuras * \param tamLista Cantidad de elementos del array de estructuras * */ void graficar(EPersona[],int); <file_sep>/Estadisticas.c #include <stdio.h> #include <stdlib.h> void graficar(EPersona lista[],int tamLista) { //Contadores de clasificaciones de edades int c_18=0, c_19_35=0, c_36_mas=0, max_clasif;//MODIFICAR LAS CATEGORIAS //Recorre todo el attay, tomando una estadistica de clasificaciones de edades for(int i=0;i<=tamLista;i++){ //Cantidad de menores de 18 aņos if(lista[i].estado==1 && lista[i].edad<19){ c_18++; } //Cantidad de personas entre 19 y 35 aņos else if(lista[i].estado==1 && lista[i].edad>18 && lista[i].edad<36){ c_19_35++; } //Cantidad de personas mayores a 35 aņos else if(lista[i].estado==1){ c_36_mas++; } } //Averigua que cantidad maxima tiene la clasificacion que mas personas tiene (cantidad de lineas maximas del grafico) if(c_18>=c_19_35 && c_18>=c_36_mas){ max_clasif=c_18; } else if(c_19_35>=c_18 && c_19_35>=c_36_mas){ max_clasif=c_19_35; } else if(c_36_mas>=c_18 && c_36_mas>=c_19_35){ max_clasif=c_36_mas; } //Grafica linea por linea, los datos representativos de la estadistica anterior //En caso de haber datos en los cuales hacer una estadistica, graficara if(max_clasif!=0){ for(int i=max_clasif;i>0;i--){ if(i<=c_18){ printf(" * "); } else { printf(" "); } if(i<=c_19_35){ printf(" * "); } else { printf(" "); } if(i<=c_36_mas){ printf(" * "); } else{ printf(" "); } printf("\n"); } printf("0-18 19-35 >36\n"); } else{ printf("No hay datos, no es posible graficar una estadistica.\n"); } } <file_sep>/ordenamiento.h #include <stdio.h> #include <stdlib.h> #include <string.h> /** \brief Ordenamiento de vectores por metodo de la burbuja * * \param nums1 Vector a ordenar * \param tam_nums Cantidad de elementos del vector a ordenar * \param ascendente Ordena de forma ascendente si el valor es distinto a cero, caso contrario descendente * */ void ordenamientoBurbujaNumeros(int[],int,int); <file_sep>/Estructuras/Programa ABM/main.c #include <stdio.h> #include <stdlib.h> #include <conio.h> #include <ctype.h> #include <string.h> typedef struct{ int id; char nombre[32]; char categoria; int proyecto; int estado; } eProgramador; void inicializar_array(eProgramador[],int); void mostrar_programadores(eProgramador[],int); void mostrar_programador(eProgramador); void harcodear_programadores(eProgramador[]); int buscar_libre(eProgramador[],int); int buscar_programador(int,eProgramador[],int); void alta_programador(eProgramador[],int); void baja_programador(eProgramador[],int,int); //a = Senior //b = SemiSenior //c = Junior int menu(); int main() { eProgramador programador[50]; inicializar_array(programador,50); int id_borrar; //harcodear_programadores(programador); //alta_programador(programador,31); //mostrar_programadores(programador,50); int salir = 1; do{ switch(menu()){ case 1: system("cls"); printf("Opcion1"); alta_programador(programador,50); getch(); break; case 2: system("cls"); case 'A': printf("Opcion2"); getch(); break; case 3: system("cls"); printf("Opcion3"); printf("ID: "); scanf("%d",&id_borrar); baja_programador(programador,50,id_borrar); getch(); break; case 4: system("cls"); printf("Opcion4"); mostrar_programadores(programador,50); getch(); break; case 5: salir = 0; break; } }while(salir); return 0; } int menu(){ int opcion; system("cls"); printf("\n***Programadores***\n\n\n"); printf("1- Alta Programador\n"); printf("2- Modificacion Programador\n"); printf("3- Baja Programador\n"); printf("4- Listado Programadores\n"); printf("5- Salir\n"); printf("\n\nIngrese opcion: "); scanf("%d", &opcion); return opcion; } void inicializar_array(eProgramador program[],int tam_progra) { for(int i=0;i<tam_progra;i++) { program[i].id=0; strcpy(program[i].nombre,""); program[i].categoria='A'; program[i].proyecto=0; program[i].estado=0; } } void mostrar_programadores(eProgramador programadores[],int tam_programadores) { int flag=0; for(int i=0;i<tam_programadores;i++) { if(programadores[i].estado==1) { mostrar_programador(programadores[i]); flag=1; } } if(flag==0) { printf("No hay programadores que mostrar.\n"); } system("pause"); } void mostrar_programador(eProgramador programador) { char cat[20]; switch(programador.categoria) { case 'A': strcpy(cat,"Senior"); break; case 'B': strcpy(cat,"Semi-Senior"); break; case 'C': strcpy(cat,"Junior"); break; } printf("ID: %d Nombre: %s Categoria: %c Proyecto: %d\n",programador.id, programador.nombre, cat, programador.proyecto); } void harcodear_programadores(eProgramador program[]) { for(int i=0;i<=5;i++) { program[i].estado=1; } } int buscar_libre(eProgramador program[],int tam) { int indice_libre=-1; for(int i=0;i<tam;i++) { if(program[i].estado==0) { indice_libre=i; break; } } return indice_libre; } int buscar_programador(int id_prog,eProgramador program[],int tam) { int indice=-1; for(int i=0;i<tam;i++) { if(program[i].id==id_prog) { indice=i; break; } } return indice; } void alta_programador(eProgramador program[],int indice) { int libre=buscar_libre(program,50); if(libre!=-1) { printf("Guardar en elemento: %d\n\n",libre); printf("Ingrese ID: "); scanf("%d",&program[libre].id); printf("Nombre: "); fflush(stdin); gets(program[libre].nombre); printf("Categoria: "); fflush(stdin); scanf("%c",&program[libre].categoria); printf("Proyecto: "); scanf("%d",&program[libre].proyecto); program[libre].estado=1; } } void baja_programador(eProgramador program[],int tam,int id_program) { int indice_ok; indice_ok=buscar_programador(id_program,program,tam); if(indice_ok!=-1) { program[indice_ok].estado=0; printf("Usuario eliminado.\n"); } else { printf("No se encontro el programador.\n"); } } <file_sep>/TP_1_Cascara/funciones.h #ifndef FUNCIONES_H_INCLUDED #define FUNCIONES_H_INCLUDED /** \brief Suma dos numeros flotantes * * \param op1 Primer Operando * \param op2 Segundo Operando * \return Devuelve suma de dos operandos * */ float Sumar(float, float); /** \brief Resta dos numeros flotantes * * \param op1 Primer Operando * \param op2 Segundo Operando * \return Devuelve resta de dos operandos * */ float Restar(float, float); /** \brief Divide dos numeros flotantes * * \param op1 Primer Operando * \param op2 Segundo Operando * \return Devuelve division de dos operandos * */ float Dividir(float, float); /** \brief Multiplica dos numeros flotantes * * \param op1 Primer Operando * \param op2 Segundo Operando * \return Devuelve producto de dos operandos * */ float Multiplicar(float, float); /** \brief Calcula factorial de un numero * * \param N Numero Natural * \return Devuelve factorial de un numero * */ int Factorial(int); #endif // FUNCIONES_H_INCLUDED <file_sep>/TP_1_Cascara/main.c #include <stdio.h> #include <stdlib.h> #include "funciones.h" int main() { //Guarda si continuaremos en el menu char seguir='s'; //Opcion elegida por el usuario int opcion; //num1 y num2 son los operandos para los calculos. dif_num1 comprueba si el operando 1(num1) es entero o no float num1=0,num2=0,dif_num1; while(seguir=='s') { //Menu del programa //Limpia la consola system("cls"); //Muestra todas las opciones disponibles printf("1- Ingresar 1er operando (A=%.2f)\n",num1); printf("2- Ingresar 2do operando (B=%.2f)\n",num2); printf("3- Calcular la suma (A+B)\n"); printf("4- Calcular la resta (A-B)\n"); printf("5- Calcular la division (A/B)\n"); printf("6- Calcular la multiplicacion (A*B)\n"); printf("7- Calcular el factorial (A!)\n"); printf("8- Calcular todas las operacione\n"); printf("9- Salir\n"); //Pide ingresar una opcion al usuario printf("\nOpcion: "); scanf("%d",&opcion); //Limpia la consola system("cls"); switch(opcion) { //Segun la opcion ingresada toma una decision case 1: //1- Ingresar 1er operando (A=x) //Ingresa el primer operando printf("Operando 1: "); scanf("%f",&num1); //Comprueba si el primer operando es un entero(para calcular el factorial llegado el caso) dif_num1=num1-(int)num1; break; case 2: //2- Ingresar 2do operando (B=y) //Ingresa el segundo operando printf("Operando 2: "); scanf("%f",&num2); break; case 3: //3- Calcular la suma (A+B) printf("Resultado de suma (%.2f+%.2f): %.2f\n\n",num1,num2,Sumar(num1,num2)); system("pause"); break; case 4: //4- Calcular la resta (A-B) printf("Resultado de resta (%.2f-%.2f): %.2f\n\n",num1,num2,Restar(num1,num2)); system("pause"); break; case 5: //5- Calcular la division (A/B) //Si el divisor es cero, no permite efectuar la division, caso contrario, la calcula y la muestra if(num2==0) { printf("ERROR: No se admite la division por cero. Por favor modifique el Operando 2 ingresando otro valor.\n"); } else { printf("Resultado de division (%.2f/%.2f): %.2f\n\n",num1,num2,Dividir(num1,num2)); } system("pause"); break; case 6: //6- Calcular la multiplicacion (A*B) printf("Resultado de multiplicacion (%.2f*%.2f): %.2f\n\n",num1,num2,Multiplicar(num1,num2)); system("pause"); break; case 7: //7- Calcular el factorial (A!) //Comprueba que el numero para el factorial sea natural, y entero. De no serlo no permite el calculo if(num1<1 || dif_num1!=0) { printf("ERROR: Los factoriales deben ser con numeros naturales (enteros y positivos). A continuacion modifique el valor del operando 1 antes de elegir esta opcion.\n"); } else { printf("Resultado de Factorial (%.0f!): %d\n\n",num1,Factorial((int)num1)); } system("pause"); break; case 8: //8- Calcular todas las operacione //Operacion de la opcion 3 printf("Resultado de suma (%.2f+%.2f): %.2f\n\n",num1,num2,Sumar(num1,num2)); //Operacion de la opcion 4 printf("Resultado de resta (%.2f-%.2f): %.2f\n\n",num1,num2,Restar(num1,num2)); //Operacion de la opcion 5 //Si el divisor es cero, no permite efectuar la division, caso contrario, la calcula y la muestra if(num2==0) { printf("ERROR: No se admite la division por cero. Por favor modifique el Operando 2 ingresando otro valor.\n\n"); } else { printf("Resultado de division (%.2f/%.2f): %.2f\n\n",num1,num2,Dividir(num1,num2)); } //Operacion de la opcion 6 printf("Resultado de multiplicacion (%.2f*%.2f): %.2f\n\n",num1,num2,Multiplicar(num1,num2)); //Operacion de la opcion 7 //Comprueba que el numero para el factorial sea natural, y entero. De no serlo no permite el calculo if(num1<1 || dif_num1!=0) { printf("ERROR: Los factoriales deben ser con numeros naturales (enteros y positivos). A continuacion modifique el valor del operando 1 antes de elegir esta opcion.\n\n"); } else { printf("Resultado de Factorial (%.0f!): %d\n\n",num1,Factorial((int)num1)); } system("pause"); break; case 9: //9- Salir seguir='n'; break; default: //Si la opcion ingresada no es valida, lo avisa y a continuacion, repetira el menu y pedira reingresar una opcion printf("ERROR: Opcion no valida.\n\n"); system("pause"); } } return 0; } <file_sep>/Arrays/Ejercicios/Matrices - Ej. 1/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> int validarCadena(char[], int); void mostrarNombres(char[][32],int); void mostrarNombre(char[]); void ordenarCadenas(char[][32],int); int main() { char nombres[5][32],buffer[128]; for(int i=0;i<=4;i++) { printf("Ingrese nombre: "); gets(buffer); while(!validarCadena(buffer,32)) { printf("ERROR > Ingrese nombre: "); gets(buffer); } strcpy(nombres[i],buffer); } ordenarCadenas(nombres,5); mostrarNombres(nombres,5); system("pause"); system("cls"); for(int i=0;i<5;i++) { mostrarNombre(nombres[i]); } system("pause"); return 0; } int validarCadena(char cadena[], int long_cadena) { int valor=0; if(strlen(cadena)<long_cadena) { valor=1; } return valor; } void mostrarNombres(char f_nombres[][32],int a) { for (int i=0; i<a; i++) { printf("%s\n",f_nombres[i]); } } void mostrarNombre(char f_nombres[]) { printf("%s\n",f_nombres); } void ordenarCadenas(char f_nombres[][32], int filas) { char oC_buffer[32]; for(int i=0; i < filas-1; i++) { for(int j= i+1; j < filas; j++) { if(strcmp(f_nombres[i],f_nombres[j])>0) { strcpy(oC_buffer,f_nombres[i]); strcpy(f_nombres[i],f_nombres[j]); strcpy(f_nombres[j],oC_buffer); } } } } <file_sep>/README.md # Lab-Prog.-I Laboratorio I / Programacion I - Ejercicios <file_sep>/validaciones.h /** \brief Compruena si una cadena es numerica * * \param str[] Cadena de caracteres a analizar * \return 0-No es numerica, 1-Es numerica * */ int esNumerico(char str[]); /** \brief Compruena si una cadena es un numero de telefono * * \param str[] Cadena de caracteres a analizar * \return 0-No es telefono, 1-Es telefono * */ int esTelefono(char str[]); /** \brief Compruena si una cadena es alfanumerica * * \param str[] Cadena de caracteres a analizar * \return 0-No es alfanumerica, 1-Es alfanumerica * */ int esAlfaNumerico(char str[]); /** \brief Compruena si una cadena esta compuesta solo por letras y espacios * * \param str[] Cadena de caracteres a analizar * \return 0-No es solo letras y espacios, 1-Es solo letras y espacios * */ int esSoloLetras(char str[]); <file_sep>/Arrays/Vectores Paralelos/main.c #include <stdio.h> #include <stdlib.h> int main() { /*Cuatro vectores de 5 elementos. Una variable auxiliar para calcular el promedio a guardar en el ultimo vector (promedios)*/ int leg[]={38,24,18,83,57}; int notas1[]={10,7,2,2,5}; int notas2[]={4,10,2,5,4}; float promedios[5],prom_aux; //Recorremos cada fila(posicion) del conjunto de vectores leyendo, calculando y escribiendo datos for(int i=0;i<5;i++) { prom_aux=(float)(notas1[i]+notas2[i])/2; promedios[i]=prom_aux; printf("Pos: %d Leg: %2d Parcial 1: %2d Parcial 2: %2d Promedio: %2.2f\n",i,leg[i],notas1[i],notas2[i],promedios[i]); } //Pausa system("pause"); return 0; }
7e2e92e2b3db5d1c0de9451149f19cb02618983c
[ "Markdown", "C" ]
25
C
Tomizuahir/Lab-Prog.-I
9d352e1a326fd5d10d3f2190685072099c99d9d0
72025c979866639bbcb64245ccdf3c283743b981
refs/heads/main
<file_sep>package com.itheima.mybatis.sqlsession.proxy; import com.itheima.mybatis.cfg.Mapper; import com.itheima.utils.Executor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.sql.Connection; import java.util.Map; /** * @program: day01_eesy_04mybatis_design * @description * @author: 晏宝辉 * @create: 2021-04-16 21:53 **/ public class MapperProxy implements InvocationHandler { //map的key是全限定类名加方法名 private Map<String, Mapper> mappers; private Connection coon; public MapperProxy(Map<String,Mapper> mappers,Connection coon){ this.mappers = mappers; this.coon = coon; } /** * 用于对方法进行增强,我们的增强其实是调用selectList方法 * @param proxy * @param method * @param args * @return * @throws Throwable */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //获取方法名 String methodName =method.getName(); //获取类名 String className = method.getDeclaringClass().getName(); //组合key String key = className+"."+methodName; //获取mappers中的mapper对象 Mapper mapper = mappers.get(key); if (mapper==null){ throw new IllegalArgumentException("传入参数有误"); } //调用工具类查询所有 return new Executor().selectList(mapper,coon); } } <file_sep>package com.itheima.dao; import com.itheima.domain.QueryVo; import com.itheima.domain.User; import java.util.List; /** * @program: day02_eesy_01mybatisCRUD * @description * @author: 晏宝辉 * @create: 2021-04-17 13:12 **/ public interface IUserDao { List<User> findAll(); User queryUserById(Integer userId); List<User> queryByName(String username); /** * 根据QueryVo中的条件查询用户 * @param vo * @return */ List<User> findUserByVo(QueryVo vo); /** * 根据传入的参数条件查询 * @param user 查询的条件,有可能是用户名,有可能是性别,也有可能是地址,还有可能都没有 * @return */ List<User> findUserByCondition(User user); List<User> findUserInIds(QueryVo vo); } <file_sep>package com.itheima.mybatis.sqlsession; /** * @program: day01_eesy_04mybatis_design * @description * @author: 晏宝辉 * @create: 2021-04-16 21:11 **/ public interface SqlSession { /** * 根据参数创建一个代理对象 * @param daoInterfaceClass dao的接口字节码 * @param <T> * @return */ <T> T getMapper(Class<T> daoInterfaceClass); /** * 释放资源 */ void close(); } <file_sep>package com.itheima.test; import com.itheima.dao.IUserDao; import com.itheima.domain.QueryVo; import com.itheima.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @program: day02_eesy_01mybatisCRUD * @description * @author: 晏宝辉 * @create: 2021-04-17 13:16 **/ public class MybatisTest { private InputStream in; private SqlSession sqlSession; private IUserDao userDao; @Before public void init() throws Exception{ in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); sqlSession = sqlSessionFactory.openSession(); userDao = sqlSession.getMapper(IUserDao.class); } @After public void destroy() throws Exception{ //提交事务 sqlSession.commit(); sqlSession.close(); in.close(); } @Test public void testFindAll(){ List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user); } } @Test public void testQueryUserById(){ User user = userDao.queryUserById(53); System.out.println(user); } @Test public void testQueryByName(){ List<User> users = userDao.queryByName("%my%"); // List<User> users = userDao.queryByName("my"); for (User user : users) { System.out.println(user); } } @Test public void testFindUserByVo(){ QueryVo vo = new QueryVo(); User user = new User(); user.setUsername("%my%"); vo.setUser(user); List<User> users = userDao.findUserByVo(vo); for (User user1 : users) { System.out.println(user1); } } @Test public void testFindUserByCondition(){ User user = new User(); user.setUsername("last_insert"); user.setSex("男"); List<User> users = userDao.findUserByCondition(user); for (User u : users) { System.out.println(u); } } @Test public void testFindUserInIds(){ QueryVo vo = new QueryVo(); List<Integer> list = new ArrayList<>(); list.add(42); list.add(43); list.add(45); vo.setIds(list); List<User> users = userDao.findUserInIds(vo); for (User user : users) { System.out.println(user); } } }
ef181a2192903e8f105b17999e6ac4973303e0c3
[ "Java" ]
4
Java
yanbaohui/mybatis
69d265229c28dd33e42c7dbbea3b1909b6319ee1
18434f6e8f30232bc16ffd6efd813a691af5b13b
refs/heads/master
<repo_name>changhyeon743/rush<file_sep>/rush/EndingScene.h #pragma once class EndingScene { public: EndingScene(); ~EndingScene(); void PrintEnding(); }; <file_sep>/rush/MainScene.h #pragma once #include "GameScene.h" //게임씬 클래스 사용 #include "EndingScene.h" class MainScene { public: MainScene(); ~MainScene(); GameScene game; //게임 장면 구조체 EndingScene endig; void PrintTitle(); //타이틀 출력 void SelectCharacter(); //플레이어 기호 입력 }; <file_sep>/rush/GameScene.h #pragma once #include "Player.h" //Player 클래스 사용 #include "Maps.h" class GameScene { public: Player* player; //플레이어1 int current; //빈공간 채운 수 GameScene(); ~GameScene(); void PrintLine(); //맵 그리는 함수 void CountDown(); //제한 횟수 void PlayGame(); //게임 시작 void Ending(); //엔딩 void DrawMap(); }; <file_sep>/rush/Maps.cpp #include "ConsoleFunctions.h" #include "Maps.h" #include "Player.h" #include "Point.h" Maps::Maps() { currentLevel = 0; goal = 0; current = 0; }; Maps::~Maps() {}; char Maps::maps[maxLevel][ size ][ size ] = { { { "111111111" }, { "1p0000011" }, { "111011011" }, { "100011001" }, { "100000001" }, { "100011111" }, { "100011001" }, { "110000001" }, { "111111111" }, }, { { "111111111" }, { "10p011111" }, { "101011011" }, { "100011001" }, { "100000001" }, { "100011101" }, { "100011001" }, { "110000011" }, { "111111111" }, }, { { "111111111" }, { "100000001" }, { "101011101" }, { "101000001" }, { "101010101" }, { "100000101" }, { "101110101" }, { "1000001p1" }, { "111111111" }, } }; Maps* Maps::instance = nullptr; Maps* Maps::GetInstance() { if (instance == nullptr) instance = new Maps(); return instance; } void Maps::PurgeInstance() { delete instance; instance = nullptr; } Point Maps::GetPlayerLoc() { int h, w; for (h = 0; h < size-1; h++) { for (w = 0; w < size-1; w++) { if (maps[currentLevel][h][w] == 'p') { return Point(w, h); } } printf("\n"); } return Point(1, 1); } void Maps::Color(int x, int y) { if (currentMap[y][x] != '2') { currentMap[y][x] = '2'; current++; gotoxy(18, 3); std::cout << current << " / " << goal; } } void Maps::DrawLevel() { system("cls"); int h, w; for (h = 0; h < size-1; h++) { for (w = 0; w < size-1; w++) { currentMap[h][w] = maps[currentLevel][h][w]; char element = currentMap[h][w]; if (element == '1') { setBackgroundColor(ColorLightWhite); std::cout << ' '; setBackgroundColor(ColorBlack); } else { goal++; std::cout << ' '; } } printf("\n"); } } void Maps::LevelUp() { currentLevel++; goal = 0; current = 0; } char Maps::GetChar(int x, int y) { return currentMap[y][x]; } <file_sep>/rush/MainScene.cpp #include "MainScene.h" #include "ConsoleFunctions.h" using namespace std; MainScene::MainScene() { } MainScene::~MainScene() { } void MainScene::PrintTitle() { system("cls"); gotoxy(3, 2); cout << "RUSH"; //타이틀 출력 gotoxy(3, 5); cout << "Press any key to start" << endl; _getch(); system("cls"); } <file_sep>/rush/Player.cpp #include "Player.h" #include "ConsoleFunctions.h" #include "Maps.h" #include <iostream> Player::Player(int x,int y) { this->x = x; this->y = y; this->icon = 'O'; } Player::~Player() { } void Player::Draw(char c){ gotoxy(x, y); if (c == this->icon) { std::cout << c; } else if (c=='2'){ setBackgroundColor(ColorLightSkyblue); std::cout << ' '; setBackgroundColor(ColorBlack); } setTextColor(ColorWhite); } void Player::Action(int to) { Point havetoGo = Go(to); int oldX = x; int oldY = y; Move(havetoGo.x, havetoGo.y); if (havetoGo.x == oldX && havetoGo.y == oldY) //더 이상 못감 return; Sleep(200); Action(to); } Point Player::Go(int to) { int newX = x; int newY = y; switch (to) { case UP: newY--; break; case LEFT: newX--; break; case RIGHT: newX++; break; case DOWN: newY++; break; default: break; } //벽이 아닐 경우 if (Maps::GetInstance()->GetChar(newX, newY) != '1') { //Sleep(1000); return Point(newX, newY); } else { return Point(x, y); } } void Player::Move(int x,int y) { Draw(Maps::GetInstance()->GetChar(this->x,this->y)); this->x = x; this->y = y; Draw(icon); Maps::GetInstance()->Color(x, y); //Sleep(1000); //Move(to); } <file_sep>/rush/EndingScene.cpp #include "EndingScene.h" #include "ConsoleFunctions.h" #include <iostream> using namespace std; EndingScene::EndingScene() { } EndingScene::~EndingScene() { } void EndingScene::PrintEnding() { system("cls"); gotoxy(0, 2); cout << "##### ##### " << endl; cout << "# # # #" << endl; cout << "# # " << endl; cout << "# #### # ####" << endl; cout << "# # # # " << endl; cout << "# # # # " << endl; cout << "##### #####" << endl; cout << endl; cout << "Press any key to exit" << endl; _getch(); system("cls"); }<file_sep>/rush/main.cpp #include <iostream> #include "MainScene.h" int main() { MainScene mainScene; mainScene.PrintTitle(); mainScene.game.DrawMap(); mainScene.game.PlayGame(); mainScene.endig.PrintEnding(); return 0; }<file_sep>/rush/Player.h #pragma once #include "Point.h" class Player { public: int x; int y; char icon; Player(int x,int y); ~Player(); void Move(int x,int y); //움직이는 함수 void Draw(char c); //현재 위치에 플레이어 출력 void Action(int to); //재귀를 위한 액션 Point Go(int to); //어디로 가야할지 알려주는 함수 }; <file_sep>/rush/Ending.h #pragma once class Ending { public: Ending(); ~Ending(); }; <file_sep>/rush/Maps.h #pragma once #include "Point.h" const static int size = 10; const static int maxLevel = 3; class Maps { private: Maps(); ~Maps(); static char maps[maxLevel][ size ][ size ]; static Maps* instance; public: int currentLevel; int goal; int current; char currentMap[size][size]; static Maps* GetInstance(); static void PurgeInstance(); Point GetPlayerLoc(); void DrawLevel(); void LevelUp(); char GetChar(int x, int y); void Color(int x, int y); };<file_sep>/rush/GameScene.cpp #include "GameScene.h" #include "ConsoleFunctions.h" #include "Maps.h" #include "Point.h" GameScene::GameScene() { } GameScene::~GameScene() { delete player; } void GameScene::PlayGame() { player->Draw(player->icon); while(true) { if (Maps::GetInstance()->currentLevel >= maxLevel) return; if (Maps::GetInstance()->current >= Maps::GetInstance()->goal) { Maps::GetInstance()->LevelUp(); DrawMap(); } if (_kbhit()) { int key = _getch(); player->Action(key); } } } void GameScene::DrawMap() { system("cls"); Point point = Maps::GetInstance()->GetPlayerLoc(); player = new Player(point.x, point.y); Maps::GetInstance()->DrawLevel(); //maps->DrawLevel(); }
da7efda975f299584c3775757e577a50b5f8f98c
[ "C++" ]
12
C++
changhyeon743/rush
3a988941f2c5adc691f583904d01b5d56797780f
3b2d6b739376006262ebb88a16dc15f018a20eae
refs/heads/master
<file_sep>#include<iostream> #include <sys/time.h> #include <string.h> #include <map> #include <string> #include <vector> #include <sstream> #include <stdio.h> #include <stdlib.h> #include "globalfunction.h" using namespace std; class FileSeg{ public: FileSeg(int clientId,int fileId,int segId){ mFileId = fileId; mSegId = segId; mClientId = clientId; } int mClientId; int mFileId; int mSegId; }; vector<FileSeg> sequenceList; void clientOptStrategy(int clientNum,int blockNum){ unsigned int hitTimes =0,totalRequest=0; map<int ,vector<FileSeg> > buf; int curFileId,curSegId,curClient; for(unsigned int i=0;i<sequenceList.size();i++){ curFileId = sequenceList[i].mFileId; curSegId = sequenceList[i].mSegId; curClient = sequenceList[i].mClientId; if(curFileId > 10) continue; totalRequest++; //in the buf bool isHit = false; for(size_t j=0;j<buf[curClient].size();j++){ if(buf[curClient][j].mSegId == curSegId){ isHit = true; break; } } if(isHit == true){ hitTimes ++; continue; } //not in the buf if(buf[curClient].size()< blockNum){//just push in buf[curClient].push_back(sequenceList[i]); }else{//eliminate vector<int> dis(blockNum); for(int j=0;j<dis.size();j++){ dis[j]=sequenceList.size(); } int max= 0; int targetIndex; for(size_t j=0;j<buf[curClient].size();j++){ for(size_t k = i+1;k<sequenceList.size();k++){ if( sequenceList[k].mFileId == buf[curClient][j].mFileId && sequenceList[k].mSegId == buf[curClient][j].mSegId){ dis[j]=k; break; } } } //chose the max k for(size_t j=0;j<dis.size();j++){ if(dis[j] > max){ max = dis[j]; targetIndex = j; } } buf[curClient].erase(buf[curClient].begin()+targetIndex); buf[curClient].push_back(sequenceList[i]); } } cout<<hitTimes<<" "<<totalRequest<<endl; } void serverOptStrategy(int blockNum){ int curFileId,curSegId,hitTimes,totalRequest; vector<FileSeg> buf; hitTimes=0; totalRequest = 0; for(unsigned int i=0;i<sequenceList.size();i++){ curFileId = sequenceList[i].mFileId; curSegId = sequenceList[i].mSegId; totalRequest++; //in the buf bool isHit = false; for(size_t j=0;j<buf.size();j++){ if(buf[j].mSegId == curSegId && buf[j].mFileId == curFileId){ isHit = true; break; } } if(isHit == true){ hitTimes ++; continue; } //not in the buf if(buf.size()< blockNum){//just push in buf.push_back(sequenceList[i]); }else{//eliminate vector<int> dis(blockNum); for(int j=0;j<dis.size();j++){ dis[j]=sequenceList.size(); } int max= 0; int targetIndex; for(size_t j=0;j<buf.size();j++){ for(size_t k = i+1;k<sequenceList.size();k++){ if( sequenceList[k].mFileId == buf[j].mFileId && sequenceList[k].mSegId == buf[j].mSegId){ dis[j]=k; break; } } } //chose the max k for(size_t j=0;j<dis.size();j++){ if(dis[j] > max){ max = dis[j]; targetIndex = j; } } buf.erase(buf.begin()+targetIndex); buf.push_back(sequenceList[i]); } } cout<<hitTimes<<" "<<totalRequest<<endl; } int main(int argc,char *argv[]){ if(argc !=2){ cout<<"input error"<<endl; exit(1); } std::map<std::string,std::string> keyMap; char *configFileName = "./config/simulator.cfg"; ParseConfigFile(configFileName,keyMap); int blockNums,serverBlockNums; int clientNums; bool isP2POpen; blockNums = atoi(keyMap["BlockNums"].c_str()); isP2POpen = !strcmp(keyMap["isP2POpen"].c_str(),"true") ? true : false; serverBlockNums = atoi(keyMap["ServerBlockNums"].c_str()); clientNums = atoi(keyMap["ClientNums"].c_str()); //init the sequenceList sequenceList.clear(); ifstream ifs(argv[1]); int a,b,c,d,e,f,g; while(!ifs.eof()){ ifs >>a>>b>>c>>d>>e>>f>>g; if(ifs.fail()) break; if(b>10 && isP2POpen== true) continue; FileSeg newSeg(a,b,c); sequenceList.push_back(newSeg); } ifs.close(); cout<<"p2p is "; if(isP2POpen == true){ cout<<"open"<<endl; clientOptStrategy(clientNums,blockNums); }else{ cout<<"not open"<<endl; serverOptStrategy(serverBlockNums); } return 0; } <file_sep>#ifndef BUFMANAGERBYLRFU_H #define BUFMANAGERBYLRFU_H #include "dbuffer.h" #include <sys/time.h> typedef struct lrfuBlockInfo{ unsigned int fileId; unsigned int segId; float weight; int lastTime; float lastWeight; }lrfuBlockInfo; class DBufferLRFU: public DBuffer{ public: DBufferLRFU(int blockSize,int blockNums,float lambda); virtual ~DBufferLRFU(); virtual bool Read(int fileId,int segId); virtual void Write(int fileId,int segId,int &ofileId,int &osegId); virtual void Strategy(int fileId,int segId,int &ofileId,int &osegId); virtual bool FindBlock(int fileId,int segId); int AddBlock(int fileId,int segId); virtual void BlockReset(){} private: // struct timeval tv; list<lrfuBlockInfo> lrfuBuf; int initial_parameter(); float _lambda; // int mBlockSize; // int mBlockNums; unsigned int timeslot; }; #endif <file_sep>/* * myheap.cpp * * Created on: 2013-2-19 * Author: zhaojun */ #include "myheap.h" template <class T,class BinaryOperation> Myheap<T,BinaryOperation>::Myheap(){ m_vect.clear(); } template <class T,class BinaryOperation> void Myheap<T,BinaryOperation>::PushHeap(T t){ m_vect.push_back(t); // cout << "~~~~~~~~~~~" << endl; _AdjustHeap(BinaryOperation()); } template <class T,class BinaryOperation> T &Myheap<T,BinaryOperation>::PopHeap(int tag){ T t = m_vect[tag]; m_vect[tag] = m_vect[m_vect.size() - 1]; m_vect[m_vect.size() - 1] = t; m_vect.pop_back(); //_AdjustHeap(BinaryOperation<T>()); return t; } template <class T,class BinaryOperation> void Myheap<T,BinaryOperation>::AdjustHeap(){ _AdjustHeap(BinaryOperation()); } template <class T,class BinaryOperation> void Myheap<T,BinaryOperation>::_AdjustHeap(BinaryOperation binary_op){ for(int i = (m_vect.size() - 1);i > 0;i--){ int fatherTag = (i - 1) / 2; // cout << "........." << i << " " << m_vect[i].leftTime << " " << fatherTag // << " " << m_vect[fatherTag].leftTime << endl; if(binary_op(m_vect[i],m_vect[fatherTag])){ T t = m_vect[i]; m_vect[i] = m_vect[fatherTag]; m_vect[fatherTag] = t; // cout << i << " " << m_vect[i].leftTime << " " << fatherTag // << " " << m_vect[fatherTag].leftTime << endl; } } } template <class T,class BinaryOperation> T &Myheap<T,BinaryOperation>::GetElement(int tag){ return m_vect[tag]; } <file_sep>#ifndef __GLOBAL_FUNCTION_H__ #define __GLOBAL_FUNCTION_H__ #include <fstream> #include <string> #include <iostream> #include <map> #include <sys/time.h> #include <stdlib.h> #define UNUSED(a) if(a){} void Trim(std::string &s); void ParseConfigFile(char *configFileName,std::map<std::string,std::string> &keyMap); int RandomI(int first,int second); double RandomF(int a,int b); long int getTimeInterval(struct timeval *a,struct timeval *b); #endif <file_sep>#ifndef __LOG_H__ #define __LOG_H__ #include <iostream> #include <sys/time.h> using namespace std; #define MY_LOG_UNCOND 0 #define MY_LOG_INFO 1 #define MY_LOG_ERR 2 #ifndef CUR_LOG_LEVEL #define CUR_LOG_LEVEL 0 #endif #define LOG(level,msg) #define LOG_INFO(msg) #define LOG_DISK(ofs,msg) #define LOG_ERR(msg) LOG(2,msg) #endif <file_sep>/* * myserver.cpp * * Created on: 2013-2-20 * Author: zhaojun */ #include "myserver.h" #include "log.h" #include <netinet/in.h> #include <arpa/inet.h> #include <memory.h> #include <stdlib.h> #include <sstream> void *ThreadToServer(void *arg){ MyServer *server = (MyServer *)arg; server->Run(); return NULL; } void *ThreadToSearch(void *arg){ MyServer *server = (MyServer *)arg; server->ReadFromDevice(); return NULL; } MyServer::MyServer(double bandWidth,int blockSize,int blockNums,string cacheAlgorithm ,int period,double lrfuLambda,int perSendSize,bool isP2POpen, int fileNum,int maxLength,int minLength,double minbitRate,double maxBitRate, int serverPort,int clientPort,int devNums,int clientNums, char **clusterAddress,int takeSampleFre,bool isUseRealDevice){ mBand = bandWidth; mBlockSize = blockSize / 1000; //add by sunpy mBlockNum = blockNums; mBufStrategy = cacheAlgorithm; mPeriod = period; mLrfuLambda = lrfuLambda; //add end mPerSendSize = perSendSize; mIsP2POpen = isP2POpen; mMaxBandSize = (mBand / 8.0) * 1000 * 4; mUsedBandSize = 0; mNeedSendBandSize = 0; mLinkedNums = 0; mNeverShow = false; mIsUseRealDevice = isUseRealDevice; mCurReqBlock = mReqList.end(); mReqList.clear(); mPreReqList.clear(); mFileNum = fileNum; mMinLength = minLength; mMaxLength = maxLength; mMinBitRate = minbitRate; mMaxBitRate = maxBitRate; mDataServer = new DataServer(mFileNum,mMinLength,mMaxLength,blockSize,mMinBitRate,mMaxBitRate); mTakeSampleFre = takeSampleFre; mDevNums = devNums; mClientNums = clientNums; mServerPort = serverPort; mClientPort = clientPort; for(int i = 0;i < devNums;i++){ mClusterAddress[i] = clusterAddress[i]; } for(int i = 0;i <= MAX_CLIENT_NUM;i++){ // mClientInfo[i].listenFd = -1; mClientInfo[i].recvFd = -1; // mClientLinks[i] = 0; } LOG_INFO(""); LOG_INFO("Server Config"); LOG_INFO("BandWidth = " << mBand); LOG_INFO("BlockSize = " << mBlockSize); LOG_INFO("PerSendSize = " << mPerSendSize); LOG_INFO("IsP2POpen = " << (mIsP2POpen ? "true" : "false")); LOG_INFO("FileNums = " << mFileNum); LOG_INFO("MinLength = " << mMinLength); LOG_INFO("MaxLength = " << mMaxLength); LOG_INFO("MinBitRate = " << mMinBitRate); LOG_INFO("MaxBitRate = " << mMaxBitRate); LOG_INFO("ServerPort = " << mServerPort); LOG_INFO("DevNums = " << mDevNums); LOG_INFO("BlockNum = "<< mBlockNum); LOG_INFO("Buffer strategy = "<<mBufStrategy); LOG_INFO("Period = "<<mPeriod); LOG_INFO("LrfuLambda ="<< mLrfuLambda); for(int i = 0;i < devNums;i++){ LOG_INFO("Cluster " << i << " address is:" << mClusterAddress[i]); } Init(); mOFs.open("data/result.log",ios::out); //add by sunpy @0518 initServerBuf(); //add end; pthread_create(&mtid,NULL,ThreadToServer,this); pthread_create(&mRtid,NULL,ThreadToSearch,this); } void MyServer::initServerBuf(){ sequenceOfs.open("data/sequence.log",ios_base::out); mTotalRequest = mReadFromServer= mReadFromBuf = mReadFromDisk=0; for(size_t i=1;i<=mClientNums;i++){ connectStatus[i] =false;//is not connect } if(mBufStrategy == "LRU"){ mDbuffer = new DBufferLRU(mBlockSize,mBlockNum); } else if(mBufStrategy == "DW"){ mDbuffer = new DBufferDW(mBlockSize,mBlockNum,mPeriod); } else if(mBufStrategy == "DWS"){ mDbuffer = new DBufferDWS(mBlockSize,mBlockNum,mPeriod); } else if(mBufStrategy =="LFRU"){ mDbuffer = new DBufferLFRU(mBlockSize,mBlockNum,mPeriod); } else if(mBufStrategy =="PR"){ mDbuffer = new DBufferPR(mBlockSize,mBlockNum); } else if(mBufStrategy =="LFU"){ mDbuffer = new DBufferLFU(mBlockSize,mBlockNum); } else if(mBufStrategy =="LFUS"){ mDbuffer = new DBufferLFUS(mBlockSize,mBlockNum); } else if(mBufStrategy =="LRUS"){ mDbuffer = new DBufferLRUS(mBlockSize,mBlockNum); } else if(mBufStrategy=="LRFU"){ mDbuffer = new DBufferLRFU(mBlockSize,mBlockNum,mLrfuLambda); } else if(mBufStrategy=="FIFO"){ mDbuffer = new DBufferFIFO(mBlockSize,mBlockNum); } if(mDbuffer->IsBlockReset()){ TimerEvent timeEvent; timeEvent.isNew = true; timeEvent.sockfd = mBufferResetFd[1]; timeEvent.leftTime = mPeriod * 1000000; globalTimer.RegisterTimer(timeEvent); // LOG_WRITE("",mRecordFs); LOG_INFO("server has blockreset reset period:" << mPeriod); //BufferReset(); } } void MyServer::BufferReset(){ TimerEvent timeEvent; timeEvent.isNew = true; timeEvent.sockfd = mBufferResetFd[1]; timeEvent.leftTime = mPeriod * 1000000; globalTimer.RegisterTimer(timeEvent); mDbuffer->BlockReset(); } //add end @sunpy 0518 MyServer::~MyServer(){ delete mDataServer; mCurReqBlock = mReqList.end(); for(int i = 0;i <= MAX_CLIENT_NUM;i++){ if(mClientInfo[i].recvFd != -1){ // close(mClientInfo[i].listenFd); close(mClientInfo[i].recvFd); } } mReqList.clear(); mPreReqList.clear(); close(mNetSockFd); close(mEpollFd); mOFs.close(); for(int i = 1;i < mClientNums;i++){ mClientDelayOfs[i].close(); } // close(mListenSockFd[0]); // close(mListenSockFd[1]); } void MyServer::Init(){ mEpollFd = epoll_create(MAX_LISTEN_NUM); mREpollFd = epoll_create(MAX_LISTEN_NUM); epoll_event ev; mNetSockFd = socket(AF_INET,SOCK_STREAM,0); socketpair(AF_UNIX,SOCK_STREAM,0,mTakeSample); socketpair(AF_UNIX,SOCK_STREAM,0,mReadDevice); ev.data.fd = mReadDevice[0]; ev.events = EPOLLIN; epoll_ctl(mREpollFd,EPOLL_CTL_ADD,mReadDevice[0],&ev); ev.data.fd = mReadDevice[1]; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mReadDevice[1],&ev); ev.data.fd = mTakeSample[0]; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mTakeSample[0],&ev); ev.data.fd = mNetSockFd; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mNetSockFd,&ev); ev.data.fd = mFakeTran.GetFd(); ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mFakeTran.GetFd(),&ev); //add by sunpy@0518 socketpair(AF_UNIX,SOCK_STREAM,0,mBufferResetFd); ev.data.fd = mBufferResetFd[0]; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mBufferResetFd[0],&ev); //add end; struct sockaddr_in serverAddr; bzero(&serverAddr,sizeof(serverAddr)); serverAddr.sin_addr.s_addr = INADDR_ANY; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(mServerPort); int val = 1; setsockopt(mNetSockFd,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(val)); if(bind(mNetSockFd,(struct sockaddr *)&serverAddr,sizeof(struct sockaddr)) == -1){ LOG_INFO("Server Bind Error!"); exit(1); } if(listen(mNetSockFd,20) == -1){ LOG_INFO("Server Listen Error!"); exit(1); } LOG_INFO("before"); stringstream sstream; for(int i = 1;i <= mClientNums;i++){ sstream.str(""); sstream << "data/clientdelay" << i << ".log"; string fileName = sstream.str(); mClientDelayOfs[i].open(fileName.c_str(),ios::out); } LOG_INFO("after"); } //int MyServer::JudgeCluster(char *address){ // for(int i = 0;i < mDevNums;i++){ // if(strcmp(address,mClusterAddress[i]) == 0) // return i; // } // return -1; //} void MyServer::ReadFromDevice(){ epoll_event events[MAX_LISTEN_NUM]; while(true){ int nfds = epoll_wait(mREpollFd,events,MAX_LISTEN_NUM,-1); for(int i = 0;i < nfds;i++){ if(events[i].data.fd == mReadDevice[0]){ char buffer[20]; read(events[i].data.fd,buffer,20); int *ptr = (int *)buffer; int type = *ptr; ptr++; switch(type){ case MSG_SEARCH_DEVICE:{ int clientNum = *ptr; ptr++; int fileId = *ptr; ptr++; int segId = *ptr; double bitRate; int segNum; bool isOut = false; if(!mIsUseRealDevice){ mDataServer->GetFileInfo(fileId,&bitRate,&segNum); } else{ //add by sunpy @0518 mDataServer->GetFileInfo(fileId,&bitRate,&segNum); //Nothing if(true ==mDbuffer->Read(fileId,segId)){//read from buf mReadFromBuf++; LOG_INFO(" SERVERBUF read <"<<fileId<<","<<segId<<"> in buf"); }else{//read from disk mReadFromDisk++; int oFileId,oSegId; mDbuffer->Write(fileId,segId,oFileId,oSegId); LOG_INFO(" SERVERBUF eliminate <"<<oFileId<<","<<oSegId<<"> in disk"); LOG_INFO(" SERVERBUF add <"<<fileId<<","<<segId<<"> to buf"); } //add end } if(segId > segNum){ isOut = true; } ptr = (int *)buffer; *ptr = MSG_SEARCH_DEVICE; ptr++; *ptr = clientNum; ptr++; bool *boolPtr = (bool *)ptr; *boolPtr = isOut; boolPtr++; char *chPtr = (char *)boolPtr; *chPtr = (segNum >> 16) & 0xFF; chPtr++; *chPtr = (segNum >> 8) & 0xFF; chPtr++; *chPtr = segNum & 0xFF; chPtr++; double *dbPtr = (double *)chPtr; *dbPtr = bitRate; send(mReadDevice[0],buffer,20,0); break; } } } } } } void MyServer::TakeSample(){ // LOG_INFO(""); // LOG_INFO("server need to send " << mNeedSendBandSize); LOG_DISK(mOFs,mNeedSendBandSize); TimerEvent event; event.isNew = true; event.sockfd = mTakeSample[1]; event.leftTime = mTakeSampleFre * 1000000; globalTimer.RegisterTimer(event); } void MyServer::Run(){ // LOG_INFO("server all fd:" << mListenSockFd[0] << "," << mListenSockFd[1]); TimerEvent timerEvent; timerEvent.isNew = true; timerEvent.sockfd = mTakeSample[1]; timerEvent.leftTime = mTakeSampleFre * 1000000; globalTimer.RegisterTimer(timerEvent); epoll_event events[MAX_LISTEN_NUM]; while(true){ int fds = epoll_wait(mEpollFd,events,MAX_LISTEN_NUM,-1); for(int i = 0;i < fds;i++){ if(events[i].events == EPOLLIN){ if(events[i].data.fd == mFakeTran.GetFd()){ char buffer[20]; read(mFakeTran.GetFd(),buffer,20); // int *ptr = (int *)buffer; // *ptr = MSG_FAKE_FIN; DealWithMessage(buffer,20); } else if(events[i].data.fd == mTakeSample[0]){ char buffer[20]; read(mTakeSample[0],buffer,20); TakeSample(); } //add by sunpy @0518 else if(events[i].data.fd == mBufferResetFd[0]){ char buffer[20]; int length = recv(events[i].data.fd,buffer,20,0); BufferReset(); LOG_INFO("server reset buffer"); }//add end @0518 else if(events[i].data.fd == mNetSockFd){ struct sockaddr_in clientAddr; unsigned int length; bzero(&clientAddr,sizeof(struct sockaddr_in)); length = sizeof(clientAddr); int clientFd = accept(mNetSockFd,(struct sockaddr *)(&clientAddr),&length); epoll_event ev; bzero(&ev,sizeof(ev)); ev.data.fd = clientFd; ev.events = EPOLLIN; char buffer[20]; recv(clientFd,buffer,20,0); int *ptr = (int *)buffer; int clientNum = *ptr; int port = mClientPort + ((clientNum - 1) % (mClientNums / mDevNums)); mClientInfo[clientNum].address.sin_addr = clientAddr.sin_addr; mClientInfo[clientNum].address.sin_port = htons(port); mClientInfo[clientNum].recvFd = clientFd; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,clientFd,&ev); // char buffer[20]; mLinkedNums++; LOG_INFO(""); LOG_INFO("server response MSG_CONNECT_FIN to " << clientNum << " fd is:" << clientFd); ptr = (int *)buffer; *ptr = MSG_CONNECT_FIN; ptr++; *ptr = 0; ptr++; *ptr = 19; send(clientFd,buffer,20,0); // } } else{ char buffer[20]; int length = recv(events[i].data.fd,buffer,20,0); // LOG_INFO("server recv message length:" << length); DealWithMessage(buffer,length); } } } } } list<ClientReqBlock>::iterator MyServer::SearchTheReqList(int fileId,int segId){ list<ClientReqBlock>::iterator reqIter = mReqList.begin(); while(reqIter != mReqList.end()){ if(reqIter->fileId == fileId && reqIter->segId == segId) return reqIter; reqIter++; } return reqIter; } void MyServer::writeRequestSequence(int clientNum,int fileId,int segId){ sequenceOfs<<clientNum<<" "<<fileId<<" "<<segId<<" "<<mTotalRequest<<" "<<mReadFromServer<<" "<<mReadFromBuf<<" "<<mReadFromDisk<<endl; LOG_INFO("server receive MSG_SEG_ASK from "<<clientNum<<" and request <"<<fileId<<","<<segId<<">"); } void MyServer::DealWithMessage(char *buf,int length){ int *ptr = (int *)buf; int type = *ptr; ptr++; switch(type){ case MSG_CLIENT_JOIN:{ int clientNum = *ptr; char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_JOIN_ACK; tmpPtr++; *tmpPtr = 0; LOG_INFO(""); LOG_INFO("server receive MSG_CLIENT_JOIN from " << clientNum << " and response MSG_JOIN_ACK"); send(mClientInfo[clientNum].recvFd,buffer,20,0); break; } case MSG_CLIENT_LEAVE:{ int clientNum = *ptr; epoll_event ev; ev.data.fd = mClientInfo[clientNum].recvFd; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_DEL,mClientInfo[clientNum].recvFd,&ev); close(mClientInfo[clientNum].recvFd); mClientInfo[clientNum].recvFd = -1; // mClientInfo[clientNum].listenFd = -1; LOG_INFO(""); LOG_INFO("server receive MSG_CLIENT_LEAVE from " << clientNum << " and remove the fd from epoll"); break; } case MSG_SEARCH_DEVICE:{ int clientNum = *ptr; ptr++; bool *boolPtr = (bool *)ptr; bool isOut = *boolPtr; boolPtr++; char chValue = *((char *)boolPtr); int segNum = (0x00FF0000 & (chValue << 16)); boolPtr++; chValue = *((char *)boolPtr); segNum = (segNum | ((chValue << 8) & 0x0000FF00)); boolPtr++; chValue = *((char *)boolPtr); boolPtr++; segNum = (segNum | (chValue & 0xFF)); double *dbPtr = (double *)boolPtr; double bitRate = *dbPtr; if(isOut){ char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_BAD_REQ; tmpPtr++; *tmpPtr = 0; send(mClientInfo[clientNum].recvFd,buffer,20,0); LOG_INFO(""); LOG_INFO("server receive MSG_SEG_ASK from " << clientNum << "and response MSG_BAD_REQ"); break; } //否则提供 char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_SEG_ACK; tmpPtr++; *tmpPtr = 0; tmpPtr++; *tmpPtr = segNum; tmpPtr++; dbPtr = (double *)tmpPtr; *dbPtr = bitRate; send(mClientInfo[clientNum].recvFd,buffer,20,0); LOG_INFO(""); LOG_INFO("server receive MSG_SEARCH_DEVICE from " << clientNum << " and response MSG_SEG_ACK segNum:" << segNum); break; } case MSG_SEG_ASK:{ int clientNum = *ptr; ptr++; int fileId = *ptr; ptr++; int segId = *ptr; double bitRate; int segNum; //add by sunpy @0518 writeRequestSequence(clientNum,fileId,segId); if(connectStatus[clientNum]== false &&( mBufStrategy== "DWS"||mBufStrategy =="LFUS" ||mBufStrategy=="LRUS") ){ connectStatus[clientNum]=true; mDbuffer->addNewClient(clientNum,fileId); mDbuffer->getInLine(clientNum); LOG_INFO("cache algorithm is "<<mBufStrategy<<",add new client "<<clientNum<<",it will visit file "<<fileId); } //add end // mDataServer->GetFileInfo(fileId,&bitRate,&segNum); //添加bitrate和最大段数 // if(segId > segNum){ // char buffer[20]; // int *tmpPtr = (int *)buffer; // *tmpPtr = MSG_BAD_REQ; // tmpPtr++; // *tmpPtr = 0; // send(mClientInfo[clientNum].recvFd,buffer,20,0); // LOG_INFO(""); // LOG_INFO("server receive MSG_SEG_ASK from " << clientNum << // "and response MSG_BAD_REQ"); // break; // } // // add by sunpy @518 mTotalRequest ++; //add end if(mIsP2POpen){ int bestClient = mDataServer->SearchBestClient(fileId,segId); LOG_INFO("server find best client " << bestClient); if(bestClient != -1){ char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_REDIRECT; tmpPtr++; *tmpPtr = 0; tmpPtr++; *tmpPtr = bestClient; tmpPtr++; *tmpPtr = mClientInfo[bestClient].address.sin_addr.s_addr; tmpPtr++; *tmpPtr = mClientInfo[bestClient].address.sin_port; send(mClientInfo[clientNum].recvFd,buffer,20,0); LOG_INFO(""); LOG_INFO("server receive MSG_SEG_ASK from " << clientNum << " and response MSG_REDIRECT to " << bestClient); break; } } char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_SEARCH_DEVICE; tmpPtr++; *tmpPtr = clientNum; tmpPtr++; *tmpPtr = fileId; tmpPtr++; *tmpPtr = segId; //add by sunpy mReadFromServer++; //add end send(mReadDevice[1],buffer,20,0); LOG_INFO(""); LOG_INFO("server receive MSG_SEG_ASK from " << clientNum << " and start to search the device"); //否则提供 // char buffer[20]; // int *tmpPtr = (int *)buffer; // *tmpPtr = MSG_SEG_ACK; // tmpPtr++; // *tmpPtr = 0; // tmpPtr++; // *tmpPtr = segNum; // tmpPtr++; // double *dbPtr = (double *)tmpPtr; // *dbPtr = bitRate; // send(mClientInfo[clientNum].recvFd,buffer,20,0); // LOG_INFO(""); // LOG_INFO("server receive MSG_SEG_ASK from " << clientNum << // " and response MSG_SEG_ACK"); break; } case MSG_REQUEST_SEG:{ int clientNum = *ptr; ptr++; int fileId = *ptr; ptr++; int segId = *ptr; ClientReqBlock reqBlock; reqBlock.clientNum = clientNum; reqBlock.fileId = fileId; reqBlock.segId = segId; reqBlock.oper = OPER_WRITE; reqBlock.leftSize = mBlockSize * 1000; reqBlock.preOper = OPER_WRITE; reqBlock.localfin = NONE_FIN; mNeedSendBandSize += reqBlock.leftSize; mPreReqList.push_back(reqBlock); if(mUsedBandSize < mMaxBandSize){ ClientReqBlock tmpBlock = mPreReqList.front(); mPreReqList.pop_front(); mReqList.push_back(tmpBlock); mUsedBandSize += mBlockSize * 1000; } if(mUsedBandSize >= mMaxBandSize && !mNeverShow){ LOG_INFO("server reach its max serve ability,the num is " << mLinkedNums); mNeverShow = true; } LOG_INFO(""); LOG_INFO("server receive MSG_REQUEST_SEG from " << clientNum << " fileId:" << fileId << ",segId:" << segId << " and start simulator transport"); if(mCurReqBlock == mReqList.end()){ GetNextBlock(); mFakeTran.Active(); } break; } case MSG_DELETE_SEG:{ int clientNum = *ptr; ptr++; int fileId = *ptr; ptr++; int segId = *ptr; LOG_INFO(""); LOG_INFO("server receive MSG_DELETE_SEG from " << clientNum << " and delete the fileId:" << fileId << ",segId:" << segId << " from database"); mDataServer->DeleteFromIndex(fileId,segId,clientNum); break; } case MSG_ADD_SEG:{ int clientNum = *ptr; ptr++; int fileId = *ptr; ptr++; int segId = *ptr; ptr++; int linkedNum = *ptr; LOG_INFO(""); LOG_INFO("server receive MSG_ADD_SEG from " << clientNum << " and add the fileId:" << fileId << ",segId:" << segId << " into database"); // list<ClientReqBlock>::iterator iter = SearchTheReqList(fileId,segId); // if(iter != mReqList.end()){ // if(mCurReqBlock == iter) // mCurReqBlock++; // mReqList.erase(iter); // } // mClientLinks[clientNum]++; mDataServer->InsertIntoIndex(fileId,segId,clientNum,linkedNum); break; } case MSG_FAKE_FIN:{ int toClientNum = *ptr; ptr++; int oper = *ptr; bool isNativeProduce = false; // ptr++; // int segId = *ptr; // if(mCurReqBlock != mReqList.end()) // GetNextBlock(); list<ClientReqBlock>::iterator tmpIter = mReqList.begin(); while(oper == OPER_WRITE && tmpIter != mReqList.end()){ if(tmpIter->clientNum == toClientNum){ if(tmpIter->leftSize <= 0){ char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_SEG_FIN; tmpPtr++; *tmpPtr = 0; tmpPtr++; *tmpPtr = tmpIter->fileId; tmpPtr++; *tmpPtr = tmpIter->segId; send(mClientInfo[tmpIter->clientNum].recvFd,buffer,20,0); if(mCurReqBlock == tmpIter){ GetNextBlock(); isNativeProduce = true; } mReqList.erase(tmpIter); mUsedBandSize -= (mBlockSize * 1000); mNeedSendBandSize -= (mBlockSize * 1000); bool localTag = false; list<ClientReqBlock>::iterator preIter = mPreReqList.begin(); // list<ClientReqBlock>::iterator tmpIter; while(preIter != mPreReqList.end()){ bool tmpTag = false; if(mIsP2POpen){ int bestClient = mDataServer->SearchBestClient(preIter->fileId, preIter->segId); // LOG_INFO("server find best client " << bestClient); if(bestClient != -1){ // char buffer[20]; tmpPtr = (int *)buffer; *tmpPtr = MSG_REDIRECT; tmpPtr++; *tmpPtr = 0; tmpPtr++; *tmpPtr = bestClient; tmpPtr++; *tmpPtr = mClientInfo[bestClient].address.sin_addr.s_addr; tmpPtr++; *tmpPtr = mClientInfo[bestClient].address.sin_port; send(mClientInfo[preIter->clientNum].recvFd,buffer,20,0); LOG_INFO(""); LOG_INFO("server send MSG_REDIRECT to " << preIter->clientNum << " redirect to " << bestClient); mNeedSendBandSize -= (mBlockSize * 1000); tmpIter = preIter; preIter++; mPreReqList.erase(tmpIter); tmpTag = true; // break; } } if(!tmpTag){ tmpIter = mReqList.begin(); int count = 0; while(tmpIter != mReqList.end()){ if(preIter->fileId == tmpIter->fileId && preIter->segId == tmpIter->segId) count++; tmpIter++; } if(count < 3){ ClientReqBlock tmpReqBlock = *preIter; mReqList.push_back(tmpReqBlock); mPreReqList.erase(preIter); mUsedBandSize += (mBlockSize * 1000); break; } preIter++; } } if(!mPreReqList.empty() && preIter == mPreReqList.end()){ ClientReqBlock tmpReqBlock = mPreReqList.front(); mPreReqList.pop_front(); mReqList.push_back(tmpReqBlock); mUsedBandSize += (mBlockSize * 1000); } break; } if(tmpIter->localfin == REMOTE_FIN){ tmpIter->oper = tmpIter->preOper; tmpIter->localfin = NONE_FIN; } else{ tmpIter->localfin = LOCAL_FIN; } break; } tmpIter++; } if(mCurReqBlock != mReqList.end() && !isNativeProduce) GetNextBlock(); if(mCurReqBlock != mReqList.end() && mCurReqBlock->oper != OPER_WAIT){ mCurReqBlock->oper = OPER_WAIT; mFakeTran.TranData(mBand,mPerSendSize,mCurReqBlock->clientNum,mCurReqBlock->preOper); mCurReqBlock->localfin = NONE_FIN; char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_REMOTE_FAKE_FIN; tmpPtr++; *tmpPtr = 0;//服务器编号 tmpPtr++; *tmpPtr = mCurReqBlock->preOper == OPER_READ ? OPER_WRITE : OPER_READ; send(mClientInfo[mCurReqBlock->clientNum].recvFd,buffer,20,0); // LOG_INFO(""); // LOG_INFO("server send MSG_REMOTE_FAKE_FIN to " << mCurReqBlock->clientNum << // " leftsize:" << mCurReqBlock->leftSize << "," << mCurReqBlock->segId); // GetNextBlock(); } break; } case MSG_REMOTE_FAKE_FIN:{ int clientNum = *ptr; ptr++; list<ClientReqBlock>::iterator iter = mReqList.begin(); // list<ClientReqBlock>::iterator tmpIter = mReqList.begin(); bool isFound = false; while(iter != mReqList.end()){ if(iter->clientNum == clientNum){ iter->leftSize -= mPerSendSize; if(iter->localfin == LOCAL_FIN){ iter->oper = iter->preOper; iter->localfin = NONE_FIN; isFound = true; } else{ iter->localfin = REMOTE_FIN; isFound = false; } // LOG_INFO(""); // LOG_INFO("server receive MSG_REMOTE_FAKE_FIN from " << clientNum << // " leftsize:" << iter->leftSize << "," << iter->segId << ",localfin" << iter->localfin); // LOG_INFO("1"); if(iter->leftSize <= 0 && iter->localfin != REMOTE_FIN){ // mReqList.erase(iter); char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_SEG_FIN; tmpPtr++; *tmpPtr = 0; tmpPtr++; *tmpPtr = iter->fileId; tmpPtr++; *tmpPtr = iter->segId; send(mClientInfo[iter->clientNum].recvFd,buffer,20,0); if(mCurReqBlock == iter){ mCurReqBlock++; } mUsedBandSize -= (mBlockSize * 1000); mNeedSendBandSize -= (mBlockSize * 1000); mReqList.erase(iter); list<ClientReqBlock>::iterator preIter = mPreReqList.begin(); list<ClientReqBlock>::iterator tmpIter; while(preIter != mPreReqList.end()){ bool tmpTag = false; if(mIsP2POpen){ int bestClient = mDataServer->SearchBestClient(preIter->fileId, preIter->segId); // LOG_INFO("server find best client " << bestClient); if(bestClient != -1){ // char buffer[20]; tmpPtr = (int *)buffer; *tmpPtr = MSG_REDIRECT; tmpPtr++; *tmpPtr = 0; tmpPtr++; *tmpPtr = bestClient; tmpPtr++; *tmpPtr = mClientInfo[bestClient].address.sin_addr.s_addr; tmpPtr++; *tmpPtr = mClientInfo[bestClient].address.sin_port; send(mClientInfo[preIter->clientNum].recvFd,buffer,20,0); LOG_INFO(""); LOG_INFO("server send MSG_REDIRECT to " << preIter->clientNum << " redirect to " << bestClient); mNeedSendBandSize -= (mBlockSize * 1000); tmpIter = preIter; preIter++; mPreReqList.erase(tmpIter); tmpTag = true; // break; } } if(!tmpTag){ tmpIter = mReqList.begin(); int count = 0; while(tmpIter != mReqList.end()){ if(preIter->fileId == tmpIter->fileId && preIter->segId == tmpIter->segId) count++; tmpIter++; } if(count < 3){ ClientReqBlock tmpReqBlock = *preIter; mPreReqList.erase(preIter); mReqList.push_back(tmpReqBlock); break; } preIter++; } } // LOG_INFO("2"); if(!mPreReqList.empty() && preIter == mPreReqList.end()){ ClientReqBlock tmpReqBlock = mPreReqList.front(); mPreReqList.pop_front(); mReqList.push_back(tmpReqBlock); } } else{ iter->oper = iter->preOper; isFound = true; } // if(mCurReqBlock == mReqList.end()) // mCurReqBlock = iter; break; } iter++; } // if(mCurReqBlock != mReqList.end() && mCurReqBlock->) // GetNextBlock(); if(isFound && mCurReqBlock == mReqList.end()){ GetNextBlock(); mFakeTran.Active(); } break; } case MSG_CLIENT_DELAY:{ int clientNum = *ptr; ptr++; double delayTime = *((double *)ptr); mClientDelayOfs[clientNum].setf(ios::fixed, ios::floatfield); mClientDelayOfs[clientNum].precision(2); mClientDelayOfs[clientNum] << delayTime << endl; break; } default:{ LOG_INFO(""); LOG_INFO("server receive unknow message"); break; } } } void MyServer::GetNextBlock(){ list<ClientReqBlock>::iterator iter = mCurReqBlock; if(iter == mReqList.end()) mCurReqBlock = mReqList.begin(); // else if(mCurReqBlock->oper != OPER_WAIT && mCurReqBlock->leftSize > 0){ // return; // } else mCurReqBlock++; while(mCurReqBlock != iter){ if(mCurReqBlock != mReqList.end() && mCurReqBlock->oper != OPER_WAIT && mCurReqBlock->leftSize > 0){ return; } if(mCurReqBlock == mReqList.end()) mCurReqBlock = mReqList.begin(); else mCurReqBlock++; } if(iter != mReqList.end() && mCurReqBlock->oper != OPER_WAIT && mCurReqBlock->leftSize > 0) return; mCurReqBlock = mReqList.end(); } <file_sep>#!/bin/bash if [ $UID != 0 ];then echo "You must be a root" exit fi ulimit -n 65535 sed 's/\(ServerBand=\).*/\14000/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(SourceNums=\).*/\1100/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(ClientNums=\).*/\1150/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Multiple=\).*/\11/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Thelta=\).*/\1729/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(isP2POpen=\).*/\1true/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(PerSendSize=\).*/\11000/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Special=\).*/\1true/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(isRepeat=\).*/\1true/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; BUFFER=(DW) STARTNUMS=1 ENDNUMS=3 sed 's/\(BufferStrategy=\).*/\1'"DWS"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(ClientBufStrategy=\).*/\1'"${BUFFER[$i]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; for((i=$STARTNUMS;i<=$ENDNUMS;i++)) do rm -rf data/requestFiel*.log rm -rf data/client*.log rm -rf data/sequence.log cp -rf test_$i/requestFile*.log data/ if [ $i -ge 0 ] && [ $i -lt 4 ];then sed 's/\(BlockSize=\).*/\110000/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(BlockNums=\).*/\120/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(ServerBlockNums=\).*/\11000/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(isP2POpen=\).*/\1true/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(IsUseRealDevice=\).*/\1true/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; fi if [ $i = 4 ];then sed 's/\(BlockSize=\).*/\15000/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(BlockNums=\).*/\140/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; fi if [ $i = 5 ];then sed 's/\(BlockSize=\).*/\120000/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(BlockNums=\).*/\1100/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; fi if [ $i -ge 6 ];then sed 's/\(BlockSize=\).*/\110000/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(BlockNums=\).*/\140/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; fi ./server_exe > server.log & sleep 1 ./client_exe > client.log & sleep 5000 while true do sed -n '$,$p' server.log > temp nowtimes=`sed 's/At:\(.*\) server .*/\1/g' temp` if [ $(echo "${nowtimes} > 5001" | bc)x = 1x ];then break fi sleep 1 done killall server_exe killall client_exe rm -rf test_$i/client*.log rm -rf test_$i/sequence.log #./optResult data/sequence.log >> data/sequence.log mv data/sequence.log test_$i/ mv data/client*.log test_$i/ mv data/result.log test_$i/ done <file_sep>#ifndef BUFMANAGERBYLRUS_H #define BUFMANAGERBYLRUS_H #include "dbuffer.h" #include<vector> #include<map> using namespace std; class LRUSBlockInfo{ public: LRUSBlockInfo(){ fileId = 0; segId = 0; } LRUSBlockInfo( int _fileId, int _segId):fileId(_fileId),segId(_segId){ } int fileId; int segId; }; class DBufferLRUS: public DBuffer{ public: DBufferLRUS(int blockSize,int blockNums); virtual ~DBufferLRUS(); virtual bool Read(int fileId,int segId); virtual void Write(int fileId,int segId,int &ofileId,int &osegId); virtual void Strategy(int fileId,int segId,int &ofileId,int &osegId); virtual bool FindBlock(int fileId,int segId); int AddBlock(int fileId,int segId); public: virtual int getInLine( int clientId); virtual int getOutLine( int clientId); int getWeight(int fileId); virtual int addNewClient(int clientId, int fileId); private: list<LRUSBlockInfo> lruQueue; pthread_mutex_t dwbuf_mutex; map<unsigned int ,bool> isOnline;//the status of client ,online or outline //map<unsigned int,unsigned int> visitedFile;//the file that each client visit map<unsigned int,vector<unsigned int> > FileVisitors;//the files visitors; }; #endif <file_sep>#include "dbufferlfru.h" long long int getTimeIntervallfru(struct timeval *a,struct timeval *b){ long long int usec; usec = a->tv_sec - b->tv_sec; usec = 1000000*usec; usec += a->tv_usec - b->tv_usec; return usec; } DBufferLFRU::DBufferLFRU(int blockSize,int blockNums,int period) : DBuffer(blockSize,blockNums) { gettimeofday(&t0,NULL); // t0 = tv.tv_sec * 1000000 + tv.tv_usec; if(period ==0) period = 500; _period = period; // mBlockSize = blockSize; // mBlockNums = blockNums; buf.clear(); m_isblockReset = true; } DBufferLFRU::~DBufferLFRU(){ buf.clear(); } void DBufferLFRU::BlockReset(){ list<LFRUBlockInfoo>::iterator it; gettimeofday(&t0,NULL); for(it = buf.begin();it!=buf.end();it++){ it->weight = 0.0; it->periodCounter = 1; // gettimeofday(&(it->lastAccessTime),NULL); // it->lastAccessTime = t0; it->lastAccessTime.tv_sec = t0.tv_sec; it->lastAccessTime.tv_usec = t0.tv_usec; } } void DBufferLFRU::Write(int fileId,int segId,int &ofileId,int &osegId){ ofileId = -1; osegId = -1; if(buf.size() >= mBlockNums){ Strategy(fileId,segId,ofileId,osegId); } else{ AddBlock(fileId,segId); } } bool DBufferLFRU::Read(int fileId,int segId){ LFRUBlockInfoo temp; temp.fileId = fileId; temp.segId = segId; list<LFRUBlockInfoo>::iterator it; int flag = 0; struct timeval tv; for(it = buf.begin();it!=buf.end();it++){ if( it->fileId ==temp.fileId && it->segId == temp.segId){ it->periodCounter++; gettimeofday(&(it->lastAccessTime),NULL); // it->lastAccessTime = tv.tv_sec * 1000000 + tv.tv_usec; flag = 1; break; } } if(flag == 0){ cout<<"in bufManagerByLRU: can't find the segment <"<<fileId<<","<<segId<<">"<<endl; return false; } //readBlock(fileId,segId); return true; } bool DBufferLFRU::FindBlock(int fileId,int segId){ list<LFRUBlockInfoo>::iterator it; for(it = buf.begin();it !=buf.end();it++){ if(it->fileId == fileId && it->segId == segId){ return true; } } return false; } void DBufferLFRU::Strategy(int fileId,int segId,int &ofileId,int &osegId){ double Fk; unsigned long Rk; list<LFRUBlockInfoo>::iterator it, maxIt; double maxWeight =0.0; gettimeofday(&recallTime,NULL); // recallTime = tv.tv_sec * 1000000 + tv.tv_usec; for(it = buf.begin();it !=buf.end();it++){ if(it->segId == segId && it->fileId == fileId ){ it->weight = 0.0; it->periodCounter = 1; gettimeofday(&(it->lastAccessTime),NULL); return; } if(it->periodCounter ==0){ cout<<"counter error"<<endl; exit(1); } Fk = getTimeIntervallfru(&recallTime,&t0)/(double)(it->periodCounter * 1000000.0); Rk = getTimeIntervallfru(&recallTime ,&(it->lastAccessTime))/1000000.0; it->weight =((long long)_period- getTimeIntervallfru(&recallTime,&t0)/ 1000000.0) ; it->weight = it->weight * Rk /(double)_period ; it->weight += (getTimeIntervallfru(&recallTime ,&t0)*Fk/ (1000000.0 * (double)_period )); //cout << fileId << "," << segId << "Fk:" << Fk << ",Rk:" << Rk << ",period:" << _period << ",recallTime:" << recallTime.tv_sec<<":"<<recallTime.tv_usec << ",weight:" << it->weight << ",t0:" << t0.tv_sec<<":"<<t0.tv_usec << ",periodCounter:" << it->periodCounter << ",accessTime:" << it->lastAccessTime.tv_sec<<":"<<it->lastAccessTime.tv_usec << endl; if(it->weight > maxWeight){ maxWeight = it->weight; maxIt=it; } } ofileId = maxIt->fileId; osegId = maxIt->segId; buf.erase(maxIt); AddBlock(fileId,segId); } int DBufferLFRU::AddBlock(int fileId,int segId){ LFRUBlockInfoo temp; temp.fileId = fileId; temp.segId = segId; temp.weight = 0.0; temp.periodCounter = 1; gettimeofday(&(temp.lastAccessTime),NULL); // temp.lastAccessTime = t0; buf.push_back(temp); return 0; } <file_sep>#include "dbufferpr.h" #include <float.h> #include <math.h> const double PARA = 0.5;// for p = 2 DBufferPR::DBufferPR(int blockSize,int blockNums) :DBuffer(blockSize,blockNums) { // mBlockSize = blockSize; // mBlockNums = blockNums; timeslot = 0; prBuf.clear(); } DBufferPR::~DBufferPR(){ prBuf.clear(); } int DBufferPR::initial_parameter(){ list<prBlockInfo>::iterator it; for(it = prBuf.begin();it!=prBuf.end();it++){ it->weight = 0.0; } return 0; } void DBufferPR::Write(int fileId,int segId,int &ofileId,int &osegId){ ofileId = -1; osegId = -1; if(prBuf.size() >= mBlockNums){ Strategy(fileId,segId,ofileId,osegId); } else{ AddBlock(fileId,segId); } } bool DBufferPR::Read(int fileId,int segId){ prBlockInfo temp; temp.fileId = fileId; temp.segId = segId; list<prBlockInfo>::iterator it; // int accessTime; int flag = 0; for(it = prBuf.begin();it!=prBuf.end();it++){ if( it->fileId ==temp.fileId && it->segId == temp.segId){ it->lastTime = timeslot; timeslot++; flag = 1; break; } } if(flag == 0){ // cout<<"in DBufferPR: can't find the segment <"<<fileId<<","<<segId<<">"<<endl; return false; } return true; } bool DBufferPR::FindBlock(int fileId,int segId){ list<prBlockInfo>::iterator it; for(it = prBuf.begin();it !=prBuf.end();it++){ if(it->fileId == fileId && it->segId == segId){ return true; } } return false; } void DBufferPR::Strategy(int fileId,int segId,int &ofileId,int &osegId){ list<prBlockInfo>::iterator it, minIt; float minWeight = 111111111.0; double temp; // int baseTime; // gettimeofday(&tv,NULL); // baseTime = tv.tv_sec * 1000000 + tv.tv_usec; //cout<<"will write "<<fileId<<","<<segId<<endl; for(it = prBuf.begin();it !=prBuf.end();it++){ // temp=(it->weight)*pow(PARA,((timeslot - (it->lastTime))*_lambda)) ; if(it->segId <segId) temp = (double)(it->segId - segId); else temp = (timeslot - (it->lastTime))/(double)((int)it->segId - (int)segId) ; if(temp < minWeight){ minWeight = temp; minIt=it; } // cout <<"for " <<it->fileId<<","<< it->segId << ",weigth:" << temp << ",timeslot:" << timeslot << ",lasttime:" << it->lastTime << ",minWeight:" << minWeight << endl; // if(it->weight < minWeight){ // minWeight = it->weight; // minIt=it; // } } ofileId = minIt->fileId; osegId = minIt->segId; // cout<<"eliminate "<<ofileId<<","<<osegId<<endl; // sendEliminateBlock(minIt->fileId,minIt->segId); prBuf.erase(minIt); AddBlock(fileId,segId); } int DBufferPR::AddBlock(int fileId,int segId){ prBlockInfo temp; temp.fileId = fileId; temp.segId = segId; temp.lastTime =timeslot; temp.weight = 1.0; timeslot++; prBuf.push_back(temp); return 0; } <file_sep>/* * myclient.h * * Created on: 2013-2-21 * Author: zhaojun */ #ifndef MYCLIENT_H_ #define MYCLIENT_H_ #include "mymessage.h" #include "mytimer.h" #include "modelassemble.h" #include "faketran.h" #include "dbuffer.h" #include "dbufferlru.h" #include "dbufferpr.h" #include "dbufferdw.h" #include "dbufferlfru.h" #include "dbufferlfu.h" #include "dbufferlrfu.h" #include "dbufferfifo.h" #include <sys/socket.h> #include <pthread.h> #include <fstream> extern MyTimer globalTimer; class MyClient{ public: MyClient(ModelAssemble *model,int blockSize,int perSendSize, double bandWidth,int blockNums,int clientNum,int serverPort,int clientPort,int devNums, int clientNums,char **clusterAddress,char *serverAddress,char *bufferStrategy, int period,double lrfuLambda,bool isRepeat,int preFetch,bool special,bool isStartTogether); ~MyClient(); void Init(); void Run(); void DealWithMessage(char *buffer,int length); void Play(); void GetNextBlock(); bool SearchTheReqList(int fileId,int segId); void BufferReset(); int getClientNum() const { return mClientNum; } pthread_t GetTid(){return mtid;} // int JudgeCluster(char *address); private: // int mListenSockFd[2]; bool mIsReadFin; int mBufferResetFd[2]; int mNetSockFd; int mMyPort; int mClientPort; int mAskNum; char *mClusterAddress[MAX_DEV_NUM]; int mDevNums; int mClientNums; char *mServerAddress; int mServerPort; int mPlaySockFd[2]; // int mServerFd; int mEpollFd; ModelAssemble *mModel; DBuffer *mDbuffer; FakeTran mFakeTran; list<ClientReqBlock> mReqList; int mBlockSize; int mPerSendSize; list<ClientReqBlock>::iterator mCurReqBlock; int mFileId; int mSegId; int mClientNum; int mBlockNum; bool mIsPlaying; double mBitRate; int mMaxSegId; int mPlayerStatus; int mJumpSeg; int mLinkedNums; double mBand; int mPreFetch; ClientInfoBlock mClientInfo[MAX_CLIENT_NUM + 1]; pthread_t mtid; string mFileName; ofstream mOFs; ofstream mRecordFs; bool mDelay; timeval mDelayBeginTime; timeval mDelayEndTime; char *mBufferStrategy; int mPeriod; double mLrfuLambda; bool mIsRepeat; int mHitTimes; int mTotalTimes; bool mSpecial; int mOldFileId; int mOldSegId; int mDload1; int mDload2; bool mIsStartTogether; bool mIsFirstStart; }; #endif /* MYCLIENT_H_ */ <file_sep>/* * faketran.h * * Created on: 2013-2-20 * Author: zhaojun */ #ifndef FAKETRAN_H_ #define FAKETRAN_H_ #include "mytimer.h" #include <sys/socket.h> extern MyTimer globalTimer; extern double globalModify; class FakeTran{ public: FakeTran(); ~FakeTran(); int GetFd(){return mSockFd[0];} int GetOtherFd(){return mSockFd[1];} void TranData(double bandWidth,int blockSize,int toClientNum,int oper); void Active(); private: int mSockFd[2]; }; #endif /* FAKETRAN_H_ */ <file_sep>/* * myclientmanage.cpp * * Created on: 2013-2-23 * Author: zhaojun */ #include "myclientmanage.h" #include "log.h" MyClientManage::MyClientManage(char *serverAddress,int perSendSize,int blockSize, int blockNums,double bandWidth,int fileNum,double thelta,double lambda, double zeta,double sigma,double forZeta,double forSigma,int hotPlaces,int playToPlay,int playToPause,int playToForward, int playToBackward,int playToStop,int clientNums,char **clusterAddress,int serverPort, int clientPort,int devNums,int clusterNum,bool isStartTogether,char *bufferStrategy, int period,int lrfuLambda,bool isRepeat){ mPerSendSize = perSendSize; mBlockNums = blockNums; mBand = bandWidth; mBlockSize = blockSize; mIsStartTogether = isStartTogether; mFileNum = fileNum; mThelta = thelta; mLambda = lambda; mZeta = zeta; mSigma = sigma; mPlayToPlay = playToPlay; mPlayToBackward = playToBackward; mPlayToForward = playToForward; mPlayToPause = playToPause; mPlayToStop = playToStop; mClientNums = clientNums; mClusterNum = clusterNum; mClusterAddress = clusterAddress; mServerPort = serverPort; mClientPort = clientPort; mDevNums = devNums; mServerAddress = serverAddress; mBufferStrategy = bufferStrategy; mClientVect.clear(); mPeriod = period; mLrfuLambda = lrfuLambda / 1000.0; mIsRepeat = isRepeat; LOG_INFO(""); LOG_INFO("Client Config"); LOG_INFO("BandWidth = " << mBand); LOG_INFO("BlockSize = " << mBlockSize); LOG_INFO("BlockNums = " << mBlockNums); LOG_INFO("PerSendSize = " << mPerSendSize); LOG_INFO("FileNums = " << mFileNum); LOG_INFO("Thelta = " << mThelta); LOG_INFO("Lambda = " << mLambda); LOG_INFO("Zeta = " << mZeta); LOG_INFO("Sigma = " << mSigma); LOG_INFO("PlayToPlay = " << mPlayToPlay); LOG_INFO("PlayToBackward = " << mPlayToBackward); LOG_INFO("PlayToForward = " << mPlayToForward); LOG_INFO("PlayToPause = " << mPlayToPause); LOG_INFO("PlayToStop = " << mPlayToStop); LOG_INFO("ClientNums = " << mClientNums); LOG_INFO("ServerPort = " << mServerPort); LOG_INFO("ServerAddress = " << mServerAddress); LOG_INFO("ClientPort = " << mClientPort); LOG_INFO("DevNums = " << mDevNums); LOG_INFO("BufferStrategy = " << mBufferStrategy); LOG_INFO("Period = " << mPeriod); LOG_INFO("LrfuLambda = " << mLrfuLambda); LOG_INFO("IsRepeat = " << mIsRepeat); cout << "HotPlaces " << hotPlaces << endl; for(int i = 0;i < devNums;i++){ LOG_INFO("Cluster " << i << " address is:" << mClusterAddress[i]); } mModel = new ModelAssemble(mFileNum,mThelta,mLambda,mZeta,mSigma,forZeta,forSigma,mClientNums, mPlayToPlay,mPlayToPause,mPlayToForward,mPlayToBackward,mPlayToStop,mIsStartTogether,hotPlaces); } MyClientManage::~MyClientManage(){ delete mModel; for(int i = 1;i < mClientVect.size();i++){ delete mClientVect[i]; } mClientVect.clear(); } void MyClientManage::CreateClient(){ mClientVect.push_back(NULL); int startClient = (mClientNums / mDevNums) * mClusterNum + 1; int endClient = startClient + (mClientNums / mDevNums); for(int i = startClient;i < endClient;i++){ MyClient *client = new MyClient(mModel,mBlockSize,mPerSendSize,mBand,mBlockNums,i,mServerPort, mClientPort,mDevNums,mClientNums,mClusterAddress,mServerAddress,mBufferStrategy, mPeriod,mLrfuLambda,mIsRepeat); delete client; } } <file_sep>/* * myclient.cpp * * Created on: 2013-2-21 * Author: zhaojun */ #include "myclient.h" #include <sys/epoll.h> #include <sys/socket.h> #include <netinet/in.h> #include <memory.h> #include <arpa/inet.h> #include <stdlib.h> #include <netinet/tcp.h> #include <sstream> #include "log.h" void *ThreadToClient(void *arg){ MyClient *client = (MyClient *)arg; client->Run(); return NULL; } MyClient::MyClient(ModelAssemble *model,int blockSize,int perSendSize, double bandWidth,int blockNums,int clientNum,int serverPort,int clientPort,int devNums, int clientNums,char **clusterAddress,char *serverAddress,char *bufferStrategy, int period,double lrfuLambda,bool isRepeat,int preFetch,bool special,bool isStartTogether){ // mServerFd = serverFd; mIsStartTogether = isStartTogether; mModel = model; mOldFileId = -1; mOldSegId = -1; mBlockSize = blockSize; mPerSendSize = perSendSize; mBand = bandWidth; mBlockNum = blockNums; mClientNum = clientNum; mPreFetch = preFetch; mBufferStrategy = bufferStrategy; mPeriod = period; mLrfuLambda = lrfuLambda; mIsRepeat = isRepeat; stringstream sstream; sstream.str(""); sstream << "data/clientHit" << clientNum << ".log"; string fileName = sstream.str(); mOFs.open(fileName.c_str(),ios::out); mDelay = false; sstream.str(""); sstream << "data/client" << clientNum << ".log"; fileName = sstream.str(); mRecordFs.open(fileName.c_str(),ios::out); mIsReadFin = true; mAskNum = 0; mLinkedNums = 0; mSpecial = special; mIsFirstStart = true; if(strcmp(mBufferStrategy,"LRU") == 0){ mDbuffer = new DBufferLRU(blockSize,mBlockNum); } else if(strcmp(mBufferStrategy,"DW") == 0){ mDbuffer = new DBufferDW(blockSize,mBlockNum,mPeriod); } else if(strcmp(mBufferStrategy,"LFRU") == 0){ mDbuffer = new DBufferLFRU(blockSize,mBlockNum,mPeriod); } else if(strcmp(mBufferStrategy,"PR") == 0){ mDbuffer = new DBufferPR(blockSize,mBlockNum); } else if(strcmp(mBufferStrategy,"LFU") == 0){ mDbuffer = new DBufferLFU(blockSize,mBlockNum); } else if(strcmp(mBufferStrategy,"LRFU") == 0){ mDbuffer = new DBufferLRFU(blockSize,mBlockNum,mLrfuLambda); } else if(strcmp(mBufferStrategy,"FIFO") == 0){ mDbuffer = new DBufferFIFO(blockSize,mBlockNum); } mReqList.clear(); mServerPort = serverPort; mClientPort = clientPort; mDevNums = devNums; mClientNums = clientNums; mServerAddress = serverAddress; mMyPort = mClientPort + ((mClientNum - 1) % (mClientNums / mDevNums)); LOG_WRITE("Client " << mClientNum << " port is:" << mMyPort,mRecordFs); for(int i = 0;i < devNums;i++){ mClusterAddress[i] = clusterAddress[i]; } for(int i = 0;i <= MAX_CLIENT_NUM;i++){ // mClientInfo[i].listenFd = -1; mClientInfo[i].recvFd = -1; } mCurReqBlock = mReqList.end(); Init(); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " init finished",mRecordFs); mIsPlaying = false; mJumpSeg = 0; mPlayerStatus = PLAY; mHitTimes = 0; mTotalTimes = 0; mDload1 = -1; mDload2 = -1; pthread_create(&mtid,NULL,ThreadToClient,this); } MyClient::~MyClient(){ mReqList.clear(); delete mDbuffer; mModel = NULL; mCurReqBlock = mReqList.end(); for(int i = 0;i <= MAX_CLIENT_NUM;i++){ if(mClientInfo[i].recvFd != -1){ // close(mClientInfo[i].listenFd); close(mClientInfo[i].recvFd); // mClientInfo[i].listenFd = -1; mClientInfo[i].recvFd = -1; } } mOFs.close(); mRecordFs.close(); close(mNetSockFd); close(mEpollFd); // mOFs.close(); } void MyClient::Init(){ mEpollFd = epoll_create(MAX_LISTEN_NUM); epoll_event ev; mNetSockFd = socket(AF_INET,SOCK_STREAM,0); struct sockaddr_in clientAddress; bzero(&clientAddress,sizeof(clientAddress)); clientAddress.sin_addr.s_addr = INADDR_ANY; clientAddress.sin_port = htons(mMyPort); clientAddress.sin_family = AF_INET; int val = 1; setsockopt(mNetSockFd,SOL_SOCKET,SO_REUSEADDR,&val,sizeof(val)); if(bind(mNetSockFd,(struct sockaddr *)&clientAddress,sizeof(clientAddress)) == -1){ LOG_WRITE("Client " << mClientNum << " Bind Error!",mRecordFs); exit(1); } if(listen(mNetSockFd,20) == -1){ LOG_WRITE("Client " << mClientNum << " Listen Error!",mRecordFs); exit(1); } ev.data.fd = mNetSockFd; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mNetSockFd,&ev); ev.data.fd = mFakeTran.GetFd(); ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mFakeTran.GetFd(),&ev); socketpair(AF_UNIX,SOCK_STREAM,0,mPlaySockFd); ev.data.fd = mPlaySockFd[0]; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mPlaySockFd[0],&ev); socketpair(AF_UNIX,SOCK_STREAM,0,mBufferResetFd); ev.data.fd = mBufferResetFd[0]; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mBufferResetFd[0],&ev); } //int MyClient::JudgeCluster(char *address){ // for(int i = 0;i < mDevNums;i++){ // if(strcmp(address,mClusterAddress[i]) == 0) // return i; // } // return -1; //} void MyClient::BufferReset(){ TimerEvent timeEvent; timeEvent.isNew = true; timeEvent.sockfd = mBufferResetFd[1]; timeEvent.leftTime = mPeriod * 1000000; globalTimer.RegisterTimer(timeEvent); mDbuffer->BlockReset(); } void MyClient::Run(){ fstream iofs; bool readOrWrite = false; TimerEvent timeEvent; if(mIsRepeat){ stringstream sstream; sstream.str(""); sstream << "data/requestFile" << mClientNum << ".log"; string requestFilename = sstream.str(); iofs.open(requestFilename.c_str(),ios::in); readOrWrite = true; if(iofs.fail()){ iofs.open(requestFilename.c_str(),ios::out); readOrWrite = false; } } // LOG_WRITE("client " << mClientNum << " before"); if(mIsRepeat && readOrWrite){ iofs >> mFileId; iofs >> mSegId; iofs >> timeEvent.leftTime; iofs >> mSegId; } else{ mFileId = mModel->GetStartFileId(); mSegId = mModel->GetStartSegId(); timeEvent.leftTime = mModel->GetStartTime(mClientNum) * 1000000; if(mIsRepeat){ iofs << mFileId << endl; iofs << mSegId << endl; iofs << timeEvent.leftTime << endl; } } if(mIsStartTogether) timeEvent.leftTime = 0; cout << mFileId << " is client " << mClientNum << " request file" << endl; // LOG_WRITE("client " << mClientNum << " before1"); // LOG_WRITE("client " << mClientNum << " before2"); timeEvent.isNew = true; timeEvent.sockfd = mFakeTran.GetOtherFd(); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " start time at:" << timeEvent.leftTime,mRecordFs); globalTimer.RegisterTimer(timeEvent); bool firstTime = true; int toggleSwitch = 0; epoll_event events[MAX_LISTEN_NUM]; int oldSegId = 0; int readSegId = 1; bool isFromBuffer = false; while(true){ int fds = epoll_wait(mEpollFd,events,MAX_LISTEN_NUM,-1); if(firstTime){ int connectFd; char buffer[20]; // char nullChar; read(events[0].data.fd,buffer,20); struct sockaddr_in serverAddress; bzero(&serverAddress,sizeof(serverAddress)); serverAddress.sin_addr.s_addr = inet_addr(mServerAddress); serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(mServerPort); connectFd = socket(AF_INET,SOCK_STREAM,0); mClientInfo[0].recvFd = connectFd; mClientInfo[0].address.sin_addr = serverAddress.sin_addr; mClientInfo[0].address.sin_port = serverAddress.sin_port; int flag = 1; setsockopt(connectFd,IPPROTO_TCP,TCP_NODELAY,&flag,sizeof(flag)); // setsockopt( sock, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag) ); if(connect(connectFd,(struct sockaddr *)&serverAddress,sizeof(struct sockaddr)) == -1){ LOG_WRITE("Client " << mClientNum << " Connect 0 Error!",mRecordFs); exit(1); } epoll_event ev; ev.data.fd = connectFd; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,connectFd,&ev); int *tmpPtr = (int *)buffer; *tmpPtr = mClientNum; send(connectFd,buffer,20,0); if(mDbuffer->IsBlockReset()){ timeEvent.isNew = true; timeEvent.sockfd = mBufferResetFd[1]; timeEvent.leftTime = mPeriod * 1000000; globalTimer.RegisterTimer(timeEvent); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " has blockreset reset period:" << mPeriod,mRecordFs); //BufferReset(); } firstTime = false; unsigned int length = mModel->GslRandLogNormal(); mJumpSeg = length / mBlockSize; if(readOrWrite) { LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " read",mRecordFs); mJumpSeg = 1; LOG_WRITE("client " << mClientNum << " JumpSeg:" << mJumpSeg,mRecordFs); } // if(!readOrWrite && mIsRepeat) // iofs << mSeg LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " start to join the network request fileId:" << mFileId,mRecordFs); continue; } for(int i = 0;i < fds;i++){ if(events[i].events == EPOLLIN){ if(events[i].data.fd != mPlaySockFd[0]){ if(events[i].data.fd == mFakeTran.GetFd()){ char buffer[20]; read(mFakeTran.GetFd(),buffer,20); DealWithMessage(buffer,20); } else if(events[i].data.fd == mNetSockFd){ struct sockaddr_in clientAddr; unsigned int length; epoll_event ev; length = sizeof(clientAddr); int clientFd = accept(mNetSockFd,(struct sockaddr *)&clientAddr,&length); // mLinkedNums++; char buffer[20]; int *ptr = (int *)buffer; recv(clientFd,buffer,20,0); int clientNum = *ptr; int port = mClientPort + ((clientNum - 1) % (mClientNums / mDevNums)); if(mClientInfo[clientNum].recvFd == -1){ mClientInfo[clientNum].address.sin_addr = clientAddr.sin_addr; mClientInfo[clientNum].address.sin_port = htons(port); mClientInfo[clientNum].recvFd = clientFd; } LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " response MSG_CONNECT_FIN to " << clientNum << " fd is:" << clientFd,mRecordFs); ev.data.fd = clientFd; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,clientFd,&ev); ptr = (int *)buffer; *ptr = MSG_CONNECT_FIN; ptr++; *ptr = mClientNum; send(mClientInfo[clientNum].recvFd,buffer,20,0); } else if(events[i].data.fd == mBufferResetFd[0]){ char buffer[20]; int length = recv(events[i].data.fd,buffer,20,0); BufferReset(); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " reset buffer",mRecordFs); } else{ char buffer[20]; memset(buffer,0,20); int length = recv(events[i].data.fd,buffer,20,0); DealWithMessage(buffer,length); // int asdf = events[i].events == EPOLLIN ? 1 : 0; // LOG_WRITE("my fd:" << events[i].data.fd << " epollin:" << asdf << " length:" << length); } } else{ char buffer[20]; read(mPlaySockFd[0],&buffer,20); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << "JumpSeg:" << mJumpSeg,mRecordFs); if(mJumpSeg == 0){ mPlayerStatus = mModel->GetNextStatus(mPlayerStatus); if(mPlayerStatus == STOP){ LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " status is STOP",mRecordFs); break; } unsigned int length = mModel->GslRandLogNormal(); mJumpSeg = length / mBlockSize; LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " currentstatus is:" << mPlayerStatus << ",JumpSeg:" << mJumpSeg << ",length:" << length,mRecordFs); if(mJumpSeg == 0) mJumpSeg++; if(mPlayerStatus == FORWARD){ mSegId += mJumpSeg; if(mSegId > mMaxSegId){ mSegId = 1; // mSegId = mMaxSegId; } mJumpSeg = 0; // char nullChar = '\0'; send(mPlaySockFd[1],buffer,20,0); // continue; } else if(mPlayerStatus == BACKWARD){ mSegId -= mJumpSeg; if(mSegId < 1) mSegId = 1; mJumpSeg = 0; // char nullChar = '\0'; send(mPlaySockFd[1],buffer,20,0); // continue; } } // if(mIsRepeat && !readOrWrite && mPlayerStatus == PLAY) // iofs << mSegId << endl; bool isPreFetch; if(mPreFetch > 0) isPreFetch = true; else isPreFetch = false; if(mJumpSeg != 0 || readOrWrite){ bool isJustStart = false; if(oldSegId == 0) isJustStart = true; if(!mDelay){ mDelay = true; gettimeofday(&mDelayBeginTime,NULL); if(mSpecial && mOldFileId != -1){ int tmpFileId,tmpSegId; char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_SEG_FIN; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = mOldFileId; tmpPtr++; *tmpPtr = mOldSegId; send(mClientInfo[mAskNum].recvFd,buffer,20,0); mDbuffer->Write(mOldFileId,mOldSegId,tmpFileId,tmpSegId); if(tmpFileId != -1){ char delbuffer[20]; tmpPtr = (int *)delbuffer; *tmpPtr = MSG_DELETE_SEG; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = tmpFileId; tmpPtr++; *tmpPtr = tmpSegId; LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " send MSG_DELETE_SEG fileId:" << tmpFileId << ",segId" << tmpSegId,mRecordFs); send(mClientInfo[0].recvFd,delbuffer,20,0); } char addbuffer[20]; tmpPtr = (int *)addbuffer; *tmpPtr = MSG_ADD_SEG; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = mOldFileId; tmpPtr++; *tmpPtr = mOldSegId; tmpPtr++; *tmpPtr = mLinkedNums; LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " send MSG_ADD_SEG fileId:" << mOldFileId << ",segId" << mOldSegId,mRecordFs); send(mClientInfo[0].recvFd,addbuffer,20,0); mAskNum = 0; } } oldSegId = mSegId; mSegId = readSegId; bool isRead; if(mSpecial){ mTotalTimes++; isRead = mDbuffer->Read(mFileId,mSegId); if(isRead){ isFromBuffer = true; mHitTimes++; } else{ if(mSegId == mDload1 || mSegId == mDload2) isRead = true; else isRead = false; isFromBuffer = false; // LOG_WRITE("now isRead ") } } else isRead = mDbuffer->Read(mFileId,mSegId); //if(isRead){ // LOG_WRITE("client " << mClientNum << " read segId:" << mSegId); //} //else{ // LOG_WRITE("client " << mClientNum << " read failed segId:" << mSegId); //} if(readOrWrite){ if(!mSpecial){ if((mSegId - oldSegId) != 0 && isRead && oldSegId != 0){ mHitTimes++; } else if((mSegId - oldSegId) != 0 && !isRead){ mTotalTimes--; } } } double delayTime = 0; if(mSpecial && !isRead && !isJustStart){ // mAskNum = 0; int *ptr; ptr = (int *)buffer; *ptr = MSG_SEG_ASK; ptr++; *ptr = mClientNum; ptr++; *ptr = mFileId; ptr++; *ptr = mSegId; send(mClientInfo[mAskNum].recvFd,buffer,20,0); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " send MSG_SEG_ASK to " << mAskNum << " fileId:" << mFileId << " segId:" << mSegId,mRecordFs); // } if(isRead || mSpecial){ //第一次转向客户端请求获得,需要修正一次 // if(mAskNum != 0 && toggleSwitch == 1){ // mHitTimes++; // toggleSwitch = 0; // } // else if(mAskNum == 0 && toggleSwitch == 0){ // toggleSwitch = 1; // } if(!isFromBuffer){ mOldFileId = mFileId; mOldSegId = mSegId; } else mOldFileId = -1; mDelay = false; gettimeofday(&mDelayEndTime,NULL); delayTime = ((mDelayEndTime.tv_sec - mDelayBeginTime.tv_sec) + (mDelayEndTime.tv_usec - mDelayBeginTime.tv_usec) / 1000000.0); if(delayTime < 0.1) delayTime = 0; // mOFs << delayTime << endl; // mOFs << ((mDelayEndTime.tv_sec - mDelayBeginTime.tv_sec) + // (mDelayEndTime.tv_usec - mDelayBeginTime.tv_usec) / 1000000.0) << endl; // mOFs.flush(); mOFs << mTotalTimes << " " << mHitTimes << endl; timeEvent.isNew = true; timeEvent.leftTime = ((mBlockSize * 8) * 1000000) / mBitRate; timeEvent.sockfd = mPlaySockFd[1]; globalTimer.RegisterTimer(timeEvent); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " play fileId:" << mFileId << ",segId:" << mSegId << ",playtime:" << timeEvent.leftTime << " Hit times:" << mHitTimes << " TotalTimes:" << mTotalTimes,mRecordFs); // if(mSpecial){ // char addbuffer[20]; // int *tmpPtr = (int *)addbuffer; // *tmpPtr = MSG_ADD_SEG; // tmpPtr++; // *tmpPtr = mClientNum; // tmpPtr++; // *tmpPtr = mFileId; // tmpPtr++; // *tmpPtr = mSegId; // tmpPtr++; // *tmpPtr = mReqList.size() - 1;//mLinkedNums; // LOG_WRITE(""); // LOG_WRITE("client " << mClientNum << " send MSG_ADD_SEG fileId:" << mFileId << // ",segId" << mSegId); // send(mClientInfo[0].recvFd,addbuffer,20,0); // } if(!readOrWrite){ LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " write",mRecordFs); mJumpSeg--; if(mIsRepeat) iofs << mSegId << endl; } else{ iofs >> readSegId; // iofs >> mSegId; } if(!mSpecial){ mSegId++; } // isSegChange = true; if(mSegId > mMaxSegId) mSegId = 1; mIsPlaying = true; } else{ mIsPlaying = false; isPreFetch = true; } bool isInBuffer = false; if(isPreFetch && !mSpecial) isInBuffer = mDbuffer->FindBlock(mFileId,mSegId); if(mIsReadFin && !isInBuffer && !mSpecial){ mTotalTimes++; int *ptr; if(!mDelay){ ptr = (int *)buffer; *ptr = MSG_CLIENT_DELAY; ptr++; *ptr = mClientNum; ptr++; double *dbptr = (double *)ptr; *dbptr = delayTime; send(mClientInfo[0].recvFd,buffer,20,0); } // if(!SearchTheReqList(mFileId,mSegId)){ mIsReadFin = false; ptr = (int *)buffer; *ptr = MSG_SEG_ASK; ptr++; *ptr = mClientNum; ptr++; *ptr = mFileId; ptr++; *ptr = mSegId; send(mClientInfo[mAskNum].recvFd,buffer,20,0); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " send MSG_SEG_ASK to " << mAskNum << " TWO",mRecordFs); // } } else if(isInBuffer){ if(mSpecial){ mHitTimes++; } else{ if((mSegId - readSegId) == 0){ mHitTimes++; } } mTotalTimes++; } // if(mIsReadFin && readOrWrite){ // oldSegId = mSegId; // mSegId = readSegId; // } } } } } } if(mIsRepeat) iofs.close(); } bool MyClient::SearchTheReqList(int fileId,int segId){ list<ClientReqBlock>::iterator reqIter = mReqList.begin(); while(reqIter != mReqList.end()){ if(reqIter->fileId == fileId && reqIter->segId == segId && reqIter->preOper == OPER_READ) return true; reqIter++; } return false; } void MyClient::DealWithMessage(char *buf,int length){ int *ptr = (int *)buf; int type = *ptr; ptr++; switch(type){ case MSG_CONNECT_FIN:{ int clientNum = *ptr; ptr++; int mytag = *ptr; // LOG_WRITE("my tag is:" << mytag); char buffer[20]; ptr = (int *)buffer; *ptr = MSG_CLIENT_JOIN; ptr++; *ptr = mClientNum; ptr++; send(mClientInfo[clientNum].recvFd,buffer,20,0); LOG_WRITE("",mRecordFs); LOG_WRITE("Client " << mClientNum << " receive MSG_CONNECT_FIN from " << clientNum << " and response MSG_CLIENT_JOIN " << mClientInfo[clientNum].recvFd,mRecordFs); // LOG_WRITE("client all fd:" << sockFd[0] << "," << sockFd[1] << "," << // mPlaySockFd[0] << "," << mPlaySockFd[1] << "," << mListenSockFd[0] << "," << // mListenSockFd[1]); break; } case MSG_CLIENT_JOIN:{ int clientNum = *ptr; ptr++; epoll_event ev; char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_JOIN_ACK; tmpPtr++; *tmpPtr = mClientNum; send(mClientInfo[clientNum].recvFd,buffer,20,0); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " response MSG_JOIN_ACK to " << clientNum,mRecordFs); break; } case MSG_JOIN_ACK:{ // char buffer[20]; // send(mPlaySockFd[1],buffer,20,0); int clientNum = *ptr; char buffer[20]; int *tmpPtr = (int *)buffer; if(mAskNum == 0 && !mSpecial) mTotalTimes++; *tmpPtr = MSG_SEG_ASK; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = mFileId; tmpPtr++; *tmpPtr = mSegId; send(mClientInfo[clientNum].recvFd,buffer,20,0); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_JOIN_ACK from " << clientNum << " and response MSG_SEG_ASK, ask fileId:" << mFileId << ",segId:" << mSegId,mRecordFs); break; } case MSG_CLIENT_LEAVE:{ int clientNum = *ptr; epoll_event ev; ev.data.fd = mClientInfo[clientNum].recvFd; ev.events = EPOLLIN; epoll_ctl(mEpollFd,EPOLL_CTL_DEL,mClientInfo[clientNum].recvFd,&ev); close(mClientInfo[clientNum].recvFd); mClientInfo[clientNum].recvFd = -1; LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_CLIENT_LEAVE from " << clientNum,mRecordFs); break; } case MSG_SEG_ACK:{ int clientNum = *ptr; ptr++; mMaxSegId = *ptr; ptr++; mBitRate = *((double *)ptr); if(mAskNum != 0) mHitTimes++; if(mSpecial && mIsFirstStart){ char buffer[20]; send(mPlaySockFd[1],buffer,20,0); mIsFirstStart = false; } if(!mSpecial){ ClientReqBlock reqBlock; reqBlock.clientNum = clientNum; reqBlock.fileId = mFileId; reqBlock.segId = mSegId; reqBlock.preOper = OPER_READ; reqBlock.oper = OPER_WAIT; reqBlock.leftSize = mBlockSize * 1000; reqBlock.localfin = NONE_FIN; mReqList.push_back(reqBlock); // mLinkedNums++; char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_REQUEST_SEG; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = mFileId; tmpPtr++; *tmpPtr = mSegId; send(mClientInfo[clientNum].recvFd,buffer,20,0); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_SEG_ACK from " << clientNum << " and response MSG_REQUEST_SEG",mRecordFs); } // if(mCurReqBlock == NULL) // mFakeTran.Active(); break; } case MSG_SEG_ASK:{ int clientNum = *ptr; ptr++; int fileId = *ptr; ptr++; int segId = *ptr; if(!mSpecial) mLinkedNums = mReqList.size(); bool isInBuffer = mDbuffer->Read(fileId,segId); if(mLinkedNums > MAX_CLIENT_LINKS || !isInBuffer){ char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_REDIRECT; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = 0;//服务器编号 tmpPtr++; *tmpPtr = mClientInfo[0].address.sin_addr.s_addr; tmpPtr++; *tmpPtr = mClientInfo[0].address.sin_port; send(mClientInfo[clientNum].recvFd,buffer,20,0); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_SEG_ACK from " << clientNum << " and response MSG_REDIRECT to server",mRecordFs); if(!isInBuffer){ LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " do no have fileId:" << fileId << " segId:" << segId,mRecordFs); } break; } if(mSpecial) mLinkedNums++; char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_SEG_ACK; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = mMaxSegId; tmpPtr++; double *dbPtr = (double *)tmpPtr; *dbPtr = mBitRate; send(mClientInfo[clientNum].recvFd,buffer,20,0); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_SEG_ASK from " << clientNum << " and response MSG_SEG_ACK",mRecordFs); break; } case MSG_REQUEST_SEG:{ int clientNum = *ptr; ptr++; int fileId = *ptr; ptr++; int segId = *ptr; ClientReqBlock reqBlock; reqBlock.clientNum = clientNum; reqBlock.fileId = fileId; reqBlock.segId = segId; reqBlock.oper = OPER_WRITE; reqBlock.leftSize = mBlockSize * 1000; reqBlock.preOper = OPER_WRITE; reqBlock.localfin = NONE_FIN; mReqList.push_back(reqBlock); if(mCurReqBlock == mReqList.end()){ GetNextBlock(); mFakeTran.Active(); } LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_REQUEST_SEG from " << clientNum,mRecordFs); // LOG_WRITE("client " << mClientNum << " request list size:" << mReqList.size()); break; } case MSG_REDIRECT:{ int fromClientNum = *ptr; ptr++; int clientNum = *ptr; ptr++; // int listenFd = *ptr; list<ClientReqBlock>::iterator iter = mReqList.begin(); while(iter != mReqList.end()){ if(iter->preOper == OPER_READ && iter->clientNum == fromClientNum){ mReqList.erase(iter); break; } iter++; } mAskNum = clientNum; LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_REDIRECT and response MSG_SEG_ASK to " << clientNum,mRecordFs); if(mClientInfo[clientNum].recvFd == -1){ struct sockaddr_in clientAddr; bzero(&clientAddr,sizeof(clientAddr)); mClientInfo[clientNum].address.sin_addr.s_addr = *ptr; ptr++; mClientInfo[clientNum].address.sin_port = *ptr; clientAddr.sin_addr = mClientInfo[clientNum].address.sin_addr; clientAddr.sin_port = mClientInfo[clientNum].address.sin_port; clientAddr.sin_family = AF_INET; int connectFd = socket(AF_INET,SOCK_STREAM,0); epoll_event ev; ev.data.fd = connectFd; ev.events = EPOLLIN; mClientInfo[clientNum].recvFd = connectFd; epoll_ctl(mEpollFd,EPOLL_CTL_ADD,connectFd,&ev); if(connect(connectFd,(struct sockaddr *)&clientAddr,sizeof(clientAddr)) == -1){ LOG_WRITE("client " << mClientNum << " MSG_REDIRECT " << clientNum << " error!!!",mRecordFs); exit(1); } char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = mClientNum; send(connectFd,buffer,20,0); LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_REDIRECT to " << clientNum,mRecordFs); } else{ //mTotalTimes++; char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_SEG_ASK; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = mFileId; tmpPtr++; *tmpPtr = mSegId; send(mClientInfo[clientNum].recvFd,buffer,20,0); } break; } case MSG_RESET_BUFFER:{ mDbuffer->BlockReset(); break; } case MSG_FAKE_FIN:{ bool isNativeProduce = false; int toClientNum = *ptr; ptr++; int oper = *ptr; // ptr++; // int segId = *ptr; list<ClientReqBlock>::iterator tmpIter = mReqList.begin(); while(oper == OPER_WRITE && tmpIter != mReqList.end()){ if(tmpIter->clientNum == toClientNum && tmpIter->preOper == OPER_WRITE){ if(tmpIter->leftSize <= 0){ char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_SEG_FIN; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = tmpIter->fileId; tmpPtr++; *tmpPtr = tmpIter->segId; send(mClientInfo[tmpIter->clientNum].recvFd,buffer,20,0); if(mCurReqBlock == tmpIter){ GetNextBlock(); isNativeProduce = true; // mCurReqBlock++; // if(mCurReqBlock == mReqList.end()) } // mLinkedNums--; mReqList.erase(tmpIter); break; } if(tmpIter->localfin == REMOTE_FIN){ tmpIter->oper = tmpIter->preOper; tmpIter->localfin = NONE_FIN; } else{ tmpIter->localfin = LOCAL_FIN; } break; } tmpIter++; } if(mCurReqBlock != mReqList.end()){ // LOG_WRITE(""); // LOG_WRITE("client " << mClientNum << " req from " << mCurReqBlock->clientNum << // " left size:" << mCurReqBlock->leftSize << " operate:" << mCurReqBlock->preOper << // " localfin:" << mCurReqBlock->localfin); if(mCurReqBlock->oper == OPER_WAIT && mCurReqBlock->preOper == OPER_READ){ mCurReqBlock->leftSize -= mPerSendSize; int *tmpPtr; char buffer[20]; tmpPtr = (int *)buffer; *tmpPtr = MSG_REMOTE_FAKE_FIN; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = mCurReqBlock->preOper == OPER_READ ? OPER_WRITE : OPER_READ; int sendLength; sendLength = send(mClientInfo[mCurReqBlock->clientNum].recvFd,buffer,20,0); if(mCurReqBlock->leftSize <= 0){ // int ofileId = -1; // int osegId = -1; // if(mSpecial){ // if(mDload1 != -1) // mDload2 = mDload1; // mDload1 = mCurReqBlock->segId; // } // else{ // mDbuffer->Write(mCurReqBlock->fileId,mCurReqBlock->segId,ofileId,osegId); // } // // //原播放的地方 //// mIsReadFin = true; //// if(!mIsPlaying){ ////// char nullChar = '\0'; //// send(mPlaySockFd[1],buffer,20,0); //// mIsPlaying = true; //// //LOG_WRITE("client " << mClientNum << " will play now segId:" << mCurReqBlock->segId << "," << "mSegId:" << mSegId); //// } // // if(ofileId != -1){ // char delbuffer[20]; // tmpPtr = (int *)delbuffer; // *tmpPtr = MSG_DELETE_SEG; // tmpPtr++; // *tmpPtr = mClientNum; // tmpPtr++; // *tmpPtr = ofileId; // tmpPtr++; // *tmpPtr = osegId; // LOG_WRITE(""); // LOG_WRITE("client " << mClientNum << " send MSG_DELETE_SEG fileId:" << ofileId << // ",segId" << osegId); // send(mClientInfo[0].recvFd,delbuffer,20,0); // } // if(!mSpecial){ // char addbuffer[20]; // tmpPtr = (int *)addbuffer; // *tmpPtr = MSG_ADD_SEG; // tmpPtr++; // *tmpPtr = mClientNum; // tmpPtr++; // *tmpPtr = mCurReqBlock->fileId; // tmpPtr++; // *tmpPtr = mCurReqBlock->segId; // tmpPtr++; // *tmpPtr = mReqList.size() - 1;//mLinkedNums; // LOG_WRITE(""); // LOG_WRITE("client " << mClientNum << " send MSG_ADD_SEG fileId:" << mCurReqBlock->fileId << // ",segId" << mCurReqBlock->segId); // send(mClientInfo[0].recvFd,addbuffer,20,0); // } list<ClientReqBlock>::iterator reqIter = mCurReqBlock; mCurReqBlock++; mReqList.erase(reqIter); } GetNextBlock(); } else if(!isNativeProduce && mCurReqBlock->preOper == OPER_WRITE){ GetNextBlock(); } if(mCurReqBlock != mReqList.end()){ mCurReqBlock->oper = OPER_WAIT; mFakeTran.TranData(mBand,mPerSendSize,mCurReqBlock->clientNum,mCurReqBlock->preOper); if(mCurReqBlock->preOper == OPER_WRITE){ mCurReqBlock->localfin = NONE_FIN; char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_REMOTE_FAKE_FIN; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = mCurReqBlock->preOper == OPER_READ ? OPER_WRITE : OPER_READ; send(mClientInfo[mCurReqBlock->clientNum].recvFd,buffer,20,0); // GetNextBlock(); } } } break; } case MSG_REMOTE_FAKE_FIN:{ int clientNum = *ptr; ptr++; int oper = *ptr; list<ClientReqBlock>::iterator iter = mReqList.begin(); bool isFound = false; while(iter != mReqList.end()){ if(iter->clientNum == clientNum && iter->preOper == oper){ if(iter->preOper == OPER_WRITE){ iter->leftSize -= mPerSendSize; if(iter->localfin == LOCAL_FIN){ iter->oper = iter->preOper; iter->localfin = NONE_FIN; isFound = true; } else{ iter->localfin = REMOTE_FIN; isFound = false; } if(isFound && iter->leftSize <= 0){ char buffer[20]; int *tmpPtr = (int *)buffer; *tmpPtr = MSG_SEG_FIN; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = iter->fileId; tmpPtr++; *tmpPtr = iter->segId; send(mClientInfo[iter->clientNum].recvFd,buffer,20,0); if(mCurReqBlock == iter){ mCurReqBlock++; } // mLinkedNums--; mReqList.erase(iter); isFound = false; } } else{ iter->oper = iter->preOper; isFound = true; } // if(iter->leftSize == mBlockSize * 1000){ // LOG_WRITE(""); // LOG_WRITE("client " << mClientNum << " receive MSG_REMOTE_FAKE_FIN from " << // iter->clientNum << ",leftSize:" << iter->leftSize << ",oper:" << iter->preOper << // ",localfin:" << iter->localfin); // } break; } iter++; } if(isFound && mCurReqBlock == mReqList.end()){ GetNextBlock(); mFakeTran.Active(); } break; } case MSG_SEG_FIN:{ int clientNum = *ptr; ptr++; int fileId = *ptr; ptr++; int segId = *ptr; if(mSpecial){ mLinkedNums--; LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_SEG_FIN from " << clientNum << " mLinkedNums:" << mLinkedNums,mRecordFs); } if(!mSpecial){ int *tmpPtr; int ofileId = -1; int osegId = -1; LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " receive MSG_SEG_FIN from " << clientNum,mRecordFs); char buffer[20]; if(mSpecial){ if(mDload1 != -1) mDload2 = mDload1; mDload1 = segId; } else{ mDbuffer->Write(fileId,segId,ofileId,osegId); } //原播放的地方 mIsReadFin = true; if(!mIsPlaying){ // char nullChar = '\0'; send(mPlaySockFd[1],buffer,20,0); mIsPlaying = true; //LOG_WRITE("client " << mClientNum << " will play now segId:" << mCurReqBlock->segId << "," << "mSegId:" << mSegId); } if(ofileId != -1){ char delbuffer[20]; tmpPtr = (int *)delbuffer; *tmpPtr = MSG_DELETE_SEG; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = ofileId; tmpPtr++; *tmpPtr = osegId; LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " send MSG_DELETE_SEG fileId:" << ofileId << ",segId" << osegId,mRecordFs); send(mClientInfo[0].recvFd,delbuffer,20,0); } if(!mSpecial){ char addbuffer[20]; tmpPtr = (int *)addbuffer; *tmpPtr = MSG_ADD_SEG; tmpPtr++; *tmpPtr = mClientNum; tmpPtr++; *tmpPtr = fileId; tmpPtr++; *tmpPtr = segId; tmpPtr++; *tmpPtr = mReqList.size() - 1;//mLinkedNums; LOG_WRITE("",mRecordFs); LOG_WRITE("client " << mClientNum << " send MSG_ADD_SEG fileId:" << fileId << ",segId" << segId,mRecordFs); send(mClientInfo[0].recvFd,addbuffer,20,0); } } break; } } } void MyClient::GetNextBlock(){ list<ClientReqBlock>::iterator iter = mCurReqBlock; if(iter == mReqList.end()) mCurReqBlock = mReqList.begin(); // else if(mCurReqBlock->oper != OPER_WAIT && mCurReqBlock->leftSize > 0){ // return; // } else mCurReqBlock++; while(mCurReqBlock != iter){ if(mCurReqBlock != mReqList.end() && mCurReqBlock->oper != OPER_WAIT && mCurReqBlock->leftSize > 0){ return; } if(mCurReqBlock == mReqList.end()) mCurReqBlock = mReqList.begin(); else mCurReqBlock++; } if(iter != mReqList.end() && mCurReqBlock->oper != OPER_WAIT && mCurReqBlock->leftSize > 0) return; mCurReqBlock = mReqList.end(); } <file_sep>#include "dbufferdws.h" #include<math.h> DBufferDWS::DBufferDWS(int blockSize,int blockNums,int period) : DBuffer(blockSize,blockNums) { if(period ==0) period = 500; _period = period; m_isblockReset = true; gettimeofday(&_t0,NULL); } DBufferDWS::~DBufferDWS(){ } void DBufferDWS::BlockReset(){ list<DWSBlockInfo>::iterator it; // gettimeofday(&_t0,NULL); for(it = lruQueue.begin();it!=lruQueue.end();it++){ (*it).m_histOld = (*it).m_histNew; //(*it)->m_histOld = (*it)->m_histOld + (*it)->m_histNew ; (*it).m_histNew = 1; //it->weight = 0; } } void DBufferDWS::Write(int fileId,int segId,int &ofileId,int &osegId){ ofileId = -1; osegId = -1; if(lruQueue.size() >= mBlockNums){ Strategy(fileId,segId,ofileId,osegId); } else{ AddBlock(fileId,segId); } } bool DBufferDWS::Read(int fileId,int segId){ list<DWSBlockInfo>::iterator it; DWSBlockInfo readedBlock; for(it = lruQueue.begin();it!=lruQueue.end();it++){ // cout<<"block <"<<(*it)->fileId<<","<<(*it)->segId<<">"<<endl; if( (*it).fileId ==fileId && (*it).segId == segId){ (*it).m_histNew ++; // readedBlock = *it; // lruQueue.erase(it); break; } } if(it == lruQueue.end()){ // cout<<"in DBufferDWS: can't find the segment <"<<fileId<<","<<segId<<">"<<endl; return false; } // else{ // lruQueue.push_back(readedBlock); // } //readBlock(fileId,segId); return true; } bool DBufferDWS::FindBlock(int fileId,int segId){ list<DWSBlockInfo>::iterator it; for(it = lruQueue.begin();it !=lruQueue.end();it++){ if((*it).fileId == fileId && (*it).segId == segId){ return true; } } return false; } void DBufferDWS::Strategy(int fileId,int segId,int &ofileId,int &osegId){ // unsigned int fileId,segId; int minWeight =111111111; DWSBlockInfo eliminateBlockPtr; list<DWSBlockInfo>::iterator it,minHistIt,minHistNewIt,minIt; double pfnew ,pfold; //struct timeval cur_tv; int minHistNew; minHistNew = minWeight; //gettimeofday(&cur_tv,NULL); //pfnew = getTimeInterval(&cur_tv,&_t0)/(double)(_period*1000000.0); // pfold = 1- pfnew*pfnew; // pfnew = pow(pfnew,0.25); for(it = lruQueue.begin();it != lruQueue.end();it++){ (*it).weight = (*it).m_histOld + (*it).m_histNew ; (*it).weight = (*it).weight * getWeight((*it).fileId); // cout<<"for file <"<<it->fileId<<","<<it->segId<<">,"<<"old hist = "<<(*it).m_histOld<<",new hist ="<<(*it).m_histNew<<",weight = "<<it->weight<<",the weight of file "<<it->fileId<<" is "<<getWeight(it->fileId)<<endl; // <<",weight = "<<(*it).weight<<endl; /*if(minHistNew > (*it).m_histNew){ minHistNewIt = it; minHistNew = (*it).m_histNew; }*/ if( (*it).weight < minWeight){ minWeight = (*it).weight; minHistIt = it; } } /* if(minHistNew == 0){ eliminateBlockPtr = *minHistNewIt; minIt = minHistNewIt; }else{ eliminateBlockPtr = *minHistIt; minIt = minHistIt; }*/ eliminateBlockPtr = *minHistIt; minIt = minHistIt; // cout<<"delete "<< (*minIt).fileId <<" "<<(*minIt).segId<<endl; ofileId = eliminateBlockPtr.fileId; osegId = eliminateBlockPtr.segId; // delete eliminateBlockPtr; lruQueue.erase(minIt); AddBlock(fileId,segId); } int DBufferDWS::AddBlock(int fileId,int segId){ DWSBlockInfo temp(fileId,segId); lruQueue.push_back(temp); return 0; } int DBufferDWS::getInLine( int clientId){ isOnline[clientId] = true; //cout<<"client "<<clientId<<" is on line"<<endl; return 0; } int DBufferDWS::getOutLine( int clientId){ isOnline[clientId] = false; return 0; } int DBufferDWS::addNewClient( int clientId, int fileId){ //check if exist unsigned int curClient; for(size_t i = 0;i<FileVisitors[fileId].size();i++){ curClient = FileVisitors[fileId][i]; if(curClient == clientId){ // cout<<"is already in client list"<<endl; return -1; } } //add to the list FileVisitors[fileId].push_back(clientId); /* cout<<"the file clients:"<<endl; map<unsigned int,vector<unsigned int> >::iterator it; for(it = FileVisitors.begin();it!=FileVisitors.end();it++){ cout<<"for file "<<it->first<<":"; for(int i=0;i<FileVisitors[it->first].size();i++){ cout<<FileVisitors[it->first][i]<<" "; } cout<<endl; }*/ return 0; } int DBufferDWS::getWeight( int fileId){ unsigned int curClient; int weight = 0; for(size_t i = 0;i<FileVisitors[fileId].size();i++){ curClient = FileVisitors[fileId][i]; if(isOnline[curClient]==true){ //cout<<"client "<<curClient<<" is on line"<<endl; weight++; } } return weight; } <file_sep>#include "dbuffer.h" DBuffer::DBuffer(int blockSize,int blockNum){ // m_blockSize = blockSize; // m_blockNum = blockNum; //// pthread_cond_init(&m_notEmptyCond,NULL); //// pthread_cond_init(&m_notFullCond,NULL); //// pthread_mutex_init(&m_mutex,NULL); // // m_blockList.clear(); // m_curBlockNum = 0; m_isblockReset = false; mBlockSize = blockSize; mBlockNums = blockNum; } DBuffer::~DBuffer(){ // pthread_cond_destroy(&m_notEmptyCond); // pthread_cond_destroy(&m_notFullCond); // pthread_mutex_destroy(&m_mutex); // m_blockList.clear(); } //void DBuffer::MutexLock(){ // pthread_mutex_lock(&m_mutex); //} // //void DBuffer::MutexUnLock(){ // pthread_mutex_unlock(&m_mutex); //} // //void DBuffer::NotEmptySignal(){ // pthread_cond_signal(&m_notEmptyCond); //} // //void DBuffer::NotFullSignal(){ // pthread_cond_signal(&m_notFullCond); //} bool DBuffer::IsBlockReset(){ return m_isblockReset; } bool DBuffer::FindBlock(int fileId,int segId){//,bool locked){ //// pthread_mutex_lock(&m_mutex); // if(!m_blockList.empty()){ // std::list<Block>::iterator listIter = m_blockList.begin(); //// listIter++; // while(listIter != m_blockList.end()){ // if(listIter->fileId == fileId && listIter->segId == segId){ // return true; // } // listIter++; // } // } //// pthread_mutex_unlock(&m_mutex); return false; } //bool DBuffer::FindAndAdjustBlock(int fileId,int segId){ //// if(!m_blockList.empty()){ //// std::list<Block>::iterator listIter = m_blockList.begin(); //// while(listIter != m_blockList.end()){ //// if(listIter->fileId == fileId && listIter->segId == segId){ //// Block block = *listIter; //// m_blockList.erase(listIter); //// m_blockList.push_front(block); //// return true; //// } //// listIter++; //// } //// } // // return false; //} bool DBuffer::Read(int fileId,int segId){ //// pthread_mutex_lock(&m_mutex); // if(m_blockList.empty()){ //// pthread_mutex_unlock(&m_mutex); // return false; // } // if(!(m_blockList.front().fileId == fileId && m_blockList.front().segId == segId)){ //// pthread_cond_signal(&m_notFullCond); // if(!FindAndAdjustBlock(fileId,segId)){ //// NS_LOG_UNCOND("Not find fileId:" << fileId << ",segId" << segId); //// pthread_mutex_unlock(&m_mutex); // return false; //// pthread_cond_wait(&m_notEmptyCond,&m_mutex); // } // } // //// pthread_mutex_unlock(&m_mutex); return true; } void DBuffer::Write(int fileId,int segId,int &ofileId,int &osegId){ // pthread_mutex_lock(&m_mutex); // ofileId = -1; // osegId = -1; // if(m_curBlockNum < m_blockNum){ // m_blockList.push_front(Block(fileId,segId)); // m_curBlockNum++; // } // else{ // Strategy(fileId,segId,ofileId,osegId); // } // pthread_cond_signal(&m_notEmptyCond); // if(m_curBlockNum == m_blockNum) // pthread_cond_wait(&m_notFullCond,&m_mutex); // pthread_mutex_unlock(&m_mutex); } //LRU算法 void DBuffer::Strategy(int fileId,int segId,int &ofileId,int &osegId){ // list<Block>::iterator listIter = m_blockList.end(); // listIter--; // ofileId = listIter->fileId; // osegId = listIter->segId; // m_blockList.erase(listIter); // m_blockList.push_front(Block(fileId,segId)); } #if 0 //测试用 static bool isRunning = true; static int requestFileId = -1; static int requestSegId = -1; pthread_mutex_t requestMutex; int RandomI(int i){ return (rand() / (RAND_MAX * 1.0)) * i; } void *ThreadToWrite(void *arg){ DBuffer *ptr = (DBuffer *)arg; int times = 0; while(isRunning){ int fileId = RandomI(10); int segId = RandomI(1000); pthread_mutex_lock(&requestMutex); if(requestFileId != -1){ fileId = requestFileId; segId = requestSegId; requestFileId = -1; requestSegId = -1; } pthread_mutex_unlock(&requestMutex); ptr->Write(NULL,0,fileId,segId); std::cout << "WRITE:" << times << std::endl; times++; ptr->PrintBuffer(); } ptr->NotEmptySignal(); std::cout << "Write Finish" << std::endl; return 0; } void *ThreadToRead(void *arg){ DBuffer *ptr = (DBuffer *)arg; int times = 0; while(isRunning){ int fileId = RandomI(10); int segId = RandomI(1000); ptr->MutexLock(); if(!(ptr->FindAndAdjustBlock(fileId,segId))){ pthread_mutex_lock(&requestMutex); requestFileId = fileId; requestSegId = segId; pthread_mutex_unlock(&requestMutex); } ptr->MutexUnLock(); ptr->Read(NULL,0,fileId,segId); std::cout << "READ:" << times << std::endl; times++; ptr->PrintBuffer(); } ptr->NotFullSignal(); std::cout << "Read Finish" << std::endl; return 0; } void IntHandler(int sig){ isRunning = false; } int main(int argc,char *argv[]){ DBuffer dbuffer(20,10); pthread_t tidRead,tidWrite; signal(SIGINT,IntHandler); pthread_mutex_init(&requestMutex,NULL); pthread_create(&tidRead,NULL,ThreadToRead,&dbuffer); pthread_create(&tidWrite,NULL,ThreadToWrite,&dbuffer); pthread_join(tidRead,NULL); pthread_join(tidWrite,NULL); pthread_mutex_destroy(&requestMutex); std::cout << "Finish" << std::endl; return 0; } #endif <file_sep>#ifndef __LOG_H__ #define __LOG_H__ #include <iostream> #include <sys/time.h> using namespace std; #define MY_LOG_UNCOND 0 #define MY_LOG_INFO 1 #define MY_LOG_ERR 2 #ifndef CUR_LOG_LEVEL #define CUR_LOG_LEVEL 0 #endif extern timeval globalStartTime; extern MyTimer globalTimer; #define LOG(level,msg) \ { \ timeval localEndTime; \ gettimeofday(&localEndTime,NULL); \ if(level == 1) \ cout << "At:" << (((localEndTime.tv_sec - globalStartTime.tv_sec) + \ (localEndTime.tv_usec - globalStartTime.tv_usec) / 1000000.0) / globalTimer.getMultiple()) \ << " " << msg << endl; \ else if(level == 2) \ cerr << msg << endl; \ } #define LOG_INFO(msg) LOG(1,msg) #define LOG_WRITE(msg,ofs)\ { \ timeval localEndTime; \ gettimeofday(&localEndTime,NULL); \ ofs << "At:" << (((localEndTime.tv_sec - globalStartTime.tv_sec) + \ (localEndTime.tv_usec - globalStartTime.tv_usec) / 1000000.0) / globalTimer.getMultiple()) \ << " " << msg << endl; \ } #define LOG_DISK(ofs,msg) \ { \ timeval localEndTime; \ gettimeofday(&localEndTime,NULL); \ ofs << (((localEndTime.tv_sec - globalStartTime.tv_sec) + \ (localEndTime.tv_usec - globalStartTime.tv_usec) / 1000000.0) / globalTimer.getMultiple()) \ << " " << msg << endl; \ } #define LOG_ERR(msg) LOG(2,msg) #endif <file_sep>#ifndef BUFMANAGERBYLFRU_H #define BUFMANAGERBYLFRU_H #include "dbuffer.h" #include <sys/time.h> using namespace std; typedef struct LFRUBlockInfoo{ unsigned int fileId; unsigned int segId; double weight; int periodCounter; // unsigned long lastAccessTime; struct timeval lastAccessTime; }LFRUBlockInfoo; class DBufferLFRU : public DBuffer{ public: DBufferLFRU(int blockSize,int blockNums,int period); virtual ~DBufferLFRU(); virtual bool Read(int fileId,int segId); virtual void Write(int fileId,int segId,int &ofileId,int &osegId); virtual void Strategy(int fileId,int segId,int &ofileId,int &osegId); virtual bool FindBlock(int fileId,int segId); int AddBlock(int fileId,int segId); void BlockReset(); private: list<LFRUBlockInfoo> buf; // unsigned long recallTime; struct timeval recallTime; struct timeval t0; // unsigned long t0; unsigned int _period; // int mBlockSize; // int mBlockNums; }; #endif <file_sep>/* * myclient.cpp * * Created on: 2013-2-21 * Author: zhaojun */ #include "myclient.h" #include <sys/epoll.h> #include <sys/socket.h> #include <netinet/in.h> #include <memory.h> #include <arpa/inet.h> #include <stdlib.h> #include <netinet/tcp.h> #include <sstream> #include <iostream> #include "log.h" void *ThreadToClient(void *arg){ MyClient *client = (MyClient *)arg; client->Run(); return NULL; } MyClient::MyClient(ModelAssemble *model,int blockSize,int perSendSize, double bandWidth,int blockNums,int clientNum,int serverPort,int clientPort,int devNums, int clientNums,char **clusterAddress,char *serverAddress,char *bufferStrategy, int period,double lrfuLambda,bool isRepeat){ mModel = model; mClientNum = clientNum; mBlockSize = blockSize / 1000; mJumpSeg = 0; mPlayerStatus = PLAY; mMaxSegId = 2000; Run(); } MyClient::~MyClient(){ } void MyClient::Init(){ } //int MyClient::JudgeCluster(char *address){ // for(int i = 0;i < mDevNums;i++){ // if(strcmp(address,mClusterAddress[i]) == 0) // return i; // } // return -1; //} void MyClient::Run(){ fstream iofs; stringstream sstream; sstream.str(""); sstream << "data/requestFile" << mClientNum << ".log"; string requestFilename = sstream.str(); iofs.open(requestFilename.c_str(),ios::out); mFileId = mModel->GetStartFileId(); mSegId = mModel->GetStartSegId(); iofs << mFileId << endl; iofs << mSegId << endl; long long leftTime = mModel->GetStartTime(mClientNum) * 1000000; iofs << leftTime << endl; int times = 0; bool firstTime = true; while(times < 4000){ if(firstTime){ unsigned int length = mModel->GslRandLogNormal(mPlayerStatus); mJumpSeg = length / 4; firstTime = false; continue; } if(mJumpSeg == 0){ mPlayerStatus = mModel->GetNextStatus(mPlayerStatus); unsigned int length = mModel->GslRandLogNormal(mPlayerStatus); mJumpSeg = length / 4; if(mJumpSeg == 0) mJumpSeg++; if(mPlayerStatus == FORWARD){ mSegId += mJumpSeg; if(mSegId > mMaxSegId){ mSegId = 1; } mJumpSeg = 0; mModel->AdjustHotPlace(mFileId,mSegId); } else if(mPlayerStatus == BACKWARD){ mSegId -= mJumpSeg; if(mSegId < 1) mSegId = 1; mJumpSeg = 0; // cout << "BACKWARD" << endl; mModel->AdjustHotPlace(mFileId,mSegId); } } if(mJumpSeg != 0){ mJumpSeg--; iofs << mSegId << endl; mSegId++; } times++; } iofs.close(); } bool MyClient::SearchTheReqList(int fileId,int segId){ } void MyClient::DealWithMessage(char *buf,int length){ } void MyClient::GetNextBlock(){ } <file_sep>#ifndef BUFMANAGERBYDW_H #define BUFMANAGERBYDW_H #include "dbuffer.h" #include<map> using namespace std; class DWBlockInfo{ public: DWBlockInfo(){ fileId = 0; segId = 0; weight = 0; m_histNew = 1; m_histOld = 0; } DWBlockInfo( int _fileId, int _segId):fileId(_fileId),segId(_segId){ weight = 0; m_histNew = 1; m_histOld = 0; } int fileId; int segId; double weight; struct timeval vtime; int m_histNew; int m_histOld; }; class DBufferDW: public DBuffer{ public: DBufferDW(int blockSize,int blockNums,int period); virtual ~DBufferDW(); virtual bool Read(int fileId,int segId); virtual void Write(int fileId,int segId,int &ofileId,int &osegId); virtual void Strategy(int fileId,int segId,int &ofileId,int &osegId); virtual bool FindBlock(int fileId,int segId); int AddBlock(int fileId,int segId); void BlockReset(); private: // list<DWBlockInfo> dwBuf; list<DWBlockInfo> lruQueue; pthread_mutex_t dwbuf_mutex; struct timeval _t0; int _period; int timeslot; // TimeCallBack myAlarmEvent; // int m_blockSize; // int m_blockNum; }; #endif <file_sep>/* * behaviormodel.cpp * * Created on: 2013-2-21 * Author: zhaojun */ #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <math.h> #include <algorithm> #include "modelassemble.h" #include "globalfunction.h" static const gsl_rng_type *m_t; static gsl_rng *m_r; ModelAssemble::ModelAssemble(int fileNum,double thelta,double lambda, double backZeta,double backSigma,double forZeta,double forSigma,int maxClientNum, int playToPlay,int playToPause,int playToForward,int playToBackward, int playToStop,bool isStartTogether,int hotPlaceNums){ mIsStartTogether = isStartTogether; mFileNum = fileNum; mThelta = thelta / 1000.0; mLambda = lambda / 1000.0; mBackZeta = backZeta / 1000.0; mBackSigma = backSigma / 1000.0; mForZeta = forZeta / 1000.0; mForSigma = forSigma / 1000.0; mHotPlaceNums = hotPlaceNums; mMaxClientNum = maxClientNum; MMBlock tmpBlock; tmpBlock.status = PLAY; tmpBlock.prob = playToPlay; mMMVect.push_back(tmpBlock); tmpBlock.status = PAUSE; tmpBlock.prob = playToPause; mMMVect.push_back(tmpBlock); tmpBlock.status = FORWARD; tmpBlock.prob = playToForward; mMMVect.push_back(tmpBlock); tmpBlock.status = BACKWARD; tmpBlock.prob = playToBackward; mMMVect.push_back(tmpBlock); tmpBlock.status = STOP; tmpBlock.prob = playToStop; mMMVect.push_back(tmpBlock); GslInit(); CreateStartTime(); CreateZipfDistribution(); // LOG_INFO("mMaxClientNum = " << mMaxClientNum); } ModelAssemble::~ModelAssemble(){ gsl_rng_free(m_r); mMMVect.clear(); } void ModelAssemble::GslInit(){ gsl_rng_env_setup(); m_t = gsl_rng_default; m_r = gsl_rng_alloc(m_t); } void ModelAssemble::CreateStartTime(){ double temp; mStartTime.push_back(0.0); double sum = 0.0; for(int i = 1;i < mMaxClientNum;i++){ temp = RandomF(0,1); temp = 1 - temp; temp = 0 - log(temp) / mLambda; //秒 sum += temp; mStartTime.push_back(sum); } // for(int i = 0;i < mMaxClientNum;i++) // cout << mStartTime[i] << endl; } void ModelAssemble::AdjustHotPlace(int fileId,int &segId){ if(mHotPlaceNums != -1){ int nearest = 0; int minSegNums = 1000000; // cout << mHotPlaceVect[fileId].size() << endl; for(int i = 0;i < mHotPlaceVect[fileId].size();i++){ if(mHotPlaceVect[fileId][i] < segId && (segId - mHotPlaceVect[fileId][i]) < minSegNums){ minSegNums = segId - mHotPlaceVect[fileId][i]; nearest = mHotPlaceVect[fileId][i]; } } if(minSegNums < 100){ adjustTimes++; segId = nearest; //cout << adjustTimes << endl; } } } void ModelAssemble::CreateZipfDistribution(){ double denominator = 0.0; double u; for(int i = 0;i < mFileNum;i++){ denominator += pow(i + 1,0 - mThelta); } // LOG_INFO("Thelta " << mThelta); for(int i = 0;i < mFileNum;i++){ u = pow(i + 1,0 - mThelta); u = u / denominator; mProbability.push_back(u); } for(int i = 0;i < mFileNum;i++){ if(mHotPlaceNums != -1){ for(int j = 0;j < mHotPlaceNums;j++){ int segId = RandomI(1,2000); mHotPlaceVect[i + 1].push_back(segId); //cout << (i + 1) << " " << segId << endl; } } } } int ModelAssemble::GetStartFileId(){ double temp = RandomF(0,1); double sum = 0.0; for(int i = mFileNum - 1;i >= 0;i--){ sum += mProbability[i]; if(sum > temp){ return i + 1; } } return 0; } int ModelAssemble::GetNextStatus(int curStatus){ if((curStatus == PAUSE) | (curStatus == FORWARD) | (curStatus == BACKWARD)) return PLAY; else{ int temp = RandomI(1,1000); int sum = 0; for(unsigned int i = 0;i < mMMVect.size();i++){ sum += mMMVect[i].prob; if(sum >= temp){ return mMMVect[i].status; } } } } double ModelAssemble::GslRandLogNormal(int curStatus){ double result; if(curStatus == PLAY || curStatus == BACKWARD) result = gsl_ran_lognormal(m_r,mBackZeta,mBackSigma); else if(curStatus == FORWARD) result = gsl_ran_lognormal(m_r,mForZeta,mForSigma); return result; } <file_sep>#ifndef BUFMANAGERBYLFU_H #define BUFMANAGERBYLFU_H #include "dbuffer.h" typedef struct LFUBlockInfo{ unsigned int fileId; unsigned int segId; int counts; }LFUBlockInfo; class DBufferLFU: public DBuffer{ public: DBufferLFU(int blockSize,int blockNums); virtual ~DBufferLFU(); virtual bool Read(int fileId,int segId); virtual void Write(int fileId,int segId,int &ofileId,int &osegId); virtual void Strategy(int fileId,int segId,int &ofileId,int &osegId); virtual bool FindBlock(int fileId,int segId); int AddBlock(int fileId,int segId); virtual void BlockReset(){} private: list<LFUBlockInfo> buf; // int mBlockSize; // int mBlockNums; int initial_parameter(); }; #endif <file_sep>CC=g++ -Wall -g -O2 CFLAGS= LDFLAGS=-lpthread -lgsl -lgslcblas -lm SERVER=myheap.o mytimer.o dataserver.o faketran.o globalfunction.o servermain.o myserver.o \ dbuffer.o dbufferlru.o dbufferdw.o dbufferlfru.o dbufferlfu.o dbufferlrfu.o dbufferfifo.o dbufferpr.o \ dbufferdws.o dbufferlfus.o dbufferlrus.o CLIENT=myheap.o mytimer.o dbuffer.o faketran.o globalfunction.o modelassemble.o myclient.o myclientmanage.o clientmain.o \ dbufferlru.o dbufferdw.o dbufferlfru.o dbufferlfu.o dbufferlrfu.o dbufferfifo.o dbufferpr.o OPT=optMain.o globalfunction.o LISTGENERATOR=tools/src/globalfunction.o tools/src/modelassemble.o tools/src/myclient.o tools/src/myclientmanage.o tools/src/clientmain.o all:server_exe client_exe listgenerator optResult .PHONY:all server_exe:$(SERVER) $(CC) $^ -o $@ $(CFLAGS) $(LDFLAGS) client_exe:$(CLIENT) $(CC) $^ -o $@ $(CFLAGAS) $(LDFLAGS) optResult:$(OPT) $(CC) $^ -o $@ $(CFLAGAS) $(LDFLAGS) listgenerator:$(LISTGENERATOR) $(CC) $^ -o $@ $(CFLAGAS) $(LDFLAGS) %.o:src/%.cpp $(CC) -c $^ clean: rm -rf *.o rm -rf client_exe server_exe listgenerator <file_sep>/* * mytimer.cpp * * Created on: 2013-2-19 * Author: zhaojun */ #include "mytimer.h" #include <signal.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/time.h> #include <pthread.h> #include <iostream> #include "myheap.cpp" using namespace std; void *ThreadToTimer(void *arg){ MyTimer *mytimer = (MyTimer *)arg; mytimer->Run(); return NULL; } MyTimer::MyTimer(int multiple){ m_multiple = multiple; pthread_mutex_init(&m_vectMutex,NULL); pthread_cond_init(&m_vectCond,NULL); pthread_create(&m_tid,NULL,ThreadToTimer,this); } MyTimer::~MyTimer(){ pthread_mutex_destroy(&m_vectMutex); pthread_cond_destroy(&m_vectCond); pthread_cancel(m_tid); } void MyTimer::RegisterTimer(TimerEvent event){ pthread_mutex_lock(&m_vectMutex); event.leftTime = event.leftTime * m_multiple; m_heap.PushHeap(event); pthread_cond_signal(&m_vectCond); pthread_mutex_unlock(&m_vectMutex); } void MyTimer::WakeTimer(TimerEvent event){ // char nullChar = '\0'; write(event.sockfd,event.buffer,20); } void MyTimer::CancelTimer(TimerEvent event){ //暂不提供 } void MyTimer::Run(){ int hasSleepTime = -1; while(true){ pthread_mutex_lock(&m_vectMutex); if(!m_heap.IsEmpty()){ for(int i = m_heap.Size() - 1;i >= 0;i--){ if(!m_heap.GetElement(i).isNew && hasSleepTime != -1){ // cout << "element i lefttime:" << m_heap.GetElement(i).leftTime << ",hasleeptime:" // << hasSleepTime << endl; m_heap.GetElement(i).leftTime -= hasSleepTime; if(m_heap.GetElement(i).leftTime <= 0){ WakeTimer(m_heap.GetElement(i)); m_heap.PopHeap(i); if(i < m_heap.Size()){ if(m_heap.GetElement(i).isNew){ m_heap.GetElement(i).isNew = false; cout << "bad thing happen" << endl; } } } } else m_heap.GetElement(i).isNew = false; } m_heap.AdjustHeap(); TimerEvent event = m_heap.Front(); timespec tm; timeval beginTime; timeval endTime; gettimeofday(&beginTime,NULL); int sleepTime = event.leftTime; tm.tv_nsec = (sleepTime % 1000000 + beginTime.tv_usec) * 1000; tm.tv_sec = (sleepTime) / 1000000 + beginTime.tv_sec; tm.tv_sec = tm.tv_nsec / 1000000000 + tm.tv_sec; tm.tv_nsec = tm.tv_nsec % 1000000000; pthread_cond_timedwait(&m_vectCond,&m_vectMutex,&tm); gettimeofday(&endTime,NULL); hasSleepTime = (endTime.tv_sec - beginTime.tv_sec) * 1000000 + endTime.tv_usec - beginTime.tv_usec; } else{ pthread_cond_wait(&m_vectCond,&m_vectMutex); hasSleepTime = -1; } pthread_mutex_unlock(&m_vectMutex); } } #if 0 #include <sys/epoll.h> #define THREAD_NUM 10 int startTime = 1000000; int epollfd; MyTimer timer(1); void *ThreadToRegister(void *arg){ TimerEvent event; event.isNew = true; event.leftTime = *((int *)arg); int sockfd[2]; socketpair(AF_UNIX,SOCK_STREAM,0,sockfd); event.sockfd = sockfd[1]; epoll_event ev; ev.data.fd = sockfd[0]; ev.events = EPOLLIN; epoll_ctl(epollfd,EPOLL_CTL_ADD,sockfd[0],&ev); timer.RegisterTimer(event); // cout << sockfd[0] << " has regishter" << endl; } int main(){ epollfd = epoll_create(10); epoll_event events[10]; pthread_t tid[THREAD_NUM]; int sleepTime[THREAD_NUM]; for(int i = 0;i < THREAD_NUM;i++){ sleepTime[i] = startTime * (i + 1); pthread_create(&tid[i],NULL,ThreadToRegister,&(sleepTime[i])); } while(true){ int fds = epoll_wait(epollfd,events,10,-1); for(int i = 0;i < fds;i++){ char nullChar; read(events[i].data.fd,&nullChar,1); cout << events[i].data.fd << " wake up from timer" << endl; } } for(int i = 0;i < THREAD_NUM;i++) pthread_join(tid[i],NULL); return 0; } #endif <file_sep>/* * behaviormodel.h * * Created on: 2013-2-21 * Author: zhaojun */ #ifndef BEHAVIORMODEL_H_ #define BEHAVIORMODEL_H_ #include "mymessage.h" #include "globalfunction.h" #include <vector> using namespace std; struct MMBlock{ int status; int prob; }; class ModelAssemble{ public: ModelAssemble(int fileNum,double thelta,double lambda, double zeta,double sigma,int maxClientNum, int playToPlay,int playToPause,int playToForward,int playToBackward, int playToStop,bool isStartTogether); ~ModelAssemble(); int GetNextStatus(int curStatus); int GetStartFileId(); int GetStartSegId(){return 1;} void GslInit(); void CreateZipfDistribution(); void CreateStartTime(); double GetStartTime(int clientNum){ if(mIsStartTogether) return 0; return mStartTime[clientNum - 1]; } double GslRandLogNormal(); private: int mFileNum; vector<double> mProbability; vector<double> mStartTime; double mThelta; double mLambda; double mZeta; double mSigma; int mMaxClientNum; vector<MMBlock> mMMVect; bool mIsStartTogether; }; #endif /* BEHAVIORMODEL_H_ */ <file_sep>#ifndef BUFMANAGERBYPR_H #define BUFMANAGERBYPR_H #include "dbuffer.h" #include <sys/time.h> typedef struct prBlockInfo{ int fileId; int segId; float weight; int lastTime; }prBlockInfo; class DBufferPR: public DBuffer{ public: DBufferPR(int blockSize,int blockNums); virtual ~DBufferPR(); virtual bool Read(int fileId,int segId); virtual void Write(int fileId,int segId,int &ofileId,int &osegId); virtual void Strategy(int fileId,int segId,int &ofileId,int &osegId); virtual bool FindBlock(int fileId,int segId); int AddBlock(int fileId,int segId); virtual void BlockReset(){} private: // struct timeval tv; list<prBlockInfo> prBuf; int initial_parameter(); // int mBlockSize; // int mBlockNums; int timeslot; }; #endif <file_sep>/* * main.cpp * * Created on: 2013-2-24 * Author: zhaojun */ #include "myclientmanage.h" #include "globalfunction.h" #include <sys/time.h> #include <string.h> #include <map> #include <string> #include <sstream> using namespace std; timeval globalStartTime; double globalModify; //bool globalReadList = false; //MyServer(double bandWidth,int blockSize,int perSendSize,bool isP2POpen, // int fileNum,int maxLength,int minLength,double bitRate) //MyClientManage(int serverFd,int perSendSize,int blockSize, // int blockNums,double bandWidth,int fileNum,double thelta,double lambda, // double zeta,double sigma,int playToPlay,int playToPause,int playToForward, // int playToBackward,int playToStop); int main(){ srand((unsigned int)time(NULL)); gettimeofday(&globalStartTime,NULL); // MyServer *server; MyClientManage *clientManage; std::map<std::string,std::string> keyMap; char *configFileName = "./config/simulator.cfg"; ParseConfigFile(configFileName,keyMap); double serverBand,clientBand; int blockSize,perSendSize; bool isP2POpen; int fileNum; int maxLength,minLength; double bitRate; int serverFd; int blockNums; int thelta,lambda,zeta,sigma; int forZeta,forSigma; int hotPlaces; int playToPlay,playToPause,playToForward,playToBackward,playToStop; int clientNums; int devNums; char *clusterAddress[MAX_DEV_NUM]; int serverPort; int clientPort; int clusterNum; char *serverAddress; bool isStartTogether; char *bufferStrategy; int period; int lrfuLambda; bool isRepeat; serverBand = atof(keyMap["ServerBand"].c_str()); clientBand = atof(keyMap["ClientBand"].c_str()); blockSize = atoi(keyMap["BlockSize"].c_str()); perSendSize = atoi(keyMap["PerSendSize"].c_str()); isP2POpen = !strcmp(keyMap["isP2POpen"].c_str(),"true") ? true : false; isRepeat = !strcmp(keyMap["isRepeat"].c_str(),"true") ? true : false; // globalReadList = !strcmp(keyMap["ReadList"].c_str(),"true") ? true : false; fileNum = atoi(keyMap["SourceNums"].c_str()); maxLength = atoi(keyMap["MaxLength"].c_str()); minLength = atoi(keyMap["MinLength"].c_str()); bitRate = atof(keyMap["BitRate"].c_str()); blockNums = atoi(keyMap["BlockNums"].c_str()); thelta = atoi(keyMap["Thelta"].c_str()); lambda = atoi(keyMap["Lambda"].c_str()); zeta = atoi(keyMap["BackZeta"].c_str()); sigma = atoi(keyMap["BackSigma"].c_str()); forZeta = atoi(keyMap["ForZeta"].c_str()); forSigma = atoi(keyMap["ForSigma"].c_str()); hotPlaces = atoi(keyMap["HotPlaces"].c_str()); playToPlay = atoi(keyMap["PlayToPlay"].c_str()); playToPause = atoi(keyMap["PlayToPause"].c_str()); playToForward = atoi(keyMap["PlayToForward"].c_str()); playToBackward = atoi(keyMap["PlayToBackward"].c_str()); playToStop = atoi(keyMap["PlayToStop"].c_str()); clientNums = atoi(keyMap["ClientNums"].c_str()); devNums = atoi(keyMap["DevNums"].c_str()); serverPort = atoi(keyMap["ServerPort"].c_str()); clientPort = atoi(keyMap["ClientPort"].c_str()); clusterNum = atoi(keyMap["ClusterNum"].c_str()); isStartTogether = !strcmp(keyMap["IsStartTogether"].c_str(),"true") ? true : false; globalModify = atof(keyMap["Modify"].c_str()); serverAddress = const_cast<char *>(keyMap["ServerAddress"].c_str()); bufferStrategy = const_cast<char *>(keyMap["BufferStrategy"].c_str()); period = atoi(keyMap["Period"].c_str()); lrfuLambda = atoi(keyMap["LrfuLambda"].c_str()); int multiple = atoi(keyMap["Multiple"].c_str()); stringstream sstring; for(int i = 0;i < devNums;i++){ sstring.str(""); sstring << "ClusterAddress" << (i + 1); string keyName = sstring.str(); clusterAddress[i] = const_cast<char *>(keyMap[keyName.c_str()].c_str()); } // server = new MyServer(serverBand,blockSize,perSendSize,isP2POpen,fileNum,maxLength,minLength, // bitRate,serverPort,clientPort,devNums,clientNums,clusterAddress); clientManage = new MyClientManage(serverAddress,perSendSize,blockSize,blockNums,clientBand,fileNum,thelta,lambda, zeta,sigma,forZeta,forSigma,hotPlaces,playToPlay,playToPause,playToForward,playToBackward,playToStop,clientNums,clusterAddress, serverPort,clientPort,devNums,clusterNum,isStartTogether,bufferStrategy, period,lrfuLambda,isRepeat); // clientManage->CreateClient(); keyMap.clear(); // delete server; delete clientManage; // exit(0); return 0; } <file_sep>#ifndef BUFMANAGERBYDWS_H #define BUFMANAGERBYDWS_H #include "dbuffer.h" #include<vector> #include<map> using namespace std; class DWSBlockInfo{ public: DWSBlockInfo(){ fileId = 0; segId = 0; weight = 0; m_histNew = 1; m_histOld = 1; } DWSBlockInfo( int _fileId, int _segId):fileId(_fileId),segId(_segId){ weight = 0; m_histNew = 1; m_histOld = 1; } int fileId; int segId; double weight; int m_histNew; int m_histOld; }; class DBufferDWS: public DBuffer{ public: DBufferDWS(int blockSize,int blockNums,int period); virtual ~DBufferDWS(); virtual bool Read(int fileId,int segId); virtual void Write(int fileId,int segId,int &ofileId,int &osegId); virtual void Strategy(int fileId,int segId,int &ofileId,int &osegId); virtual bool FindBlock(int fileId,int segId); int AddBlock(int fileId,int segId); void BlockReset(); public: virtual int getInLine( int clientId); virtual int getOutLine( int clientId); int getWeight(int fileId); virtual int addNewClient(int clientId, int fileId); private: // list<DWSBlockInfo> dwBuf; list<DWSBlockInfo> lruQueue; pthread_mutex_t dwbuf_mutex; struct timeval _t0; int _period; // TimeCallBack myAlarmEvent; // int m_blockSize; // int m_blockNum; map<unsigned int ,bool> isOnline;//the status of client ,online or outline //map<unsigned int,unsigned int> visitedFile;//the file that each client visit map<unsigned int,vector<unsigned int> > FileVisitors;//the files visitors; }; #endif <file_sep>/* * mymanageclient.h * * Created on: 2013-2-23 * Author: zhaojun */ #ifndef MYMANAGECLIENT_H_ #define MYMANAGECLIENT_H_ #include "myclient.h" #include "modelassemble.h" #include <vector> using namespace std; class MyClientManage{ public: MyClientManage(char *serverAddress,int perSendSize,int blockSize, int blockNums,double bandWidth,int fileNum,double thelta,double lambda, double zeta,double sigma,double forZeta,double forSigma,int hotPlaces,int playToPlay,int playToPause,int playToForward, int playToBackward,int playToStop,int clientNums,char **clusterAddress,int serverPort, int clientPort,int devNums,int clusterNum,bool isStartTogether,char *bufferStrategy, int period,int lrfuLambda,bool isRepeat); ~MyClientManage(); void CreateClient(); double GetBand() const { return mBand; } void SetBand(double band) { mBand = band; } int GetBlockNum() const { return mBlockNums; } void SetBlockNum(int blockNums) { mBlockNums = blockNums; } int GetBlockSize() const { return mBlockSize; } void SetBlockSize(int blockSize) { mBlockSize = blockSize; } int GetClientNums() const { return mClientNums; } void SetClientNums(int clientNums) { mClientNums = clientNums; } vector<MyClient*> GetClientVect() const { return mClientVect; } void SetClientVect(vector<MyClient*> clientVect) { mClientVect = clientVect; } int GetFileNum() const { return mFileNum; } void SetFileNum(int fileNum) { mFileNum = fileNum; } double GetLambda() const { return mLambda; } void SetLambda(double lambda) { mLambda = lambda; } ModelAssemble* GetModel() const { return mModel; } void SetModel(ModelAssemble* model) { mModel = model; } int GetPerSendSize() const { return mPerSendSize; } void SetPerSendSize(int perSendSize) { mPerSendSize = perSendSize; } int GetPlayToBackward() const { return mPlayToBackward; } void SetPlayToBackward(int playToBackward) { mPlayToBackward = playToBackward; } int GetPlayToForward() const { return mPlayToForward; } void SetPlayToForward(int playToForward) { mPlayToForward = playToForward; } int GetPlayToPause() const { return mPlayToPause; } void SetPlayToPause(int playToPause) { mPlayToPause = playToPause; } int GetPlayToPlay() const { return mPlayToPlay; } void SetPlayToPlay(int playToPlay) { mPlayToPlay = playToPlay; } int GetPlayToStop() const { return mPlayToStop; } void SetPlayToStop(int playToStop) { mPlayToStop = playToStop; } double GetSigma() const { return mSigma; } void SetSigma(double sigma) { mSigma = sigma; } double GetThelta() const { return mThelta; } void SetThelta(double thelta) { mThelta = thelta; } double GetZeta() const { return mZeta; } void SetZeta(double zeta) { mZeta = zeta; } pthread_t GetTid(){return mClientVect[1]->GetTid();} private: int mClientNums; vector<MyClient *> mClientVect; ModelAssemble *mModel; int mPerSendSize; int mBlockSize; int mBlockNums; double mBand; int mFileNum; double mThelta; double mLambda; double mZeta; double mSigma; int mPlayToPlay; int mPlayToPause; int mPlayToForward; int mPlayToBackward; int mPlayToStop; char **mClusterAddress; int mServerPort; int mClientPort; int mDevNums; int mClusterNum; char *mServerAddress; bool mIsStartTogether; char *mBufferStrategy; int mPeriod; double mLrfuLambda; bool mIsRepeat; }; #endif /* MYMANAGECLIENT_H_ */ <file_sep>#include "dbufferlfus.h" #include<sstream> #include<math.h> DBufferLFUS::DBufferLFUS(int blockSize,int blockNums) : DBuffer(blockSize,blockNums) { } DBufferLFUS::~DBufferLFUS(){ } void DBufferLFUS::Write(int fileId,int segId,int &ofileId,int &osegId){ ofileId = -1; osegId = -1; if(lruQueue.size() >= mBlockNums){ Strategy(fileId,segId,ofileId,osegId); } else{ AddBlock(fileId,segId); } } bool DBufferLFUS::Read(int fileId,int segId){ list<LFUSBlockInfo>::iterator it; LFUSBlockInfo readedBlock; for(it = lruQueue.begin();it!=lruQueue.end();it++){ // cout<<"block <"<<(*it)->fileId<<","<<(*it)->segId<<">"<<endl; if( (*it).fileId ==fileId && (*it).segId == segId){ // cout<<endl<<"read block "<<it->fileId<<","<<it->segId<<endl; (*it).count ++; // readedBlock = *it; // lruQueue.erase(it); break; } } if(it == lruQueue.end()){ // cout<<"in DBufferLFUS: can't find the segment <"<<fileId<<","<<segId<<">"<<endl; return false; } // else{ // lruQueue.push_back(readedBlock); // } //readBlock(fileId,segId); return true; } bool DBufferLFUS::FindBlock(int fileId,int segId){ list<LFUSBlockInfo>::iterator it; for(it = lruQueue.begin();it !=lruQueue.end();it++){ if((*it).fileId == fileId && (*it).segId == segId){ return true; } } return false; } void DBufferLFUS::Strategy(int fileId,int segId,int &ofileId,int &osegId){ // unsigned int fileId,segId; int minWeight =111111111; LFUSBlockInfo eliminateBlockPtr; list<LFUSBlockInfo>::iterator it,minHistIt,minHistNewIt,minIt; double pfnew ,pfold; struct timeval cur_tv; int minHistNew; minHistNew = minWeight; // cout<<endl<<endl<<"start eliminate:"<<endl; for(it = lruQueue.begin();it != lruQueue.end();it++){ // cout<<"for file <"<<it->fileId<<","<<it->segId<<">,"<<"count ="<<(*it).count<<",the file weight is "<<getWeight(it->fileId)<<endl; int temp = (*it).count * getWeight(it->fileId); if( temp < minWeight){ minWeight = temp; minHistIt = it; } } /* if(minHistNew == 0){ eliminateBlockPtr = *minHistNewIt; minIt = minHistNewIt; }else{ eliminateBlockPtr = *minHistIt; minIt = minHistIt; }*/ eliminateBlockPtr = *minHistIt; minIt = minHistIt; // cout<<"delete "<< (*minIt).fileId <<" "<<(*minIt).segId<<endl; ofileId = eliminateBlockPtr.fileId; osegId = eliminateBlockPtr.segId; // delete eliminateBlockPtr; lruQueue.erase(minIt); AddBlock(fileId,segId); } int DBufferLFUS::AddBlock(int fileId,int segId){ LFUSBlockInfo temp(fileId,segId); lruQueue.push_back(temp); return 0; } int DBufferLFUS::getInLine( int clientId){ isOnline[clientId] = true; //cout<<"client "<<clientId<<" is on line"<<endl; return 0; } int DBufferLFUS::getOutLine( int clientId){ isOnline[clientId] = false; return 0; } int DBufferLFUS::addNewClient( int clientId, int fileId){ //check if exist unsigned int curClient; for(size_t i = 0;i<FileVisitors[fileId].size();i++){ curClient = FileVisitors[fileId][i]; if(curClient == clientId){ // cout<<"is already in client list"<<endl; return -1; } } //add to the list FileVisitors[fileId].push_back(clientId); /* cout<<"the file clients:"<<endl; map<unsigned int,vector<unsigned int> >::iterator it; for(it = FileVisitors.begin();it!=FileVisitors.end();it++){ cout<<"for file "<<it->first<<":"; for(int i=0;i<FileVisitors[it->first].size();i++){ cout<<FileVisitors[it->first][i]<<" "; } cout<<endl; }*/ return 0; } int DBufferLFUS::getWeight( int fileId){ unsigned int curClient; int weight = 0; for(size_t i = 0;i<FileVisitors[fileId].size();i++){ curClient = FileVisitors[fileId][i]; if(isOnline[curClient]==true){ //cout<<"client "<<curClient<<" is on line"<<endl; weight++; } } return weight; } <file_sep>#include "dbufferlrus.h" #include<math.h> DBufferLRUS::DBufferLRUS(int blockSize,int blockNums) : DBuffer(blockSize,blockNums) { lruQueue.clear(); } DBufferLRUS::~DBufferLRUS(){ } void DBufferLRUS::Write(int fileId,int segId,int &ofileId,int &osegId){ ofileId = -1; osegId = -1; if(lruQueue.size() >= mBlockNums){ Strategy(fileId,segId,ofileId,osegId); } else{ AddBlock(fileId,segId); } } bool DBufferLRUS::Read(int fileId,int segId){ list<LRUSBlockInfo>::iterator it; LRUSBlockInfo readedBlock; for(it = lruQueue.begin();it!=lruQueue.end();it++){ // cout<<"block <"<<(*it)->fileId<<","<<(*it)->segId<<">"<<endl; if( (*it).fileId ==fileId && (*it).segId == segId){ readedBlock = *it; lruQueue.erase(it); break; } } if(it == lruQueue.end()){ // cout<<"in DBufferLRUS: can't find the segment <"<<fileId<<","<<segId<<">"<<endl; return false; } else{ // cout<<"read block "<<readedBlock.fileId<<","<<readedBlock.segId<<endl; lruQueue.push_back(readedBlock); } //readBlock(fileId,segId); return true; } bool DBufferLRUS::FindBlock(int fileId,int segId){ list<LRUSBlockInfo>::iterator it; for(it = lruQueue.begin();it !=lruQueue.end();it++){ if((*it).fileId == fileId && (*it).segId == segId){ return true; } } return false; } void DBufferLRUS::Strategy(int fileId,int segId,int &ofileId,int &osegId){ // unsigned int fileId,segId; int minWeight =111111111; int temp; LRUSBlockInfo eliminateBlockPtr; list<LRUSBlockInfo>::iterator it,minHistIt,minHistNewIt,minIt; int minHistNew; minHistNew = minWeight; cout<<endl<<endl; for(it = lruQueue.begin();it != lruQueue.end();it++){ temp = getWeight((*it).fileId); // cout<<"for file <"<<it->fileId<<","<<it->segId<<">,its file weight = "<<temp<<endl; if( temp < minWeight){ minWeight = temp; minHistIt = it; } } /* if(minHistNew == 0){ eliminateBlockPtr = *minHistNewIt; minIt = minHistNewIt; }else{ eliminateBlockPtr = *minHistIt; minIt = minHistIt; }*/ eliminateBlockPtr = *minHistIt; minIt = minHistIt; cout<<"delete "<< (*minIt).fileId <<" "<<(*minIt).segId<<endl; ofileId = eliminateBlockPtr.fileId; osegId = eliminateBlockPtr.segId; // delete eliminateBlockPtr; lruQueue.erase(minIt); AddBlock(fileId,segId); } int DBufferLRUS::AddBlock(int fileId,int segId){ LRUSBlockInfo temp(fileId,segId); lruQueue.push_back(temp); return 0; } int DBufferLRUS::getInLine( int clientId){ isOnline[clientId] = true; //cout<<"client "<<clientId<<" is on line"<<endl; return 0; } int DBufferLRUS::getOutLine( int clientId){ isOnline[clientId] = false; return 0; } int DBufferLRUS::addNewClient( int clientId, int fileId){ //check if exist unsigned int curClient; for(size_t i = 0;i<FileVisitors[fileId].size();i++){ curClient = FileVisitors[fileId][i]; if(curClient == clientId){ // cout<<"is already in client list"<<endl; return -1; } } //add to the list FileVisitors[fileId].push_back(clientId); /* cout<<"the file clients:"<<endl; map<unsigned int,vector<unsigned int> >::iterator it; for(it = FileVisitors.begin();it!=FileVisitors.end();it++){ cout<<"for file "<<it->first<<":"; for(int i=0;i<FileVisitors[it->first].size();i++){ cout<<FileVisitors[it->first][i]<<" "; } cout<<endl; }*/ return 0; } int DBufferLRUS::getWeight( int fileId){ unsigned int curClient; int weight = 0; for(size_t i = 0;i<FileVisitors[fileId].size();i++){ curClient = FileVisitors[fileId][i]; if(isOnline[curClient]==true){ //cout<<"client "<<curClient<<" is on line"<<endl; weight++; } } return weight; } <file_sep>#ifndef __D_BUFFER_H__ #define __D_BUFFER_H__ #include "globalfunction.h" #include <iostream> #include <pthread.h> #include <unistd.h> #include <list> #include <time.h> #include <stdlib.h> #include <signal.h> using namespace std; //struct Block{ // Block(int fileId,int segId){//,bool isLocked){ // this->fileId = fileId; // this->segId = segId; //// this->isLocked = isLocked; // } // int fileId; // int segId; //// bool isLocked; //// int freq; //}; class DBuffer{ public: DBuffer(int blockSize,int blockNum); virtual ~DBuffer(); virtual bool Read(int fileId,int segId); virtual void Write(int fileId,int segId,int &ofileId,int &osegId); // virtual bool FindAndAdjustBlock(int fileId,int segId); virtual void Strategy(int fileId,int segId,int &ofileId,int &osegId); bool IsBlockReset(); virtual void BlockReset(){} // virtual void PrintBuffer(); // void MutexLock(); // void MutexUnLock(); // void NotFullSignal(); // void NotEmptySignal(); virtual bool FindBlock(int fileId,int segId); virtual int addNewClient( int clientId, int fileId){} virtual int getInLine( int clientId){} virtual int getOutLine(unsigned int clientId){} protected: // pthread_cond_t m_notEmptyCond; // pthread_cond_t m_notFullCond; // pthread_mutex_t m_mutex; // list<Block> m_blockList; int mBlockSize;//单位为KB int mBlockNums; // int m_curBlockNum; bool m_isblockReset; }; #endif <file_sep>#!/bin/bash ssh -t [email protected] "sudo poweroff" ssh -t [email protected] "sudo poweroff" ssh -t [email protected] "sudo poweroff" ssh -t [email protected] "sudo poweroff" ssh -t [email protected] "sudo poweroff" ssh -t [email protected] "sudo poweroff" ssh -t [email protected] "sudo poweroff" ssh -t [email protected] "sudo poweroff" ssh -t [email protected] "sudo poweroff" ssh -t [email protected] "sudo poweroff" <file_sep>/* * behaviormodel.h * * Created on: 2013-2-21 * Author: zhaojun */ #ifndef BEHAVIORMODEL_H_ #define BEHAVIORMODEL_H_ #include "mymessage.h" #include "globalfunction.h" #include <vector> static int adjustTimes = 0; using namespace std; struct MMBlock{ int status; int prob; }; class ModelAssemble{ public: ModelAssemble(int fileNum,double thelta,double lambda, double backZeta,double backSigma,double forZeta,double forSigma,int maxClientNum, int playToPlay,int playToPause,int playToForward,int playToBackward, int playToStop,bool isStartTogether,int hotPlaceNums); ~ModelAssemble(); int GetNextStatus(int curStatus); int GetStartFileId(); int GetStartSegId(){return 1;} void GslInit(); void CreateZipfDistribution(); void CreateStartTime(); double GetStartTime(int clientNum){ if(mIsStartTogether) return 0; return mStartTime[clientNum - 1]; } double GslRandLogNormal(int curStatus); void AdjustHotPlace(int fileId,int &segId); private: int mFileNum; vector<double> mProbability; vector<double> mStartTime; vector<int> mHotPlaceVect[MAX_FILE_NUM + 1]; double mThelta; double mLambda; double mBackZeta; double mBackSigma; double mForZeta; double mForSigma; int mMaxClientNum; int mHotPlaceNums; vector<MMBlock> mMMVect; bool mIsStartTogether; }; #endif /* BEHAVIORMODEL_H_ */ <file_sep>/* * globalfunction.cc * * Created on: 2013-1-1 * Author: zhaojun */ #include "globalfunction.h" void Trim(std::string &s){ s.erase(0,s.find_first_not_of(" ")); s.erase(s.find_last_not_of(" ") + 1); } void ParseConfigFile(char *configFileName,std::map<std::string,std::string> &keyMap){ std::ifstream infile; infile.open(configFileName); std::string line; while(std::getline(infile,line)){ if(line.empty()) continue; Trim(line); if(line.at(0) == '#') continue; int equalPos = line.find_first_of('='); std::string key = line.substr(0,equalPos); std::string value = line.substr(equalPos + 1); Trim(key); Trim(value); keyMap.insert(std::make_pair(key,value)); // cout << key << "=" << value << endl; // if(!infile.good()) // break; } infile.close(); } int RandomI(int first,int second){ double temp = random() / (RAND_MAX * 1.0); return (int)(first + (second - first) * temp); } double RandomF(int a,int b){ double temp = random() / (RAND_MAX * 1.0); return a + (b - a) * temp; } double RandomF(double a,double b){ double temp = random() / (RAND_MAX * 1.0); return a + (b - a) * temp; } <file_sep>/* * faketran.cpp * * Created on: 2013-2-20 * Author: zhaojun */ #include "faketran.h" #include "mymessage.h" #include "log.h" FakeTran::FakeTran(){ socketpair(AF_UNIX,SOCK_STREAM,0,mSockFd); } FakeTran::~FakeTran(){ close(mSockFd[0]); close(mSockFd[1]); } void FakeTran::TranData(double bandWidth,int blockSize,int toClientNum,int oper){ //blockSize单位为KB double sleepTime = (blockSize / 1000.0) / (bandWidth / 8); TimerEvent event; event.isNew = true; event.sockfd = mSockFd[1]; event.leftTime = sleepTime * 1000000; event.leftTime -= (1000 * (globalModify - 1)); // LOG_INFO("sleep time is:" << event.leftTime); int *ptr = (int *)event.buffer; *ptr = MSG_FAKE_FIN; ptr++; *ptr = toClientNum; ptr++; *ptr = oper; // ptr++; // *ptr = segId; globalTimer.RegisterTimer(event); } void FakeTran::Active(){ char buffer[20]; int *ptr = (int *)buffer; *ptr = MSG_FAKE_FIN; ptr++; *ptr = -1; ptr++; *ptr = -1; send(mSockFd[1],buffer,20,0); } <file_sep>/* * DataServer.cpp * * Created on: 2013-2-20 * Author: zhaojun */ #include "dataserver.h" #include "globalfunction.h" DataServer::DataServer(int fileNum,int minLength,int maxLength,int blockSize, double minBitRate,double maxBitRate){ mFileNum = fileNum; for(int i = 1;i <= MAX_FILE_NUM;i++){ mFileInfo[i].bitRate = RandomF(minBitRate,maxBitRate); mFileInfo[i].fileId = i; mFileInfo[i].segNum = 0; mFileInfo[i].info.clear(); } for(int i = 1;i <= fileNum;i++){ int length = RandomI(minLength,maxLength); mFileInfo[i].segNum = (length * 1000) / blockSize; } } DataServer::~DataServer(){ for(int i = 1;i <= mFileNum;i++){ mFileInfo[i].info.clear(); } } int DataServer::SearchBestClient(int fileId,int segId){ int bestClient = -1; int minLinked = 1000000; if(!mFileInfo[fileId].info.empty()){ list<FileInfoBlock>::iterator iter = mFileInfo[fileId].info.begin(); while(iter != mFileInfo[fileId].info.end()){ if(iter->segId == segId && mClientLinks[iter->clientNum] < minLinked && mClientLinks[iter->clientNum] <= (MAX_CLIENT_LINKS * 2)){ minLinked = mClientLinks[iter->clientNum]; bestClient = iter->clientNum; } iter++; } } if(bestClient != -1){ mClientLinks[bestClient]++; } return bestClient; } void DataServer::GetFileInfo(int fileId,double *bitRate,int *segNum){ *bitRate = mFileInfo[fileId].bitRate; *segNum = mFileInfo[fileId].segNum; } void DataServer::InsertIntoIndex(int fileId,int segId,int clientNum,int linkedNum){ DeleteFromIndex(fileId,segId,clientNum); FileInfoBlock fileInfoBlock; // fileInfoBlock.linkedNum = linkedNum; fileInfoBlock.clientNum = clientNum; mClientLinks[clientNum] = linkedNum; fileInfoBlock.segId = segId; mFileInfo[fileId].info.push_back(fileInfoBlock); } void DataServer::DeleteFromIndex(int fileId,int segId,int clientNum){ list<FileInfoBlock>::iterator iter = mFileInfo[fileId].info.begin(); while(iter != mFileInfo[fileId].info.end()){ if(iter->segId == segId && iter->clientNum == clientNum){ list<FileInfoBlock>::iterator tmpIter = iter; iter++; mFileInfo[fileId].info.erase(tmpIter); continue; } iter++; } } <file_sep>/* * myserver.h * * Created on: 2013-2-20 * Author: zhaojun */ #ifndef MYSERVER_H_ #define MYSERVER_H_ #include "dataserver.h" #include "mytimer.h" #include "faketran.h" #include "mymessage.h" //add by sunpy@0518 #include "dbuffer.h" #include "dbufferlru.h" #include "dbufferpr.h" #include "dbufferdw.h" #include "dbufferdws.h" #include "dbufferlfru.h" #include "dbufferlfu.h" #include "dbufferlfus.h" #include "dbufferlrus.h" #include "dbufferlrfu.h" #include "dbufferfifo.h" //add end @0518 #include <sys/socket.h> #include <sys/epoll.h> #include <list> #include <fstream> class MyServer{ public: MyServer(double bandWidth,int blockSize,int blockNums,string bufStrategy,int period,double lrfuLambda,int perSendSize,bool isP2POpen, int fileNum,int maxLength,int minLength,double minbitRate,double maxBitRate,int serverPort,int clientPort,int devNums, int clientNums,char **clusterAddress,int takeSampleFre,bool isUseRealDevice); ~MyServer(); void Init(); void Run(); void DealWithMessage(char *buf,int length); void GetNextBlock(); void TakeSample(); pthread_t GetTid(){return mtid;} list<ClientReqBlock>::iterator SearchTheReqList(int fileId,int segId); void ReadFromDevice(); //add by sunpy @0518 public: void writeRequestSequence(int clientId,int fileId,int segId); void initServerBuf(); void BufferReset(); private: fstream sequenceOfs; unsigned int mTotalRequest; unsigned int mReadFromServer; unsigned int mReadFromBuf; unsigned int mReadFromDisk; int mBlockNum; int mPeriod; double mLrfuLambda; string mBufStrategy; DBuffer *mDbuffer; int mBufferResetFd[2]; map<unsigned int,bool> connectStatus; //add end // int GetListenSockFd(){return mListenSockFd[1];} // int JudgeCluster(char *address); private: // int mListenSockFd[2];//AF_UNIX协议,1号对外公布,0号用于epoll循环 int mReadDevice[2]; int mREpollFd; int mTakeSample[2]; int mTakeSampleFre; int mNetSockFd; int mServerPort; int mClientPort; char *mClusterAddress[MAX_DEV_NUM]; int mDevNums; int mClientNums; // int mCurTranFd; int mEpollFd; DataServer *mDataServer; bool mIsP2POpen; double mBand; FakeTran mFakeTran; ClientInfoBlock mClientInfo[MAX_CLIENT_NUM + 1]; list<ClientReqBlock> mReqList; list<ClientReqBlock> mPreReqList; double mBlockSize; int mPerSendSize; list<ClientReqBlock>::iterator mCurReqBlock; int mFileNum; int mMinLength; int mMaxLength; double mMinBitRate; double mMaxBitRate; pthread_t mtid; pthread_t mRtid; int mLinkedNums; int mMaxBandSize; int mUsedBandSize; int mNeedSendBandSize; bool mNeverShow; ofstream mOFs; ofstream mClientDelayOfs[MAX_CLIENT_NUM + 1]; bool mIsUseRealDevice; // FileBlock mFileBlock[MAX_FILE_NUM + 1]; // int mClientLinks[MAX_CLIENT_NUM + 1]; }; #endif /* MYSERVER_H_ */ <file_sep>/* * DataServer.h * * Created on: 2013-2-20 * Author: zhaojun */ #ifndef DATASERVER_H_ #define DATASERVER_H_ #include <list> #include "mymessage.h" using namespace std; struct FileInfoBlock{ int segId; // double linkedNum; int clientNum; }; struct DataBlock{ int fileId; int segNum; double bitRate; list<FileInfoBlock> info; }; class DataServer{ public: DataServer(int fileNum,int minLength,int maxLength,int blockSize,double minBitRate,double maxBitRate); ~DataServer(); int SearchBestClient(int fileId,int segId); void GetFileInfo(int fileId,double *bitRate,int *segNum); void InsertIntoIndex(int fileId,int segId,int clientNum,int linkedNum); void DeleteFromIndex(int fileId,int segId,int clientNum); private: DataBlock mFileInfo[MAX_FILE_NUM + 1]; int mClientLinks[MAX_CLIENT_NUM + 1]; int mFileNum; }; #endif /* DATASERVER_H_ */ <file_sep>/* * mytimer.h * * Created on: 2013-2-19 * Author: zhaojun */ #ifndef MYTIMER_H_ #define MYTIMER_H_ #include "myheap.h" #include <pthread.h> #include <functional> using namespace std; struct TimerEvent{ long long leftTime; //pthread_t tid; int sockfd; bool isNew; char buffer[20]; }; inline bool operator < (const TimerEvent &event1,const TimerEvent &event2){ return event1.leftTime < event2.leftTime; } template <class T> struct myless{ bool operator()(const T &x,const T &y) const {return x < y;} }; class MyTimer{ public: MyTimer(int multiple); ~MyTimer(); void RegisterTimer(TimerEvent event); void WaitTimer(); void WakeTimer(TimerEvent event); void CancelTimer(TimerEvent event); void Run(); double getMultiple() const { return m_multiple; } void setMultiple(double multiple) { m_multiple = multiple; } private: Myheap< TimerEvent,myless<TimerEvent> > m_heap; pthread_t m_tid; pthread_mutex_t m_vectMutex; pthread_cond_t m_vectCond; double m_multiple; }; #endif /* MYTIMER_H_ */ <file_sep>/* * myclient.h * * Created on: 2013-2-21 * Author: zhaojun */ #ifndef MYCLIENT_H_ #define MYCLIENT_H_ #include "mymessage.h" #include "modelassemble.h" #include <sys/socket.h> #include <pthread.h> #include <fstream> class MyClient{ public: MyClient(ModelAssemble *model,int blockSize,int perSendSize, double bandWidth,int blockNums,int clientNum,int serverPort,int clientPort,int devNums, int clientNums,char **clusterAddress,char *serverAddress,char *bufferStrategy, int period,double lrfuLambda,bool isRepeat); ~MyClient(); void Init(); void Run(); void DealWithMessage(char *buffer,int length); void Play(); void GetNextBlock(); bool SearchTheReqList(int fileId,int segId); int getClientNum() const { return mClientNum; } pthread_t GetTid(){return mtid;} // int JudgeCluster(char *address); private: // int mListenSockFd[2]; bool mIsReadFin; int mNetSockFd; int mMyPort; int mClientPort; int mAskNum; char *mClusterAddress[MAX_DEV_NUM]; int mDevNums; int mClientNums; char *mServerAddress; int mServerPort; int mPlaySockFd[2]; // int mServerFd; int mEpollFd; ModelAssemble *mModel; int mBlockSize; int mPerSendSize; int mFileId; int mSegId; int mClientNum; int mBlockNum; bool mIsPlaying; double mBitRate; int mMaxSegId; int mPlayerStatus; int mJumpSeg; int mLinkedNums; double mBand; pthread_t mtid; string mFileName; ofstream mOFs; bool mDelay; char *mBufferStrategy; int mPeriod; double mLrfuLambda; bool mIsRepeat; int mHitTimes; int mTotalTimes; }; #endif /* MYCLIENT_H_ */ <file_sep>#!/bin/bash filename=$1 DATE=`date | sed 's/\(.*\) \(.*\):\(.*\):\(.*\) \(.*\) \(.*\)/\2\3\4/g'` mv $filename ${filename}_${DATE} <file_sep>#!/bin/bash if [ $UID != 0 ];then echo "You must be a root" exit fi function getrequestfile() { rm data/requestList_$1.log rm data/file*.log for((z=1;z<=$1;z++)) do fileseg=`sed -n '1,1p' data/requestFile$z.log`; echo $fileseg $z >> data/requestList_$1.log done } umount data mount tmpramdisk data ulimit -n 65535 sed 's/\(BufferStrategy=\).*/\1LRU/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(ServerBand=\).*/\12000/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(SourceNums=\).*/\1100/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(ClientNums=\).*/\1150/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(PerSendSize=\).*/\1200/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Special=\).*/\1false/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Prefetch=\).*/\11/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(IsStartTogether=\).*/\1false/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Lambda=\).*/\1100/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; RUNTIMES=$1 if [ ! $RUNTIMES ];then RUNTIMES=3 fi CLIENTNUMS=(115 110) CLIENTNUMSLENGTH=${#CLIENTNUMS[@]} MULTI=(2) MULTILENGTH=${#MULTI[@]} ISP2P=(false) ISP2PLENGTH=${#ISP2P[@]} THELTA=(729) THELTALENGTH=${#THELTA[@]} PLAYTOPLAY=(600) PLAYTOBACK=(400) PLAYTOFOR=(0) MMLENGTH=${#PLAYTOFOR[@]} echo "****Test****" echo "1.repeat isp2popen true or false test" echo "2.repeat multiple 2 or 4 test" echo "3.p2p effect test" echo "4.limit value" echo "5.all above(not recommended)" echo -n "enter option:";read option #repeat test if [ ${option} == 1 ] || [ ${option} == 5 ];then sed 's/\(Multiple=\).*/\1'"${MULTI[0]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Thelta=\).*/\1729/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(ClientNums=\).*/\1150/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; rm -rf data/requestFile*.log ./listgenerator getrequestfile ${CLIENTNUMS[0]} mv data/requestList_${CLIENTNUMS[0]}.log result/A_${CLIENTNUMS[0]}_${THELTA[0]}_R_${PLAYTOPLAY[0]}_${PLAYTOBACK[0]}_${PLAYTOFOR[0]}_${j}_requestList.log; for((i=0;i<$ISP2PLENGTH;i++)) do sed 's/\(isP2POpen=\).*/\1'"${ISP2P[$i]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; for((j=0;j<${RUNTIMES};j++)) do killall server_exe; killall client_exe; ./server_exe > server.log & sleep 1 ./client_exe > client.log & sleeptimes=`expr ${MULTI[0]} \* 8000` sleep $sleeptimes; killall server_exe; killall client_exe; if [ ${ISP2P[$i]} == true ];then # mv server.log result/A_${CLIENTNUMS[0]}_${THELTA[0]}_Y_R_${PLAYTOPLAY[0]}_${PLAYTOBACK[0]}_${PLAYTOFOR[0]}_${j}_server.log; mv data/result.log result/A_${CLIENTNUMS[0]}_${THELTA[0]}_Y_R_${PLAYTOPLAY[0]}_${PLAYTOBACK[0]}_${PLAYTOFOR[0]}_${j}_result.log; else # mv server.log result/A_${CLIENTNUMS[0]}_${THELTA[0]}_N_R_${PLAYTOPLAY[0]}_${PLAYTOBACK[0]}_${PLAYTOFOR[0]}_${j}_server.log; mv data/result.log result/A_${CLIENTNUMS[0]}_${THELTA[0]}_N_R_${PLAYTOPLAY[0]}_${PLAYTOBACK[0]}_${PLAYTOFOR[0]}_${j}_result.log; fi done done fi if [ ${option} == 2 ] || [ ${option} == 5 ];then sed 's/\(ClientNums=\).*/\1'"${CLIENTNUMS[0]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(isP2POpen=\).*/\1'"${ISP2P[0]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Thelta=\).*/\1'"${THELTA[0]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; rm -rf data/requestFile*.log ./listgenerator getrequestfile ${CLIENTNUMS[0]} mv data/requestList_${CLIENTNUMS[0]}.log result/B_${CLIENTNUMS[0]}_${THELTA[0]}_R_${PLAYTOPLAY[0]}_${PLAYTOBACK[0]}_${PLAYTOFOR[0]}_requestList.log for((i=0;i<$MULTILENGTH;i++)) do sed 's/\(Multiple=\).*/\1'"${MULTI[$i]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; for((j=0;j<1;j++)) do killall server_exe; killall client_exe; ./server_exe > server.log & sleep 1 ./client_exe > client.log & if [ ${MULTI[$i]} == 2 ];then sleeptimes=`expr ${MULTI[$i]} \* 8000` else sleeptimes=`expr ${MULTI[$i]} \* 8000` fi sleep $sleeptimes killall server_exe; killall client_exe; mv data/result.log result/B_${CLIENTNUMS[0]}_${THELTA[0]}_Y_R_${PLAYTOPLAY[0]}_${PLAYTOBACK[0]}_${PLAYTOFOR[0]}_${MULTI[$i]}_result.log; done done fi #p2p effect if [ ${option} == 3 ] || [ ${option} == 5 ];then sed 's/\(Multiple=\).*/\1'"${MULTI[0]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; for((l=0;l<$THELTALENGTH;l++)) do sed 's/\(Thelta=\).*/\1'"${THELTA[$l]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; for((j=0;j<$CLIENTNUMSLENGTH;j++)) do sed 's/\(ClientNums=\).*/\1'"${CLIENTNUMS[$j]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; for((i=0;i<$ISP2PLENGTH;i++)) do echo ${ISP2P[$i]} pause sed 's/\(isP2POpen=\).*/\1'"${ISP2P[$i]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; for((n=0;n<$MMLENGTH;n++)) do sed 's/\(PlayToPlay=\).*/\1'"${PLAYTOPLAY[$n]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(PlayToForward=\).*/\1'"${PLAYTOFOR[$n]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(PlayToBackward=\).*/\1'"${PLAYTOBACK[$n]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; rm -rf data/requestFile*.log ./listgenerator getrequestfile ${CLIENTNUMS[$j]} mv data/requestList_${CLIENTNUMS[$j]}.log result/C_${CLIENTNUMS[$j]}_${THELTA[$l]}_R_${PLAYTOPLAY[$n]}_${PLAYTOBACK[$n]}_${PLAYTOFOR[$n]}_requestList.log for((m=0;m<1;m++)) do killall server_exe; killall client_exe; ./server_exe > server.log & sleep 1 ./client_exe > client.log & sleeptimes=`expr ${MULTI[0]} \* 8000` sleep $sleeptimes killall server_exe; killall client_exe; if [ ${ISP2P[$i]} == true ];then mv data/result.log result/C_${CLIENTNUMS[$j]}_${THELTA[$l]}_Y_R_${PLAYTOPLAY[$n]}_${PLAYTOBACK[$n]}_${PLAYTOFOR[$n]}_${m}_result.log; else mv data/result.log result/C_${CLIENTNUMS[$j]}_${THELTA[$l]}_N_R_${PLAYTOPLAY[$n]}_${PLAYTOBACK[$n]}_${PLAYTOFOR[$n]}_${m}_result.log; fi done done done done done fi if [ $option == 4 ] || [ $option == 5 ];then sed 's/\(ClientNums=\).*/\1'"${CLIENTNUMS[0]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Multiple=\).*/\1'"${MULTI[0]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; sed 's/\(Thelta=\).*/\1'"${THELTA[0]}"'/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; for((i=0;i<$RUNTIMES;i++)) do rm -rf data/requestFile*.log ./listgenerator sed 's/\(isP2POpen=\).*/\1true/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; ./server_exe > server.log & sleep 1 ./client_exe > client.log & while true do grep "reach" server.log > temp if [ -s temp ];then break else sleep 100 fi done killall server_exe killall client_exe mv temp result/E_${THELTA[0]}_${i}_limitvalue.log mv data/result.log result/E_Y_${THELTA[0]}_${i}_result.log sed 's/\(isP2POpen=\).*/\1false/g' config/simulator.cfg > temp;cat temp > config/simulator.cfg; ./server_exe > server.log & sleep 1 ./client_exe > client.log & while true do grep "reach" server.log > temp if [ -s temp ];then break else sleep 100 fi done killall server_exe killall client_exe cat temp >> result/E_${THELTA[0]}_${i}_limitvalue.log mv data/result.log result/E_N_${THELTA[0]}_${i}_result.log done fi <file_sep>/* * main.cpp * * Created on: 2013-2-24 * Author: zhaojun */ #include "myserver.h" #include "myclientmanage.h" #include "globalfunction.h" #include "mytimer.h" #include <sys/time.h> #include <string.h> #include <map> #include <string> #include <sstream> #include "log.h" using namespace std; MyTimer globalTimer(1); timeval globalStartTime; double globalModify; //MyServer(double bandWidth,int blockSize,int perSendSize,bool isP2POpen, // int fileNum,int maxLength,int minLength,double bitRate) //MyClientManage(int serverFd,int perSendSize,int blockSize, // int blockNums,double bandWidth,int fileNum,double thelta,double lambda, // double zeta,double sigma,int playToPlay,int playToPause,int playToForward, // int playToBackward,int playToStop); int main(){ srand((unsigned int)time(NULL)); gettimeofday(&globalStartTime,NULL); MyServer *server; // MyClientManage *clientManage; std::map<std::string,std::string> keyMap; char *configFileName = "./config/simulator.cfg"; ParseConfigFile(configFileName,keyMap); double serverBand,clientBand; int blockSize,perSendSize; bool isP2POpen; int fileNum; int maxLength,minLength; double minBitRate,maxBitRate; int serverFd; int blockNums,serverBlockNums; //add by sunpy string bufferStrategy; int period; double lrfuLambda; //add end int thelta,lambda,zeta,sigma; int playToPlay,playToPause,playToForward,playToBackward,playToStop; int clientNums; int devNums; char *clusterAddress[MAX_DEV_NUM]; int serverPort; int clientPort; int sampleFre; bool isUseRealDevice; serverBand = atof(keyMap["ServerBand"].c_str()); clientBand = atof(keyMap["ClientBand"].c_str()); blockSize = atoi(keyMap["BlockSize"].c_str()); perSendSize = atoi(keyMap["PerSendSize"].c_str()); isP2POpen = !strcmp(keyMap["isP2POpen"].c_str(),"true") ? true : false; fileNum = atoi(keyMap["SourceNums"].c_str()); maxLength = atoi(keyMap["MaxLength"].c_str()); minLength = atoi(keyMap["MinLength"].c_str()); minBitRate = atof(keyMap["MinBitRate"].c_str()); maxBitRate = atof(keyMap["MaxBitRate"].c_str()); blockNums = atoi(keyMap["BlockNums"].c_str()); //add by sunpy serverBlockNums = atoi(keyMap["ServerBlockNums"].c_str()); bufferStrategy = keyMap["BufferStrategy"]; period = atoi(keyMap["Period"].c_str()); lrfuLambda = atoi(keyMap["LrfuLambda"].c_str()); //add end thelta = atoi(keyMap["Thelta"].c_str()); lambda = atoi(keyMap["Lambda"].c_str()); zeta = atoi(keyMap["Zeta"].c_str()); sigma = atoi(keyMap["Sigma"].c_str()); playToPlay = atoi(keyMap["PlayToPlay"].c_str()); playToPause = atoi(keyMap["PlayToPause"].c_str()); playToForward = atoi(keyMap["PlayToForward"].c_str()); playToBackward = atoi(keyMap["PlayToBackward"].c_str()); playToStop = atoi(keyMap["PlayToStop"].c_str()); clientNums = atoi(keyMap["ClientNums"].c_str()); devNums = atoi(keyMap["DevNums"].c_str()); serverPort = atoi(keyMap["ServerPort"].c_str()); clientPort = atoi(keyMap["ClientPort"].c_str()); sampleFre = atoi(keyMap["SampleFrequency"].c_str()); globalModify = atof(keyMap["Modify"].c_str()); isUseRealDevice = !strcmp(keyMap["IsUseRealDevice"].c_str(),"true") ? true : false; int multiple = atoi(keyMap["Multiple"].c_str()); globalTimer.setMultiple(multiple); stringstream sstring; for(int i = 0;i < devNums;i++){ sstring.str(""); sstring << "ClusterAddress" << (i + 1); string keyName = sstring.str(); clusterAddress[i] = const_cast<char *>(keyMap[keyName.c_str()].c_str()); } server = new MyServer(serverBand,blockSize,serverBlockNums,bufferStrategy,period,lrfuLambda,perSendSize,isP2POpen,fileNum,maxLength,minLength, minBitRate,maxBitRate,serverPort,clientPort,devNums,clientNums,clusterAddress,sampleFre,isUseRealDevice); // clientManage = new MyClientManage(serverFd,perSendSize,blockSize,blockNums,clientBand,fileNum,thelta,lambda, // zeta,sigma,playToPlay,playToPause,playToForward,playToBackward,playToStop,clientNums); // // cout << "create clients" << endl; // clientManage->CreateClient(); // sleep(10); pthread_join(server->GetTid(),NULL); keyMap.clear(); delete server; // delete clientManage; // exit(0); return 0; } <file_sep>/* * dbufferfifo.h * * Created on: 2013-5-13 * Author: zhaojun */ #ifndef DBUFFERFIFO_H_ #define DBUFFERFIFO_H_ #include "globalfunction.h" #include "dbuffer.h" #include <iostream> #include <pthread.h> #include <unistd.h> #include <list> #include <time.h> #include <stdlib.h> #include <signal.h> using namespace std; struct FIFOBlock{ FIFOBlock(int fileId,int segId){//,bool isLocked){ this->fileId = fileId; this->segId = segId; // this->isLocked = isLocked; } int fileId; int segId; // bool isLocked; // int freq; }; class DBufferFIFO : public DBuffer{ public: DBufferFIFO(int blockSize,int blockNum); virtual ~DBufferFIFO(); virtual bool Read(int fileId,int segId); virtual void Write(int fileId,int segId,int &ofileId,int &osegId); virtual void Strategy(int fileId,int segId,int &ofileId,int &osegId); virtual bool FindBlock(int fileId,int segId); protected: list<FIFOBlock> m_blockList; int m_curBlockNum; }; #endif /* DBUFFERFIFO_H_ */ <file_sep>#include "dbufferdw.h" #include<math.h> DBufferDW::DBufferDW(int blockSize,int blockNums,int period) : DBuffer(blockSize,blockNums) { if(period ==0) period = 500; _period = period; m_isblockReset = true; gettimeofday(&_t0,NULL); } DBufferDW::~DBufferDW(){ } void DBufferDW::BlockReset(){ list<DWBlockInfo>::iterator it; gettimeofday(&_t0,NULL); for(it = lruQueue.begin();it!=lruQueue.end();it++){ (*it).m_histOld = (*it).m_histNew; //(*it)->m_histOld = (*it)->m_histOld + (*it)->m_histNew ; (*it).m_histNew = 0; // cout<<"reset <"<<it->fileId<<","<<it->segId<<">,old hist = "<<(*it).m_histOld<<",new hist ="<<(*it).m_histNew<<",weight = "<<(*it).weight<<endl; } } void DBufferDW::Write(int fileId,int segId,int &ofileId,int &osegId){ ofileId = -1; osegId = -1; if(lruQueue.size() >= mBlockNums){ Strategy(fileId,segId,ofileId,osegId); } else{ AddBlock(fileId,segId); } } bool DBufferDW::Read(int fileId,int segId){ list<DWBlockInfo>::iterator it; DWBlockInfo readedBlock; for(it = lruQueue.begin();it!=lruQueue.end();it++){ if( (*it).fileId ==fileId && (*it).segId == segId){ (*it).m_histNew ++; // readedBlock = *it; // lruQueue.erase(it); break; } // cout<<"for file "<<it->fileId<<","<<it->segId<<",curTime = "<<it->vtime.tv_sec<<":"<<it->vtime.tv_usec<<endl; } if(it == lruQueue.end()){ // cout<<"in DBufferDW: can't find the segment <"<<fileId<<","<<segId<<">"<<endl; return false; } // else{ // lruQueue.push_back(readedBlock); // } //readBlock(fileId,segId); return true; } bool DBufferDW::FindBlock(int fileId,int segId){ list<DWBlockInfo>::iterator it; for(it = lruQueue.begin();it !=lruQueue.end();it++){ if((*it).fileId == fileId && (*it).segId == segId){ return true; } } return false; } void DBufferDW::Strategy(int fileId,int segId,int &ofileId,int &osegId){ // unsigned int fileId,segId; double maxWeight =-111111111.0; DWBlockInfo eliminateBlockPtr; list<DWBlockInfo>::iterator it,minIt; double pfnew ,pfold; struct timeval cur_tv; gettimeofday(&cur_tv,NULL); pfnew = getTimeInterval(&cur_tv,&_t0)/(1000000.0 * _period); pfold = 1 - pow(pfnew,2); pfnew = 1 + (pfnew); minIt = lruQueue.begin(); for(it = lruQueue.begin();it != lruQueue.end();it++){ (*it).weight = (*it).m_histOld + (*it).m_histNew ; // cout<<"for <"<<it->fileId<<","<<it->segId<<">,old hist = "<<(*it).m_histOld<<",new hist ="<<(*it).m_histNew<<",weight = "<<(*it).weight<<endl; if( (*it).weight > maxWeight){ maxWeight = (*it).weight; minIt = it; } // cout<<"for file "<<it->fileId<<","<<it->segId<<",curTime = "<<it->vtime.tv_sec<<":"<<it->vtime.tv_usec<<",minIt = "<<minIt->fileId<<","<<minIt->segId<<endl; } ofileId = minIt->fileId; osegId = minIt->segId; // cout<<"delete "<< ofileId <<" "<<osegId<<",weight = "<<minIt->m_histOld + minIt->m_histNew<<endl; lruQueue.erase(minIt); AddBlock(fileId,segId); } int DBufferDW::AddBlock(int fileId,int segId){ DWBlockInfo temp(fileId,segId); lruQueue.push_back(temp); return 0; } <file_sep>#!/bin/bash BUFFER=(LRU) killall exam.sh killall compare.sh killall run.sh killall server_exe killall client_exe <file_sep>/* * myheap.h * * Created on: 2013-2-19 * Author: zhaojun */ #ifndef MYHEAP_H_ #define MYHEAP_H_ #include <vector> #include <iostream> using namespace std; template <class T,class BinaryOperation> class Myheap{ public: Myheap(); // void MakeHeap(vector<T>::iterator firstIter,vector<T>::iterator secondIter){} void PushHeap(T t); T &PopHeap(int tag); void SortHeap(); void Erase(T t); T &Front(){return m_vect[0];} T &GetElement(int tag); bool IsEmpty(){return m_vect.empty();} int Size(){return m_vect.size();} void AdjustHeap(); void PrintHeap(){ for(int i = 0;i < m_vect.size();i++) cout << m_vect[i].leftTime << " "; cout << endl; } private: void _AdjustHeap(BinaryOperation binary_op); private: vector<T> m_vect; }; #endif /* MYHEAP_H_ */ <file_sep>#ifndef __MY_MESSAGE_H__ #define __MY_MESSAGE_H__ #include <memory> #include <sys/socket.h> #include <netinet/in.h> #include <list> using namespace std; #define MSG_CLIENT_JOIN 0 #define MSG_REQUEST_SEG 1 #define MSG_DELETE_SEG 2 #define MSG_FAKE_FIN 3 #define MSG_ADD_SEG 4 #define MSG_REMOTE_FAKE_FIN 5 #define MSG_BAD_REQ 6 #define MSG_REDIRECT 7 #define MSG_SEG_ASK 8 #define MSG_SEG_ACK 9 #define MSG_JOIN_ACK 10 #define MSG_CLIENT_LEAVE 11 #define MSG_CONNECT_FIN 12 #define MSG_TAKE_SAMPLE 20 #define MSG_CLIENT_DELAY 21 #define MSG_SEARCH_DEVICE 22 #define OPER_READ 0 #define OPER_WRITE 1 #define OPER_WAIT 2//先执行读,而后移除 #define SERVER_NUM 0 #define PER_SEND_PACKETS 1000 #define MAX_CLIENT_NUM 200 #define MAX_FILE_NUM 1000 #define MAX_DEV_NUM 100 #define MAX_CLIENT_LINKS 2 //seconds #define LOSS_CONNECT_TIME 5 #define LOCAL_FIN 0 #define REMOTE_FIN 1 #define NONE_FIN 2 #define START_FIN 3 enum HMMSTATUS{ EMPTY, PLAY, STOP, FORWARD, BACKWARD, PAUSE }; #define MAX_LISTEN_NUM 1000 struct ClientInfoBlock{ // int listenFd;//被动 int recvFd;//被动 // int drivListenFd; // int drivrecvFd; struct sockaddr_in address; }; struct ClientReqBlock{ int oper; int leftSize; int fileId; int segId; int clientNum; int preOper; int segNums; double bitRate; int localfin; }; //struct FileSegBlock{ // list<ClientReqBlock>::iterator reqIter; // int segId; // int clientNum; // bool isIn; //}; // //struct FileBlock{ // list<FileSegBlock> fileSegList; //}; #endif
a5b96a498b2cb3828e6b83a0470572df8fa651c8
[ "Makefile", "C++", "Shell" ]
49
C++
sunpy1106/Simulator
2f95cf1a29335353326831fda20fd5ff6dfed554
b40bf39bb73bbb2526be250a4c48aeed0145df71
refs/heads/master
<file_sep> let orgusername =document.getElementById("email"); let orgemail = document.getElementById("password"); let orgphone=document.getElementById("phone"); let orgpassword=document.getElementById("password"); let orgcpassword=document.getElementById("cpassword"); let submit = document.getElementsByClassName("btn"); if(window.localStorage){ localStorage.setItem("username","user1"); localStorage.setItem("email","<EMAIL>"); localStorage.setItem("phone","1234567892"); localStorage.setItem("password","<PASSWORD>"); localStorage.setItem("cpassword","<PASSWORD>"); let username = localStorage.getItem("username"); let email = localStorage.getItem("email"); let phone = localStorage.getItem("phone"); let password = localStorage.getItem("password"); let cpassword = localStorage.getItem("cpassword"); let message =document.getElementsByTagName("P"); function showcase(){ if(username==orgusername.value && email==orgemail.value && phone==orgphone.value && password==<PASSWORD>.value && cpassword==orgpassword.value && password==<PASSWORD>){ message.innerHTML ="Register successful..."; } else{ message.innerHTML="username or password invalid.."; } } submit.addEventListener('click',showcase) } else{ console.log("Not Supported.."); } <file_sep> const form =document.getElementById('form'); const username =document.getElementById('username'); const email=document.getElementById('email'); const phone =document.getElementById('phone'); const password =document.getElementById('password'); const cpassword =document.getElementById('cpassword'); //add event form.addEventListener('submit', (event) => { event.preventDefault(); validate(); }) //define the validate the function function validate(){ const usernameVal =username.Value.trim(); const emailVal=email.Value.trim(); const phoneVal =phone.Value.trim(); const passwordVal =password.value.trim(); const cpasswordVal =cpassword.value.trim(); //SeterrorMsg code function setErrorMsg(input, errormsgs){ const formControl =input.parentElemnet; const small = formControl.querySelector('small'); formControl.className ='.form-control.error'; small.innerText = errormsgs; } // Setsuccess code function setSuccessMsg(input){ const formControl =input.parentElemnet; formControl.className='.form-control.success'; } //validate username if(usernameVal ===""){ setErrorMsg(username,'username cannot be blank'); }else if(usernameVal <= 2){ setErrorMsg(username, 'username must be 3 character'); }else{ setSuccessMsg(username); } //validate email if(emailVal ===""){ setErrorMsg(email,'Email cannot be blank'); }else if(!isEmail(emailVal)){ setErrorMsg(email, 'Not the valid Email'); }else{ setSuccessMsg(email); } //validate the phone number //validate email if(phoneVal===""){ setErrorMsg(phone,'Phone cannot be blank'); }else if(phoneVal != 10){ setErrorMsg(username, 'Not the valid phone number'); }else{ setSuccessMsg(phone); } // validate the password if(passwordVal===""){ setErrorMsg(password,'Phone cannot be blank'); }else if(passwordVal.lenght <= 5){ setErrorMsg(password, 'Password Minimum 6 character'); }else{ setSuccessMsg(password); } // validate the confirm password if(cpasswordVal===""){ setErrorMsg(cpassword,'Phone cannot be blank'); }else if(passwordVal != cpasswordVal){ setErrorMsg(cpassword, 'Password cannot be match'); }else{ setSuccessMsg(cpassword); } // more email validate function isEmail(emailVal){ var atSymbol = emailVal.indexOf(''); if(atSymbol <1) return false; var dot = emailVal.lastindexOf('.'); if(dot <= atSymbol +3) return false; if(dot === emailVal.lenght-1) return false; return true; } }
eacddab9e61559e5d62c25d94df25b9cf4005766
[ "JavaScript" ]
2
JavaScript
Akash-Pal-oss/Project1.1
64f0e17852fd8df590abe3e7f1e9d55852f7e28c
e74f8049d2078060ca895d5f39d82ded7bd0d60f
refs/heads/master
<file_sep># Auto generated configuration file # using: # Revision: 1.400 # Source: /local/reps/CMSSW/CMSSW/Configuration/PyReleaseValidation/python/ConfigBuilder.py,v # with command line options: WtoMuNu_14TeV_cfi.py -s GEN,SIM --conditions POSTLS161_V12::All --geometry Geometry/GEMGeometry/cmsExtendedGeometryPostLS1plusGEMXML_cfi --datatier GEN-SIM --eventcontent FEVTDEBUG -n 200 --no_exec --fileout out_sim.root --evt_type WtoMuNu_14TeV_cfi.py import FWCore.ParameterSet.Config as cms process = cms.Process('SIM') # import of standard configurations process.load('Configuration.StandardSequences.Services_cff') process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi') process.load('FWCore.MessageService.MessageLogger_cfi') process.load('Configuration.EventContent.EventContent_cff') process.load('SimGeneral.MixingModule.mixNoPU_cfi') process.load('Configuration.StandardSequences.GeometryRecoDB_cff') process.load('Geometry.GEMGeometry.cmsExtendedGeometryPostLS1plusGEMXML_cfi') process.load('Configuration.StandardSequences.MagneticField_38T_cff') process.load('Configuration.StandardSequences.Generator_cff') process.load('IOMC.EventVertexGenerators.VtxSmearedRealistic8TeVCollision_cfi') process.load('GeneratorInterface.Core.genFilterSummary_cff') process.load('Configuration.StandardSequences.SimIdeal_cff') process.load('Configuration.StandardSequences.EndOfProcess_cff') process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(10000) ) # Input source process.source = cms.Source("EmptySource") process.options = cms.untracked.PSet( ) # Production Info process.configurationMetadata = cms.untracked.PSet( version = cms.untracked.string('$Revision: 1.400 $'), annotation = cms.untracked.string('WtoMuNu_14TeV_cfi.py nevts:200'), name = cms.untracked.string('PyReleaseValidation') ) # Output definition process.FEVTDEBUGoutput = cms.OutputModule("PoolOutputModule", splitLevel = cms.untracked.int32(0), eventAutoFlushCompressedSize = cms.untracked.int32(5242880), outputCommands = process.FEVTDEBUGEventContent.outputCommands, fileName = cms.untracked.string('out_sim.root'), dataset = cms.untracked.PSet( filterName = cms.untracked.string(''), dataTier = cms.untracked.string('GEN-SIM') ), SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('generation_step') ) ) # Additional output definition # Other statements process.genstepfilter.triggerConditions=cms.vstring("generation_step") from Configuration.AlCa.GlobalTag import GlobalTag process.GlobalTag = GlobalTag(process.GlobalTag, 'POSTLS161_V12::All', '') from Configuration.Generator.PythiaUEZ2starSettings_cfi import * process.generator = cms.EDFilter("Pythia6GeneratorFilter", pythiaPylistVerbosity = cms.untracked.int32(0), filterEfficiency = cms.untracked.double(1.0), pythiaHepMCVerbosity = cms.untracked.bool(False), crossSection = cms.untracked.double(1774.0), comEnergy = cms.double(14000.0), maxEventsToPrint = cms.untracked.int32(0), PythiaParameters = cms.PSet( pythiaUESettingsBlock, processParameters = cms.vstring( 'MSEL = 0 !User defined processes', 'MSUB(2) = 1 !W production', 'MDME(190,1) = 0 !W decay into dbar u', 'MDME(191,1) = 0 !W decay into dbar c', 'MDME(192,1) = 0 !W decay into dbar t', 'MDME(194,1) = 0 !W decay into sbar u', 'MDME(195,1) = 0 !W decay into sbar c', 'MDME(196,1) = 0 !W decay into sbar t', 'MDME(198,1) = 0 !W decay into bbar u', 'MDME(199,1) = 0 !W decay into bbar c', 'MDME(200,1) = 0 !W decay into bbar t', 'MDME(206,1) = 0 !W decay into e+ nu_e', 'MDME(207,1) = 1 !W decay into mu+ nu_mu', 'MDME(208,1) = 0 !W decay into tau+ nu_tau'), # This is a vector of ParameterSet names to be read, in this order parameterSets = cms.vstring('pythiaUESettings', 'processParameters' ), ) ) # select generated muons and antimuons process.genMuons = cms.EDFilter("PdgIdCandViewSelector", src = cms.InputTag("genParticles"), pdgId = cms.vint32( 13, -13 ) ) # filter by applying cuts to these generated muons process.genMuonsGEM = cms.EDFilter("CandViewSelector", src = cms.InputTag("genMuons"), cut = cms.string( "abs(eta)<2.4 & abs(eta)>0.9" ), filter = cms.bool(True) ) process.gen_mu_select = cms.Sequence(process.genMuons * process.genMuonsGEM) # Path and EndPath definitions process.generation_step = cms.Path(process.pgen * process.gen_mu_select) process.simulation_step = cms.Path(process.gen_mu_select * process.psim) process.genfiltersummary_step = cms.EndPath(process.genFilterSummary) process.endjob_step = cms.EndPath(process.endOfProcess) process.FEVTDEBUGoutput_step = cms.EndPath(process.FEVTDEBUGoutput) process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) ) # Schedule definition process.schedule = cms.Schedule(process.generation_step,process.genfiltersummary_step,process.simulation_step,process.endjob_step,process.FEVTDEBUGoutput_step) for path in process.paths: getattr(process,path)._seq = process.generator * getattr(process,path)._seq <file_sep>import os import FWCore.ParameterSet.Config as cms process = cms.PSet() process.verbose = cms.uint32( 1 ) process.inputFile = cms.string('/afs/cern.ch/user/d/dildick/work/GEM/CMSSW_6_2_0_pre5/src/gem_localrec_ana.root') process.targetDir = cms.string('/afs/cern.ch/user/d/dildick/work/GEM/CMSSW_6_2_0_pre5/src/new_dir/') process.ext = cms.string(".png") process.nregion = cms.int32( 2 ) process.nlayer = cms.int32( 2 ) process.npart = cms.int32( 8 ) <file_sep>import os import FWCore.ParameterSet.Config as cms process = cms.PSet() process.inputFile = cms.string('/afs/cern.ch/user/d/dildick/work/GEM/CMSSW_6_2_0_pre5/src/gem_digi_ana.root') process.targetDir = cms.string('/afs/cern.ch/user/d/dildick/work/GEM/CMSSW_6_2_0_pre5/src/new_dir/') process.ext = cms.string(".png") process.npads = cms.uint32( 96 ) <file_sep> #include <cstdlib> #include <cmath> #include <cassert> #include <string> #include <vector> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include "boost/lexical_cast.hpp" #include <TROOT.h> #include <TSystem.h> #include <TFile.h> #include <TKey.h> #include <TTree.h> #include <TH1D.h> #include <TH2D.h> #include <TF1.h> #include <TF2.h> #include <TFitResult.h> #include <TMath.h> #include <TCanvas.h> #include <TCut.h> #include <TGraphAsymmErrors.h> #include <TPaveStats.h> #include <TText.h> #include "FWCore/FWLite/interface/AutoLibraryLoader.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/PythonParameterSet/interface/MakeParameterSets.h" using namespace std; // void draw_geff(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, // TString to_draw, TCut denom_cut, TCut extra_num_cut, TString opt = "", int color = kBlue, int marker_st = 1, float marker_sz = 1.); void draw_occ(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt = ""); void draw_1D(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt = ""); int main( int argc, char * argv[] ) { int returnStatus_( 0 ); // Load libraries gSystem->Load( "libFWCoreFWLite" ); AutoLibraryLoader::enable(); // Check configuration file if ( argc < 2 ) { std::cout << argv[ 0 ] << " --> Usage:" << std::endl << " " << argv[ 0 ] << " [CONFIG_FILE.py]" << std::endl; returnStatus_ += 0x1; return returnStatus_; } if ( ! edm::readPSetsFrom( argv[ 1 ] )->existsAs< edm::ParameterSet >( "process" ) ) { std::cout << argv[ 0 ] << " --> ERROR:" << std::endl << " cms.PSet 'process' missing in " << argv[ 1 ] << std::endl; returnStatus_ += 0x2; return returnStatus_; } const edm::ParameterSet & process_( edm::readPSetsFrom( argv[ 1 ] )->getParameter< edm::ParameterSet >( "process" ) ); const TString inputFile_( process_.getParameter< std::string >( "inputFile" ) ); const TString targetDir_( process_.getParameter< std::string >( "targetDir" ) ); const TString ext_( process_.getParameter< std::string >( "ext" ) ); const int nregion_( process_.getParameter< int >( "nregion" ) ); const int npart_( process_.getParameter< int >( "npart" ) ); // Constants const TString analyzer_( "GEMRecHitAnalyzer" ); const TString rechits_( "GEMRecHitTree" ); const TString simTracks_( "Tracks" ); const TCut rm1("region==-1"); const TCut rp1("region==1"); const TCut l1("layer==1"); const TCut l2("layer==2"); // Open input file std::cout << std::endl << argv[ 0 ] << " --> INFO:" << std::endl << " using input file '" << inputFile_ << "'" << std::endl; TFile * fileIn_( TFile::Open( inputFile_, "UPDATE" ) ); if ( ! fileIn_ ) { std::cout << argv[ 0 ] << " --> ERROR:" << std::endl << " input file '" << inputFile_ << "' missing" << std::endl; returnStatus_ += 0x10; return returnStatus_; } TDirectory * dirAna_( (TDirectory *) fileIn_->Get( analyzer_ ) ); if ( ! dirAna_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " rechits '" << analyzer_ << "' does not exist in input file" << std::endl; returnStatus_ += 0x20; return returnStatus_; } TTree * treeHits_( (TTree *) dirAna_->Get( rechits_ ) ); if ( ! treeHits_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " rechits '" << rechits_ << "' does not exist in directory" << std::endl; returnStatus_ += 0x30; return returnStatus_; } /// occupancy draw_occ(targetDir_, "localrh_xy_rm1_l1", ext_, treeHits_, " SimHit occupancy: region-1, layer1;globalX [cm];globalY [cm]", "h_", "(100,-260,260,100,-260,260)", "globalY:globalX", rm1 && l1, "COLZ"); draw_occ(targetDir_, "localrh_xy_rm1_l2", ext_, treeHits_, " SimHit occupancy: region-1, layer2;globalX [cm];globalY [cm]", "h_", "(100,-260,260,100,-260,260)", "globalY:globalX", rm1 && l2, "COLZ"); draw_occ(targetDir_, "localrh_xy_rp1_l1", ext_, treeHits_, " SimHit occupancy: region1, layer1;globalX [cm];globalY [cm]", "h_", "(100,-260,260,100,-260,260)", "globalY:globalX", rp1 && l1, "COLZ"); draw_occ(targetDir_, "localrh_xy_rp1_l2", ext_, treeHits_, " SimHit occupancy: region1, layer2;globalX [cm];globalY [cm]", "h_", "(100,-260,260,100,-260,260)", "globalY:globalX", rp1 && l2, "COLZ"); draw_occ(targetDir_, "localrh_zr_rm1", ext_, treeHits_, " SimHit occupancy: region-1;globalZ [cm];globalR [cm]", "h_", "(200,-573,-564,110,130,240)", "sqrt(globalX*globalX+globalY*globalY):globalZ", rm1, "COLZ"); draw_occ(targetDir_, "localrh_zr_rp1", ext_, treeHits_, " SimHit occupancy: region1;globalZ [cm];globalR [cm]", "h_", "(200,564,573,110,130,240)", "sqrt(globalX*globalX+globalY*globalY):globalZ", rp1, "COLZ"); /// eta occupancy plot int region=0; int layer=0; int roll=0; TBranch *b_region; TBranch *b_layer; TBranch *b_roll; treeHits_->SetBranchAddress("region", &region, &b_region); treeHits_->SetBranchAddress("layer", &layer, &b_layer); treeHits_->SetBranchAddress("roll", &roll, &b_roll); TH1D* h = new TH1D("h", " SimHit occupancy in eta partitions; occupancy in #eta partition; entries",4*npart_,1.,1.+4*npart_); int nbytes = 0; int nb = 0; for (Long64_t jentry=0; jentry<treeHits_->GetEntriesFast();jentry++) { Long64_t ientry = treeHits_->LoadTree(jentry); if (ientry < 0) break; nb = treeHits_->GetEntry(jentry); nbytes += nb; h->Fill(roll + (layer==2? npart_:0) + (region==1? 2.*npart_:0 ) ); } TCanvas* c = new TCanvas("c","c",600,600); c->Clear(); gPad->SetLogx(0); gPad->SetLogy(0); int ibin(1); for (int iregion = 1; iregion<nregion_+1; ++iregion){ TString region( (iregion == 1) ? "-" : "+" ); for (int ilayer = 1; ilayer<nregion_+1; ++ilayer){ TString layer( TString::Itoa(ilayer,10)); for (int ipart = 1; ipart<npart_+1; ++ipart){ TString part( TString::Itoa(ipart,10)); h->GetXaxis()->SetBinLabel(ibin,region+layer+part); ++ibin; } } } h->SetMinimum(0.); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(""); c->SaveAs(targetDir_ +"localrh_globalEta" + ext_); return returnStatus_; } // void draw_geff(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, // TString to_draw, TCut denom_cut, TCut extra_num_cut, TString opt, int color, int marker_st, float marker_sz) // { // TCanvas* c( new TCanvas("c","c",600,600) ); // c->Clear(); // gPad->SetGrid(1); // t->Draw(to_draw + ">>num_" + h_name + h_bins, denom_cut && extra_num_cut, "goff"); // TH1F* num((TH1F*) gDirectory->Get("num_" + h_name)->Clone("eff_" + h_name)); // t->Draw(to_draw + ">>denom_" + h_name + h_bins, denom_cut, "goff"); // TH1F* den((TH1F*) gDirectory->Get("denom_" + h_name)->Clone("denom_" + h_name)); // TGraphAsymmErrors *eff( new TGraphAsymmErrors(num, den)); // if (!opt.Contains("same")) { // num->Reset(); // num->GetYaxis()->SetRangeUser(0.,1.05); // num->SetStats(0); // num->SetTitle(title); // num->Draw(); // } // eff->SetLineWidth(2); // eff->SetLineColor(color); // eff->SetMarkerStyle(marker_st); // eff->SetMarkerColor(color); // eff->SetMarkerSize(marker_sz); // eff->Draw(opt + " same"); // // Do fit in the flat region // bool etaPlot(c_title.Contains("eta")); // const double xmin(etaPlot ? 1.64 : -999.); // const double xmax(etaPlot ? 2.12 : 999.); // TF1 *f1 = new TF1("fit1","pol0", xmin, xmax); // TFitResultPtr r = eff->Fit("fit1","RQS"); // TPaveStats *ptstats = new TPaveStats(0.25,0.35,0.75,0.55,"brNDC"); // ptstats->SetName("stats"); // ptstats->SetBorderSize(0); // ptstats->SetLineWidth(0); // ptstats->SetFillColor(0); // ptstats->SetTextAlign(11); // ptstats->SetTextFont(42); // ptstats->SetTextSize(.05); // ptstats->SetTextColor(kRed); // ptstats->SetOptStat(0); // ptstats->SetOptFit(1111); // std::stringstream sstream; // sstream << TMath::Nint(r->Chi2()); // const TString chi2(boost::lexical_cast< std::string >(sstream.str())); // sstream.str(std::string()); // sstream << r->Ndf(); // const TString ndf(boost::lexical_cast< std::string >(sstream.str())); // sstream.str(std::string()); // sstream << TMath::Nint(r->Prob()*100); // const TString prob(boost::lexical_cast< std::string >(sstream.str())); // sstream.str(std::string()); // sstream << f1->GetParameter(0);//<< std::setprecision(4) // const TString p0(boost::lexical_cast< std::string >(sstream.str())); // sstream.str(std::string()); // sstream << std::setprecision(2) << f1->GetParError(0); // const TString p0e(boost::lexical_cast< std::string >(sstream.str())); // ptstats->AddText("#chi^{2} / ndf: " + chi2 + "/" + ndf); // // ptstats->AddText("Fit probability: " + prob + " %"); // // ptstats->AddText("Fitted efficiency = " + p0 + " #pm " + p0e + " %" ); // ptstats->AddText("Fitted efficiency: " + p0 + " %"); // ptstats->Draw("same"); // c->Modified(); // c->SaveAs(target_dir + c_title + ext); // delete num; // delete den; // delete eff; // delete c; // } void draw_occ(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt) { TCanvas* c = new TCanvas("c","c",600,600); t->Draw(to_draw + ">>" + h_name + h_bins, cut); TH2F* h = (TH2F*) gDirectory->Get(h_name)->Clone(h_name); h->SetTitle(title); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(opt); c->SaveAs(target_dir + c_title + ext); delete h; delete c; } void draw_1D(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt) { TCanvas* c = new TCanvas("c","c",600,600); t->Draw(to_draw + ">>" + h_name + h_bins, cut); TH1F* h = (TH1F*) gDirectory->Get(h_name)->Clone(h_name); h->SetTitle(title); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(opt); h->SetMinimum(0.); c->SaveAs(target_dir + c_title + ext); delete h; delete c; } <file_sep>#include <cstdlib> #include <cmath> #include <cassert> #include <string> #include <vector> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include "boost/lexical_cast.hpp" #include <TROOT.h> #include <TSystem.h> #include <TFile.h> #include <TStyle.h> #include <TKey.h> #include <TTree.h> #include <TH1D.h> #include <TH2D.h> #include <TF1.h> #include <TF2.h> #include <TFitResult.h> #include <TMath.h> #include <TCanvas.h> #include <TCut.h> #include <TGraphAsymmErrors.h> #include <TPaveStats.h> #include <TText.h> #include "FWCore/FWLite/interface/AutoLibraryLoader.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/PythonParameterSet/interface/MakeParameterSets.h" void draw_geff(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut denom_cut, TCut extra_num_cut, TString opt = "", int color = kBlue, int marker_st = 1, float marker_sz = 1.); void draw_occ(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt = ""); void draw_1D(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt = ""); void draw_bx(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt = ""); int main( int argc, char * argv[] ) { int returnStatus_( 0 ); // Load libraries gSystem->Load( "libFWCoreFWLite" ); AutoLibraryLoader::enable(); // Check configuration file if ( argc < 2 ) { std::cout << argv[ 0 ] << " --> Usage:" << std::endl << " " << argv[ 0 ] << " [CONFIG_FILE.py]" << std::endl; returnStatus_ += 0x1; return returnStatus_; } if ( ! edm::readPSetsFrom( argv[ 1 ] )->existsAs< edm::ParameterSet >( "process" ) ) { std::cout << argv[ 0 ] << " --> ERROR:" << std::endl << " cms.PSet 'process' missing in " << argv[ 1 ] << std::endl; returnStatus_ += 0x2; return returnStatus_; } const edm::ParameterSet & process_( edm::readPSetsFrom( argv[ 1 ] )->getParameter< edm::ParameterSet >( "process" ) ); const TString inputFile_( process_.getParameter< std::string >( "inputFile" ) ); const TString targetDir_( process_.getParameter< std::string >( "targetDir" ) ); const TString ext_( process_.getParameter< std::string >( "ext" ) ); const unsigned npads_(process_.getParameter< unsigned >( "npads" )); const TString npadss(boost::lexical_cast< std::string >(npads_)); // Constants const TString analyzer_("GEMDigiAnalyzer"); const TString digis_("GEMDigiTree"); const TString pads_("GEMCSCPadDigiTree"); const TString copads_("GEMCSCCoPadDigiTree"); const TString tracks_("TrackTree"); const TCut rm1("region==-1"); const TCut rp1("region==1"); const TCut l1("layer==1"); const TCut l2("layer==2"); // Open input file std::cout << std::endl << argv[ 0 ] << " --> INFO:" << std::endl << " using input file '" << inputFile_ << "'" << std::endl; TFile * fileIn_( TFile::Open( inputFile_, "UPDATE" ) ); if ( ! fileIn_ ) { std::cout << argv[ 0 ] << " --> ERROR:" << std::endl << " input file '" << inputFile_ << "' missing" << std::endl; returnStatus_ += 0x10; return returnStatus_; } TDirectory * dirAna_( (TDirectory *) fileIn_->Get( analyzer_ ) ); if ( ! dirAna_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " simhits '" << analyzer_ << "' does not exist in input file" << std::endl; returnStatus_ += 0x20; return returnStatus_; } TTree * treeDigis_( (TTree *) dirAna_->Get( digis_ ) ); if ( ! treeDigis_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " digis '" << digis_ << "' does not exist in directory" << std::endl; returnStatus_ += 0x30; return returnStatus_; } /// occupancy plots draw_occ(targetDir_, "strip_dg_xy_rm1_l1", ext_, treeDigis_, "Digi occupancy: region-1, layer1; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rm1 && l1, "COLZ"); draw_occ(targetDir_, "strip_dg_xy_rm1_l2", ext_, treeDigis_, "Digi occupancy: region-1, layer2; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rm1 && l2, "COLZ"); draw_occ(targetDir_, "strip_dg_xy_rp1_l1", ext_, treeDigis_, "Digi occupancy: region1, layer1; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rp1 && l1, "COLZ"); draw_occ(targetDir_, "strip_dg_xy_rp1_l2", ext_, treeDigis_, "Digi occupancy: region1, layer2; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rp1 && l2, "COLZ"); draw_occ(targetDir_, "strip_dg_zr_rm1", ext_, treeDigis_, "Digi occupancy: region-1; globalZ [cm]; globalR [cm]", "h_", "(200,-573,-564,55,130,240)", "g_r:g_z", rm1, "COLZ"); draw_occ(targetDir_, "strip_dg_zr_rp1", ext_, treeDigis_, "Digi occupancy: region1; globalZ [cm]; globalR [cm]", "h_", "(200,564,573,55,130,240)", "g_r:g_z", rp1, "COLZ"); draw_occ(targetDir_, "strip_dg_phistrip_rm1_l1", ext_, treeDigis_, "Digi occupancy: region-1 layer1; phi [rad]; strip", "h_", "(280,-3.141592654,3.141592654,192,0,384)", "strip:g_phi", rm1 && l1, "COLZ"); draw_occ(targetDir_, "strip_dg_phistrip_rm1_l2", ext_, treeDigis_, "Digi occupancy: region-1 layer2; phi [rad]; strip", "h_", "(280,-3.141592654,3.141592654,192,0,384)", "strip:g_phi", rm1 && l2, "COLZ"); draw_occ(targetDir_, "strip_dg_phistrip_rp1_l1", ext_, treeDigis_, "Digi occupancy: region1 layer1; phi [rad]; strip", "h_", "(280,-3.141592654,3.141592654,192,0,384)", "strip:g_phi", rp1 && l1, "COLZ"); draw_occ(targetDir_, "strip_dg_phistrip_rp1_l2", ext_, treeDigis_, "Digi occupancy: region1 layer2; phi [rad]; strip", "h_", "(280,-3.141592654,3.141592654,192,0,384)", "strip:g_phi", rp1 && l2, "COLZ"); draw_1D(targetDir_, "strip_dg_rm1_l1", ext_, treeDigis_, "Digi occupancy per strip number, region-1 layer1;strip number;entries", "h_", "(384,0.5,384.5)", "strip", rm1 && l1); draw_1D(targetDir_, "strip_dg_rm1_l2", ext_, treeDigis_, "Digi occupancy per strip number, region-1 layer2;strip number;entries", "h_", "(384,0.5,384.5)", "strip", rm1 && l2); draw_1D(targetDir_, "strip_dg_rp1_l1", ext_, treeDigis_, "Digi occupancy per strip number, region1 layer1;strip number;entries", "h_", "(384,0.5,384.5)", "strip", rp1 && l1); draw_1D(targetDir_, "strip_dg_rp1_l2", ext_, treeDigis_, "Digi occupancy per strip number, region1 layer2;strip number;entries", "h_", "(384,0.5,384.5)", "strip", rp1 && l2); /// Bunch crossing plots draw_bx(targetDir_, "strip_digi_bx_rm1_l1", ext_, treeDigis_, "Bunch crossing: region-1, layer1;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rm1 && l1); draw_bx(targetDir_, "strip_digi_bx_rm1_l2", ext_, treeDigis_, "Bunch crossing: region-1, layer2;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rm1 && l2); draw_bx(targetDir_, "strip_digi_bx_rp1_l1", ext_, treeDigis_, "Bunch crossing: region1, layer1;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rp1 && l1); draw_bx(targetDir_, "strip_digi_bx_rp1_l2", ext_, treeDigis_, "Bunch crossing: region1, layer2;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rp1 && l2); TTree * treePads_( (TTree *) dirAna_->Get( pads_ ) ); if ( ! treePads_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " pads '" << pads_ << "' does not exist in directory" << std::endl; returnStatus_ += 0x30; return returnStatus_; } /// occupancy plots draw_occ(targetDir_, "pad_dg_xy_rm1_l1", ext_, treePads_, "Pad occupancy: region-1, layer1; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rm1 && l1, "COLZ"); draw_occ(targetDir_, "pad_dg_xy_rm1_l2", ext_, treePads_, "Pad occupancy: region-1, layer2; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rm1 && l2, "COLZ"); draw_occ(targetDir_, "pad_dg_xy_rp1_l1", ext_, treePads_, "Pad occupancy: region1, layer1; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rp1 && l1, "COLZ"); draw_occ(targetDir_, "pad_dg_xy_rp1_l2", ext_, treePads_, "Pad occupancy: region1, layer2; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rp1 && l2, "COLZ"); draw_occ(targetDir_, "pad_dg_zr_rm1", ext_, treePads_, "Pad occupancy: region-1; globalZ [cm]; globalR [cm]", "h_", "(200,-573,-564,55,130,240)", "g_r:g_z", rm1, "COLZ"); draw_occ(targetDir_, "pad_dg_zr_rp1", ext_, treePads_, "Pad occupancy: region1; globalZ [cm]; globalR [cm]", "h_", "(200,564,573,55,130,240)", "g_r:g_z", rp1, "COLZ"); draw_occ(targetDir_, "pad_dg_phipad_rm1_l1", ext_, treePads_, "Pad occupancy: region-1 layer1; phi [rad]; pad", "h_", "(280,-3.141592654,3.141592654," + boost::lexical_cast< std::string >((double) (npads_/2.)) + ",0," + npadss + ")", "pad:g_phi", rm1 && l1, "COLZ"); draw_occ(targetDir_, "pad_dg_phipad_rm1_l2", ext_, treePads_, "Pad occupancy: region-1 layer2; phi [rad]; pad", "h_", "(280,-3.141592654,3.141592654," + boost::lexical_cast< std::string >((double) (npads_/2.)) + ",0," + npadss + ")", "pad:g_phi", rm1 && l2, "COLZ"); draw_occ(targetDir_, "pad_dg_phipad_rp1_l1", ext_, treePads_, "Pad occupancy: region1 layer1; phi [rad]; pad", "h_", "(280,-3.141592654,3.141592654," + boost::lexical_cast< std::string >((double) (npads_/2.)) + ",0," + npadss + ")", "pad:g_phi", rp1 && l1, "COLZ"); draw_occ(targetDir_, "pad_dg_phipad_rp1_l2", ext_, treePads_, "Pad occupancy: region1 layer2; phi [rad]; pad", "h_", "(280,-3.141592654,3.141592654," + boost::lexical_cast< std::string >((double) (npads_/2.)) + ",0," + npadss + ")", "pad:g_phi", rp1 && l2, "COLZ"); draw_1D(targetDir_, "pad_dg_rm1_l1", ext_, treePads_, "Digi occupancy per pad number, region-1 layer1;pad number;entries", "h_", "(" + npadss + ",0.5," + boost::lexical_cast< std::string >( (double) (npads_ + 0.5)) + ")", "pad", rm1 && l1); draw_1D(targetDir_, "pad_dg_rm1_l2", ext_, treePads_, "Digi occupancy per pad number, region-1 layer2;pad number;entries", "h_", "(" + npadss + ",0.5," + boost::lexical_cast< std::string >( (double) (npads_ + 0.5)) + ")", "pad", rm1 && l2); draw_1D(targetDir_, "pad_dg_rp1_l1", ext_, treePads_, "Digi occupancy per pad number, region1 layer1;pad number;entries", "h_", "(" + npadss + ",0.5," + boost::lexical_cast< std::string >( (double) (npads_ + 0.5)) + ")", "pad", rp1 && l1); draw_1D(targetDir_, "pad_dg_rp1_l2", ext_, treePads_, "Digi occupancy per pad number, region1 layer2;pad number;entries", "h_", "(" + npadss + ",0.5," + boost::lexical_cast< std::string >( (double) (npads_ + 0.5)) + ")", "pad", rp1 && l2); /// Bunch crossing plots draw_bx(targetDir_, "pad_dg_bx_rm1_l1", ext_, treePads_, "Bunch crossing: region-1, layer1;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rm1 && l1); draw_bx(targetDir_, "pad_dg_bx_rm1_l2", ext_, treePads_, "Bunch crossing: region-1, layer2;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rm1 && l2); draw_bx(targetDir_, "pad_dg_bx_rp1_l1", ext_, treePads_, "Bunch crossing: region1, layer1;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rp1 && l1); draw_bx(targetDir_, "pad_dg_bx_rp1_l2", ext_, treePads_, "Bunch crossing: region1, layer2;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rp1 && l2); TTree * treeCoPads_( (TTree *) dirAna_->Get( copads_ ) ); if ( ! treePads_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " copad '" << copads_ << "' does not exist in directory" << std::endl; returnStatus_ += 0x30; return returnStatus_; } /// occupancy plots draw_occ(targetDir_, "copad_dg_xy_rm1_l1", ext_, treeCoPads_, "Pad occupancy: region-1; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rm1, "COLZ"); draw_occ(targetDir_, "copad_dg_xy_rp1_l1", ext_, treeCoPads_, "Pad occupancy: region1; globalX [cm]; globalY [cm]", "h_", "(260,-260,260,260,-260,260)", "g_x:g_y", rp1, "COLZ"); draw_occ(targetDir_, "copad_dg_zr_rm1", ext_, treeCoPads_, "Pad occupancy: region-1; globalZ [cm]; globalR [cm]", "h_", "(200,-573,-564,55,130,240)", "g_r:g_z", rm1, "COLZ"); draw_occ(targetDir_, "copad_dg_zr_rp1", ext_, treeCoPads_, "Pad occupancy: region1; globalZ [cm]; globalR [cm]", "h_", "(200,564,573,55,130,240)", "g_r:g_z", rp1, "COLZ"); draw_occ(targetDir_, "copad_dg_phipad_rm1_l1", ext_, treeCoPads_, "Pad occupancy: region-1; phi [rad]; pad", "h_", "(280,-3.141592654,3.141592654," + boost::lexical_cast< std::string >((double) (npads_/2.)) + ",0," + npadss + ")", "pad:g_phi", rm1, "COLZ"); draw_occ(targetDir_, "copad_dg_phipad_rp1_l1", ext_, treeCoPads_, "Pad occupancy: region1; phi [rad]; pad", "h_", "(280,-3.141592654,3.141592654," + boost::lexical_cast< std::string >((double) (npads_/2.)) + ",0," + npadss + ")", "pad:g_phi", rp1, "COLZ"); draw_1D(targetDir_, "copad_dg_rm1_l1", ext_, treeCoPads_, "Digi occupancy per pad number, region-1;pad number;entries", "h_", "(" + npadss + ",0.5," + boost::lexical_cast< std::string >( (double) (npads_ + 0.5)) + ")", "pad", rm1); draw_1D(targetDir_, "copad_dg_rp1_l1", ext_, treeCoPads_, "Digi occupancy per pad number, region1;pad number;entries", "h_", "(" + npadss + ",0.5," + boost::lexical_cast< std::string >( (double) (npads_ + 0.5)) + ")", "pad", rp1); /// Bunch crossing plots draw_bx(targetDir_, "copad_dg_bx_rm1", ext_, treeCoPads_, "Bunch crossing: region-1;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rm1); draw_bx(targetDir_, "copad_dg_bx_rp1", ext_, treeCoPads_, "Bunch crossing: region1;bunch crossing;entries", "h_", "(11,-5.5,5.5)", "bx", rp1); /// Tracks TTree * treeTracks_( (TTree *) dirAna_->Get( tracks_ ) ); if ( ! treeTracks_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " tracks '" << tracks_ << "' does not exist in directory" << std::endl; returnStatus_ += 0x30; return returnStatus_; } const TCut ok_eta("TMath::Abs(eta) > 1.64 && TMath::Abs(eta) < 2.12"); const TCut ok_gL1sh("gem_sh_layer1 > 0"); const TCut ok_gL2sh("gem_sh_layer2 > 0"); const TCut ok_gL1dg("gem_dg_layer1 > 0"); const TCut ok_gL2dg("gem_dg_layer2 > 0"); const TCut ok_gL1pad("gem_pad_layer1 > 0"); const TCut ok_gL2pad("gem_pad_layer2 > 0"); /// digis draw_geff(targetDir_, "eff_eta_track_dg_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l2;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_dg_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l2;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL2dg, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_dg_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 or l2;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL2dg || ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_dg_gem_l1and2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 and l2;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL2dg && ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_dg_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta, ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_dg_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l2;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta, ok_gL2dg, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_dg_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 or l2;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta, ok_gL2dg || ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_dg_gem_l1and2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 and l2;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta, ok_gL2dg && ok_gL1dg, "P", kBlue); // digis with matched simhits draw_geff(targetDir_, "eff_eta_track_dg_sh_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 with a matched SimHit;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", ok_gL1sh, ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_dg_sh_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l2 with a matched SimHit;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", ok_gL2sh, ok_gL2dg, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_dg_sh_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 or l2 with a matched SimHit;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", ok_gL1sh || ok_gL2sh, ok_gL2dg || ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_dg_sh_gem_l1and2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 and l2 with a matched SimHit;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", ok_gL1sh && ok_gL2sh, ok_gL2dg && ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_dg_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 with a matched SimHit;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta && ok_gL1sh, ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_dg_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l2 with a matched SimHit;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta && ok_gL2sh, ok_gL2dg, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_dg_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 or l2 with a matched SimHit;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta && (ok_gL1sh || ok_gL2sh), ok_gL2dg || ok_gL1dg, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_dg_gem_l1and2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Digi in l1 and l2 with a matched SimHit;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta && (ok_gL1sh && ok_gL2sh), ok_gL2dg && ok_gL1dg, "P", kBlue); /// pads draw_geff(targetDir_, "eff_eta_track_pad_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l1;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL1pad, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_pad_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l2;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL2pad, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_pad_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l1 or l2;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL2pad || ok_gL1pad, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_pad_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l1;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta, ok_gL1pad, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_pad_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l2;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta, ok_gL2pad, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_pad_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l1 or l2;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta, ok_gL2pad || ok_gL1pad, "P", kBlue); // pads with matched simhits draw_geff(targetDir_, "eff_eta_track_pad_sh_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l1 with a matched SimHit;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", ok_gL1sh, ok_gL1pad, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_pad_sh_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l2 with a matched SimHit;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", ok_gL2sh, ok_gL2pad, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_pad_sh_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l1 or l2 with a matched SimHit;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", ok_gL1sh || ok_gL2sh, ok_gL2pad || ok_gL1pad, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_pad_sh_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l1 with a matched SimHit;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta && ok_gL1sh, ok_gL1pad, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_pad_sh_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l2 with a matched SimHit;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta && ok_gL2sh, ok_gL2pad, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_pad_sh_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM Pad in l1 or l2 with a matched SimHit;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta && (ok_gL1sh || ok_gL2sh), ok_gL2pad || ok_gL1pad, "P", kBlue); /// copads draw_geff(targetDir_, "eff_eta_track_copad_gem", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM CoPad;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL1pad && ok_gL2pad, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_copad_gem", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM CoPad;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta, ok_gL1pad && ok_gL2pad, "P", kBlue); // copads with matched simhits draw_geff(targetDir_, "eff_eta_track_copad_sh_gem", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM CoPad with a matched SimHit;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", ok_gL1sh && ok_gL2sh, ok_gL1pad && ok_gL2pad, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_copad_sh_gem", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM CoPad with a matched SimHit;SimTrack #phi [rad];Eff.", "h_", "(100,-3.141592654,3.141592654)", "phi", ok_eta && (ok_gL1sh && ok_gL2sh), ok_gL1pad && ok_gL2pad, "P", kBlue); // track plots draw_1D(targetDir_, "track_pt", ext_, treeTracks_, "Track p_{T};Track p_{T} [GeV];Entries", "h_", "(100,0,200)", "pt", ""); draw_1D(targetDir_, "track_eta", ext_, treeTracks_, "Track |#eta|;Track |#eta|;Entries", "h_", "(100,1.5,2.2)", "eta", ""); draw_1D(targetDir_, "track_phi", ext_, treeTracks_, "Track #phi;Track #phi [rad];Entries", "h_", "(100,-3.141592654,3.141592654)", "phi", ""); return returnStatus_; } void draw_geff(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut denom_cut, TCut extra_num_cut, TString opt, int color, int marker_st, float marker_sz) { TCanvas* c( new TCanvas("c","c",600,600) ); c->Clear(); gPad->SetGrid(1); gStyle->SetStatStyle(0); gStyle->SetOptStat(1110); t->Draw(to_draw + ">>num_" + h_name + h_bins, denom_cut && extra_num_cut, "goff"); TH1F* num((TH1F*) gDirectory->Get("num_" + h_name)->Clone("eff_" + h_name)); t->Draw(to_draw + ">>denom_" + h_name + h_bins, denom_cut, "goff"); TH1F* den((TH1F*) gDirectory->Get("denom_" + h_name)->Clone("denom_" + h_name)); TGraphAsymmErrors *eff( new TGraphAsymmErrors(num, den)); if (!opt.Contains("same")) { num->Reset(); num->GetYaxis()->SetRangeUser(0.,1.05); num->SetStats(0); num->SetTitle(title); num->Draw(); } eff->SetLineWidth(2); eff->SetLineColor(color); eff->SetMarkerStyle(marker_st); eff->SetMarkerColor(color); eff->SetMarkerSize(marker_sz); eff->Draw(opt + " same"); // Do fit in the flat region bool etaPlot(c_title.Contains("eta")); const double xmin(etaPlot ? 1.64 : -999.); const double xmax(etaPlot ? 2.12 : 999.); TF1 *f1 = new TF1("fit1","pol0", xmin, xmax); TFitResultPtr r = eff->Fit("fit1","RQS"); TPaveStats *ptstats = new TPaveStats(0.25,0.35,0.75,0.55,"brNDC"); ptstats->SetName("stats"); ptstats->SetBorderSize(0); ptstats->SetLineWidth(0); ptstats->SetFillColor(0); ptstats->SetTextAlign(11); ptstats->SetTextFont(42); ptstats->SetTextSize(.05); ptstats->SetTextColor(kRed); ptstats->SetOptStat(0); ptstats->SetOptFit(1111); std::stringstream sstream; sstream << TMath::Nint(r->Chi2()); const TString chi2(boost::lexical_cast< std::string >(sstream.str())); sstream.str(std::string()); sstream << r->Ndf(); const TString ndf(boost::lexical_cast< std::string >(sstream.str())); sstream.str(std::string()); sstream << TMath::Nint(r->Prob()*100); const TString prob(boost::lexical_cast< std::string >(sstream.str())); sstream.str(std::string()); sstream << std::setprecision(4) << f1->GetParameter(0) * 100; const TString p0(boost::lexical_cast< std::string >(sstream.str())); sstream.str(std::string()); sstream << std::setprecision(2) << f1->GetParError(0) * 100; const TString p0e(boost::lexical_cast< std::string >(sstream.str())); ptstats->AddText("#chi^{2} / ndf: " + chi2 + "/" + ndf); // ptstats->AddText("Fit probability: " + prob + " %"); // ptstats->AddText("Fitted efficiency = " + p0 + " #pm " + p0e + " %" ); ptstats->AddText("Fitted efficiency: " + p0 + " #pm " + p0e + " %"); ptstats->Draw("same"); TPaveText *pt = new TPaveText(0.09899329,0.9178322,0.8993289,0.9737762,"blNDC"); pt->SetName("title"); pt->SetBorderSize(1); pt->SetFillColor(0); pt->SetFillStyle(0); pt->SetTextFont(42); pt->AddText(eff->GetTitle()); pt->Draw("same"); c->Modified(); c->SaveAs(target_dir + c_title + ext); delete num; delete den; delete eff; delete c; } void draw_occ(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt) { gStyle->SetStatStyle(0); gStyle->SetOptStat(1110); TCanvas* c = new TCanvas("c","c",600,600); t->Draw(to_draw + ">>" + h_name + h_bins, cut); TH2F* h = (TH2F*) gDirectory->Get(h_name)->Clone(h_name); h->SetTitle(title); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(opt); c->SaveAs(target_dir + c_title + ext); delete h; delete c; } void draw_1D(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt) { gStyle->SetStatStyle(0); gStyle->SetOptStat(1110); TCanvas* c = new TCanvas("c","c",600,600); t->Draw(to_draw + ">>" + h_name + h_bins, cut); TH1F* h = (TH1F*) gDirectory->Get(h_name)->Clone(h_name); h->SetTitle(title); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(opt); h->SetMinimum(0.); c->SaveAs(target_dir + c_title + ext); delete h; delete c; } void draw_bx(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt) { gStyle->SetStatStyle(0); gStyle->SetOptStat(1110); TCanvas* c = new TCanvas("c","c",600,600); t->Draw(to_draw + ">>" + h_name + h_bins, cut); gPad->SetLogy(); TH1F* h = (TH1F*) gDirectory->Get(h_name)->Clone(h_name); h->SetTitle(title); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(opt); h->SetMinimum(1.); c->SaveAs(target_dir + c_title + ext); delete h; delete c; } <file_sep>#include <cstdlib> #include <cmath> #include <cassert> #include <string> #include <vector> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <algorithm> #include <iterator> #include "boost/lexical_cast.hpp" #include <TROOT.h> #include <TSystem.h> #include <TFile.h> #include <TStyle.h> #include <TKey.h> #include <TTree.h> #include <TH1D.h> #include <TH2D.h> #include <TF1.h> #include <TF2.h> #include <TFitResult.h> #include <TMath.h> #include <TCanvas.h> #include <TCut.h> #include <TGraphAsymmErrors.h> #include <TPaveStats.h> #include <TText.h> #include "FWCore/FWLite/interface/AutoLibraryLoader.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/PythonParameterSet/interface/MakeParameterSets.h" using namespace std; void draw_geff(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut denom_cut, TCut extra_num_cut, TString opt = "", int color = kBlue, int marker_st = 1, float marker_sz = 1.); void draw_occ(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt = ""); void draw_1D(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt = ""); int main( int argc, char * argv[] ) { int returnStatus_( 0 ); // Load libraries gSystem->Load( "libFWCoreFWLite" ); AutoLibraryLoader::enable(); // Check configuration file if ( argc < 2 ) { std::cout << argv[ 0 ] << " --> Usage:" << std::endl << " " << argv[ 0 ] << " [CONFIG_FILE.py]" << std::endl; returnStatus_ += 0x1; return returnStatus_; } if ( ! edm::readPSetsFrom( argv[ 1 ] )->existsAs< edm::ParameterSet >( "process" ) ) { std::cout << argv[ 0 ] << " --> ERROR:" << std::endl << " cms.PSet 'process' missing in " << argv[ 1 ] << std::endl; returnStatus_ += 0x2; return returnStatus_; } const edm::ParameterSet & process_( edm::readPSetsFrom( argv[ 1 ] )->getParameter< edm::ParameterSet >( "process" ) ); const TString inputFile_( process_.getParameter< std::string >( "inputFile" ) ); const TString targetDir_( process_.getParameter< std::string >( "targetDir" ) ); const TString ext_( process_.getParameter< std::string >( "ext" ) ); const int nregion_( process_.getParameter< int >( "nregion" ) ); const int npart_( process_.getParameter< int >( "npart" ) ); // Constants const TString analyzer_( "GEMSimHitAnalyzer" ); const TString simHits_( "GEMSimHits" ); const TString simTracks_( "Tracks" ); const TCut rm1("region==-1"); const TCut rp1("region==1"); const TCut l1("layer==1"); const TCut l2("layer==2"); std::vector<TCut> muonSelection(3); muonSelection.clear(); muonSelection.push_back("TMath::Abs(particleType)==13"); muonSelection.push_back("TMath::Abs(particleType)!=13"); muonSelection.push_back(""); std::vector<TString> titlePrefix(3); titlePrefix.clear(); titlePrefix.push_back("Muon"); titlePrefix.push_back("Non muon"); titlePrefix.push_back("All"); std::vector<TString> histSuffix(3); histSuffix.clear(); histSuffix.push_back("_muon"); histSuffix.push_back("_nonmuon"); histSuffix.push_back("_all"); // Open input file std::cout << std::endl << argv[ 0 ] << " --> INFO:" << std::endl << " using input file '" << inputFile_ << "'" << std::endl; TFile * fileIn_( TFile::Open( inputFile_, "UPDATE" ) ); if ( ! fileIn_ ) { std::cout << argv[ 0 ] << " --> ERROR:" << std::endl << " input file '" << inputFile_ << "' missing" << std::endl; returnStatus_ += 0x10; return returnStatus_; } TDirectory * dirAna_( (TDirectory *) fileIn_->Get( analyzer_ ) ); if ( ! dirAna_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " simhits '" << analyzer_ << "' does not exist in input file" << std::endl; returnStatus_ += 0x20; return returnStatus_; } TTree * treeHits_( (TTree *) dirAna_->Get( simHits_ ) ); if ( ! treeHits_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " simhits '" << simHits_ << "' does not exist in directory" << std::endl; returnStatus_ += 0x30; return returnStatus_; } gStyle->SetStatStyle(0); for (unsigned uSel = 0; uSel < 3; ++uSel){ TCut sel(muonSelection.at(uSel)); TString pre(titlePrefix.at(uSel)); TString suff(histSuffix.at(uSel)); // occupancy draw_occ(targetDir_, "sh_xy_rm1_l1" + suff, ext_, treeHits_, pre + " SimHit occupancy: region-1, layer1;globalX [cm];globalY [cm]", "h_", "(100,-260,260,100,-260,260)", "globalY:globalX", rm1 && l1 && sel, "COLZ"); draw_occ(targetDir_, "sh_xy_rm1_l2" + suff, ext_, treeHits_, pre + " SimHit occupancy: region-1, layer2;globalX [cm];globalY [cm]", "h_", "(100,-260,260,100,-260,260)", "globalY:globalX", rm1 && l2 && sel, "COLZ"); draw_occ(targetDir_, "sh_xy_rp1_l1" + suff, ext_, treeHits_, pre + " SimHit occupancy: region1, layer1;globalX [cm];globalY [cm]", "h_", "(100,-260,260,100,-260,260)", "globalY:globalX", rp1 && l1 && sel, "COLZ"); draw_occ(targetDir_, "sh_xy_rp1_l2" + suff, ext_, treeHits_, pre + " SimHit occupancy: region1, layer2;globalX [cm];globalY [cm]", "h_", "(100,-260,260,100,-260,260)", "globalY:globalX", rp1 && l2 && sel, "COLZ"); draw_occ(targetDir_, "sh_zr_rm1" + suff, ext_, treeHits_, pre + " SimHit occupancy: region-1;globalZ [cm];globalR [cm]", "h_", "(200,-573,-564,110,130,240)", "sqrt(globalX*globalX+globalY*globalY):globalZ", rm1 && sel, "COLZ"); draw_occ(targetDir_, "sh_zr_rp1" + suff, ext_, treeHits_, pre + " SimHit occupancy: region1;globalZ [cm];globalR [cm]", "h_", "(200,564,573,110,130,240)", "sqrt(globalX*globalX+globalY*globalY):globalZ", rp1 && sel, "COLZ"); // tof draw_1D(targetDir_, "sh_tof_rm1_l1" + suff, ext_, treeHits_, pre + " SimHit TOF: region-1, layer1;Time of flight [ns];entries", "h_", "(40,18,22)", "timeOfFlight", rm1 && l1 && sel); draw_1D(targetDir_, "sh_tof_rm1_l2" + suff, ext_, treeHits_, pre + " SimHit TOF: region-1, layer2;Time of flight [ns];entries", "h_", "(40,18,22)", "timeOfFlight", rm1 && l2 && sel); draw_1D(targetDir_, "sh_tof_rp1_l1" + suff, ext_, treeHits_, pre + " SimHit TOF: region1, layer1;Time of flight [ns];entries", "h_", "(40,18,22)", "timeOfFlight", rp1 && l1 && sel); draw_1D(targetDir_, "sh_tof_rp1_l2" + suff, ext_, treeHits_, pre + " SimHit TOF: region1, layer2;Time of flight [ns];entries", "h_", "(40,18,22)", "timeOfFlight", rp1 && l2 && sel); /// momentum plot TCanvas* c = new TCanvas("c","c",600,600); c->Clear(); treeHits_->Draw("pabs>>h(200,0.,200.)",sel); TH1D* h((TH1D*) gDirectory->Get("h")); gPad->SetLogx(0); gPad->SetLogy(1); h->SetTitle(pre + " SimHits absolute momentum;Momentum [GeV/c];entries"); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(""); c->SaveAs(targetDir_ +"sh_momentum" + suff + ext_); // draw_1D(targetDir_, "sh_pdgid" + suff, ext_, treeHits_, pre + " SimHit PDG Id;PDG Id;entries", // "h_", "(200,-100.,100.)", "particleType", sel); /// eta occupancy plot int region=0; int layer=0; int roll=0; int particletype=0; TBranch *b_region; TBranch *b_layer; TBranch *b_roll; TBranch *b_particleType; treeHits_->SetBranchAddress("region", &region, &b_region); treeHits_->SetBranchAddress("layer", &layer, &b_layer); treeHits_->SetBranchAddress("roll", &roll, &b_roll); treeHits_->SetBranchAddress("particleType", &particletype, &b_particleType); h = new TH1D("h", pre + " SimHit occupancy in eta partitions; occupancy in #eta partition; entries",4*npart_,1.,1.+4*npart_); int nbytes = 0; int nb = 0; for (Long64_t jentry=0; jentry<treeHits_->GetEntriesFast();jentry++) { Long64_t ientry = treeHits_->LoadTree(jentry); if (ientry < 0) break; nb = treeHits_->GetEntry(jentry); nbytes += nb; switch(uSel){ case 0: if (abs(particletype)==13) h->Fill(roll + (layer==2? npart_:0) + (region==1? 2.*npart_:0 ) ); break; case 1: if (abs(particletype)!=13) h->Fill(roll + (layer==2? npart_:0) + (region==1? 2.*npart_:0 ) ); break; case 2: h->Fill(roll + (layer==2? npart_:0) + (region==1? 2.*npart_:0 ) ); break; } } c->Clear(); gPad->SetLogx(0); gPad->SetLogy(0); int ibin(1); for (int iregion = 1; iregion<nregion_+1; ++iregion){ TString region( (iregion == 1) ? "-" : "+" ); for (int ilayer = 1; ilayer<nregion_+1; ++ilayer){ TString layer( TString::Itoa(ilayer,10)); for (int ipart = 1; ipart<npart_+1; ++ipart){ TString part( TString::Itoa(ipart,10)); h->GetXaxis()->SetBinLabel(ibin,region+layer+part); ++ibin; } } } h->SetMinimum(0.); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(""); c->SaveAs(targetDir_ +"sh_globalEta" + suff + ext_); /// energy loss plot h = new TH1D("h","",60,0.,6000.); Float_t energyLoss=0; TBranch *b_energyLoss; treeHits_->SetBranchAddress("energyLoss", &energyLoss, &b_energyLoss); for (Long64_t jentry=0; jentry<treeHits_->GetEntriesFast();jentry++) { Long64_t ientry = treeHits_->LoadTree(jentry); if (ientry < 0) break; nb = treeHits_->GetEntry(jentry); nbytes += nb; switch(uSel){ case 0: if (abs(particletype)==13) h->Fill( energyLoss*1.e9 ); break; case 1: if (abs(particletype)!=13) h->Fill( energyLoss*1.e9 ); break; case 2: h->Fill( energyLoss*1.e9 ); break; } } c->Clear(); gPad->SetLogx(0); gPad->SetLogy(0); h->SetTitle(pre + " SimHit energy loss;Energy loss [eV];entries"); h->SetMinimum(0.); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(""); c->SaveAs(targetDir_ + "sh_energyloss" + suff + ext_); } TTree * treeTracks_( (TTree *) dirAna_->Get( simTracks_ ) ); if ( ! treeTracks_ ) { std::cout << argv[ 0 ] << " --> WARNING:" << std::endl << " tracks '" << simTracks_ << "' does not exist in directory" << std::endl; returnStatus_ += 0x30; return returnStatus_; } const TCut ok_eta("TMath::Abs(eta) > 1.64 && TMath::Abs(eta) < 2.12"); const TCut ok_gL1sh("gem_sh_layer1 > 0"); const TCut ok_gL2sh("gem_sh_layer2 > 0"); draw_geff(targetDir_, "eff_eta_track_sh_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1 or GEMl2;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL1sh || ok_gL2sh, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_sh_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL1sh, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_sh_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM SimHit in GEMl2;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL2sh, "P", kBlue); draw_geff(targetDir_, "eff_eta_track_sh_gem_l1and2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1 and GEMl2;SimTrack |#eta|;Eff.", "h_", "(140,1.5,2.2)", "TMath::Abs(eta)", "", ok_gL1sh && ok_gL2sh, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_sh_gem_l1or2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1 or GEMl2;SimTrack #phi [rad];Eff.", "h_", "(100,-3.14159265358979312,3.14159265358979312)", "phi", ok_eta, ok_gL1sh || ok_gL2sh, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_sh_gem_l1", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1;SimTrack #phi [rad];Eff.", "h_", "(100,-3.14159265358979312,3.14159265358979312)", "phi", ok_eta, ok_gL1sh, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_sh_gem_l2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM SimHit in GEMl2;SimTrack #phi [rad];Eff.", "h_", "(100,-3.14159265358979312,3.14159265358979312)", "phi", ok_eta, ok_gL2sh, "P", kBlue); draw_geff(targetDir_, "eff_phi_track_sh_gem_l1and2", ext_, treeTracks_, "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1 and GEMl2;SimTrack #phi [rad];Eff.", "h_", "(100,-3.14159265358979312,3.14159265358979312)", "phi", ok_eta, ok_gL1sh && ok_gL2sh, "P", kBlue); // draw_geff(targetDir_, "eff_globalx_track_sh_gem_l1or2", ext_, treeTracks_, // "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1 or GEMl2;SimTrack globalx;Eff.", // "h_", "(250,-250.,250)", "globalX", "", ok_gL1sh || ok_gL2sh, "P", kBlue); // draw_geff(targetDir_, "eff_globalx_track_sh_gem_l1", ext_, treeTracks_, // "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1;SimTrack globalx;Eff.", // "h_", "(250,-250.,250)", "globalX", "", ok_gL1sh, "P", kBlue); // draw_geff(targetDir_, "eff_globalx_track_sh_gem_l2", ext_, treeTracks_, // "Eff. for a SimTrack to have an associated GEM SimHit in GEMl2;SimTrack globalx;Eff.", // "h_", "(250,-250.,250)", "globalx_layer1", "", ok_gL2sh, "P", kBlue); // draw_geff(targetDir_, "eff_globalx_track_sh_gem_l1and2", ext_, treeTracks_, // "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1 and GEMl2;SimTrack globalx;Eff.", // "h_", "(250,-250.,250)", "globalx_layer1", "", ok_gL1sh && ok_gL2sh, "P", kBlue); // draw_geff(targetDir_, "eff_globaly_track_sh_gem_l1or2", ext_, treeTracks_, // "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1 or GEMl2;SimTrack globaly;Eff.", // "h_", "(250,-250.,250)", "globaly_layer1", "", ok_gL1sh || ok_gL2sh, "P", kBlue); // draw_geff(targetDir_, "eff_globaly_track_sh_gem_l1", ext_, treeTracks_, // "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1;SimTrack globaly;Eff.", // "h_", "(250,-250.,250)", "globaly_layer1", "", ok_gL1sh, "P", kBlue); // draw_geff(targetDir_, "eff_globaly_track_sh_gem_l2", ext_, treeTracks_, // "Eff. for a SimTrack to have an associated GEM SimHit in GEMl2;SimTrack globaly;Eff.", // "h_", "(250,-250.,250)", "globaly_layer1", "", ok_gL2sh, "P", kBlue); // draw_geff(targetDir_, "eff_globaly_track_sh_gem_l1and2", ext_, treeTracks_, // "Eff. for a SimTrack to have an associated GEM SimHit in GEMl1 and GEMl2;SimTrack globaly;Eff.", // "h_", "(250,-250.,250)", "globaly_layer1", "", ok_gL1sh && ok_gL2sh, "P", kBlue); draw_1D(targetDir_, "track_pt", ext_, treeTracks_, "Track p_{T};Track p_{T} [GeV];Entries", "h_", "(100,0,200)", "pt", ""); draw_1D(targetDir_, "track_eta", ext_, treeTracks_, "Track |#eta|;Track |#eta|;Entries", "h_", "(100,1.5,2.2)", "eta", ""); draw_1D(targetDir_, "track_phi", ext_, treeTracks_, "Track #phi;Track #phi [rad];Entries", "h_", "(100,-3.14159265358979312,3.14159265358979312)", "phi", ""); return returnStatus_; } void draw_geff(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut denom_cut, TCut extra_num_cut, TString opt, int color, int marker_st, float marker_sz) { TCanvas* c( new TCanvas("c","c",600,600) ); c->Clear(); gPad->SetGrid(1); gStyle->SetStatStyle(0); t->Draw(to_draw + ">>num_" + h_name + h_bins, denom_cut && extra_num_cut, "goff"); TH1F* num((TH1F*) gDirectory->Get("num_" + h_name)->Clone("eff_" + h_name)); t->Draw(to_draw + ">>denom_" + h_name + h_bins, denom_cut, "goff"); TH1F* den((TH1F*) gDirectory->Get("denom_" + h_name)->Clone("denom_" + h_name)); TGraphAsymmErrors *eff( new TGraphAsymmErrors(num, den)); if (!opt.Contains("same")) { num->Reset(); num->GetYaxis()->SetRangeUser(0.,1.05); num->SetStats(0); num->SetTitle(title); num->Draw(); } eff->SetLineWidth(2); eff->SetLineColor(color); eff->SetMarkerStyle(marker_st); eff->SetMarkerColor(color); eff->SetMarkerSize(marker_sz); eff->Draw(opt + " same"); // Do fit in the flat region bool etaPlot(c_title.Contains("eta")); const double xmin(etaPlot ? 1.64 : -999.); const double xmax(etaPlot ? 2.12 : 999.); TF1 *f1 = new TF1("fit1","pol0", xmin, xmax); TFitResultPtr r = eff->Fit("fit1","RQS"); TPaveStats *ptstats = new TPaveStats(0.25,0.35,0.75,0.55,"brNDC"); ptstats->SetName("stats"); ptstats->SetBorderSize(0); ptstats->SetLineWidth(0); ptstats->SetFillColor(0); ptstats->SetTextAlign(11); ptstats->SetTextFont(42); ptstats->SetTextSize(.05); ptstats->SetTextColor(kRed); ptstats->SetOptStat(0); ptstats->SetOptFit(1111); std::stringstream sstream; sstream << TMath::Nint(r->Chi2()); const TString chi2(boost::lexical_cast< std::string >(sstream.str())); sstream.str(std::string()); sstream << r->Ndf(); const TString ndf(boost::lexical_cast< std::string >(sstream.str())); sstream.str(std::string()); sstream << TMath::Nint(r->Prob()*100); const TString prob(boost::lexical_cast< std::string >(sstream.str())); sstream.str(std::string()); sstream << std::setprecision(4) << f1->GetParameter(0) * 100; const TString p0(boost::lexical_cast< std::string >(sstream.str())); sstream.str(std::string()); sstream << std::setprecision(2) << f1->GetParError(0) * 100; const TString p0e(boost::lexical_cast< std::string >(sstream.str())); ptstats->AddText("#chi^{2} / ndf: " + chi2 + "/" + ndf); // ptstats->AddText("Fit probability: " + prob + " %"); // ptstats->AddText("Fitted efficiency = " + p0 + " #pm " + p0e + " %" ); ptstats->AddText("Fitted efficiency: " + p0 + " #pm " + p0e + " %"); ptstats->Draw("same"); TPaveText *pt = new TPaveText(0.09899329,0.9178322,0.8993289,0.9737762,"blNDC"); pt->SetName("title"); pt->SetBorderSize(1); pt->SetFillColor(0); pt->SetFillStyle(0); pt->SetTextFont(42); pt->AddText(eff->GetTitle()); pt->Draw("same"); c->Modified(); c->SaveAs(target_dir + c_title + ext); delete num; delete den; delete eff; delete c; } void draw_occ(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt) { gStyle->SetStatStyle(0); gStyle->SetOptStat(1110); TCanvas* c = new TCanvas("c","c",600,600); t->Draw(to_draw + ">>" + h_name + h_bins, cut); TH2F* h = (TH2F*) gDirectory->Get(h_name)->Clone(h_name); h->SetTitle(title); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(opt); c->SaveAs(target_dir + c_title + ext); delete h; delete c; } void draw_1D(TString target_dir, TString c_title, TString ext, TTree *t, TString title, TString h_name, TString h_bins, TString to_draw, TCut cut, TString opt) { gStyle->SetStatStyle(0); gStyle->SetOptStat(1110); TCanvas* c = new TCanvas("c","c",600,600); t->Draw(to_draw + ">>" + h_name + h_bins, cut); TH1F* h = (TH1F*) gDirectory->Get(h_name)->Clone(h_name); h->SetTitle(title); h->SetLineWidth(2); h->SetLineColor(kBlue); h->Draw(opt); h->SetMinimum(0.); c->SaveAs(target_dir + c_title + ext); delete h; delete c; }
a6b4833e02bd9d74e15c39cf4adfa9fcece3be91
[ "C", "Python" ]
6
Python
rradogna/cmssw
f5b309f111747cadc6121dfae4c1b06acb9d2256
2c3f2706cd694b2807ef19df021dd77d3955b57b
refs/heads/main
<repo_name>Souravthakur540/User-Management-System-App<file_sep>/README.md # User-Management-System-App CRUD Implementation ![](images/1.png) <br/><br/> ![](images/2.png) <br/><br/> ![](images/3.png) <br/><br/> <file_sep>/assets/js/index.js $('#add_user').submit(function(event){ alert("Data Inserted Successfully!") }) $('#update_user').submit(function(event){ event.preventDefault() var unindexed_array = $(this).serializeArray() var data = {} $.map(unindexed_array, function(n, i){ data[n['name']] = n['value'] }) console.log(data) var request = { 'url': `http://localhost:3000/api/users/${data.id}`, 'method': 'PUT', 'data': data } $.ajax(request).done(function(response){ alert('Data updated successfully!') }) }) if(window.location.pathname == '/'){ $ondelete = $('.table tbody td a.delete') $ondelete.click(function(){ var id = $(this).attr('data-id') var request = { 'url': `http://localhost:3000/api/users/${id}`, 'method': 'DELETE' } if(confirm('Do you want to delete this record?')){ $.ajax(request).done(function(response){ alert('Data Deleted Successfully!') location.reload() }) } }) } // $(document).ready(function() { // $(".next").click(function() { // $(".pagination") // .find(".pageNumber.active") // .next() // .addClass("active"); // $(".pagination") // .find(".pageNumber.active") // .prev() // .removeClass("active"); // }); // $(".prev").click(function() { // $(".pagination") // .find(".pageNumber.active") // .prev() // .addClass("active"); // $(".pagination") // .find(".pageNumber.active") // .next() // .removeClass("active"); // }); // }); $(document).on('click', '.prev', function () { const first = $(this).siblings().first(); if (!first.hasClass('active')) { const active = $(this).siblings('.active'); const prevItem = active.prev(); const link = prevItem.children('a').prop('href'); active.removeClass('active'); prevItem.addClass('active'); window.location.href = link; } }); $(document).on('click', '.next', function () { const last = $(this).siblings().last(); if (!last.hasClass('active')) { const active = $(this).siblings('.active'); const nextItem = active.next(); const link = nextItem.children('a').prop('href'); active.removeClass('active'); nextItem.addClass('active'); window.location.href = link; } });
93b92c3c67e46d59604c27e93cb41dd8e8b6c462
[ "Markdown", "JavaScript" ]
2
Markdown
Souravthakur540/User-Management-System-App
5a0617938145e4351448f6b985eb6cefbeea9ae5
1797ab6ecbc1ab213ef86eb11bea290a42ba5ca8
refs/heads/master
<repo_name>AthenOf/pile_exercise<file_sep>/pile.py # Création de pile # def cree_pile(n): return[1]+[None]*n def empiler(p, x): if(not is_full(p)): p[p[0]]=x; p[0]+=1 return p def depiler(p): if(not is_empty(p)): p[p[0]-1]=None; p[0]-=1 return p def is_empty(p): return p[0]==1 #Vérification de si la pile n'est pas vide # def is_full(p): return p[-1]!=None #-----------------------------------------------------------------------------------------------------# #Différentes erreurs # if __name__ == "__main__": # Exécution caché # error = "Pile obsolète !" pile = cree_pile(2) # Création 2 piles pour test et bug # assert pile==[1,None,None],error+"pile.cree_pile(n) résultat faux" empiler(pile, "test") assert pile==[2,"test",None],error+"pile.empiler(p,x) résultat faux" depiler(pile) assert pile==[1,None,None],error+"pile.depiler(p) résultat faux" print(pile)
4e2a04d8b5f425c8fbad697f83340dcda3cb8ecb
[ "Python" ]
1
Python
AthenOf/pile_exercise
a7650212b66506c8bb6c878b7c51a862fd6cab85
929259db39b25b0571c40514d1bad1d172319589
refs/heads/master
<file_sep>//print all natural numbers between 1 to n using recursion #include <iostream> using namespace std; int numAll(int n){ if(n>= 1){ numAll(n-1); cout<<n<<" "; } } int main(){ int n; cin>>n; numAll(n); return 0; } <file_sep>#include <iostream> using namespace std; int fact(int n) { if (n==0) { return 0; } else if ( n == 1) { return 1; } else { return n*fact(n-1); } } int main() { int n,f; cin>>n; f = fact(n); cout<<f; } <file_sep>#include <iostream> using namespace std; int EvenOdd(int num, int n) { if(num > n) return 0; cout<<num<<" "; EvenOdd(num+2, n); } int main() { int n; cin>>n; cout<<"EVEN: "; EvenOdd(2, n); cout<<endl; cout<<"ODD: "; EvenOdd(1, n); return 0; }
7393235e87197b54e1d8631a610b04e77ed1b9e7
[ "C++" ]
3
C++
naveenkumar2405/Recursion_Programs
bf9944f7ce44939433b005905557ca80e5c3e715
083fec0e959e4d0efe1d76ff06a2e89b3919d243
refs/heads/master
<file_sep>context("ShinyBuilder") test_that('package functions are present',{ expect_true(is.function(dbListInit)) expect_true(is.function(dbListAdd)) expect_true(is.function(dbListRemove)) expect_true(is.function(dbListPrint)) }) # test_that('DB connections work with sample queries',{ # db_list <- dbListInit() # lapply(db_list, function(db_obj) expect_is(with(db_obj, do.call(query_fn, list(db, default_query))), 'data.frame')) # })<file_sep># Copyright (c) 2014 Clear Channel Broadcasting, Inc. # https://github.com/iheartradio/ShinyBuilder # Licensed under the MIT License (MIT) #' Update All Dashboards #' #' @param dashboards a vector of dashboard names. By default, all dashboards in the dashboards directory are updated #' @export #' @examples #' \dontrun{updateDashboards()} updateDashboards <- function(dashboards = NULL){ if(is.null(dashboards)) #dashboards <- list.files(path = paste0(getwd(),'/dashboards'), full.names = T) dashboards <- list.files(path = system.file('dashboards', package = 'ShinyBuilder'), full.names = T) db_list <- dbListInit() #source('ShinyBuilder/R/db_list.R') for (dashboard_file in dashboards){ #Load current dashboard load(dashboard_file) print(paste0('Updating ', dashboard_file)) #Update chart data for (i in 1:length(dashboard_state)){ if(str_detect(dashboard_state[[i]]$id, 'gItemPlot')){ input_query <- dashboard_state[[i]]$query db_obj <- db_list[[dashboard_state[[i]]$db_name]] dashboard_state[[i]]$data <- do.call(db_obj$qry_fn, list(db_obj$db, input_query)) } } #Save current dashboard save(dashboard_state, file = dashboard_file) } }
1a11a087e58ce3721e53ecad19d44403025bf037
[ "R" ]
2
R
johndharrison/ShinyBuilder
ea5d082a149c9c035aaad64ac7c9ef1f868cead4
36e0a81dc8ecd2e4d65fa45a988f54423ae3e627
refs/heads/master
<file_sep># iQIYI-homepage Tried to mimic the homepage of iQIYI, my first project : ) This project used HTML5 CSS3, javascript and jquery to finish the outlook of the iQIYI webpage with some interactions. Key take-aways would be: 1. how to write a carousel using jquery only, no pluggings or bootstrap 2. use CSS3 animation to switch two pictures and no need for any js or jquery code (simplest carousel of only two pictures) 3. use CSS3 animation to zoom in pictures 4. implement the flex position to display elements with ease 5. how to pop up a new window/slidedown-menu using jquery 6. 5-star comments with jquery 7. other small tricks like relative/absolute/ position plus z-index to make small tags on top of content, box-sizing: border-box to aviod shifting of content, and how to google things when you are in trouble! For next project I would try to group the js code to sort out the index.js to make modules of code for easier maintainance. Will try bootstrap or React next time to write a page. My javascript/jquery basic knowledge should be extended as well. And more comments to make the source code readable! <file_sep>$(window).ready(function(){ $("#upload").click(function(){ $("#upload-list").slideToggle("3000"); }); $("#download").click(function(){ $("#download-list").slideToggle("3000"); }); $("#news").click(function(){ $(".news-panel").slideToggle("3000"); }); $("#first").hover(function(){ $(".news-panel-body").html("您还没有收到新的更新消息"); }); $("#last").hover(function(){ $(".news-panel-body").html("您还没有登录您登录后可以查看完整的通知列表"); }); $("#second").hover(function(){ $(".news-panel-body").html("暂时还没有新的推荐"); }); $("#record").click(function(){ $(".record-panel").slideToggle("3000"); }); var index = 0; var time=setInterval(move,3000); function move(){ if(index===5) index=0; $(".img li").eq(index).stop().fadeIn(3000).siblings().stop().fadeOut(3000); $(".num li").eq(index).addClass("current").siblings().removeClass(); index++; } $(".num li").hover(function(){ /*console.log($(this).index());*/ $(this).addClass("current"); $(this).siblings().removeClass(); $(".img li").eq($(this).index()).stop().fadeIn(1000).siblings().stop().fadeOut(1000); clearInterval(time); }, ); $(".num li").mouseleave(function(){ index=$(this).index()+1; time = setInterval(move,3000); }); $(".btn").hover(function(){ clearInterval(time); $(this).css({"cursor":"pointer", }); }, (function(){ time = setInterval(move,3000); }) ); $(".right_btn").bind("click",function(){ index++; if(index===6) index=1; $(".img li").eq(index-1).stop().fadeIn(1000).siblings().stop().fadeOut(1000); $(".num li").eq(index-1).addClass("current").siblings().removeClass(); console.log(index); }); $(".left_btn").bind("click",function(){ index--; if(index===0) index=5; $(".img li").eq(index-1).stop().fadeIn(1000).siblings().stop().fadeOut(1000); $(".num li").eq(index-1).addClass("current").siblings().removeClass(); console.log(index); }); var time2=setInterval(move2,5000); var index2=0; function move2(){ if(index2 === 2) index2 = 0; $(".s-img li").eq(index2).fadeIn(2000).siblings().stop().fadeOut(2000); index2 = index2 + 1; }; var time3=setInterval(move3,3000); var index3=0; function move3(){ switch (index3) { case 0: $(".s-img2 li").eq(index3).show().siblings().hide(); $(".left-pic-word h3").html("我们的演唱会"); $(".left-pic-word p").html("大厂兄弟情!姚弛送卫生纸庆祝王喆搬新居"); index3 = 1; break; case 1: $(".s-img2 li").eq(index3).show().siblings().hide(); $(".left-pic-word h3").html("青春环游记"); $(".left-pic-word p").html("王凯宋轶伪装者再聚首 魏大勋吴谨言大秀浮夸演技"); index3 = 0; break; } } $(".variety-left-picbox").hover(function(){ clearInterval(time3) }, function(){ time3=setInterval(move3,3000) }); $(".right_btn2").bind("click",function(){ switch (index3) { case 0: $(".s-img2 li").eq(index3).show().siblings().hide(); $(".left-pic-word h3").html("我们的演唱会"); $(".left-pic-word p").html("大厂兄弟情!姚弛送卫生纸庆祝王喆搬新居"); index3 = 1; break; case 1: $(".s-img2 li").eq(index3).show().siblings().hide(); $(".left-pic-word h3").html("青春环游记"); $(".left-pic-word p").html("王凯宋轶伪装者再聚首 魏大勋吴谨言大秀浮夸演技"); index3 = 0; break; } console.log(index3); }); $(".left_btn2").bind("click",function(){ switch (index3) { case 0: $(".s-img2 li").eq(index3).show().siblings().hide(); $(".left-pic-word h3").html("我们的演唱会"); $(".left-pic-word p").html("大厂兄弟情!姚弛送卫生纸庆祝王喆搬新居"); index3 = 1; break; case 1: $(".s-img2 li").eq(index3).show().siblings().hide(); $(".left-pic-word h3").html("青春环游记"); $(".left-pic-word p").html("王凯宋轶伪装者再聚首 魏大勋吴谨言大秀浮夸演技"); index3 = 0; break; } }); $(".pic-word").hover(function(){ $(this).children("span").css("visibility","visible"); },function(){ $(this).children("span").css("visibility","hidden") }); $(".movie-box").hover(function () { $(this).children(".hide").show(); }, function () { $(this).children(".hide").hide(); }); $(".wustar ul li").hover(function(){ $(this).removeClass("wustar").addClass('hs'); $(this).prevAll().removeClass("wustar").addClass('hs'); },function(){ $(this).removeClass('hs'); $(this).prevAll().removeClass('hs'); }); $(".star ul li").click(function () { $(this).addClass('cs'); $(this).prevAll().addClass('cs'); $(this).nextAll().removeClass('cs'); }); });
2f82a34e194b1a8068fdbdd23486ae08c4eb1815
[ "Markdown", "JavaScript" ]
2
Markdown
Claire-Deng/iQIYI-homepage
b9d4cfd6f880b9038228051009e6f2c2f90b9af8
9a6a1da9ab177209b32e94d37b97b587b51febf0
refs/heads/master
<repo_name>Dalal1983/SSKNet<file_sep>/Region_Clustering.py import numpy as np from collections import Counter from skimage import color,io from tqdm import tqdm def Clustering(img,S_centers, S_clusters): global flag, idx_hash_final pix_size = 5 # superpixel size d_th = 4 # Hash similarity threshold idx_num = 1 # Final label index sub_num = 0 idx_entropy = 0 label = np.zeros((len(S_centers), pix_size, pix_size)) # Hash fingerprint tag kind_label = np.arange((len(S_centers))) # Cluster initial label diff_label = 500 * np.ones(shape=(len(S_centers),1)) # Superpixel difference table final_label = -2 * np.ones(shape=(len(kind_label))) # Final centroid cluster label final_pix_label = -1 * np.ones(shape=(S_clusters.shape[0] * S_clusters.shape[1], 1)) #final_pix_label = -1 * np.ones(shape=(S_clusters.shape[0], S_clusters.shape[1])) for i in range(len(S_centers)): idx = (S_clusters == i) colornp = img[idx] colornp = color.rgb2grey(colornp) # print(colornp) array_gray = np.resize(colornp,(pix_size,pix_size)) # Superpixel grayscale supix_mean = np.sum(array_gray) / pix_size**2 # Superpixel gray average # print(supix_mean.shape) for j in range(array_gray.shape[0]): for p in range(array_gray.shape[1]): if(array_gray[j][p] >= supix_mean): label[i][j][p] = 1 else: label[i][j][p] = 0 # hist = list(array_gray) # print(array_gray.shape) label = label.reshape(len(S_centers), pix_size**2) # print('Superpixel hash label',label,label.shape) for x in tqdm(range(len(S_centers))): # if(len(label[i] == len(label[j]))): for y in range(x,len(S_centers)): if x == y and y < len(S_centers)-1: y = y + 1 diff = label[x] - label[y] diff_num =len(label[x][np.nonzero(diff)]) # print(x,y,diff_num,) if (diff_num <= d_th) and (diff_num < diff_label[y]): if (kind_label[x] != x ) : kind_label[y] = kind_label[x] diff_label[y] = diff_num else: kind_label[y] = x diff_label[y] = diff_num # print(kind_label) # print(Counter(kind_label)) idx_label = np.unique(kind_label) # Returns the sorted category index array print('idx_label',idx_label) for t in idx_label: for q in range(len(kind_label)): if kind_label[q] == t and Counter(kind_label)[t] > 10: final_label[q] = idx_num flag = 1 if kind_label[q] == t and Counter(kind_label)[t] <= 10: final_label[q] = -1 flag = 0 idx_num += flag for a in range(len(kind_label)): if final_label[a] == -1: final_label[a] = idx_num # print(final_label) # final_label = final_label[:len(final_label) - z + 1] # print('Final number in each category:',Counter(final_label)) print('finlabel',final_label.shape) print('centers',S_centers.shape) '''flag_label = S_clusters.reshape(S_clusters.shape[0] * S_clusters.shape[1],1) for q in range(len(final_label)): for p in range(len(final_pix_label)): if flag_label[p] == q: final_pix_label[p] = final_label[q] final_pix_label.reshape(S_clusters.shape[0], S_clusters.shape[1]) print('finall pix label',final_pix_label)''' hash_slic_label = np.column_stack((S_centers, final_label)) # print('hash slic label:',hash_slic_label.shape) ''' Information Entropy Mapping ''' entropy = np.zeros(len(np.unique(final_label))) stander = len(np.unique(final_label)) # print('np.uniqule',np.unique(final_label)) for i, k in enumerate(np.unique(final_label)): idx1 = (final_label == k) idx2 = S_centers[idx1] idxnum = np.random.randint(0, Counter(final_label)[k], [1]) idxy, idxx = int(idx2[idxnum, 3]), int(idx2[idxnum, 4]) # print(idxx, idxy) idx_img = img[idxx - 2:idxx + 3, idxy - 2:idxy + 3, :] idx_img_grey = color.rgb2grey(idx_img).reshape(25) # print('np.uniqule_supergrey', np.unique(idx_img_grey)) for c, j in enumerate(np.unique(idx_img_grey)): idx_num = Counter(idx_img_grey)[j] idx_p = idx_num / 25 idx_entropy -= idx_p * np.log2(idx_p) # print('idx_entropy', idx_entropy) entropy[i] = idx_entropy idx_entropy = 0 percent = (entropy / np.sum(entropy) * 100).astype(np.int) if np.sum(percent) < 100: reduce_cut = 100 - np.sum(percent) for e in range(reduce_cut): if e == stander - 1: e = 0 percent[e] += 1 print('Each Group Entropy:', entropy) print('Each Group Mapping:', percent) for t, q in enumerate(np.unique(final_label)): idx3 = (hash_slic_label[:, 5] == q) idx_hash = hash_slic_label[idx3] idx_rand = np.random.randint(0, len(idx_hash), [percent[t]]) idx_hash_t = idx_hash[idx_rand] if t == 0: idx_hash_final = idx_hash_t else: idx_hash_final = np.vstack((idx_hash_final, idx_hash_t)) print('Kernel Total Number:', idx_hash_final.shape) return idx_hash_final <file_sep>/SSKNet.py import torch import torch.nn as nn from torch.nn import functional as F import numpy as np class SeKG_Module(nn.Module): def __init__(self, channels, cut_size, reduction=16): super(SeKG_Module, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc_1 = nn.Conv2d(channels, channels // reduction, kernel_size=1, padding=0) self.conv_1 = nn.Conv2d(1, 1, kernel_size=(3, 3), stride=1, padding=1) self.conv_2 = nn.Conv2d(1, 1, kernel_size=(5, 5), stride=1, padding=2) self.conv_3 = nn.Conv2d(1, 1, kernel_size=(7, 7), stride=1, padding=3) self.relu = nn.ReLU(inplace=True) self.fc_2 = nn.Conv2d(channels // reduction, channels, kernel_size=1, padding=0) self.sigmoid = nn.Sigmoid() self.cut_size = int((cut_size - 1) / 2) def forward(self, x): global spectrum_kernel_all, spectrum original = x x = self.avg_pool(x) spe_f = torch.transpose(x, 1, 3) # print(x.shape) spe_f3 = self.conv_1(spe_f) spe_f5 = self.conv_2(spe_f) spe_f7 = self.conv_3(spe_f) x1_3 = torch.transpose(spe_f3, 3, 1) x1_5 = torch.transpose(spe_f5, 3, 1) x1_7 = torch.transpose(spe_f7, 3, 1) x = x + x1_3 + x1_5 + x1_7 # print(x.shape) x = self.fc_1(x) x = self.relu(x) x = self.fc_2(x) x = self.sigmoid(x) original = original * x original = torch.unsqueeze(original, dim=0).expand((original.shape[0], original.shape[0], original.shape[1], original.shape[2], original.shape[3])) for i in range(original.shape[1]): for k in range(5): idx = np.random.randint(0, original.shape[2], 100) spectrum_kernel_s = original[i:i+1, k:k+1, idx, self.cut_size-1:self.cut_size+2, self.cut_size-1:self.cut_size+2] if k == 0: spectrum_kernel_all = spectrum_kernel_s else: spectrum_kernel_all = torch.cat((spectrum_kernel_s, spectrum_kernel_all), dim=1) # print(spectrum_kernel_all.shape) if i == 0: spectrum = spectrum_kernel_all else: spectrum = torch.cat((spectrum, spectrum_kernel_all), dim=0) # print('spectrum:', spectrum.shape) return spectrum class Layer(nn.Module): def __init__(self, ch_in, ch_out, stride=1): super(Layer, self).__init__() self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=5, stride=stride, padding=2) self.bn1 = nn.BatchNorm2d(ch_out) self.extra = nn.Sequential() if ch_out != ch_in or stride != 1: self.extra = nn.Sequential( nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=stride), nn.BatchNorm2d(ch_out) ) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.extra(x) + out out = F.relu(out) return out class SSKNet(nn.Module): def __init__(self): super(SSKNet, self).__init__() self.sekg = SeKG_Module(200, cut_size=11, reduction=16) # I_200 self.conv1 = nn.Sequential( nn.Conv2d(5, 50, kernel_size=3, stride=1, padding=1), # I_200 nn.BatchNorm2d(50) ) self.layer1 = Layer(50, 100, stride=1) self.layer2 = Layer(100, 100, stride=1) self.layer3 = Layer(100, 100, stride=1) self.layer4 = Layer(100, 100, stride=1) self.layer5 = Layer(100, 100, stride=1) self.outlayer = nn.Linear(100 * 1 * 1, 16) self.extra = nn.Conv2d(200, 5, kernel_size=1, stride=1) # I_200 self.extra100 = nn.Conv2d(200, 100, kernel_size=1, stride=1) self.batch_norm = nn.BatchNorm2d(100) self.batch_norm2 = nn.BatchNorm2d(5) def forward(self, x, kernel_weight1, kernel_weight2, kernel_weight3, kernel_weight4, HSI_CUT_SIZE): spectrum_kernel = self.sekg(x) # print(spectrum_kernel) origin_data = x origin_data = self.extra(origin_data) origin_data = self.batch_norm2(origin_data) spact = self.extra100(x) spact = F.leaky_relu(self.batch_norm(spact)) x = F.conv2d(x, weight=kernel_weight1, padding=2) # print(x.shape) x = F.leaky_relu(self.batch_norm(x)) x = F.conv2d(x, weight=kernel_weight2, padding=2) x = F.leaky_relu(self.batch_norm(x)) x = F.conv2d(x, weight=kernel_weight3, padding=2) x = F.leaky_relu(self.batch_norm(x)) x = F.conv2d(x, weight=kernel_weight4, padding=2) x = F.leaky_relu(self.batch_norm(x)) x = x + spact x = F.leaky_relu(x) # print(x) for t in range(x.shape[0]): x_feature = x[t:t+1, :, :, :] # x_feature = x_feature_1.unsqueeze(0) # print('p_num:', x_feature.shape) p_kernel = spectrum_kernel[t:t + 1, :, :, :, :] p_kernel = torch.tensor(p_kernel, requires_grad=False) # print('p_kernel:', p_kernel.shape) p_kernel = torch.squeeze(p_kernel, dim=0) # print('p_kernel', p_kernel.shape) out = F.conv2d(x_feature, weight=p_kernel, stride=1, padding=1) # print(x) if t == 0: x_all = out else: x_all = torch.cat((x_all, out), dim=0) # x_all[t] = x x_all = self.batch_norm2(x_all) x_all = x_all + origin_data x_all = self.batch_norm2(x_all) x = F.relu(x_all) # print('x:', x.shape) x = F.relu(self.conv1(x)) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.layer5(x) x = F.adaptive_avg_pool2d(x, [1, 1]) x = x.view(x.size(0), -1) x = self.outlayer(x) return x <file_sep>/Region_Segmentation.py import numpy as np from skimage import io, color import tqdm def generate_pixels(): indnp = np.mgrid[0:S_height,0:S_width].swapaxes(0,2).swapaxes(0,1) # print(indnp) for i in tqdm.tqdm(range(S_ITERATIONS)): SLIC_distances = 1 * np.ones(img.shape[:2]) for j in range(S_centers.shape[0]): # Cycle based on each centroid # Search close pixels in the 2S*2S area x_low, x_high = int(S_centers[j][3] - step), int(S_centers[j][3] + step) y_low, y_high = int(S_centers[j][4] - step), int(S_centers[j][4] + step) if x_low <= 0: x_low = 0 if x_high > S_width: x_high = S_width if y_low <=0: y_low = 0 if y_high > S_height: y_high = S_height cropimg = S_labimg[y_low : y_high , x_low : x_high] # Calculate distance between each point color_diff = cropimg - S_labimg[int(S_centers[j][4]), int(S_centers[j][3])] # color_distance = np.sum(np.square(color_diff), axis=2) color_distance = np.sqrt(np.sum(np.square(color_diff), axis=2)) yy, xx = np.ogrid[y_low : y_high, x_low : x_high] # Generate 2D space coordinates # pixdist = (yy - S_centers[j][4]) ** 2 + (xx - S_centers[j][3]) ** 2 pixdist = ((yy-S_centers[j][4])**2 + (xx-S_centers[j][3])**2)**0.5 # S_m is "m" in the paper, (m/S)*dxy dist = ((color_distance / S_m) ** 2 + (pixdist / step) ** 2) # Calculate 5D total distance # dist = ((color_distance/S_m)**2 + (pixdist/step)**2)**0.5 distance_crop = SLIC_distances[y_low : y_high, x_low : x_high] idx = dist < distance_crop distance_crop[idx] = dist[idx] # Update distance SLIC_distances[y_low : y_high, x_low : x_high] = distance_crop # Optimal distance in 2S * 2S S_clusters[y_low : y_high, x_low : x_high][idx] = j for k in range(len(S_centers)): # SLIC_centers=[L,A,B,X,Y] idx = (S_clusters == k) # print('idx:',idx.shape) colornp = S_labimg[idx] # print(colornp.shape) distnp = indnp[idx] S_centers[k][0:3] = np.sum(colornp, axis=0) # Sum LAB values sumy, sumx = np.sum(distnp, axis=0) # Sum space coordinates S_centers[k][3:] = sumx, sumy S_centers[k] /= np.sum(idx) def display_contours(color): rgb_img = img.copy() is_taken = np.zeros(img.shape[:2], np.bool) contours = [] for i in range(S_width): for j in range(S_height): nr_p = 0 for dx, dy in [(-1,0), (-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1)]: x = i + dx y = j + dy if x>=0 and x < S_width and y>=0 and y < S_height: if is_taken[y, x] == False and S_clusters[j, i] != S_clusters[y, x]: nr_p += 1 if nr_p >= 2: is_taken[j, i] = True contours.append([j, i]) for i in range(len(contours)): rgb_img[contours[i][0], contours[i][1]] = color # for k in range(S_centers.shape[0]): # i,j = S_centers[k][-2:] # img[int(i),int(j)] = (0,0,0) # io.imsave("S_contours.jpg", rgb_img) return rgb_img def display_center(): lab_img = np.zeros([S_height,S_width,3]).astype(np.float64) for i in range(S_width): for j in range(S_height): k = int(S_clusters[j, i]) lab_img[j,i] = S_centers[k][0:3] rgb_img = color.lab2rgb(lab_img) # io.imsave("S_centers.jpg",rgb_img) return (rgb_img*255).astype(np.uint8) def find_local_minimum(center): min_grad = 1 loc_min = center for i in range(center[0] - 1, center[0] + 2): # (i,j) for j in range(center[1] - 1, center[1] + 2): # Draw initial spreading point c1 = S_labimg[j+1, i] c2 = S_labimg[j, i+1] c3 = S_labimg[j, i] if ((c1[0] - c3[0])**2) + ((c2[0] - c3[0])**2) < min_grad: min_grad = abs(c1[0] - c3[0]) + abs(c2[0] - c3[0]) loc_min = [i, j] # Calculate the min gradient '''if ((c1[0] - c3[0])**2)**0.5 + ((c2[0] - c3[0])**2)**0.5 < min_grad: min_grad = abs(c1[0] - c3[0]) + abs(c2[0] - c3[0]) loc_min = [i, j]''' return loc_min # Find superpixel centroid def calculate_centers(): centers = [] for i in range(step, S_width - int(step/2), step): #(i,j) for j in range(step, S_height - int(step/2), step): # Take the center point evenly in step nc = find_local_minimum(center=(i, j)) color = S_labimg[nc[1], nc[0]] # Mapp to LAB coordinates center = [color[0], color[1], color[2], nc[0], nc[1]] # [L,A,B,i,j] centers.append(center) return centers def region_sege(): global img, step, S_ITERATIONS, S_height, S_width, S_labimg, S_distances, S_clusters, S_center_counts, \ S_centers, S_m, SLIC_k distances_m = 50 super_pixel_k = 800 # 800 / 8000 / 4000 img = io.imread('image_pca1.png') print('Maxpixel:',img.max(),'inpixel:',img.min()) S_m = distances_m # Distance weight S_k = super_pixel_k # ber step= int((img.shape[0]*img.shape[1]/S_k)**0.5) # Superpixel size print('Sup_size',step) S_ITERATIONS= 1 S_height, S_width = img.shape[:2] S_labimg = color.rgb2lab(img) # RGB-LAB S_distances = 1 * np.ones(img.shape[:2]) S_clusters = -1 * S_distances centers_label = calculate_centers() # Superpixel centroid table 5D S_center_counts = np.zeros(len(centers_label)) print('Centroid Num:', S_center_counts.shape) S_centers = np.array(centers_label) '''S_center_counts = np.zeros(len(calculate_centers())) print(S_center_counts) S_centers = np.array(calculate_centers())''' generate_pixels() calculate_centers() display_contours([0.0, 0.0, 0.0]) display_center() return S_centers, S_clusters # print(img,img_center,img_contours) # result = np.hstack([img_contours,img_center]) <file_sep>/README.md # SSKNet Hyperspectral Image Classification Based On Spatial and Spectral Kernels Generation Network. Before you start running the code, make sure that you have installed the various libraries in requirements. If you need more experimental data sets, you can download them from: http://www.ehu.eus/ccwintco/index.php/Hyperspectral_Remote_Sensing_Scenes <file_sep>/Generate_Kernel.py import torch import torch.nn as nn import numpy as np from torch.nn import functional as F from torch.utils.data import DataLoader import Cut_Data def Generate_Init(Data_Border, kernel_pos, HSI_CUT_SIZE, KERNEL_CUT_SIZE, KERNEL_BATCH_SIZE): kernel_cut = Cut_Data.Cut_kernel_data(Data_Border, kernel_pos, HSI_CUT_SIZE, KERNEL_CUT_SIZE) kernel_loder = DataLoader(kernel_cut, batch_size=KERNEL_BATCH_SIZE, shuffle=False, num_workers=0, drop_last=True) for i, kernel_weight_1 in enumerate(iter(kernel_loder)): print(i, kernel_weight_1.shape) kernel_weight_1 = torch.as_tensor(kernel_weight_1, dtype=torch.float32).cuda() kernel_weight_1 = nn.Parameter(data=kernel_weight_1, requires_grad=False) return kernel_weight_1 def Generate_Weights(Data_Border, HSI_CUT_SIZE, KERNEL_CUT_SIZE, KERNEL_BATCH_SIZE, kernel_weight, kernel_pos): top_size, bottom_size, left_size, right_size = (int((HSI_CUT_SIZE - 1) / 2), int((HSI_CUT_SIZE - 1) / 2), int((HSI_CUT_SIZE - 1) / 2), int((HSI_CUT_SIZE - 1) / 2)) if len(Data_Border.shape) == 3: Data_Border = torch.tensor(Data_Border, dtype=torch.float32).cuda() Data_Border = Data_Border.unsqueeze(0) # print('data border:', Data_Border.shape) Data_Border_feature = F.conv2d(Data_Border, weight=kernel_weight, padding=2) Data_Border_feature = F.leaky_relu(Data_Border_feature) Features_Border = F.pad(Data_Border_feature, pad=[top_size, bottom_size, left_size, right_size], mode='constant', value=0) Features_Border = Features_Border.squeeze() Features_Border = Features_Border.data.cpu().numpy() pix_max2 = np.max(Features_Border) pix_min2 = np.min(Features_Border) Features_Border = (Features_Border - pix_min2) / (pix_max2 - pix_min2) # print('Features_Border', Features_Border) kernel_cut = Cut_Data.Cut_features_data(Features_Border, kernel_pos, HSI_CUT_SIZE, KERNEL_CUT_SIZE) kernel_loder = DataLoader(kernel_cut, batch_size=KERNEL_BATCH_SIZE, shuffle=False, num_workers=0, drop_last=True) for i, kernel_weight in enumerate(iter(kernel_loder)): print('Spatial kernel size:', kernel_weight.shape) kernel_weight = torch.as_tensor(kernel_weight, dtype=torch.float32).cuda() kernel_weight = nn.Parameter(data=kernel_weight, requires_grad=False) return kernel_weight, Data_Border_feature <file_sep>/Cut_Data.py import numpy as np import torch.utils.data class Cutdata(torch.utils.data.Dataset): # Train data cut def __init__(self, image, pos_lab, cut_size, transform=None, target_transform=None): super(Cutdata, self).__init__() self.cut_size = int((cut_size - 1) / 2) # (B,C,H,W) self.pos_lab = pos_lab self.image = image self.transform = transform # self.t = 0 def __getitem__(self, index): i, j, label = self.pos_lab[index] i = i + self.cut_size j = j + self.cut_size image_cut = self.image[:, i - self.cut_size: i + self.cut_size + 1, j - self.cut_size: j + self.cut_size + 1] # self.t += 1 # print(self.t) # print('image_cut shape',image_cut.shape) self.label = label return image_cut, self.label def __len__(self): return len(self.pos_lab) class Cutalldata(torch.utils.data.Dataset): # All data cut def __init__(self, image, pos_lab, cut_size, transform=None, target_transform=None): super(Cutalldata, self).__init__() self.cut_size = int((cut_size - 1) / 2) self.pos_lab = pos_lab self.image = image self.transform = transform def __getitem__(self, index): i, j = self.pos_lab[index] i = i + self.cut_size j = j + self.cut_size image_cut = self.image[:, i - self.cut_size: i + self.cut_size + 1, j - self.cut_size: j + self.cut_size + 1] return image_cut def __len__(self): return len(self.pos_lab) class Cut_kernel_data(torch.utils.data.Dataset): # Spectral kernel cut def __init__(self, image, pos_lab, cut_size, kernel_size, transform=None, target_transform=None): super(Cut_kernel_data, self).__init__() self.cut_size = int((cut_size - 1) / 2) self.kernel_size = int((kernel_size - 1) / 2) self.pos_lab = pos_lab self.image = image self.transform = transform def __getitem__(self, index): i, j = self.pos_lab[index] i = i + self.cut_size j = j + self.cut_size image_cut = self.image[:, i - self.kernel_size: i + self.kernel_size + 1, j - self.kernel_size: j + self.kernel_size + 1] return image_cut def __len__(self): return len(self.pos_lab) class Cut_features_data(torch.utils.data.Dataset): def __init__(self, image, pos_lab, cut_size, kernel_size, transform=None, target_transform=None): super(Cut_features_data, self).__init__() self.cut_size = int((cut_size - 1) / 2) self.kernel_size = int((kernel_size - 1) / 2) self.pos_lab = pos_lab self.image = image self.transform = transform def __getitem__(self, index): i, j = self.pos_lab[index] i = i + self.cut_size j = j + self.cut_size image_cut = self.image[:, i - self.kernel_size: i + self.kernel_size + 1, j - self.kernel_size: j + self.kernel_size + 1] return image_cut def __len__(self): return len(self.pos_lab)<file_sep>/Main.py import torch.nn as nn from torch import optim import scipy.io as scio import numpy as np from sklearn.decomposition import PCA import cv2 from skimage import color, io import Region_Segmentation import Region_Clustering from torch.utils.data import DataLoader from torch.optim.lr_scheduler import MultiStepLR from sklearn.metrics import confusion_matrix from sklearn.metrics import cohen_kappa_score import torch.utils.data import Cut_Data import SSKNet from Generate_Kernel import Generate_Weights, Generate_Init HSI_CUT_SIZE = 11 # Parameter initialization KERNEL_CUT_SIZE = 5 TRAIN_RATE = [0.55,0.035,0.056,0.125,0.074,0.05,0.5,0.064,0.5,0.05,0.024,0.058,0.145,0.041,0.078,0.5] EPOCH = 300 BATCH_SIZE = 32 KERNEL_BATCH_SIZE = 100 LR = 0.003 BorderInter = cv2.BORDER_REFLECT_101 Data_Hsi = scio.loadmat('Indian_pines_corrected.mat') # Load data Label_Hsi = scio.loadmat('Indian_pines_gt.mat') # Load label # print(Data_Hsi) # print(Label_Hsi) Data = np.array(Data_Hsi['indian_pines_corrected']) Label = np.array(Label_Hsi['indian_pines_gt']) top_size, bottom_size, left_size, right_size = (int((HSI_CUT_SIZE - 1) / 2), int((HSI_CUT_SIZE - 1) / 2), int((HSI_CUT_SIZE - 1) / 2), int((HSI_CUT_SIZE - 1) / 2)) Data_Border = cv2.copyMakeBorder(Data, top_size, bottom_size, left_size, right_size, BorderInter) all_Label = np.max(Label) # Data = np.array(Data).transpose((2,0,1)) Data_Border = np.array(Data_Border).transpose((2, 0, 1)) pix_max = np.max(Data_Border) # Data normalization pix_min = np.min(Data_Border) Data_Border = (Data_Border - pix_min) / (pix_max - pix_min) array_1 = Data.reshape(np.prod(Data.shape[:2]), np.prod(Data.shape[2:])) pca = PCA(n_components=3) # Principal components array_2 = pca.fit_transform(array_1) # Parameter fitting # print(array_2.shape) Data_PCA = array_2.reshape(Data.shape[0], Data.shape[1], array_2.shape[1]) # Recovery dimension cv2.imwrite('image_pca1.png', Data_PCA) img = io.imread('image_pca1.png') S_centers, S_clusters = Region_Segmentation.region_sege() # Homogenous region segmentation idx_hash_final = Region_Clustering.Clustering(img, S_centers, S_clusters) # Rough region clustering hash_label = np.array(idx_hash_final[:, [4, 3, 5]], dtype='int64') # idx_keenel = np.lexsort(hash_label.T) # hash_label = hash_label[idx_keenel] kernel_pos = np.array(hash_label[:, [0, 1]], dtype='int64') np.random.shuffle(kernel_pos) # kernel_pos = kernel_pos[idx_num] kernel_weight_1 = Generate_Init(Data_Border, kernel_pos, HSI_CUT_SIZE, KERNEL_CUT_SIZE, KERNEL_BATCH_SIZE) Data = np.array(Data).transpose((2, 0, 1)) global train_label, train_data_pos, valid_label, valid_data_pos, all_label, all_label_pos index_all = np.array(np.where(Label != -1)) index_all = index_all.transpose() len_all = len(index_all) index_a = np.arange(len_all, dtype='int64') np.random.shuffle(index_a) all_pos = index_all[index_a] # print('all data',all_data_pos.shape) # all_data_pos = np.vstack((empty_data_pos, train_data_pos, valid_data_pos, test_data_pos)) np.random.shuffle(all_pos) for i in range(1, all_Label+1): index_label_i = np.array(np.where(Label == i)) index_label_i = index_label_i.transpose() # print(index_label_i.shape) len_label_i = len(index_label_i) # all_num += len_label_i len_train_i = int(len_label_i * TRAIN_RATE[i-1]) len_valid_i = int((len_label_i - len_train_i)) len_label_i = int(len_label_i ) index_i = np.arange(len_label_i, dtype='int64') np.random.shuffle(index_i) train_label_i = i * np.ones((len_train_i, 1), dtype='int64') valid_label_i = i * np.ones((len_valid_i, 1), dtype='int64') all_label_i = i * np.ones((len_label_i, 1), dtype='int64') if i == 1: train_label = train_label_i train_data_pos = index_label_i[index_i[:len_train_i]] valid_label = valid_label_i valid_data_pos = index_label_i[index_i[len_train_i:len_train_i + len_valid_i]] all_label = all_label_i all_label_pos = index_label_i[index_i[:len_label_i]] else: train_label = np.append(train_label, train_label_i, axis=0) train_data_pos = np.append(train_data_pos, index_label_i[index_i[:len_train_i]], axis=0) valid_label = np.append(valid_label, valid_label_i, axis=0) valid_data_pos = np.append(valid_data_pos, index_label_i[index_i[len_train_i:len_train_i + len_valid_i]], axis=0) all_label = np.append(all_label, all_label_i, axis=0) all_label_pos = np.append(all_label_pos, index_label_i[index_i[:len_label_i]], axis=0) train_label -= 1 valid_label -= 1 all_label -= 1 train_data = np.hstack((train_data_pos, train_label)) np.random.shuffle(train_data) valid_data = np.hstack((valid_data_pos, valid_label)) np.random.shuffle(valid_data) all_label_data1 = np.hstack((all_label_pos, all_label)) np.random.shuffle(all_label_data1) # all_label_data2 = np.vstack((train_data, valid_data)) # np.random.shuffle(all_label_data2) #print( len(all_label_data1)) #print(len(valid_data)) true_label = all_label_data1[:, 2] pred_label = np.zeros(len(true_label), dtype=int) pix_max = np.max(Data_Border) pix_min = np.min(Data_Border) Data_Border = (Data_Border - pix_min) / (pix_max - pix_min) train_cut = Cut_Data.Cutdata(Data_Border, train_data, HSI_CUT_SIZE) train_loder = DataLoader(train_cut, batch_size=BATCH_SIZE, shuffle=False, num_workers=0, drop_last=True) # print(train_cut[0][0]) # data1 , label1 = train_cut[5000] # print(label1) # print(data1.shape) valid_cut = Cut_Data.Cutdata(Data_Border, valid_data, HSI_CUT_SIZE) valid_loder = DataLoader(valid_cut, batch_size=BATCH_SIZE, shuffle=False, num_workers=0, drop_last=True) all_label_cut = Cut_Data.Cutdata(Data_Border, all_label_data1, HSI_CUT_SIZE) all_label_loder = DataLoader(all_label_cut, batch_size=BATCH_SIZE, shuffle=False, num_workers=0) all_cut = Cut_Data.Cutalldata(Data_Border, all_pos, HSI_CUT_SIZE) all_loder = DataLoader(all_cut, batch_size=BATCH_SIZE, shuffle=False, num_workers=0, drop_last=True) device = torch.device('cuda') model = SSKNet.SSKNet().to(device) criteon = nn.CrossEntropyLoss().to(device) optimizer = optim.Adam(model.parameters(), lr=LR, weight_decay=1e-5) schedulr = MultiStepLR(optimizer, milestones=[60, 90, 120, 150, 180, 200, 220, 240], gamma=0.9) # Generate spatial kernels kernel_weight_2, Data_Border_feature = Generate_Weights(Data_Border, HSI_CUT_SIZE, KERNEL_CUT_SIZE, KERNEL_BATCH_SIZE, kernel_weight_1, kernel_pos) kernel_weight_3, Data_Border_feature = Generate_Weights(Data_Border_feature, HSI_CUT_SIZE, KERNEL_CUT_SIZE, KERNEL_BATCH_SIZE, kernel_weight_2, kernel_pos) kernel_weight_4, Data_Border_feature = Generate_Weights(Data_Border_feature, HSI_CUT_SIZE, KERNEL_CUT_SIZE, KERNEL_BATCH_SIZE, kernel_weight_3, kernel_pos) # Train for epoch in range(EPOCH): model.train() schedulr.step() valid_idx = iter(valid_loder) for batchidx, (x, y) in enumerate(iter(train_loder)): x = torch.as_tensor(x, dtype= torch.float32).to(device) # weight-float32 Data-double64 y = torch.as_tensor(y, dtype= torch.long).to(device) # print(y.dtype) # print(batchidx) output = model(x, kernel_weight_1, kernel_weight_2, kernel_weight_3, kernel_weight_4, HSI_CUT_SIZE) loss = criteon(output, y) optimizer.zero_grad() loss.backward() optimizer.step() if batchidx % 40 == 0: loss = loss.data.cpu().numpy() x_v, y_v = next(valid_idx) x_v = torch.as_tensor(x_v, dtype= torch.float32).to(device) y_v = torch.as_tensor(y_v, dtype= torch.long).to(device) output_v = model(x_v, kernel_weight_1, kernel_weight_2, kernel_weight_3, kernel_weight_4, HSI_CUT_SIZE) output_v = output_v.data.cpu().numpy() kind_v = np.argmax(output_v, axis= 1) accuracy_v = 0 for idx_v, i in enumerate(kind_v): if i == y_v[idx_v]: accuracy_v += 1 accuracy_v = accuracy_v / (len(kind_v)) print('Epoch:', epoch, ' Batch:', batchidx, ' Loss:%.4f' % loss, ' Accuracy:%.2f' % (accuracy_v * 100)) num_t = 0 all_color = np.zeros((145, 145, 3)) all_result_label = np.zeros((145, 145)) for k, (x_t, y_t) in enumerate(iter(all_label_loder)): x_t = torch.as_tensor(x_t, dtype=torch.float32).to(device) y_t = torch.as_tensor(y_t, dtype=torch.long).to(device) output_t = model(x_t, kernel_weight_1, kernel_weight_2, kernel_weight_3, kernel_weight_4, HSI_CUT_SIZE) output_t = output_t.data.cpu().numpy() kind_t = np.argmax(output_t, axis=1) # print('kindt',kind_t.shape) for i, j in enumerate(kind_t): pred_label[num_t] = j num_t += 1 conf_mat = confusion_matrix(true_label, pred_label, labels=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) print(conf_mat) kappa_value = cohen_kappa_score(true_label, pred_label, labels=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) print('kappa:', kappa_value) dsa = 0 pe = 0 pe_rows = np.sum(conf_mat, axis=0) pe_cols = np.sum(conf_mat, axis=1) for i, diag in enumerate(conf_mat): pred = diag[i] dsa += diag[i] pe += diag[i] * diag[i] acr = pred / pe_cols[i] rep = pred / pe_rows[i] f1 = 2*acr*rep / (acr + rep) print(" Class %d: Accuracy: %.5f Recall: %.5f F1: %.5f" % (i, acr, rep, f1)) all_conf_mat = np.sum(conf_mat) p = dsa / all_conf_mat pe = pe / (all_conf_mat * all_conf_mat) kappa = (p - pe) / (1 - pe) print("OA: %.5f Kappa: %.5f" % (p, kappa)) for k_a, (x_a, y_a) in enumerate(iter(all_label_loder)): x_a = torch.as_tensor(x_a, dtype=torch.float32).to(device) output_t = model(x_a, kernel_weight_1, kernel_weight_2, kernel_weight_3, kernel_weight_4, HSI_CUT_SIZE) output_t = output_t.data.cpu().numpy() kind_t = np.argmax(output_t, axis=1) for i, j in enumerate(kind_t): xt, yt, lab = all_label_data1[k_a * x_a.shape[0] + i] # all_pos/ all_label_pos label_t = kind_t[i] if label_t == 0: all_color[xt][yt] = [255,255,102] all_result_label[xt][yt] = label_t if label_t == 1: all_color[xt][yt] = [0,48,205] all_result_label[xt][yt] = label_t if label_t == 2: all_color[xt][yt] = [255,102,0] all_result_label[xt][yt] = label_t if label_t == 3: all_color[xt][yt] = [0,255,104] all_result_label[xt][yt] = label_t if label_t == 4: all_color[xt][yt] = [255,48,205] all_result_label[xt][yt] = label_t if label_t == 5: all_color[xt][yt] = [102,0,255] all_result_label[xt][yt] = label_t if label_t == 6: all_color[xt][yt] = [0,154,255] all_result_label[xt][yt] = label_t if label_t == 7: all_color[xt][yt] = [0,255,0] all_result_label[xt][yt] = label_t if label_t == 8: all_color[xt][yt] = [128,128,0] all_result_label[xt][yt] = label_t if label_t == 9: all_color[xt][yt] = [128,0,128] all_result_label[xt][yt] = label_t if label_t == 10: all_color[xt][yt] = [47,205,205] all_result_label[xt][yt] = label_t if label_t == 11: all_color[xt][yt] = [0,102,102] all_result_label[xt][yt] = label_t if label_t == 12: all_color[xt][yt] = [47,205,48] all_result_label[xt][yt] = label_t if label_t == 13: all_color[xt][yt] = [102,48,0] all_result_label[xt][yt] = label_t if label_t == 14: all_color[xt][yt] = [102,255,255] all_result_label[xt][yt] = label_t if label_t == 15: all_color[xt][yt] = [255,255,0] all_result_label[xt][yt] = label_t io.imsave('./out_picture.png',all_color.astype(np.uint8))
108d0a3f01eb6a9c7c8f043006d7b72e61b831a4
[ "Markdown", "Python" ]
7
Python
Dalal1983/SSKNet
d32f15896fe3d5a008788f15fa9e738125291e2a
a784e0d1c9cdfe749c039881793fe42d62a63b15
refs/heads/master
<repo_name>lyang24/Thinkful<file_sep>/random_forest.py #cleaning data with pandas import pandas as pd #read tables activity = pd.read_table('C:\Users\<NAME>\Documents\UCI HAR Dataset/activity_labels.txt', header=None, sep=' ', names=('ID','Activity')) features = pd.read_table('C:\Users\<NAME>\Documents\UCI HAR Dataset/features.txt', sep=' ', header=None, names=('ID','Sensor')) X_test = pd.read_table('C:\Users\<NAME>\Documents\UCI HAR Dataset/test/X_test.txt', sep='\s+', header=None) y_test = pd.read_table('C:\Users\<NAME>\Documents\UCI HAR Dataset/test/y_test.txt', sep=' ', header=None, names=['activity']) X_train = pd.read_table('C:\Users\<NAME>\Documents\UCI HAR Dataset/train/X_train.txt', sep='\s+', header=None) y_train = pd.read_table('C:\Users\<NAME>\Documents\UCI HAR Dataset/train/y_train.txt', sep=' ', header=None, names=['activity']) Sub_train = pd.read_table('C:\Users\<NAME>\Documents\UCI HAR Dataset/train/subject_train.txt', header=None, names=['SubjectID']) Sub_test = pd.read_table('C:\Users\<NAME>\Documents\UCI HAR Dataset/test/subject_test.txt', header=None, names=['SubjectID']) #one big ah-ha moment sep = '' generate an error instead use sep = ' ' #some times\t would cause system to not read part of the path #restore the original data allX = pd.concat([X_test, X_train], ignore_index = True) ally = pd.concat([y_test, y_train], ignore_index = True) sensorNames = features['Sensor'] allX.columns = sensorNames # just in case i want to train_test_split in future X_train.columns = sensorNames X_test.columns = sensorNames allSub = pd.concat([Sub_train, Sub_test], ignore_index=True) fdata = pd.concat([allX, allSub], axis=1) allY = y_train.append(y_test, ignore_index=True) #one big ah-ha moment sep = '' generate an error instead use sep = ' ' #some times\t would cause system to not read part of the path #restore the original data allX = pd.concat([X_test, X_train], ignore_index = True) ally = pd.concat([y_test, y_train], ignore_index = True) sensorNames = features['Sensor'] allX.columns = sensorNames # just in case i want to train_test_split in future X_train.columns = sensorNames X_test.columns = sensorNames allSub = pd.concat([Sub_train, Sub_test], ignore_index=True) fdata = pd.concat([allX, allSub], axis=1) allY = y_train.append(y_test, ignore_index=True) import numpy as np from sklearn.metrics import roc_auc_score from sklearn.ensemble import RandomForestClassifier #allX.describe() #make sure there is no nan values #train model to set a bench mark model = RandomForestClassifier(n_estimators = 50, oob_score=True, random_state=42) %time model.fit(X_train,y_train['activity'].values) model.oob_score_ #0.9787812840043526 y_pred_class = model.predict(X_test) # valiadate model #Accuracy from sklearn import metrics print metrics.accuracy_score(y_test, y_pred_class) #92% #confusion matrix confusion = metrics.confusion_matrix(y_test,y_pred_class) print confusion #[[481 11 4 0 0 0] # [ 50 415 6 0 0 0] # [ 17 38 365 0 0 0] # [ 0 0 0 440 51 0] # [ 0 0 0 46 486 0] # [ 0 0 0 0 0 537]]<file_sep>/kmeans1.py from scipy.spatial.distance import cdist, pdist import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/Thinkful-Ed/curric-data-001-data-sets/master/un/un.csv') #df.count() X = df.drop(df.columns[:6], axis=1) X = X.drop(X.columns[4:], axis = 1) #how to extract columns better? X = X.dropna() import numpy as np from sklearn.cluster import KMeans k_range = (1,10) kmeans = [KMeans(n_clusters=number, random_state=42).fit(X) for number in k_range] #train model centroids = [i.cluster_centers_ for i in kmeans] #compute centriods k_euclid_distance = [cdist(X, cent, 'euclidean') for cent in centroids] #each point to each cluster center dist = [np.min(ke,axis = 1) for ke in k_euclid_distance] wcss = [sum(d**2) for d in dist] #Total within-cluster sum of squares tss = sum(pdist(X)**2)/X.shape[0] #Total sum of squares bss = tss - wcss #between-cluster sum of squares<file_sep>/knn.py import numpy as np from sklearn.datasets import load_iris from sklearn.neighbors import KNeighborsClassifier from sklearn.cross_validation import train_test_split from sklearn import metrics iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.3, random_state = 4) scores = [] #set up and tuning the model for k in range(1, 15): knn = KNeighborsClassifier(n_neighbors = k) knn.fit(X_train, y_train) y_predict = knn.predict(X_test) scores.append(metrics.accuracy_score(y_test,y_predict)) print scores # use k = 3 # retrain the model with entire dateset knn = KNeighborsClassifier(n_neighbors=3) knn.fit(X,y)<file_sep>/cross_validation.py import numpy as np import pandas as pd import statsmodels.api as sm loansData = pd.read_csv('https://github.com/Thinkful-Ed/curric-data-001-data-sets/raw/master/loans/loansData.csv') loansData['FICO.Range'] = loansData['FICO.Range'].apply(lambda x: x.split('-')[0]) loansData['FICO.Range'] = loansData['FICO.Range'].astype(float) loansData['Interest.Rate'] = loansData['Interest.Rate'].map(lambda x: x.rstrip('%')) loansData['Interest.Rate'] = loansData['Interest.Rate'].astype(float) loansData['Loan.Length'] =loansData['Loan.Length'].map(lambda x: x.rstrip(' months')) loansData['Loan.Length'] =loansData['Loan.Length'].astype(int) intrate = loansData['Interest.Rate'] loanamt = loansData['Amount.Requested'] fico = loansData['FICO.Range'] y = np.matrix(intrate).transpose() x1 = np.matrix(fico).transpose() x2 = np.matrix(loanamt).transpose() x = np.column_stack([x1,x2]) X = sm.add_constant(x) model = sm.OLS(y,X) f = model.fit() from sklearn.model_selection import KFold kf = KFold(n_splits=10) model = sm.OLS(y[train], X[train]) for train, test in kf.split(X): model = sm.OLS(y[train], X[train]).fit() y_predicted = model.predict(X[test]) y_actual = y[test] #loop MSE & r**2 print ((y_actual - y_predicted)**2).mean()<file_sep>/cv.py from sklearn import svm from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target from sklearn.cross_validation import cross_val_score svc = svm.SVC(kernel='linear') scores = cross_val_score(svc, X, y, cv=5, scoring = 'accuracy') print scores.mean() #0.98<file_sep>/overfitting.py import numpy as np import pandas as pd import statsmodels.formula.api as smf from sklearn import metrics import matplotlib.pyplot as plt np.random.seed(414) # Gen toy data x = np.linspace(0, 15, 1000) y = 3 * np.sin(x) + np.random.normal(1 + x, .2, 1000) train_x, train_y = x[:700], y[:700] test_x, test_y = x[700:], y[700:] train_df = pd.DataFrame({'x': train_x, 'y': train_y}) test_df = pd.DataFrame({'x': test_x, 'y': test_y}) poly_1 = smf.ols(formula='y ~ 1 + x', data=train_df).fit() # poly_1.summary() #R-squared: 0.642 #Liner fit y1 = poly_1.predict(test_df) poly_2 = smf.ols(formula='y ~ 1 + x + I(x**2)', data=train_df).fit() #poly_2.summary() #R-squared: 0.666 # Quadratic Fit y2 = poly_2.predict(test_df) plt.plot(x, y, label='original') plt.plot(test_x, y1, label='linear') plt.plot(test_x, y2, label='quadratic') plt.show() print metrics.accuracy_score(y[700:], y1) print metrics.accuracy_score(y[700:], y2) #value error<file_sep>/database.py import sqlite3 as lite import pandas as pd #preload data cities = (('New York City', 'NY'), ('Boston', 'MA'), ('Chicago', 'IL'), ('Miami', 'FL'), ('Dallas', 'TX'), ('Seattle', 'WA'), ('Portland', 'OR'), ('San Francisco', 'CA'), ('Los Angeles', 'CA'), ('Washington', 'DC'), ('Hoston', 'TX'), ('Las Vegas', 'NV'), ('Atlanta', 'GA')) weather = (('New York City',2013,'July','January',62), ('Boston',2013,'July','January',59), ('Chicago',2013,'July','January',59), ('Miami',2013,'August','January',84), ('Dallas', 2013,'July','January',77)) con = lite.connect('test.db') # Set up database(create tables and insert prepared value) with con: cur = con.cursor() cur.execute("DROP TABLE IF EXISTS cities;") cur.execute("DROP TABLE IF EXISTS weather;") cur.execute("CREATE TABLE cities (name text, state text);") cur.execute("CREATE TABLE weather ('city' text, 'year' integer, 'warm_month' text, 'cold_month' text,'average_high' integer);") cur.executemany("INSERT INTO cities VALUES(?,?)", cities) cur.executemany("INSERT INTO weather VALUES(?,?,?,?,?)", weather) #join tables and load data into pandas data frames cur.execute("SELECT name, state, year, warm_month, cold_month FROM cities INNER JOIN weather ON name = city;") rows = cur.fetchall() cols = [desc[0] for desc in cur.description] df = pd.DataFrame(rows, columns=cols) <file_sep>/multivariate.py import numpy as np import pandas as pd import statsmodels.api as sm loansData = pd.read_csv('https://github.com/Thinkful-Ed/curric-data-001-data-sets/raw/master/loans/loansData.csv') loansData['FICO.Range'] = loansData['FICO.Range'].apply(lambda x: x.split('-')[0]) loansData['FICO.Range'] = loansData['FICO.Range'].astype(float) loansData['Interest.Rate'] = loansData['Interest.Rate'].map(lambda x: x.rstrip('%')) loansData['Interest.Rate'] = loansData['Interest.Rate'].astype(float) loansData['Loan.Length'] =loansData['Loan.Length'].map(lambda x: x.rstrip(' months')) loansData['Loan.Length'] =loansData['Loan.Length'].astype(int) loansData['Home.Ownership.ord'] = pd.Categorical(loansData['Home.Ownership']).codes # I learned how to replace NAN with 0 loansData['Monthly.Income'].fillna(0, inplace=True) intrate = loansData['Interest.Rate'] loanamt = loansData['Amount.Requested'] fico = loansData['FICO.Range'] income = loansData['Monthly.Income'] own = loansData['Home.Ownership.ord'] y = np.matrix(intrate).transpose() x1 = np.matrix(fico).transpose() x2 = np.matrix(loanamt).transpose() x3 = np.matrix(income).transpose() x4 = np.matrix(own).transpose() x = np.column_stack([x1,x2,x3,x4]) X = sm.add_constant(x) model = sm.OLS(y,X) f = model.fit() f.summary()<file_sep>/svm.py import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score iris = datasets.load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42) scores = [] for i in range (1,10): svc = svm.SVC(kernel = 'linear', C = i) svc.fit(X_train, y_train) results = svc.predict(X_test) scores.append(accuracy_score) # bias and variance trade off <file_sep>/losgistic_regression.py import pandas as pd import statsmodels.api as sm import math #upgraded version - thanks to my mentor kyle # Train model def train_model(fname): cleanloansData = pd.read_csv(fname) cleanloansData['IR_TF'] = cleanloansData['Interest.Rate'].map(lambda x: 0 if x < 12 else 1) cleanloansData['Intercept'] = 1.0 # ind_vars = list(cleanloansData.columns.values) ind_vars = ['Amount.Requested', 'FICO.Range','Intercept' ] logit = sm.Logit(cleanloansData['IR_TF'], cleanloansData[ind_vars]) result = logit.fit() coeff = result.params return coeff def run_model(coeff, v, yz): p = 1.0/(1 + math.exp(coeff[2] + coeff[1] * yz - coeff[0] * v)) print(p) coeff = train_model('C:\\Users\<NAME>\loansData_clean.csv') run_model(coeff, 1000, 750) # Expectations run_model(coeff, 10000000, 250) # Should reject! run_model(coeff, 10, 820) # Obviously accept! # Get use case of the model as input v = float(input("How much do you want to borrow ")) yz = float(input("what is your FICO score ")) run_model(coef, v, yz) <file_sep>/prob.py import numpy as np import scipy.stats as stats import matplotlib.pyplot as plt x = [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 4, 4, 4, 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9] plt.boxplot(x) plt.show() plt.hist(x, histtype='bar') plt.show() plt.figure() graph = stats.probplot(x, plot = plt) plt.show() <file_sep>/city_bike.py import requests from pandas.io.json import json_normalize import matplotlib.pyplot as plt import pandas as pd import sqlite3 as lite import time from dateutil.parser import parse import collections import datetime #IntegrityError: UNIQUE constraint failed: citibike_reference.id url = 'http://www.citibikenyc.com/stations/json' sql = "INSERT INTO citibike_reference (id, totalDocks, city, altitude, stAddress2, longitude, postalCode, testStation, stAddress1, stationName, landMark, latitude, location) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)" con = lite.connect('citi_bike.db') cur = con.cursor() # get data def gcdata(url, sql, con, cur): r = requests.get(url) df = json_normalize(r.json()['stationBeanList']) exec_time = parse(r.json()['executionTime']) # set up sqlite3 connection # for loops populating data with con: cur.execute('INSERT INTO available_bikes (execution_time) VALUES (?)', (exec_time.strftime('%Y-%m-%dT%H:%M:%S'),)) #for station in r.json()['stationBeanList']: #id, totalDocks, city, altitude, stAddress2, longitude, postalCode, testStation, stAddress1, stationName, landMark, latitude, location) # cur.execute(sql,(station['id'],station['totalDocks'],station['city'],station['altitude'],station['stAddress2'],station['longitude'],station['postalCode'],station['testStation'],station['stAddress1'],station['stationName'],station['landMark'],station['latitude'],station['location'])) for station in r.json()['stationBeanList']: cur.execute("UPDATE available_bikes SET _" + str(k) + " = " + str(v) + " WHERE execution_time = " + str((exec_time - datetime.datetime(1970,1,1)).total_seconds()) + ";") con.commit print('data imported') # looping to retrive and analyze an hour of bike data for times in range(60): gcdata(url, sql, con, cur) time.sleep(60)<file_sep>/prob_lending_club.py import matplotlib.pyplot as plt import pandas as pd import scipy.stats as stats loansdata = pd.read_csv('https://github.com/Thinkful-Ed/curric-data-001-data-sets/raw/master/loans/loansData.csv') loansdata.dropna(inplace = True) loansdata.boxplot(column = 'Amount.Funded.By.Investors') plt.savefig('Loan-data-Boxplot.png') loansdata.hist(column='Amount.Funded.By.Investors') plt.show('Loan-data-histogram.png') plt.figure() graph = stats.probplot(loansdata['Amount.Funded.By.Investors'], dist="norm", plot=plt) plt.savefig('Loan-data-qq-plot.png')<file_sep>/naive_bayes.py import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/Thinkful-Ed/curric-data-001-data-sets/master/ideal-weight/ideal_weight.csv') #data cleaning x = list(df.columns.values) for i in range(len(x)): x[i] = x[i].replace("'", "") df.columns = x df['sex'] = df['sex'].astype(str) df['sex'] = df['sex'].apply(lambda x: x.replace("'", "")) df['sex'] = pd.Categorical(df['sex']).codes # 1 - male, 0 - female #how to display 2 histogram??? #df.hist(column='ideal') #df.hist(column='actual') #plt.legend(loc='upper right') #plt.show() # build model # inspritions - df_X = df[df.AScan.notnull()][['total_length', 'vowel_ratio', 'twoLetters_lastName']].values from sklearn.naive_bayes import GaussianNB clf = GaussianNB() x = df[['sex']].values y = df[['actual', 'ideal', 'diff']].values clf.fit(y,x) #test model print(clf.predict([[145, 160, -15]])) # male print(clf.predict([[160, 145, 15]])) # female # makes sense guys wants to get bigger, girl wants to stay fit #How many points were mislabeled? How many points were there in the dataset, total? #not sure how to answer <file_sep>/linear_regression.py import numpy as np import pandas as pd import statsmodels.api as sm loansData = pd.read_csv('https://github.com/Thinkful-Ed/curric-data-001-data-sets/raw/master/loans/loansData.csv') loansData['FICO.Range'] = loansData['FICO.Range'].apply(lambda x: x.split('-')[0]) loansData['FICO.Range'] = loansData['FICO.Range'].astype(float) loansData['Interest.Rate'] = loansData['Interest.Rate'].map(lambda x: x.rstrip('%')) loansData['Interest.Rate'] = loansData['Interest.Rate'].astype(float) loansData['Loan.Length'] =loansData['Loan.Length'].map(lambda x: x.rstrip(' months')) loansData['Loan.Length'] =loansData['Loan.Length'].astype(int) intrate = loansData['Interest.Rate'] loanamt = loansData['Amount.Requested'] fico = loansData['FICO.Range'] y = np.matrix(intrate).transpose() x1 = np.matrix(fico).transpose() x2 = np.matrix(loanamt).transpose() x = np.column_stack([x1,x2]) X = sm.add_constant(x) model = sm.OLS(y,X) f = model.fit() f.summary()<file_sep>/tempurature.py import pandas as pd import datetime as dt import requests import sqlite3 as lite con = lite.connect('weather.db') cur = con.cursor() cities.keys() #set up table #with con: #cur.execute('CREATE TABLE daily_temp ( day_of_reading INT, Atlanta REAL, Austin REAL, Boston REAL, Chicago REAL, Cleveland REAL);') api_key = '042476534a83cd8a28fd35226ad56eb7' cities ={ "Atlanta": '33.762909,-84.422675', "Austin": '30.303936,-97.754355', "Boston": '42.331960,-71.020173', "Chicago": '41.837551,-87.681844', "Cleveland": '41.478462,-81.679435' } for i, j in cities.iteritems(): while qry_date < datetime.datetime.now(): url = 'https://api.forecast.io/forecast/' + api_key + '/' + i + ',' + qry_date.strftime('%Y-%m-%dT12:00:00') # /LATITUDE,LONGITUDE,TIME r = requests.get(url) with con: cur.execute('UPDATE daily_temp SET ' + j + ' = ' + str(r.json()['daily']['data'][0]['temperatureMax']) + ' WHERE day_of_reading = ' + query_date.strftime('%d')) qry_date += datetime.timedelta(days =1) con.close #ValueError: No JSON object could be decoded? server data error? <file_sep>/stats.py import pandas as pd data = '''Region,Alcohol,Tobacco North,6.47,4.03 Yorkshire,6.13,3.76 Northeast,6.19,3.77 East Midlands,4.89,3.34 West Midlands,5.63,3.47 East Anglia,4.52,2.92 Southeast,5.89,3.20 Southwest,4.79,2.71 Wales,5.27,3.53 Scotland,6.08,4.51 Northern Ireland,4.02,4.56''' data = data.splitlines() #split string by line data = [i.split(',') for i in data] #further split by comma column_names = data[0] # this is the first row data_rows = data[1::] # these are all the following rows of data df = pd.DataFrame(data_rows, columns=column_names) df['Alcohol'] = df['Alcohol'].astype(float) df['Tobacco'] = df['Tobacco'].astype(float) m1 = df['Alcohol'].mean() m2 = df['Alcohol'].median() #m3 = df['Alcohol'].mode() m4 = max(df['Alcohol']) - min(df['Alcohol']) m5 = df['Alcohol'].std() m6 = df['Alcohol'].var() m7 = max(df['Tobacco']) - min(df['Tobacco']) m8 = df['Tobacco'].std() m9 = df['Tobacco'].var() m10 = df['Tobacco'].mean() m11 = df['Tobacco'].median() #m12 = df['Tobacoo'].mode() print("the mean for Alcohol and Tobacco in this dataset is: {} and {}".format(m1,m10)) print("the variance for Alcohol is {} and the variance for Tobacco in this dataset is {}".format(m6,m9)) print("In this dataset Alcohol range is {} and Tobacco range is {}".format(m4, m7)) print("the standard deviation for Alcohol and Tobacco in this dataset is: {} and {}".format(m5,m8)) print("the median for Alcohol and Tobacco in this dataset is: {} and {}".format(m2,m11)) #print("the mode for Alcohol and Tobacco in this dataset is: {} and {}".format(m3,m12))<file_sep>/monte_carlo.py import random import numpy as np import matplotlib.pyplot as plt # let's create a fair coin object that can be flipped: Results = [] maxs = [] mins = [] class Coin(object): '''this is a Modified coin, normal distribution''' sides = np.random.normal(100, 15, size=10000) last_result = None def flip(self): '''call coin.flip() to flip the coin and record it as the last result''' self.last_result = result = random.choice(self.sides) return result # let's create some auxilliary functions to manipulate the coins: def create_coins(number): '''create a list of a number of coin objects''' return [Coin() for _ in xrange(number)] def flip_coins(coins): '''side effect function, modifies object in place, returns None''' for coin in coins: coin.flip() def the_max(flipped_coins): return max(coin.last_result for coin in flipped_coins) def the_min(flipped_coins): return min(coin.last_result for coin in flipped_coins) def capture(flipped_coins): return list(coin.last_result for coin in flipped_coins) def main(): coins = create_coins(10) for i in xrange(100): flip_coins(coins) maxs.append(the_max(coins)) mins.append(the_min(coins)) Results.extend(capture(coins)) # I learned the difference between append and extednd, append in this case will create multi dimensional array if __name__ == '__main__': main() % matplotlib inline plt.hist(Results) # replace Results with maxs or mins to get the distribution of the extremes plt.title('Distribution') plt.show()<file_sep>/education.py from bs4 import BeautifulSoup import requests import pandas as pd import csv import statsmodels.api as sm # get raw html url = "http://web.archive.org/web/20110514112442/http://unstats.un.org/unsd/demographic/products/socind/education.htm" def make_soup(url): r = requests.get(url) soupdata = BeautifulSoup(r.content, 'html.parser') return soupdata soup = make_soup(url) rows = [] data = soup('table')[6] # I feel like i am hard coding this for record in data.find_all('tr')[8:]: rows.append([val.text.encode('utf8') for val in record.find_all('td')]) with open('C:\Users\<NAME>\Desktop\out.csv', 'wb') as f: writer = csv.writer(f) writer.writerows(row for row in rows) #DATA IS NOT PERFECT import sqlite3 as lite con = lite.connect('edu.db') cur = con.cursor() with con: cur.execute('CREATE TABLE edulife (country TEXT PRIMARY KEY, year INTEGER, male_avg INTEGER, female_avg INTEGER);') with open('C:\Users\<NAME>\Desktop\out.csv','rU') as inputFile1: inputReader1 = csv.reader(inputFile1) import sqlite3 as lite with con: #cur.execute('DROP TABLE gdp;') cur.execute('CREATE TABLE gdp (country_name TEXT,Country Code TEXT PRIMARY KEY, _1999 REAL, _2000 REAL, _2001 ,REAL _2002 REAL, _2003 REAL, _2004 REAL, _2005 REAL, _2006 REAL, _2007 REAL, _2008 REAL, _2009 REAL, _2010 REAL);') with open('C:\Users\<NAME>\Desktop\API_NY.GDP.MKTP.CD_DS2_en_csv_v2.csv','rU') as inputFile: next(inputFile) # skip the first 3 lines next(inputFile) next(inputFile) header = next(inputFile) inputReader = csv.reader(inputFile) for line in inputReader: with con: cur.execute('INSERT INTO gdp (country_name, _1999, _2000, _2001, _2002, _2003, _2004, _2005, _2006, _2007, _2008, _2009, _2010) VALUES ("' + line[0] + '","' + '","'.join(line[43:55]) + '");') with con: cur.execute('SELECT * FROM gdp INNER JOIN edulife ON edulife.country = gdp.country_name;') rows = cur.fetchall() cols = [desc[0] for desc in cur.description] df = pd.DataFrame(rows, columns=cols) #check if data is imported correctly #with con: #for row in cur.execute('SELECT * FROM gdp;'): #print (row) # the data set is finished use regression to test out if gdp is correlated with education life.
3031d2c79937f65f50694d4881c518a8c3f8af82
[ "Python" ]
19
Python
lyang24/Thinkful
9d77f291437ddeab6b9b3f74f4bde96d82a285df
0f26ce1e33da1b18681eabb6d320f3c0c5fab431
refs/heads/master
<file_sep>""" # 新增价格区域 http://test.dairyqueen.com.cn/api/v1/product/3850201175919951873/region/market?stringified=true allow_sale: true currency: "CNY" id: "4055613822868967425" retail: 10 takeaway_dianping_mobile: false tax_rate: 0 unit_id: "3932395201819324417" # 生效价格 http://test.dairyqueen.com.cn/api/v1/product/region/market/4522654325176737793/state/enable?stringified=true """ import requests import openpyxl import pymongo import time from random import randint # store_url = 'http://test.dairyqueen.com.cn' store_url = 'http://store.dairyqueen.com.cn' default_unit_id = '3932395201819324417' headers = { 'authorization': '{}'.format('Bearer eJpUMkgXOrWKFIvnm8WwBA'), # 该env环境下的authorization 'Cookie': 'hex_server_session={}'.format('c1d28cbd-8cec-4b5c-bac8-ca357567154c'), # 该env环境下的Cookie } USER_AGENTS = [ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)", "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)", "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)", "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)", "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0", "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20", "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52", ] def get_product_id_by_mongo(): mongo_client = pymongo.MongoClient(host='127.0.0.1', port=27072,) db_name = mongo_client.saas_dq query = { 'status': 'ENABLED', 'data_state': 'ENABLED' } result = db_name.product.find(query, {'_id': 1, 'name': 1, 'code': 1, 'relation.unit.id': 1}) product_dic = {r['code']: r for r in result} product_ids = [i['_id'] for i in list(product_dic.values())] return product_dic, product_ids def get_product_market_raltion(product_ids): mongo_client = pymongo.MongoClient(host='127.0.0.1', port=27072,) db_name = mongo_client.saas_dq # format_ids = ["NumberLong('{}'.format(i))" for i in product_ids] query = { 'org_id': {'$in': product_ids}, 'to_org_type': 'market_region', 'data_state': 'DRAFT' } result = db_name.product_relation.find(query, {'_id': 1, 'org_id': 1}) product_market_relation_res = {i['org_id']: i['_id'] for i in result} return product_market_relation_res path = '/Users/hws/Downloads/DQ商品售价-市场区域-20210810(拉萨门店).xlsx' wb = openpyxl.load_workbook(path) sh = wb['Sheet2'] rows = sh.max_row cols = sh.max_column # print(rows, cols) product_dic, product_ids = get_product_id_by_mongo() # print(product_dic) all_ids = [] for row in range(2, rows + 1): product_code = str(sh.cell(row, 2).value) market_code = str(sh.cell(row, 4).value) price = str(sh.cell(row, 5).value) product_id = product_dic.get(product_code, {}).get('_id') unit_id_res = product_dic.get(product_code, {}).get('relation', {}).get('unit', []) unit_id = unit_id_res and unit_id_res[0].get('id') or default_unit_id if not product_id: print('第{}行商品{}不存在'.format(row, product_code)) continue all_ids.append(product_id) data = { 'market': [{ 'allow_sale': True, 'currency': "CNY", 'id': "4522620766904156160", # 市场区域ID, 就改一个,先写成固定的 'retail': price, 'takeaway_dianping_mobile': False, 'tax_rate': 0, 'unit_id': unit_id }] } # print(data) random_agent = USER_AGENTS[randint(0, len(USER_AGENTS)-1)] headers.update({ 'User-Agent':random_agent, }) res = requests.post(store_url + '/api/v1/product/{}/region/market?stringified=true'.format(product_id), headers=headers, json=data) print(res.json()) time.sleep(1) print(len(all_ids)) product_market_relation_res = get_product_market_raltion(all_ids) for i in all_ids: # if str(i) != '3850201109834498049': # continue relation_id = product_market_relation_res.get(i) print(i, relation_id) random_agent = USER_AGENTS[randint(0, len(USER_AGENTS)-1)] headers.update({ 'User-Agent':random_agent, }) requests.put(store_url + '/api/v1/product/region/market/{}/state/enable?stringified=true'.format(relation_id), headers=headers) time.sleep(0.5) <file_sep>import rsa import base64 private_key = """-----<KEY> kp<KEY>""" public_key = """-----<KEY>""" string_sign_temp = 'ni hao a!!' private_key = rsa.PrivateKey.load_pkcs1(private_key.encode()) sign = base64.b64encode(rsa.sign(string_sign_temp.encode(), private_key, 'SHA-1')).decode('utf-8') print('get sign is :') print(sign) print('==' * 20) public_key = rsa.PublicKey.load_pkcs1_openssl_pem(public_key) # ori_str = rsa.decrypt(base64.b64decode(sign.encode('utf-8')), public_key).decode() # print(ori_str) print(base64.b64decode(sign.encode('utf-8'))) # r = rsa.verify(string_sign_temp, base64.b64decode(sign.encode('utf-8')), public_key) # print(r) print(rsa.decrypt(base64.b64decode(sign.encode('utf-8')), public_key))<file_sep># 先从MongoDB读取shop的信息,要手动格式化一下,或者有api读取shop信息 import openpyxl import requests shop_list = [{ "_id": "3850146064724131841", "name": "嘉定罗宾森店", "extend_code": { "comm_shop_id": "3601d022edb545c5bf8aa2dab4bcd6a6", "ex_code": "20016", "alipay_id": "2015060900077000000000176457", "us_id": "42041", "comm_code": "301003400000115", "upcard_terminal": "02148860", "upcard_mer_id": "102210058120739", "ex_id": "223", "ex_cost_center_code": "1200042041", "dcore_store_appid": "s20170823000005197" } }, { "_id": "3850146080528269313", "name": "上海仲盛店", "extend_code": { "comm_shop_id": "cddcc4bd4cf24ba4ade6d7606fa4b48d", "ex_code": "20043", "alipay_id": "2015060900077000000000178453", "us_id": "42256", "comm_code": "301003400000377", "upcard_terminal": "02194925", "upcard_mer_id": "102210058120718", "ex_id": "240", "ex_cost_center_code": "1200042256", "dcore_store_appid": "s20170823000005487" } }, { "_id": "3850146089889955841", "name": "重庆洪崖洞店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20053", "comm_shop_id": "b0d8987d48c043a1b2fdf1bec7f95fd4", "us_id": "42337", "alipay_id": "2015061200077000000000193010", "takeaway_eleme_id": '', "upcard_terminal": "02306269", "comm_code": "301003400000320", "upcard_mer_id": "102230058120110", "ex_id": "632", "ex_cost_center_code": "1200042337", "dcore_store_appid": "s20170823000005496" } }, { "_id": "3850146093790658561", "name": "徐州彭城店", "extend_code": { "comm_shop_id": "71930119cd0d49fa8db1dbc99570087f", "ex_code": "20060", "alipay_id": "2015061100077000000000182834", "us_id": "42378", "comm_code": "301003400000225", "upcard_terminal": "51211252", "upcard_mer_id": "102512058120390", "ex_id": "991", "ex_cost_center_code": "1200042378", "dcore_store_appid": "s20170823000005562" } }, { "_id": "3850146067915997185", "name": "南京水游城", "extend_code": { "comm_shop_id": "f23da3b0a54f4b4698a31a74df9c1bcc", "ex_code": "20022", "alipay_id": "2015061000077000000000191173", "us_id": "42134", "comm_code": "301003400000435", "upcard_terminal": "02516545", "upcard_mer_id": "102250058120833", "ex_id": "304", "ex_cost_center_code": "1200042134", "dcore_store_appid": "s20170823000005478" } }, { "_id": "3850146075474132993", "name": "上海华诚店", "extend_code": { "comm_shop_id": "b64aa6c8e7be4a068064cff1e6d5fc6d", "ex_code": "20033", "alipay_id": "2015060900077000000000174612", "us_id": "42253", "comm_code": "301003400000334", "upcard_terminal": "02148897", "upcard_mer_id": "102210058120702", "ex_id": "241", "ex_cost_center_code": "1200042253", "dcore_store_appid": "s20170823000005486" } }, { "_id": "3850146102749691905", "name": "大华店", "extend_code": { "comm_shop_id": "36327010dc4b4406ad080b6e88663884", "ex_code": "20078", "alipay_id": "2015060900077000000000174615", "us_id": "42427", "comm_code": "301003400000116", "upcard_terminal": "02194800", "upcard_mer_id": "102210058126900", "ex_id": "261", "ex_cost_center_code": "1200042427", "dcore_store_appid": "s20170823000005210" } }, { "_id": "3850146106943995905", "name": "宁波银泰江东店", "extend_code": { "comm_shop_id": "49e6e190ceca4f1eb1de70d968aefdf4", "ex_code": "20086", "alipay_id": "2015060900077000000000178459", "us_id": "42467", "comm_code": "301003400000149", "upcard_terminal": "57401978", "upcard_mer_id": "102574058120109", "ex_id": "433", "ex_cost_center_code": "1200042467", "dcore_store_appid": "s20170823000005573" } }, { "_id": "3850146109762568193", "name": "上海飞洲店", "extend_code": { "comm_shop_id": "4dc4941a29ed4c529a839cd9b9195922", "ex_code": "20092", "alipay_id": "2020011500077000000086880219", "us_id": "42503", "comm_code": "301003400000335", "upcard_terminal": "02194796", "upcard_mer_id": "102210058126896", "ex_id": "270", "ex_cost_center_code": "1200042503", "dianping_store_id": "4125018", "dcore_store_appid": "s20170823000005500" } }, { "_id": "3850146111314460673", "name": "重庆西城天街店", "extend_code": { "comm_shop_id": "07a1ce65483744dd92f681d82438fe55", "ex_code": "20095", "alipay_id": "2015061200077000000000188807", "us_id": "42507", "comm_code": "301003400000033", "upcard_terminal": "02306262", "upcard_mer_id": "102230058120117", "ex_id": "638", "ex_cost_center_code": "1200042507", "dcore_store_appid": "s20170823000005213" } }, { "_id": "3850146118616743937", "name": "太原铜锣湾店", "extend_code": { "comm_shop_id": "952bb1e3197045ae9b23d8b94cc969a9", "ex_code": "20109", "alipay_id": "2015061100077000000000191215", "us_id": "42572", "comm_code": "301003400000274", "upcard_terminal": "35103739", "upcard_mer_id": "102351058121620", "ex_id": "691", "ex_cost_center_code": "1200042572", "dcore_store_appid": "s20170823000005507" } }, { "_id": "3850146062694088705", "name": "成都盐市口店", "extend_code": { "comm_shop_id": "c506ba759c104ee48adc51c1a3958f78", "ex_code": "20012", "alipay_id": "2015061200077000000000182874", "us_id": "41961", "comm_code": "301003400000355", "upcard_terminal": "02817522", "upcard_mer_id": "102280058121932", "ex_id": "209", "ex_cost_center_code": "1200041961", "dcore_store_appid": "s20170823000005471" } }, { "_id": "3850146114422439937", "name": "淮安中央新亚店", "extend_code": { "comm_shop_id": "9e54150610e340fe8e677d68ded338b9", "ex_code": "20101", "alipay_id": "2015061100077000000000188753", "us_id": "42571", "comm_code": "301003400000293", "upcard_terminal": "51211882", "upcard_mer_id": "102512058120392", "ex_id": "611", "ex_cost_center_code": "1200042571", "dcore_store_appid": "s20170929000006494" } }, { "_id": "3850146068947795969", "name": "常熟虞景文华店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20024", "comm_shop_id": "f65c1f05e9e740e791f44c4e08a7d961", "us_id": "42144", "alipay_id": "2015061100077000000000191198", "takeaway_eleme_id": '', "upcard_terminal": "51215443", "comm_code": "301003400000443", "upcard_mer_id": "102512058123023", "ex_id": "554", "ex_cost_center_code": "1200042144", "dcore_store_appid": "s20170823000005199" } }, { "_id": "3850146069987983361", "name": "福州万象城店", "extend_code": { "comm_shop_id": "169177d275b0427a82535c201bf57cba", "ex_code": "20026", "alipay_id": "2015061200077000000000192991", "us_id": "42207", "comm_code": "301003400000056", "upcard_terminal": "59105748", "upcard_mer_id": "102591058120151", "ex_id": "854", "ex_cost_center_code": "1200042207", "dcore_store_appid": "s20170823000005481" } }, { "_id": "3850146123163369473", "name": "宜昌万达店", "extend_code": { "comm_shop_id": "ee762a825b4d4a1f9f31c99139ef16b8", "ex_code": "20117", "alipay_id": "2015061200077000000000194551", "us_id": "42614", "comm_code": "301003400000428", "upcard_terminal": "71700535", "upcard_mer_id": "102717058120032", "ex_id": "792", "ex_cost_center_code": "1200042614", "dcore_store_appid": "s20170823000005514" } }, { "_id": "3850146071627956225", "name": "常州莱蒙店", "extend_code": { "comm_shop_id": "5963ee101ddd44ddaa4780a0541d8d6f", "ex_code": "20029", "alipay_id": "2015061000077000000000192926", "us_id": "42229", "comm_code": "301003400000181", "upcard_terminal": "51211275", "upcard_mer_id": "102512058120367", "ex_id": "556", "ex_cost_center_code": "1200042229", "dcore_store_appid": "s20170823000005484" } }, { "_id": "3850146131107381249", "name": "上海我格广场店", "extend_code": { "comm_shop_id": "c0098057bb5445c5b0b182f4346c1b3c", "ex_code": "20132", "alipay_id": "2015060900077000000000176463", "us_id": "42582", "comm_code": "301003400000344", "upcard_terminal": "02148838", "upcard_mer_id": "102210058120844", "ex_id": "283", "ex_cost_center_code": "1200042582", "dcore_store_appid": "s20170823000005508" } }, { "_id": "3850146072097718273", "name": "扬州珍园店", "extend_code": { "comm_shop_id": "a730f974c3e447d3be04e808ceecbdde", "ex_code": "20030", "alipay_id": "2015061100077000000000188755", "us_id": "42235", "comm_code": "301003400000312", "upcard_terminal": "51211881", "upcard_mer_id": "102512058120376", "ex_id": "702", "ex_cost_center_code": "1200042235", "dcore_store_appid": "s20170823000005201" } }, { "_id": "3850146077982326785", "name": "上海调频壹店", "extend_code": { "comm_shop_id": "21e3a1578bd84f118e1861a1a997de63", "ex_code": "20038", "alipay_id": "2015060900077000000000166169", "us_id": "42264", "comm_code": "301003400000073", "upcard_terminal": "02194798", "upcard_mer_id": "102210058126898", "ex_id": "243", "ex_cost_center_code": "1200042264", "dcore_store_appid": "s20170823000005488" } }, { "_id": "3850146129471602689", "name": "郑州嘉茂店", "extend_code": { "comm_shop_id": "58115443c255454c83954c9275a5aef1", "ex_code": "20129", "alipay_id": "2015061100077000000000194502", "us_id": "42637", "comm_code": "301003400000179", "upcard_terminal": "37108518", "upcard_mer_id": "102371058121212", "ex_id": "934", "ex_cost_center_code": "1200042637", "dcore_store_appid": "s20170823000005219" } }, { "_id": "3850146095304802305", "name": "青岛延吉万达店", "extend_code": { "comm_shop_id": "90146645791e43caa835e5f52f0804d1", "ex_code": "20063", "alipay_id": "2015061100077000000000194507", "us_id": "42374", "comm_code": "301003400000269", "upcard_terminal": "53204092", "upcard_mer_id": "102532058120478", "ex_id": "181", "ex_cost_center_code": "1200042374", "dcore_store_appid": "s20170823000005206" } }, { "_id": "3850146131585531905", "name": "苏州宫巷店", "extend_code": { "comm_shop_id": "f4bb237b5e88402ab574c34cb20ac94f", "ex_code": "20133", "alipay_id": "2015061000077000000000192925", "us_id": "42657", "comm_code": "301003400000442", "upcard_terminal": "51211247", "upcard_mer_id": "102512058120459", "ex_id": "509", "ex_cost_center_code": "1200042657", "dcore_store_appid": "s20170823000005521" } }, { "_id": "3850146104419024897", "name": "郑州国贸店", "extend_code": { "comm_shop_id": "c5e8f8638cb5400791d06cf1ca821154", "ex_code": "20081", "alipay_id": "2015061100077000000000182837", "us_id": "42444", "comm_code": "301003400000356", "upcard_terminal": "37110808", "upcard_mer_id": "102371058121023", "ex_id": "933", "ex_cost_center_code": "1200042444", "dcore_store_appid": "s20170823000005570" } }, { "_id": "3850146104876204033", "name": "南昌动壹店", "extend_code": { "comm_shop_id": "4c375abf3a914937b9c05233a58d3457", "ex_code": "20082", "alipay_id": "2015061000077000000000191159", "us_id": "42459", "comm_code": "301003400000151", "upcard_terminal": "79101366", "upcard_mer_id": "102791058120008", "ex_id": "981", "ex_cost_center_code": "1200042459", "dcore_store_appid": "s20170823000005572" } }, { "_id": "3850146148555685889", "name": "莘庄龙之梦店", "extend_code": { "comm_shop_id": "4c5456e37d1f478a89cb2fbc4340f9a0", "ex_code": "20165", "alipay_id": "2015060900077000000000178454", "us_id": "42720", "comm_code": "301003400000152", "upcard_terminal": "02194926", "upcard_mer_id": "102210058120846", "ex_id": "288", "ex_cost_center_code": "1200042720", "dcore_store_appid": "s20170823000005223" } }, { "_id": "3850146072571674625", "name": "成都锦里店", "extend_code": { "comm_shop_id": "532c7c9cf78d4e34a2bde16ee67bdc8d", "ex_code": "20031", "alipay_id": "2021090900077000000027663651", "us_id": "42236", "comm_code": "301003400000168", "upcard_terminal": "02817519", "upcard_mer_id": "102280058121935", "ex_id": "805", "ex_cost_center_code": "1200042236", "dcore_store_appid": "s20170823000005485" } }, { "_id": "3850146094847623169", "name": "重庆沙坪坝店", "extend_code": { "comm_shop_id": "1e53dcf2eb4b401c91dc113085d8981d", "ex_code": "20062", "alipay_id": "2016112200077000000020268761", "us_id": "42371", "comm_code": "301003400000069", "upcard_terminal": "02306268", "upcard_mer_id": "102230058120111", "ex_id": "635", "ex_cost_center_code": "1200042371", "dcore_store_appid": "s20170823000005497" } }, { "_id": "3850146121133326337", "name": "济南玉函银座店", "extend_code": { "comm_shop_id": "ccc22391582a4f70a384b259903d668c", "ex_code": "20114", "alipay_id": "2015061100077000000000194512", "us_id": "42567", "comm_code": "301003400000372", "upcard_terminal": "53101188", "upcard_mer_id": "102531058120052", "ex_id": "534", "ex_cost_center_code": "1200042567", "dcore_store_appid": "s20170823000005506" } }, { "_id": "3850146122685218817", "name": "襄樊万达店", "extend_code": { "comm_shop_id": "c4f111fd30d04d789d46bd8d71ab0f73", "ex_code": "20116", "alipay_id": "2015061200077000000000194554", "us_id": "42619", "comm_code": "301003400000353", "upcard_terminal": "71003032", "upcard_mer_id": "102710058120531", "ex_id": "781", "ex_cost_center_code": "1200042619", "dcore_store_appid": "s20170823000005218" } }, { "_id": "3850146125256327169", "name": "绍兴柯桥万达店", "extend_code": { "comm_shop_id": "181678e85a284c1582df74ee8d61367f", "ex_code": "20121", "alipay_id": "2016112200077000000020302520", "us_id": "42635", "comm_code": "301003400000059", "upcard_terminal": "57500298", "upcard_mer_id": "102575058120020", "ex_id": "362", "ex_cost_center_code": "1200042635", "dcore_store_appid": "s20170823000005516" } }, { "_id": "3850146133250670593", "name": "淮安万达店", "extend_code": { "comm_shop_id": "ebd1a8688ac340ef8c322a55e7b29a0c", "ex_code": "20136", "alipay_id": "2015061100077000000000192953", "us_id": "42643", "comm_code": "301003400000426", "upcard_terminal": "51700220", "upcard_mer_id": "102517058120006", "ex_id": "612", "ex_cost_center_code": "1200042643", "dcore_store_appid": "s20170823000005519" } }, { "_id": "3850146115601039361", "name": "宁波天一二店", "extend_code": { "comm_shop_id": "27d64f2e53764b8eba77416139d0d60c", "ex_code": "20103", "alipay_id": "2018041900077000000048257589", "us_id": "42563", "comm_code": "301003400000088", "upcard_terminal": "57401977", "upcard_mer_id": "102574058120110", "ex_id": "436", "ex_cost_center_code": "1200042563", "dcore_store_appid": "s20170823000005214" } }, { "_id": "3850146137394642945", "name": "江阴新一城店", "extend_code": { "comm_shop_id": "576f2d79de764dceb9a3dec0fce66e09", "ex_code": "20144", "alipay_id": "2015061100077000000000188749", "us_id": "42699", "comm_code": "301003400000177", "upcard_terminal": "51000995", "upcard_mer_id": "102510058120023", "ex_id": "372", "ex_cost_center_code": "1200042699", "dcore_store_appid": "s20170823000005333" } }, { "_id": "3850146125742866433", "name": "贵阳亨特国际店", "extend_code": { "comm_shop_id": "4f134bf6a9e241fa9f1f4a050bc203ad", "ex_code": "20122", "alipay_id": "2015093000077000000004452740", "us_id": "42149", "comm_code": "301003400000160", "upcard_terminal": "85101188", "upcard_mer_id": "102851058120125", "ex_id": "722", "ex_cost_center_code": "1200042149", "dcore_store_appid": "s20170823000005480" } }, { "_id": "3850146200917377025", "name": "绵阳涪城万达", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20250", "comm_shop_id": "881caaafd1d645998425c1adb2b6cb08", "us_id": "43174", "alipay_id": "2015061200077000000000191239", "takeaway_eleme_id": '', "upcard_terminal": "81600335", "comm_code": "301003400000257", "upcard_mer_id": "102816058120025", "ex_id": "", "ex_cost_center_code": "1200043174", "dcore_store_appid": "s20170823000005360" } }, { "_id": "3850146203522039809", "name": "苏州山塘街", "extend_code": { "comm_shop_id": "f240df6958f3403e98f026ff95ce0bda", "ex_code": "20253", "alipay_id": "2015061000077000000000188730", "us_id": "43342", "comm_code": "301003400000436", "upcard_terminal": "51211240", "upcard_mer_id": "102512058120798", "ex_id": "515", "ex_cost_center_code": "1200043342", "dcore_store_appid": "s20170823000005362" } }, { "_id": "3850146224606806017", "name": "郑州建文店", "extend_code": { "comm_shop_id": "4c5bfea87a934b81bdca2c2d44859d87", "ex_code": "20280", "alipay_id": "2015061100077000000000194503", "us_id": "43553", "comm_code": "301003400000153", "upcard_terminal": "37110794", "upcard_mer_id": "102371058122198", "ex_id": "20023", "ex_cost_center_code": "1200043553", "dcore_store_appid": "s20170823000005263" } }, { "_id": "3850146230332030977", "name": "余姚万达", "extend_code": { "comm_shop_id": "852f877c039e41a1a755165f4869a84a", "ex_code": "20291", "alipay_id": "2015061000077000000000188723", "us_id": "43516", "comm_code": "301003400000252", "upcard_terminal": "57402350", "upcard_mer_id": "102574058120259", "ex_id": "20042", "ex_cost_center_code": "1200043516", "dcore_store_appid": "s20170823000005253" } }, { "_id": "3850146051738566657", "name": "诸暨雄风新天地", "extend_code": { "comm_shop_id": "f03c6490ddc04e9280581bd621fe5e2b", "ex_code": "10181", "alipay_id": "2015061000077000000000192913", "us_id": "43675", "comm_code": "301003400000432", "upcard_terminal": "57500814", "upcard_mer_id": "102575058120042", "ex_id": "20073", "ex_cost_center_code": "1200043675", "dcore_store_appid": "s20170823000005384" } }, { "_id": "3850146139198193665", "name": "银川金花店", "extend_code": { "comm_shop_id": "b3431ff5dfd244878acfb4ea2488698c", "ex_code": "20147", "alipay_id": "2015061200077000000000182892", "us_id": "42705", "comm_code": "301003400000327", "upcard_terminal": "95100476", "upcard_mer_id": "102951058120211", "ex_id": "475", "ex_cost_center_code": "1200042705", "dcore_store_appid": "s20170823000005525" } }, { "_id": "3850146155367235585", "name": "临沂九州商厦", "extend_code": { "comm_shop_id": "3d4efe338ea4468bb7645970616cea3a", "ex_code": "20178", "alipay_id": "2015061100077000000000182844", "us_id": "42819", "comm_code": "301003400000125", "upcard_terminal": "53900037", "upcard_mer_id": "102539058120001", "ex_id": "537", "ex_cost_center_code": "1200042819", "dcore_store_appid": "s20170823000005538" } }, { "_id": "3850146066959695873", "name": "上海置地广场店", "extend_code": { "comm_shop_id": "018fc48bd88d4397a788f260171c80a6", "ex_code": "20020", "alipay_id": "2015060900077000000000178451", "us_id": "42107", "comm_code": "301003400000024", "upcard_terminal": "02148886", "upcard_mer_id": "102210058120713", "ex_id": "228", "ex_cost_center_code": "1200042107", "dcore_store_appid": "s20170823000005198" } }, { "_id": "3850146150355042305", "name": "镇江万达", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20168", "comm_shop_id": "4dc63587b83347d9bc7c8036cc647387", "us_id": "42780", "alipay_id": "2015061100077000000000182831", "takeaway_eleme_id": '', "upcard_terminal": "51103377", "comm_code": "301003400000156", "upcard_mer_id": "102511058121212", "ex_id": "565", "ex_cost_center_code": "1200042780", "dcore_store_appid": "s20170823000005226" } }, { "_id": "3850146107883520001", "name": "贵阳南国花锦店", "extend_code": { "comm_shop_id": "6b0f7697f0bf426daa74904b2128032a", "ex_code": "20088", "alipay_id": "2015061200077000000000182872", "us_id": "42478", "comm_code": "301003400000211", "upcard_terminal": "85101189", "upcard_mer_id": "102851058120028", "ex_id": "721", "ex_cost_center_code": "1200042478", "dcore_store_appid": "s20170823000005212" } }, { "_id": "3850146086261882881", "name": "上海龙之梦店", "extend_code": { "comm_shop_id": "9a63cb3a782f4784aa8245ab79096ba9", "ex_code": "20046", "alipay_id": "2015060900077000000000166155", "us_id": "42307", "comm_code": "301003400000284", "upcard_terminal": "02193654", "upcard_mer_id": "102210058120721", "ex_id": "252", "ex_cost_center_code": "1200042307", "dcore_store_appid": "s20170823000005492" } }, { "_id": "3850146158500380673", "name": "武汉东沙万达", "extend_code": { "comm_shop_id": "9c3023c5d62b4f6baffff4b9eb114dbd", "ex_code": "20184", "alipay_id": "2015061200077000000000188814", "us_id": "42778", "comm_code": "301003400000287", "upcard_terminal": "02713544", "upcard_mer_id": "102270058122423", "ex_id": "924", "ex_cost_center_code": "1200042778", "dcore_store_appid": "s20170823000005533" } }, { "_id": "3850146116074995713", "name": "上海川沙东海岸店", "extend_code": { "comm_shop_id": "0ab7032bcc5c45d7a10e98aded3cc765", "ex_code": "20104", "alipay_id": "2015060900077000000000176454", "us_id": "42566", "comm_code": "301003400000039", "upcard_terminal": "02148849", "upcard_mer_id": "102210058120750", "ex_id": "275", "ex_cost_center_code": "1200042566", "dcore_store_appid": "s20170823000005505" } }, { "_id": "3850146180763746305", "name": "深圳连城新天地", "extend_code": { "comm_shop_id": "2edcfab2ea6c49e4b8a3efd4a02ca941", "ex_code": "20219", "alipay_id": "2015061200077000000000182864", "us_id": "42775", "comm_code": "301003400000099", "upcard_terminal": "75516860", "upcard_mer_id": "102755058120866", "ex_id": "488", "ex_cost_center_code": "1200042775", "dcore_store_appid": "s20170823000005532" } }, { "_id": "3850146088338063361", "name": "重庆北城店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20050", "comm_shop_id": "fe542073e01749eeb6430ea415673b52", "us_id": "42343", "alipay_id": "2015061200077000000000191244", "takeaway_eleme_id": '', "upcard_terminal": "02306271", "comm_code": "301003400000458", "upcard_mer_id": "102230058120108", "ex_id": "634", "ex_cost_center_code": "1200042343", "dcore_store_appid": "s20170823000005205" } }, { "_id": "3850146099742375937", "name": "成都红牌楼店", "extend_code": { "comm_shop_id": "b4191164e75e41d593455a557eac6275", "ex_code": "20072", "alipay_id": "2015061200077000000000188801", "us_id": "42393", "comm_code": "301003400000331", "upcard_terminal": "02817516", "upcard_mer_id": "102280058121938", "ex_id": "806", "ex_cost_center_code": "1200042393", "dcore_store_appid": "s20170823000005566" } }, { "_id": "3850146159527985153", "name": "郑州中原万达", "extend_code": { "comm_shop_id": "e3ad385ac9af42e393c3a2bd02484a4c", "ex_code": "20186", "alipay_id": "2015061100077000000000188759", "us_id": "42866", "comm_code": "301003400000413", "upcard_terminal": "37108513", "upcard_mer_id": "102371058122078", "ex_id": "937", "ex_cost_center_code": "1200042866", "dcore_store_appid": "s20170823000005546" } }, { "_id": "3850146182533742593", "name": "连云港中央商场", "extend_code": { "comm_shop_id": "3b850ebc59604315b38cd5f8cf71332e", "ex_code": "20222", "alipay_id": "2015061100077000000000191203", "us_id": "42944", "comm_code": "301003400000122", "upcard_terminal": "51800155", "upcard_mer_id": "102518058120008", "ex_id": "996", "ex_cost_center_code": "1200042944", "dcore_store_appid": "s20170823000005346" } }, { "_id": "3850146294441967617", "name": "湛江鼎盛店", "extend_code": { "comm_shop_id": "7312336e40484ddc9c672f055157a0d9", "ex_code": "20413", "alipay_id": "2015061200077000000000192990", "us_id": "43954", "comm_code": "301003400000230", "upcard_terminal": "75900281", "upcard_mer_id": "102759058120013", "ex_id": "20202", "ex_cost_center_code": "1200043954", "dcore_store_appid": "s20170823000005585" } }, { "_id": "3850146100228915201", "name": "上海宝山安信店", "extend_code": { "comm_shop_id": "a7b9d6ef4a2a4aae9deeec180423e725", "ex_code": "20073", "alipay_id": "2015060900077000000000169198", "us_id": "42384", "comm_code": "301003400000313", "upcard_terminal": "02194799", "upcard_mer_id": "102210058126899", "ex_id": "258", "ex_cost_center_code": "1200042384", "dcore_store_appid": "s20170823000005207" } }, { "_id": "3850146301450649601", "name": "西安曲江金地店", "extend_code": { "comm_shop_id": "0a87c203472f4a8fa3ba258aaf042edb", "ex_code": "20422", "alipay_id": "2015093000077000000004460351", "us_id": "44013", "comm_code": "301003400000038", "upcard_terminal": "02990622", "upcard_mer_id": "102290058122792", "ex_id": "20211", "ex_cost_center_code": "1200044013", "dcore_store_appid": "s20170823000005297" } }, { "_id": "3850146183477460993", "name": "驻马店新玛特", "extend_code": { "comm_shop_id": "912f8c4b0cf041af8b7c5c76130b35c6", "ex_code": "20224", "alipay_id": "2015061100077000000000194506", "us_id": "42943", "comm_code": "301003400004732", "upcard_terminal": "39601298", "upcard_mer_id": "102396058120019", "ex_id": "945", "ex_cost_center_code": "1200042943", "dcore_store_appid": "s20170823000005345" } }, { "_id": "3850146101369765889", "name": "松江开元店", "extend_code": { "comm_shop_id": "b8e8d9a653cb4511980ccdebccd1c31d", "ex_code": "20075", "alipay_id": "2015060900077000000000176453", "us_id": "42413", "comm_code": "301003400000336", "upcard_terminal": "02148867", "upcard_mer_id": "102210058120732", "ex_id": "260", "ex_cost_center_code": "1200042413", "dcore_store_appid": "s20170823000005209" } }, { "_id": "3850146302948016129", "name": "丽水万地店", "extend_code": { "us_id": "44016", "ex_id": "20220", "ex_cost_center_code": "1200044016", "ex_code": "20423" } }, { "_id": "3850146066296995841", "name": "常熟印象城店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20019", "comm_shop_id": "b109ace497354add9afaa0124aa44165", "us_id": "41997", "alipay_id": "2015061100077000000000182830", "takeaway_eleme_id": '', "upcard_terminal": "51215442", "comm_code": "301003400000322", "upcard_mer_id": "102512058123022", "ex_id": "552", "ex_cost_center_code": "1200041997", "dcore_store_appid": "s20170823000005364" } }, { "_id": "3850146192285499393", "name": "晋江万达店", "extend_code": { "comm_shop_id": "5b3a28a0b9e047b5ae1300183c0b1591", "ex_code": "20233", "alipay_id": "2015061200077000000000194536", "us_id": "43062", "comm_code": "301003400000186", "upcard_terminal": "59500694", "upcard_mer_id": "102595058120137", "ex_id": "758", "ex_cost_center_code": "1200043062", "dcore_store_appid": "s20170823000005352" } }, { "_id": "3850146173453074433", "name": "虹口龙之梦", "extend_code": { "comm_shop_id": "2dd7f92ca4ab4646a9214c242224634a", "ex_code": "20205", "alipay_id": "2015060900077000000000169215", "us_id": "42842", "comm_code": "301003400000095", "upcard_terminal": "02194859", "upcard_mer_id": "102210058120983", "ex_id": "2003", "ex_cost_center_code": "1200042842", "dcore_store_appid": "s20170823000005543" } }, { "_id": "3850146319918170113", "name": "太原茂业店", "extend_code": { "comm_shop_id": "a713fb7c75004fe5989aac59f713ac73", "ex_code": "20450", "alipay_id": "2015093000077000000004438544", "us_id": "43922", "comm_code": "301003400000311", "upcard_terminal": "35103999", "upcard_mer_id": "102351058121525", "ex_id": "20222", "ex_cost_center_code": "1200043922", "dcore_store_appid": "s20170823000005577" } }, { "_id": "3850146235088371713", "name": "徐州金鹰", "extend_code": { "comm_shop_id": "e2e28e217adf42d487a181066508a420", "ex_code": "20300", "alipay_id": "2019100900077000000083379295", "us_id": "43637", "comm_code": "301003400000411", "upcard_terminal": "51600590", "upcard_mer_id": "102516058120114", "ex_id": "20057", "ex_cost_center_code": "1200043637", "dcore_store_appid": "s20170823000005271" } }, { "_id": "3850146073200820225", "name": "上海人民广场店", "extend_code": { "comm_shop_id": "6b09b5dfc5b147f581953f7feda99698", "ex_code": "20032", "alipay_id": "2015093000077000000004490205", "us_id": "42102", "comm_code": "301003400000210", "upcard_terminal": "02194795", "upcard_mer_id": "102210058126895", "ex_id": "237", "ex_cost_center_code": "1200042102", "dcore_store_appid": "s20170823000005476" } }, { "_id": "3850146146143961089", "name": "江桥万达", "extend_code": { "comm_shop_id": "83f3050cb74849299edbdeab5f3b78b8", "ex_code": "20160", "alipay_id": "2015060900077000000000176465", "us_id": "42755", "comm_code": "301003400000250", "upcard_terminal": "02194856", "upcard_mer_id": "102210058120849", "ex_id": "292", "ex_cost_center_code": "1200042755", "dcore_store_appid": "s20170823000005530" } }, { "_id": "3850146179299934209", "name": "济宁佳世客", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20216", "comm_shop_id": "1fe0462a4372433ead3e05f97ec00175", "us_id": "42945", "alipay_id": "2015061100077000000000194515", "takeaway_eleme_id": '', "upcard_terminal": "53700586", "comm_code": "301003400000070", "upcard_mer_id": "102537058120003", "ex_id": "545", "ex_cost_center_code": "1200042945", "dcore_store_appid": "s20170823000005236" } }, { "_id": "3850146321524588545", "name": "武汉光谷世界城", "extend_code": { "comm_shop_id": "e0fcdeaf474b4eafa7f824956f93dfea", "ex_code": "20453", "alipay_id": "2015093000077000000004452737", "us_id": "43937", "comm_code": "301003400000409", "upcard_terminal": "02723116", "upcard_mer_id": "102270058125030", "ex_id": "20255", "ex_cost_center_code": "1200043937", "dcore_store_appid": "s20170823000005581" } }, { "_id": "3850146108353282049", "name": "成山路店", "extend_code": { "comm_shop_id": "8b7dc996d2864d9facc64dcce6f3d27b", "ex_code": "20089", "alipay_id": "2015060900077000000000169200", "us_id": "42477", "comm_code": "301003400000263", "upcard_terminal": "02190200", "upcard_mer_id": "102210058120746", "ex_id": "267", "ex_cost_center_code": "1200042477", "dcore_store_appid": "s20170823000005575" } }, { "_id": "3850146184463122433", "name": "长沙悦方", "extend_code": { "comm_shop_id": "843c10be51d542aa9d8fd70990891868", "ex_code": "20226", "alipay_id": "2015061200077000000000188816", "us_id": "42991", "comm_code": "301003400000251", "upcard_terminal": "73106061", "upcard_mer_id": "102731058120845", "ex_id": "738", "ex_cost_center_code": "1200042991", "dcore_store_appid": "s20170823000005349" } }, { "_id": "3850146322732548097", "name": "郑州大卫城店", "extend_code": { "comm_shop_id": "d0135377e87d4314be52b09116fdc83c", "ex_code": "20455", "alipay_id": "2015093000077000000004451343", "us_id": "44077", "comm_code": "301003400000385", "upcard_terminal": "37110828", "upcard_mer_id": "102371058122403", "ex_id": "20245", "ex_cost_center_code": "1200044077", "dcore_store_appid": "s20170823000005611" } }, { "_id": "3850146167618797569", "name": "舟山凯虹", "extend_code": { "comm_shop_id": "03981a70a5ff43e4927d260c04cc3125", "ex_code": "20194", "alipay_id": "2015061000077000000000188717", "us_id": "42870", "comm_code": "301003400000029", "upcard_terminal": "58000375", "upcard_mer_id": "102580058120040", "ex_id": "332", "ex_cost_center_code": "1200042870", "dcore_store_appid": "s20170823000005548" } }, { "_id": "3850146324053753857", "name": "淄博万象汇", "extend_code": { "comm_shop_id": "6f654248590e45b49c81e24538b5ca2f", "ex_code": "20457", "alipay_id": "2015093000077000000004486033", "us_id": "44134", "comm_code": "301003400000221", "upcard_terminal": "53390075", "upcard_mer_id": "102533058120084", "ex_id": "", "ex_cost_center_code": "1200044134", "dcore_store_appid": "s20170823000005622" } }, { "_id": "3850146096315629569", "name": "重庆万达店", "extend_code": { "comm_shop_id": "4e7bc86cf9c64520993ef0c6677c7548", "ex_code": "20065", "alipay_id": "2018041900077000000048354821", "us_id": "42390", "comm_code": "301003400000159", "upcard_terminal": "02306267", "upcard_mer_id": "102230058120112", "ex_id": "636", "ex_cost_center_code": "1200042390", "dcore_store_appid": "s20170823000005565" } }, { "_id": "3850146154901667841", "name": "贵阳恒峰", "extend_code": { "comm_shop_id": "722cceb67dd247c0951bbf6226d142bb", "ex_code": "20177", "alipay_id": "2015061200077000000000192995", "us_id": "42828", "comm_code": "301003400000226", "upcard_terminal": "85101187", "upcard_mer_id": "102851058120161", "ex_id": "723", "ex_cost_center_code": "1200042828", "dcore_store_appid": "s20170823000005541" } }, { "_id": "3850146327857987585", "name": "咸阳正兴店", "extend_code": { "comm_shop_id": "2e5d8ee430544a23b0fca6180072e338", "ex_code": "20464", "alipay_id": "2015093000077000000004460350", "us_id": "44163", "comm_code": "301003400000098", "upcard_terminal": "02990947", "upcard_mer_id": "102290058122902", "ex_id": "20265", "ex_cost_center_code": "1200044163", "dcore_store_appid": "s20170823000005625" } }, { "_id": "3850146262212935681", "name": "银川西夏万达", "extend_code": { "comm_shop_id": "31489210ba974ccf858c004993385d2c", "ex_code": "20353", "alipay_id": "2015061200077000000000188822", "us_id": "43832", "comm_code": "301003400000106", "upcard_terminal": "95100525", "upcard_mer_id": "102951058120225", "ex_id": "20140", "ex_cost_center_code": "1200043832", "dcore_store_appid": "s20170823000005408" } }, { "_id": "3850146172958146561", "name": "绵阳新世界", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20204", "comm_shop_id": "966b65c74f07418780864734084bad8c", "us_id": "42892", "alipay_id": "2015061200077000000000191236", "takeaway_eleme_id": '', "upcard_terminal": "81600336", "comm_code": "301003400000275", "upcard_mer_id": "102816058120005", "ex_id": "818", "ex_cost_center_code": "1200042892", "dcore_store_appid": "s20170823000005552" } }, { "_id": "3850146227832225793", "name": "长沙开福万达店", "extend_code": { "comm_shop_id": "8ebedea25c694865b0532a75e9831157", "ex_code": "20286", "alipay_id": "2015093000077000000004511905", "us_id": "43542", "comm_code": "301003400000266", "upcard_terminal": "73109820", "upcard_mer_id": "102731058121596", "ex_id": "20021", "ex_cost_center_code": "1200043542", "dcore_store_appid": "s20170823000005256" } }, { "_id": "3850146106012860417", "name": "绍兴世茂店", "extend_code": { "comm_shop_id": "2805cc9fe7a340b8a45b2e5a117fcb29", "ex_code": "20084", "alipay_id": "2015093000077000000004518859", "us_id": "42469", "comm_code": "301003400000089", "upcard_terminal": "57103822", "upcard_mer_id": "102571058120392", "ex_id": "361", "ex_cost_center_code": "1200042469", "dcore_store_appid": "s20170823000005574" } }, { "_id": "3850146202389577729", "name": "宁波印象城店", "extend_code": { "comm_shop_id": "cab2672464a94b75883a8c07d7b4edc5", "ex_code": "20251", "alipay_id": "2015061000077000000000182803", "us_id": "43185", "comm_code": "301003400000368", "upcard_terminal": "57403308", "upcard_mer_id": "102574058120522", "ex_id": "441", "ex_cost_center_code": "1200043185", "dcore_store_appid": "s20170823000005361" } }, { "_id": "3850146175042715649", "name": "武汉百联奥特莱斯", "extend_code": { "comm_shop_id": "9d363bae9f7c40eb8a18c65cb85a3b27", "ex_code": "20208", "alipay_id": "2015061200077000000000193011", "us_id": "42902", "comm_code": "301003400000290", "upcard_terminal": "02713541", "upcard_mer_id": "102270058122465", "ex_id": "928", "ex_cost_center_code": "1200042902", "dcore_store_appid": "s20170823000005234" } }, { "_id": "3850146343452409857", "name": "宁波银泰环球城店", "extend_code": { "comm_shop_id": "da14515038c24458b9855bfbb29407aa", "ex_code": "20483", "alipay_id": "2015093000077000000004438545", "us_id": "44236", "comm_code": "301003400000401", "upcard_terminal": "57403154", "upcard_mer_id": "102574058120495", "ex_id": "20294", "ex_cost_center_code": "1200044236", "dcore_store_appid": "s20170823000005642" } }, { "_id": "3850146235621048321", "name": "成都高新伊藤", "extend_code": { "comm_shop_id": "6f47a4c518da4ffd9e9c07e770a08e69", "ex_code": "20301", "alipay_id": "2015061200077000000000192999", "us_id": "43661", "comm_code": "301003400000220", "upcard_terminal": "02883679", "upcard_mer_id": "102280058123576", "ex_id": "99999", "ex_cost_center_code": "1200043661", "dcore_store_appid": "s20170823000005382" } }, { "_id": "3850146227295354881", "name": "南京龙江新城店", "extend_code": { "comm_shop_id": "c3a352f0b33c418f8f0c7b52060a262e", "ex_code": "20285", "alipay_id": "2015061000077000000000191172", "us_id": "43549", "comm_code": "301003400000350", "upcard_terminal": "02592754", "upcard_mer_id": "102250058121909", "ex_id": "20025", "ex_cost_center_code": "1200043549", "dcore_store_appid": "s20170823000005260" } }, { "_id": "3850146237164552193", "name": "深圳龙岗万科广场", "extend_code": { "comm_shop_id": "078573ba949c4ae1a1f7096e914ac079", "ex_code": "20304", "alipay_id": "2015061200077000000000192985", "us_id": "43672", "comm_code": "301003400000032", "upcard_terminal": "75512047", "upcard_mer_id": "102755058121836", "ex_id": "98765", "ex_cost_center_code": "1200043672", "dcore_store_appid": "s20170823000005383" } }, { "_id": "3850146192801398785", "name": "宁德万达店", "extend_code": { "comm_shop_id": "e85573e530ff4bfc8d061be9d584eb7a", "ex_code": "20234", "alipay_id": "2015061200077000000000191230", "us_id": "43065", "comm_code": "301003400000417", "upcard_terminal": "59300038", "upcard_mer_id": "102593058120004", "ex_id": "865", "ex_cost_center_code": "1200043065", "dcore_store_appid": "s20170823000005696" } }, { "_id": "3850146126778859521", "name": "武汉菱角湖万达店", "extend_code": { "comm_shop_id": "bfb337f6b3574719bae9ec05ad97d5ad", "ex_code": "20124", "alipay_id": "2015061200077000000000194558", "us_id": "42613", "comm_code": "301003400000342", "upcard_terminal": "02729439", "upcard_mer_id": "102270058122023", "ex_id": "916", "ex_cost_center_code": "1200042613", "dcore_store_appid": "s20170823000005513" } }, { "_id": "3850146065198088193", "name": "西安万达店", "extend_code": { "comm_shop_id": "729976c8626848e19ea5217bfcceb7c8", "ex_code": "20017", "alipay_id": "2015061200077000000000191254", "us_id": "42062", "comm_code": "301003400000227", "upcard_terminal": "02903688", "upcard_mer_id": "102290058122437", "ex_id": "951", "ex_cost_center_code": "1200042062", "dcore_store_appid": "s20170823000005474" } }, { "_id": "3850146065764319233", "name": "上海五莲店", "extend_code": { "comm_shop_id": "91cb11157d6b4267be46e3c18f4e4557", "ex_code": "20018", "alipay_id": "2015060900077000000000178440", "us_id": "42088", "comm_code": "301003400000273", "upcard_terminal": "02148910", "upcard_mer_id": "102210058120689", "ex_id": "502", "ex_cost_center_code": "1200042088", "dcore_store_appid": "s20170823000005475" } }, { "_id": "3850146304504102913", "name": "青州泰华城", "extend_code": { "us_id": "44024", "ex_id": "20207", "ex_cost_center_code": "1200044024", "ex_code": "20425" } }, { "_id": "3850146242680061953", "name": "上海浦江镇店", "extend_code": { "comm_shop_id": "5ad6bc7015c941e781f4d9e944dc99fa", "ex_code": "20315", "alipay_id": "2015060900077000000000169207", "us_id": "43659", "comm_code": "301003400000185", "upcard_terminal": "02149983", "upcard_mer_id": "102210058125753", "ex_id": "20071", "ex_cost_center_code": "1200043659", "dcore_store_appid": "s20170823000005381" } }, { "_id": "3850146224061546497", "name": "南京商厦店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20279", "comm_shop_id": "705e444cd279467391ad1162992b377b", "us_id": "43552", "alipay_id": "2015061000077000000000182814", "takeaway_eleme_id": '', "upcard_terminal": "02593529", "comm_code": "301003400000222", "upcard_mer_id": "102250058121864", "ex_id": "20022", "ex_cost_center_code": "1200043552", "dcore_store_appid": "s20170823000005262" } }, { "_id": "3850146335319654401", "name": "黄石万达店", "extend_code": { "comm_shop_id": "d419e7488f1a4005bc7d1bd89ec87fe5", "ex_code": "20469", "alipay_id": "2015093000077000000004477748", "us_id": "44193", "comm_code": "301003400000390", "upcard_terminal": "71430057", "upcard_mer_id": "102714058120015", "ex_id": "20259", "ex_cost_center_code": "1200044193", "dcore_store_appid": "s20170823000005631" } }, { "_id": "3850146244198400001", "name": "西安高新永辉", "extend_code": { "comm_shop_id": "e37909afe0d6408f83397cbc3f5db9b9", "ex_code": "20318", "alipay_id": "2015061200077000000000188818", "us_id": "43674", "comm_code": "301003400000412", "upcard_terminal": "02990372", "upcard_mer_id": "102290058122687", "ex_id": "20085", "ex_cost_center_code": "1200043674", "dcore_store_appid": "s20170823000005273" } }, { "_id": "3850146225319837697", "name": "杭州城西银泰城", "extend_code": { "comm_shop_id": "896125a609bb476c924598cc60698cbc", "ex_code": "20281", "alipay_id": "2015060900077000000000178462", "us_id": "43548", "comm_code": "301003400000171", "upcard_terminal": "57104200", "upcard_mer_id": "102571058120812", "ex_id": "20019", "ex_cost_center_code": "1200043548", "dcore_store_appid": "s20170823000005259" } }, { "_id": "3850146076438822913", "name": "武汉新佳丽店", "extend_code": { "comm_shop_id": "34f428487f1f4e2f998cee57eb6c37aa", "ex_code": "20035", "alipay_id": "2015061200077000000000193014", "us_id": "42257", "comm_code": "301003400000114", "upcard_terminal": "02713561", "upcard_mer_id": "102270058121832", "ex_id": "912", "ex_cost_center_code": "1200042257", "dcore_store_appid": "s20170823000005202" } }, { "_id": "3850146256487710721", "name": "武汉汉口城市广场", "extend_code": { "comm_shop_id": "48e0a5e8597e4d638e01ab4f183cc79b", "ex_code": "20342", "alipay_id": "2015061200077000000000194552", "us_id": "43760", "comm_code": "301003400000146", "upcard_terminal": "02722083", "upcard_mer_id": "102270058124771", "ex_id": "20134", "ex_cost_center_code": "1200043760", "dcore_store_appid": "s20170823000005394" } }, { "_id": "3850146376176369665", "name": "章丘唐人中心", "extend_code": { "comm_shop_id": "0f68fb88009644429a6edad37b931407", "ex_code": "20541", "alipay_id": "2016011100077000000014128752", "us_id": "44411", "comm_code": "301003400000043", "upcard_terminal": "53101201", "upcard_mer_id": "102531058120523", "ex_id": "20375", "ex_cost_center_code": "1200044411", "dcore_store_appid": "s20170823000005674" } }, { "_id": "3850146245670600705", "name": "湛江万象金沙湾广场", "extend_code": { "comm_shop_id": "392d5fa2cbe642f89176364d8fcbb3c3", "ex_code": "20321", "alipay_id": "2015061200077000000000188792", "us_id": "43636", "comm_code": "301003400000119", "upcard_terminal": "75900241", "upcard_mer_id": "102759058120006", "ex_id": "99888", "ex_cost_center_code": "1200043636", "dcore_store_appid": "s20170823000005379" } }, { "_id": "3850146361487917057", "name": "昆山九方店", "extend_code": { "comm_shop_id": "44e572d89e1b48a1b5bfc3036787ef54", "ex_code": "20513", "alipay_id": "2016020300077000000014719681", "us_id": "44333", "comm_code": "301003400000191", "upcard_terminal": "51215315", "upcard_mer_id": "102512058122983", "ex_id": "20326", "ex_cost_center_code": "1200044333", "dcore_store_appid": "s20170823000005320" } }, { "_id": "3850146270186307585", "name": "顾村绿地", "extend_code": { "comm_shop_id": "6949c0c00bc347c997837b9c17c4b7ac", "ex_code": "20367", "alipay_id": "2015060900077000000000166172", "us_id": "43930", "comm_code": "301003400000207", "upcard_terminal": "02190306", "upcard_mer_id": "102210058125878", "ex_id": "20165", "ex_cost_center_code": "1200043930", "dcore_store_appid": "s20170823000005289" } }, { "_id": "3850146077491593217", "name": "上海南站二店", "extend_code": { "comm_shop_id": "87b0a9b0abc242ecbd56af68f41f2d31", "ex_code": "20037", "alipay_id": "2016112200077000000020281356", "us_id": "42269", "comm_code": "301003400000256", "upcard_terminal": "02194793", "upcard_mer_id": "102210058126893", "ex_id": "244", "ex_cost_center_code": "1200042269", "dcore_store_appid": "s20170823000005490" } }, { "_id": "3850146385483530241", "name": "青岛金狮广场店", "extend_code": { "comm_shop_id": "a5033490ef8941f1bf0cf05686a02807", "ex_code": "20558", "alipay_id": "2016081500077000000018020531", "us_id": "44367", "comm_code": "301003400000307", "upcard_terminal": "53205312", "upcard_mer_id": "102532058121382", "ex_id": "20411", "ex_cost_center_code": "1200044367", "dcore_store_appid": "s20170823000005323" } }, { "_id": "3850146231749705729", "name": "南京马群花园城", "extend_code": { "comm_shop_id": "b13171ecb48c43fc9098daaa6c7f63b3", "ex_code": "20294", "alipay_id": "2015061000077000000000191169", "us_id": "43612", "comm_code": "301003400000323", "upcard_terminal": "02593531", "upcard_mer_id": "102250058121979", "ex_id": "20048", "ex_cost_center_code": "1200043612", "dcore_store_appid": "s20170823000005378" } }, { "_id": "3850146277538922497", "name": "南充顺庆1227", "extend_code": { "comm_shop_id": "7675bd0e2ebd4d40b26f1252d00bd4de", "ex_code": "20381", "alipay_id": "2015061200077000000000182876", "us_id": "43929", "comm_code": "301003400000233", "upcard_terminal": "81700193", "upcard_mer_id": "102817058120011", "ex_id": "", "ex_cost_center_code": "1200043929", "dcore_store_appid": "s20170823000005579" } }, { "_id": "3850146278096764929", "name": "濮阳万利", "extend_code": { "comm_shop_id": "8226ec0c686045758b7254f841bf5ea5", "ex_code": "20382", "alipay_id": "2019050500077000000077036041", "us_id": "43938", "comm_code": "301003400000247", "upcard_terminal": "39301031", "upcard_mer_id": "102393058120017", "ex_id": "20173", "ex_cost_center_code": "1200043938", "dcore_store_appid": "s20170823000005290" } }, { "_id": "3850146232223662081", "name": "蚌埠万达", "extend_code": { "comm_shop_id": "3eeb9c24c93e474b89adfda137faced2", "ex_code": "20295", "alipay_id": "2015061200077000000000188785", "us_id": "43611", "comm_code": "301003400000131", "upcard_terminal": "55202300", "upcard_mer_id": "102552058120026", "ex_id": "20037", "ex_cost_center_code": "1200043611", "dcore_store_appid": "s20170823000005377" } }, { "_id": "3850146407616872449", "name": "湘潭万达店", "extend_code": { "comm_shop_id": "8f74f89c807f4d48a7a52ad8f6bb1687", "ex_code": "20585", "alipay_id": "2016081600077000000018020831", "us_id": "44508", "comm_code": "301003400000267", "upcard_terminal": "73109946", "upcard_mer_id": "102731058121604", "ex_id": "20418", "ex_cost_center_code": "1200044508", "dcore_store_appid": "s20170823000005682" } }, { "_id": "3850146240184451073", "name": "海宁银泰城", "extend_code": { "comm_shop_id": "fbfb044a0589479490d567fa6f5702da", "ex_code": "20310", "alipay_id": "2015061000077000000000188724", "us_id": "43529", "comm_code": "301003400000454", "upcard_terminal": "57302902", "upcard_mer_id": "102573058120062", "ex_id": "20033", "ex_cost_center_code": "1200043529", "dcore_store_appid": "s20170823000005254" } }, { "_id": "3850146408111800321", "name": "资阳万达", "extend_code": { "comm_shop_id": "8dca11fdc19d4ca497befa62c28ddbed", "ex_code": "20612", "alipay_id": "2016111700077000000020010118", "us_id": "44504", "comm_code": "301003400000264", "upcard_terminal": "02894232", "upcard_mer_id": "102280058125188", "ex_id": "20414", "ex_cost_center_code": "1200044504", "dcore_store_appid": "s20170823000005328" } }, { "_id": "3850146202985168897", "name": "衢州景文", "extend_code": { "comm_shop_id": "d6393bd30278481c930ac027a54772e7", "ex_code": "20252", "alipay_id": "2015061000077000000000188719", "us_id": "43184", "comm_code": "301003400000394", "upcard_terminal": "57000077", "upcard_mer_id": "102570058120002", "ex_id": "686", "ex_cost_center_code": "1200043184", "dcore_store_appid": "s20170823000005241" } }, { "_id": "3850146255489466369", "name": "济宁贵和二店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20340", "comm_shop_id": "236b918f099d4a39a000157659323e46", "us_id": "43784", "alipay_id": "2015061100077000000000188763", "takeaway_eleme_id": '', "upcard_terminal": "53700800", "comm_code": "301003400000079", "upcard_mer_id": "102537058120038", "ex_id": "20138", "ex_cost_center_code": "1200043784", "dcore_store_appid": "s20170823000005279" } }, { "_id": "3850146243179184129", "name": "武汉凯德武胜店", "extend_code": { "comm_shop_id": "3fafb817aeaf4dd18ec426a09429f447", "ex_code": "20316", "alipay_id": "2015061200077000000000188820", "us_id": "43676", "comm_code": "301003400000132", "upcard_terminal": "02722339", "upcard_mer_id": "102270058124839", "ex_id": "20072", "ex_cost_center_code": "1200043676", "dcore_store_appid": "s20170823000005385" } }, { "_id": "3850146293410168833", "name": "武汉永旺梦乐城店", "extend_code": { "comm_shop_id": "f9759cef87d9461cb67962818d4b4264", "ex_code": "20411", "alipay_id": "2015093000077000000004439948", "us_id": "44017", "comm_code": "301003400000448", "upcard_terminal": "02722412", "upcard_mer_id": "102270058124861", "ex_id": "20224", "ex_cost_center_code": "1200044017", "dcore_store_appid": "s20170823000005603" } }, { "_id": "3850146097737498625", "name": "南京仙林金鹰店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20069", "comm_shop_id": "62e6e0e7270746eca1650f075716d0d7", "us_id": "42415", "alipay_id": "2015061000077000000000191175", "takeaway_eleme_id": '', "upcard_terminal": "02516542", "comm_code": "301003400000201", "upcard_mer_id": "102250058120836", "ex_id": "309", "ex_cost_center_code": "1200042415", "dcore_store_appid": "s20170823000005568" } }, { "_id": "3850146249198010369", "name": "临海银泰店", "extend_code": { "comm_shop_id": "88ee4def92004395a900bafcbf0f0f09", "ex_code": "20328", "alipay_id": "2015093000077000000004511912", "us_id": "43751", "comm_code": "301003400000258", "upcard_terminal": "57600854", "upcard_mer_id": "102576058120036", "ex_id": "20112", "ex_cost_center_code": "1200043751", "dcore_store_appid": "s20170823000005392" } }, { "_id": "3850146405028986881", "name": "嘉定大融城店", "extend_code": { "comm_shop_id": "9fb052715006443c95c32036ec9f4def", "ex_code": "20603", "alipay_id": "2016112400077000000023066705", "us_id": "44502", "comm_code": "301003400004604", "upcard_terminal": "21098215", "upcard_mer_id": "102210058126921", "ex_id": "20415", "ex_cost_center_code": "1200844502", "dcore_store_appid": "s20170823000005173" } }, { "_id": "3850146240679378945", "name": "淮北金鹰", "extend_code": { "comm_shop_id": "c381a4e2e91541e6909715acab49ef72", "ex_code": "20311", "alipay_id": "2015061200077000000000192986", "us_id": "43607", "comm_code": "301003400000349", "upcard_terminal": "56100669", "upcard_mer_id": "102561058120180", "ex_id": "20045", "ex_cost_center_code": "1200043607", "dcore_store_appid": "s20170823000005375" } }, { "_id": "3850146117631082497", "name": "上海虹井店", "extend_code": { "comm_shop_id": "c1e7b2ce88b341dabcfcaa38f507a244", "ex_code": "20107", "alipay_id": "2015060900077000000000176452", "us_id": "42543", "comm_code": "301003400000348", "upcard_terminal": "02148858", "upcard_mer_id": "102210058120741", "ex_id": "277", "ex_cost_center_code": "1200042543", "dianping_store_id": "4288836", "dcore_store_appid": "s20170823000005502" } }, { "_id": "3850146298950844417", "name": "深圳龙华九方购物中心店", "extend_code": { "us_id": "44012", "ex_id": "20226", "ex_cost_center_code": "1200044012", "ex_code": "20419" } }, { "_id": "3850146183964000257", "name": "武汉摩尔城", "extend_code": { "comm_shop_id": "9f7bf893d82c43798e56e6951659911c", "ex_code": "20225", "alipay_id": "2017120400077000000046825993", "us_id": "42994", "comm_code": "301003400000297", "upcard_terminal": "02713539", "upcard_mer_id": "102270058122536", "ex_id": "929", "ex_cost_center_code": "1200042994", "dcore_store_appid": "s20170823000005237" } }, { "_id": "3850146303988203521", "name": "青州泰华城", "extend_code": { "comm_shop_id": "ae1f7e7601e045d19213a8a6dacf2102", "ex_code": "20425", "alipay_id": "2015121500077000000013754527", "us_id": "44024", "comm_code": "301003400000318", "upcard_terminal": "53601843", "upcard_mer_id": "102536058120135", "ex_id": "20207", "ex_cost_center_code": "1200044024", "dcore_store_appid": "s20170823000005299" } }, { "_id": "3850146191794765825", "name": "合肥天鹅湖万达", "extend_code": { "comm_shop_id": "eec51fb82c214364907cd90c1fb64e33", "ex_code": "20232", "alipay_id": "2015061100077000000000188771", "us_id": "42922", "comm_code": "301003400000429", "upcard_terminal": "55118202", "upcard_mer_id": "102551058122783", "ex_id": "158", "ex_cost_center_code": "1200042922", "dcore_store_appid": "s20170823000005559" } }, { "_id": "3850146307691773953", "name": "重庆合川步步高", "extend_code": { "us_id": "43962", "ex_id": "20209", "ex_cost_center_code": "1200043962", "ex_code": "20428" } }, { "_id": "3850146255996977153", "name": "宜宾洋洋百货", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20341", "comm_shop_id": "2e5ac6c1da224be38fd9063fa9511a30", "us_id": "43788", "alipay_id": "2015061200077000000000194547", "takeaway_eleme_id": '', "upcard_terminal": "83100169", "comm_code": "301003400000097", "upcard_mer_id": "102831058120008", "ex_id": "20136", "ex_cost_center_code": "1200043788", "dcore_store_appid": "s20170823000005280" } }, { "_id": "3850146120185413633", "name": "东方浮庭店", "extend_code": { "comm_shop_id": "0fa2c075b15e44299263902ef1389474", "ex_code": "20112", "alipay_id": "2015060900077000000000169197", "us_id": "42606", "comm_code": "301003400000044", "upcard_terminal": "02148847", "upcard_mer_id": "102210058120752", "ex_id": "280", "ex_cost_center_code": "1200042606", "dcore_store_appid": "s20170823000005510" } }, { "_id": "3850146267703279617", "name": "南京虹悦城店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "43883", "comm_shop_id": "c90ad1b33a3f45188b0a7d4314707b50", "us_id": "43883", "alipay_id": "2021022600077000000017037541", "takeaway_eleme_id": '', "upcard_terminal": "02593483", "comm_code": "301003400004648", "upcard_mer_id": "102250058122298", "ex_id": "43883", "ex_cost_center_code": "1200043883", "dcore_store_appid": "s20170823000005156" } }, { "_id": "3850146121645031425", "name": "济南魏家庄万达店", "extend_code": { "comm_shop_id": "6dc82249c3f44e2ba63f3fbeb7aaf75d", "ex_code": "20115", "alipay_id": "2015061100077000000000192963", "us_id": "42612", "comm_code": "301003400000216", "upcard_terminal": "53100856", "upcard_mer_id": "102531058120055", "ex_id": "535", "ex_cost_center_code": "1200042612", "dcore_store_appid": "s20170823000005217" } }, { "_id": "3850146199424204801", "name": "重庆时代天街店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20247", "comm_shop_id": "c7c9af9fe3a147918f3c66e2f7f0e874", "us_id": "43170", "alipay_id": "2015061200077000000000182879", "takeaway_eleme_id": '', "upcard_terminal": "02306258", "comm_code": "301003400000362", "upcard_mer_id": "102230058120635", "ex_id": "644", "ex_cost_center_code": "1200043170", "dcore_store_appid": "s20170823000005358" } }, { "_id": "3850146288884514817", "name": "温州平阳万达", "extend_code": { "comm_shop_id": "f75825e314464a8a9a4d1e564cd6dd09", "ex_code": "20402", "alipay_id": "2015061100077000000000191194", "us_id": "43999", "comm_code": "301003400000446", "upcard_terminal": "57700529", "upcard_mer_id": "102577058120129", "ex_id": "", "ex_cost_center_code": "1200043999", "dcore_store_appid": "s20170823000005598" } }, { "_id": "3850146271671091201", "name": "苏州繁花中心", "extend_code": { "comm_shop_id": "8085fbdb50424923a269655bb24bb1a7", "ex_code": "20370", "alipay_id": "2015061100077000000000194497", "us_id": "43876", "comm_code": "301003400000245", "upcard_terminal": "51213123", "upcard_mer_id": "102512058122265", "ex_id": "20162", "ex_cost_center_code": "1200043876", "dcore_store_appid": "s20170823000005413" } }, { "_id": "3850146151290372097", "name": "武汉经开万达店", "extend_code": { "comm_shop_id": "ba397866d98d4d78aebc72739553078b", "ex_code": "20170", "alipay_id": "2015061200077000000000191251", "us_id": "42779", "comm_code": "301003400000338", "upcard_terminal": "02713547", "upcard_mer_id": "102270058122408", "ex_id": "921", "ex_cost_center_code": "1200042779", "dcore_store_appid": "s20170823000005534" } }, { "_id": "3850146281057943553", "name": "嘉善恒利广场", "extend_code": { "comm_shop_id": "cadefa14887349eaaaec7caaa9738c62", "ex_code": "20387", "alipay_id": "2015060900077000000000169205", "us_id": "43907", "comm_code": "301003400000369", "upcard_terminal": "57302203", "upcard_mer_id": "102573058120071", "ex_id": "20184", "ex_cost_center_code": "1200043907", "dcore_store_appid": "s20170823000005418" } }, { "_id": "3850146305741422593", "name": "南宁西关店", "extend_code": { "us_id": "43995", "ex_id": "20221", "ex_cost_center_code": "1200043995", "ex_code": "20426" } }, { "_id": "3863171950377435137", "name": "高邮世贸广场店", "extend_code": { "comm_shop_id": "1d8b960d830c40ce908e27362daeb651", "ex_cost_center_code": "1200844541", "alipay_id": "2016111600077000000020025550", "us_id": "44541", "comm_code": "301003400004478", "upcard_terminal": "51400880", "upcard_mer_id": "102514058120266", "ex_id": "20431", "ex_code": "20608", "dcore_store_appid": "s20170823000005422" } }, { "_id": "3850146157984481281", "name": "贵阳金阳", "extend_code": { "comm_shop_id": "c4fb752d9c684956bb1465500fd3d0c5", "ex_code": "20183", "alipay_id": "2015061200077000000000194540", "us_id": "42816", "comm_code": "301003400000354", "upcard_terminal": "85101186", "upcard_mer_id": "102851058120162", "ex_id": "724", "ex_cost_center_code": "1200042816", "dcore_store_appid": "s20170823000005537" } }, { "_id": "3850146281582231553", "name": "盐城中南城店", "extend_code": { "comm_shop_id": "00f55c720f2d490abed0048123b2d42c", "ex_code": "20388", "alipay_id": "2015061100077000000000194500", "us_id": "43750", "comm_code": "301003400004442", "upcard_terminal": "51545352", "upcard_mer_id": "102515058120366", "ex_id": "20166", "ex_cost_center_code": "1200843750", "dcore_store_appid": "s20170823000005153" } }, { "_id": "3850146317267369985", "name": "昆明嘉年华广场", "extend_code": { "comm_shop_id": "b3acca69ddcc4015bf9bc38ce2f4c545", "ex_code": "20445", "alipay_id": "2015061200077000000000191233", "us_id": "44079", "comm_code": "301003400000330", "upcard_terminal": "87109746", "upcard_mer_id": "102871058126161", "ex_id": "", "ex_cost_center_code": "1200044079", "dcore_store_appid": "s20170823000005613" } }, { "_id": "3863178864440115201", "name": "杭州萧山银隆(加盟)", "extend_code": { "comm_shop_id": "40bece0ef221432ab200baa91f0ad110", "ex_cost_center_code": "1200844532", "alipay_id": "2016111500077000000020026700", "us_id": "44532", "comm_code": "301003400004511", "upcard_terminal": "57109657", "upcard_mer_id": "102571058122478", "ex_id": "20436", "ex_code": "20611", "dcore_store_appid": "s20170823000005175" } }, { "_id": "3850146340617060353", "name": "东营万达店", "extend_code": { "comm_shop_id": "7d87f6e87d5f4d96aa2b1c2ca92675f8", "ex_code": "20478", "alipay_id": "2016031800077000000015089785", "us_id": "44210", "comm_code": "301003400000240", "upcard_terminal": "54600157", "upcard_mer_id": "102546058120067", "ex_id": "20283", "ex_cost_center_code": "1200044210", "dcore_store_appid": "s20170823000005633" } }, { "_id": "3850146166582804481", "name": "潍坊泰华城", "extend_code": { "comm_shop_id": "fa355e5b759f42058b7fe22c895b48b4", "ex_code": "20192", "alipay_id": "2015061200077000000000182861", "us_id": "42883", "comm_code": "301003400000449", "upcard_terminal": "53600620", "upcard_mer_id": "102536058120051", "ex_id": "539", "ex_cost_center_code": "1200042883", "dcore_store_appid": "s20170823000005550" } }, { "_id": "3850146262699474945", "name": "吉安天虹店", "extend_code": { "comm_shop_id": "c76cd16b7532447887c55e4184f70875", "ex_code": "20354", "alipay_id": "2015061000077000000000192921", "us_id": "43828", "comm_code": "301003400000361", "upcard_terminal": "79600227", "upcard_mer_id": "102796058120016", "ex_id": "20148", "ex_cost_center_code": "1200043828", "dcore_store_appid": "s20170823000005406" } }, { "_id": "3850146063688138753", "name": "成都万达店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20014", "comm_shop_id": "9bbeaff557334a53adb6580e5be1c432", "us_id": "42015", "alipay_id": "2015061200077000000000192996", "takeaway_eleme_id": '', "upcard_terminal": "02817520", "comm_code": "301003400000286", "upcard_mer_id": "102280058121934", "ex_id": "803", "ex_cost_center_code": "1200042015", "dcore_store_appid": "s20170823000005473" } }, { "_id": "3850146178054225921", "name": "厦门SM广场", "extend_code": { "comm_shop_id": "0927485e3f7a48498cd5e1a379257c1e", "ex_code": "20214", "alipay_id": "2015061200077000000000194534", "us_id": "42947", "comm_code": "301003400000370", "upcard_terminal": "59204818", "upcard_mer_id": "102592058120359", "ex_id": "756", "ex_cost_center_code": "1200042947", "dcore_store_appid": "s20170823000005347" } }, { "_id": "3850146349529956353", "name": "合肥百大鼓楼店", "extend_code": { "comm_shop_id": "5a21b27b1c674e5cb01b6af9ce80e841", "ex_code": "20494", "alipay_id": "2015093000077000000004515141", "us_id": "44261", "comm_code": "301003400000184", "upcard_terminal": "55126320", "upcard_mer_id": "102551058123558", "ex_id": "20297", "ex_cost_center_code": "1200044261", "dcore_store_appid": "s20170823000005316" } }, { "_id": "3850146061125419009", "name": "上海大宁店", "extend_code": { "comm_shop_id": "8a6425413a3448c1985d4f329b791c22", "ex_code": "20009", "alipay_id": "2015060900077000000000176450", "us_id": "41765", "comm_code": "301003400000260", "upcard_terminal": "02194797", "upcard_mer_id": "102210058126897", "ex_id": "207", "ex_cost_center_code": "1200041765", "dianping_store_id": "1958392", "dcore_store_appid": "s20170823000005469" } }, { "_id": "3850146372489576449", "name": "成都大悦城", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20534", "comm_shop_id": "70e1769c0ad14e54994cf200cd48d09d", "us_id": "44361", "alipay_id": "2016010800077000000014149218", "takeaway_eleme_id": '', "upcard_terminal": "02891111", "comm_code": "301003400000224", "upcard_mer_id": "102280058125064", "ex_id": "20349", "ex_cost_center_code": "1200044361", "dcore_store_appid": "s20170823000005322" } }, { "_id": "3850146365829021697", "name": "柳州城中万达店", "extend_code": { "comm_shop_id": "262af0d9100348c6adb1435b32b3ac62", "ex_code": "20521", "alipay_id": "2016011100077000000014253180", "us_id": "44232", "comm_code": "301003400000084", "upcard_terminal": "77201445", "upcard_mer_id": "102772058120730", "ex_id": "20331", "ex_cost_center_code": "1200044232", "dcore_store_appid": "s20170823000005639" } }, { "_id": "3850146061611958273", "name": "上海百联中环店", "extend_code": { "comm_shop_id": "15d293f2e4874550ac2b84065c7cb9d3", "ex_code": "20010", "alipay_id": "2015060900077000000000176447", "us_id": "41881", "comm_code": "301003400000053", "upcard_terminal": "02193652", "upcard_mer_id": "102210058120683", "ex_id": "217", "ex_cost_center_code": "1200041881", "dcore_store_appid": "s20170823000005470" } }, { "_id": "3850146318303363073", "name": "聊城金鼎购物中心", "extend_code": { "comm_shop_id": "ca2efb3a185b4b6b88ec3435977d8b53", "ex_code": "20447", "alipay_id": "2015061200077000000000191221", "us_id": "44088", "comm_code": "301003400000367", "upcard_terminal": "63500056", "upcard_mer_id": "102635058120013", "ex_id": "", "ex_cost_center_code": "1200044088", "dcore_store_appid": "s20170823000005616" } }, { "_id": "3850146295918362625", "name": "无锡荟聚中心", "extend_code": { "comm_shop_id": "29455f3e5090428fa7b9ae4f67f712dd", "ex_code": "20416", "alipay_id": "2015061000077000000000194480", "us_id": "43960", "comm_code": "301003400000090", "upcard_terminal": "51102342", "upcard_mer_id": "102510058121879", "ex_id": "20203", "ex_cost_center_code": "1200043960", "dcore_store_appid": "s20170823000005589" } }, { "_id": "3850146175533449217", "name": "郑州CBD", "extend_code": { "comm_shop_id": "d8a11f853f2343e99f579c9b7a4a517c", "ex_code": "20209", "alipay_id": "2015061100077000000000191205", "us_id": "42886", "comm_code": "301003400000396", "upcard_terminal": "37111877", "upcard_mer_id": "102371058122434", "ex_id": "938", "ex_cost_center_code": "1200042886", "dcore_store_appid": "s20170823000005232" } }, { "_id": "3850146371000598529", "name": "昆明海伦国际店", "extend_code": { "comm_shop_id": "fee78919a04f4b0eaf4c536c806500cf", "ex_code": "20531", "alipay_id": "2016011100077000000014087484", "us_id": "44364", "comm_code": "301003400000460", "upcard_terminal": "87111655", "upcard_mer_id": "102871058126571", "ex_id": "20373", "ex_cost_center_code": "1200044364", "dcore_store_appid": "s20170823000005667" } }, { "_id": "3850146187067785217", "name": "宝山万达", "extend_code": { "comm_shop_id": "e0a7e8a852e0469a9dab10e26758a557", "ex_code": "20231", "alipay_id": "2015060900077000000000178444", "us_id": "42941", "comm_code": "301003400000407", "upcard_terminal": "02194801", "upcard_mer_id": "102210058126901", "ex_id": "2009", "ex_cost_center_code": "1200042941", "dcore_store_appid": "s20170823000005235" } }, { "_id": "3850146320966746113", "name": "武汉宜家店", "extend_code": { "comm_shop_id": "89d2dd5793bb4d4fa59d9600ef9bb6a9", "ex_code": "20452", "alipay_id": "2015093000077000000004511902", "us_id": "44109", "comm_code": "301003400000259", "upcard_terminal": "02723063", "upcard_mer_id": "102270058125024", "ex_id": "20257", "ex_cost_center_code": "1200044109", "dcore_store_appid": "s20170823000005618" } }, { "_id": "3850146177555103745", "name": "岳阳步步高", "extend_code": { "comm_shop_id": "a9d1b6813dcf45ab87e8fc9f4cee61de", "ex_code": "20213", "alipay_id": "2015061200077000000000182887", "us_id": "42898", "comm_code": "301003400000315", "upcard_terminal": "73000039", "upcard_mer_id": "102730058120004", "ex_id": "833", "ex_cost_center_code": "1200042898", "dcore_store_appid": "s20170823000005555" } }, { "_id": "3850146197834563585", "name": "黄岛佳世客", "extend_code": { "comm_shop_id": "83bdca5abd1c49beb0fdfb94d5dd4c5a", "ex_code": "20244", "alipay_id": "2015061100077000000000182841", "us_id": "43101", "comm_code": "301003400000249", "upcard_terminal": "53204081", "upcard_mer_id": "102532058120851", "ex_id": "132", "ex_cost_center_code": "1200043101", "dcore_store_appid": "s20170823000005354" } }, { "_id": "3850146374586728449", "name": "贵阳正德家邦店", "extend_code": { "comm_shop_id": "4ffe83f9925744ed8a809af10019c02e", "ex_code": "20538", "alipay_id": "2016011100077000000014076723", "us_id": "44246", "comm_code": "301003400000161", "upcard_terminal": "85101430", "upcard_mer_id": "102851058120424", "ex_id": "20341", "ex_cost_center_code": "1200044246", "dcore_store_appid": "s20170823000005647" } }, { "_id": "3850146283670994945", "name": "龙岩万达店", "extend_code": { "comm_shop_id": "bfe5e4d9142b4644a3d061f0ffc0012c", "ex_code": "20392", "alipay_id": "2015061200077000000000188797", "us_id": "43958", "comm_code": "301003400000343", "upcard_terminal": "59700254", "upcard_mer_id": "102597058120113", "ex_id": "20169", "ex_cost_center_code": "1200043958", "dcore_store_appid": "s20170823000005587" } }, { "_id": "3850146375090044929", "name": "都江堰百伦店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20539", "comm_shop_id": "181c3bea399b41b18887e7ae206b21a0", "us_id": "44345", "alipay_id": "2016011100077000000014257689", "takeaway_eleme_id": '', "upcard_terminal": "02891194", "comm_code": "301003400000060", "upcard_mer_id": "102280058125088", "ex_id": "20347", "ex_cost_center_code": "1200044345", "dcore_store_appid": "s20170823000005662" } }, { "_id": "3850146248648556545", "name": "合肥银泰店", "extend_code": { "comm_shop_id": "4dcefc0620c54fc6861ecf203be1c504", "ex_code": "20327", "alipay_id": "2015061100077000000000192966", "us_id": "43785", "comm_code": "301003400000157", "upcard_terminal": "55120663", "upcard_mer_id": "102551058123256", "ex_id": "20122", "ex_cost_center_code": "1200043785", "dcore_store_appid": "s20170823000005400" } }, { "_id": "3850146284325306369", "name": "老闵行店", "extend_code": { "comm_shop_id": "ba413dc591fc47279e60f1a73bbfc73e", "ex_code": "20393", "alipay_id": "2015060900077000000000169204", "us_id": "43908", "comm_code": "301003400000339", "upcard_terminal": "02194924", "upcard_mer_id": "102210058125946", "ex_id": "20199", "ex_cost_center_code": "1200043908", "dcore_store_appid": "s20170823000005419" } }, { "_id": "3850146057908387841", "name": "上海西郊百联店", "extend_code": { "comm_shop_id": "031efd37cf6b4c5eb5ea8d3e54b6457c", "ex_code": "20003", "alipay_id": "2015060900077000000000178445", "us_id": "41589", "comm_code": "301003400000027", "upcard_terminal": "02194921", "upcard_mer_id": "102210058120675", "ex_id": "205", "ex_cost_center_code": "1200041589", "dcore_store_appid": "s20170823000005467" } }, { "_id": "3850146251794284545", "name": "连云港嘉瑞宝", "extend_code": { "comm_shop_id": "b9c604d14a1b4ad495b546b06efee524", "ex_code": "20333", "alipay_id": "2015061100077000000000182832", "us_id": "43715", "comm_code": "301003400000337", "upcard_terminal": "51800579", "upcard_mer_id": "102518058120014", "ex_id": "20125", "ex_cost_center_code": "1200043715", "dcore_store_appid": "s20170823000005275" } }, { "_id": "3850146377275277313", "name": "平顶山鹰城世贸", "extend_code": { "comm_shop_id": "05c5a2b824a64e7196047cc79a9af122", "ex_code": "20543", "alipay_id": "2016011100077000000014135346", "us_id": "44366", "comm_code": "301003400000030", "upcard_terminal": "37501828", "upcard_mer_id": "102375058120285", "ex_id": "20370", "ex_cost_center_code": "1200044366", "dcore_store_appid": "s20170823000005668" } }, { "_id": "3850146067429457921", "name": "南京1912店", "extend_code": { "comm_shop_id": "b38f50abe22b486895c39761634406ec", "ex_code": "20021", "alipay_id": "2015061000077000000000182809", "us_id": "42126", "comm_code": "301003400000328", "upcard_terminal": "02516550", "upcard_mer_id": "102250058120828", "ex_id": "305", "ex_cost_center_code": "1200042126", "dcore_store_appid": "s20170823000005477" } }, { "_id": "3850146096793780225", "name": "西安解放万达店", "extend_code": { "comm_shop_id": "4631795460bb479599c0a17e7ecc752e", "ex_code": "20067", "alipay_id": "2015061200077000000000193015", "us_id": "42387", "comm_code": "301003400000141", "upcard_terminal": "02903681", "upcard_mer_id": "102290058122444", "ex_id": "958", "ex_cost_center_code": "1200042387", "dcore_store_appid": "s20170823000005564" } }, { "_id": "3850146252788334593", "name": "中原城市广场", "extend_code": { "comm_shop_id": "0cba0c7b5f98485b90e4660d0636ef52", "ex_code": "20335", "alipay_id": "2015060900077000000000176456", "us_id": "43776", "comm_code": "301003400000042", "upcard_terminal": "02193285", "upcard_mer_id": "102210058125782", "ex_id": "20128", "ex_cost_center_code": "1200043776", "dcore_store_appid": "s20170823000005395" } }, { "_id": "3850146328948506625", "name": "柳州步步高店", "extend_code": { "comm_shop_id": "5559d0ad6aee496b86a80e449ae4d98d", "ex_code": "20466", "alipay_id": "2015093000077000000004499871", "us_id": "44178", "comm_code": "301003400000172", "upcard_terminal": "77201405", "upcard_mer_id": "102772058120690", "ex_id": "20271", "ex_cost_center_code": "1200044178", "dcore_store_appid": "s20170823000005627" } }, { "_id": "3850146292927823873", "name": "个旧丽水金湾", "extend_code": { "comm_shop_id": "33a9c52f61e347c492499be919f96225", "ex_code": "20410", "alipay_id": "2015061200077000000000193008", "us_id": "43993", "comm_code": "301003400000110", "upcard_terminal": "87300506", "upcard_mer_id": "102873058120363", "ex_id": "20206", "ex_cost_center_code": "1200043993", "dcore_store_appid": "s20170823000005295" } }, { "_id": "3850146242206105601", "name": "三林金谊广场", "extend_code": { "comm_shop_id": "5f7225e33bbc49d4a436a744941fab01", "ex_code": "20314", "alipay_id": "2015060900077000000000166164", "us_id": "43678", "comm_code": "301003400000198", "upcard_terminal": "02193707", "upcard_mer_id": "102210058125752", "ex_id": "20080", "ex_cost_center_code": "1200043678", "dcore_store_appid": "s20170823000005386" } }, { "_id": "3850146068461256705", "name": "南京金轮店", "extend_code": { "comm_shop_id": "8751a8393afe48cca5c78a42e9f2bf99", "ex_code": "20023", "alipay_id": "2015061000077000000000191171", "us_id": "42137", "comm_code": "301003400000255", "upcard_terminal": "02516544", "upcard_mer_id": "102250058120834", "ex_id": "306", "ex_cost_center_code": "1200042137", "dcore_store_appid": "s20170823000005479" } }, { "_id": "3850146085720817665", "name": "上海惠南店", "extend_code": { "comm_shop_id": "9ea930cba93640a9bac3b9248a360449", "ex_code": "20045", "alipay_id": "2015060900077000000000174616", "us_id": "42302", "comm_code": "301003400000294", "upcard_terminal": "02148880", "upcard_mer_id": "102210058120719", "ex_id": "248", "ex_cost_center_code": "1200042302", "dcore_store_appid": "s20170823000005491" } }, { "_id": "3850146250200449025", "name": "无锡清扬路", "extend_code": { "comm_shop_id": "3c5c9e21b5264dcd901369d2dcdb68a1", "ex_code": "20330", "alipay_id": "2020030200077000000092104834", "us_id": "43789", "comm_code": "301003400004506", "upcard_terminal": "51103375", "upcard_mer_id": "102510058122096", "ex_id": "20121", "ex_cost_center_code": "1200043789", "dcore_store_appid": "s20170823000005154" } }, { "_id": "3850146097267736577", "name": "重庆百联店", "extend_code": { "comm_shop_id": "2cda330de808408e808ec1dd41a80d7d", "ex_code": "20068", "alipay_id": "2015061200077000000000188808", "us_id": "42386", "comm_code": "301003400000094", "upcard_terminal": "02306266", "upcard_mer_id": "102230058120113", "ex_id": "637", "ex_cost_center_code": "1200042386", "dcore_store_appid": "s20170823000005563" } }, { "_id": "3850146200409866241", "name": "成都金牛万达店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20249", "comm_shop_id": "cfa1636b843147e689c28d16d33e5501", "us_id": "43173", "alipay_id": "2015061200077000000000192998", "takeaway_eleme_id": '', "upcard_terminal": "02817503", "comm_code": "301003400000383", "upcard_mer_id": "102280058122947", "ex_id": "8002", "ex_cost_center_code": "1200043173", "dcore_store_appid": "s20170823000005359" } }, { "_id": "3850146315124080641", "name": "武汉武商众圆广场", "extend_code": { "comm_shop_id": "077ad732b004427db9136f4ff395247d", "ex_code": "20441", "alipay_id": "2015061200077000000000188810", "us_id": "43991", "comm_code": "301003400000031", "upcard_terminal": "02722812", "upcard_mer_id": "102270058124931", "ex_id": "20204", "ex_cost_center_code": "1200043991", "dcore_store_appid": "s20170823000005593" } }, { "_id": "3850146351216066561", "name": "太原龙湖万达", "extend_code": { "comm_shop_id": "fade296a0d29471a9f5dea7062299c13", "ex_code": "20497", "alipay_id": "2015113000077000000006669872", "us_id": "44237", "comm_code": "301003400000451", "upcard_terminal": "35103694", "upcard_mer_id": "102351058121580", "ex_id": "20291", "ex_cost_center_code": "1200044237", "dcore_store_appid": "s20170823000005313" } }, { "_id": "3850146299441577985", "name": "盐城宝龙店", "extend_code": { "comm_shop_id": "c9d21b9803a64f0182469c5d664bb532", "ex_code": "20420", "alipay_id": "2015061100077000000000192954", "us_id": "43996", "comm_code": "301003400000365", "upcard_terminal": "51545365", "upcard_mer_id": "102515058120367", "ex_id": "20219", "ex_cost_center_code": "1200043996", "dcore_store_appid": "s20170823000005597" } }, { "_id": "3850146284807651329", "name": "烟台万达店", "extend_code": { "comm_shop_id": "ff19931090de4fad8a464936a4aa8394", "ex_code": "20394", "alipay_id": "2015061100077000000000192965", "us_id": "44000", "comm_code": "301003400000463", "upcard_terminal": "53530348", "upcard_mer_id": "102535058120140", "ex_id": "20191", "ex_cost_center_code": "1200044000", "dcore_store_appid": "s20170823000005599" } }, { "_id": "3850146124178391041", "name": "湖州爱山店", "extend_code": { "comm_shop_id": "9e3161b7f44d45f7b1fc015ba783ed36", "ex_code": "20119", "alipay_id": "2021092200077000000027981843", "us_id": "42608", "comm_code": "301003400000292", "upcard_terminal": "57200075", "upcard_mer_id": "102572058120006", "ex_id": "421", "ex_cost_center_code": "1200042608", "dcore_store_appid": "s20170823000005511" } }, { "_id": "3850146368945389569", "name": "南通万达", "extend_code": { "comm_shop_id": "ef764caeffc04408af79c5023d4428c3", "ex_code": "20527", "alipay_id": "2016031800077000000014990612", "us_id": "44235", "comm_code": "301003400000431", "upcard_terminal": "51300830", "upcard_mer_id": "102513058120145", "ex_id": "20336", "ex_cost_center_code": "1200044235", "dcore_store_appid": "s20170823000005641" } }, { "_id": "3850146222857781249", "name": "贵阳鸿通城", "extend_code": { "comm_shop_id": "2bd98fe0497f4a7596185c47a927810b", "ex_code": "20277", "alipay_id": "2015061200077000000000194542", "us_id": "43468", "comm_code": "301003400000092", "upcard_terminal": "85101432", "upcard_mer_id": "102851058120346", "ex_id": "", "ex_cost_center_code": "1200043468", "dcore_store_appid": "s20170823000005247" } }, { "_id": "3850146384481091585", "name": "宁波高鑫广场", "extend_code": { "comm_shop_id": "6af19c6e0672487583d82c77e53af9d1", "ex_code": "20556", "alipay_id": "2016031800077000000015016816", "us_id": "44408", "comm_code": "301003400000209", "upcard_terminal": "57403294", "upcard_mer_id": "102574058120518", "ex_id": "20377", "ex_cost_center_code": "1200044408", "dcore_store_appid": "s20170823000005325" } }, { "_id": "3850146272237322241", "name": "东莞东城万达店", "extend_code": { "comm_shop_id": "d8795b25a28448f29217ac8f4ab3de36", "ex_code": "20371", "alipay_id": "2015061200077000000000188790", "us_id": "43904", "comm_code": "301003400000395", "upcard_terminal": "75900242", "upcard_mer_id": "102759058120011", "ex_id": "20154", "ex_cost_center_code": "1200043904", "dcore_store_appid": "s20170823000005416" } }, { "_id": "3850146316751470593", "name": "珠海富华里", "extend_code": { "comm_shop_id": "5bc1cefbec154c4e98ebfae9b1ca330f", "ex_code": "20444", "alipay_id": "2015061200077000000000182867", "us_id": "44086", "comm_code": "301003400000190", "upcard_terminal": "75601310", "upcard_mer_id": "102756058120158", "ex_id": "20234", "ex_cost_center_code": "1200044086", "dcore_store_appid": "s20170823000005614" } }, { "_id": "3850146297424117761", "name": "郑州瀚海北金店", "extend_code": { "us_id": "43957", "ex_id": "20218", "ex_cost_center_code": "1200043957", "ex_code": "20417" } }, { "_id": "3850146273227177985", "name": "荆州万达店", "extend_code": { "comm_shop_id": "68bd62f85a854849a7fa63016ebed89e", "ex_code": "20373", "alipay_id": "2015061200077000000000182880", "us_id": "43910", "comm_code": "301003400000206", "upcard_terminal": "71600159", "upcard_mer_id": "102716058120041", "ex_id": "20170", "ex_cost_center_code": "1200043910", "dcore_store_appid": "s20170823000005420" } }, { "_id": "3850146234614415361", "name": "徐州云龙万达", "extend_code": { "comm_shop_id": "4e04f82fe6ec48f08a1350c017595e72", "ex_code": "20299", "alipay_id": "2015061100077000000000194499", "us_id": "43608", "comm_code": "301003400000158", "upcard_terminal": "51600591", "upcard_mer_id": "102516058120113", "ex_id": "20052", "ex_cost_center_code": "1200043608", "dcore_store_appid": "s20170823000005376" } }, { "_id": "3850146274363834369", "name": "芜湖华强店", "extend_code": { "comm_shop_id": "c9e412d139af4525be057d518d751ea4", "ex_code": "20375", "alipay_id": "2015061100077000000000194520", "us_id": "43909", "comm_code": "301003400000366", "upcard_terminal": "55300828", "upcard_mer_id": "102553058120217", "ex_id": "20177", "ex_cost_center_code": "1200043909", "dcore_store_appid": "s20170823000005287" } }, { "_id": "3850146403821027329", "name": "昆明广场", "extend_code": { "comm_shop_id": "afe42b24523d4e1c89288f5ebe700579", "ex_code": "20618", "alipay_id": "2016111600077000000019999004", "us_id": "44434", "comm_code": "301003400000319", "upcard_terminal": "87111711", "upcard_mer_id": "102871058126596", "ex_id": "20400", "ex_cost_center_code": "1200044434", "dcore_store_appid": "s20170823000005326" } }, { "_id": "3850146327337893889", "name": "嘉兴万达", "extend_code": { "comm_shop_id": "e5d6f0c8b2aa4e8398afc628153b07d0", "ex_code": "20463", "alipay_id": "2015093000077000000004500946", "us_id": "44135", "comm_code": "301003400000415", "upcard_terminal": "57302985", "upcard_mer_id": "102573058120082", "ex_id": "", "ex_cost_center_code": "1200044135", "dcore_store_appid": "s20170823000005623" } }, { "_id": "3850146277048188929", "name": "武汉群星城店", "extend_code": { "comm_shop_id": "cd8c0906bbd6473b89181d5f38734da0", "ex_code": "20380", "alipay_id": "2015061200077000000000194550", "us_id": "43955", "comm_code": "301003400000376", "upcard_terminal": "02722084", "upcard_mer_id": "102270058124770", "ex_id": "20186", "ex_cost_center_code": "1200043955", "dcore_store_appid": "s20170823000005586" } }, { "_id": "3850146309465964545", "name": "宜昌水悦城", "extend_code": { "comm_shop_id": "51af7b725e0b45269ef88e5ea7bff8a6", "ex_code": "20430", "alipay_id": "2015093000077000000004515138", "us_id": "44078", "comm_code": "301003400000166", "upcard_terminal": "71701841", "upcard_mer_id": "102717058120173", "ex_id": "", "ex_cost_center_code": "1200044078", "dcore_store_appid": "s20170823000005612" } }, { "_id": "3850146407067418625", "name": "湛江万达店", "extend_code": { "comm_shop_id": "da295504d8a9479590e1401b9c41774f", "ex_code": "20605", "alipay_id": "2016111700077000000020031207", "us_id": "44506", "comm_code": "301003400000402", "upcard_terminal": "75900414", "upcard_mer_id": "102759058120040", "ex_id": "20417", "ex_cost_center_code": "1200044506", "dcore_store_appid": "s20170823000005680" } }, { "_id": "3850146283159289857", "name": "淮南新世界店", "extend_code": { "comm_shop_id": "64bc18a216c04d1789cf5c3744fb939f", "ex_code": "20391", "alipay_id": "2015061200077000000000192982", "us_id": "43923", "comm_code": "301003400000203", "upcard_terminal": "55400193", "upcard_mer_id": "102554058120071", "ex_id": "20190", "ex_cost_center_code": "1200043923", "dcore_store_appid": "s20170823000005578" } }, { "_id": "3850146347965480961", "name": "无锡人民路百盛", "extend_code": { "comm_shop_id": "c3cac56713fa4ffab9e5e9d3b345713d", "ex_code": "20491", "alipay_id": "2015093000077000000004505788", "us_id": "44248", "comm_code": "301003400000351", "upcard_terminal": "51103159", "upcard_mer_id": "102510058122068", "ex_id": "20304", "ex_cost_center_code": "1200044248", "dcore_store_appid": "s20170823000005648" } }, { "_id": "3850146404366286849", "name": "长沙梅溪湖步步高影院店", "extend_code": { "comm_shop_id": "73c4261111464b33917e0415c67673c7", "ex_code": "20561", "alipay_id": "2016081500077000000018032559", "us_id": "44479", "comm_code": "301003400000231", "upcard_terminal": "73110806", "upcard_mer_id": "102731058121608", "ex_id": "20420", "ex_cost_center_code": "1200044479", "dcore_store_appid": "s20170823000005677" } }, { "_id": "3850146324682899457", "name": "南京中海环宇城店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20458", "comm_shop_id": "08e63c0575264480b1a9ac2fbc9f241b", "us_id": "44137", "alipay_id": "2015121500077000000013820426", "takeaway_eleme_id": '', "upcard_terminal": "02595296", "comm_code": "301003400000037", "upcard_mer_id": "102250058122468", "ex_id": "20261", "ex_cost_center_code": "1200044137", "dcore_store_appid": "s20170823000005624" } }, { "_id": "3850146412192858113", "name": "杭州东站加盟店", "extend_code": { "comm_shop_id": "1ec5943c41aa4014b0cbb78049020959", "ex_code": "20584", "alipay_id": "2018040900077000000048275897", "us_id": "44520", "comm_code": "301003400004523", "upcard_terminal": "57109726", "upcard_mer_id": "102571058122479", "ex_id": "20429", "ex_cost_center_code": "1200844520", "dcore_store_appid": "s20170929000006487" } }, { "_id": "3850146126221017089", "name": "西藏路大悦城店", "extend_code": { "comm_shop_id": "3e878781ae1f49478421cb6404c9a970", "ex_code": "20123", "alipay_id": "2015060900077000000000176455", "us_id": "42636", "comm_code": "301003400000129", "upcard_terminal": "02148839", "upcard_mer_id": "102210058120781", "ex_id": "284", "ex_cost_center_code": "1200042636", "dcore_store_appid": "s20170823000005517" } }, { "_id": "3850146297898074113", "name": "杭州水晶城购物中心", "extend_code": { "comm_shop_id": "8b43ed89f39044cf8e7191133ae1960a", "ex_code": "20418", "alipay_id": "2015060900077000000000166166", "us_id": "43989", "comm_code": "301003400000262", "upcard_terminal": "57104289", "upcard_mer_id": "102571058121029", "ex_id": "20223", "ex_cost_center_code": "1200043989", "dcore_store_appid": "s20170823000005592" } }, { "_id": "3850146334573068289", "name": "缤谷广场一期", "extend_code": { "comm_shop_id": "cd5d30ded8d2492ab8cb31c31442f689", "ex_code": "20468", "alipay_id": "2015093000077000000004490206", "us_id": "44136", "comm_code": "301003400000374", "upcard_terminal": "02193914", "upcard_mer_id": "102210058126730", "ex_id": "20276", "ex_cost_center_code": "1200044136", "dcore_store_appid": "s20170823000005306" } }, { "_id": "3850146338947727361", "name": "德阳洋洋百货南街店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20475", "comm_shop_id": "64e5c303df4c4610890091e6f8ec955b", "us_id": "44121", "alipay_id": "2015061200077000000000188804", "takeaway_eleme_id": '', "upcard_terminal": "83890052", "comm_code": "301003400000204", "upcard_mer_id": "102838058120072", "ex_id": "20273", "ex_cost_center_code": "1200044121", "dcore_store_appid": "s20170823000005619" } }, { "_id": "3850146301953966081", "name": "西安曲江金地店", "extend_code": { "us_id": "44013", "ex_id": "20211", "ex_cost_center_code": "1200044013", "ex_code": "20422" } }, { "_id": "3850146339618816001", "name": "南通文峰城市广场店", "extend_code": { "comm_shop_id": "9a1d0639ee4643b68c79f0640361a88c", "ex_code": "20476", "alipay_id": "2018041900077000000048356376", "us_id": "44194", "comm_code": "301003400000283", "upcard_terminal": "51300623", "upcard_mer_id": "102513058120076", "ex_id": "20285", "ex_cost_center_code": "1200044194", "dcore_store_appid": "s20170823000005632" } }, { "_id": "3850146366860820481", "name": "永城金博大", "extend_code": { "comm_shop_id": "1b4492f5d80f4086a0be3fbc6011b6d8", "ex_code": "20523", "alipay_id": "2016011100077000000014092239", "us_id": "44296", "comm_code": "301003400000064", "upcard_terminal": "37001237", "upcard_mer_id": "102370058120016", "ex_id": "20330", "ex_cost_center_code": "1200044296", "dcore_store_appid": "s20170823000005318" } }, { "_id": "3850146340117938177", "name": "渭南万达店", "extend_code": { "comm_shop_id": "5ee859ae60dc4b03ad97034980f791f9", "ex_code": "20477", "alipay_id": "2015093000077000000004397091", "us_id": "44195", "comm_code": "301003400000197", "upcard_terminal": "91330019", "upcard_mer_id": "102913058120011", "ex_id": "20281", "ex_cost_center_code": "1200044195", "dcore_store_appid": "s20170823000005309" } }, { "_id": "3850146370006548481", "name": "南沙万达店", "extend_code": { "comm_shop_id": "15ec81c87b5644569ed514f9c994c6ea", "ex_code": "20529", "alipay_id": "2016011100077000000014107389", "us_id": "44284", "comm_code": "301003400000054", "upcard_terminal": "02081978", "upcard_mer_id": "102200058120765", "ex_id": "20342", "ex_cost_center_code": "1200044284", "dcore_store_appid": "s20170823000005317" } }, { "_id": "3850146145628061697", "name": "武汉徐东销品茂", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20159", "comm_shop_id": "eee38489bbb7468798e2b2259fa06535", "us_id": "42758", "alipay_id": "2015061200077000000000182884", "takeaway_eleme_id": '', "upcard_terminal": "02713548", "comm_code": "301003400000430", "upcard_mer_id": "102270058122304", "ex_id": "920", "ex_cost_center_code": "1200042758", "dcore_store_appid": "s20170823000005531" } }, { "_id": "3850146382891450369", "name": "李沧乐客城", "extend_code": { "comm_shop_id": "31439f966dbf4bdd9cf13f146027d547", "ex_code": "20553", "alipay_id": "2016031800077000000015165667", "us_id": "44435", "comm_code": "301003400000105", "upcard_terminal": "53205649", "upcard_mer_id": "102532058121372", "ex_id": "20404", "ex_cost_center_code": "1200044435", "dcore_store_appid": "s20170823000005676" } }, { "_id": "3850146146630500353", "name": "松江平高", "extend_code": { "comm_shop_id": "badf3f1d9d254d08bad834731023033f", "ex_code": "20161", "alipay_id": "2018051500077000000051645407", "us_id": "42724", "comm_code": "301003400000341", "upcard_terminal": "02148834", "upcard_mer_id": "102210058120848", "ex_id": "291", "ex_cost_center_code": "1200042724", "dcore_store_appid": "s20170823000005224" } }, { "_id": "3850146341648859137", "name": "西安曲江龙湖星悦荟店", "extend_code": { "comm_shop_id": "bac2da8f84504027aba17f95decb0277", "ex_code": "20480", "alipay_id": "2015093000077000000004496093", "us_id": "44239", "comm_code": "301003400000340", "upcard_terminal": "02991003", "upcard_mer_id": "102290058122918", "ex_id": "20286", "ex_cost_center_code": "1200044239", "dcore_store_appid": "s20170823000005644" } }, { "_id": "3850146108848209921", "name": "金华天地银泰店", "extend_code": { "comm_shop_id": "c6e191cb0402444294aa17cba0bc420d", "ex_code": "20090", "alipay_id": "2015061000077000000000188720", "us_id": "42493", "comm_code": "301003400000359", "upcard_terminal": "57103823", "upcard_mer_id": "102571058120390", "ex_id": "681", "ex_cost_center_code": "1200042493", "dcore_store_appid": "s20170823000005499" } }, { "_id": "3850146345448898561", "name": "阜阳颍州万达", "extend_code": { "comm_shop_id": "cea7b0e32fd84cde968797e2fcdf897c", "ex_code": "20487", "alipay_id": "2015093000077000000004449376", "us_id": "44229", "comm_code": "301003400000382", "upcard_terminal": "55801250", "upcard_mer_id": "102558058120384", "ex_id": "20290", "ex_cost_center_code": "1200044229", "dcore_store_appid": "s20170823000005311" } }, { "_id": "3850146405553274881", "name": "镇江苏宁(加盟)", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20593", "comm_shop_id": "447a8060d3bb47339d0f188d51ac4e71", "us_id": "44505", "alipay_id": "2016111600077000000019998970", "takeaway_eleme_id": '', "upcard_terminal": "51103399", "comm_code": "301003400004514", "upcard_mer_id": "102511058121216", "ex_id": "20422", "ex_cost_center_code": "1200844505", "dcore_store_appid": "s20170823000005338" } }, { "_id": "3850146248157822977", "name": "郑州锦艺店", "extend_code": { "comm_shop_id": "6b63438f69da4c91a34d1ce641376ca5", "ex_code": "20326", "alipay_id": "2018040400077000000048185151", "us_id": "43714", "comm_code": "301003400000213", "upcard_terminal": "37110795", "upcard_mer_id": "102371058122279", "ex_id": "20110", "ex_cost_center_code": "1200043714", "dcore_store_appid": "s20170823000005388" } }, { "_id": "3850146360992989185", "name": "西安印象城", "extend_code": { "comm_shop_id": "f3ca75a912a74aff8bd22d8fbf3e4d7b", "ex_code": "20512", "alipay_id": "2015120700077000000013343193", "us_id": "44238", "comm_code": "301003400000441", "upcard_terminal": "02991083", "upcard_mer_id": "102290058122930", "ex_id": "20318", "ex_cost_center_code": "1200044238", "dcore_store_appid": "s20170823000005643" } }, { "_id": "3850146123696046081", "name": "青浦桥梓湾店", "extend_code": { "comm_shop_id": "9ce3d9fc145e46fa88881bfff3f6fb8a", "ex_code": "20118", "alipay_id": "2015060900077000000000169208", "us_id": "42609", "comm_code": "301003400000289", "upcard_terminal": "02194803", "upcard_mer_id": "102210058126903", "ex_id": "282", "ex_cost_center_code": "1200042609", "dcore_store_appid": "s20170823000005512" } }, { "_id": "3850146352289808385", "name": "西双版纳万达", "extend_code": { "comm_shop_id": "029196710a444442b0bad9f54afffd58", "ex_code": "20499", "alipay_id": "2015093000077000000004511911", "us_id": "44240", "comm_code": "301003400000026", "upcard_terminal": "87110109", "upcard_mer_id": "102691058120118", "ex_id": "20302", "ex_cost_center_code": "1200044240", "dcore_store_appid": "s20170823000005314" } }, { "_id": "3850146361974456321", "name": "绍兴汇金", "extend_code": { "comm_shop_id": "2de6c5c6a4584162b10e138cd2084cb4", "ex_code": "20514", "alipay_id": "2015121500077000000013667398", "us_id": "44293", "comm_code": "301003400000096", "upcard_terminal": "57500771", "upcard_mer_id": "102575058120106", "ex_id": "20327", "ex_cost_center_code": "1200044293", "dcore_store_appid": "s20170823000005653" } }, { "_id": "3850146149830754305", "name": "西安立丰广场店", "extend_code": { "comm_shop_id": "2f8583111a08449094c519ce488ccc8b", "ex_code": "20167", "alipay_id": "2016112200077000000020268730", "us_id": "42793", "comm_code": "301003400000100", "upcard_terminal": "02903677", "upcard_mer_id": "102290058122453", "ex_id": "962", "ex_cost_center_code": "1200042793", "dcore_store_appid": "s20170823000005535" } }, { "_id": "3850146355414564865", "name": "西塘古镇", "extend_code": { "comm_shop_id": "ab46f87884124d9a89636ee74c9a6051", "ex_code": "20505", "alipay_id": "2021102800077000000029382046", "us_id": "44241", "comm_code": "301003400000317", "upcard_terminal": "57303145", "upcard_mer_id": "102573058120136", "ex_id": "20303", "ex_cost_center_code": "1200044241", "dcore_store_appid": "s20170823000005645" } }, { "_id": "3850146134831923201", "name": "重庆大渡口壹街店", "extend_code": { "comm_shop_id": "97ef30defe1d4c2a88d00e1a1fb965cf", "ex_code": "20139", "alipay_id": "2015061200077000000000188806", "us_id": "42685", "comm_code": "301003400000278", "upcard_terminal": "02306261", "upcard_mer_id": "102230058120198", "ex_id": "641", "ex_cost_center_code": "1200042685", "dcore_store_appid": "s20170823000005524" } }, { "_id": "3850146063193210881", "name": "上虞百货店", "extend_code": { "comm_shop_id": "6b265f95477e4e23804e73ad79381eb0", "ex_code": "20013", "alipay_id": "2015060900077000000000174623", "us_id": "42006", "comm_code": "301003400000212", "upcard_terminal": "57103824", "upcard_mer_id": "102571058120389", "ex_id": "451", "ex_cost_center_code": "1200042006", "dcore_store_appid": "s20170823000005472" } }, { "_id": "3850146410599022593", "name": "昆山昆城店", "extend_code": { "comm_shop_id": "9d8eb96312af441bb12786aeb41e8195", "ex_code": "20609", "alipay_id": "2016050900077000000015478520", "us_id": "44548", "comm_code": "301003400000291", "upcard_terminal": "51216860", "upcard_mer_id": "102512089993243", "ex_id": "", "ex_cost_center_code": "1200044548", "dcore_store_appid": "s20170823000005424" } }, { "_id": "3850146160463314945", "name": "昌里", "extend_code": { "comm_shop_id": "a471961cbcda4ca6bac37175c42027a7", "ex_code": "20188", "alipay_id": "2015060900077000000000174619", "us_id": "42850", "comm_code": "301003400000304", "upcard_terminal": "02148816", "upcard_mer_id": "102210058120966", "ex_id": "2002", "ex_cost_center_code": "1200042850", "dcore_store_appid": "s20170823000005544" } }, { "_id": "3850146342244450305", "name": "泰安万达广场店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20481", "comm_shop_id": "870d4e946418483287522bd978b00744", "us_id": "44211", "alipay_id": "2015113000077000000006599324", "takeaway_eleme_id": '', "upcard_terminal": "53885523", "comm_code": "301003400000254", "upcard_mer_id": "102538058120492", "ex_id": "20274", "ex_cost_center_code": "1200044211", "dcore_store_appid": "s20170823000005634" } }, { "_id": "3850146379577950209", "name": "嘉兴八佰伴", "extend_code": { "comm_shop_id": "f23d4145209245848d194ce38c5e6bee", "ex_code": "20547", "alipay_id": "2016031800077000000015026503", "us_id": "44406", "comm_code": "301003400000434", "upcard_terminal": "57303158", "upcard_mer_id": "102573058120140", "ex_id": "20394", "ex_cost_center_code": "1200044406", "dcore_store_appid": "s20170823000005673" } }, { "_id": "3850146260568768513", "name": "南京澳林广场店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20350", "comm_shop_id": "64af83e5988247fdba557fcbaf072b2f", "us_id": "43834", "alipay_id": "2015061000077000000000188729", "takeaway_eleme_id": '', "upcard_terminal": "02593482", "comm_code": "301003400000202", "upcard_mer_id": "102250058122251", "ex_id": "20146", "ex_cost_center_code": "1200043834", "dcore_store_appid": "s20170823000005409" } }, { "_id": "3850146344484208641", "name": "青浦百联奥特莱斯", "extend_code": { "comm_shop_id": "07a62e94176c4a6e8153bcd53ea97cfa", "ex_code": "20485", "alipay_id": "2018041900077000000048365157", "us_id": "44256", "comm_code": "301003400004452", "upcard_terminal": "02194015", "upcard_mer_id": "102210058126747", "ex_id": "20301", "ex_cost_center_code": "1200844256", "dcore_store_appid": "s20170823000005164" } }, { "_id": "3850146385965875201", "name": "蜀都万达店", "extend_code": { "comm_shop_id": "673e68ff23ff4925a97f867fc9c01d54", "ex_code": "20559", "alipay_id": "2016050900077000000015450642", "us_id": "44481", "comm_code": "301003400000205", "upcard_terminal": "02893985", "upcard_mer_id": "102280058125169", "ex_id": "20408", "ex_cost_center_code": "1200044481", "dcore_store_appid": "s20170823000005327" } }, { "_id": "3850146170768719873", "name": "常州新北万达", "extend_code": { "comm_shop_id": "52ab400f3c5d4fd38b5e530d485e8b88", "ex_code": "20200", "alipay_id": "2015061000077000000000192928", "us_id": "42897", "comm_code": "301003400000167", "upcard_terminal": "51900953", "upcard_mer_id": "102519058120149", "ex_id": "558", "ex_cost_center_code": "1200042897", "dcore_store_appid": "s20170823000005233" } }, { "_id": "3850146173973168129", "name": "成都王府井", "extend_code": { "comm_shop_id": "19bf63f85106443b8a4dd0eb12f03b43", "ex_code": "20206", "alipay_id": "2015061200077000000000191237", "us_id": "42896", "comm_code": "301003400000063", "upcard_terminal": "02817506", "upcard_mer_id": "102280058122415", "ex_id": "817", "ex_cost_center_code": "1200042896", "dcore_store_appid": "s20170823000005554" } }, { "_id": "3850146180268818433", "name": "武汉光谷天地", "extend_code": { "comm_shop_id": "17596db283b64a3ea04591a9b71183db", "ex_code": "20218", "alipay_id": "2015061200077000000000193012", "us_id": "42885", "comm_code": "301003400000057", "upcard_terminal": "02713540", "upcard_mer_id": "102270058122469", "ex_id": "927", "ex_cost_center_code": "1200042885", "dcore_store_appid": "s20170823000005551" } }, { "_id": "3850146360347066369", "name": "重庆巴南万达店", "extend_code": { "comm_shop_id": "7ec83f96f11a48788a747170aa7a19ce", "ex_code": "20511", "alipay_id": "2015113000077000000006713015", "us_id": "44227", "comm_code": "301003400000242", "upcard_terminal": "02385374", "upcard_mer_id": "102230058121781", "ex_id": "20296", "ex_cost_center_code": "1200044227", "dcore_store_appid": "s20170823000005635" } }, { "_id": "3850146070461939713", "name": "上海七宝嘉茂店", "extend_code": { "comm_shop_id": "31520e8428c7478b80647bd8f35d44b2", "ex_code": "20027", "alipay_id": "2015060900077000000000174613", "us_id": "42210", "comm_code": "301003400000107", "upcard_terminal": "02194923", "upcard_mer_id": "102210058120699", "ex_id": "236", "ex_cost_center_code": "1200042210", "dcore_store_appid": "s20170823000005482" } }, { "_id": "3850146273751465985", "name": "连云港苏宁广场店", "extend_code": { "comm_shop_id": "7b03e2bb670a47ff82197181c4ade072", "ex_code": "20374", "alipay_id": "2016011100077000000014099173", "us_id": "43939", "comm_code": "301003400004564", "upcard_terminal": "51800158", "upcard_mer_id": "102518058120020", "ex_id": "20182", "ex_cost_center_code": "1200843939", "dcore_store_appid": "s20170823000005159" } }, { "_id": "3850146364088385537", "name": "西安阳光天地店", "extend_code": { "comm_shop_id": "145d13098a4f44ab8499dee8dd22179f", "ex_code": "20518", "alipay_id": "2015121500077000000013671574", "us_id": "44316", "comm_code": "301003400000050", "upcard_terminal": "02991139", "upcard_mer_id": "102290058122936", "ex_id": "20321", "ex_cost_center_code": "1200044316", "dcore_store_appid": "s20170823000005658" } }, { "_id": "3850146280567209985", "name": "昆明西山万达店", "extend_code": { "comm_shop_id": "9cd0c2208d7a452e8800c0e374f4f30a", "ex_code": "20386", "alipay_id": "2015061200077000000000191231", "us_id": "43905", "comm_code": "301003400000288", "upcard_terminal": "87108973", "upcard_mer_id": "102871058125507", "ex_id": "20171", "ex_cost_center_code": "1200043905", "dcore_store_appid": "s20170823000005417" } }, { "_id": "3850146075960672257", "name": "上海黄兴店", "extend_code": { "comm_shop_id": "5e45c205fcbf487890397415655c1615", "ex_code": "20034", "alipay_id": "2015060900077000000000178448", "us_id": "42265", "comm_code": "301003400000196", "upcard_terminal": "02148896", "upcard_mer_id": "102210058120703", "ex_id": "242", "ex_cost_center_code": "1200042265", "dcore_store_appid": "s20170823000005489" } }, { "_id": "3850146193325686785", "name": "南昌红谷滩", "extend_code": { "comm_shop_id": "791c85e444d4421892852f5d424ed228", "ex_code": "20235", "alipay_id": "2015061000077000000000194476", "us_id": "43064", "comm_code": "301003400000235", "upcard_terminal": "79101363", "upcard_mer_id": "102791058120129", "ex_id": "984", "ex_cost_center_code": "1200043064", "dcore_store_appid": "s20170823000005353" } }, { "_id": "3850146380056100865", "name": "扬州华懋购物中心加盟", "extend_code": { "comm_shop_id": "5d8f5d5b15094c0d87bac77eb7a5d7ff", "ex_code": "20548", "alipay_id": "2016011100077000000014227415", "us_id": "44372", "comm_code": "301003400004539", "upcard_terminal": "51400825", "upcard_mer_id": "102514058120231", "ex_id": "20390", "ex_cost_center_code": "1200844372", "dcore_store_appid": "s20170823000005334" } }, { "_id": "3850146094247837697", "name": "上海金桥店", "extend_code": { "comm_shop_id": "a5062db5de3a47639bb9dd361dfce430", "ex_code": "20061", "alipay_id": "2015060900077000000000169201", "us_id": "42377", "comm_code": "301003400000308", "upcard_terminal": "02148871", "upcard_mer_id": "102210058120728", "ex_id": "220", "ex_cost_center_code": "1200042377", "dcore_store_appid": "s20170823000005561" } }, { "_id": "3850146384980213761", "name": "常州文化宫延陵(加盟)", "extend_code": { "comm_shop_id": "04371ae82b284fffb16a1da0da21fb10", "ex_code": "20557", "alipay_id": "2016050900077000000015478521", "us_id": "44480", "comm_code": "301003400004446", "upcard_terminal": "51900952", "upcard_mer_id": "102519058120148", "ex_id": "20409", "ex_cost_center_code": "1200844480", "dcore_store_appid": "s20170823000005337" } }, { "_id": "3850146095871033345", "name": "济南嘉华店", "extend_code": { "comm_shop_id": "eac4768deb544f6291e14b871b8916d0", "ex_code": "20064", "alipay_id": "2015061100077000000000192962", "us_id": "42373", "comm_code": "301003400000422", "upcard_terminal": "53100857", "upcard_mer_id": "102531058120053", "ex_id": "532", "ex_cost_center_code": "1200042373", "dcore_store_appid": "s20170823000005498" } }, { "_id": "3850146194864996353", "name": "芜湖万达", "extend_code": { "comm_shop_id": "cd1c6196e27144c783d3006b1f116e1e", "ex_code": "20238", "alipay_id": "2015061100077000000000192970", "us_id": "42900", "comm_code": "301003400000373", "upcard_terminal": "55301396", "upcard_mer_id": "102553058120173", "ex_id": "464", "ex_cost_center_code": "1200042900", "dcore_store_appid": "s20170823000005556" } }, { "_id": "3850146406060785665", "name": "荆门万达", "extend_code": { "comm_shop_id": "23969bddac5f4e648a965dbe1521b866", "ex_code": "20604", "alipay_id": "2016111700077000000019991158", "us_id": "44507", "comm_code": "301003400000080", "upcard_terminal": "72400282", "upcard_mer_id": "102724058120083", "ex_id": "20416", "ex_cost_center_code": "1200044507", "dcore_store_appid": "s20170823000005681" } }, { "_id": "3850146209268236289", "name": "上海南翔", "extend_code": { "comm_shop_id": "448fd677478143cea99237d7d2bcd1b1", "ex_code": "20257", "alipay_id": "2015060900077000000000178446", "us_id": "43150", "comm_code": "301003400000139", "upcard_terminal": "02148808", "upcard_mer_id": "102210058121110", "ex_id": "2011", "ex_cost_center_code": "1200043150", "dcore_store_appid": "s20170823000005357" } }, { "_id": "3850146198937665537", "name": "莆田万达店", "extend_code": { "comm_shop_id": "f042971d60cc4e04b6568057e05d51fb", "ex_code": "20246", "alipay_id": "2015061200077000000000182869", "us_id": "43171", "comm_code": "301003400000433", "upcard_terminal": "59400363", "upcard_mer_id": "102594058120022", "ex_id": "866", "ex_cost_center_code": "1200043171", "dcore_store_appid": "s20170929000006503" } }, { "_id": "3850146214192349185", "name": "杭州湖滨名品", "extend_code": { "comm_shop_id": "2fee40a8f4354c0b90613f1587a43e9a", "ex_code": "20261", "alipay_id": "2015060900077000000000178456", "us_id": "43419", "comm_code": "301003400000101", "upcard_terminal": "57103814", "upcard_mer_id": "102571058120785", "ex_id": "412", "ex_cost_center_code": "1200043419", "dcore_store_appid": "s20170823000005368" } }, { "_id": "3850146290969083905", "name": "淄博银泰城店", "extend_code": { "comm_shop_id": "5d8b87109753400fa78d584c30f303bc", "ex_code": "20406", "alipay_id": "2015061100077000000000188769", "us_id": "43992", "comm_code": "301003400000194", "upcard_terminal": "53390014", "upcard_mer_id": "102533058120066", "ex_id": "20216", "ex_cost_center_code": "1200043992", "dcore_store_appid": "s20170823000005594" } }, { "_id": "3850146217124167681", "name": "湖州浙北", "extend_code": { "comm_shop_id": "567e5894194c417f8c53ae25c5d24973", "ex_code": "20266", "alipay_id": "2015061000077000000000192920", "us_id": "43457", "comm_code": "301003400000176", "upcard_terminal": "57200074", "upcard_mer_id": "102572058120008", "ex_id": "20004", "ex_cost_center_code": "1200043457", "dcore_store_appid": "s20170823000005371" } }, { "_id": "3850146298405584897", "name": "深圳龙华九方购物中心店", "extend_code": { "comm_shop_id": "6ed4b5a05aba452facb800d0a70f645b", "ex_code": "20419", "alipay_id": "2015061200077000000000191227", "us_id": "44012", "comm_code": "301003400000218", "upcard_terminal": "75512777", "upcard_mer_id": "102755058122316", "ex_id": "20226", "ex_cost_center_code": "1200044012", "dcore_store_appid": "s20170823000005600" } }, { "_id": "3850146214695665665", "name": "杭州西溪印象城", "extend_code": { "comm_shop_id": "e0f202315136422e9267cdf0ce74a496", "ex_code": "20262", "alipay_id": "2015060900077000000000176464", "us_id": "43420", "comm_code": "301003400000408", "upcard_terminal": "57103813", "upcard_mer_id": "102571058120786", "ex_id": "411", "ex_cost_center_code": "1200043420", "dcore_store_appid": "s20170823000005369" } }, { "_id": "3850146099264225281", "name": "湘潭华隆步步高店", "extend_code": { "comm_shop_id": "270e43e469254701b10248a05f086ed0", "ex_code": "20071", "alipay_id": "2015061200077000000000182889", "us_id": "42409", "comm_code": "301003400000085", "upcard_terminal": "73203911", "upcard_mer_id": "102732058120152", "ex_id": "832", "ex_cost_center_code": "1200042409", "dcore_store_appid": "s20170823000005567" } }, { "_id": "3850146413992214529", "name": "襄阳天元四季城", "extend_code": { "comm_shop_id": "22570bbfdfcb41d880fec7cc57d1d6fc", "ex_code": "20615", "alipay_id": "2016081500077000000018020536", "us_id": "44534", "comm_code": "301003400000075", "upcard_terminal": "71004522", "upcard_mer_id": "102710058121112", "ex_id": "", "ex_cost_center_code": "1200044534", "dcore_store_appid": "s20170823000005683" } }, { "_id": "3850146219833688065", "name": "重庆万州万达", "extend_code": { "comm_shop_id": "2bc0457bde594535947d401c3b693e63", "ex_code": "20271", "alipay_id": "2015061200077000000000188809", "us_id": "43480", "comm_code": "301003400000091", "upcard_terminal": "02383942", "upcard_mer_id": "102230058120757", "ex_id": "20009", "ex_cost_center_code": "1200043480", "dcore_store_appid": "s20170823000005248" } }, { "_id": "3850146303505858561", "name": "西安汉神", "extend_code": { "comm_shop_id": "f35e6bc7a9db46e3aec0d307b2488bdc", "ex_code": "20424", "alipay_id": "2015093000077000000004416507", "us_id": "44015", "comm_code": "301003400000440", "upcard_terminal": "02990620", "upcard_mer_id": "102290058122791", "ex_id": "", "ex_cost_center_code": "1200044015", "dcore_store_appid": "s20170823000005602" } }, { "_id": "3850146112304316417", "name": "西安南大街店", "extend_code": { "comm_shop_id": "72d27066902e475a9d91e073c7a0c5e2", "ex_code": "20097", "alipay_id": "2015061200077000000000191252", "us_id": "42551", "comm_code": "301003400000228", "upcard_terminal": "02903680", "upcard_mer_id": "102290058122445", "ex_id": "959", "ex_cost_center_code": "1200042551", "dcore_store_appid": "s20170823000005503" } }, { "_id": "3850146128976674817", "name": "合肥包河万达店", "extend_code": { "comm_shop_id": "b60b3b402c304a72ad279f7304ed7849", "ex_code": "20128", "alipay_id": "2015061100077000000000194518", "us_id": "42624", "comm_code": "301003400000333", "upcard_terminal": "55118205", "upcard_mer_id": "102551058121525", "ex_id": "155", "ex_cost_center_code": "1200042624", "dcore_store_appid": "s20170823000005515" } }, { "_id": "3850146218231463937", "name": "信阳天润广场", "extend_code": { "comm_shop_id": "cd7ee407ef3149cfb1b21f1e67228a29", "ex_code": "20268", "alipay_id": "2015061100077000000000191209", "us_id": "43460", "comm_code": "301003400000375", "upcard_terminal": "37602307", "upcard_mer_id": "102376058120094", "ex_id": "20007", "ex_cost_center_code": "1200043460", "dcore_store_appid": "s20170823000005373" } }, { "_id": "3850146154310270977", "name": "东莞星河城", "extend_code": { "comm_shop_id": "868e5a8067a548b4baea11643fa11a98", "ex_code": "20176", "alipay_id": "2015061200077000000000192989", "us_id": "42803", "comm_code": "301003400000253", "upcard_terminal": "76903426", "upcard_mer_id": "102769058120283", "ex_id": "496", "ex_cost_center_code": "1200042803", "dcore_store_appid": "s20170823000005536" } }, { "_id": "3850146231267360769", "name": "昆明新西南", "extend_code": { "comm_shop_id": "c663e66af0024751ba3b930ea773a266", "ex_code": "43583", "alipay_id": "2015061200077000000000192993", "us_id": "43583", "comm_code": "301003400000358", "upcard_terminal": "87108951", "upcard_mer_id": "102871058125486", "ex_id": "43583", "ex_cost_center_code": "1200043583", "dcore_store_appid": "s20170823000005265" } }, { "_id": "3850146139856699393", "name": "杭州星光大道店", "extend_code": { "comm_shop_id": "d453b5912b4a4c1cab468decfeeac74d", "ex_code": "20148", "alipay_id": "2015060900077000000000176462", "us_id": "42722", "comm_code": "301003400000391", "upcard_terminal": "57103821", "upcard_mer_id": "102571058120438", "ex_id": "405", "ex_cost_center_code": "1200042722", "dcore_store_appid": "s20170823000005527" } }, { "_id": "3850146157518913537", "name": "武汉武商摩尔", "extend_code": { "comm_shop_id": "d2acbef3c7684e45892e8a01288a17d9", "ex_code": "20182", "alipay_id": "2015061200077000000000191249", "us_id": "42820", "comm_code": "301003400000387", "upcard_terminal": "02713545", "upcard_mer_id": "102270058122422", "ex_id": "923", "ex_cost_center_code": "1200042820", "dcore_store_appid": "s20170823000005539" } }, { "_id": "3850146232823447553", "name": "西安大明宫", "extend_code": { "comm_shop_id": "2251bac0e03e4995962ae58691eda811", "ex_code": "20296", "alipay_id": "2015061200077000000000191257", "us_id": "43532", "comm_code": "301003400000074", "upcard_terminal": "02990374", "upcard_mer_id": "102290058122670", "ex_id": "20036", "ex_cost_center_code": "1200043532", "dcore_store_appid": "s20170823000005255" } }, { "_id": "3850146086857474049", "name": "上海周浦万达店", "extend_code": { "comm_shop_id": "616b35dd0b0a42ed8d37f214f0b12491", "ex_code": "20047", "alipay_id": "2015060900077000000000169206", "us_id": "42309", "comm_code": "301003400000199", "upcard_terminal": "02190470", "upcard_mer_id": "102210058120706", "ex_id": "249", "ex_cost_center_code": "1200042309", "dcore_store_appid": "s20170823000005242" } }, { "_id": "3850146245196644353", "name": "成都万象城店", "extend_code": { "comm_shop_id": "4cdaff88678e46e4b552ed4df69296b6", "ex_code": "20320", "alipay_id": "2015061200077000000000193002", "us_id": "43658", "comm_code": "301003400000155", "upcard_terminal": "02883677", "upcard_mer_id": "102280058123760", "ex_id": "20077", "ex_cost_center_code": "1200043658", "dcore_store_appid": "s20170823000005272" } }, { "_id": "3850146171293007873", "name": "开封新玛特", "extend_code": { "comm_shop_id": "1112148ffae24cd7a4a010309d4da074", "ex_code": "20201", "alipay_id": "2015061100077000000000192959", "us_id": "42930", "comm_code": "301003400000046", "upcard_terminal": "37801837", "upcard_mer_id": "102378058120171", "ex_id": "939", "ex_cost_center_code": "1200042930", "dcore_store_appid": "s20170823000005344" } }, { "_id": "3850146237667868673", "name": "南京江宁万达", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20305", "comm_shop_id": "5a02bed48ee54f0384def4339aec2b7b", "us_id": "43610", "alipay_id": "2015061000077000000000194481", "takeaway_eleme_id": '', "upcard_terminal": "02593530", "comm_code": "301003400000183", "upcard_mer_id": "102250058122030", "ex_id": "20047", "ex_cost_center_code": "1200043610", "dcore_store_appid": "s20170823000005270" } }, { "_id": "3850146357935341569", "name": "成都金楠天街店", "extend_code": { "comm_shop_id": "ce1ad091047b409b95ac8cb750e46eea", "ex_code": "20509", "alipay_id": "2015113000077000000006583511", "us_id": "44294", "comm_code": "301003400000378", "upcard_terminal": "02890172", "upcard_mer_id": "102280058124947", "ex_id": "20322", "ex_cost_center_code": "1200044294", "dcore_store_appid": "s20170823000005654" } }, { "_id": "3850146090930143233", "name": "昆明顺城店", "extend_code": { "comm_shop_id": "90b1e28d66c348d3b5f56123d29848a8", "ex_code": "20055", "alipay_id": "2015061200077000000000188796", "us_id": "42316", "comm_code": "301003400000270", "upcard_terminal": "87106454", "upcard_mer_id": "102871058120239", "ex_id": "773", "ex_cost_center_code": "1200042316", "dcore_store_appid": "s20170823000005494" } }, { "_id": "3850146239706300417", "name": "舟山银泰", "extend_code": { "comm_shop_id": "f312543ceb78416b98ce0313ea57837c", "ex_code": "20309", "alipay_id": "2015061000077000000000192914", "us_id": "43588", "comm_code": "301003400000439", "upcard_terminal": "58000374", "upcard_mer_id": "102580058120019", "ex_id": "20053", "ex_cost_center_code": "1200043588", "dcore_store_appid": "s20170823000005269" } }, { "_id": "3850146243653140481", "name": "启东店", "extend_code": { "comm_shop_id": "93572dc93fa54f5ea34d8ec59feb41f0", "ex_code": "20317", "alipay_id": "2015093000077000000004436861", "us_id": "43670", "comm_code": "301003400004593", "upcard_terminal": "51300824", "upcard_mer_id": "102513058120054", "ex_id": "20084", "ex_cost_center_code": "1200843670", "dcore_store_appid": "s20170823000005152" } }, { "_id": "3850146247662895105", "name": "郑州万象城店", "extend_code": { "comm_shop_id": "a8a98a5deac145f487ae3c7e74c0726f", "ex_code": "20325", "alipay_id": "2015061100077000000000194501", "us_id": "43761", "comm_code": "301003400000314", "upcard_terminal": "37110793", "upcard_mer_id": "102371058122276", "ex_id": "20105", "ex_cost_center_code": "1200043761", "dcore_store_appid": "s20170823000005277" } }, { "_id": "3850146238670307329", "name": "广州中华广场", "extend_code": { "comm_shop_id": "e6612273f9f14ba3a8f95337590453b4", "ex_code": "20307", "alipay_id": "2015061200077000000000191223", "us_id": "43638", "comm_code": "301003400000416", "upcard_terminal": "02081956", "upcard_mer_id": "102200058120371", "ex_id": "99777", "ex_cost_center_code": "1200043638", "dcore_store_appid": "s20170823000005380" } }, { "_id": "3850146306223767553", "name": "厦门翔安汇景", "extend_code": { "comm_shop_id": "c8791ca9b1a74c2eba6f15d9365f87a1", "ex_code": "20427", "alipay_id": "2015061200077000000000192992", "us_id": "44014", "comm_code": "301003400000363", "upcard_terminal": "59204820", "upcard_mer_id": "102592058120542", "ex_id": "20214", "ex_cost_center_code": "1200044014", "dcore_store_appid": "s20170823000005601" } }, { "_id": "3850146174447124481", "name": "西安曲江银泰", "extend_code": { "comm_shop_id": "fa6b27df58f14ceb85b2df548940aeef", "ex_code": "20207", "alipay_id": "2015061200077000000000194561", "us_id": "42901", "comm_code": "301003400000450", "upcard_terminal": "02903674", "upcard_mer_id": "102290058122463", "ex_id": "964", "ex_cost_center_code": "1200042901", "dcore_store_appid": "s20170823000005557" } }, { "_id": "3850146287915630593", "name": "南京文鼎广场", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20400", "comm_shop_id": "81eec69d92a54c27a2124480bf56cc03", "us_id": "43880", "alipay_id": "2015061100077000000000188750", "takeaway_eleme_id": '', "upcard_terminal": "02594648", "comm_code": "301003400000246", "upcard_mer_id": "102250058122399", "ex_id": "20149", "ex_cost_center_code": "1200043880", "dcore_store_appid": "s20170823000005285" } }, { "_id": "3850146127424782337", "name": "福州金融街万达店", "extend_code": { "comm_shop_id": "eb31692ddfb44e039bba30177c0b2601", "ex_code": "20125", "alipay_id": "2015061200077000000000188791", "us_id": "42638", "comm_code": "301003400000424", "upcard_terminal": "59106682", "upcard_mer_id": "102591058120180", "ex_id": "855", "ex_cost_center_code": "1200042638", "dcore_store_appid": "s20170823000005518" } }, { "_id": "3850146147112845313", "name": "苏州绿宝广场", "extend_code": { "comm_shop_id": "226d608a44334afaa55fd8cfdd31192c", "ex_code": "20162", "alipay_id": "2015061000077000000000182815", "us_id": "42759", "comm_code": "301003400000076", "upcard_terminal": "51211245", "upcard_mer_id": "102512058120519", "ex_id": "511", "ex_cost_center_code": "1200042759", "dcore_store_appid": "s20170823000005225" } }, { "_id": "3850146294953672705", "name": "九江九方店", "extend_code": { "comm_shop_id": "998a014478de481c807243be4bceaa4d", "ex_code": "20414", "alipay_id": "2015061000077000000000191165", "us_id": "44025", "comm_code": "301003400000282", "upcard_terminal": "79200395", "upcard_mer_id": "102792058120133", "ex_id": "20225", "ex_cost_center_code": "1200044025", "dcore_store_appid": "s20170823000005605" } }, { "_id": "3850146318802485249", "name": "眉山万景国际", "extend_code": { "comm_shop_id": "279a374a3afe4c37bea14110245b2683", "ex_code": "20448", "alipay_id": "2015061200077000000000191238", "us_id": "44094", "comm_code": "301003400000087", "upcard_terminal": "83390005", "upcard_mer_id": "102833058120016", "ex_id": "20247", "ex_cost_center_code": "1200044094", "dcore_store_appid": "s20170823000005303" } }, { "_id": "3850146155870552065", "name": "银川万达店", "extend_code": { "comm_shop_id": "fb16041eb666409e87aeab2e6395b2ff", "ex_code": "20179", "alipay_id": "2015061200077000000000182893", "us_id": "42829", "comm_code": "301003400000452", "upcard_terminal": "95100475", "upcard_mer_id": "102951058120212", "ex_id": "476", "ex_cost_center_code": "1200042829", "dcore_store_appid": "s20170823000005542" } }, { "_id": "3850146323466551297", "name": "洛阳王府井达玛格利", "extend_code": { "comm_shop_id": "b31fea3c11744f5691e7a10532c6e421", "ex_code": "20456", "alipay_id": "2015093000077000000004529780", "us_id": "44087", "comm_code": "301003400000326", "upcard_terminal": "37922540", "upcard_mer_id": "102379058120420", "ex_id": "", "ex_cost_center_code": "1200044087", "dcore_store_appid": "s20170823000005615" } }, { "_id": "3850146325832138753", "name": "兰州北京华联店", "extend_code": { "comm_shop_id": "e997cec00ccd4f2eaf824e9ecbcb7343", "ex_code": "20460", "alipay_id": "2015093000077000000004456914", "us_id": "44177", "comm_code": "301003400000418", "upcard_terminal": "93101009", "upcard_mer_id": "102931058120185", "ex_id": "20263", "ex_cost_center_code": "1200044177", "dcore_store_appid": "s20170823000005307" } }, { "_id": "3850146168688345089", "name": "杭州南宋御街", "extend_code": { "comm_shop_id": "fd05a62bf76748e9b47c6bcae45fac5a", "ex_code": "20196", "alipay_id": "2015060900077000000000166168", "us_id": "42881", "comm_code": "301003400000456", "upcard_terminal": "57103817", "upcard_mer_id": "102571058120465", "ex_id": "408", "ex_cost_center_code": "1200042881", "dcore_store_appid": "s20170823000005231" } }, { "_id": "3850146336464699393", "name": "安阳万达店", "extend_code": { "comm_shop_id": "36f0331f19194d4db3a8bfd2a591b671", "ex_code": "20471", "alipay_id": "2015093000077000000004454239", "us_id": "44190", "comm_code": "301003400000117", "upcard_terminal": "37202987", "upcard_mer_id": "102372058121256", "ex_id": "20269", "ex_cost_center_code": "1200044190", "dcore_store_appid": "s20170823000005629" } }, { "_id": "3850146197335441409", "name": "南通文峰", "extend_code": { "comm_shop_id": "61da7f1f75ba49229fe304f5f03f82a0", "ex_code": "20243", "alipay_id": "2018041900077000000048255677", "us_id": "43128", "comm_code": "301003400000200", "upcard_terminal": "51300175", "upcard_mer_id": "102513058120041", "ex_id": "568", "ex_cost_center_code": "1200043128", "dcore_store_appid": "s20170823000005355" } }, { "_id": "3850146341170708481", "name": "南京万谷慧", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20479", "comm_shop_id": "ff0a48ea50234da1821aa80c8d6d6d3f", "us_id": "44058", "alipay_id": "2015093000077000000004387800", "takeaway_eleme_id": '', "upcard_terminal": "02595909", "comm_code": "301003400000462", "upcard_mer_id": "102250058122640", "ex_id": "20227", "ex_cost_center_code": "1200044058", "dcore_store_appid": "s20170823000005301" } }, { "_id": "3854097531449376769", "name": "苏州吴江万宝财富广场店", "extend_code": { "comm_shop_id": "b96aeb583e474406bbc759f0c3a4b826", "alipay_id": "2016111500077000000019999539", "us_id": "44539", "comm_code": "301003400004631", "upcard_terminal": "51215575", "upcard_mer_id": "102512058123108", "ex_cost_center_code": "1200844539", "dcore_store_appid": "s20170823000005421" } }, { "_id": "3850146370501476353", "name": "临汾新安达圣店", "extend_code": { "comm_shop_id": "d9a0ff7c39554e67905f348e42d1ecb9", "ex_code": "20530", "alipay_id": "2016011100077000000014084490", "us_id": "44349", "comm_code": "301003400000399", "upcard_terminal": "35700738", "upcard_mer_id": "102357058120037", "ex_id": "20345", "ex_cost_center_code": "1200044349", "dcore_store_appid": "s20170823000005664" } }, { "_id": "3850146215287062529", "name": "广州天河城店", "extend_code": { "comm_shop_id": "f26367822d654e91ac2ab3f3eb4135f2", "ex_code": "20263", "alipay_id": "2015061200077000000000194532", "us_id": "43461", "comm_code": "301003400000437", "upcard_terminal": "02003961", "upcard_mer_id": "102200058120301", "ex_id": "20003", "ex_cost_center_code": "1200043461", "dcore_store_appid": "s20170823000005246" } }, { "_id": "3850146219288428545", "name": "无锡惠山万达店", "extend_code": { "comm_shop_id": "56262e121d96407495d814b39957a925", "ex_code": "20270", "alipay_id": "2015061000077000000000188725", "us_id": "43456", "comm_code": "301003400000174", "upcard_terminal": "51102375", "upcard_mer_id": "102510058120328", "ex_id": "660", "ex_cost_center_code": "1200043456", "dcore_store_appid": "s20170823000005370" } }, { "_id": "3850146380655886337", "name": "广州丽影店", "extend_code": { "comm_shop_id": "993dcadbad1841b3a166dfa20b3b65da", "ex_code": "20549", "alipay_id": "2016042500077000000015407363", "us_id": "44245", "comm_code": "301003400000280", "upcard_terminal": "02081919", "upcard_mer_id": "102200058120750", "ex_id": "20310", "ex_cost_center_code": "1200044245", "dcore_store_appid": "s20170823000005646" } }, { "_id": "3850146373567512577", "name": "许昌亨源通", "extend_code": { "comm_shop_id": "000c5c5e42374dcba16f37b8310336a0", "ex_code": "20536", "alipay_id": "2016011100077000000014214785", "us_id": "44374", "comm_code": "301003400000021", "upcard_terminal": "37401535", "upcard_mer_id": "102374058120057", "ex_id": "20371", "ex_cost_center_code": "1200044374", "dcore_store_appid": "s20170823000005672" } }, { "_id": "3850146279938064385", "name": "兰州城关万达店", "extend_code": { "comm_shop_id": "0fff0f7da55f4f9b907ae73fd3689a09", "ex_code": "20385", "alipay_id": "2015061200077000000000188821", "us_id": "43961", "comm_code": "301003400000045", "upcard_terminal": "93100949", "upcard_mer_id": "102931058120161", "ex_id": "20167", "ex_cost_center_code": "1200043961", "dcore_store_appid": "s20170929000006492" } }, { "_id": "3850146204251848705", "name": "深圳海雅缤纷城", "extend_code": { "comm_shop_id": "e9fc8fd3592e4b84baa2e45b986890e8", "ex_code": "20254", "alipay_id": "2015061200077000000000188787", "us_id": "43147", "comm_code": "301003400000420", "upcard_terminal": "75507872", "upcard_mer_id": "102755058121074", "ex_id": "490", "ex_cost_center_code": "1200043147", "dcore_store_appid": "s20170823000005356" } }, { "_id": "3850146282081353729", "name": "贵阳中大国际店", "extend_code": { "comm_shop_id": "18e8dcfcc3f84acfad4d50280be5daa3", "ex_code": "20389", "alipay_id": "2015061200077000000000182871", "us_id": "43829", "comm_code": "301003400000062", "upcard_terminal": "85101270", "upcard_mer_id": "102851058120379", "ex_id": "20195", "ex_cost_center_code": "1200043829", "dcore_store_appid": "s20170823000005407" } }, { "_id": "3850146229287649281", "name": "福州王府井", "extend_code": { "comm_shop_id": "4925b7280cd5452a969af748d0ff041a", "ex_code": "20289", "alipay_id": "2015061200077000000000191228", "us_id": "43127", "comm_code": "301003400000147", "upcard_terminal": "59106038", "upcard_mer_id": "102591058120294", "ex_id": "859", "ex_cost_center_code": "1200043127", "dcore_store_appid": "s20170929000006502" } }, { "_id": "3850146233641336833", "name": "南昌红谷滩世茂", "extend_code": { "comm_shop_id": "304616b2753c47519b55acd119c6c9b3", "ex_code": "20297", "alipay_id": "2015061000077000000000194473", "us_id": "43596", "comm_code": "301003400000102", "upcard_terminal": "79190459", "upcard_mer_id": "102791058120462", "ex_id": "20035", "ex_cost_center_code": "1200043596", "dcore_store_appid": "s20170823000005374" } }, { "_id": "3850146216599879681", "name": "宜兴万达", "extend_code": { "comm_shop_id": "5000003f62c046288aacf1cdcb2a70e9", "ex_code": "20265", "alipay_id": "2015061000077000000000194479", "us_id": "43422", "comm_code": "301003400000162", "upcard_terminal": "51000993", "upcard_mer_id": "102510058120318", "ex_id": "352", "ex_cost_center_code": "1200043422", "dcore_store_appid": "s20170823000005244" } }, { "_id": "3850146378927833089", "name": "许昌时代广场店", "extend_code": { "comm_shop_id": "c6eb88e979cd4b419c97ca9efd8734d0", "ex_code": "20546", "alipay_id": "2016011100077000000014137251", "us_id": "44344", "comm_code": "301003400000360", "upcard_terminal": "37401536", "upcard_mer_id": "102374058120058", "ex_id": "20346", "ex_cost_center_code": "1200044344", "dcore_store_appid": "s20170823000005661" } }, { "_id": "3850146296421679105", "name": "无锡宜家", "extend_code": { "us_id": "43960", "ex_id": "20203", "ex_cost_center_code": "1200043960", "ex_code": "20416" } }, { "_id": "3850146382409105409", "name": "鹤壁爱之城", "extend_code": { "comm_shop_id": "69d44594d4934897bb55e9ecbdfc3537", "ex_code": "20552", "alipay_id": "2016050900077000000015488024", "us_id": "44332", "comm_code": "301003400000208", "upcard_terminal": "39201377", "upcard_mer_id": "102392058120291", "ex_id": "20406", "ex_cost_center_code": "1200044332", "dcore_store_appid": "s20170823000005659" } }, { "_id": "3850146400234897409", "name": "西安奥特莱斯", "extend_code": { "comm_shop_id": "f86cb2e9b6fd4ec3af62ce7da6953279", "ex_code": "20597", "alipay_id": "2016111700077000000020165781", "us_id": "44283", "comm_code": "301003400000447", "upcard_terminal": "02991151", "upcard_mer_id": "102290058122944", "ex_id": "20344", "ex_cost_center_code": "1200044283", "dcore_store_appid": "s20170823000005652" } }, { "_id": "3850146225802182657", "name": "济源信尧店", "extend_code": { "comm_shop_id": "3315c02333c3479995b65fe6841433bf", "ex_code": "20282", "alipay_id": "2015061100077000000000192960", "us_id": "43551", "comm_code": "301003400000109", "upcard_terminal": "39102437", "upcard_mer_id": "102391058120149", "ex_id": "20026", "ex_cost_center_code": "1200043551", "dcore_store_appid": "s20170823000005261" } }, { "_id": "3850146259968983041", "name": "烟台大悦城", "extend_code": { "comm_shop_id": "184c5ca32a494bc184219ebfde2a35a6", "ex_code": "20349", "alipay_id": "2015061100077000000000188765", "us_id": "43825", "comm_code": "301003400000061", "upcard_terminal": "53530367", "upcard_mer_id": "102535058120116", "ex_id": "20145", "ex_cost_center_code": "1200043825", "dcore_store_appid": "s20170823000005404" } }, { "_id": "3850146253920796673", "name": "潍坊万达店", "extend_code": { "comm_shop_id": "b101829a3a224d159abe5b59b2c0befb", "ex_code": "20337", "alipay_id": "2015061100077000000000191213", "us_id": "43797", "comm_code": "301003400000321", "upcard_terminal": "53601856", "upcard_mer_id": "102536058120095", "ex_id": "20109", "ex_cost_center_code": "1200043797", "dcore_store_appid": "s20170823000005402" } }, { "_id": "3850146406572490753", "name": "济南高新万达", "extend_code": { "comm_shop_id": "08d405a788c94fd69524d97d0bcea960", "ex_code": "20592", "alipay_id": "2016080600077000000017911378", "us_id": "44503", "comm_code": "301003400000036", "upcard_terminal": "53101267", "upcard_mer_id": "102531058120531", "ex_id": "20419", "ex_cost_center_code": "1200044503", "dcore_store_appid": "s20170823000005679" } }, { "_id": "3850146239190401025", "name": "武汉奥山世纪城", "extend_code": { "comm_shop_id": "4c80f0cad1ae408dbac95071c2fa384f", "ex_code": "20308", "alipay_id": "2015061200077000000000191256", "us_id": "43578", "comm_code": "301003400000154", "upcard_terminal": "02722801", "upcard_mer_id": "102270058124237", "ex_id": "20034", "ex_cost_center_code": "1200043578", "dcore_store_appid": "s20170823000005264" } }, { "_id": "3850146263169236993", "name": "扬州时代广场店", "extend_code": { "comm_shop_id": "f2a9e15ebcca4366a9def358373af2c1", "ex_code": "20355", "alipay_id": "2015061100077000000000192956", "us_id": "43735", "comm_code": "301003400000438", "upcard_terminal": "51400315", "upcard_mer_id": "102514058120151", "ex_id": "20153", "ex_cost_center_code": "1200043735", "dcore_store_appid": "s20170823000005391" } }, { "_id": "3850146244726882305", "name": "郑州西元", "extend_code": { "comm_shop_id": "3d5db88e96bc477cab8193246c5e7358", "ex_code": "20319", "alipay_id": "2015061100077000000000188760", "us_id": "43677", "comm_code": "301003400000126", "upcard_terminal": "37110792", "upcard_mer_id": "102371058122258", "ex_id": "20081", "ex_cost_center_code": "1200043677", "dcore_store_appid": "s20170823000005274" } }, { "_id": "3850146254931623937", "name": "松江万达", "extend_code": { "comm_shop_id": "c4d7dd2ac8f7411b90cfbd91001cd3c6", "ex_code": "20339", "alipay_id": "2015060900077000000000178455", "us_id": "43781", "comm_code": "301003400000352", "upcard_terminal": "02190187", "upcard_mer_id": "102210058125837", "ex_id": "20103", "ex_cost_center_code": "1200043781", "dcore_store_appid": "s20170823000005398" } }, { "_id": "3850146266717618177", "name": "常州武进万达", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20361", "comm_shop_id": "44b9427f30eb40d59999e0e9358bf3c3", "us_id": "43882", "alipay_id": "2015061100077000000000182829", "takeaway_eleme_id": '', "upcard_terminal": "51900658", "comm_code": "301003400000140", "upcard_mer_id": "102519058120079", "ex_id": "20151", "ex_cost_center_code": "1200043882", "dcore_store_appid": "s20170823000005415" } }, { "_id": "3850146261747367937", "name": "济宁太白路万达店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20352", "comm_shop_id": "802f1b3305b04eefbec71e95785bfeaa", "us_id": "43827", "alipay_id": "2015061100077000000000182843", "takeaway_eleme_id": '', "upcard_terminal": "53700799", "comm_code": "301003400000244", "upcard_mer_id": "102537058120039", "ex_id": "20129", "ex_cost_center_code": "1200043827", "dcore_store_appid": "s20170823000005405" } }, { "_id": "3850146264356225025", "name": "金华万达店", "extend_code": { "comm_shop_id": "7f71b1e07f3f42cf843ef31f8274908a", "ex_code": "20357", "alipay_id": "2015061000077000000000182802", "us_id": "43835", "comm_code": "301003400000243", "upcard_terminal": "57990014", "upcard_mer_id": "102579058120128", "ex_id": "20127", "ex_cost_center_code": "1200043835", "dcore_store_appid": "s20170823000005283" } }, { "_id": "3850146310455820289", "name": "赣州九方店", "extend_code": { "comm_shop_id": "422bb26511644408a57c8dbe9856ccc4", "ex_code": "20432", "alipay_id": "2015061000077000000000188722", "us_id": "44026", "comm_code": "301003400000137", "upcard_terminal": "79700565", "upcard_mer_id": "102797058120354", "ex_id": "20240", "ex_cost_center_code": "1200044026", "dcore_store_appid": "s20170823000005606" } }, { "_id": "3850146286959329281", "name": "荆州人信汇店", "extend_code": { "comm_shop_id": "7c11f737e90b4b20b1564427113ec3bc", "ex_code": "20398", "alipay_id": "2015061200077000000000191247", "us_id": "43994", "comm_code": "301003400000236", "upcard_terminal": "71600161", "upcard_mer_id": "102716058120042", "ex_id": "20201", "ex_cost_center_code": "1200043994", "dcore_store_appid": "s20170823000005595" } }, { "_id": "3850146296937578497", "name": "郑州瀚海北金店", "extend_code": { "comm_shop_id": "e4c661d5e3174ce3883615473389ad9d", "ex_code": "20417", "alipay_id": "2015061100077000000000191204", "us_id": "43957", "comm_code": "301003400000414", "upcard_terminal": "37110720", "upcard_mer_id": "102371058122384", "ex_id": "20218", "ex_cost_center_code": "1200043957", "dcore_store_appid": "s20170823000005292" } }, { "_id": "3850146314616569857", "name": "张江长泰广场", "extend_code": { "comm_shop_id": "9768851747024e938fa5c78aee62c817", "ex_code": "20440", "alipay_id": "2015060900077000000000166156", "us_id": "43952", "comm_code": "301003400000277", "upcard_terminal": "02193305", "upcard_mer_id": "102210058126458", "ex_id": "20243", "ex_cost_center_code": "1200043952", "dcore_store_appid": "s20170823000005291" } }, { "_id": "3850146299944894465", "name": "盐城宝龙店", "extend_code": { "us_id": "43996", "ex_id": "20219", "ex_cost_center_code": "1200043996", "ex_code": "20420" } }, { "_id": "3850146315753226241", "name": "南宁会展航洋城", "extend_code": { "comm_shop_id": "467a67805b8c4dfba73d0eb13f665208", "ex_code": "20442", "alipay_id": "2016011100077000000014150644", "us_id": "44023", "comm_code": "301003400000142", "upcard_terminal": "77103788", "upcard_mer_id": "102771058121963", "ex_id": "20246", "ex_cost_center_code": "1200044023", "dcore_store_appid": "s20170823000005604" } }, { "_id": "3850146292453867521", "name": "昆明红星爱琴海", "extend_code": { "comm_shop_id": "ebedf8527a0d4a04a5074f3c07c7e87b", "ex_code": "20409", "alipay_id": "2015061200077000000000194538", "us_id": "43990", "comm_code": "301003400000427", "upcard_terminal": "87111957", "upcard_mer_id": "102871058126647", "ex_id": "", "ex_cost_center_code": "1200043990", "dcore_store_appid": "s20170823000005294" } }, { "_id": "3850146300951527425", "name": "杭州中大银泰店", "extend_code": { "us_id": "43063", "ex_id": "20200", "ex_cost_center_code": "1200043063", "ex_code": "20421" } }, { "_id": "3850146308983619585", "name": "九江联盛店", "extend_code": { "us_id": "43998", "ex_id": "20230", "ex_cost_center_code": "1200043998", "ex_code": "20429" } }, { "_id": "3850146302448893953", "name": "丽水万地店", "extend_code": { "comm_shop_id": "01c26919641a41b0972adac069f16f1a", "ex_code": "20423", "alipay_id": "2015061000077000000000192916", "us_id": "44016", "comm_code": "301003400000025", "upcard_terminal": "57800239", "upcard_mer_id": "102578058120009", "ex_id": "20220", "ex_cost_center_code": "1200044016", "dcore_store_appid": "s20170823000005298" } }, { "_id": "3850146310954942465", "name": "南通圆融店", "extend_code": { "comm_shop_id": "65617c4cfca348d49bdec904b12ae9e7", "ex_code": "20433", "alipay_id": "2015093000077000000004515139", "us_id": "43956", "comm_code": "301003400004544", "upcard_terminal": "51300187", "upcard_mer_id": "102513058120065", "ex_id": "20193", "ex_cost_center_code": "1200843956", "dcore_store_appid": "s20170823000005160" } }, { "_id": "3863190461975887873", "name": "亳州万达广场加盟店", "extend_code": { "comm_shop_id": "e313c53127b149c4be5582701b70db7a", "alipay_id": "2016111700077000000020149009", "us_id": "44568", "comm_code": "301003400004668", "upcard_terminal": "55801456", "upcard_mer_id": "102558058120429", "ex_id": "20437", "ex_cost_center_code": "1200844568", "dcore_store_appid": "s20170823000005425" } }, { "_id": "3850146313572188161", "name": "济南领秀城", "extend_code": { "comm_shop_id": "014338012d9a4f8482115449b207bc9d", "ex_code": "20438", "alipay_id": "2015061100077000000000191212", "us_id": "44057", "comm_code": "301003400000023", "upcard_terminal": "53101187", "upcard_mer_id": "102531058120516", "ex_id": "", "ex_cost_center_code": "1200044057", "dcore_store_appid": "s20170823000005610" } }, { "_id": "3850146342785515521", "name": "马鞍山金鹰天地", "extend_code": { "comm_shop_id": "fd8f622157b54bc3adef6a13bc2c4e6a", "ex_code": "20482", "alipay_id": "2015093000077000000004503888", "us_id": "44233", "comm_code": "301003400000457", "upcard_terminal": "55500393", "upcard_mer_id": "102555058120069", "ex_id": "20293", "ex_cost_center_code": "1200044233", "dcore_store_appid": "s20170823000005312" } }, { "_id": "3850146311458258945", "name": "桂林万福广场", "extend_code": { "comm_shop_id": "5b60ec9e2b1f47879fa44151c80f8c3f", "ex_code": "20434", "alipay_id": "2015061200077000000000188805", "us_id": "44055", "comm_code": "301003400000187", "upcard_terminal": "77300711", "upcard_mer_id": "102773058120438", "ex_id": "", "ex_cost_center_code": "1200044055", "dcore_store_appid": "s20170823000005609" } }, { "_id": "3850146317762297857", "name": "岳阳天虹店", "extend_code": { "comm_shop_id": "d2c1291e0a214aa88cb8c7b523fadb9e", "ex_code": "20446", "alipay_id": "2015093000077000000004488628", "us_id": "43824", "comm_code": "301003400000388", "upcard_terminal": "73000531", "upcard_mer_id": "102730058120035", "ex_id": "20250", "ex_cost_center_code": "1200043824", "dcore_store_appid": "s20170823000005403" } }, { "_id": "3850146343993475073", "name": "杭州文一物美", "extend_code": { "comm_shop_id": "1c63d979184c493fa8a9067030cbbf1d", "ex_code": "20484", "alipay_id": "2015093000077000000004480416", "us_id": "44179", "comm_code": "301003400000066", "upcard_terminal": "57108821", "upcard_mer_id": "102571058122149", "ex_id": "20289", "ex_cost_center_code": "1200044179", "dcore_store_appid": "s20170823000005628" } }, { "_id": "3850146320459235329", "name": "青岛万象城", "extend_code": { "comm_shop_id": "5631366691c146869010fc5bdfd18e24", "ex_code": "20451", "alipay_id": "2015093000077000000004464583", "us_id": "44107", "comm_code": "301003400000175", "upcard_terminal": "53205105", "upcard_mer_id": "102532058121351", "ex_id": "20254", "ex_cost_center_code": "1200044107", "dcore_store_appid": "s20170823000005617" } }, { "_id": "3850146354420514817", "name": "苏州吴江吾悦加盟", "extend_code": { "comm_shop_id": "30f18deccc1c44dda3919ba6c5b19306", "ex_code": "20503", "alipay_id": "2015093000077000000004466436", "us_id": "44274", "comm_code": "301003400004496", "upcard_terminal": "51215129", "upcard_mer_id": "102512058122961", "ex_id": "20312", "ex_cost_center_code": "1200844274", "dcore_store_appid": "s20170823000005167" } }, { "_id": "3850146365283762177", "name": "渭南信达", "extend_code": { "comm_shop_id": "2c2b7958d8d241c5b4767ff93656d0cd", "ex_code": "20520", "alipay_id": "2016012100077000000014458612", "us_id": "44350", "comm_code": "301003400000093", "upcard_terminal": "91330023", "upcard_mer_id": "102913058120013", "ex_id": "20343", "ex_cost_center_code": "1200044350", "dcore_store_appid": "s20170823000005665" } }, { "_id": "3850146333826482177", "name": "长沙德思勤店", "extend_code": { "comm_shop_id": "a4d414ff82b044e3939c253e581a53ff", "ex_code": "20467", "alipay_id": "2015093000077000000004451342", "us_id": "44165", "comm_code": "301003400000305", "upcard_terminal": "73109129", "upcard_mer_id": "102731058121544", "ex_id": "20272", "ex_cost_center_code": "1200044165", "dcore_store_appid": "s20170823000005626" } }, { "_id": "3850146381175980033", "name": "银川东方红广场店", "extend_code": { "comm_shop_id": "7e0e475195b741fe82b7ac43ba0c4e4b", "ex_code": "20550", "alipay_id": "2016111700077000000020171853", "us_id": "44433", "comm_code": "301003400000241", "upcard_terminal": "95100616", "upcard_mer_id": "102951058120244", "ex_id": "20402", "ex_cost_center_code": "1200044433", "dcore_store_appid": "s20170823000005675" } }, { "_id": "3850146362481967105", "name": "德州万达店", "extend_code": { "comm_shop_id": "1472fd60b6424ca48d4e3fb57511b939", "ex_code": "20515", "alipay_id": "2016011100077000000014153677", "us_id": "44228", "comm_code": "301003400000051", "upcard_terminal": "53400045", "upcard_mer_id": "102534058120010", "ex_id": "20319", "ex_cost_center_code": "1200044228", "dcore_store_appid": "s20170823000005636" } }, { "_id": "3850146328482938881", "name": "内江万达店", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20465", "comm_shop_id": "3700d853cc38457da21109e25bb8e980", "us_id": "44133", "alipay_id": "2015093000077000000004479169", "takeaway_eleme_id": '', "upcard_terminal": "83240047", "comm_code": "301003400000118", "upcard_mer_id": "102832058120004", "ex_id": "20266", "ex_cost_center_code": "1200044133", "dcore_store_appid": "s20170823000005621" } }, { "_id": "3850146346455531521", "name": "长清大学城店", "extend_code": { "comm_shop_id": "72dd4f2e97854becbdecf9421a822851", "ex_code": "20489", "alipay_id": "2015093000077000000004411685", "us_id": "44231", "comm_code": "301003400000229", "upcard_terminal": "53101194", "upcard_mer_id": "102531058120518", "ex_id": "20288", "ex_cost_center_code": "1200044231", "dcore_store_appid": "s20170823000005638" } }, { "_id": "3850146348980502529", "name": "桂林万达店", "extend_code": { "comm_shop_id": "17fc796a3b7947d6975d4d25d28db246", "ex_code": "20493", "alipay_id": "2015113000077000000006787409", "us_id": "44230", "comm_code": "301003400000058", "upcard_terminal": "77300780", "upcard_mer_id": "102773058120469", "ex_id": "20284", "ex_cost_center_code": "1200044230", "dcore_store_appid": "s20170823000005637" } }, { "_id": "3850146356035321857", "name": "安康高新万达店", "extend_code": { "comm_shop_id": "ccae2caf49a341909ca68a0365e30fc0", "ex_code": "20506", "alipay_id": "2016012100077000000014371362", "us_id": "44244", "comm_code": "301003400000371", "upcard_terminal": "91500056", "upcard_mer_id": "102915058120004", "ex_id": "20316", "ex_cost_center_code": "1200044244", "dcore_store_appid": "s20170929000006491" } }, { "_id": "3850146369440317441", "name": "丹阳吾悦", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20528", "comm_shop_id": "50d3079997d3468ab64bd4bb6af9cc7c", "us_id": "44362", "alipay_id": "2016011200077000000014111817", "takeaway_eleme_id": '', "upcard_terminal": "51103301", "comm_code": "301003400000164", "upcard_mer_id": "102511058121182", "ex_id": "20334", "ex_cost_center_code": "1200044362", "dcore_store_appid": "s20170823000005666" } }, { "_id": "3850146383977775105", "name": "西宁力盟店", "extend_code": { "comm_shop_id": "eb8f67a541ee4ad78938efba440f0636", "ex_code": "20555", "alipay_id": "2016031800077000000015094619", "us_id": "44371", "comm_code": "301003400000425", "upcard_terminal": "97100382", "upcard_mer_id": "102971058120232", "ex_id": "20403", "ex_cost_center_code": "1200044371", "dcore_store_appid": "s20170823000005324" } }, { "_id": "3869271134012702721", "name": "常德万达广场店", "extend_code": { "comm_shop_id": "dbdd13a644bf41eea38f3bf05f65cf9d", "ex_code": "20625", "alipay_id": "2016110200077000000019662896", "us_id": "44556", "comm_code": "301003400000404", "upcard_terminal": "73601475", "upcard_mer_id": "102736058120031", "ex_id": "20454", "ex_cost_center_code": "1200044556", "dcore_store_appid": "s20170823000005684" } }, { "_id": "3850146363031420929", "name": "常州九洲新世界", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20516", "comm_shop_id": "beb5b08035814e66a859377e2c7618be", "us_id": "44271", "alipay_id": "2016011200077000000014263932", "takeaway_eleme_id": '', "upcard_terminal": "51900921", "comm_code": "301003400004636", "upcard_mer_id": "102519058120140", "ex_id": "20333", "ex_cost_center_code": "1200844271", "dcore_store_appid": "s20170823000005166" } }, { "_id": "3850146367368331265", "name": "富阳玉长城", "extend_code": { "comm_shop_id": "7c590955193341439c1dc4736f465ddd", "ex_code": "20524", "alipay_id": "2016031800077000000015036324", "us_id": "44347", "comm_code": "301003400000238", "upcard_terminal": "57109443", "upcard_mer_id": "102571058122427", "ex_id": "20348", "ex_cost_center_code": "1200044347", "dcore_store_appid": "s20170823000005663" } }, { "_id": "3850146411635015681", "name": "南昌万达茂店", "extend_code": { "comm_shop_id": "b15f4c0eff53445799966ca0edbce0a5", "ex_code": "20610", "alipay_id": "2016111600077000000019990441", "us_id": "44495", "comm_code": "301003400000325", "upcard_terminal": "79190465", "upcard_mer_id": "102791058120614", "ex_id": "", "ex_cost_center_code": "1200044495", "dcore_store_appid": "s20170823000005678" } }, { "_id": "3873324792933253121", "name": "邳州新苏", "extend_code": { "comm_shop_id": "a7b8056287614209a7e7a37b31744274", "ex_code": "20620", "alipay_id": "2016111700077000000019992933", "us_id": "44583", "comm_code": "301003400004615", "upcard_terminal": "51600877", "upcard_mer_id": "102516058120230", "ex_id": "20459", "ex_cost_center_code": "1200844583", "dcore_store_appid": "s20170823000005429" } }, { "_id": "3873587551059050497", "name": "杭州运河上街", "extend_code": { "comm_shop_id": "96f24e96ed4b4e708b0686bdf85dd6f1", "ex_code": "20627", "alipay_id": "2016111400077000000019961039", "us_id": "44584", "comm_code": "301003400004596", "upcard_terminal": "57109980", "upcard_mer_id": "102571058122507", "ex_id": "20460", "ex_cost_center_code": "1200844584", "dcore_store_appid": "s20170823000005180" } }, { "_id": "3875522205441851393", "name": "合肥瑶海万达店", "extend_code": { "comm_shop_id": "75146db201ac4710bcc8a7c35ab6a73e", "ex_code": "20619", "alipay_id": "2016111500077000000020025227", "us_id": "44585", "comm_code": "301003400004555", "upcard_terminal": "55129620", "upcard_mer_id": "102551058123672", "ex_id": "20462", "ex_cost_center_code": "1200844585", "dcore_store_appid": "s20170823000005430" } }, { "_id": "3876153153984397313", "name": "三门峡万达", "extend_code": { "comm_shop_id": "4002e8c31a2e4731bcedd1f8b0855b00", "ex_code": "20632", "alipay_id": "2016111600077000000020014296", "us_id": "44601", "comm_code": "301003400000134", "upcard_terminal": "39801114", "upcard_mer_id": "102398058120016", "ex_id": "20464", "ex_cost_center_code": "1200044601", "dcore_store_appid": "s20170823000005330" } }, { "_id": "3876159232373948417", "name": "合肥万达茂", "extend_code": { "comm_shop_id": "e7f8488cf20841088d4e5402f7667c36", "ex_code": "20583", "alipay_id": "2016112100077000000020315788", "us_id": "44575", "comm_code": "301003400004673", "upcard_terminal": "55129615", "upcard_mer_id": "102551058123669", "ex_id": "20450", "ex_cost_center_code": "1200844575", "dcore_store_appid": "s20170823000005178" } }, { "_id": "3878042887929200641", "name": "徐州铜山万达", "extend_code": { "comm_shop_id": "41024ba93e694f88aced25f862c4303a", "ex_code": "20629", "alipay_id": "2016111400077000000019938321", "us_id": "44607", "comm_code": "301003400004512", "upcard_terminal": "51600880", "upcard_mer_id": "102516058120232", "ex_id": "20468", "ex_cost_center_code": "1200844607", "dcore_store_appid": "s20170823000005433" } }, { "_id": "3878414640677388289", "name": "宁海西子国际", "extend_code": { "comm_shop_id": "ed126009e0ce44c1b23ae9500ce728e8", "ex_code": "20622", "alipay_id": "2016111500077000000019990160", "us_id": "44579", "comm_code": "301003400004677", "upcard_terminal": "57403372", "upcard_mer_id": "102574058120527", "ex_id": "20451", "ex_cost_center_code": "1200844579", "dcore_store_appid": "s20170823000005427" } }, { "_id": "3883396195845931009", "name": "蚌埠银泰城", "extend_code": { "comm_shop_id": "14ad34c86bd745b19bf8b6b9e7972c9c", "ex_code": "20638", "alipay_id": "2017120400077000000046754136", "us_id": "44605", "comm_code": "301003400004466", "upcard_terminal": "55202607", "upcard_mer_id": "102552058120097", "ex_cost_center_code": "1200844605", "dcore_store_appid": "s20170823000005181" } }, { "_id": "3891058106678902785", "name": "连云港万达广场店", "extend_code": { "comm_shop_id": "c1769bacba45497ca84d7db0bb3752b1", "ex_code": "20635", "alipay_id": "2017120400077000000046744552", "us_id": "44593", "comm_code": "301003400004640", "upcard_terminal": "51800662", "upcard_mer_id": "102518058120066", "ex_cost_center_code": "1200844593", "dcore_store_appid": "s20170823000005439" } }, { "_id": "3891708784841588737", "name": "郑州二七万达", "extend_code": { "comm_shop_id": "514a6cd3d22f436d8af6fbe29b24fc6c", "ex_code": "20637", "alipay_id": "2018040400077000000048193647", "us_id": "44628", "comm_code": "301003400000165", "upcard_terminal": "37112065", "upcard_mer_id": "102371058122461", "ex_cost_center_code": "1200044628", "dcore_store_appid": "s20170823000005688" } }, { "_id": "3893230750010441729", "name": "成都青羊万达", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20639", "comm_shop_id": "fbe9f78d8cf4408b9cd28f2baf957a02", "us_id": "44632", "alipay_id": "2017120400077000000046745555", "takeaway_eleme_id": '', "upcard_terminal": "02895967", "comm_code": "301003400000453", "upcard_mer_id": "102280058125263", "ex_cost_center_code": "1200044632", "dcore_store_appid": "s20170823000005690" } }, { "_id": "3893273023725174785", "name": "郑州惠济万达", "extend_code": { "takeaway_honeymoon_id": '', "ex_code": "20634", "comm_shop_id": "6f2d53b800ce4432bbb6fbb374f00e90", "us_id": "44602", "alipay_id": "2018040400077000000048193649", "takeaway_eleme_id": '', "upcard_terminal": "37112066", "comm_code": "301003400000219", "upcard_mer_id": "102371058122462", "ex_cost_center_code": "1200044602", "dcore_store_appid": "s20170823000005685" } }, { "_id": "3896474707003703297", "name": "杭州滨江宝龙", "extend_code": { "comm_shop_id": "dbbb683dd83a4fe98a637d8a4fba8617", "ex_code": "20641", "alipay_id": "2017120400077000000046699854", "us_id": "44701", "comm_code": "301003400004662", "upcard_terminal": "57110445", "upcard_mer_id": "102571058122527", "ex_cost_center_code": "1200844701", "dcore_store_appid": "s20170823000005183" } }, { "_id": "3896478014455676929", "name": "建德太平洋", "extend_code": { "comm_shop_id": "d87ad61122a84d208091d5fb8c9da435", "ex_code": "20640", "alipay_id": "2018040900077000000048270638", "us_id": "44699", "comm_code": "301003400004659", "upcard_terminal": "57110446", "upcard_mer_id": "102571058122528", "ex_cost_center_code": "1200844699", "dcore_store_appid": "s20170823000005436" } }, { "_id": "3896481459271106561", "name": "烟台开发区万达店", "extend_code": { "comm_shop_id": "db271312c32742b4bade2db57e048c44", "ex_code": "20642", "alipay_id": "2018041200077000000048267150", "us_id": "44629", "comm_code": "301003400000403", "upcard_terminal": "53530406", "upcard_mer_id": "102535058120167", "ex_cost_center_code": "1200044629", "dcore_store_appid": "s20170823000005331" } }, { "_id": "3898241725730127873", "name": "宿州万达", "extend_code": { "comm_shop_id": "546463e178434941978b5f889e359418", "ex_code": "20643", "alipay_id": "2017120400077000000046765144", "us_id": "44705", "comm_code": "301003400004528", "upcard_terminal": "55740026", "upcard_mer_id": "102557058120095", "ex_cost_center_code": "1200844705", "dcore_store_appid": "s20170823000005438" } }, { "_id": "3901599326224252929", "name": "三明万达店", "extend_code": { "comm_shop_id": "55e5d6265c774f6bb4115facf615f0dd", "ex_code": "20646", "alipay_id": "2018040900077000000048249322", "us_id": "44630", "comm_code": "301003400000173", "upcard_terminal": "59800139", "upcard_mer_id": "102598058120041", "ex_cost_center_code": "1200044630", "dcore_store_appid": "s20170823000005689" } }, { "_id": "3902216432686989313", "name": "滨州万达", "extend_code": { "comm_shop_id": "6c6dbc06acab49048bc20aa91aedfc05", "ex_code": "20647", "alipay_id": "2018040900077000000048281145", "us_id": "44633", "comm_code": "301003400000214", "upcard_terminal": "54300018", "upcard_mer_id": "102543058120085", "ex_cost_center_code": "1200044633", "dcore_store_appid": "s20170823000005332" } }, { "_id": "3904032209438244865", "name": "象山博浪太平洋店", "extend_code": { "comm_shop_id": "208be415155b4c70927e7e02fa82c967", "ex_code": "20648", "alipay_id": "2017120400077000000046770747", "us_id": "44700", "comm_code": "301003400004482", "upcard_terminal": "57403414", "upcard_mer_id": "102574058120535", "ex_cost_center_code": "1200844700", "dcore_store_appid": "s20170823000005437" } }, { "_id": "3904821037111443457", "name": "湖州万达", "extend_code": { "comm_shop_id": "b3647b4840a94e849e1b6f5b5193ba38", "ex_code": "20649", "alipay_id": "2017120400077000000046768872", "us_id": "44720", "comm_code": "301003400004626", "upcard_terminal": "57297181", "upcard_mer_id": "102572058120068", "ex_cost_center_code": "1200844720", "dcore_store_appid": "s20170823000005184" } }, { "_id": "3906632910475624449", "name": "六安万达", "extend_code": { "comm_shop_id": "208fc01a65014d6dae44edee75b6e714", "ex_code": "20650", "alipay_id": "2018040900077000000048283968", "us_id": "44727", "comm_code": "301003400004483", "upcard_terminal": "56401490", "upcard_mer_id": "102564058120147", "ex_cost_center_code": "1200844727", "dcore_store_appid": "s20170823000005441" } }, { "_id": "3907309584703815681", "name": "嘉善万联城", "extend_code": { "comm_shop_id": "f2691169f6224907bcfae967a5370c2f", "ex_code": "20651", "alipay_id": "2017120400077000000046728533", "us_id": "44726", "comm_code": "301003400004681", "upcard_terminal": "57303460", "upcard_mer_id": "102573058120167", "ex_cost_center_code": "1200844726", "dcore_store_appid": "s20170823000005440" } }, { "_id": "3918904884010680321", "name": "盐城建军路金鹰店", "extend_code": { "comm_shop_id": "d31d4623d5de446fa2f673e6fd2ae1bd", "ex_code": "20653", "alipay_id": "2017120400077000000046768876", "us_id": "44770", "comm_code": "301003400004657", "upcard_terminal": "51500739", "upcard_mer_id": "102515058120461", "ex_cost_center_code": "1200844770", "dcore_store_appid": "s20170823000005443" } }, { "_id": "3935323620915888129", "name": "上海百脑汇中金", "extend_code": { "comm_shop_id": "73373740e3544eb08ad97506c6020f33", "alipay_id": "2017120100077000000046764861", "us_id": "44799", "comm_code": "301003400004553", "upcard_terminal": "02100360", "upcard_mer_id": "102210058127338", "ex_cost_center_code": "1200844799", "dcore_store_appid": "s20170823000005186" } }, { "_id": "3936702061001609217", "name": "合肥悦方", "extend_code": { "comm_shop_id": "111aaf6778874be6a6746d8344a1cfb5", "alipay_id": "2017120100077000000046705835", "us_id": "44800", "comm_code": "301003400004462", "upcard_terminal": "55108258", "upcard_mer_id": "102551058123725", "ex_cost_center_code": "1200844800", "dcore_store_appid": "s20170823000005445" } }, { "_id": "3939969521955577857", "name": "武汉佰港城店", "extend_code": { "comm_shop_id": "08abf1638f6643e0a65881661fc55604", "ex_code": "", "alipay_id": "2017120100077000000046707781", "us_id": "44804", "comm_code": "301003400000035", "upcard_terminal": "02708725", "upcard_mer_id": "102270058125346", "ex_cost_center_code": "1200044804", "dcore_store_appid": "s20170823000005693" } }, { "_id": "3949689889562189825", "name": "南通中南加盟店", "extend_code": { "comm_shop_id": "b72625ffd12b47f8b3ef693e0dac034f", "alipay_id": "2018040900077000000048286798", "us_id": "44818", "comm_code": "301003400004628", "upcard_terminal": "51300955", "upcard_mer_id": "102513058120211", "ex_cost_center_code": "1200844818", "dcore_store_appid": "s20170823000005448" } }, { "_id": "3953061342424817665", "name": "义乌之心", "extend_code": { "comm_shop_id": "1e959784c6c0427bb06f3845786fd8fd", "alipay_id": "2018040900077000000048275914", "us_id": "44817", "comm_code": "301003400004480", "upcard_terminal": "57990577", "upcard_mer_id": "102579058120236", "ex_cost_center_code": "1200844817", "dcore_store_appid": "s20170823000005465" } }, { "_id": "3957672566130307073", "name": "上海莲花国际", "extend_code": { "comm_shop_id": "bdcc7e0fba7c49d3ac110e8abc6dbe73", "alipay_id": "2017120100077000000046736390", "us_id": "44826", "comm_code": "301003400004635", "upcard_terminal": "02100302", "upcard_mer_id": "102210058127362", "ex_cost_center_code": "1200844826", "dcore_store_appid": "s20170823000005187" } }, { "_id": "3958032643133870081", "name": "滁州苏宁广场", "extend_code": { "comm_shop_id": "8f6fa896f4e24c5a9edc8c0668bbeb8b", "alipay_id": "2018040900077000000048275898", "us_id": "44824", "comm_code": "301003400004590", "upcard_terminal": "55000331", "upcard_mer_id": "102550058120071", "ex_cost_center_code": "1200844824", "dcore_store_appid": "s20170823000005449" } }, { "_id": "3966059407857238017", "name": "如皋文峰加盟店", "extend_code": { "comm_shop_id": "a5d7114096bb443ebf23cd73cf99d1c1", "alipay_id": "2017120400077000000046773987", "us_id": "44850", "comm_code": "301003400004612", "upcard_terminal": "51300962", "upcard_mer_id": "102513058120216", "ex_cost_center_code": "1200844850", "dcore_store_appid": "s20170823000005453" } }, { "_id": "3966093447387537409", "name": "枣庄万达", "extend_code": { "comm_shop_id": "a33d2d5687b248f88ce661e498c6ff65", "alipay_id": "2017120400077000000046728539", "us_id": "44864", "comm_code": "301003400004607", "upcard_terminal": "63200098", "upcard_mer_id": "102632058120025", "ex_cost_center_code": "1200844864", "dcore_store_appid": "s20170823000005457" } }, { "_id": "3966096594713075713", "name": "漯河大商新玛特", "extend_code": { "comm_shop_id": "7d1c25ae05d145d8bb4f4a572fa1d74e", "alipay_id": "2018040400077000000048200655", "us_id": "44862", "comm_code": "301003400004567", "upcard_terminal": "39501433", "upcard_mer_id": "102395089990085", "ex_cost_center_code": "1200844862", "dcore_store_appid": "s20170823000005455" } }, { "_id": "3966100462889066497", "name": "焦作万达", "extend_code": { "comm_shop_id": "77dd986b49d4437c95a0e24b27249f7e", "alipay_id": "2017120100077000000046751943", "us_id": "44861", "comm_code": "301003400004558", "upcard_terminal": "39102509", "upcard_mer_id": "102391089990186", "ex_cost_center_code": "1200844861", "dcore_store_appid": "s20170823000005190" } }, { "_id": "3968195667572068353", "name": "益阳万达广场店", "extend_code": { "comm_shop_id": "19da77983fca471bbc9cfec8b2c4d958", "alipay_id": "2017120400077000000046768863", "us_id": "44863", "comm_code": "301003400004472", "upcard_terminal": "73700870", "upcard_mer_id": "102737089990043", "ex_cost_center_code": "1200844863", "dcore_store_appid": "s20170823000005456" } }, { "_id": "3970708804825374721", "name": "兴化东方商厦", "extend_code": { "comm_shop_id": "8412ccbf8ad84f4199950bf9ee838a4f", "alipay_id": "2017120400077000000046770756", "us_id": "44825", "comm_code": "301003400004576", "upcard_terminal": "52300736", "upcard_mer_id": "102523058120111", "ex_id": "", "ex_cost_center_code": "1200844825", "dcore_store_appid": "s20170823000005451" } }, { "_id": "3970723154399453185", "name": "盐城万达广场", "extend_code": { "comm_shop_id": "5511192321874a8ca51fe3f0562dda01", "alipay_id": "2017120400077000000046745569", "us_id": "44856", "comm_code": "301003400004530", "upcard_terminal": "51500809", "upcard_mer_id": "102515058120472", "ex_cost_center_code": "1200844856", "dcore_store_appid": "s20170823000005454" } }, { "_id": "3974341319478169601", "name": "昆山万达店", "extend_code": { "comm_shop_id": "79bf41c5af684b2aadbfb0057d22cce3", "alipay_id": "2017120100077000000046775297", "us_id": "44868", "comm_code": "301003400004561", "upcard_terminal": "51215951", "upcard_mer_id": "102512058123161", "ex_cost_center_code": "1200844868", "dcore_store_appid": "s20170823000005459" } }, { "_id": "3977285180676460545", "name": "南京江宁金鹰(加盟)", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "aaad2a3622a14910b21458e16461817b", "us_id": "44869", "alipay_id": "2017120100077000000046723049", "comm_code": "301003400004617", "takeaway_eleme_id": '', "upcard_mer_id": "102250058123272", "ex_cost_center_code": "1200844869", "dcore_store_appid": "s20170823000005460", "upcard_terminal": "02598814" } }, { "_id": "3977287272995196929", "name": "常州新城吾悦(加盟店)", "extend_code": { "comm_shop_id": "2a0f3f99b9c049f2a3e8dd998f1c65ff", "alipay_id": "2018071000077000000059042277", "us_id": "44867", "comm_code": "301003400004488", "upcard_terminal": "51901161", "upcard_mer_id": "102519058120204", "ex_cost_center_code": "1200844867", "dcore_store_appid": "s20170823000005458" } }, { "_id": "3979829786309996545", "name": "常熟万达", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "6244df76e1cd4de9adf15c034baeb820", "us_id": "44875", "alipay_id": "2017120100077000000046723060", "comm_code": "301003400004541", "takeaway_eleme_id": '', "upcard_mer_id": "102520089990007", "ex_cost_center_code": "1200844875", "dcore_store_appid": "s20170823000005461", "upcard_terminal": "52000085" } }, { "_id": "3984873648719810561", "name": "常熟江南印象", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "3b73658c410846ae84e572e6f5c66aca", "us_id": "44886", "alipay_id": "2017120100077000000046721963", "comm_code": "301003400004505", "takeaway_eleme_id": '', "upcard_mer_id": "102512089993167", "ex_id": "", "ex_cost_center_code": "1200844886", "dcore_store_appid": "s20170929000006485", "upcard_terminal": "51215961" } }, { "_id": "3985236110106099713", "name": "周口万顺达", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "707acb78761f4ba08441fd9ce609c6b0", "us_id": "44896", "alipay_id": "2018040400077000000048176794", "comm_code": "301003400004550", "takeaway_eleme_id": '', "upcard_mer_id": "102394089990038", "ex_cost_center_code": "1200844896", "dcore_store_appid": "s20170823000005464", "upcard_terminal": "39401115" } }, { "_id": "3994699034354524161", "name": "南东食品一店", "extend_code": { "comm_shop_id": "816f7969939d424089e8b63cd479070f", "alipay_id": "2017120400077000000046723324", "us_id": "44914", "comm_code": "301003400004573", "upcard_terminal": "02100411", "upcard_mer_id": "102210058227491", "ex_cost_center_code": "1200844914", "dcore_store_appid": "s20170929000006481" } }, { "_id": "3994703758243516417", "name": "郑州乐尚生活广场", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "b9516e09407143c5a1e44e39e6fe66e2", "us_id": "44938", "alipay_id": "2018040900077000000048288285", "comm_code": "301003400004630", "takeaway_eleme_id": '', "upcard_mer_id": "102371058222730", "ex_cost_center_code": "1200844938", "dcore_store_appid": "s20170929000006501", "upcard_terminal": "37112486" } }, { "_id": "3995354263162851329", "name": "西安太白印象城", "extend_code": { "comm_shop_id": "5df937ed089b40678f8ce09b3ae0ebae", "alipay_id": "2017120400077000000046770741", "us_id": "44933", "comm_code": "301003400000195", "upcard_terminal": "02904311", "upcard_mer_id": "102290058223117", "ex_cost_center_code": "1200044933", "dcore_store_appid": "s20170929000006489" } }, { "_id": "3995730255083913217", "name": "东阳银泰", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "a2d59076155f486987639ce8f7be7247", "us_id": "44901", "alipay_id": "2017120400077000000046722217", "comm_code": "301003400004606", "takeaway_eleme_id": '', "upcard_mer_id": "102579089990249", "ex_cost_center_code": "1200844901", "dcore_store_appid": "s20170929000006488", "upcard_terminal": "57990603" } }, { "_id": "3997174071516418049", "name": "济宁运河城", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "e156237095a64288886b6152c823731f", "us_id": "44924", "alipay_id": "2017120600077000000046923728", "comm_code": "301003400004665", "takeaway_eleme_id": '', "upcard_mer_id": "102539089990304", "ex_cost_center_code": "1200844924", "dcore_store_appid": "s20170929000006496", "upcard_terminal": "53950776" } }, { "_id": "3997176235735457793", "name": "连云港利群店", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "851eaacfd20e4d8ba12744bb6184be6f", "us_id": "44935", "alipay_id": "2017120400077000000046750245", "comm_code": "301003400004577", "takeaway_eleme_id": '', "upcard_mer_id": "102518089990077", "ex_cost_center_code": "1200844935", "dcore_store_appid": "s20170929000006497", "upcard_terminal": "51800720" } }, { "_id": "3997560956944306177", "name": "香港名都", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "d9adc4bd46b04279bd7663741f72ca63", "us_id": "44926", "alipay_id": "2017120100077000000046777016", "comm_code": "301003400000400", "takeaway_eleme_id": '', "upcard_mer_id": "102210089997762", "ex_cost_center_code": "1200044926", "dcore_store_appid": "s20170929000006480", "upcard_terminal": "02105290" } }, { "_id": "3999773029309284353", "name": "无锡梅村南服务区", "extend_code": { "comm_shop_id": "1cc61da075bc44e6ab1f82f167084709", "alipay_id": "2017120400077000000046759054", "us_id": "44945", "comm_code": "301003400004477", "upcard_terminal": "51001731", "upcard_mer_id": "102510089992602", "ex_cost_center_code": "1200844945", "dcore_store_appid": "s20170928000006468" } }, { "_id": "3999774685956632577", "name": "无锡梅村北服务区", "extend_code": { "comm_shop_id": "a6f21e7b119a4f448cdba7106af51dac", "alipay_id": "2017120400077000000046759054", "us_id": "44947", "comm_code": "301003400004614", "upcard_terminal": "51001732", "upcard_mer_id": "102510089992603", "ex_cost_center_code": "1200844947", "dcore_store_appid": "s20170928000006470" } }, { "_id": "4001376863112306689", "name": "国融测试门店02", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "0905bf5cac37403695e02ed9197757ff", "pay100_terminal_id": "18097171", "us_id": "00002", "alipay_id": "2015060900077000000000176452", "takeaway_eleme_id": '', "pay100_merchant_no": "829005812003177", "comm_code": "301003400000348", "upcard_mer_id": "102210058126861", "pay100_access_token": "<KEY>", "dcore_store_appid": "s20160610000000406", "upcard_terminal": "02194635" } }, { "_id": "4002249564373131265", "name": "杭州龙湖天街店", "extend_code": { "takeaway_honeymoon_id": '', "comm_shop_id": "94ab09c76e234165820c6e16c4300a97", "us_id": "44939", "alipay_id": "2017120100077000000046739063", "comm_code": "301003400004595", "takeaway_eleme_id": '', "upcard_mer_id": "102571089992670", "ex_cost_center_code": "1200844939", "dcore_store_appid": "s20171018000006595", "upcard_terminal": "57111371" } }, { "_id": "4004830607795531777", "name": "衡阳万达", "extend_code": { "comm_shop_id": "5632ee0d5a6a4f07ba39cc3b2e88735b", "alipay_id": "2017120400077000000046738075", "us_id": "44975", "comm_code": "301003400004532", "upcard_terminal": "73401178", "upcard_mer_id": "102734089990075", "ex_cost_center_code": "1200844975", "dcore_store_appid": "s20171018000006603" } }, { "_id": "4005915785624084481", "name": "新乡胖东来", "extend_code": { "comm_shop_id": "0a74b0275a38460883dd55a5f5e530a2", "alipay_id": "2018040400077000000048215754", "us_id": "44912", "comm_code": "301003400004456", "upcard_terminal": "37301800", "upcard_mer_id": "102373089990129", "ex_cost_center_code": "1200844912", "dcore_store_appid": "s20171018000006605" } }, { "_id": "4007436278454431745", "name": "仪征北服务区", "extend_code": { "comm_shop_id": "926d0b5d2eff4f979393176ffe8cc447", "alipay_id": "2017120100077000000046775299", "us_id": "44957", "comm_code": "301003400004592", "upcard_terminal": "51401108", "upcard_mer_id": "102514089990290", "ex_cost_center_code": "1200844957", "dcore_store_appid": "s20170928000006467" } }, { "_id": "4007436814637395969", "name": "仪征南服务区", "extend_code": { "comm_shop_id": "8e98876b901a47bc97c2c71c2c984b6b", "alipay_id": "2017120100077000000046775299", "us_id": "44958", "comm_code": "301003400004588", "upcard_terminal": "51401109", "upcard_mer_id": "102514089990291", "ex_cost_center_code": "1200844958", "dcore_store_appid": "s20170928000006466" } }, { "_id": "4007676009175732225", "name": "重庆北站出发店", "extend_code": { "comm_shop_id": "bc6f6d06896a4f6b9554bbd58d1469b4", "alipay_id": "2018040900077000000048286799", "us_id": "44972", "comm_code": "301003400004632", "upcard_terminal": "02380235", "upcard_mer_id": "102230089992056", "ex_cost_center_code": "1200844972", "dcore_store_appid": "s20171020000006679" } }, { "_id": "4008482139026063361", "name": "合肥商之都", "extend_code": { "comm_shop_id": "37890bde536c4adcae5a787fb1532a2f", "alipay_id": "2017120100077000000046777006", "us_id": "44955", "comm_code": "301003400004503", "upcard_terminal": "55700255", "upcard_mer_id": "102557089990115", "ex_cost_center_code": "1200844955", "dcore_store_appid": "s20171018000006608" } }, { "_id": "4010288854749007873", "name": "合肥万象城", "extend_code": { "comm_shop_id": "4b4f2189f3224df4bf619cd811b9aec3", "alipay_id": "2017120300077000000046752172", "us_id": "44849", "comm_code": "301003400004519", "upcard_terminal": "55130567", "upcard_mer_id": "102551089993762", "ex_cost_center_code": "1200844849", "dcore_store_appid": "s20171020000006680" } }, { "_id": "4015293472954216449", "name": "铜陵万达广场", "extend_code": { "comm_shop_id": "85deba940f49433692989ade6b19681d", "alipay_id": "2017120300077000000046766873", "us_id": "44986", "comm_code": "301003400004579", "upcard_terminal": "56210142", "upcard_mer_id": "102562089990106", "ex_cost_center_code": "1200844986", "dcore_store_appid": "s20171020000006682" } }, { "_id": "4016018515533459457", "name": "西安高新万达", "extend_code": { "comm_shop_id": "15ca185291c9482baa1aa9310188ae3a", "ex_code": "", "alipay_id": "2017120300077000000046773913", "us_id": "44992", "comm_code": "301003400000052", "upcard_terminal": "02905015", "upcard_mer_id": "102290089993129", "ex_cost_center_code": "1200044992", "dcore_store_appid": "s20171020000006683" } }, { "_id": "4016456551866130433", "name": "泸州佳乐世纪城店", "extend_code": { "comm_shop_id": "1bd11d7ce61d45c99dcc399163836f78", "alipay_id": "2018040900077000000048259004", "us_id": "45009", "comm_code": "301003400004476", "upcard_terminal": "83000976", "upcard_mer_id": "102830089990201", "ex_cost_center_code": "1200845009", "dcore_store_appid": "s20171020000006686" } }, { "_id": "4022567895717613569", "name": "通州万达", "extend_code": { "comm_shop_id": "71c86122849a4674820c040cd0fc5c21", "ex_code": "", "alipay_id": "2018040900077000000048275899", "us_id": "45022", "comm_code": "301003400004551", "upcard_terminal": "51301218", "upcard_mer_id": "102513089990230", "ex_cost_center_code": "1200845022", "dcore_store_appid": "s20171102000006792" } }, { "_id": "4022985230646005761", "name": "苏州中心店", "extend_code": { "comm_shop_id": "0822659ab7b241afac9b3a2998f48071", "alipay_id": "2017120300077000000046750182", "us_id": "45001", "comm_code": "301003400004455", "upcard_terminal": "51216565", "upcard_mer_id": "102512089993186", "ex_cost_center_code": "1200845001", "dcore_store_appid": "s20171102000006794" } }, { "_id": "4024054442479214593", "name": "平顶山万达店", "extend_code": { "comm_shop_id": "78a5c52624534ed4a34c22f152496b1d", "alipay_id": "2018040900077000000048255945", "us_id": "45016", "comm_code": "301003400004560", "upcard_terminal": "37112760", "upcard_mer_id": "102371089992753", "ex_cost_center_code": "1200845016", "dcore_store_appid": "s20171114000006907" } }, { "_id": "4024083696136933377", "name": "郑州朗悦公园茂店", "extend_code": { "comm_shop_id": "037971e53a864ae59b348dff8290a5f2", "alipay_id": "2018040400077000000048185150", "us_id": "44990", "comm_code": "301003400004445", "upcard_terminal": "37112762", "upcard_mer_id": "102371089992755", "ex_cost_center_code": "1200844990", "dcore_store_appid": "s20171114000006909" } }, { "_id": "4027629077436919809", "name": "大丰美庐广场店", "extend_code": { "comm_shop_id": "c18178168c3a4076be27492ac6babf0f", "alipay_id": "2017120300077000000046740433", "us_id": "45007", "comm_code": "301003400004641", "upcard_terminal": "51501012", "upcard_mer_id": "102515089990476", "ex_cost_center_code": "1200845007", "dcore_store_appid": "s20171114000006910" } }, { "_id": "4028778360471429121", "name": "漕河泾测试店", "extend_code": { "us_id": "00001", "dcore_store_appid": "s20171116000006958", "ex_cost_center_code": "1200000001", "alipay_id": "2017120400077000000046740477" } }, { "_id": "4028800153556328449", "name": "上海肇嘉浜路店", "extend_code": { "comm_shop_id": "d544f97522c141b784b563bfd3218a33", "alipay_id": "2018040900077000000048255959", "us_id": "45036", "comm_code": "301003400000393", "upcard_terminal": "02110411", "upcard_mer_id": "102210089997915", "ex_cost_center_code": "1200045036", "dcore_store_appid": "s20171117000006961" } }, { "_id": "4029145940016906241", "name": "上海颛桥万达店", "extend_code": { "comm_shop_id": "527550bdda0c48808d22e218bfb541d4", "alipay_id": "2018041200077000000048287424", "us_id": "45048", "comm_code": "301003400004527", "upcard_terminal": "02110415", "upcard_mer_id": "102210089997917", "ex_cost_center_code": "1200845048", "dcore_store_appid": "s20171120000006973" } }, { "_id": "4030209818787983361", "name": "新乡万达店", "extend_code": { "comm_shop_id": "731eb48f3f6b4f28b282736a89af2d4b", "alipay_id": "2018041200077000000048287428", "us_id": "45044", "comm_code": "301003400004552", "upcard_terminal": "37301852", "upcard_mer_id": "102373089990132", "ex_cost_center_code": "1200845044", "dcore_store_appid": "s20171120000006974" } }, { "_id": "4030526770225795073", "name": "衢州万达店", "extend_code": { "comm_shop_id": "12d5f5b2f56549af874dab400b0166ff", "alipay_id": "2018040900077000000048286782", "us_id": "45046", "comm_code": "301003400004465", "upcard_terminal": "57000331", "upcard_mer_id": "102570089990044", "ex_cost_center_code": "1200845046", "dcore_store_appid": "s20171218000007122" } }, { "_id": "4034215829710839809", "name": "新乡宝龙店", "extend_code": { "comm_shop_id": "7a6ea4ade8764e2fb6afeb3b864c4362", "alipay_id": "2018041200077000000048276561", "us_id": "45058", "comm_code": "301003400004563", "upcard_terminal": "37301865", "upcard_mer_id": "102373089990133", "ex_cost_center_code": "1200845058", "dcore_store_appid": "s20171201000007071" } }, { "_id": "4034221029533986817", "name": "南浔新世界店", "extend_code": { "comm_shop_id": "69fa93ceea5b409a91c93b0cbec45a06", "alipay_id": "2018040900077000000048281146", "us_id": "45027", "comm_code": "301003400004547", "upcard_terminal": "57297190", "upcard_mer_id": "102572089990073", "ex_cost_center_code": "1200845027", "dcore_store_appid": "s20171201000007070" } }, { "_id": "4036409149526679553", "name": "岳阳步步高新天地店", "extend_code": { "comm_shop_id": "86cba843e9154fc0bc7dcfb3053b3046", "alipay_id": "2018041200077000000048267149", "us_id": "45059", "comm_code": "301003400004580", "upcard_terminal": "73001785", "upcard_mer_id": "102730089990073", "ex_cost_center_code": "1200845059", "dcore_store_appid": "s20171208000007093" } }, { "_id": "4036411317603905537", "name": "长沙富兴中心店", "extend_code": { "comm_shop_id": "ac2e9a2a52234f54a9dca81664bc1252", "alipay_id": "2018040900077000000048270640", "us_id": "45068", "comm_code": "301003400004618", "upcard_terminal": "73117020", "upcard_mer_id": "102731089992001", "ex_cost_center_code": "1200045068", "dcore_store_appid": "s20171208000007092" } }, { "_id": "4036748517250641921", "name": "开封星光天地店", "extend_code": { "comm_shop_id": "a65a628c040b4e3a8dcdc1609a2f1197", "alipay_id": "2018040400077000000048199601", "us_id": "45063", "comm_code": "301003400004613", "upcard_terminal": "37112988", "upcard_mer_id": "102371089992764", "ex_cost_center_code": "1200845063", "dcore_store_appid": "s20171213000007110" } }, { "_id": "4037857286976069633", "name": "苏州盛泽购物公园店", "extend_code": { "comm_shop_id": "20578a2034a948e6a93c0c94a3d8a6c5", "alipay_id": "2018040900077000000048266504", "us_id": "45028", "comm_code": "301003400004481", "upcard_terminal": "51216596", "upcard_mer_id": "102512089993195", "ex_cost_center_code": "1200845028", "dcore_store_appid": "s20171213000007111" } }, { "_id": "4038119643050315777", "name": "泗阳中央商场店", "extend_code": { "comm_shop_id": "7b6ba7f9ebe64e6da8230104239e5b32", "alipay_id": "2018040400077000000048183971", "us_id": "45049", "comm_code": "301003400004565", "upcard_terminal": "52701299", "upcard_mer_id": "102527089990301", "ex_cost_center_code": "1200845049", "dcore_store_appid": "s20171213000007113" } }, { "_id": "4038122496011173889", "name": "合肥国购店", "extend_code": { "comm_shop_id": "f6a56d9aad1347d9b421057d457f1639", "alipay_id": "2018040900077000000048283970", "us_id": "45071", "comm_code": "301003400004685", "upcard_terminal": "55130910", "upcard_mer_id": "102551089993784", "ex_cost_center_code": "1200845071", "dcore_store_appid": "s20171213000007112" } }, { "_id": "4038542360897060865", "name": "苏州相城天虹广场店", "extend_code": { "comm_shop_id": "3fc73d5480be442a97f2ab968f46ef66", "alipay_id": "2018040900077000000048281147", "us_id": "45056", "comm_code": "301003400004509", "upcard_terminal": "51216597", "upcard_mer_id": "102512089993196", "ex_cost_center_code": "1200845056", "dcore_store_appid": "s20171213000007114" } }, { "_id": "4038952094685507585", "name": "邵阳友阿国际广场店", "extend_code": { "comm_shop_id": "bd8d89b2184243cda69a9288549e58f8", "alipay_id": "2018040900077000000048259005", "us_id": "45077", "comm_code": "301003400004634", "upcard_terminal": "73901012", "upcard_mer_id": "102739089990048", "ex_cost_center_code": "1200845077", "dcore_store_appid": "s20171215000007116" } }, { "_id": "4041759819603394561", "name": "扬州江都金鹰店", "extend_code": { "comm_shop_id": "cd87eb76a8df4085bf6273098ab17922", "alipay_id": "2018040400077000000048176802", "us_id": "45100", "comm_code": "301003400004652", "upcard_terminal": "51401392", "upcard_mer_id": "102514089990300", "ex_cost_center_code": "1200845100", "dcore_store_appid": "s20171230000007137" } }, { "_id": "4041828426640879617", "name": "延安万达店", "extend_code": { "comm_shop_id": "96810e0d6160419e817e6241983d8d56", "alipay_id": "2018040900077000000048249324", "us_id": "45081", "comm_code": "301003400000276", "upcard_terminal": "91100098", "upcard_mer_id": "102911089990023", "ex_cost_center_code": "1200045081", "dcore_store_appid": "s20171227000007131" } }, { "_id": "4047933462918709249", "name": "湖州长兴东鱼坊店", "extend_code": { "comm_shop_id": "87ac10b59d964afba0b5798d07fe7275", "alipay_id": "2018040900077000000048281149", "us_id": "45029", "comm_code": "301003400004583", "upcard_terminal": "57297191", "upcard_mer_id": "102572089990074", "ex_cost_center_code": "1200845029", "dcore_store_appid": "s20180109000007153" } }, { "_id": "4048346706482503681", "name": "安庆吾悦广场店", "extend_code": { "comm_shop_id": "e2a0e954e48847619dc35fbe5e89a61a", "ex_cost_center_code": "1200845101", "alipay_id": "2018040900077000000048281148", "us_id": "45101", "comm_code": "301003400004667", "upcard_terminal": "55600321", "upcard_mer_id": "102556089990117", "ex_id": "45101", "ex_code": "45101", "dcore_store_appid": "s20180112000007160" } }, { "_id": "4048386376470007809", "name": "西安新乐汇店", "extend_code": { "comm_shop_id": "e23eacfb1bcc41f08f9731c8f47e9fe8", "alipay_id": "2018040400077000000048209499", "us_id": "45079", "comm_code": "301003400000410", "upcard_terminal": "02905370", "upcard_mer_id": "102290089993186", "ex_cost_center_code": "1200045079", "dcore_store_appid": "s20180112000007162" } }, { "_id": "4049375426659905537", "name": "上海证大大拇指广场店", "extend_code": { "comm_shop_id": "76e8c9e3aa4d49e098091d60933a7eea", "alipay_id": "2018040900077000000048249338", "us_id": "45080", "comm_code": "301003400000234", "upcard_terminal": "02139377", "upcard_mer_id": "102210089998000", "ex_cost_center_code": "1200045080", "dcore_store_appid": "s20180116000007175" } }, { "_id": "4051987334999449601", "name": "徐州东站店", "extend_code": { "comm_shop_id": "5015606cf0634f6891322bb56fa19faf", "us_id": "45110", "comm_code": "301003400004721", "upcard_terminal": "51601357", "upcard_mer_id": "102516089990265", "ex_cost_center_code": "1200845110", "dcore_store_appid": "s20180126000007200" } }, { "_id": "4064314349316845569", "name": "苏州泉屋百货店", "extend_code": { "comm_shop_id": "93a35ea818ca4dd49188803d09c366e7", "alipay_id": "2018040900077000000048270642", "us_id": "45118", "comm_code": "301003400004594", "upcard_terminal": "51216691", "upcard_mer_id": "102512089993214", "ex_cost_center_code": "1200845118", "dcore_store_appid": "S2018031610007319" } }, { "_id": "4076607790348185601", "name": "青岛影都万达茂店", "extend_code": { "comm_shop_id": "cdc84d4ba70449ae9ce7844490bf48ec", "alipay_id": "2018051500077000000051645406", "us_id": "45122", "comm_code": "301003400004653", "upcard_terminal": "53206369", "upcard_mer_id": "102532089991483", "ex_cost_center_code": "1200845122", "dcore_store_appid": "S2018032910007438" } }, { "_id": "4079094118134743041", "name": "徐州苏宁店", "extend_code": { "comm_shop_id": "67dd4fe552904b49b3f28a4274f02dc8", "alipay_id": "2018051500077000000051727409", "us_id": "45154", "comm_code": "301003400004545", "upcard_terminal": "51601363", "upcard_mer_id": "102516089990267", "ex_cost_center_code": "1200845154", "dcore_store_appid": "S2018040910007462" } }, { "_id": "4079127921389006849", "name": "郑州东站店", "extend_code": { "comm_shop_id": "174b38d2458c4bba95585db65189dd6d", "us_id": "45151", "comm_code": "301003400004468", "upcard_terminal": "39601449", "upcard_mer_id": "102396089990063", "ex_cost_center_code": "1200845151", "dcore_store_appid": "S2018040910007463" } }, { "_id": "4079163645891452929", "name": "南昌西湖万达店", "extend_code": { "comm_shop_id": "7d8149a9fded4b6c99bfd9435cac43ee", "alipay_id": "2018051500077000000051631031", "us_id": "45153", "comm_code": "301003400004568", "upcard_terminal": "79191389", "upcard_mer_id": "102791089990672", "ex_cost_center_code": "1200845153", "dcore_store_appid": "S2018040910007465" } }, { "_id": "4080945562105540609", "name": "洛阳建业凯旋店", "extend_code": { "comm_shop_id": "213d04e748054363b2834e0949df9750", "alipay_id": "2018051500077000000051629688", "us_id": "45155", "comm_code": "301003400004484", "upcard_terminal": "37901855", "upcard_mer_id": "102379089990507", "ex_cost_center_code": "1200845155", "dcore_store_appid": "S2018041110007497" } }, { "_id": "4083475493077458945", "name": "大同百盛店", "extend_code": { "comm_shop_id": "8564eb9e9b024954aeb6667277b95f4d", "alipay_id": "2018070200077000000058090637", "us_id": "45161", "comm_code": "301003400004578", "upcard_terminal": "35200232", "upcard_mer_id": "102352089990049", "ex_cost_center_code": "1200845161", "dcore_store_appid": "S2018041610007624" } }, { "_id": "4085973522101977089", "name": "瑞安吾悦店", "extend_code": { "comm_shop_id": "73b0916329eb4ed0acb693c21d9909a3", "alipay_id": "2018081500077000000061409413", "us_id": "45169", "comm_code": "301003400004554", "upcard_terminal": "57701270", "upcard_mer_id": "102577089990232", "ex_cost_center_code": "1200845169", "dcore_store_appid": "S2018042310007654" } }, { "_id": "4085980156278366209", "name": "上海曹路家乐福店", "extend_code": { "comm_shop_id": "30b312af5cb14b21b17db5dff2f02e67", "alipay_id": "2018071000077000000058974770", "us_id": "45167", "comm_code": "301003400004495", "upcard_terminal": "02139643", "upcard_mer_id": "102210089998036", "ex_cost_center_code": "1200845167", "dcore_store_appid": "S2018042310007655" } }, { "_id": "4086423399983869953", "name": "溧阳万达店", "extend_code": { "comm_shop_id": "1e17f000ab014d1aa2e214b4bfcd42ee", "alipay_id": "2018081500077000000061414820", "us_id": "45177", "comm_code": "301003400004479", "upcard_terminal": "51901534", "upcard_mer_id": "102519089990215", "ex_cost_center_code": "1200845177", "dcore_store_appid": "S2018042610007686" } }, { "_id": "4087425920756776961", "name": "贵阳观山湖万达店", "extend_code": { "comm_shop_id": "2330ae456ac84fbf992bc62c18acf6d6", "alipay_id": "2018071000077000000058981444", "us_id": "45170", "comm_code": "301003400000077", "upcard_terminal": "85101969", "upcard_mer_id": "102851089990541", "ex_cost_center_code": "1200045170", "dcore_store_appid": "S2018042810007698" } }, { "_id": "4087873879549825025", "name": "南京万达茂店", "extend_code": { "comm_shop_id": "87182bdb70b84952af932278c08fc82c", "alipay_id": "2018071000077000000058972962", "us_id": "45187", "comm_code": "301003400004582", "upcard_terminal": "02581210", "upcard_mer_id": "102250089993563", "ex_cost_center_code": "1200845187", "dcore_store_appid": "S2018050310007754" } }, { "_id": "4089334362867511297", "name": "扬州京华城一店", "extend_code": { "comm_shop_id": "077c1349233a4d159679332642dd5ec3", "alipay_id": "2018072700077000000060272404", "us_id": "45176", "comm_code": "301003400004451", "upcard_terminal": "51401433", "upcard_mer_id": "102514089990318", "ex_cost_center_code": "1200845176", "dcore_store_appid": "S2018050310007755" } }, { "_id": "4091471121304784897", "name": "黄冈万达店", "extend_code": { "comm_shop_id": "2a1910a92476469db17c384437eb36fb", "alipay_id": "2018071000077000000059037186", "us_id": "45189", "comm_code": "301003400004489", "upcard_terminal": "71300240", "upcard_mer_id": "102713089990039", "ex_cost_center_code": "1200845189", "dcore_store_appid": "S2018051610007893" } }, { "_id": "4091478386262851585", "name": "晋城兰花城店", "extend_code": { "comm_shop_id": "1a605f2a9d5e46348fc765a1c6211f8e", "alipay_id": "2018071000077000000058981449", "us_id": "45191", "comm_code": "301003400004473", "upcard_terminal": "35600037", "upcard_mer_id": "102356089990022", "ex_cost_center_code": "1200845191", "dcore_store_appid": "S2018051610007894" } }, { "_id": "4092169478572806145", "name": "长沙金茂店", "extend_code": { "comm_shop_id": "fc1b61839af84cf7a5084b0bc6965115", "alipay_id": "2018071000077000000058978334", "us_id": "45197", "comm_code": "301003400004691", "upcard_terminal": "73117588", "upcard_mer_id": "102731089992069", "ex_cost_center_code": "1200845197", "dcore_store_appid": "S2018051610007895" } }, { "_id": "4092487770278039553", "name": "烟台莱山佳世客店", "extend_code": { "comm_shop_id": "cb5e67951f8648c4874bdd9a0fc5a7fe", "alipay_id": "2018071000077000000059001134", "us_id": "45196", "comm_code": "301003400004647", "upcard_terminal": "53500394", "upcard_mer_id": "102535089990205", "ex_cost_center_code": "1200845196", "dcore_store_appid": "S2018051610007898" } }, { "_id": "4096921136813035521", "name": "上海静安大融城店", "extend_code": { "comm_shop_id": "34012477ac3a45b3b6efc968feae8838", "alipay_id": "2018070200077000000058067107", "us_id": "45205", "comm_code": "301003400004500", "upcard_terminal": "02139750", "upcard_mer_id": "102210089998091", "ex_cost_center_code": "1200845205", "dcore_store_appid": "S2018052410007967" } }, { "_id": "4096922839413235713", "name": "威海威高店", "extend_code": { "comm_shop_id": "6975bdcb8e5d473fbb173fa2f0c3095c", "ex_code": "", "alipay_id": "2018081500077000000061409414", "us_id": "45204", "comm_code": "301003400004546", "upcard_terminal": "63103746", "upcard_mer_id": "102631089992119", "ex_cost_center_code": "1200845204", "dcore_store_appid": "S2018052410007968" } }, { "_id": "4096924580198096897", "name": "日照万象汇店", "extend_code": { "comm_shop_id": "fee45ad2d2374a24863bfad6a25d5eb8", "alipay_id": "2018070200077000000058103829", "us_id": "45203", "comm_code": "301003400004693", "upcard_terminal": "63300006", "upcard_mer_id": "102633089990021", "ex_cost_center_code": "1200845203", "dcore_store_appid": "S2018052410007965" } }, { "_id": "4100137793345470465", "name": "苏州市阳澄湖服务区北区店", "extend_code": { "comm_shop_id": "c0c9c578fbcd4218a960323b417cf298", "alipay_id": "2018081500077000000061413731", "us_id": "45211", "comm_code": "301003400004639", "upcard_terminal": "51216815", "upcard_mer_id": "102512089993230", "ex_cost_center_code": "1200845211", "dcore_store_appid": "S2018060110007985" } }, { "_id": "4102278598728146945", "name": "晋中奥特莱斯店", "extend_code": { "comm_shop_id": "b28c34b273054aab96037616982d54c8", "alipay_id": "2018101200077000000063543383", "us_id": "45208", "comm_code": "301003400004625", "upcard_terminal": "35400080", "upcard_mer_id": "102354089990031", "ex_cost_center_code": "1200845208", "dcore_store_appid": "S2018060710008014" } }, { "_id": "4103732800994172929", "name": "商丘万达店", "extend_code": { "comm_shop_id": "90e1e5a409b348faa3a89a994f53979c", "alipay_id": "2018081500077000000061405827", "us_id": "45209", "comm_code": "301003400004591", "upcard_terminal": "37001398", "upcard_mer_id": "102370089990039", "ex_cost_center_code": "1200845209", "dcore_store_appid": "S2018061210008019" } }, { "_id": "4110238706563067905", "name": "青岛丽达店", "extend_code": { "comm_shop_id": "cd54d6397a3741a5ab68257bdbf75450", "alipay_id": "2018081500077000000061409415", "us_id": "45195", "comm_code": "301003400004651", "upcard_terminal": "53206386", "upcard_mer_id": "102532089991494", "ex_cost_center_code": "1200845195", "dcore_store_appid": "S2018070510008048" } }, { "_id": "4113975942941487105", "name": "合肥港汇店", "extend_code": { "comm_shop_id": "0c19a00fd6ae470899467e90b0a90984", "alipay_id": "2018082300077000000061873604", "us_id": "45243", "comm_code": "301003400004460", "upcard_terminal": "55131087", "upcard_mer_id": "102551089993813", "ex_cost_center_code": "1200845243", "dcore_store_appid": "S2018071010008058" } }, { "_id": "4114237766378766337", "name": "泰兴广陵东服务区店", "extend_code": { "comm_shop_id": "d8b2df697db64a7ea9f251c610956bca", "us_id": "45247", "comm_code": "301003400004660", "upcard_terminal": "52300873", "upcard_mer_id": "102523089990124", "ex_cost_center_code": "1200845247", "dcore_store_appid": "S2018071010008059" } }, { "_id": "4114239187195158529", "name": "泰兴广陵西服务区店", "extend_code": { "comm_shop_id": "8b186bfcfb6644c19b7bb27cf6b38ac6", "us_id": "45246", "comm_code": "301003400004586", "upcard_terminal": "52300874", "upcard_mer_id": "102523089990125", "ex_cost_center_code": "1200845246", "dcore_store_appid": "S2018081310008105" } }, { "_id": "4114581614087012353", "name": "南通永旺店", "extend_code": { "comm_shop_id": "8acc29019bbc4f9eaf757b7f6cb7b0df", "alipay_id": "2018080600077000000060849571", "us_id": "45249", "comm_code": "301003400004585", "upcard_terminal": "51301300", "upcard_mer_id": "102513089990242", "ex_cost_center_code": "1200845249", "dcore_store_appid": "S2018071110008062" } }, { "_id": "4114641263291166721", "name": "上海五角场合生汇店", "extend_code": { "comm_shop_id": "f6c6c484fad641da955788722573fa5e", "alipay_id": "2019032700077000000073564862", "us_id": "45248", "comm_code": "301003400000445", "upcard_terminal": "02111253", "upcard_mer_id": "102210089998155", "ex_cost_center_code": "1200045248", "dcore_store_appid": "S2018071310008074" } }, { "_id": "4115405479240224769", "name": "延安治平凤凰城店", "extend_code": { "comm_shop_id": "9aca77a1916f4c6eb677967d5c1cd478", "alipay_id": "2018081500077000000061413745", "us_id": "45233", "comm_code": "301003400000285", "upcard_terminal": "91100202", "upcard_mer_id": "102911089990027", "ex_cost_center_code": "1200045233", "dcore_store_appid": "S2018071910008081" } }, { "_id": "4115407112690946049", "name": "杭州萧山机场店", "extend_code": { "comm_shop_id": "e500a5066dd5498299db6e4147b7752f", "alipay_id": "2019011400077000000069533575", "us_id": "45210", "comm_code": "301003400004671", "upcard_terminal": "57112492", "upcard_mer_id": "102571089992939", "ex_cost_center_code": "1200845210", "dcore_store_appid": "S2018071310008075" } }, { "_id": "4116413591081840641", "name": "深圳宝安机场店", "extend_code": { "comm_shop_id": "adbdcd0f97804898b4e6449849b41b9e", "alipay_id": "2019010200077000000069210530", "us_id": "45234", "comm_code": "301003400004738", "upcard_terminal": "75519144", "upcard_mer_id": "102755089993786", "ex_cost_center_code": "1200045234", "dcore_store_appid": "S2018071810008077" } }, { "_id": "4116830373533507585", "name": "太原万象城店", "extend_code": { "comm_shop_id": "40a0fa1a4af44132919522aa846db5ff", "alipay_id": "2018092700077000000063170418", "us_id": "45236", "comm_code": "301003400004510", "upcard_terminal": "35104472", "upcard_mer_id": "102351056991908", "ex_cost_center_code": "1200845236", "dcore_store_appid": "S2018071810008078" } }, { "_id": "4116831979571179521", "name": "太原富力广场店", "extend_code": { "comm_shop_id": "f87159334248402faa2dde96106624c3", "alipay_id": "2018082300077000000061877007", "us_id": "45258", "comm_code": "301003400004687", "upcard_terminal": "35104473", "upcard_mer_id": "103351056991909", "ex_cost_center_code": "1200845258", "dcore_store_appid": "S2018071810008079" } }, { "_id": "4117919376773586945", "name": "扬州仪征宝能店", "extend_code": { "comm_shop_id": "f52fd7d599f44f458f89081fb053b4d5", "alipay_id": "2018111500077000000065937133", "us_id": "45256", "comm_code": "301003400004684", "upcard_terminal": "51401512", "upcard_mer_id": "102514089990326", "ex_cost_center_code": "1200845256", "dcore_store_appid": "S2018072410008085" } }, { "_id": "4118992973852532737", "name": "湖州德清银河城店", "extend_code": { "comm_shop_id": "c64ef9b5dd3f49f8893d12132588230f", "alipay_id": "2018110200077000000065441004", "us_id": "45242", "comm_code": "301003400004644", "upcard_terminal": "57297260", "upcard_mer_id": "102572089990081", "ex_cost_center_code": "1200845242", "dcore_store_appid": "S2018072410008087" } }, { "_id": "4118997338543366145", "name": "九江万达店", "extend_code": { "comm_shop_id": "fc50007df0c2437faf20e5ccf16dfbb3", "alipay_id": "2018081500077000000061414821", "us_id": "45259", "comm_code": "301003400004692", "upcard_terminal": "79200762", "upcard_mer_id": "102792089990177", "ex_cost_center_code": "1200845259", "dcore_store_appid": "S2018072410008086" } }, { "_id": "4121533209572458497", "name": "长治万达店", "extend_code": { "comm_shop_id": "ad9fae892de64ffe9cb3138079962634", "alipay_id": "2018092700077000000063133400", "us_id": "45273", "comm_code": "301003400004619", "upcard_terminal": "35500056", "upcard_mer_id": "102355089990028", "ex_cost_center_code": "1200845273", "dcore_store_appid": "S2018080210008096" } }, { "_id": "4122677878704488449", "name": "郑州熙地港店", "extend_code": { "comm_shop_id": "2d99bb9722644d3880625a78b86a5da2", "alipay_id": "2019011400077000000069539833", "us_id": "45265", "comm_code": "301003400004492", "upcard_terminal": "37113912", "upcard_mer_id": "102371089992855", "ex_cost_center_code": "1200845265", "dcore_store_appid": "S2018080210008098" } }, { "_id": "4122679299960795137", "name": "临汾生龙国际店", "extend_code": { "comm_shop_id": "12a9a3e6d5254ff5b9167507ed24504b", "alipay_id": "2018092700077000000063171913", "us_id": "45280", "comm_code": "301003400004464", "upcard_terminal": "35700764", "upcard_mer_id": "102357089990056", "ex_cost_center_code": "1200845280", "dcore_store_appid": "S2018080210008097" } }, { "_id": "4124764025048219649", "name": "平湖吾悦店", "extend_code": { "comm_shop_id": "b71b2d25b8f04295ab2f8cd8332b0d12", "alipay_id": "2018110200077000000065441031", "us_id": "45281", "comm_code": "301003400004627", "upcard_terminal": "57304056", "upcard_mer_id": "102573089990195", "ex_cost_center_code": "1200845281", "dcore_store_appid": "S2018081310008106" } }, { "_id": "4125152715792138241", "name": "郑州杉杉奥特莱斯店", "extend_code": { "comm_shop_id": "9f417f868b51479eb4139dfaaa653538", "us_id": "45261", "comm_code": "301003400004603", "upcard_terminal": "37113965", "upcard_mer_id": "102371089992858", "ex_cost_center_code": "1200845261", "dcore_store_appid": "S2018081310008108" } }, { "_id": "4126601657147342849", "name": "郑州绿地新都会店", "extend_code": { "comm_shop_id": "c9c92223279f4197b5338eb557d38026", "alipay_id": "2018091300077000000062649175", "us_id": "45293", "comm_code": "301003400004646", "upcard_terminal": "37113966", "upcard_mer_id": "102371089992859", "ex_cost_center_code": "1200845293", "dcore_store_appid": "S2018081310008109" } }, { "_id": "4126605730021203969", "name": "阜阳百太星马国际店", "extend_code": { "comm_shop_id": "6ebf5b72099844fcbbd7ee87b93e3042", "alipay_id": "2019012100077000000069848970", "us_id": "45266", "comm_code": "301003400004727", "upcard_terminal": "55801941", "upcard_mer_id": "102558089990688", "ex_cost_center_code": "1200845266", "dcore_store_appid": "S2018092910008214" } }, { "_id": "4126611687771553793", "name": "湖州长兴九汇城店", "extend_code": { "comm_shop_id": "a50c33ad5ced4e929c33fcfe686810e0", "alipay_id": "2018110200077000000065439779", "us_id": "45285", "comm_code": "301003400004610", "upcard_terminal": "57297264", "upcard_mer_id": "102572089990083", "ex_cost_center_code": "1200845285", "dcore_store_appid": "S2018081310008110" } }, { "_id": "4129103498775916545", "name": "郑州汇艺店", "extend_code": { "comm_shop_id": "af3e7313fb2a4986803d27891c11bcfb", "alipay_id": "2018092700077000000063168539", "us_id": "45299", "comm_code": "301003400004622", "upcard_terminal": "37113913", "upcard_mer_id": "102371089992856", "ex_cost_center_code": "1200845299", "dcore_store_appid": "S2018082010008150" } }, { "_id": "4129104916787679233", "name": "淮北万达店", "extend_code": { "comm_shop_id": "d7cdede3d76e4f2a942a128659bd978f", "alipay_id": "2019041000077000000075866478", "us_id": "45300", "comm_code": "301003400004658", "upcard_terminal": "56100891", "upcard_mer_id": "102561089990247", "ex_cost_center_code": "1200845300", "dcore_store_appid": "S2018082010008149" } }, { "_id": "4132033900400844801", "name": "南京溧水万达店", "extend_code": { "comm_shop_id": "517d7a869e87460480495f9e484362b2", "alipay_id": "2018101900077000000064357079", "us_id": "45308", "comm_code": "301003400004525", "upcard_terminal": "02582214", "upcard_mer_id": "102250089993824", "ex_cost_center_code": "1200845308", "dcore_store_appid": "S2018090310008173" } }, { "_id": "4132035420274376705", "name": "南通万象城店", "extend_code": { "comm_shop_id": "f1e550f367b04354a9d59dcd2458a8c0", "alipay_id": "2018092700077000000063170419", "us_id": "45307", "comm_code": "301003400004680", "upcard_terminal": "51301420", "upcard_mer_id": "102513089990253", "ex_cost_center_code": "1200845307", "dcore_store_appid": "S2018090310008175" } }, { "_id": "4133151762527371265", "name": "常州龙城天街店", "extend_code": { "comm_shop_id": "ee0d20a5199740f0a94126a4457433e5", "alipay_id": "2018122600077000000068543282", "us_id": "45312", "comm_code": "301003400004678", "upcard_terminal": "51902019", "upcard_mer_id": "102519089990226", "ex_cost_center_code": "1200845312", "dcore_store_appid": "S2018090310008176" } }, { "_id": "4134204740237754369", "name": "宁波慈城东服务区店", "extend_code": { "comm_shop_id": "99db7ae4921a4f19887caf2fd2c52bfc", "us_id": "45322", "comm_code": "301003400004598", "upcard_terminal": "57404550", "upcard_mer_id": "102574089990675", "ex_cost_center_code": "1200845322", "dcore_store_appid": "S2018090610008186" } }, { "_id": "4134210349346463745", "name": "宁波慈城西服务区店", "extend_code": { "comm_shop_id": "11818412aa594e09ad0dc90087b4c6b6", "us_id": "45321", "comm_code": "301003400004463", "upcard_terminal": "57404551", "upcard_mer_id": "102574089990676", "ex_cost_center_code": "1200845321", "dcore_store_appid": "S2018092910008211" } }, { "_id": "4134215215138557953", "name": "上海奉贤宝龙店", "extend_code": { "comm_shop_id": "f7d3f546082a48c8a2e33ccccdeec5e4", "alipay_id": "2018092900077000000063208125", "us_id": "45316", "comm_code": "301003400004686", "upcard_terminal": "02111626", "upcard_mer_id": "102210089998307", "ex_cost_center_code": "1200845316", "dcore_store_appid": "S2018092910008210" } }, { "_id": "4134635867201208321", "name": "扬州吾悦店", "extend_code": { "comm_shop_id": "07d2020a4fb243f98c15bc45dcabdeb5", "alipay_id": "2018111500077000000065942777", "us_id": "45298", "comm_code": "301003400004453", "upcard_terminal": "51401645", "upcard_mer_id": "102514089990335", "ex_cost_center_code": "1200845298", "dcore_store_appid": "S2018090610008188" } }, { "_id": "4139286224734511105", "name": "达州升华广场店", "extend_code": { "comm_shop_id": "7fab9cbf57394feb9be0fddb7957861b", "alipay_id": "2018111500077000000065947582", "us_id": "45344", "comm_code": "301003400004570", "upcard_terminal": "81800321", "upcard_mer_id": "102818089990043", "ex_cost_center_code": "1200845344", "dcore_store_appid": "S2018092110008200" } }, { "_id": "4139315531955630081", "name": "南昌酷加天虹店", "extend_code": { "comm_shop_id": "835fccebfd3847458da673a731c0aab3", "alipay_id": "2018101600077000000063658138", "us_id": "45332", "comm_code": "301003400004574", "upcard_terminal": "79191472", "upcard_mer_id": "102791089990719", "ex_cost_center_code": "1200845332", "dcore_store_appid": "S2018092110008199" } }, { "_id": "4140016321382154241", "name": "驻马店爱家店", "extend_code": { "comm_shop_id": "afe1c69689d04b58b32016e01cd97a8b", "alipay_id": "2018110200077000000065438423", "us_id": "45343", "comm_code": "301003400004739", "upcard_terminal": "39601585", "upcard_mer_id": "102396089990065", "ex_cost_center_code": "1200845343", "dcore_store_appid": "S2018092110008201" } }, { "_id": "4140421607509770241", "name": "忻州开来欣悦店", "extend_code": { "comm_shop_id": "8ebf87feaa2c41778eacd4a554095793", "alipay_id": "2018110200077000000065439778", "us_id": "45348", "comm_code": "301003400004589", "upcard_terminal": "35000073", "upcard_mer_id": "102350089990059", "ex_cost_center_code": "1200845348", "dcore_store_appid": "S2018092110008202" } }, { "_id": "4140789178306994177", "name": "菏泽万达店", "extend_code": { "comm_shop_id": "33979b9dceff4ebcb54b25dc8931d176", "us_id": "45325", "comm_code": "301003400004499", "upcard_terminal": "53000575", "upcard_mer_id": "102530089990234", "ex_cost_center_code": "1200845325", "dcore_store_appid": "S2018092110008204" } }, { "_id": "4140790602041192449", "name": "济南万虹银座店", "extend_code": { "comm_shop_id": "fa1186d8ca294f37841174105810590e", "alipay_id": "2018121900077000000068322823", "us_id": "45345", "comm_code": "301003400004690", "upcard_terminal": "53101612", "upcard_mer_id": "102531089990641", "ex_cost_center_code": "1200845345", "dcore_store_appid": "S2018092110008203" } }, { "_id": "4144004231356600321", "name": "巢湖万达店", "extend_code": { "comm_shop_id": "d3146bb3e0474ecf8e25e84de9658cdd", "alipay_id": "2018110800077000000065641240", "us_id": "45365", "comm_code": "301003400004656", "upcard_terminal": "55131437", "upcard_mer_id": "102551089993838", "ex_cost_center_code": "1200845365", "dcore_store_appid": "S2018092910008217" } }, { "_id": "4146845449628708865", "name": "郑州正弘城店", "extend_code": { "comm_shop_id": "345e0cfab09a4cb39487e9e6713ddb56", "alipay_id": "2019011000077000000069426365", "us_id": "45372", "comm_code": "301003400004501", "upcard_terminal": "37114056", "upcard_mer_id": "102371089992867", "ex_cost_center_code": "1200845372", "dcore_store_appid": "S2018100910008221" } }, { "_id": "4150176012169773057", "name": "抚州硕果时代店", "extend_code": { "comm_shop_id": "28b9b4d62b1e43c6a3098836d544ddbc", "alipay_id": "2018122600077000000068537438", "us_id": "45284", "comm_code": "301003400004707", "upcard_terminal": "79400205", "upcard_mer_id": "102794089990050", "ex_cost_center_code": "1200845284", "dcore_store_appid": "S2018101710008256" } }, { "_id": "4150196479186903041", "name": "金华永盛店", "extend_code": { "comm_shop_id": "3a73519256ac449cbb658445a987e526", "alipay_id": "2018110200077000000065430167", "us_id": "45364", "comm_code": "301003400004504", "upcard_terminal": "57990795", "upcard_mer_id": "102579089990277", "ex_cost_center_code": "1200845364", "dcore_store_appid": "S2018101710008258" } }, { "_id": "4152649549586010113", "name": "合肥大洋百货店", "extend_code": { "comm_shop_id": "51cfa4f050f04be292900bba0300ae97", "alipay_id": "2018111500077000000066207550", "us_id": "45411", "comm_code": "301003400004526", "upcard_terminal": "55131445", "upcard_mer_id": "102551089993842", "ex_cost_center_code": "1200845411", "dcore_store_appid": "S2018102410008288" } }, { "_id": "4153006374760136705", "name": "上海白玉兰广场店", "extend_code": { "comm_shop_id": "109104b27bc0448788f26770a5e30d58", "alipay_id": "2020060800077000000095144926", "us_id": "45405", "comm_code": "301003400004701", "upcard_terminal": "02111816", "upcard_mer_id": "102210089998402", "ex_cost_center_code": "1200045405" } }, { "_id": "4153471261688762369", "name": "合肥滨湖世纪金源店", "extend_code": { "comm_shop_id": "ed28728be88f4024bc4f04a447ac010b", "alipay_id": "2019010200077000000069206207", "us_id": "45404", "comm_code": "301003400004421", "upcard_terminal": "55131446", "upcard_mer_id": "102551089993843", "ex_cost_center_code": "1200845404" } }, { "_id": "4154464939744419841", "name": "合肥滨湖银泰店", "extend_code": { "comm_shop_id": "f060b01bb6df4c90a189409bc11ec957", "alipay_id": "2019010200077000000069209188", "us_id": "45410", "comm_code": "301003400004422", "upcard_terminal": "55131447", "upcard_mer_id": "102551089993844", "ex_cost_center_code": "1200845410" } }, { "_id": "4154471226036903937", "name": "许昌万达店", "extend_code": { "comm_shop_id": "0a118489d8c34d3fa54f59fe0217f36f", "alipay_id": "2019041000077000000075864242", "us_id": "45413", "comm_code": "301003400004696", "upcard_terminal": "37401780", "upcard_mer_id": "102374089990077", "ex_cost_center_code": "1200845413" } }, { "_id": "4154503143297040385", "name": "大同万达店", "extend_code": { "comm_shop_id": "765cc7c88ca548798ebfadd92b9dbcbb", "alipay_id": "2018112800077000000067691992", "us_id": "45418", "comm_code": "301003400004557", "upcard_terminal": "35200233", "upcard_mer_id": "102352089990050", "ex_cost_center_code": "1200845418" } }, { "_id": "4154504983742676993", "name": "忻州开来欣悦影院店", "extend_code": { "comm_shop_id": "cf363c47c2f043d688a5ef2255775570", "us_id": "45373", "comm_code": "301003400004401", "upcard_terminal": "35000074", "upcard_mer_id": "102350089990060", "ex_cost_center_code": "1200845373" } }, { "_id": "4159888449808629761", "name": "张家港万达店", "extend_code": { "comm_shop_id": "5387787ac56b4173b025bbb17436ca07", "alipay_id": "2019010200077000000069206208", "us_id": "45441", "comm_code": "301003400004722", "upcard_terminal": "51217436", "upcard_mer_id": "102512089993305", "ex_cost_center_code": "1200845441" } }, { "_id": "4160976205647978497", "name": "上海金山万达店", "extend_code": { "comm_shop_id": "fb4b7c222e2e416eaf40de96a15c1251", "alipay_id": "2018121900077000000068328904", "us_id": "45445", "comm_code": "301003400004745", "upcard_terminal": "02111968", "upcard_mer_id": "102210089998439", "ex_cost_center_code": "1200845445" } }, { "_id": "4160978965889052673", "name": "临沂泰盛店", "extend_code": { "comm_shop_id": "20937489ecca4b8188da24c234f3fffb", "alipay_id": "2018122600077000000068530306", "us_id": "45403", "comm_code": "301003400004704", "upcard_terminal": "53952341", "upcard_mer_id": "102539089990430", "ex_cost_center_code": "1200845403" } }, { "_id": "4162431335909015553", "name": "青岛城阳万象汇店", "extend_code": { "comm_shop_id": "9b28cbe0f8004fb08be9bc4a23f70c65", "alipay_id": "2018122100077000000068395417", "us_id": "45444", "comm_code": "301003400004735", "upcard_terminal": "53206420", "upcard_mer_id": "102532089991518", "ex_cost_center_code": "1200845444" } }, { "_id": "4165028107158962177", "name": "舟山定海凯虹店", "extend_code": { "comm_shop_id": "459f904ac2b64ec5905715c07290a4a1", "alipay_id": "2019011400077000000069537808", "us_id": "45420", "comm_code": "301003400004718", "upcard_terminal": "58000400", "upcard_mer_id": "102580089990051", "ex_cost_center_code": "1200045420" } }, { "_id": "4165327831024205825", "name": "郑州局外太格茂店", "extend_code": { "comm_shop_id": "8193d54a29f7461999a5ca6f038386b5", "alipay_id": "2018122600077000000068530305", "us_id": "45425", "comm_code": "301003400004730", "upcard_terminal": "37114114", "upcard_mer_id": "102371089992872", "ex_cost_center_code": "1200845425" } }, { "_id": "4165681062380634113", "name": "启东吾悦店", "extend_code": { "comm_shop_id": "989f5a492a45409b87fee6b72d793444", "alipay_id": "2018122600077000000068537439", "us_id": "45467", "comm_code": "301003400004734", "upcard_terminal": "51301431", "upcard_mer_id": "102513089990257", "ex_cost_center_code": "1200845467" } }, { "_id": "4165729105024806913", "name": "运城万达店", "extend_code": { "comm_shop_id": "1634f8a81f1c47ca9abfee092de4c783", "alipay_id": "2019010200077000000069217892", "us_id": "45448", "comm_code": "301003400004400", "upcard_terminal": "35900133", "upcard_mer_id": "102359089990034", "ex_cost_center_code": "1200845448" } }, { "_id": "4165730245892542465", "name": "岳阳步步高星都汇店", "extend_code": { "comm_shop_id": "24512b3854b14348876ffd4f2fd7110e", "alipay_id": "2019010200077000000069202176", "us_id": "45477", "comm_code": "301003400004705", "upcard_terminal": "73002209", "upcard_mer_id": "102730089990077", "ex_cost_center_code": "1200845477" } }, { "_id": "4165742820760801281", "name": "厦门阿罗海店", "extend_code": { "comm_shop_id": "1036b5373d2343ca9f0077884c26c4a2", "alipay_id": "2018122600077000000068570705", "us_id": "45476", "comm_code": "301003400004700", "upcard_terminal": "59205666", "upcard_mer_id": "102592089990666", "ex_cost_center_code": "1200845476" } }, { "_id": "4166039404921270273", "name": "扬州邗江万达店", "extend_code": { "comm_shop_id": "7a07dde0032e4f6bbe250d473ddcef52", "alipay_id": "2019010200077000000069214350", "us_id": "45472", "comm_code": "301003400004728", "upcard_terminal": "51401651", "upcard_mer_id": "102514089990338", "ex_cost_center_code": "1200845472" } }, { "_id": "4167250700683948033", "name": "兰州中心店", "extend_code": { "comm_shop_id": "6bc8cc82b62941dfaefcc0b01ef7c78a", "alipay_id": "2019011400077000000069539785", "us_id": "45419", "comm_code": "301003400004726", "upcard_terminal": "93101216", "upcard_mer_id": "102931089990228", "ex_cost_center_code": "1200045419" } }, { "_id": "4167588597452136449", "name": "济南和谐店", "extend_code": { "comm_shop_id": "3aba265663224256b72d75831d96dff3", "alipay_id": "2019042500077000000076477421", "us_id": "45483", "comm_code": "301003400004713", "upcard_terminal": "53101617", "upcard_mer_id": "102531089990644", "ex_cost_center_code": "1200845483" } }, { "_id": "4168303011669086209", "name": "泰州茂业店", "extend_code": { "comm_shop_id": "f712ac32e3f74a88bdd3db0a559162ea", "alipay_id": "2019010200077000000069216289", "us_id": "45474", "comm_code": "301003400004744", "upcard_terminal": "52300991", "upcard_mer_id": "102523089990137", "ex_cost_center_code": "1200845474" } }, { "_id": "4168318777077153793", "name": "三门峡梦之城店", "extend_code": { "comm_shop_id": "0e236304fe5040e79c7c2f0eeb6d42ea", "alipay_id": "2019041100077000000076000442", "us_id": "45490", "comm_code": "301003400004699", "upcard_terminal": "39801126", "upcard_mer_id": "102398089990029", "ex_cost_center_code": "1200845490" } }, { "_id": "4168612141303578625", "name": "常州环球港店", "extend_code": { "comm_shop_id": "0d89f531a9cd457a94e6b520dd92cca4", "alipay_id": "2019010200077000000069214351", "us_id": "45447", "comm_code": "301003400004698", "upcard_terminal": "51902029", "upcard_mer_id": "102519089990232", "ex_cost_center_code": "1200845447" } }, { "_id": "4168703113316777985", "name": "扬州五彩世界店", "extend_code": { "comm_shop_id": "29b59fd6a04c4daf8874b65ea1445126", "alipay_id": "2018122600077000000068530304", "us_id": "45443", "comm_code": "301003400004708", "upcard_terminal": "51401690", "upcard_mer_id": "102514089990341", "ex_cost_center_code": "1200845443" } }, { "_id": "4171169440537362433", "name": "洛阳正大店", "extend_code": { "comm_shop_id": "e5f70d0277d24e5aa8065372b8f81c4c", "alipay_id": "2019051000077000000077229176", "us_id": "45501", "comm_code": "301003400004743", "upcard_terminal": "37902016", "upcard_mer_id": "102379089990512", "ex_cost_center_code": "1200845501" } }, { "_id": "4178789021156511745", "name": "信阳罗山华鼎城店", "extend_code": { "comm_shop_id": "e30b00513a85448689385240af345840", "alipay_id": "2019021500077000000070980530", "us_id": "45515", "comm_code": "301003400004742", "upcard_terminal": "37602996", "upcard_mer_id": "102376089990155", "ex_cost_center_code": "1200845515" } }, { "_id": "4179865584621322241", "name": "苏州园区永旺梦乐城店", "extend_code": { "comm_shop_id": "3b9256bd551744feada97e52ff8a5ac2", "alipay_id": "2019021500077000000070960588", "us_id": "45518", "comm_code": "301003400004714", "upcard_terminal": "51217451", "upcard_mer_id": "102512089993313", "ex_cost_center_code": "1200845518" } }, { "_id": "4180622686182809601", "name": "广东大槐东服务区店", "extend_code": { "comm_shop_id": "25e27720a5db4ee899fb1951f4aa621e", "us_id": "45517", "comm_code": "301003400004706", "upcard_terminal": "75090152", "upcard_mer_id": "102750089990064", "ex_cost_center_code": "1200045517" } }, { "_id": "4180623942064128001", "name": "广东大槐西服务区店", "extend_code": { "comm_shop_id": "a0b6d6829fff4c51a2947f697e9478d2", "us_id": "45516", "comm_code": "301003400004831", "upcard_terminal": "75090153", "upcard_mer_id": "102750089990065", "ex_cost_center_code": "1200045516", "dianping_store_id": "" } }, { "_id": "4198046181180911617", "name": "厦门湖里万达店", "extend_code": { "comm_shop_id": "a2481a3a22494022a2425896fb4002f3", "alipay_id": "2019122000077000000085656944", "us_id": "45549", "comm_code": "301003400004806", "upcard_terminal": "59204819", "upcard_mer_id": "102592058120541", "ex_cost_center_code": "1200845549" } }, { "_id": "4202675140379578369", "name": "鄂州新亚太国际店", "extend_code": { "comm_shop_id": "f8622fec00224cedab85596e1d55c3eb", "us_id": "45529", "comm_code": "301003400004809", "upcard_terminal": "71150020", "upcard_mer_id": "102711089990013", "ex_cost_center_code": "1200845529" } }, { "_id": "4207713452165398529", "name": "合肥万科店", "extend_code": { "comm_shop_id": "432b5dedfadb4a4da14d8fb4649c5ef5", "alipay_id": "2019051500077000000077394467", "us_id": "45556", "comm_code": "301003400004821", "upcard_terminal": "55131871", "upcard_mer_id": "102551089993874", "ex_cost_center_code": "1200845556" } }, { "_id": "4208132735067004929", "name": "合肥肥东吾悦店", "extend_code": { "comm_shop_id": "eb09f8b90bea41f498f17307e00c52ab", "alipay_id": "2019101800077000000083653837", "us_id": "45563", "upcard_terminal": "55131872", "upcard_mer_id": "102551089993875", "ex_cost_center_code": "1200845563" } }, { "_id": "4208926120304644097", "name": "新昌世贸店", "extend_code": { "comm_shop_id": "24c60da1e67f44a89c4bbd86d136d9d0", "alipay_id": "2019122500077000000085760325", "us_id": "45574", "comm_code": "301003400004816", "upcard_terminal": "57501409", "upcard_mer_id": "102575089990178", "ex_cost_center_code": "1200845574" } }, { "_id": "4208931230917259265", "name": "苏州龙湖狮山天街店", "extend_code": { "comm_shop_id": "19cc8b7ad28741b1b9f5c97fb6872435", "alipay_id": "2019062700077000000079582295", "us_id": "45570", "comm_code": "301003400004813", "upcard_terminal": "51217487", "upcard_mer_id": "102512089993326", "ex_cost_center_code": "1200845570" } }, { "_id": "4211050697250721793", "name": "青浦万达茂店", "extend_code": { "comm_shop_id": "88ce89b4670442a69be9694cdaea5f5f", "ex_code": "45569", "alipay_id": "2019101400077000000083562898", "us_id": "45569", "comm_code": "301003400004804", "upcard_terminal": "02199659", "upcard_mer_id": "102210089998554", "ex_cost_center_code": "1200045569" } }, { "_id": "4213219671288963073", "name": "南京华采天地店", "extend_code": { "comm_shop_id": "49786b9de04c4609a1250c2b5983f9f8", "alipay_id": "2019111900077000000084756998", "us_id": "45581", "comm_code": "301003400004823", "upcard_terminal": "02583214", "upcard_mer_id": "102250089993932", "ex_cost_center_code": "1200845581" } }, { "_id": "4214312227799261185", "name": "郑州木色店", "extend_code": { "comm_shop_id": "011b00773e9f48b28c9dc30e04552c00", "alipay_id": "2019061000077000000078946814", "us_id": "45588", "comm_code": "301003400004810", "upcard_terminal": "37114329", "upcard_mer_id": "102371089992891", "ex_cost_center_code": "1200845588" } }, { "_id": "4216038488840843265", "name": "苏州吴江华润万象汇店", "extend_code": { "comm_shop_id": "0680c7a030a94c8b8b143b8c7bb0b27d", "alipay_id": "2019092600077000000082997803", "us_id": "45571", "comm_code": "301003400004811", "upcard_terminal": "51217498", "upcard_mer_id": "102512089993329", "ex_cost_center_code": "1200845571" } }, { "_id": "4217975891788771329", "name": "杭州金沙印象城店", "extend_code": { "comm_shop_id": "7149d86affc24cb992070e0924c13972", "alipay_id": "2019122500077000000085765655", "us_id": "45591", "comm_code": "301003400004827", "upcard_terminal": "57113808", "upcard_mer_id": "102571089993135", "ex_cost_center_code": "1200845591" } }, { "_id": "4220455818191876097", "name": "南昌王府井购物中心店", "extend_code": { "comm_shop_id": "f28cff788b534c4d94338b32c1df3685", "alipay_id": "2019070800077000000080192207", "us_id": "45593", "comm_code": "301003400004842", "upcard_terminal": "07950002", "upcard_mer_id": "102791058220742", "ex_cost_center_code": "1200845593" } }, { "_id": "4223316429929222145", "name": "济南印象城店", "extend_code": { "comm_shop_id": "b4edd73222b949cdbfe6f7dd0f5a757b", "alipay_id": "2019062500077000000079456854", "us_id": "45600", "comm_code": "301003400004833", "upcard_terminal": "53101650", "upcard_mer_id": "102531089990654", "ex_cost_center_code": "1200845600" } }, { "_id": "4224486993269325825", "name": "七宝万科店", "extend_code": { "comm_shop_id": "f03f26abd5bf4150a9255d10db43a709", "alipay_id": "2019101400077000000083561582", "us_id": "45604", "comm_code": "301003400004808", "upcard_terminal": "02108095", "upcard_mer_id": "102210058228754", "ex_cost_center_code": "1200045604" } }, { "_id": "4224494527853682689", "name": "贵州凯里国贸店", "extend_code": { "comm_shop_id": "ab1a856f45d742d7939f891296627105", "alipay_id": "2019121900077000000085649238", "us_id": "45606", "upcard_terminal": "85590017", "upcard_mer_id": "102855089990017", "ex_cost_center_code": "1200045606" } }, { "_id": "4225931375332503553", "name": "广州云门new park店", "extend_code": { "comm_shop_id": "6ae7a0d27c014bac985cb4f2beb36989", "alipay_id": "2019080800077000000081078204", "us_id": "45603", "comm_code": "301003400004826", "upcard_terminal": "02082894", "upcard_mer_id": "102200089991106", "ex_cost_center_code": "1200045603" } }, { "_id": "4225933325107351553", "name": "海门龙信广场店", "extend_code": { "comm_shop_id": "15ea2aa2a3934a878753fe5e9bd26266", "alipay_id": "2019061700077000000079152148", "us_id": "45599", "comm_code": "301003400004812", "upcard_terminal": "51301450", "upcard_mer_id": "102513089990264", "ex_cost_center_code": "1200845599" } }, { "_id": "4225934705314746369", "name": "洛阳泉舜店", "extend_code": { "comm_shop_id": "3a4fcdc2d3ac435da5fd05f1940ae088", "alipay_id": "2019061000077000000078945191", "us_id": "45611", "comm_code": "301003400004819", "upcard_terminal": "37902017", "upcard_mer_id": "102379089990513", "ex_cost_center_code": "1200845611" } }, { "_id": "4228822079782264832", "name": "杭州余杭万达店", "extend_code": { "comm_shop_id": "c1c0427fde174a27bb5f243d5162cc8c", "alipay_id": "2019091600077000000082640203", "us_id": "45615", "upcard_terminal": "57114077", "upcard_mer_id": "102571089993146", "ex_cost_center_code": "1200845615" } }, { "_id": "4230971390993371136", "name": "成都温江新尚天地店", "extend_code": { "comm_shop_id": "1eaa4bd0ceb94d819700e70a384daa14", "alipay_id": "2019071500077000000080410984", "us_id": "45629", "comm_code": "301003400004815", "upcard_terminal": "02829701", "upcard_mer_id": "102280089996659", "ex_cost_center_code": "1200845629" } }, { "_id": "4230973845076447232", "name": "武汉人信汇店", "extend_code": { "comm_shop_id": "6a6516e63fa34459b5e6464e21a99d88", "alipay_id": "2019072200077000000080601687", "us_id": "45627", "comm_code": "301003400004824", "upcard_terminal": "02731111", "upcard_mer_id": "102270089995588", "ex_cost_center_code": "1200845627" } }, { "_id": "4230976043718021120", "name": "滨海县海悦城店", "extend_code": { "comm_shop_id": "41d35065507444f081fd508b4e24509c", "us_id": "45614", "comm_code": "301003400004820", "upcard_terminal": "51501044", "upcard_mer_id": "102515089990487", "ex_cost_center_code": "1200845614" } }, { "_id": "4233186903303655424", "name": "重庆来福士店", "extend_code": { "comm_shop_id": "d1e5ef83b0fe4b36b9f35a941f348391", "alipay_id": "2019091200077000000082537399", "us_id": "45605", "upcard_terminal": "02310097", "upcard_mer_id": "102230089992578", "ex_cost_center_code": "1200045605" } }, { "_id": "4233433928653869056", "name": "常熟永旺梦乐城店", "extend_code": { "comm_shop_id": "1d64812f8616417bbe0311eb443eea53", "alipay_id": "2019070200077000000079858871", "us_id": "45613", "comm_code": "301003400004814", "upcard_terminal": "51217547", "upcard_mer_id": "102512089993340", "ex_cost_center_code": "1200845613" } }, { "_id": "4233443346170777600", "name": "无锡融创茂店", "extend_code": { "comm_shop_id": "48f2ad7d5c464129b887d35516d518fd", "alipay_id": "2019062700077000000079578463", "us_id": "45630", "comm_code": "301003400004822", "upcard_terminal": "51004304", "upcard_mer_id": "102510089993828", "ex_cost_center_code": "1200845630" } }, { "_id": "4235704935947177984", "name": "深圳金光华店", "extend_code": { "us_id": "45633", "upcard_mer_id": "102755089994224", "ex_cost_center_code": "1200045633", "comm_shop_id": "df117370e97247708e30491a795beac2", "upcard_terminal": "75520555" } }, { "_id": "4238199221091569664", "name": "京东", "extend_code": { "us_id": "45406", "ex_cost_center_code": "1200045406", "comm_shop_id": "42" } }, { "_id": "4238265115767476224", "name": "淮安吾悦广场店", "extend_code": { "comm_shop_id": "9feb5c06645c44bcb886ccb4b909dc20", "alipay_id": "2019091200077000000082536132", "us_id": "45635", "upcard_terminal": "51701460", "upcard_mer_id": "102517089990103", "ex_cost_center_code": "1200845635" } }, { "_id": "4241179079203622912", "name": "宁波杭州湾世纪金源店", "extend_code": { "comm_shop_id": "1b9ca6ce5c5842a48ea16c7287ffad47", "alipay_id": "2019080200077000000080895579", "us_id": "45655", "upcard_terminal": "57404985", "upcard_mer_id": "102574089990707", "ex_cost_center_code": "1200845655" } }, { "_id": "4241185397750632448", "name": "巩义德丰香榭里店", "extend_code": { "comm_shop_id": "867881346d864613b2befbdbc0f4b0d5", "alipay_id": "2020032400077000000092589564", "us_id": "45634", "upcard_terminal": "37114418", "upcard_mer_id": "102371089992921", "ex_cost_center_code": "1200845634" } }, { "_id": "4243303888272236544", "name": "苏州新区永旺店", "extend_code": { "comm_shop_id": "8ec3fe99dd15435e94af6327a067c221", "alipay_id": "2019101400077000000083561589", "us_id": "45659", "upcard_terminal": "51217552", "upcard_mer_id": "102512089993346", "ex_cost_center_code": "1200845659" } }, { "_id": "4244779874385936384", "name": "南通如东欧尚店", "extend_code": { "comm_shop_id": "d70a399743894c7698a84052efd5103b", "alipay_id": "2019103000077000000084080875", "us_id": "45645", "upcard_terminal": "51301455", "upcard_mer_id": "102513089990267", "ex_cost_center_code": "1200845645" } }, { "_id": "4244786433493057536", "name": "徐州三胞国际广场店", "extend_code": { "comm_shop_id": "78fb94bb9ac94377b010652caa87f775", "alipay_id": "2019082900077000000081987572", "us_id": "45661", "upcard_terminal": "51601718", "upcard_mer_id": "102516089990292", "ex_cost_center_code": "1200845661" } }, { "_id": "4246917558256549888", "name": "太原公园时代店", "extend_code": { "us_id": "45669", "upcard_mer_id": "102351089992037", "ex_cost_center_code": "1200845669", "comm_shop_id": "0d9ae84e5e50498da294231655cfc363", "upcard_terminal": "35104673" } }, { "_id": "4248412012570230784", "name": "平湖南河头店", "extend_code": { "comm_shop_id": "8ebd653b9e4e4f54850af35cddffe842", "alipay_id": "2019123100077000000085897658", "us_id": "45668", "upcard_terminal": "57304200", "upcard_mer_id": "102573058220211", "ex_cost_center_code": "1200845668" } }, { "_id": "4253546321522200576", "name": "蛋糕仓配", "extend_code": { "us_id": "40001", "ex_id": "40001", "ex_code": "40001", "ex_cost_center_code": "1200040001" } }, { "_id": "4253847668826050560", "name": "临沂万象汇店", "extend_code": { "comm_shop_id": "55f49e0165b54ee1ad02f3491505c9d0", "ex_code": "45676", "alipay_id": "2020042200077000000093741372", "us_id": "45676", "upcard_terminal": "53952418", "upcard_mer_id": "102539089990459", "ex_id": "45676", "ex_cost_center_code": "1200845676" } }, { "_id": "4253850283970400257", "name": "临沂万达店", "extend_code": { "comm_shop_id": "0db049f6ad1b4b1d9d59308c6a2b6a78", "ex_code": "45675", "alipay_id": "2020042200077000000093739953", "us_id": "45675", "upcard_terminal": "53952417", "upcard_mer_id": "102539089990458", "ex_id": "45675", "ex_cost_center_code": "1200845675" } }, { "_id": "4253851784402976768", "name": "连云港赣榆吾悦广场店", "extend_code": { "comm_shop_id": "fc1f7551d37d4fa3a8956d73dcfafff7", "ex_code": "45677", "alipay_id": "2019121600077000000085554033", "us_id": "45677", "upcard_terminal": "51800798", "upcard_mer_id": "102518089990095", "ex_id": "45677", "ex_cost_center_code": "1200845677" } }, { "_id": "4256991223148974080", "name": "合肥万象汇店", "extend_code": { "comm_shop_id": "6b5bc066f2784877a4a4abd7fece87c2", "ex_code": "", "alipay_id": "2020042300077000000093779511", "us_id": "45681", "upcard_terminal": "55132218", "upcard_mer_id": "102551089993923", "ex_cost_center_code": "1200845681" } }, { "_id": "4256996464334475264", "name": "西安正荣彩虹谷店", "extend_code": { "comm_shop_id": "e3ea958951034c0d88c720afbe743beb", "alipay_id": "2019092700077000000083077258", "us_id": "45674", "upcard_terminal": "02907294", "upcard_mer_id": "102290089993361", "ex_cost_center_code": "1200845674" } }, { "_id": "4258552441118658560", "name": "濮阳恒丰店", "extend_code": { "comm_shop_id": "ba472111360848c29749af9af50cb2b8", "alipay_id": "2019111800077000000084701157", "us_id": "45685", "upcard_terminal": "39301050", "upcard_mer_id": " 102393089990032", "ex_cost_center_code": "1200845685" } }, { "_id": "4258555715762786304", "name": "武汉凯德西城店", "extend_code": { "comm_shop_id": "b3643764e7d54040af481ad92be8308d", "alipay_id": "2019091000077000000082470265", "us_id": "45693", "upcard_terminal": "02731326", "upcard_mer_id": "102270089995776", "ex_cost_center_code": "1200845693" } }, { "_id": "4258560512280760320", "name": "洛阳万达店", "extend_code": { "comm_shop_id": "50cb236ab8764882ac54d0e4c46e83a6", "alipay_id": "2019091000077000000082473368", "us_id": "45698", "upcard_terminal": "37902018", "upcard_mer_id": "102379089990514", "ex_cost_center_code": "1200845698" } }, { "_id": "4258812682901131264", "name": "广州百脑汇店", "extend_code": { "comm_shop_id": "a3d504ee159442ce946cea5af7dd7e51", "alipay_id": "2019100900077000000083379296", "us_id": "45699", "upcard_terminal": "02083949", "upcard_mer_id": "102200089991152", "ex_cost_center_code": "1200845699" } }, { "_id": "4258875212885397504", "name": "西双版纳王府广场店", "extend_code": { "comm_shop_id": "897d356ef46e4f16ac7581658b09328e", "alipay_id": "2019121900077000000085649236", "us_id": "45701", "upcard_terminal": "69100030", "upcard_mer_id": "102691089990126", "ex_cost_center_code": "1200845701" } }, { "_id": "4261110271038197760", "name": "广汉百伦店", "extend_code": { "us_id": "45700", "upcard_mer_id": "102838089990117", "ex_cost_center_code": "1200845700", "comm_shop_id": "0594619f605b4cdfafb079991e4f5575", "upcard_terminal": "83890645" } }, { "_id": "4261341418020147200", "name": "西安西咸吾悦店", "extend_code": { "comm_shop_id": "c79de7a4b76742598ea4e93251d8dd9f", "alipay_id": "2019120200077000000085147972", "us_id": "45687", "upcard_terminal": "02907304", "upcard_mer_id": "102290089993366", "ex_cost_center_code": "1200845687" } }, { "_id": "4262192023844425728", "name": "昆明瑞鼎城店", "extend_code": { "comm_shop_id": "16d770df66ac41d8afa2f6a7c1b201a8", "alipay_id": "2019121900077000000085603174", "us_id": "45712", "upcard_terminal": "87113853", "upcard_mer_id": "102871089996988", "ex_cost_center_code": "1200845712" } }, { "_id": "4264698043607027712", "name": "淮安茂业天地店", "extend_code": { "comm_shop_id": "d8cc5affb2b049c780b803b36751b789", "alipay_id": "2020062400077000000095670713", "us_id": "45717", "upcard_terminal": "51701461", "upcard_mer_id": "102517089990104", "ex_cost_center_code": "1200845717" } }, { "_id": "4264699648242880512", "name": "常州金坛新天地店", "extend_code": { "comm_shop_id": "f0a46195e4d649b79526d58a75e170a4", "alipay_id": "2019110600077000000084412677", "us_id": "45686", "upcard_terminal": "51902140", "upcard_mer_id": "102519089990239", "ex_cost_center_code": "1200845686" } }, { "_id": "4264701090664026112", "name": "沭阳雨润中央商场店", "extend_code": { "comm_shop_id": "288f3180114f4288a0137e8e7bdc62ec", "alipay_id": "2019111800077000000084702855", "us_id": "45716", "upcard_terminal": "52701928", "upcard_mer_id": "102527089990314", "ex_cost_center_code": "1200845716" } }, { "_id": "4266445588981092352", "name": "南京黄栗墅南服务区店", "extend_code": { "us_id": "45720", "upcard_mer_id": "102250089993999", "ex_cost_center_code": "1200845720", "comm_shop_id": "6fa657b1abe84859a6b50a91313a2777", "upcard_terminal": "02584500" } }, { "_id": "4267164412483211264", "name": "扬州宝应吾悦店", "extend_code": { "comm_shop_id": "9a6633812bff45ddad0ce12c3b4809ee", "alipay_id": "2019103000077000000084077898", "us_id": "45715", "upcard_terminal": "51401746", "upcard_mer_id": "102514089990353", "ex_cost_center_code": "1200845715" } }, { "_id": "4267167954568744960", "name": "聊城万达店", "extend_code": { "comm_shop_id": "f4b4363a629c416c94cd7da21ab5a60d", "alipay_id": "2020041300077000000093511665", "us_id": "45722", "upcard_terminal": "63500060", "upcard_mer_id": "102635089990030", "ex_cost_center_code": "1200845722" } }, { "_id": "4267169396348162048", "name": "济南万象城店", "extend_code": { "comm_shop_id": "e22611ab85014076b2c8bc3c941b5017", "alipay_id": "2020033100077000000092776087", "us_id": "45708", "upcard_terminal": "53101688", "upcard_mer_id": "102531089990659", "ex_cost_center_code": "1200845708" } }, { "_id": "4268712347750633472", "name": "济南东北服务区店", "extend_code": { "us_id": "45728", "upcard_mer_id": "102531089990660", "ex_cost_center_code": "1200845728", "comm_shop_id": "04f01b8a735d4df19974ba2d39505eab", "upcard_terminal": "53101689" } }, { "_id": "4268713828314779648", "name": "济南东南服务区店", "extend_code": { "us_id": "45729", "upcard_mer_id": "102531089990661", "ex_cost_center_code": "1200845729", "comm_shop_id": "440827dff5b74627b4dc3b2f9e42cb6d", "upcard_terminal": "53101690" } }, { "_id": "4271978999430778880", "name": "泰州姜堰时代店", "extend_code": { "comm_shop_id": "97971c6742d345778cb658cbcd408987", "alipay_id": "2019103000077000000084077899", "us_id": "45727", "upcard_terminal": "52301029", "upcard_mer_id": "102523089990144", "ex_cost_center_code": "1200845727" } }, { "_id": "4273761756603486208", "name": "常州天宁吾悦店", "extend_code": { "comm_shop_id": "1e95bc36c52b42d189fe3a88d9ad5d96", "alipay_id": "2019110600077000000084405309", "us_id": "45731", "upcard_terminal": "51902145", "upcard_mer_id": "102519089990242", "ex_cost_center_code": "1200845731" } }, { "_id": "4274857481202569216", "name": "青岛凯德茂店", "extend_code": { "comm_shop_id": "118c3f45848149be8ec043d7f9af7ebc", "alipay_id": "2020010700077000000086341666", "us_id": "45732", "upcard_terminal": "53206492", "upcard_mer_id": "102532089991555", "ex_cost_center_code": "1200845732" } }, { "_id": "4275957033708032000", "name": "随州万达店", "extend_code": { "us_id": "45750", "upcard_mer_id": "102722089990020", "ex_cost_center_code": "1200845750", "comm_shop_id": "8074dd7b59b64bfbb9874412fcef14f5", "upcard_terminal": "72200125" } }, { "_id": "4275958556798226432", "name": "福州长乐万星店", "extend_code": { "comm_shop_id": "0f97dba5df384d2a96bc1c1b805cb2dc", "alipay_id": "2019111100077000000084532014", "us_id": "45754", "upcard_terminal": "59113831", "upcard_mer_id": "102591089990674", "ex_cost_center_code": "1200845754" } }, { "_id": "4275959968726781952", "name": "郑州航海路丹尼斯店", "extend_code": { "comm_shop_id": "8f0ed18592774651adc1af126b638fce", "alipay_id": "2020032400077000000092599667", "us_id": "45746", "upcard_terminal": "37114444", "upcard_mer_id": "102371089992999", "ex_cost_center_code": "1200845746" } }, { "_id": "4275961306562957312", "name": "吉安天虹二店", "extend_code": { "comm_shop_id": "28a08582c9d9497ea7cb91d0d1c7e81a", "alipay_id": "2020032400077000000092589565", "us_id": "45748", "upcard_terminal": "79600974", "upcard_mer_id": "102796089990046", "ex_cost_center_code": "1200845748" } }, { "_id": "4276282522205163520", "name": "佛山金沙洲金铂天地店", "extend_code": { "comm_shop_id": "c1fc75ebb8f04c2685dce5aca95a90c8", "alipay_id": "2019112700077000000085023649", "us_id": "45747", "upcard_terminal": "75703882", "upcard_mer_id": "102757089990665", "ex_cost_center_code": "1200045747" } }, { "_id": "4281387215881244672", "name": "杭州西溪龙湖天街店", "extend_code": { "comm_shop_id": "0e850b6dcc6340aba832e0c29eca5ca6", "alipay_id": "2019121900077000000085649237", "us_id": "45760", "upcard_terminal": "57114976", "upcard_mer_id": "102571089993201", "ex_cost_center_code": "1200845760" } }, { "_id": "4284187678389309440", "name": "庆阳东方丽晶MALL店", "extend_code": { "comm_shop_id": "eb68266041f447b9a4b203c6c5932421", "alipay_id": "2020042100077000000093732010", "us_id": "45776", "upcard_terminal": "93400018", "upcard_mer_id": "102934089990015", "ex_cost_center_code": "1200045776" } }, { "_id": "4285358875844022272", "name": "滕州万达店", "extend_code": { "comm_shop_id": "f222647e4075496db2916c0f48f28d2a", "alipay_id": "2019123000077000000085880428", "us_id": "45752", "upcard_terminal": "63200099", "upcard_mer_id": "102632089990034", "ex_cost_center_code": "1200845752" } }, { "_id": "4285360871560974336", "name": "郑州机场南中心店", "extend_code": { "comm_shop_id": "13a3f9e5a578462d9b4f5ce51740b9f4", "company_code": "", "us_id": "45694", "upcard_terminal": "97100417", "upcard_mer_id": "102971089990249", "ex_cost_center_code": "1200845694" } }, { "_id": "4285362435658878976", "name": "杭州博雅城店", "extend_code": { "comm_shop_id": "572f84cf71044ff0a437a2a9500afae1", "alipay_id": "2020010700077000000086343469", "us_id": "45778", "upcard_terminal": "57114977", "upcard_mer_id": "102571089993202", "ex_cost_center_code": "1200845778" } }, { "_id": "4285363821876350976", "name": "汉中吾悦店", "extend_code": { "comm_shop_id": "91d85d3d4d4a44218bd43a84ee61886f", "alipay_id": "2019120200077000000085123092", "us_id": "45777", "upcard_terminal": "91600102", "upcard_mer_id": "102916089990019", "ex_cost_center_code": "1200845777" } }, { "_id": "4287529483126181888", "name": "徐州丰县欢乐城店", "extend_code": { "comm_shop_id": "90fc24179f6c463d9c4dd26b22e87b3c", "alipay_id": "2019121900077000000085651239", "us_id": "45781", "upcard_terminal": "51601817", "upcard_mer_id": "102516089990307", "ex_cost_center_code": "1200845781" } }, { "_id": "4287531202274922496", "name": "青岛黄岛永旺店", "extend_code": { "comm_shop_id": "e9bf736f060f48bfbd080d5cc8b0ce74", "alipay_id": "2019121900077000000085651238", "us_id": "45765", "upcard_terminal": "53206502", "upcard_mer_id": "102532089991646", "ex_cost_center_code": "1200845765" } }, { "_id": "4287532561766289408", "name": "上海浦江万达店", "extend_code": { "comm_shop_id": "6e183f3df42441c4aa161a95de6e6923", "alipay_id": "2020033000077000000092775681", "us_id": "45780", "upcard_terminal": "02109461", "upcard_mer_id": "102210089999228", "ex_cost_center_code": "1200845780" } }, { "_id": "4287533562703384576", "name": "银川大阅城店", "extend_code": { "comm_shop_id": "e370315435bf40beac855ea8ef2689de", "alipay_id": "2020010700077000000086341665", "us_id": "45785", "upcard_terminal": "95102588", "upcard_mer_id": "102951089991004", "ex_cost_center_code": "1200045785" } }, { "_id": "4289350741081985024", "name": "重庆江北机场T2A店", "extend_code": { "us_id": "45788", "upcard_mer_id": "102230089992761", "ex_cost_center_code": "1200845788", "comm_shop_id": "b803f6fa06fc4def9fce6e9644c7a68b", "upcard_terminal": "02311529" } }, { "_id": "4289352218714312704", "name": "重庆江北机场T2B店", "extend_code": { "us_id": "45789", "upcard_mer_id": "102230089992762", "ex_cost_center_code": "1200845789", "comm_shop_id": "8923a69f2d64470c85d6781dc0728a90", "upcard_terminal": "02311530" } }, { "_id": "4289354905203773440", "name": "桂林东西巷店", "extend_code": { "comm_shop_id": "0e3abddfbe5d452281c2caeba1c3956a", "alipay_id": "2020010700077000000086344667", "us_id": "45758", "upcard_terminal": "77301673", "upcard_mer_id": "102773089990524", "ex_cost_center_code": "1200845758" } }, { "_id": "4289357921629769728", "name": "连云港海州吾悦店", "extend_code": { "comm_shop_id": "e41d3d9e0bc04874a54b65aa6c8a7485", "alipay_id": "2019121900077000000085652439", "us_id": "45753", "upcard_terminal": "51800803", "upcard_mer_id": "102518089990100", "ex_cost_center_code": "1200845753" } }, { "_id": "4290405516382896128", "name": "上海复地活力城店", "extend_code": { "comm_shop_id": "8ef9300090fb4776afd887b4f8821da2", "alipay_id": "2020042100077000000093730699", "us_id": "45787", "upcard_terminal": "02109687", "upcard_mer_id": "102210089999245", "ex_cost_center_code": "1200845787" } }, { "_id": "4290406980945739776", "name": "上海剑川路龙湖店", "extend_code": { "comm_shop_id": "cbf4b55dfb1b4606907c5351ccf3003d", "alipay_id": "2019123100077000000086162353", "us_id": "45793", "upcard_terminal": "02109688", "upcard_mer_id": "102210089999246", "ex_cost_center_code": "1200845793" } }, { "_id": "4290408081153622016", "name": "南京南站店", "extend_code": { "us_id": "45795", "upcard_mer_id": "102250089994037", "ex_cost_center_code": "1200845795", "comm_shop_id": "c730c8c6676049ab9e89e62e529c70ee", "upcard_terminal": "02585099" } }, { "_id": "4292610335877169152", "name": "泉州浦西万达店", "extend_code": { "comm_shop_id": "99ab76ad555840cca70b76abf721c22d", "alipay_id": "2019122500077000000085760324", "us_id": "45799", "upcard_terminal": "59501753", "upcard_mer_id": "102595089990342", "ex_cost_center_code": "1200045799" } }, { "_id": "4292612759085940736", "name": "杭州大悦城店", "extend_code": { "comm_shop_id": "38a0c10de8304574ab449f5ff314ca20", "alipay_id": "2020010700077000000086343470", "us_id": "45798", "upcard_terminal": "57115185", "upcard_mer_id": "102571089993213", "ex_cost_center_code": "1200845798" } }, { "_id": "4292613943221878784", "name": "郑州中牟天泽城店", "extend_code": { "comm_shop_id": "9d8bd2e5981142c38a48db0df2853d01", "alipay_id": "2020051800077000000094408977", "us_id": "45797", "upcard_terminal": "37114494", "upcard_mer_id": "102371089993007", "ex_cost_center_code": "1200845797" } }, { "_id": "4292615657425502208", "name": "淮安楚州万达店", "extend_code": { "comm_shop_id": "b1169e3cb5654743b5a5a0075f1a4868", "alipay_id": "2020062400077000000095661413", "us_id": "45805", "upcard_terminal": "51701473", "upcard_mer_id": "102517089990112", "ex_cost_center_code": "1200845805" } }, { "_id": "4295431863522066432", "name": "苏州盛泽碧桂园店", "extend_code": { "comm_shop_id": "c8c1039e9f8f4958a7b78e1775b410f3", "alipay_id": "2020101900077000000007345883", "us_id": "45796", "upcard_terminal": "51217652", "upcard_mer_id": "102512089993393", "ex_cost_center_code": "1200845796" } }, { "_id": "4295433169955487744", "name": "怀化万达店", "extend_code": { "us_id": "45804", "upcard_mer_id": "102745089990056", "ex_cost_center_code": "1200845804", "comm_shop_id": "6c12ae4990174ab8889211ccd7890dac", "upcard_terminal": "74501336" } }, { "_id": "4295434461952114688", "name": "如皋吾悦店", "extend_code": { "comm_shop_id": "509ec681fe124c0a926c292947ef9931", "alipay_id": "2020040300077000000092869011", "us_id": "45792", "upcard_terminal": "51301460", "upcard_mer_id": "102513089990276", "ex_cost_center_code": "1200845792" } }, { "_id": "4296602450353225728", "name": "郑州万锦城店", "extend_code": { "comm_shop_id": "923f6533e6d448b3a4e4ccc2bf385995", "alipay_id": "2020011500077000000086882010", "us_id": "45810", "upcard_terminal": "37114496", "upcard_mer_id": "102371089993009", "ex_cost_center_code": "1200845810" } }, { "_id": "4296604174614822913", "name": "扬州东关街店", "extend_code": { "us_id": "45803", "upcard_mer_id": "102514089990365", "ex_cost_center_code": "1200845803", "comm_shop_id": "8e965260c44e4c94b07c87ef1ffff891", "upcard_terminal": "51402002" } }, { "_id": "4296966128328015872", "name": "泰安爱琴海店", "extend_code": { "us_id": "45809", "upcard_mer_id": "102538089990572", "ex_cost_center_code": "1200845809", "comm_shop_id": "44ef870247524135bf01862a8188e385", "upcard_terminal": "53800667" } }, { "_id": "4296967508887371776", "name": "合肥北城万达店", "extend_code": { "comm_shop_id": "b19295d6e3e741babe05665ee1206e2b", "alipay_id": "2020030900077000000092243223", "us_id": "45812", "upcard_terminal": "55132404", "upcard_mer_id": "102551089993954", "ex_cost_center_code": "1200845812" } }, { "_id": "4297230402816344064", "name": "濮阳万达店", "extend_code": { "comm_shop_id": "6b7c3c1d42b84d0ba9f9be2bd2cb8297", "alipay_id": "2020011500077000000086880218", "us_id": "45816", "upcard_terminal": "39301051", "upcard_mer_id": "102393089990039", "ex_cost_center_code": "1200845816" } }, { "_id": "4297607682621243392", "name": "高邮吾悦店", "extend_code": { "comm_shop_id": "361f6bb508eb445cae9d86b0317690df", "alipay_id": "2020011600077000000087239442", "us_id": "45811", "upcard_terminal": "51402003", "upcard_mer_id": "102514089990366", "ex_cost_center_code": "1200845811" } }, { "_id": "4300231256288854016", "name": "郑州瀚海海尚店", "extend_code": { "comm_shop_id": "b298064c907c4529961650046054dc4f", "alipay_id": "2020032400077000000092589566", "us_id": "45817", "upcard_terminal": "37114577", "upcard_mer_id": "102371089993013", "ex_cost_center_code": "1200845817" } }, { "_id": "4300232608515653632", "name": "南京六合龙湖天街店", "extend_code": { "comm_shop_id": "81bb605227f643e39d4dc59522c3133a", "alipay_id": "2020030200077000000092103141", "us_id": "45800", "upcard_terminal": "02585220", "upcard_mer_id": "102250089994048", "ex_cost_center_code": "1200845800" } }, { "_id": "4300234219631738880", "name": "孝感服务区北区店", "extend_code": { "us_id": "45825", "upcard_mer_id": "102712089990426", "ex_cost_center_code": "1200845825", "comm_shop_id": "d81aa83ab0a041a1a2810daccdb4c1a0", "upcard_terminal": "71200082" } }, { "_id": "4300492797798023168", "name": "西安大雁塔东街店", "extend_code": { "us_id": "45826", "upcard_mer_id": "102290089993400", "ex_cost_center_code": "1200845826", "comm_shop_id": "333b14c53ecb4cf0a72dd31afe41c34c", "upcard_terminal": "02910257" } }, { "_id": "4302053469753212928", "name": "南浔服务区北区店", "extend_code": { "comm_shop_id": "b9d0a67a4667459fa1f2545a7e7934c2", "us_id": "45801", "upcard_terminal": "57297325", "upcard_mer_id": "102572089990094", "ex_id": "45801", "ex_cost_center_code": "1200845801" } }, { "_id": "4302055864797265920", "name": "阜阳临泉丰泽悦城店", "extend_code": { "comm_shop_id": "e48cd774aeaa4387afcdf106d95e9e79", "alipay_id": "2020031200077000000092343792", "us_id": "45832", "upcard_terminal": "55802185", "upcard_mer_id": "102558089990754", "ex_cost_center_code": "1200845832" } }, { "_id": "4302799970209136640", "name": "盐城新弄里店", "extend_code": { "comm_shop_id": "cb462629eb3b40c1a6431271373285a8", "alipay_id": "2020030200077000000092101862", "us_id": "45828", "upcard_terminal": "51501055", "upcard_mer_id": "102515089990495", "ex_cost_center_code": "1200845828" } }, { "_id": "4303117755711782912", "name": "太仓沙溪北服务区店", "extend_code": { "us_id": "45840", "upcard_mer_id": "102512089993395", "ex_cost_center_code": "1200845840", "comm_shop_id": "ee5e8556f2e14a87a15dd7d00aab1e18", "upcard_terminal": "51217661" } }, { "_id": "4303124525293305856", "name": "西安立丰城市生活广场店", "extend_code": { "us_id": "45844", "upcard_mer_id": "102290089993402", "ex_cost_center_code": "1200845844", "comm_shop_id": "6eb32203fe3e4ea9923645a017035926", "upcard_terminal": "02910259" } }, { "_id": "4303125910155984896", "name": "西安万和城店", "extend_code": { "comm_shop_id": "610e1c15d9e84e4b9f668599fd83ec4d", "alipay_id": "2020010700077000000086338363", "us_id": "45845", "upcard_terminal": "02910258", "upcard_mer_id": "102290089993401", "ex_cost_center_code": "1200845845" } }, { "_id": "4303129458742689792", "name": "无锡万象城店", "extend_code": { "comm_shop_id": "481c232ac84d42debbf7f14b6e413955", "alipay_id": "2019123100077000000085900209", "us_id": "45847", "upcard_terminal": "51004730", "upcard_mer_id": "102510089994210", "ex_cost_center_code": "1200845847" } }, { "_id": "4303131624928772096", "name": "桐乡吾悦店", "extend_code": { "comm_shop_id": "71070c319aa24e89a89805b97b22a70f", "alipay_id": "2020061600077000000095297669", "us_id": "45846", "upcard_terminal": "57304208", "upcard_mer_id": "102573089990217", "ex_cost_center_code": "1200845846" } }, { "_id": "4304888050655199232", "name": "济南恒隆店", "extend_code": { "comm_shop_id": "242d0a78e1c84f1684e8b258865c108d", "alipay_id": "2020040300077000000092873412", "us_id": "45851", "upcard_terminal": "53101700", "upcard_mer_id": "102531089990758", "ex_cost_center_code": "1200845851" } }, { "_id": "4307010121820569600", "name": "荆州监利宏泰店", "extend_code": { "us_id": "45866", "upcard_mer_id": "102716089990081", "ex_cost_center_code": "1200845866", "comm_shop_id": "00e75bba309f43d88325ee3ac4155284", "upcard_terminal": "71600283" } }, { "_id": "4307011575247568896", "name": "盐城吾悦店", "extend_code": { "comm_shop_id": "20fe63801986477e8dd4f8a100dd8909", "alipay_id": "2020033000077000000092775680", "us_id": "45870", "upcard_terminal": "51501062", "upcard_mer_id": "102515089990496", "ex_cost_center_code": "1200845870" } }, { "_id": "4307012786214436864", "name": "银川中海环宇天地店", "extend_code": { "us_id": "45867", "upcard_mer_id": "102951089991006", "ex_cost_center_code": "1200845867", "comm_shop_id": "3efd2abe38b9476c93d5f03287e4e5a9", "upcard_terminal": "95102619" } }, { "_id": "4307014746283999232", "name": "马鞍山含山县玉龙湖店", "extend_code": { "comm_shop_id": "1c2089204847429288d405f38dd63c14", "alipay_id": "2020041600077000000093600871", "us_id": "45865", "upcard_terminal": "55500588", "upcard_mer_id": "102555089990096", "ex_cost_center_code": "1200845865" } }, { "_id": "4307015917891551232", "name": "砀山万达店", "extend_code": { "comm_shop_id": "4bdaa1dd2ed14bcd9e6ae39998f0966c", "alipay_id": "2020031200077000000092343791", "us_id": "45873", "upcard_terminal": "55700481", "upcard_mer_id": "102557089990125", "ex_cost_center_code": "1200845873" } }, { "_id": "4307740354441936896", "name": "登封万佳中心城店", "extend_code": { "comm_shop_id": "e59ff61364ab403d8cb3ff53fe449cc7", "alipay_id": "2020123000077000000013302500", "us_id": "45872", "upcard_terminal": "37114623", "upcard_mer_id": "102371089993015", "ex_cost_center_code": "1200845872" } }, { "_id": "4348048881001463808", "name": "中山大信新都会店", "extend_code": { "comm_shop_id": "20d9415206cc47e8921e3ff2c288657b", "alipay_id": "2020071400077000000098797734", "us_id": "45903", "upcard_terminal": "76001565", "upcard_mer_id": "102760089990335", "ex_id": "45903", "ex_cost_center_code": "1200845903" } }, { "_id": "4348051545059819520", "name": "昆明世纪金源店", "extend_code": { "comm_shop_id": "a60c818ab1e24ce09a04d3755845045c", "ex_code": "45904", "alipay_id": "2020051800077000000094411123", "us_id": "45904", "upcard_terminal": "87113933", "upcard_mer_id": "102871089996997", "ex_cost_center_code": "1200845904" } }, { "_id": "4356411764739440640", "name": "重庆金沙龙湖天街店", "extend_code": { "comm_shop_id": "838b89a1888f436792e4a7c032143a66", "ex_code": "45909", "alipay_id": "2021010800077000000013636950", "us_id": "45909", "upcard_terminal": "02312136", "upcard_mer_id": "102230089992840", "ex_id": "45909", "ex_cost_center_code": "1200045909" } }, { "_id": "4357806338053570560", "name": "深圳深业上城店", "extend_code": { "comm_shop_id": "e2a8d2caf7b5421e886b85d56d4dc266", "ex_code": "45914", "alipay_id": "2020061600077000000095315239", "us_id": "45914", "upcard_terminal": "75524777", "upcard_mer_id": "102755089995666", "ex_id": "45914", "ex_cost_center_code": "1200845914" } }, { "_id": "4361446207728418816", "name": "兴义欢乐橙店", "extend_code": { "comm_shop_id": "7cab2eebcf0f47379ac6ae0a02622b00", "ex_code": "45916", "alipay_id": "2020061600077000000095297668", "us_id": "45916", "upcard_terminal": "85900106", "upcard_mer_id": "102859089990014", "ex_id": "45916", "ex_cost_center_code": "1200845916" } }, { "_id": "4361449197763887104", "name": "蒙自南湖荟店", "extend_code": { "comm_shop_id": "514c527a8b3a4a51a486f543993c29d1", "ex_code": "45918", "us_id": "45918", "upcard_terminal": "87300727", "upcard_mer_id": "102873089990422", "ex_id": "45918", "ex_cost_center_code": "1200845918" } }, { "_id": "4361451488617201664", "name": "贵阳花溪万科店", "extend_code": { "comm_shop_id": "b06e0299fbeb4a2088bc59c86081b330", "ex_code": "45919", "alipay_id": "2020062400077000000095669110", "us_id": "45919", "upcard_terminal": "85102849", "upcard_mer_id": "102851089990592", "ex_id": "45919", "ex_cost_center_code": "1200845919" } }, { "_id": "4361471575621435392", "name": "南通海安万达店", "extend_code": { "comm_shop_id": "ee8a6f4fa409420aae91d9679d3d109a", "ex_code": "45917", "alipay_id": "2020071400077000000098792965", "us_id": "45917", "upcard_terminal": "51301529", "upcard_mer_id": "102513089990282", "ex_id": "45917", "ex_cost_center_code": "1200845917" } }, { "_id": "4364025192370995200", "name": "兰州国芳杉杉奥特莱斯店", "extend_code": { "comm_shop_id": "f5318a0e90e84886a6b24681fa2ee3c2", "ex_code": "45910", "alipay_id": "2021110500077000000029761090", "us_id": "45910", "upcard_terminal": "93101318", "upcard_mer_id": "102931089990241", "ex_id": "45910", "ex_cost_center_code": "1200045910" } }, { "_id": "4365069702291062784", "name": "无锡锡东大润发店", "extend_code": { "comm_shop_id": "9b28b230f2f0414c8f569ef811e039cf", "ex_code": "45920", "alipay_id": "2020080600077000000099554197", "us_id": "45920", "upcard_terminal": "51005020", "upcard_mer_id": "102510089994349", "ex_id": "45920", "ex_cost_center_code": "1200845920" } }, { "_id": "4365071990074146816", "name": "深圳卓悦汇店", "extend_code": { "comm_shop_id": "f52e732532b24dac844f3108cdbe2d23", "ex_code": "45921", "alipay_id": "2020072700077000000099267864", "us_id": "45921", "upcard_terminal": "75524877", "upcard_mer_id": "102755089995750", "ex_id": "45921", "ex_cost_center_code": "1200045921" } }, { "_id": "4366496911824322560", "name": "西安高新大都荟店", "extend_code": { "comm_shop_id": "f9863c68d06543eb8bf9401fa5acd348", "ex_code": "45922", "alipay_id": "2020072400077000000099094919", "us_id": "45922", "upcard_terminal": "02910294", "upcard_mer_id": "102290089993420", "ex_id": "45922", "ex_cost_center_code": "1200845922" } }, { "_id": "4372965043023708160", "name": "南丰城店", "extend_code": { "comm_shop_id": "b815027097a0460fa12ce38b3f8d29e9", "ex_code": "45934", "alipay_id": "2020081300077000000001063214", "us_id": "45934", "upcard_terminal": "02112841", "upcard_mer_id": "102210089999379", "ex_id": "45934", "ex_cost_center_code": "1200045934" } }, { "_id": "4372967935851921408", "name": "渭南吾悦广场店", "extend_code": { "comm_shop_id": "e8d57395802c456a9ea2eee1e5069e66", "ex_code": "45925", "alipay_id": "2021062800077000000023581561", "us_id": "45925", "upcard_terminal": "91300372", "upcard_mer_id": "102913089990036", "ex_id": "45925", "ex_cost_center_code": "1200845925" } }, { "_id": "4372971656501592064", "name": "寿光万达店", "extend_code": { "comm_shop_id": "7db20711f5ea435ba4e5f14eb77d8183", "ex_code": "45931", "alipay_id": "2020081300077000000001063001", "us_id": "45931", "upcard_terminal": "53606374", "upcard_mer_id": "102536089990739", "ex_id": "45931", "ex_cost_center_code": "1200845931" } }, { "_id": "4372973901964148736", "name": "海口友谊阳光城店", "extend_code": { "comm_shop_id": "58022baff2704fe8b2f6ff714ee9b583", "ex_code": "45933", "alipay_id": "2020072900077000000099334097", "us_id": "45933", "upcard_terminal": "89801976", "upcard_mer_id": "102898089990638", "ex_id": "45933", "ex_cost_center_code": "1200845933" } }, { "_id": "4372975937875116032", "name": "三亚滨海世界店", "extend_code": { "comm_shop_id": "27705a81f7ed49ff93a9e4991e078000", "ex_code": "45911", "alipay_id": "2020081300077000000001063002", "us_id": "45911", "upcard_terminal": "89801977", "upcard_mer_id": "102898089990639", "ex_id": "45911", "ex_cost_center_code": "1200045911" } }, { "_id": "4376300270651506688", "name": "孝感服务区南区店", "extend_code": { "comm_shop_id": "7c63c7419147476aaa7e284aefca1c64", "ex_code": "45936", "us_id": "45936", "upcard_terminal": "71200083", "upcard_mer_id": "102712089990427", "ex_id": "45936", "ex_cost_center_code": "1200845936" } }, { "_id": "4376319295544688640", "name": "西安西咸万象城店", "extend_code": { "comm_shop_id": "5c655320468546fa8fe298bca1a93432", "ex_code": "45942", "alipay_id": "2020072700077000000099267865", "us_id": "45942", "upcard_terminal": "02910373", "upcard_mer_id": "102290089993425", "ex_id": "45942", "ex_cost_center_code": "1200845942" } }, { "_id": "4378520938667343872", "name": "太原国金中心店", "extend_code": { "comm_shop_id": "2d2f7a91468541778d73e2539a18625f", "ex_code": "45940", "alipay_id": "2020092900077000000003519020", "us_id": "45940", "upcard_terminal": "35104887", "upcard_mer_id": "102351089992164", "ex_id": "45940", "ex_cost_center_code": "1200845940" } }, { "_id": "4383485710831779840", "name": "阜阳吾悦店", "extend_code": { "comm_shop_id": "19c068af11174993b900e840214c6ec0", "ex_code": "45943", "alipay_id": "2021102600077000000029271048", "us_id": "45943", "upcard_terminal": "55802415", "upcard_mer_id": "102558089990764", "ex_id": "45943", "ex_cost_center_code": "1200845943" } }, { "_id": "4386130885617942528", "name": "兴化吾悦店", "extend_code": { "comm_shop_id": "76b0faea91f247478dd97daa984744e0", "ex_code": "45937", "alipay_id": "2021102800077000000029382054", "us_id": "45937", "upcard_terminal": "52301063", "upcard_mer_id": "102523089990152", "ex_id": "45937", "ex_cost_center_code": "1200845937" } }, { "_id": "4387941392733732864", "name": "毕节花园城店", "extend_code": { "comm_shop_id": "11f6ced34a394a43ae95f8713d6e0a67", "ex_code": "45954", "us_id": "45954", "upcard_terminal": "85700062", "upcard_mer_id": "102857089990021", "ex_id": "45954", "ex_cost_center_code": "1200845954" } }, { "_id": "4387947305460891648", "name": "福州泰禾广场店", "extend_code": { "comm_shop_id": "0f5836388b074813a27224f548ee3a65", "ex_code": "45953", "alipay_id": "2020090900077000000002553407", "us_id": "45953", "upcard_terminal": "59114146", "upcard_mer_id": "102591089990694", "ex_id": "45953", "ex_cost_center_code": "1200845953" } }, { "_id": "4388255581494902784", "name": "珠海优特汇店", "extend_code": { "comm_shop_id": "4e85c3aff0c342239eb0528bc5d230ec", "ex_code": "45950", "alipay_id": "2020101900077000000007345882", "us_id": "45950", "upcard_terminal": "75602231", "upcard_mer_id": "102756089990222", "ex_id": "45950", "ex_cost_center_code": "1200845950" } }, { "_id": "4388256959403458560", "name": "三亚青春颂店", "extend_code": { "comm_shop_id": "29a9b4d1035e4001899c0ff3e78331e6", "ex_code": "45957", "alipay_id": "2020092800077000000003401922", "us_id": "45957", "upcard_terminal": "89801983", "upcard_mer_id": "102898089990641", "ex_id": "45957", "ex_cost_center_code": "1200845957" } }, { "_id": "4389379616115064832", "name": "重庆西站店", "extend_code": { "comm_shop_id": "645ebc7639cc427c8f4a49fc3e045007", "ex_code": "45956", "alipay_id": "2021102600077000000029272278", "us_id": "45956", "upcard_terminal": "02312240", "upcard_mer_id": "102230089992885", "ex_id": "45956", "ex_cost_center_code": "1200845956" } }, { "_id": "4390804055180476416", "name": "青岛合肥路佳世客店", "extend_code": { "comm_shop_id": "36f64239a2744b17b8844d9557dba4b2", "ex_code": "45949", "alipay_id": "2020092200077000000003024303", "us_id": "45949", "upcard_terminal": "53206610", "upcard_mer_id": "102532089991679", "ex_id": "45949", "ex_cost_center_code": "1200845949" } }, { "_id": "4391895151423848448", "name": "广东悦汇城店", "extend_code": { "comm_shop_id": "1437b0ec9eab4aba957694b4721eaf88", "ex_code": "45962", "alipay_id": "2020092800077000000003403578", "us_id": "45962", "upcard_terminal": "02005455", "upcard_mer_id": "102200089991261", "ex_id": "45962", "ex_cost_center_code": "1200045962" } }, { "_id": "4391897109522087936", "name": "西安UPlaza店", "extend_code": { "comm_shop_id": "5091acc79cfb401e89ebfba8b9c63243", "ex_code": "45963", "alipay_id": "2020092200077000000003024304", "us_id": "45963", "upcard_terminal": "02910476", "upcard_mer_id": "102290089993441", "ex_id": "45963", "ex_cost_center_code": "1200845963" } }, { "_id": "4391899144959066112", "name": "新南宁万象城店", "extend_code": { "comm_shop_id": "d607cd14a0c14b578581ef4a42a8aed1", "ex_code": "45965", "alipay_id": "2020101200077000000007013526", "us_id": "45965", "upcard_terminal": "77106041", "upcard_mer_id": "102771089992196", "ex_id": "45965", "ex_cost_center_code": "1200045965" } }, { "_id": "4398052426228236288", "name": "衡阳杉杉奥特莱斯店", "extend_code": { "comm_shop_id": "7e8526296a8e47be8ce3a9ae1ed00b97", "ex_code": "45968", "us_id": "45968", "upcard_terminal": "83890691", "upcard_mer_id": "102838089990120", "ex_id": "45968", "ex_cost_center_code": "1200845968" } }, { "_id": "4398054206588616704", "name": "常州文化广场店", "extend_code": { "comm_shop_id": "d8670ac5bc8149a38e09ee09c912ec40", "ex_code": "45971", "alipay_id": "2020120900077000000010445232", "us_id": "45971", "upcard_terminal": "51902170", "upcard_mer_id": "102519089990250", "ex_id": "45971", "ex_cost_center_code": "1200845971" } }, { "_id": "4398055515450572800", "name": "海盐吾悦店", "extend_code": { "comm_shop_id": "a325a947394f4340bbfd454e92aef873", "ex_code": "45973", "alipay_id": "2020110500077000000008032337", "us_id": "45973", "upcard_terminal": "57304366", "upcard_mer_id": "102573089990224", "ex_id": "45973", "ex_cost_center_code": "1200845973" } }, { "_id": "4398808738801156096", "name": "西安昆明池店", "extend_code": { "comm_shop_id": "dd5bfda3055e4d438629cacd65356ee0", "ex_code": "45932", "us_id": "45932", "upcard_terminal": "02910493", "upcard_mer_id": "102290089993444", "ex_id": "4593245932", "ex_cost_center_code": "1200845932" } }, { "_id": "4400596504904007680", "name": "南京雨花吾悦店", "extend_code": { "comm_shop_id": "dbf6c5e4a3f7456f92871fcfad8f7bb1", "ex_code": "45976", "alipay_id": "2020120900077000000010443361", "us_id": "45976", "upcard_terminal": "02588792", "upcard_mer_id": "102250089994109", "ex_id": "45976", "ex_cost_center_code": "1200845976" } }, { "_id": "4400604720048177152", "name": "金湖苏宁店", "extend_code": { "comm_shop_id": "e6c4dec499c647c1a705076e8b6e8ecb", "ex_code": "45951", "alipay_id": "2020120900077000000010443363", "us_id": "45951", "upcard_terminal": "51701585", "upcard_mer_id": "102517089990120", "ex_id": "4595145951", "ex_cost_center_code": "1200845951" } }, { "_id": "4400606041526566912", "name": "郑州高新万达店", "extend_code": { "comm_shop_id": "c678b5ecd6234c9f934f9d43040d3558", "ex_code": "45977", "us_id": "45977", "upcard_terminal": "37115009", "upcard_mer_id": "102371089993040", "ex_id": "45977", "ex_cost_center_code": "1200845977" } }, { "_id": "4401656886586277888", "name": "安顺国贸店", "extend_code": { "comm_shop_id": "0b280e6e86484484ad135a60e1c8d6ff", "ex_code": "45994", "alipay_id": "2020101200077000000007013527", "us_id": "45994", "upcard_terminal": "85102854", "upcard_mer_id": "102851089990595", "ex_id": "45994", "ex_cost_center_code": "1200845994" } }, { "_id": "4401659878639173632", "name": "上海港城新天地店", "extend_code": { "comm_shop_id": "795aa53fe2b344f3b520721585ce07ff", "ex_code": "45984", "us_id": "45984", "upcard_terminal": "02113303", "upcard_mer_id": "102210089999463", "ex_id": "45984", "ex_cost_center_code": "1200845984" } }, { "_id": "4401661382624313344", "name": "成都东航中心店", "extend_code": { "comm_shop_id": "f1becacad17047f19635c0f028253b3c", "ex_code": "45986", "us_id": "45986", "upcard_terminal": "02833443", "upcard_mer_id": "102280089997757", "ex_id": "45986", "ex_cost_center_code": "1200845986" } }, { "_id": "4402072802507685888", "name": "西安香醍龙湖店", "extend_code": { "comm_shop_id": "647d4a9e6e334f2aa7ff9a68affdc0c2", "ex_code": "45985", "alipay_id": "2020122200077000000012946463", "us_id": "45985", "upcard_terminal": "02907484", "upcard_mer_id": "102290089993445", "ex_id": "45985", "ex_cost_center_code": "1200845985" } }, { "_id": "4402074319969124352", "name": "合肥新桥机场店", "extend_code": { "comm_shop_id": "6b257c07f6e44d1fa9142ba9f9cdabb4", "ex_code": "45982", "us_id": "45982", "upcard_terminal": "55132629", "upcard_mer_id": "102551089993972", "ex_id": "45982", "ex_cost_center_code": "1200845982" } }, { "_id": "4403513639892451328", "name": "徐州沛县城投广场店", "extend_code": { "comm_shop_id": "efd70c9b5a174b6eaf310439a0f750eb", "ex_code": "45988", "alipay_id": "2021070700077000000023828581", "us_id": "45988", "upcard_terminal": "51601883", "upcard_mer_id": "102516089990316", "ex_id": "45988", "ex_cost_center_code": "1200845988" } }, { "_id": "4403786764840402944", "name": "合肥罍街店", "extend_code": { "comm_shop_id": "04c6e542ccae463f9cd9cebdee554381", "ex_code": "45983", "alipay_id": "2020120900077000000010444092", "us_id": "45983", "upcard_terminal": "55132628", "upcard_mer_id": "102551089993971", "ex_id": "45983", "ex_cost_center_code": "1200845983" } }, { "_id": "4403788646925271040", "name": "淮南吾悦店", "extend_code": { "comm_shop_id": "6dbf1788ce874413a13c0baf17edd2ba", "ex_code": "45997", "alipay_id": "2020110500077000000008038966", "us_id": "45997", "upcard_terminal": "55401101", "upcard_mer_id": "102554089990141", "ex_id": "45997", "ex_cost_center_code": "1200845997" } }, { "_id": "4404589051254996992", "name": "西宁万达店", "extend_code": { "comm_shop_id": "7cf1d4e7e0074733adeb4b6b1401ec5d", "ex_code": "45998", "alipay_id": "2021110500077000000029760139", "us_id": "45998", "upcard_terminal": "97100419", "upcard_mer_id": "102971089990251", "ex_id": "45998", "ex_cost_center_code": "1200845998" } }, { "_id": "4404591784699658240", "name": "东台黄海森林公园店", "extend_code": { "comm_shop_id": "7ecfcb5027344440a0a57384e3efb15d", "ex_code": "45996", "us_id": "45996", "upcard_terminal": "51501134", "upcard_mer_id": "102515089990501", "ex_id": "45996", "ex_cost_center_code": "1200845996" } }, { "_id": "4405687701762801664", "name": "射阳吾悦店", "extend_code": { "comm_shop_id": "2fb53e98e018475488fef0494193ff9b", "ex_code": "45993", "alipay_id": "2021101900077000000029063759", "us_id": "45993", "upcard_terminal": "51501135", "upcard_mer_id": "102515089990502", "ex_id": "45993", "ex_cost_center_code": "1200845993" } }, { "_id": "4405936798340022272", "name": "信阳万达店", "extend_code": { "comm_shop_id": "cd7d6ed3592449429d415249446bb320", "ex_code": "45990", "alipay_id": "2021111100077000000030078261", "us_id": "45990", "upcard_terminal": "37603181", "upcard_mer_id": "102376089990175", "ex_id": "45990", "ex_cost_center_code": "1200845990" } }, { "_id": "4407843470004256768", "name": "西安Momopark店", "extend_code": { "comm_shop_id": "17d5397a67cd4522a0671c813b4bfc83", "ex_code": "45991", "alipay_id": "2020110500077000000008032354", "us_id": "45991", "upcard_terminal": "02907537", "upcard_mer_id": "102290089993456", "ex_id": "45991", "ex_cost_center_code": "1200845991" } }, { "_id": "4407845446486097920", "name": "杭州永旺梦乐城店", "extend_code": { "comm_shop_id": "4fa93966c9fc4c97a2b551c7da76b0c0", "ex_code": "46005", "alipay_id": "2020122200077000000012948913", "us_id": "46005", "upcard_terminal": "57115507", "upcard_mer_id": "102571089993277", "ex_id": "46005", "ex_cost_center_code": "1200846005" } }, { "_id": "4408217690907377664", "name": "贵阳益田假日里店", "extend_code": { "comm_shop_id": "4a7676c354c444c5bd66495b3113e981", "ex_code": "46011", "alipay_id": "2021102600077000000029273728", "us_id": "46011", "upcard_terminal": "85102861", "upcard_mer_id": "102851089990600", "ex_id": "46011", "ex_cost_center_code": "1200846011" } }, { "_id": "4408219408118349824", "name": "崇明万达店", "extend_code": { "comm_shop_id": "3b9d9a7811154c0980243332dc8e62c7", "ex_code": "46009", "us_id": "46009", "upcard_terminal": "02113355", "upcard_mer_id": "102210089999481", "ex_id": "46009", "ex_cost_center_code": "1200846009" } }, { "_id": "4408220817438048256", "name": "湖州吾悦店", "extend_code": { "comm_shop_id": "2371be9663154f528453766644d8f33a", "ex_code": "46010", "alipay_id": "2020110600077000000008084336", "us_id": "46010", "upcard_terminal": "57297333", "upcard_mer_id": "102572089990100", "ex_id": "46010", "ex_cost_center_code": "1200846010" } }, { "_id": "4408222122382491649", "name": "徐州贾汪吾悦店", "extend_code": { "comm_shop_id": "10e53a4fb4bb4e959af6581564f9c074", "ex_code": "46006", "us_id": "46006", "upcard_terminal": "51601884", "upcard_mer_id": "102516089990317", "ex_id": "46006", "ex_cost_center_code": "1200846006" } }, { "_id": "4408849400971984896", "name": "赣州万象城店", "extend_code": { "comm_shop_id": "3dffd5a0308744f1b14c3f73d9dd50eb", "ex_code": "46013", "us_id": "46013", "upcard_terminal": "79701556", "upcard_mer_id": "102797089990406", "ex_id": "46013", "ex_cost_center_code": "1200846013" } }, { "_id": "4414360281961005056", "name": "宝鸡天下汇店", "extend_code": { "comm_shop_id": "c84bb139ee234319900fefa00ad78d79", "ex_code": "46016", "alipay_id": "2021102600077000000029272258", "us_id": "46016", "upcard_terminal": "91700305", "upcard_mer_id": "102917089990037", "ex_id": "46016", "ex_cost_center_code": "1200846016" } }, { "_id": "4414362017975042048", "name": "如皋金雅店", "extend_code": { "comm_shop_id": "f2d8a20a7a594dd29bd0e574588840de", "ex_code": "46008", "us_id": "46008", "upcard_terminal": "51301541", "upcard_mer_id": "102513089990289 ", "ex_id": "46008", "ex_cost_center_code": "1200846008" } }, { "_id": "4415803368423882752", "name": "海门狮山店", "extend_code": { "comm_shop_id": "b42c3b8f0e9d47b19c101b7ba045c277", "ex_code": "46037", "us_id": "46037", "upcard_terminal": "51301542", "upcard_mer_id": "102513089990290", "ex_id": "46037", "ex_cost_center_code": "1200846037" } }, { "_id": "4415822172902162432", "name": "三亚蓝海广场店", "extend_code": { "comm_shop_id": "c299839c3b954b4f8500aa1e9725aa7b", "ex_code": "46030", "alipay_id": "2020120900077000000010443362", "us_id": "46030", "upcard_terminal": "89801987", "upcard_mer_id": "102898089990645", "ex_id": "46030", "ex_cost_center_code": "1200846030" } }, { "_id": "4416157027632447488", "name": "东台吾悦店", "extend_code": { "comm_shop_id": "b2e0f12b41714b47b549b7ca2ed00ef5", "ex_code": "46032", "us_id": "46032", "upcard_terminal": "51501196", "upcard_mer_id": "102515089990505", "ex_id": "46032", "ex_cost_center_code": "1200846032" } }, { "_id": "4416842214259326976", "name": "苏州星湖龙湖天街店", "extend_code": { "comm_shop_id": "f9c229bf2e4445109fd8c5055321eafd", "ex_code": "46039", "alipay_id": "2020123000077000000013302468", "us_id": "46039", "upcard_terminal": "51218007", "upcard_mer_id": "102512089993429", "ex_id": "46039", "ex_cost_center_code": "1200846039" } }, { "_id": "4416875245665845248", "name": "银川Ccmall店", "extend_code": { "comm_shop_id": "cabcea1ee47f43cfbe09818df2226a17", "ex_code": "46038", "alipay_id": "2020122200077000000012948914", "us_id": "46038", "upcard_terminal": "95102632", "upcard_mer_id": "102951089991008", "ex_id": "46038", "ex_cost_center_code": "1200846038" } }, { "_id": "4416880132327800832", "name": "海南儋州恒大海花岛沙滩吧店", "extend_code": { "comm_shop_id": "41f48e2c38b64e6db4bd2154b5911df4", "ex_code": "46031", "alipay_id": "2021020900077000000016669999", "us_id": "46031", "upcard_terminal": "89801988", "upcard_mer_id": "102898089990646", "ex_id": "46031", "ex_cost_center_code": "1200846031" } }, { "_id": "4416885632851279872", "name": "济南龙湖奥体天街店", "extend_code": { "comm_shop_id": "8c6f63c98b474f50b758097fae3450c9", "ex_code": "46015", "alipay_id": "2021010800077000000013636949", "us_id": "46015", "upcard_terminal": "53101824", "upcard_mer_id": "102531089990776", "ex_id": "46015", "ex_cost_center_code": "1200846015" } }, { "_id": "4416887417410224128", "name": "东台德润店", "extend_code": { "comm_shop_id": "c301336e623945689c01cc3b24d6a862", "ex_code": "46033", "us_id": "46033", "upcard_terminal": "51501197", "upcard_mer_id": "102515089990506", "ex_id": "46033", "ex_cost_center_code": "1200846033" } }, { "_id": "4417276235204329472", "name": "盐城悦达889店", "extend_code": { "comm_shop_id": "d221c1fe18b4436790eaded140f2a74d", "ex_code": "46043", "alipay_id": "2021101900077000000029058685", "us_id": "46043", "upcard_terminal": "51501198", "upcard_mer_id": "102515089990507", "ex_id": "46043", "ex_cost_center_code": "1200846043" } }, { "_id": "4419470449266688000", "name": "自贡万达店", "extend_code": { "comm_shop_id": "2f3ca04ff9b9499ba53e24a8aee7fa93", "ex_code": "46051", "alipay_id": "2021102600077000000029273855", "us_id": "46051", "upcard_terminal": "81301079", "upcard_mer_id": "102813089990063", "ex_id": "46051", "ex_cost_center_code": "1200846051" } }, { "_id": "4420799278480424960", "name": "海口日月广场店", "extend_code": { "comm_shop_id": "6f271266cc5d45a0a48375e80e022658", "ex_code": "46047", "alipay_id": "2020120900077000000010443364", "us_id": "46047", "upcard_terminal": "89801989", "upcard_mer_id": "102898089990647", "ex_id": "46047", "ex_cost_center_code": "1200846047" } }, { "_id": "4420800342109749248", "name": "济宁兖州贵和广场店", "extend_code": { "comm_shop_id": "e3390a49a14947a4a121ae6a4cf0d6d0", "ex_code": "46046", "alipay_id": "2020123000077000000013302471", "us_id": "46046", "upcard_terminal": "53701206", "upcard_mer_id": "102537089990184", "ex_id": "46046", "ex_cost_center_code": "1200846046" } }, { "_id": "4420802479942303744", "name": "海门大有镜店", "extend_code": { "comm_shop_id": "aaed0dca070a45acb3329062b3e04c50", "ex_code": "46036", "alipay_id": "2020123000077000000013302472", "us_id": "46036", "upcard_terminal": "51301593", "upcard_mer_id": "102513089990292", "ex_id": "46036", "ex_cost_center_code": "1200846036" } }, { "_id": "4420917981876355072", "name": "南昌铜锣湾店", "extend_code": { "comm_shop_id": "d464acd58d584618b5218182ac98d21f", "ex_code": "46041", "alipay_id": "2020122200077000000012946462", "us_id": "46041", "upcard_terminal": "79192352", "upcard_mer_id": "102791089990771", "ex_id": "46041", "ex_cost_center_code": "1200046041" } }, { "_id": "4421619118006927360", "name": "贵阳玖福城店", "extend_code": { "comm_shop_id": "27e3a766da6c4ffd89cf99dce248954d", "ex_code": "46042", "alipay_id": "2021010800077000000013636948", "us_id": "46042", "upcard_terminal": "85102967", "upcard_mer_id": "102851089990603", "ex_id": "46042", "ex_cost_center_code": "1200046042" } }, { "_id": "4421622254952022016", "name": "象山万达店", "extend_code": { "comm_shop_id": "fe4dbad191424c068d2554461669d60b", "ex_code": "46053", "alipay_id": "2020122200077000000012945558", "us_id": "46053", "upcard_terminal": "57405350", "upcard_mer_id": "102574089990747", "ex_id": "46053", "ex_cost_center_code": "1200846053" } }, { "_id": "4421623610530103296", "name": "天长吾悦店", "extend_code": { "comm_shop_id": "3e62f0ffe039473b8bcea7204b872cc1", "ex_code": "46055", "alipay_id": "2021102600077000000029271066", "us_id": "46055", "upcard_terminal": "55000701", "upcard_mer_id": "102550089990093", "ex_id": "46055", "ex_cost_center_code": "1200846055" } }, { "_id": "4421624774831144960", "name": "荆州吾悦店", "extend_code": { "comm_shop_id": "e0fdf674cdad42cf9d7c4017f5ddca70", "ex_code": "46054", "alipay_id": "2021092300077000000027995340", "us_id": "46054", "upcard_terminal": "71600314", "upcard_mer_id": "102716089990083", "ex_id": "46054", "ex_cost_center_code": "1200846054" } }, { "_id": "4421631425105690624", "name": "商丘港汇万达店", "extend_code": { "comm_shop_id": "1f298050992f451abb5a932d361ff679", "ex_code": "46049", "us_id": "46049", "upcard_terminal": "37001399", "upcard_mer_id": "102370089990045", "ex_id": "46049", "ex_cost_center_code": "1200846049" } }, { "_id": "4422356409788727296", "name": "上海LCM置汇旭辉店", "extend_code": { "comm_shop_id": "273e93cd3d7b438f91e773c638610ed7", "ex_code": "46040", "alipay_id": "2020123000077000000013302467", "us_id": "46040", "upcard_terminal": "02113504", "upcard_mer_id": "102210089999500", "ex_id": "46040", "ex_cost_center_code": "1200046040" } }, { "_id": "4422362271861211136", "name": "温州万象城店", "extend_code": { "comm_shop_id": "ca8989ff40714b67a39d4ea9221c0daa", "ex_code": "46048", "alipay_id": "2020120900077000000010444090", "us_id": "46048", "upcard_terminal": "57701378", "upcard_mer_id": "102577089990258", "ex_id": "46048", "ex_cost_center_code": "1200846048" } }, { "_id": "4423789834601005056", "name": "扬州蜀冈万达店", "extend_code": { "comm_shop_id": "4ba859d9d27649daa74a2a479f7a0ec6", "ex_code": "46050", "alipay_id": "2021010800077000000013701394", "us_id": "46050", "upcard_terminal": "51402125", "upcard_mer_id": "102514089990371", "ex_id": "46050", "ex_cost_center_code": "1200846050" } }, { "_id": "4423791452918677504", "name": "宜昌夷陵万达店", "extend_code": { "comm_shop_id": "46ec6eeface54f69a2dd10d3ed190dc5", "ex_code": "46056", "alipay_id": "2020123000077000000013301149", "us_id": "46056", "upcard_terminal": "71703761", "upcard_mer_id": "102717089990305", "ex_id": "46056", "ex_cost_center_code": "1200846056" } }, { "_id": "4423794107384659968", "name": "周口开元万达店", "extend_code": { "comm_shop_id": "d4ffc5f60c0a4f8fbdc4e9a02ce98f48", "ex_code": "46063", "us_id": "46063", "upcard_terminal": "39401207", "upcard_mer_id": "102394089990056", "ex_id": "46063", "ex_cost_center_code": "1200846063" } }, { "_id": "4423798981933465600", "name": "重庆悦荟店", "extend_code": { "comm_shop_id": "7bbed0fbd9a14bd0adcbcdbc40fec165", "ex_code": "46062", "us_id": "46062", "upcard_terminal": "02312354", "upcard_mer_id": "102230089992937", "ex_id": "46062", "ex_cost_center_code": "1200046062" } }, { "_id": "4426307962639810560", "name": "张家港锦丰东服务区店", "extend_code": { "comm_shop_id": "b743d456c22649adaee9465495c82aa1", "ex_code": "45938", "us_id": "45938", "upcard_terminal": "51218046", "upcard_mer_id": "102512089993434", "ex_id": "45938", "ex_cost_center_code": "1200845938" } }, { "_id": "4426309182842503168", "name": "张家港锦丰西服务区店", "extend_code": { "comm_shop_id": "7c62e06f0b064ddfa41d59c84161471f", "ex_code": "45939", "us_id": "45939", "upcard_terminal": "51218011", "upcard_mer_id": "102512089993430 ", "ex_id": "45939", "ex_cost_center_code": "1200845939" } }, { "_id": "4426312133959024640", "name": "西安砂之船奥特莱斯店", "extend_code": { "comm_shop_id": "9a9c6b66e4774090b9db3ff09e678e9c", "ex_code": "46069", "alipay_id": "2021010800077000000013701404", "us_id": "46069", "upcard_terminal": "02907561", "upcard_mer_id": "102290089993459", "ex_id": "46069", "ex_cost_center_code": "1200846069" } }, { "_id": "4427401656923095040", "name": "西安盛安广场店", "extend_code": { "comm_shop_id": "3a1df4ce53844084b47049ef34e6a6be", "ex_code": "46070", "alipay_id": "2021061000077000000021912673", "us_id": "46070", "upcard_terminal": "02907562", "upcard_mer_id": "102290089993460", "ex_id": "46070", "ex_cost_center_code": "1200846070" } }, { "_id": "4427409902698266624", "name": "银川新华联店", "extend_code": { "comm_shop_id": "1602ea988fc74fbca57c24b7b2a11cd6", "ex_code": "46071", "alipay_id": "2021010800077000000013636947", "us_id": "46071", "upcard_terminal": "95102633", "upcard_mer_id": "102951089991009", "ex_id": "46071", "ex_cost_center_code": "1200846071" } }, { "_id": "4429875275636965376", "name": "深圳龙华壹方天地店", "extend_code": { "comm_shop_id": "30574b52d0ff4000a1c9f25178ab1741", "ex_code": "46072", "alipay_id": "2020123000077000000013302469", "us_id": "46072", "upcard_terminal": "75525697", "upcard_mer_id": "102755089996010", "ex_id": "46072", "ex_cost_center_code": "1200846072" } }, { "_id": "4429880672435372032", "name": "西安回民街店", "extend_code": { "comm_shop_id": "32cf750f67cc4ab3ace3d1938e60504b", "ex_code": "46057", "alipay_id": "2020123000077000000013306039", "us_id": "46057", "upcard_terminal": "02907619", "upcard_mer_id": "102290089993517", "ex_id": "46057", "ex_cost_center_code": "1200846057" } }, { "_id": "4429882886415482880", "name": "嘉兴旭辉广场店", "extend_code": { "comm_shop_id": "dbe95e8f84d94a1c952ec45e9d328713", "ex_code": "46076", "alipay_id": "2021010800077000000013701392", "us_id": "46076", "upcard_terminal": "57304467", "upcard_mer_id": "102573089990227", "ex_id": "46076", "ex_cost_center_code": "1200846076" } }, { "_id": "4432440369235427328", "name": "大同百盛2店", "extend_code": { "comm_shop_id": "59e63db5f2fe46109926798599291611", "ex_code": "46079", "alipay_id": "2021070600077000000023799114", "us_id": "46079", "upcard_terminal": "35200304", "upcard_mer_id": "102352089990053", "ex_id": "46079", "ex_cost_center_code": "1200846079" } }, { "_id": "4432443063366877184", "name": "昆明1903店", "extend_code": { "comm_shop_id": "b7e6dda0f1ef4456a331a65f7313ab52", "ex_code": "46080", "alipay_id": "2021102600077000000029271052", "us_id": "46080", "upcard_terminal": "87114112", "upcard_mer_id": "102871089997006", "ex_id": "46080", "ex_cost_center_code": "1200846080" } }, { "_id": "4432465507276357632", "name": "涟水吾悦店", "extend_code": { "comm_shop_id": "7c93cb75b32545ac89e2c5f58467d1a6", "ex_code": "46014", "alipay_id": "2020123000077000000013301150", "us_id": "46014", "upcard_terminal": "51701986", "upcard_mer_id": "102517089990122", "ex_id": "46014", "ex_cost_center_code": "1200846014" } }, { "_id": "4432466407449493504", "name": "银川宁阳广场店", "extend_code": { "comm_shop_id": "c77b80353ca44103ac60f922cbe57271", "ex_code": "46082", "us_id": "46082", "upcard_terminal": "95102639", "upcard_mer_id": "102951089991011", "ex_id": "46082", "ex_cost_center_code": "1200846082" } }, { "_id": "4432470071329193984", "name": "温州龙湾吾悦店", "extend_code": { "comm_shop_id": "ad0218c0e95f42df8056b5b60f09d22a", "ex_code": "46084", "alipay_id": "2020122200077000000012946464", "us_id": "46084", "upcard_terminal": "57701430", "upcard_mer_id": "102577089990261", "ex_id": "46084", "ex_cost_center_code": "1200846084" } }, { "_id": "4433591864915951616", "name": "温州南站店", "extend_code": { "comm_shop_id": "9d2269e730bf4581b4e5dcae8033075a", "ex_code": "46081", "us_id": "46081", "upcard_terminal": "57701429", "upcard_mer_id": "102577089990260", "ex_id": "46081", "ex_cost_center_code": "1200846081" } }, { "_id": "4433920505130582016", "name": "苏州站店", "extend_code": { "comm_shop_id": "52b0babc6d274451b896f62c7ec83fd4", "ex_code": "46089", "us_id": "46089", "upcard_terminal": "51218019", "upcard_mer_id": "102512089993432", "ex_id": "46089", "ex_cost_center_code": "1200846089" } }, { "_id": "4433922116049502208", "name": "西安集乐里店", "extend_code": { "comm_shop_id": "a1cdfd4ef8164a7fb41fe24c18b84bd1", "ex_code": "46088", "us_id": "46088", "upcard_terminal": "02907623", "upcard_mer_id": "102290089993521", "ex_id": "46088", "ex_cost_center_code": "1200846088" } }, { "_id": "4433942470004342784", "name": "芜湖古城店", "extend_code": { "comm_shop_id": "34044363a0ad41a2b650a2fc3609d678", "ex_code": "46087", "alipay_id": "2021102600077000000029272277", "us_id": "46087", "upcard_terminal": "55301917", "upcard_mer_id": "102553089990433", "ex_id": "46087", "ex_cost_center_code": "1200846087" } }, { "_id": "4434268126634377216", "name": "广州番禺天河城店", "extend_code": { "comm_shop_id": "d6cc2cabf7554010815b90025f4acb92", "ex_code": "46086", "alipay_id": "2020123000077000000013302501", "us_id": "46086", "upcard_terminal": "02005582", "upcard_mer_id": "102200089991278", "ex_id": "46086", "ex_cost_center_code": "1200046086" } }, { "_id": "4436386345595764736", "name": "胶州宝龙店", "extend_code": { "comm_shop_id": "e241196986b549389ddf6fee8de379fa", "ex_code": "46096", "alipay_id": "2021062200077000000022905442", "us_id": "46096", "upcard_terminal": "53206622", "upcard_mer_id": "102532089991691", "ex_id": "46096", "ex_cost_center_code": "1200846096" } }, { "_id": "4436387402715561984", "name": "兰州老街店", "extend_code": { "comm_shop_id": "20adce2004f844f882687c27f92bdcdf", "ex_code": "46077", "alipay_id": "2021110500077000000029762930", "us_id": "46077", "upcard_terminal": "93101719", "upcard_mer_id": "102931089990251", "ex_id": "46077", "ex_cost_center_code": "1200846077" } }, { "_id": "4436390072629100544", "name": "乐山伊藤洋华堂店", "extend_code": { "comm_shop_id": "8911a79f07fd447bb14cdf4d6a68c279", "ex_code": "46102", "alipay_id": "2021010800077000000013701393", "us_id": "46102", "upcard_terminal": "83390434", "upcard_mer_id": "102833089990047", "ex_id": "46102", "ex_cost_center_code": "1200046102" } }, { "_id": "4436391664690462720", "name": "苏州悠方店", "extend_code": { "comm_shop_id": "7dfdefe228e648138efdef0ff34287e3", "ex_code": "46100", "alipay_id": "2021012900077000000016127858", "us_id": "46100", "upcard_terminal": "51218038", "upcard_mer_id": "102512089993433", "ex_id": "46100", "ex_cost_center_code": "1200846100" } }, { "_id": "4436498380098699264", "name": "济南中海环宇城店", "extend_code": { "comm_shop_id": "11074c99cfe546d8b2e6f9886bed6f85", "ex_code": "46052", "us_id": "46052", "upcard_terminal": "53101866", "upcard_mer_id": "102531089990779", "ex_id": "46052", "ex_cost_center_code": "1200846052" } }, { "_id": "4436499811178446849", "name": "焦作云台山景区店", "extend_code": { "comm_shop_id": "ff7befda7ae2460fb96db1110835aa7a", "ex_code": "46115", "us_id": "46115", "upcard_terminal": "39102510", "upcard_mer_id": "102391089990195", "ex_id": "46115", "ex_cost_center_code": "1200846115" } }, { "_id": "4438933763541467136", "name": "济南莱芜茂业店", "extend_code": { "comm_shop_id": "7f7850df61fc4d1eb3942f7bfa161051", "ex_code": "46097", "alipay_id": "2021053100077000000021244575", "us_id": "46097", "upcard_terminal": "53101865", "upcard_mer_id": "102531089990778", "ex_id": "46097", "ex_cost_center_code": "1200846097" } }, { "_id": "4438934844765929472", "name": "三亚凤凰国际机场店", "extend_code": { "comm_shop_id": "446d3d17e2db4551a96dc5b919a2907b", "ex_code": "46118", "alipay_id": "2021020900077000000016657460", "us_id": "46118", "upcard_terminal": "89802005", "upcard_mer_id": "102898089990652", "ex_id": "46118", "ex_cost_center_code": "1200846118" } }, { "_id": "4439652755734298624", "name": "商丘夏邑亿舟城店", "extend_code": { "comm_shop_id": "d6244cce06e449b48e56ae7568049266", "ex_code": "46117", "us_id": "46117", "upcard_terminal": "37001400", "upcard_mer_id": "102370089990046", "ex_id": "46117", "ex_cost_center_code": "1200846117" } }, { "_id": "4439654842731921408", "name": "济南融创茂店", "extend_code": { "comm_shop_id": "09e34caa0fe14df49216f30eed354ea4", "ex_code": "46114", "alipay_id": "2021062400077000000023016366", "us_id": "46114", "upcard_terminal": "53101867", "upcard_mer_id": "102531089990780", "ex_id": "46114", "ex_cost_center_code": "1200846114" } }, { "_id": "4439657578621894656", "name": "郑州新郑新尚天地店", "extend_code": { "comm_shop_id": "a11a9131c3224a7c8dbf51b26dfac1dd", "ex_code": "46135", "us_id": "46135", "upcard_terminal": "37115166", "upcard_mer_id": "102371089993057", "ex_id": "46135", "ex_cost_center_code": "1200846135" } }, { "_id": "4439658471584989184", "name": "西安永宁里店", "extend_code": { "comm_shop_id": "dc99fa8bf90d43459d9b61b91931a938", "ex_code": "46140", "alipay_id": "2021061000077000000021911193", "us_id": "46140", "upcard_terminal": "02907667", "upcard_mer_id": "102290089993524", "ex_id": "46140", "ex_cost_center_code": "1200846140" } }, { "_id": "4439659372492161024", "name": "合肥中环店", "extend_code": { "comm_shop_id": "54bfe2147ae9405596b22fd6f6a8c2d6", "ex_code": "46136", "alipay_id": "2021102600077000000029273726", "us_id": "46136", "upcard_terminal": "55132760", "upcard_mer_id": "102551089993981", "ex_id": "46136", "ex_cost_center_code": "1200846136" } }, { "_id": "4441458834847891456", "name": "驻马店爱克玖隆茂店", "extend_code": { "comm_shop_id": "fc319e5fb2d04ec1a22578a270913a3a", "ex_code": "46152", "alipay_id": "2021012900077000000016127859", "us_id": "46152", "upcard_terminal": "39601596", "upcard_mer_id": "102396089990071", "ex_id": "46152", "ex_cost_center_code": "1200846152" } }, { "_id": "4441460512779173888", "name": "重庆光环购物中心店", "extend_code": { "comm_shop_id": "4b4aa3a7a29c4bc2afdd7c57f49edec4", "ex_code": "46151", "alipay_id": "2021042700077000000019734196", "us_id": "46151", "upcard_terminal": "02312459", "upcard_mer_id": "102230089992960", "ex_id": "46151", "ex_cost_center_code": "1200846151" } }, { "_id": "4441461591789076480", "name": "上海虹桥龙湖天街店", "extend_code": { "comm_shop_id": "704474d709e9432189afd4ed2dcbf039", "ex_code": "46148", "alipay_id": "2021062200077000000022902520", "us_id": "46148", "upcard_terminal": "02113738", "upcard_mer_id": "102210089999562", "ex_id": "46148", "ex_cost_center_code": "1200846148" } }, { "_id": "4441467270625001473", "name": "海口美兰国际机场店", "extend_code": { "comm_shop_id": "bf402a491adc42a9bdaf1e4de6eaafa9", "ex_code": "46139", "us_id": "46139", "upcard_terminal": "89802006", "upcard_mer_id": "102898089990653", "ex_id": "46139", "ex_cost_center_code": "1200846139" } }, { "_id": "4441471212738084864", "name": "昭通彝良世纪金街店", "extend_code": { "comm_shop_id": "4ee8dc1f68e1476f8f860ccf2b155d48", "ex_code": "46137", "us_id": "46137", "upcard_terminal": "87000274", "upcard_mer_id": "102870089990186", "ex_id": "46137", "ex_cost_center_code": "1200846137" } }, { "_id": "4441472500494303232", "name": "泰州万象城二期店", "extend_code": { "comm_shop_id": "7da129c14df8450ea06f01248ffce67f", "ex_code": "46141", "us_id": "46141", "upcard_terminal": "52301064", "upcard_mer_id": "102523089990153", "ex_id": "46141", "ex_cost_center_code": "1200846141" } }, { "_id": "4441478441751085056", "name": "兰州欣大百货店", "extend_code": { "comm_shop_id": "753501511a4b4b00a362e4c237cddf0c", "ex_code": "46150", "alipay_id": "2021110500077000000029762929", "us_id": "46150", "upcard_terminal": "93101720", "upcard_mer_id": "102931089990252", "ex_id": "46150", "ex_cost_center_code": "1200846150" } }, { "_id": "4441505005247201280", "name": "铜仁时代商汇店", "extend_code": { "comm_shop_id": "b8e777a367c04acbb7510fca362f28a2", "ex_code": "46112", "alipay_id": "2021102600077000000029271050", "us_id": "46112", "upcard_terminal": "85600036", "upcard_mer_id": "102856089990010", "ex_id": "46112", "ex_cost_center_code": "1200846112" } }, { "_id": "4441506408321581056", "name": "贵州都匀中寰广场店", "extend_code": { "comm_shop_id": "ce1752d45d394718bd6a4aa3ac32ee17", "ex_code": "46138", "us_id": "46138", "upcard_terminal": "85410082", "upcard_mer_id": "102854089990025", "ex_id": "46138", "ex_cost_center_code": "1200846138" } }, { "_id": "4451246041670418432", "name": "扬州砂之船奥特莱斯店", "extend_code": { "comm_shop_id": "89db22b94d354ccd8d9aefaa406008a9", "ex_code": "46154", "alipay_id": "2021020900077000000016657461", "us_id": "46154", "upcard_terminal": "51402161", "upcard_mer_id": "102514089990374", "ex_id": "46154", "ex_cost_center_code": "1200846154" } }, { "_id": "4456014294720512000", "name": "福州宜家店", "extend_code": { "comm_shop_id": "ec41fbb5658640e79cd81d326378383e", "ex_code": "46155", "us_id": "46155", "upcard_terminal": "59114246", "upcard_mer_id": "102591089990702", "ex_id": "46155", "ex_cost_center_code": "1200046155" } }, { "_id": "4467998408243740672", "name": "泰安吾悦店", "extend_code": { "comm_shop_id": "5e1ca4a9e521471f99870900e9f4986d", "ex_code": "46160", "us_id": "46160", "upcard_terminal": "53800718", "upcard_mer_id": "102538089990574", "ex_id": "46160", "ex_cost_center_code": "1200846160" } }, { "_id": "4468006395129659392", "name": "南翔印象城店", "extend_code": { "comm_shop_id": "cae899d009f94eb380e0eeb74dedb1cd", "ex_code": "46164", "alipay_id": "2021081200077000000025982595", "us_id": "46164", "upcard_terminal": "02114208", "upcard_mer_id": "102210090000001", "ex_id": "46164", "ex_cost_center_code": "1200046164" } }, { "_id": "4472269086652432384", "name": "厦门大学访客中心店", "extend_code": { "comm_shop_id": "ec1c6dbdd9f54c47b0fd36588b2d2ed8", "ex_code": "46162", "alipay_id": "2021042700077000000019734193", "us_id": "46162", "upcard_terminal": "59206137", "upcard_mer_id": "102592090000001", "ex_id": "46162", "ex_cost_center_code": "1200846162" } }, { "_id": "4472272824813289472", "name": "合肥黉街店", "extend_code": { "comm_shop_id": "40b9483178d64efd83237d11766df92a", "ex_code": "46165", "alipay_id": "2021053100077000000021247686", "us_id": "46165", "upcard_terminal": "55132833", "upcard_mer_id": "102551090000001", "ex_id": "46165", "ex_cost_center_code": "1200846165" } }, { "_id": "4477056217048481792", "name": "成都绿地伊藤468店", "extend_code": { "comm_shop_id": "a426be686ea945689b67f0169919cb4a", "ex_code": "46172", "alipay_id": "2021102600077000000029272426", "us_id": "46172", "upcard_terminal": "02835257", "upcard_mer_id": "102280090000015", "ex_id": "46172", "ex_cost_center_code": "1200046172" } }, { "_id": "4477345921962672128", "name": "启东凤凰荟购物中心店", "extend_code": { "comm_shop_id": "2164cac59ebc4e2bade09067069ed306", "ex_code": "46183", "us_id": "46183", "upcard_terminal": "51301654", "upcard_mer_id": "102513090000001", "ex_id": "46183", "ex_cost_center_code": "1200846183" } }, { "_id": "4477711045047123968", "name": "海南琼海环球春天店", "extend_code": { "comm_shop_id": "423fd8dbc0b24b7db5a323c95cccf86a", "ex_code": "46185", "alipay_id": "2021060100077000000021288032", "us_id": "46185", "upcard_terminal": "89802020", "upcard_mer_id": "102898090000002", "ex_id": "46185", "ex_cost_center_code": "1200846185" } }, { "_id": "4479509126600228864", "name": "曲靖金都国际店", "extend_code": { "comm_shop_id": "9d771e01492f44d385ad6ae591687995", "ex_code": "46190", "us_id": "46190", "upcard_terminal": "87400744", "upcard_mer_id": "102874090000001", "ex_id": "46190", "ex_cost_center_code": "1200846190" } }, { "_id": "4480596516605558784", "name": "盒马", "extend_code": { "us_id": "46034", "ex_id": "46034", "ex_cost_center_code": "1200046034", "ex_code": "46034" } }, { "_id": "4480597822053318656", "name": "天猫宅配", "extend_code": { "us_id": "45929", "ex_id": "45929", "ex_cost_center_code": "1200045929", "ex_code": "45929" } }, { "_id": "4480666118190596096", "name": "成都天府国际机场店", "extend_code": { "comm_shop_id": "5f865a7f1aac4d29aa62826923c325e0", "ex_code": "46166", "us_id": "46166", "upcard_terminal": "02835306", "upcard_mer_id": "102280090000023", "ex_id": "46166", "ex_cost_center_code": "1200846166" } }, { "_id": "4481777193296363520", "name": "上海陆家嘴1885广场店", "extend_code": { "comm_shop_id": "2f362141dab34a52b17df697f1a6207d", "ex_code": "46192", "alipay_id": "2021062200077000000022903422", "us_id": "46192", "upcard_terminal": "02114252", "upcard_mer_id": "102210090000012", "ex_id": "46192", "ex_cost_center_code": "1200046192" } }, { "_id": "4481779930155253760", "name": "武汉金桥永旺店", "extend_code": { "comm_shop_id": "9069ae69893f42ee9948041d59446995", "ex_code": "46184", "us_id": "46184", "upcard_terminal": "02732323", "upcard_mer_id": "102270090000005", "ex_id": "46184", "ex_cost_center_code": "1200846184" } }, { "_id": "4481784262581846016", "name": "宁波万象城店", "extend_code": { "comm_shop_id": "6db8e587ef4642fb80495a136025088f", "ex_code": "46191", "alipay_id": "2021053100077000000021245689", "us_id": "46191", "upcard_terminal": "57405489", "upcard_mer_id": "102574090000001", "ex_id": "46191", "ex_cost_center_code": "1200046191" } }, { "_id": "4482494311914569728", "name": "济宁吾悦店", "extend_code": { "comm_shop_id": "f3f560dbbffd4bf8b1e81a5f9de05173", "ex_code": "46196", "alipay_id": "2021072600077000000025212002", "us_id": "46196", "upcard_terminal": "53701207", "upcard_mer_id": "102537090000001", "ex_id": "46196", "ex_cost_center_code": "1200846196" } }, { "_id": "4484597483533533184", "name": "南昌青山湖万象汇店", "extend_code": { "comm_shop_id": "f3389f20df6b4e8aa6ea862d9e9c3a56", "ex_code": "46195", "alipay_id": "2021053100077000000021245090", "us_id": "46195", "upcard_terminal": "79192604", "upcard_mer_id": "102791090000002", "ex_id": "46195", "ex_cost_center_code": "1200846195" } }, { "_id": "4485772380838330368", "name": "扬中吾悦店", "extend_code": { "comm_shop_id": "cc8c8e214f1243ea82e659a3f6b54e9a", "ex_code": "46208", "alipay_id": "2021102600077000000029271049", "us_id": "46208", "upcard_terminal": "51104702", "upcard_mer_id": "102511090000001", "ex_id": "46208", "ex_cost_center_code": "1200846208" } }, { "_id": "4485774483996573696", "name": "天水万达店", "extend_code": { "comm_shop_id": "36c394ab0a9a46659aabc427999e7edc", "ex_code": "46204", "alipay_id": "2021062200077000000022903853", "us_id": "46204", "upcard_terminal": "93800016", "upcard_mer_id": "102938090000001", "ex_id": "46204", "ex_cost_center_code": "1200846204" } }, { "_id": "4488218227043762176", "name": "佛山王府井紫薇港店", "extend_code": { "comm_shop_id": "f4d73a13c9104eac9f493450cfdc294f", "ex_code": "46210", "alipay_id": "2021072600077000000025210470", "us_id": "46210", "upcard_terminal": "75704140", "upcard_mer_id": "102757090000008", "ex_id": "46210", "ex_cost_center_code": "1200846210" } }, { "_id": "4488219218455592960", "name": "贵阳龙湾万达店", "extend_code": { "comm_shop_id": "2d319be99e0847e2add6cdc129f30a5c", "ex_code": "46211", "alipay_id": "2021061100077000000021913566", "us_id": "46211", "upcard_terminal": "85102973", "upcard_mer_id": "102851090000001", "ex_id": "46211", "ex_cost_center_code": "1200846211" } }, { "_id": "4488223581198647296", "name": "长沙荟聚店", "extend_code": { "comm_shop_id": "c64ce2c856c0483e9de4ca8afe86cab5", "ex_code": "46217", "alipay_id": "2021062800077000000023605505", "us_id": "46217", "upcard_terminal": "73144432", "upcard_mer_id": "102731090000009", "ex_id": "46217", "ex_cost_center_code": "1200846217" } }, { "_id": "4489298264534843392", "name": "上海漕河泾印象城店", "extend_code": { "comm_shop_id": "db7e2899f27f43fd9f7b3f747654f697", "ex_code": "46202", "alipay_id": "2021053100077000000021247690", "us_id": "46202", "upcard_terminal": "02114533", "upcard_mer_id": "102210090000018", "ex_id": "46202", "ex_cost_center_code": "1200046202" } }, { "_id": "4492544034817998848", "name": "上海莘庄维璟印象城店", "extend_code": { "comm_shop_id": "5ce9676420a74e4eac639bcc6d716283", "ex_code": "46219", "alipay_id": "2021070700077000000023825635", "us_id": "46219", "upcard_terminal": "02114537", "upcard_mer_id": "102210090000022", "ex_id": "46219", "ex_cost_center_code": "1200846219" } }, { "_id": "4494445383923040256", "name": "吴忠万达店", "extend_code": { "comm_shop_id": "949dc81f282f47ea93ad6343074dc24e", "ex_code": "46226", "alipay_id": "2021062800077000000023606749", "us_id": "46226", "upcard_terminal": "95300074", "upcard_mer_id": "102953090000001", "ex_id": "46226", "ex_cost_center_code": "1200846226" } }, { "_id": "4494448431881814016", "name": "三亚海昌梦幻海洋不夜城店", "extend_code": { "comm_shop_id": "8946903a29d04ff1afd61878e31e6757", "ex_cost_center_code": "1200046229", "alipay_id": "2021073000077000000025330817", "us_id": "46229", "upcard_terminal": "89802021", "upcard_mer_id": "102898090000003", "ex_id": "46229", "ex_code": "46229" } }, { "_id": "4495821609061351424", "name": "南京桥北万象汇店", "extend_code": { "comm_shop_id": "b06964d494f042769643c4df7c0106d9", "ex_code": "46180", "us_id": "46180", "upcard_terminal": "02519577", "upcard_mer_id": "102250090000002", "ex_id": "46180", "ex_cost_center_code": "1200846180" } }, { "_id": "4495826708391297024", "name": "盘州合力生活广场店", "extend_code": { "comm_shop_id": "94b7831af5de4570ab180c018717b434", "ex_code": "46223", "alipay_id": "2021071900077000000024884862", "us_id": "46223", "upcard_terminal": "85800193", "upcard_mer_id": "102858090000001", "ex_id": "46223", "ex_cost_center_code": "1200846223" } }, { "_id": "4495879005251076096", "name": "西宁中惠万达店", "extend_code": { "comm_shop_id": "6117deffddbb462fb14886725daaac14", "ex_code": "46225", "alipay_id": "2021110500077000000029761089", "us_id": "46225", "upcard_terminal": "97100456", "upcard_mer_id": "102971090000001", "ex_id": "46225", "ex_cost_center_code": "1200846225" } }, { "_id": "4495880108218810368", "name": "淄博临淄茂业时代广场店", "extend_code": { "comm_shop_id": "5f3fa11c806047f0b7d9f8e77d8b82ae", "ex_code": "46207", "alipay_id": "2021071900077000000024887649", "us_id": "46207", "upcard_terminal": "53311402", "upcard_mer_id": "102533090000001", "ex_id": "46207", "ex_cost_center_code": "1200846207" } }, { "_id": "4497287026141331456", "name": "宝鸡银泰店", "extend_code": { "comm_shop_id": "a286de62824e4c758e5f5b878839e6e2", "ex_code": "46239", "alipay_id": "2021062200077000000022903857", "us_id": "46239", "upcard_terminal": "91700391", "upcard_mer_id": "102917090000001", "ex_id": "46239", "ex_cost_center_code": "1200846239" } }, { "_id": "4497382852150722561", "name": "武汉江宸天街店", "extend_code": { "comm_shop_id": "5a4b100a2c6a49d39984da0d5ff20a27", "ex_code": "46230", "alipay_id": "2021062200077000000022906327", "us_id": "46230", "upcard_terminal": "02732425", "upcard_mer_id": "102270090000016", "ex_id": "46230", "ex_cost_center_code": "1200046230" } }, { "_id": "4497702865348886528", "name": "西安诗经里店", "extend_code": { "comm_shop_id": "aa6d2a3743fa469193b920cb5aaa500f", "ex_code": "46209", "us_id": "46209", "upcard_terminal": "02907849", "upcard_mer_id": "102290090000012", "ex_id": "46209", "ex_cost_center_code": "1200846209" } }, { "_id": "4498408736999636992", "name": "深圳龙岗万达店", "extend_code": { "comm_shop_id": "fa9bdf57b89c4b1cb092219f87aa507b", "ex_code": "46238", "alipay_id": "2021091000077000000027686676", "us_id": "46238", "upcard_terminal": "75527364", "upcard_mer_id": "102755090000002", "ex_id": "46238", "ex_cost_center_code": "1200046238" } }, { "_id": "4498412415974670336", "name": "菏泽佳和城店", "extend_code": { "comm_shop_id": "395d7b50198b4998b553508aff7c5b0b", "ex_code": "46240", "us_id": "46240", "upcard_terminal": "53000582", "upcard_mer_id": "102530090000001", "ex_id": "46240", "ex_cost_center_code": "1200846240" } }, { "_id": "4498414215968620544", "name": "揭阳天虹店", "extend_code": { "comm_shop_id": "7aaf146133524171aa3375cb6b6b112b", "ex_code": "46236", "alipay_id": "2021072600077000000025208922", "us_id": "46236", "upcard_terminal": "66300081", "upcard_mer_id": "102663090000001", "ex_id": "46236", "ex_cost_center_code": "1200846236" } }, { "_id": "4499794263996923904", "name": "眉山仁寿万达店", "extend_code": { "comm_shop_id": "7b4d8acd8b6644a5af3825ea926f12bc", "ex_code": "46237", "alipay_id": "2021102100077000000029116580", "us_id": "46237", "upcard_terminal": "02835871", "upcard_mer_id": "102280090000061", "ex_id": "46237", "ex_cost_center_code": "1200846237" } }, { "_id": "4500598271296700416", "name": "镇江吾悦店", "extend_code": { "comm_shop_id": "975b675383b1497faf62e81c68e4c815", "ex_code": "46243", "alipay_id": "2021081200077000000025710507", "us_id": "46243", "upcard_terminal": "51104703", "upcard_mer_id": "102511090000002", "ex_id": "46243", "ex_cost_center_code": "1200846243" } }, { "_id": "4500599131598782464", "name": "成都金牛凯德店", "extend_code": { "comm_shop_id": "136f6fc8a3f441e9bdd18281362129fc", "ex_code": "46246", "alipay_id": "2021091800077000000027857303", "us_id": "46246", "upcard_terminal": "02835911", "upcard_mer_id": "102280090000070", "ex_id": "46246", "ex_cost_center_code": "1200846246" } }, { "_id": "4500599916701188096", "name": "成都群光广场店", "extend_code": { "comm_shop_id": "be361b920c9947ec91f6491d128c7649", "ex_code": "46245", "alipay_id": "2021071900077000000024884863", "us_id": "46245", "upcard_terminal": "02835910", "upcard_mer_id": "102280090000069", "ex_id": "46245", "ex_cost_center_code": "1200846245" } }, { "_id": "4500602802285871104", "name": "珠海金湾华发商都店", "extend_code": { "comm_shop_id": "7b4937d4cc7845f8a663677faeb06033", "ex_code": "46244", "alipay_id": "2021092200077000000027976696", "us_id": "46244", "upcard_terminal": "75602328", "upcard_mer_id": "102756090000001", "ex_id": "46244", "ex_cost_center_code": "1200846244" } }, { "_id": "4500603791319531520", "name": "嘉兴八佰伴华府店", "extend_code": { "comm_shop_id": "c53efc80d0ef4e20a5c3d7d50ed591a8", "ex_code": "46259", "alipay_id": "2021073000077000000025330818", "us_id": "46259", "upcard_terminal": "57304593", "upcard_mer_id": "102573090000001", "ex_id": "46259", "ex_cost_center_code": "1200846259" } }, { "_id": "4502705714529075200", "name": "西安幸福林带店", "extend_code": { "comm_shop_id": "2b7b7199bad243c488c1545d49cda769", "ex_code": "46260", "alipay_id": "2021090200077000000027471584", "us_id": "46260", "upcard_terminal": "02907853", "upcard_mer_id": "102290090000013", "ex_id": "46260", "ex_cost_center_code": "1200846260" } }, { "_id": "4502709321001369600", "name": "湖州德清正翔店", "extend_code": { "comm_shop_id": "d3a4be08ef8d4b3a94e4b733e77aacb7", "ex_code": "46258", "alipay_id": "2021080200077000000025417359", "us_id": "46258", "upcard_terminal": "57297336", "upcard_mer_id": "102572090000001", "ex_id": "46258", "ex_cost_center_code": "1200846258" } }, { "_id": "4502710944087965696", "name": "衡阳酃湖万达店", "extend_code": { "comm_shop_id": "0f086b02323842f6aa62882926e80306", "ex_code": "46256", "us_id": "46256", "upcard_terminal": "73403778", "upcard_mer_id": "102734090000001", "ex_id": "46256", "ex_cost_center_code": "1200846256" } }, { "_id": "4506044308085833728", "name": "上海宝山龙湖天街店", "extend_code": { "comm_shop_id": "17ac7c849add4b46af3031a5ecd3c637", "ex_code": "46266", "alipay_id": "2021090300077000000027500318", "us_id": "46266", "upcard_terminal": "02114564", "upcard_mer_id": "102210090000040", "ex_id": "46266", "ex_cost_center_code": "1200846266" } }, { "_id": "4506045607728676864", "name": "邵阳步步高新天地店", "extend_code": { "comm_shop_id": "ff0a43ec026448e19274bcf43632821e", "ex_code": "46265", "us_id": "46265", "upcard_terminal": "73903888", "upcard_mer_id": "102739090000001", "ex_id": "46265", "ex_cost_center_code": "1200846265" } }, { "_id": "4506047288893800448", "name": "衢州吾悦店", "extend_code": { "comm_shop_id": "efd7fd4c2b8c4683bc4d8c9a054e8ca4", "ex_code": "46257", "alipay_id": "2021083100077000000027426475", "us_id": "46257", "upcard_terminal": "57000401", "upcard_mer_id": "102570090000001", "ex_id": "46257", "ex_cost_center_code": "1200846257" } }, { "_id": "4508577165077413888", "name": "遵义亨特店", "extend_code": { "comm_shop_id": "636a9218c9334e558872282be6e31698", "ex_code": "46262", "alipay_id": "2021101100077000000028380358", "us_id": "46262", "upcard_terminal": "85102978", "upcard_mer_id": "102851090000006", "ex_id": "46262", "ex_cost_center_code": "1200846262" } }, { "_id": "4508578562267185152", "name": "成都建设路伊藤店", "extend_code": { "comm_shop_id": "9007d4e9efcf466180b591cdc6644bbc", "ex_code": "46274", "alipay_id": "2021092800077000000028117155", "us_id": "46274", "upcard_terminal": "02835954", "upcard_mer_id": "102280090000081", "ex_id": "46274", "ex_cost_center_code": "1200046274" } }, { "_id": "4510790398676860928", "name": "南宁荟聚店", "extend_code": { "comm_shop_id": "b8e3c2d1cba3482cac474b44cc2a1b0b", "ex_code": "46272", "alipay_id": "2021102600077000000029272327", "us_id": "46272", "upcard_terminal": "77107141", "upcard_mer_id": "102771090000001", "ex_id": "46272", "ex_cost_center_code": "1200046272" } }, { "_id": "4510793415975272448", "name": "太原泰享里店", "extend_code": { "comm_shop_id": "46f1986cc1874b258c479d3e44e84820", "ex_code": "46275", "alipay_id": "2021102600077000000029272261", "us_id": "46275", "upcard_terminal": "35106273", "upcard_mer_id": "102351090000191", "ex_id": "46275", "ex_cost_center_code": "1200846275" } }, { "_id": "4512226906411663360", "name": "坊子泰华城店", "extend_code": { "comm_shop_id": "17514eeaea24444bb95e41d6ce4d6f02", "ex_code": "46273\t\t", "us_id": "46273", "upcard_terminal": "53608445", "upcard_mer_id": "102536090000010", "ex_id": "46273\t\t", "ex_cost_center_code": "1200046273" } }, { "_id": "4512231359583911936", "name": "太原晋阳里公园店", "extend_code": { "comm_shop_id": "7cac129e69fe495aa24dbd6e330706be", "ex_code": "46277", "alipay_id": "2021102600077000000029272262", "us_id": "46277", "upcard_terminal": "35106301", "upcard_mer_id": "102351090000220", "ex_id": "46277", "ex_cost_center_code": "1200846277" } }, { "_id": "4512235829717925888", "name": "盱眙苏宁广场店", "extend_code": { "comm_shop_id": "81901c7880514f299d96c3f368069eac", "ex_code": "70627", "us_id": "70627", "upcard_terminal": "51702563", "upcard_mer_id": "102517090000001", "ex_id": "70627", "ex_cost_center_code": "1200870627" } }, { "_id": "4515053764266196992", "name": "京东POP店", "extend_code": { "us_id": "45407", "ex_id": "45407", "ex_cost_center_code": "1200045407", "ex_code": "45407" } }, { "_id": "4515384089064275968", "name": "贵州遵义国贸店", "extend_code": { "comm_shop_id": "c9fd150bcaf34801ba314abeed662294", "ex_code": "46269", "alipay_id": "2015061200077000000000188800", "us_id": "46269", "upcard_terminal": "85102979", "upcard_mer_id": "102851090000007", "ex_id": "46269", "ex_cost_center_code": "1200046269" } }, { "_id": "4516977979630321664", "name": "诸城百盛店", "extend_code": { "comm_shop_id": "72f6284a95bd497fb7cc0d6f29cfa444", "ex_code": "70638", "us_id": "70638", "upcard_terminal": "53608449", "upcard_mer_id": "102536090000014", "ex_id": "70638", "ex_cost_center_code": "1200870638" } }, { "_id": "4517241789905666048", "name": "徐州新沂吾悦店", "extend_code": { "comm_shop_id": "efa388fb7a5946ccbe99bdddb450f45b", "ex_code": "70635", "us_id": "70635", "upcard_terminal": "51602013", "upcard_mer_id": "102516090000002", "ex_id": "70635", "ex_cost_center_code": "1200870635" } }, { "_id": "4517247785256386560", "name": "苏州吴中龙湖天街店", "extend_code": { "comm_shop_id": "ec0680effccf4c9fb0881568b24f8fd6", "ex_code": "46261", "alipay_id": "2021100800077000000028308818", "us_id": "46261", "upcard_terminal": "51218107", "upcard_mer_id": "102512090000005", "ex_id": "46261", "ex_cost_center_code": "1200846261" } }, { "_id": "4517266234120634368", "name": "揭阳万达店", "extend_code": { "comm_shop_id": "4af32924d4504b67846b61e89a3e1dce", "ex_code": "70634", "alipay_id": "2021102100077000000029116579", "us_id": "70634", "upcard_terminal": "66300082", "upcard_mer_id": "102663090000002", "ex_id": "70634", "ex_cost_center_code": "1200870634" } }, { "_id": "4520214932869906432", "name": "上海龙茗店", "extend_code": { "comm_shop_id": "259ea3fe5a77499ea9166be2bbe17db6", "ex_code": "70645", "alipay_id": "2021102600077000000029272259", "us_id": "70645", "upcard_terminal": "02114687", "upcard_mer_id": "102210090000127", "ex_id": "70645", "ex_cost_center_code": "1200070645" } }, { "_id": "4520875770144391168", "name": "永州万达店", "extend_code": { "comm_shop_id": "09649e26a2d8473097c31fd68ca7cb2f", "ex_code": "70648", "us_id": "70648", "upcard_terminal": "74601090", "upcard_mer_id": "102746090000001", "ex_id": "70648", "ex_cost_center_code": "1200870648" } }, { "_id": "4521241753489014784", "name": "上海松江印象城店", "extend_code": { "comm_shop_id": "c2006a9350ed411e806b820bf39226b6", "ex_code": "70644", "alipay_id": "2021111800077000000030324038", "us_id": "70644", "upcard_terminal": "02114686", "upcard_mer_id": "102210090000126", "ex_id": "70644", "ex_cost_center_code": "1200070644" } }, { "_id": "4521278359335895040", "name": "南京建邺吾悦店", "extend_code": { "comm_shop_id": "2fe63b7e5f0d49a088e9146e601e651c", "ex_code": "70649", "alipay_id": "2021091400077000000027762915", "us_id": "70649", "upcard_terminal": "02519981", "upcard_mer_id": "102250090000007", "ex_id": "70649", "ex_cost_center_code": "1200870649" } }, { "_id": "4522084409429491712", "name": "上海国华广场店", "extend_code": { "comm_shop_id": "e35e47ed177f41d6b70db96f2f25552e", "ex_code": "70654", "alipay_id": "2021090700077000000027577645", "us_id": "70654", "upcard_terminal": "02114707", "upcard_mer_id": "102210090000129", "ex_id": "70654", "ex_cost_center_code": "1200070654" } }, { "_id": "4522293316642963456", "name": "拉萨柳梧万达店", "extend_code": { "comm_shop_id": "5524f935f2984ae0b56ec97f8863b7ce", "ex_code": "70647", "us_id": "70647", "upcard_terminal": "89100387", "upcard_mer_id": "102891090000001", "ex_id": "70647", "ex_cost_center_code": "1200870647" } }, { "_id": "4522990890479812608", "name": "苏州相城大悦春风里店", "extend_code": { "comm_shop_id": "7eeadf2701db484ebf3a65e946af1dfc", "ex_code": "70650", "alipay_id": "2021091800077000000027857304", "us_id": "70650", "upcard_terminal": "51218219", "upcard_mer_id": "102512090000006", "ex_id": "70650", "ex_cost_center_code": "1200870650" } }, { "_id": "4523008775239532544", "name": "青岛胶东国际机场店", "extend_code": { "comm_shop_id": "b75985fbfdfb4450b3e28b0a8cb43263", "ex_code": "70656", "us_id": "70656", "upcard_terminal": "53206757", "upcard_mer_id": "102532090000059", "ex_id": "70656", "ex_cost_center_code": "1200070656" } }, { "_id": "4523023333148622848", "name": "杭州萧山印象城店", "extend_code": { "comm_shop_id": "9760b2403c0f4eef8d9730998dd30404", "ex_code": "46278", "alipay_id": "2021101400077000000028489501", "us_id": "46278", "upcard_terminal": "57115829", "upcard_mer_id": "102571090000006", "ex_id": "46278", "ex_cost_center_code": "1200846278" } }, { "_id": "4523025870983561217", "name": "南京河西龙湖店", "extend_code": { "comm_shop_id": "efb2f2d280be49118dd81ed64d03ac9c", "ex_code": "70639", "alipay_id": "2021091000077000000027690741", "us_id": "70639", "upcard_terminal": "02519980", "upcard_mer_id": "102250090000006", "ex_id": "70639", "ex_cost_center_code": "1200870639" } }, { "_id": "4524930328336302080", "name": "荥阳吾悦广场店", "extend_code": { "comm_shop_id": "223959a613924e04abe21d5d81954ee4", "ex_code": "70657", "us_id": "70657", "upcard_terminal": "37115776", "upcard_mer_id": "102371090000023", "ex_id": "70657", "ex_cost_center_code": "1200870657" } }, { "_id": "4524932521827270656", "name": "涡阳县绿城青牛广场店", "extend_code": { "comm_shop_id": "b2fbb4cb24f549d1b97ea95bfbba7ffc", "ex_code": "70658", "alipay_id": "2021111600077000000030285004", "us_id": "70658", "upcard_terminal": "55802661", "upcard_mer_id": "102558090000002", "ex_id": "70658", "ex_cost_center_code": "1200870658" } }, { "_id": "4528141951385501696", "name": "广州花城汇店", "extend_code": { "comm_shop_id": "0f1b5496f803480ea1f3038e27715b5e", "ex_code": "70673", "us_id": "70673", "upcard_terminal": "02005716", "upcard_mer_id": "102200090000001", "ex_id": "70673", "ex_cost_center_code": "1200070673" } }, { "_id": "4528148216052482048", "name": "银川建发现代城店", "extend_code": { "comm_shop_id": "85719f9801384f05aed771886b4f80e1", "ex_code": "70671", "us_id": "70671", "upcard_terminal": "95102690", "upcard_mer_id": "102951090000002", "ex_id": "70671", "ex_cost_center_code": "1200870671" } }, { "_id": "4528412149984296960", "name": "上海安亭店", "extend_code": { "comm_shop_id": "04f9437bc55b4960bed9d411bb1968bb", "ex_code": "70674", "alipay_id": "2021102800077000000029406374", "us_id": "70674", "upcard_terminal": "02114744", "upcard_mer_id": "102210090000133", "ex_id": "70674", "ex_cost_center_code": "1200070674" } }, { "_id": "4528416577919418368", "name": "贵阳小河万科店", "extend_code": { "comm_shop_id": "74d448ac18eb4de4b661de0c3b536027", "ex_code": "70676", "alipay_id": "2021100800077000000028308817", "us_id": "70676", "upcard_terminal": "85102983", "upcard_mer_id": "102851090000010", "ex_id": "70676", "ex_cost_center_code": "1200870676" } }, { "_id": "4528803627491426304", "name": "合肥砂之船奥特莱斯店", "extend_code": { "comm_shop_id": "657a2fab5e01477da4aea0f54b4e6d99", "ex_code": "70667", "us_id": "70667", "upcard_terminal": "55133219", "upcard_mer_id": "102551090000004", "ex_id": "70667", "ex_cost_center_code": "1200870667" } }, { "_id": "4528892160306610176", "name": "南京龙湾龙湖店", "extend_code": { "comm_shop_id": "acf56d06b7f0465ba2988d7617a599ab", "ex_code": "70669", "us_id": "70669", "upcard_terminal": "02523502", "upcard_mer_id": "102250090000009", "ex_id": "70669", "ex_cost_center_code": "1200870669" } }, { "_id": "4529177541056954368", "name": "长沙大悦城店", "extend_code": { "comm_shop_id": "00e1e5a182534891af1dfedb7e06c6b8", "ex_code": "70672", "alipay_id": "2021092800077000000028118888", "us_id": "70672", "upcard_terminal": "73147576", "upcard_mer_id": "102731090000014", "ex_id": "70672", "ex_cost_center_code": "1200070672" } }, { "_id": "4530321313568423936", "name": "上海宝杨宝龙店", "extend_code": { "comm_shop_id": "8ed238b50ace4d2f9ffe09f9f1656cff", "ex_code": "70675", "alipay_id": "2021111600077000000030257122", "us_id": "70675", "upcard_terminal": "02114757", "upcard_mer_id": "102210090000140", "ex_id": "70675", "ex_cost_center_code": "1200070675" } }, { "_id": "4532479701786066944", "name": "<NAME>", "extend_code": { "comm_shop_id": "d7e758744c994ca8979724b49b381c77", "ex_code": "70683", "alipay_id": "2021092800077000000028116044", "us_id": "70683", "upcard_terminal": "66300083", "upcard_mer_id": "102663090000003", "ex_id": "70683", "ex_cost_center_code": "1200870683" } }, { "_id": "4533877648373350401", "name": "湖州织里吾悦店", "extend_code": { "comm_shop_id": "5130aed5676b490f8e7f658cfbf76465", "ex_code": "46279", "us_id": "46279", "upcard_terminal": "57297337", "upcard_mer_id": "102572090000002", "ex_id": "46279", "ex_cost_center_code": "1200846279" } }, { "_id": "4533880126045192192", "name": "宿迁吾悦店", "extend_code": { "comm_shop_id": "d24c7eeb680d4fa5916379d949ebeeaa", "ex_code": "70670", "us_id": "70670", "upcard_terminal": "52703413", "upcard_mer_id": "102527090000001", "ex_id": "70670", "ex_cost_center_code": "1200870670" } }, { "_id": "4534933924821925888", "name": "珠海城市阳台店", "extend_code": { "comm_shop_id": "207074d02c6b4491be35e7dbd5f6ba6b", "ex_code": "70684", "alipay_id": "2021111800077000000030329962", "us_id": "70684", "upcard_terminal": "75602378", "upcard_mer_id": "102756090000002", "ex_id": "70684", "ex_cost_center_code": "1200870684" } }, { "_id": "4534936828324675584", "name": "嘉兴月河古街店", "extend_code": { "comm_shop_id": "1a7fc631706f40548f350e7de4d45583", "ex_code": "70686", "us_id": "70686", "upcard_terminal": "57304595", "upcard_mer_id": "102573090000003", "ex_id": "70686", "ex_cost_center_code": "1200870686" } }, { "_id": "4535785321062793216", "name": "忻州古城店", "extend_code": { "comm_shop_id": "dacd9063d3fc49708d9a4ae9aa715309", "ex_code": "70687", "us_id": "70687", "upcard_terminal": "35000142", "upcard_mer_id": "102350090000001", "ex_id": "70687", "ex_cost_center_code": "1200870687" } }, { "_id": "4536146426276675584", "name": "昆山万象汇店", "extend_code": { "comm_shop_id": "d427f757793843e3aab639ab58ca18df", "ex_code": "70692", "alipay_id": "2021110500077000000029760152", "us_id": "70692", "upcard_terminal": "51218225", "upcard_mer_id": "102512090000007", "ex_id": "70692", "ex_cost_center_code": "1200870692" } }, { "_id": "4536745214791974912", "name": "杭州紫荆龙湖店", "extend_code": { "ex_code": "70694", "alipay_id": "2021102600077000000029271051", "us_id": "70694", "upcard_terminal": "57115834", "upcard_mer_id": "102571090000007", "ex_id": "70694", "ex_cost_center_code": "1200070694" } }, { "_id": "4536750507336728576", "name": "福州东百店", "extend_code": { "ex_code": "70690", "alipay_id": "2021102600077000000029271068", "us_id": "70690", "upcard_terminal": "59115519", "upcard_mer_id": "102591090000009", "ex_id": "70690", "ex_cost_center_code": "1200870690" } }, { "_id": "4536754436921425920", "name": "银川吾悦店", "extend_code": { "ex_cost_center_code": "1200870691", "us_id": "70691", "upcard_terminal": "95102693", "upcard_mer_id": "102951090000003", "ex_id": "70691", "ex_code": "70691" } }, { "_id": "4538695655142522880", "name": "深圳丰盛町蛋糕店", "extend_code": { "ex_cost_center_code": "1200000003", "us_id": "00003", "upcard_terminal": "75527757", "upcard_mer_id": "102755090000004", "ex_id": "00003", "ex_code": "00003" } }, { "_id": "4540886187553914880", "name": "仁怀方圆荟店", "extend_code": { "ex_code": "70689", "alipay_id": "2021111600077000000030253644", "us_id": "70689", "upcard_terminal": "85102984", "upcard_mer_id": "102851090000011", "ex_id": "70689", "ex_cost_center_code": "1200870689" } }, { "_id": "4545582512111419392", "name": "商丘帝壹茂店", "extend_code": { "ex_code": "70716", "alipay_id": "2021111600077000000030257126", "us_id": "70716", "upcard_terminal": "37001404", "upcard_mer_id": "102370090000002", "ex_id": "70716", "ex_cost_center_code": "1200870716" } }, { "_id": "4553489936130572288", "name": "武汉汉阳万达店", "extend_code": { "ex_cost_center_code": "1200070735", "us_id": "70735", "upcard_terminal": "02732837", "upcard_mer_id": "102270090000248", "ex_id": "70735", "ex_code": "70735" } }, { "_id": "4553553070937669632", "name": "郑州富田新天地店", "extend_code": { "ex_cost_center_code": "1200870734", "us_id": "70734", "upcard_terminal": "37116062", "upcard_mer_id": "102371090000036", "ex_id": "70734", "ex_code": "70734" } }] new_comm_shop_id = {} new_comm_code = {} for i in shop_list: if i.get('extend_code', {}).get('comm_shop_id'): new_comm_shop_id[i.get('name')] = i.get('extend_code', {}).get('comm_shop_id') or '' if i.get('extend_code', {}).get('comm_code'): new_comm_code[i.get('name')] = i.get('extend_code', {}).get('comm_code') or '' # print(new_comm_shop_id) # print(new_comm_code) # print(new_comm_shop_id.get('3850146064724131841'), new_comm_code.get('3850146064724131841')) # path = '/Users/hws/Downloads/get_shop_jh_id.xlsx' # wb = openpyxl.load_workbook(path) # sh = wb['门店列表'] # rows = sh.max_row # cols = sh.max_column # print('==='+str(sh.cell(2, 8).value).replace(' ', '')+'---') outwb = openpyxl.Workbook() # outws = outwb.create_sheet('new_sheet') outws = outwb.create_sheet(index=0) for i in range(1, len(shop_list)): # for j in range(1, cols + 2): # outws.cell(i, j).value = sh.cell(i, j).value if j != 10 else str(sh.cell(i, j).value) # 每行多加一列 if i == 1: outws.cell(i, 1).value = '门店名称' outws.cell(i, 2).value = '美方ID' outws.cell(i, 3).value = '最新交行门店ID' outws.cell(i, 4).value = '最新交行积分门店ID' else: outws.cell(i, 1).value = shop_list[i - 1].get('name') outws.cell(i, 2).value = shop_list[i - 1].get('extend_code', {}).get('us_id') outws.cell(i, 3).value = shop_list[i - 1].get('extend_code', {}).get('comm_code') outws.cell(i, 4).value = shop_list[i - 1].get('extend_code', {}).get('comm_shop_id') filename2 = '/Users/hws/Downloads/get_shop_jh_id_new.xlsx' outwb.save(filename2) print(filename2, ' down!!') <file_sep># 使用sha1加密用户密码,以及可以使用flask框架werkzeug验证密码是否一致 password = '<PASSWORD>' salt = '<PASSWORD>' iterations = 1000 prefix = 'pbkdf2:sha1:1000' from hashlib import pbkdf2_hmac import binascii ser = binascii.hexlify(pbkdf2_hmac("sha1", password.encode('utf-8'), salt.encode('utf-8'), iterations, 20)).decode() new_ser = '{}${}${}'.format(prefix, salt, ser) print(new_ser) from werkzeug.security import check_password_hash print(check_password_hash(new_ser, password)) <file_sep>""" 在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的, 也不知道每个数字重复几次。请找出数组中任意一个重复的数字 要求时间复杂度 O(N),空间复杂度 O(1) """ import time nums = [3, 1, 5, 2, 0, 6, 4, 7, 4, 2] # 交换过程 # nums = [2, 1, 5, 3, 0, 6, 4, 7, 2] # nums = [5, 1, 2, 3, 0, 6, 4, 7, 2] # nums = [6, 1, 2, 3, 0, 5, 4, 7, 2] # nums = [4, 1, 2, 3, 0, 5, 6, 7, 2] # nums = [0, 1, 2, 3, 4, 5, 6, 7, 2] def find_num(nums): for i in range(len(nums)): while nums[i] != i: if nums[nums[i]] == nums[i]: return nums[i] t_reverse(nums, i, nums[i]) print(nums) return -1 def t_reverse(nums, i, i_num): """ nums: 原数组 i: 当前循环值的下标 i_num: 对应i下标的值 """ temp = nums[i] nums[i] = nums[i_num] nums[i_num] = temp print(find_num(nums)) """ 题解:在循环过程中,把当前数字,放在列表对应下标位置上,如果当前数字和对应下标上的值相等时,则是重复 """ <file_sep>def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 left_arr = arr[:mid] right_arr = arr[mid:] merge_sort(left_arr) merge_sort(right_arr) i = j = k = 0 while i < len(left_arr) and j < len(right_arr): if left_arr[i] < right_arr[j]: arr[k] = left_arr[i] i += 1 else: arr[k] = right_arr[j] j += 1 k += 1 while i < len(left_arr): arr[k] = left_arr[i] i += 1 k += 1 while j < len(right_arr): arr[k] = right_arr[j] j += 1 k += 1 return arr def quick_sort(arr): if len(arr) <= 1: return arr else: pivot = arr[0] less_than_pivot = [x for x in arr[1:] if x <= pivot] greater_than_pivot = [x for x in arr[1:] if x > pivot] return quick_sort(less_than_pivot) + [pivot] + quick_sort(greater_than_pivot) <file_sep>""" 给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外,这两个数都不会以 0 开头 输入: l1 = [2,4,3],12 = [5,6,4]输出: [7,0,8] 解释: 342 + 465 = 807. """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def pprint(ListNode): l = [] l.append(ListNode.val) if ListNode.next: l.extend(pprint(ListNode.next)) return l def addTwoNumbers(l1: ListNode, l2: ListNode) -> ListNode: dummy = ListNode(0) cur = dummy carry = 0 while l1 or l2: x = l1.val if l1 else 0 y = l2.val if l2 else 0 s = x + y + carry carry = s // 10 cur.next = ListNode(s % 10) cur = cur.next if l1: l1 = l1.next if l2: l2 = l2.next if carry > 0: cur.next = ListNode(carry) return dummy.next l1 = ListNode(4, ListNode(5, ListNode(6, ListNode(3)))) l2 = ListNode(7, ListNode(2, ListNode(8))) # print(pprint(l1)) print(pprint(addTwoNumbers(l1, l2)))<file_sep># coding:utf-8 import psycopg2 import datetime import json import requests def conn_pg_get_info(): error = '' rows = [] result = [] total = 0 try: conn = psycopg2.connect(host='rm-uf6ad3241v0k432qb.pg.rds.aliyuncs.com', port='3433', database='hex_estate_bi', user='postgres', password='<PASSWORD>') cursor = conn.cursor() cursor.execute(""" SELECT store_name || '[' || store_code || ']' store_name, sync_type, CASE WHEN sync_type IN ( 'HTTP', 'TCP', 'WebSerT', 'WebService', 'Webservice' ) THEN CASE WHEN date_part( 'day', now() - sync_time :: TIMESTAMP ) > 1 THEN 'error' ELSE 'success' END WHEN sync_type = 'FTP' THEN CASE WHEN date_part( 'day', now() - sync_time :: TIMESTAMP ) > 2 THEN 'error' ELSE 'success' END ELSE 'error' END sync_status, sync_time FROM estate_store WHERE status = '100' """) rows = cursor.fetchall() total = len(rows) for row in rows: if row[2] == 'error': result.append(row) return total, result except Exception as e: error = str(e) print('连接pg查询失败: {}'.format(error)) finally: # 关闭游标 cursor.close() # 关闭数据库连接 conn.close() def format_msg(total, result): if not result: return '' title = 'DQ物业' head = """###{} {}\n>""".format(title, 'DQ') error_count = len(result) body = """> 物业状态为100的共{}笔数据, 超过时间限制同步共{}笔数据\n >""".format(total, error_count) for r in result: body += """> 门店:{}, 同步类型[{}], 最近一次同步时间为{} \n >""".format(r[0], r[1], r[3].strftime("%Y-%m-%d %H:%M:%S")) tail = """> #### {}发布 \n""".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) return head + body + tail def send_ding_talk_msg(msg): url = 'https://oapi.dingtalk.com/robot/send?access_token=a8ef2ef0eac8fa45dbaa3abc2e64d1de0b8716fe07fd0e08a27606324a1b0c3e' headers = { "Content-Type": "application/json ;charset=utf-8 " } msg_dic = { "msgtype": "text", "text": {"content": msg}, # "markdown": { # "title": "监控", # "text": msg # }, "at": { "atMobiles": [ "17610351121" ], "isAtAll": False } } res = requests.post(url, data=json.dumps(msg_dic), headers=headers) print(res.text) if __name__ == '__main__': total, result = conn_pg_get_info() msg = format_msg(total, result) print(msg) # if msg: # send_ding_talk_msg(msg) <file_sep>import openpyxl import requests import json path = '/Users/hws/Downloads/测试门店清单.xlsx' wb = openpyxl.load_workbook(path) sh = wb['YM'] rows = sh.max_row cols = sh.max_column print(rows, cols) shop_infos = [] for i in range(2, rows + 1): us_id = sh.cell(i, 1).value ex_cost_center_code = sh.cell(i, 5).value shop_name = sh.cell(i, 8).value name_en = sh.cell(i, 9).value address = sh.cell(i, 15).value store_type = "DRS" if '直营' in sh.cell(i, 20).value else 'FRS' shop_infos.append({ "name": shop_name, "name_en": name_en, "store_type": store_type, "status": "OPENED", "code": "", "extend_code": { "us_id": us_id, "ex_cost_center_code": ex_cost_center_code }, "currency": "CNY", "open_date": "2022-09-28", "close_date": "2099-09-28", "address": address, "relation": {} }) headers = { 'authorization': 'Bearer <KEY>', 'Cookie': 'hex_server_session={}'.format('4d24a349-00ea-4d63-8f2c-e6c4f80ee353'), 'content-type': 'application/json' } get_shop_url = "http://teststore.meet-xiaomian.com/api/v1/store?code=all&include_state=true&include_total=true&relation=all&search_fields=extend_code.ex_code%2Cextend_code.us_id%2Cextend_code.ex_id%2Ccode%2Cname%2Caddress%2Crelation.geo_region.name%2Crelation.branch.name%2Crelation.distribution_region.name%2Crelation.attribute_region.name%2Crelation.formula_region.name%2Crelation.market_region.name%2Crelation.order_region.name&stringified=true&is_task=true&sort=extend_code.ex_code&order=asc&offset=0&limit=1000&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true&_=1664332102744" res = requests.get(get_shop_url, headers=headers) shop_us_id = [r.get('extend_code').get('us_id') for r in res.json().get('payload').get('rows')] # print(shop_us_id) url = "https://test.dairyqueen.com.cn/api/v1/store?stringified=true" for shop in shop_infos: if shop.get('extend_code').get('us_id') not in shop_us_id: # print(shop) requests.post(url, json=shop, headers=headers) print(shop.get('name') + '创建成功!') else: print('已存在: %s' % shop) # path = '/Users/hws/Downloads/测试门店清单.xlsx' # wb = openpyxl.load_workbook(path) # sh = wb['DQ'] # rows = sh.max_row # cols = sh.max_column # print(rows, cols) # shop_infos = [] # for i in range(2, rows + 1):<file_sep>import requests import json import time import xlrd from openpyxl import Workbook, load_workbook #请求头部 authorization = 'Bearer <KEY>' hex_server_session = '9f697a29-fc04-4cd4-871b-5ebb814f081f' test_url = 'http://test.dairyqueen.com.cn' store_url = 'http://store.dairyqueen.com.cn' store_ppj_url = 'http://store.papajohnshanghai.com' test_be_url = 'http://hwstest.brutcakecafe.com' store_be_url = 'http://store.brutcakecafe.com' headers1 = { 'authorization': '{}'.format(authorization), 'Cookie': 'hex_server_session={}'.format(hex_server_session), } headers2 = { 'authorization': '{}'.format(authorization), 'Content-Type': 'application/json', 'Cookie': 'hex_server_session={}'.format(hex_server_session), } final_url = store_ppj_url def get_product_id(id): """ 根据商品编码拿到商品id及单位 """ url = final_url + '/api/v1/product?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&relation=all&include_state=true'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) product_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(id): product_id = i['id'] except IndexError as e: print('物料编码{}不存在'.format(id)) return if not product_id: print('物料编码{}不存在'.format(id)) return return product_id def get_region_order_rel_id(product_id): url = final_url + '/api/v1/product/{}/region/order?stringified=true&include_total=true&is_task=true&order=asc' \ '&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true'.format(product_id) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() dic = data['payload'] lis = dic['rows'] for i in lis: if i['id'] == '4635061286305038336': rel_id_new = i['rel_id'] break return rel_id_new def accept_region_order(rel_id): url = final_url + '/api/v1/product/region/order/{}/state/disable?stringified=true'.format(rel_id) response = requests.request("PUT", url, headers=headers1) data = response.json() return def one_trun(code): product_id = get_product_id(code) if not product_id: print('物料编码{}不存在'.format(code)) return # create_region_order(product_id) rel_id = get_region_order_rel_id(product_id) accept_region_order(rel_id) print('商品{}禁用订货区域北京-测试'.format(code)) return def test(): wb = Workbook() ws = wb.active file_path = '/Users/yjq/Desktop/test.xlsx' # 打开一个已有文件 wb = load_workbook(file_path) sheet_list = wb.sheetnames sheet = wb[wb.sheetnames[0]] total_list = [] for r in range(2, sheet.max_row + 1): row_list = [] # 每一行建立一个list for c in range(1, sheet.max_column + 1): v = str(sheet.cell(r, c).value) v = v.replace('\n', '') row_list.append(v) total_list.append(row_list) print(len(total_list), total_list) return total_list if __name__ == '__main__': lis = test() for i in lis: one_trun(i[0]) print('----------------------------------') time.sleep(0.1)<file_sep>import requests data = {'merchantOrderId': '45993622031273861142', 'terminalCode': u'2202009082233194872', 'merchantCode': u'811010210101001'} headers = dict( Authorization='OPEN-ACCESS-TOKEN AccessToken=<KEY>' ) url = 'https://qpay.qmai.cn/poslink/transaction/voidpayment' res = requests.post(url, json=data, headers=headers) print(res.content) <file_sep># import openpyxl # outwb = openpyxl.Workbook() # outws = outwb.create_sheet(index=0) # for i in range(1, 10): # outws.cell(i, 1).value = '0.3000' # filename2 = '/Users/hws/Downloads/test.xlsx' # outwb.save(filename2) # print(filename2, ' down!!') from urllib import parse import requests # import json # url = "http://store.dairyqueen.com.cn/api/v1/bi/product/sales?subtotal=day&region=1&region_level=0&start_date=2021-08-11&end_date=2021-08-12&category_ids=3895644930529886111&product_is_master=false&limit=10&offset=0&stringified=true" # payload={} # headers = { # 'Proxy-Connection': 'keep-alive', # 'Cache-Control': 'max-age=0', # 'authorization': 'Bearer pqW-1wbJPiifLN6gP0tScA', # 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36', # 'content-type': 'application/json', # 'Accept': '*/*', # 'Referer': 'http://store.dairyqueen.com.cn/', # 'Accept-Language': 'zh-CN,zh;q=0.9', # 'Cookie': 'hex_server_session=48680e9e-484c-4438-bd6d-19fd86a51fb5; hex_server_session=48680e9e-484c-4438-bd6d-<PASSWORD>' # } # response = requests.request("GET", url, headers=headers, data=payload) # print(response.text) # print(response.headers) import requests # url = "https://v.douyin.com/eHHc1ft/" # payload={} # headers = { # 'authority': 'v.douyin.com', # 'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"', # 'sec-ch-ua-mobile': '?0', # 'upgrade-insecure-requests': '1', # 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36', # 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', # 'sec-fetch-site': 'none', # 'sec-fetch-mode': 'navigate', # 'sec-fetch-user': '?1', # 'sec-fetch-dest': 'document', # 'accept-language': 'zh-CN,zh;q=0.9' # } # response = requests.request("GET", url, headers=headers, data=payload) # 抖音基础信息 headers = {"Content-Type": "application/x-www-form-urlencoded"} client_token = '<KEY>' # # # 核销券 # data = { # 'verify_token': '94b5812f-cb95-46bf-9fd9-c60a7f9f305f', # 'encrypted_codes': ['C<KEY>'] # } # response = requests.post('https://open.douyin.com/namek/fulfilment/verify/?client_token={}'.format(client_token), json=data, headers=headers) # print(response.text, '*'* 10) # data = { # 'verify_token': '<PASSWORD>', # 'encrypted_codes': ['C<KEY>'] # } # response = requests.post('https://open.douyin.com/namek/fulfilment/verify/?client_token={}'.format(client_token), json=data, headers=headers) # print(response.text, '#'* 10) # 取消核销券 headers = {"Content-Type": "application/json"} data = { 'verify_id': '7215501566219683855', 'certificate_id': '7215493514816569384' } response = requests.post('https://open.douyin.com/namek/fulfilment/cancel/?client_token={}'.format(client_token), json=data, headers=headers) # s = response.text # print(type(s)) # print('*' * 10) print(response.json()) # # 券状态查询 # data = { # "encrypted_code": "<KEY> # } # response = requests.get('https://open.douyin.com/namek/fulfilment/query/certificate/?client_token={}'.format(client_token), params=data, headers=headers) # print(response.json()) # res = requests.get('https://open.douyin.com/namek/poi/query/?client_token={}&page=1&size=1000'.format(client_token)) # print(res.text) # with open ('/Users/hws/Downloads/shop.json','w') as f: # f.write(res.text) <file_sep># coding:utf-8 import requests import json import time import xlrd from openpyxl import Workbook, load_workbook #请求头部 authorization = '<KEY>' hex_server_session = '5cc8acf0-328b-4a17-afa5-b9e46c5f9752' test_url = 'http://test.dairyqueen.com.cn' store_url = 'http://store.dairyqueen.com.cn' store_ppj_url = 'http://store.papajohnshanghai.com' test_be_url = 'http://hwstest.brutcakecafe.com' store_be_url = 'http://store.brutcakecafe.com' headers1 = { 'authorization': '{}'.format(authorization), 'Cookie': 'hex_server_session={}'.format(hex_server_session), } headers2 = { 'authorization': '{}'.format(authorization), 'Content-Type': 'charset=utf8', 'Cookie': 'hex_server_session={}'.format(hex_server_session), } branch_dict = {} store_id_dict = {} def get_product_id(id): """ 根据商品编码拿到商品id """ url = test_url + '/api/v1/product?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&include_state=true'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) product_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(id): product_id = i['id'] except IndexError as e: print('物料编码{}不存在'.format(id)) return # dic = data['payload'][0] # product_id = dic['id'] # print('product_id', product_id) # data = json.dumps(data, sort_keys=True, indent=4, separators=(',', ':')) # print(type(data), data) # print(product_id) if not product_id: print('物料编码{}不存在'.format(id)) return return product_id def change_category(id, branch_id): url = test_url + '/api/v1/store/{}?stringified=true'.format(id) s = {"relation": {"branch": '{}'.format(branch_id)}} # print(s) data = json.dumps(s) response = requests.request("PUT", url, headers=headers1, data=data) data = response.json() return def get_request_id2(id): """ 拿到所有变更计划的 request_id """ url = test_url + '/api/v1/store/task?stringified=true&include_total=true&record_id={}&order=asc&offset=0&limit=1'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() dic = data['payload'] lis = dic['rows'] # print('lis', lis) approve_id = lis[0]['id'] return approve_id def confirm_changes2(request_id): """ 审核变更计划 """ url = test_url + '/api/v1/store/task/{}/status/APPROVED?stringified=true'.format(request_id) # print(url) response = requests.request("PUT", url, headers=headers1) data = response.json() # print(data) # time.sleep(0.1) return def get_request_id(code): url = test_url + '/api/v1/store/{}?is_task=true&relation=all&code=all&is_new=true&include_state=true&stringified=true'.format(code) print(url) response = requests.get(url, headers=headers1) data = response.json() # print(type(data), data) request_id = None try: dic = data['payload'] request_id = dic['request_id'] name = dic['name'] except IndexError as e: print('门店{}不存在'.format(code)) return if not request_id: print('门店{}修改出错'.format(code)) return return request_id, name def accept_action2(name, request_id): """ 接受更改操作,用map去拼接正确的名字 eg.DQ全国 """ url = test_url + '/api/v1/store/change/{}/to/task?stringified=true'.format(request_id) s = {"name": "{}".format(name), "immediate": False, "start_time": "2021-06-30 17:41:17"} # print(s) data = json.dumps(s, ensure_ascii=False).encode("utf-8") # print(data) response = requests.post(url, headers=headers2, data=data) data2 = response.json() # time.sleep(0.1) return def one_trun(code, branch_id, branch_name): change_category(code, branch_id) request_id, name = get_request_id(code) accept_action2(name, request_id) request_id2 = get_request_id2(code) confirm_changes2(request_id2) print('门店{}修改区经理{}'.format(name, branch_name)) return def test(): wb = Workbook() ws = wb.active file_path = '/Users/yjq/Desktop/test.xlsx' # 打开一个已有文件 wb = load_workbook(file_path) sheet_list = wb.sheetnames sheet = wb[wb.sheetnames[0]] total_list = [] for r in range(2, sheet.max_row + 1): row_list = [] # 每一行建立一个list for c in range(1, sheet.max_column + 1): v = str(sheet.cell(r, c).value) v = v.replace('\n', '') row_list.append(v) total_list.append(row_list) print(len(total_list), total_list) return total_list def get_branch(): url = test_url + '/api/v1/region/branch?stringified=true&include_total=true&include_state=true&include_parents=true&relation=all&search_fields=name,code&order=asc&offset=0&limit=300&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true&_=1625035086928' response = requests.get(url, headers=headers1) data = response.json() try: dic = data['payload'] lis = dic['rows'] total = dic['total'] for i in lis: name = i['name'] _id = i['id'] if name in branch_dict: print('请检查{}是否唯一'.format(name)) branch_dict[name] = _id # print(len(branch_dict), branch_dict) except IndexError as e: print('获取管理区域出错', e) return if total != len(branch_dict): print('管理区域数量不一致,请检查是否同名区经理') return branch_dict def get_store_id(): url = test_url + '/api/v1/store?code=all&include_state=true&include_total=true&relation=all&search_fields=extend_code.ex_code%2Cextend_code.us_id%2Cextend_code.ex_id%2Ccode%2Cname%2Caddress%2Crelation.geo_region.name%2Crelation.branch.name%2Crelation.distribution_region.name%2Crelation.attribute_region.name%2Crelation.formula_region.name%2Crelation.market_region.name%2Crelation.order_region.name&stringified=true&is_task=true&sort=extend_code.ex_code&order=asc&offset=0&limit=1500&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true&_=1625036536949' response = requests.get(url, headers=headers1) data = response.json() try: dic = data['payload'] lis = dic['rows'] total = dic['total'] for i in lis: us_id = i['extend_code']['us_id'] _id = i['id'] if us_id in store_id_dict: print('请检查{}是否唯一'.format(us_id)) store_id_dict[us_id] = _id # print(len(store_id_dict), store_id_dict) except IndexError as e: print('获取门店id出错', e) return if total != len(store_id_dict): print('门店数量不一致,请检查是否同名美编') return store_id_dict if __name__ == '__main__': # lis = test() # dic_branch = get_branch() # dic_store = get_store_id() # for i in lis: # one_trun(dic_store[i[0]], dic_branch[i[1]], i[1]) # print('----------------------------------') # time.sleep(0.1) get_request_id(3935321603065405441) # 使用说明:打开网页获取此时的authorization; 全局修改url为想要执行的品牌; 转换模版格式 # 批量执行时, 可能会因执行一直发请求等原因报错, 重新执行即可————这条不确定,建议从执行失败的重新执行 # 文件格式如下:门店美编 | 区经理名称 # 42608 | 陈超 # 43460 | 赵海迪 <file_sep>nums = [2, 3, 6, 5, 1, 4, 8, 11, 0, 7] # 模拟栈操作实现非递归的快速排序 def quick_sort(nums): if len(nums) < 2: return nums stack = [] # 初始把待排序列表起始和结束位置放入栈 stack.append(len(nums)-1) stack.append(0) # 当栈有元素就一直循环 while stack: left = stack.pop() right = stack.pop() # 确定基准值 index = partition(nums, left, right) if left < index - 1: stack.append(index - 1) stack.append(left) if right > index + 1: stack.append(right) stack.append(index + 1) return nums def partition(nums, left, right): # 在当前列表,还是按照快排思想,左边小于基准值,右边大于等于基准值,左右下标向中间靠拢,返回左或右值 pivot = nums[left] while left < right: while left < right and nums[right] >= pivot: right -= 1 nums[left] = nums[right] while left < right and nums[left] <= pivot: left += 1 nums[right] = nums[left] # 此时left == right nums[left] = pivot return left print(quick_sort(nums))<file_sep>import openpyxl import pymongo import requests import json path = '/Users/hws/Downloads/DQ门店POIID明细表2.xlsx' wb = openpyxl.load_workbook(path) sh = wb['Sheet3'] rows = sh.max_row cols = sh.max_column print(rows, cols) update_dic = {} cf_set = set() for i in range(2, rows + 1): us_id = sh.cell(i, 3).value tiktok_id = sh.cell(i, 1).value.replace('\t', '') if us_id != '#N/A' and us_id != '美方ID': # print("美编ID:%s: 抖音门店ID:%s" % (us_id, tiktok_id)) if us_id in update_dic: cf_set.add(us_id) update_dic[us_id] = tiktok_id print(len(update_dic), rows - 1) if cf_set: for c in cf_set: del update_dic[c] print(cf_set) print(len(update_dic), rows - 1) mongo_client_pos = pymongo.MongoClient('127.0.0.1', 27072) db_name_pos = mongo_client_pos.saas_dq # print(update_dic) headers = { 'authorization': 'Bearer rvCywgEBMSKJeAOYkRD10A', 'Cookie': 'hex_server_session={}'.format('27b1bbaf-4c41-4037-afe1-4e7f1eb93f0f'), } store_id_dict = {} def get_store_id(): url = 'http://store.dairyqueen.com.cn' + '/api/v1/store?code=all&include_state=true&include_total=true&relation=all&search_fields=extend_code.ex_code%2Cextend_code.us_id%2Cextend_code.ex_id%2Ccode%2Cname%2Caddress%2Crelation.geo_region.name%2Crelation.branch.name%2Crelation.distribution_region.name%2Crelation.attribute_region.name%2Crelation.formula_region.name%2Crelation.market_region.name%2Crelation.order_region.name&stringified=true&is_task=true&sort=extend_code.ex_code&order=asc&offset=0&limit=1600&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true&_=1625036536949' response = requests.get(url, headers=headers) data = response.json() n = 0 try: dic = data['payload'] lis = dic['rows'] total = dic['total'] for i in lis: us_id = i['extend_code']['us_id'] _id = i['id'] comm_shop_id = i['extend_code']['comm_shop_id'] if 'comm_shop_id' in i['extend_code'] else '0' if us_id in store_id_dict: print('请检查{}是否唯一'.format(us_id)) if not us_id: n = n + 1 print(n, _id) store_id_dict[str(us_id)] = str(_id) # store_shop_id_dict[us_id] = comm_shop_id # print(len(store_id_dict), store_id_dict) except IndexError as e: print('获取门店id出错', e) return if total != len(store_id_dict): print('门店数量不一致,请检查是否同名美编', 'total:{}'.format(total), 'dict:{}'.format(len(store_id_dict))) print('有{}家门店没有美编'.format(n)) print('----------------------------------') return store_id_dict def change_comm_shop_id(store_id, comm_id): store_have_problem_list = [] put_change_url = 'http://store.dairyqueen.com.cn/api/v1/store/' + str(store_id) + '?stringified=true' param_body = { "extend_code": { "tiktok_shop_id": "{}".format(comm_id) } } put_change_jiaohang_res = requests.put(put_change_url, headers=headers, data=json.dumps(param_body)).json() if isinstance(put_change_jiaohang_res, dict): if put_change_jiaohang_res['payload']: get_store_info_url = 'http://store.dairyqueen.com.cn/api/v1/store/' + str( store_id) + '?is_task=true&relation=all&code=all&is_new=true&include_state=true&stringified=true' # 生成变更计划 get_task_id_res = requests.get(get_store_info_url, headers=headers).json()['payload'] task_id = get_task_id_res['request_id'] store_name = get_task_id_res['name'] if task_id: post_apply_url = 'http://store.dairyqueen.com.cn/api/v1/store/change/' + str( task_id) + '/to/task?stringified=true' post_body = {"name": "{}".format(store_name), "immediate": True, "start_time": ""} post_res = requests.post(post_apply_url, headers=headers, data=json.dumps(post_body)).json() if isinstance(post_res, dict): if post_res['payload']: # 使变更计划生效 get_approve_info_url = 'http://store.dairyqueen.com.cn/api/v1/store/task?stringified=true&include_total=true&record_id=' + str( store_id) + '&order=asc&offset=0&limit=1' get_approve_id_res = requests.get(get_approve_info_url, headers=headers).json()['payload'][ 'rows'] approve_id = get_approve_id_res[0]['id'] approve_url = 'http://store.dairyqueen.com.cn/api/v1/store/task/' + str( approve_id) + '/status/APPROVED?stringified=true' approve_res = requests.put(approve_url, headers=headers).json() if isinstance(approve_res, dict): if approve_res['payload']: print('{}修改成功'.format(store_id)) else: print('{}修改失败'.format(store_id)) store_have_problem_list.append(store_id) else: print('{}修改失败'.format(store_id)) store_have_problem_list.append(store_id) else: print('{}修改失败'.format(store_id)) store_have_problem_list.append(store_id) else: print('{}修改失败'.format(store_id)) store_have_problem_list.append(store_id) else: print('{}未获得payload'.format(store_id)) store_have_problem_list.append(store_id) else: print('{}修改失败!'.format(store_id)) store_have_problem_list.append(store_id) return store_info = get_store_id() for u, t in update_dic.items(): print(u, t) store_id = store_info.get(str(u)) change_comm_shop_id(store_id, t) print(u, t, '更新成功!!!!!') # print(store_id)<file_sep>import requests import hashlib import copy secret_key = '<KEY>' member_code = 'M00016001736' ticket_id = '34f725b787ff40db9d1e876313802de6' def generate_sign(request_body): # type: (dict) -> str # 雪沥的签名方法, 从 request_body 中生成签名 sorted_keys = sorted(copy.copy(list(request_body.keys()))) l = [] for k in sorted_keys: if request_body.get(k) is None: # 如果值是空不参与排序 continue v = request_body[k] if type(v) is list or type(v) is dict: continue s = '{}={}'.format(k, v) l.append(s) l.append('key={}'.format(secret_key)) s = '&'.join(l).encode() r = hashlib.md5(s).hexdigest() return r data = dict( memberCode=member_code, externalId=ticket_id, ) url = 'https://openapi.dairyqueen.com.cn/openapi/order/cancelSubmitOrder' headers = { 'sign': generate_sign(data), 'Content-Type': 'application/json' } headers.update(dict( tenantId='1', channelId='105' )) print(headers) res = requests.post(url, data=data, headers=headers) print(res.content)<file_sep>nums = [2, 3, 6, 5, 1, 4, 8, 11, 0, 7] def quick_sort(nums): if not nums: return [] else: pivot = nums[0] quick_left = [i for i in nums[1:] if i < pivot] quick_right = [i for i in nums[1:] if i >= pivot] return quick_sort(quick_left) + [pivot] + quick_sort(quick_right) print(quick_sort(nums)) <file_sep>import redis import time REDIS_HOST = 'localhost' REDIS_PORT = 6379 REDIS_DB = 0 ERROR_THRESHOLD = 3 ERROR_WINDOW = 5 * 60 # 5 minutes def log_error(redis_client, error_timestamp): redis_client.zadd('error_log', {error_timestamp: time.time()}) def get_error_log(redis_client): error_log = redis_client.zrange('error_log', 0, -1, withscores=True) return error_log def remove_old_errors(redis_client): old_timestamp = time.time() - ERROR_WINDOW redis_client.zremrangebyscore('error_log', 0, old_timestamp) def check_errors(redis_client): remove_old_errors(redis_client) error_log = get_error_log(redis_client) if len(error_log) < ERROR_THRESHOLD: return False error_count = 0 first_error_timestamp = None for timestamp, score in error_log: if first_error_timestamp is None: first_error_timestamp = timestamp error_count += 1 if error_count >= ERROR_THRESHOLD: time_range = (first_error_timestamp, timestamp) return time_range if time.time() - timestamp > ERROR_WINDOW: error_count = 0 first_error_timestamp = None return False if __name__ == '__main__': r = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB) log_error(r, 'error1') log_error(r, 'error2') log_error(r, 'error3') log_error(r, 'error4') log_error(r, 'error5') time_range = check_errors(r) if time_range: print(f'Continuous errors found: {time_range}') # do something to handle continuous errors else: print('No continuous errors found') <file_sep># class A: # def test_a(self): # self.test_a_a() # print('123AAAA') # def test_a_a(self): # print('123A_a_A_A_A_A_A_') # def send(self): # self.test_a() # class B(A): # def test_a(self): # super(B, self).test_a() # print('456BBBB') # def test_a_a(self): # print('456A_a_A_A_A_A_A_') # b = B() # b.test_a() # def func1_1(name): # print(name) # def func1(func): # print('func1_inner') # def func1_inner(*args, **kwargs): # print('func1_inner_inner_inner:start') # a =func(*args, **kwargs) # print('func1_inner_inner_inner:end') # return a # return func1_inner # return func1 # def func2_2(name): # print(name) # def func2(func): # print('func2_inner') # def func2_inner(*args, **kwargs): # print('func2_inner_inner_inner:start') # a = 1 # if 5 > 2: # a = func(*args, **kwargs) # print('func2_inner_inner_inner:end') # return a # return func2_inner # return func2 # @func1_1('1') # @func2_2('2') # def test(a): # print('a: %s' % a) # test(2) import gevent from gevent import monkey import time monkey.patch_all() def test1(): for i in range(10): time.sleep(0.2) print('1:%s' % i) def test2(): for i in range(10): time.sleep(0.1) print('2:%s' % i) def test3(): for i in range(10): time.sleep(0.1) print('3:%s' % i) j1 = gevent.spawn(test1) j2 = gevent.spawn(test2) j3 = gevent.spawn(test3) j1.join() j3.join() j2.join() <file_sep>import openpyxl path = '/Users/hws/Downloads/product_market_price{}.xlsx' result = [] for i in range(1, 6): wb = openpyxl.load_workbook(path.format(i)) sh = wb['Sheet1'] rows = sh.max_row cols = sh.max_column print(rows) result.append(()) for c in range(2, rows + 1): if sh.cell(c, 1).value: result.append((sh.cell(c, 1).value, sh.cell(c, 2).value, sh.cell(c, 3).value, sh.cell(c, 4).value, sh.cell(c, 5).value)) outwb = openpyxl.Workbook() outws = outwb.create_sheet(index=0) title = ['商品名称', '商品编码', '市场区域名称', '市场区域编码', '价格'] for i in range(1, 6): outws.cell(1, i).value = title[i -1] index = 2 for product in result: print(product) if not product: continue outws.cell(index, 1).value = product[0] outws.cell(index, 2).value = product[1] outws.cell(index, 3).value = product[2] outws.cell(index, 4).value = product[3] outws.cell(index, 5).value = product[4] index += 1 filename = '/Users/hws/Downloads/product_market_price_all.xlsx' print(filename + ' down!!') outwb.save(filename) <file_sep>import requests import json corip_id = 'wwd3c8a2e69de3864a' s_id = 'l9bORWigG1hdNdbdImMj9KL6tmf3qK7QRgknUUDkAgE' a_id = '1000003' # token = '<KEY>' def get_token(c_id, s_id): url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}'.format(c_id, s_id) response = requests.get(url) print(response.json()) token = response.json().get('access_token') return token def get_agent_scope(token): url = 'https://qyapi.weixin.qq.com/cgi-bin/agent/get?access_token={}&agentid={}'.format(token, a_id) resp = requests.get(url) print(resp.json()) def get_user_info(token, u_id): url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={}&userid={}'.format(token, u_id) resp = requests.get(url) print(resp.json()) def send_message(token, u_id): url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={}'.format(token) data = { "touser" : u_id, "msgtype": "text", "agentid": a_id, "text": { "content": "<a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwd3c8a2e69de3864a&redirect_uri=http%3A%2F%2Fh5.store.meet-xiaomian.com%2Flogin&response_type=code&scope=snsapi_userinfo&agentid=1000002&state=YMHexLogin&connect_redirect=1#wechat_redirect\">有物料即将过期,请查看</a>" } } requests.post(url, json.dumps(data)) def get_department(toekn): url = 'https://qyapi.weixin.qq.com/cgi-bin/department/get?access_token={}&id=2'.format(token) resp = requests.get(url) print(resp.json()) token = get_token(corip_id, s_id) get_user_info(token, 'peng.zhen') # print(get_token(corip_id, s_id)) # get_agent_scope(token) # send_message(token, 'CeShiGongSi') # get_department(token)<file_sep>import pymongo from dateutil.parser import parse from datetime import datetime mongo_client = pymongo.MongoClient(host='127.0.0.1', port=27071,) db_name = mongo_client.saas_dq # db_name = mongo_client.saas_dq_uat start_date = '2021-08-01T00:00:00.000Z' end_date = '2021-08-03T00:00:00.000Z' query = { "store_us_id": 46269, "created": { "$gte": parse(start_date), "$lt": parse(end_date) } } # query = { # 'payload.body.order_unique_no': 'af17f761772047948e9ba760ff436a30' # } result = db_name.pos.find(query, {'_id': 1, 'created': 1, 'payload.body.order_unique_no': 1}) for i in result: print(i['_id'], i['created'], i['payload']['body']['order_unique_no']) created_time = str(i['created']).split(' ')[1].split(':') now_time = datetime(2021, 8, 11, int(created_time[0]), int(created_time[1]), int(created_time[2])) print(now_time) db_name.pos.update_one({ 'payload.body.order_unique_no': i['payload']['body']['order_unique_no'] }, { '$set': {'created': now_time} } ) <file_sep>import requests import json import time import xlrd from openpyxl import Workbook, load_workbook #请求头部 authorization = '<KEY>' hex_server_session = '525109fb-8292-46bf-91fe-d5c2e0c4afb7' test_url = 'http://test.dairyqueen.com.cn' store_url = 'http://store.dairyqueen.com.cn' store_ppj_url = 'http://store.papajohnshanghai.com' test_be_url = 'http://hwstest.brutcakecafe.com' store_be_url = 'http://store.brutcakecafe.com' headers1 = { 'authorization': '{}'.format(authorization), 'Cookie': 'hex_server_session={}'.format(hex_server_session), } headers2 = { 'authorization': '{}'.format(authorization), 'Content-Type': 'application/json', 'Cookie': 'hex_server_session={}'.format(hex_server_session), } final_url = store_ppj_url product_category_dict = { # "气泡酒": "4090051089326727169", # "红葡萄酒": "4040457617528483841", # "白葡萄酒": "4040457445163560961", # "桃红葡萄酒": "4090050979716980737", # "香槟": "4254888438505357313", # "自然酒": "4304491642519732225", # "创意特调": "4040458597879934977", # "水果特饮": "4129830273809276929", # "啤酒": "4297596158832197633", # "烈酒": "4297575309534216193", # "Brunch": "4225906075867734017", # "加料": "4040460792524337153", # "鸡尾酒": "4142559571498360833" "干货>原材料>干货-食材": "3932463413040226305", "干货>包材>干货-包材": "3932463417993699329", "干货>市场宣传品>干货-市场宣传品": "3932463420227198977", "干货>营运物料>干货-营运物料": "3932463418498736129", "干货>清洁用品>干货-清洁用品": "3932463419733700609" } def get_product_id(id): """ 根据商品编码拿到商品id """ url = final_url + '/api/v1/product?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&include_state=true&relation=all'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) product_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(id): product_id = i['id'] old_category_id = str(i['relation']['product_category']) except IndexError as e: print('物料编码{}不存在'.format(id)) return # dic = data['payload'][0] # product_id = dic['id'] # print('product_id', product_id) # data = json.dumps(data, sort_keys=True, indent=4, separators=(',', ':')) # print(type(data), data) # print(product_id) if not product_id: print('物料编码{}不存在'.format(id)) return return product_id, old_category_id def change_category(id, category_id): url = final_url + '/api/v1/product/{}?stringified=true'.format(id) s = {"relation": {"product_category": '{}'.format(category_id)}} # print(s) data = json.dumps(s) response = requests.request("PUT", url, headers=headers1, data=data) data = response.json() return def get_request_id2(id): """ 拿到所有变更计划的 request_id """ url = final_url + '/api/v1/product/task?stringified=true&include_total=true&record_id={}&order=asc&offset=0&limit=1'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() dic = data['payload'] lis = dic['rows'] # print('lis', lis) approve_id = lis[0]['id'] return approve_id def confirm_changes2(request_id): """ 审核变更计划 """ url = final_url + '/api/v1/product/task/{}/status/APPROVED?stringified=true'.format(request_id) # print(url) response = requests.request("PUT", url, headers=headers1) data = response.json() # print(data) # time.sleep(0.1) return def get_request_id(code): url = final_url + '/api/v1/product?search={}'.format(code) # print(url) response = requests.get(url, headers=headers1) data = response.json() # print(type(data), data) request_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(code): request_id = i['request_id'] name = i['name'] except IndexError as e: print('物料编码{}不存在'.format(id)) return if not request_id: print('物料编码{}不存在'.format(id)) return return request_id, name def accept_action2(name, request_id): """ 接受更改操作,用map去拼接正确的名字 eg.DQ全国 """ url = final_url + '/api/v1/product/change/{}/to/task?stringified=true'.format(request_id) s = {"name": "{}".format(name), "immediate": True, "start_time": ""} # print(s) data = json.dumps(s, ensure_ascii=False).encode("utf-8") # print(data) response = requests.post(url, headers=headers2, data=data) data2 = response.json() # time.sleep(0.1) return def one_trun(code, name_, category, category_name): product_id, old_category = get_product_id(code) if not product_id: print('物料编码{}不存在'.format(id)) return if category == old_category: print('商品{}原分类已经为{}不用修改'.format(name_, category_name)) return change_category(product_id, category) request_id, name = get_request_id(code) accept_action2(name, request_id) request_id2 = get_request_id2(product_id) confirm_changes2(request_id2) print('商品{}更改分类为{}'.format(name, category_name)) return def test(): wb = Workbook() ws = wb.active file_path = '/Users/hws/Downloads/PPJHEX物料属性分类修改-20221103.xlsx' # file_path = '/Users/hws/Downloads/ttttqqq.xlsx' # 打开一个已有文件 wb = load_workbook(file_path) sheet_list = wb.sheetnames sheet = wb[wb.sheetnames[0]] total_list = [] for r in range(2, sheet.max_row + 1): row_list = [] # 每一行建立一个list for c in range(1, sheet.max_column + 1): v = str(sheet.cell(r, c).value) v = v.replace('\n', '') row_list.append(v) total_list.append(row_list) print(len(total_list), total_list) return total_list if __name__ == '__main__': lis = test() for i in lis: product_category = product_category_dict[i[3]] # product_category = 4115420549723475969 one_trun(i[1], i[0], product_category, i[3]) print('----------------------------------') time.sleep(2) # 使用说明:打开网页获取此时的authorization; 全局修改url为想要执行的品牌; 转换模版格式 # 批量执行时, 可能会因执行一直发请求等原因报错, 重新执行即可————这条不确定,建议从执行失败的重新执行 # 文件格式如下:商品编码| 商品名称 |商品分类 # 9330146 | BTG10004旭金堡副牌 |气泡酒 # 8010000029 | SW10001一束花莫斯卡托阿斯蒂微起泡甜白 |红葡萄酒 # 第三个参数为导入商品的分类,暂时做法从页面上去取,因此product_category_dict里必须有该分类 # for i in lis: # get_product_id(i[0]) <file_sep># coding: utf-8 # ssh -N -L 4151:192.168.2.159:4151 [email protected] -p 2637 import requests url = 'http://localhost:4155/pub?topic=1101.supply.stocktake.store.upload' def fix(): ll = [4682348969091694593,4682348981875933195,4682348570213384198,4682348579222749184,4682348590627061761,4682348831728238592,4682348889605439489,4682348973667680259,4682348597287616516,4682348837348605954,4682349264991453189] for l in ll: body = '{"doc_id":"%s"}' % l req = requests.post(url, data=body) print(req.text) fix()<file_sep>import requests import openpyxl ######################参数修改部分################ env = 'be' host = { 'dq_host': 'https://store.dairyqueen.com.cn', 'ppj_host': 'https://store.papajohnshanghai.com', 'xm_host': 'http://store.meet-xiaomian.com', 'be_host': 'http://store.brutcakecafe.com' } category_id = 4442541390362423297 # 该env环境下的分类ID base_info = { 'url': '{}/api/v1/product'.format(host.get('{}_host'.format(env))), 'unit_url': '{}/api/v1/product/unit'.format(host.get('{}_host'.format(env))), 'headers': { 'authorization': '{}'.format('Bearer 2fJE1BOPR1UKLmjCxH8ZhBvrTVtmIT'), # 该env环境下的authorization 'Cookie': 'hex_server_session={}'.format('2ca26a03-7fd2-4670-864f-9ddff211cbfb'), # 该env环境下的Cookie } } request_unit_url = '{}/api/v1/product/unit'.format(host.get('{}_host'.format(env))), filename2 = '/Users/hws/Downloads/{}_product_unit_rate.xlsx'.format(env) ######################参数修改部分################ response = requests.get(request_unit_url, headers=base_info.get('headers'),) unit_info = response.json()['payload'] unit_dic = {} for unit in unit_info: unit_dic[str(unit['id'])] = unit['name'] response = requests.get(base_info.get('url'), headers=base_info.get('headers'), params={'category': category_id, 'relation': 'all'}) res_json = response.json() product_list = res_json['payload'] outwb = openpyxl.Workbook() outws = outwb.create_sheet(index=0) title = ['商品编码', '商品名称', '名称', '换算比率', '核算单位', '销售单位', '配方单位', '订货单位', '盘点单位', '复核单位'] for i in range(1, 11): outws.cell(1, i).value = title[i -1] index = 2 for product in product_list: p_code = product['code'] p_name = product['name'] unit_info = product.get('relation').get('unit') or [] for col in range(len(unit_info)): outws.cell(index, 1).value = p_code outws.cell(index, 2).value = p_name outws.cell(index, 3).value = unit_dic[str(unit_info[col].get('id'))] or '' outws.cell(index, 4).value = unit_info[col].get('rate') or False outws.cell(index, 5).value = unit_info[col].get('default') or False outws.cell(index, 6).value = unit_info[col].get('sales') or False outws.cell(index, 7).value = unit_info[col].get('bom') or False outws.cell(index, 8).value = unit_info[col].get('order') or False outws.cell(index, 9).value = unit_info[col].get('stocktake') or False outws.cell(index, 10).value = unit_info[col].get('recheck') or False index += 1 print(filename2 + ' down!!') outwb.save(filename2)<file_sep>import requests import json import time import xlrd from openpyxl import Workbook, load_workbook #请求头部 authorization = 'Bearer rH47mdvlctEnVE61bBbiD5HhUdAGFm' hex_server_session = '9ab1418d-f21d-4b53-9db6-aec3509aa04d' test_url = 'http://test.dairyqueen.com.cn' store_url = 'http://store.dairyqueen.com.cn' store_ppj_url = 'http://store.papajohnshanghai.com' test_be_url = 'http://hwstest.brutcakecafe.com' store_be_url = 'http://store.brutcakecafe.com' headers1 = { 'authorization': '{}'.format(authorization), 'Cookie': 'hex_server_session={}'.format(hex_server_session), } headers2 = { 'authorization': '{}'.format(authorization), 'Content-Type': 'application/json', 'Cookie': 'hex_server_session={}'.format(hex_server_session), } product_category_dict = { "蔬菜碗": "4683546227026006017", "分享盘": "4683548178824400897", "小食": "4683550940505149441", "意面": "4683551127923429377", "三明治": "4683551245649154049", "主菜": "4683551541041401857", "蛋糕": "4683551630157778945", "咖啡": "4683551793865658369", "果汁": "4683551861532364801", "茶": "4683551934597140481", "水果特饮": "4683552040654311425", "鸡尾酒": "4683552203510747137" } final_url = store_be_url def get_product_id(id): """ 根据商品编码拿到商品id """ url = final_url + '/api/v1/product?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&include_state=true'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) product_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(id): product_id = i['id'] except IndexError as e: print('物料编码{}不存在'.format(id)) return # dic = data['payload'][0] # product_id = dic['id'] # print('product_id', product_id) # data = json.dumps(data, sort_keys=True, indent=4, separators=(',', ':')) # print(type(data), data) # print(product_id) if not product_id: print('物料编码{}不存在'.format(id)) return return product_id def create_one_product(code, name, category): """ 创建新商品 """ url = final_url + '/api/v1/product?stringified=true' false = False null = None s = {"code": "{}".format(code), "name": "{}".format(name), "name_en": "", "main_type": "NORMAL", "bom_type": "MADE", "storage_type": "NORMALTP", "category": "{}".format(category), "spec": "", "retail": null, "is_cup_measure": false, "extends": {}, "accounting_type": "MA", "brand_id": "3809835199387140099", "operation_type": "SELFSPT", "status": "ENABLED", "relation": {"product_category": "{}".format(category), "tag": []}, "extend_code": {"spec_1": ""}, "alarm_stock": null, "display_order": null} # print(s) data = json.dumps(s) response = requests.request("POST", url, headers=headers1, data=data) data = response.json() return def accept_new_product(product_id): url = final_url + '/api/v1/product/{}/state/enable?stringified=true'.format(product_id) response = requests.request("PUT", url, headers=headers1) data = response.json() return def create_region_attribute(product_id): url = final_url + '/api/v1/product/{}/region/attribute?stringified=true'.format(product_id) false = False true = True s = {"attribute": [{"id": "4027811609199616001", "inventory_type": "COUNT", "stocktake_circle": "DWM", "allow_adjust": true, "allow_stocktake": true, "allow_transfer": true}]} # 添加属性区域,默认全国属性区域 data = json.dumps(s) response = requests.request("PUT", url, headers=headers2, data=data) data1 = response.json() return def get_region_rel_id(product_id): url = final_url + '/api/v1/product/{}/region/attribute?stringified=true&include_total=true&is_task=true&order=asc' \ '&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true'.format(product_id) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() dic = data['payload'] lis = dic['rows'] rel_id = lis[0]['rel_id'] return rel_id def accept_region_attribute(rel_id): url = final_url + '/api/v1/product/region/attribute/{}/state/enable?stringified=true'.format(rel_id) response = requests.request("PUT", url, headers=headers1) data = response.json() return def add_unit(product_id): url = final_url + '/api/v1/product/{}/unit?stringified=true'.format(product_id) false = False true = True s = [{"id": "4027815141868937217", "rate": 1, "default": true, "stocktake": true, "sales": true, "bom": true, "order": true, "recheck": false}] # 默认添加单位:个 data = json.dumps(s) response = requests.request("PUT", url, headers=headers2, data=data) data1 = response.json() return def get_request_id(code): url = final_url + '/api/v1/product?search={}'.format(code) # print(url) response = requests.get(url, headers=headers1) data = response.json() # print(type(data), data) request_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(code): request_id = i['request_id'] except IndexError as e: print('物料编码{}不存在'.format(id)) return if not request_id: print('物料编码{}不存在'.format(id)) return return request_id def accept_unit(request_id, name): url = final_url + '/api/v1/product/change/{}/to/task?stringified=true'.format(request_id) true = True s = {"name": "{}".format(name), "immediate": true, "start_time": ""} # print(s) data = json.dumps(s) response = requests.request("POST", url, headers=headers1, data=data) data = response.json() return def confirm_unit(product_id): url = final_url + '/api/v1/product/task?stringified=true&include_total=true&record_id={}&order=asc'.format(product_id) response = requests.get(url, headers=headers1) data = response.json() dic = data['payload'] lis = dic['rows'] # print('lis', lis) request_id = lis[0]['id'] return request_id def approve_unit(request_id): url = final_url + '/api/v1/product/task/{}/status/APPROVED?stringified=true'.format(request_id) response = requests.request("PUT", url, headers=headers1) data = response.json() return def one_trun(code, name, category): create_one_product(code, name, category) print('创建商品{}'.format(name)) product_id = get_product_id(code) if not product_id: print('物料编码{}不存在'.format(code)) return accept_new_product(product_id) print('生效商品{}'.format(name)) create_region_attribute(product_id) rel_id = get_region_rel_id(product_id) accept_region_attribute(rel_id) print('商品{}添加属性区域'.format(name)) add_unit(product_id) request_id = get_request_id(code) accept_unit(request_id, name) request_id2 = confirm_unit(product_id) approve_unit(request_id2) print('商品{}添加单位'.format(name)) return def test(): wb = Workbook() ws = wb.active file_path = '/Users/hws/Downloads/be合阔主档导入-20221028.xlsx' # 打开一个已有文件 wb = load_workbook(file_path) sheet_list = wb.sheetnames sheet = wb[wb.sheetnames[0]] total_list = [] for r in range(2, sheet.max_row + 1): row_list = [] # 每一行建立一个list for c in range(1, sheet.max_column + 1): v = str(sheet.cell(r, c).value) v = v.replace('\n', '') row_list.append(v) total_list.append(row_list) print(len(total_list), total_list) return total_list if __name__ == '__main__': lis = test() for i in lis: product_category = product_category_dict[i[11]] one_trun(i[1], i[2], product_category) print('----------------------------------') time.sleep(0.1) # 使用说明:打开网页获取此时的authorization; 全局修改url为想要执行的品牌; 转换模版格式 # 批量执行时, 可能会因执行一直发请求等原因报错, 重新执行即可————这条不确定,建议从执行失败的重新执行 # 文件格式如下:商品编码| 商品名称 |商品分类 # 9330146 | BTG10004旭金堡副牌 |气泡酒 # 8010000029 | SW10001一束花莫斯卡托阿斯蒂微起泡甜白 |红葡萄酒 # 第三个参数为导入商品的分类,暂时做法从页面上去取,因此一次导入的商品分类必须一致 # 0810:优化成做成map,需要更新的分类放在product_category_dict中 # for i in lis: # get_product_id(i[0]) <file_sep>class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sortList(head: ListNode) -> ListNode: # 递归终止条件:链表为空或只有一个节点 if not head or not head.next: return head # 使用快慢指针找到链表中点 slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next # 将链表拆分成两个子链表 mid = slow.next slow.next = None # 对两个子链表分别进行归并排序 left = sortList(head) right = sortList(mid) # 合并两个有序子链表 dummy = ListNode(0) curr = dummy while left and right: if left.val < right.val: curr.next = left left = left.next else: curr.next = right right = right.next curr = curr.next curr.next = left or right return dummy.next """ 给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 例子:head = [4,2,1,3] 输出:[1,2,3,4] 使用方法: 假设链表为 head = ListNode(4, ListNode(2, ListNode(1, ListNode(3)))) ,则调用 sortList(head) 即可得到排好序的链表。 注意:代码中的 ListNode 类定义了链表节点的数据结构,它包含一个 val 属性表示节点的值,以及一个 next 属性表示下一个节点的指针。在调用 sortList 函数时,需要传入链表的头节点 head。 """<file_sep># coding: utf-8 # param = "{\n" + \ # "\"columnNames\": [\n" + \ # "\"location_id\",\n" + \ # "\"store_id\",\n" + \ # "\"store_name\",\n" + \ # "\"b_date\",\n" + \ # "\"serial\",\n" + \ # "\"start_time\",\n" + \ # "\"end_time\",\n" + \ # "\"receivable\",\n" + \ # "\"real_income\",\n" + \ # "\"discount_amount\",\n" + \ # "\"is_chargeback\",\n" + \ # "\"chargeback\",\n" + \ # "\"time\",\n" + \ # "\"refresh_time\",\n" + \ # "],\n" + \ # "\"keyCol\":\"store_id,serial\",\n" + \ # "\"records\": [\n" + \ # "[\n" +\ # "\"%(location_id)s\",\n" + \ # "\"%(store_id)s\",\n" + \ # "\"%(store_name)s\",\n" + \ # "\"%(b_date)s\",\n" + \ # "\"%(serial)s\",\n" + \ # "\"%(start_time)s\",\n" + \ # "\"%(end_time)s\",\n" + \ # "\"%(receivable)s\",\n" + \ # "\"%(real_income)s\",\n" + \ # "\"%(discount_amount)s\",\n" + \ # "\"%(is_chargeback)s\",\n" + \ # "\"%(chargeback)s\",\n" + \ # "\"%(time)s\",\n" + \ # "\"%(refresh_time)s\",\n" + \ # "],\n" + \ # "],\n" + \ # "\"tableName\": \"Business\"\n" + \ # "}" # param = param % { # 'location_id': "200851", # 'store_id': "110010082", # 'store_name': "DQ", # 'b_date': "2022-10-21", # 'serial': 46809992755463782411111, # 'start_time': "2022-10-21 10:18:34", # 'end_time': "2022-10-21 10:18:34", # 'receivable': 53.0, # 'real_income': 53.0, # 'discount_amount': 0, # 'is_chargeback': "否", # 'chargeback': 0, # 'time': "2022-10-21 11:42:22", # 'refresh_time': "2022-10-21 11:42:22" # } # # print(param) # # import base64 # # from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher # # from Crypto.PublicKey import RSA # # def encryption(text, public_key): # # # 字符串指定编码(转为bytes) # # text = text.encode('utf-8') # # # 构建公钥对象 # # cipher_public = PKCS1_cipher.new(RSA.importKey(public_key)) # # text_encrypted = cipher_public.encrypt(text) # # # base64编码,并转为字符串 # # # print(text_encrypted) # # text_encrypted_base64 = base64.b64encode(text_encrypted) # # return text_encrypted_base64 # # public_key = """-----BEGIN RSA PUBLIC KEY----- # # <KEY> # # -----END RSA PUBLIC KEY----- # # """ # # qiye_code = '000062' # # qiye_ser = '38ab46f762e63b64' # # a = encryption(qiye_code, public_key) # # b = encryption(qiye_ser, public_key) # # print('corporationCode: %s' % a) # # print('ser: %s' % b) # # from pyDes import des, CBC, PAD_PKCS5, ECB # # def des_encrypt(s): # # # secret_key = KEY[:8] # # # iv = secret_key # # # k = des(secret_key, CBC, b'00000000', pad=None, padmode=PAD_PKCS5) # # # # print(k.__dict__) # # # k.setKey(base64.b64decode(qiye_ser)) # # # # print(k.__dict__) # # # en = k.encrypt(s, padmode=PAD_PKCS5) # # secret_key1 = b'%s' % base64.b64decode(qiye_ser) # # secret_key = secret_key1[:8] # # iv = secret_key # # k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5) # # # k.setKey(base64.b64decode(qiye_ser)) # # en = k.encrypt(s, padmode=PAD_PKCS5) # # return base64.b64encode(en) # # data = des_encrypt(param) # # print('*' * 10) # # print('data: %s' % data) # # from Crypto.Cipher import DES # # def new_des(s_data): # # pad = 8 - len(s_data) % 8 # # pad_str = "" # # for i in range(pad): # # pad_str = pad_str + chr(pad) # # generator = DES.new(base64.b64decode(qiye_ser)[:8], DES.MODE_ECB) # # encrypted = generator.encrypt(s_data + pad_str) # # new_data = base64.b64encode(encrypted) # # return new_data # # new_data = new_des(param) # # print('new_data: %s' % new_data) # # import requests # # data = { # # 'corporationCode': a, # # 'data': new_data # # } # # res = requests.post('https://bi.tcsl.com.cn:8055/lb/api/data/str', json=data, headers={'Content-Type': 'application/json; charset=utf-8'}) # # print(res.json()) # # generator = DES.new(base64.b64decode(qiye_ser)[:8], DES.MODE_ECB) # # origin_str = generator.decrypt(base64.b64decode(new_data)) # # print(len(origin_str)) # # print(type(origin_str)) # # print(eval(origin_str)) # a = {'247': '12321', '136': "23123", '123': '23454231', '112': '2341'} # print(a) def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) import time a = time.time() print(fib(40)) b = time.time() print(b -a) <file_sep># -*- coding: utf-8 -*- from copy import deepcopy import json from set_meal import meal def get_order_product_db_map(order_info): """ 本次开发修改内容: 1、在此把套餐结构转化为单品,此后所有逻辑都不需要改动 2、套餐内属性分别加在 每个 "propertyMemo":"drink"的⼦项上 3、套餐内加料放在 第一个 "propertyMemo":"drink"的⼦项上 4、分摊金额,最后一个子项调整尾差 5、在修改后的子项转单品上新增 set_meal_id 记录原套餐ID,在部分退时找商品时用 property_adding_product举例: {"10001":{"property":[{"pid":610172,"items":[{"uid":2428177,"name":"冷","nameEn":"","nameTw":"","price":0, "realTimePrice":0,"editType":0,"isStandardType":False,"itemType":3,"weight":0,"mealFee":0,"mulMealFee":0, "part":0,"selectNum":1,"num":1,"bizType":0,"materialCost":0,"totalPrice":0}],"type":3,"editType":0, "propertyMemo":""}],"adding":[{"index":0,"totalPrice":0,"mealFee":0,"uid":800941492,"weight":0, "itemProduct":{"extMappingType":0,"pid":0,"extId":"83910039"},"bizType":0,"isStandardType":true,"price":0, "editType":0,"name":"不加料","num":1,"nameTw":"","mulMealFee":0,"materialCost":0,"part":0,"realTimePrice":0, "nameEn":"","itemType":1}],"drink":[{"uid":2428180,"name":"大口草莓","nameEn":"", "nameTw":"","price":0,"realTimePrice":0,"editType":0,"isStandardType":False,"itemType":2,"weight":0,"mealFee":0, "mulMealFee":0,"part":0,"selectNum":2,"num":2,"bizType":0,"materialCost":0,"totalPrice":0}], "other":[{"pid":610174,"items":[{"uid":2428182,"name":"牛角包","nameEn":"", "nameTw":"","price":0,"realTimePrice":0,"editType":0,"isStandardType":False,"itemType":2,"weight":0,"mealFee":0, "mulMealFee":0,"part":0,"selectNum":1,"num":1,"bizType":0,"materialCost":0,"totalPrice":0}],"type":2, "editType":0,"propertyMemo":"bread"}]}} """ new_products = [] fix_products = deepcopy(order_info.get('products', [])) # 先取出套餐内的属性和加料 property_addition_product = {} for index, product in enumerate(fix_products): if product.get('nameTw') == 'Set': default_key = product.get('extId') + '_' + str(index) property_addition_product.setdefault(default_key, {}) # 记录所有单品加料的总价格 property_addition_product[default_key].setdefault('single_product_all_price', 0) for lr in product.get('listRequirements'): for pr in lr.get('propertys'): property_addition_product[default_key].setdefault('property', []) property_addition_product[default_key].setdefault('addition', []) property_addition_product[default_key].setdefault('drink', []) property_addition_product[default_key].setdefault('other', []) # 属性 if pr.get('propertyMemo') == 'property': property_addition_product[default_key]['property'].append(pr) # 加料 elif pr.get('propertyMemo') == 'addition': for inner_product in pr.get('items'): property_addition_product[default_key]['addition'].append(inner_product) property_addition_product[default_key]['single_product_all_price'] += \ round(inner_product.get('price') * inner_product.get('num'), 2) # 饮品,餐道:一个套餐内可能有多个drink,每个drink里可能有多个单品 elif pr.get('propertyMemo') == 'drink': for inner_product in pr.get('items'): property_addition_product[default_key]['drink'].append(inner_product) property_addition_product[default_key]['single_product_all_price'] += \ round(inner_product.get('price') * inner_product.get('num'), 2) # 面包以及其他,先放在一起 else: for inner_product in pr.get('items'): property_addition_product[default_key]['other'].append(inner_product) property_addition_product[default_key]['single_product_all_price'] += \ round(inner_product.get('price') * inner_product.get('num'), 2) print('--' * 10) print(json.dumps(property_addition_product)) print('--' * 10) for index, product in enumerate(fix_products): if not product.get('nameTw'): # 单品直接添加 new_products.append(product) elif product.get('nameTw') == 'Set': # 套餐特殊处理 default_key = product.get('extId') + '_' + str(index) set_meal_price = set_meal_price_copy = product.get('totalPrice') / product.get('num') # 单个套餐价格 single_product_all_price = property_addition_product.get(default_key).\ get('single_product_all_price') # 设置一个序列,在退款时按照此序列在最后一个单品补尾差 seq_id = 0 # 先处理drink以外的单品 for other_product in property_addition_product.get(default_key).get('other'): single_price = round((other_product.get('price') * 1.0 / single_product_all_price) * set_meal_price, 2) # 考虑到一个套餐内可能有相同单品,减去倍数值 set_meal_price_copy -= (single_price * other_product.get('num')) new_products.append({ 'extId': other_product.get('itemProduct', {}).get('extId'), 'num': other_product.get('num') * product.get('num'), 'name': other_product.get('name'), 'realTimePrice': single_price, 'realTimeTotalPrice': single_price * other_product.get('num') * product.get('num'), # 以下字段是字部分退款时需要 'set_meal_id': default_key, 'set_seq_id': seq_id, 'set_meal_price': set_meal_price, 'set_single_rate': other_product.get('num'), 'set_refund_qty': 0, 'set_meal_qty': product.get('num') }) seq_id += 1 drink_len = len(property_addition_product.get(default_key).get('drink')) for index, drink_product in enumerate(property_addition_product.get(default_key).get('drink')): # 加料只在第一个单品添加,属性全部都有 list_requirements = deepcopy([{ 'propertys': property_addition_product.get(default_key).get('property') or [], 'num': drink_product.get('num') * product.get('num') }]) if index == 0: for add_product in property_addition_product.get(default_key).get('addition'): add_price = round(add_product.get('realTimePrice') * 1.0 / single_product_all_price * set_meal_price, 2) add_product['realTimePrice'] = add_price list_requirements[0]['propertys'].append({ 'items': [add_product] }) # 考虑到一个套餐内可能有相同加料,减去倍数值 set_meal_price_copy -= (add_price * add_product.get('num')) if index == (drink_len - 1): single_price = round(set_meal_price_copy / drink_product.get('num'), 2) else: single_price = round((drink_product.get('price') * 1.0 / single_product_all_price) * set_meal_price, 2) # 考虑到一个套餐内可能有相同单品,减去倍数值 set_meal_price_copy -= (single_price * drink_product.get('num')) new_products.append({ 'extId': drink_product.get('itemProduct', {}).get('extId'), 'num': drink_product.get('num') * product.get('num'), 'name': drink_product.get('name'), 'realTimePrice': single_price, 'realTimeTotalPrice': single_price * drink_product.get('num') * product.get('num'), 'listRequirements': list_requirements, # 以下字段是字部分退款时需要 'set_meal_id': default_key, 'set_seq_id': seq_id, 'set_meal_price': set_meal_price, 'set_single_rate': drink_product.get('num'), 'set_refund_qty': 0, 'set_meal_qty': product.get('num') }) seq_id += 1 else: logging.info('报文商品结构既不是单品也不是套餐: %s' % product) raise DataValidationException(ErrorCode.DataNotValid, error_msg="商品结构有误!") order_info['products'] = new_products print(json.dumps(order_info)) meal = json.loads(meal) get_order_product_db_map(meal.get('data')) <file_sep>import requests import json import time import xlrd from openpyxl import Workbook, load_workbook #请求头部 authorization = 'Bearer <KEY>' hex_server_session = '10dc48db-916e-4009-b524-011de6111cf1' test_url = 'http://test.dairyqueen.com.cn' store_url = 'http://store.dairyqueen.com.cn' store_ppj_url = 'http://store.papajohnshanghai.com' test_be_url = 'http://hwstest.brutcakecafe.com' store_be_url = 'http://store.brutcakecafe.com' headers = { 'Connection': 'keep-alive', 'Host': 'test.dairyqueen.com.cn', 'Cache-Control': 'max-age=0', 'authorization': '{}'.format(authorization), 'content-type': 'application/json', 'Accept': '*/*', 'Origin': 'http://store.papajohnshanghai.com/', 'Referer': 'http://store.papajohnshanghai.com/', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cookie': 'hex_server_session={}'.format(hex_server_session), } headers1 = { 'authorization': '{}'.format(authorization), 'Cookie': 'hex_server_session={}'.format(hex_server_session), } headers2 = { 'authorization': '{}'.format(authorization), 'Content-Type': 'application/json', 'Cookie': 'hex_server_session={}'.format(hex_server_session), } no_id = [] no_id_name = [] have_id = [] have_id_name = [] promotion_id_dic = {} def get_Promotion(id): """ 取得促销 discount_meta 的id """ url = test_url + '/api/v1/promotion/rule?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&include_state=true'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) try: dic = data['payload'] except IndexError as e: print('促销编码{}不存在'.format(id)) return if len(dic) > 1: print('编码不唯一,请检查') return # dic = data['payload']['context']['discount_meta'] promotion_id = dic[0]['id'] lis = dic[0]['context']['discount_meta'] dis_id = lis['id'] name = lis['name'] if not dis_id: no_id.append(id) no_id_name.append(name) promotion_id_dic[id] = promotion_id else: have_id.append(id) have_id_name.append(name) return promotion_id def get_Promotion_id(id): """ 取得促销 discount_meta 的id """ url = test_url + '/api/v1/promotion/rule?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&include_state=true'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) try: dic = data['payload'] except IndexError as e: print('促销编码{}不存在'.format(id)) return if len(dic) > 1: print('编码不唯一,请检查') return # dic = data['payload']['context']['discount_meta'] lis = dic[0]['context']['discount_meta'] dis_id = lis['id'] name = lis['name'] if not dis_id: no_id.append(id) no_id_name.append(name) else: have_id.append(id) have_id_name.append(name) return def get_discount_id(code): """ 取得 discount 的id """ url = test_url + '/api/v1/discount?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&include_state=true'.format(code) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) try: dic = data['payload'] except IndexError as e: print('促销编码{}不存在'.format(id)) return if len(dic['rows']) > 1: print('编码不唯一,请检查') return # dic = data['payload']['context']['discount_meta'] promotion = dic['rows'][0] promotion_id = promotion['id'] # print(promotion_id) return promotion_id def get_promotion_content(id, promotion_id): """ 取得促销 promotion 的content """ url = test_url + '/api/v1/promotion/rule/{}?stringified=true&is_new=true'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) try: dic = data['payload'] except IndexError as e: print('促销编码{}不存在'.format(id)) return dic['context']['discount_meta']['id'] = str(promotion_id) # print(dic) return dic def update_promotion(id, dic): url = test_url + '/api/v1/promotion/rule/{}'.format(id) data = json.dumps(dic) response = requests.request("PUT", url, headers=headers1, data=data) return def get_request_id(id): """ 取得促销 request 的 id """ url = test_url + '/api/v1/promotion/rule?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&include_state=true'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) try: dic = data['payload'] except IndexError as e: print('促销编码{}不存在'.format(id)) return # dic = data['payload']['context']['discount_meta'] request_id = dic[0]['request_id'] return request_id def apply_change(request_id): url = test_url + '/api/v1/promotion/rule/change/{}/apply'.format(request_id) # print(url) response = requests.request("PUT", url, headers=headers1) data = response.json() return if __name__ == '__main__': # lis = [ # '202103161', # '202103162', # '202103163', # '202103251', # '202103253', # '202103252', # '202103291', # '202103292', # '202103293', # '202103294', # '202103295', # '202103296', # '202103298', # '202103301', # '202103311', # '202103312', # '202104021', # '202104025', # '202104052', # '202104026', # '202104121', # '202104131'] # dic = {'202103162': 4469349136514220032, '202103163': 4469358546829475840, '202103251': 4472649870634680320, '202103253': 4472661515834556416, '202103252': 4472658839805689856, '202103291': 4474046767131852800, '202103292': 4474052790672490496, '202103293': 4474053672269021184, '202103294': 4474093960840642560, '202103295': 4474095313021337600, '202103296': 4474112075267866624, '202103298': 4474133581045760000, '202103301': 4474503715035873280, '202103311': 4474782259838222336, '202103312': 4474899470061961216, '202104021': 4475545674307371008, '202104025': 4475713582522204160, '202104052': 4477676312334467072, '202104026': 4475713885422256128, '202104121': 4479121399539073024, '202104131': 4479517429409546240} # lis = ['202103162'] lis = ["202104191"] for i in lis: get_Promotion(i) print("have_id_name", have_id_name, len(have_id_name)) print("no_id_name", no_id_name, len(no_id_name)) for i in lis: promotion_long_id = get_Promotion(i) print('折扣{}的长id为{}'.format(i, promotion_long_id)) promotion = get_discount_id(i) print('折扣{}的折扣id为{}'.format(i, promotion)) dic = get_promotion_content(promotion_long_id, promotion) update_promotion(promotion_long_id, dic) print('更新折扣{}的payload的id'.format(i)) request_id = get_request_id(i) print('折扣{}的request_id为{}'.format(i, request_id)) apply_change(request_id) print('折扣{}更新完成'.format(i)) time.sleep(5) <file_sep># coding=utf8 import zeep from zeep import Client from zeep.cache import SqliteCache from zeep.transports import Transport # 定义WebService的访问地址和参数 wsdl = 'http://172.16.17.32:10001/frdif/n_frdif.asmx?WSDL' username = 'test' password = '<PASSWORD>' cmdid = '2000' # inputpara = "'01','W-B119','0012','123213123','2023-04-07 16:00:00','1','000228',20.00,1,20.00,0001,,,20,0,0,0,0" # 根据具体需求自定义 inputpara = "01,W-B119,0012,12321312312,2023-04-07 16:00:00,1,000228,20.00,1,20.00,0001,,,20,0,0,0,0" # 根据具体需求自定义 outputpara = '' return_val = 0 errormsg = '' class DQConfig(object): WEBSERVICE = 'http://172.16.17.32:10001/frdif/n_frdif.asmx?WSDL' GATEWAY_TIME_OUT = 60 class WebServiceApi(object): def __init__(self, config): self.config = config self.__transport = None self.__client = None self.__port_name = None def client(self): if self.__client is None: self.__transport = Transport(cache=SqliteCache()) self.__client = Client(self.config.WEBSERVICE, transport=self.__transport) return self.__client def sync_processdata(self, url, **kwargs): service = self.client().create_service('{http://tempurl.org}n_frdifSoap', url) res = service.processdata(**kwargs) return res api = WebServiceApi(DQConfig) data = {} # data['transStr'] = inputpara data['userid'] = 'test' data['password'] = '<PASSWORD>' data['cmdid'] = '2000' data['inputpara'] = inputpara data['outputpara'] = '' data['rtn'] = 1 data['errormsg'] = '' resp = api.sync_processdata(wsdl, **data) print(resp) print(resp.errormsg) print(resp['errormsg']) print(resp['rtn']==-1) <file_sep>import requests import json import time import xlrd from openpyxl import Workbook, load_workbook final_url = 'https://store.papajohnshanghai.com' headers1 = { 'authorization': 'Bearer <KEY>', 'Cookie': 'hex_server_session={}'.format('75034011-57fa-4415-b282-48f133fda13f'), 'content-type': 'application/json' } def get_product_id(id): """ 根据商品编码拿到商品id及单位 """ url = final_url + '/api/v1/product?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&relation=all&include_state=true'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) product_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(id): product_id = i['id'] status = i['status'] name = i['name'] except IndexError as e: print('物料编码{}不存在IndexError'.format(id)) return 0, 0 if not product_id: print('物料编码{}不存在'.format(id)) return 0, 0 return product_id, status, name def disable_status(pid): url = final_url + '/api/v1/product/{}?stringified=true'.format(pid) s = {"status": "DISABLED"} # print(s) data = json.dumps(s) response = requests.request("PUT", url, headers=headers1, data=data) data = response.json() time.sleep(3) return def get_request_id(code): url = final_url + '/api/v1/product?search={}'.format(code) # print(url) response = requests.get(url, headers=headers1) data = response.json() # print(type(data), data) request_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(code): request_id = i['request_id'] name = i['name'] except IndexError as e: print('物料编码{}不存在11111'.format(id)) return None, None if not request_id: print('物料编码{}不存在222'.format(id)) return None, None return request_id, name def accept_action2(name, request_id): """ 接受更改操作,用map去拼接正确的名字 eg.DQ全国 """ url = final_url + '/api/v1/product/change/{}/to/task?stringified=true'.format(request_id) s = {"name": "{}".format(name), "immediate": True, "start_time": ""} # print(s) data = json.dumps(s, ensure_ascii=False).encode("utf-8") # print(data) response = requests.post(url, headers=headers1, data=data) data2 = response.json() # time.sleep(0.1) return def get_region_order_rel_id(product_id): url = final_url + '/api/v1/product/{}/region/order?stringified=true&include_total=true&is_task=true&order=asc' \ '&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true'.format(product_id) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() dic = data['payload'] lis = dic['rows'] rel_id_new = [i.get('rel_id') for i in lis] # print('订货区域区域:%s' % rel_id_new) return rel_id_new def accept_region_order(rel_id): url = final_url + '/api/v1/product/region/order/{}/state/disable?stringified=true'.format(rel_id) response = requests.request("PUT", url, headers=headers1) data = response.json() return def get_distribution_order_rel_id(product_id): url = final_url + '/api/v1/product/{}/region/distribution?stringified=true&include_total=true&is_task=true&order=asc' \ '&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true'.format(product_id) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() dic = data['payload'] lis = dic['rows'] rel_id_new = [i.get('rel_id') for i in lis] # print('配送区域:%s' % rel_id_new) return rel_id_new def accept_distribution_order(rel_id): url = final_url + '/api/v1/product/region/distribution/{}/state/disable?stringified=true'.format(rel_id) response = requests.request("PUT", url, headers=headers1) data = response.json() return def get_attribute_order_rel_id(product_id): url = final_url + '/api/v1/product/{}/region/attribute?stringified=true&include_total=true&is_task=true&order=asc' \ '&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true'.format(product_id) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() dic = data['payload'] lis = dic['rows'] rel_id_new = [i.get('rel_id') for i in lis] # print('属性区域:%s' % rel_id_new) return rel_id_new def accept_attribute_order(rel_id): url = final_url + '/api/v1/product/region/attribute/{}/state/disable?stringified=true'.format(rel_id) response = requests.request("PUT", url, headers=headers1) data = response.json() return def get_task_id(code): url = final_url + '/api/v1/product/task?stringified=true&include_total=true&search_fields=name&order=asc&offset=0&limit=10' response = requests.get(url, headers=headers1) data = response.json() row = data['payload']['rows'] print(row) now_id = None for i in row: if code == i.get('name') and i.get('process_status') == 'INITED': now_id = i.get('id') break return now_id def put_task_id(task_id): url = final_url + 'api/v1/product/task/{}/status/APPROVED?stringified=true'.format(task_id) response = requests.request("PUT", url, headers=headers1) return def one_trun(code): # 禁用商品 product_id, status,name = get_product_id(code) if not product_id: print('物料编码{}不存在'.format(code)) return if status != 'DISABLED': disable_status(product_id) print('商品{}修改为禁用状态'.format(code)) print(code, '*' * 10) request_id, name = get_request_id(code) print(request_id, name) accept_action2(name, request_id) print('商品{}接受生成变更计划'.format(code)) else: print('商品{}已经是禁用状态'.format(code)) # 禁用商品订货区域 rel_ids = get_region_order_rel_id(product_id) for r in rel_ids: accept_region_order(r) print('商品订货区域:%s 完成' % code) # 禁用配送区域 dis_ids = get_distribution_order_rel_id(product_id) for d in dis_ids: accept_distribution_order(d) print('商品配送区域:%s 完成' % code) # 禁用属性区域 att_ids = get_attribute_order_rel_id(product_id) for a in att_ids: accept_attribute_order(a) print('商品属性区域:%s 完成' % code) print('商品:%s 完成' % code) time.sleep(3) return def push_task(code): product_id, status,name = get_product_id(code) now_id = get_task_id(name) if now_id: put_task_id(now_id) print('code:%s 接受变更计划') def test(): wb = Workbook() ws = wb.active # file_path = '/Users/hws/Downloads/PPJHEX物料主档批量禁用-20221009 (1).xlsx' file_path = '/Users/hws/Downloads/工作簿1.xlsx' # 打开一个已有文件 wb = load_workbook(file_path) sheet_list = wb.sheetnames sheet = wb[wb.sheetnames[0]] total_list = [] for r in range(2, sheet.max_row + 1): row_list = [] # 每一行建立一个list for c in range(1, sheet.max_column + 1): v = str(sheet.cell(r, c).value) v = v.replace('\n', '') row_list.append(v) total_list.append(row_list) print(len(total_list), total_list) return total_list lis = test() for i in lis: print(i[1]) one_trun(i[1]) # for i in lis: # push_task(i[1]) <file_sep># coding: utf-8 from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric import utils from cryptography.hazmat.primitives import serialization import binascii # 生成SM2密钥对 private_key = ec.generate_private_key(ec.SECP256K1()) public_key = private_key.public_key() # 获取私钥DER编码格式的字节串,并将其转换为16进制字符串 private_key_der = private_key.private_bytes( encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) private_key_hex = binascii.hexlify(private_key_der) # 获取公钥DER编码格式的字节串,并将其转换为16进制字符串 public_key_der = public_key.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo ) public_key_hex = binascii.hexlify(public_key_der) # 返回公钥和私钥的字符串表示形式 print '{{"publicKey":"{}","privateKey":"{}"}}'.format(public_key_hex, private_key_hex) <file_sep>def t(l): product_info_map = {'1234': {'qty': 1, 'refund_qty': 0}, '81010293': {'qty': 1, 'refund_qty': 0}} for i in l: product_info = product_info_map.get(i.get('extPid')) if product_info: qty = product_info.get("qty", 0) refund_qty = product_info.get("refund_qty", 0) product_info['refund_qty'] = refund_qty + i.get('num') print(product_info_map) l = [ { "extPid":"1234", "refundIndex":1, "price":5, "pname":"芒果酪酪-乐", "num":1, "refundPrice":5 }, { "extPid":"81010293", "refundIndex":2, "price":20, "pname":"薄荷津津柠檬茶", "num":1, "refundPrice":20 }, { "extPid":"81010295", "refundIndex":3, "price":22, "pname":"祁红津津柠檬茶", "num":1, "refundPrice":22 } ] t(l)<file_sep>import requests import openpyxl host = { 'dq': 'http://store.dairyqueen.com.cn', 'ppj': 'https://store.papajohnshanghai.com' } url = '/api/v1/staff?code=all&include_total=true&include_user=true&relation=all&search_fields=name%2Ccode%2Crelation.store.name&offset={}&limit={}&stringified=true&search=&sort=name&order=desc&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true&_=1650014759358' def main(env, headers): return_res = [] for i in range(21): print(i) post_url = '{}{}'.format(host.get(env), url.format(i * 1000, 1000)) resp = requests.get(post_url, headers=headers) # print(resp.json(), post_url, env, headers) user_infos = resp.json()['payload']['rows'] # print(user_infos) for rs in user_infos: d = dict() d['code'] = rs.get('code') d['name'] = rs.get('name') d['login'] = rs.get('user').get('name') if rs.get('user') else '-' d['data_state'] = rs.get('data_state') d['created'] = rs['created'] d['updated'] = rs['updated'] return_res.append(d) outwb = openpyxl.Workbook() outws = outwb.create_sheet(index=0) title = ['员工编号', '名字', '登录名', '状态', '创建时间', '更新时间'] for i in range(1, 7): outws.cell(1, i).value = title[i -1] index = 2 for product in return_res: outws.cell(index, 1).value = product['code'] outws.cell(index, 2).value = product['name'] outws.cell(index, 3).value = product['login'] outws.cell(index, 4).value = product['data_state'] outws.cell(index, 5).value = product['created'] outws.cell(index, 6).value = product['updated'] index += 1 filename = '/Users/hws/Downloads/{}_userinfo.xlsx'.format(env) print(filename + ' down!!') outwb.save(filename) if __name__ == '__main__': # env = 'ppj' # headers = { # 'authorization': '{}'.format('Bearer EOK2CD68OLybgnCqNXgUsw'), # 该env环境下的authorization # 'Cookie': 'hex_server_session={}'.format('f9ae2e68-27c0-47f6-b2c4-7cf9153b615e'), # 该env环境下的Cookie # } env = 'dq' headers = { 'authorization': '{}'.format('Bearer vRJt4vZ-POODmZLvTurWmA'), # 该env环境下的authorization 'Cookie': 'hex_server_session={}'.format('91e7a4f8-2b8f-4de8-881a-e6611b5ce77d'), # 该env环境下的Cookie } main(env, headers)<file_sep>import requests import json url = "https://store.papajohnshanghai.com/api/v1/store?code=all&include_state=true&include_total=true&relation=all&search_fields=extend_code.ex_code%2Cextend_code.us_id%2Cextend_code.ex_id%2Ccode%2Cname%2Caddress%2Crelation.geo_region.name%2Crelation.branch.name%2Crelation.distribution_region.name%2Crelation.attribute_region.name%2Crelation.formula_region.name%2Crelation.market_region.name%2Crelation.order_region.name&stringified=true&is_task=true&sort=extend_code.ex_code&order=asc&offset=0&limit=10&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true&_=1669601595295" payload={} headers = { 'authority': 'store.papajohnshanghai.com', 'accept': 'application/json, text/javascript, */*; q=0.01', 'accept-language': 'zh-CN,zh;q=0.9', 'authorization': 'Bearer NDJTLozhOrmGQtclhPO66A', 'cache-control': 'no-cache', 'content-type': 'application/json', 'cookie': 'hex_server_session=d291f916-3f60-448d-9a3e-c07d86ba1829', 'pragma': 'no-cache', 'referer': 'https://store.papajohnshanghai.com/', 'sec-ch-ua': '"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"macOS"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36', 'x-requested-with': 'XMLHttpRequest' } a = 1 while a < 100: response = requests.request("GET", url, headers=headers, data=payload) print(a) a += 1 # print(response.text) <file_sep>import requests import openpyxl import pymongo # from product_ids import product_ids import time from random import randint import multiprocessing import os def worker(num, product_ids): host = 'http://store.dairyqueen.com.cn' region_market_url = '/api/v1/region/market' product_url = '/api/v1/product/{}/region/market' USER_AGENTS = [ "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)", "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)", "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)", "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)", "Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0", "Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20", "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52", ] random_agent = USER_AGENTS[randint(0, len(USER_AGENTS)-1)] headers = { 'authorization': '{}'.format('Bearer wJxl5YgdMViyF74xBTWS-w'), # 该env环境下的authorization 'Cookie': 'hex_server_session={}'.format('3ea89622-d1a7-42cc-b686-cef2db6128c9'), # 该env环境下的Cookie } region_market_response = requests.get(host + region_market_url, headers=headers) region_market_res = region_market_response.json()['payload'] # print(region_market_res) region_market_dic = {market['id']: { 'name': market['name'], 'code': market['code'] } for market in region_market_res} # print(region_market_dic) mongo_client = pymongo.MongoClient(host='127.0.0.1', port=27072,) db_name = mongo_client.saas_dq query = { 'status': 'ENABLED', 'data_state': 'ENABLED' } result = db_name.product.find(query, {'_id': 1, 'name': 1, 'code': 1}) product_dic = {r['_id']: r for r in result} return_res = [] if not product_ids: p_ids = product_ids[1000 * (num - 1): 1000 * num] else: p_ids = product_ids for p_id in p_ids: print('进程名称: [%s], 商品id: [%s], 当前进度: %s%%' % (multiprocessing.current_process().name, p_id, round((p_ids.index(p_id) + 1) * 100 / len(p_ids), 3) )) random_agent = USER_AGENTS[randint(0, len(USER_AGENTS)-1)] headers.update({ 'User-Agent':random_agent, }) try: product_info = requests.get(host + product_url.format(p_id), headers=headers) except Exception as e: flg = False product_info = None print('进程名称: [%s] 商品id: [%s] 失败' % (multiprocessing.current_process().name, p_id), '*' * 10) sleep_time = 3 for i in range(3): time.sleep(sleep_time) random_agent = USER_AGENTS[randint(0, len(USER_AGENTS)-1)] headers.update({ 'User-Agent':random_agent, }) try: product_info = requests.get(host + product_url.format(p_id), headers=headers) print('进程名称: [%s] 商品id: [%s] 第[%s]次成功' % (multiprocessing.current_process().name, p_id, i + 1), '*' * 10) flg = True except Exception as e: print(e) if flg: break sleep_time = sleep_time * 2 product_info_res = product_info.json()['payload'] if product_info else [] for i in product_info_res: d = dict() d['p_name'] = product_dic[p_id].get('name') d['p_code'] = product_dic[p_id].get('code') d['market_name'] = region_market_dic[i['id']]['name'] d['market_code'] = region_market_dic[i['id']]['code'] d['price'] = i['retail'] return_res.append(d) time.sleep(1) print('**' * 20) print(return_res) print('--' * 20) outwb = openpyxl.Workbook() outws = outwb.create_sheet(index=0) title = ['商品名称', '商品编码', '市场区域名称', '市场区域编码', '价格'] for i in range(1, 6): outws.cell(1, i).value = title[i -1] index = 2 for product in return_res: outws.cell(index, 1).value = product['p_name'] outws.cell(index, 2).value = product['p_code'] outws.cell(index, 3).value = product['market_name'] outws.cell(index, 4).value = product['market_code'] outws.cell(index, 5).value = product['price'] index += 1 filename = '/Users/hws/Downloads/product_market_price{}.xlsx'.format(num) print(filename + ' down!!') outwb.save(filename) if __name__ == '__main__': # print('888') # p_list = [] # for i in range(1, 7): # p = multiprocessing.Process(target=worker, args=(i, )) # p_list.append(p) # for p in p_list: # p.start() # path = '/Users/hws/Downloads/奶昔.xlsx' # wb = openpyxl.load_workbook(path) # sh = wb['Sheet1'] # rows = sh.max_row # cols = sh.max_column # product_codes = [] # for i in range(2, rows + 1): # product_code = str(sh.cell(i, 2).value) # product_codes.append(product_code) # print(product_codes) # print(len(product_codes)) mongo_client_pos = pymongo.MongoClient('127.0.0.1', 27072) db_name_pos = mongo_client_pos.saas_dq res = db_name_pos.product.find({ 'status': 'ENABLED', 'data_state': 'ENABLED' }) product_ids = [] for r in res: print(r['_id']) product_ids.append(r['_id']) worker(1, product_ids) <file_sep># 阿里云短信 from hashlib import sha1 import datetime import requests import json import base64 import hmac import uuid import urllib import hashlib def send_messages(params): AccessKeySecret = '' # 公共参数 params.update({ "AccessKeyId": "", "Format": "json", "RegionId": "cn-hangzhou", "SignatureMethod": "HMAC-SHA1", "SignatureNonce": str(uuid.uuid4()), "SignatureVersion": "1.0", "Timestamp": datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"), "Version": "2017-05-25", }) if "Signature" in params: params.pop("Signature") dict = sorted(params.items(), key=lambda x: x[0]) # 按规定格式转码拼接 # 签名 sign = "" for key, value in dict: sign += "&" + URLcoder(key) + "=" + URLcoder(value) sign = sign[1:] stringToSign = 'GET' + '&' + URLcoder('/') + "&" + URLcoder(sign) AccessKeySecret = AccessKeySecret + '&' signature = base64.b64encode(hmac.new(AccessKeySecret.encode("utf8"), stringToSign.encode("utf8"), digestmod=hashlib.sha1).digest()) params['Signature'] = signature.decode() return params # 格式转换 def URLcoder(String): return urllib.parse.quote(String, ' ').replace('+', '%20').replace('*', '%2A').replace('%7E', '~') # 发送短信.入口 def sendmessages(): destUrl = 'https://dysmsapi.aliyuncs.com/' headers = {'content-type': 'application/json'} params = { "Action": "SendSms", "PhoneNumbers": "", "SignName": "复星iHR", "TemplateCode": "SMS_187951124", "TemplateParam": "{\"name\":\"翁樟韬123\"}", } params = send_messages(params) destUrl = destUrl print (destUrl, params) r = requests.post(destUrl, params=params, headers=headers) # 打印结果 print (r.text) sendmessages() <file_sep>import requests import json import time import xlrd from openpyxl import Workbook, load_workbook #请求头部 authorization = '<KEY>' hex_server_session = '9f697a29-fc04-4cd4-871b-5ebb814f081f' test_url = 'http://test.dairyqueen.com.cn' store_url = 'http://store.dairyqueen.com.cn' store_ppj_url = 'http://store.papajohnshanghai.com' test_be_url = 'http://hwstest.brutcakecafe.com' store_be_url = 'http://store.brutcakecafe.com' headers1 = { 'authorization': '{}'.format(authorization), 'Cookie': 'hex_server_session={}'.format(hex_server_session), } headers2 = { 'authorization': '{}'.format(authorization), 'Content-Type': 'application/json', 'Cookie': 'hex_server_session={}'.format(hex_server_session), } final_url = store_ppj_url def get_product_id(id): """ 根据商品编码拿到商品id及单位 """ url = final_url + '/api/v1/product?search={}&is_task=true&state=draft%2Cenabled&status=&include_request=true' \ '&is_new=true&relation=all&include_state=true'.format(id) # print(url) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() # print(type(data), data) product_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(id): product_id = i['id'] status = i['status'] except IndexError as e: print('物料编码{}不存在'.format(id)) return 0, 0 if not product_id: print('物料编码{}不存在'.format(id)) return 0, 0 return product_id, status def get_region_order_rel_id(product_id): url = final_url + '/api/v1/product/{}/region/order?stringified=true&include_total=true&is_task=true&order=asc' \ '&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true'.format(product_id) response = requests.get(url, headers=headers1) # print(response.status_code) data = response.json() dic = data['payload'] lis = dic['rows'] for i in lis: if i['id'] == '4635061286305038336': rel_id_new = i['rel_id'] break return rel_id_new def accept_region_order(rel_id): url = final_url + '/api/v1/product/region/order/{}/state/disable?stringified=true'.format(rel_id) response = requests.request("PUT", url, headers=headers1) data = response.json() return def get_request_id(code): url = final_url + '/api/v1/product?search={}'.format(code) # print(url) response = requests.get(url, headers=headers1) data = response.json() # print(type(data), data) request_id = None try: dic = data['payload'] for i in dic: if i['code'] == str(code): request_id = i['request_id'] name = i['name'] except IndexError as e: print('物料编码{}不存在'.format(id)) return if not request_id: print('物料编码{}不存在'.format(id)) return return request_id, name def accept_action2(name, request_id): """ 接受更改操作,用map去拼接正确的名字 eg.DQ全国 """ url = final_url + '/api/v1/product/change/{}/to/task?stringified=true'.format(request_id) s = {"name": "{}".format(name), "immediate": True, "start_time": ""} # print(s) data = json.dumps(s, ensure_ascii=False).encode("utf-8") # print(data) response = requests.post(url, headers=headers2, data=data) data2 = response.json() # time.sleep(0.1) return def disable_status(pid): url = final_url + '/api/v1/product/{}?stringified=true'.format(pid) s = {"status": "DISABLED"} # print(s) data = json.dumps(s) response = requests.request("PUT", url, headers=headers1, data=data) data = response.json() return def one_trun(code): product_id, status = get_product_id(code) if not product_id: print('物料编码{}不存在'.format(code)) return if status == 'DISABLED': print('商品{}已经是禁用状态'.format(code)) return disable_status(product_id) print('商品{}修改为禁用状态'.format(code)) request_id, name = get_request_id(code) accept_action2(name, request_id) print('商品{}创建变更计划'.format(code)) return def test(): wb = Workbook() ws = wb.active file_path = '/Users/yjq/Desktop/test.xlsx' # 打开一个已有文件 wb = load_workbook(file_path) sheet_list = wb.sheetnames sheet = wb[wb.sheetnames[0]] total_list = [] for r in range(2, sheet.max_row + 1): row_list = [] # 每一行建立一个list for c in range(1, sheet.max_column + 1): v = str(sheet.cell(r, c).value) v = v.replace('\n', '') row_list.append(v) total_list.append(row_list) print(len(total_list), total_list) return total_list if __name__ == '__main__': lis = test() for i in lis: one_trun(i[0]) print('----------------------------------') time.sleep(0.1)<file_sep>########################################################### # 1、获取现有已生效分类(用于判断是否已经存在) GET # /api/orgs/discount-category # 2、新建折扣分类 (先建一级,后二级) POST # /api/orgs/discount-category # 3、分类生效 # /api/v1/discount-category/{category_id}/state/enable ########################################################### import requests import openpyxl host = { 'dq_host': 'http://test.dairyqueen.com.cn', 'ppj_host': 'http://test.dairyqueen.com.cn', 'ym_host': 'http://teststore.meet-xiaomian.com', 'be_host': 'http://hwstest.brutcakecafe.com', } # host = { # 'dq_host': 'http://store.dairyqueen.com.cn', # 'ppj_host': 'https://store.papajohnshanghai.com', # 'ym_host': 'http://store.meet-xiaomian.com', # 'be_host': 'http://store.brutcakecafe.com', # } headers = { 'authorization': '{}'.format('Bearer oHAmikLuoc2m5hCMKYnGi0XIEApyEe'), # 该env环境下的authorization 'Cookie': 'hex_server_session={}'.format('be51beb2-6353-4bc4-ba9a-5176cc7c9704'), # 该env环境下的Cookie } def get_env_host(env): host_info = { 'category_url':'{}/api/orgs/discount-category'.format(host.get('{}_host'.format(env.lower()))), 'enable_category_url': '%s/api/v1/discount-category/{}/state/enable' % host.get('{}_host'.format(env.lower())), } return host_info # 根据Excel组合成层级关系 def read_excel_info_base(cfb_env, path): wb = openpyxl.load_workbook(path) sh = wb['%s折扣' % cfb_env] rows = sh.max_row cols = sh.max_column upload_dic = {} first_dic = {} second_dic = {} for row in range(2, rows + 1): first_name = sh.cell(row, 1).value first_code = str(sh.cell(row, 2).value) second_name = sh.cell(row, 3).value second_code = str(sh.cell(row, 4).value) if second_code and second_code != 'None': first_dic[first_code] = first_name second_dic[second_code] = second_name upload_dic.setdefault(first_code, set()) upload_dic[first_code].add(second_code) print(upload_dic, '\n', first_dic, '\n', second_dic) return upload_dic, first_dic, second_dic def read_sys_category(env): res = get_env_host(env) host = res['category_url'] response = requests.get(host, headers=headers) category_res = response.json()['payload'] return {r.get('code'): r.get('id') for r in category_res} def create_zk_category(env, category_code, category_name, parent_id): # 根据现有名称、父级名称建折扣分类 res = get_env_host(env) host = res['category_url'] post_data = { 'code': category_code, 'name': category_name, 'parent_id': parent_id } print(post_data, '添加折扣&&&&&&&&&&') response = requests.post(host, headers=headers, json=post_data) print(response.json(), '添加折扣======') category_res = response.json()['payload'] return category_res.get('id') def enable_zk_category(env, category_id): res = get_env_host(env) host = res['enable_category_url'].format(category_id) response = requests.put(host, headers=headers) return True def main(env, path): upload_dic, first_dic, second_dic = read_excel_info_base(env, path) sys_category = read_sys_category(env) parent_code_id = sys_category.get('03') print(parent_code_id, '*' * 10, sys_category) if parent_code_id: for first_code, secode_code_list in upload_dic.items(): first_id = sys_category.get(first_code) # 一级目录 if not first_id: # 创建分类 first_id = create_zk_category(env, first_code, first_dic[first_code], parent_code_id) sys_category[first_code] = first_id # 生效分类 enable_zk_category(env, first_id) # 二级分类 for sec_code in list(secode_code_list): second_id = sys_category.get(sec_code) if not second_id: second_id = create_zk_category(env, sec_code, second_dic[sec_code], first_id) sys_category[sec_code] = second_id enable_zk_category(env, second_id) return True if __name__ == "__main__": # path = '/Users/hws/Downloads/CFB新增商品类别数据.xlsx' # main('PPJ', path) env = 'BE' l = [('80016-1234', '80016-1234-test')] active_ids = [] for i in l: ca_id = create_zk_category(env, i[0], i[1], "4163554550471278593") active_ids.append(ca_id) # ca_id = create_zk_category(env, '90013', 'OK卡', 4520115621821710336) # active_ids.append(ca_id) # print(active_ids) <file_sep>import requests import json url = "https://store.dairyqueen.com.cn/api/v1/store?code=all&include_state=true&include_total=true&relation=all&search_fields=extend_code.ex_code%2Cextend_code.us_id%2Cextend_code.ex_id%2Ccode%2Cname%2Caddress%2Crelation.geo_region.name%2Crelation.branch.name%2Crelation.distribution_region.name%2Crelation.attribute_region.name%2Crelation.formula_region.name%2Crelation.market_region.name%2Crelation.order_region.name&stringified=true&is_task=true&sort=extend_code.ex_code&order=asc&state=draft%2Cenabled&status=&include_request=true&is_new=true&include_state=true&_=1676357126738" payload={} headers = { 'authority': 'store.dairyqueen.com.cn', 'accept': 'application/json, text/javascript, */*; q=0.01', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8', 'authorization': 'Bearer hoO4rqOcOgCQzvqH619OKQ', 'content-type': 'application/json', 'cookie': 'hex_server_session=0f39e346-35b3-49f4-8ffa-c691ea1bd21e; hex_server_session=0f39e346-35b3-49f4-8ffa-c691ea1bd21e', 'referer': 'https://store.dairyqueen.com.cn/', 'sec-ch-ua': '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"macOS"', 'sec-fetch-dest': 'empty', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36', 'x-requested-with': 'XMLHttpRequest' } response = requests.request("GET", url, headers=headers, data=payload) print(response.json())
f280a2574ae1c12a9e9eb8226596a239d15f82f5
[ "Python" ]
41
Python
Wangjt0118/mycode
e377b096997c2cb4f6906b1760e76037ec01c3a9
80e91b301562f8e97e3faf2cd2eee591bf05008a
refs/heads/master
<repo_name>jota40/dietaClient<file_sep>/src/main/java/es/jota/gwt/client/display/fotos/MyUploaderProgress.java package es.jota.gwt.client.display.fotos; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.DivElement; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Widget; import es.jota.gwt.client.uploader.ui.MyUploaderBaseProgress; import gwtupload.client.IUploadStatus.Status; public class MyUploaderProgress extends MyUploaderBaseProgress { private static MyUploaderProgressUiBinder uiBinder = GWT.create(MyUploaderProgressUiBinder.class); interface MyUploaderProgressUiBinder extends UiBinder<Widget, MyUploaderProgress> {} // @UiField ProgressBar progress; @UiField DivElement progressText; public MyUploaderProgress() { initWidget(uiBinder.createAndBindUi(this)); } @UiHandler("cancel") void cancelOnClick(ClickEvent e) { cancel(); } @Override public void updateStatus( Status status ) { /* switch (status) { case CHANGED: case QUEUED: case SUBMITING: progress.setColor( Color.INFO ); progress.setPercent( 0 ); break; case INPROGRESS: progress.setColor( Color.INFO ); progress.addStyleName("active"); break; case SUCCESS: case REPEATED: progress.setColor( Color.SUCCESS ); progress.setPercent( 100 ); progress.removeStyleName("active"); break; case CANCELING: progress.setColor( Color.DANGER ); break; case INVALID: case CANCELED: case ERROR: case DELETED: progress.setColor( Color.DANGER ); progress.setPercent( 100 ); progress.removeStyleName("active"); break; } */ } @Override public void updateText( String msg ) { progressText.setInnerHTML( msg ); } @Override public void updatePercent( Integer percent ) { // progress.setPercent(percent); } @Override public boolean validate() { return true; } }<file_sep>/src/main/java/es/jota/gwt/client/widgets/presenter/interfaces/ISuggestSelection.java package es.jota.gwt.client.widgets.presenter.interfaces; public interface ISuggestSelection { public interface Delegate { void clickOnSelection(ISuggestSelection selection); } int getIndex(); }<file_sep>/src/main/java/es/jota/gwt/client/display/grupoAlimento/GrupoAlimentoDisplayViewImpl.java package es.jota.gwt.client.display.grupoAlimento; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.ParagraphElement; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Widget; import es.jota.gwt.client.utils.UtilClient; import es.jota.gwt.client.widgets.display.MenuItem; public class GrupoAlimentoDisplayViewImpl extends Composite implements GrupoAlimentoDisplayView { private static GrupoAlimentoDisplayViewUiBinder uiBinder = GWT.create(GrupoAlimentoDisplayViewUiBinder.class); interface GrupoAlimentoDisplayViewUiBinder extends UiBinder<Widget, GrupoAlimentoDisplayViewImpl>{} @UiField HTMLPanel menu; @UiField MenuItem listar; @UiField MenuItem nuevo; @UiField MenuItem editar; @UiField ParagraphElement nombre; @UiField ParagraphElement color; @UiField ParagraphElement descripcion; private GrupoAlimentoDisplayView.Listener listener; @Override public void setListener(Listener listener) { this.listener = listener; } public GrupoAlimentoDisplayViewImpl() { initWidget(uiBinder.createAndBindUi(this)); } // menu @Override public HTMLPanel getMenu() { return menu; } @Override public void setEditarUrl( String url ) { editar.setHref( url ); } @Override public void setListarUrl( String url ) { listar.setHref( url ); } @Override public void setNuevoUrl( String url ) { nuevo.setHref( url ); } // fillForm @Override public void setNombre( String nombre ) { this.nombre.setInnerHTML( nombre ); } @Override public void setColor( String color ) { this.color.setInnerHTML( color ); } @Override public void setDescripcion( String descripcion ) { this.descripcion.setInnerSafeHtml( UtilClient.Cadena.string2SafeHtml( descripcion ) ); } }<file_sep>/src/main/java/es/jota/gwt/client/place/ingrediente/IngredientePlaceView.java package es.jota.gwt.client.place.ingrediente; import com.google.gwt.place.shared.PlaceTokenizer; import com.google.gwt.place.shared.Prefix; public class IngredientePlaceView extends IngredientePlace { private final static String NAME = "ingrediente"; private Long id; private IngredientePlaceView( Long id ) { this.id = id; } public Long getId() { return id; } @Prefix(NAME) public static class Tokenizer implements PlaceTokenizer<IngredientePlaceView> { @Override public String getToken( IngredientePlaceView place ) { return place.getId().toString(); } @Override public IngredientePlaceView getPlace( String token ) { try { Long id = Long.parseLong( token ); return instance( id ); } catch (Exception e) { } return null; } } public static IngredientePlaceView instance( Long id ) { return new IngredientePlaceView( id ); } public static String getUrl( Long id ) { return "#" + NAME + ":" + id; } }<file_sep>/src/main/java/es/jota/gwt/client/mappers/AppPlaceHistoryMapper.java package es.jota.gwt.client.mappers; import com.google.gwt.place.shared.PlaceHistoryMapper; import com.google.gwt.place.shared.WithTokenizers; import es.jota.gwt.client.place.grupoAlimento.GrupoAlimentoPlaceEdit; import es.jota.gwt.client.place.grupoAlimento.GrupoAlimentoPlaceList; import es.jota.gwt.client.place.grupoAlimento.GrupoAlimentoPlaceNew; import es.jota.gwt.client.place.grupoAlimento.GrupoAlimentoPlaceView; import es.jota.gwt.client.place.ingrediente.IngredientePlaceEdit; import es.jota.gwt.client.place.ingrediente.IngredientePlaceList; import es.jota.gwt.client.place.ingrediente.IngredientePlaceNew; import es.jota.gwt.client.place.ingrediente.IngredientePlaceView; import es.jota.gwt.client.place.inicio.InicioPlace; import es.jota.gwt.client.place.presupuesto.PresupuestoPlaceNew; import es.jota.gwt.client.place.receta.RecetaPlaceEdit; import es.jota.gwt.client.place.receta.RecetaPlaceList; import es.jota.gwt.client.place.receta.RecetaPlaceNew; import es.jota.gwt.client.place.receta.RecetaPlaceView; import es.jota.gwt.client.place.unidadDeMedida.UnidadDeMedidaPlaceEdit; import es.jota.gwt.client.place.unidadDeMedida.UnidadDeMedidaPlaceList; import es.jota.gwt.client.place.unidadDeMedida.UnidadDeMedidaPlaceNew; import es.jota.gwt.client.place.unidadDeMedida.UnidadDeMedidaPlaceView; /** * PlaceHistoryMapper interface is used to attach all places which the * PlaceHistoryHandler should be aware of. This is done via the @WithTokenizers * annotation or by extending PlaceHistoryMapperWithFactory and creating a * separate TokenizerFactory. */ @WithTokenizers( { InicioPlace.Tokenizer.class, IngredientePlaceEdit.Tokenizer.class, IngredientePlaceList.Tokenizer.class, IngredientePlaceNew.Tokenizer.class, IngredientePlaceView.Tokenizer.class, UnidadDeMedidaPlaceEdit.Tokenizer.class, UnidadDeMedidaPlaceList.Tokenizer.class, UnidadDeMedidaPlaceNew.Tokenizer.class, UnidadDeMedidaPlaceView.Tokenizer.class, RecetaPlaceEdit.Tokenizer.class, RecetaPlaceList.Tokenizer.class, RecetaPlaceNew.Tokenizer.class, RecetaPlaceView.Tokenizer.class, GrupoAlimentoPlaceEdit.Tokenizer.class, GrupoAlimentoPlaceList.Tokenizer.class, GrupoAlimentoPlaceNew.Tokenizer.class, GrupoAlimentoPlaceView.Tokenizer.class, PresupuestoPlaceNew.Tokenizer.class } ) public interface AppPlaceHistoryMapper extends PlaceHistoryMapper { } <file_sep>/src/main/java/es/jota/gwt/client/place/fotos/FotoPlace.java package es.jota.gwt.client.place.fotos; import com.google.gwt.place.shared.Place; import com.google.gwt.place.shared.PlaceTokenizer; import com.google.gwt.place.shared.Prefix; public class FotoPlace extends Place { private final static String NAME = "foto"; private final static String VIEW = "view"; private final static String EDIT = "edit"; private final static String FORBIDDEN = "forbidden"; private String command; private FotoPlace( String command ) { this.command = command; } public String getCommand() { return command; } @Prefix(NAME) public static class Tokenizer implements PlaceTokenizer<FotoPlace> { @Override public String getToken(FotoPlace place) { return place.getCommand(); } @Override public FotoPlace getPlace(String token) { if ( token.equalsIgnoreCase( VIEW ) ){ return instanceView(); } if ( token.equalsIgnoreCase( EDIT ) ){ return instanceEdit(); } return instanceForbidden(); } } public boolean isView(){ return VIEW.equals( command ); } public boolean isEdit(){ return EDIT.equals( command ); } public boolean isForbidden(){ return FORBIDDEN.equals( command ); } public static FotoPlace instanceView() { return new FotoPlace( VIEW ); } public static FotoPlace instanceEdit() { return new FotoPlace( EDIT ); } public static FotoPlace instanceForbidden() { return new FotoPlace( FORBIDDEN ); } public static String getUrlView() { return NAME + ":" + VIEW; } public static String getUrlEdit() { return NAME + ":" + EDIT; } public static String getUrlForbidden() { return NAME + ":" + FORBIDDEN; } }<file_sep>/src/main/java/es/jota/gwt/client/widgets/presenter/events/ValueRemoveHandler.java package es.jota.gwt.client.widgets.presenter.events; import com.google.gwt.event.shared.EventHandler; public interface ValueRemoveHandler<T> extends EventHandler { void onValueRemove(ValueRemoveEvent<T> event); } <file_sep>/src/main/java/es/jota/gwt/client/display/fotos/MyUploaderForm.java package es.jota.gwt.client.display.fotos; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.Widget; import es.jota.gwt.client.uploader.interfaz.IUploaderProgress; import es.jota.gwt.client.uploader.ui.MyUploaderBaseForm; public class MyUploaderForm extends MyUploaderBaseForm { private static MyUploaderFormUiBinder uiBinder = GWT.create(MyUploaderFormUiBinder.class); interface MyUploaderFormUiBinder extends UiBinder<Widget, MyUploaderForm> {} @UiField FormPanel formPanel; public MyUploaderForm() { initWidget(uiBinder.createAndBindUi(this)); formPanel.getElement().setAttribute( "style", "width: 0px; visibility: hidden;" ); } @UiHandler("uploadFake") void upLoadFakeOnClick(ClickEvent e) { openFileSelection(); } @Override protected IUploaderProgress instanceUploaderProgress() { return new MyUploaderProgress(); } @Override public FormPanel getFormPanel() { return formPanel; } }<file_sep>/src/main/java/es/jota/gwt/client/cellTable/pager/PagerScrollerDisplay.java package es.jota.gwt.client.cellTable.pager; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import es.jota.gwt.client.cellTable.pager.MyPager.MyPagerView; public class PagerScrollerDisplay extends Composite implements MyPagerView { private static PagerScrollerDisplayUiBinder uiBinder = GWT.create(PagerScrollerDisplayUiBinder.class); interface PagerScrollerDisplayUiBinder extends UiBinder<Widget, PagerScrollerDisplay>{} @UiField Anchor mas; private MyPager listener; @UiHandler("mas") public void primeroYListarOnClick(ClickEvent event) { listener.nextPage(); } @Override public void setListener( MyPager listener ) { this.listener = listener; } public PagerScrollerDisplay() { initWidget(uiBinder.createAndBindUi(this)); } private void setEnabled( Anchor link, boolean enabled ) { if ( enabled ) { link.getElement().getParentElement().removeClassName( "disabled" ); } else { link.getElement().getParentElement().addClassName( "disabled" ); } } @Override public void onRangeOrRowCountChanged() { setEnabled( mas, listener.hasNextPage() ); } }<file_sep>/src/main/java/es/jota/gwt/client/display/grupoAlimento/GrupoAlimentoDisplayView.java package es.jota.gwt.client.display.grupoAlimento; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.IsWidget; public interface GrupoAlimentoDisplayView extends IsWidget { void setListener( GrupoAlimentoDisplayView.Listener listener ); public interface Listener { } // menu HTMLPanel getMenu(); void setEditarUrl( String url); void setListarUrl( String url ); void setNuevoUrl( String url ); // fillForm void setColor( String abreviacion ); void setNombre( String nombre ); void setDescripcion( String descripcion ); }<file_sep>/src/main/java/es/jota/gwt/client/place/receta/RecetaPlace.java package es.jota.gwt.client.place.receta; import com.google.gwt.activity.shared.Activity; import com.google.gwt.place.shared.Place; import es.jota.gwt.client.miApp; public class RecetaPlace extends Place { protected RecetaPlace() { } public Activity getActivity( Place place ) { if ( place instanceof RecetaPlaceEdit ) return miApp.INJECTOR.getRecetaActivityEdit().setPlace( (RecetaPlaceEdit)place ); if ( place instanceof RecetaPlaceList ) return miApp.INJECTOR.getRecetaActivityList().setPlace( (RecetaPlaceList)place ); if ( place instanceof RecetaPlaceNew ) return miApp.INJECTOR.getRecetaActivityNew().setPlace( (RecetaPlaceNew)place ); if ( place instanceof RecetaPlaceView ) return miApp.INJECTOR.getRecetaActivityView().setPlace( (RecetaPlaceView)place ); return null; } }<file_sep>/src/main/java/es/jota/gwt/client/display/unidadDeMedida/UnidadDeMedidaDisplayList.java package es.jota.gwt.client.display.unidadDeMedida; import jota.server.dto.UnidadDeMedidaDto; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.IsWidget; import es.jota.gwt.client.cellTable.pager.MyPager.MyPagerView; public interface UnidadDeMedidaDisplayList extends IsWidget { void setListener( UnidadDeMedidaDisplayList.Listener listener ); public interface Listener { void reset(); void refresh(); void borrar( Long idUnidadDeMedida ); } // menu HTMLPanel getMenu(); void setNuevoUrl( String url ); CellTable<UnidadDeMedidaDto> getTabla(); MyPagerView getPagerDisplay(); }<file_sep>/src/main/java/es/jota/gwt/client/place/grupoAlimento/GrupoAlimentoPlaceNew.java package es.jota.gwt.client.place.grupoAlimento; import com.google.gwt.place.shared.PlaceTokenizer; import com.google.gwt.place.shared.Prefix; public class GrupoAlimentoPlaceNew extends GrupoAlimentoPlace { private final static String NAME = "grupoAlimentoNew"; private GrupoAlimentoPlaceNew() { } @Prefix(NAME) public static class Tokenizer implements PlaceTokenizer<GrupoAlimentoPlaceNew> { @Override public String getToken(GrupoAlimentoPlaceNew place) { return ""; } @Override public GrupoAlimentoPlaceNew getPlace(String token) { return instance(); } } public static GrupoAlimentoPlaceNew instance() { return new GrupoAlimentoPlaceNew(); } public static String getUrl() { return "#" + NAME + ":"; } }<file_sep>/src/main/java/es/jota/gwt/client/place/grupoAlimento/GrupoAlimentoPlaceList.java package es.jota.gwt.client.place.grupoAlimento; import com.google.gwt.place.shared.PlaceTokenizer; import com.google.gwt.place.shared.Prefix; public class GrupoAlimentoPlaceList extends GrupoAlimentoPlace { private final static String NAME = "gruposAlimento"; private GrupoAlimentoPlaceList() { } @Prefix(NAME) public static class Tokenizer implements PlaceTokenizer<GrupoAlimentoPlaceList> { @Override public String getToken(GrupoAlimentoPlaceList place) { return ""; } @Override public GrupoAlimentoPlaceList getPlace(String token) { return instance(); } } public static GrupoAlimentoPlaceList instance() { return new GrupoAlimentoPlaceList(); } public static String getUrl() { return "#" + NAME + ":"; } }<file_sep>/src/main/java/es/jota/gwt/client/display/inicio/InicioViewImpl.java package es.jota.gwt.client.display.inicio; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; public class InicioViewImpl extends Composite implements InicioView { private static InicioViewImplUiBinder uiBinder = GWT.create(InicioViewImplUiBinder.class); interface InicioViewImplUiBinder extends UiBinder<Widget, InicioViewImpl>{} private InicioView.Listener listener; public InicioViewImpl() { initWidget(uiBinder.createAndBindUi(this)); } @Override public void setListener(Listener listener) { this.listener = listener; } }<file_sep>/src/main/java/es/jota/gwt/client/display/ingredienteDeReceta/IngredienteDeRecetaDisplayViewImpl.java package es.jota.gwt.client.display.ingredienteDeReceta; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import jota.server.dto.IngredienteDeRecetaDto; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.TableCellElement; import com.google.gwt.dom.client.TableRowElement; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Widget; import es.jota.gwt.client.place.ingrediente.IngredientePlaceEdit; import es.jota.gwt.client.place.ingrediente.IngredientePlaceView; import es.jota.gwt.client.utils.UtilClient; import es.jota.gwt.client.utils.enums.IconoEnum; import es.jota.gwt.client.widgets.display.TrWidget; public class IngredienteDeRecetaDisplayViewImpl extends TrWidget implements IngredienteDeRecetaDisplayView { private static IngredienteDeRecetaDisplayEditUiBinder uiBinder = GWT.create(IngredienteDeRecetaDisplayEditUiBinder.class); interface IngredienteDeRecetaDisplayEditUiBinder extends UiBinder<Widget, IngredienteDeRecetaDisplayViewImpl>{} @UiField TableRowElement tr; @UiField TableCellElement ingrediente; @UiField TableCellElement racionesPorComensal; @UiField TableCellElement cantidad; @UiField TableCellElement unidadDeMedida; @UiField TableCellElement coste; IngredienteDeRecetaDto ingredienteDeRecetaDto; private IngredienteDeRecetaDisplayView.Listener listener; public IngredienteDeRecetaDisplayViewImpl() { ingredienteDeRecetaDto = new IngredienteDeRecetaDto(); initWidget(uiBinder.createAndBindUi(this)); } @Override public IngredienteDeRecetaDisplayView setListener( IngredienteDeRecetaDisplayView.Listener listener ) { this.listener = listener; return this; } @Override public List<TableRowElement> getTr() { return Arrays.asList( tr ); } @Override public void set( IngredienteDeRecetaDto ingredienteDeRecetaDto ) { this.ingredienteDeRecetaDto = ingredienteDeRecetaDto; tr.setClassName( ingredienteDeRecetaDto.getIngredienteDto().getGrupoAlimento().getColor() ); Long id = ingredienteDeRecetaDto.getIdIngrediente(); String nombre = ingredienteDeRecetaDto.getIngredienteDto().getNombre(); ingrediente.setInnerSafeHtml( UtilClient.TEMPLATES.mainLinkCell( IngredientePlaceEdit.getUrl( id ), IconoEnum.EDITAR.get(), IngredientePlaceView.getUrl( id ), nombre ) ); unidadDeMedida.setInnerHTML( ingredienteDeRecetaDto.getIngredienteDto().getUnidadDeMedida() == null ? "" : ingredienteDeRecetaDto.getIngredienteDto().getUnidadDeMedida().getNombre() ); setDatosCalculados(); } @Override public IngredienteDeRecetaDto get() { return ingredienteDeRecetaDto; } @Override public void cambiarPax( BigDecimal pax ) { ingredienteDeRecetaDto.setPax( pax == null ? 0 : pax.intValue() ); setDatosCalculados(); } private void setDatosCalculados() { racionesPorComensal.setInnerHTML( UtilClient.Numeros.number2String( ingredienteDeRecetaDto.calcularRacionesPorComensal() ) ); cantidad.setInnerHTML( UtilClient.Numeros.number2String( ingredienteDeRecetaDto.calcularCantidad() ) ); coste.setInnerHTML( UtilClient.Numeros.number2String( ingredienteDeRecetaDto.calcularTotal(), "€" ) ); } @Override public void addCantidadPorComensal( BigDecimal incremento ) { ingredienteDeRecetaDto.addCantidadPorComensal( incremento ); setDatosCalculados(); } }<file_sep>/src/main/java/es/jota/gwt/client/display/unidadDeMedida/UnidadDeMedidaDisplayListImpl.java package es.jota.gwt.client.display.unidadDeMedida; import jota.server.dto.UnidadDeMedidaDto; import com.google.gwt.cell.client.SafeHtmlCell; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Widget; import es.jota.gwt.client.cellTable.pager.AccionesCell; import es.jota.gwt.client.cellTable.pager.PagerPaginationDisplay; import es.jota.gwt.client.place.unidadDeMedida.UnidadDeMedidaPlaceEdit; import es.jota.gwt.client.place.unidadDeMedida.UnidadDeMedidaPlaceView; import es.jota.gwt.client.utils.UtilClient; import es.jota.gwt.client.utils.enums.AccionEnum; import es.jota.gwt.client.utils.enums.IconoEnum; import es.jota.gwt.client.widgets.display.MenuItem; public class UnidadDeMedidaDisplayListImpl extends Composite implements UnidadDeMedidaDisplayList { private static UnidadDeMedidaDisplayListUiBinder uiBinder = GWT.create(UnidadDeMedidaDisplayListUiBinder.class); interface UnidadDeMedidaDisplayListUiBinder extends UiBinder<Widget, UnidadDeMedidaDisplayListImpl>{} @UiField HTMLPanel menu; @UiField MenuItem nuevo; @UiField Anchor reset; @UiField(provided=true) CellTable<UnidadDeMedidaDto> tabla; @UiField PagerPaginationDisplay paginator; private UnidadDeMedidaDisplayList.Listener listener; @Override public void setListener( UnidadDeMedidaDisplayList.Listener listener ) { this.listener = listener; } public UnidadDeMedidaDisplayListImpl() { tabla = new CellTable<UnidadDeMedidaDto>( 15 ); initTableColumns(); initWidget(uiBinder.createAndBindUi(this)); } @UiHandler("reset") public void resetOnClick(ClickEvent event) { listener.reset(); } @UiHandler("refresh") public void refreshOnClick(ClickEvent event) { listener.refresh(); } // Menu @Override public HTMLPanel getMenu() { return menu; } @Override public void setNuevoUrl( String url ) { nuevo.setHref( url ); } private void initTableColumns() { Column<UnidadDeMedidaDto, SafeHtml> nombreColumn = new Column<UnidadDeMedidaDto, SafeHtml>( new SafeHtmlCell()) { @Override public SafeHtml getValue( UnidadDeMedidaDto object) { Long id = object.getId(); return UtilClient.TEMPLATES.mainLinkCell( UnidadDeMedidaPlaceEdit.getUrl( id ), IconoEnum.EDITAR.get(), UnidadDeMedidaPlaceView.getUrl( id ), object.getNombre() ); } }; Column<UnidadDeMedidaDto, SafeHtml> abreviacionColumn = new Column<UnidadDeMedidaDto, SafeHtml>( new SafeHtmlCell()) { @Override public SafeHtml getValue( UnidadDeMedidaDto object) { String cell = object.getAbreviacion(); return new SafeHtmlBuilder().appendHtmlConstant( cell ).toSafeHtml(); } }; Column<UnidadDeMedidaDto, SafeHtml> descripcionColumn = new Column<UnidadDeMedidaDto, SafeHtml>( new SafeHtmlCell()) { @Override public SafeHtml getValue( UnidadDeMedidaDto object) { String cell = object.getDescripcion(); return new SafeHtmlBuilder().appendEscapedLines( cell ).toSafeHtml(); } }; AccionesCell accionesCell = new AccionesCell(){ @Override protected void doAction( String accionId, String accionValue ) { try { Long idUnidadDeMedida = Long.parseLong( accionValue ); switch ( AccionEnum.getEnum( accionId ) ) { case BORRAR: listener.borrar( idUnidadDeMedida ); break; } } catch (Exception e) { } } }; Column<UnidadDeMedidaDto, SafeHtml> accionesColumn = new Column<UnidadDeMedidaDto, SafeHtml>( accionesCell ) { @Override public SafeHtml getValue( UnidadDeMedidaDto object ) { Long id = object.getId(); SafeHtmlBuilder shb = new SafeHtmlBuilder(); shb.append( UtilClient.TEMPLATES.accionDelegate( AccionEnum.BORRAR.getId().toString(), id.toString(), AccionEnum.BORRAR.getColor().getBtn(), AccionEnum.BORRAR.getIcono().get() ) ); return shb.toSafeHtml(); } }; // nombreColumn.setSortable(true); tabla.addColumn( nombreColumn, "Nombre"); tabla.addColumn( abreviacionColumn, "Abreviacion"); tabla.addColumn( descripcionColumn, "Descripcion"); tabla.addColumn( accionesColumn, "Acciones"); } @Override public CellTable<UnidadDeMedidaDto> getTabla() { return tabla; } @Override public PagerPaginationDisplay getPagerDisplay() { return paginator; } }<file_sep>/src/main/java/es/jota/gwt/client/place/unidadDeMedida/UnidadDeMedidaPlaceNew.java package es.jota.gwt.client.place.unidadDeMedida; import com.google.gwt.place.shared.PlaceTokenizer; import com.google.gwt.place.shared.Prefix; public class UnidadDeMedidaPlaceNew extends UnidadDeMedidaPlace { private final static String NAME = "unidadDeMedidaNew"; private UnidadDeMedidaPlaceNew() { } @Prefix(NAME) public static class Tokenizer implements PlaceTokenizer<UnidadDeMedidaPlaceNew> { @Override public String getToken(UnidadDeMedidaPlaceNew place) { return ""; } @Override public UnidadDeMedidaPlaceNew getPlace(String token) { return instance(); } } public static UnidadDeMedidaPlaceNew instance() { return new UnidadDeMedidaPlaceNew(); } public static String getUrl() { return "#" + NAME + ":"; } }<file_sep>/src/main/java/es/jota/gwt/client/display/unidadDeMedida/UnidadDeMedidaDisplayViewImpl.java package es.jota.gwt.client.display.unidadDeMedida; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.ParagraphElement; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.Widget; import es.jota.gwt.client.utils.UtilClient; import es.jota.gwt.client.widgets.display.MenuItem; public class UnidadDeMedidaDisplayViewImpl extends Composite implements UnidadDeMedidaDisplayView { private static UnidadDeMedidaDisplayViewUiBinder uiBinder = GWT.create(UnidadDeMedidaDisplayViewUiBinder.class); interface UnidadDeMedidaDisplayViewUiBinder extends UiBinder<Widget, UnidadDeMedidaDisplayViewImpl>{} @UiField HTMLPanel menu; @UiField MenuItem listar; @UiField MenuItem nuevo; @UiField MenuItem editar; @UiField ParagraphElement abreviacion; @UiField ParagraphElement nombre; @UiField ParagraphElement descripcion; private UnidadDeMedidaDisplayView.Listener listener; @Override public void setListener(Listener listener) { this.listener = listener; } public UnidadDeMedidaDisplayViewImpl() { initWidget(uiBinder.createAndBindUi(this)); } // menu @Override public HTMLPanel getMenu() { return menu; } @Override public void setEditarUrl( String url ) { editar.setHref( url ); } @Override public void setListarUrl( String url ) { listar.setHref( url ); } @Override public void setNuevoUrl( String url ) { nuevo.setHref( url ); } // fillForm @Override public void setAbreviacion( String abreviacion ) { this.abreviacion.setInnerHTML( abreviacion ); } @Override public void setNombre( String nombre ) { this.nombre.setInnerHTML( nombre ); } @Override public void setDescripcion( String descripcion ) { this.descripcion.setInnerSafeHtml( UtilClient.Cadena.string2SafeHtml( descripcion ) ); } }<file_sep>/src/main/java/es/jota/gwt/client/widgets/presenter/events/ValueAddHandler.java package es.jota.gwt.client.widgets.presenter.events; import com.google.gwt.event.shared.EventHandler; public interface ValueAddHandler<T> extends EventHandler { void onValueAdd(ValueAddEvent<T> event); } <file_sep>/src/main/java/es/jota/gwt/server/service/RecetaGwtServiceImpl.java package es.jota.gwt.server.service; import java.util.List; import jota.server.dto.FiltroServer; import jota.server.dto.IngredienteDeRecetaDto; import jota.server.dto.RecetaDto; import jota.server.exceptions.ServiceException; import jota.server.service.RecetaService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import es.jota.gwt.client.my.MyRemoteServiceServlet; import es.jota.gwt.client.service.RecetaGwtService; @Controller @RequestMapping("/recetaGwtService.gwt") public class RecetaGwtServiceImpl extends MyRemoteServiceServlet implements RecetaGwtService { private final Logger LOG = LoggerFactory.getLogger(RecetaGwtServiceImpl.class); private static final long serialVersionUID = -948716413193872587L; @Autowired RecetaService recetaService; @Override public RecetaDto getRecetaDtoById( Long id ) throws ServiceException { RecetaDto dev = null; dev = recetaService.getById( id ); return dev; } @Override public void modificarReceta( Long idReceta, RecetaDto recetaDto, List<IngredienteDeRecetaDto> ingredientesDeRecetaDto ) throws ServiceException { try { recetaService.modificar( idReceta, recetaDto, ingredientesDeRecetaDto ); }catch (Exception e) { e.printStackTrace(); } } @Override public Long insertarReceta( RecetaDto recetaDto, List<IngredienteDeRecetaDto> ingredientesDeRecetaDto ) throws ServiceException { Long dev = null; dev = recetaService.insertar( recetaDto, ingredientesDeRecetaDto ); return dev; } @Override public List<RecetaDto> findRecetasByFiltro( int start, int size, FiltroServer filtro ) throws ServiceException { List<RecetaDto> dev = null; dev = recetaService.findByFiltro( start, size, filtro ); return dev; } @Override public void borrarRecetaById( Long id ) throws ServiceException { recetaService.borrarById( id ); } }<file_sep>/src/main/java/es/jota/gwt/client/my/MyRemoteServiceServlet.java package es.jota.gwt.client.my; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.ServletContextAware; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.server.rpc.RemoteServiceServlet; public abstract class MyRemoteServiceServlet extends RemoteServiceServlet implements ServletContextAware, Controller, RemoteService { private static final long serialVersionUID = 7420008554025683977L; static final Logger LOG = LoggerFactory.getLogger(MyRemoteServiceServlet.class); private ServletContext servletContext; public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } public ServletContext getServletContext() { return servletContext; } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { try { doPost(request, response); } catch (Exception ex) { LOG.error("handleRequest error " + ex); } return null; } } <file_sep>/src/main/java/es/jota/gwt/client/activity/ingrediente/IngredienteActivityView.java package es.jota.gwt.client.activity.ingrediente; import jota.server.dto.IngredienteDto; import es.jota.gwt.client.miApp; import es.jota.gwt.client.display.ingrediente.IngredienteDisplayView; import es.jota.gwt.client.my.MyAbstractActivity; import es.jota.gwt.client.my.MyAsyncCallback; import es.jota.gwt.client.place.ingrediente.IngredientePlaceEdit; import es.jota.gwt.client.place.ingrediente.IngredientePlaceList; import es.jota.gwt.client.place.ingrediente.IngredientePlaceNew; import es.jota.gwt.client.place.ingrediente.IngredientePlaceView; import es.jota.gwt.client.service.IngredienteGwtService; public class IngredienteActivityView extends MyAbstractActivity<IngredientePlaceView> implements IngredienteDisplayView.Listener { private IngredienteDisplayView display; public IngredienteActivityView() { display = miApp.INJECTOR.getIngredienteDisplayView(); display.setListener( this ); display.setListarUrl( IngredientePlaceList.getUrl() ); display.setNuevoUrl( IngredientePlaceNew.getUrl() ); } @Override protected void start() { display.setEditarUrl( IngredientePlaceEdit.getUrl( place.getId() ) ); miApp.INJECTOR.getTopPublicoView().setMenu( display.getMenu() ); view(); } public void view() { IngredienteGwtService.Util.getInstance().getIngredienteDtoById( place.getId(), new MyAsyncCallback<IngredienteDto>( "Ingrediente", "Leyendo, id = " + place.getId() ) { @Override public void handleOnSuccess( IngredienteDto ingredienteDto ) { if ( ingredienteDto == null ) { goTo( IngredientePlaceNew.instance() ); } else { fillForm( ingredienteDto ); containerWidget.setWidget(display.asWidget()); } } }); } public void fillForm( IngredienteDto ingredienteDto ) { display.setNombre( ingredienteDto.getNombre() ); display.setDescripcion( ingredienteDto.getDescripcion() ); display.setPesoPorRacion( ingredienteDto.getPesoPorRacion() ); display.setCoste( ingredienteDto.getCoste() ); display.setUnidadDeMedida( ingredienteDto.getUnidadDeMedida() == null ? "" : ingredienteDto.getUnidadDeMedida().getNombre() ); display.setGrupoAlimento( ingredienteDto.getGrupoAlimento() == null ? "" : ingredienteDto.getGrupoAlimento().getNombre() ); } }<file_sep>/src/main/java/es/jota/gwt/client/service/IngredienteGwtServiceAsync.java package es.jota.gwt.client.service; import java.util.List; import jota.server.dto.FiltroServer; import jota.server.dto.IngredienteDto; import com.google.gwt.user.client.rpc.AsyncCallback; public interface IngredienteGwtServiceAsync { void getIngredienteDtoById( Long id, AsyncCallback<IngredienteDto> asyncCallback ); void modificarIngrediente( Long id, IngredienteDto ingredienteDto, Long idUnidadDeMedida, Long idGrupoAlimento, AsyncCallback<Void> asyncCallback ); void insertarIngrediente( IngredienteDto ingredienteDto, Long idUnidadDeMedida, Long idGrupoAlimento , AsyncCallback<Long> asyncCallback ); void findIngredientesByFiltro( int start, int size, FiltroServer filtro, AsyncCallback<List<IngredienteDto>> asyncCallback ); void borrarIngredienteById( Long id, AsyncCallback<Void> asyncCallback ); }<file_sep>/src/main/java/es/jota/gwt/client/display/grupoAlimento/GrupoAlimentoDisplayEdit.java package es.jota.gwt.client.display.grupoAlimento; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.IsWidget; import es.jota.gwt.client.interfaces.IEditActivity; public interface GrupoAlimentoDisplayEdit extends IsWidget { void setListener( GrupoAlimentoDisplayEdit.Listener listener ); public interface Listener extends IEditActivity.Listener { } // menu HTMLPanel getMenu(); void setListarUrl( String url ); void setNuevoUrl( String url ); void setVerUrl( String url); // fillForm void setColor( String abreviacion ); void setNombre( String nombre ); void setDescripcion( String descripcion ); // fillObject String getColor(); String getNombre(); String getDescripcion(); ///////////// }<file_sep>/src/main/java/es/jota/gwt/client/activity/logs/LogsActivity.java package es.jota.gwt.client.activity.logs; import com.google.gwt.place.shared.Place; import es.jota.gwt.client.miApp; import es.jota.gwt.client.display.logs.AlertView; import es.jota.gwt.client.display.logs.AlertViewImpl; import es.jota.gwt.client.display.logs.LogsView; import es.jota.gwt.client.my.MyAbstractActivity; public class LogsActivity extends MyAbstractActivity<Place> implements LogsView.Presenter { private LogsView display = miApp.INJECTOR.getLogsView(); public LogsActivity() { } @Override protected void start() { containerWidget.setWidget(display.asWidget()); } public AlertView crearAlert( String titulo, String texto ) { AlertView alert = new AlertViewImpl( titulo, texto ); display.getPanel().add( alert ); return alert; } }<file_sep>/src/main/java/es/jota/gwt/client/display/receta/RecetaDisplayList.java package es.jota.gwt.client.display.receta; import jota.server.dto.RecetaDto; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.IsWidget; import es.jota.gwt.client.cellTable.pager.MyPager.MyPagerView; public interface RecetaDisplayList extends IsWidget { void setListener( RecetaDisplayList.Listener listener ); public interface Listener { void reset(); void refresh(); void borrar( Long idIngrediente ); } // menu HTMLPanel getMenu(); void setNuevoUrl( String url ); CellTable<RecetaDto> getTabla(); MyPagerView getPagerDisplay(); }<file_sep>/src/main/java/es/jota/gwt/client/activity/ingrediente/IngredienteActivityList.java package es.jota.gwt.client.activity.ingrediente; import java.util.List; import jota.server.dto.FiltroServer; import jota.server.dto.IngredienteDto; import com.google.gwt.user.client.rpc.AsyncCallback; import es.jota.gwt.client.miApp; import es.jota.gwt.client.cellTable.pager.MyPagerScroller; import es.jota.gwt.client.display.ingrediente.IngredienteDisplayList; import es.jota.gwt.client.my.MyAbstractActivity; import es.jota.gwt.client.my.MyAsyncCallback; import es.jota.gwt.client.place.ingrediente.IngredientePlaceList; import es.jota.gwt.client.place.ingrediente.IngredientePlaceNew; import es.jota.gwt.client.service.IngredienteGwtService; public class IngredienteActivityList extends MyAbstractActivity<IngredientePlaceList> implements IngredienteDisplayList.Listener { private IngredienteDisplayList display; private MyPagerScroller<IngredienteDto> pager; private boolean canRefresh; public IngredienteActivityList() { canRefresh = false; display = miApp.INJECTOR.getIngredienteDisplayList(); display.setListener( this ); display.setNuevoUrl( IngredientePlaceNew.getUrl() ); pager = new MyPagerScroller<IngredienteDto>( display.getTabla(), display.getPagerDisplay() ) { @Override public void loadAsyncData( int start, int length, AsyncCallback<List<IngredienteDto>> asyncCallback ) { IngredienteGwtService.Util.getInstance().findIngredientesByFiltro( start, length, new FiltroServer(), asyncCallback ); } }; } @Override protected void start() { miApp.INJECTOR.getTopPublicoView().setMenu( display.getMenu() ); if ( canRefresh ) { refresh(); } canRefresh = true; containerWidget.setWidget(display.asWidget()); } @Override public void reset() { pager.reset(); } @Override public void refresh() { pager.refresh(); } @Override public void borrar( Long idIngrediente ) { IngredienteGwtService.Util.getInstance().borrarIngredienteById( idIngrediente, new MyAsyncCallback<Void>( "Ingrediente", "Borrando, id = " + idIngrediente ) { @Override public void handleOnSuccess(Void result) { refresh(); } }); } }<file_sep>/src/main/java/es/jota/gwt/client/gin/InjectorDisplay.java package es.jota.gwt.client.gin; import com.google.gwt.inject.client.GinModules; import com.google.gwt.inject.client.Ginjector; import es.jota.gwt.client.activity.fotos.FotosActivity; import es.jota.gwt.client.activity.fotos.FotosView; import es.jota.gwt.client.activity.grupoAlimento.GrupoAlimentoActivityEdit; import es.jota.gwt.client.activity.grupoAlimento.GrupoAlimentoActivityList; import es.jota.gwt.client.activity.grupoAlimento.GrupoAlimentoActivityNew; import es.jota.gwt.client.activity.grupoAlimento.GrupoAlimentoActivityView; import es.jota.gwt.client.activity.ingrediente.IngredienteActivityEdit; import es.jota.gwt.client.activity.ingrediente.IngredienteActivityList; import es.jota.gwt.client.activity.ingrediente.IngredienteActivityNew; import es.jota.gwt.client.activity.ingrediente.IngredienteActivityView; import es.jota.gwt.client.activity.inicio.InicioActivity; import es.jota.gwt.client.activity.logs.LogsActivity; import es.jota.gwt.client.activity.menu.TopActivity; import es.jota.gwt.client.activity.presupuesto.PresupuestoActivityNew; import es.jota.gwt.client.activity.receta.RecetaActivityEdit; import es.jota.gwt.client.activity.receta.RecetaActivityList; import es.jota.gwt.client.activity.receta.RecetaActivityNew; import es.jota.gwt.client.activity.receta.RecetaActivityView; import es.jota.gwt.client.activity.unidadDeMedida.UnidadDeMedidaActivityEdit; import es.jota.gwt.client.activity.unidadDeMedida.UnidadDeMedidaActivityList; import es.jota.gwt.client.activity.unidadDeMedida.UnidadDeMedidaActivityNew; import es.jota.gwt.client.activity.unidadDeMedida.UnidadDeMedidaActivityView; import es.jota.gwt.client.display.grupoAlimento.GrupoAlimentoDisplayEdit; import es.jota.gwt.client.display.grupoAlimento.GrupoAlimentoDisplayList; import es.jota.gwt.client.display.grupoAlimento.GrupoAlimentoDisplayNew; import es.jota.gwt.client.display.grupoAlimento.GrupoAlimentoDisplayView; import es.jota.gwt.client.display.ingrediente.IngredienteDisplayEdit; import es.jota.gwt.client.display.ingrediente.IngredienteDisplayList; import es.jota.gwt.client.display.ingrediente.IngredienteDisplayNew; import es.jota.gwt.client.display.ingrediente.IngredienteDisplayView; import es.jota.gwt.client.display.ingredienteDeReceta.IngredienteDeRecetaDisplayEdit; import es.jota.gwt.client.display.ingredienteDeReceta.IngredienteDeRecetaDisplayView; import es.jota.gwt.client.display.inicio.InicioView; import es.jota.gwt.client.display.logs.LogsView; import es.jota.gwt.client.display.menu.TopView; import es.jota.gwt.client.display.presupuesto.PresupuestoDisplayNewView; import es.jota.gwt.client.display.receta.RecetaDisplayEdit; import es.jota.gwt.client.display.receta.RecetaDisplayList; import es.jota.gwt.client.display.receta.RecetaDisplayNew; import es.jota.gwt.client.display.receta.RecetaDisplayView; import es.jota.gwt.client.display.unidadDeMedida.UnidadDeMedidaDisplayEdit; import es.jota.gwt.client.display.unidadDeMedida.UnidadDeMedidaDisplayList; import es.jota.gwt.client.display.unidadDeMedida.UnidadDeMedidaDisplayNew; import es.jota.gwt.client.display.unidadDeMedida.UnidadDeMedidaDisplayView; @GinModules(InjectorModule.class) public interface InjectorDisplay extends Ginjector { // ACTIVITY public FotosActivity getFotosActivity(); public InicioActivity getInicioActivity(); public LogsActivity getLogsActivity(); public TopActivity getTopMenuActivity(); public IngredienteActivityEdit getIngredienteActivityEdit(); public IngredienteActivityList getIngredienteActivityList(); public IngredienteActivityNew getIngredienteActivityNew(); public IngredienteActivityView getIngredienteActivityView(); public UnidadDeMedidaActivityEdit getUnidadDeMedidaActivityEdit(); public UnidadDeMedidaActivityList getUnidadDeMedidaActivityList(); public UnidadDeMedidaActivityNew getUnidadDeMedidaActivityNew(); public UnidadDeMedidaActivityView getUnidadDeMedidaActivityView(); public RecetaActivityEdit getRecetaActivityEdit(); public RecetaActivityList getRecetaActivityList(); public RecetaActivityNew getRecetaActivityNew(); public RecetaActivityView getRecetaActivityView(); public GrupoAlimentoActivityEdit getGrupoAlimentoActivityEdit(); public GrupoAlimentoActivityList getGrupoAlimentoActivityList(); public GrupoAlimentoActivityNew getGrupoAlimentoActivityNew(); public GrupoAlimentoActivityView getGrupoAlimentoActivityView(); public PresupuestoActivityNew getPresupuestoActivityNew(); //VIEW public LogsView getLogsView(); public TopView getTopPublicoView(); public InicioView getInicioView(); public FotosView getFotosView(); public IngredienteDisplayEdit getIngredienteDisplayEdit(); public IngredienteDisplayList getIngredienteDisplayList(); public IngredienteDisplayNew getIngredienteDisplayNew(); public IngredienteDisplayView getIngredienteDisplayView(); public UnidadDeMedidaDisplayEdit getUnidadDeMedidaDisplayEdit(); public UnidadDeMedidaDisplayList getUnidadDeMedidaDisplayList(); public UnidadDeMedidaDisplayNew getUnidadDeMedidaDisplayNew(); public UnidadDeMedidaDisplayView getUnidadDeMedidaDisplayView(); public RecetaDisplayEdit getRecetaDisplayEdit(); public RecetaDisplayList getRecetaDisplayList(); public RecetaDisplayNew getRecetaDisplayNew(); public RecetaDisplayView getRecetaDisplayView(); public IngredienteDeRecetaDisplayEdit getIngredienteDeRecetaDisplayEdit(); public IngredienteDeRecetaDisplayView getIngredienteDeRecetaDisplayView(); public GrupoAlimentoDisplayEdit getGrupoAlimentoDisplayEdit(); public GrupoAlimentoDisplayList getGrupoAlimentoDisplayList(); public GrupoAlimentoDisplayNew getGrupoAlimentoDisplayNew(); public GrupoAlimentoDisplayView getGrupoAlimentoDisplayView(); public PresupuestoDisplayNewView getPresupuestoDisplayNewView(); }<file_sep>/src/main/java/es/jota/gwt/server/service/UnidadDeMedidaGwtServiceImpl.java package es.jota.gwt.server.service; import java.util.List; import jota.server.dto.FiltroServer; import jota.server.dto.FiltroWhere; import jota.server.dto.UnidadDeMedidaDto; import jota.server.exceptions.ServiceException; import jota.server.service.UnidadDeMedidaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import es.jota.gwt.client.my.MyRemoteServiceServlet; import es.jota.gwt.client.service.UnidadDeMedidaGwtService; @Controller @RequestMapping("/unidadDeMedidaGwtService.gwt") public class UnidadDeMedidaGwtServiceImpl extends MyRemoteServiceServlet implements UnidadDeMedidaGwtService { private static final long serialVersionUID = -948716413193872587L; @Autowired UnidadDeMedidaService unidadDeMedidaService; @Override public void dummy( FiltroWhere a ) { } @Override public UnidadDeMedidaDto getUnidadDeMedidaDtoById( Long id ) throws ServiceException { UnidadDeMedidaDto dev = null; dev = unidadDeMedidaService.getById( id ); return dev; } @Override public void modificarUnidadDeMedida( Long id, UnidadDeMedidaDto unidadDeMedidaDto ) throws ServiceException { unidadDeMedidaService.modificar( id, unidadDeMedidaDto ); } @Override public Long insertarUnidadDeMedida( UnidadDeMedidaDto unidadDeMedidaDto ) throws ServiceException { Long dev = null; dev = unidadDeMedidaService.insertar( unidadDeMedidaDto ); return dev; } @Override public List<UnidadDeMedidaDto> findUnidadesDeMedidaByFiltro( int start, int size, FiltroServer filtro ) throws ServiceException { List<UnidadDeMedidaDto> dev = null; dev = unidadDeMedidaService.findByFiltro( start, size, filtro ); return dev; } @Override public void borrarUnidadDeMedidaById( Long id ) throws ServiceException { unidadDeMedidaService.borrarById( id ); } }<file_sep>/src/main/java/es/jota/gwt/client/display/ingredienteDeReceta/IngredienteDeRecetaDisplayEdit.java package es.jota.gwt.client.display.ingredienteDeReceta; import jota.server.dto.IngredienteDeRecetaDto; public interface IngredienteDeRecetaDisplayEdit { IngredienteDeRecetaDisplayEdit setListener( IngredienteDeRecetaDisplayEdit.Listener listener ); public interface Listener { } IngredienteDeRecetaDto get(); void set( IngredienteDeRecetaDto ingredienteDeRecetaDto ); }<file_sep>/src/main/java/es/jota/gwt/client/place/unidadDeMedida/UnidadDeMedidaPlace.java package es.jota.gwt.client.place.unidadDeMedida; import com.google.gwt.activity.shared.Activity; import com.google.gwt.place.shared.Place; import es.jota.gwt.client.miApp; public class UnidadDeMedidaPlace extends Place { protected UnidadDeMedidaPlace() { } public Activity getActivity( Place place ) { if ( place instanceof UnidadDeMedidaPlaceEdit ) return miApp.INJECTOR.getUnidadDeMedidaActivityEdit().setPlace( (UnidadDeMedidaPlaceEdit)place ); if ( place instanceof UnidadDeMedidaPlaceList ) return miApp.INJECTOR.getUnidadDeMedidaActivityList().setPlace( (UnidadDeMedidaPlaceList)place ); if ( place instanceof UnidadDeMedidaPlaceNew ) return miApp.INJECTOR.getUnidadDeMedidaActivityNew().setPlace( (UnidadDeMedidaPlaceNew)place ); if ( place instanceof UnidadDeMedidaPlaceView ) return miApp.INJECTOR.getUnidadDeMedidaActivityView().setPlace( (UnidadDeMedidaPlaceView)place ); return null; } }<file_sep>/src/main/java/es/jota/gwt/client/interfaces/INewActivity.java package es.jota.gwt.client.interfaces; import com.google.gwt.user.client.ui.IsWidget; public interface INewActivity extends IsWidget { public interface Listener { void guardarYListar(); void guardarYNuevo(); void guardar(); void limpiar(); } }<file_sep>/src/main/java/es/jota/gwt/client/place/ingrediente/IngredientePlaceNew.java package es.jota.gwt.client.place.ingrediente; import com.google.gwt.place.shared.PlaceTokenizer; import com.google.gwt.place.shared.Prefix; public class IngredientePlaceNew extends IngredientePlace { private final static String NAME = "ingredienteNew"; private IngredientePlaceNew() { } @Prefix(NAME) public static class Tokenizer implements PlaceTokenizer<IngredientePlaceNew> { @Override public String getToken(IngredientePlaceNew place) { return ""; } @Override public IngredientePlaceNew getPlace(String token) { return instance(); } } public static IngredientePlaceNew instance() { return new IngredientePlaceNew(); } public static String getUrl() { return "#" + NAME + ":"; } }<file_sep>/src/main/java/es/jota/gwt/server/service/IngredienteGwtServiceImpl.java package es.jota.gwt.server.service; import java.util.List; import jota.server.dto.FiltroServer; import jota.server.dto.IngredienteDto; import jota.server.exceptions.ServiceException; import jota.server.service.IngredienteService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import es.jota.gwt.client.my.MyRemoteServiceServlet; import es.jota.gwt.client.service.IngredienteGwtService; @Controller @RequestMapping("/ingredienteGwtService.gwt") public class IngredienteGwtServiceImpl extends MyRemoteServiceServlet implements IngredienteGwtService { private final Logger LOG = LoggerFactory.getLogger(IngredienteGwtServiceImpl.class); private static final long serialVersionUID = -948716413193872587L; @Autowired IngredienteService ingredienteService; @Override public IngredienteDto getIngredienteDtoById( Long id ) throws ServiceException { IngredienteDto dev = null; dev = ingredienteService.getById( id ); return dev; } @Override public void modificarIngrediente( Long idIngrediente, IngredienteDto ingredienteDto, Long idUnidadDeMedida, Long idGrupoAlimento ) throws ServiceException { ingredienteService.modificar( idIngrediente, ingredienteDto, idUnidadDeMedida, idGrupoAlimento ); } @Override public Long insertarIngrediente( IngredienteDto ingredienteDto, Long idUnidadDeMedida, Long idGrupoAlimento ) throws ServiceException { Long dev = null; dev = ingredienteService.insertar( ingredienteDto, idUnidadDeMedida, idGrupoAlimento ); return dev; } @Override public List<IngredienteDto> findIngredientesByFiltro( int start, int size, FiltroServer filtro ) throws ServiceException { List<IngredienteDto> dev = null; dev = ingredienteService.findByFiltro( start, size, filtro ); return dev; } @Override public void borrarIngredienteById( Long id ) throws ServiceException { ingredienteService.borrarById( id ); } }<file_sep>/src/main/java/es/jota/gwt/client/display/ingrediente/IngredienteDisplayView.java package es.jota.gwt.client.display.ingrediente; import java.math.BigDecimal; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.IsWidget; public interface IngredienteDisplayView extends IsWidget { void setListener( IngredienteDisplayView.Listener listener ); public interface Listener { } // menu HTMLPanel getMenu(); void setEditarUrl( String url); void setListarUrl( String url ); void setNuevoUrl( String url ); // fillForm void setNombre( String nombre ); void setDescripcion( String descripcion ); void setPesoPorRacion( BigDecimal pesoPorRacion ); void setCoste( BigDecimal coste ); void setUnidadDeMedida( String unidadDeMedida ); void setGrupoAlimento( String grupoAlimento ); }<file_sep>/src/main/java/es/jota/gwt/client/widgets/custom/SuggestRecetas.java package es.jota.gwt.client.widgets.custom; import java.util.ArrayList; import java.util.List; import jota.server.dto.FiltroServer; import jota.server.dto.FiltroWhere; import jota.server.dto.RecetaDto; import com.google.gwt.user.client.rpc.AsyncCallback; import es.jota.gwt.client.service.RecetaGwtService; import es.jota.gwt.client.widgets.presenter.SelectValuePresenter; import es.jota.gwt.client.widgets.presenter.interfaces.IAcceptableValuesProvider; import es.jota.gwt.client.widgets.presenter.interfaces.ISelectValue; public class SuggestRecetas extends SelectValuePresenter<RecetaDto> { public SuggestRecetas( ISelectValue.IDisplay display ) { super( display, true ); setItemTextProvider( new IItemProvider<RecetaDto>() { @Override public String get(RecetaDto item) { return item.getNombre(); } }); setAcceptableValuesProvider( new IAcceptableValuesProvider() { @Override public void load( int start, int size, String query, final long timestamp ) { FiltroServer filtro = new FiltroServer(); filtro.add( new FiltroWhere( "and nombre like :nombre", "nombre", "%" + query + "%") ); RecetaGwtService.Util.getInstance().findRecetasByFiltro( start, size, filtro, new AsyncCallback<List<RecetaDto>>() { @Override public void onFailure( Throwable caught ) { setAcceptableValues( new ArrayList<RecetaDto>(), timestamp ); } @Override public void onSuccess( List<RecetaDto> result ) { setAcceptableValues( result, timestamp ); } }); } }); } }<file_sep>/src/main/java/es/jota/gwt/client/activity/unidadDeMedida/UnidadDeMedidaActivityNew.java package es.jota.gwt.client.activity.unidadDeMedida; import jota.server.dto.UnidadDeMedidaDto; import es.jota.gwt.client.miApp; import es.jota.gwt.client.activity.IDoAfterInsert; import es.jota.gwt.client.display.unidadDeMedida.UnidadDeMedidaDisplayNew; import es.jota.gwt.client.my.MyAbstractActivity; import es.jota.gwt.client.my.MyAsyncCallback; import es.jota.gwt.client.place.unidadDeMedida.UnidadDeMedidaPlaceEdit; import es.jota.gwt.client.place.unidadDeMedida.UnidadDeMedidaPlaceList; import es.jota.gwt.client.place.unidadDeMedida.UnidadDeMedidaPlaceNew; import es.jota.gwt.client.service.UnidadDeMedidaGwtService; public class UnidadDeMedidaActivityNew extends MyAbstractActivity<UnidadDeMedidaPlaceNew> implements UnidadDeMedidaDisplayNew.Listener { private UnidadDeMedidaDisplayNew display; public UnidadDeMedidaActivityNew() { display = miApp.INJECTOR.getUnidadDeMedidaDisplayNew(); display.setListener( this ); display.setListarUrl( UnidadDeMedidaPlaceList.getUrl() ); } @Override protected void start() { miApp.INJECTOR.getTopPublicoView().setMenu( display.getMenu() ); display.setClean(); containerWidget.setWidget(display.asWidget()); } @Override public void guardarYListar() { guardar( new IDoAfterInsert<Long>() { @Override public void exec( Long idUnidadDeMedida ) { goTo( UnidadDeMedidaPlaceList.instance() ); } }); } @Override public void guardarYNuevo() { guardar( new IDoAfterInsert<Long>() { @Override public void exec( Long idReceta ) { start(); } }); } @Override public void guardar() { guardar( new IDoAfterInsert<Long>() { @Override public void exec( Long idUnidadDeMedida ) { goTo( UnidadDeMedidaPlaceEdit.instance( idUnidadDeMedida ) ); } }); } private void guardar( final IDoAfterInsert<Long> doAfterInsert ) { UnidadDeMedidaGwtService.Util.getInstance().insertarUnidadDeMedida( fillObject(), new MyAsyncCallback<Long>( "Unidad de medida", "Insertando", null, "Insertado" ) { @Override public void handleOnSuccess( Long idUnidadDeMedida ) { doAfterInsert.exec( idUnidadDeMedida ); } }); } private UnidadDeMedidaDto fillObject() { UnidadDeMedidaDto unidadDeMedidaDto = new UnidadDeMedidaDto(); unidadDeMedidaDto.setAbreviacion( display.getAbreviacion() ); unidadDeMedidaDto.setNombre( display.getNombre() ); unidadDeMedidaDto.setDescripcion( display.getDescripcion() ); return unidadDeMedidaDto; } @Override public void limpiar() { display.setClean(); } }<file_sep>/src/main/java/es/jota/gwt/client/validator/notNull.java package es.jota.gwt.client.validator; public class notNull extends Validation<Object> { public notNull(Object value) { super(value); } @Override public String validate() { String dev = null; if ( value == null ) { dev = "No puede ser null"; } return dev; } } <file_sep>/src/main/java/es/jota/gwt/client/widgets/presenter/interfaces/HasValueAddHandlers.java package es.jota.gwt.client.widgets.presenter.interfaces; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.HasHandlers; import es.jota.gwt.client.widgets.presenter.events.ValueAddHandler; public interface HasValueAddHandlers<T> extends HasHandlers { HandlerRegistration addValueAddHandler( ValueAddHandler<T> handler ); }<file_sep>/src/main/java/es/jota/gwt/client/activity/grupoAlimento/GrupoAlimentoActivityNew.java package es.jota.gwt.client.activity.grupoAlimento; import jota.server.dto.GrupoAlimentoDto; import es.jota.gwt.client.miApp; import es.jota.gwt.client.activity.IDoAfterInsert; import es.jota.gwt.client.display.grupoAlimento.GrupoAlimentoDisplayNew; import es.jota.gwt.client.my.MyAbstractActivity; import es.jota.gwt.client.my.MyAsyncCallback; import es.jota.gwt.client.place.grupoAlimento.GrupoAlimentoPlaceEdit; import es.jota.gwt.client.place.grupoAlimento.GrupoAlimentoPlaceList; import es.jota.gwt.client.place.grupoAlimento.GrupoAlimentoPlaceNew; import es.jota.gwt.client.service.GrupoAlimentoGwtService; public class GrupoAlimentoActivityNew extends MyAbstractActivity<GrupoAlimentoPlaceNew> implements GrupoAlimentoDisplayNew.Listener { private GrupoAlimentoDisplayNew display; public GrupoAlimentoActivityNew() { display = miApp.INJECTOR.getGrupoAlimentoDisplayNew(); display.setListener( this ); display.setListarUrl( GrupoAlimentoPlaceList.getUrl() ); } @Override protected void start() { miApp.INJECTOR.getTopPublicoView().setMenu( display.getMenu() ); display.setClean(); containerWidget.setWidget(display.asWidget()); } @Override public void guardarYListar() { guardar( new IDoAfterInsert<Long>() { @Override public void exec( Long idGrupoAlimento ) { goTo( GrupoAlimentoPlaceList.instance() ); } }); } @Override public void guardarYNuevo() { guardar( new IDoAfterInsert<Long>() { @Override public void exec( Long idReceta ) { start(); } }); } @Override public void guardar() { guardar( new IDoAfterInsert<Long>() { @Override public void exec( Long idGrupoAlimento ) { goTo( GrupoAlimentoPlaceEdit.instance( idGrupoAlimento ) ); } }); } private void guardar( final IDoAfterInsert<Long> doAfterInsert ) { GrupoAlimentoGwtService.Util.getInstance().insertarGrupoAlimento( fillObject(), new MyAsyncCallback<Long>( "Grupo alimenticio", "Insertando", null, "Insertado" ) { @Override public void handleOnSuccess( Long idGrupoAlimento ) { doAfterInsert.exec( idGrupoAlimento ); } }); } private GrupoAlimentoDto fillObject() { GrupoAlimentoDto grupoAlimentoDto = new GrupoAlimentoDto(); grupoAlimentoDto.setColor( display.getColor() ); grupoAlimentoDto.setNombre( display.getNombre() ); grupoAlimentoDto.setDescripcion( display.getDescripcion() ); return grupoAlimentoDto; } @Override public void limpiar() { display.setClean(); } }<file_sep>/src/main/java/es/jota/gwt/client/display/receta/RecetaDisplayNew.java package es.jota.gwt.client.display.receta; import java.math.BigDecimal; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.IsWidget; import es.jota.gwt.client.interfaces.INewActivity; import es.jota.gwt.client.widgets.display.TBodyPanel; public interface RecetaDisplayNew extends IsWidget { void setListener( RecetaDisplayNew.Listener listener ); public interface Listener extends INewActivity.Listener { void addIngredientesDeReceta(); } // menu HTMLPanel getMenu(); void setListarUrl( String url ); // cleanForm void clear(); // fillReceta String getNombre(); String getDescripcion(); BigDecimal getPax(); // fillIngredientesDeReceta TBodyPanel getIngredientesDeReceta(); // Validate boolean validate(); ///////////// }<file_sep>/src/main/java/es/jota/gwt/client/place/grupoAlimento/GrupoAlimentoPlace.java package es.jota.gwt.client.place.grupoAlimento; import com.google.gwt.activity.shared.Activity; import com.google.gwt.place.shared.Place; import es.jota.gwt.client.miApp; public class GrupoAlimentoPlace extends Place { protected GrupoAlimentoPlace() { } public Activity getActivity( Place place ) { if ( place instanceof GrupoAlimentoPlaceEdit ) return miApp.INJECTOR.getGrupoAlimentoActivityEdit().setPlace( (GrupoAlimentoPlaceEdit)place ); if ( place instanceof GrupoAlimentoPlaceList ) return miApp.INJECTOR.getGrupoAlimentoActivityList().setPlace( (GrupoAlimentoPlaceList)place ); if ( place instanceof GrupoAlimentoPlaceNew ) return miApp.INJECTOR.getGrupoAlimentoActivityNew().setPlace( (GrupoAlimentoPlaceNew)place ); if ( place instanceof GrupoAlimentoPlaceView ) return miApp.INJECTOR.getGrupoAlimentoActivityView().setPlace( (GrupoAlimentoPlaceView)place ); return null; } }
4849eedebbe7a88ae9eaf56532bcef1d5e2a89e1
[ "Java" ]
43
Java
jota40/dietaClient
beae7e1fee4280e911d8433b386e2730f76fd363
d9842d9ab88e6dbb9ea8ff9ea403652b53f8d7da
refs/heads/master
<file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblrealms * * @ORM\Table(name="tblRealms", uniqueConstraints={@ORM\UniqueConstraint(name="strRealmKey_UNIQUE", columns={"strRealmKey"})}, indexes={@ORM\Index(name="fk_tblRealms_tblRealmTypes1_idx", columns={"intRealmTypeID"})}) * @ORM\Entity */ class Tblrealms { /** * @var integer * * @ORM\Column(name="intRealmID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intrealmid; /** * @var string * * @ORM\Column(name="strRealmKey", type="string", length=45, nullable=false) */ private $strrealmkey; /** * @var string * * @ORM\Column(name="strRealmSecret", type="string", length=100, nullable=false) */ private $strrealmsecret; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * @var \Security\Entity\Tblrealmtypes * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblrealmtypes") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intRealmTypeID", referencedColumnName="intRealmTypeID") * }) */ private $intrealmtypeid; /** * Get intrealmid * * @return integer */ public function getIntrealmid() { return $this->intrealmid; } /** * Set strrealmkey * * @param string $strrealmkey * @return Tblrealms */ public function setStrrealmkey($strrealmkey) { $this->strrealmkey = $strrealmkey; return $this; } /** * Get strrealmkey * * @return string */ public function getStrrealmkey() { return $this->strrealmkey; } /** * Set strrealmsecret * * @param string $strrealmsecret * @return Tblrealms */ public function setStrrealmsecret($strrealmsecret) { $this->strrealmsecret = $strrealmsecret; return $this; } /** * Get strrealmsecret * * @return string */ public function getStrrealmsecret() { return $this->strrealmsecret; } /** * Set intstatus * * @param integer $intstatus * @return Tblrealms */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } /** * Set intrealmtypeid * * @param \Security\Entity\Tblrealmtypes $intrealmtypeid * @return Tblrealms */ public function setIntrealmtypeid(\Security\Entity\Tblrealmtypes $intrealmtypeid = null) { $this->intrealmtypeid = $intrealmtypeid; return $this; } /** * Get intrealmtypeid * * @return \Security\Entity\Tblrealmtypes */ public function getIntrealmtypeid() { return $this->intrealmtypeid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblproductcategory * * @ORM\Table(name="tblProductCategory", indexes={@ORM\Index(name="fk_tblProductCategory_tblProducts1_idx", columns={"intProductID"})}) * @ORM\Entity */ class Tblproductcategory { /** * @var integer * * @ORM\Column(name="intCategoryID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcategoryid; /** * @var string * * @ORM\Column(name="strCategoryName", type="string", length=45, nullable=false) */ private $strcategoryname; /** * @var \Security\Entity\Tblproducts * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblproducts") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intProductID", referencedColumnName="intProductID") * }) */ private $intproductid; /** * Get intcategoryid * * @return integer */ public function getIntcategoryid() { return $this->intcategoryid; } /** * Set strcategoryname * * @param string $strcategoryname * @return Tblproductcategory */ public function setStrcategoryname($strcategoryname) { $this->strcategoryname = $strcategoryname; return $this; } /** * Get strcategoryname * * @return string */ public function getStrcategoryname() { return $this->strcategoryname; } /** * Set intproductid * * @param \Security\Entity\Tblproducts $intproductid * @return Tblproductcategory */ public function setIntproductid(\Security\Entity\Tblproducts $intproductid = null) { $this->intproductid = $intproductid; return $this; } /** * Get intproductid * * @return \Security\Entity\Tblproducts */ public function getIntproductid() { return $this->intproductid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblusers * * @ORM\Table(name="tblUsers", uniqueConstraints={@ORM\UniqueConstraint(name="username_UNIQUE", columns={"strUsername"}), @ORM\UniqueConstraint(name="user_id_UNIQUE", columns={"intUserID"}), @ORM\UniqueConstraint(name="name_UNIQUE", columns={"strName"}), @ORM\UniqueConstraint(name="email_UNIQUE", columns={"strEmail"})}, indexes={@ORM\Index(name="fk_users_roles_idx", columns={"intRoleID"}), @ORM\Index(name="fk_users_status1_idx", columns={"intUserStatusID"})}) * @ORM\Entity */ class Tblusers { /** * @var integer * * @ORM\Column(name="intUserID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intuserid; /** * @var string * * @ORM\Column(name="strName", type="string", length=45, nullable=true) */ private $strname; /** * @var string * * @ORM\Column(name="strEmail", type="string", length=45, nullable=true) */ private $stremail; /** * @var string * * @ORM\Column(name="strUsername", type="string", length=45, nullable=false) */ private $strusername; /** * @var string * * @ORM\Column(name="strPassword", type="string", length=45, nullable=false) */ private $strpassword; /** * @var \Security\Entity\Tblroles * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblroles") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intRoleID", referencedColumnName="intRoleID") * }) */ private $introleid; /** * @var \Security\Entity\Tbluserstatus * * @ORM\ManyToOne(targetEntity="Security\Entity\Tbluserstatus") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intUserStatusID", referencedColumnName="intUserStatusID") * }) */ private $intuserstatusid; /** * Get intuserid * * @return integer */ public function getIntuserid() { return $this->intuserid; } /** * Set strname * * @param string $strname * @return Tblusers */ public function setStrname($strname) { $this->strname = $strname; return $this; } /** * Get strname * * @return string */ public function getStrname() { return $this->strname; } /** * Set stremail * * @param string $stremail * @return Tblusers */ public function setStremail($stremail) { $this->stremail = $stremail; return $this; } /** * Get stremail * * @return string */ public function getStremail() { return $this->stremail; } /** * Set strusername * * @param string $strusername * @return Tblusers */ public function setStrusername($strusername) { $this->strusername = $strusername; return $this; } /** * Get strusername * * @return string */ public function getStrusername() { return $this->strusername; } /** * Set strpassword * * @param string $strpassword * @return Tblusers */ public function setStrpassword($strpassword) { $this->strpassword = $strpassword; return $this; } /** * Get strpassword * * @return string */ public function getStrpassword() { return $this->strpassword; } /** * Set introleid * * @param \Security\Entity\Tblroles $introleid * @return Tblusers */ public function setIntroleid(\Security\Entity\Tblroles $introleid = null) { $this->introleid = $introleid; return $this; } /** * Get introleid * * @return \Security\Entity\Tblroles */ public function getIntroleid() { return $this->introleid; } /** * Set intuserstatusid * * @param \Security\Entity\Tbluserstatus $intuserstatusid * @return Tblusers */ public function setIntuserstatusid(\Security\Entity\Tbluserstatus $intuserstatusid = null) { $this->intuserstatusid = $intuserstatusid; return $this; } /** * Get intuserstatusid * * @return \Security\Entity\Tbluserstatus */ public function getIntuserstatusid() { return $this->intuserstatusid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblproductcost * * @ORM\Table(name="tblProductCost", indexes={@ORM\Index(name="fk_tblProductCost_tblProducts1_idx", columns={"intProductID"}), @ORM\Index(name="fk_tblProductCost_tblCurrency1_idx", columns={"intCurrencyID"})}) * @ORM\Entity */ class Tblproductcost { /** * @var integer * * @ORM\Column(name="intProductCostID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intproductcostid; /** * @var string * * @ORM\Column(name="actual_landed_cost", type="string", length=45, nullable=true) */ private $actualLandedCost; /** * @var string * * @ORM\Column(name="purchase_cost", type="string", length=45, nullable=true) */ private $purchaseCost; /** * @var \Security\Entity\Tblcurrency * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblcurrency") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCurrencyID", referencedColumnName="intCurrencyID") * }) */ private $intcurrencyid; /** * @var \Security\Entity\Tblproducts * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblproducts") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intProductID", referencedColumnName="intProductID") * }) */ private $intproductid; /** * Get intproductcostid * * @return integer */ public function getIntproductcostid() { return $this->intproductcostid; } /** * Set actualLandedCost * * @param string $actualLandedCost * @return Tblproductcost */ public function setActualLandedCost($actualLandedCost) { $this->actualLandedCost = $actualLandedCost; return $this; } /** * Get actualLandedCost * * @return string */ public function getActualLandedCost() { return $this->actualLandedCost; } /** * Set purchaseCost * * @param string $purchaseCost * @return Tblproductcost */ public function setPurchaseCost($purchaseCost) { $this->purchaseCost = $purchaseCost; return $this; } /** * Get purchaseCost * * @return string */ public function getPurchaseCost() { return $this->purchaseCost; } /** * Set intcurrencyid * * @param \Security\Entity\Tblcurrency $intcurrencyid * @return Tblproductcost */ public function setIntcurrencyid(\Security\Entity\Tblcurrency $intcurrencyid = null) { $this->intcurrencyid = $intcurrencyid; return $this; } /** * Get intcurrencyid * * @return \Security\Entity\Tblcurrency */ public function getIntcurrencyid() { return $this->intcurrencyid; } /** * Set intproductid * * @param \Security\Entity\Tblproducts $intproductid * @return Tblproductcost */ public function setIntproductid(\Security\Entity\Tblproducts $intproductid = null) { $this->intproductid = $intproductid; return $this; } /** * Get intproductid * * @return \Security\Entity\Tblproducts */ public function getIntproductid() { return $this->intproductid; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblproductstatus * * @ORM\Table(name="tblProductStatus", uniqueConstraints={@ORM\UniqueConstraint(name="strProductStatus_UNIQUE", columns={"strProductStatus"})}) * @ORM\Entity */ class Tblproductstatus { /** * @var integer * * @ORM\Column(name="intProductStatusID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intproductstatusid; /** * @var string * * @ORM\Column(name="strProductStatus", type="string", length=45, nullable=false) */ private $strproductstatus; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intproductstatusid * * @return integer */ public function getIntproductstatusid() { return $this->intproductstatusid; } /** * Set strproductstatus * * @param string $strproductstatus * @return Tblproductstatus */ public function setStrproductstatus($strproductstatus) { $this->strproductstatus = $strproductstatus; return $this; } /** * Get strproductstatus * * @return string */ public function getStrproductstatus() { return $this->strproductstatus; } /** * Set intactive * * @param integer $intactive * @return Tblproductstatus */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep>var ajaxCreatePerson = function(data,cb){ callAjaxRequest("POST","/api/person/add",data,cb); }; var ajaxEditPerson = function(data,id,cb){ callAjaxRequest("POST","/api/person/edit/"+id,data,cb); }; var ajaxGetPersonTypeOptions = function(cb){ callAjaxRequest(null,"/api/person/type/list",null,cb); };<file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tbluserstatus * * @ORM\Table(name="tblUserStatus") * @ORM\Entity */ class Tbluserstatus { /** * @var integer * * @ORM\Column(name="intUserStatusID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intuserstatusid; /** * @var string * * @ORM\Column(name="strCategory", type="string", length=45, nullable=false) */ private $strcategory; /** * @var string * * @ORM\Column(name="strStatus", type="string", length=45, nullable=false) */ private $strstatus; /** * Get intuserstatusid * * @return integer */ public function getIntuserstatusid() { return $this->intuserstatusid; } /** * Set strcategory * * @param string $strcategory * @return Tbluserstatus */ public function setStrcategory($strcategory) { $this->strcategory = $strcategory; return $this; } /** * Get strcategory * * @return string */ public function getStrcategory() { return $this->strcategory; } /** * Set strstatus * * @param string $strstatus * @return Tbluserstatus */ public function setStrstatus($strstatus) { $this->strstatus = $strstatus; return $this; } /** * Get strstatus * * @return string */ public function getStrstatus() { return $this->strstatus; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tbluom * * @ORM\Table(name="tblUOM", uniqueConstraints={@ORM\UniqueConstraint(name="strUOM_UNIQUE", columns={"strUOM"})}) * @ORM\Entity */ class Tbluom { /** * @var integer * * @ORM\Column(name="intUOMID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intuomid; /** * @var string * * @ORM\Column(name="strUOM", type="string", length=45, nullable=false) */ private $struom; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intuomid * * @return integer */ public function getIntuomid() { return $this->intuomid; } /** * Set struom * * @param string $struom * @return Tbluom */ public function setStruom($struom) { $this->struom = $struom; return $this; } /** * Get struom * * @return string */ public function getStruom() { return $this->struom; } /** * Set intactive * * @param integer $intactive * @return Tbluom */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblentitytype * * @ORM\Table(name="tblEntityType") * @ORM\Entity */ class Tblentitytype { /** * @var integer * * @ORM\Column(name="intEntityTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intentitytypeid; /** * @var string * * @ORM\Column(name="strEntityTypeName", type="string", length=45, nullable=false) */ private $strentitytypename; /** * @var string * * @ORM\Column(name="intActive", type="string", length=45, nullable=true) */ private $intactive = '1'; /** * Get intentitytypeid * * @return integer */ public function getIntentitytypeid() { return $this->intentitytypeid; } /** * Set strentitytypename * * @param string $strentitytypename * @return Tblentitytype */ public function setStrentitytypename($strentitytypename) { $this->strentitytypename = $strentitytypename; return $this; } /** * Get strentitytypename * * @return string */ public function getStrentitytypename() { return $this->strentitytypename; } /** * Set intactive * * @param string $intactive * @return Tblentitytype */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return string */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblprovince * * @ORM\Table(name="tblProvince") * @ORM\Entity */ class Tblprovince { /** * @var integer * * @ORM\Column(name="intProvinceID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intprovinceid; /** * @var string * * @ORM\Column(name="strProvinceName", type="string", length=45, nullable=false) */ private $strprovincename; /** * Get intprovinceid * * @return integer */ public function getIntprovinceid() { return $this->intprovinceid; } /** * Set strprovincename * * @param string $strprovincename * @return Tblprovince */ public function setStrprovincename($strprovincename) { $this->strprovincename = $strprovincename; return $this; } /** * Get strprovincename * * @return string */ public function getStrprovincename() { return $this->strprovincename; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tbllocationtypes * * @ORM\Table(name="tblLocationTypes", uniqueConstraints={@ORM\UniqueConstraint(name="strLocationType_UNIQUE", columns={"strLocationType"})}) * @ORM\Entity */ class Tbllocationtypes { /** * @var integer * * @ORM\Column(name="intLocationTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intlocationtypeid; /** * @var string * * @ORM\Column(name="strLocationType", type="string", length=45, nullable=false) */ private $strlocationtype; /** * Get intlocationtypeid * * @return integer */ public function getIntlocationtypeid() { return $this->intlocationtypeid; } /** * Set strlocationtype * * @param string $strlocationtype * @return Tbllocationtypes */ public function setStrlocationtype($strlocationtype) { $this->strlocationtype = $strlocationtype; return $this; } /** * Get strlocationtype * * @return string */ public function getStrlocationtype() { return $this->strlocationtype; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblactionfields * * @ORM\Table(name="tblActionFields", indexes={@ORM\Index(name="fk_tblActionFields_tblAttributes1_idx", columns={"intAttributeID"}), @ORM\Index(name="fk_tblActionFields_tblActions1_idx", columns={"intActionID"}), @ORM\Index(name="fk_tblActionFields_tblDisplayTypes1_idx", columns={"intDisplayTypeID"}), @ORM\Index(name="fk_tblActionFields_tblActionFieldType1_idx", columns={"intActionFieldTypeID"})}) * @ORM\Entity */ class Tblactionfields { /** * @var integer * * @ORM\Column(name="intActionFieldID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $intactionfieldid; /** * @var integer * * @ORM\Column(name="intOrder", type="integer", nullable=true) */ private $intorder; /** * @var integer * * @ORM\Column(name="intGroup", type="integer", nullable=true) */ private $intgroup; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * @var \Main\Entity\Tblactionfieldtype * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Main\Entity\Tblactionfieldtype") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intActionFieldTypeID", referencedColumnName="intActionFieldTypeID") * }) */ private $intactionfieldtypeid; /** * @var \Main\Entity\Tblactions * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Main\Entity\Tblactions") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intActionID", referencedColumnName="intActionID") * }) */ private $intactionid; /** * @var \Main\Entity\Tblattributes * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Main\Entity\Tblattributes") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intAttributeID", referencedColumnName="intAttributeID") * }) */ private $intattributeid; /** * @var \Main\Entity\Tbldisplaytypes * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Main\Entity\Tbldisplaytypes") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intDisplayTypeID", referencedColumnName="intDisplayTypeID") * }) */ private $intdisplaytypeid; /** * Set intactionfieldid * * @param integer $intactionfieldid * @return Tblactionfields */ public function setIntactionfieldid($intactionfieldid) { $this->intactionfieldid = $intactionfieldid; return $this; } /** * Get intactionfieldid * * @return integer */ public function getIntactionfieldid() { return $this->intactionfieldid; } /** * Set intorder * * @param integer $intorder * @return Tblactionfields */ public function setIntorder($intorder) { $this->intorder = $intorder; return $this; } /** * Get intorder * * @return integer */ public function getIntorder() { return $this->intorder; } /** * Set intgroup * * @param integer $intgroup * @return Tblactionfields */ public function setIntgroup($intgroup) { $this->intgroup = $intgroup; return $this; } /** * Get intgroup * * @return integer */ public function getIntgroup() { return $this->intgroup; } /** * Set intstatus * * @param integer $intstatus * @return Tblactionfields */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } /** * Set intactionfieldtypeid * * @param \Main\Entity\Tblactionfieldtype $intactionfieldtypeid * @return Tblactionfields */ public function setIntactionfieldtypeid(\Main\Entity\Tblactionfieldtype $intactionfieldtypeid) { $this->intactionfieldtypeid = $intactionfieldtypeid; return $this; } /** * Get intactionfieldtypeid * * @return \Main\Entity\Tblactionfieldtype */ public function getIntactionfieldtypeid() { return $this->intactionfieldtypeid; } /** * Set intactionid * * @param \Main\Entity\Tblactions $intactionid * @return Tblactionfields */ public function setIntactionid(\Main\Entity\Tblactions $intactionid) { $this->intactionid = $intactionid; return $this; } /** * Get intactionid * * @return \Main\Entity\Tblactions */ public function getIntactionid() { return $this->intactionid; } /** * Set intattributeid * * @param \Main\Entity\Tblattributes $intattributeid * @return Tblactionfields */ public function setIntattributeid(\Main\Entity\Tblattributes $intattributeid) { $this->intattributeid = $intattributeid; return $this; } /** * Get intattributeid * * @return \Main\Entity\Tblattributes */ public function getIntattributeid() { return $this->intattributeid; } /** * Set intdisplaytypeid * * @param \Main\Entity\Tbldisplaytypes $intdisplaytypeid * @return Tblactionfields */ public function setIntdisplaytypeid(\Main\Entity\Tbldisplaytypes $intdisplaytypeid) { $this->intdisplaytypeid = $intdisplaytypeid; return $this; } /** * Get intdisplaytypeid * * @return \Main\Entity\Tbldisplaytypes */ public function getIntdisplaytypeid() { return $this->intdisplaytypeid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblrealmtypes * * @ORM\Table(name="tblRealmTypes") * @ORM\Entity */ class Tblrealmtypes { /** * @var integer * * @ORM\Column(name="intRealmTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intrealmtypeid; /** * @var string * * @ORM\Column(name="strRealmType", type="string", length=45, nullable=true) */ private $strrealmtype; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * Get intrealmtypeid * * @return integer */ public function getIntrealmtypeid() { return $this->intrealmtypeid; } /** * Set strrealmtype * * @param string $strrealmtype * @return Tblrealmtypes */ public function setStrrealmtype($strrealmtype) { $this->strrealmtype = $strrealmtype; return $this; } /** * Get strrealmtype * * @return string */ public function getStrrealmtype() { return $this->strrealmtype; } /** * Set intstatus * * @param integer $intstatus * @return Tblrealmtypes */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblobjects * * @ORM\Table(name="tblObjects") * @ORM\Entity */ class Tblobjects { /** * @var integer * * @ORM\Column(name="intObjectID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intobjectid; /** * @var string * * @ORM\Column(name="strObjectName", type="string", length=45, nullable=true) */ private $strobjectname; /** * @var string * * @ORM\Column(name="strObjectLabel", type="string", length=45, nullable=true) */ private $strobjectlabel; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * Get intobjectid * * @return integer */ public function getIntobjectid() { return $this->intobjectid; } /** * Set strobjectname * * @param string $strobjectname * @return Tblobjects */ public function setStrobjectname($strobjectname) { $this->strobjectname = $strobjectname; return $this; } /** * Get strobjectname * * @return string */ public function getStrobjectname() { return $this->strobjectname; } /** * Set strobjectlabel * * @param string $strobjectlabel * @return Tblobjects */ public function setStrobjectlabel($strobjectlabel) { $this->strobjectlabel = $strobjectlabel; return $this; } /** * Get strobjectlabel * * @return string */ public function getStrobjectlabel() { return $this->strobjectlabel; } /** * Set intstatus * * @param integer $intstatus * @return Tblobjects */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblmodules * * @ORM\Table(name="tblModules", indexes={@ORM\Index(name="fk_tblModules_tblRealms1_idx", columns={"intRealmID"})}) * @ORM\Entity */ class Tblmodules { /** * @var integer * * @ORM\Column(name="intModuleID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intmoduleid; /** * @var string * * @ORM\Column(name="strModuleName", type="string", length=45, nullable=true) */ private $strmodulename; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus; /** * @var \Main\Entity\Tblrealms * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblrealms") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intRealmID", referencedColumnName="intRealmID") * }) */ private $intrealmid; /** * Get intmoduleid * * @return integer */ public function getIntmoduleid() { return $this->intmoduleid; } /** * Set strmodulename * * @param string $strmodulename * @return Tblmodules */ public function setStrmodulename($strmodulename) { $this->strmodulename = $strmodulename; return $this; } /** * Get strmodulename * * @return string */ public function getStrmodulename() { return $this->strmodulename; } /** * Set intstatus * * @param integer $intstatus * @return Tblmodules */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } /** * Set intrealmid * * @param \Main\Entity\Tblrealms $intrealmid * @return Tblmodules */ public function setIntrealmid(\Main\Entity\Tblrealms $intrealmid = null) { $this->intrealmid = $intrealmid; return $this; } /** * Get intrealmid * * @return \Main\Entity\Tblrealms */ public function getIntrealmid() { return $this->intrealmid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblpaymentterms * * @ORM\Table(name="tblPaymentTerms", uniqueConstraints={@ORM\UniqueConstraint(name="strPaymentTermName_UNIQUE", columns={"strPaymentTerm"})}) * @ORM\Entity */ class Tblpaymentterms { /** * @var integer * * @ORM\Column(name="intPaymentTermID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intpaymenttermid; /** * @var string * * @ORM\Column(name="strPaymentTerm", type="string", length=45, nullable=false) */ private $strpaymentterm; /** * @var integer * * @ORM\Column(name="intValueInDays", type="integer", nullable=true) */ private $intvalueindays; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intpaymenttermid * * @return integer */ public function getIntpaymenttermid() { return $this->intpaymenttermid; } /** * Set strpaymentterm * * @param string $strpaymentterm * @return Tblpaymentterms */ public function setStrpaymentterm($strpaymentterm) { $this->strpaymentterm = $strpaymentterm; return $this; } /** * Get strpaymentterm * * @return string */ public function getStrpaymentterm() { return $this->strpaymentterm; } /** * Set intvalueindays * * @param integer $intvalueindays * @return Tblpaymentterms */ public function setIntvalueindays($intvalueindays) { $this->intvalueindays = $intvalueindays; return $this; } /** * Get intvalueindays * * @return integer */ public function getIntvalueindays() { return $this->intvalueindays; } /** * Set intactive * * @param integer $intactive * @return Tblpaymentterms */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Users; return array( 'router' => array( 'routes' => array( 'users_security_login' => array( 'type' => 'Literal', 'options' => array( 'route' => '/users/security/login', 'defaults' => array( '__NAMESPACE__' => 'Users\Controller', 'controller' => 'Security', 'action' => 'login', ), ), ), 'users_api_login' => array( 'type' => 'Literal', 'options' => array( 'route' => '/users/api/login', 'defaults' => array( '__NAMESPACE__' => 'Users\Controller', 'controller' => 'Api', 'action' => 'login', ), ), ), 'users_api_logout' => array( 'type' => 'Literal', 'options' => array( 'route' => '/users/api/logout', 'defaults' => array( '__NAMESPACE__' => 'Users\Controller', 'controller' => 'Api', 'action' => 'logout', ), ), ) ), ), 'doctrine' => array( 'authentication' => array( 'orm_default' => array( 'object_manager' => 'Doctrine\ORM\EntityManager', 'identity_class' => 'Main\Entity\Tblusers', 'identity_property' => 'strusername', 'credential_property' => 'strpassword', ), ), ), 'controllers' => array( 'invokables' => array( 'Users\Controller\Security' => 'Users\Controller\SecurityController', 'Users\Controller\Api' => 'Users\Controller\ApiController', ), ), 'view_manager' => array( 'template_path_stack' => array( __DIR__ . '/../view', ), ) );<file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblcustomerstatus * * @ORM\Table(name="tblCustomerStatus", uniqueConstraints={@ORM\UniqueConstraint(name="strCustomerStatus_UNIQUE", columns={"strCustomerStatus"})}) * @ORM\Entity */ class Tblcustomerstatus { /** * @var integer * * @ORM\Column(name="intCustomerStatusID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcustomerstatusid; /** * @var string * * @ORM\Column(name="strCustomerStatus", type="string", length=45, nullable=false) */ private $strcustomerstatus; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intcustomerstatusid * * @return integer */ public function getIntcustomerstatusid() { return $this->intcustomerstatusid; } /** * Set strcustomerstatus * * @param string $strcustomerstatus * @return Tblcustomerstatus */ public function setStrcustomerstatus($strcustomerstatus) { $this->strcustomerstatus = $strcustomerstatus; return $this; } /** * Get strcustomerstatus * * @return string */ public function getStrcustomerstatus() { return $this->strcustomerstatus; } /** * Set intactive * * @param integer $intactive * @return Tblcustomerstatus */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tbladdresstype * * @ORM\Table(name="tblAddressType") * @ORM\Entity */ class Tbladdresstype { /** * @var integer * * @ORM\Column(name="intAddressTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intaddresstypeid; /** * @var string * * @ORM\Column(name="strAddressType", type="string", length=45, nullable=true) */ private $straddresstype; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intaddresstypeid * * @return integer */ public function getIntaddresstypeid() { return $this->intaddresstypeid; } /** * Set straddresstype * * @param string $straddresstype * @return Tbladdresstype */ public function setStraddresstype($straddresstype) { $this->straddresstype = $straddresstype; return $this; } /** * Get straddresstype * * @return string */ public function getStraddresstype() { return $this->straddresstype; } /** * Set intactive * * @param integer $intactive * @return Tbladdresstype */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblcustomers * * @ORM\Table(name="tblCustomers", indexes={@ORM\Index(name="fk_tblCustomers_tblCustomerType1_idx", columns={"intCustomerTypeID"}), @ORM\Index(name="fk_tblCustomers_tblCustomerCategory1_idx", columns={"intCustomerCategoryID"}), @ORM\Index(name="fk_tblCustomers_tblPerson2_idx", columns={"intOwnerID"}), @ORM\Index(name="fk_tblCustomers_tblPerson3_idx", columns={"intContactID"}), @ORM\Index(name="fk_tblCustomers_tblCustomerStatus1_idx", columns={"intCustomerStatusID"}), @ORM\Index(name="fk_tblCustomers_tblUsers1_idx", columns={"intSalesExecutiveID"}), @ORM\Index(name="fk_tblCustomers_tblPerson1_idx", columns={"intPersonID"}), @ORM\Index(name="fk_tblCustomers_tblCompany1", columns={"intCompanyID"})}) * @ORM\Entity */ class Tblcustomers { /** * @var integer * * @ORM\Column(name="intCustomerID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcustomerid; /** * @var integer * * @ORM\Column(name="intUnpaidInvoiceAllowed", type="integer", nullable=true) */ private $intunpaidinvoiceallowed; /** * @var float * * @ORM\Column(name="fltCreditLimit", type="float", precision=10, scale=0, nullable=true) */ private $fltcreditlimit; /** * @var \Main\Entity\Tblcompany * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblcompany") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCompanyID", referencedColumnName="intCompanyID") * }) */ private $intcompanyid; /** * @var \Main\Entity\Tblcustomercategory * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblcustomercategory") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCustomerCategoryID", referencedColumnName="intCustomerCategoryID") * }) */ private $intcustomercategoryid; /** * @var \Main\Entity\Tblcustomerstatus * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblcustomerstatus") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCustomerStatusID", referencedColumnName="intCustomerStatusID") * }) */ private $intcustomerstatusid; /** * @var \Main\Entity\Tblcustomertype * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblcustomertype") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCustomerTypeID", referencedColumnName="intCustomerTypeID") * }) */ private $intcustomertypeid; /** * @var \Main\Entity\Tblperson * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblperson") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intPersonID", referencedColumnName="intPersonID") * }) */ private $intpersonid; /** * @var \Main\Entity\Tblperson * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblperson") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intOwnerID", referencedColumnName="intPersonID") * }) */ private $intownerid; /** * @var \Main\Entity\Tblperson * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblperson") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intContactID", referencedColumnName="intPersonID") * }) */ private $intcontactid; /** * @var \Main\Entity\Tblusers * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblusers") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intSalesExecutiveID", referencedColumnName="intUserID") * }) */ private $intsalesexecutiveid; /** * Get intcustomerid * * @return integer */ public function getIntcustomerid() { return $this->intcustomerid; } /** * Set intunpaidinvoiceallowed * * @param integer $intunpaidinvoiceallowed * @return Tblcustomers */ public function setIntunpaidinvoiceallowed($intunpaidinvoiceallowed) { $this->intunpaidinvoiceallowed = $intunpaidinvoiceallowed; return $this; } /** * Get intunpaidinvoiceallowed * * @return integer */ public function getIntunpaidinvoiceallowed() { return $this->intunpaidinvoiceallowed; } /** * Set fltcreditlimit * * @param float $fltcreditlimit * @return Tblcustomers */ public function setFltcreditlimit($fltcreditlimit) { $this->fltcreditlimit = $fltcreditlimit; return $this; } /** * Get fltcreditlimit * * @return float */ public function getFltcreditlimit() { return $this->fltcreditlimit; } /** * Set intcompanyid * * @param \Main\Entity\Tblcompany $intcompanyid * @return Tblcustomers */ public function setIntcompanyid(\Main\Entity\Tblcompany $intcompanyid = null) { $this->intcompanyid = $intcompanyid; return $this; } /** * Get intcompanyid * * @return \Main\Entity\Tblcompany */ public function getIntcompanyid() { return $this->intcompanyid; } /** * Set intcustomercategoryid * * @param \Main\Entity\Tblcustomercategory $intcustomercategoryid * @return Tblcustomers */ public function setIntcustomercategoryid(\Main\Entity\Tblcustomercategory $intcustomercategoryid = null) { $this->intcustomercategoryid = $intcustomercategoryid; return $this; } /** * Get intcustomercategoryid * * @return \Main\Entity\Tblcustomercategory */ public function getIntcustomercategoryid() { return $this->intcustomercategoryid; } /** * Set intcustomerstatusid * * @param \Main\Entity\Tblcustomerstatus $intcustomerstatusid * @return Tblcustomers */ public function setIntcustomerstatusid(\Main\Entity\Tblcustomerstatus $intcustomerstatusid = null) { $this->intcustomerstatusid = $intcustomerstatusid; return $this; } /** * Get intcustomerstatusid * * @return \Main\Entity\Tblcustomerstatus */ public function getIntcustomerstatusid() { return $this->intcustomerstatusid; } /** * Set intcustomertypeid * * @param \Main\Entity\Tblcustomertype $intcustomertypeid * @return Tblcustomers */ public function setIntcustomertypeid(\Main\Entity\Tblcustomertype $intcustomertypeid = null) { $this->intcustomertypeid = $intcustomertypeid; return $this; } /** * Get intcustomertypeid * * @return \Main\Entity\Tblcustomertype */ public function getIntcustomertypeid() { return $this->intcustomertypeid; } /** * Set intpersonid * * @param \Main\Entity\Tblperson $intpersonid * @return Tblcustomers */ public function setIntpersonid(\Main\Entity\Tblperson $intpersonid = null) { $this->intpersonid = $intpersonid; return $this; } /** * Get intpersonid * * @return \Main\Entity\Tblperson */ public function getIntpersonid() { return $this->intpersonid; } /** * Set intownerid * * @param \Main\Entity\Tblperson $intownerid * @return Tblcustomers */ public function setIntownerid(\Main\Entity\Tblperson $intownerid = null) { $this->intownerid = $intownerid; return $this; } /** * Get intownerid * * @return \Main\Entity\Tblperson */ public function getIntownerid() { return $this->intownerid; } /** * Set intcontactid * * @param \Main\Entity\Tblperson $intcontactid * @return Tblcustomers */ public function setIntcontactid(\Main\Entity\Tblperson $intcontactid = null) { $this->intcontactid = $intcontactid; return $this; } /** * Get intcontactid * * @return \Main\Entity\Tblperson */ public function getIntcontactid() { return $this->intcontactid; } /** * Set intsalesexecutiveid * * @param \Main\Entity\Tblusers $intsalesexecutiveid * @return Tblcustomers */ public function setIntsalesexecutiveid(\Main\Entity\Tblusers $intsalesexecutiveid = null) { $this->intsalesexecutiveid = $intsalesexecutiveid; return $this; } /** * Get intsalesexecutiveid * * @return \Main\Entity\Tblusers */ public function getIntsalesexecutiveid() { return $this->intsalesexecutiveid; } } <file_sep> var ajaxCreateRealms = function(data,cb){ callAjaxRequest("POST","/api/realms/add",data,cb); }; var ajaxEditRealms = function(data,id,cb){ callAjaxRequest("POST","/api/realms/edit/"+id,data,cb); }; var ajaxGetRealmTypeOptions = function(cb){ callAjaxRequest(null,"/api/realms/type/list",null,cb); }; var ajaxGetRealmOptions = function(cb){ callAjaxRequest("POST","/api/realms/list",null,cb); }; <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblsuppliers * * @ORM\Table(name="tblSuppliers", uniqueConstraints={@ORM\UniqueConstraint(name="intCompanyID_UNIQUE", columns={"intCompanyID"})}, indexes={@ORM\Index(name="fk_tblSuppliers_tblSupplierStatus1_idx", columns={"intSupplierStatusID"}), @ORM\Index(name="fk_tblSuppliers_tblPerson1_idx", columns={"intPersonID"})}) * @ORM\Entity */ class Tblsuppliers { /** * @var integer * * @ORM\Column(name="intSupplierID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intsupplierid; /** * @var \Security\Entity\Tblcompany * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblcompany") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCompanyID", referencedColumnName="intCompanyID") * }) */ private $intcompanyid; /** * @var \Security\Entity\Tblperson * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblperson") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intPersonID", referencedColumnName="intPersonID") * }) */ private $intpersonid; /** * @var \Security\Entity\Tblsupplierstatus * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblsupplierstatus") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intSupplierStatusID", referencedColumnName="intSupplierStatusID") * }) */ private $intsupplierstatusid; /** * Get intsupplierid * * @return integer */ public function getIntsupplierid() { return $this->intsupplierid; } /** * Set intcompanyid * * @param \Security\Entity\Tblcompany $intcompanyid * @return Tblsuppliers */ public function setIntcompanyid(\Security\Entity\Tblcompany $intcompanyid = null) { $this->intcompanyid = $intcompanyid; return $this; } /** * Get intcompanyid * * @return \Security\Entity\Tblcompany */ public function getIntcompanyid() { return $this->intcompanyid; } /** * Set intpersonid * * @param \Security\Entity\Tblperson $intpersonid * @return Tblsuppliers */ public function setIntpersonid(\Security\Entity\Tblperson $intpersonid = null) { $this->intpersonid = $intpersonid; return $this; } /** * Get intpersonid * * @return \Security\Entity\Tblperson */ public function getIntpersonid() { return $this->intpersonid; } /** * Set intsupplierstatusid * * @param \Security\Entity\Tblsupplierstatus $intsupplierstatusid * @return Tblsuppliers */ public function setIntsupplierstatusid(\Security\Entity\Tblsupplierstatus $intsupplierstatusid = null) { $this->intsupplierstatusid = $intsupplierstatusid; return $this; } /** * Get intsupplierstatusid * * @return \Security\Entity\Tblsupplierstatus */ public function getIntsupplierstatusid() { return $this->intsupplierstatusid; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblattributetypes * * @ORM\Table(name="tblAttributeTypes") * @ORM\Entity */ class Tblattributetypes { /** * @var integer * * @ORM\Column(name="intAttributeTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intattributetypeid; /** * @var string * * @ORM\Column(name="intAttributeType", type="string", length=45, nullable=false) */ private $intattributetype; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * Get intattributetypeid * * @return integer */ public function getIntattributetypeid() { return $this->intattributetypeid; } /** * Set intattributetype * * @param string $intattributetype * @return Tblattributetypes */ public function setIntattributetype($intattributetype) { $this->intattributetype = $intattributetype; return $this; } /** * Get intattributetype * * @return string */ public function getIntattributetype() { return $this->intattributetype; } /** * Set intstatus * * @param integer $intstatus * @return Tblattributetypes */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblproductprice * * @ORM\Table(name="tblProductPrice", indexes={@ORM\Index(name="fk_tblProductPrice_tblPriceType1_idx", columns={"intPriceTypeID"}), @ORM\Index(name="fk_tblProductPrice_tblCurrency1_idx", columns={"intCurrencyID"}), @ORM\Index(name="fk_tblProductPrice_tblProducts1_idx", columns={"intProductID"})}) * @ORM\Entity */ class Tblproductprice { /** * @var integer * * @ORM\Column(name="intProductPriceID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intproductpriceid; /** * @var float * * @ORM\Column(name="floatPrice", type="float", precision=10, scale=0, nullable=false) */ private $floatprice; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * @var \Security\Entity\Tblcurrency * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblcurrency") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCurrencyID", referencedColumnName="intCurrencyID") * }) */ private $intcurrencyid; /** * @var \Security\Entity\Tblpricetype * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblpricetype") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intPriceTypeID", referencedColumnName="intPriceTypeID") * }) */ private $intpricetypeid; /** * @var \Security\Entity\Tblproducts * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblproducts") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intProductID", referencedColumnName="intProductID") * }) */ private $intproductid; /** * Get intproductpriceid * * @return integer */ public function getIntproductpriceid() { return $this->intproductpriceid; } /** * Set floatprice * * @param float $floatprice * @return Tblproductprice */ public function setFloatprice($floatprice) { $this->floatprice = $floatprice; return $this; } /** * Get floatprice * * @return float */ public function getFloatprice() { return $this->floatprice; } /** * Set intactive * * @param integer $intactive * @return Tblproductprice */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } /** * Set intcurrencyid * * @param \Security\Entity\Tblcurrency $intcurrencyid * @return Tblproductprice */ public function setIntcurrencyid(\Security\Entity\Tblcurrency $intcurrencyid = null) { $this->intcurrencyid = $intcurrencyid; return $this; } /** * Get intcurrencyid * * @return \Security\Entity\Tblcurrency */ public function getIntcurrencyid() { return $this->intcurrencyid; } /** * Set intpricetypeid * * @param \Security\Entity\Tblpricetype $intpricetypeid * @return Tblproductprice */ public function setIntpricetypeid(\Security\Entity\Tblpricetype $intpricetypeid = null) { $this->intpricetypeid = $intpricetypeid; return $this; } /** * Get intpricetypeid * * @return \Security\Entity\Tblpricetype */ public function getIntpricetypeid() { return $this->intpricetypeid; } /** * Set intproductid * * @param \Security\Entity\Tblproducts $intproductid * @return Tblproductprice */ public function setIntproductid(\Security\Entity\Tblproducts $intproductid = null) { $this->intproductid = $intproductid; return $this; } /** * Get intproductid * * @return \Security\Entity\Tblproducts */ public function getIntproductid() { return $this->intproductid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblattributes * * @ORM\Table(name="tblAttributes", indexes={@ORM\Index(name="fk_tblAttributes_tblObjects1_idx", columns={"intObjectID"}), @ORM\Index(name="fk_tblAttributes_tblAttributeTypes1_idx", columns={"intAttributeTypeID"})}) * @ORM\Entity */ class Tblattributes { /** * @var integer * * @ORM\Column(name="intAttributeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $intattributeid; /** * @var string * * @ORM\Column(name="strAttributeName", type="string", length=45, nullable=true) */ private $strattributename; /** * @var string * * @ORM\Column(name="strAttributeLabel", type="string", length=45, nullable=true) */ private $strattributelabel; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * @var \Security\Entity\Tblattributetypes * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Security\Entity\Tblattributetypes") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intAttributeTypeID", referencedColumnName="intAttributeTypeID") * }) */ private $intattributetypeid; /** * @var \Security\Entity\Tblobjects * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Security\Entity\Tblobjects") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intObjectID", referencedColumnName="intObjectID") * }) */ private $intobjectid; /** * Set intattributeid * * @param integer $intattributeid * @return Tblattributes */ public function setIntattributeid($intattributeid) { $this->intattributeid = $intattributeid; return $this; } /** * Get intattributeid * * @return integer */ public function getIntattributeid() { return $this->intattributeid; } /** * Set strattributename * * @param string $strattributename * @return Tblattributes */ public function setStrattributename($strattributename) { $this->strattributename = $strattributename; return $this; } /** * Get strattributename * * @return string */ public function getStrattributename() { return $this->strattributename; } /** * Set strattributelabel * * @param string $strattributelabel * @return Tblattributes */ public function setStrattributelabel($strattributelabel) { $this->strattributelabel = $strattributelabel; return $this; } /** * Get strattributelabel * * @return string */ public function getStrattributelabel() { return $this->strattributelabel; } /** * Set intstatus * * @param integer $intstatus * @return Tblattributes */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } /** * Set intattributetypeid * * @param \Security\Entity\Tblattributetypes $intattributetypeid * @return Tblattributes */ public function setIntattributetypeid(\Security\Entity\Tblattributetypes $intattributetypeid) { $this->intattributetypeid = $intattributetypeid; return $this; } /** * Get intattributetypeid * * @return \Security\Entity\Tblattributetypes */ public function getIntattributetypeid() { return $this->intattributetypeid; } /** * Set intobjectid * * @param \Security\Entity\Tblobjects $intobjectid * @return Tblattributes */ public function setIntobjectid(\Security\Entity\Tblobjects $intobjectid) { $this->intobjectid = $intobjectid; return $this; } /** * Get intobjectid * * @return \Security\Entity\Tblobjects */ public function getIntobjectid() { return $this->intobjectid; } } <file_sep><?php namespace Users\Controller; use Zend\Mvc\Controller\AbstractRestfulController, Zend\View\Model\JsonModel; class ApiController extends AbstractRestfulController { protected $em = null; protected $as = null; public function setEntityManager(\Doctrine\ORM\EntityManager $em) { $this->em = $em; } public function getEntityManager() { if (null === $this->em) { $this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); } return $this->em; } public function loginAction() { $data = $this->getRequest()->getPost(); if($data['username'] && $data['password']){ $authService = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService'); $adapter = $authService->getAdapter(); $adapter->setIdentityValue($data['username']); $adapter->setCredentialValue($data['password']); $authResult = $authService->authenticate(); if($authResult->isValid()){ return new JsonModel(array( "result" => "success" )); } else{ $this->response->setStatusCode(401); return new JsonModel(array( "code" => $authResult->getCode(), "message" => $authResult->getMessages() )); } } else{ $this->response->setStatusCode(401); return new JsonModel(array( "code" => -100, "message" => "Parameters not set" )); } } public function logoutAction(){ $auth = $this->getServiceLocator()->get('doctrine.authenticationservice.orm_default'); $auth->clearIdentity(); return new JsonModel(array( "result" => "success" )); } } <file_sep><?php /** * Global Configuration Override * * You can use this file for overriding configuration values from modules, etc. * You would place values in here that are agnostic to the environment and not * sensitive to security. * * @NOTE: In practice, this file will typically be INCLUDED in your source * control, so do not include passwords or other sensitive information in this * file. */ return array( 'doctrine' => array( 'driver' => array( 'Security_driver' => array( 'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver', 'cache' => 'array', 'paths' => array( __DIR__ . '/../../module/Main/src/Main/Entity', ) ), 'orm_default' => array( 'drivers' => array( 'Main\Entity' => 'Security_driver' ) ) ), 'configuration' => array( 'orm_default' => array( 'metadata_cache' => 'array', 'query_cache' => 'array', 'result_cache' => 'array', 'hydration_cache' => 'array', 'generate_proxies' => true, 'proxy_dir' => 'data/DoctrineORMModule/Proxy', 'proxy_namespace' => 'DoctrineORMModule\Proxy', ), ), ), 'service_manager' => array( 'abstract_factories' => array( 'Zend\Cache\Service\StorageCacheAbstractServiceFactory', 'Zend\Log\LoggerAbstractServiceFactory', ), 'aliases' => array( 'translator' => 'MvcTranslator', ), ), 'translator' => array( 'locale' => 'en_US', 'translation_file_patterns' => array( array( 'type' => 'gettext', 'base_dir' => __DIR__ . '/../language', 'pattern' => '%s.mo', ), ), ), 'view_manager' => array( 'display_not_found_reason' => true, 'display_exceptions' => true, 'doctype' => 'HTML5', 'not_found_template' => 'error/404', 'exception_template' => 'error/index', 'template_map' => array( 'layout/layout' => __DIR__ . '/../../module/Main/view/layout/layout.phtml', 'error/404' => __DIR__ . '/../../module/Main/view/error/404.phtml', 'error/index' => __DIR__ . '/../../module/Main/view/error/index.phtml', ), 'strategies' => array( 'ViewJsonStrategy', ), ) ); <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblactionfieldoptionfilters * * @ORM\Table(name="tblActionFieldOptionFilters", indexes={@ORM\Index(name="fk_tblActionFieldOptionFilters_tblActionFieldOptions1_idx", columns={"intActionFieldOptionID"})}) * @ORM\Entity */ class Tblactionfieldoptionfilters { /** * @var integer * * @ORM\Column(name="intActionFieldOptionFilterID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $intactionfieldoptionfilterid; /** * @var integer * * @ORM\Column(name="intAttributeID", type="integer", nullable=true) */ private $intattributeid; /** * @var string * * @ORM\Column(name="strFilterValue", type="string", length=100, nullable=true) */ private $strfiltervalue; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * @var \Security\Entity\Tblactionfieldoptions * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Security\Entity\Tblactionfieldoptions") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intActionFieldOptionID", referencedColumnName="intActionFieldOptionID") * }) */ private $intactionfieldoptionid; /** * Set intactionfieldoptionfilterid * * @param integer $intactionfieldoptionfilterid * @return Tblactionfieldoptionfilters */ public function setIntactionfieldoptionfilterid($intactionfieldoptionfilterid) { $this->intactionfieldoptionfilterid = $intactionfieldoptionfilterid; return $this; } /** * Get intactionfieldoptionfilterid * * @return integer */ public function getIntactionfieldoptionfilterid() { return $this->intactionfieldoptionfilterid; } /** * Set intattributeid * * @param integer $intattributeid * @return Tblactionfieldoptionfilters */ public function setIntattributeid($intattributeid) { $this->intattributeid = $intattributeid; return $this; } /** * Get intattributeid * * @return integer */ public function getIntattributeid() { return $this->intattributeid; } /** * Set strfiltervalue * * @param string $strfiltervalue * @return Tblactionfieldoptionfilters */ public function setStrfiltervalue($strfiltervalue) { $this->strfiltervalue = $strfiltervalue; return $this; } /** * Get strfiltervalue * * @return string */ public function getStrfiltervalue() { return $this->strfiltervalue; } /** * Set intstatus * * @param integer $intstatus * @return Tblactionfieldoptionfilters */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } /** * Set intactionfieldoptionid * * @param \Security\Entity\Tblactionfieldoptions $intactionfieldoptionid * @return Tblactionfieldoptionfilters */ public function setIntactionfieldoptionid(\Security\Entity\Tblactionfieldoptions $intactionfieldoptionid) { $this->intactionfieldoptionid = $intactionfieldoptionid; return $this; } /** * Get intactionfieldoptionid * * @return \Security\Entity\Tblactionfieldoptions */ public function getIntactionfieldoptionid() { return $this->intactionfieldoptionid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblcompanytype * * @ORM\Table(name="tblCompanyType", uniqueConstraints={@ORM\UniqueConstraint(name="strCompanyType_UNIQUE", columns={"strCompanyType"})}) * @ORM\Entity */ class Tblcompanytype { /** * @var integer * * @ORM\Column(name="intCompanyTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcompanytypeid; /** * @var string * * @ORM\Column(name="strCompanyType", type="string", length=45, nullable=false) */ private $strcompanytype; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intcompanytypeid * * @return integer */ public function getIntcompanytypeid() { return $this->intcompanytypeid; } /** * Set strcompanytype * * @param string $strcompanytype * @return Tblcompanytype */ public function setStrcompanytype($strcompanytype) { $this->strcompanytype = $strcompanytype; return $this; } /** * Get strcompanytype * * @return string */ public function getStrcompanytype() { return $this->strcompanytype; } /** * Set intactive * * @param integer $intactive * @return Tblcompanytype */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblproductcondition * * @ORM\Table(name="tblProductCondition", uniqueConstraints={@ORM\UniqueConstraint(name="strConditionName_UNIQUE", columns={"strConditionName"})}) * @ORM\Entity */ class Tblproductcondition { /** * @var integer * * @ORM\Column(name="intConditionID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intconditionid; /** * @var string * * @ORM\Column(name="strConditionName", type="string", length=45, nullable=false) */ private $strconditionname; /** * @var string * * @ORM\Column(name="intActive", type="string", length=45, nullable=true) */ private $intactive = '1'; /** * Get intconditionid * * @return integer */ public function getIntconditionid() { return $this->intconditionid; } /** * Set strconditionname * * @param string $strconditionname * @return Tblproductcondition */ public function setStrconditionname($strconditionname) { $this->strconditionname = $strconditionname; return $this; } /** * Get strconditionname * * @return string */ public function getStrconditionname() { return $this->strconditionname; } /** * Set intactive * * @param string $intactive * @return Tblproductcondition */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return string */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblpricetype * * @ORM\Table(name="tblPriceType", uniqueConstraints={@ORM\UniqueConstraint(name="strPriceType_UNIQUE", columns={"strPriceType"})}) * @ORM\Entity */ class Tblpricetype { /** * @var integer * * @ORM\Column(name="intPriceTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intpricetypeid; /** * @var string * * @ORM\Column(name="strPriceType", type="string", length=45, nullable=false) */ private $strpricetype; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intpricetypeid * * @return integer */ public function getIntpricetypeid() { return $this->intpricetypeid; } /** * Set strpricetype * * @param string $strpricetype * @return Tblpricetype */ public function setStrpricetype($strpricetype) { $this->strpricetype = $strpricetype; return $this; } /** * Get strpricetype * * @return string */ public function getStrpricetype() { return $this->strpricetype; } /** * Set intactive * * @param integer $intactive * @return Tblpricetype */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblcity * * @ORM\Table(name="tblCity", indexes={@ORM\Index(name="fk_tblCity_tblProvince1_idx", columns={"intProvinceID"})}) * @ORM\Entity */ class Tblcity { /** * @var integer * * @ORM\Column(name="intCityID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcityid; /** * @var string * * @ORM\Column(name="strCityName", type="string", length=45, nullable=false) */ private $strcityname; /** * @var \Main\Entity\Tblprovince * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblprovince") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intProvinceID", referencedColumnName="intProvinceID") * }) */ private $intprovinceid; /** * Get intcityid * * @return integer */ public function getIntcityid() { return $this->intcityid; } /** * Set strcityname * * @param string $strcityname * @return Tblcity */ public function setStrcityname($strcityname) { $this->strcityname = $strcityname; return $this; } /** * Get strcityname * * @return string */ public function getStrcityname() { return $this->strcityname; } /** * Set intprovinceid * * @param \Main\Entity\Tblprovince $intprovinceid * @return Tblcity */ public function setIntprovinceid(\Main\Entity\Tblprovince $intprovinceid = null) { $this->intprovinceid = $intprovinceid; return $this; } /** * Get intprovinceid * * @return \Main\Entity\Tblprovince */ public function getIntprovinceid() { return $this->intprovinceid; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblproductclassification * * @ORM\Table(name="tblProductClassification", uniqueConstraints={@ORM\UniqueConstraint(name="strProductClassification_UNIQUE", columns={"strProductClassification"})}) * @ORM\Entity */ class Tblproductclassification { /** * @var integer * * @ORM\Column(name="intProductClassificationID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intproductclassificationid; /** * @var string * * @ORM\Column(name="strProductClassification", type="string", length=45, nullable=false) */ private $strproductclassification; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intproductclassificationid * * @return integer */ public function getIntproductclassificationid() { return $this->intproductclassificationid; } /** * Set strproductclassification * * @param string $strproductclassification * @return Tblproductclassification */ public function setStrproductclassification($strproductclassification) { $this->strproductclassification = $strproductclassification; return $this; } /** * Get strproductclassification * * @return string */ public function getStrproductclassification() { return $this->strproductclassification; } /** * Set intactive * * @param integer $intactive * @return Tblproductclassification */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Main; use Zend\Mvc\ModuleRouteListener; use Zend\Mvc\MvcEvent; class Module { public function onBootstrap(MvcEvent $e) { $eventManager = $e->getApplication()->getEventManager(); $eventManager->attach( 'route', function($e) { $app = $e->getApplication(); $routeMatch = $e->getRouteMatch(); $auth = $app->getServiceManager()->get('doctrine.authenticationservice.orm_default'); $user = $auth->getIdentity(); $whiteList = array("users_security_login","users_api_login"); if (!$user && !in_array($routeMatch->getMatchedRouteName(),$whiteList)) { $response = $e->getResponse(); if(!$response->getContent()){ $response->getHeaders()->addHeaderLine( 'Location', $e->getRouter()->assemble( array(), array('name' => 'users_security_login') ) ); $response->setStatusCode(302); return $response; } } }, -100 ); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__, ), ), ); } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblproducts * * @ORM\Table(name="tblProducts", uniqueConstraints={@ORM\UniqueConstraint(name="strProductCode_UNIQUE", columns={"strProductCode"})}, indexes={@ORM\Index(name="fk_tblProducts_tblProductClassification1_idx", columns={"intProductClassificationID"}), @ORM\Index(name="fk_tblProducts_tblBrands1_idx", columns={"intBrandID"}), @ORM\Index(name="fk_tblProducts_tblSuppliers1_idx", columns={"intSupplierID"}), @ORM\Index(name="fk_tblProducts_tblUOM1_idx", columns={"intUOMID"}), @ORM\Index(name="fk_tblProducts_tblProductStatus1_idx", columns={"intProductStatusID"})}) * @ORM\Entity */ class Tblproducts { /** * @var integer * * @ORM\Column(name="intProductID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intproductid; /** * @var string * * @ORM\Column(name="strProductCode", type="string", length=100, nullable=false) */ private $strproductcode; /** * @var string * * @ORM\Column(name="strProductName", type="string", length=250, nullable=true) */ private $strproductname; /** * @var string * * @ORM\Column(name="strDescription", type="string", length=250, nullable=true) */ private $strdescription; /** * @var string * * @ORM\Column(name="strColor", type="string", length=45, nullable=true) */ private $strcolor; /** * @var string * * @ORM\Column(name="strSize", type="string", length=45, nullable=true) */ private $strsize; /** * @var string * * @ORM\Column(name="strWeight", type="string", length=45, nullable=true) */ private $strweight; /** * @var \Main\Entity\Tblbrands * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblbrands") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intBrandID", referencedColumnName="intBrandID") * }) */ private $intbrandid; /** * @var \Main\Entity\Tblproductclassification * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblproductclassification") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intProductClassificationID", referencedColumnName="intProductClassificationID") * }) */ private $intproductclassificationid; /** * @var \Main\Entity\Tblproductstatus * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblproductstatus") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intProductStatusID", referencedColumnName="intProductStatusID") * }) */ private $intproductstatusid; /** * @var \Main\Entity\Tblsuppliers * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblsuppliers") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intSupplierID", referencedColumnName="intSupplierID") * }) */ private $intsupplierid; /** * @var \Main\Entity\Tbluom * * @ORM\ManyToOne(targetEntity="Main\Entity\Tbluom") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intUOMID", referencedColumnName="intUOMID") * }) */ private $intuomid; /** * Get intproductid * * @return integer */ public function getIntproductid() { return $this->intproductid; } /** * Set strproductcode * * @param string $strproductcode * @return Tblproducts */ public function setStrproductcode($strproductcode) { $this->strproductcode = $strproductcode; return $this; } /** * Get strproductcode * * @return string */ public function getStrproductcode() { return $this->strproductcode; } /** * Set strproductname * * @param string $strproductname * @return Tblproducts */ public function setStrproductname($strproductname) { $this->strproductname = $strproductname; return $this; } /** * Get strproductname * * @return string */ public function getStrproductname() { return $this->strproductname; } /** * Set strdescription * * @param string $strdescription * @return Tblproducts */ public function setStrdescription($strdescription) { $this->strdescription = $strdescription; return $this; } /** * Get strdescription * * @return string */ public function getStrdescription() { return $this->strdescription; } /** * Set strcolor * * @param string $strcolor * @return Tblproducts */ public function setStrcolor($strcolor) { $this->strcolor = $strcolor; return $this; } /** * Get strcolor * * @return string */ public function getStrcolor() { return $this->strcolor; } /** * Set strsize * * @param string $strsize * @return Tblproducts */ public function setStrsize($strsize) { $this->strsize = $strsize; return $this; } /** * Get strsize * * @return string */ public function getStrsize() { return $this->strsize; } /** * Set strweight * * @param string $strweight * @return Tblproducts */ public function setStrweight($strweight) { $this->strweight = $strweight; return $this; } /** * Get strweight * * @return string */ public function getStrweight() { return $this->strweight; } /** * Set intbrandid * * @param \Main\Entity\Tblbrands $intbrandid * @return Tblproducts */ public function setIntbrandid(\Main\Entity\Tblbrands $intbrandid = null) { $this->intbrandid = $intbrandid; return $this; } /** * Get intbrandid * * @return \Main\Entity\Tblbrands */ public function getIntbrandid() { return $this->intbrandid; } /** * Set intproductclassificationid * * @param \Main\Entity\Tblproductclassification $intproductclassificationid * @return Tblproducts */ public function setIntproductclassificationid(\Main\Entity\Tblproductclassification $intproductclassificationid = null) { $this->intproductclassificationid = $intproductclassificationid; return $this; } /** * Get intproductclassificationid * * @return \Main\Entity\Tblproductclassification */ public function getIntproductclassificationid() { return $this->intproductclassificationid; } /** * Set intproductstatusid * * @param \Main\Entity\Tblproductstatus $intproductstatusid * @return Tblproducts */ public function setIntproductstatusid(\Main\Entity\Tblproductstatus $intproductstatusid = null) { $this->intproductstatusid = $intproductstatusid; return $this; } /** * Get intproductstatusid * * @return \Main\Entity\Tblproductstatus */ public function getIntproductstatusid() { return $this->intproductstatusid; } /** * Set intsupplierid * * @param \Main\Entity\Tblsuppliers $intsupplierid * @return Tblproducts */ public function setIntsupplierid(\Main\Entity\Tblsuppliers $intsupplierid = null) { $this->intsupplierid = $intsupplierid; return $this; } /** * Get intsupplierid * * @return \Main\Entity\Tblsuppliers */ public function getIntsupplierid() { return $this->intsupplierid; } /** * Set intuomid * * @param \Main\Entity\Tbluom $intuomid * @return Tblproducts */ public function setIntuomid(\Main\Entity\Tbluom $intuomid = null) { $this->intuomid = $intuomid; return $this; } /** * Get intuomid * * @return \Main\Entity\Tbluom */ public function getIntuomid() { return $this->intuomid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblcustomerterms * * @ORM\Table(name="tblCustomerTerms", indexes={@ORM\Index(name="fk_tblCustomerTerms_tblPaymentTerms1_idx", columns={"intPaymentTermID"}), @ORM\Index(name="fk_tblCustomerTerms_tblCustomers1_idx", columns={"intCustomerID"})}) * @ORM\Entity */ class Tblcustomerterms { /** * @var integer * * @ORM\Column(name="intCustomerTermID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcustomertermid; /** * @var \Security\Entity\Tblcustomers * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblcustomers") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCustomerID", referencedColumnName="intCustomerID") * }) */ private $intcustomerid; /** * @var \Security\Entity\Tblpaymentterms * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblpaymentterms") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intPaymentTermID", referencedColumnName="intPaymentTermID") * }) */ private $intpaymenttermid; /** * Get intcustomertermid * * @return integer */ public function getIntcustomertermid() { return $this->intcustomertermid; } /** * Set intcustomerid * * @param \Security\Entity\Tblcustomers $intcustomerid * @return Tblcustomerterms */ public function setIntcustomerid(\Security\Entity\Tblcustomers $intcustomerid = null) { $this->intcustomerid = $intcustomerid; return $this; } /** * Get intcustomerid * * @return \Security\Entity\Tblcustomers */ public function getIntcustomerid() { return $this->intcustomerid; } /** * Set intpaymenttermid * * @param \Security\Entity\Tblpaymentterms $intpaymenttermid * @return Tblcustomerterms */ public function setIntpaymenttermid(\Security\Entity\Tblpaymentterms $intpaymenttermid = null) { $this->intpaymenttermid = $intpaymenttermid; return $this; } /** * Get intpaymenttermid * * @return \Security\Entity\Tblpaymentterms */ public function getIntpaymenttermid() { return $this->intpaymenttermid; } } <file_sep><?php return array( 'doctrine' => array( 'driver' => array( 'Security_driver' => array( 'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver', 'cache' => 'array', 'paths' => array( __DIR__ . '/../src/Security/Entity', ) ), 'orm_default' => array( 'drivers' => array( 'Security\Entity' => 'Security_driver' ) ) ), 'configuration' => array( 'orm_default' => array( 'metadata_cache' => 'array', 'query_cache' => 'array', 'result_cache' => 'array', 'hydration_cache' => 'array', 'generate_proxies' => true, 'proxy_dir' => 'data/DoctrineORMModule/Proxy', 'proxy_namespace' => 'DoctrineORMModule\Proxy', ), ), 'authentication' => array( 'orm_default' => array( 'object_manager' => 'Doctrine\ORM\EntityManager', 'identity_class' => 'Security\Entity\Tbluser', 'identity_property' => 'strusername', 'credential_property' => 'strpassword', ), ), ), 'router' => array( 'routes' => array( 'home' => array( 'type' => 'Zend\Mvc\Router\Http\Literal', 'options' => array( 'route' => '/', 'defaults' => array( '__NAMESPACE__' => 'Security\Controller', 'controller' => 'Auth', 'action' => 'login', ), ), ) ), ), 'service_manager' => array( 'abstract_factories' => array( 'Zend\Cache\Service\StorageCacheAbstractServiceFactory', 'Zend\Log\LoggerAbstractServiceFactory', ), 'aliases' => array( 'translator' => 'MvcTranslator', ), ), 'translator' => array( 'locale' => 'en_US', 'translation_file_patterns' => array( array( 'type' => 'gettext', 'base_dir' => __DIR__ . '/../language', 'pattern' => '%s.mo', ), ), ), 'controllers' => array( 'invokables' => array( 'Security\Controller\Auth' => 'Security\Controller\AuthController' ), ), 'view_manager' => array( 'display_not_found_reason' => true, 'display_exceptions' => true, 'doctype' => 'HTML5', 'not_found_template' => 'error/404', 'exception_template' => 'error/index', 'template_map' => array( 'layout/layout' => __DIR__ . '/../view/layout/layout.phtml', 'security/index/index' => __DIR__ . '/../view/security/index/index.phtml', 'error/404' => __DIR__ . '/../view/error/404.phtml', 'error/index' => __DIR__ . '/../view/error/index.phtml', ), 'template_path_stack' => array( __DIR__ . '/../view', ), ) ); <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tbldisplaytypes * * @ORM\Table(name="tblDisplayTypes") * @ORM\Entity */ class Tbldisplaytypes { /** * @var integer * * @ORM\Column(name="intDisplayTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intdisplaytypeid; /** * @var string * * @ORM\Column(name="strDisplayType", type="string", length=45, nullable=true) */ private $strdisplaytype; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * Get intdisplaytypeid * * @return integer */ public function getIntdisplaytypeid() { return $this->intdisplaytypeid; } /** * Set strdisplaytype * * @param string $strdisplaytype * @return Tbldisplaytypes */ public function setStrdisplaytype($strdisplaytype) { $this->strdisplaytype = $strdisplaytype; return $this; } /** * Get strdisplaytype * * @return string */ public function getStrdisplaytype() { return $this->strdisplaytype; } /** * Set intstatus * * @param integer $intstatus * @return Tbldisplaytypes */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblcustomercategory * * @ORM\Table(name="tblCustomerCategory", uniqueConstraints={@ORM\UniqueConstraint(name="strCustomerCategory_UNIQUE", columns={"strCustomerCategory"})}) * @ORM\Entity */ class Tblcustomercategory { /** * @var integer * * @ORM\Column(name="intCustomerCategoryID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcustomercategoryid; /** * @var string * * @ORM\Column(name="strCustomerCategory", type="string", length=45, nullable=false) */ private $strcustomercategory; /** * Get intcustomercategoryid * * @return integer */ public function getIntcustomercategoryid() { return $this->intcustomercategoryid; } /** * Set strcustomercategory * * @param string $strcustomercategory * @return Tblcustomercategory */ public function setStrcustomercategory($strcustomercategory) { $this->strcustomercategory = $strcustomercategory; return $this; } /** * Get strcustomercategory * * @return string */ public function getStrcustomercategory() { return $this->strcustomercategory; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblentityaddress * * @ORM\Table(name="tblEntityAddress", indexes={@ORM\Index(name="fk_tblEntityAddress_tblAddressType1_idx", columns={"intAddressTypeID"}), @ORM\Index(name="fk_tblEntityAddress_tblCity1_idx", columns={"intCityID"}), @ORM\Index(name="fk_tblEntityAddress_tblCompany1_idx", columns={"intCompanyID"}), @ORM\Index(name="fk_tblEntityAddress_tblPerson1_idx", columns={"intPersonID"})}) * @ORM\Entity */ class Tblentityaddress { /** * @var integer * * @ORM\Column(name="intlEntityAddressID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intlentityaddressid; /** * @var string * * @ORM\Column(name="strAddress", type="string", length=45, nullable=false) */ private $straddress; /** * @var string * * @ORM\Column(name="strZipCode", type="string", length=45, nullable=true) */ private $strzipcode; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * @var \Main\Entity\Tbladdresstype * * @ORM\ManyToOne(targetEntity="Main\Entity\Tbladdresstype") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intAddressTypeID", referencedColumnName="intAddressTypeID") * }) */ private $intaddresstypeid; /** * @var \Main\Entity\Tblcity * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblcity") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCityID", referencedColumnName="intCityID") * }) */ private $intcityid; /** * @var \Main\Entity\Tblcompany * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblcompany") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCompanyID", referencedColumnName="intCompanyID") * }) */ private $intcompanyid; /** * @var \Main\Entity\Tblperson * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblperson") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intPersonID", referencedColumnName="intPersonID") * }) */ private $intpersonid; /** * Get intlentityaddressid * * @return integer */ public function getIntlentityaddressid() { return $this->intlentityaddressid; } /** * Set straddress * * @param string $straddress * @return Tblentityaddress */ public function setStraddress($straddress) { $this->straddress = $straddress; return $this; } /** * Get straddress * * @return string */ public function getStraddress() { return $this->straddress; } /** * Set strzipcode * * @param string $strzipcode * @return Tblentityaddress */ public function setStrzipcode($strzipcode) { $this->strzipcode = $strzipcode; return $this; } /** * Get strzipcode * * @return string */ public function getStrzipcode() { return $this->strzipcode; } /** * Set intstatus * * @param integer $intstatus * @return Tblentityaddress */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } /** * Set intaddresstypeid * * @param \Main\Entity\Tbladdresstype $intaddresstypeid * @return Tblentityaddress */ public function setIntaddresstypeid(\Main\Entity\Tbladdresstype $intaddresstypeid = null) { $this->intaddresstypeid = $intaddresstypeid; return $this; } /** * Get intaddresstypeid * * @return \Main\Entity\Tbladdresstype */ public function getIntaddresstypeid() { return $this->intaddresstypeid; } /** * Set intcityid * * @param \Main\Entity\Tblcity $intcityid * @return Tblentityaddress */ public function setIntcityid(\Main\Entity\Tblcity $intcityid = null) { $this->intcityid = $intcityid; return $this; } /** * Get intcityid * * @return \Main\Entity\Tblcity */ public function getIntcityid() { return $this->intcityid; } /** * Set intcompanyid * * @param \Main\Entity\Tblcompany $intcompanyid * @return Tblentityaddress */ public function setIntcompanyid(\Main\Entity\Tblcompany $intcompanyid = null) { $this->intcompanyid = $intcompanyid; return $this; } /** * Get intcompanyid * * @return \Main\Entity\Tblcompany */ public function getIntcompanyid() { return $this->intcompanyid; } /** * Set intpersonid * * @param \Main\Entity\Tblperson $intpersonid * @return Tblentityaddress */ public function setIntpersonid(\Main\Entity\Tblperson $intpersonid = null) { $this->intpersonid = $intpersonid; return $this; } /** * Get intpersonid * * @return \Main\Entity\Tblperson */ public function getIntpersonid() { return $this->intpersonid; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblrolepermissions * * @ORM\Table(name="tblRolePermissions", indexes={@ORM\Index(name="fk_tblRolePermissions_roles1_idx", columns={"intRoleID"}), @ORM\Index(name="fk_tblRolePermissions_tblPermissions1_idx", columns={"intPermissionID"})}) * @ORM\Entity */ class Tblrolepermissions { /** * @var integer * * @ORM\Column(name="intRolePermissionID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $introlepermissionid; /** * @var \Main\Entity\Tblroles * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblroles") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intRoleID", referencedColumnName="intRoleID") * }) */ private $introleid; /** * @var \Main\Entity\Tblpermissions * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblpermissions") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intPermissionID", referencedColumnName="intPermissionID") * }) */ private $intpermissionid; /** * Get introlepermissionid * * @return integer */ public function getIntrolepermissionid() { return $this->introlepermissionid; } /** * Set introleid * * @param \Main\Entity\Tblroles $introleid * @return Tblrolepermissions */ public function setIntroleid(\Main\Entity\Tblroles $introleid = null) { $this->introleid = $introleid; return $this; } /** * Get introleid * * @return \Main\Entity\Tblroles */ public function getIntroleid() { return $this->introleid; } /** * Set intpermissionid * * @param \Main\Entity\Tblpermissions $intpermissionid * @return Tblrolepermissions */ public function setIntpermissionid(\Main\Entity\Tblpermissions $intpermissionid = null) { $this->intpermissionid = $intpermissionid; return $this; } /** * Get intpermissionid * * @return \Main\Entity\Tblpermissions */ public function getIntpermissionid() { return $this->intpermissionid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblinventorylocation * * @ORM\Table(name="tblInventoryLocation", indexes={@ORM\Index(name="fk_tblInventoryLocation_tblLocationTypes1_idx", columns={"intLocationTypeID"}), @ORM\Index(name="fk_tblInventoryLocation_tblCompany1_idx", columns={"intCompanyID"}), @ORM\Index(name="fk_tblInventoryLocation_tblPerson1_idx", columns={"intPersonID"})}) * @ORM\Entity */ class Tblinventorylocation { /** * @var integer * * @ORM\Column(name="intLocationID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intlocationid; /** * @var string * * @ORM\Column(name="strLocationName", type="string", length=100, nullable=true) */ private $strlocationname; /** * @var \Security\Entity\Tblcompany * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblcompany") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCompanyID", referencedColumnName="intCompanyID") * }) */ private $intcompanyid; /** * @var \Security\Entity\Tbllocationtypes * * @ORM\ManyToOne(targetEntity="Security\Entity\Tbllocationtypes") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intLocationTypeID", referencedColumnName="intLocationTypeID") * }) */ private $intlocationtypeid; /** * @var \Security\Entity\Tblperson * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblperson") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intPersonID", referencedColumnName="intPersonID") * }) */ private $intpersonid; /** * Get intlocationid * * @return integer */ public function getIntlocationid() { return $this->intlocationid; } /** * Set strlocationname * * @param string $strlocationname * @return Tblinventorylocation */ public function setStrlocationname($strlocationname) { $this->strlocationname = $strlocationname; return $this; } /** * Get strlocationname * * @return string */ public function getStrlocationname() { return $this->strlocationname; } /** * Set intcompanyid * * @param \Security\Entity\Tblcompany $intcompanyid * @return Tblinventorylocation */ public function setIntcompanyid(\Security\Entity\Tblcompany $intcompanyid = null) { $this->intcompanyid = $intcompanyid; return $this; } /** * Get intcompanyid * * @return \Security\Entity\Tblcompany */ public function getIntcompanyid() { return $this->intcompanyid; } /** * Set intlocationtypeid * * @param \Security\Entity\Tbllocationtypes $intlocationtypeid * @return Tblinventorylocation */ public function setIntlocationtypeid(\Security\Entity\Tbllocationtypes $intlocationtypeid = null) { $this->intlocationtypeid = $intlocationtypeid; return $this; } /** * Get intlocationtypeid * * @return \Security\Entity\Tbllocationtypes */ public function getIntlocationtypeid() { return $this->intlocationtypeid; } /** * Set intpersonid * * @param \Security\Entity\Tblperson $intpersonid * @return Tblinventorylocation */ public function setIntpersonid(\Security\Entity\Tblperson $intpersonid = null) { $this->intpersonid = $intpersonid; return $this; } /** * Get intpersonid * * @return \Security\Entity\Tblperson */ public function getIntpersonid() { return $this->intpersonid; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblsupplierstatus * * @ORM\Table(name="tblSupplierStatus", uniqueConstraints={@ORM\UniqueConstraint(name="strSupplierStatus_UNIQUE", columns={"strSupplierStatus"})}) * @ORM\Entity */ class Tblsupplierstatus { /** * @var integer * * @ORM\Column(name="intSupplierStatusID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intsupplierstatusid; /** * @var string * * @ORM\Column(name="strSupplierStatus", type="string", length=45, nullable=false) */ private $strsupplierstatus; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intsupplierstatusid * * @return integer */ public function getIntsupplierstatusid() { return $this->intsupplierstatusid; } /** * Set strsupplierstatus * * @param string $strsupplierstatus * @return Tblsupplierstatus */ public function setStrsupplierstatus($strsupplierstatus) { $this->strsupplierstatus = $strsupplierstatus; return $this; } /** * Get strsupplierstatus * * @return string */ public function getStrsupplierstatus() { return $this->strsupplierstatus; } /** * Set intactive * * @param integer $intactive * @return Tblsupplierstatus */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep> var ajaxLogin = function(data,cb){ callAjaxRequest("POST","/users/api/login",data,cb); }; <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblcurrency * * @ORM\Table(name="tblCurrency", uniqueConstraints={@ORM\UniqueConstraint(name="strCurrency_UNIQUE", columns={"strCurrency"})}) * @ORM\Entity */ class Tblcurrency { /** * @var integer * * @ORM\Column(name="intCurrencyID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcurrencyid; /** * @var string * * @ORM\Column(name="strCurrency", type="string", length=45, nullable=false) */ private $strcurrency; /** * @var integer * * @ORM\Column(name="inActive", type="integer", nullable=true) */ private $inactive = '1'; /** * Get intcurrencyid * * @return integer */ public function getIntcurrencyid() { return $this->intcurrencyid; } /** * Set strcurrency * * @param string $strcurrency * @return Tblcurrency */ public function setStrcurrency($strcurrency) { $this->strcurrency = $strcurrency; return $this; } /** * Get strcurrency * * @return string */ public function getStrcurrency() { return $this->strcurrency; } /** * Set inactive * * @param integer $inactive * @return Tblcurrency */ public function setInactive($inactive) { $this->inactive = $inactive; return $this; } /** * Get inactive * * @return integer */ public function getInactive() { return $this->inactive; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblroles * * @ORM\Table(name="tblRoles", uniqueConstraints={@ORM\UniqueConstraint(name="role_UNIQUE", columns={"strRole"})}) * @ORM\Entity */ class Tblroles { /** * @var integer * * @ORM\Column(name="intRoleID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $introleid; /** * @var string * * @ORM\Column(name="strRole", type="string", length=45, nullable=false) */ private $strrole; /** * Get introleid * * @return integer */ public function getIntroleid() { return $this->introleid; } /** * Set strrole * * @param string $strrole * @return Tblroles */ public function setStrrole($strrole) { $this->strrole = $strrole; return $this; } /** * Get strrole * * @return string */ public function getStrrole() { return $this->strrole; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblpermissions * * @ORM\Table(name="tblPermissions") * @ORM\Entity */ class Tblpermissions { /** * @var integer * * @ORM\Column(name="intPermissionID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intpermissionid; /** * @var string * * @ORM\Column(name="strModule", type="string", length=45, nullable=true) */ private $strmodule; /** * @var string * * @ORM\Column(name="strController", type="string", length=45, nullable=true) */ private $strcontroller; /** * @var string * * @ORM\Column(name="strAction", type="string", length=45, nullable=true) */ private $straction; /** * Get intpermissionid * * @return integer */ public function getIntpermissionid() { return $this->intpermissionid; } /** * Set strmodule * * @param string $strmodule * @return Tblpermissions */ public function setStrmodule($strmodule) { $this->strmodule = $strmodule; return $this; } /** * Get strmodule * * @return string */ public function getStrmodule() { return $this->strmodule; } /** * Set strcontroller * * @param string $strcontroller * @return Tblpermissions */ public function setStrcontroller($strcontroller) { $this->strcontroller = $strcontroller; return $this; } /** * Get strcontroller * * @return string */ public function getStrcontroller() { return $this->strcontroller; } /** * Set straction * * @param string $straction * @return Tblpermissions */ public function setStraction($straction) { $this->straction = $straction; return $this; } /** * Get straction * * @return string */ public function getStraction() { return $this->straction; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblactions * * @ORM\Table(name="tblActions", indexes={@ORM\Index(name="fk_tblActions_tblProcess1_idx", columns={"intProcessID"}), @ORM\Index(name="fk_tblActions_tblActionTypes1_idx", columns={"intActionTypeID"})}) * @ORM\Entity */ class Tblactions { /** * @var integer * * @ORM\Column(name="intActionID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $intactionid; /** * @var string * * @ORM\Column(name="strActionName", type="string", length=45, nullable=false) */ private $stractionname; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus; /** * @var \Security\Entity\Tblactiontypes * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Security\Entity\Tblactiontypes") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intActionTypeID", referencedColumnName="intActionTypeID") * }) */ private $intactiontypeid; /** * @var \Security\Entity\Tblprocess * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Security\Entity\Tblprocess") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intProcessID", referencedColumnName="intProcessID") * }) */ private $intprocessid; /** * Set intactionid * * @param integer $intactionid * @return Tblactions */ public function setIntactionid($intactionid) { $this->intactionid = $intactionid; return $this; } /** * Get intactionid * * @return integer */ public function getIntactionid() { return $this->intactionid; } /** * Set stractionname * * @param string $stractionname * @return Tblactions */ public function setStractionname($stractionname) { $this->stractionname = $stractionname; return $this; } /** * Get stractionname * * @return string */ public function getStractionname() { return $this->stractionname; } /** * Set intstatus * * @param integer $intstatus * @return Tblactions */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } /** * Set intactiontypeid * * @param \Security\Entity\Tblactiontypes $intactiontypeid * @return Tblactions */ public function setIntactiontypeid(\Security\Entity\Tblactiontypes $intactiontypeid) { $this->intactiontypeid = $intactiontypeid; return $this; } /** * Get intactiontypeid * * @return \Security\Entity\Tblactiontypes */ public function getIntactiontypeid() { return $this->intactiontypeid; } /** * Set intprocessid * * @param \Security\Entity\Tblprocess $intprocessid * @return Tblactions */ public function setIntprocessid(\Security\Entity\Tblprocess $intprocessid) { $this->intprocessid = $intprocessid; return $this; } /** * Get intprocessid * * @return \Security\Entity\Tblprocess */ public function getIntprocessid() { return $this->intprocessid; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblcustomertype * * @ORM\Table(name="tblCustomerType", uniqueConstraints={@ORM\UniqueConstraint(name="intCustomerType_UNIQUE", columns={"strCustomerType"})}) * @ORM\Entity */ class Tblcustomertype { /** * @var integer * * @ORM\Column(name="intCustomerTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcustomertypeid; /** * @var string * * @ORM\Column(name="strCustomerType", type="string", length=45, nullable=false) */ private $strcustomertype; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intcustomertypeid * * @return integer */ public function getIntcustomertypeid() { return $this->intcustomertypeid; } /** * Set strcustomertype * * @param string $strcustomertype * @return Tblcustomertype */ public function setStrcustomertype($strcustomertype) { $this->strcustomertype = $strcustomertype; return $this; } /** * Get strcustomertype * * @return string */ public function getStrcustomertype() { return $this->strcustomertype; } /** * Set intactive * * @param integer $intactive * @return Tblcustomertype */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep>var ajaxCreateModules = function(data,cb){ callAjaxRequest("POST","/api/modules/add",data,cb); }; var ajaxEditModules = function(data,id,cb){ callAjaxRequest("POST","/api/modules/edit/"+id,data,cb); }; <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblcompany * * @ORM\Table(name="tblCompany", indexes={@ORM\Index(name="fk_tblCompany_tblCompanyType1_idx", columns={"intCompanyTypeID"})}) * @ORM\Entity */ class Tblcompany { /** * @var integer * * @ORM\Column(name="intCompanyID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intcompanyid; /** * @var integer * * @ORM\Column(name="intCompanyCategoryID", type="integer", nullable=true) */ private $intcompanycategoryid; /** * @var string * * @ORM\Column(name="strCompanyName", type="string", length=45, nullable=true) */ private $strcompanyname; /** * @var string * * @ORM\Column(name="strTradeName", type="string", length=45, nullable=true) */ private $strtradename; /** * @var string * * @ORM\Column(name="strWebsite", type="string", length=45, nullable=true) */ private $strwebsite; /** * @var string * * @ORM\Column(name="intCompanyStatusID", type="string", length=45, nullable=true) */ private $intcompanystatusid; /** * @var string * * @ORM\Column(name="strTIN", type="string", length=45, nullable=true) */ private $strtin; /** * @var \Main\Entity\Tblcompanytype * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblcompanytype") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intCompanyTypeID", referencedColumnName="intCompanyTypeID") * }) */ private $intcompanytypeid; /** * Get intcompanyid * * @return integer */ public function getIntcompanyid() { return $this->intcompanyid; } /** * Set intcompanycategoryid * * @param integer $intcompanycategoryid * @return Tblcompany */ public function setIntcompanycategoryid($intcompanycategoryid) { $this->intcompanycategoryid = $intcompanycategoryid; return $this; } /** * Get intcompanycategoryid * * @return integer */ public function getIntcompanycategoryid() { return $this->intcompanycategoryid; } /** * Set strcompanyname * * @param string $strcompanyname * @return Tblcompany */ public function setStrcompanyname($strcompanyname) { $this->strcompanyname = $strcompanyname; return $this; } /** * Get strcompanyname * * @return string */ public function getStrcompanyname() { return $this->strcompanyname; } /** * Set strtradename * * @param string $strtradename * @return Tblcompany */ public function setStrtradename($strtradename) { $this->strtradename = $strtradename; return $this; } /** * Get strtradename * * @return string */ public function getStrtradename() { return $this->strtradename; } /** * Set strwebsite * * @param string $strwebsite * @return Tblcompany */ public function setStrwebsite($strwebsite) { $this->strwebsite = $strwebsite; return $this; } /** * Get strwebsite * * @return string */ public function getStrwebsite() { return $this->strwebsite; } /** * Set intcompanystatusid * * @param string $intcompanystatusid * @return Tblcompany */ public function setIntcompanystatusid($intcompanystatusid) { $this->intcompanystatusid = $intcompanystatusid; return $this; } /** * Get intcompanystatusid * * @return string */ public function getIntcompanystatusid() { return $this->intcompanystatusid; } /** * Set strtin * * @param string $strtin * @return Tblcompany */ public function setStrtin($strtin) { $this->strtin = $strtin; return $this; } /** * Get strtin * * @return string */ public function getStrtin() { return $this->strtin; } /** * Set intcompanytypeid * * @param \Main\Entity\Tblcompanytype $intcompanytypeid * @return Tblcompany */ public function setIntcompanytypeid(\Main\Entity\Tblcompanytype $intcompanytypeid = null) { $this->intcompanytypeid = $intcompanytypeid; return $this; } /** * Get intcompanytypeid * * @return \Main\Entity\Tblcompanytype */ public function getIntcompanytypeid() { return $this->intcompanytypeid; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblpersontype * * @ORM\Table(name="tblPersonType", uniqueConstraints={@ORM\UniqueConstraint(name="strPersonType_UNIQUE", columns={"strPersonType"})}) * @ORM\Entity */ class Tblpersontype { /** * @var integer * * @ORM\Column(name="intPersonTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intpersontypeid; /** * @var string * * @ORM\Column(name="strPersonType", type="string", length=45, nullable=false) */ private $strpersontype; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intpersontypeid * * @return integer */ public function getIntpersontypeid() { return $this->intpersontypeid; } /** * Set strpersontype * * @param string $strpersontype * @return Tblpersontype */ public function setStrpersontype($strpersontype) { $this->strpersontype = $strpersontype; return $this; } /** * Get strpersontype * * @return string */ public function getStrpersontype() { return $this->strpersontype; } /** * Set intactive * * @param integer $intactive * @return Tblpersontype */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblprocess * * @ORM\Table(name="tblProcess", indexes={@ORM\Index(name="fk_tblProcess_tblModules1_idx", columns={"intModuleID"})}) * @ORM\Entity */ class Tblprocess { /** * @var integer * * @ORM\Column(name="intProcessID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $intprocessid; /** * @var string * * @ORM\Column(name="intProcessName", type="string", length=45, nullable=false) */ private $intprocessname; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus; /** * @var \Main\Entity\Tblmodules * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Main\Entity\Tblmodules") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intModuleID", referencedColumnName="intModuleID") * }) */ private $intmoduleid; /** * Set intprocessid * * @param integer $intprocessid * @return Tblprocess */ public function setIntprocessid($intprocessid) { $this->intprocessid = $intprocessid; return $this; } /** * Get intprocessid * * @return integer */ public function getIntprocessid() { return $this->intprocessid; } /** * Set intprocessname * * @param string $intprocessname * @return Tblprocess */ public function setIntprocessname($intprocessname) { $this->intprocessname = $intprocessname; return $this; } /** * Get intprocessname * * @return string */ public function getIntprocessname() { return $this->intprocessname; } /** * Set intstatus * * @param integer $intstatus * @return Tblprocess */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } /** * Set intmoduleid * * @param \Main\Entity\Tblmodules $intmoduleid * @return Tblprocess */ public function setIntmoduleid(\Main\Entity\Tblmodules $intmoduleid) { $this->intmoduleid = $intmoduleid; return $this; } /** * Get intmoduleid * * @return \Main\Entity\Tblmodules */ public function getIntmoduleid() { return $this->intmoduleid; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblperson * * @ORM\Table(name="tblPerson", uniqueConstraints={@ORM\UniqueConstraint(name="strPersonEmail_UNIQUE", columns={"strPersonEmail"})}, indexes={@ORM\Index(name="fk_tblPerson_tblPersonType1_idx", columns={"intPersonTypeID"})}) * @ORM\Entity */ class Tblperson { /** * @var integer * * @ORM\Column(name="intPersonID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intpersonid; /** * @var string * * @ORM\Column(name="strPersonName", type="string", length=45, nullable=true) */ private $strpersonname; /** * @var string * * @ORM\Column(name="strPersonEmail", type="string", length=45, nullable=false) */ private $strpersonemail; /** * @var string * * @ORM\Column(name="strPersonPhone", type="string", length=45, nullable=true) */ private $strpersonphone; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * @var \Main\Entity\Tblpersontype * * @ORM\ManyToOne(targetEntity="Main\Entity\Tblpersontype") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intPersonTypeID", referencedColumnName="intPersonTypeID") * }) */ private $intpersontypeid; /** * Get intpersonid * * @return integer */ public function getIntpersonid() { return $this->intpersonid; } /** * Set strpersonname * * @param string $strpersonname * @return Tblperson */ public function setStrpersonname($strpersonname) { $this->strpersonname = $strpersonname; return $this; } /** * Get strpersonname * * @return string */ public function getStrpersonname() { return $this->strpersonname; } /** * Set strpersonemail * * @param string $strpersonemail * @return Tblperson */ public function setStrpersonemail($strpersonemail) { $this->strpersonemail = $strpersonemail; return $this; } /** * Get strpersonemail * * @return string */ public function getStrpersonemail() { return $this->strpersonemail; } /** * Set strpersonphone * * @param string $strpersonphone * @return Tblperson */ public function setStrpersonphone($strpersonphone) { $this->strpersonphone = $strpersonphone; return $this; } /** * Get strpersonphone * * @return string */ public function getStrpersonphone() { return $this->strpersonphone; } /** * Set intactive * * @param integer $intactive * @return Tblperson */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } /** * Set intpersontypeid * * @param \Main\Entity\Tblpersontype $intpersontypeid * @return Tblperson */ public function setIntpersontypeid(\Main\Entity\Tblpersontype $intpersontypeid = null) { $this->intpersontypeid = $intpersontypeid; return $this; } /** * Get intpersontypeid * * @return \Main\Entity\Tblpersontype */ public function getIntpersontypeid() { return $this->intpersontypeid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblactionfieldtype * * @ORM\Table(name="tblActionFieldType") * @ORM\Entity */ class Tblactionfieldtype { /** * @var integer * * @ORM\Column(name="intActionFieldTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $intactionfieldtypeid; /** * @var string * * @ORM\Column(name="strActionFieldName", type="string", length=45, nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $stractionfieldname; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * Set intactionfieldtypeid * * @param integer $intactionfieldtypeid * @return Tblactionfieldtype */ public function setIntactionfieldtypeid($intactionfieldtypeid) { $this->intactionfieldtypeid = $intactionfieldtypeid; return $this; } /** * Get intactionfieldtypeid * * @return integer */ public function getIntactionfieldtypeid() { return $this->intactionfieldtypeid; } /** * Set stractionfieldname * * @param string $stractionfieldname * @return Tblactionfieldtype */ public function setStractionfieldname($stractionfieldname) { $this->stractionfieldname = $stractionfieldname; return $this; } /** * Get stractionfieldname * * @return string */ public function getStractionfieldname() { return $this->stractionfieldname; } /** * Set intstatus * * @param integer $intstatus * @return Tblactionfieldtype */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblactiontypes * * @ORM\Table(name="tblActionTypes") * @ORM\Entity */ class Tblactiontypes { /** * @var integer * * @ORM\Column(name="intActionTypeID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intactiontypeid; /** * @var string * * @ORM\Column(name="intActionTypeName", type="string", length=45, nullable=true) */ private $intactiontypename; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus; /** * Get intactiontypeid * * @return integer */ public function getIntactiontypeid() { return $this->intactiontypeid; } /** * Set intactiontypename * * @param string $intactiontypename * @return Tblactiontypes */ public function setIntactiontypename($intactiontypename) { $this->intactiontypename = $intactiontypename; return $this; } /** * Get intactiontypename * * @return string */ public function getIntactiontypename() { return $this->intactiontypename; } /** * Set intstatus * * @param integer $intstatus * @return Tblactiontypes */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblbrands * * @ORM\Table(name="tblBrands", uniqueConstraints={@ORM\UniqueConstraint(name="strBrandName_UNIQUE", columns={"strBrandName"})}) * @ORM\Entity */ class Tblbrands { /** * @var integer * * @ORM\Column(name="intBrandID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intbrandid; /** * @var string * * @ORM\Column(name="strBrandName", type="string", length=50, nullable=false) */ private $strbrandname; /** * @var integer * * @ORM\Column(name="intActive", type="integer", nullable=true) */ private $intactive = '1'; /** * Get intbrandid * * @return integer */ public function getIntbrandid() { return $this->intbrandid; } /** * Set strbrandname * * @param string $strbrandname * @return Tblbrands */ public function setStrbrandname($strbrandname) { $this->strbrandname = $strbrandname; return $this; } /** * Get strbrandname * * @return string */ public function getStrbrandname() { return $this->strbrandname; } /** * Set intactive * * @param integer $intactive * @return Tblbrands */ public function setIntactive($intactive) { $this->intactive = $intactive; return $this; } /** * Get intactive * * @return integer */ public function getIntactive() { return $this->intactive; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblproductinventory * * @ORM\Table(name="tblProductInventory", indexes={@ORM\Index(name="fk_tblProductInventory_tblInventoryLocation1_idx", columns={"intLocationID"}), @ORM\Index(name="fk_tblProductInventory_tblProductCondition1_idx", columns={"intConditionID"}), @ORM\Index(name="fk_tblProductInventory_tblProducts1_idx", columns={"intProductID"})}) * @ORM\Entity */ class Tblproductinventory { /** * @var integer * * @ORM\Column(name="intInventoryID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intinventoryid; /** * @var integer * * @ORM\Column(name="intReserveStock", type="integer", nullable=true) */ private $intreservestock; /** * @var integer * * @ORM\Column(name="intActualStock", type="integer", nullable=true) */ private $intactualstock; /** * @var \Security\Entity\Tblinventorylocation * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblinventorylocation") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intLocationID", referencedColumnName="intLocationID") * }) */ private $intlocationid; /** * @var \Security\Entity\Tblproductcondition * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblproductcondition") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intConditionID", referencedColumnName="intConditionID") * }) */ private $intconditionid; /** * @var \Security\Entity\Tblproducts * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblproducts") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intProductID", referencedColumnName="intProductID") * }) */ private $intproductid; /** * Get intinventoryid * * @return integer */ public function getIntinventoryid() { return $this->intinventoryid; } /** * Set intreservestock * * @param integer $intreservestock * @return Tblproductinventory */ public function setIntreservestock($intreservestock) { $this->intreservestock = $intreservestock; return $this; } /** * Get intreservestock * * @return integer */ public function getIntreservestock() { return $this->intreservestock; } /** * Set intactualstock * * @param integer $intactualstock * @return Tblproductinventory */ public function setIntactualstock($intactualstock) { $this->intactualstock = $intactualstock; return $this; } /** * Get intactualstock * * @return integer */ public function getIntactualstock() { return $this->intactualstock; } /** * Set intlocationid * * @param \Security\Entity\Tblinventorylocation $intlocationid * @return Tblproductinventory */ public function setIntlocationid(\Security\Entity\Tblinventorylocation $intlocationid = null) { $this->intlocationid = $intlocationid; return $this; } /** * Get intlocationid * * @return \Security\Entity\Tblinventorylocation */ public function getIntlocationid() { return $this->intlocationid; } /** * Set intconditionid * * @param \Security\Entity\Tblproductcondition $intconditionid * @return Tblproductinventory */ public function setIntconditionid(\Security\Entity\Tblproductcondition $intconditionid = null) { $this->intconditionid = $intconditionid; return $this; } /** * Get intconditionid * * @return \Security\Entity\Tblproductcondition */ public function getIntconditionid() { return $this->intconditionid; } /** * Set intproductid * * @param \Security\Entity\Tblproducts $intproductid * @return Tblproductinventory */ public function setIntproductid(\Security\Entity\Tblproducts $intproductid = null) { $this->intproductid = $intproductid; return $this; } /** * Get intproductid * * @return \Security\Entity\Tblproducts */ public function getIntproductid() { return $this->intproductid; } } <file_sep><?php namespace Main\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblactionfieldoptions * * @ORM\Table(name="tblActionFieldOptions", indexes={@ORM\Index(name="fk_tblActionFieldOptions_tblObjects1_idx", columns={"intObjectID"}), @ORM\Index(name="fk_tblActionFieldOptions_tblActionFields1_idx", columns={"intActionFieldID"})}) * @ORM\Entity */ class Tblactionfieldoptions { /** * @var integer * * @ORM\Column(name="intActionFieldOptionID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") */ private $intactionfieldoptionid; /** * @var integer * * @ORM\Column(name="intStatus", type="integer", nullable=true) */ private $intstatus = '1'; /** * @var \Main\Entity\Tblactionfields * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Main\Entity\Tblactionfields") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intActionFieldID", referencedColumnName="intActionFieldID") * }) */ private $intactionfieldid; /** * @var \Main\Entity\Tblobjects * * @ORM\Id * @ORM\GeneratedValue(strategy="NONE") * @ORM\OneToOne(targetEntity="Main\Entity\Tblobjects") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intObjectID", referencedColumnName="intObjectID") * }) */ private $intobjectid; /** * Set intactionfieldoptionid * * @param integer $intactionfieldoptionid * @return Tblactionfieldoptions */ public function setIntactionfieldoptionid($intactionfieldoptionid) { $this->intactionfieldoptionid = $intactionfieldoptionid; return $this; } /** * Get intactionfieldoptionid * * @return integer */ public function getIntactionfieldoptionid() { return $this->intactionfieldoptionid; } /** * Set intstatus * * @param integer $intstatus * @return Tblactionfieldoptions */ public function setIntstatus($intstatus) { $this->intstatus = $intstatus; return $this; } /** * Get intstatus * * @return integer */ public function getIntstatus() { return $this->intstatus; } /** * Set intactionfieldid * * @param \Main\Entity\Tblactionfields $intactionfieldid * @return Tblactionfieldoptions */ public function setIntactionfieldid(\Main\Entity\Tblactionfields $intactionfieldid) { $this->intactionfieldid = $intactionfieldid; return $this; } /** * Get intactionfieldid * * @return \Main\Entity\Tblactionfields */ public function getIntactionfieldid() { return $this->intactionfieldid; } /** * Set intobjectid * * @param \Main\Entity\Tblobjects $intobjectid * @return Tblactionfieldoptions */ public function setIntobjectid(\Main\Entity\Tblobjects $intobjectid) { $this->intobjectid = $intobjectid; return $this; } /** * Get intobjectid * * @return \Main\Entity\Tblobjects */ public function getIntobjectid() { return $this->intobjectid; } } <file_sep><?php namespace Security\Entity; use Doctrine\ORM\Mapping as ORM; /** * Tblbundles * * @ORM\Table(name="tblBundles", indexes={@ORM\Index(name="fk_tblBundles_tblProducts1_idx", columns={"intProductID"})}) * @ORM\Entity */ class Tblbundles { /** * @var integer * * @ORM\Column(name="intBundleID", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $intbundleid; /** * @var integer * * @ORM\Column(name="intChildID", type="integer", nullable=true) */ private $intchildid; /** * @var integer * * @ORM\Column(name="intQuantity", type="integer", nullable=true) */ private $intquantity; /** * @var \Security\Entity\Tblproducts * * @ORM\ManyToOne(targetEntity="Security\Entity\Tblproducts") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="intProductID", referencedColumnName="intProductID") * }) */ private $intproductid; /** * Get intbundleid * * @return integer */ public function getIntbundleid() { return $this->intbundleid; } /** * Set intchildid * * @param integer $intchildid * @return Tblbundles */ public function setIntchildid($intchildid) { $this->intchildid = $intchildid; return $this; } /** * Get intchildid * * @return integer */ public function getIntchildid() { return $this->intchildid; } /** * Set intquantity * * @param integer $intquantity * @return Tblbundles */ public function setIntquantity($intquantity) { $this->intquantity = $intquantity; return $this; } /** * Get intquantity * * @return integer */ public function getIntquantity() { return $this->intquantity; } /** * Set intproductid * * @param \Security\Entity\Tblproducts $intproductid * @return Tblbundles */ public function setIntproductid(\Security\Entity\Tblproducts $intproductid = null) { $this->intproductid = $intproductid; return $this; } /** * Get intproductid * * @return \Security\Entity\Tblproducts */ public function getIntproductid() { return $this->intproductid; } }
8badf456216c9ea38672f5a80806563016644352
[ "JavaScript", "PHP" ]
60
PHP
devhood/erp-base
8c250e44799a3db1740069e465d525a018b403c4
25d3c9df32711d5086edfaf2a0548b9968a636ff
refs/heads/master
<repo_name>EdeJ/dropit-native<file_sep>/config/colors.js export default { customBackground: '#EEE9DB', customRed: '#CB2431', customLightRed: '#FFEFEF', customGreen: '#69BA5E', customDarkGreen: '#58A34D', customBrown: '#635748', customBorderBeige: '#D0B899', customWhite: '#FFF' }<file_sep>/components/PageTemplate.js import React from 'react' import { SafeAreaView, StatusBar, StyleSheet, View } from 'react-native' import TopHeader from '../components/TopHeader' import colors from '../config/colors' function PageTemplate({ children, navigation }) { return ( <SafeAreaView style={styles.container}> <StatusBar style="auto" /> <TopHeader navigation={navigation} /> <View style={styles.page}> {children} </View> </SafeAreaView> ) } export default PageTemplate const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: colors.customBackground, }, page: { paddingTop: 20, paddingLeft: 20, paddingRight: 20, paddingBottom: 80 } }) <file_sep>/screens/AllDemos.js import React, { useEffect, useState } from 'react' import { ScrollView, StyleSheet, Text, View } from 'react-native' import { getAllUsers } from '../helpers/axiosConfig' import { useAuthentication } from '../hooks/authentication' import Spinner from '../components/Spinner' import PageTitle from '../components/PageTitle' import PageTemplate from '../components/PageTemplate' import colors from '../config/colors' function AllDemos({ navigation }) { const { getUser } = useAuthentication() const [allUsers, setAllUsers] = useState() useEffect(() => { fetchData() async function fetchData() { const user = await getUser() if (!user) { navigation.navigate('SignIn') return } try { const result = await getAllUsers() setAllUsers(result.data) } catch (error) { navigation.navigate('Home') console.error(error) } } }, []) if (!allUsers) { return <Spinner message="loading demos..." /> } return ( <PageTemplate navigation={navigation}> <PageTitle>All Demos</PageTitle> <View style={styles.list}> {allUsers && ( <ScrollView style={styles.allDemosView}> {allUsers.map(user => ( <View key={user.userId}> {user.demos.length > 0 && ( <View> <Text style={styles.user} >User: {user.username}</Text> {user.demos.map(demo => ( <View key={demo.id} style={styles.card}> <Text style={styles.demoText} >{demo.songTitle}</Text> </View> ))} </View> )} </View> ))} </ScrollView> )} </View> </PageTemplate> ) } const styles = StyleSheet.create({ allDemosView: { paddingTop: 20, paddingBottom: 60 }, list: { paddingBottom: 60 }, user: { color: colors.customGreen, fontWeight: 'bold' }, card: { flexDirection: 'row', alignItems: 'center', borderColor: colors.customBrown, borderStyle: 'solid', borderWidth: 1, borderRadius: 5, paddingLeft: 20, paddingRight: 20, paddingTop: 10, paddingBottom: 10, marginTop: 10, marginBottom: 20 }, playIcon: { width: 36, height: 36, marginRight: 20 }, text: { fontSize: 20, color: colors.customBrown } }) export default AllDemos
9695f25c290b749a356ad322940e686233623b39
[ "JavaScript" ]
3
JavaScript
EdeJ/dropit-native
35c240479c2a0dc1e5f3d75d97126d11e04768a2
be5e950ef654b98471263084736a5666fb36ae0c
refs/heads/master
<file_sep>"# zadanie-17-7" <file_sep>module.exports = { 'GOOGLE_CLIENT_ID': '366444113234-hrn5o4iti3626dv03v09g75fbt8m24rl.apps.googleusercontent.com', 'GOOGLE_CLIENT_SECRET': '<KEY>', 'CALLBACK_URL': 'http://localhost:3000/auth/google/callback' };
65008dbf9b7c068b65c82253f649f56e0d012653
[ "Markdown", "JavaScript" ]
2
Markdown
KamilWojtczak123/zadanie-17-7
3e7617f06a3827ceb5009fdca9feff03d52673af
a0005b705cf9e495ee53b53e4828f390a35e4518
refs/heads/master
<repo_name>ghacupha/redux-sample-project<file_sep>/src/app/state/user.effects.ts import {Injectable} from "@angular/core"; import {Actions, createEffect, ofType} from "@ngrx/effects"; import {UsersService} from "../users/user.service"; import { userAdditionWorked, userAdditionFailed, usersFetched, usersFetchFailed, usersFetchWorked, userHasBeenCreated, userHasBeenDeleted, userDeletionWorked, userDeletionFailed, userListRefreshFailed, userHasBeenUpdated, userUpdateWorked, userUpdateFailed } from "./user.actions"; import {catchError, map, mergeMap} from "rxjs/operators"; import {of} from "rxjs"; import {User} from "../users/users.model"; import {createAction} from "@ngrx/store"; @Injectable() export class UserEffects { fetchUsersEffect$ = createEffect( () => this.actions$.pipe( ofType(usersFetched), mergeMap( () => this.usersService.getAllUsers().pipe( map((users: User[]) => usersFetchWorked({users})), catchError(error => of(usersFetchFailed({error}))) ) ) ) ); createUserEffect$ = createEffect( () => this.actions$.pipe( ofType(userHasBeenCreated), mergeMap( (action) => this.usersService.addUser(action.user).pipe( map(user => userAdditionWorked({user})), catchError(error => of(userAdditionFailed({error}))) ) ) ) ); /** * Delete users and then dispatched user-deletion-worked with the array of new * user list to the reducer */ deleteUserEffect$ = createEffect( () => this.actions$.pipe( ofType(userHasBeenDeleted), mergeMap( (action) => this.usersService.deleteUser(action.userId).pipe( mergeMap(() => this.usersService.getAllUsers().pipe( map((users: User[]) => userDeletionWorked({users})), catchError(error => of(userListRefreshFailed({error}))) )), catchError(error => of(userDeletionFailed({error}))) ) ) ) ) updateUserEffect$ = createEffect( () => this.actions$.pipe( ofType(userHasBeenUpdated), mergeMap(action => this.usersService.updateUser(action.user).pipe( map(users => userUpdateWorked({users})), catchError(error => of(userUpdateFailed({error}))) )) ) ); constructor( private actions$: Actions, private usersService: UsersService) { } } <file_sep>/src/app/state/user.reducer.ts import {Action, createReducer, on} from "@ngrx/store"; import {User} from "../users/users.model"; import { userAdditionWorked, userDeletionWorked, userHasBeenSelected, userSelectionWorked, usersFetchWorked, userUpdateWorked } from "./user.actions"; export const usersFeatureSelectorKey = "users"; export interface State { users: User[] selectedUser: User | undefined } export const initialState: State = { users: [], selectedUser: undefined } const _reducer = createReducer( initialState, on(usersFetchWorked, (state, {users}) => { return { ...state, users: [...state.users, ...users] } }), on(userAdditionWorked, (state, {user}) => { return { ...state, users: [...state.users, user] } }), on(userDeletionWorked, (state, {users}) => { return { ...state, users: [...users] } }), on(userUpdateWorked, (state, {users}) => { return { ...state, users: [...users], } }), on(userHasBeenSelected, (state, {user}) => { return { ...state, selectedUser: {...user} } }), on(userSelectionWorked, (state) => ({ ...state, selectedUser: undefined })) ) export function reducer(state: State | undefined, action: Action): State { return _reducer(state, action) } <file_sep>/src/app/users/users.module.ts import {NgModule} from "@angular/core"; import {StoreModule} from "@ngrx/store"; import {reducer, usersFeatureSelectorKey} from "../state/user.reducer"; import {UserListComponent} from "../components/user-list.component"; import {UsersService} from "./user.service"; import {EffectsModule} from "@ngrx/effects"; import {UserEffects} from "../state/user.effects"; import {CommonModule} from "@angular/common"; import {HttpClientModule} from "@angular/common/http"; import {UserAddComponent} from "../components/user-add.component"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {RouterModule, Routes} from "@angular/router"; const routes: Routes = [ { path: 'users', component: UserListComponent }, { path: 'updates', component: UserAddComponent } ] @NgModule({ declarations: [UserListComponent, UserAddComponent], imports: [ CommonModule, HttpClientModule, EffectsModule.forFeature([UserEffects]), StoreModule.forFeature(usersFeatureSelectorKey, reducer), ReactiveFormsModule, RouterModule.forRoot(routes), FormsModule, ], exports: [UserListComponent, UserAddComponent, RouterModule], providers: [UsersService] }) export class UsersModule{} <file_sep>/src/app/components/user-add.component.ts import {Component, Input, OnInit} from "@angular/core"; import {select, Store} from "@ngrx/store"; import {State} from "../state/user.reducer"; import {FormBuilder, FormGroup} from "@angular/forms"; import {User} from "../users/users.model"; import {userHasBeenCreated, userHasBeenUpdated, userSelectionWorked} from "../state/user.actions"; import {selectUserForUpdate} from "../state/user.selectors"; import {Router} from "@angular/router"; @Component({ selector: 'app-add-user', templateUrl: 'user-add.template.html' }) export class UserAddComponent implements OnInit { updateUser?: User; editForm: FormGroup = this.fb.group({ id: [''], name: [''], email: [''], purpose: [''], programme: [''], }); isSaving: boolean = false; isUpdating: boolean = false; constructor(private state: Store<State>, private fb: FormBuilder, private router: Router) { } ngOnInit(): void { this.state.pipe(select(selectUserForUpdate)).subscribe(user => this.updateUser = user); if (this.updateUser !== undefined) { this.updateForm(this.updateUser); this.isUpdating = true; } this.state.dispatch(userSelectionWorked()) } save() { this.isSaving = true; const user = this.createFromForm(); if (this.isUpdating){ this.state.dispatch(userHasBeenUpdated({user})) this.isUpdating = false } else { this.state.dispatch(userHasBeenCreated({user})) } this.isSaving = false; } private createFromForm(): User { return { ...new User(), id: this.editForm.get(['id'])!.value, name: this.editForm.get(['name'])!.value, email: this.editForm.get(['email'])!.value, purpose: this.editForm.get(['purpose'])!.value, programme: this.editForm.get(['programme'])!.value, }; } private updateForm(user?: User | undefined): void { this.editForm.patchValue({ id: user?.id, name: user?.name, email: user?.email, purpose: user?.purpose, programme: user?.programme, }); } gotoUsers() { this.router.navigate(['users']) } } <file_sep>/src/app/state/user.selectors.ts import {State, usersFeatureSelectorKey} from "./user.reducer"; import {createFeatureSelector, createSelector} from "@ngrx/store"; export const userFeatureSelector = createFeatureSelector<State>(usersFeatureSelectorKey); export const selectUsers = createSelector( userFeatureSelector, (state: State) => state.users ); export const selectUserForUpdate = createSelector( userFeatureSelector, (state: State) => state.selectedUser ) <file_sep>/src/app/components/user-list.component.ts import {Component, OnInit} from "@angular/core"; import {Observable} from "rxjs"; import {User} from "../users/users.model"; import {select, Store} from "@ngrx/store"; import {State} from "../state/user.reducer"; import {userHasBeenDeleted, userHasBeenSelected, usersFetched} from "../state/user.actions"; import {selectUsers} from "../state/user.selectors"; import {Router} from "@angular/router"; @Component({ selector: 'app-user-list', templateUrl: 'user-list.template.html' }) export class UserListComponent implements OnInit { users$?: Observable<User[]>; constructor(private state: Store<State>, private route: Router) { // to avoid duplicating the list this.users$ = undefined; } ngOnInit() { this.state.dispatch(usersFetched()); this.users$ = this.state.pipe(select(selectUsers)); } delete(userId: number): void { this.state.dispatch(userHasBeenDeleted({userId})); } update(user: User): void { this.state.dispatch(userHasBeenSelected({user})) this.route.navigate(['updates']); } addUser() { this.route.navigate(['updates']) } } <file_sep>/src/app/state/user.actions.ts import {createAction, props} from "@ngrx/store"; import {User} from "../users/users.model"; export const usersFetched = createAction( '[Users Page] Users fetched' ) export const usersFetchWorked = createAction( '[Users API] Users fetched successfully', props<{users: User[]}>() ) export const usersFetchFailed = createAction( '[Users API] Users fetch failed', props<{error: string}>() ) /** * Dispatched when the user adds a new user */ export const userHasBeenCreated = createAction( '[Users Page] Users created', props<{user: User}>() ) /** * Dispatched when the user is added successfully */ export const userAdditionWorked = createAction( '[Users API] Users added successfully', props<{user: User}>() ) /** * Dispatched when the user addition process fails */ export const userAdditionFailed = createAction( '[Users API] Users add failed', props<{error: string}>() ) /** * Dispatched when a user entity is deleted */ export const userHasBeenDeleted = createAction( '[Users Page] user deleted', props<{userId: number}>() ); /** * Dispatched when user is deleted successfully and has list of current * users as metadata */ export const userDeletionWorked = createAction( '[Users API] User has been deleted successfully', props<{users: User[]}>() ) /** * Dispatched after user list is dispatch in the event we delete a user; * and then failure is experienced */ export const userListRefreshFailed = createAction( '[Users API] Refresh of user list has failed', props<{error: string}>() ) export const userDeletionFailed = createAction( '[Users API] User has deletion has failed', props<{error: String}>() ) export const userHasBeenUpdated = createAction( '[User Page] User has been updated', props<{user: User}>() ) export const userUpdateWorked = createAction( '[User API] User has been updated', props<{users: User[]}>() ) export const userUpdateFailed = createAction( '[User API] User has been updated', props<{error: string}>() ) export const userHasBeenSelected = createAction( '[User Page] User has been selected', props<{user: User}>() ) export const userSelectionWorked = createAction( '[User Page] User selection worked', ) <file_sep>/src/app/users/user.service.ts import {Injectable} from "@angular/core"; import {HttpClient} from "@angular/common/http"; import {EMPTY, Observable, of} from "rxjs"; import {User} from "./users.model"; import {State} from "../state/user.reducer"; import {select, Store} from "@ngrx/store"; import {selectUsers} from "../state/user.selectors"; @Injectable({providedIn: 'root'}) export class UsersService { userUrl = 'http://localhost:3000/users'; constructor( private http: HttpClient, private state: Store<State> ) { } getAllUsers(): Observable<User[]> { return this.http.get<User[]>(this.userUrl); } /** * We add a user and return EMPTY if the user exists * * @param user */ addUser(user: User): Observable<User> { return this.http.post<User>(this.userUrl, user); } updateUser(user: User): Observable<User[]> { if (!this.contains(this.existingUsers, user.id)) { this.http.put<User>(this.userUrl, user) return this.getAllUsers(); } else return of(this.existingUsers) } get existingUsers() { const existingUsers: User[] = []; this.state.pipe(select(selectUsers)).subscribe(users => { existingUsers.push(...users) }); return existingUsers; } /** * Returns observable object which I won't use * @param userId */ deleteUser(userId: number): Observable<Object> { return this.http.delete(`${this.userUrl}/${userId}`) } contains(a: User[], userId: number): boolean { let i: number = a.length; while (i--) { if (a[i].id === userId) { return true; } } return false; } }
f22a0bb934a1ada1ff0a34710053fa3b49de3d91
[ "TypeScript" ]
8
TypeScript
ghacupha/redux-sample-project
e1c58c56c8892400005b693bd629d2870bc3d46c
21b6ed66c84734977f1e6714847df4648bedcf15
refs/heads/master
<repo_name>chirinom/rails-longest-word-game<file_sep>/app/controllers/games_controller.rb require 'open-uri' require 'json' class GamesController < ApplicationController def new letters_array = ('A'..'Z').to_a @letters = 10.times.map {letters_array.sample} end def score @word = params[:word] url = "https://wagon-dictionary.herokuapp.com/#{@word}" api_words = open(url).read words = JSON.parse(api_words) if words['found'] == false @result = "Sorry but #{@word} does not seem to be a valid English word.." elsif has?(@word) == false @result = "Sorry but #{@word} can't be built with the given letters" else words['found'] == true @result = "Congratulations! #{@word} is a valid English word!" end end def has?(word) @letters = params[:letters].downcase.split("") word.split("").all? do |character| @letters.include?(character) end end end
77a623ef4b94c40875d5494db4d762061a2aa6aa
[ "Ruby" ]
1
Ruby
chirinom/rails-longest-word-game
99887084a8e742b66c8517511a139cf8f09aa1a9
b0ceb8a220096097beba2f26440165acc8ca8860
refs/heads/master
<repo_name>lb2281075105/RN8818-uniapp<file_sep>/README.md # RN8818-uniapp HBuilderX + uniapp + vue 开发Android、iOS 、多种平台小程序(微信、支付宝、抖音、头条等)、H5 ``` git init git add README.md git commit -m "first commit" git remote add origin https://github.com/lb2281075105/uniapp.git git push -u origin master git pull origin master --allow-unrelated-histories ```<file_sep>/common/index.js import request from './api.js' export const getHomeData = (options) => request(options);
f8233c505c6efbf7ea9edcdc2ab18e270572d4ad
[ "Markdown", "JavaScript" ]
2
Markdown
lb2281075105/RN8818-uniapp
6d43765771599427c2d8bc22ade573c55026d4bc
6b4408c1585f2d9571ac37695d7418ca27b5547b
refs/heads/master
<file_sep><?php namespace Bomeravi\dateConverter; class dateCalculator { private $start_date; private $temp_start_date; private $temp_end_date; private $end_date; private $include_day; private $step; private $by_month_day_step; private $by_month; private $by_week; private $total_days; private $full_diff; //for storing temp_values; private $temp_days; //returned datas; //real ; /* diff year y diff month m diff day d diff total_days = days; diff rem_days = 0; //for virtual for my isp; diff year = v_y diff month = v_m diff day = v_d diff total days = v_days diff rem_days = v_remdays; //for step; diff year = s_y diff month = s_m diff days = s_d diff total_days = s_days diff rem = s_remdays; */ public function __construct() { $this->include_day = true; $this->step = 30; } public function input_dates($date1, $date2=null, $include_day = true){ if(!is_object($date1)){ $this->start_date = new \DateTime($date1); } if($date2 != null){ if(!is_object($date2)){ $this->end_date = new \DateTime($date2); } } else { $this->end_date = new \DateTime; } $this->include_day = boolval($include_day); //var_dump($this); } private function d_diff($date1, $date2){ return $date1->diff($date2); } public function add_from_today($day){ //expiry date calculation from today //echo $day; $ddate = new \DateTime;//date("D-M-d"); //var_dump($ddate); date_add($ddate, date_interval_create_from_date_string($day . " days")); return date_format($ddate, 'Y-m-d'); } public function diff_in_weeks_and_days($from, $to) { $day = 24 * 3600; $from = strtotime($from); $to = strtotime($to) + $day; $diff = abs($to - $from); $weeks = floor($diff / $day / 7); $days = $diff / $day - $weeks * 7; $out = array(); if ($weeks) $out[] = "$weeks Week" . ($weeks > 1 ? 's' : ''); if ($days) $out[] = "$days Day" . ($days > 1 ? 's' : ''); return implode(', ', $out); } public function no_of_weeks_and_days($tdays){ $weeks = 0; $days = 0; $weeks = intval($tdays/7); $days = $tdays%7; $out = array(); if ($weeks) $out[] = "$weeks Week" . ($weeks > 1 ? 's' : ''); if ($days) $out[] = "$days Day" . ($days > 1 ? 's' : ''); return implode(', ', $out); } private function date_form($date , $t) { if($t == 'days'){ return $date->format("%a"); } } private function calculate_by_step($days, $step=30){ $v_year = 0; $v_month = 0; $v_day = 0; $no_of_month = intval(365/$step); $v_day = $days % $step; $v_month = intval(( ($days - $v_day) / $step)% $no_of_month); $v_year = intval( ($days - $v_day) / ($no_of_month * $step)); $v['s_y'] = $v_year; $v['s_m'] = $v_month; $v['s_d'] = $v_day; $v['s_rem'] = $step - $v_day; return $v; } private function process(){ $date11 = clone $this->start_date; $date21 = clone $this->end_date; //var_dump($date11); if($this->include_day) { date_sub($date11, date_interval_create_from_date_string('1 day')); //$date11->add(new DateInterval('PT10H30S')); //$date11->modify('-1 day'); //var_dump($this->date1); } $this->full_diff = $this->d_diff($date11, $this->end_date); $this->total_days = $this->date_form($diff, "days"); //get no of days eg 1261 days; } public function calculator() { //$st = $this->date1; $date11 = clone $this->start_date; $date21 = clone $this->end_date; //var_dump($date11); if($this->include_day) { if($this->start_date <= $this->end_date){ //echo "it is executed"; date_sub($date11, date_interval_create_from_date_string('1 day')); //$date11->add(new DateInterval('PT10H30S')); //$date11->modify('-1 day'); //var_dump($this->date1); } else { date_sub($date21, date_interval_create_from_date_string('1 day')); } } $diff = $this->d_diff($date11, $date21); //var_dump($date11,$this->end_date,$diff); $fulldays = $this->date_form($diff, "days"); //echo $fulldays;//get no of days eg 1261 days; $this->total_days = $this->date_form($diff, "days"); //get no of days eg 1261 days; $v = $this->calculate_by_step($fulldays); //calculate by step for no of days; // $rem = 30 - $fulldays % 30; it is for isp $rem = 30-$diff->d; //$ttt = $this->from_today($rem); // real expire date $days = ($this->end_date->format('d') + 30 - $date11->format('d')) % 30; return array( "y" => $diff->y, "m" => $diff->m, "d" => $diff->d, "v_d" => $days, "days" => $fulldays, "v_days" => $diff->y * 360 + $diff->m * 30 + $days, "rem_days" => $rem, 'v_rem_days' => 30 - $days, 'start_date' => date_format($this->start_date, "Y-m-d"), // "expire_date" => $ttt, 'v_expire_date' => date_format(date_add($this->end_date, date_interval_create_from_date_string(30-$days . " days")), "Y-m-d"), 's_y' => $v['s_y'], 's_m' => $v['s_m'], 's_d' => $v['s_d'], 's_rem' => $v['s_rem'], 's_expire_date' => date_format(date_add($date21, date_interval_create_from_date_string($v['s_rem'] ." days")), "Y-m-d"), ); } }<file_sep># dateconverter Date Converter for nepali to english and english to nepali based on https://github.com/amant/Nepali-Date-Convert for composer It also have function to calculate the date difference between datas.
7b83f14c549162181cc04e05e339c9399bcc3f34
[ "Markdown", "PHP" ]
2
PHP
bomeravi/dateconverter
50fa9e4632068abe99c01281f0509cc84b2e56c4
51ff46679125d634f2a94694db170b42763da28c
refs/heads/master
<repo_name>ndifrekea/ContactManager<file_sep>/contact.py class Contact(): def __init__(self, name, phone, email, website, birthday, linkedin, picture): self.name=name self.phone=phone self.email=email self.website=website self.birthday=birthday self.linkedin=linkedin self.picture=picture def set_contact(self, name, phone, email, website, birthday, linkedin, picture): self.name=name self.phone=phone self.email=email self.website=website self.birthday=birthday self.linkedin=linkedin self.picture=picture def get_contact(self): print(self.name, self.phone, self.email, self.website, self.birthday, self.linkedin ,self.picture) new_name=input("What is your name?") new_phone=input("Phone Number?") new_email=input("What is your email?") new_website=input("The name of your website?") dob=input("Your date of birth?") linkedin=input("LinkedIn Name?") pictureid=input("Picture Id") new_contact=Contact(new_name, new_phone, new_email, new_website, dob, linkedin, pictureid) new_contact.set_contact(new_name, new_phone, new_email, new_website, dob, linkedin, pictureid) new_contact.get_contact()
31237723abc69195af3dc231203b361914b537a9
[ "Python" ]
1
Python
ndifrekea/ContactManager
e0ced328faa056aba4ff6b94bc3edfcb16d7e702
71c50bb3f32574d6f99d430ed698498bad37c8ef
refs/heads/master
<repo_name>NathanReginato/Angula-auth<file_sep>/.env.example DATABASE_URL=postgres://localhost/beer-bonuses JWT_SECRET=replace <file_sep>/readme.md # Beer Bonuses Installation: ``` createdb beer-bonuses npm install cp .env.example .env knex migrate:latest ```
0319eadfb6ee73756ccc4920b763192e4425628f
[ "Markdown", "Shell" ]
2
Shell
NathanReginato/Angula-auth
a2893219d62a6db5eb18cf8d06d331016014975d
0f466a3460f5d9c68c1bad30169dfbc2f89f21f4
refs/heads/master
<file_sep>Game Show App - Phrase Hunter <p> This is a browser-based, word guessing game: "Phrase Hunter." where the player will be able to select a random, hidden phrase, and tries to guess, by clicking letters on an onscreen keyboard.</p> <hr> <h2>Game Rules:</h2> <p>Each time the player guesses a letter, the program compares the letter the player has chosen with the random phrase. If the letter is in the phrase, the game board displays the chosen letters on the screen.</p> <p>A player continues to select letters until they guess the phrase (and win), or make five incorrect guesses (and lose).</p> <p>If the player completes the phrase before they run out of guesses, a winning screen appears. If the player guesses incorrectly 5 times, a losing screen appears.</p> <p>A player can guess a letter only once. After they’ve guessed a letter, your programming will need to disable that letter on the onscreen keyboard.</p> <h2>Technologies Used:</h2> <ul> <li>PHP</li> <li>OOP</li> <li>HTML</li> <li>CSS</li> </ul> <h2>Support & Contact Details:</h2> <p>Feel free to email me at <b><EMAIL></b> if you have any questions, comments or concerns. <h2>License</h2> <p><a href="https://teamtreehouse.com/home">Team Treehouse</a> starter files</p> <p>Copyright (c) 2020 <b><NAME> <file_sep><?php session_start(); if (isset($_POST['start']) || isset($_POST['restart'])) { $_SESSION['phrase'] = ""; $_SESSION['selected'] = []; } include "inc/header.php"; include "inc/phrase.php"; include "inc/game.php"; if (isset($_POST['key'])) { $_SESSION['selected'][] = $_POST['key']; } $phrase = new Phrase($_SESSION['phrase'], $_SESSION['selected']); $_SESSION['phrase'] = $phrase->getCurrentPhrase(); $game = new Game($phrase); ?> <body> <div class="main-container"> <div id="banner" class="section"> <h2 class="header">Phrase Hunter</h2> <?php if ($game->checkforLose() || $game->checkForWin()) { echo $game->gameOver(); return; } echo $phrase->addPhraseToDisplay(); echo $game->displayKeyboard(); ?> <div id='scoreboard' class='section'> <ol> <?php echo $game->displayScore(); ?> </ol> </div> </div> </div> </body> </html> <file_sep><?php class Phrase { private $currentPhrase; private $selected; public $phrases = [ 'Boldness be my friend', 'Leave no stone unturned', 'Broken crayons still color', 'The adventure begins', 'Dream without fear', 'Love without limits' ]; private $string = ""; public function __construct($phrase = "", $selected = []) { if (!empty($phrase) && !empty($selected)) { $this->currentPhrase = $phrase; } else { shuffle($this->phrases); $this->currentPhrase = $this->phrases[0]; } $this->selected = $selected; } /*Builds the HTML for the letters of the phrase. Each letter is presented by an empty box, one list item for each letter. See the example_html/phrase.txt file for an example of what the render HTML for a phrase should look like when the game starts. When the player correctly guesses a letter, the empty box is replaced with the matched letter. Use the class "hide" to hide a letter and "show" to show a letter. Make sure the phrase displayed on the screen doesn't include boxes for spaces*/ public function addPhraseToDisplay() { $characters = str_split(strtolower($this->currentPhrase)); foreach ($characters as $character) { if ($character != " ") { if (in_array($character, $this->selected)) { $this->string .= "<li class='show letter h'>$character</li>"; } else { $this->string .= "<li class='hide letter h'>$character</li>"; } } else { $this->string .= "<li class='hide space'> </li>"; } } return $this->string; } /*checks to see if a letter matches a letter in the phrase. Accepts a single letter to check against the phrase. Returns true or false.*/ public function checkLetter($letter) { $uniqueCharacters = array_unique(str_split(str_replace(' ', '', strtolower($this->currentPhrase)))); return in_array($letter, $uniqueCharacters); } public function getLetterArray() { $uniqueCharacters = array_unique(str_split(str_replace(' ', '', strtolower($this->currentPhrase)))); return $uniqueCharacters; } public function getSelected() { return $this->selected; } public function getCurrentPhrase() { return $this->currentPhrase; } public function numberLost() { $count = count(array_diff($this->selected, $this->getLetterArray())); return $count; } } <file_sep><?php class Game { private $phrase; private $lives = 5; private $scoreIconHtml = ""; public function __construct(Phrase $phrase) { $this->phrase = $phrase; } /*Create a onscreen keyboard form. See the example_html/keyboard.txt file for an example of what the render HTML for the keyboard should look like. If the letter has been selected the button should be disabled. Additionally, the class "correct" or "incorrect' should be added based on the checkLetter() method of the Phrase object. Return a string of HTML for the keyboard form. */ public function displayKeyboard() { $keyboard = "<form method='POST' action='play.php'> <div id='qwerty' class='section'> <div class='keyrow'>". $this->letter('q'). $this->letter('w'). $this->letter('e'). $this->letter('r'). $this->letter('t'). $this->letter('y'). $this->letter('u'). $this->letter('i'). $this->letter('o'). $this->letter('p'). "</div> <div class='keyrow'>". $this->letter('a'). $this->letter('s'). $this->letter('d'). $this->letter('f'). $this->letter('g'). $this->letter('h'). $this->letter('j'). $this->letter('k'). $this->letter('l'). "</div> <div class='keyrow'>". $this->letter('z'). $this->letter('x'). $this->letter('c'). $this->letter('v'). $this->letter('b'). $this->letter('n'). $this->letter('m'). "</div> </div> </form>"; return $keyboard; } /*Display the number of guesses available. See the example_html/scoreboard.txt file for an example of what the render HTML for a scoreboard should look like. Return string HTML of Scoreboard.*/ public function displayScore() { for ($i = 0; $i < $this->lives - $this->phrase->numberLost(); $i++) { $this->scoreIconHtml .= "<li class='tries'><img src='images/liveHeart.png' height='35px' widght='30px'></li>"; } for ($x = 0; $x < $this->phrase->numberLost(); $x++ ) { $this->scoreIconHtml .= "<li class='tries'><img src='images/lostHeart.png' height='35px' widght='30px'></li>"; } return $this->scoreIconHtml; } public function letter ($letter) { if (!in_array($letter, $this->phrase->getSelected())) { $outcome = "<button class='key' name='key' value='".$letter."'>".$letter."</button>"; return $outcome; } if ($this->phrase->checkLetter($letter)) { $outcome = "<button class='key' name='key' value='".$letter."' style='background-color: green'>".$letter."</button>"; return $outcome; } else { $outcome = "<button class='key' name='key' value='".$letter."' style='background-color: red' disabled>".$letter."</button>"; } return $outcome; } //this method checks to see if the player has selected all of the letters. public function checkForWin() { $matchArray = array_intersect($this->phrase->getLetterArray(), $this->phrase->getSelected()); if (count($matchArray) == count($this->phrase->getLetterArray())) { return true; } } //this method checks to see if the player has guessed too many wrong letters. public function checkForLose() { if ($this->phrase->numberLost() == 5) { return true; } } //this method displays one message if the player wins and another message if they lose. It returns false if the game has not been won or lost. public function gameOver() { if ($this->checkForLose()) { $message = "<h1 id='game-over-message'>The phrase was: '". $this->phrase->getCurrentPhrase()."'. Better luck next time!</h1> <form action='play.php' method='POST'> <input id='btn__reset' type='submit' name='restart' value='Restart Game' /> </form>"; return $message; } if ($this->checkForWin()) { $message = "<h1 id='game-over-message-won'>Congratulations on guessing: '".$this->phrase->getCurrentPhrase()."'.</h1> <form action='play.php' method='POST'> <input id='btn__reset' type='submit' name='restart' value='Restart Game' /> </form>"; return $message; } } }
bca7a514ccd2371981ee1d60f62b60c1acda8e6e
[ "Markdown", "PHP" ]
4
Markdown
veggiepilot/game_show_app
e9c3b4ba4e689bb349e92ee04fcef08f4e38bd05
70a89e8ff9df5340422d5dafb41dfa19e3883f8f
refs/heads/master
<repo_name>ghostfeng/YFCategory<file_sep>/README.md # YFCategory 这里总结了UIKit和Foundation的一些常用的分类,可以用作工具 <file_sep>/YFCategory.podspec Pod::Spec.new do |s| s.name = 'YFCategory' s.version = '0.0.5' s.summary = 'Some commonly used category.' s.homepage = 'https://github.com/ghostfeng/YFCategory' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'LiuYongfeng' => '<EMAIL>' } s.source = { :git => 'https://github.com/ghostfeng/YFCategory.git', :tag => s.version } s.source_files = 'YFCategory/YFCategory.h' s.public_header_files = 'YFCategory/YFCategory.h' s.ios.deployment_target = '8.0' s.requires_arc = true s.subspec 'Foundation' do |ss| ss.source_files = 'YFCategory/Foundation/*.{h,m}' ss.public_header_files = 'YFCategory/Foundation/*.h' end s.subspec 'UIKit' do |ss| ss.source_files = 'YFCategory/UIKit/*.{h,m}' ss.public_header_files = 'YFCategory/UIKit/*.h' end s.subspec 'Photos' do |ss| ss.source_files = 'YFCategory/Photos/*.{h,m}' ss.public_header_files = 'YFCategory/Photos/*.h' end s.frameworks = 'Foundation','UIKit','Photos' end
0da5841d9849089424f1e0dae7d14561de4d58dc
[ "Markdown", "Ruby" ]
2
Markdown
ghostfeng/YFCategory
2d932651a38ff8023d33108f44feae8ce445f5bc
acb6d1e2d9bf7c847ec59cf015917a0d3c158577
refs/heads/master
<repo_name>ryangrunest/SecondSaturday<file_sep>/README.md # SecondSaturday Website for Second Saturday, a non-profit in Portland, OR <file_sep>/SecondSaturday/blog/models.py from django.db import models # Create your models here. class Blog(models.Model): blog_author = models.CharField(max_length=50) blog_text = models.TextField() pub_date = models.DateTimeField('date published')<file_sep>/SecondSaturday/blog/views.py # from django.shortcuts import render # from django.http import HttpResponse # # Create your views here. # def index(request): # return HttpResponse("Hello, world. You're at the blog index.") from blog.models import Blog from blog.serializers import BlogSerializer from rest_framework import generics class BlogListCreate(generics.ListCreateAPIView): queryset = Blog.objects.all() serializer_class = BlogSerializer<file_sep>/SecondSaturday/blog/urls.py from django.urls import path from . import views urlpatterns = [ path('api/blog/', views.BlogListCreate.as_view() ), ]
f2209f1df4338e838f3526d24914a87133141bde
[ "Markdown", "Python" ]
4
Markdown
ryangrunest/SecondSaturday
4ec49ab8aeba87ca1031433abd8458bf0f2c08aa
93da17d6ea4b6d2880dc92d1e9f492c0b0bb794b
refs/heads/master
<file_sep>/* Todo List App */ window.onload = function () { //declaring variables for the following; let form = document.getElementById("form"); let input = document.getElementById("input"); let btn = document.getElementById("btn"); let list = document.getElementById("list"); let btnClr = document.getElementById("btnClr"); let id = 1; let liItem = ""; let todoList = []; //button event listener, gets activated when clicked btn.addEventListener("click", addTodoItem); //list event listener list.addEventListener("click", boxChecked); //event listener for clear list btnClr.addEventListener("click", clearList); // input.addEventListener("keydown", addTodoItem); if (localStorage.length < 0) { btnClr.style.display = "none"; //hiding clear btn console.log("button"); } //checking localStorage has data if(localStorage.length <= 0) { btnClr.style.display = "none"; } //adding to-do items to list function addTodoItem() { //when value gets entered, the here button enables if(input.value === "") { alert("You must enter some value!"); } else { if(list.style.borderTop === "") { console.log("here!") list.style.borderTop = "2px solid white"; btnClr.style.display = "inline"; } //allows the user to input text let text = input.value; let item = `<li id="li-${id}">${text}<input id="box-${id}" class="checkboxes" type="checkbox"></li>`; list.insertAdjacentHTML('beforeend', item); liItem = {item: text, checked: false}; todoList.push(liItem); id++; addToLocalStorage(); form.reset(); } } //adding string through style to list item function boxChecked(event) { const element = event.target; if (element.type === "checkbox") { element.parentNode.style.textDecoration = "line-through"; todoList = JSON.parse(localStorage.getItem("todoList")); todoList[element.id.split('-')[1] - 1].checked = element.checked.toString(); localStorage.setItem("todoList", JSON.stringify(todoList)); } } //adding data to local storage function addToLocalStorage() { if (typeof (Storage) !== "undefined") { localStorage.setItem("todoList", JSON.stringify(todoList)); } else { alert("browser doesn't support local storage!"); } } //display all todo list elements together in order to display the list function displayList() { list.style.borderTop = "2px solid white"; todoList = JSON.parse(localStorage.getItem("todoList")); todoList.forEach(function (element) { console.log(element.item) let text = element.item; let item = `<li id="li-${id}">${text}<input id="box-${id}" class="checkboxes" type="checkbox"></li>`; list.insertAdjacentHTML("beforeend", item); //if there is a checked box, then style will be implemented if (element.checked) { let li = document.getElementById("li-" + id); li.style.textDecoration = "line-through"; li.childNodes[1].checked = element.checked; } id++; }); } //clearing list event listener function clearList() { todoList = []; localStorage.clear(); list.innerHTML = ""; btnClr.style.display = "none"; list.style.borderTop = ""; } } /* Quote Generator App */ //using math function of getting randome quotes from twitter site below function genQuote() { let randNum = Math.floor(Math.random() * 8) + 1; document.getElementById('quote').innerHTML = quotes[randNum]; let tweetQuote = quotes[randNum].split(' ').join('%20'); tweetQuote = tweetQuote.split('<br>').join(''); tweetQuote = "https://twitter.com/intent/tweet?text=" + tweetQuote.split('"').join('') $('.twitter-share-button').attr('href', tweetQuote); } //listing some good quotes let quotes = ["The Greatest Teacher, Failure is" - "Yoda", "\"Fear leads to self-doubt which is the worst enemy of creativity.\" - <NAME>", "\"Only those who dare to fail greatly can ever achieve greatly.\"- <NAME>", "\"All our dreams can come true, if we have the courage to pursue them.\"- <NAME>", "\"Imitation is not just the sincerest form of flattery - it's the sincerest form of learning.\"- <NAME>", "\"There are no facts, only interpretations.\"- <NAME>", "\"If you always put limit on everything you do, physical or anything else. It will spread into your work and into your life. There are no limits. There are only plateaus, and you must not stay there, you must go beyond them.\"- <NAME>", "\"In the midst of movement and chaos, keep stillness inside of you.\" - <NAME>", ]; /* Weather App */ //using constant elements for all. const iconElement = document.querySelector(".weather-icon"); const tempElement = document.querySelector(".temperature-value p"); const descElement = document.querySelector(".temperature-description p"); const locationElement = document.querySelector(".location p"); const notificationElement = document.querySelector(".notification"); const weather = {}; //the temperature should only be measured in celcius weather.temperature = { unit : "celsius" } //declaring constant value for kelvin const KELVIN = 273; const key = "<KEY>"; //implementing location and it will block the weather display for user unitl it allows it to display and will need to refesh the page if('geolocation' in navigator){ navigator.geolocation.getCurrentPosition(setPosition, showError); }else{ notificationElement.style.display = "block"; notificationElement.innerHTML = "<p>Browser doesn't Support Geolocation</p>"; } //fetching positions of the user's location function setPosition(position){ let latitude = position.coords.latitude; let longitude = position.coords.longitude; getWeather(latitude, longitude); } //else it will display error if no location identified function showError(error){ notificationElement.style.display = "block"; notificationElement.innerHTML = `<p> ${error.message} </p>`; } //the location is identified from below link function getWeather(latitude, longitude){ let api = `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${key}`; fetch(api) .then(function(response){ let data = response.json(); return data; }) //calculating and converting ferhenheit to celcius .then(function(data){ weather.temperature.value = Math.floor(data.main.temp - KELVIN); weather.description = data.weather[0].description; weather.iconId = data.weather[0].icon; weather.city = data.name; weather.country = data.sys.country; }) //displaying the weather .then(function(){ displayWeather(); }); } //displaying location with weather function displayWeather(){ iconElement.innerHTML = `<img src="symbols/${weather.iconId}.png"/>`; tempElement.innerHTML = `${weather.temperature.value}°<span>C</span>`; descElement.innerHTML = weather.description; locationElement.innerHTML = `${weather.city}, ${weather.country}`; } //formula to convert farenheit to celicus function celsiusToFahrenheit(temperature){ return (temperature * 9/5) + 32; } tempElement.addEventListener("click", function(){ if(weather.temperature.value === undefined) return; if(weather.temperature.unit == "celsius"){ let fahrenheit = celsiusToFahrenheit(weather.temperature.value); fahrenheit = Math.floor(fahrenheit); tempElement.innerHTML = `${fahrenheit}°<span>F</span>`; weather.temperature.unit = "fahrenheit"; } else { tempElement.innerHTML = `${weather.temperature.value}°<span>C</span>`; weather.temperature.unit = "celsius" } }); /* Image setting in gallery */ // Image count function is used to find the number of image onjects in image arrays imgCount = () => { return image.length; } // The function below is used to find the number of images which is fit on single row of the gallery maxImgPLine = () => { let size = window.innerWidth; // Setting the viewport width to less than 600px, and placinng only one image per row /* Math.round function tells the width percentage of the viewport and it is divided by 100px, to calculate the number of 100 px needed in the images to fit in 80% width */ if(size < 600){ return 1; }else { let num = Math.round((size * 0.8) / 180); // If the number of px is less than one then, fix only one image in a row else, fix maximum of 6 images in a row if (num < 1) { return 1; }else{ if(num < 6){ return num; }else{ return 6; } } } } // The function below is used to find out how many images should be put on a line imgPerLine = () => { if (maxImgPLine() === 1){ return 1; }else { let value; let max = Math.floor(maxImgPLine()); // Cancelling the interference of iterator z with other for loops // For loop takes maximum of 1/3 part of maximum line size for (z = 0; z < Math.round(imgCount() / 3); z++) { // If the loop takes off 1 image from maximum per iteration until the total number of images is evenly divisible by the number found if((imgCount() % (max - z)) === 0){ value = (max - z); } } // If no image is identified then, it will use the maximum size of the line if(!value){ value = max; } // If maximum size of line is used then, take half of the line else return to down if(value > max / 2) { value = max / 2; } return Math.floor(value); } } // Below function describes the total number of images that can be stored in a line lineTotal = () => { return Math.ceil(imgCount() / imgPerLine()); } // Build gallery function places images lines in the gallery function buildGallery() { let current; let next; let gallery = document.getElementById("gallery"); // emptying the galllery gallery.innerHTML = ""; /* For every line required, add the HTML to the gallery this means, total number of line starts at 1 and i started counting from 0 so, i need one less than the line total Fetching the gallery */ for(i = 0; i <= (lineTotal() - 1); i++){ current = gallery.innerHTML; // Adding this html to the end of it and the gallery with old items ir replaced by new one // The div class is creating serveral rows in grid which has several rows of images with description box and text // The description text box in div class uses i as identifier next = current + "<div class =\"row\" id=\"grid-" + i + "\"></div><div class = \"descBox\"><div class=\"descText\" id=\"descBox-" + i + "\"></div>"; gallery.innerHTML = next; } } // The fill gallery function fills each line with number of images function fillGallery() { let current; let num = 0; // The for loop uses iterator i-- for total line-1 as i started coutning from 0 not 1 // Each line of images is filled in the grid for(i = 0; i <= (lineTotal() - 1); i++){ let grid = document.getElementById("grid-" + i); // Getting contents of the lineto be added in html and put both items back in // This creates buttons for images, clicks for descriptions from images as arrays of the objects // Every image is responsible for title section due to hover due to use of boostraap for(j = 0; j <= (imgPerLine() - 1); j++){ current = grid.innerHTML; grid.innerHTML = current + "<div class=\"col\"><button id=\"img" + (num) + "\" onclick=\"addDescription(" + num + ", " + i + ")\"><img src=\"" + image[num].src + "\" class=\"img-fluid\" alt=\"Responsive image\"><div class=\"middle\">" + image[num].title + "</div></button><div class=\"triangle-up\" id=\"tri" + num + "\"></div></div>"; num++; } } } // Opening description box and adding requried portfolio items as description function addDescription(num, line) { // Fetching the required box, based on images in gallery line let box = document.getElementById("descBox-" + line); let newContent = ""; // If the images have links, include it in the contents of the description box // Else refer the image in object object array and attributes such as .desc or .title if(image[num].link) { newContent = "<h2>" + image[num].title + "</h2><p>" + image[num].desc + "</p><p>" + image[num].date + "</p><div class=\"icon\"><a href=\"" + image[num].link + "\"><i class=\"fab fa-github\" aria-hidden=\"true\"></i></a></div>"; } else { newContent = "<h2>" + image[num].title + "</h2><p>" + image[num].desc + "</p><p>" + image[num].date + "</p>"; } // There are 3 possibilities for how the content should be entered in the gallery // If the current box is closed then, fill in the inner boxes with required contents if(!box.style.maxHeight) { box.innerHTML = newContent; // For every line close description box for(i = 0; i <= (lineTotal() - 1); i++){ document.getElementById("descBox-" + i).style.maxHeight = null; } // Hiding all pointers, that point to other images for(i = 0; i <= (imgCount() - 1); i++){ document.getElementById("tri" + i).style.opacity = "0"; } // Showing the pointer corresponding to image clicked document.getElementById("tri" + num).style.opacity = "1"; // Showing the description box under the image clicked //if the clicked box was open and already had the content in it box.style.maxHeight = box.scrollHeight + "px"; } else if (box.style.maxHeight === box.scrollHeight + "px" && box.innerHTML === newContent) { box.style.maxHeight = null;// Close the box for(i = 0; i <= (imgCount() - 1); i++){ //hide all pointers again document.getElementById("tri" + i).style.opacity = "0"; } // Otherwise (the box is open but has the wrong content) } else { box.style.maxHeight = null; //close the box for(i = 0; i <= (imgCount() - 1); i++){//hide all image pointers document.getElementById("tri" + i).style.opacity = "0"; } // The window is waiting for the box to close, put in the new content, then open the box and show the corresponding pointer window.setTimeout(function() {box.innerHTML = newContent; box.style.maxHeight = box.scrollHeight + "px"; document.getElementById("tri" + num).style.opacity = "1";}, 260); } } // Collapse portfolio function is used to close all boxes in the portfolio and scrolling the portfolio away // To do so, close every line of coressponding portfolio away and for each image hid its pointer function collapsePortfolio() { for(i = 0; i <= (lineTotal() - 1); i++){ document.getElementById("descBox-" + i).style.maxHeight = null; } for(i = 0; i <= (imgCount() - 1); i++){ document.getElementById("tri" + i).style.opacity = "0"; } } // Copy text function puts my email on the clipboard to copy if clicked by the user and tip text gets successful if written // This function is taken from https://developer.mozilla.org/en-US/docs/Web/API/Clipboard/writeText function copyText() { navigator.clipboard.writeText("<EMAIL>").then(function() { let tip = document.getElementById("tiptext"); let tipbox = document.getElementById("tip") tipbox.style.transform = "scale(1.1) translateX(.4rem)"; tip.innerHTML = "Copied!" window.setTimeout(function() {tipbox.style.transform = "scale(1) translateX(0)"}, 800); document.getElementById("mail").addEventListener("mouseleave", function() {window.setTimeout(function() {tip.innerHTML = "Copy E-mail"}, 200)}); }, function() { // Alert occurs when the written information is failed and message is displayed as cannot copy alert("Sorry, cannot copy."); }); }
46a06c69415824a30e27088ef7fc0c53d0509027
[ "JavaScript" ]
1
JavaScript
rootvi97/rootvi_19438739_AS_2
f3f0f6195e07e2d6e9b919ab737c6708a7230441
bd0d981da8595874f9a775f3536bf7aa946778ab
refs/heads/master
<file_sep>if ! grep "export ROS_HOSTNAME=racecar" ~/.bashrc ; then echo -e "\nexport ROS_HOSTNAME=racecar" >> ~/.bashrc echo "export ROS_MASTER_URI=http://racecar:11311" >> ~/.bashrc fi if ! grep "192.168.1.100 racecar" /etc/hosts ; then echo -e "\n192.168.1.100 racecar" >> /etc/hosts fi <file_sep>Download models from Google drive https://drive.google.com/drive/folders/128RIyyfZ6gFGVfDhojuN9wENw2Z3u_zC <file_sep>#!/usr/bin/env python import rospy import math from sensor_msgs.msg import Joy from ackermann_msgs.msg import AckermannDriveStamped #BUTTON MAPPING # X [2] = Flip steering # Y [3] = Fine steering mode (-1 to 1 -> -0.5 to 0.5) # A [0] = Switch driving mode (default = RT+LT, alternate = RT-LT) # B [1] = No function # LB [4] = Brake # RB [5] = Brake #AXIS MAPPING # LT [2] = throttle forward/reverse (-1 to 1) # RT [5] = throttle forward (-1 to 1) # L [0] = steering control (-1 to 1) # L [1] = No function #deals with LT RT starting at zero by waiting to write thrusters until both axes have been updated controllerInitializationStarted = False #allows for two step start (LT RT to 1 and then back to 0) controllerInitialized = False #global vars with default values set #vars for flipping steering lastSteeringState = 0 #in order to look for rising edge on button steeringState = -1 #vars for switching driving mode lastThrottleState = 0 #in order to look for rising edge on button throttleState = True #true means adding throttles (no reverse), false means reverse enabled lastFineSteeringState = 0 fineSteeringState = True #true means -1 to 1, false means -0.5 to 0.5 (rads in simulation) #helper function to map values def map(input, inMin, inMax, outMin, outMax): output = (input - inMin) * (outMax - outMin) / (inMax - inMin) + outMin return output def JoyCB(data): #Use global/static vars global controllerInitializationStarted global controllerInitialized global lastSteeringState global steeringState global lastThrottleState global throttleState global lastFineSteeringState global fineSteeringState #steering direction if(data.buttons[2] != lastSteeringState and lastSteeringState == 0): steeringState = -steeringState rospy.logdebug("Changing steering direction") lastSteeringState = data.buttons[2] #driving mode if(data.buttons[0] != lastThrottleState and lastThrottleState == 0): throttleState = not throttleState rospy.logdebug("Changing driving mode") lastThrottleState = data.buttons[0] #fine steering mode if(data.buttons[3] != lastFineSteeringState and lastFineSteeringState == 0): fineSteeringState = not fineSteeringState rospy.logdebug("Changing steering mode") lastFineSteeringState = data.buttons[3] #apply modificaitons to throttle based on drive mode selection #acceptible values for physical jetson car are +-5 (not in m/s) for now if not controllerInitialized: throttleVal = 0 if(controllerInitializationStarted and data.axes[2] == 1 and data.axes[5] == 1): #controller should be corrected by now controllerInitialized = True elif(data.axes[2] == -1 and data.axes[5] == -1): controllerInitializationStarted = True elif throttleState: throttleVal = map(data.axes[5], 1, -1, 0, 2) + map(data.axes[2], 1, -1, 0, 2) #range is 0 to 4 else: throttleVal = map(data.axes[5], 1, -1, 0, 2) - map(data.axes[2], 1, -1, 0, 2) #range is -2 to 2 # #handle braking if applied (doesn't correlate to anything in simulation) # if(data.buttons[4] == 1 or data.buttons[5] == 1): # throttleVal = 6 #out of range value triggers active brake in ARC1 firmware #apply modifications to steering based on steering mode selection if fineSteeringState: steeringVal = data.axes[0] #range is -1 to 1 else: steeringVal = data.axes[0]/2 #range is -0.5 to 0.5 msg = AckermannDriveStamped(); msg.header.stamp = rospy.Time.now() msg.header.frame_id = "base_link" msg.drive.acceleration = 0; #drive acceleration unknown msg.drive.speed = throttleVal msg.drive.jerk = 0; #jerk unknown msg.drive.steering_angle = steeringVal*steeringState #steering state is 1 or -1 to flip steering if needed msg.drive.steering_angle_velocity = 0 #angle velocity unknown pub.publish(msg) rospy.init_node("joy_teleop") rospy.Subscriber("joy", Joy, JoyCB) pub = rospy.Publisher('controller/ackermann_cmd', AckermannDriveStamped, queue_size=1) rospy.spin() #keep node from closing
ca2a0ce254bde021644bf7371e3d73737f6cece5
[ "Markdown", "Python", "Shell" ]
3
Shell
FoMothrRussa/jetson_car
3aced75424efda190b108a9dbc33607481f71164
ef2a721ae5985a2eb995cb18a94be50bc058966f
refs/heads/master
<repo_name>axynos/LembituKrediit-Reloaded<file_sep>/src/io/github/axynos/LembituKrediitReloaded/SLAPI.java package io.github.axynos.LembituKrediitReloaded; import io.github.axynos.LembituKrediitReloaded.LKRManager; import io.github.axynos.LembituKrediitReloaded.LembituKrediitMain; public class SLAPI { private static LembituKrediitMain plugin = LKRManager.getPlugin(); public static void saveBalances() { for(String p : LKRManager.getBalanceMap().keySet()) { plugin.getConfig().set("balance."+ p, LKRManager.getBalanceMap().get(p)); } plugin.saveConfig(); } public static void loadBalances() { if(!plugin.getConfig().contains("balance")) return; for(String s : plugin.getConfig().getConfigurationSection("balance").getKeys(false)) { LKRManager.setBalance(s, plugin.getConfig().getDouble("balance." + s)); } } } <file_sep>/README.md -# LembituKrediit-Reloaded LembituKrediitReloaded SRC Authors: <NAME> "AxynoS" Kruus - framework coding, documentation, gambling update <NAME> "Tharix" Peedimaa - coding the gambling update and //TODO Primary: - Code the gambling update. Secondary: - Code cleanup and optimization. - Add offline/online if statement. - Add UUID support for publishing. - Add database support. //LembituKastid - GUI: -- /lk kast --- Opens InventoryGUI --- Displays chests & keys(tripwire hook) --- Left click key to open chest ---- Display different rewards(0.2, 0.2, 0.2, 0.3, 0.4, 0.5, 0.6 0.8 1.0 seconds) ---- User rewarded with the item ---- Chest and key removed Economy: - EssentialsECO/LembituKrediit™ -- VERY high price on EssentialsECO, pretty small price on LembituKrediit.<file_sep>/src/io/github/axynos/LembituKrediitReloaded/PlayerJoin.java package io.github.axynos.LembituKrediitReloaded; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; public class PlayerJoin implements Listener{ @EventHandler public void onJoin(PlayerJoinEvent event){ if(LKRManager.hasAccount(event.getPlayer().getName())) return; LKRManager.setBalance((event.getPlayer().getName()), 0D); SLAPI.saveBalances(); } } <file_sep>/src/io/github/axynos/LembituKrediitReloaded/onInventoryClick.java package io.github.axynos.LembituKrediitReloaded; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.inventory.InventoryClickEvent; public class onInventoryClick { //Makes sure you don't have to put item back. @EventHandler public void onInventoryClick(InventoryClickEvent event){ Player player = (Player) event.getWhoClicked(); if(!ChatColor.stripColor(event.getInventory().getName()).equalsIgnoreCase("LembituKastid")) return; player.sendMessage("Java is a cunt"); event.setCancelled(true); if(event.getCurrentItem() == null || event.getCurrentItem().getType() == Material.AIR || !event.getCurrentItem().hasItemMeta()){ player.closeInventory(); } if(event.getCurrentItem().getType() == Material.CHEST){ player.closeInventory(); player.sendMessage(ChatColor.GREEN + "Java is a bitch"); } switch(event.getCurrentItem().getType()) { case CHEST: player.sendMessage("This is a bitch isnt it"); break; case PAPER: player.sendMessage("Nigga fuck yo shit."); default: break; } } }
523e6491bbd08abe8e61faf6852ddd078527e051
[ "Markdown", "Java" ]
4
Java
axynos/LembituKrediit-Reloaded
ad0c1f69b1ee0516fcfa5d4fcbc994237ce14a73
a6c1ad1849b25e0c29037a8b645168b11461d58a
refs/heads/master
<repo_name>DoKuNu/AngularJS<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/components/dashboard.component.ts import { Component, OnInit } from '@angular/core'; import { Config } from '../config'; import { Router } from '@angular/router'; import { StudentItem } from "../models/student.item"; import { StudentService } from "../services/students.service"; @Component({ selector: 'dashboard-page', templateUrl: 'app/partials/components/dashboard.component.html', providers: [StudentService], }) export class DashboardComponent implements OnInit { studentsList: StudentItem[] = []; constructor( private router: Router, private studentService: StudentService ){}; gotoStudentDetails(student: StudentItem): void { let id = ['/detail', student.id]; this.router.navigate(id); }; ngOnInit(): void { this.studentService.getStudents().then(studentsList => this.studentsList = studentsList); }; }<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/services/in-memory-data.service.ts // Gérénation d'une API "in memory" : à propos du service HTTP https://goo.gl/S6imGs import { InMemoryDbService } from 'angular-in-memory-web-api'; import { StudentItem } from "../models/student.item"; // Export de l'API "in memory" export class InMemoryDataService implements InMemoryDbService { createDb() { // Cette variable définie le contenu de l'API et son adresse let studentsDb = [ new StudentItem({id: 1, firstName: 'Pierre', lastName: 'Stone', state: 2}), new StudentItem({id: 2, firstName: 'Sophie', lastName: 'Bourdon', state: 3}), new StudentItem({id: 3, firstName: 'Jacques', lastName: 'Rakchy', state: 2}), new StudentItem({id: 4, firstName: 'Julie', lastName: 'Bicoule', state: 1}), new StudentItem({id: 5, firstName: 'Charles', lastName: 'Violon', state: 1}), new StudentItem({id: 6, firstName: 'Claire', lastName: 'Obscure', state: 1}), ]; return {studentsDb}; } } <file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/components/edit.student.component.ts import { Component, OnInit } from '@angular/core'; import { Config } from '../config'; import { StudentItem } from "../models/student.item"; import { StudentService } from "../services/students.service"; @Component({ selector: 'edit-student-page', templateUrl: 'app/partials/components/edit.student.component.html', providers: [StudentService], }) export class EditStudentComponent implements OnInit { selectedStudent: StudentItem; newStudent: StudentItem; studentsList: StudentItem[]; constructor( private studentService: StudentService ){}; onSelect(student: StudentItem){ this.selectedStudent = student; }; // Création d'un fonction pour ajouter une entrée dans l'API addNewStudent(newStudent: any): void { // Vérification de la variable à ajouter if (!newStudent) { return; } // Appel de la fonction create() du service this.studentService.create(this.newStudent) // Appel de la fonction .then() : ajout de la nouvell entrée .then(newStudent => { this.studentsList.push(this.newStudent); this.resetInput(); }); } resetInput(){ this.newStudent = {id: 0, firstName: '', lastName: '', state: 1} } getStudents(): void { this.studentService.getStudents().then(students => this.studentsList = students); } ngOnInit(): void { this.getStudents(); this.resetInput(); } }<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/directives/student.details.directive.ts // Création d'une directive : à propos des directives https://goo.gl/fGh7QS import {Component, Input, Output, EventEmitter} from "@angular/core"; import { Config } from '../config'; import {StudentItem} from "../models/student.item"; @Component({ selector: 'student-item', templateUrl: 'app/partials/directives/student.details.component.html', }) export class StudentDirective { editBtn = Config.EDIT_BTN; state1 = Config.STATE1; state2 = Config.STATE2; state3 = Config.STATE3; @Input() student: StudentItem; @Output() sendStudentDetail = new EventEmitter(); onSelect(event: Event){ this.sendStudentDetail.emit(this.student); } }<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/models/student.item.ts // Création d'un model de données : à propos des models https://goo.gl/DsFwMk export class StudentItem { public id: number; public firstName: string; public lastName: string; public state: number; constructor(data: any){ this.id = data.id; this.firstName = data.firstName; this.lastName = data.lastName; this.state = data.state; } }<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/main.ts // A propos de la configuration de l'application : https://goo.gl/iK45yx // Importer platformBrowserDynamic pour initier l'application import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; // Importer la class du component principal import { AppModule } from './app.module'; // Bootstraper le component platformBrowserDynamic().bootstrapModule(AppModule); <file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/directives/add.student.directive.ts // Création d'une directive : à propos des directives https://goo.gl/fGh7QS import {Component, Input, Output, EventEmitter} from "@angular/core"; import { Config } from '../config'; import { StudentItem } from "../models/student.item"; @Component({ selector: 'add-student', templateUrl: 'app/partials/directives/add.student.component.html', }) export class AddStudentDirective { add = Config.ADD; addStudent = Config.ADD_STUDENT; firstName = Config.FIRSTNAME; lastName = Config.LASTNAME; state = Config.STATE; selectedStudent: StudentItem; @Input() newStudent: StudentItem; @Output() sendNewStudentData = new EventEmitter(); addNewStudent(event: any){ this.sendNewStudentData.emit(this.newStudent); }; }<file_sep>/README.md # AngularJS Cours #SUPDEWEB AngularJS Démo avec Angular 2 réalisée lors du cours d'AngularJS à #SUPDEWEB Surtout là pour tester Github via Windows <file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/components/student.details.component.ts import {Component,Input, OnInit} from "@angular/core"; import { ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import { StudentService } from '../services/students.service' import { Config } from '../config'; import { StudentItem } from "../models/student.item"; @Component({ selector: 'student-detail', templateUrl: 'app/partials/components/student.details.component.html', }) export class StudentDetailsComponent implements OnInit{ edit = Config.EDIT; deleteBtn = Config.DELETE_BTN; firstName = Config.FIRSTNAME; lastName = Config.LASTNAME; saveBtn = Config.SAVE; backBtn = Config.BACK; singleStudent: StudentItem; @Input() newStudent: StudentItem; studentsList: StudentItem[] = []; constructor( private studentService: StudentService, private route: ActivatedRoute, private location: Location ) {} ngOnInit(): void { this.route.params.forEach((params: Params) => { let id = +params['id']; this.studentService.getStudent(id).then(singleStudent => this.singleStudent = singleStudent); }) }; save(): void { this.studentService.update(this.singleStudent) .then(() => this.goBack()); } // Création d'une fonction pour supprimer une entrée : à propos du service HTTP https://goo.gl/S6imGs delete(studentId: any): void { // Selection du service this.studentService // Appel de la fonction .delete() prenant l'ID en paramètre .delete(studentId) // Appel de la fonction .then() : suppréssion de l'entrèe .then(() => { this.studentsList = this.studentsList.filter(h => h != studentId); if (this.singleStudent.id == studentId) { this.singleStudent = null; } this.location.back(); }); } goBack(): void { this.location.back(); } }<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/services/students.service.ts import { Injectable } from '@angular/core'; // Importer des services Headers et Http : à propos du service HTTP https://goo.gl/S6imGs import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { StudentItem } from "../models/student.item"; @Injectable() export class StudentService { // Récupération de l'adresse de l'API private studentsUrl = 'app/studentsDb'; // Création d'une variable pour la gestion des erreurs private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); }; // Ajout du service Http dans le constructor constructor(private http: Http) { }; // Modification de la fonction getStudent getStudents(): Promise<StudentItem[]> { // Utilisation de la fonction .get() return this.http.get(this.studentsUrl) // Appel de la promesse .toPromise() // Utilisation de la fonction .then() : alimentation du jeu de données .then(response => response.json().data as StudentItem[]) // Capture du code erreur .catch(this.handleError); }; // Création d'un fonction pour mettre une entrée update(student: StudentItem): Promise<StudentItem> { // Définition de l'adresse de l'appel API const url = `${this.studentsUrl}/${student.id}`; // Envoie de la requête HTTP return this.http // Définition du header de la requête .put(url, JSON.stringify(student), { headers: new Headers({'Content-Type': 'application/json'}) }) // Appel de la promesse .toPromise() // Utilisation de la fonction .then() : modification de l'objet student .then(() => student) // Capture du code erreur .catch(this.handleError); }; // Création d'un fonction pour ajouter une entrée create(newStudent: StudentItem): Promise<StudentItem> { // Envoie de la requête HTTP return this.http // Définition du header de la requête .post(this.studentsUrl, JSON.stringify(newStudent), {headers: new Headers({'Content-Type': 'application/json'})}) // Appel de la promesse .toPromise() // Utilisation de la fonction .then() : ajout d'une nouvelle entrée .then(res => res.json().data) // Capture du code erreur .catch(this.handleError); }; // Création d'une fonction pour supprimer une entrée delete(id: number): Promise<void> { // Définition de l'adresse pour l'appel API const url = `${this.studentsUrl}/${id}`; // Envoie de la requête HTTP return this.http // Appel de la fonction .delete() prenant l'url et la définition du Header en paramètre .delete(url, {headers: new Headers({'Content-Type': 'application/json'})}) // Appel de la promesse .toPromise() // Utilisation de la fonction .then() : rien à faire .then(() => null) // Capture du code erreur .catch(this.handleError); } getStudent(id: number): Promise<StudentItem> { return this.getStudents().then(students => students.find(singleStudent => singleStudent.id === id)); }; };<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/app.routing.ts // Création des routes : à propos des routes https://goo.gl/FbKYVx import { ModuleWithProviders } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { EditStudentComponent } from './components/edit.student.component'; import { DashboardComponent } from './components/dashboard.component'; import { StudentDetailsComponent } from './components/student.details.component'; const appRoutes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: DashboardComponent }, { path: 'edit', component: EditStudentComponent }, // Définition d'un paramêtre ID dans la route : à propos des routes dynamiques https://goo.gl/Qe53YN { path: 'detail/:id', component: StudentDetailsComponent } ]; export const Router: ModuleWithProviders = RouterModule.forRoot(appRoutes);<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/app.component.ts import { Component } from '@angular/core'; import { Config } from './config'; @Component({ selector: 'my-app', templateUrl: 'app/partials/app.component.html', }) export class AppComponent { title = Config.APP_TITLE; text = Config.APP_SS_TITLE; }<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/directives/edit.student.directive.ts // Création d'une directive : à propos des directives https://goo.gl/fGh7QS import {Component, Input} from "@angular/core"; import { Config } from '../config'; import { StudentItem } from "../models/student.item"; @Component({ selector: 'edit-student', templateUrl: 'app/partials/directives/edit.student.component.html', }) export class EditStudentDirective { edit = Config.EDIT; deleteBtn = Config.DELETE_BTN; firstName = Config.FIRSTNAME; lastName = Config.LASTNAME; @Input() selectedStudent: StudentItem; }<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/config.ts export class Config{ // Création des constantes de l'application public static get APP_TITLE(): string{ return 'Student Platform'}; public static get APP_SS_TITLE(): string{ return 'Liste des étudiants'}; public static get EDIT_BTN(): string{ return 'Modifier'}; public static get DELETE_BTN(): string{ return 'Supprimer'}; public static get EDIT(): string{ return 'Editer'}; public static get STATE(): string{ return 'Etat'}; public static get STATE1(): string{ return 'Présent'}; public static get STATE2(): string{ return 'En retard'}; public static get STATE3(): string{ return 'Absent'}; public static get ADD(): string{ return 'Ajouter'}; public static get ADD_STUDENT(): string{ return 'Ajouter un étudiant'}; public static get FIRSTNAME(): string{ return 'Prénom'}; public static get LASTNAME(): string{ return 'Nom'}; public static get SAVE(): string{ return 'Enregistrer'}; public static get BACK(): string{ return 'Retour'}; }<file_sep>/Desktop/SUPDEWEB/AngularJS/ANG2support-master/app/app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // Importer du modul HttpModul : à propos du service HTTP https://goo.gl/S6imGs import { HttpModule } from '@angular/http'; // Gérénation d'une API "in memory" import { InMemoryWebApiModule } from 'angular-in-memory-web-api'; import { InMemoryDataService } from './services/in-memory-data.service'; import { AppComponent } from './app.component'; import { EditStudentComponent } from './components/edit.student.component'; import { DashboardComponent } from './components/dashboard.component'; import { StudentDetailsComponent } from './components/student.details.component'; import { AddStudentDirective } from "./directives/add.student.directive"; import { EditStudentDirective } from "./directives/edit.student.directive"; import { StudentDirective } from "./directives/student.details.directive"; import { StudentService } from './services/students.service'; import { Router } from './app.routing'; @NgModule({ // Ajout du service HTTP et InMemoryWebApiModule imports: [ BrowserModule, FormsModule, HttpModule, InMemoryWebApiModule.forRoot(InMemoryDataService), Router ], declarations: [ AppComponent, EditStudentComponent, DashboardComponent, StudentDetailsComponent, AddStudentDirective, EditStudentDirective, StudentDirective ], providers: [ StudentService ], bootstrap: [ AppComponent ] }) export class AppModule { }
46132eb6a2dd66f02f250c6db2b59701e8d52523
[ "Markdown", "TypeScript" ]
15
TypeScript
DoKuNu/AngularJS
4fcf7baeaa3e229754167d8e69330c41feea1b14
0251e80181229d8e4ac46cc7e8f6d7b19155a9df
refs/heads/main
<file_sep># CRUD-Servlets A simple one-page application to manage books in Books database. Available operations are: Create, Read, Insert and Delete. Created with technologies: Java EE, JDBC, MySql <file_sep>package zad1.service; import zad1.DbHelper; import zad1.models.Book; import java.awt.image.DataBuffer; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class BookService { Connection connection; public BookService(){ this.connection = DbHelper.getConnection("login", "qwerty12345"); } public List<Book> getAll() throws SQLException { Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT * from " + DbHelper.tableName); ArrayList<Book> bookResults = new ArrayList<>(); while(rs.next()){ bookResults.add(new Book(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getDouble(4))); } rs.close(); statement.close(); return bookResults; } public Optional<Book> getBookById(int id) throws SQLException{ Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT * from" +DbHelper.tableName + " where " + DbHelper.id + "=" + id); rs.next(); statement.close(); rs.close(); return Optional.of(new Book(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getDouble(4))); } public void insertBook(Book b) throws SQLException{ Statement statement = connection.createStatement(); statement.executeUpdate("insert into " + DbHelper.tableName +"("+DbHelper.author+", " + DbHelper.book+ ", " + DbHelper.price + ") values (" + "'" + b.getAuthor() +"'" + ", " +"'" + b.getName() + "'" + ", " +"'" + b.getPrice() +"'" + ")"); statement.close(); } public void updateBook(Book b) throws SQLException{ PreparedStatement statement = connection.prepareStatement( "update " + DbHelper.tableName + " set " + DbHelper.author + "=?, " + DbHelper.book + "=?, " + DbHelper.price + "=? where " + DbHelper.id + "=" + b.getId() ); statement.setString(1, b.getAuthor()); statement.setString(2, b.getName()); statement.setString(3, Double.toString(b.getPrice())); statement.executeUpdate(); statement.close(); } public void deleteBook(int id) throws SQLException{ PreparedStatement statement = connection.prepareStatement("delete from " + DbHelper.tableName + " where " + DbHelper.id + "=" + id); statement.executeUpdate(); statement.close(); } }
4d4069bc80bc757e9e8b881a7e92097ff83f933c
[ "Markdown", "Java" ]
2
Markdown
s18966/CRUD-Servlets
83b759cf2717c86be3b24be73bcfb1e33d0112df
e76016864e96737dd30d7cf4f54434072b8290dc
refs/heads/master
<repo_name>Mayo19/peppercorn<file_sep>/app/models/champion.rb class Champion < ActiveRecord::Base end <file_sep>/secrets.rb RIOT_KEY="<KEY>" <file_sep>/app/controllers/api/v1/champion_controller.rb module Api module V1 class ChampionsController < Api::BaseController def index champions = Champion.all render json: champions end def show champion_id = params[:champion_id] end end end end <file_sep>/app/serializers/champion_serializer.rb class ChampionSerializer < ActiveModel::Serializer attributes :id, :name, :tags, :rito_id 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 rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) champion = HTTParty.get("https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?champData=image,tags&api_key=<KEY>") champion["data"].each do |a, champion_data| name = champion_data["name"] title = champion_data["title"] tags = champion_data["tags"] image = champion_data["image"]["full"] rito_id = champion_data["champ_id"] Champion.find_or_create_by!(name: name, title: title, tags: tags, image: image, rito_id: rito_id) end
c3460ddb328c342a54a2853132987b6b7f26fc99
[ "Ruby" ]
5
Ruby
Mayo19/peppercorn
b2befc238b643eac8c3687b19f56078fbebd2b9d
bf192946852de9866cd792d8eaba8263cad2fac4
refs/heads/master
<file_sep> import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.catalina.Session; import java.util.*; /** * Servlet implementation class for Servlet: Billhandler * */ public class Billhandler extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L; /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public Billhandler() { super(); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String event = ""; String return_Val = ""; String item_Name=""; String billNo = ""; System.out.println("Entering in doget method of BillHandlerservlet........."); try{ event = request.getParameter("Event"); item_Name =request.getParameter("ITEM_NAME"); /* if(event==null){ BillDAO obj = new BillDAO(); billNo = obj.getBillNumber(); System.out.println("inside NEWBILL EVENT...billnumber::"+billNo); request.setAttribute("BILL_Number",billNo); request.getRequestDispatcher("Billing_Screen.jsp").forward(request, response); } */ if(event.equalsIgnoreCase("LOADUNIT")){ BillDAO DAO = new BillDAO(); return_Val = DAO.loadUnit(item_Name); } if(event.equalsIgnoreCase("NEWBILL")){ System.out.println("inside NEWBILL EVENT..."); BillDAO obj = new BillDAO(); billNo = obj.getBillNumber(); System.out.println("inside NEWBILL EVENT...billnumber::"+billNo); request.setAttribute("BILL_Number",billNo); request.getRequestDispatcher("Billing_Screen.jsp").forward(request, response); } if(event.equalsIgnoreCase("LOADSELLPRICE")){ BillDAO DAO = new BillDAO(); return_Val = DAO.loadSellPrice(item_Name); } if(event.equalsIgnoreCase("PREV_BILL")){ System.out.println("GouthamMonica"); BillDAO DAO = new BillDAO(); return_Val = DAO.loadSellPrice(item_Name); } if(event.equalsIgnoreCase("LOADALL")){ BillDAO DAO = new BillDAO(); return_Val = DAO.loadall(item_Name); } if(event.equalsIgnoreCase("VALIDATE_ITEM")){ BillDAO DAO = new BillDAO(); return_Val = DAO.validateItem(item_Name); } if(event.equalsIgnoreCase("PRINT_SAVE")){ String val =request.getParameter("Item_Name_1"); System.out.println("val-->"+val); System.out.println("PRINT_SAVE"); Enumeration item_name =request.getParameterNames(); while(item_name.hasMoreElements()){ String ID = (String)item_name.nextElement(); System.out.println("ID-->"+ID); } BillDAO DAO = new BillDAO(); } }catch(Exception e) { System.out.println("heck somethink went wrong........."); e.printStackTrace(); } finally{ response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println(return_Val); } } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("Inside dopost of billhandler servlet...."); String event =""; int total_count =0; String Bill_no = "1601100000"; int bill_seq =0; String item_name = ""; String item_id = ""; String item_Qty = ""; String item_Unit = ""; String item_price = ""; ArrayList ordered_List = null; HashMap data_Map = null; String return_Flag = ""; HttpSession session = request.getSession(); session.setAttribute("USER_NAME", "PARADOX"); String user = (String)session.getAttribute("USER_NAME"); HashMap lMap = new HashMap(); String totalAmt = ""; String billNo = "0"; StringBuffer itemBuffer = new StringBuffer(); try{ ordered_List = new ArrayList(); event = request.getParameter("Event"); System.out.println("Event posted is:::"+event); /*if(event==null){ BillDAO obj = new BillDAO(); billNo = obj.getBillNumber(); System.out.println("inside NEWBILL EVENT...billnumber::"+billNo); request.setAttribute("BILL_Number",billNo); request.getRequestDispatcher("Billing_Screen.jsp").forward(request, response); }*/ if(event.equals("PRINT_SAVE")){ //NEW CHANGE START HERE String billNumber = null; String itemId[] =null; String itemName[]=null; String quantity[] =null; String Unit[] =null; String price[]=null; String MRP[] = null; String total[] =null; String billTotal=null; String totalBilledAmt = null; //NEW CHANGE ENDS HERE billNumber=request.getParameter("BillNumber"); System.out.println("billNumber::"+billNumber); lMap.put("billNumber", billNumber); itemId=request.getParameterValues("t_itemID"); System.out.println("itemId::"+itemId); lMap.put("itemId", itemId); itemName=request.getParameterValues("t_ItemName"); System.out.println("itemName::"+itemName); for(int i =0;i<itemName.length;i++){ System.out.println("itemName values::"+itemName[i]); } lMap.put("itemName", itemName); quantity=request.getParameterValues("t_Quantity"); System.out.println("t_Quantity::"+quantity); lMap.put("quantity", quantity); Unit=request.getParameterValues("t_Unit"); System.out.println("Unit::"+Unit); lMap.put("Unit", Unit); total=request.getParameterValues("t_currTotal"); System.out.println("total row Amount::"+total); lMap.put("total", total); MRP=request.getParameterValues("t_Price"); System.out.println("MRP::"+MRP); lMap.put("MRP", MRP); price=request.getParameterValues("t_sellPrice"); System.out.println("SELLING_price::"+price); lMap.put("sellprice", price); totalBilledAmt = request.getParameter("Bill_Total"); System.out.println("totalBilledAmt ::"+totalBilledAmt); lMap.put("totalBilledAmt", totalBilledAmt); lMap.put("INPUTTER_ID",user); System.out.println("HashMap for BILLDAO::"+lMap); BillDAO obj = new BillDAO(); return_Flag = obj.add_Billrecord(lMap); if(return_Flag.equals("TRUE")){ request.setAttribute("BILL_STATUS", "TRUE"); //CREATING NEW BILL NUMBER.. billNo = obj.getBillNumber(); System.out.println("inside NEWBILL EVENT...billnumber::"+billNo); request.setAttribute("BILL_Number",billNo); request.getRequestDispatcher("Billing_Screen.jsp").forward(request, response); } else{ billNo = obj.getBillNumber(); System.out.println("inside NEWBILL EVENT...billnumber::"+billNo); request.setAttribute("BILL_Number",billNo); request.setAttribute("BILL_STATUS", "FAIL"); request.getRequestDispatcher("Billing_Screen.jsp").forward(request, response); } } /* if(request.getParameter("TOTAL_BILL_COUNT")!=null) total_count =Integer.parseInt(request.getParameter("TOTAL_BILL_COUNT")); lMap.put("TOTAL_COUNT",total_count); totalAmt = request.getParameter("total_amount"); lMap.put("TOTAL_AMOUNT",totalAmt); lMap.put("INPUTTER_ID",user); lMap.put("BILL_NUMBER",billNo); System.out.println("Total no of bill items Inside dopost of billhandler servlet...."+total_count); if(total_count>0){ //ordered_List.add(0,total_count); //ordered_List.add(1,user); for(int i = 0;i<total_count;i++){ data_Map = new HashMap(); data_Map.put("BILL_SEQ",i); data_Map.put("BILL_NUM",Bill_no); item_name = request.getParameter("Item_Name_"+i); data_Map.put("Item_Name_"+i, item_name); item_Qty = request.getParameter("Quantity_"+i); data_Map.put("Quantity_"+i,item_Qty); item_Unit = request.getParameter("Unit_"+i); data_Map.put("Unit_"+i,item_Unit); item_price = request.getParameter("Price_"+i); data_Map.put("Price_"+i,item_price); data_Map.put("Item_id_"+i,"1234"); ordered_List.add(data_Map); } lMap.put("BILL_LIST",ordered_List); System.out.println("ArrayList with HashMap values--->"+ordered_List); System.out.println("ArrayList size--->"+ordered_List.size()); BillDAO obj = new BillDAO(); return_Flag = obj.add_Billrecord(lMap); if(return_Flag.equals("TRUE")){ request.setAttribute("BILL_STATUS", "TRUE"); request.getRequestDispatcher("Billing_Screen.jsp").forward(request, response); } else{ request.setAttribute("BILL_STATUS", "FAIL"); request.getRequestDispatcher("Billing_Screen.jsp").forward(request, response); } }else{ System.out.println("Total no of bill items Inside dopost of billhandler servlet...."+total_count); System.out.println("There is Nothing Inside bill depost of billhandler servlet...."); request.setAttribute("BILL_STATUS", "NO_BILL_END"); request.getRequestDispatcher("Billing_Screen.jsp").forward(request, response); } } */else if(event.equalsIgnoreCase("NEWBILL")){ System.out.println("inside NEWBILL EVENT..."); BillDAO obj = new BillDAO(); billNo = obj.getBillNumber(); System.out.println("inside NEWBILL EVENT...billnumber::"+billNo); request.setAttribute("BILL_Number",billNo); request.getRequestDispatcher("Billing_Screen.jsp").forward(request, response); } //AJAXCALL FOR LOADING ALL UNIT else if(event.equalsIgnoreCase("LOADITEM_NAME")){ System.out.println("Ajaxcall in GET method of MasterServlet-->"+request.getParameter("value")); String value = request.getParameter("value"); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); BillDAO DAO = new BillDAO(); itemBuffer.append(DAO.itemBuffer(value)); System.out.println("itemBuffer-->"+itemBuffer); out.println(itemBuffer.toString()); } //Added for QuickSearch Screen else if(event.equalsIgnoreCase("LOAD_QUICKVIEW_GRID")){ System.out.println("Ajaxcall in doPost method of Billhandler-->"+request.getParameter("value")); String value = request.getParameter("value"); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); BillDAO DAO = new BillDAO(); itemBuffer.append(DAO.returnQuickSearch(value)); System.out.println("itemBuffer-->"+itemBuffer); out.println(itemBuffer.toString()); } }catch(Exception e){ System.out.println("Something went wrong...."+e); e.printStackTrace(); } } } <file_sep>import java.util.HashMap; import java.sql.*; public class MasterDAO { /*public String AddItem(HashMap AdddataMap){ String returnFlag = "FAIL"; int itemid = 0; System.out.println("dataMap in AddItem-->"+AdddataMap); Connection conn =null; String query = "INSERT INTO ITEM_MASTER VALUES(?,?,?,?,?,SYSDATE(),?)"; //String query2 = "SELECT MAX(ITEM_NO) ITEM_NO FROM ITEM_MASTER"; int rSet = 0; int i =0; PreparedStatement psmt = null; System.out.println("dataMap in masterDAO by goutham-->"+AdddataMap); try{ conn = DBConnection.getConnection(); psmt = conn.prepareStatement(query); //psmt = conn.prepareStatement(query2); rSet = psmt.executeUpdate(); //while(rSet.next()){ //System.out.println("Inside item_id generator query"+rSet); //itemid = rSet.getInt("ITEM_NO"); //System.out.println("ItemId is -->"+itemid); //} //psmt.setInt(1,(rSet.getInt(itemid))); psmt.setInt(1,Integer.parseInt(NullCheck((String)AdddataMap.get("Item_No")))); psmt.setString(2,NullCheck((String)AdddataMap.get("Item_Name"))); psmt.setString(3,NullCheck((String)AdddataMap.get("UNIT"))); psmt.setString(4,NullCheck((String)AdddataMap.get("M_R_P"))); psmt.setString(5,NullCheck((String)AdddataMap.get("rate"))); psmt.setString(6,NullCheck((String)AdddataMap.get("Dealer"))); i=psmt.executeUpdate(); if(i>0){ System.out.println(i+"No of rows Inserted ......"); returnFlag = "SUCCESS"; }else{ System.out.println("no of rows Inserted see error log......"); returnFlag = "FAIL"; } }catch(Exception e){ System.out.println("Something went wrong during Add item........"); e.printStackTrace(); }finally{ try { if(psmt!=null){ psmt.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("returnFlag in AddItem-->"+returnFlag); return returnFlag; }*/ public String AddItem(HashMap AdddataMap) { String returnFlag = "FAIL"; int itemid = 0 ; int sai; Connection conn =null; ResultSet rSet = null; PreparedStatement psmt = null; PreparedStatement psmt2 = null; try{ System.out.println("Inside Try block of add method"); String query_for_add="SELECT MAX(ITEM_NO) ITEM_NO FROM ITEM_MASTER"; conn = DBConnection.getConnection(); psmt = conn.prepareStatement(query_for_add); rSet = psmt.executeQuery(); if(rSet.next()){ System.out.println("inside first IF rset"); System.out.println("Inside item_id generator query"+rSet); itemid = rSet.getInt(1); System.out.println("ItemId is -->"+itemid); } if(itemid>0) { int i =0; System.out.println("Inside item_id greater than 0 condition"); sai= itemid+1; System.out.println("Value of Sai-->"+sai); String query_for_add2="INSERT INTO ITEM_MASTER VALUES(?,UPPER(?),?,UPPER(?),SYSDATE(),UPPER(?),?)"; conn = DBConnection.getConnection(); psmt2 = conn.prepareStatement(query_for_add2); psmt2.setInt(1,sai); psmt2.setString(2,NullCheck((String)AdddataMap.get("Item_Name"))); psmt2.setString(3,NullCheck((String)AdddataMap.get("M_R_P"))); psmt2.setString(4,NullCheck((String)AdddataMap.get("UNIT"))); psmt2.setString(5,NullCheck((String)AdddataMap.get("Dealer"))); psmt2.setString(6,NullCheck((String)AdddataMap.get("rate"))); i=psmt2.executeUpdate(); if(i>0) { returnFlag = "SUCCESS"; } } else { System.out.println("Inside Else"); } } catch(Exception e){ System.out.println("Something went wrong during Add item........"); e.printStackTrace(); }finally{ try { if(psmt!=null){ psmt.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("returnFlag in AddItem-->"+returnFlag); return returnFlag; } public String AddItem_popup(HashMap AdddataMap) { String returnFlag_popup = "FAIL"; int itemid = 0 ; int sai; System.out.println("dataMap in AddItem-->"+AdddataMap); Connection conn =null; ResultSet rSet = null; PreparedStatement psmt = null; PreparedStatement psmt2 = null; System.out.println("dataMap in masterDAO by goutham-->"+AdddataMap); try{ System.out.println("Inside Try block of add method"); String query_for_add="SELECT MAX(ITEM_NO) ITEM_NO FROM ITEM_MASTER"; conn = DBConnection.getConnection(); psmt = conn.prepareStatement(query_for_add); rSet = psmt.executeQuery(); if(rSet.next()){ System.out.println("inside first IF rset"); System.out.println("Inside item_id generator query"+rSet); itemid = rSet.getInt(1); System.out.println("ItemId is -->"+itemid); } if(itemid>0) { int i =0; System.out.println("Inside item_id greater than 0 condition"); sai= itemid+1; System.out.println("Value of Sai-->"+sai); String query_for_add2="INSERT INTO ITEM_MASTER VALUES(?,UPPER(?),?,UPPER(?),SYSDATE(),UPPER(?),?)"; conn = DBConnection.getConnection(); psmt2 = conn.prepareStatement(query_for_add2); psmt2.setInt(1,sai); psmt2.setString(2,NullCheck((String)AdddataMap.get("Item_Name"))); psmt2.setString(3,NullCheck((String)AdddataMap.get("M_R_P"))); psmt2.setString(4,NullCheck((String)AdddataMap.get("UNIT"))); psmt2.setString(5,NullCheck((String)AdddataMap.get("Dealer"))); psmt2.setString(6,NullCheck((String)AdddataMap.get("rate"))); i=psmt2.executeUpdate(); if(i>0) { returnFlag_popup = "SUCCESS"; } } else { System.out.println("Inside Else"); } } catch(Exception e){ System.out.println("Something went wrong during Add item........"); e.printStackTrace(); }finally{ try { if(psmt!=null){ psmt.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("returnFlag in AddItem-->"+returnFlag_popup); return returnFlag_popup; } private int getInt(int sai) { // TODO Auto-generated method stub return 0; } public String NullCheck(String input){ if(input==null || input==""){ input="000000"; } return input; } public String EditItem(HashMap editdatamap) { String modifyreturnFlag = "FAIL"; System.out.println("dataMap in EditItem-->"+editdatamap); Connection conn =null; String query = "UPDATE ITEM_MASTER SET ITEM_NAME=UPPER(?),ITEM_UNIT=UPPER(?),ITEM_MRP=?,ITEM_RATE=?,ITEM_DATE=SYSDATE(),ITEM_DEALER=UPPER(?) WHERE ITEM_NO=?"; ResultSet rSet = null; int i =0; PreparedStatement psmt = null; try{ conn = DBConnection.getConnection(); psmt = conn.prepareStatement(query); System.out.println(psmt); System.out.println("After connection Establish"); psmt.setString(1,NullCheck((String)editdatamap.get("Item_Name_2"))); psmt.setString(2,NullCheck((String)editdatamap.get("UNIT_2"))); psmt.setString(3,NullCheck((String)editdatamap.get("M_R_P_2"))); psmt.setString(4,NullCheck((String)editdatamap.get("rate_2"))); psmt.setString(5,NullCheck((String)editdatamap.get("Dealer_2"))); psmt.setInt(6,Integer.parseInt(NullCheck((String)editdatamap.get("Item_No_2")))); i=psmt.executeUpdate(); if(i>0){ System.out.println(i+"No of rows Inserted ......"); modifyreturnFlag = "SUCCESS"; }else{ System.out.println("No rows Inserted for edit table see error log......"); modifyreturnFlag = "FAIL"; } }catch(Exception e){ System.out.println("Something went wrong during Add item........"); e.printStackTrace(); }finally{ try { if(psmt!=null){ psmt.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("returnFlag in EditItem-->"+modifyreturnFlag); return modifyreturnFlag; } public String DeleteItem(HashMap Deletedatamap){ String deletereturnFlag = "FAIL"; Connection conn =null; String query = "DELETE FROM ITEM_MASTER WHERE ITEM_NO=?"; ResultSet rSet = null; int i =0; PreparedStatement psmt = null; try{ conn = DBConnection.getConnection(); psmt = conn.prepareStatement(query); psmt.setInt(1,Integer.parseInt(NullCheck((String)Deletedatamap.get("Item_No_4")))); i=psmt.executeUpdate(); if(i>0){ System.out.println(i+"No of rows Deleted ......"); deletereturnFlag = "SUCCESS"; }else{ System.out.println("no of rows Deleted see error log......"); deletereturnFlag = "FAIL"; } }catch(Exception e){ System.out.println("Something went wrong during Delete item........"); e.printStackTrace(); }finally{ try { if(psmt!=null){ psmt.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("returnFlag in Delete method-->"+deletereturnFlag); return deletereturnFlag; } public HashMap gettotbill(HashMap gettotbillmap) { String returnFlag = "FAIL"; System.out.println("gettotbillmap in EditItem-->"+gettotbillmap); HashMap gettotal = new HashMap(); Connection conn =null; String query = "SELECT SUM(BILL_AMT) TOT_AMT FROM BILL_MASTER WHERE INPUT_DT between ? and ?"; ResultSet rSet = null; int i =0; int sum=0; PreparedStatement psmt = null; try{ conn = DBConnection.getConnection(); psmt = conn.prepareStatement(query); System.out.println(psmt); System.out.println(query); System.out.println("After connection Establish"); psmt.setString(1,((String)gettotbillmap.get("fromdate"))); psmt.setString(2,((String)gettotbillmap.get("todate"))); rSet=psmt.executeQuery(); while(rSet.next()) { sum=rSet.getInt(1); System.out.println("Total is "+sum); System.out.println("gettotbillmap in GetTotalBillAmount-->"+gettotbillmap); } gettotal.put("tot", sum); }catch(Exception e){ System.out.println("Something went wrong during Bill Total........"); e.printStackTrace(); }finally{ try { if(psmt!=null){ psmt.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("gettotbillmap in EditItem-->"+gettotbillmap); return gettotal; } public StringBuffer itemBuffer(String dataMap){ int count = 0; StringBuffer itemBuffer = null; System.out.println("dataMap in AddItem-->"+dataMap); Connection conn =null; String query = "SELECT ITEM_NAME FROM ITEM_MASTER WHERE ITEM_NAME LIKE ('%"+dataMap+"%')"; ResultSet rSet = null; int i =0; PreparedStatement psmt = null; try{ itemBuffer = new StringBuffer(); conn = DBConnection.getConnection(); psmt = conn.prepareStatement(query); System.out.println("Query for for search item--->"+query); rSet=psmt.executeQuery(); while(rSet.next()){ if(count==0) { itemBuffer.append(rSet.getString("ITEM_NAME")); count++; } else{ itemBuffer.append("~"); itemBuffer.append(rSet.getString("ITEM_NAME")); } } }catch(Exception e){ System.out.println("Something went wrong during itemBuffer........"); e.printStackTrace(); }finally{ try { if(rSet!=null){ rSet.close(); } if(psmt!=null){ psmt.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("itemBuffer in itemBuffer method-->"+itemBuffer); return itemBuffer; } public String loadall_maint(String dataString){ StringBuffer Unit_Buffer = null; String Unit =""; System.out.println("dataString in loadUnit-->"+dataString); Connection conn =null; String query = "SELECT ITEM_NO,ITEM_NAME,ITEM_MRP,ITEM_RATE,ITEM_UNIT,ITEM_DEALER FROM ITEM_MASTER WHERE ITEM_NAME = ?"; ResultSet rSet = null; int i =0; PreparedStatement psmt = null; try{ Unit_Buffer = new StringBuffer(); conn = DBConnection.getConnection(); psmt = conn.prepareStatement(query); System.out.println("Query for for search item--->"+query); psmt.setString(1,dataString); rSet=psmt.executeQuery(); while(rSet.next()){ Unit_Buffer.append(rSet.getString("ITEM_NO")); Unit_Buffer.append("~"); Unit_Buffer.append(rSet.getString("ITEM_NAME")); Unit_Buffer.append("~"); Unit_Buffer.append(rSet.getString("ITEM_MRP")); Unit_Buffer.append("~"); Unit_Buffer.append(rSet.getString("ITEM_RATE")); Unit_Buffer.append("~"); Unit_Buffer.append(rSet.getString("ITEM_UNIT")); Unit_Buffer.append("~"); Unit_Buffer.append(rSet.getString("ITEM_DEALER")); } Unit = Unit_Buffer.toString(); }catch(Exception e){ System.out.println("Something went wrong during Unit. OF LOADALL......."); e.printStackTrace(); }finally{ try { if(rSet!=null){ rSet.close(); } if(psmt!=null){ psmt.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("Unit in Unit method-->"+Unit); return Unit; } public String changepass(HashMap changepass) { String passwordreturnFlag = "FAIL"; Connection conn =null; ResultSet rSet = null; int i =0; String db_hint = null; PreparedStatement psmt = null; PreparedStatement psmt1 = null; try{ System.out.println("Inside try"); String hint_query="SELECT HINT FROM USER_TABLE"; conn = DBConnection.getConnection(); psmt = conn.prepareStatement(hint_query); rSet=psmt.executeQuery(); if(rSet.next()) { db_hint=rSet.getString(1); System.out.println("Hint provided-->"+db_hint); } if(db_hint!= null) { System.out.println("inside 2nd if"); String l_db_hint=db_hint; System.out.println("l_db_hint-->"+l_db_hint); if(((String)changepass.get("new_pass1")).equalsIgnoreCase(((String)changepass.get("new_pass2")))) { String update_pass="UPDATE USER_TABLE SET PASSWORD=?,DATE=SYSDATE() WHERE HINT=?"; conn = DBConnection.getConnection(); psmt1 = conn.prepareStatement(update_pass); psmt1.setString(1,NullCheck((String)changepass.get("new_pass1"))); psmt1.setString(2,l_db_hint); i=psmt1.executeUpdate(); } } if(i>0){ System.out.println("Password Updated successFully ......"); passwordreturnFlag = "SUCCESS"; }else{ System.out.println("Password Update Fail......"); passwordreturnFlag = "FAIL"; } }catch(Exception e){ System.out.println("Something went wrong during change credential........"); e.printStackTrace(); }finally{ try { if(psmt!=null){ psmt.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("returnFlag in credential-->"+passwordreturnFlag); return passwordreturnFlag; } } <file_sep> import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Session; import com.sun.corba.se.spi.orbutil.fsm.Action; /** * Servlet implementation class for Servlet: MasterServlet * */ public class MasterServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L; /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public MasterServlet() { super(); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub StringBuffer itemBuffer = new StringBuffer(); String event = ""; String return_Val = ""; String item_Name=""; PrintWriter out = null; try{ out = response.getWriter(); event = request.getParameter("Event"); item_Name =request.getParameter("ITEM_NAME"); System.out.println("Ajaxcall in GET method of MasterServlet-->"+request.getParameter("value")); String value = request.getParameter("value"); if(event.equalsIgnoreCase("LOAD_NAME")){ response.setContentType("text/plain"); MasterDAO DAO = new MasterDAO(); itemBuffer.append(DAO.itemBuffer(value)); System.out.println("itemBuffer-->"+itemBuffer); return_Val=itemBuffer.toString(); } if(event.equalsIgnoreCase("LOADALL_MAINT")){ response.setContentType("text/plain"); MasterDAO DAO1 = new MasterDAO(); return_Val = DAO1.loadall_maint(item_Name); } }catch(Exception e) { e.printStackTrace(); } finally{ out.println(return_Val); } } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HashMap AdddataMap =new HashMap(); HashMap editdatamap = new HashMap(); HashMap Deletedatamap = new HashMap(); HashMap gettotbillmap = new HashMap(); HashMap changepass = new HashMap(); String returnFlag = "FAIL"; String modifyreturnFlag = "FAIL"; String deletereturnFlag = "FAIL"; String passwordreturnFlag = "FAIL"; String returnFlag_popup="FAIL"; String Event = request.getParameter("EVENT"); MasterDAO OBJ = new MasterDAO(); if(Event.equalsIgnoreCase("ADDITEM")) { System.out.println("Inside Master Servlet Add item event"); String Item_Name = request.getParameter("I_name"); String M_R_P = request.getParameter("M_R_P"); String rate = request.getParameter("rate"); String UNIT = request.getParameter("UNIT_1"); String Item_Date = request.getParameter("ITEM_DATE"); String Dealer = request.getParameter("Dealer_1"); if(Dealer.equalsIgnoreCase("")||Dealer.equalsIgnoreCase(null)) { System.out.println("inside null check"); Dealer="SBA"; } AdddataMap.put("Event",Event); AdddataMap.put("Item_Name",Item_Name); AdddataMap.put("M_R_P",M_R_P); AdddataMap.put("rate",rate); AdddataMap.put("UNIT",UNIT); AdddataMap.put("ITEM_DATE",Item_Date); AdddataMap.put("Dealer",Dealer); returnFlag = OBJ.AddItem(AdddataMap); System.out.println("return falg in master servlet::"+returnFlag); if(returnFlag.equalsIgnoreCase("SUCCESS")){ request.setAttribute("returnFlag", returnFlag); request.getRequestDispatcher("Maint.jsp").forward(request,response); } else{ request.setAttribute("returnFlag", returnFlag); request.getRequestDispatcher("Maint.jsp").forward(request,response); } } /* FOR ADD ITEM POP UP*/ else if(Event.equalsIgnoreCase("ADDITEM_POPUP")) { System.out.println("Inside Master Servlet Add item-POPUP event"); String Item_Name = request.getParameter("I_name"); String M_R_P = request.getParameter("M_R_P"); String rate = request.getParameter("rate"); String UNIT = request.getParameter("UNIT_1"); String Item_Date = request.getParameter("ITEM_DATE"); String Dealer = request.getParameter("Dealer_1"); System.out.println("Dealer Name-->popup"+Dealer); if(Dealer.equalsIgnoreCase("")||Dealer.equalsIgnoreCase(null)) { System.out.println("inside null check-popup"); Dealer="SBA"; } AdddataMap.put("Event",Event); AdddataMap.put("Item_Name",Item_Name); AdddataMap.put("M_R_P",M_R_P); AdddataMap.put("rate",rate); AdddataMap.put("UNIT",UNIT); AdddataMap.put("ITEM_DATE",Item_Date); AdddataMap.put("Dealer",Dealer); returnFlag_popup = OBJ.AddItem_popup(AdddataMap); System.out.println("return flag in POPUP master servlet::"+returnFlag_popup); if(returnFlag_popup.equalsIgnoreCase("SUCCESS")){ request.setAttribute("returnFlag_popup", returnFlag_popup); request.getRequestDispatcher("additem.jsp").forward(request,response); } else{ request.setAttribute("returnFlag_popup", returnFlag_popup); } } else if((Event.equalsIgnoreCase("SEARCHITEM"))) { String Search_Item_name = request.getParameter("item_Name_3"); String Item_No_2 = request.getParameter("I_no_2"); String Item_Name_2 = request.getParameter("I_name_2"); String M_R_P_2 = request.getParameter("M_R_P_2"); String rate_2 = request.getParameter("rate_2"); String UNIT_2 = request.getParameter("I_Unit_2"); String Dealer_2 = request.getParameter("I_Dealer_2"); if(Dealer_2.equalsIgnoreCase("")||Dealer_2.equalsIgnoreCase(null)) { System.out.println("inside null check"); Dealer_2="SBA"; } System.out.println("Search_Item_name-->"+Search_Item_name); editdatamap.put("Event",Event); editdatamap.put("Item_No_2",Item_No_2); editdatamap.put("Item_Name_2",Item_Name_2); editdatamap.put("M_R_P_2",M_R_P_2); editdatamap.put("rate_2",rate_2); editdatamap.put("UNIT_2",UNIT_2); //editdatamap.put("Item_Date_2",Item_Date_2); editdatamap.put("Dealer_2",Dealer_2); modifyreturnFlag= OBJ.EditItem(editdatamap); if(modifyreturnFlag.equalsIgnoreCase("SUCCESS")){ request.setAttribute("modifyreturnFlag", modifyreturnFlag); request.getRequestDispatcher("Maint.jsp").forward(request,response); } else{ response.sendRedirect("Maint.jsp"); } } /*Modify Item JSP form*/ else if((Event.equalsIgnoreCase("POPUP_MODIFYITEM"))) { String Search_Item_name = request.getParameter("item_Name_3"); String Item_No_2 = request.getParameter("I_no_2"); String Item_Name_2 = request.getParameter("I_name_2"); String M_R_P_2 = request.getParameter("M_R_P_2"); String rate_2 = request.getParameter("rate_2"); String UNIT_2 = request.getParameter("I_Unit_2"); //String Item_Date_2 = request.getParameter("ITEM_DATE"); String Dealer_2 = request.getParameter("I_Dealer_2"); if(Dealer_2.equalsIgnoreCase("")||Dealer_2.equalsIgnoreCase(null)) { System.out.println("inside null check"); Dealer_2="SBA"; } System.out.println("Search_Item_name-->"+Search_Item_name); editdatamap.put("Event",Event); editdatamap.put("Item_No_2",Item_No_2); editdatamap.put("Item_Name_2",Item_Name_2); editdatamap.put("M_R_P_2",M_R_P_2); editdatamap.put("rate_2",rate_2); editdatamap.put("UNIT_2",UNIT_2); editdatamap.put("Dealer_2",Dealer_2); modifyreturnFlag= OBJ.EditItem(editdatamap); if(modifyreturnFlag.equalsIgnoreCase("SUCCESS")){ request.setAttribute("modifyreturnFlag", modifyreturnFlag); request.getRequestDispatcher("Edit_item.jsp").forward(request,response); } else{ request.setAttribute("modifyreturnFlag", modifyreturnFlag); } } else if((Event.equalsIgnoreCase("DELETEITEM"))) { String Item_No_4 = request.getParameter("I_no_4"); Deletedatamap.put("Item_No_4",Item_No_4); deletereturnFlag= OBJ.DeleteItem(Deletedatamap); if(deletereturnFlag.equalsIgnoreCase("SUCCESS")){ request.setAttribute("deletereturnFlag", deletereturnFlag); request.getRequestDispatcher("Maint.jsp").forward(request,response); } else{ response.sendRedirect("Maint.jsp"); } } /*else if ((Event.equalsIgnoreCase("GETTOTALBILL"))) { String fromdate = request.getParameter("from_date"); String todate = request.getParameter("to_date"); gettotbillmap.put("Event",Event); gettotbillmap.put("fromdate",fromdate); gettotbillmap.put("todate",todate); gettotbillmap= OBJ.gettotbill(gettotbillmap); int gettotal = (Integer)gettotbillmap.get("tot"); request.setAttribute("gettotal", gettotal); request.setAttribute("fromdate", fromdate); request.setAttribute("todate", todate); request.getRequestDispatcher("Maint.jsp").forward(request, response); }*/ else if((Event.equalsIgnoreCase("GETPASSCHANGE"))) { System.out.println("Inside MasterServlet"); String Hint_maint = request.getParameter("Hint_maint"); String new_pass1 = request.getParameter("new_pass1"); String new_pass2 = request.getParameter("new_pass2"); changepass.put("Event",Event); changepass.put("Hint_maint",Hint_maint); changepass.put("new_pass1",<PASSWORD>); changepass.put("new_pass2",<PASSWORD>); passwordreturnFlag= OBJ.changepass(changepass); if(passwordreturnFlag.equalsIgnoreCase("SUCCESS")){ request.setAttribute("passwordreturnFlag", passwordreturnFlag); request.getRequestDispatcher("Maint.jsp").forward(request,response); } else{ response.sendRedirect("Maint.jsp"); } } } }<file_sep>function ViewAddItem(){ document.getElementById("section").style.visibility ="hidden"; document.getElementById("section1").style.visibility =""; document.getElementById("section2").style.visibility ="hidden"; document.getElementById("section3").style.visibility ="hidden"; document.getElementById("section4").style.visibility ="hidden"; document.getElementById("section5").style.visibility ="hidden"; document.getElementById("section6").style.visibility ="hidden"; } function ViewEditItem(){ document.getElementById("section").style.visibility ="hidden"; document.getElementById("section1").style.visibility ="hidden"; document.getElementById("section2").style.visibility =""; document.getElementById("section3").style.visibility ="hidden"; document.getElementById("section4").style.visibility ="hidden"; document.getElementById("section5").style.visibility ="hidden"; document.getElementById("section6").style.visibility ="hidden"; } function ViewViewItem(){ document.getElementById("section").style.visibility ="hidden"; document.getElementById("section1").style.visibility ="hidden"; document.getElementById("section2").style.visibility ="hidden"; document.getElementById("section3").style.visibility =""; document.getElementById("section4").style.visibility ="hidden"; document.getElementById("section5").style.visibility ="hidden"; document.getElementById("section6").style.visibility ="hidden"; } function ViewDeleteItem(){ document.getElementById("section").style.visibility ="hidden"; document.getElementById("section1").style.visibility ="hidden"; document.getElementById("section2").style.visibility ="hidden"; document.getElementById("section3").style.visibility ="hidden"; document.getElementById("section4").style.visibility =""; document.getElementById("section5").style.visibility ="hidden"; document.getElementById("section6").style.visibility ="hidden"; } function ViewPassordChange(){ document.getElementById("section").style.visibility ="hidden"; document.getElementById("section1").style.visibility ="hidden"; document.getElementById("section2").style.visibility ="hidden"; document.getElementById("section3").style.visibility ="hidden"; document.getElementById("section4").style.visibility ="hidden"; document.getElementById("section5").style.visibility =""; document.getElementById("section6").style.visibility ="hidden"; } function ViewSalesDetails(){ document.getElementById("section").style.visibility ="hidden"; document.getElementById("section1").style.visibility ="hidden"; document.getElementById("section2").style.visibility ="hidden"; document.getElementById("section3").style.visibility ="hidden"; document.getElementById("section4").style.visibility ="hidden"; document.getElementById("section5").style.visibility ="hidden"; document.getElementById("section6").style.visibility =""; } function mandate_check_add(){ var a=document.getElementById("I_name").value; var b=document.getElementById("M_R_P").value; var c=document.getElementById("rate").value; var d=document.getElementById("UNIT_1").value; if(a=="") { alert("Please Enter the Item Name and then submit"); return false; } else if(b=="") { alert("Please Enter the MRP and then submit"); return false; } else if(c=="") { alert("Please Enter the Price and then submit"); return false; } else if(d=="") { alert("Please Enter the Unit and then submit"); return false; } return true; } function mandate_check_edit(){ var e=document.getElementById("I_name_2").value; var f=document.getElementById("M_R_P_2").value; var g=document.getElementById("rate_2").value; var h=document.getElementById("I_Unit_2").value; if(e=="") { alert("Please Enter the Item Name and then submit"); return false; } else if(f=="") { alert("Please Enter the MRP and then submit"); return false; } else if(g=="") { alert("Please Enter the Price and then submit"); return false; } else if(h=="") { alert("Please Enter the Unit and then submit"); return false; } return true; } function AddItem_popup(){ if(mandate_check_add()) { document.getElementById("ADDITEMFORMPOPUP").submit(); } else { return false; } } function EditItem_popup(){ if(mandate_check_edit()) { document.getElementById("MODIFYITEMFORMPOPUP").submit(); } else { return false; } } function AddItem(){ if(mandate_check_add()) { document.getElementById("ADDITEMFORM").submit(); } else { return false; } } function EditItem(){ if(mandate_check_edit()) { document.getElementById("MODIFYITEMFORM").submit(); } else { return false; } } function gettotal(){ document.getElementById("GETTOTALBILLFORM").submit(); } function DeleteItem(){ document.getElementById("DELETEITEMFORM").submit(); } function Changepass(){ document.getElementById("GETPASSCHANGEFORM").submit(); } function loadScreen(){ var status = "<%=returnFlag%>"; document.getElementById("section1").style.visibility ="hidden"; document.getElementById("section2").style.visibility ="hidden"; document.getElementById("section3").style.visibility ="hidden"; document.getElementById("section4").style.visibility ="hidden"; document.getElementById("section5").style.visibility ="hidden"; document.getElementById("section6").style.visibility ="hidden"; if(status=="SUCCESS"){ alert("Record added successfully"); } if(status=="FAIL"){ alert("Record not added"); } } /* Used for Edit Item in Maintenance Screen */ var requestOBJ; function checkItemName(event) { var keyc = event.KeyCode || event.which; var value = document.getElementById("item_Name_2").value; //alert(value); var URL = "MasterServlet?Event=LOAD_NAME&value="+value; if(window.XMLHttpRequest){ requestOBJ = new XMLHttpRequest(); }else if(window.ActiveXObject){ requestOBJ= new ActivXCObject("Microsoft.XMLHTTP"); } try{ requestOBJ.onreadystatechange=processData2; requestOBJ.open("GET",URL,true); requestOBJ.send(); }catch(e){ alert("Something went wrong"); } } function processData2(){ var itemarray=""; var Tempvar=""; var pos; if(requestOBJ.readyState==4){ if(requestOBJ.status==200){ var responsetext= requestOBJ.responseText; responsetext= responsetext.replace("<xml>",""); responsetext= responsetext.replace("<xml>",""); if(responsetext.indexOf("~")>0){ //alert("responsetext::"+responsetext); itemarray = responsetext.split("~"); for(var i=0;i<itemarray.length;i++){ Tempvar += "'"; Tempvar += itemarray[i]; Tempvar += "',"; if(i==itemarray.length-1){ pos = Tempvar.lastIndexOf(","); Tempvar = Tempvar.substring(0,pos); } } }else{ if(responsetext!=""){ itemarray.push(responsetext); } } $( "#item_Name_2" ).autocomplete({ minLength:3, delay:500, source: itemarray,//this will added our billing items to dropdown autoFocus:true }); } } } function loadalldetails() { var URL=""; var item_Name=document.getElementById("item_Name_2").value; if(item_Name==""){ return false; } URL = "MasterServlet?Event=LOADALL_MAINT&ITEM_NAME="+item_Name; if(window.XMLHTTPRequest){ requestOBJ=new XMLHTTPRequest(); }else if(window.ActiveXObject){ requestOBJ= new ActivXCObject("Microsoft.XMLHTTP"); } try{ requestOBJ.onreadystatechange=processUnit2; requestOBJ.open("GET",URL,true); requestOBJ.send(); }catch(e){ alert("Somethink went wrong IN LOADALL_MAINT FUNCTION IN BILLVALIDATOR..."); } } function processUnit2(){ if(requestOBJ.readyState==4){ if(requestOBJ.status==200){ var item_Array=""; var responsetext= requestOBJ.responseText; //alert(responsetext); item_Array = responsetext.split("~"); //alert(item_Array); document.getElementById("I_no_2").value=item_Array[0]; document.getElementById("I_name_2").value=item_Array[1]; document.getElementById("M_R_P_2").value=item_Array[2]; document.getElementById("rate_2").value=item_Array[3]; document.getElementById("I_Unit_2").value=item_Array[4]; document.getElementById("I_Dealer_2").value=item_Array[5]; } } } /* End of search in Edit Item*/ /* Start of Search in View Item*/ var requestOBJ_View; function checkItemName_View(event) { var keyc = event.KeyCode || event.which; var value = document.getElementById("item_Name_3").value; var URL = "MasterServlet?Event=LOAD_NAME&value="+value; if(window.XMLHttpRequest){ requestOBJ_View = new XMLHttpRequest(); }else if(window.ActiveXObject){ requestOBJ_View= new ActivXCObject("Microsoft.XMLHTTP"); } try{ requestOBJ_View.onreadystatechange=processData3; requestOBJ_View.open("GET",URL,true); requestOBJ_View.send(); }catch(e){ alert("Something went wrong"); } } function processData3(){ var itemarray=""; var Tempvar=""; var pos; if(requestOBJ_View.readyState==4){ if(requestOBJ_View.status==200){ var responsetext= requestOBJ_View.responseText; responsetext= responsetext.replace("<xml>",""); responsetext= responsetext.replace("<xml>",""); if(responsetext.indexOf("~")>0){ itemarray = responsetext.split("~"); for(var i=0;i<itemarray.length;i++){ Tempvar += "'"; Tempvar += itemarray[i]; Tempvar += "',"; if(i==itemarray.length-1){ pos = Tempvar.lastIndexOf(","); Tempvar = Tempvar.substring(0,pos); } } }else{ if(responsetext!=""){ itemarray.push(responsetext); } } $( "#item_Name_3" ).autocomplete({ minLength:3, delay:500, source: itemarray,//this will added our billing items to dropdown autoFocus:true }); } } } function loadalldetails_View() { var URL=""; var item_Name=document.getElementById("item_Name_3").value; if(item_Name==""){ return false; } URL = "MasterServlet?Event=LOADALL_MAINT&ITEM_NAME="+item_Name; if(window.XMLHTTPRequest){ requestOBJ_View=new XMLHTTPRequest(); }else if(window.ActiveXObject){ requestOBJ_View= new ActivXCObject("Microsoft.XMLHTTP"); } try{ requestOBJ_View.onreadystatechange=processUnit3; requestOBJ_View.open("GET",URL,true); requestOBJ_View.send(); }catch(e){ alert("Somethink went wrong IN LOADALL FUNCTION IN BILLVALIDATOR..."); } } function processUnit3(){ if(requestOBJ_View.readyState==4){ if(requestOBJ_View.status==200){ var item_Array=""; var responsetext= requestOBJ_View.responseText; item_Array = responsetext.split("~"); document.getElementById("I_no_3").value=item_Array[0]; document.getElementById("I_name_3").value=item_Array[1]; document.getElementById("M_R_P_3").value=item_Array[2]; document.getElementById("rate_3").value=item_Array[3]; document.getElementById("I_Unit_3").value=item_Array[4]; document.getElementById("I_Dealer_3").value=item_Array[5]; } } } /*End of View Item contenct */ /* Start of Delete Item content*/ var requestOBJ; function checkItemName_Delete(event) { var keyc = event.KeyCode || event.which; var value = document.getElementById("item_Name_4").value; var URL = "MasterServlet?Event=LOAD_NAME&value="+value; if(window.XMLHttpRequest){ requestOBJ = new XMLHttpRequest(); }else if(window.ActiveXObject){ requestOBJ= new ActivXCObject("Microsoft.XMLHTTP"); } try{ requestOBJ.onreadystatechange=processData4; requestOBJ.open("GET",URL,true); requestOBJ.send(); }catch(e){ alert("Something went wrong"); } } function processData4(){ var itemarray=""; var Tempvar=""; var pos; if(requestOBJ.readyState==4){ if(requestOBJ.status==200){ var responsetext= requestOBJ.responseText; responsetext= responsetext.replace("<xml>",""); responsetext= responsetext.replace("<xml>",""); if(responsetext.indexOf("~")>0){ itemarray = responsetext.split("~"); for(var i=0;i<itemarray.length;i++){ Tempvar += "'"; Tempvar += itemarray[i]; Tempvar += "',"; if(i==itemarray.length-1){ pos = Tempvar.lastIndexOf(","); Tempvar = Tempvar.substring(0,pos); } } }else{ if(responsetext!=""){ itemarray.push(responsetext); } } $( "#item_Name_4" ).autocomplete({ minLength:3, delay:500, source: itemarray,//this will added our billing items to dropdown autoFocus:true }); } } } function loadalldetails_Delete() { var URL=""; var item_Name=document.getElementById("item_Name_4").value; if(item_Name==""){ return false; } URL = "MasterServlet?Event=LOADALL_MAINT&ITEM_NAME="+item_Name; if(window.XMLHTTPRequest){ requestOBJ=new XMLHTTPRequest(); }else if(window.ActiveXObject){ requestOBJ= new ActivXCObject("Microsoft.XMLHTTP"); } try{ requestOBJ.onreadystatechange=processUnit4; requestOBJ.open("GET",URL,true); requestOBJ.send(); }catch(e){ alert("Somethink went wrong IN LOADALL FUNCTION IN BILLVALIDATOR..."); } } function processUnit4(){ if(requestOBJ.readyState==4){ if(requestOBJ.status==200){ var item_Array=""; var responsetext= requestOBJ.responseText; item_Array = responsetext.split("~"); document.getElementById("I_no_4").value=item_Array[0]; document.getElementById("I_name_4").value=item_Array[1]; document.getElementById("M_R_P_4").value=item_Array[2]; document.getElementById("rate_4").value=item_Array[3]; document.getElementById("I_Unit_4").value=item_Array[4]; document.getElementById("I_Dealer_4").value=item_Array[5]; } } } <file_sep>$(document).ready(function() { $('.dropdown').on('show.bs.dropdown', function() { $(this).find('.dropdown-menu').first().stop(true, true).slideDown(); }); // Add slideUp animation to Bootstrap dropdown when collapsing. $('.dropdown').on('hide.bs.dropdown', function() { $(this).find('.dropdown-menu').first().stop(true, true).slideUp(); }); // tabs $('.common-tab li').click(function() { var tab_id = $(this).attr('data-tab'); $('.common-tab li').removeClass('current'); $('.tab-content').removeClass('current'); $(this).addClass('current'); $("#" + tab_id).addClass('current'); }); // matchHeight // $('.integrations-list p').matchHeight(); // $('.integrations-list h4').matchHeight(); }); $(function() { var Accordion = function(el, multiple) { this.el = el || {}; this.multiple = multiple || false; // Variables privadas var links = this.el.find('.link'); // Evento links.on('click', { el: this.el, multiple: this.multiple }, this.dropdown) } Accordion.prototype.dropdown = function(e) { var $el = e.data.el; $this = $(this), $next = $this.next(); $next.slideToggle(); $this.parent().toggleClass('open'); if (!e.data.multiple) { $el.find('.submenu').not($next).slideUp().parent().removeClass('open'); }; } var accordion = new Accordion($('#accordion'), false); // $('#color').colpick({ // layout: 'hex', // submit: 0, // color: 'auto', // colorScheme: 'light', // onChange: function(hsb, hex, rgb, fromSetColor) { // if (!fromSetColor) $('#color').val('#' + hex).css({ 'background': '#' + hex}); // // if (!fromSetColor) $('#color span').val('#' + hex).css({'color': '#' + hex }); // }, // onSubmit: function(hsb, hex, rgb, el) { // $('#color').colpickHide(); // } // }); }); // List with handle // Sortable.create(listWithHandle, { // handle: '.move', // animation: 1000 // }); // Sortable.create(listWithHandle, { // handle: '.signin-field', // animation: 1000 // });
fa5d48aa237244041742d403799725378393b62e
[ "JavaScript", "Java" ]
5
Java
magicwebsolutions/smartyPOS-BillPortal
5d82738c6272208abdd6f3ebafc4d5cc0ea1e882
ab082fe3066a4a7ac8bc0729129436dbe2f0dc63
refs/heads/master
<repo_name>ellethee/vim-mediawiki-editor<file_sep>/README.md # vim-mediawiki-editor Edit MediaWiki articles from the comfort of Vim, your favorite text editor! <p align="center"> <img src="https://raw.githubusercontent.com/aquach/vim-mediawiki-editor/master/examples/demo.gif"> </p> ## Installation vim-mediawiki-editor requires Vim compiled with python support and the [python `mwclient` library](https://github.com/mwclient/mwclient). You likely have Python support, but you can check with `vim --version | grep +python`. MacVim comes with Python support. If you get an error, try `pip install mwclient` to get the library. Once you have these, use your favorite Vim plugin manager to install `aquach/vim-mediawiki-editor`, or copy `plugin` and `doc` into your `.vim` folder. I recommend pairing this plugin with [mediawiki.vim](https://github.com/chikamichi/mediawiki.vim) for syntax highlighting and with [goyo.vim](https://github.com/junegunn/goyo.vim) for WriteRoom-esque editing. ## Usage vim-mediawiki-editor offers these commands: #### :MWRead <article-name> Loads the given article into the current buffer. ``` :MWRead Radish ``` #### :MWWrite [article-name] Writes the buffer back to the site. If you don't specify an article name, it defaults to the article you currently have open with `:MWRead`. After prompting you for the edit summary and major/minor edit, it will publish your work back to the site. #### :MWDiff [article-name] Diffs the current buffer against the hosted version of the article specified on the site. If you don't specify an article name, it defaults to the article you currently have open with `:MWRead`. #### :MWBrowse [article-name] Views the article specified in your configured browser. If you don't specify an article name, it defaults to the article you currently have open with `:MWRead`. ## Configuration If you don't specify these settings, vim-mediawiki-editor will prompt you when you first run a vim-mediawiki-editor command. #### g:mediawiki_editor_url The URL of the site you're editing. For the English wikipedia, that'd be `en.wikipedia.org`. #### g:mediawiki_editor_path The MediaWiki [script path](https://www.mediawiki.org/wiki/Manual:$wgScriptPath). For the wikipedias and other WMF wikis, this is `/w/`, but for other wikis it can be `/`, `/wiki/`, or some other value. #### g:mediawiki_editor_username Your account username. #### g:mediawiki_editor_password Your account password. I recommend putting the URL and username in your `.vimrc` and letting Vim ask for your password. ## Contributing This plugin is currently quite simple. Contributions, suggestions, and feedback are all welcomed! <file_sep>/plugin/mediawiki_editor.py from __future__ import print_function import sys try: import mwclient except ImportError: sys.stderr.write( 'mwclient not installed; install perhaps via' ' pip install mwclient.\n') raise from_cmdline = False try: __file__ from_cmdline = True except NameError: pass if not from_cmdline: import vim VALID_PROTOCOLS = ['http', 'https'] # Utility. def sq_escape(s): return s.replace("'", "''") def fn_escape(s): return vim.eval("fnameescape('%s')" % sq_escape(s)) def input(prompt, text='', password=False): vim.command('call inputsave()') vim.command("let i = %s('%s', '%s')" % (('inputsecret' if password else 'input'), sq_escape(prompt), sq_escape(text))) vim.command('call inputrestore()') return vim.eval('i') def var_exists(var): return bool(int(vim.eval("exists('%s')" % sq_escape(var)))) def get_from_config(var): if var_exists(var): return vim.eval(var) return None def get_from_config_or_prompt(var, prompt, password=False, text=''): c = get_from_config(var) if c is not None: return c else: resp = input(prompt, text=text, password=password) vim.command("let %s = '%s'" % (var, sq_escape(resp))) return resp def base_url(): return get_from_config_or_prompt('g:mediawiki_editor_url', "Mediawiki URL, like 'en.wikipedia.org': ") def site(): if site.cached_site: return site.cached_site scheme = get_from_config('g:mediawiki_editor_uri_scheme') if scheme not in VALID_PROTOCOLS: scheme = 'https' s = mwclient.Site((scheme, base_url()), path=get_from_config_or_prompt('g:mediawiki_editor_path', 'Mediawiki Script Path: ', text='/w/')) try: s.login( get_from_config_or_prompt('g:mediawiki_editor_username', 'Mediawiki Username: '), get_from_config_or_prompt('g:mediawiki_editor_password', 'Mediawiki Password: ', password=True) ) except mwclient.errors.LoginError as e: sys.stderr.write('Error logging in: %s\n' % e) vim.command( 'unlet g:mediawiki_editor_username ' 'g:mediawiki_editor_password' ) raise site.cached_site = s return s site.cached_site = None def infer_default(article_name): if not article_name: article_name = vim.current.buffer.vars.get('article_name') else: article_name = article_name[0] if not article_name: sys.stderr.write('No article specified.\n') return article_name # Commands. def mw_read(article_name): s = site() vim.current.buffer[:] = s.Pages[article_name].text().split("\n") vim.command('set ft=mediawiki') vim.command("let b:article_name = '%s'" % sq_escape(article_name)) def mw_write(article_name): article_name = infer_default(article_name) s = site() page = s.Pages[article_name] summary = input('Edit summary: ') minor = input('Minor edit? [y/n]: ') == 'y' print (' ') result = page.save("\n".join(vim.current.buffer[:]), summary=summary, minor=minor) if result['result']: print ('Successfully edited %s.' % result['title']) else: sys.stderr.write('Failed to edit %s.\n' % article_name) def mw_diff(article_name): article_name = infer_default(article_name) s = site() vim.command('diffthis') vim.command('leftabove vsplit %s' % fn_escape(article_name + ' - REMOTE')) vim.command('setlocal buftype=nofile bufhidden=delete nobuflisted') vim.command('set ft=mediawiki') vim.current.buffer[:] = s.Pages[article_name].text().split("\n") vim.command('diffthis') vim.command('set nomodifiable') def mw_browse(article_name): article_name = infer_default(article_name) url = 'http://%s/wiki/%s' % (base_url(), article_name) if not var_exists('g:loaded_netrw'): vim.command('runtime! autoload/netrw.vim') if var_exists('*netrw#BrowseX'): vim.command("call netrw#BrowseX('%s', 0)" % sq_escape(url)) else: vim.command("call netrw#NetrwBrowseX('%s', 0)" % sq_escape(url))
f93dbdfe55bd74ab32fc37ab066e47b3ef2c41fe
[ "Markdown", "Python" ]
2
Markdown
ellethee/vim-mediawiki-editor
a2bccb16eef3aaf3d52f5f2753aa106e47e54b28
ffffaff77d577ffaad6b65848fe4e80e3ccdf03d
refs/heads/master
<repo_name>LMFinney/toh-pt6-tests<file_sep>/README.md # toh-pt6-tests Demonstrating karma and jasmine tests with the Tour of Heroes <file_sep>/src/app/dashboard/dashboard.component.spec.ts import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterModule } from '@angular/router'; import { of } from 'rxjs/observable/of'; import { DashboardComponent } from './dashboard.component'; import { HeroSearchComponent } from '../hero-search/hero-search.component'; import { HeroService } from '../hero.service'; describe('DashboardComponent', () => { let component: DashboardComponent; let fixture: ComponentFixture<DashboardComponent>; beforeEach(async(() => { const svcSpy = jasmine.createSpyObj('heroService', ['getHeroes']); svcSpy.getHeroes.and.returnValue(of([])); TestBed.configureTestingModule({ imports: [RouterModule], providers: [ { provide: HeroService, useValue: svcSpy } ], declarations: [DashboardComponent, HeroSearchComponent] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(DashboardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); });
588479b15b7104c4b9ef0dc8feecdc6f72d00606
[ "Markdown", "TypeScript" ]
2
Markdown
LMFinney/toh-pt6-tests
9006fa83a0f428cbfab49231481b7bfced3e225b
092d86c39c7d367d97179a9089a4d745f1f0be84
refs/heads/master
<file_sep>const Park = function (name, ticketPrice) { this.name = name; this.ticketPrice = ticketPrice; this.dinosaurs = []; } Park.prototype.dinoCount = function () { return this.dinosaurs.length; }; Park.prototype.addDino = function (newDino) { this.dinosaurs.push(newDino) }; Park.prototype.addDino = function (newDino) { this.dinosaurs.push(newDino) }; Park.prototype.removeDino = function (oldDino) { for (let i = 0 ; i < this.dinoCount() ; i++) { if (this.dinosaurs[i] === oldDino) { this.dinosaurs.splice(i,1); break; } } }; Park.prototype.popularDino = function () { let busiestDinosaur = null; let mostVisits = 0; for (let i = 0 ; i < this.dinoCount() ; i++ ) { if (this.dinosaurs[i].guestsAttractedPerDay > mostVisits) { busiestDinosaur = this.dinosaurs[i]; mostVisits = this.dinosaurs[i].guestsAttractedPerDay; } } return busiestDinosaur; }; Park.prototype.dinosOfSpecies = function (type) { let dinos = []; for (let dino of this.dinosaurs) { if (dino.species === type) { dinos.push(dino); } } return dinos; }; Park.prototype.removeSpecies = function (type) { let oldDinos = this.dinosOfSpecies(type); for (let dino of oldDinos) { this.removeDino(dino); } }; Park.prototype.dailyVisitors = function () { let visitors = 0; for (let dino of this.dinosaurs) { visitors += dino.guestsAttractedPerDay; } return visitors }; Park.prototype.yearlyVisitors = function () { return 365 * this.dailyVisitors(); }; Park.prototype.yearlyRevenue = function () { return this.yearlyVisitors() * this.ticketPrice }; module.exports = Park; Park.prototype.dietPortfolio = function () { let carns = 0; let herbs = 0; let omnis = 0; for (let dino of this.dinosaurs) { if (dino.diet === 'carnivore') { carns += 1; } else if (dino.diet === 'herbivore') { herbs += 1; } else if (dino.diet === 'omnivore') { omnis += 1; } } return { carnivore: carns, herbivore: herbs, omnivore: omnis } }; <file_sep>const assert = require('assert'); const Park = require('../models/park.js'); const Dinosaur = require('../models/dinosaur.js'); describe('Park', function() { let samantha; let tina; let steve; let terry; let park; beforeEach(function () { samantha = new Dinosaur('t-rex', 'carnivore', 50); tina = new Dinosaur('t-rex', 'carnivore', 40); steve = new Dinosaur('rachiosaurus', 'herbivore', 35); terry = new Dinosaur('avimimus', 'omnivore', 25); park = new Park(`<NAME>`, 40); }) it('should have a name', function () { assert.strictEqual(park.name, `<NAME>`); }); it('should have a ticket price', function () { assert.strictEqual(park.ticketPrice, 40); }); it('should have a collection of dinosaurs', function () { assert.deepStrictEqual(park.dinosaurs, []); }); it('should be able to count its dinosaurs', function () { assert.strictEqual(park.dinoCount(), 0); }); it('should be able to add a dinosaur to its collection', function () { park.addDino(samantha); assert.strictEqual(park.dinoCount(), 1); }); it('should be able to remove a dinosaur from its collection', function () { park.addDino(samantha); park.addDino(tina); park.removeDino(samantha); assert.strictEqual(park.dinoCount(), 1); }); it('should be able to find the dinosaur that attracts the most visitors', function () { park.addDino(samantha); park.addDino(tina); park.addDino(steve); park.addDino(terry); assert.strictEqual(park.popularDino(), samantha); }); it('should be able to find all dinosaurs of a particular species', function () { park.addDino(samantha); park.addDino(tina); park.addDino(steve); park.addDino(terry); assert.deepStrictEqual(park.dinosOfSpecies('t-rex'), [samantha, tina]); }); it('should be able to remove all dinosaurs of a particular species', function () { park.addDino(samantha); park.addDino(tina); park.addDino(steve); park.addDino(terry); park.removeSpecies('t-rex'); assert.strictEqual(park.dinoCount(), 2); }); it('should be able to determine the average visits per day', function () { park.addDino(samantha); park.addDino(tina); park.addDino(steve); park.addDino(terry); assert.strictEqual(park.dailyVisitors(), 150); }); it('should be able to determine the average visits per year', function () { park.addDino(samantha); park.addDino(tina); park.addDino(steve); park.addDino(terry); assert.strictEqual(park.yearlyVisitors(), 54750) }); it('should be able to determine the average revenue per year', function () { park.addDino(samantha); park.addDino(tina); park.addDino(steve); park.addDino(terry); assert.strictEqual(park.yearlyRevenue(), 2190000); }); it('should create an object describing the diet breakdown of the dinosaurs', function () { park.addDino(samantha); park.addDino(tina); park.addDino(steve); park.addDino(terry); const expected = { carnivore: 2, herbivore: 1, omnivore: 1 }; assert.deepStrictEqual(park.dietPortfolio(), expected); }); });
8980a33ba2f23c5b6badb0c3e68c2c71528188b3
[ "JavaScript" ]
2
JavaScript
robwilson195/w6-d2-hw-jurassic_park
f9abc196b3c4806c1b916ce6f85d8fa978e8f92e
6f2647b74e7ee34cb83d985657c466456855dacf
refs/heads/master
<file_sep>package mfetl import ( "context" "database/sql" "fmt" "github.com/myfantasy/mfdb" "github.com/myfantasy/mfe" ) // CopyTable - copy table from any db to any sql db func CopyTable(conf mfe.Variant) (err error) { mfe.LogActionF("", "mfetl.CopyTable", "Conf Load") dbTypeFrom := conf.GE("db_type_from").Str() dbFromCS := conf.GE("db_from").Str() dbTypeTo := conf.GE("db_type_to").Str() dbToCS := conf.GE("db_to").Str() ctx := context.Background() dbTo, err := sql.Open(dbTypeTo, dbToCS) if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.CopyTable", "Open Destination") return err } defer dbTo.Close() mfe.LogActionF("", "mfetl.CopyTable", "Open Source") dbFrom, err := sql.Open(dbTypeFrom, dbFromCS) if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.CopyTable", "Open Source") return err } defer dbFrom.Close() cFrom, err := dbFrom.Conn(ctx) if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.CopyTable", "Open Source Connection") return err } defer cFrom.Close() cTo, e := dbTo.Conn(ctx) if e != nil { mfe.LogExtErrorF(e.Error(), "mfetl.CopyTable", "Open Source Connection") return e } defer cTo.Close() return CopyTableConnections(ctx, cFrom, cTo, dbTypeFrom, dbTypeTo, conf) } // CopyTableConnections - copy table from any db to any sql db func CopyTableConnections(ctx context.Context, cFrom *sql.Conn, cTo *sql.Conn, dbTypeFrom string, dbTypeTo string, conf mfe.Variant) (err error) { mfe.LogActionF("", "mfetl.CopyTableConnections", "Conf Load") queryFrom := FromTableCopyQuery(conf, dbTypeFrom) sbf := mfdb.SBulkFieldCreate(conf.GE("fields")) tableTo := conf.GE("table_to").Str() schemaTo := conf.GE("schema_to").Str() batchSize := mfe.CoalesceI(int(conf.GE("batch_size").Int()), 10000) mfe.LogActionF("", "mfetl.CopyTable", "Open Destination") err = mfdb.ExecuteBatchInConnection(ctx, cFrom, queryFrom, batchSize, func(v mfe.Variant) (err error) { mfe.LogActionF("", "mfetl.CopyTable", "Start Write Batch") var e error if dbTypeTo == "sqlserver" { e = MSCopy(ctx, cTo, tableTo, sbf, v) } else if dbTypeTo == "postgres" { e = PGCopy(ctx, cTo, schemaTo, tableTo, sbf, v) } else { query := mfdb.InsertQuery(&v, tableTo) _, e = mfdb.ExecuteInConnection(ctx, cTo, query) } return e }) return err } // FromTableCopyQuery - create query for get rows from source func FromTableCopyQuery(conf mfe.Variant, dbTypeFrom string) (s string) { queryFrom := conf.GE("query_from").Str() if queryFrom == "" { sbf := mfdb.SBulkFieldCreate(conf.GE("fields")) tableFrom := conf.GE("table_from").Str() idName := mfe.CoalesceS(conf.GE("id_name").Str(), "_id") limit := mfe.CoalesceI(conf.GE("limit").Int(), 10000) var fieldsList string if sbf.Any() { fieldsList = mfe.JoinS(",", sbf.Columns()...) } else { fieldsList = "*" } if dbTypeFrom == "sqlserver" { queryFrom = "select top (" + fmt.Sprint(limit) + ") " + fieldsList + " from " + tableFrom + " order by " + idName + ";" } else { queryFrom = "select " + fieldsList + " from " + tableFrom + " order by " + idName + " limit " + fmt.Sprint(limit) + ";" } } return queryFrom } <file_sep>#mfetl tools for etl ###Copy table Simple copy table ###Table queue Copy table from source table to destination table then delete rows from sourse table then mark as ready rows in destination table Table sourse must have int64 _id (column name may be not _id) Table destination must have int64 _id and (bool _is_ready marker or string query to get complited ids) (columns name may be not _id and _is_ready) ## RunMethod run methods by param "method" ## Examples #### Copy Table pg to pg ```json { "method":"copy", "db_type_from":"postgres", "db_from":"host=host_from port=5432 dbname=db_name user=some_user password=<PASSWORD> sslmode=disable", "db_type_to":"postgres", "db_to":"host=host_to port=5432 dbname=db_name_to user=some_user_to password=<PASSWORD>_<PASSWORD>_<PASSWORD>_to sslmode=disable", "query_from":"select delivery_id, status_id, user_id from logistics.delivery limit 100000;", "table_to":"delivery_tst", "schema_to":"logistics", "fields":[ { "name":"delivery_id", "type":"int64" }, { "name":"status_id", "type":"int" } ] } ``` pg to sql ```json { "method":"copy", "db_type_from":"postgres", "db_from":"host=host_from port=5432 dbname=db_name user=some_user password=<PASSWORD> sslmode=disable", "db_type_to":"sqlserver", "db_to":"server=host_to;user id=domain\\some_user_to;password=<PASSWORD>;port=1433;database=db_name_to", "query_from":"select delivery_id, status_id, user_id from logistics.delivery limit 100000;", "table_to":"logistics.delivery_tst", "schema_to":"", "fields":[ { "name":"delivery_id", "type":"int64" }, { "name":"status_id", "type":"int" } ] } ``` #### Table Queue <file_sep>package mfetl import ( "errors" "github.com/myfantasy/mfe" ) // RunMethods Run methods conf param: method type RunMethods struct { Funcs map[string]func(conf mfe.Variant) (err error) } // RunByName methods by methodName func (rm RunMethods) RunByName(methodName string, conf mfe.Variant) (err error) { method, d := rm.Funcs[conf.GE(methodName).Str()] if d { return method(conf) } return errors.New("Method not found") } // Run methods conf param: method func (rm RunMethods) Run(conf mfe.Variant) (err error) { method, d := rm.Funcs[conf.GE("method").Str()] if d { return method(conf) } return errors.New("Method not found") } // CreateRunMethods create RunMethods with standart funcs func CreateRunMethods() (rm RunMethods) { rm.Funcs = map[string]func(conf mfe.Variant) error{} rm.Funcs["copy"] = CopyTable rm.Funcs["table_queue"] = TableQueue return rm } <file_sep>package mfetl import ( "context" "database/sql" "fmt" "strings" "github.com/myfantasy/mfdb" "github.com/myfantasy/mfe" ) // TableQueue - copy data from source table or query to destincation table or query and remove info from source table and mark as ready func TableQueue(conf mfe.Variant) (err error) { mfe.LogActionF("", "mfetl.TableQueue", "Conf Load") dbTypeFrom := conf.GE("db_type_from").Str() dbFromCS := conf.GE("db_from").Str() dbTypeTo := conf.GE("db_type_to").Str() dbToCS := conf.GE("db_to").Str() ctx := context.Background() dbTo, err := sql.Open(dbTypeTo, dbToCS) if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.CopyTable", "Open Destination") return err } defer dbTo.Close() mfe.LogActionF("", "mfetl.CopyTable", "Open Source") dbFrom, err := sql.Open(dbTypeFrom, dbFromCS) if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.CopyTable", "Open Source") return err } defer dbFrom.Close() cFrom, err := dbFrom.Conn(ctx) if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.CopyTable", "Open Source Connection") return err } defer cFrom.Close() cTo, e := dbTo.Conn(ctx) if e != nil { mfe.LogExtErrorF(e.Error(), "mfetl.CopyTable", "Open Source Connection") return e } defer cTo.Close() return TableQueueConnections(ctx, cFrom, cTo, dbTypeFrom, dbTypeTo, conf) } // TableQueueConnections - copy data from source table or query to destincation table or query and remove info from source table and mark as ready func TableQueueConnections(ctx context.Context, cFrom *sql.Conn, cTo *sql.Conn, dbTypeFrom string, dbTypeTo string, conf mfe.Variant) (err error) { mfe.LogActionF("", "mfetl.TableQueueConnections", "Conf Load") a := true var e error for a && e == nil { mfe.LogActionF("", "mfetl.TableQueueConnections", "Clear Old") a, e = tableQueueGetCompletedRowsAndClear(ctx, cFrom, cTo, dbTypeFrom, dbTypeTo, conf) if e != nil { return e } } mfe.LogActionF("", "mfetl.TableQueueConnections", "Copy") e = CopyTableConnections(ctx, cFrom, cTo, dbTypeFrom, dbTypeTo, conf) if e != nil { return e } for a && e == nil { mfe.LogActionF("", "mfetl.TableQueueConnections", "Clear New") a, e = tableQueueGetCompletedRowsAndClear(ctx, cFrom, cTo, dbTypeFrom, dbTypeTo, conf) if e != nil { return e } } return err } func tableQueueGetCompletedRowsAndClear(ctx context.Context, cFrom *sql.Conn, cTo *sql.Conn, dbTypeFrom string, dbTypeTo string, conf mfe.Variant) (any bool, err error) { idName := mfe.CoalesceS(conf.GE("id_name").Str(), "_id") isReady := mfe.CoalesceS(conf.GE("is_ready_name").Str(), "_is_ready") limit := mfe.CoalesceI(conf.GE("limit").Int(), 10000) tableFrom := conf.GE("table_from").Str() tableTo := conf.GE("table_to").Str() schemaTo := conf.GE("schema_to").Str() srcIDTempPreDoFrom := conf.GE("ids_temp_pre_do_from").Str() srcIDTempPreDoTo := conf.GE("ids_temp_pre_do_to").Str() srcIDTempTableFrom := conf.GE("ids_temp_table_from").Str() srcIDTempTableTo := conf.GE("ids_temp_table_to").Str() if dbTypeFrom == "postgres" { tableTo = schemaTo + "." + tableTo } queryGetDestIds := conf.GE("dest_query_get_ids").Str() if queryGetDestIds == "" { if dbTypeFrom == "sqlserver" { queryGetDestIds = "select top (" + fmt.Sprint(limit) + ") " + idName + " from " + tableTo + " where " + isReady + " = 0;" } else { queryGetDestIds = "select " + idName + " from " + tableTo + " order by " + idName + " limit " + fmt.Sprint(limit) + ";" } } queryMarkIdsInSource := conf.GE("src_query_mark_ids").Str() if queryMarkIdsInSource == "" { if dbTypeFrom == "sqlserver" { queryMarkIdsInSource = "delete t from " + tableFrom + " t inner join #ids s on t." + idName + " = s." + idName + ";" } else if dbTypeFrom == "postgres" { queryMarkIdsInSource = "delete from " + tableFrom + " where " + idName + " = any({arr_ids});" } } queryMarkIdsInDestination := conf.GE("dst_query_mark_ids").Str() if queryMarkIdsInDestination == "" { if dbTypeFrom == "sqlserver" { queryMarkIdsInDestination = "delete t from " + tableTo + " t inner join #ids s on t." + idName + " = s." + idName + ";" } else if dbTypeFrom == "postgres" { queryMarkIdsInDestination = "delete from " + tableTo + " where " + idName + " = any({arr_ids});" } } batchSize := mfe.CoalesceI(int(conf.GE("batch_size").Int()), 10000) mfe.LogActionF("", "mfetl.tableQueueGetCompletedRowsAndClear", "Open Destination") any = false vIDs := mfe.VariantNewSV() err = mfdb.ExecuteBatchInConnection(ctx, cTo, queryGetDestIds, batchSize, func(v mfe.Variant) (err error) { mfe.LogActionF("", "mfetl.tableQueueGetCompletedRowsAndClear", "Start Write Batch") any = any || v.Count() > 0 vIDs.AddRange(&v) e := queueIdsClear(ctx, cFrom, v, dbTypeFrom, idName, queryMarkIdsInSource, srcIDTempPreDoFrom, srcIDTempTableFrom) return e }) if err != nil { return any, err } err = queueIdsClear(ctx, cTo, vIDs, dbTypeTo, idName, queryMarkIdsInDestination, srcIDTempPreDoTo, srcIDTempTableTo) return any, err } func queueIdsClear(ctx context.Context, c *sql.Conn, v mfe.Variant, dbType string, idName string, queryMarkIds string, idTempPreDo string, idTempTable string) (e error) { if dbType == "sqlserver" { _, e = mfdb.ExecuteInConnection(ctx, c, "create table #ids("+idName+" bigint);") if e != nil { return e } e = MSCopy(ctx, c, "#ids", mfdb.SBulkFieldCreateString(idName, "int64"), v) if e != nil { return e } _, e = mfdb.ExecuteInConnection(ctx, c, queryMarkIds) if e != nil { return e } _, e = mfdb.ExecuteInConnection(ctx, c, "drop table #ids;") } else if dbType == "postgres" { q := strings.Replace(queryMarkIds, "{arr_ids}", mfdb.Array(&v, idName), -1) _, e = mfdb.ExecuteInConnection(ctx, c, q) if e != nil { return e } } else { _, e = mfdb.ExecuteInConnection(ctx, c, idTempPreDo) if e != nil { return e } query := mfdb.InsertQuery(&v, idTempTable) _, e = mfdb.ExecuteInConnection(ctx, c, query) if e != nil { return e } _, e = mfdb.ExecuteInConnection(ctx, c, queryMarkIds) } return e } <file_sep>package mfetl import ( "context" "database/sql" "fmt" mssql "github.com/denisenkom/go-mssqldb" "github.com/myfantasy/mfdb" "github.com/myfantasy/mfe" ) // MSCopy copy to MS to table func MSCopy(ctx context.Context, c *sql.Conn, tableName string, sbf mfdb.SBulkField, v mfe.Variant) (err error) { txn, err := c.BeginTx(ctx, nil) if err != nil { return err } fields := sbf.Columns() stmt, err := txn.Prepare(mssql.CopyIn(tableName, mssql.BulkOptions{}, fields...)) if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.MSCopy", "Prepare") return err } for _, vi := range v.SV() { ins := sbf.Values(vi) _, err = stmt.Exec(ins...) if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.MSCopy", "item add") return err } } result, err := stmt.Exec() if err != nil { return err } err = stmt.Close() if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.MSCopy", "Prepare") return err } err = txn.Commit() if err != nil { mfe.LogExtErrorF(err.Error(), "mfetl.MSCopy", "Prepare") return err } mfe.LogActionF("Rows: "+fmt.Sprint(result), "mfetl.MSCopy", "Done") return nil }
3351ef70a6b4f763d32b3321e31e635603d235f1
[ "Markdown", "Go" ]
5
Go
myfantasy/mfetl
58cfae1ab9846818758b868745d543a0808c377d
da418ef12b0b92e1ab66c7e5bd2abab4e6ddaafa
refs/heads/master
<file_sep>import React from 'react'; import Avatar from '../Avatar/Avatar'; import Button from '../Button/Button'; import AvatarImage from '../../assets/avatar.jpg'; import './cardMeetUp.css'; const CardMeetUp = () => { const thanksForJoin = () => { alert('Terima kasih sudah join meetup'); } return ( <div> <div className="cardJoinUs"> <div> <Avatar src={AvatarImage} /> </div> <div> <p>Hacktiv 8 Meetup</p> <Button textButton="JOIN US" onClick={thanksForJoin}/> </div> </div> </div> ); } export default CardMeetUp;<file_sep>import React from 'react'; const HelloWorld = () => { const name = '<NAME>'; const copyright = 'INALUM 2020'; const width = 500; const onClickImage = () => { alert('You clicked image'); }; let showImage = true; const listNumbers = [1, 2, 3, 4, 5]; return ( <div> <h1 className="title">Hello World</h1> <p className="description">A JavaScript Library for Building User interface</p> <p>{name.toLowerCase()}</p> { showImage ? ( <img src="https://images.unsplash.com/photo-1598454444233-9dc334394ed3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1949&q=80" width={width} alt="Car" onClick={onClickImage} /> ) : ( <div></div> ) } { listNumbers.map((element) => ( <ul> <li>{element}</li> </ul> )) } <p>{copyright}</p> </div> ); }; export default HelloWorld;<file_sep>import React from 'react' import './navbar.css'; const Navbar = ({ children }) => { return ( <div className="wrapper"> <div className="wrapperNav"> <ul className="listWrapper"> <li>QTemu</li> <li>Create Meetup</li> <li>Explore</li> </ul> <div> Login </div> </div> { children } </div> ); } export default Navbar;<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { Col } from 'react-bootstrap'; import Button from '../Button/Button'; import './pastmeetup.css'; const PastMeetupCard = ({ data }) => { return ( <> { data.map((item) => ( <Col className="wrapper" key={item.id}> <div className="card bg-light"> <div className="card-body text-left"> <h6 className="card-title">{item.date}</h6> <hr/> <p>{item.desc}</p> <p><b>{item.attendens}</b> went</p> <Button textButton="View"/> </div> </div> </Col> )) } </> ); } PastMeetupCard.propTypes = { date: PropTypes.string, event_desc: PropTypes.string, attendees: PropTypes.number } export default PastMeetupCard;
da88c80d6bee52b9c325d594b206fb2424f050ee
[ "JavaScript" ]
4
JavaScript
davidwinalda/basic-component
20acece42a5a7768139e4a16fb82df66935663d4
1558ee68a47a0aecbf4b889b75e5b5df820e7966
refs/heads/master
<file_sep> import React, { useState, useEffect } from 'react'; import Header from './components/Header' import LocationCard from './components/LocationCard' import Footer from './components/Footer' import { library } from '@fortawesome/fontawesome-svg-core' import { fab } from '@fortawesome/free-brands-svg-icons' import { faMapMarkerAlt, faPhone } from '@fortawesome/free-solid-svg-icons' //importing icons library.add(fab, faMapMarkerAlt, faPhone) //testing variables //console.log(process.env.REACT_APP_API_KEY); //console.log(process.env.REACT_APP_API_URL); const base = process.env.REACT_APP_API_URL + process.env.REACT_APP_API_KEY; const App = () => { const[locations, setLocations] = useState([]); //const [hasError, setErrors] = useState(false); useEffect(() => { fetch(base) .then((res) => res.json()) .then((data) => { setLocations(data.records); }) .catch((err) => { console.log(err); }); }, []); return ( <div className="container-fluid px-0"> <Header /> <div className="container mt-5"> <div className="row align-items-center"> <div className="card-deck mx-auto"> {locations.map(location => <LocationCard {...location.fields} /> )} </div> </div> <p className="text-center">Más información en <a href="https://oxigeno.sanpedro.gob.mx/" target="_blank" rel="noreferrer">Oxígeno SPGG</a></p> </div> <Footer /> </div> ) } export default App; <file_sep>import React from 'react'; import './LocationCard.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' const LocationCard = (props) => { return ( <div className="col-sm-4"> <div className="card mt-1 mb-4 mx-auto"> <div className="card-content"> <h5 className="card-title">{props.empresa}</h5> <p className="phone"> <FontAwesomeIcon icon="phone"/> {props.tel}</p> <p>{props.horario && <small className="text-muted">Horario: {props.horario}</small> }</p> <p> {props.recarga && <span aria-label="Recarga">Recarga: {props.recarga}</span>} {props.venta && <span>Venta: {props.venta}</span>} {props.renta && <span>Renta: {props.renta}</span>} </p> <p > <span>{props.whatsapp && <a href={props.whatsapp} aria-label="Whatsapp" rel="noreferrer"><FontAwesomeIcon icon={['fab', 'whatsapp']} className="wa" /></a>}</span> <span>{props.dir && <a href={props.dir} aria-label="Dirección" target="_blank" rel="noreferrer"><FontAwesomeIcon icon="map-marker-alt" className="map" /></a>}</span> <span>{props.web && <a href={props.web} aria-label="Web/Facebook" target="_blank" rel="noreferrer">Web/Facebook</a>}</span> </p> </div> </div> </div> ) } export default LocationCard;<file_sep>import React from 'react'; import './Header.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' const Header = () => { return ( <div className="container-fluid px-0"> <div className="title"> <h1 className="display-4">Oxígeno en Monterrey</h1> <div className="subtitle"> <p className="lead">Listado de proveedores de oxígeno (tanques y/o concentradores) en Monterrey y área metropolitana.</p> <p className="social">Compartir en <a href="https://www.facebook.com/sharer/sharer.php?u=https://oxigenomty.cc" target="_blank" rel="noreferrer" title="Compartir en Facebook"><FontAwesomeIcon icon={["fab", "facebook"]} className="social-icon"/></a> <a href="https://api.whatsapp.com/send?text=https://oxigenomty.cc" target="_blank" rel="noreferrer"><FontAwesomeIcon icon={["fab", "whatsapp"]} /></a> <a href="https://twitter.com/intent/tweet?text=Oxígeno MTY&amp;url=https://oxigenomty.cc" target="_blank" rel="noreferrer" title="Compartir en Twitter"><FontAwesomeIcon icon={["fab", "twitter"]} /></a> </p> <p className="warning"> <a href="https://www.forbes.com.mx/noticias-consejos-para-prevenir-fraudes-en-venta-o-renta-de-tanques-de-oxigeno/" target="_blank" rel="noreferrer"> Consejos para prevenir fraudes en la venta y renta de oxígeno</a> </p> </div> </div> <div className="jumbotron jumbotron-fluid"></div> </div> ) } export default Header<file_sep># Oxígeno MTY Oxygen providers available in Monterrey. Made with React, Airtable and Netlify. # Demo https://oxigenomty.cc
160f99b7dc9044c47810729be5cea640c29643ae
[ "JavaScript", "Markdown" ]
4
JavaScript
ph81/oxmty
9b8725ed804281bfd6016bc71d9984c265b34489
786191afc3545770779cfaece43ab6f8ff0d13d4
refs/heads/master
<file_sep>import { Component, OnInit, Input } from '@angular/core'; import { HttpService } from "../../http.service" import {ActivatedRoute, Router, Params} from "@angular/router"; @Component({ selector: 'app-showedit', templateUrl: './showedit.component.html', styleUrls: ['./showedit.component.css'] }) export class ShoweditComponent implements OnInit { @Input() product: {}; constructor(private _route: ActivatedRoute,private _router: Router,private _httpService: HttpService) { } ngOnInit() { this.product = { title: "", price: "", imgUrl: ""} } getOneProduct(id: string) { this._httpService.getOneProduct(id).subscribe(data => { if(data["message"] == "Success") { this.product = data["data"]; console.log("TEST HERE", this.product); // this._router.navigate(["/products/all"]); } }); } // // update Product route: -------------------- // updateProduct(id: string) { // this._httpService.updateProduct(id).subscribe(data => { // if(data["message"] == "Success") { // // this.getAllProducts(); // this._router.navigate(["/products/all"]); // } // }); // } } <file_sep>import { Component, OnInit } from '@angular/core'; import { HttpService } from "../../http.service" import {ActivatedRoute, Router, Params} from "@angular/router"; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'] }) export class CreateComponent implements OnInit { constructor(private _httpService: HttpService, private _router: Router) { } newProduct = { title: "", price: "", imgUrl: "" }; ngOnInit() { } // Create New Product Route:--------------- createProduct() { let observable = this._httpService.createProduct(this.newProduct); observable.subscribe(data => { console.log("Product Successfully Created!"); this.newProduct = { title: "", price: "", imgUrl: "" } // Reroute to All Products: this._router.navigate(["/products/all"]); }); } }
dab46c5e205d73f247103b4968083ff6a2eb1897
[ "TypeScript" ]
2
TypeScript
EsC369/Mean_Product_Managers-FullStack
b0430c2e308e348a619fd7f40a63869e7659eb09
5251f19f85f48d4218dad98736226b142a09f13c
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Text; namespace KCrawler { public class KeywordDao { private readonly static AccessHelper db = new AccessHelper(); public static void DeleteUrlKeyword(int id) { const string sql = "DELETE * FROM UrlKeyword WHERE ID="; db.ExecuteScalar(sql + id.ToString()); } public static void DeleteHtmlKeyword(int id) { const string sql = "DELETE * FROM HtmlKeyword WHERE ID="; db.ExecuteScalar(sql + id.ToString()); } public static void DeleteCookies(int id) { const string sql = "DELETE * FROM Cookies WHERE ID="; db.ExecuteScalar(sql + id.ToString()); } public static void AddKeyword(HtmlKeywordInfo model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into HtmlKeyword("); strSql.Append("KName,Keywords,TaskID)"); strSql.Append(" values ("); strSql.Append("@KName,@Keywords,@TaskID)"); db.AddInParameter("KName", DbType.AnsiString, model.KName); db.AddInParameter("Keywords", DbType.AnsiString, model.Keywords); db.AddInParameter("TaskID", DbType.Int32, model.TaskID); db.ExecuteScalar(strSql.ToString()); } public static void AddKeyword(UrlKeywordInfo model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into UrlKeyword("); strSql.Append("KName,Keywords,TaskID)"); strSql.Append(" values ("); strSql.Append("@KName,@Keywords,@TaskID)"); db.AddInParameter("KName", DbType.AnsiString, model.KName); db.AddInParameter("Keywords", DbType.AnsiString, model.Keywords); db.AddInParameter("TaskID", DbType.Int32, model.TaskID); db.ExecuteScalar(strSql.ToString()); } public static void AddCookies(CookieInfo model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into Cookies("); strSql.Append("Url,UserAgent,Cookies,TaskID)"); strSql.Append(" values ("); strSql.Append("@Url,@UserAgent,@Cookies,@TaskID)"); db.AddInParameter("Url", DbType.AnsiString, model.Url); db.AddInParameter("UserAgent", DbType.AnsiString, model.UserAgent); db.AddInParameter("Cookies", DbType.AnsiString, model.Cookies); db.AddInParameter("TaskID", DbType.Int32, model.TaskID); db.ExecuteScalar(strSql.ToString()); } public static List<CookieInfo> GetCookieList(int taskid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select ID,Url,UserAgent,Cookies,TaskID "); strSql.Append(" FROM Cookies "); strSql.Append(" where taskid=").Append(taskid); List<CookieInfo> list = new List<CookieInfo>(); using (IDataReader dataReader = db.ExecuteReader(strSql.ToString())) { while (dataReader.Read()) { list.Add(CookieReaderBind(dataReader)); } } return list; } public static List<HtmlKeywordInfo> GetHtmlKeywordList(int taskid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select ID,KName,Keywords,TaskID "); strSql.Append(" FROM HtmlKeyword "); strSql.Append(" where TaskID=").Append(taskid); List<HtmlKeywordInfo> list = new List<HtmlKeywordInfo>(); HtmlKeywordInfo hk; using (IDataReader dataReader = db.ExecuteReader(strSql.ToString())) { while (dataReader.Read()) { hk = ReaderBind(dataReader) as HtmlKeywordInfo; list.Add(hk); } } return list; } public static List<UrlKeywordInfo> GetUrlKeywordList(int taskid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select ID,KName,Keywords,TaskID "); strSql.Append(" FROM UrlKeyword "); strSql.Append(" where TaskID=").Append(taskid); List<UrlKeywordInfo> list = new List<UrlKeywordInfo>(); UrlKeywordInfo uk; using (IDataReader dataReader = db.ExecuteReader(strSql.ToString())) { while (dataReader.Read()) { uk = ReaderBind(dataReader) as UrlKeywordInfo; list.Add(uk); } } return list; } /// <summary> /// url html 子 父 类 /// </summary> private static UrlKeywordInfo ReaderBind(IDataReader dataReader) { UrlKeywordInfo model = new UrlKeywordInfo(); object ojb; ojb = dataReader["ID"]; if (ojb != null && ojb != DBNull.Value) { model.ID = (int)ojb; } model.KName = dataReader["KName"].ToString(); model.Keywords = dataReader["Keywords"].ToString(); ojb = dataReader["TaskID"]; if (ojb != null && ojb != DBNull.Value) { model.TaskID = (int)ojb; } return model; } private static CookieInfo CookieReaderBind(IDataReader dataReader) { CookieInfo model = new CookieInfo(); object ojb; ojb = dataReader["ID"]; if (ojb != null && ojb != DBNull.Value) { model.ID = (int)ojb; } model.Url = dataReader["Url"].ToString(); model.UserAgent = dataReader["UserAgent"].ToString(); model.Cookies = dataReader["Cookies"].ToString(); ojb = dataReader["TaskID"]; if (ojb != null && ojb != DBNull.Value) { model.TaskID = (int)ojb; } return model; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace KCrawler { public class TaskInfo { //Ctask左侧任务栏 private bool isLunched = false; public bool IsLunched { get { return isLunched; } set { isLunched = value; } } public string TaskID { get { return ID.ToString(); } } public int ID { get; set; } public string TaskName { get; set; } public bool NotSave { get; set; } public string Unicode { get; set; } public string DownloadFolder { get; set; } public bool IsInternal { get; set; } public string EntranceURL { get; set; } public int ThreadCount { get; set; } public int ConnectionTimeout { get; set; } public int ThreadSleepTimeWhenQueueIsEmpty { get; set; } public int MinFileSize { get; set; } public string MinKB { get { return MinFileSize.ToString() + "KB"; } } public string MinMB { get { return MinFileSize <= 1024 ? MinKB : Convert.ToDouble(MinFileSize / 1024).ToString(".00") + "MB"; } } public string Description { get; set; } public bool IsPreference { get; set; } public List<HtmlKeywordInfo> HtmlKeyword { get; set; } public List<UrlKeywordInfo> UrlKeyword { get; set; } public List<CookieInfo> CookieList { get; set; } public List<PriorityInfo> Priority { get; set; } public List<FilterInfo> Filter { get; set; } public bool IsFilterAllMime { get; set; } public bool IsAddUkey { get; set; } public string Domain { get { return Utility.GetDomain(EntranceURL); } } public string FilterText { get { StringBuilder s = new StringBuilder(); foreach (var u in Filter) { s.Append('\t'); s.AppendLine(u.EMText); } return s.ToString(); } } public string PriorityText { get { StringBuilder s = new StringBuilder(); foreach (var u in Priority) { s.Append('\t'); s.AppendLine(u.EMText); } return s.ToString(); } } public string UrlKeywordText { get { StringBuilder s = new StringBuilder(); foreach (var u in UrlKeyword) { s.Append('\t'); s.AppendLine(u.KOutput); } return s.ToString(); } } public string HtmlKeywordText { get { StringBuilder s = new StringBuilder(); foreach (var h in HtmlKeyword) { s.Append('\t'); s.AppendLine(h.KOutput); } return s.ToString(); } } public string Category { get; set; } public List<ExtractOption> ExtractOptionList { get; set; } public string ExtractedXml { get { if (null == ExtractOptionList) return string.Empty; if (ExtractOptionList.Count == 0) return string.Empty; StringBuilder currentItem = new StringBuilder(); currentItem.AppendLine(C.Xml_Item); foreach (var option in ExtractOptionList) { currentItem.AppendLine(option.XmlItem); } currentItem.AppendLine(C.Xml_ItemEnd); return currentItem.ToString(); } } public List<ExtractOption> ExtractLinks { get { return ExtractOptionList.Where(a => a.ExtractType == ExtractOption.Option_Links).ToList(); } } public List<ExtractOption> ExtractContent { get { return ExtractOptionList.Where(a => a.ExtractType == ExtractOption.Option_Content).ToList(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Text; namespace KCrawler { public class PriorityFilterDao { private readonly static AccessHelper db = new AccessHelper(); public static void AddPriority(int taskID, List<PriorityInfo> pi) { const string sql = " INSERT INTO [Priority] ( TaskID, MimeID,Priority ) VALUES({0},{1},{2}) "; const string filter = " DELETE * FROM filter WHERE TaskID={0} AND MimeID={1}"; foreach (PriorityInfo p in pi) { db.ExecuteNonQuery(string.Format(sql, taskID, p.MimeID, p.Priority)); db.ExecuteNonQuery(string.Format(filter, taskID, p.MimeID)); } } public static void AddFilter(int taskID, List<int> mimeID) { const string sql = " INSERT INTO [Filter] ( TaskID, MimeID ) VALUES({0},{1}) "; foreach (int id in mimeID) db.ExecuteNonQuery(string.Format(sql, taskID, id)); } /// <summary> /// 返回新增taskid /// </summary> public static void RemovePriority(int[] rowID) { const string sql = " DELETE * FROM Pirority WHERE ID= "; foreach (int id in rowID) db.ExecuteNonQuery(sql + id); } public static void RemoveFilter(int[] rowID) { const string sql = " DELETE * FROM Filter WHERE ID= "; foreach (int id in rowID) db.ExecuteNonQuery(sql + id); } public static List<FilterInfo> GetFilter(int taskID) { const string sql = "SELECT * FROM Mime RIGHT JOIN Filter ON Mime.ID = Filter.MimeID WHERE TaskID={0}"; IDataReader dr = db.ExecuteReader(string.Format(sql, taskID)); var list = new List<FilterInfo>(); FilterInfo model; while (dr.Read()) { model = new FilterInfo(); object ojb; model.Extension = dr["Extension"].ToString(); model.Mime = dr["Mime"].ToString(); model.Category = dr["Category"].ToString(); ojb = dr["Filter.ID"]; if (ojb != null && ojb != DBNull.Value) model.ID = (int)ojb; list.Add(model); } return list; } public static List<PriorityInfo> GetPriority(int taskID) { const string sql = "SELECT * FROM Mime RIGHT JOIN Priority ON Mime.ID = Priority.MimeID WHERE TaskID = {0}"; IDataReader dr = db.ExecuteReader(string.Format(sql, taskID)); var list = new List<PriorityInfo>(); PriorityInfo model; while (dr.Read()) { model = new PriorityInfo(); object ojb; model.Extension = dr["Extension"].ToString(); model.Mime = dr["Mime"].ToString(); model.Category = dr["Category"].ToString(); model.MimeID = (int)dr["mimeid"]; ojb = dr["Priority.ID"]; if (ojb != null && ojb != DBNull.Value) model.ID = (int)ojb; ojb = dr["Priority"]; if (ojb != null && ojb != DBNull.Value) model.Priority = Convert.ToInt16(ojb); list.Add(model); } return list; } public static List<MimeInfo> GetMimeWithoutFilter(int taskID) { StringBuilder sql = new StringBuilder(); sql.Append(" SELECT * "); sql.Append(" FROM Mime "); sql.AppendFormat(" WHERE Mime.[id] Not In (select mimeid from Filter where taskid={0}) ", taskID); sql.AppendFormat(" AND Mime.[id] Not In (select mimeid from Priority where taskid={0}) ", taskID); IDataReader dr = db.ExecuteReader(sql.ToString()); var list = new List<MimeInfo>(); while (dr.Read()) { list.Add(MimeReaderBind(dr)); } return list; } public static List<MimeInfo> GetMimeWithoutPriority(int taskID) { StringBuilder sql = new StringBuilder(); sql.Append(" SELECT * "); sql.Append(" FROM Mime "); sql.AppendFormat(" WHERE Mime.[id] Not In (select mimeid from Priority where taskid={0}) ", taskID); sql.AppendFormat(" AND Mime.[id] Not In (select mimeid from Filter where taskid={0}) ", taskID); IDataReader dr = db.ExecuteReader(sql.ToString()); var list = new List<MimeInfo>(); while (dr.Read()) { list.Add(MimeReaderBind(dr)); } return list; } private static MimeInfo MimeReaderBind(IDataReader dataReader) { MimeInfo model = new MimeInfo(); object ojb; model.Extension = dataReader["Extension"].ToString(); model.Mime = dataReader["Mime"].ToString(); model.Category = dataReader["Category"].ToString(); model.MType = Convert.ToInt16(dataReader["MType"]); ojb = dataReader["ID"]; if (ojb != null && ojb != DBNull.Value) { model.ID = (int)ojb; } return model; } public static List<MimeInfo> FileTypeMime { get { IDataReader dataReader = db.ExecuteReader("SELECT * FROM [Mime] WHERE MType=1 "); var list = new List<MimeInfo>(); while (dataReader.Read()) { list.Add(MimeReaderBind(dataReader)); } return list; } } public static List<string> Protocol { get { IDataReader dataReader = db.ExecuteReader("SELECT [Prefix] FROM [Protocol] "); var p=new List<string>(); while (dataReader.Read()) { p.Add(dataReader["Prefix"].ToString()); } return p; } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using KCrawler; using System.Windows.Forms; using System.Threading; using System.Data; namespace Netscape { public class Task { //爬虫运行窗体,包含 internal static Dictionary<int, CDetails> Pool { get; private set; } static Task() { if (Pool == null) Pool = new Dictionary<int, CDetails>(); } internal static void HideView( int taskID) { foreach (var t in Task.Pool) { if (taskID <0) { t.Value.Hide(); continue; } if (t.Value.TaskID != taskID) t.Value.Hide(); } } internal static void HideView() { HideView(-1); } //线程,保存爬去数据 internal static void ThreadProc(ThreadStart ts) { Thread stopThread = new Thread(ts); stopThread.Start(); while (true) { Application.DoEvents(); if (!stopThread.IsAlive) break; Thread.Sleep(100); } } internal static void ThreadProc(ParameterizedThreadStart ts, object p) { Thread stopThread = new Thread(ts); stopThread.Start(p); while (true) { Application.DoEvents(); if (!stopThread.IsAlive) break; Thread.Sleep(100); } } internal static void ThreadQueueSave(object s) { Save(); } internal static void Save() { foreach (var kv in Pool) { //if (kv.Value.CrawlerInfo.NotSave) // kv.Value.Spider.Dump("Save"); kv.Value.Spider.Save(); } } //根据任务section获得窗体 public static CDetails GetSpiderView(int taskid) { if (Pool.ContainsKey(taskid)) return Pool[taskid]; CDetails spiderWindow = new CDetails(); spiderWindow.Spider = new Downloader(taskid); Pool.Add(taskid, spiderWindow); return spiderWindow; } internal static void Pause() { foreach (var kv in Pool) { if (kv.Value.Spider.Status != DownloaderStatus.Running) continue; kv.Value.Spider.Suspend(); } } internal static void Stop() { foreach (var kv in Pool) { kv.Value.Spider.Abort(); } } internal static void Start() { foreach (var kv in Pool) { kv.Value.Spider.Start(); } } //线程调用 internal static void Dump() { foreach (var kv in Pool) { if (kv.Value.Spider.Status == DownloaderStatus.Stopped) kv.Value.Spider.Restore(); kv.Value.Spider.Dump(); } } internal static void WriteXmlFile(object s) { foreach (var a in Task.Pool) if (a.Value.Spider.Status != DownloaderStatus.Stopped) a.Value.Spider.WriteXmlFile(); } } } <file_sep> namespace KCrawler { using System.Threading; using System; public partial class CrawlerThread { public event CrawlerStatusChangedEventHandler StatusChanged; public ManualResetEvent manualEvent = new ManualResetEvent(true); private Thread cthread; public CrawlerThread(Downloader d) { cthread = new Thread(DoWork); this.Downloader = d; } private string mimeType; public string MimeType { get { return mimeType; } set { mimeType = value; } } /// <summary> /// 当前线程消息用于判断状态 /// </summary> public Thread CThread { get { return cthread; } } public string Name { get; set; } public CrawlerStatusType Status { get; private set; } public string StatusText { get { switch (Status) { case CrawlerStatusType.Fetch: return R.CrawlerStatusType_Fetch; case CrawlerStatusType.Parse: return R.CrawlerStatusType_Parse; case CrawlerStatusType.Save: return R.CrawlerStatusType_Save; case CrawlerStatusType.Sleep: return R.CrawlerStatusType_Sleep; } return Status.ToString(); } } public string Url { get; set; } private Downloader Downloader { get; set; } internal void Start() { cthread.Start(); } internal void Abort() { //清空excel配置文件哈希表缓存 cthread.Abort(); } internal void Suspend() { if (cthread.IsAlive) manualEvent.Reset(); } internal void Resume() { if (cthread.IsAlive) manualEvent.Set(); } public void DoWork() { try { if (null == Downloader.UrlsQueueFrontier) return; while (true) { if (Downloader.UrlsQueueFrontier.Count > 0) { try { //加休眠缓和cpu manualEvent.WaitOne(-1); // 从队列中获取URL string url = (string)Downloader.UrlsQueueFrontier.Dequeue(); // 获取页面 //如果不保存文件则直接添加到url列表, if (!Utility.IsGoodUri(ref url)) continue; Fetch(url); Thread.Sleep(50); } catch (InvalidOperationException ioe) { SleepWhenQueueIsEmpty(); Downloader.Logger.Error(ioe.Message); } } else { SleepWhenQueueIsEmpty(); } } } catch (ThreadAbortException tae) { Downloader.Logger.Error(tae.Message); } } // 为避免挤占CPU, 队列为空时睡觉. private void SleepWhenQueueIsEmpty() { Status = CrawlerStatusType.Sleep; Url = string.Empty; StatusChanged(this, null); Thread.Sleep(Downloader.CrawlerInfo.ThreadSleepTimeWhenQueueIsEmpty * 1000); } } } <file_sep> namespace Netscape { using KCrawler; using Lv.Docking; using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Windows.Forms; public partial class CTask : DockContent { public event CTaskLivtViewHandler DownloaderSelected; public event StatusEventHandler CrawlerStatusChanged; private StatusEventArgs statusArgs = new StatusEventArgs(); private StringBuilder sets = new StringBuilder(); private static List<TaskInfo> taskList; public CTask() { InitializeComponent(); Init(); } //更新任务后,Ctask缓存列表更新 internal static void UpdateCTask(ref TaskInfo ti) { if (null == taskList) return; for(int i=0;i<taskList.Count;i++) { if (taskList[i].ID == ti.ID) { taskList[i] = ti; return; } } } private void Init() { lvTask.Items.Clear(); int index; taskList = TaskCache.GetTaskList(); for (int i = 0; i < taskList.Count; i++) { index = i + 1; lvTask.Items.Add(taskList[i].MinKB); lvTask.Items[i].SubItems.Add(taskList[i].TaskName); lvTask.Items[i].SubItems.Add(DownloaderStatus.Stopped.ToString()); lvTask.Items[i].ToolTipText = (taskList[i].DownloadFolder); // if (taskList[i].IsInternal) lvTask.Items[i].SubItems.Add(taskList[i].IsInternal.ToString()); // if (taskList[i].NotSave) lvTask.Items[i].SubItems.Add(taskList[i].NotSave.ToString()); } } public void RefreshData() { //任务缓存移除后重置listview if (!Cache.KCache.Contains(TaskCache.C_TaskList)) { Init(); return; } for (int i = 0; i < lvTask.Items.Count; i++) { lvTask.Items[i].Text = taskList[i].MinKB; lvTask.Items[i].SubItems[1].Text = taskList[i].TaskName; if (taskList[i].IsLunched ) lvTask.Items[i].SubItems[2].Text = Task.GetSpiderView(taskList[i].ID).Spider.StatusText; lvTask.Items[i].SubItems[3].Text = taskList[i].IsInternal ? R.CTasK_IsInternal : String.Empty; lvTask.Items[i].SubItems[3].Text = taskList[i].IsInternal ? R.CTasK_IsInternal : String.Empty; lvTask.Items[i].SubItems[4].Text = taskList[i].NotSave ? R.CTasK_AreOnlyLinks : String.Empty; } //每2分钟保存一次爬去数据 if (DateTime.Now.Minute % 2 == 0 && DateTime.Now.Second % 59 == 0) { ThreadPool.QueueUserWorkItem(new WaitCallback(Task.ThreadQueueSave)); ThreadPool.QueueUserWorkItem(new WaitCallback(Task.WriteXmlFile)); Thread.Sleep(750); } } private void CTask_Shown(object sender, EventArgs e) { timerStatus.Start(); } private void Start() { if (lvTask.SelectedIndices.Count <= 0) return; int index = lvTask.SelectedIndices[0]; taskList[index].IsLunched = true; CDetails cd = Task.GetSpiderView(taskList[index].ID); //如果已经启动则跳出 if (cd.Spider.Status == DownloaderStatus.Running) { if (DownloaderSelected != null) DownloaderSelected(this, new CTaskEventArgs(cd)); return; } //如果暂停则恢复 if (cd.Spider.Status == DownloaderStatus.Paused) { if (DownloaderSelected != null) DownloaderSelected(this, new CTaskEventArgs(cd)); cd.Spider.Resume(); return; } //开启任务 // lvTask.Items[index].SubItems[2].Text = R.CTask_StartingTask; statusArgs.Start(R.CTask_StartingTask); if (CrawlerStatusChanged != null) CrawlerStatusChanged(null, statusArgs); Thread threadStartTask = new Thread(new ThreadStart(Task.GetSpiderView(taskList[index].ID).Spider.Start)); threadStartTask.Start(); while (true) { if (!threadStartTask.IsAlive) { statusArgs.Done(R.CDetails_Done); if (DownloaderSelected != null) DownloaderSelected(this, new CTaskEventArgs(cd)); break; } Application.DoEvents(); Thread.Sleep(100); } if (CrawlerStatusChanged != null) CrawlerStatusChanged(null, statusArgs); } private void lvTask_DoubleClick(object sender, EventArgs e) { Start(); } private void taskContextMenu_MenuItemClicked(object sender, EventArgs e) { if (lvTask.SelectedIndices.Count <= 0) { MessageBox.Show(R.CTask_NullTaskSelected); return; } ToolStripMenuItem tsm = sender as ToolStripMenuItem; if (tsm == null) return; switch (tsm.Name) { case "tsmStart": Start(); break; case "tsmDeleteTask": DeleteTask(); return; } } //刷新事件 private void timerStatus_Tick(object sender, EventArgs e) { RefreshData(); } //这里控制快捷菜单,根据任务id private void taskContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e) { if (lvTask.SelectedIndices.Count <= 0) return; taskContextMenu.TaskID = taskList[lvTask.SelectedIndices[0]].ID; taskContextMenu.ChangeMenuStrip(Task.GetSpiderView(taskContextMenu.TaskID).Spider.Status); } private void lvTask_KeyUp(object sender, KeyEventArgs e) { if (e.KeyData != Keys.Delete) return; if (lvTask.SelectedIndices.Count <= 0) return; DeleteTask(); } private void DeleteTask() { DialogResult dr = MessageBox.Show(R.CTask_ConfirmRemoveTask, String.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == System.Windows.Forms.DialogResult.No) return; Task.GetSpiderView(taskList[lvTask.SelectedIndices[0]].ID).Spider.Abort(); TaskDao.DeleteTask(taskList[lvTask.SelectedIndices[0]].ID); //清缓存 Cache.ClearTaskList(); Task.GetSpiderView(taskList[lvTask.SelectedIndices[0]].ID).Close(); Init(); } //主窗体任务栏 private void lvTask_MouseClick(object sender, MouseEventArgs e) { if (lvTask.SelectedIndices.Count <= 0) return; int index = lvTask.SelectedIndices[0]; sets.AppendFormat("[{0}]", taskList[index].TaskName); sets.Append(R.CDetails_EntranceURL + taskList[index].EntranceURL).Append(" "); ; if (!string.IsNullOrEmpty(taskList[index].Unicode)) sets.Append(R.CDetails_Unicode + taskList[index].Unicode).Append(" "); sets.Append(R.CDetails_DownloadFolder + taskList[index].DownloadFolder).Append(" "); statusArgs.Info(sets.ToString()); sets.Remove(0, sets.Length); if (CrawlerStatusChanged != null) CrawlerStatusChanged(null, statusArgs); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Drawing; using KCrawler; namespace Netscape { public delegate void CTaskLivtViewHandler(object sender, CTaskEventArgs e); public delegate void TaskMenuHandler(object sender, EventArgs e); public delegate void StatusEventHandler(object sender, StatusEventArgs e); public delegate void MimeBoxEventHandler(object sender, EventArgs e); public delegate void PriorityLevelHandler(object sender, EventArgs e); public delegate void ExtractionHandler(object sender, EventArgs e); /// <summary> /// 格式转换选择代理【用于flowcontainer按钮发送到主窗体】 /// </summary> public class CTaskEventArgs : EventArgs //事件参数类 { public CTaskEventArgs(CDetails cd) { CrawlerDetailForm = cd; } public CDetails CrawlerDetailForm { get; private set; } } //状态栏事件参数 public class StatusEventArgs : EventArgs { private bool isShowOnBallon = false; public string Text { get; set; } public Color BackgroundColor { get; set; } public Color ForeColor { get; set; } public bool IsShowOnBallon { get { return isShowOnBallon; } set { isShowOnBallon = value; } } public void Info(string info) { BackgroundColor = CK.ColorControl; Text = info; } public void Done() { Text = "就绪"; BackgroundColor = CK.ColorControl; } public void Done(string doneString) { BackgroundColor = CK.ColorControl; Text = doneString; } public void Error(string error) { BackgroundColor = CK.ColorError; Text = error; } public void Start(string text) { Text = text; BackgroundColor = CK.ColorStart; ; } } } <file_sep> using KCrawler; using System; using System.ComponentModel; using System.Diagnostics; using System.Windows.Forms; namespace Netscape { public partial class TaskContextMenu : ContextMenuStrip { public event TaskMenuHandler ClickedTask; public int TaskID { get; set; } public TaskContextMenu() { InitializeComponent(); } public TaskContextMenu(IContainer container) { container.Add(this); InitializeComponent(); tsmClearTask.Click += Menu_Click; tsmExportTask.Click += Menu_Click; tsmCloseWnd.Click += Menu_Click; tsmCloseAllButThis.Click += Menu_Click; tsmCloseAll.Click += Menu_Click; } //根据运行状态显示菜单项 internal void ChangeMenuStrip(DownloaderStatus ds) { tsmStart.Enabled = true; tsmStop.Enabled = true; // tsmPause.Enabled = true; switch (ds) { case DownloaderStatus.Running: tsmStart.Enabled = false; break; case DownloaderStatus.Paused: tsmPause.Enabled = false; break; case DownloaderStatus.Stopped: tsmStop.Enabled = false; tsmPause.Enabled = false; break; } } private void Export() { Task.ThreadProc(Task.GetSpiderView(TaskID).Spider.Dump); if (MessageBox.Show(R.CTask_ExportedInfo, Task.GetSpiderView(TaskID).CrawlerInfo.TaskName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) Process.Start(Task.GetSpiderView(TaskID).CrawlerInfo.DownloadFolder); } private void Menu_Click(object sender, EventArgs e) { ToolStripMenuItem tsm = sender as ToolStripMenuItem; if (ClickedTask != null) ClickedTask(tsm, e); switch (tsm.Name) { case "tsmIni": KGeneral.GetInstance(); break; } if (TaskID == 0) return; switch (tsm.Name) { case "tsmDownloadFolder": if (System.IO.Directory.Exists(Task.GetSpiderView(TaskID).CrawlerInfo.DownloadFolder)) Process.Start(Task.GetSpiderView(TaskID).CrawlerInfo.DownloadFolder); break; //case "tsmDeleteTask": // DeleteTask(); // break; case "tsmTask": ACrawler acrawler = new ACrawler(TaskID); acrawler.Show(); break; case "tsmPause": Task.GetSpiderView(TaskID).Spider.Suspend(); break; case "tsmStop": Task.ThreadProc(Task.GetSpiderView(TaskID).Spider.Abort); break; case "tsmClearTask": if (MessageBox.Show(R.CTask_ClearTask + Task.GetSpiderView(TaskID).CrawlerInfo.TaskName, TaskID.ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) Task.GetSpiderView(TaskID).Spider.Clear(); break; case "tsmExportTask": Export(); break; } } internal void ChangeMenuStrip(Type type) { if (type == typeof(CDetails)) { tsmDeleteTask.Visible = false; tsmCloseAllButThis.Visible = true; tsmCloseWnd.Visible = true; tsmCloseAll.Visible = true; sepCDetails.Visible = true; } } } } <file_sep>using System; using System.Text; using System.Windows.Forms; using KCrawler; using System.Net; namespace Netscape { public partial class UcExtract : UCBase { private AddExtractInfo addExtract; private string previewHtml; private Downloader spiderExtract; public string Unicode { get; set; } public UcExtract() { InitializeComponent(); combAddress.DropDownStyle = ComboBoxStyle.DropDown; } internal void SetUrlAddress(string url) { combAddress.Text = url; } public override void BindData() { //listExtractOption.TaskID = TaskID; //listExtractOption.BindExtractOption(); listExtractOptions.BindExtractOptions(TaskID); combAddress.DataSource = ExtractDao.GetUrlHistory(TaskID); combAddress.DisplayMember = "Url"; if (null == addExtract) { addExtract = new AddExtractInfo(TaskID, listExtractOptions.Items.Count); addExtract.ExtractionCallBack += addExtract_ExtractionCallBack; } } private void addExtract_ExtractionCallBack(object sender, EventArgs e) { listExtractOptions.BindExtractOptions(TaskID); } private void lnkHandle_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { addExtract.ShowDialog(); } private void Preview(object url) { try { WebClient c = new WebClient(); string address = url.ToString(); if (!Uri.IsWellFormedUriString(address, UriKind.Absolute)) address = Uri.UriSchemeHttp + Uri.SchemeDelimiter + address; ExtractDao.AddUrl(new UrlHistory() { TaskID = this.TaskID, Url = url.ToString()}); byte[] bt = c.DownloadData(new Uri(address)); previewHtml = string.IsNullOrEmpty(Unicode) ? Encoding.Default.GetString(bt) : Encoding.GetEncoding(Unicode).GetString(bt); } catch (Exception e) { previewHtml = e.Message; } } private void btnPreview_Click(object sender, EventArgs e) { txtSource.Text = R.URL_Requesting; Task.ThreadProc(new System.Threading.ParameterizedThreadStart(Preview), combAddress.Text); if (spiderExtract == null) { spiderExtract = new Downloader(); } if (listExtractOptions.ExtractionList == null || 0 == listExtractOptions.ExtractionList.Count) { txtSource.Text = previewHtml; return; } spiderExtract.CrawlerInfo.ExtractOptionList = listExtractOptions.ExtractionList; spiderExtract.ExtractString(ref previewHtml, -1); txtSource.Text = spiderExtract.CrawlerInfo.ExtractedXml; } } } <file_sep>using System.Collections.Generic; namespace KCrawler { [System.Serializable] public class UrlFrontierQueueManager { Queue<string> lowQueue = new Queue<string>(); Queue<string> belowQueue = new Queue<string>(); Queue<string> normalQueue = new Queue<string>(); Queue<string> aboveQueue = new Queue<string>(); Queue<string> highQueue = new Queue<string>(); public int Count { get { int count = 0; lock (this) { count = lowQueue.Count + belowQueue.Count + normalQueue.Count + aboveQueue.Count + highQueue.Count; } return count; } } public string QueueTotal { get { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(R.Level_5).Append(highQueue.Count); sb.Append(" " + R.Level_4).Append(aboveQueue.Count); sb.Append(" " + R.Level_3).Append(normalQueue.Count); sb.Append(" " + R.Level_2).Append(belowQueue.Count); sb.Append(" " + R.Level_1).Append(lowQueue.Count); return sb.ToString(); } } public void Clear() { lock (this) { lowQueue.Clear(); belowQueue.Clear(); normalQueue.Clear(); aboveQueue.Clear(); highQueue.Clear(); } } public void Enqueue(string url) { lock (this) { normalQueue.Enqueue(url); } } public void Enqueue(string url, FrontierQueuePriority priority) { lock (this) { switch (priority) { case FrontierQueuePriority.Low: lowQueue.Enqueue(url); break; case FrontierQueuePriority.BelowNormal: belowQueue.Enqueue(url); break; case FrontierQueuePriority.Normal: normalQueue.Enqueue(url); break; case FrontierQueuePriority.AboveNormal: aboveQueue.Enqueue(url); break; case FrontierQueuePriority.High: highQueue.Enqueue(url); break; default: normalQueue.Enqueue(url); break; } } } public string Dequeue() { lock (this) { if (highQueue.Count > 0) { return highQueue.Dequeue(); } else if (aboveQueue.Count > 0) { return aboveQueue.Dequeue(); } else if (normalQueue.Count > 0) { return normalQueue.Dequeue(); } else if (belowQueue.Count > 0) { return belowQueue.Dequeue(); } else return lowQueue.Dequeue(); } } } } <file_sep>using System; using System.Collections; namespace KCrawler { [Serializable] public class SimpleBloomFilter { private readonly static int DEFAULT_SIZE = 2 << 24; private readonly static int[] seeds = new int[] { 5, 7, 11, 13, 31, 37, 61 }; private BitArray bits = new BitArray(DEFAULT_SIZE); private SimpleHash[] func = new SimpleHash[seeds.Length]; public SimpleBloomFilter() { for (int i = 0; i < seeds.Length; i++) { func[i] = new SimpleHash(DEFAULT_SIZE, seeds[i]); } } public void Add(String value) { lock (bits.SyncRoot) { foreach (SimpleHash f in func) { bits.Set(f.hash(value), true); } } } public bool Contains(String value) { lock (bits.SyncRoot) { if (value == null) return false; if (String.IsNullOrEmpty(value) || value == "") return true; bool ret = true; foreach (SimpleHash f in func) { ret = ret && bits[f.hash(value)]; } return ret; } } [Serializable] public class SimpleHash { private int cap; private int seed; public SimpleHash(int cap, int seed) { this.cap = cap; this.seed = seed; } public int hash(String value) { int result = 0; int len = value.Length; for (int i = 0; i < len; i++) { result = seed * result + value[i]; } return (cap - 1) & result; } } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace KCrawler { public partial class Downloader { private StringBuilder xmlAppender = new StringBuilder(C.ExportXmlScheme); //配置总揽 public string Overview { get { StringBuilder overview = new StringBuilder(); overview.AppendLine(string.Empty); overview.AppendLine(R.CDetails_TaskID + CrawlerInfo.TaskID); overview.AppendLine("\t" + R.CDetails_TaskName + CrawlerInfo.TaskName); overview.AppendLine("\t" + R.CDetails_EntranceURL + CrawlerInfo.EntranceURL); //if (!string.IsNullOrEmpty(Downloader.CrawlerSets.UserAgent)) // overview.AppendLine("\tUserAgent" + Downloader.CrawlerSets.UserAgent); //if (!string.IsNullOrEmpty(Downloader.CrawlerSets.Cookies)) // overview.AppendLine("\tCookies" + Downloader.CrawlerSets.Cookies); overview.AppendLine("\t" + R.CDetails_DownloadFolder + CrawlerInfo.DownloadFolder); if (!string.IsNullOrEmpty(CrawlerInfo.Unicode)) overview.AppendLine("\t" + R.CDetails_Unicode + CrawlerInfo.Unicode); if (CrawlerInfo.IsInternal) overview.AppendLine("\t" + R.CDetails_IsInternal); if (CrawlerInfo.NotSave) overview.AppendLine("\t" + R.CDetails_NotSave); //日志 overview.AppendLine(R.CDetails_LogCount); overview.AppendLine("\t" + Logger.LogCountText); overview.AppendLine(R.CDetails_QueueCount); overview.AppendLine("\t" + UrlsQueueFrontier.QueueTotal); if (CrawlerInfo.UrlKeyword.Count > 0) { overview.AppendLine(R.CDetails_UrlKeywords); overview.AppendLine(CrawlerInfo.UrlKeywordText); } if (CrawlerInfo.HtmlKeyword.Count > 0) { overview.AppendLine(R.CDetails_Keywords); overview.AppendLine(CrawlerInfo.HtmlKeywordText); } if (CrawlerInfo.Priority.Count > 0) { overview.AppendLine(R.CDetails_Priority); overview.AppendLine(CrawlerInfo.PriorityText); } if (CrawlerInfo.Filter.Count > 0) { overview.AppendLine(R.CDetails_Filter); overview.AppendLine(CrawlerInfo.FilterText); } return overview.ToString(); } } //任务个数详细信息 public string TotalCountInfo { get { StringBuilder total = new StringBuilder(); if (CrawlerInfo.NotSave) total.Append(' ').Append(R.CrawlerSets_NotSave); if (CrawlerInfo.IsInternal) total.Append(' ').Append(R.CrawlerSets_Internal); // if (!string.IsNullOrEmpty(CrawlerSets.UrlKeywordText)) total.Append(' ').Append(R.CDetails_UrlKeywords).Append(CrawlerInfo.UrlKeyword.Count); // if (!string.IsNullOrEmpty(CrawlerSets.UrlKeywords)) total.Append(' ').Append(R.CDetails_Keywords).Append(CrawlerInfo.HtmlKeyword.Count); int c = CrawlerInfo.Priority.Count; if (c > 0) total.Append(' ').Append(R.CrawlerSets_Priority).Append(c); c = CrawlerInfo.Filter.Count; if (c > 0) total.Append(' ').Append(R.CrawlerSets_Filter).Append(c); total.Append(" " + R.Range_FileSize); total.Append(' ').AppendFormat("{0}--{1}", CrawlerInfo.MinMB, KConfig.MaxMB); return total.ToString(); } } //所有爬去文件url public string FileTotalUrls { get { StringBuilder files = new StringBuilder(); for (int i = 0; i < FilePool.Count; i++) files.Append(FilePool[i] + "\r\n"); return files.ToString(); } } private void CrawlerStatusChanged(object sender, CrawlerStatusChangedEventArgs e) { if (StatusChanged != null) { DownloaderStatusChangedEventArgs myEvent = new DownloaderStatusChangedEventArgs(); StatusChanged(this, myEvent); } } public void Suspend() { DoThread(1); } public void Resume() { DoThread(2); } public void Abort() { DoThread(3); } private void DoThread(object status) { if (crawlerThreads == null) return; int s = Convert.ToInt32(status); for (int i = 0; i < crawlerThreads.Length; i++) { if (null == crawlerThreads[i]) continue; switch (s) { case 1: crawlerThreads[i].Suspend(); systemStatus = DownloaderStatus.Paused; continue; case 2: crawlerThreads[i].Resume(); systemStatus = DownloaderStatus.Running; continue; case 3: crawlerThreads[i].Abort(); systemStatus = DownloaderStatus.Stopped; continue; } } Save(); } //保存进度,导出url,error public void Save() { try { Logger.Info(R.Log_Info_SavingQueue); SerialUnit.Save(UrlsQueueFrontier, Path_CacheQueue); Logger.Info(R.Log_Info_SavingUrl); SerialUnit.Save(CrawledUrls, Path_CrawledUrl); SerialUnit.Save(FilePool, Path_FilePool); SerialUnit.Save(BloomFilter, Path_Bloom); SerialUnit.Save(Logger.Log, Path_Log); } catch (Exception e) { Logger.Error("[Save]" + e.Message); } } //清除文件记录 public void Clear() { try { File.Delete(Path_CacheQueue); File.Delete(Path_CrawledUrl); File.Delete(Path_FilePool); File.Delete(Path_Bloom); File.Delete(Path_Log); } catch (Exception e) { Logger.Fatal("[Clear]" + e.Message); } } public void Dump() { Dump(String.Empty); } //dumptype=哪里执行的 public void Dump(string dumpType) { try { //重新还原,导出 if (systemStatus == DownloaderStatus.Stopped && UrlsQueueFrontier== null) Restore(); if (!string.IsNullOrEmpty(dumpType)) dumpType = "[" + dumpType + "]"; string pathDumpLog = Path.Combine(CrawlerInfo.DownloadFolder, dumpType + "Log.txt"); string pathDumpUrls = Path.Combine(CrawlerInfo.DownloadFolder, dumpType + "Urls.txt"); string pathDumpFiles = Path.Combine(CrawlerInfo.DownloadFolder, dumpType + "Files.txt"); //日志 using (StreamWriter writer = new StreamWriter(new FileStream(pathDumpLog, FileMode.OpenOrCreate))) { for (int i = 0; i < Logger.Log.Count; i++) if (Logger[i] != null) writer.WriteLine(Logger[i].LogOutTime); } //文件 using (StreamWriter writer = new StreamWriter(new FileStream(pathDumpFiles, FileMode.OpenOrCreate))) { for (int i = 0; i < FilePool.Count; i++) { writer.WriteLine(FilePool[i]); } } //地址 using (StreamWriter writer = new StreamWriter(new FileStream(pathDumpUrls, FileMode.OpenOrCreate))) { for (int i = 0; i < CrawledUrls.Count; i++) { writer.WriteLine(CrawledUrls[i]); } //const string Path = @"C:\Users\Administrator\Desktop\"; //var porn = File.ReadAllText(Path + "ping.ini", Encoding.Default); //var pornArray = porn.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); //var thunders = pornArray.Where(t => t.StartsWith("thunder")).ToList(); //var flashgets = pornArray.Where(t => t.ToLower().StartsWith("flashget")).ToList(); //var ed2ks = pornArray.Where(t => t.StartsWith("ed2k")).ToList(); //var address = new StringBuilder(); //foreach (var t in thunders) //{ // address.AppendLine(t); //} //foreach (var t in flashgets) //{ // address.AppendLine(t); //} //foreach (var t in ed2ks) //{ // address.AppendLine(t); //} //address.AppendFormat("\r\n\r\nthunders:{0} flashgets:{1} ed2ks:{2}", thunders.Count, flashgets.Count, ed2ks.Count); //File.WriteAllText(Path + "exported.txt", address.ToString(), Encoding.Default); } } catch (Exception e) { Logger.Error("[Dump]" + e.Message); } } /// <summary> /// 展示或内部使用,提取内容 /// </summary> /// <param name="html"></param> /// <param name="extractType"></param> /// <returns></returns> public int ExtractString(ref string html, short extractType) { List<ExtractOption> eString = null; int c = 0; switch (extractType) { case ExtractOption.Option_Links: eString = CrawlerInfo.ExtractLinks; break; case ExtractOption.Option_Content: eString = CrawlerInfo.ExtractContent; break; default: eString = CrawlerInfo.ExtractOptionList; break; } if (eString == null) return 0; if (eString.Count == 0) return 0; string restString; for (int i = 0; i < eString.Count; i++) { eString[i].ExtractedText = String.Empty; switch (eString[i].SplitType) { case ExtractOption.Split_StartLast: int startIndex = html.IndexOf(eString[i].StartString); if (startIndex < 0) continue; restString = html.Substring(eString[i].StartString.Length + startIndex); int lastIndex = restString.IndexOf(eString[i].LastString); if (lastIndex < 0) continue; eString[i].ExtractedText = restString.Substring(0, lastIndex); if (eString[i].ExtractedText.Length > 0) c++; break; case ExtractOption.Split_RegEx: var regex = new Regex(eString[i].RegEx, RegexOptions.IgnoreCase); Match match = regex.Match(html); if (match.Success) { eString[i].ExtractedText = match.Value; c++; } if (ExtractOption.Option_Content == extractType) { var regexGroup = new Regex(eString[i].RegExGroup, RegexOptions.IgnoreCase).Matches(html); StringBuilder collection = new StringBuilder(); foreach (Match m in regexGroup) { collection.AppendLine(m.Value); } if (collection.Length > 0) { eString[i].ExtractedText = collection.ToString(); c++; } } break; } } if (ExtractOption.Option_Content == extractType) { if (!string.IsNullOrEmpty(CrawlerInfo.ExtractedXml)) xmlAppender.Insert(xmlAppender.ToString().LastIndexOf(C.Xml_KSpiderEnd), CrawlerInfo.ExtractedXml); } return c; } //退出和定时导出 public void WriteXmlFile() { if (!Directory.Exists(Path.Combine(CrawlerInfo.DownloadFolder, CrawlerInfo.TaskName))) return; string path = Path.Combine(CrawlerInfo.DownloadFolder, CrawlerInfo.TaskName + DateTime.Now.ToString(C.DateFormatFile) + ".xml"); File.WriteAllText(path, xmlAppender.ToString()); } internal void ClearXmlApplender() { xmlAppender.Remove(0, xmlAppender.Length); xmlAppender.Append(C.ExportXmlScheme); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace KCrawler { public class MimeInfo { private string mime; /// <summary> /// 扩展名,变成小写,没有点,加上 /// </summary> public string DotExtenion { get { return "."+ Extension.ToLower().Trim(); } } public string Extension { get; set; } /// <summary> /// 子类使用 /// </summary> public int MimeID { get; set; } public string Mime { get { return mime.ToLower().Trim(); } set { mime = value; } } public int RowID { get; set; } public string Category { get; set; } public virtual string Text { get { return string.Format("[{0}] {1}", Category, Extension); } } public virtual string EMText { get { return string.Format("[{0}] {1}", Extension, mime); } } /// <summary> /// 父类mimeid /// </summary> public int ID { get; set; } /// <summary> /// 0=普通 1=文件(加入filepool) /// </summary> public short MType { get; set; } } public class MCateInfo { /// <summary> /// 主键mime /// </summary> private string category; public string Category { get { return category.Trim(); } set { category = value.Trim(); } } public string Desc { get; set; } public string DescEn { get; set; } public short OrderNumber { get; set; } } public class PriorityInfo :MimeInfo { public override string Text { get { return string.Format("[Level-{0}]{1}", Priority, DotExtenion); } } public string TaskName { get; set; } public short Priority { get; set; } public FrontierQueuePriority QueuePriority { get { try { return (FrontierQueuePriority)Priority; } catch { return FrontierQueuePriority.Normal; } } } } public class FilterInfo : MimeInfo { public string TaskName { get; set; } } } <file_sep>using System; using KCrawler; namespace Netscape { public partial class UCHtmlKeywords : UCBase { public UCHtmlKeywords() { InitializeComponent(); } private void btnAdd_Click(object sender, EventArgs e) { errorProvider.Clear(); if (string.IsNullOrEmpty(txtKeywords.Text)) { errorProvider.SetError(txtKeywords, R.UcKey_EmptyKeyword); return; } HtmlKeywordInfo hk = new HtmlKeywordInfo(); hk.KName = string.IsNullOrEmpty(txtName.Text) ? "HKey"+ listHtmlKeyword.Items.Count : txtName.Text; hk.TaskID = TaskID; hk.Keywords = txtKeywords.Text; KeywordDao.AddKeyword(hk); txtName.Clear(); txtKeywords.Clear(); listHtmlKeyword.BindHtml(); } internal new void BindData() { listHtmlKeyword.TaskID = TaskID; listHtmlKeyword.BindHtml(); } } } <file_sep>using System.ComponentModel; using System.Windows.Forms; namespace Netscape { public partial class StatusBar : Label, IStatus { public StatusBar() { InitializeComponent(); } public StatusBar(IContainer container) { container.Add(this); InitializeComponent(); } public void Done() { Text = "就绪"; BackColor = CK.ColorControl; } public void Done(string text) { Text = text; BackColor = CK.ColorControl; } public void Error(string text) { BackColor = CK.ColorError; Text = text; } public void Start(string text) { BackColor = CK.ColorStart; Text = text; } } } <file_sep>using KCrawler; using System; using System.ComponentModel; using System.Windows.Forms; namespace Netscape { public partial class TaskDetailView : ListViewAdvanced { private ExcelSets excelSets; private CrawlerSets crawlerSets; public string TaskID { get; set; } public TaskDetailView() { InitializeComponent(); } public TaskDetailView(IContainer container) { container.Add(this); InitializeComponent(); } public void BindData() { if (String.IsNullOrEmpty(TaskID)) return; if (excelSets == null) excelSets = new ExcelSets(TaskID); if (crawlerSets == null) crawlerSets = new CrawlerSets(TaskID); // Items.Clear(); // ListViewItemCollection itemC = new ListViewItemCollection(this); // //ListViewItem lvi =new ListViewItem() //int index = 0; // itemC.Add(new ListViewItem("fsfsdf",Groups[0])); // itemC[index].Group = Groups[0]; //foreach (string k in crawlerSets.KeywordList) //{ // if (string.IsNullOrEmpty(k)) // continue; // itemC.Add(k); // itemC[index].Group = Groups["lvgKeywords"]; // //Groups["lvgKeywords"].Items.Add(itemC[index]); // // index++; //} //foreach (string uk in crawlerSets.UrlKeywordList) //{ // if (string.IsNullOrEmpty(uk)) // continue; // itemC.Add(uk); // itemC[index++].Group = Groups["lvgUrlKeywords"]; //} //foreach (PriorityInfo pi in excelSets.Priority) //{ // itemC.Add(pi.Text); // itemC[index++].Group = Groups["lvgPiroity"]; //} //foreach (FilterInfo fi in excelSets.Filter) //{ // itemC.Add( new ListViewItem( fi.Text, Groups["lvgFilter"])); //} // Items.AddRange(itemC); } } } <file_sep>using System; using System.Text; namespace KCrawler { public class ExtractOption { private string extractedText; public const short Option_Links = 0; public const short Option_Content = 1; public const short Split_StartLast = 0; public const short Split_RegEx = 1; public int TaskID { get; set; } public int ID { get; set; } public string StartString { get; set; } public string LastString { get; set; } public short ExtractType { get; set; } public string Label { get; set; } public string StringFormat { get; set; } public short SplitType { get; set; } public string SplitTypeText { get { switch (SplitType) { case Split_StartLast: return R.Extract_Split_StartLast; case Split_RegEx: return R.Extract_Split_RegEx; default: return SplitType.ToString(); } } } public string ExtractTypeName { get { switch (ExtractType) { case Option_Links: return R.Extract_Links; case Option_Content: return R.Extract_Content; default: return String.Empty; } } } public string Text { get { return string.Format(C.Bracket, ExtractTypeName + ":" + Label, ExtractedText); } } public string ExtractedText { get { return extractedText; } set { extractedText = value; } } public string XmlItem { get { StringBuilder x = new StringBuilder(); x.AppendFormat("\t\r\n<{0}>", Label); x.AppendLine("\t\r\n<![CDATA[" + ExtractedText + "]]>"); x.AppendFormat("</{0}>", Label); return x.ToString(); } } public string RegEx { get; set; } public string RegExGroup { get; set; } } public class UrlHistory { public string Url { get; set; } public int TaskID { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using KCrawler; namespace Netscape { public partial class UcUrlKeyword : UCBase { public UcUrlKeyword() { InitializeComponent(); } private void btnAdd_Click(object sender, EventArgs e) { errorProvider.Clear(); if (string.IsNullOrEmpty(txtKeywords.Text)) { errorProvider.SetError(txtKeywords, R.UcKey_EmptyKeyword); return; } UrlKeywordInfo hk = new UrlKeywordInfo(); hk.KName = string.IsNullOrEmpty(txtName.Text) ? "UKey" + listUrlKeyword.Items.Count : txtName.Text; hk.TaskID = TaskID; hk.Keywords = txtKeywords.Text; KeywordDao.AddKeyword(hk); listUrlKeyword.BindUrl(); txtName.Clear(); txtKeywords.Clear(); } public override void BindData() { listUrlKeyword.TaskID = TaskID; listUrlKeyword.BindUrl(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace KCrawler { public class HtmlKeywordInfo { public int ID { get; set; } public string KName { get; set; } public string Keywords { get; set; } public int TaskID { get; set; } public string KOutput { get { return string.Format(C.Bracket, KName, Keywords); } } public List<string> KeywordList { get { if (string.IsNullOrEmpty(Keywords)) return null; int pos = Keywords.IndexOf(','); if (Keywords.Length > 0 && pos > -1) return new List<string>(Keywords.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)); return new List<string>() { Keywords }; } } } public class UrlKeywordInfo : HtmlKeywordInfo { } public class CookieInfo { public int ID { get; set; } public string Url { get; set; } public string UserAgent { get; set; } public string Cookies { get; set; } public int TaskID { get; set; } public string CookieListItem { get { return string.Format(C.Bracket, Url, Cookies); } } } } <file_sep>using System; using KCrawler; namespace Netscape { public partial class UCCookies : UCBase { public UCCookies() { InitializeComponent(); } public override void BindData() { listCookies.TaskID = TaskID; listCookies.BindCookies(); } private void btnAdd_Click(object sender, EventArgs e) { errorProvider.Clear(); if (string.IsNullOrEmpty(txtUrl.Text)) { errorProvider.SetError(txtUrl, R.EmptyInfo); return; } if (string.IsNullOrEmpty(txtUserAgent.Text)) { errorProvider.SetError(txtUserAgent, R.EmptyInfo); return; } if (string.IsNullOrEmpty(txtCookies.Text)) { errorProvider.SetError(txtCookies, R.EmptyInfo); return; } CookieInfo ci = new CookieInfo(); ci.Url = txtUrl.Text.ToLower(); ci.Cookies = txtCookies.Text; ci.UserAgent = txtUserAgent.Text; ci.TaskID = TaskID; KeywordDao.AddCookies(ci); listCookies.BindCookies(); txtCookies.Clear(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using KCrawler; namespace Netscape { public partial class UCFilter : UCBase { public UCFilter() { InitializeComponent(); } public override void BindData() { try { mimeBox.TaskID = TaskID; filterBox.TaskID = TaskID; mimeBox.BindMimeWithoutFilter(); filterBox.BindFilter(); base.BindData(); } catch (Exception e) { mimeBox.Items.Add(e.Message); } } private void btnFilter_Click(object sender, EventArgs e) { var btn = sender as Button; if (btn == btnFilterAll) mimeBox.SelectAll(); try { ListBox.SelectedObjectCollection list = mimeBox.SelectedItems; if (list.Count == 0) return; List<int> filterList = new List<int>(); for (int i = 0; i < list.Count; i++) { var f = list[i] as MimeInfo; filterList.Add(f.ID); } PriorityFilterDao.AddFilter(TaskID, filterList); BindData(); } catch (Exception exp) { MessageBox.Show(exp.Message); } } private void filterBox_MimeJobFinished(object sender, EventArgs e) { mimeBox.BindMimeWithoutFilter(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace KCrawler { public enum LogLevel { Saved = 0, Fatal = 1, Error = 2, Warn = 4, Info = 8, Debug = 16, Trace = 32, } public enum FrontierQueuePriority : short { Low = 1, BelowNormal = 2, Normal = 3, AboveNormal = 4, High = 5, } public enum CrawlerStatusType :short { Sleep = 0, Fetch =1, // FetchWebContent Parse=2, // ParseWebPage Save=3, // SaveToRepository } public enum DownloaderStatus : short { Stopped =0, Running =1, Paused =2 } public enum CrawlerStatusChangedEventType { } public delegate void CrawlerStatusChangedEventHandler(object sender, CrawlerStatusChangedEventArgs e); public class CrawlerStatusChangedEventArgs : EventArgs { public CrawlerStatusChangedEventType EventType { get; set; } } } <file_sep> namespace KCrawler { using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; public class SerialUnit { /// <summary> /// 把对象序列化为字节数组 /// </summary> private static byte[] SerializeObject(object obj) { if (obj == null) return null; MemoryStream ms = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; byte[] bytes = new byte[ms.Length]; ms.Read(bytes, 0, bytes.Length); ms.Close(); return bytes; } /// <summary> /// 把字节数组反序列化成对象 /// </summary> private static object DeserializeObject(byte[] bytes) { object obj = null; if (bytes == null) return obj; MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; BinaryFormatter formatter = new BinaryFormatter(); obj = formatter.Deserialize(ms); ms.Close(); return obj; } // 把对象保存成二进制文件 public static void Save(object obj, string fileName) { byte[] buffer = SerializeObject(obj); FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate); fs.Write(buffer, 0, buffer.Length); fs.Close(); } // 把二进制文件转换成对象 public static object Open(string fileName) { if (!File.Exists(fileName)) return null; IFormatter formatter = new BinaryFormatter(); Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); if (stream.Length == 0) return null; object o = formatter.Deserialize(stream); stream.Close(); return o; } } }<file_sep>using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace Netscape { public partial class RichTextAdvanced : RichTextBox { public delegate void LogAppendDelegate(Color color, string text); public RichTextAdvanced() { InitializeComponent(); } public RichTextAdvanced(IContainer container) { container.Add(this); InitializeComponent(); } private void RichTextAdvanced_LinkClicked(object sender, LinkClickedEventArgs e) { System.Diagnostics.Process.Start(e.LinkText); } public void AppendLine(string text) { AppendText(text + "\r\n"); } private void Append() { } public void AppendLine(Color color, string val) { if (string.IsNullOrEmpty(val)) return; int p1 = TextLength; //取出未添加时的字符串长度。 AppendText(val + "\r\n"); //保留每行的所有颜色。 // rtb.Text += strInput + "/n"; //添加时,仅当前行有颜色。 int p2 = val.Length; //取出要添加的文本的长度 Select(p1, p2); //选中要添加的文本 SelectionColor = color; //设置要添加的文本的字体色 } } } <file_sep>using System; using System.Windows.Forms; using KCrawler; using System.Threading; using System.IO; namespace Netscape { public partial class ACrawler : Form { private string previousUrl; private TaskInfo taskInfo; //新建 public ACrawler() { InitializeComponent(); } //access 整形taskid public ACrawler(int taskid) { InitializeComponent(); if (null == taskInfo) { taskInfo = TaskDao.GetTaskInfo(taskid); ucCookies1.TaskID = taskInfo.ID; ucPriority.TaskID = taskInfo.ID; //如果设置优先级,偏好为默认 ucPriority.PriorityLevelClicked += delegate { taskInfo.Category = string.Empty; listPreference.SelectedIndex = 0; }; ucFilter.TaskID = taskInfo.ID; ucUrlKeyword1.TaskID = taskInfo.ID; ucHtmlKeywords1.TaskID = taskInfo.ID; ucExtract1.TaskID = taskInfo.ID; listPreference.SelecteMCate(taskInfo.Category); } InitializeTask(); } //初始化 private void ACrawler_Shown(object sender, EventArgs e) { //清空task=0 TaskDao.DeleteTask(false, 0); listPreference.SelectionMode = SelectionMode.One; listPreference.BindMimeCategory(); if (null != taskInfo) { listPreference.SelecteMCate(taskInfo.Category); } else { numMinFileSize.Value = KConfig.GetMinKB(String.Empty); } lbFolder.Text = R.ACrawler_DownloadFolderInfo + InteropPlus.TaskFolder; chkFilterAll.Checked = KConfig.IsFilterAll; chkInsertUKey.Checked = KConfig.IsAddUrlKeyword; lbKeyword.Text += PFCache.LabelForMCate; } private void ACrawler_FormClosing(object sender, FormClosingEventArgs e) { if (taskInfo == null) TaskDao.DeleteTask(false, 0); } //access数据 private void InitializeTask() { Text = taskInfo.ID.ToString() + " " + taskInfo.TaskName; //替换回来 previousUrl = txtUrl.Text = taskInfo.EntranceURL.Replace(",", "\r\n"); drpUnicode.Text = taskInfo.Unicode; txtTaskName.Text = taskInfo.TaskName.Trim(); threadsCount.Value = taskInfo.ThreadCount; sleepTime.Value = taskInfo.ThreadSleepTimeWhenQueueIsEmpty; connectionTimeout.Value = taskInfo.ConnectionTimeout; txtDownloadFolder.Text = taskInfo.DownloadFolder; cbInternal.Checked = taskInfo.IsInternal; cbNotSave.Checked = taskInfo.NotSave; txtDescription.Text = taskInfo.Description; numMinFileSize.Value = taskInfo.MinFileSize; } private void AddTaskInfo() { errorProvider.Clear(); if (string.IsNullOrEmpty(txtTaskName.Text)) { errorProvider.SetError(txtTaskName, R.Empty_TaskName); txtTaskName.Focus(); return; } tabControlSettings.SelectedTab = tabBasic; //入口地址判断 try { Uri uri = new Uri(txtUrl.Text); } catch (Exception eUrl) { errorProvider.SetError(txtUrl, eUrl.Message); txtUrl.Focus(); return; } if (string.IsNullOrEmpty(txtDownloadFolder.Text)) { txtDownloadFolder.Text = InteropPlus.TaskFolder + txtTaskName.Text; try { if (!Directory.Exists(txtDownloadFolder.Text)) Directory.CreateDirectory(txtDownloadFolder.Text); } catch (Exception exp) { errorProvider.SetError(txtDownloadFolder, exp.Message); return; } } bool isNew = false; if (null == taskInfo) { isNew = true; taskInfo = new TaskInfo(); } taskInfo.EntranceURL = txtUrl.Lines.Length == 1 ? txtUrl.Lines[0] : txtUrl.Text.Replace("\r\n", ","); taskInfo.ThreadCount = Convert.ToInt32(threadsCount.Value); taskInfo.ThreadSleepTimeWhenQueueIsEmpty = Convert.ToInt32(sleepTime.Value); taskInfo.ConnectionTimeout = Convert.ToInt32(connectionTimeout.Value); taskInfo.DownloadFolder = txtDownloadFolder.Text; taskInfo.TaskName = txtTaskName.Text; taskInfo.IsInternal = cbInternal.Checked; taskInfo.NotSave = cbNotSave.Checked; taskInfo.Description = txtDescription.Text; taskInfo.MinFileSize = Convert.ToInt32(numMinFileSize.Value); if (drpUnicode.SelectedIndex == 0) taskInfo.Unicode = string.Empty; else taskInfo.Unicode = drpUnicode.Text; //添加完毕后获得taskid if (isNew) { taskInfo.ID = TaskDao.AddTask(taskInfo); TaskCache.ClearTaskList(); } else { TaskDao.UpdateTask(taskInfo); CTask.UpdateCTask(ref taskInfo); } //更新事先添加好的优先级过滤器cookies listPreference.UpdatePreference(ref taskInfo); //重置任务列表个数 CTask.UpdateCTask(ref taskInfo); Cache.ClearTaskInfo(taskInfo.ID); Task.GetSpiderView(taskInfo.ID).Spider.RefreshTaskInfo(); //配置文件 taskInfo.IsFilterAllMime = KConfig.IsFilterAll = chkFilterAll.Checked; taskInfo.IsAddUkey = KConfig.IsAddUrlKeyword = chkInsertUKey.Checked; KConfig.SetMinFileSize(taskInfo.Category, Convert.ToInt32(numMinFileSize.Value)); Text = txtTaskName.Text; //and send if (previousUrl != taskInfo.EntranceURL) { Thread t = new Thread(new ParameterizedThreadStart(InteropPlus.Send)); t.Start(taskInfo); } Close(); } private void Button_Click(object sender, EventArgs e) { var btn = sender as Button; switch (btn.Name) { case "btnFolder": InteropPlus.BindFolder(ref txtDownloadFolder); break; case "btnCancel": Close(); break; case "btnRedirect": InteropPlus.Redirect(ref txtUrl); return; case "btnOK": AddTaskInfo(); return; } } private void tabBasic_Click(object sender, EventArgs e) { if (null == tabControlSettings.SelectedTab) return; switch (tabControlSettings.SelectedTab.Name) { case "tabBasic": if (null != taskInfo) listPreference.SelecteMCate(taskInfo.Category); return; case "tabHttpHeaders": ucCookies1.BindData(); return; case "tabPriority": ucPriority.BindData(); return; case "tabFilter": ucFilter.BindData(); return; case "tabUrlKeywords": ucUrlKeyword1.BindData(); return; case "tabHtmlKeyword": ucHtmlKeywords1.BindData(); return; case "tabExtract": ucExtract1.BindData(); if (null != taskInfo) ucExtract1.SetUrlAddress(taskInfo.EntranceURL); return; } } private void drpUnicode_SelectedIndexChanged(object sender, EventArgs e) { ucExtract1.Unicode = drpUnicode.Text; } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Text; namespace KCrawler { public class PreferenceDao { private readonly static AccessHelper db = new AccessHelper(); public static List<MCateInfo> GetMimeCategoryList() { StringBuilder strSql = new StringBuilder(); strSql.Append("select Category,Desc,DescEn,OrderNumber "); strSql.Append(" FROM MCate ORDER BY OrderNumber"); var list = new List<MCateInfo>(); //默认 list.Add(new MCateInfo { Category = string.Empty, Desc = R.MCate_Default, OrderNumber = 0 }); using (IDataReader dataReader = db.ExecuteReader(strSql.ToString())) { while (dataReader.Read()) { list.Add(MCateReaderBind(dataReader)); } } return list; } static MCateInfo MCateReaderBind(IDataReader dataReader) { var model = new MCateInfo(); model.Category = dataReader["Category"].ToString(); model.Desc = dataReader["Desc"].ToString(); model.DescEn = dataReader["DescEn"].ToString(); model.OrderNumber = Convert.ToInt16(dataReader["OrderNumber"]); return model; } /// <summary> /// 更新个人喜好到优先级 urkeyword中的 Kname=category /// </summary> public static void UpdatePreference(TaskInfo ti) { StringBuilder sql = new StringBuilder(); //重置优先级 sql.Append("DELETE * FROM Priority WHERE Taskid=").Append(ti.ID); db.ExecuteNonQuery(sql.ToString()); //添加优先级 sql.Remove(0, sql.Length); sql.AppendFormat("INSERT INTO {0} (MimeID,TaskID,Priority) ", C.T_Priority); sql.AppendFormat("SELECT ID,{0},5 FROM Mime WHERE Category = '{1}'", ti.ID, ti.Category); sql.Append(""); db.ExecuteNonQuery(sql.ToString()); //关键字 if (ti.IsAddUkey) { sql.Remove(0, sql.Length); sql.AppendFormat("DELETE * FROM UrlKeyword WHERE KName IN ({0}) AND TaskID={1} ", PFCache.MCateString, ti.ID); db.ExecuteNonQuery(sql.ToString()); //添加扩展名到keywords sql.Remove(0, sql.Length); sql.Append("INSERT INTO UrlKeyword (KName,Keywords,TaskID) "); sql.AppendFormat("SELECT '{0}',Extension, {1} FROM Mime WHERE Category = '{2}'", ti.Category, ti.ID, ti.Category); db.ExecuteNonQuery(sql.ToString()); //如果是文件类型则添加非http协议关键字 if (ti.Category == "File") { sql.Remove(0, sql.Length); sql.Append("INSERT INTO UrlKeyword (KName,Keywords,TaskID) "); sql.AppendFormat("SELECT '{0}',[Prefix], {1} FROM [Protocol]", ti.Category, ti.ID, ti.Category); db.ExecuteNonQuery(sql.ToString()); } } //domain插入添加主域名到urlkeyword if (ti.IsInternal) { sql.Remove(0, sql.Length); sql.AppendFormat("SELECT count(keywords) FROM UrlKeyword WHERE Keywords = '{0}' AND TaskID={1}", ti.Domain, ti.ID); object o = db.ExecuteScalar(sql.ToString()); if (Convert.ToInt16(o) == 0) { sql.Remove(0, sql.Length); sql.AppendFormat("INSERT INTO UrlKeyword (KName,Keywords,TaskID) VALUES('Domain','{0}','{1}') ", ti.Domain, ti.ID); db.ExecuteNonQuery(sql.ToString()); } } else { sql.Remove(0, sql.Length); sql.AppendFormat("INSERT INTO UrlKeyword (KName,Keywords,TaskID) VALUES('Domain','{0}',{1}) ", ti.Domain, ti.ID); db.ExecuteNonQuery(sql.ToString()); } if (ti.IsFilterAllMime) { //重置Filter sql.Remove(0, sql.Length); sql.Append("DELETE * FROM Filter WHERE Taskid=").Append(ti.ID); db.ExecuteNonQuery(sql.ToString()); //过滤除了优先级以外的文件 sql.Remove(0, sql.Length); sql.Append(" INSERT INTO [Filter] ( TaskID, MimeID ) "); sql.AppendFormat(" SELECT {0}, ID ", ti.ID); sql.Append(" FROM Mime "); sql.Append(" WHERE 1=1"); //sql.AppendFormat(" AND Mime.[id] Not In (select mimeid from Filter where taskid={0}) ", ti.ID); sql.AppendFormat(" AND Mime.[id] Not In (select mimeid from Priority where taskid={0}) ", ti.ID); db.ExecuteNonQuery(sql.ToString()); } TaskDao.UpdateCategory(ti.ID, ti.Category); } } } <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Text; namespace KCrawler { public class TaskDao { private readonly static AccessHelper db = new AccessHelper(); private static int LastTaskID { get { return Convert.ToInt32(db.ExecuteScalar("SELECT max(ID) FROM [task] ")); } } /// <summary> /// 返回task id /// </summary> /// <param name="model"></param> /// <returns></returns> public static int AddTask(TaskInfo model) { StringBuilder strSql = new StringBuilder(); strSql.Append("INSERT INTO Task("); strSql.Append("TaskName,NotSave,Unicode,DownloadFolder,IsInternal,EntranceURL,ThreadCount,ConnectionTimeout,ThreadSleepTimeWhenQueueIsEmpty,MinFileSize,Description,IsPreference)"); strSql.Append(" values ("); strSql.Append("@TaskName,@NotSave,@Unicode,@DownloadFolder,@IsInternal,@EntranceURL,@ThreadCount,@ConnectionTimeout,@ThreadSleepTimeWhenQueueIsEmpty,@MinFileSize,@Description,@IsPreference)"); db.AddInParameter("TaskName", DbType.AnsiString, model.TaskName); db.AddInParameter("NotSave", DbType.Boolean, model.NotSave); db.AddInParameter("Unicode", DbType.AnsiString, model.Unicode); db.AddInParameter("DownloadFolder", DbType.AnsiString, model.DownloadFolder); db.AddInParameter("IsInternal", DbType.Boolean, model.IsInternal); db.AddInParameter("EntranceURL", DbType.AnsiString, model.EntranceURL); db.AddInParameter("ThreadCount", DbType.String, model.ThreadCount); db.AddInParameter("ConnectionTimeout", DbType.String, model.ConnectionTimeout); db.AddInParameter("ThreadSleepTimeWhenQueueIsEmpty", DbType.String, model.ThreadSleepTimeWhenQueueIsEmpty); db.AddInParameter("MinFileSize", DbType.Int32, model.MinFileSize); db.AddInParameter("Description", DbType.AnsiString, model.Description); db.AddInParameter("IsPreference", DbType.Boolean, model.IsPreference); db.ExecuteNonQuery(strSql.ToString()); model.ID = LastTaskID; //事先设置的全部更新 UpdateTaskID(model.ID); return model.ID; } /// <summary> /// 更新任务 acrawler /// </summary> public static bool UpdateTask(TaskInfo model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update Task set "); strSql.Append("TaskName=@TaskName,"); strSql.Append("NotSave=@NotSave,"); strSql.Append("Unicode=@Unicode,"); strSql.Append("DownloadFolder=@DownloadFolder,"); strSql.Append("IsInternal=@IsInternal,"); strSql.Append("EntranceURL=@EntranceURL,"); strSql.Append("ThreadCount=@ThreadCount,"); strSql.Append("ConnectionTimeout=@ConnectionTimeout,"); strSql.Append("ThreadSleepTimeWhenQueueIsEmpty=@ThreadSleepTimeWhenQueueIsEmpty,"); strSql.Append("MinFileSize=@MinFileSize,"); strSql.Append("Description=@Description,"); strSql.Append("IsPreference=@IsPreference,"); strSql.Append("[CreateTime]=@CreateTime "); strSql.Append(" where ID=@ID "); db.AddInParameter("TaskName", DbType.AnsiString, model.TaskName); db.AddInParameter("NotSave", DbType.Boolean, model.NotSave); db.AddInParameter("Unicode", DbType.AnsiString, model.Unicode); db.AddInParameter("DownloadFolder", DbType.AnsiString, model.DownloadFolder); db.AddInParameter("IsInternal", DbType.Boolean, model.IsInternal); db.AddInParameter("EntranceURL", DbType.AnsiString, model.EntranceURL); db.AddInParameter("ThreadCount", DbType.String, model.ThreadCount); db.AddInParameter("ConnectionTimeout", DbType.String, model.ConnectionTimeout); db.AddInParameter("ThreadSleepTimeWhenQueueIsEmpty", DbType.String, model.ThreadSleepTimeWhenQueueIsEmpty); db.AddInParameter("MinFileSize", DbType.Int32, model.MinFileSize); db.AddInParameter("Description", DbType.AnsiString, model.Description); db.AddInParameter("IsPreference", DbType.Boolean, model.IsPreference); db.AddInParameter("CreateTime", DbType.AnsiString, DateTime.Now); db.AddInParameter("ID", DbType.Int32, model.ID); int rows = db.ExecuteNonQuery(strSql.ToString()); if (rows > 0) { return true; } else { return false; } } public static void AddTaskViaPreference(int taskID) { //1 插入task StringBuilder sql = new StringBuilder(); sql.Append(" INSERT INTO Task ( [TaskName] , [NotSave] , [Unicode] , [DownloadFolder] , [IsInternal] , [EntranceURL] , "); sql.Append(" [ThreadCount] , [ConnectionTimeout] , [ThreadSleepTimeWhenQueueIsEmpty] , [MinFileSize] , [Description] , [IsPreference] ) "); sql.Append(" SELECT [TaskName] , [NotSave] , [Unicode] , [DownloadFolder] , [IsInternal] , [EntranceURL] , "); sql.Append(" [ThreadCount] , [ConnectionTimeout] , [ThreadSleepTimeWhenQueueIsEmpty] , [MinFileSize] , [Description] , false "); sql.Append(" From [task] "); sql.Append(" WHERE IsPreference =true and id= ").Append(taskID); db.ExecuteNonQuery(sql.ToString()); //2 获取新增taskid int newID = LastTaskID; //3 增加优先级 sql.Remove(0, sql.Length); sql.Append(" INSERT INTO [Priority] ( TaskID, MimeID ) "); sql.Append(" SELECT {0} , MimeID FROM Priority WHERE TaskID={1}; ", newID, taskID); db.ExecuteNonQuery(sql.ToString()); //4 添加过滤 sql.Remove(0, sql.Length); sql.Append(" INSERT INTO [Filter] ( TaskID, MimeID ) "); sql.Append(" SELECT {0} , MimeID FROM Filter WHERE TaskID={1}; ", newID, taskID); db.ExecuteNonQuery(sql.ToString()); } public static void DeleteTask(bool isDeleteTaskInfo, int taskID) { string sql = " DELETE * FROM Task WHERE ID= " + taskID.ToString(); if (isDeleteTaskInfo) db.ExecuteNonQuery(sql); sql = " DELETE * FROM Priority WHERE TaskID= " + taskID.ToString(); db.ExecuteNonQuery(sql); sql = " DELETE * FROM Filter WHERE TaskID= " + taskID.ToString(); db.ExecuteNonQuery(sql); sql = " DELETE * FROM HtmlKeyword WHERE TaskID= " + taskID.ToString(); db.ExecuteNonQuery(sql); sql = " DELETE * FROM UrlKeyword WHERE TaskID= " + taskID.ToString(); db.ExecuteNonQuery(sql); sql = " DELETE * FROM [Cookies] WHERE TaskID= " + taskID.ToString(); db.ExecuteNonQuery(sql); sql = " DELETE * FROM [Extract] WHERE TaskID= " + taskID.ToString(); db.ExecuteNonQuery(sql); } /// <summary> /// 新建爬虫,未确定则更新0 /// </summary> /// <param name="taskID"></param> public static void DeleteTask(int taskID) { DeleteTask(true, taskID); } /// <summary> /// 新建任务或修改任务后更新 /// </summary> /// <param name="taskid"></param> public static void UpdateTaskID( int taskid ) { const string sql = " UPDATE [{0}] SET TaskID = {1} WHERE TaskID= 0 "; db.ExecuteNonQuery(string.Format(sql,"Priority",taskid)); db.ExecuteNonQuery(string.Format(sql, "Filter", taskid)); db.ExecuteNonQuery(string.Format(sql, "HtmlKeyword", taskid)); db.ExecuteNonQuery(string.Format(sql, "UrlKeyword", taskid)); db.ExecuteNonQuery(string.Format(sql, "Cookies", taskid)); db.ExecuteNonQuery(string.Format(sql, "Extract", taskid)); } public static List<TaskInfo> GetPreferenceList() { const string sql = "SELECT * FROM Task WHERE IsPreference =true ORDER BY CreateTime DESC "; var list = new List<TaskInfo>(); using (IDataReader dataReader = db.ExecuteReader(sql)) { while (dataReader.Read()) { TaskInfo ti = ReaderBind(dataReader); list.Add(ti); } } return list; } public static List<TaskInfo> GetTaskList() { const string sql = "SELECT * FROM Task WHERE IsPreference =false ORDER BY CreateTime DESC "; var list = new List<TaskInfo>(); using (IDataReader dataReader = db.ExecuteReader(sql)) { while (dataReader.Read()) { TaskInfo ti = ReaderBind(dataReader); list.Add(ti); } } return list; } public static TaskInfo GetTaskInfo(int id) { string sql = "SELECT TOP 1 * FROM Task WHERE ID= " + id.ToString(); TaskInfo ti = new TaskInfo(); using (IDataReader dataReader = db.ExecuteReader(sql)) { if (dataReader.Read()) { ti = ReaderBind(dataReader); } } ti.HtmlKeyword = KeywordDao.GetHtmlKeywordList(id); ti.UrlKeyword = KeywordDao.GetUrlKeywordList(id); ti.CookieList = KeywordDao.GetCookieList(id); ti.Filter = PriorityFilterDao.GetFilter(id); ti.Priority = PriorityFilterDao.GetPriority(id); ti.ExtractOptionList = ExtractDao.GetOptionList(id); return ti; } private static TaskInfo ReaderBind(IDataReader dataReader) { TaskInfo model = new TaskInfo(); object ojb; model.TaskName = dataReader["TaskName"].ToString(); ojb = dataReader["NotSave"]; if (ojb != null && ojb != DBNull.Value) { model.NotSave = (bool)ojb; } model.Unicode = dataReader["Unicode"].ToString(); model.DownloadFolder = dataReader["DownloadFolder"].ToString(); ojb = dataReader["IsInternal"]; if (ojb != null && ojb != DBNull.Value) { model.IsInternal = (bool)ojb; } model.EntranceURL = dataReader["EntranceURL"].ToString(); model.ThreadCount = Convert.ToInt32(dataReader["ThreadCount"]); model.ConnectionTimeout = Convert.ToInt32(dataReader["ConnectionTimeout"]); model.ThreadSleepTimeWhenQueueIsEmpty = Convert.ToInt32(dataReader["ThreadSleepTimeWhenQueueIsEmpty"]); model.MinFileSize = Convert.ToInt32(dataReader["MinFileSize"]); ojb = dataReader["ID"]; if (ojb != null && ojb != DBNull.Value) { model.ID = (int)ojb; } model.Description = dataReader["Description"].ToString(); ojb = dataReader["IsPreference"]; if (ojb != null && ojb != DBNull.Value) { model.IsPreference = (bool)ojb; } model.Category = dataReader["Category"].ToString(); return model; } public static void UpdateCategory(int taskid, string category) { string sql =string.Format("UPDATE [Task] SET [Category]='{0}' WHERE ID={1}", category, taskid); db.ExecuteNonQuery(sql.ToString()); } } } <file_sep> namespace Netscape { using System.Windows.Forms; using System; using System.Diagnostics; public partial class KMain : Form { private CTask ctask = new CTask(); // private CDetails cDetails; private StartWnd start = null; public KMain() { InitializeComponent(); } private void Init() { ctask.Show(dockPanel); ctask.DownloaderSelected += ctask_DownloaderSelected; ctask.CrawlerStatusChanged += CrawlerDetailForm_CrawlerStatusChanged; start = new StartWnd(); start.Show(dockPanel); notifyIcon.BalloonTipText = R.KMain_BallonWelcome + Task.Pool.Count.ToString(); notifyIcon.ShowBalloonTip(2000); } //左侧task窗体,传输过来的窗口 private void ctask_DownloaderSelected(object sender, CTaskEventArgs e) { e.CrawlerDetailForm.Show(dockPanel); e.CrawlerDetailForm.CrawlerStatusChanged += CrawlerDetailForm_CrawlerStatusChanged; } private void CrawlerDetailForm_CrawlerStatusChanged(object sender, StatusEventArgs e) { if (string.IsNullOrEmpty(e.Text)) return; statusBottom.BackColor = e.BackgroundColor; statusBottom.Text = e.Text; notifyIcon.Text = e.Text.Length > 63 ? e.Text.Substring(0, 63) : e.Text; if (!e.IsShowOnBallon) return; notifyIcon.BalloonTipText = notifyIcon.Text; notifyIcon.ShowBalloonTip(50); } private void KMain_FormClosing(object sender, FormClosingEventArgs e) { statusBottom.Start(R.KMain_Aborting); notifyIcon.Visible = false; notifyIcon.Dispose(); Task.ThreadProc(Task.Stop); GC.Collect(); e.Cancel = false; } private void MenuAndToolbar_Click(object sender, EventArgs e) { string controlName; if (sender is ToolStripItem) controlName = ((ToolStripItem)sender).Name; else controlName = (sender as ToolBarButton).Name; switch (controlName) { case "tsmTaskFolder": Process.Start(InteropPlus.TaskFolder); return; case "tsmHelp": case "tsmPreference": if (start.IsHidden) start.Show(); start.Help(); return; case "btnIni": case "tsmSysCfg": KGeneral.GetInstance(); return; case "tsmToolbar": toolbar.Visible = toolbar.Visible ? false : true; tsmToolbar.CheckState = tsmToolbar.CheckState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked; return; case "tsmStatusBar": statusBottom.Visible = statusBottom.Visible ? false : true; tsmStatusBar.CheckState = tsmStatusBar.CheckState == CheckState.Checked ? CheckState.Unchecked : CheckState.Checked; return; case "btnNewTask": case "tsmNewTask": case "ntsmNewTask": ACrawler acrawler = new ACrawler(); acrawler.Show(); return; case "tsmTaskView": if (ctask.IsDisposed) ctask.Show(dockPanel); else ctask.Activate(); return; case "tsmActivedTaskWnd": foreach (var kv in Task.Pool) { if (kv.Value.Spider.UrlsQueueFrontier == null) continue; if (kv.Value.IsHidden) kv.Value.Show(dockPanel); } return; case "tsmStart": case "btnStartPage": if (start.IsHidden) start.Show(); StartWnd.WriteJsonCategory(); start.Start(); break; case "btnLaunch": case "tsmLaunch": case "ntsmLaunch": statusBottom.Start(R.KMain_Progressing); Task.ThreadProc(Task.Start); statusBottom.Done(R.KMain_Lunch); break; case "btnPause": case "tsmPause": case "ntsmPause": statusBottom.Start(R.KMain_Progressing); Task.ThreadProc(Task.Pause); statusBottom.Done(R.KMain_Pause); break; case "btnStop": case "tsmStop": case "ntsmStop": statusBottom.Start(R.KMain_Progressing); Task.ThreadProc(Task.Stop); statusBottom.Done(R.KMain_Stop); break; case "btnKCawlerWeb": Process.Start("http://www.easyfound.com.cn/KCrawler"); return; case "tsmKingsure": Process.Start("http://www.easyfound.com.cn"); return; case "tsmExit": case "ntsmExit": Close(); return; case "tsmExport": statusBottom.Start(R.KMain_Progressing); Task.ThreadProc(Task.Dump); statusBottom.Done(); return; case "tsmDB": case "btnDB": Process.Start(CK.KSpider_Database); return; } } private void notifyIcon_Click(object sender, EventArgs e) { if (WindowState == FormWindowState.Minimized) WindowState = FormWindowState.Normal; Activate(); } private void KMain_Shown(object sender, EventArgs e) { Init(); } } } <file_sep>using System; namespace KCrawler { public class CrawleHistroyEntry { public string Url { get; set; } public DateTime Timestamp { get; set; } // 时间戳 public long Size { get; set; } } } <file_sep> namespace KCrawler { using System.Collections.Generic; using System; using System.IO; using System.Threading; using System.Text; using System.Xml; public delegate void DownloaderStatusChangedEventHandler(object sender, DownloaderStatusChangedEventArgs e); public class DownloaderStatusChangedEventArgs : EventArgs { } public partial class Downloader { public event DownloaderStatusChangedEventHandler StatusChanged; //初始化后调用 private string Path_CacheQueue = "CacheQueue"; private string Path_CrawledUrl = "CrawlerUrl"; private string Path_FilePool = "FilePool"; private string Path_Bloom = "Bloom"; private string Path_Log = "a"; public List<string> FileTypes = new List<string>(); private CrawlerThread[] crawlerThreads; private DownloaderStatus systemStatus = DownloaderStatus.Stopped; public string BaseEntranceUrl; //写日志 public Logger Logger { get; set; } // 为了避免重复下载或陷入爬虫陷阱, 只有未被访问的URL才会被加入到队列中去 public List<string> CrawledUrls { get; private set; } public UrlFrontierQueueManager UrlsQueueFrontier { get; set; } public TaskInfo CrawlerInfo { get; set; } //布隆过滤器 internal SimpleBloomFilter BloomFilter { get; private set; } public long SavedCount { get; set; } //下载文件 public List<string> FilePool { get; set; } public Thread InnerThread { get; private set; } public CrawlerThread[] ThreadCrawlers { get { return crawlerThreads; } } //初始化一个下载爬虫则相当于获取或建立一个ini section //打开保存的数据url public Downloader(int taskID) { CrawlerInfo = TaskCache.GetTaskInfo(taskID); CrawlerInfo.IsLunched = true; SavedCount = 1; Logger = new Logger(); systemStatus = DownloaderStatus.Stopped; if (FilePool == null) FilePool = new List<string>(); Path_CrawledUrl = Path.Combine(CrawlerInfo.DownloadFolder, CrawlerInfo.TaskID + "-CrawlerUrl.sav"); Path_FilePool = Path.Combine(CrawlerInfo.DownloadFolder, CrawlerInfo.TaskID + "-FilePool.sav"); Path_CacheQueue = Path.Combine(CrawlerInfo.DownloadFolder, CrawlerInfo.TaskID + "-Queue.sav"); Path_Bloom = Path.Combine(CrawlerInfo.DownloadFolder, CrawlerInfo.TaskID + "-Bloom.sav"); Path_Log = Path.Combine(CrawlerInfo.DownloadFolder, CrawlerInfo.TaskID + "-Log.sav"); } //用于提取内容 public Downloader() { CrawlerInfo = new TaskInfo(); } /// <summary> /// 刷新配置信息 /// </summary> public void RefreshTaskInfo() { if (CrawlerInfo == null) return; CrawlerInfo = TaskCache.GetTaskInfo(CrawlerInfo.ID); } //公开方法,用于dump public void Restore() { try { //队列 object o = SerialUnit.Open(Path_CacheQueue); if (o != null) UrlsQueueFrontier = o as UrlFrontierQueueManager; else UrlsQueueFrontier = new UrlFrontierQueueManager(); //如果队列里面没有url则重新开始,就算是爬虫地址或布隆过滤器已经存在 if (UrlsQueueFrontier.Count == 0) Clear(); o = SerialUnit.Open(Path_CrawledUrl); if (o != null) CrawledUrls = o as List<string>; else CrawledUrls = new List<string>(); //压缩文件 o = SerialUnit.Open(Path_FilePool); if (o != null) FilePool = o as List<string>; else FilePool = new List<string>(); o = SerialUnit.Open(Path_Bloom); //布隆过滤器 if (o != null) BloomFilter = o as SimpleBloomFilter; else BloomFilter = new SimpleBloomFilter(); o = SerialUnit.Open(Path_Log); //日志 if (o != null && o is List<LogInfo>) { Logger.Log = o as List<LogInfo>; SavedCount = Logger.GetCount(LogLevel.Saved); } } catch (Exception e) { Logger.Error(e.Message); } } // 通常爬虫是从一系列种子(Seed)网页开始,然后使用这些网页中的链接去获取其他页面. public void InitSeeds(string[] seeds) { if (UrlsQueueFrontier == null) return; // 使用种子URL进行队列初始化 if (UrlsQueueFrontier.Count > 0) return; foreach (string s in seeds) UrlsQueueFrontier.Enqueue(s); } public void Start() { //初始化,resume和abort刷新 BaseEntranceUrl = CrawlerInfo.Domain; if (systemStatus == DownloaderStatus.Running) return; if (systemStatus == DownloaderStatus.Paused) { Resume(); return; } //还原文件文件 Restore(); //起始种子地址 InitSeeds(new string[] { CrawlerInfo.EntranceURL }); crawlerThreads = new CrawlerThread[CrawlerInfo.ThreadCount]; systemStatus = DownloaderStatus.Running; for (int i = 0; i < crawlerThreads.Length; i++) { CrawlerThread crawler = new CrawlerThread(this); crawler.Name = i.ToString(); crawler.StatusChanged += new CrawlerStatusChangedEventHandler(CrawlerStatusChanged); crawler.Start(); crawlerThreads[i] = crawler; } } /// <summary> /// 如果队列为空并且线程都在睡眠则为停止,另外在线程控制函数中操作 /// </summary> public DownloaderStatus Status { get { if (null == UrlsQueueFrontier) return DownloaderStatus.Stopped; if (systemStatus == DownloaderStatus.Running) { if (UrlsQueueFrontier.Count > 0) return DownloaderStatus.Running; foreach (CrawlerThread ct in crawlerThreads) { if (ct.CThread.ThreadState != ThreadState.WaitSleepJoin) return DownloaderStatus.Running; systemStatus = DownloaderStatus.Stopped; Dump("Done"); WriteXmlFile(); ClearXmlApplender(); // 队列为空并且都waitsleepjoin Abort(); return DownloaderStatus.Stopped; } } return systemStatus; } } //状态文字输出 public string StatusText { get { switch (Status) { case DownloaderStatus.Stopped: return R.DownloaderStatus_Stopped; case DownloaderStatus.Paused: return R.DownloaderStatus_Pause; case DownloaderStatus.Running: return R.DownloaderStatus_Running; } return systemStatus.ToString(); } } } } <file_sep> using KCrawler; using Lv.Docking; using System; using System.Text; using System.Windows.Forms; namespace Netscape { public partial class CDetails : DockContent { private int crawlerUrlIndex = 0; private int loggerIndex = 0; // private int streamFileIndex = 0; private StringBuilder crawlerInfo = new StringBuilder(); public event StatusEventHandler CrawlerStatusChanged; private StatusEventArgs statusArgs = new StatusEventArgs(); public Downloader Spider { get; set; } public CDetails() { InitializeComponent(); timer.Interval = KConfig.Interval; } public int TaskID { get { return Spider.CrawlerInfo.ID; } } public TaskInfo CrawlerInfo { get { return Spider.CrawlerInfo; } } private void Init() { lvThread.Items.Clear(); //初始化最后一次记录的个数 if (Spider.CrawledUrls != null) crawlerUrlIndex = Spider.CrawledUrls.Count; loggerIndex = Spider.Logger.Log.Count; // streamFileIndex = Downloader.StreamFile.Count; TabText = Spider.CrawlerInfo.TaskName; lkFolder.AccessibleName = Spider.CrawlerInfo.DownloadFolder; int index = 0; foreach (CrawlerThread ct in Spider.ThreadCrawlers) { lvThread.Items.Add(ct.Name); lvThread.Items[index].SubItems.Add(ct.CThread.ThreadState.ToString()); lvThread.Items[index].SubItems.Add(ct.StatusText); lvThread.Items[index].SubItems.Add(ct.Url); lvThread.Items[index].SubItems.Add(ct.MimeType); index++; } RefreshInfo(); } private void CDetails_Shown(object sender, System.EventArgs e) { //刷新数据事件 Leave += delegate { timer.Stop(); }; Enter += delegate { //滚动输出间隔 timer.Interval = KConfig.Interval; //初始化最后一次记录的个数 crawlerUrlIndex = Spider.CrawledUrls.Count; loggerIndex = Spider.Logger.Log.Count; //初始化配置值 RefreshInfo(); if (!cbStopOutput.Checked) timer.Start(); }; Init(); timer.Start(); } private void CDetails_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e) { timer.Stop(); Hide(); e.Cancel = true; } //点击,焦点 但不在定时器里面 private void RefreshInfo() { try { txtOutput.AppendLine(Spider.TotalCountInfo); StringBuilder sets = new StringBuilder(); sets.Append(R.CDetails_EntranceURL + Spider.CrawlerInfo.EntranceURL).Append(" "); sets.Append(R.CDetails_DownloadFolder + Spider.CrawlerInfo.DownloadFolder).Append(" "); lbSettings.Text = sets.ToString(); tabDetail.Text = R.CDetails_TaskDetail + (String.IsNullOrEmpty(Spider.TotalCountInfo) ? String.Empty : "[" + Spider.TotalCountInfo + "]"); txtOutput.AppendLine(CK.ColorStart, Spider.Logger.LogCountText); txtOutput.AppendLine(Spider.UrlsQueueFrontier.QueueTotal); if (Spider.FilePool.Count != 0) tpDownload.Text = R.CDetails_FileTotals + Spider.FilePool.Count.ToString(); } catch (Exception exp) { txtOutput.AppendLine(System.Drawing.Color.Red, string.Format(CK.BracketsAndInfo, DateTime.Now, exp.Message)); } } //定时更新 public void RefreshData() { try { lkFolder.AccessibleName = Spider.CrawlerInfo.DownloadFolder; crawlerInfo.Append(R.CDetails_QueueCount + Spider.UrlsQueueFrontier.Count).Append(" "); crawlerInfo.Append(R.CDetails_CrawledUrl + Spider.CrawledUrls.Count).Append(" "); crawlerInfo.Append(R.CDetails_FileTotals + Spider.FilePool.Count).Append(" "); lbTitle.Text = crawlerInfo.ToString(); crawlerInfo.Remove(0, crawlerInfo.Length); //修改线程个数后重置 if (Spider.ThreadCrawlers.Length != lvThread.Items.Count) Init(); for (int i = 0; i < Spider.ThreadCrawlers.Length; i++) { lvThread.Items[i].SubItems[1].Text = Spider.ThreadCrawlers[i].CThread.ThreadState.ToString(); lvThread.Items[i].SubItems[2].Text = Spider.ThreadCrawlers[i].StatusText; lvThread.Items[i].SubItems[3].Text = Spider.ThreadCrawlers[i].Url; lvThread.Items[i].SubItems[4].Text = Spider.ThreadCrawlers[i].MimeType; } //url地址 if (crawlerUrlIndex < Spider.CrawledUrls.Count && Spider.CrawlerInfo.NotSave) { txtOutput.AppendText(String.Format("[{0}] {1} \r\n", crawlerUrlIndex + 1, Spider.CrawledUrls[crawlerUrlIndex])); crawlerUrlIndex++; } //日志 if (loggerIndex < Spider.Logger.Log.Count) { statusArgs.IsShowOnBallon = false; statusArgs.Info(CrawlerInfo.TaskName + Spider.Logger[loggerIndex].LogOut); txtOutput.AppendLine(Spider.Logger[loggerIndex].Color, Spider.Logger[loggerIndex].LogOut); loggerIndex++; //if (CrawlerStatusChanged != null) // CrawlerStatusChanged(null, statusArgs); } //压缩下载文件 //if (streamFileIndex < Spider.FilePool.Count) //{ // statusArgs.Info(Downloader.CrawlerSets.TaskName + " " + R.CDetails_FileTotals + Downloader.FilePool.Count); //txtStreamFiles.AppendText(Downloader.FilePool[streamFileIndex] + Environment.NewLine); //streamFileIndex++; //if (CrawlerStatusChanged != null) // CrawlerStatusChanged(null, statusArgs); //} if (Spider.UrlsQueueFrontier.Count == 0 && Spider.Status == DownloaderStatus.Stopped) { timer.Stop(); statusArgs.IsShowOnBallon = true; statusArgs.Info(Spider.CrawlerInfo.TaskName + " " + R.CDetails_Done); if (CrawlerStatusChanged != null) CrawlerStatusChanged(null, statusArgs); } } catch (Exception exp) { txtOutput.AppendLine(System.Drawing.Color.Red, string.Format(CK.BracketsAndInfo, DateTime.Now, exp.Message)); } } private void timer_Tick(object sender, System.EventArgs e) { if (Spider.Status == DownloaderStatus.Stopped || DownloaderStatus.Paused == Spider.Status) { timer.Stop(); } TabText = CrawlerInfo.TaskName + "[" + Spider.StatusText + "]"; RefreshData(); } private void taskContextMenu_ClickedTask(object sender, EventArgs e) { ToolStripMenuItem tsm = sender as ToolStripMenuItem; switch (tsm.Name) { case "tsmStart": txtOutput.AppendLine(CK.ColorStart, R.KMain_Progressing); Task.ThreadProc(Spider.Start); TabText = CrawlerInfo.TaskName + "[" + Spider.StatusText + "]"; if (!timer.Enabled) timer.Start(); return; case "tsmCloseWnd": Hide(); return; case "tsmCloseAllButThis": Task.HideView( TaskID); return; case "tsmCloseAll": Task.HideView(); return; } } private void taskContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e) { menuCDetails.TaskID = Spider.CrawlerInfo.ID; menuCDetails.ChangeMenuStrip(Spider.Status); menuCDetails.ChangeMenuStrip(this.GetType()); } private void tabBottom_Selected(object sender, TabControlEventArgs e) { if (e.TabPageIndex < 0) return; if (e.TabPage != tpThread) RefreshInfo(); if (e.TabPage == tpDownload) txtStreamFiles.Text = Spider.FileTotalUrls; if (e.TabPage == tabDetail) txtOverview.Text = Spider.Overview; } //timer是否停止 private void cbStopOutput_CheckedChanged(object sender, EventArgs e) { if (cbStopOutput.Checked) { RefreshInfo(); timer.Stop(); } else timer.Start(); } private void lnkHandle_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Spider.Dump(R.Dump_Type_Export); Spider.WriteXmlFile(); if (MessageBox.Show(R.CTask_ExportedInfo, CrawlerInfo.TaskName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) InteropPlus.Redirect(CrawlerInfo.DownloadFolder); } private void lkFolder_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KCrawler { public class Cache { public readonly static Hashtable KCache = Hashtable.Synchronized(new Hashtable()); /// <summary> /// 清空缓存 /// </summary> public static void Clear(string cachePrefix) { if (string.IsNullOrEmpty(cachePrefix)) KCache.Clear(); string key = null; IDictionaryEnumerator enumerator = KCache.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Key.ToString().IndexOf(cachePrefix) > -1) { key = enumerator.Key.ToString(); break; } } if (null != key) KCache.Remove(key); } /// <summary> /// 清空缓存 /// </summary> public static void Clear() { Clear(String.Empty); } public static void ClearTaskList() { Clear(TaskCache.C_TaskList); } public static void ClearTaskInfo(int taskid) { Clear(TaskCache.CachePrefix + "GetTaskInfo" + taskid.ToString()); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KCrawler { public class KeywordCache : Cache { public const string CachePrefix = "KeywordCache"; public static List<UrlKeywordInfo> GetUrlKeywordList(int taskID) { lock (KCache.SyncRoot) { string cacheName = CachePrefix + "GetUrlKeywordList" + taskID.ToString(); if (KCache.ContainsKey(cacheName)) return KCache[cacheName] as List<UrlKeywordInfo>; else { var list = KeywordDao.GetUrlKeywordList(taskID); KCache.Add(cacheName, list); return list; } } } public static List<HtmlKeywordInfo> GetHtmlKeywordList(int taskID) { lock (KCache.SyncRoot) { string cacheName = CachePrefix + "GetHtmlKeywordList" + taskID.ToString(); if (KCache.ContainsKey(cacheName)) return KCache[cacheName] as List<HtmlKeywordInfo>; else { var list = KeywordDao.GetHtmlKeywordList(taskID); KCache.Add(cacheName, list); return list; } } } } } <file_sep> namespace KCrawler { using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Threading; public class Logger { // private string taskID; public List<LogInfo> Log { get; set; } public Logger() { // this.taskID = taskID; if (Log == null) Log = new List<LogInfo>(); } public LogInfo this[int index] { get { try { if (Log == null || Log.Count == 0) return new LogInfo() { LogTime = DateTime.Now, Message = "no log added", LogType = LogLevel.Fatal }; return Log[index]; } catch(Exception e) { return new LogInfo() { Message = e.Message, LogType = LogLevel.Fatal }; } } } public void LogMessage(string message, LogLevel logType) { Log.Add(new LogInfo() { LogTime = DateTime.Now, Message = message, LogType = logType }); } public long GetCount(LogLevel logType) { int total = 0; try { for (int i = 0; i < Log.Count; i++) { if (Log[i] == null) continue; if (logType == Log[i].LogType) total++; } } catch (Exception e) { Fatal("[LogCount]"+e.Message); return -1; } return total; } public string GetCountText(LogLevel logType) { long total = GetCount(logType); return logType + ":" + total + " "; } public string LogCountText { get { System.Text.StringBuilder t = new System.Text.StringBuilder(); t.Append("[Total] "); t.Append(GetCountText(LogLevel.Saved)); t.Append(GetCountText(LogLevel.Info)); t.Append(GetCountText(LogLevel.Error)); t.Append(GetCountText(LogLevel.Fatal)); return t.ToString(); } } public void Info(string format, params object[] args) { Info(string.Format(format, args)); } public void Info(string message) { LogMessage(message, LogLevel.Info); } public void Error(string message) { LogMessage(message, LogLevel.Error); } public void Error(string format, params object[] args) { Error(string.Format(format, args)); } public void Fatal(string message) { LogMessage(message, LogLevel.Fatal); } public void Fatal(string format, params object[] args) { Fatal(string.Format(format, args)); } } [Serializable] public class LogInfo { public string LogOut { get { return String.Format("[{0}]{1}", LogType.ToString(), Message); } } public string LogOutTime { get { return this == null ? String.Empty: String.Format("[{0}]{1} ({2})", LogType.ToString(), Message, LogTime); } } public string Message { get; set; } public DateTime LogTime { get; set; } public LogLevel LogType { get; set; } public Color Color { get { switch (LogType) { case LogLevel.Saved: return Color.Lime; case LogLevel.Info: return Color.Gold; case LogLevel.Error: case LogLevel.Warn: return Color.Yellow; case LogLevel.Fatal: return Color.Red; } return Color.Lime; } } } } <file_sep>using System; using System.Collections.Generic; using Aspose.Cells; namespace KCrawler { public class ExcelDao { public static List<string> Unicode { get { Workbook workBook = new Workbook(C.Excel_Mime); Worksheet sheetXPath = workBook.Worksheets["unicode"]; List<string> list = new List<string>(); for (int i = 1; i < sheetXPath.Cells.Rows.Count; i++) { Cells cells = sheetXPath.Cells; if (cells[i, 0].Value == null) continue; list.Add(cells[i, 0].Value.ToString()); } return list; } } public static void AddPriority(string taskID, List<PriorityInfo> list) { Workbook workBook = new Workbook(C.Excel_Mime); Worksheet sheetPrioity = workBook.Worksheets[C.Sheet_Priority]; foreach (PriorityInfo pi in list) { int lastRow = sheetPrioity.Cells.Rows.Count; sheetPrioity.Cells.InsertRow(lastRow); sheetPrioity.Cells[lastRow, 0].PutValue(taskID); sheetPrioity.Cells[lastRow, 1].PutValue(pi.Extension); sheetPrioity.Cells[lastRow, 2].PutValue(pi.Mime); sheetPrioity.Cells[lastRow, 4].PutValue(pi.Priority); } workBook.Save(C.Excel_Mime); } public static void RemovePriority(int[] rowID) { Workbook workBook = new Workbook(C.Excel_Mime); Worksheet sheetPrioity = workBook.Worksheets[C.Sheet_Priority]; foreach(int r in rowID) sheetPrioity.Cells.DeleteRow(r); workBook.AcceptAllRevisions(); workBook.Save(C.Excel_Mime); } public static void RemoveFilter(int[] rowID) { Workbook workBook = new Workbook(C.Excel_Mime); Worksheet sheet = workBook.Worksheets[C.Sheet_Filter]; foreach (int r in rowID) sheet.Cells.DeleteRow(r); workBook.AcceptAllRevisions(); workBook.Save(C.Excel_Mime); } public static void AddFilter(string taskID, List<FilterInfo> list) { Workbook workBook = new Workbook(C.Excel_Mime); Worksheet sheetPrioity = workBook.Worksheets[C.Sheet_Filter]; foreach (FilterInfo fi in list) { int lastRow = sheetPrioity.Cells.Rows.Count; sheetPrioity.Cells.InsertRow(lastRow); sheetPrioity.Cells[lastRow, 0].PutValue(taskID); sheetPrioity.Cells[lastRow, 1].PutValue(fi.Extension); sheetPrioity.Cells[lastRow, 2].PutValue(fi.Mime); } workBook.Save(C.Excel_Mime); // Clear(); // TaskName Extension Mime Category Priority(1-5) } //优先级设置 public static List<PriorityInfo> GetPriority(string taskID) { Workbook workBook = new Workbook(C.Excel_Mime); Worksheet sheetXPath = workBook.Worksheets[C.Sheet_Priority]; List<PriorityInfo> list = new List<PriorityInfo>(); PriorityInfo pi; for (int i = sheetXPath.Cells.Rows.Count - 1; i > 0; i--) { Cells cells = sheetXPath.Cells; if (cells[i, 0].Value == null) continue; pi = new PriorityInfo(); pi.TaskName = cells[i, 0].Value.ToString(); if (pi.TaskName.Trim() != taskID) continue; pi.RowID = i; pi.Extension = sheetXPath.Cells[i, 1].Value.ToString(); pi.Mime = sheetXPath.Cells[i, 2].Value.ToString(); // pi.Category = sheetXPath.Cells[i, 3].Value.ToString(); try { pi.Priority = Convert.ToInt32(sheetXPath.Cells[i, 4].Value); } catch { pi.Priority = (int)FrontierQueuePriority.Normal; } list.Add(pi); } return list; } // mime类型 过滤列表 public static List<FilterInfo> GetFilter(string taskID) { Workbook workBook = new Workbook(C.Excel_Mime); Worksheet sheetXPath = workBook.Worksheets[C.Sheet_Filter]; List<FilterInfo> list = new List<FilterInfo>(); FilterInfo filter; for (int i = sheetXPath.Cells.Rows.Count - 1; i > 0; i--) { Cells cells = sheetXPath.Cells; if (cells[i, 0].Value == null) continue; filter = new FilterInfo(); filter.TaskName = cells[i, 0].Value.ToString(); if (filter.TaskName.Trim() != taskID) continue; filter.RowID = i; filter.Extension = sheetXPath.Cells[i, 1].Value.ToString(); filter.Mime = sheetXPath.Cells[i, 2].Value.ToString().ToLower(); if (sheetXPath.Cells[i, 3].Value != null) filter.Category = sheetXPath.Cells[i, 3].Value.ToString(); list.Add(filter); } return list; } public static List<MimeInfo> GetMimeWithoutPriority(string taskID) { List<MimeInfo> list = Mime; foreach (PriorityInfo pi in GetPriority(taskID)) { list.Find(delegate(MimeInfo mi) { if (pi.Extension == mi.Extension) { list.Remove(mi); return true; } return false; }); } return list; } public static List<MimeInfo> GetMimeWithoutFilter(string taskID) { List<MimeInfo> list = Mime; foreach (FilterInfo fi in GetFilter(taskID)) { list.Find(delegate(MimeInfo mi) { if (fi.Extension == mi.Extension) { list.Remove(mi); return true; } return false; }); } return list; } public static List<MimeInfo> Mime { get { Workbook workBook = new Workbook(C.Excel_Mime); Worksheet sheetXPath = workBook.Worksheets["mime"]; List<MimeInfo> list = new List<MimeInfo>(); MimeInfo mi; //for (int i = sheetXPath.Cells.Rows.Count - 1; i > 0; i--) for (int i = 1; i < sheetXPath.Cells.Rows.Count; i++) { Cells cells = sheetXPath.Cells; if (cells[i, 0].Value == null) continue; mi = new MimeInfo(); if (cells[i, 0].Value!=null) mi.Extension = cells[i, 0].Value.ToString(); if (cells[i, 1].Value != null) mi.Mime = cells[i, 1].Value.ToString().ToLower(); if (cells[i, 2].Value != null) mi.Category = cells[i, 2].Value.ToString(); list.Add(mi); } return list; } } public static List<MimeInfo> FileTypeMime { get { List<MimeInfo> list = new List<MimeInfo>(); Workbook workBook = new Workbook(C.Excel_Mime); Worksheet sheetXPath = workBook.Worksheets["FileType"]; MimeInfo mi; for (int i = 1; i < sheetXPath.Cells.Rows.Count; i++) { Cells cells = sheetXPath.Cells; if (cells[i, 0].Value == null) continue; mi = new MimeInfo(); mi.Extension = sheetXPath.Cells[i, 0].Value.ToString(); mi.Mime = sheetXPath.Cells[i, 1].Value.ToString().ToLower(); list.Add(mi); } return list; } } } } <file_sep> namespace KCrawler { using System; using System.Collections.Generic; using System.IO; public class Utility { private const string HTTP_PREFIX = "http://"; private const string HTTPS_PREFIX = "https://"; private static readonly string[] DefaultDirectoryIndexes = { "index.htm", "index.html", "index.asp", "index.php", "index.jsp", "default.htm", "default.asp", "default.aspx", "default.php", "default.html", }; private readonly static string[] domainNameList = new string[] { ".com.cn", ".net.cn", ".org.cn", ".gov.cn", ".ac.cn", ".bj.cn", ".sh.cn", ".tj.cn", ".cq.cn", ".he.cn", ".sx.cn", ".nm.cn", ".ln.cn", ".jl.cn", ".hl.cn", ".js.cn", ".zj.cn", ".ah.cn", ".fj.cn", ".jx.cn", ".sd.cn", ".ha.cn", ".hb.cn", ".hn.cn", ".gd.cn", ".gx.cn", ".hi.cn", ".sc.cn", ".gz.cn", ".yn.cn", ".xz.cn", ".sn.cn", ".gs.cn", ".qh.cn", ".nx.cn", ".xj.cn", ".tw.cn", ".hk.cn", ".mo.cn", ".com", ".net", ".org", ".biz", ".info", ".cc", ".tv", ".cn" }; public readonly static List<string> FileProtocol = PriorityFilterDao.Protocol; public static string GetDomain(string domain) { Uri u = new Uri(domain); string url = u.Host.Replace("www.",""); int lastDot = url.LastIndexOf('.'); if (lastDot > -1) return url.Substring(0, lastDot); return url; } //正规化url public static string NormalizeUri(string url, ref string baseUrl) { if (string.IsNullOrEmpty(url)) { return baseUrl; } //文件协议 bool isFile = Utility.FileProtocol.Exists(delegate(string u) { return url.ToLower().StartsWith(u); }); if (isFile) return url; // Only handle same schema as base uri if (Uri.IsWellFormedUriString(url, UriKind.Relative)) { if (!string.IsNullOrEmpty(baseUrl)) { Uri absoluteBaseUrl = new Uri(baseUrl, UriKind.Absolute); return new Uri(absoluteBaseUrl, url).ToString(); } return new Uri(url, UriKind.Relative).ToString(); } if (Uri.IsWellFormedUriString(url, UriKind.Absolute)) { Uri baseUri = new Uri(baseUrl); Uri uri = new Uri(url); bool schemaMatch; // Special case for http/https if ((baseUri.Scheme == Uri.UriSchemeHttp) || (baseUri.Scheme == Uri.UriSchemeHttps)) { schemaMatch = string.Compare(Uri.UriSchemeHttp, uri.Scheme, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(Uri.UriSchemeHttps, uri.Scheme, StringComparison.OrdinalIgnoreCase) == 0; } else { schemaMatch = string.Compare(baseUri.Scheme, uri.Scheme, StringComparison.OrdinalIgnoreCase) == 0; } if (schemaMatch) { return new Uri(url, UriKind.Absolute).ToString(); } } return null; } //获取子目录 public static string GetBaseUri(string strUri) { string baseUri; Uri uri = new Uri(strUri); string port = string.Empty; if (!uri.IsDefaultPort) port = ":" + uri.Port; baseUri = uri.Scheme + "://" + uri.Host + port + "/"; return baseUri; } internal static bool IsGoodUri(ref string uri) { if (uri == null) return false; if (uri.StartsWith("javascript:")) return false; if (uri.StartsWith("mailto:")) return false; if (uri.StartsWith("tencent:")) return false; if (uri.StartsWith("file://")) return false; return true; } internal static string GetFolderName(string downloadFolder, string contentType) { if (string.IsNullOrEmpty(contentType)) return Path.Combine(downloadFolder, "NoContentType"); int pos = contentType.IndexOf('/'); if (pos < 0) return Path.Combine(downloadFolder, "NoContentType"); return Path.Combine(downloadFolder, contentType.Substring(0, pos)); } } } <file_sep>[KSpider] IsAddUrlKeyword=True IsFilterAll=False MaxKB=8850011 Interval=258 SpiderPool=E:\KSpiderSaved\ [CMinFileSize] Gif=0 Default=2 Flash=99 Jpg=35 File=0 Music=0 <file_sep>using System; using System.Collections.Generic; using System.Data; using System.Text; namespace KCrawler { public class ExtractDao { private readonly static AccessHelper db = new AccessHelper(); public static void AddExtractOption(ExtractOption model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into [Extract]("); strSql.Append("Label,StartString,LastString,ExtractType,TaskID,SplitType,RegEx,RegExGroup)"); strSql.Append(" values ("); strSql.Append("@Label,@StartString,@LastString,@ExtractType,@TaskID,@SplitType,@RegEx,@RegExGroup)"); db.AddInParameter("Label", DbType.AnsiString, model.Label); db.AddInParameter("StartString", DbType.AnsiString, model.StartString); db.AddInParameter("LastString", DbType.AnsiString, model.LastString); db.AddInParameter("ExtractType", DbType.String, model.ExtractType); db.AddInParameter("TaskID", DbType.Int32, model.TaskID); db.AddInParameter("SplitType", DbType.Int32, model.SplitType); db.AddInParameter("RegEx", DbType.AnsiString, model.RegEx); db.AddInParameter("RegExGroup", DbType.AnsiString, model.RegExGroup); db.ExecuteNonQuery(strSql.ToString()); } public static List<ExtractOption> GetOptionList(int taskID) { StringBuilder strSql = new StringBuilder(); strSql.Append("select *"); strSql.Append(" FROM [Extract] "); strSql.Append(" where TaskID=" + taskID); List<ExtractOption> list = new List<ExtractOption>(); using (IDataReader dataReader = db.ExecuteReader(strSql.ToString())) { while (dataReader.Read()) { list.Add(ReaderBind(dataReader)); } } return list; } static ExtractOption ReaderBind(IDataReader dataReader) { ExtractOption model = new ExtractOption(); object ojb; ojb = dataReader["ID"]; if (ojb != null && ojb != DBNull.Value) { model.ID = Convert.ToInt32(ojb); } model.TaskID = Convert.ToInt32(dataReader["TaskID"]); model.Label = dataReader["Label"].ToString(); model.StartString = dataReader["StartString"].ToString(); model.LastString = dataReader["LastString"].ToString(); model.ExtractType = Convert.ToInt16(dataReader["ExtractType"]); model.SplitType = Convert.ToInt16(dataReader["SplitType"]); model.RegEx = dataReader["RegEx"].ToString(); model.RegExGroup = dataReader["RegExGroup"].ToString(); return model; } public static void DeleteExtractInfo(int id) { const string sql = "DELETE * FROM [Extract] WHERE ID="; db.ExecuteScalar(sql + id.ToString()); } public static void UpdateExtractOption(ExtractOption model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update[Extract] set "); strSql.Append("[Label]=@Label ,"); strSql.Append("StartString=@StartString,"); strSql.Append("LastString=@LastString,"); strSql.Append("ExtractType=@ExtractType,"); strSql.Append("TaskID=@TaskID,"); strSql.Append("StringFormat=@StringFormat,"); strSql.Append("SplitType=@SplitType, "); strSql.Append("RegEx=@RegEx, "); strSql.Append("RegExGroup=@RegExGroup "); strSql.Append(" where ID=@ID "); db.AddInParameter("Label", DbType.AnsiString, model.Label); db.AddInParameter("StartString", DbType.AnsiString, model.StartString); db.AddInParameter("LastString", DbType.AnsiString, model.LastString); db.AddInParameter("ExtractType", DbType.String, model.ExtractType); db.AddInParameter("TaskID", DbType.Int32, model.TaskID); db.AddInParameter("StringFormat", DbType.AnsiString, model.StringFormat); db.AddInParameter("SplitType", DbType.String, model.SplitType); db.AddInParameter("RegEx", DbType.AnsiString, model.RegEx); db.AddInParameter("RegExGroup", DbType.AnsiString, model.RegExGroup); db.AddInParameter("ID", DbType.Int32, model.ID); db.ExecuteNonQuery(strSql.ToString()); } public static void AddUrl(UrlHistory model) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(*) "); strSql.Append(" FROM UrlHistory "); strSql.Append(" where TaskID=" + model.TaskID.ToString()); strSql.AppendFormat("AND Url='{0}'", model.Url.Replace("\'","")); int c = Convert.ToInt32(db.ExecuteScalar(strSql.ToString())); if (c > 0) return ; strSql.Remove(0, strSql.Length); strSql.Append("insert into UrlHistory("); strSql.Append("Url,TaskID)"); strSql.Append(" values ("); strSql.Append("@Url,@TaskID)"); db.AddInParameter("Url", DbType.AnsiString, model.Url); db.AddInParameter("TaskID", DbType.Int32, model.TaskID); db.ExecuteNonQuery(strSql.ToString()).ToString(); } public static void DeleteUrl() { const string sql = "DELETE * FROM [Extract] "; db.ExecuteScalar(sql); } /// <summary> /// 获得数据列表(比DataSet效率高,推荐使用) /// </summary> public static List<UrlHistory> GetUrlHistory(int taskid) { StringBuilder strSql = new StringBuilder(); strSql.Append("select Url,TaskID "); strSql.Append(" FROM UrlHistory "); strSql.Append(" where TaskID=" + taskid.ToString()); var list = new List<UrlHistory>(); using (IDataReader dataReader = db.ExecuteReader(strSql.ToString())) { while (dataReader.Read()) { list.Add(UrlReaderBind(dataReader)); } } return list; } /// <summary> /// 对象实体绑定数据 /// </summary> static UrlHistory UrlReaderBind(IDataReader dataReader) { var model = new UrlHistory(); object ojb; model.Url = dataReader["Url"].ToString(); ojb = dataReader["TaskID"]; if (ojb != null && ojb != DBNull.Value) { model.TaskID = (int)ojb; } return model; } } } <file_sep>using Lv.Docking; using System; using System.IO; using System.Windows.Forms; namespace Netscape { public partial class StartWnd : DockContent { private static readonly string StartUrl = Path.Combine(System.Environment.CurrentDirectory, R.URLStartPage); private static readonly string HelpUrl = Path.Combine(System.Environment.CurrentDirectory, R.URLHelpPage); /// <summary> /// json个人偏好模板 category /// </summary> internal static void WriteJsonCategory() { var list = KCrawler.PFCache.GetMimeCategoryList(); string CategoryJson = Newtonsoft.Json.JsonConvert.SerializeObject(list, Newtonsoft.Json.Formatting.Indented); File.WriteAllText(CK.Json_CategoryFile, "var jsonCate=" + CategoryJson); } public StartWnd() { InitializeComponent(); if (!File.Exists(CK.Json_CategoryFile)) WriteJsonCategory(); webBrowser.Url = new Uri(StartUrl); webBrowser.ObjectForScripting = new InteropPlus(); //隐藏窗口 } internal void Help() { webBrowser.Url = new Uri(HelpUrl); Activate(); } internal void Start() { webBrowser.Url = new Uri(StartUrl); Activate(); } private void StartWnd_FormClosing(object sender, FormClosingEventArgs e) { Hide(); e.Cancel = true; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; //using Aspose.Words; using System.Windows.Forms; using System.Drawing; namespace Netscape { public class CK { public readonly static string DesktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\"; public const string Json_CategoryFile = "mcate.js"; public const string Brackets = "[{0}]"; public const string BracketsAndInfo = "[{0}]{1}"; public const string BraceAndInfo = "({0}){1}"; public const string InfoAndBrackets= "{0}[{1}]"; public const string DateFormat = "yyMdHms"; public const string FileWordFilter = "word2003以上|*.docx | word97|*.doc"; public const string FileHtmlFilter = "超文本|*.htm|超文本|*.htm|超文本模板|*.mht"; public const string ExtenText = ".txt"; public const string ExtenPdf = ".pdf"; public const string ExtenHtm = ".htm"; public const string ExtenHtml = ".html"; public const string ExtenMht= ".mht"; public const string ExtenExcel97 = ".xls"; public const string ExtenExcel2000 = ".xlsx"; public const string ExtenWord97 =".doc"; public const string ExtenWord2003 = ".docx"; public readonly static Color ColorError = Color.Yellow; public readonly static Color ColorStart = Color.Yellow; public readonly static Color ColorControl = Color.WhiteSmoke;//Color.FromArgb(234, 234, 234); public const string HttpPrefix = "http://"; public const string HttpsPrefix = "https://"; public static int ExcelColumnCount = 256; public readonly static Color ColorInfo = Color.Yellow; public const string KSpider_Database = "mime.mdb"; } } <file_sep>using KCrawler; using System; using System.Windows.Forms; namespace Netscape { public partial class AddExtractInfo : Form { private int extractCount; private ExtractOption extractOption; public event ExtractionHandler ExtractionCallBack; //是否更新 private bool flag = true; internal AddExtractInfo(int taskID, int ecount) { InitializeComponent(); txtStart.AllowDrop = txtLast.AllowDrop = true; btnAdd.Visible = true; extractOption = new ExtractOption(); extractOption.TaskID = taskID; extractCount = ecount; } internal AddExtractInfo(ExtractOption option) { flag = false; InitializeComponent(); txtStart.AllowDrop = txtLast.AllowDrop = true; btnUpdate.Visible = true; BindData(option); } //list调用或内部 internal void BindData(ExtractOption option) { extractOption = option; if (extractOption.ExtractType == ExtractOption.Option_Links) rbLinks.Checked = true; else rbContent.Checked = true; txtStart.Text = extractOption.StartString; txtLast.Text = extractOption.LastString; txtName.Text = extractOption.Label; tabSplitType.SelectedIndex = extractOption.SplitType; txtRegEx.Text = extractOption.RegEx; txtRegExGroup.Text = extractOption.RegExGroup; Text = txtName.Text; } private void DoExtraction() { switch (tabSplitType.SelectedIndex) { case ExtractOption.Split_StartLast: if (String.IsNullOrEmpty(txtStart.Text)) { errorProvider1.SetError(txtStart, R.EmptyInfo); return; } if (String.IsNullOrEmpty(txtLast.Text)) { errorProvider1.SetError(txtLast, R.EmptyInfo); return; } break; case ExtractOption.Split_RegEx: if (String.IsNullOrEmpty(txtRegEx.Text) && String.IsNullOrEmpty(txtRegExGroup.Text)) { errorProvider1.SetError(txtRegEx, R.EmptyInfo); return; } break; } extractOption.StartString = txtStart.Text; extractOption.LastString = txtLast.Text; extractOption.SplitType = Convert.ToInt16(tabSplitType.SelectedIndex); extractOption.StringFormat = String.Empty; extractOption.ExtractType = Convert.ToInt16(rbLinks.Checked ? 0 : 1); extractOption.Label = string.IsNullOrEmpty(txtName.Text) ? "Label" + (++extractCount).ToString() : txtName.Text; extractOption.RegEx = txtRegEx.Text; extractOption.RegExGroup = txtRegExGroup.Text; if (flag) { ExtractDao.AddExtractOption(extractOption); txtLast.Clear(); txtStart.Clear(); } else { ExtractDao.UpdateExtractOption(extractOption); Close(); } if (ExtractionCallBack != null) ExtractionCallBack(null, null); } private void btnHandle_Click(object sender, EventArgs e) { errorProvider1.Clear(); Button b = sender as Button; switch (b.Name) { case "btnUpdate": DoExtraction(); return; case "btnAdd": DoExtraction(); return; case "btnHandle": Close(); return; } } private void linkExpression_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // linkExpression.SetExpression(ref txtRegEx); } } } <file_sep> namespace KCrawler { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; public partial class CrawlerThread { private const int bufferSize = 16384; // private const string Error_Extract_ //线程提取,2次提取 private List<string> ExtractLinks(string currentUri, string baseUri, string html) { List<string> urls = null; try { string refererLink; /*第一次提取*/ MatchCollection matches = new Regex(@"(href|HREF|src|SRC)[ ]*=[ ]*[""'][^""'#>]+[""']", RegexOptions.IgnoreCase).Matches(html); lock (matches.SyncRoot) { urls = new List<string>(); foreach (Match match in matches) { refererLink = match.Value.Substring(match.Value.IndexOf('=') + 1).Trim('"', '\'', '#', ' ', '>'); if (!Utility.IsGoodUri(ref refererLink)) continue; refererLink = Utility.NormalizeUri(refererLink, ref currentUri); if (!ValidateLink(refererLink)) continue; //布隆过滤器 if (!Downloader.BloomFilter.Contains(refererLink)) urls.Add(refererLink); Downloader.BloomFilter.Add(refererLink); } } /*第二次 html内容中提取绝对地址*/ matches = new Regex(@"(http|https|ftp|ed2k|flashget|thunder)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?", RegexOptions.IgnoreCase).Matches(html); lock (matches.SyncRoot) { foreach (Match match in matches) { if (!ValidateLink(match.Value)) continue; //布隆过滤器 if (!Downloader.BloomFilter.Contains(match.Value)) urls.Add(match.Value); Downloader.BloomFilter.Add(match.Value); } } /*第三次 截断或自定义正则*/ lock (Downloader.CrawlerInfo.ExtractLinks) { int extractedCount = Downloader.ExtractString(ref html, ExtractOption.Option_Links); if (extractedCount > 0) { foreach (var option in Downloader.CrawlerInfo.ExtractLinks) { //规整url option.ExtractedText = Utility.NormalizeUri(option.ExtractedText, ref currentUri); if (!Downloader.BloomFilter.Contains(option.ExtractedText)) urls.Add(option.ExtractedText); Downloader.BloomFilter.Add(option.ExtractedText); } } } } catch (Exception e) { Downloader.Logger.Error("[ExtractLinks]" + e.InnerException.Message); } return urls; } //过滤条件全部在这里, private void EnqueueLinks(ref string url, ref string html) { // 提取URL并加入队列. Status = CrawlerStatusType.Parse; StatusChanged(this, null); string baseUri = Utility.GetBaseUri(url); List<string> links = ExtractLinks(url, baseUri, html); foreach (string link in links) { // 添加到url列表 Downloader.CrawledUrls.Add(link); // 如果扩展名存在Excel中,则取得优先级 bool hasQueuePriority = Downloader.CrawlerInfo.Priority.Exists(delegate(PriorityInfo pi) { if (link.ToLower().EndsWith(pi.DotExtenion)) { Downloader.UrlsQueueFrontier.Enqueue(link, pi.QueuePriority); return true; } return false; }); //否则进入正常队列 if (!hasQueuePriority) Downloader.UrlsQueueFrontier.Enqueue(link); } } // 1.获取页面. 2.提取URL并加入队列. 3.保存页面(到网页库). private void Fetch(string url) { try { // 获取页面. Url = url; Status = CrawlerStatusType.Fetch; //[Fitler]过滤如果不是内部链接 if (Link_Internal_NotExists == IsInternalLink(url)) return; //获取网页byte byte[] buffer = WebBuffer(ref url, ref mimeType); //如果出现问题则什么都不做; if (buffer == null) return; string html = null; //下载文件夹,按照mime分类创建 string downloadFolder = Utility.GetFolderName(Downloader.CrawlerInfo.DownloadFolder, MimeType); if (!Directory.Exists(downloadFolder)) Directory.CreateDirectory(downloadFolder); //根据编码读取文档 if (MimeType.StartsWith(C.Mime_TextHtml)) { html = string.IsNullOrEmpty(Downloader.CrawlerInfo.Unicode) ? Encoding.Default.GetString(buffer) : Encoding.GetEncoding(Downloader.CrawlerInfo.Unicode).GetString(buffer); Downloader.ExtractString(ref html, ExtractOption.Option_Content); } else html = string.Empty; //[include]内容键字包含,如果没有则return 1=内容关键字不为空&&内容不为空&&保存文档 string keywordName = null; if (Key_NotFound == FilterHtmlKeywords(ref html, ref url, out keywordName)) { EnqueueLinks(ref url, ref html); return; } //写文件 if (buffer != null) WriteFile(ref url, ref buffer, ref downloadFolder, keywordName); //如果不是网页类型则退出 if (!MimeType.StartsWith(C.Mime_TextHtml)) return; EnqueueLinks(ref url, ref html); } catch (Exception e) { Downloader.Logger.Error("[Fetch]{0} ", e.Message); } } private byte[] WebBuffer(ref string url, ref string mimeType) { try { //[Fitler]如果是文件类型则下载,根据扩展名 bool isAddedAsFile = AddFileByExtention(ref url); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Timeout = Downloader.CrawlerInfo.ConnectionTimeout * 1000; CookieInfo cookies = GetCookies(url); if (cookies != null) { req.Headers["Cookie"] = cookies.Cookies; req.UserAgent = cookies.UserAgent; } Monitor.Enter(this); using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { if (response.StatusCode == HttpStatusCode.RequestTimeout) return null; //解除监控 Monitor.Exit(this); mimeType = response.ContentType; int fileSize = 0; //[Filter]文件大小过滤 if (!mimeType.StartsWith(C.Mime_TextHtml)) { short sizeResult = IgnoreFile(response.ContentLength, out fileSize); if (sizeResult < 0) { Downloader.Logger.Info("[Ignore{0} {1}KB] {2} {3}", sizeResult, fileSize, url, mimeType); return null; } } //[Fitler]如果检查扩展名不是文件 根据mime在检查 if (!isAddedAsFile) AddFileByMime(ref url, ref mimeType); //[Fitler] Mime先过滤, if (IsMimeFiltered(mimeType)) return null; byte[] mbuffer = new byte[bufferSize]; MemoryStream ms = new MemoryStream(); int numBytesRead = 0; while (true) { numBytesRead = response.GetResponseStream().Read(mbuffer, 0, bufferSize); if (numBytesRead <= 0) break; ms.Write(mbuffer, 0, numBytesRead); } response.Close(); return ms.ToArray(); } } catch (Exception e) { Downloader.Logger.Error("[WebBuffer] {0}", e.Message + " " + url + " "); } return null; } private void WriteFile(ref string url, ref byte[] buffer, ref string downloadFolder, string kName) { // 保存页面(到网页库). Status = CrawlerStatusType.Save; StatusChanged(this, null); //[必须放在这里]不保存文档则强行跳过!!!! if (Downloader.CrawlerInfo.NotSave) return; kName = string.IsNullOrEmpty(kName) ? "" : "(" + kName + ")"; string prefixName = kName + Downloader.SavedCount.ToString() + "-" + Guid.NewGuid().ToString().Substring(0, 4) + "-"; string fullFileName = null; string fileName = null; FileStream fileStream = null; string extension = null; try { extension = Path.HasExtension(url) ? Path.GetExtension(url) : ".html"; int qPos = extension.IndexOf('?'); if (qPos > -1) extension = extension.Substring(0, qPos); fileName = prefixName + Path.GetFileNameWithoutExtension(url) + extension; fullFileName = Path.Combine(downloadFolder, fileName); fileStream = new FileStream(fullFileName, FileMode.OpenOrCreate); fileStream.Write(buffer, 0, buffer.Length); } catch (Exception e) { fileName = "[Error]" + prefixName + ".html"; fullFileName = Path.Combine(downloadFolder, fileName); fileStream = new FileStream(fullFileName, FileMode.OpenOrCreate); fileStream.Write(buffer, 0, buffer.Length); if (e.GetType() != typeof(ArgumentException)) Downloader.Logger.Error("[WriteFile]{0}", e.Message + " " + MimeType + " " + url); } finally { fileStream.Close(); Downloader.Logger.LogMessage(string.Format(" {0} [{1}] ", url, fileName), LogLevel.Saved); Downloader.SavedCount++; } } } } <file_sep>using System; using System.IO; namespace KCrawler { public partial class CrawlerThread { private const short Link_Internal_Exists = 1; private const short Link_Internal_NotExists = -1; private const short Link_NoSets = 0; private const short Key_NonExists = -1; private const short Key_NoContent = -2; private const short Key_NotSave = -3; private const short Key_Exists = 1; private const short Key_NotFound = 0; private const short Size_Unknown = 0; private const short Size_LessThan = -1; private const short Size_MoreThran = -2; private const short Size_Normal = 1; //[Filter] private bool ValidateLink(string refererLink) { if (null == refererLink) return false; // 1) 避免爬虫陷阱 if (refererLink.Length > 400) return false; //文件协议,布隆管理器 if (!Downloader.BloomFilter.Contains(refererLink)) { if (AddFileByProtocol(refererLink)) return false; } //2) 是否只提取内部链接 以前是 (baseUri.IndexOf(Downloader.BaseEntranceUrl) < 0) if (Link_Internal_NotExists == IsInternalLink(refererLink)) return false; //3) [Fitler]先过滤,然后优先级 if (IsLinkFilteredByExtension(refererLink)) return false; //4) [include] url关键字包含,如果没有则continue if (Key_NotFound == FilterUrlKeywords(refererLink)) return false; return true; } /// <summary> /// [Fitler]过滤如果不是内部链接 /// </summary> /// <param name="url"></param> /// <returns>0=不是内部链接 1=已设置为内部链接并且关键字中存在 2=已设置但关键字中不存在</returns> private short IsInternalLink(string url) { if (Downloader.CrawlerInfo.IsInternal) { if (url.IndexOf(Downloader.BaseEntranceUrl) > 0) return Link_Internal_Exists; return Link_Internal_NotExists; } return Link_NoSets; } /// <summary> /// 如果文件小于最小值则不保存 /// </summary> /// <param name="contentLength">response</param> /// <returns></returns> private short IgnoreFile(long contentLength, out int fileSize) { fileSize = 0; if (contentLength <= 0) return Size_Unknown; fileSize = Convert.ToInt32(contentLength / 1024); //如果是0可能请求不到,不忽略 if (fileSize < Downloader.CrawlerInfo.MinFileSize) return Size_LessThan; //如果大于总kb也取消下载 if (fileSize > KConfig.MaxKB) return Size_MoreThran; return Size_Normal; } private short FilterUrlKeywords(string link) { if (null == Downloader.CrawlerInfo.UrlKeyword) return Key_NonExists; if (Downloader.CrawlerInfo.UrlKeyword.Count == 0) return Key_NonExists; //所有关键字列 foreach (UrlKeywordInfo uk in Downloader.CrawlerInfo.UrlKeyword) { //如果存在直接返回,包括单个或多个关键字 int inclucedCount = 0; var innerKeyList = uk.KeywordList; foreach (string k in innerKeyList) { if (link.IndexOf(k) > -1) inclucedCount++; } if (inclucedCount == innerKeyList.Count) return Key_Exists; } //如果内容没有该关键字则继续入队链接,但不写入文件 return Key_NotFound; } /// <summary> /// [include]内容键字包含,如果没有则return 1=内容关键字不为空&&内容不为空&&保存文档 /// </summary> /// <param name="html">网页内容</param> /// <param name="url">入口链接</param> /// <param name="keyword">关键字</param> /// <returns></returns> private short FilterHtmlKeywords(ref string html, ref string url, out string keyName) { keyName = null; //如果不保存 if (Downloader.CrawlerInfo.NotSave) return Key_NotSave; //没有内容 if (String.IsNullOrEmpty(html)) return Key_NoContent; if (null == Downloader.CrawlerInfo.HtmlKeyword) return Key_NonExists; //若果list为空则没有关键字 if (Downloader.CrawlerInfo.HtmlKeyword.Count == 0) return Key_NonExists; //所有关键字列 foreach (HtmlKeywordInfo hk in Downloader.CrawlerInfo.HtmlKeyword) { //如果存在直接返回,包括单个或多个关键字 int inclucedCount = 0; var innerKeyList = hk.KeywordList; foreach (string k in innerKeyList) { if (html.IndexOf(k) > -1) inclucedCount++; } if (inclucedCount == innerKeyList.Count) { keyName = hk.KName; return Key_Exists; } } //如果内容没有该关键字则继续入队链接,但不写入文件 return Key_NotFound; } //[Fitler]如果是文件类型则下载,根据扩展名 private bool AddFileByExtention(ref string url) { string extension = Path.GetExtension(url); if (PFCache.IsFileTypeViaExt(extension)) { Downloader.FilePool.Add(url); return true; } return false; } private bool AddFileByMime(ref string url, ref string mimeType) { if (PFCache.IsFileTypeViaMime(mimeType)) { Downloader.FilePool.Add(url); return true; } return false; } private bool AddFileByProtocol(string link) { foreach (string fp in Utility.FileProtocol) { if (link.ToLower().StartsWith(fp)) { Downloader.FilePool.Add(link); Downloader.BloomFilter.Add(link); return true; } } return false; } private CookieInfo GetCookies(string url) { var c = Downloader.CrawlerInfo.CookieList.Find(delegate(CookieInfo ci) { return url.ToLower().IndexOf(ci.Url) > -1; }); return c; } /// <summary> /// mime过滤 /// </summary> /// <param name="mimeType"></param> /// <returns></returns> private bool IsMimeFiltered(string mimeType) { if (mimeType.StartsWith(C.Mime_TextHtml)) return false; bool isFilteredMime = Downloader.CrawlerInfo.Filter.Exists(delegate(FilterInfo fi) { return mimeType.ToLower().Trim().StartsWith(fi.Mime); }); return isFilteredMime; } /// <summary> /// 扩展名过滤 /// </summary> /// <param name="link"></param> /// <returns></returns> private bool IsLinkFilteredByExtension(string link) { bool isFiltered = Downloader.CrawlerInfo.Filter.Exists(delegate(FilterInfo fi) { return link.ToLower().EndsWith(fi.DotExtenion); }); return isFiltered; } } } <file_sep>using System.Collections.Generic; using System.Net; using System.Collections.Specialized; using System.IO; using System.Windows.Forms; using KCrawler; using Newtonsoft.Json; using System; using System.Diagnostics; namespace Netscape { /// <summary> /// web浏览器,网络提交,盘等 /// </summary> [System.Runtime.InteropServices.ComVisible(true)] public class InteropPlus { private static string requestPage = "http://www.easyfound.com.cn/Request/Param.aspx"; private const string HTTP_PREFIX = "http://"; private const string HTTPS_PREFIX = "https://"; internal readonly static string TaskFolder; private const string KSpider_Path = "KSpiderSaved\\"; static InteropPlus() { if (Directory.Exists(KConfig.SpiderPool)) { TaskFolder = KConfig.SpiderPool; return; } List<string> fixedDisk = new List<string>(); DriveInfo[] drivers = DriveInfo.GetDrives(); foreach (DriveInfo driver in drivers) { if (driver.DriveType == DriveType.Fixed) fixedDisk.Add(driver.Name); } TaskFolder = fixedDisk.Count == 1 ? fixedDisk[0] + KSpider_Path : fixedDisk[1] + KSpider_Path; KConfig.SpiderPool = TaskFolder; } internal static void Redirect( string url) { try { Process.Start(url); } catch(Exception e) { MessageBox.Show(e.Message); } } internal static void Redirect(ref TextBox url) { Process.Start(url.Text); } internal static void BindFolder(ref TextBox t) { using (FolderBrowserDialog folder = new FolderBrowserDialog()) { if (folder.ShowDialog() != DialogResult.OK) return; t.Text = folder.SelectedPath; } } //线程调用 public static void Send(object o) { try { if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) return; TaskInfo crawlerInfo = o as TaskInfo; WebClient webClient = new WebClient(); NameValueCollection VarPost = new NameValueCollection(); VarPost.Add("type", "CrawlerTask"); VarPost.Add("ComputerName", SystemInformation.ComputerName); VarPost.Add("taskname", crawlerInfo.TaskName); VarPost.Add("EntranceURL", crawlerInfo.EntranceURL); VarPost.Add("IsInternal", crawlerInfo.IsInternal.ToString()); VarPost.Add("urlkeywords", crawlerInfo.UrlKeywordText); VarPost.Add("keywords", crawlerInfo.HtmlKeywordText); VarPost.Add("Category", crawlerInfo.Category); byte[] byRemoteInfo = webClient.UploadValues(requestPage, "POST", VarPost); string result = System.Text.Encoding.UTF8.GetString(byRemoteInfo); } catch (Exception e) { Log("[VarPostSend]"+e.Message); } } internal static void Log(string log) { const string Error_Log = "error.log"; if (!File.Exists(Error_Log)) File.Create(Error_Log); //日志 using (StreamWriter writer = new StreamWriter(new FileStream(Error_Log, FileMode.OpenOrCreate))) { writer.WriteLine(String.Format(CK.BracketsAndInfo, DateTime.Now.ToString(), log)); } } #region javascript 调用发送留言 protected void postMessage(string userName, string message) { if (string.IsNullOrEmpty(userName)) { MessageBox.Show("请输入署名"); return; } if (message.Length < 10) { MessageBox.Show("提交信息必须超过10个字符"); return; } string postResult = InteropPlus.PostMessage(userName, message); MessageBox.Show(postResult); } public int addJsonTask(string jsonTask) { var d = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonTask); TaskInfo ti = new TaskInfo(); ti.EntranceURL = d["EntranceURL"]; if (!Uri.IsWellFormedUriString(ti.EntranceURL, UriKind.Absolute)) { ti.EntranceURL = Uri.UriSchemeHttp + Uri.SchemeDelimiter+ ti.EntranceURL; if (!Uri.IsWellFormedUriString(ti.EntranceURL, UriKind.Absolute)) { MessageBox.Show(R.Empty_Url, ti.Description, MessageBoxButtons.OK, MessageBoxIcon.Information); return -1; } } ti.Category = d["Category"]; ti.Description = d["Desc"]; if (ti.Category.ToLower() == "jpg") ti.MinFileSize = KConfig.GetMinKB(ti.Category, 50); else ti.MinFileSize = KConfig.GetMinKB(ti.Category); Uri u = new Uri(ti.EntranceURL); ti.TaskName = String.Format(CK.BraceAndInfo, ti.Domain, ti.Description); ti.ThreadCount = 5; ti.ThreadSleepTimeWhenQueueIsEmpty = 2; ti.ConnectionTimeout = 40; ti.DownloadFolder = TaskFolder + ti.TaskName; ti.IsInternal = true; ti.IsAddUkey = true; ti.IsFilterAllMime = true; ti.NotSave = false; ti.Unicode = String.Empty; ti.IsPreference = false; ti.ID = TaskDao.AddTask(ti); PreferenceDao.UpdatePreference(ti); Cache.ClearTaskList(); return ti.ID; } public static string PostMessage(string userName, string message) { WebClient webClient = new WebClient(); NameValueCollection VarPost = new NameValueCollection(); VarPost.Add("type", "clientmessage"); VarPost.Add("username", userName); VarPost.Add("category", "crawler"); VarPost.Add("message", message); byte[] byRemoteInfo = webClient.UploadValues(requestPage, "POST", VarPost); string remoteInfo = System.Text.Encoding.UTF8.GetString(byRemoteInfo); return remoteInfo; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; namespace KCrawler { public class ClientRequest { private const double KBCount = 1024; private const double MBCount = KBCount * 1024; private const double GBCount = MBCount * 1024; private const double TBCount = GBCount * 1024; // private string taskID; public List<DownloadInfo> FilePool { get; set; } private WebClient client = null; public ClientRequest() { // this.taskID = taskID; FilePool = new List<DownloadInfo>(); client = new WebClient(); } public void AddUrl(DownloadInfo d) { if (d.Uri == null) return; client.DownloadFileAsync(d.Uri, d.SavePath + d.FileName, d); //client.DownloadFileCompleted += client_DownloadFileCompleted; //client.DownloadProgressChanged += client_DownloadProgressChanged; // FilePool.Add(d); // ThreadPool.QueueUserWorkItem(ToString()); } private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { DownloadInfo d = (DownloadInfo)e.UserState; d.Progress = e.ProgressPercentage + "%"; double secondCount = (DateTime.Now - d.StartTime).TotalSeconds; d.Speed = GetAutoSizeString(Convert.ToDouble(e.BytesReceived / secondCount), 2) + "/s"; } private void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { DownloadInfo d = (DownloadInfo)e.UserState; FilePool.Remove(d); } /// <summary> /// 得到适应大小 /// </summary> /// <param name="size">字节大小</param> /// <param name="roundCount">保留小数(位)</param> /// <returns></returns> public static string GetAutoSizeString(double size, int roundCount) { if (KBCount > size) return Math.Round(size, roundCount) + "B"; else if (MBCount > size) return Math.Round(size / KBCount, roundCount) + "KB"; else if (GBCount > size) return Math.Round(size / MBCount, roundCount) + "MB"; else if (TBCount > size) return Math.Round(size / GBCount, roundCount) + "GB"; else return Math.Round(size / TBCount, roundCount) + "TB"; } } } <file_sep>using KCrawler; using System; using System.Windows.Forms; namespace Netscape { public partial class KGeneral : Form { private static KGeneral kgen; public KGeneral() { InitializeComponent(); numMaxKB.Value = KConfig.MaxKB; trackBar1.Value = KConfig.Interval; lbMB.Text = KConfig.MaxMB; lbInterval.Text = string.Format(R.KGen_Interval, KConfig.Interval); txtPool.Text = KConfig.SpiderPool; FormClosing += delegate { kgen = null; }; } internal static void GetInstance() { if (null == kgen) { kgen = new KGeneral(); kgen.Show(); } else kgen.Activate(); } private void KGeneral_Load(object sender, EventArgs e) { } private void numMaxKB_ValueChanged(object sender, EventArgs e) { lbMB.Text = Convert.ToDouble(numMaxKB.Value / 1024).ToString(".00") + "MB"; ; KConfig.MaxKB = Convert.ToInt32(numMaxKB.Value); } private void trackBar1_Scroll(object sender, EventArgs e) { lbInterval.Text = string.Format(R.KGen_Interval, trackBar1.Value); KConfig.Interval = trackBar1.Value; } private void btnHandle_Click(object sender, EventArgs e) { InteropPlus.BindFolder(ref txtPool); if (!string.IsNullOrEmpty(txtPool.Text)) KConfig.SpiderPool = txtPool.Text; } private void txtPool_TextChanged(object sender, EventArgs e) { KConfig.SpiderPool = txtPool.Text; } private void numMaxKB_KeyUp(object sender, KeyEventArgs e) { numMaxKB_ValueChanged(sender, null); } } } <file_sep>using System; using System.Security.Permissions; using System.Windows.Forms; namespace Netscape { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)] [STAThread] static void Main() { Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.Run(new KMain()); } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { Exception ex = (Exception)e.ExceptionObject; InteropPlus.Log(ex.Message); } catch(Exception exp) { InteropPlus.Log(exp.Message); } } static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) { InteropPlus.Log("[ThreadException]"+e.Exception.Message); } } } <file_sep>using System; using System.ComponentModel; using System.Diagnostics; using System.Windows.Forms; namespace Netscape { public partial class Link : LinkLabel { public Link() { InitializeComponent(); } public Link(IContainer container) { container.Add(this); InitializeComponent(); } internal void SetExpression(ref TextboxAdvanced txt) { // txt.Text.Insert(txt.SelectionStart, Text); txt.AppendLine(Text); } protected override void OnClick(EventArgs e) { try { if (!string.IsNullOrEmpty(AccessibleName)) Process.Start(AccessibleName); } catch (Exception ex) { MessageBox.Show(ex.Message); } base.OnClick(e); } } } <file_sep>using System.Data.OleDb; using System.Collections.Generic; using System.Data; using System; namespace KCrawler { public class AccessHelper { private const string Connection_String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source='mime.mdb';Jet OLEDB:Database Password=;"; private List<OleDbParameter> paramCollection = new List<OleDbParameter>(); public static int Delete(string tableName, int id) { return new AccessHelper().ExecuteNonQuery(" DELETE * FROM " + tableName + " WHERE ID= " + id); } public AccessHelper() { } /// <summary> /// /// </summary> /// <param name="dbName">包括路径</param> public int ExecuteNonQuery(string cmdText) { OleDbConnection conn = new OleDbConnection(Connection_String); OleDbCommand cmd = new OleDbCommand(cmdText, conn); if (paramCollection.Count > 0) { foreach (OleDbParameter p in paramCollection) cmd.Parameters.Add(p); } conn.Open(); int result = cmd.ExecuteNonQuery(); conn.Close(); //清空参数 cmd.Parameters.Clear(); paramCollection.Clear(); return result; } public OleDbParameter AddInParameter(string name, System.Data.DbType dbType, object value) { //bool exists = paramCollection.Exists(delegate(OleDbParameter para) //{ // if (para.ParameterName == name && value == para.Value) // return true; // return false; //}); //if (exists) // return null; OleDbParameter p = new OleDbParameter(); p.DbType = dbType; p.ParameterName = name; p.Value = value; paramCollection.Add(p); return p; } public OleDbDataReader ExecuteReader(string cmdText) { OleDbConnection conn = new OleDbConnection(Connection_String); OleDbCommand cmd = new OleDbCommand(cmdText, conn); if (paramCollection.Count > 0) { foreach (OleDbParameter p in paramCollection) cmd.Parameters.Add(p); } conn.Open(); OleDbDataReader dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); //清空参数 cmd.Parameters.Clear(); paramCollection.Clear(); return dr; } public object ExecuteScalar(string cmdText) { OleDbConnection conn = new OleDbConnection(Connection_String); OleDbCommand cmd = new OleDbCommand(cmdText, conn); if (paramCollection.Count > 0) { foreach (OleDbParameter p in paramCollection) cmd.Parameters.Add(p); } conn.Open(); object o = cmd.ExecuteScalar(); conn.Close(); //清空参数 cmd.Parameters.Clear(); paramCollection.Clear(); return o; } internal void Close() { paramCollection.Clear(); } } } <file_sep>using System.Collections.Generic; namespace KCrawler { public class TaskCache : Cache { public const string CachePrefix = "TaskCache"; public const string C_TaskList = CachePrefix + "GetTaskList"; public static List<TaskInfo> GetTaskList() { lock (KCache.SyncRoot) { string cacheName = CachePrefix + "GetTaskList"; if (KCache.ContainsKey(cacheName)) return KCache[cacheName] as List<TaskInfo>; else { List<TaskInfo> t = TaskDao.GetTaskList(); KCache.Add(C_TaskList, t); return t; } } } public static int Count { get { return GetTaskList().Count; } } public static TaskInfo GetTaskInfo(int id) { lock (KCache.SyncRoot) { string cacheName = CachePrefix + "GetTaskInfo" + id.ToString(); if (KCache.ContainsKey(cacheName)) return KCache[cacheName] as TaskInfo; else { TaskInfo taskInfo = TaskDao.GetTaskInfo(id); KCache.Add(cacheName, taskInfo); return taskInfo; } } } public static List<FilterInfo> GetFilter(int taskID) { lock (KCache.SyncRoot) { string cacheName = "GetFilter" + taskID; if (KCache.ContainsKey(cacheName)) return KCache[cacheName] as List<FilterInfo>; else { var dt = PriorityFilterDao.GetFilter(taskID); KCache.Add(cacheName, dt); return dt; } } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using KCrawler; namespace Netscape { public partial class UCPriority : UCBase { public event PriorityLevelHandler PriorityLevelClicked; public UCPriority() { InitializeComponent(); } public override void BindData() { try { mimeBox.TaskID = TaskID; priorityBox.TaskID = TaskID; mimeBox.BindMimeWithoutPriority(); priorityBox.BindPrioity(); base.BindData(); } catch (Exception e) { mimeBox.Items.Add(e.Message); } } private void Level_Clicked(object sender, EventArgs e) { try { ListBox.SelectedObjectCollection list = mimeBox.SelectedItems; if (list.Count == 0) return; //更新偏好类型 TaskDao.UpdateCategory(TaskID, string.Empty); Button btn = sender as Button; short level = Convert.ToInt16(btn.Name.Substring(btn.Name.Length - 1, 1)); List<PriorityInfo> priorityList = new List<PriorityInfo>(); for (int i = 0; i < list.Count; i++) { var mi = list[i] as MimeInfo; priorityList.Add(new PriorityInfo { MimeID = mi.ID, Priority = level }); } PriorityFilterDao.AddPriority(TaskID, priorityList); BindData(); if (PriorityLevelClicked != null) PriorityLevelClicked(sender, e); } catch (Exception exp) { MessageBox.Show(exp.Message); } } private void priorityBox_MimeJobFinished(object sender, EventArgs e) { mimeBox.BindMimeWithoutPriority(); } } } <file_sep>using System.ComponentModel; using System.Windows.Forms; using KCrawler; using System; namespace Netscape { /// <summary> /// /// </summary> public partial class MimeBox : ListBox { public event MimeBoxEventHandler MimeJobFinished; public int TaskID { get; set; } public MimeBox(IContainer container) { container.Add(this); InitializeComponent(); tsmRemove.Click += tsmMenu_Click; tsmRemoveAll.Click += tsmMenu_Click; tsmSelectAll.Click += tsmMenu_Click; } internal void BindMimeCategory() { DataSource = PreferenceDao.GetMimeCategoryList(); DisplayMember = "Desc"; SelectedIndex = -1; } internal void SelecteMCate(string category) { for (int i = 0; i < Items.Count; i++) { if ((Items[i] as MCateInfo).Category == category) SelectedIndex = i; } } internal void BindMimeWithoutPriority() { DataSource = PriorityFilterDao.GetMimeWithoutPriority(TaskID); DisplayMember = "EMText"; SelectedIndex = -1; } internal void BindMimeWithoutFilter() { DataSource = PriorityFilterDao.GetMimeWithoutFilter(TaskID); DisplayMember = "EMText"; SelectedIndex = -1; } internal void BindPrioity() { DataSource = PriorityFilterDao.GetPriority(TaskID); DisplayMember = "Text"; SelectedIndex = -1; } internal void BindFilter() { DataSource = PriorityFilterDao.GetFilter(TaskID); DisplayMember = "EMText"; SelectedIndex = -1; } internal short UpdatePreference(ref TaskInfo taskInfo) { if (Name != "listPreference") return -1; //如果是自定义则退出 if (SelectedIndex <=0) { TaskDao.UpdateCategory(taskInfo.ID, string.Empty); return -2; } int index = SelectedIndices[0]; var mc = Items[index] as MCateInfo; if (mc.Category == taskInfo.Category) return -3; taskInfo.Category = mc.Category; PreferenceDao.UpdatePreference(taskInfo); return 0; } private void tsmMenu_Click(object sender, System.EventArgs e) { ToolStripMenuItem tsm = sender as ToolStripMenuItem; switch (tsm.Name) { case "tsmRemove": Remove(Name, false); break; case "tsmRemoveAll": Remove(Name, true); break; case "tsmSelectAll": SelectAll(); break; } if (MimeJobFinished != null) MimeJobFinished(tsm, e); } public void SelectAll() { for (int i = 0; i < Items.Count; i++) SelectedIndex = i; } private void Remove(string name, bool isAll) { try { int max = isAll ? Items.Count : SelectedIndices.Count; if (max == 0) return; int[] idArray = new int[max]; switch (name) { case "priorityBox": for (int i = 0; i < max; i++) { int s = isAll ? i : SelectedIndices[i]; var pi = Items[s] as PriorityInfo; AccessHelper.Delete("Priority", pi.ID); } BindPrioity(); return; case "filterBox": for (int i = 0; i < max; i++) { int s = isAll ? i : SelectedIndices[i]; var fi = Items[s] as FilterInfo; AccessHelper.Delete("Filter", fi.ID); } BindFilter(); return; } } catch (Exception e) { MessageBox.Show(e.Message); } } //删除 private void MimeBox_KeyUp(object sender, KeyEventArgs e) { if (SelectedIndex < 0) return; if (SelectedIndices.Count == 0) return; if (e.KeyData != Keys.Delete) return; Remove(Name, false); if (MimeJobFinished != null) MimeJobFinished(sender, e); } private void contextMenu_Opening(object sender, CancelEventArgs e) { switch (Name) { case "mimeBox": tsmRemove.Visible = false; tsmRemoveAll.Visible = false; return; case "listPreference": tsmRemove.Visible = false; tsmRemoveAll.Visible = false; tsmSelectAll.Visible = false; return; } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.OleDb; using System.IO; namespace KCrawler { public class ExcelDao { public const string HDR_YES = "Yes"; public const string HDR_NO = "No"; private static string SelectConnection(string path, string hdr) { string excelExtension = Path.GetExtension(path); if (excelExtension.ToLower() == ".xlsx") return String.Format("Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + path + ";Extended Properties='Excel 12.0; HDR={0}; IMEX=1'", hdr); else return String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";Extended Properties=\"Excel 8.0; HDR={0}; IMEX=1\"", hdr); } public static string[] GetExcelSheetName(string path, string hdr) { try { string excelExtension = Path.GetExtension(path); string strConn = SelectConnection(path, hdr); OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); string[] strTableNames = new string[dtSheetName.Rows.Count]; for (int k = 0; k < dtSheetName.Rows.Count; k++) { strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString(); } return strTableNames; } catch (Exception e) { return new string[] { e.Message }; } } public static DataTable GetDataFromSheet(string path, string hdr, string sql) { DataTable dt = new DataTable(); //try //{ string strConn = SelectConnection(path, hdr); OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); OleDbDataAdapter myCommand = null; myCommand = new OleDbDataAdapter(sql, strConn); dt = new DataTable(); myCommand.Fill(dt); return dt; //} //catch (Exception e) //{ // dt.Clear(); // dt.Columns.Add("Exception", typeof(string)); // DataRow dr = dt.NewRow(); // dr[0] = e.Message; // dt.Rows.Add(dr); // return dt; //} } public static DataTable GetDataFromSheet(string path, string sql) { return GetDataFromSheet(path, HDR_YES, sql); } } } <file_sep>using System.Collections.Generic; using System.Text; namespace KCrawler { public class PFCache : Cache { public const string CachePrefix = "PFCache"; private const string Cache_FileTypeMime = CachePrefix + "FileTypeMime"; private static List<MimeInfo> FileTypeMime { get { lock (KCache.SyncRoot) { if (KCache.ContainsKey(Cache_FileTypeMime)) return KCache[Cache_FileTypeMime] as List<MimeInfo>; else { KCache.Add(Cache_FileTypeMime, PriorityFilterDao.FileTypeMime); return KCache[Cache_FileTypeMime] as List<MimeInfo>; } } } } public static List<MCateInfo> GetMimeCategoryList() { lock (KCache.SyncRoot) { string cacheName = CachePrefix + "GetMimeCategoryList"; if (KCache.ContainsKey(cacheName)) return KCache[cacheName] as List<MCateInfo>; else { KCache.Add(cacheName, PreferenceDao.GetMimeCategoryList()); return KCache[cacheName] as List<MCateInfo>; } } } /// <summary> /// urlkeyword kname 删除使用 /// </summary> internal static string MCateString { get { var mList = PFCache.GetMimeCategoryList(); var categoryString = new StringBuilder(); foreach (var mc in mList) { if (mc.Category == "" || string.IsNullOrEmpty(mc.Category)) continue; categoryString.Append("\'"); categoryString.Append(mc.Category); categoryString.Append("\'"); categoryString.Append(','); } return categoryString.ToString().Trim(','); } } //urlkeyword说明调用 public static string LabelForMCate { get { return R.MCate_LabelPrefix + MCateString.Replace("\'", ""); } } public static bool IsFileTypeViaExt(string mimeExt) { return FileTypeMime.Exists(delegate(MimeInfo mi) { return mimeExt.ToLower() == mi.DotExtenion; }); } public static bool IsFileTypeViaMime(string mime) { return FileTypeMime.Exists(delegate(MimeInfo mi) { return mime.ToLower().StartsWith(mi.Mime); }); } } } <file_sep>using KCrawler; using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; namespace Netscape { public partial class ListViewAdvanced : ListView { private AddExtractInfo wndExtraction; public List<ExtractOption> ExtractionList { get; private set; } public const string CName_ExtractOption = "listExtractOptions"; public ListViewAdvanced() { InitializeComponent(); } public ListViewAdvanced(IContainer container) { container.Add(this); InitializeComponent(); Init(); } public void Init() { SetStyle(ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); UpdateStyles(); } private void BindExtractOptions() { if (SelectedIndices.Count <= 0) return; int index = SelectedIndices[0]; BindExtractOptions(ExtractionList[index].TaskID); Refresh(); } internal void BindExtractOptions(int taskID) { try { Items.Clear(); ExtractionList = ExtractDao.GetOptionList(taskID); ExtractOption o; for (int i = 0; i < ExtractionList.Count; i++) { o = ExtractionList[i]; Items.Add(o.Label); Items[i].SubItems.Add(o.ExtractTypeName); Items[i].SubItems.Add(o.SplitTypeText); if (o.SplitType == ExtractOption.Split_StartLast) { Items[i].SubItems.Add(o.StartString); Items[i].SubItems.Add(o.LastString); } else { Items[i].SubItems.Add(o.RegEx); Items[i].SubItems.Add(""); } //Items[i].Text = o.FieldName; //Items[i].SubItems[0].Text = o.StartString; //Items[i].SubItems[1].Text = o.LastString; //Items[i].SubItems[2].Text = o.ExtractedText; } } catch (Exception e) { Items.Add(e.Message); } } //ucExtract private void DoExtraction() { if (Name != CName_ExtractOption) return; if (ExtractionList == null) return; if (SelectedIndices.Count <= 0) return; int index = SelectedIndices[0]; if (wndExtraction == null || wndExtraction.IsDisposed) { wndExtraction = new AddExtractInfo(ExtractionList[index]); wndExtraction.ExtractionCallBack += wndExtraction_ExtractionCallBack; wndExtraction.Show(); } else { wndExtraction.BindData(ExtractionList[index]); wndExtraction.Activate(); } } void wndExtraction_ExtractionCallBack(object sender, EventArgs e) { BindExtractOptions(); } private void ListViewAdvanced_DoubleClick(object sender, EventArgs e) { DoExtraction(); } private void ListViewAdvanced_KeyUp(object sender, KeyEventArgs e) { if (SelectedIndices.Count <= 0) return; int index = SelectedIndices[0]; switch (Name) { case CName_ExtractOption: if (e.KeyData != Keys.Delete) return; ExtractDao.DeleteExtractInfo(ExtractionList[index].ID); BindExtractOptions(); return; } } } } <file_sep>using System; using System.Windows.Forms; using KCrawler; using System.Diagnostics; using System.Collections.Generic; namespace Netscape { public partial class MainForm : Form { private Downloader downloader; string currentUrl = String.Empty; public MainForm() { InitializeComponent(); downloader = new Downloader(null); downloader.StatusChanged += new DownloaderStatusChangedEventHandler(DownloaderStatusChanged); } private void ShowSettingsDialog() { ACrawler dialog = new ACrawler(); dialog.ShowDialog(); } #region UI Events private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void settingsToolStripMenuItem_Click(object sender, EventArgs e) { ShowSettingsDialog(); } private void buttonResume_Click(object sender, EventArgs e) { downloader.Resume(); } private void buttonPause_Click(object sender, EventArgs e) { downloader.Suspend(); } private void buttonStop_Click(object sender, EventArgs e) { downloader.Abort(); } private void buttonSettings_Click(object sender, EventArgs e) { ShowSettingsDialog(); } #endregion private void buttonGo_Click(object sender, EventArgs e) { downloader.InitSeeds(new string[] { txtSeed.Text }); downloader.Start(); timer.Start(); //while(true) //{ // Application.DoEvents(); // Text = "链接总数:" + downloader.CrawledUrlSet.Count.ToString(); // if (string.IsNullOrEmpty(downloader.LastCrawledUrl)) // continue; // if (downloader.LastCrawledUrl == "") // continue; // if (currentUrl == downloader.LastCrawledUrl) // continue; // currentUrl = downloader.LastCrawledUrl; // // txtOutput.AppendText(String.Format("[{0}]{1} \r\n",System.IO.Path.GetExtension(downloader.LastCrawledUrl), downloader.LastCrawledUrl )); // txtOutput.AppendText(downloader.LastCrawledUrl + Environment.NewLine); //} } delegate void UpdateDataGridCallback(Downloader d); private void UpdateDataGrid(Downloader d) { try { if (this.dataGridThreads.InvokeRequired) { UpdateDataGridCallback callback = new UpdateDataGridCallback(UpdateDataGrid); this.Invoke(callback, new object[] { d }); } else { // dataGridThreads.DataSource = typeof(CrawlerThread[]); dataGridThreads.DataSource = d.Crawlers; dataGridThreads.Columns["Name"].Width = 100; dataGridThreads.Columns["Status"].Width = 100; } } catch (ObjectDisposedException) { } } delegate void UpdateStatusStripCallback(); private void UpdateStatusStrip() { //if (this.statusStrip.InvokeRequired) //{ // UpdateStatusStripCallback callback = new UpdateStatusStripCallback(UpdateStatusStrip); // this.Invoke(callback, new object[] { }); //} //else //{ // //if (m_downloader.UrlsQueueFrontier.Count >0) // // txtOutput.AppendText(m_downloader.UrlsQueueFrontier.Dequeue() + "\r\n"); //} } private void DownloaderStatusChanged(object sender, DownloaderStatusChangedEventArgs e) { Downloader d = (Downloader)sender; UpdateDataGrid(d); } private void timer_Tick(object sender, EventArgs e) { if (string.IsNullOrEmpty(downloader.LastCrawledUrl)) return; if (downloader.LastCrawledUrl == "") return; if (currentUrl == downloader.LastCrawledUrl) return; currentUrl = downloader.LastCrawledUrl; // txtOutput.AppendText(String.Format("[{0}]{1} \r\n",System.IO.Path.GetExtension(downloader.LastCrawledUrl), downloader.LastCrawledUrl )); txtOutput.AppendText(downloader.LastCrawledUrl + Environment.NewLine); UpdateStatusStrip(); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (downloader == null) return; downloader.Abort(); } private void MainForm_Shown(object sender, EventArgs e) { } private void txtOutput_LinkClicked(object sender, LinkClickedEventArgs e) { Process.Start(e.LinkText); } } } <file_sep>using System.Windows.Forms; namespace Netscape { public partial class UCBase : UserControl { public UCBase() { InitializeComponent(); } public int TaskID { get; set; } public virtual void BindData() { //清除优先级或过滤器缓存 KCrawler.TaskCache.Clear("Priority"); KCrawler.TaskCache.Clear("Filter"); } } } <file_sep>using System.ComponentModel; using System.Windows.Forms; using KCrawler; using System.Collections.Generic; using System; namespace Netscape { public partial class KeywordBox : ListBox { public KeywordBox() { InitializeComponent(); } public KeywordBox(IContainer container) { container.Add(this); InitializeComponent(); tsmRemove.Click += tsmMenu_Click; tsmRemoveAll.Click += tsmMenu_Click; tsmSelectAll.Click += tsmMenu_Click; } internal int TaskID { get; set; } internal void BindUrl() { try { List<UrlKeywordInfo> list = KeywordDao.GetUrlKeywordList(TaskID); DataSource = list; DisplayMember = "KOutput"; SelectedIndex = -1; } catch (Exception e) { Items.Add(e.Message); } } internal void BindHtml() { try { List<HtmlKeywordInfo> list = KeywordDao.GetHtmlKeywordList(TaskID); DataSource = list; DisplayMember = "KOutput"; SelectedIndex = -1; } catch (Exception e) { Items.Add(e.Message); } } private void KeywordBox_KeyUp(object sender, KeyEventArgs e) { if (e.KeyData != Keys.Delete) return; if (SelectedIndices.Count == 0) return; Remove(); } private void Remove() { for (int i = 0; i < SelectedIndices.Count; i++) { int index = SelectedIndices[i]; if (Name == "listUrlKeyword") { UrlKeywordInfo url = Items[index] as UrlKeywordInfo; KeywordDao.DeleteUrlKeyword(url.ID); } else if (Name == "listCookies") { CookieInfo cookieInfo = Items[index] as CookieInfo; KeywordDao.DeleteCookies(cookieInfo.ID); } else if (Name == "listHtmlKeyword") { HtmlKeywordInfo html = Items[index] as HtmlKeywordInfo; KeywordDao.DeleteHtmlKeyword(html.ID); } else { var extractOption = Items[index] as ExtractOption; ExtractDao.DeleteExtractInfo(extractOption.ID); } } if (Name == "listUrlKeyword") BindUrl(); else if (Name == "listCookies") BindCookies(); else if (Name == "listHtmlKeyword") BindHtml(); else BindExtractOption(); } private void tsmMenu_Click(object sender, System.EventArgs e) { ToolStripMenuItem tsm = sender as ToolStripMenuItem; switch (tsm.Name) { case "tsmRemove": Remove(); break; case "tsmRemoveAll": SelectAll(); Remove(); break; case "tsmSelectAll": SelectAll(); break; } } public void SelectAll() { for (int i = 0; i < Items.Count; i++) SelectedIndex = i; } internal void BindCookies() { try { List<CookieInfo> list = KeywordDao.GetCookieList(TaskID); DataSource = list; DisplayMember = "CookieListItem"; } catch (Exception e) { Items.Add(e.Message); } } internal void BindExtractOption() { } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace KCrawler { public class ExcelCache { //public const string CachePrefix = ""; private const string Cache_FileTypeMime = "FileTypeMime"; public readonly static Hashtable Cache = Hashtable.Synchronized(new Hashtable()); private const string cacheName = "Unicode"; public static List<string> Unicode { get { if (Cache.ContainsKey(cacheName)) return Cache[cacheName] as List<string>; else { Cache.Add(cacheName, ExcelDao.Unicode); return ExcelDao.Unicode; } } } public static List<FilterInfo> GetFilter(string taskID) { lock (Cache.SyncRoot) { string cacheName = "GetFilter" + taskID; if (Cache.ContainsKey(cacheName)) return Cache[cacheName] as List<FilterInfo>; else { List<FilterInfo> list = ExcelDao.GetFilter(taskID); Cache.Add(cacheName, list); return list; } } } public static List<PriorityInfo> GetPriority(string taskID) { lock (Cache.SyncRoot) { string cacheName = "GetPriority" + taskID; if (Cache.ContainsKey(cacheName)) return Cache[cacheName] as List<PriorityInfo>; else { List<PriorityInfo> list = ExcelDao.GetPriority(taskID); Cache.Add(cacheName, list); return list; } } } private static List<MimeInfo> FileTypeMime { get { lock (Cache.SyncRoot) { if (Cache.ContainsKey(Cache_FileTypeMime)) return Cache[Cache_FileTypeMime] as List<MimeInfo>; else { Cache.Add(Cache_FileTypeMime, ExcelDao.FileTypeMime); return Cache[Cache_FileTypeMime] as List<MimeInfo>; } } } } public static bool IsFileTypeViaExt(string mimeExt) { return FileTypeMime.Exists(delegate(MimeInfo mi) { return mimeExt.ToLower() == mi.Extension; }); } public static bool IsFileTypeViaMime(string mime) { return FileTypeMime.Exists(delegate(MimeInfo mi) { return mime.ToLower().StartsWith(mi.Mime); }); } } } <file_sep> namespace KCrawler { using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; public class KConfig { private static readonly IniFiles ini = new IniFiles(C.IniFile); private const string ConfigurationName = "KSpider"; private const string CMinFileSize = "CMinFileSize"; public static int GetMinKB(string category) { return GetMinKB(category, 0); } public static int GetMinKB(string category, int defaultKB) { category = string.IsNullOrEmpty(category) ? "Default" : category; return ini.GetInteger(CMinFileSize, category, defaultKB); } public static void SetMinFileSize(string category, int minKb) { category = string.IsNullOrEmpty(category) ? "Default" : category; ini.WriteInteger(CMinFileSize, category, minKb); } public static bool IsAddUrlKeyword { get { return ini.GetBoolean(ConfigurationName, "IsAddUrlKeyword", true); } set { ini.SetBoolean(ConfigurationName, "IsAddUrlKeyword", value); } } public static bool IsFilterAll { get { return ini.GetBoolean(ConfigurationName, "IsFilterAll", true); } set { ini.SetBoolean(ConfigurationName, "IsFilterAll", value); } } public static int Interval { get { return ini.GetInteger(ConfigurationName, "Interval", 180); } set { ini.WriteInteger(ConfigurationName, "Interval", value); } } public static int MaxKB { get { return ini.GetInteger(ConfigurationName, "MaxKB", 100000000); } set { ini.WriteInteger(ConfigurationName, "MaxKB", value); } } public static string MaxMB { get { return Convert.ToDouble(MaxKB / 1024).ToString(".00") + "MB"; } } public static string SpiderPool { get { return ini.GetString(ConfigurationName, "SpiderPool", String.Empty); } set { ini.WriteString(ConfigurationName, "SpiderPool", value); } } } } <file_sep>using System.Text; namespace KCrawler { public class C { internal static readonly string ExportXmlScheme; internal const string Xml_Root_KSpider = "KSpider"; internal const string Xml_KSpiderEnd = "</" + Xml_Root_KSpider + ">"; internal const string Xml_Item = "<Item>"; internal const string Xml_ItemEnd = "</Item>"; static C() { var exportXmlScheme = new StringBuilder(); exportXmlScheme.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); exportXmlScheme.AppendLine("<" + Xml_Root_KSpider + ">"); exportXmlScheme.AppendLine(Xml_KSpiderEnd); ExportXmlScheme = exportXmlScheme.ToString(); } public const string StringReplacement = "{0}"; public const string IniFile = "config.ini"; public const string Mime_TextHtml = "text/html"; public const string Sheet_Priority = "Priority"; public const string Excel_Mime = "mime.xlsx"; public const string DateFormat = "yMd-Hms"; public const string DateFormatFile = "yMd"; public const string Sheet_Filter = "Filter"; public const string F_KName = "KName"; public const string F_Keywords = "Keywords"; public const string F_TaskID = "TaskID"; public const string F_ID = "ID"; public const string T_Priority = "Priority"; public const string T_Filter = "Filter"; public const string Bracket = "[{0}]{1}"; } } <file_sep> namespace Netscape { public partial class UCExtractSets : UCBase { public UCExtractSets() { InitializeComponent(); } } } <file_sep>using System.ComponentModel; using System.Windows.Forms; namespace Netscape { public partial class KCombo : ComboBox { public KCombo() { InitializeComponent(); } public KCombo(IContainer container) { container.Add(this); InitializeComponent(); } public void BindUnicode() { // DataSource = KCrawler. ExcelCache.Unicode; SelectedIndex = 0; } public void BindMime() { Items.Clear(); } } }
af3dd4bc3a2bde767c6a025d9786e5a04b45816c
[ "C#", "INI" ]
63
C#
wjcking/Netscape
c620100e7088e1f5eb5884e8bf7f9bf1b15ec45a
26240ba2feae99b75e0bc75e53cc6d6993d74883
refs/heads/master
<repo_name>khadafirp/Tugas-Scan-QR<file_sep>/app/src/main/java/com/example/qrsiswa/MainActivity.java package com.example.qrsiswa; import androidx.appcompat.app.AppCompatActivity; import androidx.cardview.widget.CardView; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.view.View; import android.widget.Toast; import com.example.qrsiswa.qrscan.ScanActivity; import com.example.qrsiswa.tambahSiswa.TambahSiswaActivity; import pub.devrel.easypermissions.EasyPermissions; public class MainActivity extends AppCompatActivity { CardView cvBtnScan, cvBtnKelompok, cvBtnTambah; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cvBtnKelompok = findViewById(R.id.cvKelompok); cvBtnScan = findViewById(R.id.cvScan); cvBtnTambah = findViewById(R.id.cvTambahSiswa); cvBtnTambah.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, TambahSiswaActivity.class); startActivity(intent); } }); cvBtnScan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { Toast.makeText(MainActivity.this, "camera", Toast.LENGTH_LONG); Intent intent = new Intent(getBaseContext(), ScanActivity.class); intent.putExtra("before", "bayar"); startActivity(intent); } else { EasyPermissions.requestPermissions(MainActivity.this, "Izinkan kami untuk mengakses kamera", 27, Manifest.permission.CAMERA); } } }); } }
e169367da2bff8f9fa0d19d8af538a8968230a30
[ "Java" ]
1
Java
khadafirp/Tugas-Scan-QR
90b6cd6e0ac8be63296f906355d542193a295edc
dc9405e12209b6086d4124d8f0a92493203d90ea
refs/heads/master
<repo_name>Miv99/MALAnimePredictor<file_sep>/user_collector.py from datetime import datetime from mal_scraper import MALScraper from requests.exceptions import RequestException from mal_scraper import InvalidUserException from mal_info import User import pickle import logging from logging.handlers import RotatingFileHandler def configure_logger(): logger = logging.getLogger() logger.setLevel(logging.INFO) # Max 50mb log file handler = RotatingFileHandler('logs/log.log', mode='a', maxBytes=10 * 1024 * 1024) formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') handler.setFormatter(formatter) logger.addHandler(handler) return logger def load_pickle_file(pickle_file, default={}): try: with open(pickle_file, 'rb') as f: r = pickle.load(f) return r except IOError: return default def save(users, anime_database, users_pickle_file_name, anime_database_pickle_file): if users is not None: with open(users_pickle_file_name + '.pickle', 'wb') as out: logging.info('Saving ' + str(len(users)) + ' unique users') pickle.dump(users, out, protocol=pickle.HIGHEST_PROTOCOL) if anime_database is not None: with open(anime_database_pickle_file + '.pickle', 'wb') as out: logging.info('Saving ' + str(len(anime_database)) + ' unique anime') pickle.dump(anime_database, out, protocol=pickle.HIGHEST_PROTOCOL) def back_up(users, anime_database, users_pickle_file_name, anime_database_pickle_file_name): time_now = str(datetime.now()).replace('.', '_').replace('-', '_').replace(':', '_') if users is not None: with open('backups/' + users_pickle_file_name + time_now + '.pickle', 'wb') as out: pickle.dump(users, out, protocol=pickle.HIGHEST_PROTOCOL) if anime_database is not None: with open('backups/' + anime_database_pickle_file_name + time_now + '.pickle', 'wb') as out: pickle.dump(anime_database, out, protocol=pickle.HIGHEST_PROTOCOL) def collect_user_data(usernames_infile, anime_database_pickle_file_name, users_pickle_file_name, autosave_period): """"" Collect info on all users in usernames_infile and saves the data to pickle files. Data is still saved even after a keyboard interrupt. usernames_infile - newline-separated text file of usernames to be read anime_database_pickle_file_name - anime database pickle file path to be read in and overwritten afterwards; do not include the .pickle extension; dict of anime id as key and mal_info.DatabaseAnime object as value users_pickle_file_name - users pickle file path to be read in and overwritten afterwards; do not include the .pickle extension dict of username as key and mal_info.User object as value autosave_period - number of user/anime requests before data is saved and backed-up """"" time_now = str(datetime.now()).replace('.', '_').replace('-', '_').replace(':', '_') logging.info('-------------------- ' + time_now + ' --------------------------') logging.info('usernames_infile = "' + usernames_infile + '"; anime_database_pickle_file = "' + anime_database_pickle_file_name + '.pickle"; users_pickle_file = "' + users_pickle_file_name + '.pickle"') with open(usernames_infile) as file: usernames = file.read().split('\n') # Anime ID : mal_info.Anime object anime_database = load_pickle_file(anime_database_pickle_file_name + '.pickle', {}) # Username : mal_info.User object # Empty username corresponds to index where user last left off processing usernames_infile users = load_pickle_file(users_pickle_file_name + '.pickle', {}) scraper = MALScraper(30) autosave_counter = 0 # Encapsulate in try/catch so that process can be keyboard-interrupted and saved at any time try: # Get info for all users for username in usernames: print(username) if users.get(username) is None: logger.info('user_collector: Requesting info for user "' + username + '"') autosave_counter += 1 try: user = scraper.get_user(username) for anime_id in user.anime_list.keys(): anime_database[anime_id] = None users[username] = user logger.info('user_collector: Retrieved info for user "' + username + '": ' + str(user)) if autosave_counter % autosave_period == 0: save(users, anime_database, users_pickle_file_name, anime_database_pickle_file_name) back_up(users, anime_database, users_pickle_file_name, anime_database_pickle_file_name) except RequestException as e: logger.critical(e) except InvalidUserException as e: logger.info(e) users[username] = User(private_list_or_nonexistent=True) except Exception as e: logger.fatal(e) users[username] = User(private_list_or_nonexistent=True) elif users[username].private_list_or_nonexistent: logger.info('user_collector: Skipping user "' + username + '"; user does not exist or has private ' 'anime list') else: logger.info('user_collector: Skipping user "' + username + '"; data already exists') # Get info for all anime being used by the users for anime_id in anime_database.keys(): print(anime_id) if anime_database.get(anime_id) is None: logger.info('user_collector: Requesting info for anime id "' + str(anime_id) + '"') autosave_counter += 1 try: anime = scraper.get_anime(str(anime_id)) anime_database[anime_id] = anime logger.info('user_collector: Retrieved info for anime id "' + str(anime_id) + '": ' + str(anime)) if autosave_counter % autosave_period == 0: save(users, anime_database, users_pickle_file_name, anime_database_pickle_file_name) back_up(users, anime_database, users_pickle_file_name, anime_database_pickle_file_name) except RequestException as e: logger.critical(e) except Exception as e: logger.fatal(e) else: logger.info('user_collector: Skipping anime id "' + str(anime_id) + '"; data already exists') except KeyboardInterrupt: logger.info('user_collector: Keyboard-interrupted') except Exception as e: print(e) save(users, anime_database, users_pickle_file_name, anime_database_pickle_file_name) back_up(users, anime_database, users_pickle_file_name, anime_database_pickle_file_name) def get_staff(anime_database_pickle_file_name, autosave_period): """"" Collect info on all users in usernames_infile and saves the data to pickle files. Data is still saved even after a keyboard interrupt. usernames_infile - newline-separated text file of usernames to be read anime_database_pickle_file_name - anime database pickle file path to be read in and overwritten afterwards; do not include the .pickle extension; dict of anime id as key and mal_info.DatabaseAnime object as value users_pickle_file_name - users pickle file path to be read in and overwritten afterwards; do not include the .pickle extension dict of username as key and mal_info.User object as value autosave_period - number of user/anime requests before data is saved and backed-up """"" time_now = str(datetime.now()).replace('.', '_').replace('-', '_').replace(':', '_') logging.info('-------------------- ' + time_now + ' --------------------------') logging.info('anime_database_pickle_file = "' + anime_database_pickle_file_name + '.pickle') # Anime ID : mal_info.Anime object anime_database = load_pickle_file(anime_database_pickle_file_name + '.pickle', {}) scraper = MALScraper(30) autosave_counter = 0 # Encapsulate in try/catch so that process can be keyboard-interrupted and saved at any time try: # Get info for all anime being used by the users for anime_id in anime_database.keys(): print(anime_id) if anime_database.get(anime_id) is None: # Request like normal logger.info('user_collector: Requesting info for anime id "' + str(anime_id) + '"') autosave_counter += 1 try: anime = scraper.get_anime(str(anime_id)) anime_database[anime_id] = anime logger.info('user_collector: Retrieved info for anime id "' + str(anime_id) + '": ' + str(anime)) if autosave_counter % autosave_period == 0: back_up(None, anime_database, None, anime_database_pickle_file_name) except RequestException as e: logger.critical(e) except Exception as e: logger.fatal(e) elif not hasattr(anime_database[anime_id], 'staff'): logger.info('user_collector: Requesting staff for anime id "' + str(anime_id) + '"') autosave_counter += 1 try: anime_database[anime_id].staff = scraper.get_staff(anime_id) logger.info('user_collector: Retrieved staff for anime id "' + str(anime_id) + '": ' + str(anime_database[anime_id].staff)) if autosave_counter % autosave_period == 0: back_up(None, anime_database, None, anime_database_pickle_file_name) except RequestException as e: logger.critical(e) except Exception as e: logger.fatal(e) else: logger.info('user_collector: Skipping anime id "' + str(anime_id) + '"; staff data already exists') except KeyboardInterrupt: logger.info('user_collector: Keyboard-interrupted') a = 0 for anime_id in anime_database.keys(): if not hasattr(anime_database[anime_id], 'staff'): a += 1 print(str(a) + ' left') except Exception as e: print(e) save(None, anime_database, None, anime_database_pickle_file_name) back_up(None, anime_database, None, anime_database_pickle_file_name) if __name__ == '__main__': logger = configure_logger() # collect_user_data('users.txt', 'anime_database', 'users_fit', 200) get_staff('anime_database', 200)<file_sep>/mal_scraper.py from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup import re import logging import json import time from mal_info import Anime from mal_info import User from datetime import datetime from collections import deque class InvalidUserException(Exception): pass # anime_id in %s ANIME_URL = 'https://myanimelist.net/anime/%s' ANIME_STATS_URL = 'https://myanimelist.net/anime/%s/_/stats' ANIME_CHARACTERS_URL = 'https://myanimelist.net/anime/%s/_/characters' # username and ((page_number - 1) * 300) in %s ANIME_LIST_URL = 'https://myanimelist.net/animelist/%s/load.json?offset=%s&status=7' # Max number of cached results CACHE_MAX_SIZE = 20 class MALScraper: def __init__(self, request_delay): """ request_delay - delay in seconds before another request can be made if a 429 Too many requests error is encountered """ self.cache = deque() self.request_delay = request_delay def get_cached_result(self, url): for item in self.cache: if item[0] == url: return item[1] def simple_get(self, url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None. """ logging.info('MALScraper: Requested "' + url + '"') # Attempt to get cached result cached_result = self.get_cached_result(url) if cached_result is not None: return cached_result try: while True: with closing(get(url, stream=True)) as resp: # Encountered 429; sleep and try again if resp.content == b'Too Many Requests\n': logging.info('429 Too Many Requests; sleeping for ' + str(self.request_delay) + ' seconds...') time.sleep(self.request_delay) continue # Update cache self.cache.append((url, resp.content)) if len(self.cache) > CACHE_MAX_SIZE: self.cache.popleft() return resp.content except RequestException as e: logging.critical('MALScraper: Error during requests to {0} : {1}'.format(url, str(e))) raise e def get_mean_score(self, anime_id): """ anime_id - string Returns an anime's mean score """ try: raw_html = self.simple_get(ANIME_STATS_URL % anime_id) html = BeautifulSoup(raw_html, 'html.parser') # Sum of scores score_sum = 0 # Sum of votes count = 0 # Enumerate score = 10 for s in html.find_all('small')[-10:]: # Number of votes for this score c = int(re.findall(r'\d+', str(s))[0]) count += c score_sum += c * score score -= 1 return score_sum/count except Exception as e: raise e def get_anime_viewing_stats(self, anime_id): """" anime_id - string Returns an anime's viewing stats: number watching, completed, on-hold, and dropped, in that order """ try: raw_html = self.simple_get(ANIME_STATS_URL % anime_id) html = BeautifulSoup(raw_html, 'html.parser') result = html.find_all('div', class_='spaceit_pad') # Identify lines that contain the stats for line in result: line = str(line) if 'Watching' in line: w_line = line elif 'Completed' in line: c_line = line elif 'On-Hold' in line: o_line = line elif 'Dropped' in line: d_line = line watching = int(re.findall(r'\d+', w_line.replace(',', ''))[0]) completed = int(re.findall(r'\d+', c_line.replace(',', ''))[0]) on_hold = int(re.findall(r'\d+', o_line.replace(',', ''))[0]) dropped = int(re.findall(r'\d+', d_line.replace(',', ''))[0]) return watching, completed, on_hold, dropped except Exception as e: raise e def get_anime_info(self, anime_id): """" anime_id - string Returns an anime's type (TV/Movie/OVA/Special) (string), number of episodes, airing start date (datetime), and list of genres (strings) """ try: raw_html = self.simple_get(ANIME_URL % anime_id) html = BeautifulSoup(raw_html, 'html.parser') # Get type if html.find('a', href='https://myanimelist.net/topanime.php?type=tv') is not None: anime_type = 'TV' elif html.find('a', href='https://myanimelist.net/topanime.php?type=special') is not None: anime_type = 'Special' elif html.find('a', href='https://myanimelist.net/topanime.php?type=ova') is not None: anime_type = 'OVA' elif html.find('a', href='https://myanimelist.net/topanime.php?type=ona') is not None: anime_type = 'ONA' elif html.find('a', href='https://myanimelist.net/topanime.php?type=movie') is not None: anime_type = 'Movie' else: anime_type = 'Music' # Get number of episodes break2 = False for text in html.find_all('span', class_='dark_text'): if break2: break if text.contents[0] == 'Episodes:': for line in text.next_siblings: if len(line) != 0: episodes = line break2 = True break try: episodes = int(episodes) except ValueError: # Unknown number of episodes (literally "Unknown") episodes = 0 # Get airing date break2 = False for text in html.find_all('span', class_='dark_text'): if break2: break if text.contents[0] == 'Aired:': for line in text.next_siblings: if len(line) != 0: aired = line[3:16] break2 = True break # Try different "month, year" and "month day, year"; ignore anime with "year" try: airing_start_date = datetime.strptime(aired[:-4], '%b, %Y\n') except ValueError: # Check if day < 10 to 0-pad it if aired[5] == ',': aired = aired[:4] + '0' + aired[4:-1] try: airing_start_date = datetime.strptime(aired, '%b %d, %Y\n') except ValueError: # No airing start date airing_start_date = None # Get genres genres = [] for text in html.find_all('a', href=re.compile('/anime/genre/')): genres.append(str(text.contents[0])) # Get studios studios = [] for studios_text in html.find_all('span', class_='dark_text'): if studios_text.contents[0] == 'Studios:': for text in studios_text.find_next_siblings('a'): # No studios if str(text.contents[0]) == 'add some': break studios.append(str(text.contents[0])) break return anime_type, episodes, airing_start_date, genres, studios except Exception as e: raise e def get_staff(self, anime_id): """" anime_id - string Returns an anime's staff, a dict of position strings as key and list of people_ids as value """ try: raw_html = self.simple_get(ANIME_CHARACTERS_URL % anime_id) html = BeautifulSoup(raw_html, 'html.parser') # Get staff staff = {} for staff_text in html.find_all('a', href=re.compile('/people/')): if staff_text.find_next_sibling('div') is None: continue # Extract person_id from href people_id = re.findall(r'\d+', str(staff_text))[0] positions = str(staff_text.find_next_sibling('div').find('small').contents[0]).split(', ') if staff.get(people_id) is None: staff[people_id] = set() for position in positions: staff[people_id].add(position) # Get voice actors for a in html.find_all('a', href=re.compile('/character/')): try: if a.find_next_sibling('div') is None: continue character_type = str(a.find_next_sibling('div').find('small').contents[0]) va = a.find_parent('td').find_next_sibling('td').find('table').find('tr').find('td').find('a') # Extract person_id from href people_id = re.findall(r'\d+', str(va))[0] if str(va.find_next_sibling('small').contents[0]) == 'Japanese': if staff.get(people_id) is None: staff[people_id] = set() staff[people_id].add(character_type) except AttributeError: # No VA listed for this character # print('No voice actor found for ' + str(a.contents[0]) + ' in anime_id ' + anime_id) logging.info('No voice actor found for ' + str(a.contents[0]) + ' in anime_id ' + str(anime_id)) return staff except Exception as e: raise e def get_anime(self, anime_id): """" anime_id - string Returns a mal_info.Anime object """ try: anime_type, episodes, airing_start_date, genres, studios = self.get_anime_info(anime_id) watching, completed, on_hold, dropped = self.get_anime_viewing_stats(anime_id) mean_score = self.get_mean_score(anime_id) staff = self.get_staff(anime_id) return Anime(id=anime_id, completed=completed, watching=watching, dropped=dropped, mean_score=mean_score, genres=genres, anime_type=anime_type, episodes=episodes, airing_start_date=airing_start_date, studios=studios, staff=staff) except Exception as e: raise e def get_anime_list(self, username): """" username - string Returns a user's anime list of dicts of anime info """ try: page = 1 reading = True animelist = [] while reading: result = self.simple_get(ANIME_LIST_URL % (username, str((page - 1) * 300))) paginated_animelist = json.loads(result) if type(paginated_animelist) is dict and paginated_animelist.get('errors') is not None: raise InvalidUserException('User does not exist or anime list is private') # Anime lists are capped at 300 anime per page if len(paginated_animelist) != 300: reading = False animelist.extend(paginated_animelist) page += 1 return animelist except Exception as e: raise e def get_user(self, username): """" username - string Returns a mal_info.User object """ try: anime_list = {} score_sum = 0 count = 0 for anime_info in self.get_anime_list(username): anime_list[anime_info['anime_id']] = (anime_info['status'], anime_info['score']) # Only count anime with scores if anime_info['score'] != 0: score_sum += anime_info['score'] count += 1 if count == 0: raise InvalidUserException('User has no scores') return User(username=username, mean_score=score_sum/count, anime_list=anime_list) except Exception as e: raise e<file_sep>/mal_info.py class User: def __init__(self, username='', mean_score=0.0, anime_list={}, private_list_or_nonexistent=False): self.username = username self.mean_score = mean_score # Dict of anime_id : (watching_status, score_given_by_this_user) # 1 = watching, 2 = completed, 4 = dropped, 6 = ptw self.anime_list = anime_list # Used to quickly skip users who do not exist or have private anime lists in user_collector self.private_list_or_nonexistent = private_list_or_nonexistent def __repr__(self): return 'mal_info.User{username: ' + str(self.username) + '; mean_score:' + str(self.mean_score)\ + '; anime list size: ' + str(len(self.anime_list)) + '}' class Anime: def __init__(self, id='', completed=0, watching=0, dropped=0, mean_score=0.0, genres=[], anime_type='', episodes=0, airing_start_date=None, studios=[], staff={}): # String self.id = id # Number of people that have completed the anime self.completed = completed # Number of people that are watching the anime self.watching = watching # Number of people that dropped the anime self.dropped = dropped # Mean score from all users self.mean_score = mean_score # Genres as name strings self.genres = genres # Movie/TV/Special/OVA/ONA/Music as a string self.anime_type = anime_type # Total number of episodes self.episodes = episodes # Anime airing start date as a datetime object self.airing_start_date = airing_start_date # Anime studios self.studios = studios # Dict of people_id : staff position string (Director, Producer, etc) # Voice actors listed as 'Main' and/or 'Supporting' self.staff = {} def __repr__(self): return '<mal_info.Anime object: ' + str(self.__dict__) + '>'<file_sep>/network.py import torch import user_collector from sklearn.model_selection import KFold from collections import defaultdict import logging from collections import deque import os import matplotlib.pyplot as plt from random import shuffle import numpy as np class Network(torch.nn.Module): def __init__(self, input_size, output_size, hidden_size): super().__init__() self.input_size = input_size self.output_size = output_size self.hidden_size = hidden_size self.linear1 = torch.nn.Linear(input_size, hidden_size) self.relu = torch.nn.ReLU() self.linear2 = torch.nn.Linear(hidden_size, output_size) self.drop_layer = torch.nn.Dropout(p=0.5) torch.nn.init.xavier_normal_(self.linear1.weight) torch.nn.init.xavier_normal_(self.linear2.weight) def forward(self, x): y = self.linear2(self.drop_layer(self.relu(self.linear1(x)))) return y # Dict of Anime ID : mal_info.DatabaseAnime object anime_database = user_collector.load_pickle_file('anime_database_test.pickle') # List of mal_info.User object users = user_collector.load_pickle_file('users_fit_test.pickle').values() def purge_anime_list(user): """ user - mal_info.User object Removes all non-scored anime in the user's anime list Returns size of new anime list """ new_list = {} for k in user.anime_list.keys(): if user.anime_list[k][1] != 0: new_list[k] = user.anime_list[k] user.anime_list = new_list return len(new_list) # Remove users with < 30 scored anime users_as_list = [x for x in users if purge_anime_list(x) >= 50] users_train = [x for x in users_as_list[0:int(len(users_as_list) * 0.8)]] users_test = [x for x in users_as_list[int(len(users_as_list) * 0.8):len(users_as_list)]] # ONA, OVA, and Special classified as Special # Music ignored types = ['TV', 'Movie', 'Special'] # Find mean value of all features # Order is same as order of features of x in get_x_list() for simpler code feature_mean_value = [] s = 0 for user in users_train: s += user.mean_score # user mean score feature_mean_value.append(s/len(users_train)) s = 0 c = 0 for anime in anime_database.values(): if anime.mean_score != 0: s += anime.mean_score c += 1 # anime mean score feature_mean_value.append(s/c) # ums of anime with same episode count and similar start date # both basically the same thing as ums feature_mean_value.append(feature_mean_value[0]) feature_mean_value.append(feature_mean_value[0]) # Get all genres genres = set() percent_dropped_list = [] # sum and count of mean scores by genre and type s_g = defaultdict(lambda: 0) c_g = defaultdict(lambda: 0) s_t = defaultdict(lambda: 0) c_t = defaultdict(lambda: 0) for anime in anime_database.values(): if anime.dropped + anime.watching + anime.completed != 0: percent_dropped_list.append(anime.dropped/(anime.dropped + anime.watching + anime.completed)) for genre in anime.genres: genres.add(genre) if anime.mean_score != 0: s_g[genre] += anime.mean_score c_g[genre] += 1 if anime.mean_score != 0: # Treat these as type Special if anime.anime_type == 'OVA' or anime.anime_type == 'ONA' or anime.anime_type == 'Special': s_t['Special'] += anime.mean_score c_t['Special'] += 1 elif anime.anime_type != 'Music': s_t[anime.anime_type] += anime.mean_score c_t[anime.anime_type] += 1 def reject_outliers(data, m = 2.): d = np.abs(data - np.median(data)) mdev = np.median(d) s = d/mdev if mdev else 0. ret = [] for i, x in enumerate(data): if s[i] < m: ret.append(x) return ret # Remove outliers percent_dropped_list = reject_outliers(percent_dropped_list) max_percent_dropped = max(percent_dropped_list) min_percent_dropped = min(percent_dropped_list) print(min_percent_dropped, max_percent_dropped) # percent of people that dropped an anime feature_mean_value.append(np.mean(percent_dropped_list)) # ums of all genres for genre in genres: feature_mean_value.append(s_g[genre]/c_g[genre]) # ums of all types for anime_type in types: feature_mean_value.append(s_t[anime_type]/c_t[anime_type]) combined_roles = {'Art Director' : ['Art Director', 'Director of Photography'], 'Design' : ['Original Character Design', 'Character Design', 'Color Design', 'Mechanical Design'], 'Writing' : ['Screenplay', 'Script', 'Series Composition'], 'Animation Director' : ['Storyboard', 'Assistant Animation Director', 'Animation Director', 'Chief Animation Director'], 'Animation' : ['Special Effects', 'Key Animation', 'Principle Drawing', '2nd Key Animation', 'Background Art', 'Animation Check', 'Digital Paint', 'Editing', 'In-Between Animation'], 'Sound' : ['Sound Director', 'Sound Effects'], 'Producer' : ['Executive Producer', 'Chief Producer', 'Producer', 'Assistant Producer', 'Production Coordination'], 'Setting' : ['Setting', 'Color Setting'], 'Director' : ['Assistant Director', 'Episode Director', 'Director'], 'Creator' : ['Creator', 'Original Creator'], 'Planning' : ['Planning', 'Layout'], 'Music' : ['Music'], 'Main VA' : ['Main'], 'Supporting VA' : ['Supporting'] } # To maintain order, just in case all_combined_role_names = list(combined_roles.keys()) def get_combined_role_name(role_name): for combined_name, roles in combined_roles.items(): if role_name in roles: return combined_name return None def get_x_list(user, ids): """ anime_database - Dict of Anime ID : mal_info.DatabaseAnime object user - mal_info.User ids - array of anime_ids to use Mean score features are calculated from anime_train_ids Returns 2 lists of length len(anime_test_indices) of tuples of (anime_id and tensors), x_list_train and x_list_test ums = user mean score x = [ums, anime_mean_score, ums_of_anime_with_similar_episode_count, ums_of_anime_with_similar_start_date, percent_of_people_that_dropped_the_anime (scaled to be near range [0, 10] before being shifted), ums_of_all_genres (0 before shift if genre is not part of the anime's genres), ums_of_all_types (0 before shift if type is not the anime's type)] """ shuffle(ids) ids_for_ums_calculation = [x for x in ids[0:int(len(ids) * 0.8)]] ids_for_training = [x for x in ids[int(len(ids) * 0.8):len(ids)]] x_list = [] ums = 0 # Doesn't have to be exactly the same; +- 3 is fine # Dict with key of episode count and value of ums ums_by_episode_count = defaultdict(lambda: 0.) # Same^; +- 3 months # Dict with key of tuple (month, year) and value of ums ums_by_start_date = defaultdict(lambda: 0.) ums_by_genre = defaultdict(lambda: 0.) ums_by_type = defaultdict(lambda: 0.) ums_by_studio = defaultdict(lambda: 0.) # Variables for keeping track of sum and count for calculating means ums_c = 0 ums_episode_c = defaultdict(lambda: 0) ums_date_c = defaultdict(lambda: 0) ums_genres_c = defaultdict(lambda: 0) ums_types_c = defaultdict(lambda: 0) ums_studios_c = defaultdict(lambda: 0) ums_people_c = defaultdict(lambda: defaultdict(lambda: 0)) ums_s = 0 ums_episode_s = defaultdict(lambda: 0) ums_date_s = defaultdict(lambda: 0) ums_genres_s = defaultdict(lambda: 0) ums_types_s = defaultdict(lambda: 0) ums_studios_s = defaultdict(lambda: 0) # Dict with key of people_id and value of # dict with keys combined_roles.keys() and value of sum of user scores of all anime in # which this people_id was working as this combined role ums_people_s = defaultdict(lambda: defaultdict(lambda: 0)) for anime_id in ids_for_ums_calculation: anime = anime_database[anime_id] # Skip type music if anime.anime_type == 'Music': continue user_score = user.anime_list[anime_id][1] ums_c += 1 ums_s += user_score for i in range(-3, 3): ums_episode_c[anime.episodes + i] += 1 ums_episode_s[anime.episodes + i] += user_score for month in range(-3, 3): # This happens with anime with start dates that are just the year (which is very few) if anime.airing_start_date is None: continue new_month = anime.airing_start_date.month + month new_year = anime.airing_start_date.year if new_month <= 0: new_year -= 1 new_month += 12 elif new_month > 12: new_year += 1 new_month -= 12 ums_date_c[(new_month, new_year)] += 1 ums_date_s[(new_month, new_year)] += user_score for genre in anime.genres: ums_genres_c[genre] += 1 ums_genres_s[genre] += user_score ums_types_c[anime.anime_type] += 1 ums_types_s[anime.anime_type] += user_score for studio in anime.studios: ums_studios_c[studio] += 1 ums_studios_s[studio] += user_score for people_id, roles in anime.staff.items(): for role in roles: combined_name = get_combined_role_name(role) if combined_name is not None: ums_people_c[people_id][combined_name] += 1 ums_people_s[people_id][combined_name] += user_score # Calculate all ums stuff ums = ums_s / ums_c for k in ums_episode_c.keys(): ums_by_episode_count[k] = ums_episode_s[k] / ums_episode_c[k] for k in ums_date_c.keys(): ums_by_start_date[k] = ums_date_s[k] / ums_date_c[k] for k in ums_genres_c.keys(): ums_by_genre[k] = ums_genres_s[k] / ums_genres_c[k] for k in ums_types_c.keys(): ums_by_type[k] = ums_types_s[k] / ums_types_c[k] for k in ums_studios_c.keys(): ums_by_studio[k] = ums_studios_s[k] / ums_studios_c[k] for anime_id in ids_for_training: anime = anime_database[anime_id] # Skip type music if anime.anime_type == 'Music': continue x = torch.zeros(INPUT_SIZE) x[0] = ums x[1] = anime_database[anime_id].mean_score x[2] = ums_by_episode_count[anime.episodes] # This happens with anime with start dates that are just the year (which is very few) if anime.airing_start_date is None: # Just use the user's mean score x[3] = ums else: x[3] = ums_by_start_date[(anime.airing_start_date.month, anime.airing_start_date.year)] # Get as a percent of most watched anime # x[4] = (anime.watching + anime.completed)/most_watched # x[4] = 5 percent_dropped = anime.dropped / (anime.watching + anime.completed + anime.dropped) # Scale to be near range [0, 10] # Will not always be in this range since outliers were removed before finding min and max percent dropped x[4] = 10 * (percent_dropped - min_percent_dropped)/(max_percent_dropped - min_percent_dropped) studio_score = 0 if len(anime.studios) != 0: for studio in anime.studios: studio_score += ums_by_studio[studio] studio_score /= len(anime.studios) x[5] = studio_score i = 6 for genre in genres: if genre in anime.genres: x[i] = ums_by_genre[genre] else: x[i] = 0 i += 1 """ # x[6] is mean of ums of all anime with overlapping genres # TODO: increase so that at least [a] number of overlapping genres? g_sum = 0 for genre in anime.genres: g_sum += ums_by_genre[genre] if len(anime.genres) == 0 or g_sum == 0: x[6] = ums else: x[6] = g_sum / len(anime.genres) i = 7 """ for anime_type in types: if anime_type == 'Special' \ and (anime.anime_type == 'OVA' or anime.anime_type == 'ONA' or anime.anime_type == 'Special'): x[i] = ums_by_type[anime_type] else: x[i] = 0 i += 1 # considering only related roles for combined_role_name in all_combined_role_names: role_sum = 0 role_count = 0 for people_id, roles in anime.staff.items(): for role in roles: if get_combined_role_name(role) == combined_role_name: role_sum += ums_people_s[people_id][combined_role_name] role_count += ums_people_c[people_id][combined_role_name] if role_count <= 0: x[i] = 0 else: x[i] = role_sum / role_count i += 1 # Shift so mean is 0 for j in range(i): if x[j] != 0: x[j] -= 5 x_list.append((anime_id, x)) return x_list def get_y(user, anime_id): y = torch.zeros(OUTPUT_SIZE) y[0] = user.anime_list[anime_id][1] return y # ums = user mean score # x = [ums, anime_mean_score, ums_of_anime_with_similar_episode_count, ums_of_anime_with_similar_start_date, # percent_of_people_that_dropped_the_anime (scaled to be near range [0, 10] before being shifted), # ums_of_all_genres (0 before shift if genre is not part of the anime's genres), # ums_of_all_types (0 before shift if type is not the anime's type)] INPUT_SIZE = 6 + len(genres) + len(types) + len(combined_roles) #INPUT_SIZE = 7 + len(types) OUTPUT_SIZE = 1 # ----- HYPERPARAMETERS ----- LEARNING_RATE = 1e-3 MOMENTUM = 0 HIDDEN_SIZE = 25 LR_SCHEDULER_GAMMA = 0.3 #LR_SCHEDULER_STEP_SIZE = 1 LR_SCHEDULER_MILESTONES = [2, 4] WEIGHT_DECAY = 1e-2 # These ones aren't too important #MAX_ANIME_PER_FOLD = 400 MAX_EPOCH = 200 # For graphing purposes POINTS_PER_EPOCH = 100 # ---------------------------- def test(): torch.manual_seed(44) criterion = torch.nn.MSELoss(reduction='mean') # Stuff that will be saved and can be loaded model = Network(INPUT_SIZE, OUTPUT_SIZE, HIDDEN_SIZE) # optimizer = torch.optim.SGD(model.parameters(), lr=LEARNING_RATE, momentum=MOMENTUM, weight_decay=WEIGHT_DECAY) optimizer = torch.optim.Adam(params=model.parameters(), lr=LEARNING_RATE) # scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=LR_SCHEDULER_STEP_SIZE, gamma=LR_SCHEDULER_GAMMA) scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=LR_SCHEDULER_MILESTONES, gamma=LR_SCHEDULER_GAMMA) plt_test_x = [] plt_test_y = [] plt_train_x = [] plt_train_y = [] epoch_train_mean_errors = [] epoch_test_mean_errors = [] epoch = 0 smallest_test = 1e20 smallest_train = 1e20 users_train_total = len(users_train) users_test_total = len(users_test) def save(): torch.save({ 'epoch': epoch, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'scheduler_state_dict': scheduler.state_dict(), 'plt_test_x': plt_test_x, 'plt_test_y': plt_test_y, 'plt_train_x': plt_train_x, 'plt_train_y': plt_train_y, 'epoch_train_mean_errors': epoch_train_mean_errors, 'epoch_test_mean_errors': epoch_test_mean_errors }, 'model states/' + model_name + '_epoch' + str(epoch) + '.pickle') def load(model_name, epoch_to_load): nonlocal model nonlocal optimizer nonlocal scheduler nonlocal epoch nonlocal plt_test_x nonlocal plt_test_y nonlocal plt_train_x nonlocal plt_train_y nonlocal epoch_train_mean_errors nonlocal epoch_test_mean_errors path = 'model states/' + model_name + '_epoch' + str(epoch_to_load) + '.pickle' checkpoint = torch.load(path) model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) scheduler.load_state_dict(checkpoint['optimizer_state_dict']) epoch = checkpoint['epoch'] plt_test_x = checkpoint['plt_test_x'] plt_test_y = checkpoint['plt_test_y'] plt_train_x = checkpoint['plt_train_x'] plt_train_y = checkpoint['plt_train_y'] epoch_train_mean_errors = checkpoint['epoch_train_mean_errors'] epoch_test_mean_errors = checkpoint['epoch_test_mean_errors'] def show_results_so_far(log): print('Epoch test mean errors:') if log: logging.info('Epoch test mean errors:') for i, error in enumerate(epoch_test_mean_errors): print('Epoch ' + str(i) + ': ' + str(error)) if log: logging.info('Epoch ' + str(i) + ': ' + str(error)) print('Epoch train mean errors:') if log: logging.info('Epoch train mean errors:') for i, error in enumerate(epoch_train_mean_errors): print('Epoch ' + str(i) + ': ' + str(error)) if log: logging.info('Epoch ' + str(i) + ': ' + str(error)) print('Smallest test: ' + str(smallest_test)) print('Smallest train: ' + str(smallest_train)) if log: logging.info('Smallest test: ' + str(smallest_test)) logging.info('Smallest train: ' + str(smallest_train)) print("Model's state_dict:") if log: logging.info('Model\'s state_dict:') for param_tensor in model.state_dict(): print(str(param_tensor) + ': ' + str(model.state_dict()[param_tensor])) if log: logging.info(str(param_tensor) + ': ' + str(model.state_dict()[param_tensor])) plt.plot(plt_test_x, plt_test_y, 'ro') plt.plot(plt_train_x, plt_train_y, 'bo') plt.show() plt.clf() plt.gcf().clear() if input('Enter 1 to load a model: ') == '1': input('') model_name = input('Enter model name: ') input('') epoch = input('Enter epoch: ') input('') load(model_name, epoch) else: input('') # just to keep track of saved model states model_name = input('Enter new model\'s name: ') input('') logging.basicConfig(filename='logs/' + model_name + '.log', format='%(asctime)s - %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO, filemode='a') try: while epoch < MAX_EPOCH: shuffle(users_train) scheduler.step() user_train_mean_loss_sum = 0 user_test_mean_loss_sum = 0 user_train_mean_loss_count = 0 user_test_mean_loss_count = 0 i = 0 epoch_train_sum = 0 epoch_train_count = 0 for user in users_train: try: keys_as_list = list(user.anime_list.keys()) ids = [keys_as_list[x] for x in range(len(keys_as_list))] x_list = get_x_list(user, ids) mean_loss_sum = 0 for x in x_list: optimizer.zero_grad() y_pred = model(x[1]) y_correct = get_y(user, x[0]) loss = criterion(y_pred, y_correct) mean_loss_sum += loss.item() epoch_train_sum += loss.item() loss.backward() optimizer.step() epoch_train_count += 1 user_train_mean_loss = mean_loss_sum / len(x_list) user_train_mean_loss_sum += user_train_mean_loss user_train_mean_loss_count += 1 if i % int(users_train_total/POINTS_PER_EPOCH) == 0: plt_train_x.append((i + (epoch * users_train_total))/users_train_total) plt_train_y.append(user_train_mean_loss_sum/user_train_mean_loss_count) smallest_train = min(smallest_train, user_train_mean_loss_sum/user_train_mean_loss_count) user_train_mean_loss_sum = 0 user_train_mean_loss_count = 0 logging.info('epoch ' + str(epoch) + ' user ' + str(i) + '/' + str(users_train_total) + '; avg train = ' + str(user_train_mean_loss)) print('epoch ' + str(epoch) + ' user ' + str(i) + '/' + str(users_train_total) + '; avg train = ' + str(user_train_mean_loss)) i += 1 except KeyboardInterrupt: show_results_so_far(False) a = input('Enter 0 to stop training') input('') if a == '0': epoch_train_mean_error = epoch_train_sum / epoch_train_count epoch_train_mean_errors.append(epoch_train_mean_error) raise KeyboardInterrupt epoch_train_mean_error = epoch_train_sum / epoch_train_count epoch_train_mean_errors.append(epoch_train_mean_error) i = 0 epoch_test_sum = 0 epoch_test_count = 0 for user in users_test: try: keys_as_list = list(user.anime_list.keys()) ids = [keys_as_list[x] for x in range(len(keys_as_list))] x_list = get_x_list(user, ids) mean_loss_sum = 0 with torch.no_grad(): for x in x_list: y_pred = model(x[1]) y_correct = get_y(user, x[0]) loss = criterion(y_pred, y_correct) mean_loss_sum += loss.item() epoch_test_sum += loss.item() epoch_test_count += 1 user_test_mean_loss = mean_loss_sum / len(x_list) user_test_mean_loss_sum += user_test_mean_loss user_test_mean_loss_count += 1 if i % int(users_test_total/POINTS_PER_EPOCH) == 0: plt_test_x.append((i + (epoch * users_test_total))/users_test_total) plt_test_y.append(user_test_mean_loss_sum / user_test_mean_loss_count) smallest_test = min(smallest_test, user_test_mean_loss_sum / user_test_mean_loss_count) user_test_mean_loss_sum = 0 user_test_mean_loss_count = 0 logging.info( 'epoch ' + str(epoch) + ' user ' + str(i) + '/' + str(users_test_total) + '; avg test = ' + str( user_test_mean_loss)) print('epoch ' + str(epoch) + ' user ' + str(i) + '/' + str(users_test_total) + '; avg test = ' + str( user_test_mean_loss)) i += 1 except KeyboardInterrupt: show_results_so_far(False) a = input('Enter 0 to stop training') input('') if a == '0': epoch_test_mean_error = epoch_test_sum / epoch_test_count epoch_test_mean_errors.append(epoch_test_mean_error) raise KeyboardInterrupt epoch_test_mean_error = epoch_test_sum/epoch_test_count epoch_test_mean_errors.append(epoch_test_mean_error) epoch += 1 save() except KeyboardInterrupt: pass finally: show_results_so_far(True) if input('Enter 1 to save (not recommended if stopped in the middle of an epoch' ' because training resumes from start of epoch): ') == '1': save() if __name__ == '__main__': if not os.path.isdir('logs'): os.makedirs('logs') if not os.path.isdir('model states'): os.makedirs('model states') test()<file_sep>/README.md # MALAnimePredictor A neural network to predict a MyAnimeList user's score for an unwatched anime Project on hold until I can figure out how to fix the network overfitting problem.
283a970d15d9ce564ad6182cf86d0f67c7dc87f8
[ "Markdown", "Python" ]
5
Python
Miv99/MALAnimePredictor
06aafdc014886f7cdf334df7ba253c27e6cf4bcd
a5528dc04f3ab4fc6aaaf2ab91b183eca68dc9ad
refs/heads/master
<file_sep>DB_DATABASE= DB_USER= DB_PASS= DB_HOST= DB_PORT= PORT=<file_sep>version: '3' networks: gateway: external: true services: rabbitmq: image: rabbitmq:3-management container_name: "rabbitmq" expose: - "15672" - "5672" - "25676" networks: - gateway ports: - "8086:15672" <file_sep>## RabbitMQ Steps: Just run the container rabbitmq. RabbitMQ can be util for comunication between microservices, like some business rules: // When create a user, create a order test for him<file_sep> exports.seed = function (knex, Promise) { // Deletes ALL existing entries return knex('orders').del() .then(function () { // Inserts seed entries return knex('orders').insert([ { id: 1, id_user: 1, description: '', approved: true }, { id: 2, id_user: 1, description: '', approved: true }, { id: 3, id_user: 1, description: '', approved: false }, ]); }); }; <file_sep>version: '3' networks: gateway: external: true services: # API app: container_name: "ms-gateway" environment: NODE_ENV: development HOST: localhost/api PORT: "3000" build: context: . dockerfile: Dockerfile user: "node" working_dir: /home/node/app networks: - gateway volumes: - ./:/home/node/app ports: - "8000:3000" command: "node server.js"<file_sep> exports.up = function (knex) { return knex.schema.createTable('orders', function (table) { table.integer('id').primary() table.integer('id_user').notNullable() table.text('description') table.boolean('approved').defaultTo(true) table.timestamps(true, true) }) } exports.down = function (knex) { return knex.schema.dropTable('orders') } <file_sep>#!/bin/bash INIT_PATH=$(pwd) # Up gateway cd "$INIT_PATH/gateway"; docker-compose up -d --build # Up RabbitMQ cd "$INIT_PATH/messager-queue"; docker-compose up -d --build # UP Users cd "$INIT_PATH/ms-user"; docker-compose up -d --build # UP Orders cd "$INIT_PATH/ms-order"; docker-compose up -d --build <file_sep># microservices-example Just example of architecture microservices with API Gateway/Management and AMQP/MQTT ## Running Make sure you have Docker installed in you workspace. ```sh ./setup.sh ``` And check your containers ```sh docker ps ``` ## Usage **Message Broker**: Make a post to `users` api sending a raw json like: ```json { "name": "test", "email": "<EMAIL>" } ``` So, if you receive something like: `[x] Sended...`, just go to container `ms-orders-api` <file_sep>const uuid = require('uuid/v4') exports.seed = function (knex, Promise) { // Deletes ALL existing entries return knex('users').del() .then(function () { // Inserts seed entries return knex('users').insert([ { id: uuid(), name: '<NAME>', email: '<EMAIL>', admin: true }, { id: uuid(), name: '<NAME>', email: '<EMAIL>', admin: true }, { id: uuid(), name: '<NAME>', email: '<EMAIL>', admin: false }, ]); }); }; <file_sep>PORT=80 HOST=http://localhost<file_sep>module.exports = (fastify, opts, next) => { const queue = 'users_created' fastify.amqpChannel.assertQueue(queue, { durable: true }) fastify.amqpChannel.consume(queue, function (msg) { if (msg !== null) { console.log('%s Received: %s', new Date(), msg.content.toString()) // fastify.inject({ // method: 'POST', // url: '/', // payload: '' // }).then(data => { // }) fastify.amqpChannel.ack(msg) } }) next() }<file_sep>const db = require('knex')(require('../knexfile')) module.exports = (fastify, opts, next) => { fastify.get('/root/', (request, reply) => { reply.send({ dialect: "Order", error: false }) }) .get('/', (request, reply) => { return db('orders').then(orders => reply.send(orders)) }) .get('/:id', (request, reply) => { return db('orders').where({ id: request.params.id }).then(orders => reply.send(orders)) }) .get('/:id/orders', (request, reply) => { return db('orders').where({ id_user: request.params.id }).then(orders => reply.send(orders)) }) next() }
20198b6882b2fc1249c52c86bac330e69d30ff8e
[ "Markdown", "JavaScript", "YAML", "Shell" ]
12
Shell
RafaelGSS/microservices-example
36a48001e03799735cc210a6bcc34501e8d9bb03
0e9e9c5087f7e1c49709feabdd40a67726077875
refs/heads/master
<file_sep>/** * Created by Antonella on 2/10/17. */ public class Wallaby extends Animal { @Override public void name() { System.out.println("I am Australian."); } @Override public void speak() { System.out.println("????"); } @Override public void bodyParts() { System.out.println("Unknown."); } @Override public void size() { System.out.println("Humongous."); } } <file_sep>public class Main { public static void main(String[] args) { Dog dog = new Dog(); Ferret ferret = new Ferret(); Wallaby wallaby = new Wallaby(); dog.size(); ferret.name(); dog.toEat(); } } <file_sep>/** * Created by Antonella on 2/10/17. */ public interface Mammal { public abstract void toEat(); void warmBlooded(); }
254d2c0683ed7f15bc1cb57cac8a0166cffe2d67
[ "Java" ]
3
Java
asolomon412/Abstract-InterfaceDemo
4a9bfd3c666963e95e466bc3d5fcae5a5469f383
1ea0e56bd2dfbed5fc5fc5fcb61357b3dc2a8935
refs/heads/master
<repo_name>jpedropmont/demo-mvc<file_sep>/src/main/java/com/joaopedro/service/FuncionarioService.java package com.joaopedro.service; import java.util.List; import java.util.Optional; import com.joaopedro.domain.Funcionario; public interface FuncionarioService { public void salvar (Funcionario funcionario); public void editar (Funcionario funcionario); public void excluir (Long id); public Optional<Funcionario> buscarPorId(Long id); public List<Funcionario> buscarTodos(); } <file_sep>/src/main/java/com/joaopedro/service/CargoService.java package com.joaopedro.service; import java.util.List; import java.util.Optional; import com.joaopedro.domain.Cargo; public interface CargoService { public void salvar (Cargo cargo); public void editar (Cargo cargo); public void excluir (Long id); public Optional<Cargo> buscarPorId(Long id); public List<Cargo> buscarTodos(); }
0fab691054d053e8729253512ca82c06d69410dc
[ "Java" ]
2
Java
jpedropmont/demo-mvc
b58f19339de81169fb3f17704cd3dbe4a38bf997
ab3f208d1a55facf397c8b9e7115d402eca83f37
refs/heads/master
<repo_name>lookoutldz/lifepoint<file_sep>/src/main/java/com/alpha/lifepoint/dao/DailyItemDAO.java package com.alpha.lifepoint.dao; import com.alpha.lifepoint.entity.DailyItem; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface DailyItemDAO extends BaseDAO<DailyItem> { List<DailyItem> findByChanger(Integer id); } <file_sep>/src/main/resources/sql/create.sql create database `life` default charset `utf8mb4`; use `life`; create table `changer`( `id` int not null auto_increment, `name` varchar(63) not null, `password` varchar(63) not null, primary key(`id`), unique(`name`) ); create table `daily_item`( `id` int not null auto_increment, `name` varchar(63) not null default '', `point` int not null, `changer_id` int not null, primary key(`id`), unique(`name`) ); create table `daily_situation`( `id` int not null auto_increment, `changer_id` int not null, `item_id` int not null, `finished` tinyint not null default 0, `date` date not null, primary key(`id`), unique(`changer_id`, `item_id`, `date`) );<file_sep>/src/main/java/com/alpha/lifepoint/entity/DailyItem.java package com.alpha.lifepoint.entity; import lombok.Data; @Data public class DailyItem { private Integer id; private String name; private Integer point; private Integer changerId; } <file_sep>/src/main/java/com/alpha/lifepoint/controller/ChangerController.java package com.alpha.lifepoint.controller; import com.alpha.lifepoint.dao.ChangerDAO; import com.alpha.lifepoint.entity.Changer; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @CrossOrigin @RequestMapping("/changer") public class ChangerController { @Autowired ChangerDAO changerDAO; @GetMapping("/ok") public Object ok() { return "ok"; } @PostMapping("/login") public Object login(@RequestBody Changer changer) { return changer; } @GetMapping("/{id}") public Object getById(@PathVariable("id") Integer id) { return changerDAO.getById(id); } @GetMapping("/all") public PageInfo<Changer> getAll(@RequestParam(value = "pageIndex", required = false) Integer pageIndex, @RequestParam(value = "pageSize", required = false) Integer pageSize) { pageIndex = pageIndex == null ? 0 : pageIndex; pageSize = pageSize == null ? 10 : pageSize; PageHelper.startPage(pageIndex, pageSize); List<Changer> changers = changerDAO.findAll(); PageInfo<Changer> pageInfo = new PageInfo<>(changers); return pageInfo; } @PostMapping("") public Object create(@RequestBody Changer changer) { return changerDAO.insert(changer); } } <file_sep>/src/main/java/com/alpha/lifepoint/entity/DailySituation.java package com.alpha.lifepoint.entity; import lombok.Data; import java.sql.Date; @Data public class DailySituation { private Integer id; private Integer changerId; private Integer itemId; private Boolean finished; private Date date; } <file_sep>/src/main/java/com/alpha/lifepoint/dao/BaseDAO.java package com.alpha.lifepoint.dao; import java.util.List; public interface BaseDAO<T> { T getById(Integer id); List<T> findAll(); Integer insert(T t); Integer update(T t); Integer delete(Integer id); }
d45b308f7ff50638cdd2c3f6566bde8ce4986e7e
[ "Java", "SQL" ]
6
Java
lookoutldz/lifepoint
9f2480f9db1c64de0373ec9d1eea0e13ba03c298
5ebda94b10fcf5687923d6d5e9ee4959847bbd0d
refs/heads/master
<file_sep>--- layout: default title: "Using Dart with JSON Web Services" description: "Learn how to consume JSON-based web services with Dart." rel: author: chris-buckett has-permalinks: true article: written_on: 2012-04-01 updated_on: 2012-11-01 collection: libraries-and-apis --- # {{ page.title }} _Written by <NAME><br> April 2012 (updated November 2012)_ Most client-side Dart apps need a way to communicate with a server, and sending JSON via [XMLHttpRequest](https://developer.mozilla.org/en/XMLHttpRequest) is the preferred way to do this. This article discusses communicating with a server using the [HttpRequest API](http://api.dartlang.org/html/HttpRequest.html) from the [dart:html](http://api.dartlang.org/html.html) library and parsing JSON data using the [dart:json](http://api.dartlang.org/json.html) library. It then goes on to show how to provide dot-notation access to JSON data through the use of JsonObject. #### Contents <ol class="toc"> <li><a href="#json-web-service">A JSON web service</a></li> <li><a href="#connecting-to-server">Connecting to a server</a> <ol> <li><a href="#getting-data">Getting data from the server</a></li> <li><a href="#saving-object">Saving objects on the server</a></li> </ol> </li> <li><a href="#parsing-json">Parsing JSON</a> <ol> <li><a href="#jsonobject">Introducing JsonObject</a></li> <li><a href="#note-on-jsonp">A note on JSONP and HttpRequest</a></li> </ol> </li> <li><a href="#summary">Summary</a></li> <li><a href="#resources">Resources</a></li> <li><a href="#about-author">About the author</a></li> </ol> <h2 id="json-web-service">A JSON web service</h2> Many modern web apps are powered by RESTful web services that send and receive data encoded as JSON. This article features a web service that responds to an HTTP GET to the URL `/programming-languages/dart` by returning the following JSON string, which contains a string, a list, and a map that represent information about the Dart language: {% highlight json %} { "language": "dart", // String "targets": ["dartium","javascript"], // List "website": { // Map "homepage": "www.dartlang.org", "api": "api.dartlang.org" } } {% endhighlight %} The same web service accepts data on the same URL with an HTTP POST. The web service interprets a POST as a request to create a new object on the server, like an SQL INSERT. The POSTed JSON data is sent in the HTTP body. <h2 id="connecting-to-server">Connecting to the server</h2> When communicating with a web service, use the HttpRequest API from the dart:html library. HttpRequest is a standard way to programmatically send and receive data to and from web servers. <h3 id="getting-data">Getting data from the server</h3> Get objects from the server using HTTP GET. HttpRequest provides a named constructor called <code>get</code> that takes a URL and a callback function that's invoked when the server responds. {% highlight dart %} getLanguageData(String languageName, onSuccess(HttpRequest req)) { var url = "http://example.com/programming-languages/$languageName"; // call the web server asynchronously var request = new HttpRequest.get(url, onSuccess); } {% endhighlight %} Then elsewhere in your code, you can define an <code>onSuccess</code> callback function and call the <code>getLanguageData</code> function: {% highlight dart %} // print the raw json response text from the server onSuccess(HttpRequest req) { print(req.responseText); // print the received raw JSON text } main() { getLanguageData("dart", onSuccess); } {% endhighlight %} Note: HttpRequest.get() is a convenience constructor, and its name will change. The full HttpRequest API is still an option for HTTP GET, if you need more control over the API. <h3 id="saving-object">Saving objects on the server</h3> To create a new object on the server, use the raw HttpRequest API with the HTTP POST method. Use the readyStateChange listener to be notified when the request is complete. The example below calls an onSuccess function when the request is complete: {% highlight dart %} saveLanguageData(String data, onSuccess(HttpRequest req)) { HttpRequest req = new HttpRequest(); // create a new XHR // add an event handler that is called when the request finishes req.on.readyStateChange.add((Event e) { if (req.readyState == HttpRequest.DONE && (req.status == 200 || req.status == 0)) { onSuccess(req); // called when the POST successfully completes } }); var url = "http://example.com/programming-languages/"; req.open("POST", url); // Use POST http method to send data in the next call req.send(data); // kick off the request to the server } // print the raw json response text from the server onSuccess(HttpRequest req) { print(req.responseText); // print the received raw JSON text } String jsonData = '{"language":"dart"}'; // etc... saveLanguageData(stringData, onSuccess); // send the data to // the server {% endhighlight %} <h2 id="parsing-json">Parsing JSON</h2> Now that you have seen how HttpRequest GETs data from the server back to the client, and POSTs data from the client to the server, the next step is to make use of the JSON data in the client application. The dart:json library provides two static functions, JSON.parse() and JSON.stringify(). The parse() function converts a JSON string into a List of values or a Map of key-value pairs, depending upon the format of the JSON: {% highlight dart %} String listAsJson = '["Dart",0.8]'; // input List of data List parsedList = JSON.parse(listAsJson); print(parsedList[0]); // Dart print(parsedList[1]); // 0.8 String mapAsJson = '{"language":"dart"}'; // input Map of data Map parsedMap = JSON.parse(mapAsJson); print(parsedMap["language"]); // dart {% endhighlight %} JSON also works for more complex data structures, such as nested maps inside of lists. Use JSON.parse() to convert the HttpRequest's response from raw text to an actual Dart object: {% highlight dart %} onSuccess(HttpRequest req) { Map data = JSON.parse(req.responseText); // parse response text print(data["language"]); // dart print(data["targets"][0]); // dartium print(data["website"]["homepage"]); // www.dartlang.org } {% endhighlight %} Using simple Maps with strings as keys has some unfortunate side effects. Making a typo in any of the string names will return a null value which could then go on to cause a NullPointerException. Accessing the values from the map cannot be validated, before run-time. One of the benefits of using Dart is support for optional static types. Static types help you catch bugs early by allowing tools to detect type mismatches before you run your code, and to throw exceptions as soon as a runtime issue occurs. An additional benefit of using static types is that Dart Editor also uses this type information to provide auto-complete information&mdash;helpful when you are using a new library or data structure. Ideally, you want to access JSON data in a structured way, taking advantage of the tools to help you catch bugs early. The following example feels more like natural Dart code: {% highlight dart %} Language data = // ... initialize data ... // property access is validated by tools print(data.language); print(data.targets[0]); print(data.website.homepage); {% endhighlight %} Fortunately, the ability to write code using this “dot notation” is built into Dart, through its support of classes. The solution, then, is to combine the flexibility of a Map with the structure of a class. <h3 id="jsonobject">Introducing JsonObject</h3> This flexibility of JSON and Maps combined with the structure of classes is made possible with JsonObject, which is a third-party open source library. JsonObject uses JSON.parse() to extract the JSON data into a map, and then it uses the noSuchMethod feature of Dart classes to provide a way to access values in the parsed map by using dot notation. To learn more about JsonObject and download its code, go to the [project on GitHub](https://github.com/chrisbu/dartwatch-JsonObject). JsonObject uses Dart's noSuchMethod method support, which enables objects to intercept unknown method calls. For example, if you invoke a getter such as data.language, where data is a JsonObject, then behind the scenes `noSuchMethod("get:language", null)` is called. Likewise, when you try to set a value on a JsonObject, `noSuchMethod("set:language", ["Dart"])` is called. JsonObject intercepts the calls to noSuchMethod and accesses the underlying Map. Here is an example of using JsonObject instead of a raw Map: {% highlight dart %} onSuccess(HttpRequest req) { // decode the JSON response text using JsonObject var data = new JsonObject.fromJsonString(req.responseText); // dot notation property access print(data.language); // Get a simple value data.language = "Dart"; // Set a simple value print(data.targets[0]); // Get a value in a list print(data.website.homepage); // Get a value from a child object }; {% endhighlight %} You can also use this in your own classes. By extending JsonObject, and providing a suitable constructor, you can increase the readability of your code, and allow your classes to convert back and forth between a JSON string and JsonObjects internal map structure. {% highlight dart %} class Language extends JsonObject { Language.fromJsonString(jsonString) : super.fromJsonString(jsonString); } onSuccess(HttpRequest req) { // decode the JSON response text using JsonObject Language data = new Language.fromJsonString(req.responseText); // dot notation property access print(data.language); // Get a simple value data.language = "Dart"; // Set a simple value print(data.targets[0]); // Get a value in a list print(data.website.homepage); // Get a value from a child object }; {% endhighlight %} JsonObject also allows you to create new, empty objects, without first converting from a JSON string, by using the default constructor: {% highlight dart %} Language data = new JsonObject(); data.language = "Dart"; data.website = new JsonObject(); data.website.homepage = "http://www.dartlang.org"; {% endhighlight %} JsonObject also implements the Map interface, which means that you can use the standard map syntax: {% highlight dart %} Language data = new JsonObject(); data["language"] = "Dart"; // standard map syntax {% endhighlight %} Because JsonObject implements Map, you can pass a JsonObject into JSON.stringify(), which converts a Map into JSON for sending the data back to the server: {% highlight dart %} Language data = new JsonObject.fromJsonString(req.responseText); // later... // convert the JsonObject data back to a string String json = JSON.stringify(data); // and POST it back to the server HttpRequest req = new HttpRequest(); req.open("POST", url); req.send(json); {% endhighlight %} You can include JsonObject in your project by using the [pub](http://pub.dartlang.org) package manager. Simply specify the following dependency: {% highlight yaml %} dependencies: json_object: git: git://github.com/chrisbu/dartwatch-JsonObject.git {% endhighlight %} and import the package using the following import statement: {% highlight dart %} import "package:json_object/json_object.dart"; {% endhighlight %} <h3 id="note-on-jsonp">A note on JSONP and HttpRequest</h3> One caveat: Make sure your app is served from the same origin (domain name, port, and application layer protocol) as the web service you are trying to access with HttpRequest. Otherwise your app will hit the Access-Control-Allow-Origin restriction. This is a security restriction to prevent loading data from a different server than the one serving the client app. You can get around this restriction in a couple of ways. The first is to use an emerging technology known as [Cross-Origin Resource Sharing](https://developer.mozilla.org/en/http_access_control) (CORS), which is starting to become implemented by web servers. The second, older way is to use a workaround called JSONP, which makes use of JavaScript callbacks. The Dart - JavaScript interop libraries in the [js interop package](https://github.com/dart-lang/js-interop/) are suitable for JavaScript callbacks: {% highlight dart %} import 'dart:html'; import 'package:js/js.dart' as js; void main() { js.scoped(() { // create a top-level JavaScript function called myJsonpCallback js.context.myJsonpCallback = new js.Callback.once( (jsonData) { print(jsonData); // js.Proxy object containing the data // see js interop docs }); // add a script tag for the api required ScriptElement script = new Element.tag("script"); // add the callback function name to the URL script.src = "http://example.com/some/api?callback=myJsonpCallback"; document.body.elements.addLast(script); // add the script to the DOM }); } {% endhighlight %} For more detailed information about JS Interop, see the [js package docs](http://dart-lang.github.com/js-interop/docs/js.html). <h2 id="summary">Summary</h2> This article showed how a client-side Dart application communicates with a JSON-based web service via HTTP GET and POST. JSON data is parsed using the dart:json library, which converts JSON strings into maps and lists. Using JsonObject with the JSON data allows you to extend the functionality of the dart:json library by letting you use dot notation to access data fields. <h2 id="resources">Resources</h2> * [dart:json](http://api.dartlang.org/json/JSON.html) * [HttpRequest](http://api.dartlang.org/html/HttpRequest.html) * [JsonObject](https://github.com/chrisbu/dartwatch-JsonObject) * [Using JSONP with Dart](http://blog.sethladd.com/2012/03/jsonp-with-dart.html) * [About access-control restrictions](https://developer.mozilla.org/en/http_access_control) <h3 id="about-author">About the author</h3> <img src="chris-buckett.png" width="95" height="115" alt="<NAME> head shot" align="left" style="margin-right: 10px"> <NAME> is a Technical Manager for [Entity Group Ltd](http://www.entity.co.uk/), responsible for building and delivering enterprise client-server webapps, mostly with GWT, Java and .Net. He runs the [dartwatch.com blog](http://blog.dartwatch.com/), and is currently writing the book _Dart in Action_, which is available at [manning.com](http://www.manning.com/buckett). <file_sep>--- layout: default title: "dart2js: The Dart-to-JavaScript Compiler" description: "Use dart2js, the Dart to JavaScript compiler, to enable your Dart web apps to work on all modern browsers." has-permalinks: true --- # {{ page.title }} This page tells you how to use the _dart2js_ tool to compile Dart code to JavaScript. Dart Editor uses dart2js behind the scenes whenever [Dart Editor compiles to JavaScript](/docs/editor/#dart2js). The `bin/dart2js` executable is in the [Dart SDK](/docs/sdk/). You can either [download the SDK separately](/docs/sdk/#download) or get it as part of the [Dart Editor package](/docs/editor/#download). ## Basic usage Here's an example of compiling a Dart file to JavaScript: {% highlight bash %} $DART_SDK/bin/dart2js test.dart {% endhighlight %} This command produces a `.js` file that contains the JavaScript equivalent of your Dart code. ## Options Common command-line options for dart2js include: -o_&lt;file&gt;_ : Generate the output into _&lt;file&gt;_. -c : Insert runtime type checks and enable assertions (checked mode). -h : Display this message (add -v for information about all options). <file_sep>--- layout: default title: "Dart: Up and Running" description: "Excerpts from the O'Reilly book." --- # {{ page.title }} <a href="http://shop.oreilly.com/product/0636920025719.do"><img src="front_cover.png" alt="Dart: Up and Running, by <NAME> and <NAME>" width="190" height="250" align="right" /></a> _Dart: Up and Running_ is published by O'Reilly and reproduced on dartlang.org with permission. Its content is licensed under the [Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License](http://creativecommons.org/licenses/by-nc-nd/3.0/us/) (CC BY-NC-ND). You can download [code samples](https://github.com/dart-lang/dart-up-and-running-book/tree/master/code) and other book files from the [GitHub project](https://github.com/dart-lang/dart-up-and-running-book). For purchase information, see the [O'Reilly book page](http://shop.oreilly.com/product/0636920025719.do). To find other books, see [Books on Dart](/books/). #### Contents 1. [Foreword](pr01.html) 1. [Preface](pr02.html) 1. [Chapter 1. Quick Start](ch01.html) 1. [Chapter 2. A Tour of the Dart Language](ch02.html) 1. [Chapter 3. A Tour of the Dart Libraries](ch03.html) 1. [Chapter 4. Tools](ch04.html) 1. [Chapter 5. Walkthrough: Dart Chat](ch05.html) {:.toc} <file_sep> var blockNum = 0; function highlight(styleName) { if (blockNum > 0) { toggleHighlight(styleName + blockNum); } toggleHighlight(styleName + ++blockNum); } function toggleHighlight(className) { elements = document.getElementsByClassName(className); for (var i = 0; i < elements.length; ++i) { elements[i].classList.toggle("highlight"); } if (elements.length == 0) { blockNum = 0; // start over } } <file_sep>--- layout: default title: "Dart Puzzlers" description: "In which <NAME>, co-author of the original Java Puzzlers, walks through the puzzles with his Dart hat on." rel: author: joshua-bloch article: written_on: 2012-05-01 collection: language-details --- # {{ page.title }} In which <NAME>, co-author of the original Java Puzzlers, walks through the puzzles with his Dart hat on. <dl> <dt> <a href="chapter-1.html">Chapter 1: Expressive Puzzlers</a> </dt> <dd> Expression evaluation. </dd> <dt> <a href="chapter-2.html">Chapter 2: Puzzlers with Character</a> </dt> <dd> Strings, characters, and other textual data. </dd> </dl> <file_sep>--- layout: default title: "A Game of Darts&mdash;Tutorials" description: "A beginner's guide to building web apps with Dart." has-permalinks: true rel: author: - mary-campione tutorial: id: tut-home article: written_on: 2012-10-01 updated_on: 2012-11-01 collection: everyday-dart --- {% capture whats_the_point %} * This blue box shows page highlights. * Learn Dart here: No web experience required. * Dart is an open-source platform for building structured HTML5 web apps. {% endcapture %} {% capture content %} Welcome to your guide to building great web apps using Dart. <div id="under-construction" markdown="1"> <h3> <i class="icon-wrench"> </i> Under construction </h3> This is a draft. Your kindly worded <a href="http://code.google.com/p/dart/issues/entry?template=Tutorial%20feedback" target="_blank"> comments and suggestions </a> are appreciated. Thank you for your patience. </div> *A Game of Darts* is a collection of tutorials, _targets_, that teaches you how to build web programs using the Dart language, tools, and APIs. You can either follow the targets in order, building your knowledge of Dart and web programming from the ground up, or customize your learning experience by choosing just the targets you need. You should already know how to program in a structured language like C or Java. It helps to be familiar with object-oriented programming. You don't need to know JavaScript or the DOM (Document Object Model) to use these tutorials. The DOM is key to web programming and you will learn about it here, starting with the basic concepts in Target 2. <hr> <img src="/imgs/Dart_Logo_21.png" width="21" height="21" alt="Dart"> [ Target 1: Get Started](get-started/) : Download the Dart software bundle, discover which tools and libraries come with the Dart software, and use Dart Editor to run two apps. <hr> <img src="/imgs/Dart_Logo_21.png" width="21" height="21" alt="Dart"> [ Target 2: Connect Dart &amp; HTML](connect-dart-html/) : Use Dart Editor to create a stripped-down Dart program that simply puts text on a browser page. Though simple, this tiny program shows you how to host a Dart program on a web page and one way to manipulate the DOM. You will also begin learning about the Dart language, Dart Editor, HTML, and CSS. <hr> <img src="/imgs/Dart_Logo_21.png" width="21" height="21" alt="Dart"> [ Target 3: Add an Element to the DOM](add-elements/) : The small app in this target responds to a user-generated event by adding an Element to the DOM. <hr> <img src="/imgs/Dart_Logo_21.png" width="21" height="21" alt="Dart"> [ Target 4: Remove Elements from the DOM](remove-elements/) : In this target, you will modify the little todo app from Target 3 to remove elements from the DOM. <hr> <img src="new-icon.png" width="48" height="48"> [ Target 5: Install Shared Packages](packages/) : Packages help programmers to organize and share code. Many open-source Dart packages are hosted at the <a href="http://pub.dartlang.org/">pub.dartlang.org</a> repository. This target walks you through the steps to install one of those packages. <div> <hr> <div class="row"> <div class="span1"> <font size="24"> <i class="icon-bullhorn"> </i> </font> </div> <div class="span8"> ...more targets coming... </div> </div> <hr> </div> <div class="row"> <div class="span3"> <p style="font-size:xx-small">Version: 30 Nov 2012</p> </div> <div class="span3"> <a href="http://code.google.com/p/dart/issues/entry?template=Tutorial%20feedback" target="_blank"> <i class="icon-comment"> </i> Send feedback </a> </div> <div class="span3"> <a href="/docs/tutorials/get-started/" class="pull-right">Get Started <i class="icon-chevron-right"> </i></a> </div> </div> {% endcapture %} {% include tutorial.html %} <file_sep>$(document).ready(function() { var addPermalink = function() { $(this).addClass('has-permalink'); $(this).append($('<a class="permalink" title="Permalink" href="#' + $(this).attr('id') + '">#</a>')); }; $.each(['h2','h3','h4'], function(n, h) { $('.has-permalinks ' + h).each(addPermalink); }); });
0484edbd7812504a43990bb66dc235fadb1c1b09
[ "Markdown", "JavaScript" ]
7
Markdown
Macb3th/dartlang.org
a954b4d6b28057a059b4e461a9fc6e18e8cb4e1a
571f4bdeacc6c79f8d6a72a77ced1a355251b342
refs/heads/master
<repo_name>chrisdepas/dotfiles<file_sep>/dotfiles/usr/share/i3blocks/clementineNowPlaying.py #!/usr/bin/env python3.6 # -*- coding: UTF-8 -*- """ clementineNowPlaying.py ======================= Version: 1.0.0 Author: <NAME> Creation Date: 2018-01-28 License: None Description ----------- Retrieves the current song in Clementine. """ import json import sys from pydbus import SessionBus # Configuration MaxCharacters = 48 ScrollFactor = 3 def main(**args): # Get mpris2 bus = SessionBus() mpris = bus.get("org.mpris.MediaPlayer2.clementine", "/org/mpris/MediaPlayer2") if mpris is None or mpris.Metadata is None: sys.exit(1) # Get metadata md = mpris.Metadata status = mpris.PlaybackStatus.strip().lower() if status is None or mpris.Position is None: sys.exit(0) # Parse metadata statusIcons = {'paused': u'\uf04c', 'playing': u'\uf04b', 'stopped': u'\uf04d'} status = statusIcons[status] if status in statusIcons else '?' artist = md.get("xesam:artist") album = md.get("xesam:album") track = md.get("xesam:title") bitrate = md.get("bitrate") if artist is None: artist = "Unknown Artist" elif isinstance(artist, list) and len(artist) > 0: artist = artist[0] album = album if album is not None else "Unknown Album" track = track if track is not None else "Unknown Track" # Build result string icons = "\uf025 {Status} ".format(Status=status) result = "{Artist} - {Album} - {Track}".format(Artist=artist, Album=album, Track=track, BitRate=bitrate) if bitrate is not None: result = "{Result} @ {Bitrate} kbps".format(Result=result, Bitrate=bitrate) # Apply scroll effect based on the time and print result posSeconds = (float(pos) / 1000000.0) strPos = int(posSeconds * ScrollFactor) % len(result) result = result[strPos:] + " " + result[0:strPos] print(icons + result[:MaxCharacters]) return 0 # Allow import without running script if __name__ == '__main__': sys.exit(main(sys.argv)) <file_sep>/dotfiles/home/michael/.local/bin/taskwarrior-productivity #!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ taskwarrior-productivity ======================== Version: 1.0.0 Author: <NAME> Creation Date: 2018-01-04 License: None Description ----------- Saves an active task and the time it was added. Arguments --------- active-name Get the name of the currently active task. active-update <id> <task-data> Add a new active taskwarrior task. active-delete <id> Delete a task that is no longer active. """ import datetime import fcntl import json import math import os import sys import traceback from functools import singledispatch # Configuration STATE_FILE_PATH = '~/.taskwarrior-productivity.state' # JSON default serialise function @singledispatch def toSerialisable(obj): """ Serialises an object based on type. """ return str(obj) # Type overloads @toSerialisable.register(datetime.datetime) def toSerialisableDatetime(obj): return obj.timestamp() class ActiveTask: """ A generic interface for an active task. """ def __init__(self, data, whenAdded): # A dictionary containing the format-specific task data self.data = data # The format of task, only 'Taskwarrior' is currently valid self.taskFormat = None # when the task became active / was added self.whenAdded = whenAdded # JSON serialise/deserialise interface methods def serialiseJSON(self): """ Returns a string representation of a dictionary of variable names and their values. """ return serialiseJSON(self.__dict__) @staticmethod def fromState(stateDict): """ Returns None if stateDict is invalid, or an ActiveTask created from stateDict. """ if stateDict is None: return None # Validate dictionary if not ('data' in stateDict and 'taskFormat' in stateDict and 'whenAdded' in stateDict): sys.stderr.write("stateDict: ActiveTask dict is not valid.\n") return None # Build class / subclass whenAdded = stateDict.get('whenAdded') if whenAdded is not None: whenAdded = datetime.datetime.fromtimestamp(whenAdded) inst = ActiveTask(stateDict.get('data'), whenAdded) inst.taskFormat = stateDict.get('taskFormat') if inst.taskFormat == 'Taskwarrior': return ActiveTaskwarriorTask(inst.data, inst.whenAdded) return inst # ActiveTask interface methods def isValid(self): """ Determines if this task is valid. """ raise NotImplementedError def getID(self): """ Returns an identifier unique to the taskFormat. """ raise NotImplementedError def getDescription(self): """ Returns a name or description of the task. """ raise NotImplementedError @toSerialisable.register(ActiveTask) def toSerialisableActiveTask(obj): return obj.__dict__ class ActiveTaskwarriorTask(ActiveTask): """ Represents an active taskwarrior task. """ def __init__(self, data, whenAdded=None): """ Create an ActiveTaskwarriorTask from a dictionary. """ self.data = data self.taskFormat = 'Taskwarrior' if whenAdded is not None: self.whenAdded = whenAdded def getRequiredVars(self): """ Returns a list of required member taskwarrior variables. """ return ['status', 'uuid', 'entry', 'description'] # ActiveTask interface methods def isValid(self): """ Returns True if this is a valid Taskwarrior task, False otherwise. This isn't completely accurate, depending on the status value there are other attributes that are required. Assumes that the ActiveTask member variables are valid. """ taskVars = list(self.data.keys()) return any([v not in taskVars for v in self.getRequiredVars()]) def getID(self): """ Returns a unique ID for this task. """ id = self.data.get('id') if id is not None: return id return self.data['uuid'] def getDescription(self): return self.data['description'] class ActiveTaskManager: def __init__(self, statePath=None): # The current active task, represented using an ActiveTask self.__activeTask = None # If we should save state self.__stateChange = False # Load the current state, if a state file was provided. if statePath is not None: self.__loadState(statePath) def __loadState(self, statePath): """ Load the current state from the given state file. If unsuccessful, the ActiveTaskManager will be in the default state. """ stateDict = {} stateData = None try: with open(statePath, 'r') as stateFile: fcntl.flock(stateFile.fileno(), fcntl.LOCK_EX) stateData = stateFile.read() fcntl.flock(stateFile.fileno(), fcntl.LOCK_UN) except FileNotFoundError as e: return try: stateDict = json.loads(stateData) except Exception as e: traceback.print_exc(file=sys.stderr) return # Validate classVars = list(self.__dict__.keys()) for v in classVars: if v not in stateDict: print("stateDict invalid (no {0})".format(v), file=sys.stderr) return # Parse classes and other toSerialisable() types here if v == '_ActiveTaskManager__activeTask': stateDict[v] = ActiveTask.fromState(stateDict[v]) self.__dict__[v] = stateDict[v] self.__stateChange = False def __saveState(self, statePath): """ Saves the current state to the given state file. """ # Open file and block until exclusive lock is obtained with open(statePath, 'w') as stateFile: fcntl.flock(stateFile.fileno(), fcntl.LOCK_EX) # Dump class dictionary to state file try: strData = json.dumps(self.__dict__, default=toSerialisable) stateFile.write(strData) except Exception as e: traceback.print_exc(file=sys.stderr) stateFile.close() # Release lock fcntl.flock(stateFile.fileno(), fcntl.LOCK_UN) def __updateActive(self, taskData): """ Updates or adds a new active task with the associated data. Assumes the task is a Taskwarrior task. """ try: taskDict = json.loads(taskData) except json.decoder.JSONDecodeError as e: traceback.print_exc(file=sys.stderr) sys.exit(2) self.__activeTask = ActiveTaskwarriorTask(taskDict, datetime.datetime.now()) self.__stateChange = True return 0 def __deleteActive(self, taskID=None): """ Deletes the given task, if it exists. """ if self.__activeTask is None: return 0 if taskID is None or self.__activeTask.getID() == taskID: self.__activeTask = None self.__stateChange = True return 0 def __activeTaskTime(self): """ Prints the minutes since the active task was added. """ if self.__activeTask is None: return 0 addedTime = self.__activeTask.whenAdded activeTime = datetime.datetime.now() - addedTime activeTimeMin = max(math.floor(activeTime.seconds / 60.0), 0) print(activeTimeMin) return 0 def command(self, *commandArgs): """ Parses the string arguments for each command and then runs it. Returns False if unsuccessful. Exits early with an error code if and error occurs. """ if len(commandArgs) == 0: print("Arguments required.\n\nCommands:") print(" active-name") print(" Prints the currently active task's name or " "description.\n") print(" active-update task-data") print(" Sets the given task as active and records the time.\n") print(" active-delete [task-uuid]") print(" Deletes the currently active task. Can check uuid.\n") print(" active-time") print(" Prints the currently active task's active time, in " "mins\n") sys.exit(0) commandName = commandArgs[0] commandArgs = commandArgs[1:] # TODO: Create command class and register commands by name # taskwarrior-productivity active-name if commandName == 'active-name': if self.__activeTask is not None: print(self.__activeTask.getDescription()) return 0 # taskwarrior-productivity active-time if commandName == 'active-time': return self.__activeTaskTime() # taskwarrior-productivity active-update task-data if commandName == 'active-update': if len(commandArgs) < 1: print( 'Error: too few arguments for {0}'.format(commandName), file=sys.stderr) sys.exit(1) self.__stateChange = True return self.__updateActive(commandArgs[0]) # taskwarrior-productivity active-delete [task-uuid] if commandName == 'active-delete': if len(commandArgs) > 0: return self.__deleteActive(commandArgs[0]) return self.__deleteActive() def saveState(self, statePath): """ Saves state if necessary. """ if not self.__stateChange: return self.__saveState(statePath) # Execute script if not imported if __name__ == '__main__': statePath = os.path.expanduser(STATE_FILE_PATH) assert statePath != STATE_FILE_PATH # Run command & save state activeTaskManager = ActiveTaskManager(statePath) activeTaskManager.command(*sys.argv[1:]) activeTaskManager.saveState(statePath) sys.exit(0) <file_sep>/dotfiles/usr/share/i3blocks/taskwarrior-statusbar-notify.sh #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # taskwarrior-activetime-notify.sh # ================================ # # Version: 1.0.0 # Author: <NAME> # Creation Date: 2018-01-09 # License: None # # Description # ----------- # Prints the time and sends a notification if it is within a range. # ############################################################################### Notifications=$1 activeMins=$(taskwarrior-productivity active-time) # Get icon if [[ -z $activeMins ]]; then echo '' exit 0 fi icon='' if (( $activeMins < 20 )); then icon='' elif (( $activeMins < 30 )); then icon='' elif (( $activeMins < 40 )); then icon='' elif (( $activeMins < 50 )); then icon='' elif (( $activeMins > 49 )); then icon='' fi # Notifications if [[ "$Notifications" == "Y" ]]; then if [[ "$activeMins" == "25" ]]; then notify2wrapper.py 'Task Information' '25 minutes remaining.' \ '/home/michael/.local/share/icons/Paper Icons/Paper/512x512/actions/' play '/home/michael/.local/share/sounds/Notifications/droplet.mp3' elif [[ "$activeMins" == "40" ]]; then notify2wrapper.py 'Task Information' '10 minutes remaining.' \ '/home/michael/.local/share/icons/Paper Icons/Paper/512x512/status/appointment-soon.png' play '/home/michael/.local/share/sounds/Notifications/break-forth.mp3' elif [[ "$activeMins" == "50" ]]; then notify2wrapper.py 'Task Information' '0 minutes remaining. ' \ '/home/michael/.local/share/icons/Paper Icons/Paper/512x512/status/appointment-missed.png' play '/home/michael/.local/share/sounds/Notifications/oringz-w439.mp3' elif [[ "$activeMins" == "55" ]]; then notify2wrapper.py 'Task Information' '5 minutes over task time.' \ '/home/michael/.local/share/icons/Paper Icons/Paper/512x512/status/appointment-missed.png' play '/home/michael/.local/share/sounds/Notifications/oringz-w447.mp3' elif [[ "$activeMins" == "60" ]]; then notify2wrapper.py 'Task Information' '10 minutes over task time.' \ '/home/michael/.local/share/icons/Paper Icons/Paper/512x512/status/appointment-missed.png' play '/home/michael/.local/share/sounds/Notifications/engaged.mp3' elif [[ "$activeMins" == "65" ]]; then notify2wrapper.py 'Task Information' '15 minutes over time.' \ '/home/michael/.local/share/icons/Paper Icons/Paper/512x512/status/appointment-missed.png' play '/home/michael/.local/share/sounds/Notifications/office-1.mp3' lock & fi fi # Format time if (( $activeMins > 59 )); then printf $icon "%+2s" "$(echo $(( $activeMins / 60 ))h $(( $activeMins % 60 )))m" else printf $icon "%+2s" "${activeMins}m" fi exit 0 <file_sep>/dotfiles/home/michael/.config/i3/i3LockScript.sh #!/bin/bash lockimg='/home/michael/Pictures/Wallpapers/orangemountain2560x1600.png' # Time & Date timepos='x+0.5*w-0.5*cw:y+0.5*h-0.5*ch' timecolor='#FFFFFFCC' timesize=48 datecolor='#FFFFFFCC' datesize=24 tdopts="--timepos='$timepos' --timecolor='$timecolor' --timesize=$timesize --datecolor='$datecolor' --datesize='$datesize'" # Status Indicator - Inside, Status Text veriftext='' wrongtext='' radius=60 indpos="x+1.8*r:y+h-1.8*r" insidevercolor='#FFFFFF88' insidewrongcolor='#FF111188' insidecolor='#00000000' siopts="--indicator --radius=$radius --indpos='$indpos' --veriftext='$veriftext' --wrongtext='$wrongtext' --insidevercolor='$insidevercolor' --insidewrongcolor='$insidewrongcolor' --insidecolor='$insidecolor'" # Status Indicator - Ring ringcolor='#FFFFFFCC' ringvercolor='#FFFFFFCC' ringwrongcolor='#FFFFFFCC' linecolor='#00000000' separatorcolor='#00000000' keyhlcolor='#11FF11CC' bshlcolor='#FF1111CC' siropts="--ringvercolor='$ringvercolor' --ringwrongcolor='$ringwrongcolor' --ringcolor='$ringcolor' --linecolor='$linecolor' --separatorcolor='$separatorcolor' --keyhlcolor='$keyhlcolor' --bshlcolor='$bshlcolor'" #eval $lockCmd echo $lockCmd <file_sep>/dotfiles/home/michael/.mozilla/firefox/profiles.ini [General] StartWithLastProfile=1 [Profile0] Name=Michael IsRelative=0 Path=/home/michael/.config/firefox/qzv15m25.Michael Default=1 <file_sep>/dotfiles/home/michael/.task/hooks/on-modify.taskwarrior-active-task #!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ on-modify.taskwarrior-active-task ================================= Version: 1.0.0 Author: <NAME> Creation Date: 2018-01-03 License: None Description ----------- Simple hook script that updates taskwarriorGetActive.py when the active task in taskwarrior changes. Usage ----- 1. Put this in your .task/hooks/ folder. Configure the path to taskwarriorGetActive.py or add it to .profile. """ import json import subprocess import sys import notify2wrapper def main(): # read on-modify data old = json.loads(sys.stdin.readline()) newStr = sys.stdin.readline() new = json.loads(newStr) notifier = notify2wrapper.Notifier() # Task complete if new['status'] == 'completed' and old['status'] != 'completed': notifier.notify( 'Taskwarrior', 'Task \'{0}\' completed.'.format(new.get('description')), ('/home/michael/.local/share/icons/papirus-icon-theme/Papirus/' '48x48/apps/com.github.lainsce.yishu.svg'), 3500 ) subprocess.run( ('play -q /home/michael/.local/share/sounds/Notifications/' 'oringz-w423.mp3'), shell=True, stdout=subprocess.DEVNULL ) print(newStr) return 0 # Task stop if 'start' not in new and 'start' in old: subprocess.run("taskwarrior-productivity active-delete", shell=True) notifier.notify( 'Taskwarrior', 'Task \'{0}\' stopped.'.format(new.get('description')), ('/home/michael/.local/share/icons/Paper Icons/Paper/512x512/' 'status/view-pim-tasks-pending.png') ) subprocess.run( ('play -q /home/michael/.local/share/sounds/Notifications/' 'engaged.mp3'), shell=True, stdout=subprocess.DEVNULL ) print(newStr) return 0 # Task start if 'start' in new and 'start' not in old: subprocess.run( "taskwarrior-productivity active-update '{0}'".format(newStr), shell=True ) notifier.notify( 'Taskwarrior', 'Task \'{0}\' started.'.format(new.get('description')), ('/home/michael/.local/share/icons/Paper Icons/Paper/512x512' '/status/view-pim-tasks-pending.png') ) subprocess.run( ('play -q /home/michael/.local/share/sounds/Notifications' '/break-forth.mp3'), shell=True, stdout=subprocess.DEVNULL ) print(newStr) return 0 print(newStr) return 0 if __name__ == '__main__': sys.exit(main()) <file_sep>/dotfiles/usr/share/i3blocks/cmus #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # cmus # ==== # # Author: Anachron # License: GPL-3.0 # # Description # ----------- # Outputs the title of the currently playing song and a status icon. # # Source # ------ # https://github.com/Anachron/i3blocks/blob/master/blocks/cmus # ############################################################################### # Get info and parse INFO_CMUS=$(cmus-remote -Q 2>/dev/null) if [[ $? -eq 0 ]]; then INFO_STATUS=$(echo "${INFO_CMUS}" | sed -n -e 's/^.*status\s*//p' | head -n 1) INFO_TITLE=$(echo "${INFO_CMUS}" | sed -n -e 's/^.*title\s*//p' | head -n 1) INFO_FILE=$(echo "${INFO_CMUS}" | sed -n -e 's/^.*file.*\///p' | head -n 1) else exit fi # Output icon (ICON) if [[ $1 == "ICON" ]]; then if echo $INFO_STATUS | grep -P '[Pp]laying' > /dev/null; then printf '' && exit 0; fi if echo $INFO_STATUS | grep -P '[Pp]aused'> /dev/null; then printf '' && exit 0; fi if echo $INFO_STATUS | grep -P '[Ss]topped'> /dev/null; then printf '' && exit 0; fi fi # Title only if [ -z "$INFO_TITLE" ]; then echo $INFO_FILE && exit 0; fi echo "${INFO_TITLE}" exit 0 <file_sep>/enable_services.sh #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # enable_services.sh # ================== # # Author: <NAME> # Creation Date: 2018-01-27 # License: None # # Description # ----------- # Enables the systemd services. # ############################################################################### echo 'Enabling user services...' systemctl --user enable psd.service echo 'Enabling system services...' sudo systemctl enable fstrim.timer exit 0 <file_sep>/sanitise.sh #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # sanitise.sh # =========== # # Author: <NAME> # Creation Date: 2018-01-28 # Modification Date: 2018-06-06 # License: MIT # # Description # ----------- # Removes sensitive information from firefox preferences. # ############################################################################### # Single-key y/n prompt function confirm { read -sn 1 -p "$* [Y/N]? " [[ ${REPLY:0:1} == [Yy] ]] && printf '\n' } # Sanitise a file function sanitise { local FILEPATH=$1 local EXPRS=$2 # Check that file actually exists if [ ! -e $FILEPATH ]; then echo "Skipping nonexistent file $FILEPATH" return 1 fi # Build sed expressions for preview and edit SHOWMATCHES='' DELETEMATCHES='' for p in $(echo "$EXPRS"); do SHOWMATCHES+="s/.*$p.*/DELETE:&/g; " DELETEMATCHES+="/.*$p.*/d; " done # Print edit preview printf "\n$FILEPATH\nEdit Preview\n%s\n" \ "===================================================================" cat "$FILEPATH" | sed -E "$SHOWMATCHES" | sed 's/DELETE:DELETE://g' \ | grep --color -E '^DELETE:|$' printf "%s\n" \ "===================================================================" # prompt user to delete matches if confirm 'Delete matches?'; then sed -E "$DELETEMATCHES" -i "$FILEPATH" echo 'Done.' else echo "Skipped '$FILEPATH'" fi return 0 } # cd into script dir cd $(dirname "$(readlink -f "$0")") # Configuration USERNAME='michael' FIREFOXPREFS='dotfiles/home/michael/.config/firefox/qzv15m25.Michael/prefs.js' FIREFOXPREFS2='dotfiles/home/michael/.config/firefox/qzv15m25.Michael/user.js' FIREFOXEXPR=$(printf '\.(\w+[-_]?)+([Tt]ime|Date) ' && \ printf '\.last-time-of-changing ' && \ printf '\..*([Bb]uild|[Dd]evice)[Ii][Dd] ' && \ printf '\.most[Rr]ecent[Dd]ate ' && \ printf '\.[Ss]essions\. ' && \ printf '\.([Dd]river|[Aa]pp)?[Vv]ersion ' && \ printf '\.last([Uu]pdate|[Vv]ersion) ' && \ printf '\.[Uu]ser[Aa]gent[Ii][Dd] ' && \ printf '\.lastDaily[[:alpha:]] ' && \ printf '\.last[Ss]uggestions[Pp]rompt[Dd]ate ' && \ printf '\.mostRecentDateSetAsDefault ' && \ printf '\.last_update_(seconds|time) ' && \ printf '\.blocklist\.last_etag ' && \ printf 'noscript\.[[:alpha:]] ' && \ printf 'network\.proxy\. ' && \ printf 'media\.gmp- ' && \ printf 'print_printer ' && \ printf '\.database\.lastMaintenance ' && \ printf '\.cohortSample ' && \ printf '\.last\.places\.sqlite ' && \ printf '\.startup\.last_success ' && \ printf '\.blocklist\.[[:alpha:]]+\.checked ' && \ printf '\..*([Cc]lient[Ii][Dd]|[Bb]uild[Ii][Dd])' ) sanitise "$FIREFOXPREFS" "$FIREFOXEXPR" sanitise "$FIREFOXPREFS2" "$FIREFOXEXPR" exit 0 <file_sep>/dotfiles/home/michael/.config/conky/taskwarrior_status_conky.sh #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # taskwarrior_status_conky.sh # =========================== # # Version: 1.0.0 # Author: <NAME> # Creation Date: 2018-01-17 # License: None # # Description # ----------- # Prints the active task and time since start. # ############################################################################### activeMins=$(taskwarrior-productivity active-time | tr -d '\n') # Icons if [[ -z $activeMins ]]; then printf '' exit 0 fi icon='' if (( $activeMins < 20 )); then icon='' elif (( $activeMins < 30 )); then icon='' elif (( $activeMins < 40 )); then icon='' elif (( $activeMins < 50 )); then icon='' elif (( $activeMins > 49 )); then icon='' fi if (( $activeMins > 59 )); then out="$icon  $(( $activeMins / 60 )):$(( $activeMins % 60))" else out="$icon  ${activeMins}" fi printf "%s %s" " $(taskwarrior-productivity active-name | tr -d '\n')" $out exit 0 <file_sep>/dotfiles/home/michael/.local/bin/input-type #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # input-type # ========== # # Description: Emulates typing in text for the given type. # Author: <NAME> <shaggyrogers> # Creation Date: 2018-03-07 # Modification Date: 2018-03-18 # License: MIT # ############################################################################### [ -z "$1" ] && WIN="$(xdotool getactivewindow)" case "$1" in 'c') INPUT="$(gpick --pick --single --output --no-newline)" ;; 'f') INPUT="$(zenity --file-selection)" ;; 's') INPUT="$(xsel)" ;; 'p') keepass2 --auto-type exit 0 ;; *) echo 'Error: Invalid type, accepted values include:' 1>&2 echo ' c Color on desktop' 1>&2 echo ' f File path' 1>&2 echo ' s X11 selection' 1>&2 echo ' p keepass2 password' 1>&2 exit 1 ;; esac xdotool type --window "$WIN" --delay 1 --clearmodifiers "$INPUT" exit 0 # vim: set ts=4 sw=4 tw=79 fdm=marker et : <file_sep>/dotfiles/usr/share/i3blocks/localTime.py #!/usr/bin/env python3.6 # -*- coding: UTF-8 -*- """ localTime.py ============ Version: 1.0.0 Author: <NAME> Creation Date: 2017-11-27 Description ----------- Displays the current time in the i3 status bar, with icons from Weather Icons (http://erikflowers.github.io/weather-icons/) """ import datetime import sys # Formats the given date. def formatDate(weekday, day, month, year): weekdays = {0: 'Mon', 1: 'Tue', 2: 'Wed', 3: 'Thu', 4: 'Fri', 5: 'Sat', 6: 'Sun'} weekday = str(weekdays.get(weekday)) dateIcon = u'<span font_desc="FontAwesome">\uf073</span>' year = str(year) if len(year) == 4: year = year[2:] return '{Icon} {Weekday} {Day}-{Month}-{Year}'.format(Icon=dateIcon, Weekday=weekday, Day=day, Month=month, Year=year) # Formats the given time. def formatTime(hours, minutes): hourIcons = {0: u'\uf089', 1: u'\uf08a', 2: u'\uf08b', 3: u'\uf08c', 4: u'\uf08d', 5: u'\uf08e', 6: u'\uf08f', 7: u'\uf090', 8: u'\uf091', 9: u'\uf092', 10: u'\uf093', 11: u'\uf094'} icon = hourIcons.get(hours % 12) if icon is None: icon = hourIcons[0] return (f'<span font_desc='Weather Icons'>{icon}</span>' f'{hours:02d}:{mins:02d}') def main(**args): today = datetime.datetime.today() date = formatDate(today.weekday(), today.day, today.month, today.year) time = formatTime(today.hour, today.minute) print("{Date} {Time}".format(Date=date, Time=time)) return 0 # Allow importing without running script if __name__ == '__main__': sys.exit(main(sys.argv)) <file_sep>/dotfiles/usr/share/i3blocks/apt_upgrades.sh #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # apt_upgrades.sh # =============== # # Version: 1.0.0 # Author: <NAME> # Creation Date: 2017-11-06 # License: None # # Description # ----------- # Prints the number of apt package upgrades. Returns 1 if there are none. # ############################################################################### # Simulate apt-get upgrade and get the number of upgrades updates=$(apt-get -q --simulate -u upgrade --assume-no | \ grep -Poe '[0-9]{1,5} to upgrade' | \ grep -Poe '[0-9]+') # Hide when there are no updates if [ "$updates" == "0" ]; then exit 1 fi echo -n $updates exit 0 <file_sep>/dotfiles/home/michael/.config/i3/config #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # config # ====== # Description: i3-gaps configuration file # Author: <NAME> <shaggyrogers> # Creation Date: 2017-11-01 # Modification Date: 2018-03-03 # License: MIT ############################################################################### # Options{{{ # Key configuration{{{ # Super_L / Alt_L / Shift / Control_L set $down j set $down2 Down set $left h set $left2 Left set $mod1 Mod4 set $mod2 Mod1 set $mod3 Shift set $mod4 'control' set $right l set $right2 Right set $up k set $up2 Up # }}} # Applications{{{ # Per-application window settings{{{ for_window [class="conky_time"] floating enable for_window [class="conky_time"] sticky enable for_window [class="conky_task"] floating enable for_window [class="conky_task"] sticky enable for_window [class="KeePass2"] floating enable for_window [class="KeePass2"] sticky enable for_window [class="KeePass2"] resize set 1024 640 for_window [class="KeePass2"] move absolute position 16 16 for_window [class="KeePass2"] move to scratchpad for_window [class="GParted"] floating enable for_window [class="GParted"] resize set 1024 640 for_window [class="GParted"] move absolute position 1048 16 for_window [class="Seahorse"] floating enable for_window [class="Seahorse"] resize set 1024 640 for_window [class="Seahorse"] move absolute position 16 664 for_window [class="kittydropdownterm"] floating enable for_window [class="kittydropdownterm"] resize set 2544 480 for_window [class="kittydropdownterm"] move position 8 -6 # }}} # Media player commands{{{ # Clementine{{{ set $clementinePlay "qdbus org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 PlayPause" set $clementinePause "qdbus org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 PlayPause" set $clementineNext "qdbus org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 Next" set $clementinePrev "qdbus org.mpris.MediaPlayer2.clementine /org/mpris/MediaPlayer2 Previous" # }}} # cmus{{{ set $cmusPlay "$HOME/.config/cmus/cmus-playpause-launch.sh" set $cmusPause "$HOME/.config/cmus/cmus-playpause-launch.sh" set $cmusNext "cmus-remote --next" set $cmusPrev "cmus-remote --prev" # }}} # }}} # }}} # Workspaces{{{ set $ws01 "1:work" set $ws02 "2:proj1" set $ws03 "3:proj2" set $ws04 "4:misc1" set $ws05 "5:misc2" set $ws06 "6:social" set $ws07 "7:todo" set $ws08 "8:media" set $ws09 "9:sysmon" set $ws10 "10:sysconf" set $ws11 "11:srvmon" set $ws12 "12:misc3" set $ws13 "13:misc4" set $ws14 "14:misc5" set $ws15 "15:misc6" set $ws16 "16:misc7" set $ws17 "17:misc8" set $ws18 "18:btc" set $ws19 "19:tor" set $ws20 "20:tails" assign [class="google-chrome"] $ws06 assign [title="Taskwarrior"] $ws07 assign [class="cmusmusicplayer"] $ws08 # }}} # Appearance{{{ # General{{{ default_orientation auto font pango:Arimo Nerd Font Bold 12 hide_edge_borders both new_window pixel 6 workspace_layout default # }}} # Status bar{{{ set $bar_background #00000000 set $bar_separator #00000000 set $bar_statusline #4B5262 set $bar_font pango:Arimo Nerd Font, Weather Icons set $bar_separator_symbol " " # }}} # Workspace indicator{{{ set $focused_workspace_bg #84AACD set $focused_workspace_border #84AACD set $focused_workspace_text #454C5B set $inactive_workspace_bg #00405C set $inactive_workspace_border #00405C set $inactive_workspace_text l454C5B set $unfocused_workspace_bg #00405C set $unfocused_workspace_border #00405C set $urgent_workspace_bg #00585C set $urgent_workspace_border #005F88 set $urgent_workspace_text #005F88 # }}} # Windows{{{ set $focused_window_bg #E1E8F0 set $focused_window_border #E1E8F0 set $focused_window_text #005F88 set $inactive_window_bg #5F88B1 set $inactive_window_border #005F88 set $inactive_window_text #E1E8F0 set $unfocused_window_bg #005F88 set $unfocused_window_border #005F88 set $unfocused_window_text #AFCCDD set $urgent_window_bg #eb709b set $urgent_window_border #5B97CF set $urgent_window_text #FAFBFC # }}} # Configure windows{{{ client.focused $focused_window_border $focused_window_bg $focused_window_text client.focused_inactive $inactive_window_border $inactive_window_bg $inactive_window_text client.unfocused $unfocused_window_border $unfocused_window_bg $unfocused_window_text client.urgent $urgent_window_border $urgent_window_bg $urgent_window_text # }}} # Configure Status bar{{{ bar { font $bar_font i3bar_command i3bar -t mode hide position bottom separator_symbol $bar_separator_symbol status_command i3blocks -c ~/.config/i3/i3blocks.conf strip_workspace_numbers yes colors { background $bar_background separator $bar_separator statusline $bar_statusline active_workspace $focused_workspace_border $focused_workspace_bg $focused_workspace_text focused_workspace $focused_workspace_border $focused_workspace_bg $focused_workspace_text inactive_workspace $inactive_workspace_border $inactive_workspace_bg $inactive_workspace_text urgent_workspace $urgent_workspace_border $urgent_workspace_bg $urgent_workspace_text } } # }}} # }}} # Misc{{{ workspace_auto_back_and_forth yes focus_follows_mouse no floating_modifier $mod1 gaps inner 12 gaps outer 4 # }}} # }}} # Shortcuts{{{ # Application shortcuts{{{ #bindsym --release $mod1+$mod2+Return exec kitty bindsym --release $mod1+$mod2+Return exec ~/.local/bin/kitty bindsym --release $mod1+$mod2+$mod3+Return exec gnome-terminal bindsym --release $mod1+$mod3+Return exec ~/.local/bin/kitty \ --class=kittydropdownterm bindsym --release $mod1+$mod2+b exec ~/.local/bin/kitty --class=ranger \ 'ranger' bindsym --release $mod1+$mod3+b exec nemo bindsym --release $mod1+$mod2+c exec rofi -modi calc:wcalc -show \ calc:wcalc bindsym --release $mod1+$mod3+c exec gnome-calculator bindsym --release $mod1+$mod2+e exec kitty-nvim -i 0 bindsym --release $mod1+$mod3+e exec kitty-nvim -i 1 bindsym --release $mod1+$mod2+i exec firefox bindsym --release $mod1+$mod3+i exec google-chrome bindsym --release $mod1+$mod2+p [class=KeePass2] scratchpad show bindsym --release $mod1+$mod3+p exec ~/.local/bin/kitty --class=aptitude \ --override background_opacity=1.0 'aptitude' bindsym --release $mod1+$mod2+q exec xkill bindsym --release $mod1+$mod2+w exec ~/.local/bin/i3-switch-workspace bindsym --release $mod1+Escape exec beep bindsym --release $mod1+d exec rofi -show run -modi run bindsym --release $mod1+q kill bindsym --release $mod1+Print exec gnome-screenshot bindsym --release $mod1+$mod2+Print exec sh -c "gnome-screenshot -a" bindsym --release $mod1+$mod3+Print exec sh -c "gnome-screenshot -a" # }}} # Insert text {{{ bindsym --release $mod1+$mod2+$mod3+c exec input-type c bindsym --release $mod1+$mod2+$mod3+f exec input-type f bindsym --release $mod1+$mod2+$mod3+p exec input-type p bindsym --release $mod1+$mod2+$mod3+s exec input-type s # }}} # Container layout{{{ # Mod1 + s / w / e : Change layout to stacked/tabbed/split){{{ bindsym $mod1+s layout stacking bindsym $mod1+w layout tabbed bindsym $mod1+e layout toggle split # }}} # Mod1 + v / Mod1 + Mod2 + h : Split container vertically/horizontally{{{ bindsym $mod1+v split v bindsym $mod1+$mod2+v split h # }}} # Mod1 + f : Toggle fullscreen for focused container{{{ bindsym $mod1+f fullscreen toggle # }}} # Mod1 + Mod2 + Space : Toggle floating for focused container{{{ bindsym $mod1+$mod2+space floating toggle # }}} # Mod1 + Space : Switch between floating and tiling window focus{{{ bindsym $mod1+space focus mode_toggle # }}} # }}} # Misc{{{ # Mod1 + R : Reload configuration file/restart i3 in-place{{{ bindsym $mod1+r reload bindsym $mod1+$mod2+r restart # }}} #bindsym $mod1+$mod2+e exec "i3-nagbar -t warning -m 'You pressed the exit shortcut. Do you really want to exit i3? This will end your X session.' -b 'Yes, exit i3' 'i3-msg exit'" # Volume controls{{{ bindsym XF86AudioRaiseVolume exec --no-startup-id pactl set-sink-volume @DEFAULT_SINK@ +5% bindsym XF86AudioLowerVolume exec --no-startup-id pactl set-sink-volume @DEFAULT_SINK@ -5% bindsym XF86AudioMute exec --no-startup-id pactl set-sink-mute @DEFAULT_SINK@ toggle # }}} # Media keys : Play / Pause / Next / Previous{{{ bindsym--release XF86AudioPlay exec --no-startup-id $cmusPlay bindsym --release XF86AudioPause exec --no-startup-id $cmusPause bindsym --release XF86AudioNext exec --no-startup-id $cmusNext bindsym --release XF86AudioPrev exec --no-startup-id $cmusPrev # }}} # }}} # Window/container shortcuts{{{ # Change focus using vim movement keys{{{ bindsym $mod1+$left focus left bindsym $mod1+$down focus down bindsym $mod1+$up focus up bindsym $mod1+$right focus right # }}} # ...using cursor keys{{{ bindsym $mod1+$left2 focus left bindsym $mod1+$down2 focus down bindsym $mod1+$up2 focus up bindsym $mod1+$right2 focus right # }}} # focus the parent/child containers{{{ bindsym $mod1+a focus parent bindsym $mod1+$mod2+a focus child # }}} # Move focused window using vim movement keys{{{ bindsym $mod1+$mod2+$left move left bindsym $mod1+$mod2+$down move down bindsym $mod1+$mod2+$up move up bindsym $mod1+$mod2+$right move right # }}} # Move focused window using cursor keys{{{ bindsym $mod1+$mod2+$left2 move left bindsym $mod1+$mod2+$down2 move down bindsym $mod1+$mod2+$up2 move up bindsym $mod1+$mod2+$right2 move right # }}} # Resize container using vim movement keys{{{ bindsym $mod1+$mod3+$left resize shrink width 10 px or 10 ppt bindsym $mod1+$mod3+$down resize grow height 10 px or 10 ppt bindsym $mod1+$mod3+$up resize shrink height 10 px or 10 ppt bindsym $mod1+$mod3+$right resize grow width 10 px or 10 ppt # }}} # Resizing container using cursor movement keys{{{ bindsym $mod1+$mod3+$left2 resize shrink width 10 px or 10 ppt bindsym $mod1+$mod3+$up2 resize grow height 10 px or 10 ppt bindsym $mod1+$mod3+$down2 resize shrink height 10 px or 10 ppt bindsym $mod1+$mod3+$right2 resize grow width 10 px or 10 ppt # }}} # }}} # Workspaces{{{ # Mod1 + Tab / Mod3 + Tab / Mod2 + Mod3 + Left/Right : next/prev workspace {{{ bindsym $mod1+$mod2+$mod3+$left workspace prev bindsym $mod1+$mod2+$mod3+$right workspace next bindsym $mod1+$mod3+Tab workspace prev bindsym $mod1+Tab workspace next # }}} # Mod1 + Mod2 + Mod3 + Up/Down : Move window to next/previous workspace{{{ bindsym $mod1+$mod2+$mod3+$down exec "i3-msg move workspace prev; \ i3-msg workspace prev" bindsym $mod1+$mod2+$mod3+$up exec "i3-msg move workspace next; \ i3-msg workspace next" # }}} # Mod1 + 0-9, Mod1 + Mod3 + 0-9 : Jump to workspace{{{ bindsym $mod1+1 workspace $ws01 bindsym $mod1+2 workspace $ws02 bindsym $mod1+3 workspace $ws03 bindsym $mod1+4 workspace $ws04 bindsym $mod1+5 workspace $ws05 bindsym $mod1+6 workspace $ws06 bindsym $mod1+7 workspace $ws07 bindsym $mod1+8 workspace $ws08 bindsym $mod1+9 workspace $ws09 bindsym $mod1+0 workspace $ws10 bindsym $mod1+$mod3+1 workspace $ws11 bindsym $mod1+$mod3+2 workspace $ws12 bindsym $mod1+$mod3+3 workspace $ws13 bindsym $mod1+$mod3+4 workspace $ws14 bindsym $mod1+$mod3+5 workspace $ws15 bindsym $mod1+$mod3+6 workspace $ws16 bindsym $mod1+$mod3+7 workspace $ws17 bindsym $mod1+$mod3+8 workspace $ws18 bindsym $mod1+$mod3+9 workspace $ws19 bindsym $mod1+$mod3+0 workspace $ws20 # }}} # Mod1 + Mod2 + 0-9, Mod1 + Mod2 + Mod3 + 0-9 : Move container to workspace{{{ bindsym $mod1+$mod2+1 move container to workspace $ws01 bindsym $mod1+$mod2+2 move container to workspace $ws02 bindsym $mod1+$mod2+3 move container to workspace $ws03 bindsym $mod1+$mod2+4 move container to workspace $ws04 bindsym $mod1+$mod2+5 move container to workspace $ws05 bindsym $mod1+$mod2+6 move container to workspace $ws06 bindsym $mod1+$mod2+7 move container to workspace $ws07 bindsym $mod1+$mod2+8 move container to workspace $ws08 bindsym $mod1+$mod2+9 move container to workspace $ws09 bindsym $mod1+$mod2+0 move container to workspace $ws10 bindsym $mod1+$mod2+$mod3+1 move container to workspace $ws11 bindsym $mod1+$mod2+$mod3+2 move container to workspace $ws12 bindsym $mod1+$mod2+$mod3+3 move container to workspace $ws13 bindsym $mod1+$mod2+$mod3+4 move container to workspace $ws14 bindsym $mod1+$mod2+$mod3+5 move container to workspace $ws15 bindsym $mod1+$mod2+$mod3+6 move container to workspace $ws16 bindsym $mod1+$mod2+$mod3+7 move container to workspace $ws17 bindsym $mod1+$mod2+$mod3+8 move container to workspace $ws18 bindsym $mod1+$mod2+$mod3+9 move container to workspace $ws19 bindsym $mod1+$mod2+$mod3+0 move container to workspace $ws20 # }}} # }}} # }}} # Launch startup applications{{{ exec --no-startup-id "compton -CGb --config '/home/michael/.config/compton.conf'" exec --no-startup-id "feh ~/.config/i3/wallpaper.jpg --no-fehbg --bg-center" exec --no-startup-id keepass2 exec --no-startup-id "google-chrome 'http://messenger.com/' &" exec --no-startup-id "kitty --class=cmusmusicplayer --override \ background_opacity=0.7 --override background='#202020' 'cmus' &" exec --no-startup-id "conky -c /usr/share/conky/conky-time.conf &" exec --no-startup-id "conky -c /usr/share/conky/active-task-timer.conf &" exec --no-startup-id sh -c "tickr" #exec --no-startup-id bash -c "(cd $HOME/'.local/taskwarriorc2'; . run.sh; exit 0) &" # Start unified remote server exec --no-startup-id "/opt/urserver/urserver-start --no-manager &" # Start phabricator daemons exec --no-startup-id sh -c "/var/www/html/phabricator_git_2018_03_18/phabricator/bin/phd start" # Hide bar - Starts visible, until show key is pressed exec --no-startup-id i3-msg bar hidden_state hide # Lock screen exec --no-startup-id sh -c "$HOME/.local/bin/lock &" # }}} # vim: set ts=4 sw=4 tw=79 fdm=marker et : <file_sep>/dotfiles/home/michael/.local/bin/lock #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # lock # ==== # # Description: Runs i3lock with a set configuration. # Author: <NAME> <shaggyrogers> # Creation Date: 2017-11-28 # Modification Date: 2018-03-03 # License: MIT # ############################################################################### if pgrep 'i3lock'; then echo 'Error: i3lock is already running. ' exit 1; fi i3lock -k --timepos='x+0.5*w-0.5*cw:y+0.5*h-0.5*ch' \ --timecolor='#FFFFFFCC' \ --timesize=48 \ --datecolor='#FFFFFFCC' \ --datesize='24' \ --indicator \ --ring-width=8 \ --radius=36 \ --indpos='x+1.8*r:y+h-1.8*r' \ --veriftext='' \ --wrongtext='' \ --insidevercolor='#FFFFFF88' \ --insidewrongcolor='#FF111188' \ --insidecolor='#00000000' \ --ringvercolor='#FFFFFFCC' \ --ringwrongcolor='#FFFFFFCC' \ --ringcolor='#FFFFFFCC' \ --linecolor='#00000000' \ --separatorcolor='#00000000' \ --keyhlcolor='#11FF11CC' \ --bshlcolor='#FF1111CC' \ -i $HOME'/.config/i3/lockimg.png' & # Commented this out for now - does not work #sleep 1.0 #i3lockpid=$! #winid=`xwininfo -name "i3lock" | grep "Window id" | grep -oE "0x[0-9a-f]+"` # #if [ -z "$winid" ]; then # echo "Could not find i3lock window" # exit 1 #fi # #conky -w "$winid" & #conkypid=$! #wait $i3lockpid #kill $conkypid exit 0 # vim: set ts=4 sw=4 tw=79 fdm=marker et : <file_sep>/dotfiles/usr/share/i3blocks/localWeather.py #!/usr/bin/env python3 # -*- coding: UTF-8 -*- """ localWeather.py =============== Version: 1.1.0 Author: <NAME> Creation Date: 2017-11-06 License: None Description ----------- A simple script that retrieves BOM weather station data and outputs a pretty and concise summary. Usage ----- Requires a font patched to have Weather Icons starting from U+E840. Font is by E<NAME>ers: http://erikflowers.github.io/weather-icons/. To configure the script, find the BOM URI for the JSON-formatted weather data you want to display and set the value of BOM_API_URL. All VIC weather stations can be found at http://www.bom.gov.au/vic/observations/vicall.shtml To display the data, call the script from i3blocks/i3blocks-gaps or anything else that can display the pango markup language. """ import json import math import re import requests import sys # Configuration BOM_API_URI = 'http://www.bom.gov.au/fwo/IDV60801/IDV60801.94865.json' def formatIcon(icon): """ Formats icon. Returns None if icon is not a string. """ return icon def getWindDirIcon(windDir): """ Returns an icon for the given compass direction. Returns None if unsuccessful. """ compass = {'n': u'\ue89c', # wi-towards-n 'nne': u'\ue89a', # wi-towards-ne 'ne': u'\ue89a', # wi-towards-ne 'ene': u'\ue89a', # wi-towards-ne 'e': u'\ue899', # wi-towards-e 'ese': u'\ue89d', # wi-towards-se 'se': u'\ue89d', # wi-towards-se 'sse': u'\ue89d', # wi-towards-se 's': u'\ue8a0', # wi-towards-s 'ssw': u'\ue89e', # wi-towards-sw 'sw': u'\ue89e', # wi-towards-sw 'wsw': u'\ue89e', # wi-towards-sw 'w': u'\ue8a1', # wi-towards-w 'wnw': u'\ue89b', # wi-towards-nw 'nw': u'\ue89b', # wi-towards-nw 'nnw': u'\ue89b'} # wi-towards-nw return compass.get(windDir.lower()) def getForecast(weather, cloud=None): """ Returns a short forecast string for the given weather data. """ if cloud is None: return weather.lower() return weather.lower() if weather != '-' else cloud.lower() def getForecastIcon(weather, cloud): """ Returns an icon for the weather forecast data. If if none is found, a default icon will be returned. """ key = weather.lower() if weather != '-' else cloud.lower() key = re.sub('mostly ', '', key) # Neither day nor night icons = {'cloudy': u'☁', # u'\ue853', # wi-cloudy 'light showers': u'🌦', # u'\ue85a', # wi-showers 'partly cloudy': u'⛅', # u'\ue881', # wi-cloud 'showers': u'🌧', # u'\ue85a', # wi-showers 'sunny': u'☀', # u'\ue84d', # wi-day-sunny 'clear': u'☀', # u'\ue84d', # wi-day-sunny 'wind': u'🌬', # u'\ue840', # wi-day-cloudy-gusts 'storm': u'⛈', # u'\ue850', # wi-day-thunderstorm 'light-rain': u'🌦', # u'\ue84b'} # wi-day-sprinkle } if key not in icons: return u'\ue84d' # wi-day-sunny return icons.get(key) def getTemperatureIcon(temp): """ Returns an icon for the temperature range. Will return an icon for any float value. """ if isinstance(temp, str) or isinstance(temp, int): temp = float(temp) fltemp = math.floor(temp) # Get icon for temperature range if fltemp <= 0: return u'' elif fltemp <= 9: return u'' elif fltemp >= 10 and fltemp <= 19: return u'' elif fltemp >= 20 and fltemp <= 24: return u'' elif fltemp >= 25 and fltemp <= 29: return u'' # fltemp >= 30: return u'' def main(*args): """ Retrieves BOM data and prints a formatted string. Returns 0 if successful or a nonzero exit code otherwise. """ # GET data and parse as JSON response = requests.get(BOM_API_URI) if response.status_code != 200: print('Error: HTTP code {0}'.format(response.status_code)) sys.exit(1) respData = json.loads(response.text) # Parse data and print formatted output latestData = respData['observations']['data'][0] shortOutput = '' output = '' # Weather if 'weather' in latestData: icon = formatIcon(getForecastIcon(latestData['weather'], latestData.get('cloud'))) forecast = getForecast(latestData['weather'], latestData.get('cloud')) output += '{0} {1} '.format(icon, forecast) shortOutput += '{0} {1} '.format(icon, forecast) # Temperature if 'air_temp' in latestData: temp = u'{0:1.1f}'.format(float(latestData['air_temp'])) icon = formatIcon(getTemperatureIcon(latestData['air_temp'])) if 'apparent_t' in latestData: appTemp = u'{0:1.1f}'.format(float(latestData['apparent_t'])) output += '{0} {1}°C ({2}) '.format(icon, temp, appTemp) shortOutput += '{0} {1}°C ({2}) '.format(icon, temp, appTemp) else: output += '{0} {1}°C '.format(icon, temp) shortOutput += '{0} {1}°C '.format(icon, temp) # Humidity if 'rel_hum' in latestData: icon = formatIcon('') output += u'{0} {1:1.0f}% '.format(icon, float(latestData['rel_hum'])) # Wind if 'wind_spd_kmh' in latestData: windSpeed = u'{0:1.0f}km/h'.format(float(latestData['wind_spd_kmh'])) icon = formatIcon('') output += '{0} {1}'.format(icon, windSpeed) print(output) print(shortOutput) return 0 # Execute script if not imported if __name__ == '__main__': sys.exit(main(sys.argv)) <file_sep>/dump_user_packages.sh #!/usr/bin/env bash # -*- coding: UTF-8 -*- ############################################################################### # dump_user_packages.sh # ===================== # # Author: jmiserez # # Description # ----------- # Dumps user-installed apt packages to a file. # # Source: https://askubuntu.com/questions/2389/generating-list-of-manually- # installed-packages-and-querying-individual-packages # # Slightly modified. # ############################################################################### SCRIPT_DIR=$(dirname "$(readlink -f "$0")") OUTFILE=$SCRIPT_DIR'/user_packages.txt' printf "$(comm -23 <(apt-mark showmanual | sort -u) \ <(gzip -dc /var/log/installer/initial-status.gz | \ sed -n 's/^Package: //p' | sort -u))" > $OUTFILE echo "Wrote $(cat $OUTFILE | wc -l) package names to $OUTFILE." exit 0
56fe34b0bab2df69191808a957a2742ade5f21e9
[ "INI", "Python", "Shell" ]
17
Python
chrisdepas/dotfiles
fcc14977811c2e3dcfb84a131b01d9200db7299c
3cc7df6b0ac9e05d67704eea14b24e197d22b6f8
refs/heads/master
<file_sep># FILE METADATA MICROSERVICE https://file-metadata-uze.herokuapp.com/ <file_sep>"use strict"; const express = require('express'), multer = require('multer'), path = require('path'), fs = require('fs'); const upload = multer({ dest: 'uploads/' }); const app = express() app.set('port', (process.env.PORT || 3000)); app.get('/', function(req, res){ res.sendFile(path.join(__dirname, '/public', 'index.html')); }); app.post('/', upload.single('file'), function(req, res){ let filePath = "./uploads/" + req.file.filename; fs.unlink(filePath); res.json({ fileName: req.file.originalname, size: req.file.size }); }); app.listen(app.get('port'), () => { console.log(`App is running on port ${app.get('port')}`); });
0938a107ffcecce33d90b6a4b6c6cea824de8fbd
[ "Markdown", "JavaScript" ]
2
Markdown
uzeuze/file_metadata_microservice
173ab4a3355a12c52cdef1e09b2f3416002646bb
372af87afe23a3ed9a4a54bda8d5af43ab6e84b2
refs/heads/master
<repo_name>PradeepRajput07/java-core<file_sep>/design-patterns/src/com/psr/dp/fatory/AnimalFactory.java package com.psr.dp.fatory; public class AnimalFactory { public Animal createAnimal(String animalType) { if (animalType == null) { return null; } if ("horse".equalsIgnoreCase(animalType)) { return new Horse(); } else if ("dog".equalsIgnoreCase(animalType)) { return new Dog(); } else if ("deer".equalsIgnoreCase(animalType)) { return new Deer(); } return null; } }<file_sep>/design-patterns/src/com/psr/dp/templatemethod/PDFFileProcessor.java package com.psr.dp.templatemethod; public class PDFFileProcessor extends FileProcessor { @Override public void readFile() { System.out.println("Reading PDF File... !!!"); } @Override public void writeFile() { System.out.println("Writing to PDF File... !!!"); } } <file_sep>/design-patterns/src/com/psr/dp/singleton/Singleton.java package com.psr.dp.singleton; import java.io.Serializable; public class Singleton implements Serializable, Cloneable{ private static final long serialVersionUID = 1L; //private static Singleton soleInstance = new Singleton(); //Eager Creation private static volatile Singleton soleInstance = null; private Singleton() { /*if(soleInstance == null) { throw new RuntimeException("Cannot create !! Please use the getInstance method"); }*/ System.out.println("Creating the instance ... !"); } public static Singleton getInstance() { //Double check locking for multithreaded envts if(soleInstance == null) { //Check 1 synchronized(Singleton.class) { if(soleInstance == null) { //Check 2 soleInstance = new Singleton(); } } } return soleInstance; } @Override protected Object clone() throws CloneNotSupportedException{ return super.clone(); } } <file_sep>/design-patterns/src/com/psr/dp/abstractfactory/HondaCarFactory.java package com.psr.dp.abstractfactory; public class HondaCarFactory implements CarFactory { @Override public Car createCar(String carType) { if (carType == null) { return null; } if ("amaze".equalsIgnoreCase(carType)) { return new Amaze(); } else if ("city".equalsIgnoreCase(carType)) { return new City(); } return null; } } <file_sep>/design-patterns/src/com/psr/dp/structural/decorator/Jalapenos.java package com.psr.dp.structural.decorator; public class Jalapenos extends PizzaToppings { public Jalapenos(Pizza pizza) { this.pizza = pizza; } @Override public String description() { return this.pizza.description() + " Jalapenos"; } @Override public Double cost() { return this.pizza.cost() + 5; } } <file_sep>/design-patterns/src/com/psr/dp/fatory/AnimalFactoryTest.java package com.psr.dp.fatory; public class AnimalFactoryTest { public static void main(String[] args) { String animalType = args[0]; AnimalFactory animalFactory = new AnimalFactory(); Animal animal = animalFactory.createAnimal(animalType); animal.eat(); } }<file_sep>/design-patterns/src/com/psr/dp/abstractfactory/CarFactory.java package com.psr.dp.abstractfactory; public interface CarFactory { Car createCar(String carType); } <file_sep>/design-patterns/src/com/psr/dp/prototype/BookShop.java package com.psr.dp.prototype; import java.util.ArrayList; import java.util.List; public class BookShop implements Cloneable { private String bookShopName; private List<Book> books = new ArrayList<>(); public String getBookShopName() { return bookShopName; } public void setBookShopName(String bookShopName) { this.bookShopName = bookShopName; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } @Override public String toString() { return "BookShop [bookShopName=" + bookShopName + ", books=" + books + "]"; } public void loadBooksData() { for(int i=1 ; i<10; i++) { Book b = new Book(); b.setBookName("Book" + i); b.setId(i); getBooks().add(b); } } // Here the perfect cloning is handled @Override protected BookShop clone() throws CloneNotSupportedException{ BookShop bs = new BookShop(); for (Book b : this.getBooks()) { bs.getBooks().add(b); } return bs; } } <file_sep>/design-patterns/src/com/psr/dp/structural/adapter/ChargeUtils.java package com.psr.dp.structural.adapter; public class ChargeUtils { public static void doCharge(Chargeable chargeable) { chargeable.charge(); } } <file_sep>/design-patterns/src/com/psr/dp/structural/adapter/Charger.java package com.psr.dp.structural.adapter; public interface Charger { public void setMobileName(String mobileName); public void supplyCharge(); } <file_sep>/design-patterns/src/com/psr/dp/templatemethod/FileProcessor.java package com.psr.dp.templatemethod; public abstract class FileProcessor { public final void processFile() { openFile(); readFile(); writeFile(); saveFile(); closeFile(); } public final void openFile() { System.out.println("Opening the file now... !!!"); } public abstract void readFile(); public abstract void writeFile(); public final void saveFile() { System.out.println("Saving the file now... !!!"); } public final void closeFile() { System.out.println("Closing the file now... !!!"); } } <file_sep>/design-patterns/src/com/psr/dp/structural/decorator/PanPizza.java package com.psr.dp.structural.decorator; public class PanPizza implements Pizza { @Override public String description() { return "Pan Pizza with :"; } @Override public Double cost() { return 10.0; } } <file_sep>/design-patterns/src/com/psr/dp/fatory/Horse.java package com.psr.dp.fatory; public class Horse implements Animal { @Override public void eat() { System.out.println("Horse is eating... !!!"); } } <file_sep>/design-patterns/src/com/psr/dp/templatemethod/WordFileProcessor.java package com.psr.dp.templatemethod; public class WordFileProcessor extends FileProcessor { @Override public void readFile() { System.out.println("Reading Word File... !!!"); } @Override public void writeFile() { System.out.println("Writing to Word File... !!!"); } }<file_sep>/design-patterns/src/com/psr/dp/structural/adapter/Chargeable.java package com.psr.dp.structural.adapter; public interface Chargeable { public void setMobileName(String mobileName); public void charge(); } <file_sep>/design-patterns/src/com/psr/dp/abstractfactory/I10.java package com.psr.dp.abstractfactory; public class I10 implements Car { @Override public void drive() { System.out.println("Driving Hyindai i10........ !!!"); } }<file_sep>/design-patterns/src/com/psr/dp/structural/adapter/AdapterPatternTest.java package com.psr.dp.structural.adapter; public class AdapterPatternTest { public static void main(String[] args) { Chargeable ch = new AppleCharger(); ch.setMobileName("iPhoneX.."); //**Using Apple Charger**// ChargeUtils.doCharge(ch); Charger samsungCharger = new SamsungCharger(); samsungCharger.setMobileName("Galaxy Note 4"); //** Using apple for charging samsung phone**// SamsungAdapter samsungAdapter = new SamsungAdapter(); samsungAdapter.setSamsungCharger(samsungCharger); ChargeUtils.doCharge(samsungAdapter); } } <file_sep>/design-patterns/src/com/psr/dp/prototype/Demo.java package com.psr.dp.prototype; public class Demo { public static void main(String[] args) throws CloneNotSupportedException { BookShop bs = new BookShop(); bs.loadBooksData(); bs.setBookShopName("Shop"); // Cloning the object i.e retrieving a prototype BookShop bs1 = bs.clone(); bs1.setBookShopName("Shop1"); bs1.getBooks().remove(0); System.out.println(bs); System.out.println(bs1); } } <file_sep>/design-patterns/src/com/psr/dp/structural/decorator/Tomatoes.java package com.psr.dp.structural.decorator; public class Tomatoes extends PizzaToppings { public Tomatoes(Pizza pizza) { this.pizza = pizza; } @Override public String description() { return this.pizza.description() + " Tomatoes"; } //Decorates the pizza with tomatoes and returns the same pizza with the cost of tomatoes included @Override public Double cost() { return pizza.cost() + 1.0; } } <file_sep>/README.md # java-core This repository contains core java programs designed to confirm my understanding <file_sep>/design-patterns/src/com/psr/dp/singleton/SingletonTest.java package com.psr.dp.singleton; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Constructor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class SingletonTest { @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception{ Singleton s1 = Singleton.getInstance(); Singleton s2 = Singleton.getInstance(); print ("s1", s1); print ("s2", s2); //Serialization Example: /*ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/temp/s2.ser")); oos.writeObject(s2); //Deserialization: ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/temp/s2.ser")); Singleton s4 = (Singleton)ois.readObject(); print ("Deserialized s2", s4);*/ //Reflection can break singleton Class clazz = Class.forName("com.psr.dp.singleton.Singleton"); Constructor<Singleton> ctor = clazz.getDeclaredConstructor(); ctor.setAccessible(true); Singleton s3 = ctor.newInstance(); print ("s3", s3); //Cloning /*Singleton s5 = (Singleton)s2.clone(); print ("s5" ,s5);*/ //Thread Pool Example ExecutorService service = Executors.newFixedThreadPool(2); service.submit(SingletonTest::useSingleton); service.submit(SingletonTest::useSingleton); service.shutdown(); } private static void print(String name, Singleton object) { System.out.println(String.format("Object: %s , Hashcode: %d", name, object.hashCode())); } public static void useSingleton() { Singleton singleton = Singleton.getInstance(); print("singleton", singleton); } }
75dba8c87d091f107f652f4ac32300e09ae74357
[ "Markdown", "Java" ]
21
Java
PradeepRajput07/java-core
a8075b6857f7fb4b209ad0c21a19e5c952c09650
0720e4a3649abf68dc98fc911aead92d3134112c
refs/heads/master
<repo_name>HarigovindV10/JioFiStatusChecker<file_sep>/README.md # JioFiStatusChecker A MacOS menu bar application to check the status of JioFi <file_sep>/JioFiStatusChecker/Display/DisplayViewController.swift // // DisplayViewController.swift // JioFiStatusChecker // // Created by <NAME> on 26/08/20. // Copyright © 2020 <NAME>. All rights reserved. // import Cocoa class DisplayViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } } extension DisplayViewController { // MARK: Storyboard instantiation static func freshController() -> DisplayViewController { //1. let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil) //2. let identifier = NSStoryboard.SceneIdentifier("DisplayViewController") //3. guard let viewcontroller = storyboard.instantiateController(withIdentifier: identifier) as? DisplayViewController else { fatalError("Why cant i find DisplayViewController? - Check Main.storyboard") } return viewcontroller } }
54136125d834a5b77ed72f1b44deefddb27de8d0
[ "Markdown", "Swift" ]
2
Markdown
HarigovindV10/JioFiStatusChecker
b7647f3438611d22ec2aaa2806c31e4b9a1dd8a8
ee31f378f590645e31df7a477426622ae0e6f2ae
refs/heads/master
<repo_name>puuuii/stock_price<file_sep>/basedata.py import pandas as pd import pickle import shutil import os def make_basedata(): # 縦持ちのDataFrame作成 basedata = _make_data_dict() # pickle化 _pickle_data(basedata) def _make_data_dict(): # 読み込みパス作成 csv_dir = './datas/csvs/' csv_pathes = [(csv_dir + path) for path in os.listdir(csv_dir)] # DataFrame作成 basedict = _csv_to_df(csv_pathes) return basedict def _csv_to_df(csv_pathes): # 全csvデータから縦に結合したDataFrameを作成 dfs = [pd.read_csv(path, encoding="shift-jis", header=None, index_col=0) for path in csv_pathes] df = pd.concat(dfs, axis=0, sort=True) df = df.iloc[:, [0, 2, 3, 4, 5, 6, 7, 8]] df.columns = ['code', 'name', 'start', 'top', 'bottom', 'end', 'value', 'place'] print(df.head()) df.index.name = 'date' df['name'] = df['name'].apply(lambda x: str(x).split(' ')[-1]) return df def _pickle_data(dict_data): # 書き出しディレクトリ初期化 datas_dir = 'datas/' basedata_dir = datas_dir + 'basedata/' try: shutil.rmtree(basedata_dir) except FileNotFoundError: pass os.mkdir(basedata_dir) # pickle化 filepath = basedata_dir + 'basedata.pkl' with open(filepath, 'wb') as f: pickle.dump(dict_data, f, protocol=4) if __name__ == "__main__": make_basedata()<file_sep>/analyze.py #%% import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import seaborn as sns import matplotlib.pyplot as plt import pickle from fbprophet import Prophet from sklearn.metrics import mean_squared_error, mean_absolute_error sns.set_style('dark') #%% with open('./datas/basedata/basedata.pkl', "rb") as f: df = pickle.load(f) df.head() #%% comture = df[df['code'] == 3844] comture.head() #%% comture.isnull().sum() #%% comture['fluc'] = comture['end'] - comture['start'] comture['fluc'].plot(figsize=(15,5)) #%% split_date = '2019/1/1' train_comture = comture.loc[comture.index <= split_date] test_comture = comture.loc[comture.index > split_date] train_data = train_comture['fluc'].reset_index().rename(columns={'date':'ds', 'fluc':'y'}) test_data = test_comture.reset_index().rename(columns={'date':'ds'})['ds'] train_data.loc[(train_data['y'] > 200) & (train_data['y'] < -200)] = None #%% model = Prophet(changepoint_prior_scale=0.001, weekly_seasonality=False) model.add_seasonality(name='monthly', period=30.5, fourier_order=5) model.fit(train_data) #%% future = model.make_future_dataframe(len(test_data)) predicted = model.predict(df=future) fig = model.plot(predicted) #%% fig = model.plot_components(predicted) #%% <file_sep>/download.py import quandl import zipfile import shutil import datetime import os import pandas as pd import requests import glob quandl.ApiConfig.api_key = '<KEY>' def download_data(get_period=100): _get_datas(get_period) def _get_datas(get_length): # ディレクトリ&ファイル初期化 datas_dir = 'datas/' zip_dir = datas_dir + 'zips/' csv_dir = datas_dir + 'csvs/' try: shutil.rmtree(datas_dir) except FileNotFoundError: pass os.mkdir(datas_dir) os.mkdir(zip_dir) os.mkdir(csv_dir) # zipファイルをwebから取得・保存 url = "http://souba-data.com/k_data/" today = datetime.date.today() urls = [_make_url(url, today, delta) for delta in range(get_length)] _ = [_make_zip(url, zip_dir) for url in urls] _ = [_extract_all(zip_path, csv_dir) for zip_path in glob.glob(zip_dir + '/*')] def _make_url(url, today, delta): date = today - datetime.timedelta(days=delta) year = str(date.year) month = str(date.month).zfill(2) day = str(date.day).zfill(2) url = url + year + "/" + year[-2:] + "_" + month + "/T" + year[-2:] + month + day + ".zip" return url def _make_zip(url, zip_dir): filename = zip_dir + url.split('/')[-1] response = requests.get(url, stream=True) if response.status_code == 200: with open(filename, 'wb') as file: file.write(response.content) def _extract_all(zip_path, csv_dir): with zipfile.ZipFile(zip_path) as zip: zip.extractall(csv_dir) if __name__ == "__main__": download_data()<file_sep>/main.py from download import download_data from basedata import make_basedata from train import Trainer from predict import Predictor N_PERIOD = 3000 # データ取得期間(日) def main(): # データをwebから取得 print('start: download_data') download_data(N_PERIOD) # web取得したデータを縦持ちのDataFrameにしてpickle化 print('start: make_basedata') make_basedata() if __name__ == "__main__": main()
9065e4da79f7344ebcbf4b8027795db1ff1cf4a9
[ "Python" ]
4
Python
puuuii/stock_price
dc15b15795193bed03e39500ab0ddcdb65fb0ddf
83e46c14a9ab421915a351cca308ab9960de2102
refs/heads/master
<repo_name>pramilcheriyath/ProgrammingAssignment2<file_sep>/cachematrix.R # This function creates a special “matrix” object that can cache its inverse # create a matrix 'x' makeCacheMatrix <- function(x = matrix()) { i <- NULL set <- function(y) { x <<- y # settting the value of matrix i <<- NULL # clearing cache } get <- function() x # getting the value of matrix setinverse <- function(inverse) # setting the value of inverse i <<- inverse getinverse <- function() i # getting the value of inverse # a list creaed from all the above list(set = set, get = get,setinverse = setinverse,getinverse = getinverse) } ## This function computes the inverse of the special "matrix" returned by makeCacheMatrix above. cacheSolve <- function(x, ...) { i <- x$getinverse() # getttng the value from inverse if (!is.null(i)) { # checking the value if it's null message("getting cached data") return(i) # returning the value of the matrix if it is not null } data <- x$get() # getting te value of the matric from the above function i <- solve(data, ...) # matrix inverse x$setinverse(i) # setting the value of inverse i }
f8fc3f3abc3789f29016cf4560aa437d25c7546f
[ "R" ]
1
R
pramilcheriyath/ProgrammingAssignment2
a43c630f86d4ae949dd521e4ceed99bdde2ca296
fbf89bb0ef5b8cc647a89d82e001c6510ae5d0c8
refs/heads/master
<repo_name>malivaibhav15/FlipCoin<file_sep>/FlipCoinSimulator.sh #!/bin/bash -x #result=k declare -A singlet declare -A doublet declare -A triplet singlet=( ["H"]=0 ["T"]=0 ) doublet=( ["HH"]=0 ["TT"]=0 ["HT"]=0 ["TH"]=0 ) triplet=( ["HHH"]=0 ["HHT"]=0 ["HTH"]=0 ["THH"]=0 ["HTT"]=0 ["THT"]=0 ["TTH"]=0 ["TTT"]=0 ) function check() { toss=$((RANDOM%2)) if [[ $toss -eq 1 ]] then printf "Heads " result=1 else printf "Tails " result=0 fi } function flipCoin() { read -p "Enter how many coins you want to flip simultaniosly: " numberOfCoin read -p "Enter the number of times you want flip the coin: " number for (( counter=0;counter<$number;counter++ )) do if [[ $numberOfCoin -eq 1 ]] then check if [[ $result -eq 1 ]] then singlet[H]=$(( ${singlet[H]}+1 )) elif [[ $result -eq 0 ]] then singlet[T]=$(( ${singlet[T]}+1 )) fi elif [[ $numberOfCoin -eq 2 ]] then check temp1=$result check temp2=$result if [[ $temp1 -eq 1 && $temp2 -eq 1 ]] then doublet[HH]=$(( ${doublet[HH]}+1 )) elif [[ $temp1 -eq 0 && $temp2 -eq 0 ]] then doublet[TT]=$(( ${doublet[TT]}+1 )) elif [[ $temp1 -eq 1 && $temp2 -eq 0 ]] then doublet[HT]=$(( ${doublet[HT]}+1 )) elif [[ $temp1 -eq 0 && $temp2 -eq 1 ]] then doublet[TH]=$(( ${doublet[TH]}+1 )) fi elif [[ $numberOfCoin -eq 3 ]] then check temp1=$result check temp2=$result check temp3=$result if [[ $temp1 -eq 1 && $temp2 -eq 1 && $temp3 -eq 1 ]] then triplet[HHH]=$(( ${triplet[HHH]}+1 )) elif [[ $temp1 -eq 1 && $temp2 -eq 1 && $temp3 -eq 0 ]] then triplet[HHT]=$(( ${triplet[HHT]}+1 )) elif [[ $temp1 -eq 1 && $temp2 -eq 0 && $temp3 -eq 1 ]] then triplet[HTH]=$(( ${triplet[HTH]}+1 )) elif [[ $temp1 -eq 0 && $temp2 -eq 1 && $temp3 -eq 1 ]] then triplet[THH]=$(( ${triplet[THH]}+1 )) elif [[ $temp1 -eq 1 && $temp2 -eq 0 && $temp3 -eq 0 ]] then triplet[HTT]=$(( ${triplet[HTT]}+1 )) elif [[ $temp1 -eq 0 && $temp2 -eq 1 && $temp3 -eq 0 ]] then triplet[THT]=$(( ${triplet[THT]}+1 )) elif [[ $temp1 -eq 0 && $temp2 -eq 0 && $temp3 -eq 1 ]] then triplet[TTH]=$(( ${triplet[TTH]}+1 )) elif [[ $temp1 -eq 0 && $temp2 -eq 0 && $temp3 -eq 0 ]] then triplet[TTT]=$(( ${triplet[TTT]}+1 )) fi fi done if [[ $numberOfCoin -eq 1 ]] then echo ${singlet[@]} echo ${!singlet[@]} echo "Percentage of H=`expr "scale=2; ( ${singlet[H]} / $number *100 ) " | bc -l`" echo "Percentage of T=`expr "scale=2; ( ${singlet[T]} / $number *100 ) " | bc -l`" elif [[ $numberOfCoin -eq 2 ]] then echo ${doublet[@]} echo ${!doublet[@]} echo "Percentage of HH="`expr "scale=2; ( ${doublet[HH]} / $number *100 ) " | bc -l` echo "Percentage of TT="`expr "scale=2; ( ${doublet[TT]} / $number *100 ) " | bc -l` echo "Percentage of HT="`expr "scale=2; ( ${doublet[HT]} / $number *100 ) " | bc -l` echo "Percentage of TT="`expr "scale=2; ( ${doublet[TH]} / $number *100 ) " | bc -l` elif [[ $numberOfCoin -eq 3 ]] then echo ${triplet[@]} echo ${!triplet[@]} echo "Percentage of HHH="`expr "scale=2; ( ${triplet[HHH]} / $number *100 ) " | bc -l` echo "Percentage of HHT="`expr "scale=2; ( ${triplet[HHT]} / $number *100 ) " | bc -l` echo "Percentage of HTH="`expr "scale=2; ( ${triplet[HTH]} / $number *100 ) " | bc -l` echo "Percentage of THH="`expr "scale=2; ( ${triplet[THH]} / $number *100 ) " | bc -l` echo "Percentage of HTT="`expr "scale=2; ( ${triplet[HTT]} / $number *100 ) " | bc -l` echo "Percentage of THT="`expr "scale=2; ( ${triplet[THT]} / $number *100 ) " | bc -l` echo "Percentage of TTH="`expr "scale=2; ( ${triplet[TTH]} / $number *100 ) " | bc -l` echo "Percentage of TTT="`expr "scale=2; ( ${triplet[TTT]} / $number *100 ) " | bc -l` fi } flipCoin
f3337c4024c710539190f952e75f1a96949bf2f2
[ "Shell" ]
1
Shell
malivaibhav15/FlipCoin
31b0d3fa6a07c646fbca73b86ae00ce9e7a1975b
2518aa1089222f6265f34812366230a4f2802bb8
refs/heads/master
<file_sep>#include <math.h> float length_2(a) /* computes length of vector a input: a output: length */ float a[]; {float x; x=sqrt(a[0]*a[0]+a[1]*a[1]); return(x); } <file_sep>void c2_spline(knot,l,data_x,data_y,bspl_x,bspl_y) /* Finds the C2 cubic spline interpolant to the data points in data_x, data_y. Input: knot: the knot sequence knot[0], ..., knot[l] l: the number of intervals data_x, data_y: the data points data_x[0], ..., data[l+2]. Attention: data_x[1] and data_x[l+1] are filled by Bessel end conditions and are thus ignored on input. Same for data_y. Output: bspl_x, bspl_y: the B-spline control polygon of the interpolant. Dimensions: bspl_x[0], ..., bspl_x[l+2]. Same for bspl_y. */ float knot[],data_x[],data_y[],bspl_x[],bspl_y[]; int l; { float alpha[100], beta[100], gamma[100], up[100], low[100]; set_up_system(knot,l,alpha,beta,gamma); l_u_system(alpha,beta,gamma,l,up,low); bessel_ends(data_x,knot,l); bessel_ends(data_y,knot,l); solve_system(up,low,gamma,l,data_x,bspl_x); solve_system(up,low,gamma,l,data_y,bspl_y); }
7f278ec09c87b93868fae459212fec93c11f6841
[ "C" ]
2
C
jasonch/348a
22d43a06938a9131ca641d2775a9a5185294bd71
873d0b151ddf1ba368a71ff25f2ed9d513352d33
refs/heads/master
<file_sep>using CasinoSim.Static_Classes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace CasinoSim { public partial class BlackJackWindow : Window { private Betting betting = new Betting(); public BlackJackWindow() { InitializeComponent(); lbl_Money.Content = Player.wallet; lbl_Bet.Content = betting.currentBet; } private void Back_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = new MainWindow(); mainWindow.Show(); Close(); } private void bet_1(object sender, RoutedEventArgs e) { if (!betting.Bet(1)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Money.Content = Player.wallet; } private void bet_5(object sender, RoutedEventArgs e) { if (!betting.Bet(5)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Money.Content = Player.wallet; } private void bet_10(object sender, RoutedEventArgs e) { if (!betting.Bet(10)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Money.Content = Player.wallet; } private void bet_20(object sender, RoutedEventArgs e) { if (!betting.Bet(20)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Money.Content = Player.wallet; } private void bet_50(object sender, RoutedEventArgs e) { if (!betting.Bet(50)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Money.Content = Player.wallet; } private void bet_100(object sender, RoutedEventArgs e) { if (!betting.Bet(100)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Money.Content = Player.wallet; } private void bet_500(object sender, RoutedEventArgs e) { if (!betting.Bet(500)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Money.Content = Player.wallet; } private void bet_1000(object sender, RoutedEventArgs e) { if (!betting.Bet(1000)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Money.Content = Player.wallet; } private void bet_5000(object sender, RoutedEventArgs e) { if (!betting.Bet(5000)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Money.Content = Player.wallet; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using CasinoSim.Static_Classes; namespace CasinoSim { /// <summary> /// Interaction logic for Banking_Window.xaml /// </summary> public partial class Banking_Window : Window { public Banking_Window() { InitializeComponent(); lbl_netWorth.Content = Player.netWorth; lbl_wallet.Content = Player.wallet; } private void Back_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = new MainWindow(); mainWindow.Show(); Close(); } private void Withdrawl_Click(object sender, RoutedEventArgs e) { int dMoney = int.Parse(txtBox_withdrawl.Text); Player.netWorth -= dMoney; Player.wallet += dMoney; lbl_netWorth.Content = Player.netWorth; lbl_wallet.Content = Player.wallet; } private void Deposit_Click(object sender, RoutedEventArgs e) { int dMoney = int.Parse(txtBox_deposit.Text); Player.netWorth += dMoney; Player.wallet -= dMoney; lbl_netWorth.Content = Player.netWorth; lbl_wallet.Content = Player.wallet; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CasinoSim.Static_Classes { public class Banking { public void Deposit(int value) { Player.netWorth += value; Player.wallet -= value; } //this sentence is FALSE!!!!!!! public void Withdraw(int value) { Player.wallet += value; Player.netWorth -= value; } } } //<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using CasinoSim.Static_Classes; namespace CasinoSim { /// <summary> /// Interaction logic for CrapsWindow.xaml /// </summary> public partial class CrapsWindow : Window { private Betting betting = new Betting(); public CrapsWindow() { InitializeComponent(); lbl_Chips.Content = Player.wallet; lbl_Bet.Content = betting.currentBet; } int totalBet = 0; private void Back_Click(object sender, RoutedEventArgs e) { if (totalBet == 0) { MainWindow mainWindow = new MainWindow(); mainWindow.Show(); Close(); } else { //lbl_InvalidBet.Content = "Cannot exit while betting"; } } private void Roll_Click(object sender, RoutedEventArgs e) { } private void bet_1(object sender, RoutedEventArgs e) { if (!betting.Bet(1)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Chips.Content = Player.wallet; } private void bet_5(object sender, RoutedEventArgs e) { if (!betting.Bet(5)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Chips.Content = Player.wallet; } private void bet_10(object sender, RoutedEventArgs e) { if (!betting.Bet(10)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Chips.Content = Player.wallet; } private void bet_20(object sender, RoutedEventArgs e) { if (!betting.Bet(20)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Chips.Content = Player.wallet; } private void bet_50(object sender, RoutedEventArgs e) { if (!betting.Bet(50)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Chips.Content = Player.wallet; } private void bet_100(object sender, RoutedEventArgs e) { if (!betting.Bet(100)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Chips.Content = Player.wallet; } private void bet_500(object sender, RoutedEventArgs e) { if (!betting.Bet(500)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Chips.Content = Player.wallet; } private void bet_1000(object sender, RoutedEventArgs e) { if (!betting.Bet(1000)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Chips.Content = Player.wallet; } private void bet_5000(object sender, RoutedEventArgs e) { if (!betting.Bet(5000)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; } lbl_Bet.Content = betting.currentBet; lbl_Chips.Content = Player.wallet; } private void btn_2_Click(object sender, RoutedEventArgs e) { } private void btn_3_Click(object sender, RoutedEventArgs e) { } private void btn_4_Click(object sender, RoutedEventArgs e) { } private void btn_9_Click(object sender, RoutedEventArgs e) { } private void btn_10_Click(object sender, RoutedEventArgs e) { } private void btn_11_Click(object sender, RoutedEventArgs e) { } private void btn_12_Click(object sender, RoutedEventArgs e) { } private void btn_AnyCraps_Click(object sender, RoutedEventArgs e) { } private void btn_dbl6_Click(object sender, RoutedEventArgs e) { } private void btn_SnakeEyes_Click(object sender, RoutedEventArgs e) { } private void btn_5and5_6_Click(object sender, RoutedEventArgs e) { } private void btn_1and2_Click(object sender, RoutedEventArgs e) { } private void btn_7_Click(object sender, RoutedEventArgs e) { } private void btn_dbl3_Click(object sender, RoutedEventArgs e) { } private void btn_dbl1_Click(object sender, RoutedEventArgs e) { } private void btn_dbl2_Click(object sender, RoutedEventArgs e) { } private void btn_dbl5_Click(object sender, RoutedEventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Documents; using CasinoSim.Generics; namespace CasinoSim.Static_Classes { public static class Deck { public static List<Card> cards = new List<Card>(); public static void fillDeck() { cards.Add(new Card(Card.Suit.Clubs, 2)); cards.Add(new Card(Card.Suit.Clubs, 3)); cards.Add(new Card(Card.Suit.Clubs, 4)); cards.Add(new Card(Card.Suit.Clubs, 5)); cards.Add(new Card(Card.Suit.Clubs, 6)); cards.Add(new Card(Card.Suit.Clubs, 7)); cards.Add(new Card(Card.Suit.Clubs, 8)); cards.Add(new Card(Card.Suit.Clubs, 9)); cards.Add(new Card(Card.Suit.Clubs, 10)); cards.Add(new Card(Card.Suit.Clubs, 11)); cards.Add(new Card(Card.Suit.Clubs, 12)); cards.Add(new Card(Card.Suit.Clubs, 13)); cards.Add(new Card(Card.Suit.Clubs, 14)); cards.Add(new Card(Card.Suit.Hearts, 2)); cards.Add(new Card(Card.Suit.Hearts, 3)); cards.Add(new Card(Card.Suit.Hearts, 4)); cards.Add(new Card(Card.Suit.Hearts, 5)); cards.Add(new Card(Card.Suit.Hearts, 6)); cards.Add(new Card(Card.Suit.Hearts, 7)); cards.Add(new Card(Card.Suit.Hearts, 8)); cards.Add(new Card(Card.Suit.Hearts, 9)); cards.Add(new Card(Card.Suit.Hearts, 10)); cards.Add(new Card(Card.Suit.Hearts, 11)); cards.Add(new Card(Card.Suit.Hearts, 12)); cards.Add(new Card(Card.Suit.Hearts, 13)); cards.Add(new Card(Card.Suit.Hearts, 14)); cards.Add(new Card(Card.Suit.Diamonds, 2)); cards.Add(new Card(Card.Suit.Diamonds, 3)); cards.Add(new Card(Card.Suit.Diamonds, 4)); cards.Add(new Card(Card.Suit.Diamonds, 5)); cards.Add(new Card(Card.Suit.Diamonds, 6)); cards.Add(new Card(Card.Suit.Diamonds, 7)); cards.Add(new Card(Card.Suit.Diamonds, 8)); cards.Add(new Card(Card.Suit.Diamonds, 9)); cards.Add(new Card(Card.Suit.Diamonds, 10)); cards.Add(new Card(Card.Suit.Diamonds, 11)); cards.Add(new Card(Card.Suit.Diamonds, 12)); cards.Add(new Card(Card.Suit.Diamonds, 13)); cards.Add(new Card(Card.Suit.Diamonds, 14)); cards.Add(new Card(Card.Suit.Spades, 2)); cards.Add(new Card(Card.Suit.Spades, 3)); cards.Add(new Card(Card.Suit.Spades, 4)); cards.Add(new Card(Card.Suit.Spades, 5)); cards.Add(new Card(Card.Suit.Spades, 6)); cards.Add(new Card(Card.Suit.Spades, 7)); cards.Add(new Card(Card.Suit.Spades, 8)); cards.Add(new Card(Card.Suit.Spades, 9)); cards.Add(new Card(Card.Suit.Spades, 10)); cards.Add(new Card(Card.Suit.Spades, 11)); cards.Add(new Card(Card.Suit.Spades, 12)); cards.Add(new Card(Card.Suit.Spades, 13)); cards.Add(new Card(Card.Suit.Spades, 14)); shuffle(); } public static void shuffle() { if(cards.Count == 0) { fillDeck(); } cards = cards.OrderBy(x => Guid.NewGuid()).ToList(); } public static Card draw() { if(cards.Count == 0) { fillDeck(); } Card card = cards[0]; cards.RemoveAt(0); return card; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace CasinoSim { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void BlackJack_Click(object sender, RoutedEventArgs e) { BlackJackWindow blackJackWindow = new BlackJackWindow(); blackJackWindow.Show(); Close(); } private void Craps_Click(object sender, RoutedEventArgs e) { CrapsWindow crapsWindow = new CrapsWindow(); crapsWindow.Show(); Close(); } private void Roulette_Click(object sender, RoutedEventArgs e) { RouletteWindow rouletteWindow = new RouletteWindow(); rouletteWindow.Show(); Close(); } private void Poker_Click(object sender, RoutedEventArgs e) { Poker pokerWindow = new Poker(); pokerWindow.Show(); Close(); } private void Slots_Click(object sender, RoutedEventArgs e) { SlotsWindow slotsWindow = new SlotsWindow(); slotsWindow.Show(); Close(); } private void Banking_Click(object sender, RoutedEventArgs e) { Banking_Window bankingWindow = new Banking_Window(); bankingWindow.Show(); Close(); } } } <file_sep>using CasinoSim.Static_Classes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace CasinoSim { /// <summary> /// Interaction logic for RouletteWindow.xaml /// </summary> public partial class RouletteWindow : Window { int totalBet = 0; int btnSelected = -1; List<Betting> bets = new List<Betting>(); // 36:1 Betting bet0 { get; set; } = new Betting(); Betting bet1 { get; set; } = new Betting(); Betting bet2 { get; set; } = new Betting(); Betting bet3 { get; set; } = new Betting(); Betting bet4 { get; set; } = new Betting(); Betting bet5 { get; set; } = new Betting(); Betting bet6 { get; set; } = new Betting(); Betting bet7 { get; set; } = new Betting(); Betting bet8 { get; set; } = new Betting(); Betting bet9 { get; set; } = new Betting(); Betting bet10 { get; set; } = new Betting(); Betting bet11 { get; set; } = new Betting(); Betting bet12 { get; set; } = new Betting(); Betting bet13 { get; set; } = new Betting(); Betting bet14 { get; set; } = new Betting(); Betting bet15 { get; set; } = new Betting(); Betting bet16 { get; set; } = new Betting(); Betting bet17 { get; set; } = new Betting(); Betting bet18 { get; set; } = new Betting(); Betting bet19 { get; set; } = new Betting(); Betting bet20 { get; set; } = new Betting(); Betting bet21 { get; set; } = new Betting(); Betting bet22 { get; set; } = new Betting(); Betting bet23 { get; set; } = new Betting(); Betting bet24 { get; set; } = new Betting(); Betting bet25 { get; set; } = new Betting(); Betting bet26 { get; set; } = new Betting(); Betting bet27 { get; set; } = new Betting(); Betting bet28 { get; set; } = new Betting(); Betting bet29 { get; set; } = new Betting(); Betting bet30 { get; set; } = new Betting(); Betting bet31 { get; set; } = new Betting(); Betting bet32 { get; set; } = new Betting(); Betting bet33 { get; set; } = new Betting(); Betting bet34 { get; set; } = new Betting(); Betting bet35 { get; set; } = new Betting(); Betting bet36 { get; set; } = new Betting(); // 1:1 Betting betRed { get; set; } = new Betting(); Betting betBlack { get; set; } = new Betting(); Betting betOdd { get; set; } = new Betting(); Betting betEven { get; set; } = new Betting(); Betting betHigh { get; set; } = new Betting(); Betting betLow { get; set; } = new Betting(); // 3:1 Betting betDozen1 { get; set; } = new Betting(); Betting betDozen2 { get; set; } = new Betting(); Betting betDozen3 { get; set; } = new Betting(); Betting betRow1 { get; set; } = new Betting(); Betting betRow2 { get; set; } = new Betting(); Betting betRow3 { get; set; } = new Betting(); // 9:1 Betting sqr1_2_4_5 { get; set; } = new Betting(); Betting sqr2_3_5_6 { get; set; } = new Betting(); Betting sqr4_5_7_8 { get; set; } = new Betting(); Betting sqr5_6_8_9 { get; set; } = new Betting(); Betting sqr7_8_10_11 { get; set; } = new Betting(); Betting sqr8_9_11_12 { get; set; } = new Betting(); Betting sqr10_11_13_14 { get; set; } = new Betting(); Betting sqr11_12_14_15 { get; set; } = new Betting(); Betting sqr13_14_16_17 { get; set; } = new Betting(); Betting sqr14_15_17_18 { get; set; } = new Betting(); Betting sqr16_17_19_20 { get; set; } = new Betting(); Betting sqr17_18_20_21 { get; set; } = new Betting(); Betting sqr19_20_22_23 { get; set; } = new Betting(); Betting sqr20_21_23_24 { get; set; } = new Betting(); Betting sqr22_23_25_26 { get; set; } = new Betting(); Betting sqr23_24_26_27 { get; set; } = new Betting(); Betting sqr25_26_28_29 { get; set; } = new Betting(); Betting sqr26_27_29_30 { get; set; } = new Betting(); Betting sqr28_29_31_32 { get; set; } = new Betting(); Betting sqr29_30_32_33 { get; set; } = new Betting(); Betting sqr31_32_34_35 { get; set; } = new Betting(); Betting sqr32_33_35_36 { get; set; } = new Betting(); // 18:1 Betting split1_2 { get; set; } = new Betting(); Betting split2_3 { get; set; } = new Betting(); Betting split4_5 { get; set; } = new Betting(); Betting split5_6 { get; set; } = new Betting(); Betting split7_8 { get; set; } = new Betting(); Betting split8_9 { get; set; } = new Betting(); Betting split10_11 { get; set; } = new Betting(); Betting split11_12 { get; set; } = new Betting(); Betting split13_14 { get; set; } = new Betting(); Betting split14_15 { get; set; } = new Betting(); Betting split16_17 { get; set; } = new Betting(); Betting split17_18 { get; set; } = new Betting(); Betting split19_20 { get; set; } = new Betting(); Betting split20_21 { get; set; } = new Betting(); Betting split22_23 { get; set; } = new Betting(); Betting split23_24 { get; set; } = new Betting(); Betting split25_26 { get; set; } = new Betting(); Betting split26_27 { get; set; } = new Betting(); Betting split28_29 { get; set; } = new Betting(); Betting split29_30 { get; set; } = new Betting(); Betting split31_32 { get; set; } = new Betting(); Betting split32_33 { get; set; } = new Betting(); Betting split34_35 { get; set; } = new Betting(); Betting split35_36 { get; set; } = new Betting(); Betting split1_4 { get; set; } = new Betting(); Betting split2_5 { get; set; } = new Betting(); Betting split3_6 { get; set; } = new Betting(); Betting split4_7 { get; set; } = new Betting(); Betting split5_8 { get; set; } = new Betting(); Betting split6_9 { get; set; } = new Betting(); Betting split7_10 { get; set; } = new Betting(); Betting split8_11 { get; set; } = new Betting(); Betting split9_12 { get; set; } = new Betting(); Betting split10_13 { get; set; } = new Betting(); Betting split11_14 { get; set; } = new Betting(); Betting split12_15 { get; set; } = new Betting(); Betting split13_16 { get; set; } = new Betting(); Betting split14_17 { get; set; } = new Betting(); Betting split15_18 { get; set; } = new Betting(); Betting split16_19 { get; set; } = new Betting(); Betting split17_20 { get; set; } = new Betting(); Betting split18_21 { get; set; } = new Betting(); Betting split19_22 { get; set; } = new Betting(); Betting split20_23 { get; set; } = new Betting(); Betting split21_24 { get; set; } = new Betting(); Betting split22_25 { get; set; } = new Betting(); Betting split23_26 { get; set; } = new Betting(); Betting split24_27 { get; set; } = new Betting(); Betting split25_28 { get; set; } = new Betting(); Betting split26_29 { get; set; } = new Betting(); Betting split27_30 { get; set; } = new Betting(); Betting split28_31 { get; set; } = new Betting(); Betting split29_32 { get; set; } = new Betting(); Betting split30_33 { get; set; } = new Betting(); Betting split31_34 { get; set; } = new Betting(); Betting split32_35 { get; set; } = new Betting(); Betting split33_36 { get; set; } = new Betting(); public RouletteWindow() { InitializeComponent(); lbl_Money.Content = Player.wallet; bets.Add(bet0); bets.Add(bet1); bets.Add(bet2); bets.Add(bet3); bets.Add(bet4); bets.Add(bet5); bets.Add(bet6); bets.Add(bet7); bets.Add(bet8); bets.Add(bet9); bets.Add(bet10); bets.Add(bet11); bets.Add(bet12); bets.Add(bet13); bets.Add(bet14); bets.Add(bet15); bets.Add(bet16); bets.Add(bet17); bets.Add(bet18); bets.Add(bet19); bets.Add(bet20); bets.Add(bet21); bets.Add(bet22); bets.Add(bet23); bets.Add(bet24); bets.Add(bet25); bets.Add(bet26); bets.Add(bet27); bets.Add(bet28); bets.Add(bet29); bets.Add(bet30); bets.Add(bet31); bets.Add(bet32); bets.Add(bet33); bets.Add(bet34); bets.Add(bet35); bets.Add(bet36); bets.Add(betRed); bets.Add(betBlack); bets.Add(betOdd); bets.Add(betEven); bets.Add(betHigh); bets.Add(betLow); bets.Add(betDozen1); bets.Add(betDozen2); bets.Add(betDozen3); bets.Add(betRow1); bets.Add(betRow2); bets.Add(betRow3); bets.Add(sqr1_2_4_5); bets.Add(sqr2_3_5_6); bets.Add(sqr4_5_7_8); bets.Add(sqr5_6_8_9); bets.Add(sqr7_8_10_11); bets.Add(sqr8_9_11_12); bets.Add(sqr10_11_13_14); bets.Add(sqr11_12_14_15); bets.Add(sqr13_14_16_17); bets.Add(sqr14_15_17_18); bets.Add(sqr16_17_19_20); bets.Add(sqr17_18_20_21); bets.Add(sqr19_20_22_23); bets.Add(sqr20_21_23_24); bets.Add(sqr22_23_25_26); bets.Add(sqr23_24_26_27); bets.Add(sqr25_26_28_29); bets.Add(sqr26_27_29_30); bets.Add(sqr28_29_31_32); bets.Add(sqr29_30_32_33); bets.Add(sqr31_32_34_35); bets.Add(sqr32_33_35_36); bets.Add(split1_2); bets.Add(split2_3); bets.Add(split4_5); bets.Add(split5_6); bets.Add(split7_8); bets.Add(split8_9); bets.Add(split10_11); bets.Add(split11_12); bets.Add(split13_14); bets.Add(split14_15); bets.Add(split16_17); bets.Add(split17_18); bets.Add(split19_20); bets.Add(split20_21); bets.Add(split22_23); bets.Add(split23_24); bets.Add(split25_26); bets.Add(split26_27); bets.Add(split28_29); bets.Add(split29_30); bets.Add(split31_32); bets.Add(split32_33); bets.Add(split34_35); bets.Add(split35_36); bets.Add(split1_4); bets.Add(split2_5); bets.Add(split3_6); bets.Add(split4_7); bets.Add(split5_8); bets.Add(split6_9); bets.Add(split7_10); bets.Add(split8_11); bets.Add(split9_12); bets.Add(split10_13); bets.Add(split11_14); bets.Add(split12_15); bets.Add(split13_16); bets.Add(split14_17); bets.Add(split15_18); bets.Add(split16_19); bets.Add(split17_20); bets.Add(split18_21); bets.Add(split19_22); bets.Add(split20_23); bets.Add(split21_24); bets.Add(split22_25); bets.Add(split23_26); bets.Add(split24_27); bets.Add(split25_28); bets.Add(split26_29); bets.Add(split27_30); bets.Add(split28_31); bets.Add(split29_32); bets.Add(split30_33); bets.Add(split31_34); bets.Add(split32_35); bets.Add(split33_36); } /// <summary> /// Selects spot to bet on /// Might need to return the button /// Binding, that should make this work /// </summary> public void btn0(object sender, RoutedEventArgs e) { btnSelected = 0; lbl_Bet.Content = GetButton().currentBet; } public void btn1(object sender, RoutedEventArgs e) { btnSelected = 1; lbl_Bet.Content = GetButton().currentBet; } public void btn2(object sender, RoutedEventArgs e) { btnSelected = 2; lbl_Bet.Content = GetButton().currentBet; } public void btn3(object sender, RoutedEventArgs e) { btnSelected = 3; lbl_Bet.Content = GetButton().currentBet; } public void btn4(object sender, RoutedEventArgs e) { btnSelected = 4; lbl_Bet.Content = GetButton().currentBet; } public void btn5(object sender, RoutedEventArgs e) { btnSelected = 5; lbl_Bet.Content = GetButton().currentBet; } public void btn6(object sender, RoutedEventArgs e) { btnSelected = 6; lbl_Bet.Content = GetButton().currentBet; } public void btn7(object sender, RoutedEventArgs e) { btnSelected = 7; lbl_Bet.Content = GetButton().currentBet; } public void btn8(object sender, RoutedEventArgs e) { btnSelected = 8; lbl_Bet.Content = GetButton().currentBet; } public void btn9(object sender, RoutedEventArgs e) { btnSelected = 9; lbl_Bet.Content = GetButton().currentBet; } public void btn10(object sender, RoutedEventArgs e) { btnSelected = 10; lbl_Bet.Content = GetButton().currentBet; } public void btn11(object sender, RoutedEventArgs e) { btnSelected = 11; lbl_Bet.Content = GetButton().currentBet; } public void btn12(object sender, RoutedEventArgs e) { btnSelected = 12; lbl_Bet.Content = GetButton().currentBet; } public void btn13(object sender, RoutedEventArgs e) { btnSelected = 13; lbl_Bet.Content = GetButton().currentBet; } public void btn14(object sender, RoutedEventArgs e) { btnSelected = 14; lbl_Bet.Content = GetButton().currentBet; } public void btn15(object sender, RoutedEventArgs e) { btnSelected = 15; lbl_Bet.Content = GetButton().currentBet; } public void btn16(object sender, RoutedEventArgs e) { btnSelected = 16; lbl_Bet.Content = GetButton().currentBet; } public void btn17(object sender, RoutedEventArgs e) { btnSelected = 17; lbl_Bet.Content = GetButton().currentBet; } public void btn18(object sender, RoutedEventArgs e) { btnSelected = 18; lbl_Bet.Content = GetButton().currentBet; } public void btn19(object sender, RoutedEventArgs e) { btnSelected = 19; lbl_Bet.Content = GetButton().currentBet; } public void btn20(object sender, RoutedEventArgs e) { btnSelected = 20; lbl_Bet.Content = GetButton().currentBet; } public void btn21(object sender, RoutedEventArgs e) { btnSelected = 21; lbl_Bet.Content = GetButton().currentBet; } public void btn22(object sender, RoutedEventArgs e) { btnSelected = 22; lbl_Bet.Content = GetButton().currentBet; } public void btn23(object sender, RoutedEventArgs e) { btnSelected = 23; lbl_Bet.Content = GetButton().currentBet; } public void btn24(object sender, RoutedEventArgs e) { btnSelected = 24; lbl_Bet.Content = GetButton().currentBet; } public void btn25(object sender, RoutedEventArgs e) { btnSelected = 25; lbl_Bet.Content = GetButton().currentBet; } public void btn26(object sender, RoutedEventArgs e) { btnSelected = 26; lbl_Bet.Content = GetButton().currentBet; } public void btn27(object sender, RoutedEventArgs e) { btnSelected = 27; lbl_Bet.Content = GetButton().currentBet; } public void btn28(object sender, RoutedEventArgs e) { btnSelected = 28; lbl_Bet.Content = GetButton().currentBet; } public void btn29(object sender, RoutedEventArgs e) { btnSelected = 29; lbl_Bet.Content = GetButton().currentBet; } public void btn30(object sender, RoutedEventArgs e) { btnSelected = 30; lbl_Bet.Content = GetButton().currentBet; } public void btn31(object sender, RoutedEventArgs e) { btnSelected = 31; lbl_Bet.Content = GetButton().currentBet; } public void btn32(object sender, RoutedEventArgs e) { btnSelected = 32; lbl_Bet.Content = GetButton().currentBet; } public void btn33(object sender, RoutedEventArgs e) { btnSelected = 33; lbl_Bet.Content = GetButton().currentBet; } public void btn34(object sender, RoutedEventArgs e) { btnSelected = 34; lbl_Bet.Content = GetButton().currentBet; } public void btn35(object sender, RoutedEventArgs e) { btnSelected = 35; lbl_Bet.Content = GetButton().currentBet; } public void btn36(object sender, RoutedEventArgs e) { btnSelected = 36; lbl_Bet.Content = GetButton().currentBet; } public void btnRed(object sender, RoutedEventArgs e) { btnSelected = 37; lbl_Bet.Content = GetButton().currentBet; } public void btnBlack(object sender, RoutedEventArgs e) { btnSelected = 38; lbl_Bet.Content = GetButton().currentBet; } public void btnOdd(object sender, RoutedEventArgs e) { btnSelected = 39; lbl_Bet.Content = GetButton().currentBet; } public void btnEven(object sender, RoutedEventArgs e) { btnSelected = 40; lbl_Bet.Content = GetButton().currentBet; } public void btnLow(object sender, RoutedEventArgs e) { btnSelected = 41; lbl_Bet.Content = GetButton().currentBet; } public void btnHigh(object sender, RoutedEventArgs e) { btnSelected = 42; lbl_Bet.Content = GetButton().currentBet; } public void btnDozen1(object sender, RoutedEventArgs e) { btnSelected = 43; lbl_Bet.Content = GetButton().currentBet; } public void btnDozen2(object sender, RoutedEventArgs e) { btnSelected = 44; lbl_Bet.Content = GetButton().currentBet; } public void btnDozen3(object sender, RoutedEventArgs e) { btnSelected = 45; lbl_Bet.Content = GetButton().currentBet; } public void btnRow1(object sender, RoutedEventArgs e) { btnSelected = 46; lbl_Bet.Content = GetButton().currentBet; } public void btnRow2(object sender, RoutedEventArgs e) { btnSelected = 47; lbl_Bet.Content = GetButton().currentBet; } public void btnRow3(object sender, RoutedEventArgs e) { btnSelected = 48; lbl_Bet.Content = GetButton().currentBet; } public void btn1_2_4_5(object sender, RoutedEventArgs e) { btnSelected = 49; lbl_Bet.Content = GetButton().currentBet; } public void btn2_3_5_6(object sender, RoutedEventArgs e) { btnSelected = 50; lbl_Bet.Content = GetButton().currentBet; } public void btn4_5_7_8(object sender, RoutedEventArgs e) { btnSelected = 51; lbl_Bet.Content = GetButton().currentBet; } public void btn5_6_8_9(object sender, RoutedEventArgs e) { btnSelected = 52; lbl_Bet.Content = GetButton().currentBet; } public void btn7_8_10_11(object sender, RoutedEventArgs e) { btnSelected = 53; lbl_Bet.Content = GetButton().currentBet; } public void btn8_9_11_12(object sender, RoutedEventArgs e) { btnSelected = 54; lbl_Bet.Content = GetButton().currentBet; } public void btn10_11_13_14(object sender, RoutedEventArgs e) { btnSelected = 55; lbl_Bet.Content = GetButton().currentBet; } public void btn11_12_14_15(object sender, RoutedEventArgs e) { btnSelected = 56; lbl_Bet.Content = GetButton().currentBet; } public void btn13_14_16_17(object sender, RoutedEventArgs e) { btnSelected = 57; lbl_Bet.Content = GetButton().currentBet; } public void btn14_15_17_18(object sender, RoutedEventArgs e) { btnSelected = 58; lbl_Bet.Content = GetButton().currentBet; } public void btn16_17_19_20(object sender, RoutedEventArgs e) { btnSelected = 59; lbl_Bet.Content = GetButton().currentBet; } public void btn17_18_20_21(object sender, RoutedEventArgs e) { btnSelected = 60; lbl_Bet.Content = GetButton().currentBet; } public void btn19_20_22_23(object sender, RoutedEventArgs e) { btnSelected = 61; lbl_Bet.Content = GetButton().currentBet; } public void btn20_21_23_24(object sender, RoutedEventArgs e) { btnSelected = 62; lbl_Bet.Content = GetButton().currentBet; } public void btn22_23_25_26(object sender, RoutedEventArgs e) { btnSelected = 63; lbl_Bet.Content = GetButton().currentBet; } public void btn23_24_26_27(object sender, RoutedEventArgs e) { btnSelected = 64; lbl_Bet.Content = GetButton().currentBet; } public void btn25_26_28_29(object sender, RoutedEventArgs e) { btnSelected = 65; lbl_Bet.Content = GetButton().currentBet; } public void btn26_27_29_30(object sender, RoutedEventArgs e) { btnSelected = 66; lbl_Bet.Content = GetButton().currentBet; } public void btn28_29_31_32(object sender, RoutedEventArgs e) { btnSelected = 67; lbl_Bet.Content = GetButton().currentBet; } public void btn29_30_32_33(object sender, RoutedEventArgs e) { btnSelected = 68; lbl_Bet.Content = GetButton().currentBet; } public void btn31_32_34_35(object sender, RoutedEventArgs e) { btnSelected = 69; lbl_Bet.Content = GetButton().currentBet; } public void btn32_33_35_36(object sender, RoutedEventArgs e) { btnSelected = 70; lbl_Bet.Content = GetButton().currentBet; } public void btn1_2(object sender, RoutedEventArgs e) { btnSelected = 71; lbl_Bet.Content = GetButton().currentBet; } public void btn2_3(object sender, RoutedEventArgs e) { btnSelected = 72; lbl_Bet.Content = GetButton().currentBet; } public void btn4_5(object sender, RoutedEventArgs e) { btnSelected = 73; lbl_Bet.Content = GetButton().currentBet; } public void btn5_6(object sender, RoutedEventArgs e) { btnSelected = 74; lbl_Bet.Content = GetButton().currentBet; } public void btn7_8(object sender, RoutedEventArgs e) { btnSelected = 75; lbl_Bet.Content = GetButton().currentBet; } public void btn8_9(object sender, RoutedEventArgs e) { btnSelected = 76; lbl_Bet.Content = GetButton().currentBet; } public void btn10_11(object sender, RoutedEventArgs e) { btnSelected = 77; lbl_Bet.Content = GetButton().currentBet; } public void btn11_12(object sender, RoutedEventArgs e) { btnSelected = 78; lbl_Bet.Content = GetButton().currentBet; } public void btn13_14(object sender, RoutedEventArgs e) { btnSelected = 79; lbl_Bet.Content = GetButton().currentBet; } public void btn14_15(object sender, RoutedEventArgs e) { btnSelected = 80; lbl_Bet.Content = GetButton().currentBet; } public void btn16_17(object sender, RoutedEventArgs e) { btnSelected = 81; lbl_Bet.Content = GetButton().currentBet; } public void btn17_18(object sender, RoutedEventArgs e) { btnSelected = 82; lbl_Bet.Content = GetButton().currentBet; } public void btn19_20(object sender, RoutedEventArgs e) { btnSelected = 83; lbl_Bet.Content = GetButton().currentBet; } public void btn20_21(object sender, RoutedEventArgs e) { btnSelected = 84; lbl_Bet.Content = GetButton().currentBet; } public void btn22_23(object sender, RoutedEventArgs e) { btnSelected = 85; lbl_Bet.Content = GetButton().currentBet; } public void btn23_24(object sender, RoutedEventArgs e) { btnSelected = 86; lbl_Bet.Content = GetButton().currentBet; } public void btn25_26(object sender, RoutedEventArgs e) { btnSelected = 87; lbl_Bet.Content = GetButton().currentBet; } public void btn26_27(object sender, RoutedEventArgs e) { btnSelected = 88; lbl_Bet.Content = GetButton().currentBet; } public void btn28_29(object sender, RoutedEventArgs e) { btnSelected = 89; lbl_Bet.Content = GetButton().currentBet; } public void btn29_30(object sender, RoutedEventArgs e) { btnSelected = 90; lbl_Bet.Content = GetButton().currentBet; } public void btn31_32(object sender, RoutedEventArgs e) { btnSelected = 91; lbl_Bet.Content = GetButton().currentBet; } public void btn32_33(object sender, RoutedEventArgs e) { btnSelected = 92; lbl_Bet.Content = GetButton().currentBet; } public void btn34_35(object sender, RoutedEventArgs e) { btnSelected = 93; lbl_Bet.Content = GetButton().currentBet; } public void btn35_36(object sender, RoutedEventArgs e) { btnSelected = 94; lbl_Bet.Content = GetButton().currentBet; } public void btn1_4(object sender, RoutedEventArgs e) { btnSelected = 95; lbl_Bet.Content = GetButton().currentBet; } public void btn2_5(object sender, RoutedEventArgs e) { btnSelected = 96; lbl_Bet.Content = GetButton().currentBet; } public void btn3_6(object sender, RoutedEventArgs e) { btnSelected = 97; lbl_Bet.Content = GetButton().currentBet; } public void btn4_7(object sender, RoutedEventArgs e) { btnSelected = 98; lbl_Bet.Content = GetButton().currentBet; } public void btn5_8(object sender, RoutedEventArgs e) { btnSelected = 99; lbl_Bet.Content = GetButton().currentBet; } public void btn6_9(object sender, RoutedEventArgs e) { btnSelected = 100; lbl_Bet.Content = GetButton().currentBet; } public void btn7_10(object sender, RoutedEventArgs e) { btnSelected = 101; lbl_Bet.Content = GetButton().currentBet; } public void btn8_11(object sender, RoutedEventArgs e) { btnSelected = 102; lbl_Bet.Content = GetButton().currentBet; } public void btn9_12(object sender, RoutedEventArgs e) { btnSelected = 103; lbl_Bet.Content = GetButton().currentBet; } public void btn10_13(object sender, RoutedEventArgs e) { btnSelected = 104; lbl_Bet.Content = GetButton().currentBet; } public void btn11_14(object sender, RoutedEventArgs e) { btnSelected = 105; lbl_Bet.Content = GetButton().currentBet; } public void btn12_15(object sender, RoutedEventArgs e) { btnSelected = 106; lbl_Bet.Content = GetButton().currentBet; } public void btn13_16(object sender, RoutedEventArgs e) { btnSelected = 107; lbl_Bet.Content = GetButton().currentBet; } public void btn14_17(object sender, RoutedEventArgs e) { btnSelected = 108; lbl_Bet.Content = GetButton().currentBet; } public void btn15_18(object sender, RoutedEventArgs e) { btnSelected = 109; lbl_Bet.Content = GetButton().currentBet; } public void btn16_19(object sender, RoutedEventArgs e) { btnSelected = 110; lbl_Bet.Content = GetButton().currentBet; } public void btn17_20(object sender, RoutedEventArgs e) { btnSelected = 111; lbl_Bet.Content = GetButton().currentBet; } public void btn18_21(object sender, RoutedEventArgs e) { btnSelected = 112; lbl_Bet.Content = GetButton().currentBet; } public void btn19_22(object sender, RoutedEventArgs e) { btnSelected = 113; lbl_Bet.Content = GetButton().currentBet; } public void btn20_23(object sender, RoutedEventArgs e) { btnSelected = 114; lbl_Bet.Content = GetButton().currentBet; } public void btn21_24(object sender, RoutedEventArgs e) { btnSelected = 115; lbl_Bet.Content = GetButton().currentBet; } public void btn22_25(object sender, RoutedEventArgs e) { btnSelected = 116; lbl_Bet.Content = GetButton().currentBet; } public void btn23_26(object sender, RoutedEventArgs e) { btnSelected = 117; lbl_Bet.Content = GetButton().currentBet; } public void btn24_27(object sender, RoutedEventArgs e) { btnSelected = 118; lbl_Bet.Content = GetButton().currentBet; } public void btn25_28(object sender, RoutedEventArgs e) { btnSelected = 119; lbl_Bet.Content = GetButton().currentBet; } public void btn26_29(object sender, RoutedEventArgs e) { btnSelected = 120; lbl_Bet.Content = GetButton().currentBet; } public void btn27_30(object sender, RoutedEventArgs e) { btnSelected = 121; lbl_Bet.Content = GetButton().currentBet; } public void btn28_31(object sender, RoutedEventArgs e) { btnSelected = 122; lbl_Bet.Content = GetButton().currentBet; } public void btn29_32(object sender, RoutedEventArgs e) { btnSelected = 123; lbl_Bet.Content = GetButton().currentBet; } public void btn30_33(object sender, RoutedEventArgs e) { btnSelected = 124; lbl_Bet.Content = GetButton().currentBet; } public void btn31_34(object sender, RoutedEventArgs e) { btnSelected = 125; lbl_Bet.Content = GetButton().currentBet; } public void btn32_35(object sender, RoutedEventArgs e) { btnSelected = 126; lbl_Bet.Content = GetButton().currentBet; } public void btn33_36(object sender, RoutedEventArgs e) { btnSelected = 127; lbl_Bet.Content = GetButton().currentBet; } private Betting GetButton() { switch (btnSelected) { case 0: return bet0; case 1: return bet1; case 2: return bet2; case 3: return bet3; case 4: return bet4; case 5: return bet5; case 6: return bet6; case 7: return bet7; case 8: return bet8; case 9: return bet9; case 10: return bet10; case 11: return bet11; case 12: return bet12; case 13: return bet13; case 14: return bet14; case 15: return bet15; case 16: return bet16; case 17: return bet17; case 18: return bet18; case 19: return bet19; case 20: return bet20; case 21: return bet21; case 22: return bet22; case 23: return bet23; case 24: return bet24; case 25: return bet25; case 26: return bet26; case 27: return bet27; case 28: return bet28; case 29: return bet29; case 30: return bet30; case 31: return bet32; case 32: return bet32; case 33: return bet33; case 34: return bet34; case 35: return bet35; case 36: return bet36; case 37: return betRed; case 38: return betBlack; case 39: return betOdd; case 40: return betEven; case 41: return betLow; case 42: return betHigh; case 43: return betDozen1; case 44: return betDozen2; case 45: return betDozen3; case 46: return betRow1; case 47: return betRow2; case 48: return betRow3; case 49: return sqr1_2_4_5; case 50: return sqr2_3_5_6; case 51: return sqr4_5_7_8; case 52: return sqr5_6_8_9; case 53: return sqr7_8_10_11; case 54: return sqr8_9_11_12; case 55: return sqr10_11_13_14; case 56: return sqr11_12_14_15; case 57: return sqr13_14_16_17; case 58: return sqr14_15_17_18; case 59: return sqr16_17_19_20; case 60: return sqr17_18_20_21; case 61: return sqr19_20_22_23; case 62: return sqr20_21_23_24; case 63: return sqr22_23_25_26; case 64: return sqr23_24_26_27; case 65: return sqr25_26_28_29; case 66: return sqr26_27_29_30; case 67: return sqr28_29_31_32; case 68: return sqr29_30_32_33; case 69: return sqr31_32_34_35; case 70: return sqr32_33_35_36; case 71: return split1_2; case 72: return split2_3; case 73: return split4_5; case 74: return split5_6; case 75: return split7_8; case 76: return split8_9; case 77: return split10_11; case 78: return split11_12; case 79: return split13_14; case 80: return split14_15; case 81: return split16_17; case 82: return split17_18; case 83: return split19_20; case 84: return split20_21; case 85: return split22_23; case 86: return split23_24; case 87: return split25_26; case 88: return split26_27; case 89: return split28_29; case 90: return split29_30; case 91: return split31_32; case 92: return split32_33; case 93: return split34_35; case 94: return split35_36; case 95: return split1_4; case 96: return split2_5; case 97: return split3_6; case 98: return split4_7; case 99: return split5_8; case 100: return split6_9; case 101: return split7_10; case 102: return split8_11; case 103: return split9_12; case 104: return split10_13; case 105: return split11_14; case 106: return split12_15; case 107: return split13_16; case 108: return split14_17; case 109: return split15_18; case 110: return split16_19; case 111: return split17_20; case 112: return split18_21; case 113: return split19_22; case 114: return split20_23; case 115: return split21_24; case 116: return split22_25; case 117: return split23_26; case 118: return split24_27; case 119: return split25_28; case 120: return split26_29; case 121: return split27_30; case 122: return split28_31; case 123: return split29_32; case 124: return split30_33; case 125: return split31_34; case 126: return split32_35; case 127: return split33_36; default: return null; } } private void bet_1(object sender, RoutedEventArgs e) { if (btnSelected == -1) { lbl_InvalidBet.Content = "Select a place to bet on"; } else if (GetButton().currentBet < 10000 && totalBet < 200000) { if (!GetButton().Bet(1)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; totalBet += 1; } lbl_Bet.Content = GetButton().currentBet; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } else if (totalBet == 200000) { lbl_InvalidBet.Content = "You've reached the Betting Limit"; } else if (GetButton().currentBet == 10000) { lbl_InvalidBet.Content = "Bet somewhere else"; } } private void bet_5(object sender, RoutedEventArgs e) { if (btnSelected == -1) { lbl_InvalidBet.Content = "Select a place to bet on"; } else if (GetButton().currentBet <= 9995 && totalBet <= 199995) { if (!GetButton().Bet(5)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; totalBet += 5; } lbl_Bet.Content = GetButton().currentBet; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } else if (totalBet == 200000) { lbl_InvalidBet.Content = "You've reached the Betting Limit"; } else if (GetButton().currentBet == 10000) { lbl_InvalidBet.Content = "Bet somewhere else"; } } private void bet_10(object sender, RoutedEventArgs e) { if (btnSelected == -1) { lbl_InvalidBet.Content = "Select a place to bet on"; } else if (GetButton().currentBet <= 9990 && totalBet <= 199990) { if (!GetButton().Bet(10)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; totalBet += 10; } lbl_Bet.Content = GetButton().currentBet; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } else if (totalBet == 200000) { lbl_InvalidBet.Content = "You've reached the Betting Limit"; } else if (GetButton().currentBet == 10000) { lbl_InvalidBet.Content = "Bet somewhere else"; } } private void bet_20(object sender, RoutedEventArgs e) { if (btnSelected == -1) { lbl_InvalidBet.Content = "Select a place to bet on"; } else if (GetButton().currentBet <= 9980 && totalBet <= 199980) { if (!GetButton().Bet(20)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; totalBet += 20; } lbl_Bet.Content = GetButton().currentBet; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } else if (totalBet == 200000) { lbl_InvalidBet.Content = "You've reached the Betting Limit"; } else if (GetButton().currentBet == 10000) { lbl_InvalidBet.Content = "Bet somewhere else"; } } private void bet_50(object sender, RoutedEventArgs e) { if (btnSelected == -1) { lbl_InvalidBet.Content = "Select a place to bet on"; } else if (GetButton().currentBet <= 9950 && totalBet <= 199950) { if (!GetButton().Bet(50)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; totalBet += 50; } lbl_Bet.Content = GetButton().currentBet; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } else if (totalBet == 200000) { lbl_InvalidBet.Content = "You've reached the Betting Limit"; } else if (GetButton().currentBet == 10000) { lbl_InvalidBet.Content = "Bet somewhere else"; } } private void bet_100(object sender, RoutedEventArgs e) { if (btnSelected == -1) { lbl_InvalidBet.Content = "Select a place to bet on"; } else if (GetButton().currentBet <= 9900 && totalBet <= 199900) { if (!GetButton().Bet(100)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; totalBet += 100; } lbl_Bet.Content = GetButton().currentBet; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } else if (totalBet == 200000) { lbl_InvalidBet.Content = "You've reached the Betting Limit"; } else if (GetButton().currentBet == 10000) { lbl_InvalidBet.Content = "Bet somewhere else"; } } private void bet_500(object sender, RoutedEventArgs e) { if (btnSelected == -1) { lbl_InvalidBet.Content = "Select a place to bet on"; } else if (GetButton().currentBet <= 9500 && totalBet <= 199500) { if (!GetButton().Bet(500)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; totalBet += 500; } lbl_Bet.Content = GetButton().currentBet; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } else if (totalBet == 200000) { lbl_InvalidBet.Content = "You've reached the Betting Limit"; } else if (GetButton().currentBet == 10000) { lbl_InvalidBet.Content = "Bet somewhere else"; } } private void bet_1000(object sender, RoutedEventArgs e) { if (btnSelected == -1) { lbl_InvalidBet.Content = "Select a place to bet on"; } else if (GetButton().currentBet <= 8000 && totalBet <= 198000) { if (!GetButton().Bet(1000)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; totalBet += 1000; } lbl_Bet.Content = GetButton().currentBet; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } else if (totalBet == 200000) { lbl_InvalidBet.Content = "You've reached the Betting Limit"; } else if (GetButton().currentBet == 10000) { lbl_InvalidBet.Content = "Bet somewhere else"; } } private void bet_5000(object sender, RoutedEventArgs e) { if (btnSelected == -1) { lbl_InvalidBet.Content = "Select a place to bet on"; } else if (GetButton().currentBet <= 5000 && totalBet <= 195000) { if (!GetButton().Bet(5000)) { lbl_InvalidBet.Content = "Not Enough Money"; } else { lbl_InvalidBet.Content = ""; totalBet += 5000; } lbl_Bet.Content = GetButton().currentBet; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } else if (totalBet == 200000) { lbl_InvalidBet.Content = "You've reached the Betting Limit"; } else if (GetButton().currentBet == 10000) { lbl_InvalidBet.Content = "Bet somewhere else"; } } private void PlayRoulette(object sender, RoutedEventArgs e) { Random rand = new Random(); int result = rand.Next(0, 37); //Display where the ball landed (on the number == result) lbl_Result.Content = $"Last result: {result}"; PayoutRoulette(result); //PayoutRoulette(23); lbl_Bet.Content = bet1.currentBet; totalBet = 0; lbl_TotalBet.Content = totalBet; lbl_Money.Content = Player.wallet; } public void PayoutRoulette(int result) { switch (result) { case 0: bet0.Payout(40); break; case 1: bet1.Payout(36); betRed.Payout(1); betOdd.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow3.Payout(3); sqr1_2_4_5.Payout(9); split1_2.Payout(18); split1_4.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 2: bet2.Payout(36); betBlack.Payout(1); betEven.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow2.Payout(3); sqr1_2_4_5.Payout(9); sqr2_3_5_6.Payout(9); split1_2.Payout(18); split2_3.Payout(18); split2_5.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 3: bet3.Payout(36); betRed.Payout(1); betOdd.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow1.Payout(3); sqr2_3_5_6.Payout(9); split2_3.Payout(18); split3_6.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 4: bet4.Payout(36); betBlack.Payout(1); betEven.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow3.Payout(3); sqr1_2_4_5.Payout(9); sqr4_5_7_8.Payout(9); split1_4.Payout(18); split4_5.Payout(18); split4_7.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 5: bet5.Payout(36); betRed.Payout(1); betOdd.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow2.Payout(3); sqr1_2_4_5.Payout(9); sqr4_5_7_8.Payout(9); sqr2_3_5_6.Payout(9); sqr5_6_8_9.Payout(9); split2_5.Payout(18); split4_5.Payout(18); split5_6.Payout(18); split5_8.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 6: bet6.Payout(36); betBlack.Payout(1); betEven.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow1.Payout(3); sqr2_3_5_6.Payout(9); sqr5_6_8_9.Payout(9); split3_6.Payout(18); split5_6.Payout(18); split6_9.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 7: bet7.Payout(36); betRed.Payout(1); betOdd.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow3.Payout(3); sqr4_5_7_8.Payout(9); sqr7_8_10_11.Payout(9); split4_7.Payout(18); split7_8.Payout(18); split7_10.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 8: bet8.Payout(36); betBlack.Payout(1); betEven.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow1.Payout(3); sqr4_5_7_8.Payout(9); sqr5_6_8_9.Payout(9); sqr7_8_10_11.Payout(9); sqr8_9_11_12.Payout(9); split5_8.Payout(18); split7_8.Payout(18); split8_9.Payout(18); split8_11.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 9: bet9.Payout(36); betRed.Payout(1); betOdd.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow1.Payout(3); sqr5_6_8_9.Payout(9); sqr8_9_11_12.Payout(9); split6_9.Payout(18); split8_9.Payout(18); split9_12.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 10: bet10.Payout(36); betBlack.Payout(1); betEven.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow3.Payout(3); sqr7_8_10_11.Payout(9); sqr10_11_13_14.Payout(9); split7_10.Payout(18); split10_11.Payout(18); split10_13.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 11: bet11.Payout(36); betBlack.Payout(1); betOdd.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow2.Payout(3); sqr7_8_10_11.Payout(9); sqr8_9_11_12.Payout(9); sqr10_11_13_14.Payout(9); sqr11_12_14_15.Payout(9); split8_11.Payout(18); split10_11.Payout(18); split11_12.Payout(18); split11_14.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 12: bet12.Payout(36); betRed.Payout(1); betEven.Payout(1); betLow.Payout(1); betDozen1.Payout(3); betRow1.Payout(3); sqr8_9_11_12.Payout(9); sqr11_12_14_15.Payout(9); split9_12.Payout(18); split11_12.Payout(18); split12_15.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 13: bet13.Payout(36); betBlack.Payout(1); betOdd.Payout(1); betLow.Payout(1); betDozen2.Payout(3); betRow3.Payout(3); sqr10_11_13_14.Payout(9); sqr13_14_16_17.Payout(9); split10_13.Payout(18); split13_14.Payout(18); split13_16.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 14: bet14.Payout(36); betRed.Payout(1); betEven.Payout(1); betLow.Payout(1); betDozen2.Payout(3); betRow2.Payout(3); sqr10_11_13_14.Payout(9); sqr11_12_14_15.Payout(9); sqr13_14_16_17.Payout(9); sqr14_15_17_18.Payout(9); split11_14.Payout(18); split13_14.Payout(18); split14_15.Payout(18); split14_17.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 15: bet15.Payout(36); betBlack.Payout(1); betOdd.Payout(1); betLow.Payout(1); betDozen2.Payout(3); betRow1.Payout(3); sqr11_12_14_15.Payout(9); sqr14_15_17_18.Payout(9); split12_15.Payout(18); split14_15.Payout(18); split15_18.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 16: bet16.Payout(36); betRed.Payout(1); betEven.Payout(1); betLow.Payout(1); betDozen2.Payout(3); betRow3.Payout(3); sqr13_14_16_17.Payout(9); sqr16_17_19_20.Payout(9); split13_16.Payout(18); split16_17.Payout(18); split16_19.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 17: bet17.Payout(36); betBlack.Payout(1); betOdd.Payout(1); betLow.Payout(1); betDozen2.Payout(3); betRow2.Payout(3); sqr13_14_16_17.Payout(9); sqr14_15_17_18.Payout(9); sqr16_17_19_20.Payout(9); sqr17_18_20_21.Payout(9); split14_17.Payout(18); split16_17.Payout(18); split17_18.Payout(18); split17_20.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 18: bet18.Payout(36); betRed.Payout(1); betEven.Payout(1); betLow.Payout(1); betDozen2.Payout(3); betRow1.Payout(3); sqr14_15_17_18.Payout(9); sqr17_18_20_21.Payout(9); split15_18.Payout(18); split17_18.Payout(18); split18_21.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 19: bet19.Payout(36); betRed.Payout(1); betOdd.Payout(1); betHigh.Payout(1); betDozen2.Payout(3); betRow3.Payout(3); sqr16_17_19_20.Payout(9); sqr19_20_22_23.Payout(9); split16_19.Payout(18); split19_20.Payout(18); split19_22.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 20: bet20.Payout(36); betBlack.Payout(1); betEven.Payout(1); betHigh.Payout(1); betDozen2.Payout(3); betRow2.Payout(3); sqr16_17_19_20.Payout(9); sqr17_18_20_21.Payout(9); sqr19_20_22_23.Payout(9); sqr20_21_23_24.Payout(9); split17_20.Payout(18); split19_20.Payout(18); split20_21.Payout(18); split20_23.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 21: bet21.Payout(36); betRed.Payout(1); betOdd.Payout(1); betHigh.Payout(1); betDozen2.Payout(3); betRow1.Payout(3); sqr17_18_20_21.Payout(9); sqr20_21_23_24.Payout(9); split18_21.Payout(18); split20_21.Payout(18); split21_24.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 22: bet22.Payout(36); betBlack.Payout(1); betEven.Payout(1); betHigh.Payout(1); betDozen2.Payout(3); betRow3.Payout(3); sqr19_20_22_23.Payout(9); sqr22_23_25_26.Payout(9); split19_22.Payout(18); split22_23.Payout(18); split22_25.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 23: if(bet23.currentBet != 0 && betRed.currentBet != 0 && betHigh.currentBet != 0 && betDozen2.currentBet != 0 && betRow2.currentBet != 0 && sqr19_20_22_23.currentBet != 0 && sqr20_21_23_24.currentBet != 0 && sqr22_23_25_26.currentBet != 0 && sqr23_24_26_27.currentBet != 0 && split20_23.currentBet != 0 && split22_23.currentBet != 0 && split23_24.currentBet != 0 && split23_26.currentBet != 0) { //insert the clip/audio of Arin screaming for winning the Fortress on 23 } bet23.Payout(36); betRed.Payout(1); betOdd.Payout(1); betHigh.Payout(1); betDozen2.Payout(3); betRow2.Payout(3); sqr19_20_22_23.Payout(9); sqr20_21_23_24.Payout(9); sqr22_23_25_26.Payout(9); sqr23_24_26_27.Payout(9); split20_23.Payout(18); split22_23.Payout(18); split23_24.Payout(18); split23_26.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 24: bet24.Payout(36); betBlack.Payout(1); betEven.Payout(1); betHigh.Payout(1); betDozen2.Payout(3); betRow1.Payout(3); sqr20_21_23_24.Payout(9); sqr23_24_26_27.Payout(9); split21_24.Payout(18); split23_24.Payout(18); split24_27.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 25: bet25.Payout(36); betRed.Payout(1); betOdd.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow3.Payout(3); sqr22_23_25_26.Payout(9); sqr25_26_28_29.Payout(9); split22_25.Payout(18); split25_26.Payout(18); split25_28.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 26: bet26.Payout(36); betBlack.Payout(1); betEven.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow2.Payout(3); sqr22_23_25_26.Payout(9); sqr23_24_26_27.Payout(9); sqr25_26_28_29.Payout(9); sqr26_27_29_30.Payout(9); split23_26.Payout(18); split25_26.Payout(18); split26_27.Payout(18); split26_29.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 27: bet27.Payout(36); betRed.Payout(1); betOdd.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow1.Payout(3); sqr23_24_26_27.Payout(9); sqr26_27_29_30.Payout(9); split24_27.Payout(18); split26_27.Payout(18); split27_30.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 28: bet28.Payout(36); betBlack.Payout(1); betEven.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow3.Payout(3); sqr25_26_28_29.Payout(9); sqr28_29_31_32.Payout(9); split25_28.Payout(18); split28_29.Payout(18); split28_31.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 29: bet29.Payout(36); betBlack.Payout(1); betOdd.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow2.Payout(3); sqr25_26_28_29.Payout(9); sqr26_27_29_30.Payout(9); sqr28_29_31_32.Payout(9); sqr29_30_32_33.Payout(9); split26_29.Payout(18); split28_29.Payout(18); split29_30.Payout(18); split29_32.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 30: bet30.Payout(36); betRed.Payout(1); betEven.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow1.Payout(3); sqr26_27_29_30.Payout(9); sqr29_30_32_33.Payout(9); split27_30.Payout(18); split29_30.Payout(18); split30_33.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 31: bet31.Payout(36); betBlack.Payout(1); betOdd.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow3.Payout(3); sqr28_29_31_32.Payout(9); sqr31_32_34_35.Payout(9); split28_31.Payout(18); split31_32.Payout(18); split31_34.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 32: bet32.Payout(36); betRed.Payout(1); betEven.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow2.Payout(3); sqr28_29_31_32.Payout(9); sqr29_30_32_33.Payout(9); sqr31_32_34_35.Payout(9); sqr32_33_35_36.Payout(9); split29_32.Payout(18); split31_32.Payout(18); split32_33.Payout(18); split32_35.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 33: bet33.Payout(36); betBlack.Payout(1); betOdd.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow1.Payout(3); sqr29_30_32_33.Payout(9); sqr32_33_35_36.Payout(9); split30_33.Payout(18); split32_33.Payout(18); split33_36.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 34: bet34.Payout(36); betRed.Payout(1); betEven.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow3.Payout(3); sqr31_32_34_35.Payout(9); split31_34.Payout(18); split34_35.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 35: bet35.Payout(36); betBlack.Payout(1); betOdd.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow2.Payout(3); sqr31_32_34_35.Payout(9); sqr32_33_35_36.Payout(9); split32_35.Payout(18); split34_35.Payout(18); split35_36.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; case 36: bet36.Payout(36); betRed.Payout(1); betEven.Payout(1); betHigh.Payout(1); betDozen3.Payout(3); betRow1.Payout(3); sqr32_33_35_36.Payout(9); split33_36.Payout(18); split35_36.Payout(18); bets.ForEach(bet => bet.currentBet = 0); break; default: break; } } private void Back_Click(object sender, RoutedEventArgs e) { if (totalBet == 0) { MainWindow mainWindow = new MainWindow(); mainWindow.Show(); Close(); } else { lbl_InvalidBet.Content = "Cannot exit while betting"; } } private void Rules_Click(object sender, RoutedEventArgs e) { RulesPopup.IsOpen = true; RulesTxt.Text = "Start by selecting the space you are betting on\n" + "Select the chips you plan on betting\n" + "You can’t place more than $10,000 on a given space\n" + "You can select more places to bet\n" + "You can’t bet more than $200,000 on the board\n" + "Press the play button to start the roulette wheel\n" + "You can’t leave the game if you have placed bets on the board"; } private void Rules_Exit(object sender, RoutedEventArgs e) { RulesPopup.IsOpen = false; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CasinoSim.Static_Classes { public class Betting { public int currentBet = 0; public bool Bet(int bet) { bool isValid = false; if (Player.wallet >= bet) { currentBet += bet; Player.wallet -= bet; isValid = true; } return isValid; } public void Payout(int multiplier) { Player.wallet += currentBet + (currentBet * multiplier); currentBet = 0; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CasinoSim.Static_Classes { public static class Player { public static int wallet = 0; public static int netWorth = 0; } }
19ab2625b6fde108eff8d35400764ffc376bc144
[ "C#" ]
9
C#
SebCushman/CasinoSim
a02438ba3ac55a0fca06871371938a4758830ed7
e9daeff6dc36f89414528ed4eb1fb2ce9e607833
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """Logical to Physical Mappers""" import collections from .logging import get_logger from .errors import * __all__ = ( "Mapper", ) class Mapper(object): """Mapper is core clas for translating logical model to physical database schema. """ # WARNING: do not put any SQL/engine/connection related stuff into this # class yet. It might be moved to the cubes as one of top-level modules # and subclassed here. def __init__(self, cube, locale=None, schema=None, fact_name=None, **options): """Abstract class for mappers which maps logical references to physical references (tables and columns). Attributes: * `cube` - mapped cube * `simplify_dimension_references` – references for flat dimensions (with one level and no details) will be just dimension names, no attribute name. Might be useful when using single-table schema, for example, with couple of one-column dimensions. * `fact_name` – fact name, if not specified then `cube.name` is used * `schema` – default database schema """ super(Mapper, self).__init__() if cube == None: raise Exception("Cube for mapper should not be None.") self.logger = get_logger() self.cube = cube # TODO: merge with mappings received as arguments self.mappings = self.cube.mappings self.locale = locale # TODO: remove this (should be in SQL only) if "simplify_dimension_references" in options: self.simplify_dimension_references = options["simplify_dimension_references"] else: self.simplify_dimension_references = True self._collect_attributes() def _collect_attributes(self): """Collect all cube attributes and create a dictionary where keys are logical references and values are `cubes.model.Attribute` objects. This method should be used after each cube or mappings change. """ self.attributes = collections.OrderedDict() for attr in self.cube.all_attributes: self.attributes[self.logical(attr)] = attr def set_locale(self, locale): """Change the mapper's locale""" self.locale = locale self._collect_attributes() # TODO: depreciate in favor of Cube.all_attributes def all_attributes(self, expand_locales=False): """Return a list of all attributes of a cube. If `expand_locales` is ``True``, then localized logical reference is returned for each attribute's locale.""" return self.attributes.values() # TODO: depreciate in favor of Cube.attribute def attribute(self, name): """Returns an attribute with logical reference `name`. """ # TODO: If attribute is not found, returns `None` (yes or no?) return self.attributes[name] def logical(self, attribute, locale=None): """Returns logical reference as string for `attribute` in `dimension`. If `dimension` is ``Null`` then fact table is assumed. The logical reference might have following forms: * ``dimension.attribute`` - dimension attribute * ``attribute`` - fact measure or detail If `simplify_dimension_references` is ``True`` then references for flat dimensios without details is `dimension`. If `locale` is specified, then locale is added to the reference. This is used by backends and other mappers, it has no real use in end-user browsing. """ reference = attribute.ref(self.simplify_dimension_references, locale) return reference def split_logical(self, reference): """Returns tuple (`dimension`, `attribute`) from `logical_reference` string. Syntax of the string is: ``dimensions.attribute``.""" split = reference.split(".") if len(split) > 1: dim_name = split[0] attr_name = ".".join(split[1:]) return (dim_name, attr_name) else: return (None, reference) def physical(self, attribute, locale=None): """Returns physical reference for attribute. Returned value is backend specific. Default implementation returns a value from the mapping dictionary. This method should be implemented by `Mapper` subclasses. """ return self.mappings.get(self.logical(attribute, locale)) <file_sep>from denormalizer import * from browser import * from store import * __all__ = [] __all__ += denormalizer.__all__ __all__ += browser.__all__ __all__ += store.__all__ <file_sep>***************************** Aggregation Browsing Backends ***************************** Backends for browsing aggregates of various data sources SQL === SQL backend uses SQLAlchemy for generating queries. It supports all databases that the SQLAlchemy supports such as: * Drizzle * Firebird * Informix * Microsoft SQL Server * MySQL * Oracle * PostgreSQL * SQLite * Sybase Browser ------- .. autoclass:: cubes.backends.sql.browser.SnowflakeBrowser .. autoclass:: cubes.backends.sql.query.QueryBuilder Slicer ====== .. autoclass:: cubes.backends.slicer.SlicerBrowser Mixpanel ======== .. autoclass:: cubes.backends.mixpanel.browser.MixpanelBrowser Mongo DB ======== .. autoclass:: cubes.backends.mongo2.browser.Mongo2Browser <file_sep>========= slicer ========= ------------------------------------- Cubes command line utility and server ------------------------------------- :Author: <NAME> <<EMAIL>> :Date: 2012-11-13 :Copyright: MIT :Version: 0.1 :Manual section: 1 SYNOPSIS ======== **slicer** command [options] | **slicer** model validate [-d|--defaults] [-w|--no-warnings] [-t|--translation *translation*] | **slicer** serve *config.ini* | **slicer** extract_locale | **slicer** translate | **slicer** test | **slicer** ddl [--dimension-prefix dimension_prefix] [--fact_prefix *prefix*] [--backend *backend*] *url* *model* | **slicer** denormalize [-p *prefix*] [-f|--force] [-m|materialize] [-i|--index] [-s|--schema *schema*] [-c|--cube *cube*] *config.ini* DESCRIPTION =========== slicer is a command-line front ent to many of cubes functionalities, from model validation to local server. OPTIONS ======= --help, -h Show this help message and exit. COMMANDS ======== serve ----- Run Cubes OLAP HTTP server. Example server configuration file ``slicer.ini``:: [server] host: localhost port: 5000 reload: yes log_level: info [workspace] url: sqlite:///tutorial.sqlite view_prefix: vft_ [model] path: models/model_04.json To run local server:: slicer serve slicer.ini In the ``[server]`` section, space separated list of modules to be imported can be specified under option ``modules``:: [server] modules=cutom_backend ... For more information about OLAP HTTP server see cubes documentation. model validate -------------- Usage:: slicer model validate /path/to/model/directory slicer model validate model.json slicer model validate http://somesite.com/model.json Optional arguments:: -d, --defaults show defaults -w, --no-warnings disable warnings -t TRANSLATION, --translation TRANSLATION model translation file Example output:: loading model wdmmg_model.json ------------------------- cubes: 1 wdmmg dimensions: 5 date pog region cofog from ------------------------- found 3 issues validation results: warning: No hierarchies in dimension 'date', flat level 'year' will be used warning: Level 'year' in dimension 'date' has no key attribute specified warning: Level 'from' in dimension 'from' has no key attribute specified 0 errors, 3 warnings The tool output contains recommendation whether the model can be used: * `model can be used` - if there are no errors, no warnings and no defaults used, mostly when the model is explicitly described in every detail * `model can be used, make sure that defaults reflect reality` - there are no errors, no warnings, but the model might be not complete and default assumptions are applied * `not recommended to use the model, some issues might emerge` - there are just warnings, no validation errors. Some queries or any other operations might produce invalid or unexpected output * `model can not be used` - model contain errors and it is unusable model json ---------- For any given input model produce reusable JSON model. model extract_locale -------------------- Extract localizable parts of the model. Use this before you start translating the model to get translation template. model translate --------------- Translate model using translation file:: slicer model translate model.json translation.json ddl --- .. note:: This is experimental command. Generates DDL schema of a model for SQL backend Usage:: slicer ddl [-h] [--dimension-prefix DIMENSION_PREFIX] [--fact-prefix FACT_PREFIX] [--backend BACKEND] url model positional arguments:: url SQL database connection URL model model reference - can be a local file path or URL optional arguments:: --dimension-prefix DIMENSION_PREFIX prefix for dimension tables --fact-prefix FACT_PREFIX prefix for fact tables --backend BACKEND backend name (currently limited only to SQL backends) denormalize ----------- Usage:: slicer denormalize [-h] [-p PREFIX] [-f] [-m] [-i] [-s SCHEMA] [-c CUBE] config positional arguments:: config slicer confuguration .ini file optional arguments:: -h, --help show this help message and exit -p PREFIX, --prefix PREFIX prefix for denormalized views (overrides config value) -f, --force replace existing views -m, --materialize create materialized view (table) -i, --index create index for key attributes -s SCHEMA, --schema SCHEMA target view schema (overrides config value) -c CUBE, --cube CUBE cube(s) to be denormalized, if not specified then all in the model Examples ~~~~~~~~ If you plan to use denormalized views, you have to specify it in the configuration in the ``[workspace]`` section:: [workspace] denormalized_view_prefix = mft_ denormalized_view_schema = denorm_views # This switch is used by the browser: use_denormalization = yes The denormalization will create tables like ``denorm_views.mft_contracts`` for a cube named ``contracts``. The browser will use the view if option ``use_denormalization`` is set to a true value. Denormalize all cubes in the model:: slicer denormalize slicer.ini Denormalize only one cube:: slicer denormalize -c contracts slicer.ini Create materialized denormalized view with indexes:: slicer denormalize --materialize --index slicer.ini Replace existing denormalized view of a cube:: slicer denormalize --force -c contracts slicer.ini Schema ~~~~~~ Schema where denormalized view is created is schema specified in the configuration file. Schema is shared with fact tables and views. If you want to have views in separate schema, specify ``denormalized_view_schema`` option in the configuration. If for any specific reason you would like to denormalize into a completely different schema than specified in the configuration, you can specify it with the ``--schema`` option. View name ~~~~~~~~~ By default, a view name is the same as corresponding cube name. If there is ``denormalized_view_prefix`` option in the configuration, then the prefix is prepended to the cube name. Or it is possible to override the option with command line argument ``--prefix``. .. note:: The tool will not allow to create view if it's name is the same as fact table name and is in the same schema. It is not even possible to ``--force`` it. A SEE ALSO ======== * `Cubes documentation <http://packages.python.org/cubes/slicer.html>`__ <file_sep># -*- coding=utf -*- from collections import namedtuple from ...errors import * try: import sqlalchemy import sqlalchemy.sql as sql from sqlalchemy.sql.functions import ReturnTypeFromArgs except ImportError: from cubes.common import MissingPackage sqlalchemy = sql = MissingPackage("sqlalchemy", "SQL aggregation browser") missing_error = MissingPackage("sqlalchemy", "SQL browser extensions") class ReturnTypeFromArgs(object): def __init__(*args, **kwargs): # Just fail by trying to call missing package missing_error() __all__ = ( "get_aggregate_function", "available_aggregate_functions" ) class AggregateFunction(object): requires_measure = True # if `True` then on `coalesce` the values are coalesced to 0 before the # aggregation. If `False` then the values are as they are and the result is # coalesced to 0. coalesce_values = True def __init__(self, name_, function_=None, *args, **kwargs): self.name = name_ self.function = function_ self.args = args self.kwargs = kwargs def __call__(self, aggregate, context, coalesce=False): """Applied the function on the aggregate and returns labelled expression. SQL expression label is the aggregate's name. This method calls `apply()` method which can be overriden by subclasses.""" expression = self.apply(aggregate, context, coalesce) expression = expression.label(aggregate.name) return expression def coalesce_value(self, aggregate, value): """Coalesce the value before aggregation of `aggregate`. `value` is a SQLAlchemy expression. Default implementation does nothing, just returns the `value`.""" return value def coalesce_aggregate(self, aggregate, value): """Coalesce the aggregated value of `aggregate`. `value` is a SQLAlchemy expression. Default implementation does nothing, just returns the `value`.""" return value def required_measures(self, aggregate): """Returns a list of measure names that the `aggregate` depends on.""" # Currently only one-attribute source is supported, therefore we just # return the attribute. if aggregate.measure: return [aggregate.measure] else: return [] # TODO: use dict of name:measure from required_measures instead of context def apply(self, aggregate, context=None, coalesce=False): """Apply the function on the aggregate. Subclasses might override this method and use other `aggregates` and browser context. If `missing_value` is not `None`, then the aggregate's source value should be wrapped in ``COALESCE(column, missing_value)``. Returns a SQLAlchemy expression.""" if not context: raise InternalError("No context provided for AggregationFunction") if not aggregate.measure: raise ModelError("No measure specified for aggregate %s, " "required for aggregate function %s" % (str(aggregate), self.name)) try: source = context.cube.measure(aggregate.measure) except NoSuchAttributeError: source = context.cube.aggregate(aggregate.measure) column = context.column(source) if coalesce: column = self.coalesce_value(aggregate, column) expression = self.function(column, *self.args, **self.kwargs) if coalesce: expression = self.coalesce_aggregate(aggregate, expression) return expression def __str__(self): return self.name class ValueCoalescingFunction(AggregateFunction): def coalesce_value(self, aggregate, value): """Coalesce the value before aggregation of `aggregate`. `value` is a SQLAlchemy expression. Default implementation coalesces to zero 0.""" # TODO: use measure's missing value (we need to get the measure object # somehow) return sql.functions.coalesce(value, 0) class SummaryCoalescingFunction(AggregateFunction): def coalesce_aggregate(self, aggregate, value): """Coalesce the aggregated value of `aggregate`. `value` is a SQLAlchemy expression. Default implementation does nothing.""" # TODO: use aggregates's missing value return sql.functions.coalesce(value, 0) class GenerativeFunction(AggregateFunction): def __init__(self, name, function=None, *args, **kwargs): """Creates a function that generates a value without using any of the measures.""" super(GenerativeFunction, self).__init__(name, function) def apply(self, aggregate, context=None, coalesce=False): return self.function(*self.args, **self.kwargs) class FactCountFunction(AggregateFunction): def __init__(self, name, function=None, *args, **kwargs): """Creates a function that provides fact (record) counts. """ super(FactCountFunction, self).__init__(name, function) def apply(self, aggregate, context=None, coalesce=False): """Count only existing facts. Assumption: every facts has an ID""" if coalesce: # TODO: pass the fact column somehow more nicely, maybe in a map: # aggregate: column column = context.fact_key_column() return sql.functions.count(column) else: return sql.functions.count(1) class avg(ReturnTypeFromArgs): pass # Works with PostgreSQL class stddev(ReturnTypeFromArgs): pass class variance(ReturnTypeFromArgs): pass _functions = ( SummaryCoalescingFunction("sum", sql.functions.sum), SummaryCoalescingFunction("count_nonempty", sql.functions.count), FactCountFunction("count"), ValueCoalescingFunction("min", sql.functions.min), ValueCoalescingFunction("max", sql.functions.max), ValueCoalescingFunction("avg", avg), ValueCoalescingFunction("stddev", stddev), ValueCoalescingFunction("variance", variance), ValueCoalescingFunction("custom", lambda c: c), ) _function_dict = {} def _create_function_dict(): if not _function_dict: for func in _functions: _function_dict[func.name] = func def get_aggregate_function(name): """Returns an aggregate function `name`. The returned function takes two arguments: `aggregate` and `context`. When called returns a labelled SQL expression.""" _create_function_dict() return _function_dict[name] def available_aggregate_functions(): """Returns a list of available aggregate function names.""" _create_function_dict() return _function_dict.keys() <file_sep>import unittest import os import re import cubes from cubes.errors import * from cubes.model import * from cubes.providers import create_cube import copy from common import TESTS_PATH, CubesTestCaseBase DIM_DATE_DESC = { "name": "date", "levels": [ {"name": "year"}, {"name": "month", "attributes": ["month", "month_name"]}, {"name": "day"} ], "hierarchies": [ {"name": "ymd", "levels": ["year", "month", "day"]}, {"name": "ymd", "levels": ["year", "month"]}, ] } DIM_FLAG_DESC = {"name": "flag"} DIM_PRODUCT_DESC = { "name": "product", "levels": [ {"name": "category", "attributes": ["key", "name"]}, {"name": "subcategory", "attributes": ["key", "name"]}, {"name": "product", "attributes": ["key", "name", "description"]} ] } class ModelTestCaseBase(unittest.TestCase): def setUp(self): self.models_path = os.path.join(TESTS_PATH, 'models') def model_path(self, model): return os.path.join(self.models_path, model) class AttributeTestCase(unittest.TestCase): """docstring for AttributeTestCase""" def test_basics(self): """Attribute creation and attribute references""" attr = cubes.Attribute("foo") self.assertEqual("foo", attr.name) self.assertEqual("foo", str(attr)) self.assertEqual("foo", attr.ref()) self.assertEqual("foo", attr.ref(simplify=False)) self.assertEqual("foo", attr.ref(simplify=True)) def test_locale(self): """References to localizable attributes""" attr = cubes.Attribute("foo") self.assertRaises(ArgumentError, attr.ref, locale="xx") attr = cubes.Attribute("foo", locales=["en", "sk"]) self.assertEqual("foo", attr.name) self.assertEqual("foo", str(attr)) self.assertEqual("foo", attr.ref()) self.assertEqual("foo.en", attr.ref(locale="en")) self.assertEqual("foo.sk", attr.ref(locale="sk")) self.assertRaises(ArgumentError, attr.ref, locale="xx") def test_simplify(self): """Simplification of attribute reference (with and without details)""" level = cubes.Level("name", attributes=["name"]) dim = cubes.Dimension("group", levels=[level]) attr = dim.attribute("name") self.assertEqual("name", attr.name) self.assertEqual("name", str(attr)) self.assertEqual("group", attr.ref()) self.assertEqual("group.name", attr.ref(simplify=False)) self.assertEqual("group", attr.ref(simplify=True)) level = cubes.Level("name", attributes=["key", "name"]) dim = cubes.Dimension("group", levels=[level]) attr = dim.attribute("name") self.assertEqual("name", attr.name) self.assertEqual("name", str(attr)) self.assertEqual("group.name", attr.ref()) self.assertEqual("group.name", attr.ref(simplify=False)) self.assertEqual("group.name", attr.ref(simplify=True)) def test_create_attribute(self): """Coalesce attribute object (string or Attribute instance)""" level = cubes.Level("name", attributes=["key", "name"]) dim = cubes.Dimension("group", levels=[level]) obj = cubes.create_attribute("name") self.assertIsInstance(obj, cubes.Attribute) self.assertEqual("name", obj.name) obj = cubes.create_attribute({"name": "key"}) obj.dimension = dim self.assertIsInstance(obj, cubes.Attribute) self.assertEqual("key", obj.name) self.assertEqual(dim, obj.dimension) attr = dim.attribute("key") obj = cubes.create_attribute(attr) obj.dimension = dim self.assertIsInstance(obj, cubes.Attribute) self.assertEqual("key", obj.name) self.assertEqual(obj, attr) def test_attribute_list(self): """Create attribute list from strings or Attribute instances""" self.assertEqual([], cubes.attribute_list([])) names = ["name", "key"] attrs = cubes.attribute_list(names) for name, attr in zip(names, attrs): self.assertIsInstance(attr, cubes.Attribute) self.assertEqual(name, attr.name) class MeasuresTestsCase(CubesTestCaseBase): def setUp(self): super(MeasuresTestsCase, self).setUp() self.metadata = self.model_metadata("measures.json") self.cubes_md = {} for cube in self.metadata["cubes"]: self.cubes_md[cube["name"]] = cube def cube(self, name): """Create a cube object `name` from measures test model.""" return create_cube(self.cubes_md[name]) def test_basic(self): md = {} with self.assertRaises(ModelError): measure = create_measure(md) measure = create_measure("amount") self.assertIsInstance(measure, Measure) self.assertEqual("amount", measure.name) md = {"name": "amount"} measure = create_measure(md) self.assertEqual("amount", measure.name) def test_copy(self): md = {"name": "amount"} measure = create_measure(md) measure2 = copy.deepcopy(measure) self.assertEqual(measure, measure2) def test_aggregate(self): md = {} with self.assertRaises(ModelError): measure = create_measure_aggregate(md) measure = create_measure_aggregate("amount_sum") self.assertIsInstance(measure, MeasureAggregate) self.assertEqual("amount_sum", measure.name) def test_create_default_aggregates(self): measure = create_measure("amount") aggs = measure.default_aggregates() self.assertEqual(1, len(aggs)) agg = aggs[0] self.assertEqual("amount_sum", agg.name) self.assertEqual("amount", agg.measure) self.assertEqual("sum", agg.function) self.assertIsNone(agg.formula) md = {"name": "amount", "aggregates": ["sum", "min"]} measure = create_measure(md) aggs = measure.default_aggregates() self.assertEqual(2, len(aggs)) self.assertEqual("amount_sum", aggs[0].name) self.assertEqual("amount", aggs[0].measure) self.assertEqual("sum", aggs[0].function) self.assertIsNone(aggs[0].formula) self.assertEqual("amount_min", aggs[1].name) self.assertEqual("amount", aggs[1].measure) self.assertEqual("min", aggs[1].function) self.assertIsNone(aggs[1].formula) def test_fact_count(self): md = {"name": "count", "function": "count"} agg = create_measure_aggregate(md) self.assertEqual("count", agg.name) self.assertIsNone(agg.measure) self.assertEqual("count", agg.function) self.assertIsNone(agg.formula) def test_empty2(self): """No measures in metadata should yield count measure with record count""" cube = self.cube("empty") self.assertIsInstance(cube, Cube) self.assertEqual(0, len(cube.measures)) self.assertEqual(1, len(cube.aggregates)) aggregate = cube.aggregates[0] self.assertEqual("record_count", aggregate.name) self.assertEqual("count", aggregate.function) self.assertIsNone(aggregate.measure) def test_amount_default(self): """Plain measure definition should yield measure_sum aggregate""" cube = self.cube("amount_default") measures = cube.measures self.assertEqual(1, len(measures)) self.assertEqual("amount", measures[0].name) self.assertIsNone(measures[0].expression) aggregates = cube.aggregates self.assertEqual(1, len(aggregates)) self.assertEqual("amount_sum", aggregates[0].name) self.assertEqual("amount", aggregates[0].measure) self.assertIsNone(aggregates[0].expression) def test_fact_count2(self): cube = self.cube("fact_count") measures = cube.measures self.assertEqual(0, len(measures)) aggregates = cube.aggregates self.assertEqual(1, len(aggregates)) self.assertEqual("total_events", aggregates[0].name) self.assertIsNone(aggregates[0].measure) self.assertIsNone(aggregates[0].expression) def test_amount_sum(self): cube = self.cube("amount_sum") measures = cube.measures self.assertEqual(1, len(measures)) self.assertEqual("amount", measures[0].name) self.assertIsNone(measures[0].expression) aggregates = cube.aggregates self.assertEqual(1, len(aggregates)) self.assertEqual("amount_sum", aggregates[0].name) self.assertEqual("sum", aggregates[0].function) self.assertEqual("amount", aggregates[0].measure) self.assertIsNone(aggregates[0].expression) def test_explicit_implicit_combined(self): # Test explicit aggregates # cube = self.cube("amount_sum_explicit") measures = cube.measures self.assertEqual(1, len(measures)) self.assertEqual("amount", measures[0].name) self.assertIsNone(measures[0].expression) aggregates = cube.aggregates self.assertEqual(1, len(aggregates)) self.assertEqual("total", aggregates[0].name) self.assertEqual("amount", aggregates[0].measure) self.assertIsNone(aggregates[0].expression) cube = self.cube("amount_sum_combined") measures = cube.measures self.assertEqual(1, len(measures)) self.assertEqual("amount", measures[0].name) self.assertIsNone(measures[0].expression) aggregates = cube.aggregates self.assertEqual(4, len(aggregates)) names = [a.name for a in aggregates] self.assertSequenceEqual(["total", "amount_sum", "amount_min", "amount_max"], names) def test_backend_provided(self): cube = self.cube("backend_provided_aggregate") measures = cube.measures self.assertEqual(0, len(measures)) aggregates = cube.aggregates self.assertEqual(1, len(aggregates)) self.assertEqual("total", aggregates[0].name) self.assertIsNone(aggregates[0].measure) self.assertIsNone(aggregates[0].expression) def measure_expression(self): cube = self.cube("measure_expression") measures = cube.measures self.assertEqual(3, len(measures)) self.assertEqual("price", measures[0].name) self.assertIsNone(measures[0].expression) self.assertEqual("costs", measures[1].name) self.assertIsNone(measures[2].expression) self.assertEqual("revenue", measures[2].name) self.assertEqual("price - costs", measures[2].expression) aggregates = cube.aggregates self.assertEqual(3, len(aggregates)) self.assertEqual("price_sum", aggregates[0].name) self.assertEqual("price", aggregates[0].measure) self.assertEqual("costs_sum", aggregates[0].name) self.assertEqual("costs", aggregates[0].measure) self.assertEqual("revenue_sum", aggregates[0].name) self.assertEqual("revenue", aggregates[0].measure) # TODO: aggregate_expression, aggregate_expression_error # TODO: measure_expression, invalid_expression def test_implicit(self): # TODO: this should be in model.py tests cube = self.cube("default_aggregates") aggregates = [a.name for a in cube.aggregates] self.assertSequenceEqual(["amount_sum", "amount_min", "amount_max" ], aggregates) def test_explicit(self): cube = self.cube("explicit_aggregates") aggregates = [a.name for a in cube.aggregates] self.assertSequenceEqual(["amount_sum", "amount_wma", "count", ], aggregates) def test_explicit_conflict(self): with self.assertRaisesRegexp(ModelError, "function mismatch"): cube = self.cube("explicit_aggregates_conflict") class LevelTestCase(unittest.TestCase): """docstring for LevelTestCase""" def test_initialization(self): """Empty attribute list for new level should raise an exception """ self.assertRaises(ModelError, cubes.Level, "month", []) def test_has_details(self): """Level "has_details" flag""" attrs = cubes.attribute_list(["year"]) level = cubes.Level("year", attrs) self.assertFalse(level.has_details) attrs = cubes.attribute_list(["month", "month_name"]) level = cubes.Level("month", attrs) self.assertTrue(level.has_details) def test_operators(self): """Level to string conversion""" self.assertEqual("date", str(cubes.Level("date", ["foo"]))) def test_create(self): """Create level from a dictionary""" desc = "year" level = cubes.create_level(desc) self.assertIsInstance(level, cubes.Level) self.assertEqual("year", level.name) self.assertEqual(["year"], [str(a) for a in level.attributes]) # Test default: Attributes desc = {"name": "year"} level = cubes.create_level(desc) self.assertIsInstance(level, cubes.Level) self.assertEqual("year", level.name) self.assertEqual(["year"], [str(a) for a in level.attributes]) # Test default: Attributes desc = {"name": "year", "attributes": ["key"]} level = cubes.create_level(desc) self.assertIsInstance(level, cubes.Level) self.assertEqual("year", level.name) self.assertEqual(["key"], [str(a) for a in level.attributes]) self.assertFalse(level.has_details) desc = {"name": "year", "attributes": ["key", "label"]} level = cubes.create_level(desc) self.assertTrue(level.has_details) self.assertEqual(["key", "label"], [str(a) for a in level.attributes]) # Level from description with full details desc = { "name": "month", "attributes": [ {"name": "month"}, {"name": "month_name", "locales": ["en", "sk"]}, {"name": "month_sname", "locales": ["en", "sk"]} ] } level = cubes.create_level(desc) self.assertTrue(level.has_details) self.assertEqual(3, len(level.attributes)) names = [str(a) for a in level.attributes] self.assertEqual(["month", "month_name", "month_sname"], names) def test_key_label_attributes(self): """Test key and label attributes - explicit and implicit""" attrs = cubes.attribute_list(["code"]) level = cubes.Level("product", attrs) self.assertIsInstance(level.key, cubes.Attribute) self.assertEqual("code", str(level.key)) self.assertIsInstance(level.label_attribute, cubes.Attribute) self.assertEqual("code", str(level.label_attribute)) attrs = cubes.attribute_list(["code", "name"]) level = cubes.Level("product", attrs) self.assertIsInstance(level.key, cubes.Attribute) self.assertEqual("code", str(level.key)) self.assertIsInstance(level.label_attribute, cubes.Attribute) self.assertEqual("name", str(level.label_attribute)) attrs = cubes.attribute_list(["info", "code", "name"]) level = cubes.Level("product", attrs, key="code", label_attribute="name") self.assertIsInstance(level.key, cubes.Attribute) self.assertEqual("code", str(level.key)) self.assertIsInstance(level.label_attribute, cubes.Attribute) self.assertEqual("name", str(level.label_attribute)) # Test key/label in full desc desc = { "name": "product", "attributes": ["info", "code", "name"], "label_attribute": "name", "key": "code" } level = cubes.create_level(desc) self.assertIsInstance(level.key, cubes.Attribute) self.assertEqual("code", str(level.key)) self.assertIsInstance(level.label_attribute, cubes.Attribute) self.assertEqual("name", str(level.label_attribute)) def test_level_inherit(self): desc = { "name": "product_type", "label": "Product Type" } level = cubes.create_level(desc) self.assertEqual(1, len(level.attributes)) attr = level.attributes[0] self.assertEqual("product_type", attr.name) self.assertEqual("Product Type", attr.label) def test_comparison(self): """Comparison of level instances""" attrs = cubes.attribute_list(["info", "code", "name"]) level1 = cubes.Level("product", attrs, key="code", label_attribute="name") level2 = cubes.Level("product", attrs, key="code", label_attribute="name") level3 = cubes.Level("product", attrs) attrs = cubes.attribute_list(["month", "month_name"]) level4 = cubes.Level("product", attrs) self.assertEqual(level1, level2) self.assertNotEqual(level2, level3) self.assertNotEqual(level2, level4) class HierarchyTestCase(unittest.TestCase): def setUp(self): self.levels = [ cubes.Level("year", attributes=["year"]), cubes.Level("month", attributes=["month", "month_name", "month_sname"]), cubes.Level("day", attributes=["day"]), cubes.Level("week", attributes=["week"]) ] self.level_names = [level.name for level in self.levels] self.dimension = cubes.Dimension("date", levels=self.levels) self.hierarchy = cubes.Hierarchy("default", ["year", "month", "day"], self.dimension) def test_initialization(self): """No dimension on initialization should raise an exception.""" with self.assertRaises(ModelError): cubes.Hierarchy("default", [], self.dimension) hier = cubes.Hierarchy("default", []) try: hier.levels except ModelInconsistencyError: pass def test_operators(self): """Hierarchy operators len(), hier[] and level in hier""" # __len__ self.assertEqual(3, len(self.hierarchy)) # __getitem__ by name self.assertEqual(self.levels[1], self.hierarchy[1]) # __contains__ by name or level self.assertTrue(self.levels[1] in self.hierarchy) self.assertTrue("year" in self.hierarchy) self.assertFalse("flower" in self.hierarchy) def test_levels_for(self): """Levels for depth""" levels = self.hierarchy.levels_for_depth(0) self.assertEqual([], levels) levels = self.hierarchy.levels_for_depth(1) self.assertEqual([self.levels[0]], levels) self.assertRaises(HierarchyError, self.hierarchy.levels_for_depth, 4) def test_level_ordering(self): """Ordering of levels (next, previous)""" self.assertEqual(self.levels[0], self.hierarchy.next_level(None)) self.assertEqual(self.levels[1], self.hierarchy.next_level(self.levels[0])) self.assertEqual(self.levels[2], self.hierarchy.next_level(self.levels[1])) self.assertEqual(None, self.hierarchy.next_level(self.levels[2])) self.assertEqual(None, self.hierarchy.previous_level(None)) self.assertEqual(None, self.hierarchy.previous_level(self.levels[0])) self.assertEqual(self.levels[0], self.hierarchy.previous_level(self.levels[1])) self.assertEqual(self.levels[1], self.hierarchy.previous_level(self.levels[2])) self.assertEqual(0, self.hierarchy.level_index(self.levels[0])) self.assertEqual(1, self.hierarchy.level_index(self.levels[1])) self.assertEqual(2, self.hierarchy.level_index(self.levels[2])) self.assertRaises(cubes.HierarchyError, self.hierarchy.level_index, self.levels[3]) def test_rollup(self): """Path roll-up for hierarchy""" path = [2010, 1, 5] self.assertEqual([2010, 1], self.hierarchy.rollup(path)) self.assertEqual([2010, 1], self.hierarchy.rollup(path, "month")) self.assertEqual([2010], self.hierarchy.rollup(path, "year")) self.assertRaises(HierarchyError, self.hierarchy.rollup, [2010], "month") self.assertRaises(HierarchyError, self.hierarchy.rollup, [2010], "unknown") def test_base_path(self): """Test base paths""" self.assertTrue(self.hierarchy.path_is_base([2012, 1, 5])) self.assertFalse(self.hierarchy.path_is_base([2012, 1])) self.assertFalse(self.hierarchy.path_is_base([2012])) self.assertFalse(self.hierarchy.path_is_base([])) def test_attributes(self): """Collecting attributes and keys""" keys = [a.name for a in self.hierarchy.key_attributes()] self.assertEqual(["year", "month", "day"], keys) attrs = [a.name for a in self.hierarchy.all_attributes] self.assertEqual(["year", "month", "month_name", "month_sname", "day"], attrs) class DimensionTestCase(unittest.TestCase): def setUp(self): self.levels = [ cubes.Level("year", attributes=["year"]), cubes.Level("month", attributes=["month", "month_name", "month_sname"]), cubes.Level("day", attributes=["day"]), cubes.Level("week", attributes=["week"]) ] self.level_names = [level.name for level in self.levels] self.dimension = cubes.Dimension("date", levels=self.levels) self.hierarchy = cubes.Hierarchy("default", ["year", "month", "day"], self.dimension) def test_create(self): """Dimension from a dictionary""" dim = cubes.create_dimension("year") self.assertIsInstance(dim, cubes.Dimension) self.assertEqual("year", dim.name) self.assertEqual(["year"], [str(a) for a in dim.all_attributes]) # Test default: explicit level attributes desc = {"name": "date", "levels": ["year"]} dim = cubes.create_dimension(desc) self.assertTrue(dim.is_flat) self.assertFalse(dim.has_details) self.assertIsInstance(dim, cubes.Dimension) self.assertEqual("date", dim.name) self.assertEqual(["year"], [str(a) for a in dim.all_attributes]) desc = {"name": "date", "levels": ["year", "month", "day"]} dim = cubes.create_dimension(desc) self.assertIsInstance(dim, cubes.Dimension) self.assertEqual("date", dim.name) names = [str(a) for a in dim.all_attributes] self.assertEqual(["year", "month", "day"], names) self.assertFalse(dim.is_flat) self.assertFalse(dim.has_details) self.assertEqual(3, len(dim.levels)) for level in dim.levels: self.assertIsInstance(level, cubes.Level) self.assertEqual(1, len(dim.hierarchies)) self.assertEqual(3, len(dim.hierarchy())) # Test default: implicit single level attributes desc = {"name": "product", "attributes": ["code", "name"]} dim = cubes.create_dimension(desc) names = [str(a) for a in dim.all_attributes] self.assertEqual(["code", "name"], names) self.assertEqual(1, len(dim.levels)) self.assertEqual(1, len(dim.hierarchies)) self.assertRaises(cubes.ModelInconsistencyError, cubes.Dimension, "date", levels=["year", "month"]) def test_flat_dimension(self): """Flat dimension and 'has details' flags""" dim = cubes.create_dimension("foo") self.assertTrue(dim.is_flat) self.assertFalse(dim.has_details) self.assertEqual(1, len(dim.levels)) level = dim.level("foo") self.assertIsInstance(level, cubes.Level) self.assertEqual("foo", level.name) self.assertEqual(1, len(level.attributes)) self.assertEqual("foo", str(level.key)) attr = level.attributes[0] self.assertIsInstance(attr, cubes.Attribute) self.assertEqual("foo", attr.name) def test_comparisons(self): """Comparison of dimension instances""" dim1 = cubes.create_dimension(DIM_DATE_DESC) dim2 = cubes.create_dimension(DIM_DATE_DESC) self.assertListEqual(dim1.levels, dim2.levels) self.assertListEqual(dim1.hierarchies.items(), dim2.hierarchies.items()) self.assertEqual(dim1, dim2) def test_to_dict(self): desc = self.dimension.to_dict() dim = cubes.create_dimension(desc) self.assertEqual(self.dimension.hierarchies, dim.hierarchies) self.assertEqual(self.dimension.levels, dim.levels) self.assertEqual(self.dimension, dim) def test_template(self): dims = {"date": self.dimension} desc = {"template": "date", "name": "date"} dim = cubes.create_dimension(desc, dims) self.assertEqual(self.dimension, dim) hier = dim.hierarchy() self.assertEqual(4, len(hier.levels)) desc["hierarchy"] = ["year", "month"] dim = cubes.create_dimension(desc, dims) self.assertEqual(1, len(dim.hierarchies)) hier = dim.hierarchy() self.assertEqual(2, len(hier.levels)) template = self.dimension.to_dict() template["hierarchies"] = [ {"name": "ym", "levels": ["year", "month"]}, {"name": "ymd", "levels": ["year", "month", "day"]} ] template["default_hierarchy_name"] = "ym" template = cubes.create_dimension(template) dims = {"date": template} desc = {"template": "date", "name":"another_date"} dim = cubes.create_dimension(desc, dims) self.assertEqual(2, len(dim.hierarchies)) self.assertEqual(["ym", "ymd"], [hier.name for hier in dim.hierarchies.values()]) class CubeTestCase(unittest.TestCase): def setUp(self): a = [DIM_DATE_DESC, DIM_PRODUCT_DESC, DIM_FLAG_DESC] self.measures = cubes.attribute_list(["amount", "discount"], Measure) self.dimensions = [cubes.create_dimension(desc) for desc in a] self.cube = cubes.Cube("contracts", dimensions=self.dimensions, measures=self.measures) def test_get_dimension(self): self.assertListEqual(self.dimensions, self.cube.dimensions) self.assertEqual("date", self.cube.dimension("date").name) self.assertEqual("product", self.cube.dimension("product").name) self.assertEqual("flag", self.cube.dimension("flag").name) self.assertRaises(NoSuchDimensionError, self.cube.dimension, "xxx") def test_get_measure(self): self.assertListEqual(self.measures, self.cube.measures) self.assertEqual("amount", self.cube.measure("amount").name) self.assertEqual("discount", self.cube.measure("discount").name) self.assertRaises(NoSuchAttributeError, self.cube.measure, "xxx") def test_attributes(self): all_attributes = self.cube.all_attributes refs = [a.ref() for a in all_attributes] expected = [ 'date.year', 'date.month', 'date.month_name', 'date.day', 'product.key', 'product.name', 'product.description', 'flag', 'amount', 'discount'] self.assertSequenceEqual(expected, refs) attributes = self.cube.get_attributes(["date.year", "product.name"]) refs = [a.ref() for a in attributes] expected = ['date.year', 'product.name'] self.assertSequenceEqual(expected, refs) attributes = self.cube.get_attributes(["amount"]) refs = [a.ref() for a in attributes] self.assertSequenceEqual(["amount"], refs) with self.assertRaises(NoSuchAttributeError): self.cube.get_attributes(["UNKNOWN"]) @unittest.skip("deferred (needs workspace)") def test_to_dict(self): desc = self.cube.to_dict() dims = dict((dim.name, dim) for dim in self.dimensions) cube = cubes.create_cube(desc, dims) self.assertEqual(self.cube.dimensions, cube.dimensions) self.assertEqual(self.cube.measures, cube.measures) self.assertEqual(self.cube, cube) class ModelTestCase(ModelTestCaseBase): def setUp(self): super(ModelTestCase, self).setUp() a = [DIM_DATE_DESC, DIM_PRODUCT_DESC, DIM_FLAG_DESC] self.measures = cubes.attribute_list(["amount", "discount"], Measure) self.dimensions = [cubes.create_dimension(desc) for desc in a] self.cube = cubes.Cube("contracts", dimensions=self.dimensions, measures=self.measures) self.model = cubes.Model(cubes=[self.cube], dimensions=self.dimensions) self.model_file = "model.json" def test_extraction(self): self.assertEqual(self.dimensions[0], self.model.dimension("date")) self.assertRaises(NoSuchDimensionError, self.model.dimension, "xxx") self.assertEqual(self.cube, self.model.cube("contracts")) self.assertRaises(ModelError, self.model.cube, "xxx") def test_localize(self): translation = { "locale": "sk", "dimensions": { "date": { "label": "Datum", "attributes": {"month":"mesiac"} } } } localized = self.model.localize(translation) dim = localized.dimension("date") self.assertEqual("Datum", dim.label) self.assertEqual("mesiac", dim.attribute("month").label) translation["dimensions"]["date"]["attributes"]["month"] = { "label":"mesiac" } dim = localized.dimension("date") self.assertEqual("Datum", dim.label) self.assertEqual("mesiac", dim.attribute("month").label) class OldModelValidatorTestCase(unittest.TestCase): def setUp(self): self.model = cubes.Model('test') self.date_levels = [ {"name":"year", "key": "year" }, {"name":"month", "key": "month" } ] self.date_levels2 = [ { "name":"year", "key": "year" }, {"name":"month", "key": "month" }, {"name":"day", "key":"day"} ] self.date_hiers = [ { "name":"ym", "levels": ["year", "month"] } ] self.date_hiers2 = [ {"name":"ym", "levels": ["year", "month"] }, {"name":"ymd", "levels": ["year", "month", "day"] } ] self.date_desc = { "name": "date", "levels": self.date_levels , "hierarchies": self.date_hiers } def test_dimension_validation(self): date_desc = { "name": "date", "levels": [ {"name": "year", "attributes": ["year"]} ] } dim = cubes.create_dimension(date_desc) self.assertEqual(1, len(dim.levels)) results = dim.validate() self.assertValidation(results, "No levels") self.assertValidation(results, "No defaut hierarchy") # FIXME: uncomment this after implementing https://github.com/Stiivi/cubes/issues/8 # self.assertValidationError(results, "No hierarchies in dimension", expected_type = "default") date_desc = { "name": "date", "levels": self.date_levels} dim = cubes.create_dimension(date_desc) results = dim.validate() # FIXME: uncomment this after implementing https://github.com/Stiivi/cubes/issues/8 # self.assertValidationError(results, "No hierarchies in dimension.*more", expected_type = "error") date_desc = { "name": "date", "levels": self.date_levels , "hierarchies": self.date_hiers } dim = cubes.create_dimension(date_desc) results = dim.validate() self.assertValidation(results, "No levels in dimension", "Dimension is invalid without levels") self.assertValidation(results, "No hierarchies in dimension", "Dimension is invalid without hierarchies") # self.assertValidationError(results, "No default hierarchy name") dim.default_hierarchy_name = 'foo' results = dim.validate() self.assertValidationError(results, "Default hierarchy .* does not") self.assertValidation(results, "No default hierarchy name") dim.default_hierarchy_name = 'ym' results = dim.validate() self.assertValidation(results, "Default hierarchy .* does not") date_desc = { "name": "date", "levels": self.date_levels2 , "hierarchies": self.date_hiers2 } dim = cubes.create_dimension(date_desc) results = dim.validate() self.assertValidationError(results, "No defaut hierarchy .* more than one") def assertValidation(self, results, expected, message = None): if not message: message = "Validation pass expected (match: '%s')" % expected for result in results: if re.match(expected, result[1]): self.fail(message) def assertValidationError(self, results, expected, message = None, expected_type = None): if not message: if expected_type: message = "Validation %s expected (match: '%s')" % (expected_type, expected) else: message = "Validation fail expected (match: '%s')" % expected for result in results: if re.match(expected, result[1]): if not expected_type or (expected_type and expected_type == result[0]): return self.fail(message) class ReadModelDescriptionTestCase(ModelTestCaseBase): def setUp(self): super(ReadModelDescriptionTestCase, self).setUp() def test_from_file(self): path = self.model_path("model.json") desc = cubes.read_model_metadata(path) self.assertIsInstance(desc, dict) self.assertTrue("cubes" in desc) self.assertTrue("dimensions" in desc) self.assertEqual(1, len(desc["cubes"])) self.assertEqual(6, len(desc["dimensions"])) def test_from_bundle(self): path = self.model_path("test.cubesmodel") desc = cubes.read_model_metadata(path) self.assertIsInstance(desc, dict) self.assertTrue("cubes" in desc) self.assertTrue("dimensions" in desc) self.assertEqual(1, len(desc["cubes"])) self.assertEqual(6, len(desc["dimensions"])) with self.assertRaises(ArgumentError): path = self.model_path("model.json") desc = cubes.read_model_metadata_bundle(path) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(AttributeTestCase)) suite.addTest(unittest.makeSuite(LevelTestCase)) suite.addTest(unittest.makeSuite(HierarchyTestCase)) suite.addTest(unittest.makeSuite(DimensionTestCase)) suite.addTest(unittest.makeSuite(CubeTestCase)) suite.addTest(unittest.makeSuite(ModelTestCase)) suite.addTest(unittest.makeSuite(OldModelValidatorTestCase)) return suite <file_sep>[memory] type: sql url: sqlite:/// [imaginary] type: imaginary location: somewhere [default] type: sql url: sqlite:/// <file_sep># -*- coding=utf -*- # import logging import os.path import json import wildcards import cubes from .errors import * from ..errors import * from .common import API_VERSION, TEMPLATE_PATH from .common import validated_parameter, str_to_bool from .common import SlicerJSONEncoder, CSVGenerator from .caching import cacheable from ..browser import SPLIT_DIMENSION_NAME try: from werkzeug.wrappers import Response from werkzeug.utils import redirect from werkzeug.exceptions import NotFound except ImportError: from cubes.common import MissingPackage _missing = MissingPackage("werkzeug", "Slicer server") Response = redirect = NotFound = _missing try: import cubes_search except ImportError: cubes_search = None __all__ = ( "ApplicationController", "ModelController", "CubesController", "SearchController" ) class ApplicationController(object): def __init__(self, args, workspace, logger, config): self.workspace = workspace self.args = wildcards.proc_wildcards(args) self.config = config self.logger = logger self.locale = self.args.get("lang") self.locales = self.workspace.locales if config.has_option("server","json_record_limit"): self.json_record_limit = config.getint("server","json_record_limit") else: self.json_record_limit = 1000 if config.has_option("server","prettyprint"): self.prettyprint = config.getboolean("server","prettyprint") else: self.prettyprint = None # Override server settings if "prettyprint" in self.args: self.prettyprint = str_to_bool(self.args.get("prettyprint")) # Read common parameters self.page = None if "page" in self.args: try: self.page = int(self.args.get("page")) except ValueError: raise RequestError("'page' should be a number") self.page_size = None if "pagesize" in self.args: try: self.page_size = int(self.args.get("pagesize")) except ValueError: raise RequestError("'pagesize' should be a number") # Collect orderings: # order is specified as order=<field>[:<direction>] # examples: # # order=date.year # order by year, unspecified direction # order=date.year:asc # order by year ascending # self.order = [] for orders in self.args.getlist("order"): for order in orders.split(","): split = order.split(":") if len(split) == 1: self.order.append( (order, None) ) else: self.order.append( (split[0], split[1]) ) if 'cache_host' in workspace.options: import caching import pymongo import cPickle as picklee ttl = int(workspace.options.get('ttl')) or 60 * 3 client = pymongo.MongoClient(host=workspace.options['cache_host']) self.logger.info("Caching Enabled, host: %s, TTL: %d" % (workspace.options['cache_host'], ttl)) cache = caching.MongoCache('CubesCache', client, ttl, dumps=caching.response_dumps, loads=caching.response_loads, logger=self.logger) self.cache = cache def index(self): handle = open(os.path.join(TEMPLATE_PATH, "index.html")) template = handle.read() handle.close() context = {} context.update(self.server_info()) doc = template.format(**context) return Response(doc, mimetype = 'text/html') def server_info(self): info = { "version": cubes.__version__, # Backward compatibility key "server_version": cubes.__version__, "api_version": API_VERSION } return info def version(self): return self.json_response(self.server_info()) def get_locales(self): """Return list of available model locales""" return self.json_response(self.locales) def get_json(self, obj): """Returns a json from `obj` using custom encoder. Take `prettyprint` setting into account.""" if self.prettyprint: indent = 4 else: indent = None encoder = SlicerJSONEncoder(indent=indent) encoder.iterator_limit = self.json_record_limit reply = encoder.iterencode(obj) return reply def json_response(self, obj): reply = self.get_json(obj) return Response(reply, mimetype='application/json') def json_request(self): content_type = self.request.headers.get('content-type') if content_type.split(';')[0] == 'application/json': try: result = json.loads(self.request.data) except Exception as e: raise RequestError("Problem loading request JSON data", reason=str(e)) return result else: raise RequestError("JSON requested should have content type " "application/json, is '%s'" % content_type) class ModelController(ApplicationController): _cached_model_reply = None def show(self): d = self._cached_model_reply if d: return Response(d, mimetype='application/json') d = {} d["cubes"] = self.workspace.list_cubes() d["message"] = "this end-point is depreciated" d["locales"] = self.locales d = json.dumps(d) self._cached_model_reply = d return Response(d, mimetype='application/json') def dimension(self, dim_name): # TODO: better message raise RequestError("Depreciated") def _cube_dict(self, cube): d = cube.to_dict(expand_dimensions=True, with_mappings=False, full_attribute_names=True, create_label=True ) return d def get_default_cube(self): raise RequestError("Depreciated") def get_cube(self, cube_name): cube = self.workspace.cube(cube_name) # Attach cube features response = self._cube_dict(cube) response["features"] = self.workspace.cube_features(cube) return self.json_response(response) _cached_cubes_list = None def list_cubes(self): resp = self._cached_cubes_list if resp is None: cubes = self.workspace.list_cubes() resp = self.get_json(cubes) self._cached_cubes_list = resp return Response(resp, mimetype='application/json') class CubesController(ApplicationController): def create_browser(self, cube_name): """Initializes the controller: * tries to get cube name * if no cube name is specified, then tries to get default cube: either explicityly specified in configuration under ``[model]`` option ``cube`` or first cube in model cube list * assigns a browser for the controller """ # FIXME: keep or remove default cube? if cube_name: self.cube = self.workspace.cube(cube_name) else: if self.config.has_option("model", "cube"): self.logger.debug("using default cube specified in cofiguration") cube_name = self.config.get("model", "cube") self.cube = self.workspace.cube(cube_name) else: self.logger.debug("using first cube from model") cubes = self.workspace.list_cubes() cube_name = cubes[0]["name"] self.cube = self.workspace.cube(cube_name) self.logger.info("browsing cube '%s' (locale: %s)" % (cube_name, self.locale)) self.browser = self.workspace.browser(self.cube, self.locale) def prepare_cell(self): cuts = self._parse_cut_spec(self.args.getlist("cut"), 'cell') self.cell = cubes.Cell(self.cube, cuts) def _parse_cut_spec(self, cut_strings, context): if cut_strings: cuts = [] for cut_string in cut_strings: self.logger.debug("preparing %s from string: '%s'" % (context, cut_string)) cuts += cubes.cuts_from_string(cut_string) else: self.logger.debug("preparing %s as whole cube" % context) cuts = [] return cuts @cacheable def aggregate(self, cube): self.create_browser(cube) self.prepare_cell() output_format = validated_parameter(self.args, "format", values=["json", "csv"], default="json") header_type = validated_parameter(self.args, "header", values=["names", "labels", "none"], default="labels") fields_str = self.args.get("fields") if fields_str: fields = fields_str.lower().split(',') else: fields = None ddlist = self.args.getlist("drilldown") # Collect measures or aggregates # Note that the framework will raise an exception when both are # specified. Use only one. # If the measures are used, then all aggregates derived from thise # measures are considered. measures = [] # TODO: this should be depreciated (backward compatibility) # TODO: raise error later (invalid argument) for mstring in self.args.getlist("measure") or []: measures += mstring.split("|") for mstring in self.args.getlist("measures") or []: measures += mstring.split("|") aggregates = [] for agg in self.args.getlist("aggregates") or []: aggregates += agg.split("|") drilldown = [] if ddlist: for ddstring in ddlist: drilldown += ddstring.split("|") split = None split_cuts = self._parse_cut_spec(self.args.getlist("split"), 'split') if split_cuts: split = cubes.Cell(self.cube, split_cuts) result = self.browser.aggregate(self.cell, measures=measures, aggregates=aggregates, drilldown=drilldown, split=split, page=self.page, page_size=self.page_size, order=self.order) if output_format == "json": return self.json_response(result) elif output_format != "csv": raise RequestError("unknown response format '%s'" % format) # csv if header_type == "names": header = result.labels elif header_type == "labels": header = [] for l in result.labels: # TODO: add a little bit of polish to this if l == SPLIT_DIMENSION_NAME: header.append('Matches Filters') else: header += [ attr.label or attr.name for attr in self.cube.get_attributes([l], aggregated=True) ] else: header = None fields = result.labels generator = CSVGenerator(result, fields, include_header=bool(header), header=header) return Response(generator.csvrows(), mimetype='text/csv') @cacheable def facts(self, cube): """Get facts. Parameters: * `fields`: comma separated list of selected fields * `page`: page number * `pagesize`: number of facts per page * `order`: list of fields to order by in form ``field:direction`` * `format`: ``csv`` or ``json`` * `header`: ``names``, ``labels`` or ``none`` """ self.create_browser(cube) self.prepare_cell() # Request parameters output_format = validated_parameter(self.args, "format", values=["json", "csv"], default="json") header_type = validated_parameter(self.args, "header", values=["names", "labels", "none"], default="labels") fields_str = self.args.get("fields") if fields_str: fields = fields_str.lower().split(',') else: fields = None # fields contain attribute names if fields: attributes = self.cube.get_attributes(fields) else: attributes = self.cube.all_attributes # Construct the field list fields = [attr.ref() for attr in attributes] self.logger.debug("--- FIELDS: %s" % (fields, )) # Get the result result = self.browser.facts(self.cell, fields=fields, order=self.order, page=self.page, page_size=self.page_size) # Add cube key to the fields (it is returned in the result) fields.insert(0, self.cube.key) # Construct the header if header_type == "names": header = fields elif header_type == "labels": header = [attr.label or attr.name for attr in attributes] header.insert(0, self.cube.key or "id") else: header = None # Get the facts iterator. `result` is expected to be an iterable Facts # object facts = iter(result) if output_format == "json": return self.json_response(facts) elif output_format == "csv": if not fields: fields = result.labels generator = CSVGenerator(facts, fields, include_header=bool(header), header=header) return Response(generator.csvrows(), mimetype='text/csv') def fact(self, cube, fact_id): self.create_browser(cube) fact = self.browser.fact(fact_id) if fact: return self.json_response(fact) else: raise NotFoundError(fact_id, "fact", message="No fact with id '%s'" % fact_id) def values(self, cube, dimension_name): self.create_browser(cube) self.prepare_cell() depth_string = self.args.get("depth") if depth_string: try: depth = int(self.args.get("depth")) except ValueError: raise RequestError("depth should be an integer") else: depth = None try: dimension = self.cube.dimension(dimension_name) except KeyError: raise NotFoundError(dim_name, "dimension", message="Dimension '%s' was not found" % dim_name) hier_name = self.args.get("hierarchy") hierarchy = dimension.hierarchy(hier_name) values = self.browser.values(self.cell, dimension, depth=depth, hierarchy=hierarchy, page=self.page, page_size=self.page_size) depth = depth or len(hierarchy) result = { "dimension": dimension.name, "depth": depth, "data": values } return self.json_response(result) def report(self, cube): """Create multi-query report response.""" self.create_browser(cube) self.prepare_cell() report_request = self.json_request() try: queries = report_request["queries"] except KeyError: help = "Wrap all your report queries under a 'queries' key. The " \ "old documentation was mentioning this requirement, however it " \ "was not correctly implemented and wrong example was provided." raise RequestError("Report request does not contain 'queries' key", help=help) cell_cuts = report_request.get("cell") if cell_cuts: # Override URL cut with the one in report cuts = [cubes.cut_from_dict(cut) for cut in cell_cuts] cell = cubes.Cell(self.browser.cube, cuts) self.logger.info("using cell from report specification (URL parameters are ignored)") else: cell = self.cell result = self.browser.report(cell, queries) return self.json_response(result) def cell_details(self, cube): self.create_browser(cube) self.prepare_cell() details = self.browser.cell_details(self.cell) cell_dict = self.cell.to_dict() for cut, detail in zip(cell_dict["cuts"], details): cut["details"] = detail return self.json_response(cell_dict) def details(self, cube): raise RequestError("'details' request is depreciated, use 'cell' request") class SearchController(ApplicationController): """docstring for SearchController Config options: sql_index_table: table name sql_schema sql_url search_backend: sphinx otherwise we raise exception. """ def create_browser(self, cube_name): # FIXME: reuse? if cube_name: self.cube = self.workspace.cube(cube_name) else: if self.config.has_option("model", "cube"): self.logger.debug("using default cube specified in cofiguration") cube_name = self.config.get("model", "cube") self.cube = self.workspace.cube(cube_name) else: self.logger.debug("using first cube from model") cube_name = self.workspace.list_cubes()[0]["name"] self.cube = self.workspace.cube(cube_name) self.browser = self.workspace.browser(self.cube, locale=self.locale) def create_searcher(self): if self.config.has_section("search"): self.options = dict(self.config.items("search")) self.engine_name = self.config.get("search", "engine") else: raise CubesError("Search engine not configured.") self.logger.debug("using search engine: %s" % self.engine_name) options = dict(self.options) del options["engine"] self.searcher = cubes_search.create_searcher(self.engine_name, browser=self.browser, locales=self.locales, **options) def search(self, cube): self.create_browser(cube) self.create_searcher() dimension = self.args.get("dimension") if not dimension: raise RequestError("No dimension provided for search") query = self.args.get("q") if not query: query = self.args.get("query") if not query: raise RequestError("No search query provided") locale = self.locale if not locale and self.locales: locale = self.locales[0] self.logger.debug("searching for '%s' in %s, locale %s" % (query, dimension, locale)) search_result = self.searcher.search(query, dimension, locale=locale) result = { "matches": search_result.dimension_matches(dimension), "dimension": dimension, "total_found": search_result.total_found, "locale": self.locale } if search_result.error: result["error"] = search_result.error if search_result.warning: result["warning"] = search_result.warning return self.json_response(result) <file_sep>import unittest from cubes.backends.sql.mapper import SnowflakeMapper from cubes.model import * from .common import CubesTestCaseBase class MapperTestCase(CubesTestCaseBase): def setUp(self): super(MapperTestCase, self).setUp() self.modelmd = self.model_metadata("mapper_test.json") self.workspace = self.create_workspace(model=self.modelmd) self.cube = self.workspace.cube("sales") self.mapper = SnowflakeMapper(self.cube, dimension_prefix='dim_') self.mapper.mappings = { "product.name": "product.product_name", "product.category": "product.category_id", "subcategory.name.en": "subcategory.subcategory_name_en", "subcategory.name.sk": "subcategory.subcategory_name_sk" } def test_logical_reference(self): dim = self.workspace.dimension("date") attr = Attribute("month", dimension=dim) self.assertEqual("date.month", self.mapper.logical(attr)) attr = Attribute("month", dimension=dim) dim = self.workspace.dimension("product") attr = Attribute("category", dimension=dim) self.assertEqual("product.category", self.mapper.logical(attr)) self.assertEqual(True, self.mapper.simplify_dimension_references) dim = self.workspace.dimension("flag") attr = Attribute("flag", dimension=dim) self.assertEqual("flag", self.mapper.logical(attr)) attr = Attribute("measure", dimension=None) self.assertEqual("measure", self.mapper.logical(attr)) def test_logical_reference_as_string(self): self.assertRaises(AttributeError, self.mapper.logical, "amount") def test_dont_simplify_dimension_references(self): self.mapper.simplify_dimension_references = False dim = self.workspace.dimension("flag") attr = Attribute("flag", dimension=dim) self.assertEqual("flag.flag", self.mapper.logical(attr)) attr = Attribute("measure", dimension=None) self.assertEqual("measure", self.mapper.logical(attr)) def test_logical_split(self): split = self.mapper.split_logical self.assertEqual(('foo', 'bar'), split('foo.bar')) self.assertEqual(('foo', 'bar.baz'), split('foo.bar.baz')) self.assertEqual((None, 'foo'), split('foo')) def assertMapping(self, expected, logical_ref, locale=None): """Create string reference by concatentanig table and column name. No schema is expected (is ignored).""" attr = self.mapper.attributes[logical_ref] ref = self.mapper.physical(attr, locale) sref = ref[1] + "." + ref[2] self.assertEqual(expected, sref) def test_physical_refs_dimensions(self): """Testing correct default mappings of dimensions (with and without explicit default prefix) in physical references.""" # No dimension prefix self.mapper.dimension_prefix = None self.assertMapping("date.year", "date.year") self.assertMapping("sales.flag", "flag") self.assertMapping("sales.amount", "amount") # self.assertEqual("fact.flag", sref("flag.flag")) # With prefix self.mapper.dimension_prefix = "dm_" self.assertMapping("dm_date.year", "date.year") self.assertMapping("dm_date.month_name", "date.month_name") self.assertMapping("sales.flag", "flag") self.assertMapping("sales.amount", "amount") self.mapper.dimension_prefix = None def test_physical_refs_flat_dims(self): self.cube.fact = None self.assertMapping("sales.flag", "flag") def test_physical_refs_facts(self): """Testing correct mappings of fact attributes in physical references""" fact = self.cube.fact self.cube.fact = None self.assertMapping("sales.amount", "amount") # self.assertEqual("sales.flag", sref("flag.flag")) self.cube.fact = fact def test_physical_refs_with_mappings_and_locales(self): """Testing correct mappings of mapped attributes and localized attributes in physical references""" # Test defaults self.assertMapping("dim_date.month_name", "date.month_name") self.assertMapping("dim_category.category_name_en", "product.category_name") self.assertMapping("dim_category.category_name_sk", "product.category_name", "sk") self.assertMapping("dim_category.category_name_en", "product.category_name", "de") # Test with mapping self.assertMapping("dim_product.product_name", "product.name") self.assertMapping("dim_product.category_id", "product.category") self.assertMapping("dim_product.product_name", "product.name", "sk") self.assertMapping("dim_category.subcategory_name_en", "product.subcategory_name") self.assertMapping("dim_category.subcategory_name_sk", "product.subcategory_name", "sk") self.assertMapping("dim_category.subcategory_name_en", "product.subcategory_name", "de") def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(MapperTestCase)) return suite <file_sep>Cubes Examples Sandbox ====================== This directory contains examples that are work in progress. They serve for educational purposes, however they might not be very well documented yet. Once a sandbox example is tuned, simplified enough to be understandable and documented, then it will be moved to the parent `examples` directory. These examples also serve for tuning usability of cubes. If they are not understandable, then some work is necessary on the framework side. If you have any example that you would like to include here, just write to the author <<EMAIL>> or better - send a pull request with files to this directory. Examples -------- Note: Former flask example was moved to root examples, as it was good enough.<file_sep>***************************** Aggregation Browser Reference ***************************** Abstraction for aggregated browsing (concrete implementation is provided by one of the backends in package :mod:`backend` or a custom backend). .. figure:: images/browser-package.png :align: center :width: 400px Browser package classes. Aggregate browsing ================== .. autoclass:: cubes.AggregationBrowser :members: Result ------ The result of aggregated browsing is returned as object: .. autoclass:: cubes.AggregationResult :members: .. autoclass:: cubes.CalculatedResultIterator :members: Facts ----- .. autoclass:: cubes.Facts :members: Slicing and Dicing ================== .. autoclass:: cubes.Cell :members: Cuts ---- .. autoclass:: cubes.Cut :members: .. autoclass:: cubes.PointCut :members: .. autoclass:: cubes.RangeCut :members: .. autoclass:: cubes.SetCut :members: Drilldown --------- .. autoclass:: cubes.Drilldown .. autofunction:: cubes.levels_from_drilldown String conversions ------------------ In applications where slicing and dicing can be specified in form of a string, such as arguments of HTTP requests of an web application, there are couple helper methods that do the string-to-object conversion: .. autofunction:: cubes.cuts_from_string .. autofunction:: cubes.string_from_cuts .. autofunction:: cubes.string_from_path .. autofunction:: cubes.path_from_string .. autofunction:: cubes.string_to_drilldown Mapper ------ .. autoclass:: cubes.Mapper .. autoclass:: cubes.backends.sql.mapper.SnowflakeMapper .. autoclass:: cubes.backends.mongo2.mapper.Mongo2Mapper <file_sep># -*- coding=utf -*- from ..extensions import get_namespace, initialize_namespace from ..errors import * from flask import Response, redirect import re __all__ = ( "Authenticator", "NotAuthenticated" ) # IMPORTANT: This is provisional code. Might be changed or removed. # class NotAuthenticated(Exception): pass def create_authenticator(name, **options): """Gets a new instance of an authorizer with name `name`.""" ns = get_namespace("slicer_authenticators") if not ns: ns = initialize_namespace("slicer_authenticators", root_class=Authenticator, suffix="_authenticator", option_checking=True) try: factory = ns[name] except KeyError: raise ConfigurationError("Unknown authenticator '%s'" % name) return factory(**options) class Authenticator(object): def authenticate(self, request): raise NotImplementedError def logout(self, request, identity): return "logged out" class AbstractBasicAuthenticator(Authenticator): def __init__(self, realm=None): self.realm = realm or "Default" self.pattern = re.compile(r"^(http(?:s?)://)([^/]+.*)$", re.IGNORECASE) def logout(self, request, identity): headers = {"WWW-Authenticate": 'Basic realm="%s"' % self.realm} url_root = request.args.get('url', request.url_root) m = self.pattern.search(url_root) if m: url_root = m.group(1) + "__logout__@" + m.group(2) return redirect(url_root, code=302) else: return Response("logged out", status=401, headers=headers) class AdminAdminAuthenticator(AbstractBasicAuthenticator): """Simple HTTP Basic authenticator for testing purposes. User name and password have to be the same. User name is passed as the authenticated identity.""" def __init__(self, realm=None, **options): super(AdminAdminAuthenticator, self).__init__(realm=realm) def authenticate(self, request): auth = request.authorization if auth and auth.username == auth.password: return auth.username else: raise NotAuthenticated raise NotAuthenticated class PassParameterAuthenticator(Authenticator): """Permissive authenticator that passes an URL parameter (default ``api_key``) as idenity.""" def __init__(self, parameter=None, **options): super(PassParameterAuthenticator, self).__init__(**options) self.parameter_name = parameter or "api_key" def authenticate(self, request): return request.args.get(self.parameter_name) class HTTPBasicProxyAuthenticator(AbstractBasicAuthenticator): def __init__(self, realm=None, **options): super(HTTPBasicProxyAuthenticator, self).__init__(realm=realm) self.realm = realm or "Default" self.pattern = re.compile(r"^(http(?:s?)://)([^/]+.*)$", re.IGNORECASE) def authenticate(self, request): """Permissive authenticator using HTTP Basic authentication that assumes the server to be behind a proxy, and that the proxy authenticated the user. Does not check for a password, just passes the `username` as identity""" auth = request.authorization if auth: return auth.username raise NotAuthenticated(realm=self.realm) <file_sep>++++++++++++++++++++++ Removed Documentation ++++++++++++++++++++++ This file contains removed documentation (might be obsolete) that might be useful in the future. Aggregation =========== * ``Cell`` is no longer used for browsing, you use only ``Browser`` and pass a cell as first argument to get aggregated or other results. * Mongo backend is no logner maintained, only ``cubes.backends.sql.SQLBrowser`` is available This is MongoDB example, other systems coming soon. First you have to prepare logical model and cube. In relational database: .. code-block:: python import cubes # connection is SQLAlchemy database connection # Create aggregation browser browser = cubes.backends.SQLBrowser(cube, connection, "mft_contracts") To browse localized data, just pass locale to the browser and all results will contain localized values for localizable attributes: .. code-block:: python browser = cubes.backends.SQLBrowser(cube, connection, "mft_contracts", locale = "sk") To browse pre-aggregated mongo data: .. code-block:: python import cubes import pymongo # Create MongoDB database connection connection = pymongo.Connection() database = connection["wdmmg_dev"] # Load model and get cube model_path = "wdmmg_model.json" model = cubes.model_from_path(model_path) cube = model.cubes["wdmmg"] Prepare aggregation browser: .. code-block:: python browser = cubes.browse.MongoSimpleCubeBrowser(cube = cube, collection = "cube", database = database) # Get the whole cube full_cube = browser.full_cube() Following aggregation code is backend-independent. Aggregate all data for year 2009: .. code-block:: python cuboid = full_cube.slice("date", ['2009']) results = cuboid.aggregate() Results will contain one aggregated record. Drill down through a dimension: .. code-block:: python results_cofog = cuboid.aggregate(drill_down = "cofog") results_date = cuboid.aggregate(drill_down = "date") `results_cofog` will contain all aggregations for "cofog" dimension at level 1 within year 2009. `results_date` will contain all aggregations for month within year 2009. Drilling-down and aggregating through single dimension. Following function will print aggregations at each level of given dimension. .. code-block:: python def expand_drill_down(dimension_name, path = []): dimension = cube.dimension(dimension_name) hierarchy = dimension.default_hierarchy # We are at last level, nothing to drill-down if hierarchy.path_is_base(path): return # Construct cuboid of our interest full_cube = browser.full_cube() cuboid = full_cube.slice("date", ['2009']) cuboid = cuboid.slice(dimension_name, path) # Perform aggregation cells = cuboid.aggregate(drill_down = dimension_name) # Print results prefix = " " * len(path) for cell in cells: path = cell["_cell"][dimension_name] current = path[-1] print "%s%s: %.1f %d" % (prefix, current, cell["amount_sum"], cell["record_count"]) expand_drill_down(dimension_name, path) The internal key `_cell` contains a dictionary with aggregated cell reference in form: ``{dimension: path}``, like ``{ "date" = [2010, 1] }`` .. note:: The output record from aggregations will change into an object instead of a dictionary, in the future. The equivalent to the _cell key will be provided as an object attribute. Assume we have two levels of date hierarhy: `year`, `month`. To get all time-based drill down: .. code-block:: python expand_drill_down("date") Possible output would be:: 2008: 1200.0 60 1: 100.0 10 2: 200.0 5 3: 50.0 1 ... 2009: 2000.0 10 1: 20.0 10 ... Creating model programmatically =============================== We need a :doc:`logical model</model>` - instance of :class:`cubes.model.Model`: .. code-block:: python model = cubes.Model() Add :class:`dimensions<cubes.model.Dimension>` to the model. Reason for having dimensions in a model is, that they might be shared by multiple cubes. .. code-block:: python model.add_dimension(cubes.Dimension("category")) model.add_dimension(cubes.Dimension("line_item")) model.add_dimension(cubes.Dimension("year")) Define a :class:`cube<cubes.Cube>` and specify already defined dimensions: .. code-block:: python cube = cubes.Cube(name="irbd_balance", model=model, dimensions=["category", "line_item", "year"], measures=["amount"] ) Create a :class:`browser<cubes.AggregationBrowser>` instance (in this example it is :class:`SQL backend<cubes.backends.sql.SQLBrowser>` implementation) and get a :class:`cell<cubes.Cell>` representing the whole cube (all data): .. code-block:: python browser = cubes.backends.sql.SQLBrowser(cube, engine.connect(), view_name = "irbd_balance") cell = browser.full_cube() Compute the aggregate. Measure fields of :class:`aggregation result<cubes.AggregationResult>` have aggregation suffix, currenlty only ``_sum``. Also a total record count within the cell is included as ``record_count``. .. code-block:: python result = browser.aggregate(cell) print "Record count: %d" % result.summary["record_count"] print "Total amount: %d" % result.summary["amount_sum"] Now try some drill-down by `category` dimension: .. code-block:: python result = browser.aggregate(cell, drilldown=["category"]) print "%-20s%10s%10s" % ("Category", "Count", "Total") for record in result.drilldown: print "%-20s%10d%10d" % (record["category"], record["record_count"], record["amount_sum"]) Drill-dow by year: .. code-block:: python result = browser.aggregate(cell, drilldown=["year"]) print "%-20s%10s%10s" % ("Year", "Count", "Total") for record in result.drilldown: print "%-20s%10d%10d" % (record["year"], record["record_count"], record["amount_sum"]) <file_sep>[datastore] type: sql url: sqlite:/// [datastore_production] type: sql url: postgres://localhost/data <file_sep>******************** Analytical Workspace ******************** Analytical workspace is ... TODO: describe. The analyital workspace manages cubes, shared (public) dimensions, data stores, model providers and model metadata. Provides aggregation browsers and maintains database connections. .. figure:: images/cubes-analytical-workspace-overview.png :align: center :width: 500px Analytical Workspace Typical cubes session takes place in a workspace. Workspace is configured either through a ``slicer.ini`` file or programatically. Using the file: .. code-block:: python from cubes import Workspace workspace = Workspace(config="slicer.ini") For more information about the configuration file options see :doc:`configuration` The manual workspace creation: .. code-block:: python from cubes import Workspace workspace = Workspace() workspace.register_default_store("sql", url="postgresql://localhost/data") workspace.load_model("model.json") Stores ====== Cube data are stored somewhere or might be provided by a service. We call this data source a data `store`. A workspace might use multiple stores to get content of the cubes. Built-in stores are: * ``sql`` – relational database store (`ROLAP`_) using star or snowflake schema * ``slicer`` – connection to another Cubes server * ``mixpanel`` – retrieves data from `Mixpanel`_ and makes it look like multidimensional cubes Supported SQL dialects (by SQLAlchemy) are: Drizzle, Firebird, Informix, Microsoft SQL Server, MySQL, Oracle, PostgreSQL, SQLite, Sybase .. _Mixpanel: https://mixpanel.com/docs/ .. _ROLAP: http://en.wikipedia.org/wiki/ROLAP See :doc:`configuration` for more information how to configure the stores. Model Providers =============== Model provider creates models of cubes, dimensions and other analytical objects. The models can be created from a metadata, database or an external source, such as API. Built-in model providers are: * ``static`` (also aliased as ``default``) – creates model objects from JSON data (files) * ``mixpanel`` – describes cubes as Mixpanel events and dimensions as Mixpanel properties To specify that the model is provided from other source than the metadata use the ``provider`` keyword in the model description: .. code-block:: javascript { "provider": "mixpanel", "store": "mixpanel" } The store:: [store] type: mixpanel api_key: MY_MIXPANEL_API_KEY api_secret: MY_MIXPANEL_API_SECRET <file_sep>Star Browser, Part 1: Mappings ============================== Star Browser is new aggregation browser in for the [Cubes](https://github.com/Stiivi/cubes) – lightweight Python OLAP Framework. I am going to talk briefly about current state and why new browser is needed. Then I will describe in more details the new browser: how mappings work, how tables are joined. At the end I will mention what will be added soon and what is planned in the future. Originally I wanted to write one blog post about this, but it was too long, so I am going to split it into three: * mappings (this one) * joins and denormalization * aggregations and new features Why new browser? ================ Current [denormalized browser](https://github.com/Stiivi/cubes/blob/master/cubes/backends/sql/browser.py) is good, but not good enough. Firstly, it has grown into a spaghetti-like structure inside and adding new features is quite difficult. Secondly, it is not immediately clear what is going on inside and not only new users are getting into troubles. For example the mapping of logical to physical is not obvious; denormalization is forced to be used, which is good at the end, but is making OLAP newbies puzzled. The new browser, called [StarBrowser](https://github.com/Stiivi/cubes/blob/master/cubes/backends/sql/star.py). is half-ready and will fix many of the old decisions with better ones. Mapping ======= Cubes provides an analyst's view of dimensions and their attributes by hiding the physical representation of data. One of the most important parts of proper OLAP on top of the relational database is the mapping of physical attributes to logical. First thing that was implemented in the new browser is proper mapping of logical attributes to physical table columns. For example, take a reference to an attribute *name* in a dimension *product*. What is the column of what table in which schema that contains the value of this dimension attribute? ![](http://media.tumblr.com/tumblr_m3ajdppDAa1qgmvbu.png) There are two ways how the mapping is being done: implicit and explicit. The simplest, straightforward and most customizable is the explicit way, where the actual column reference is provided in the model description: <pre class="prettyprint"> "mappings": { "product.name": "dm_products.product_name" } </pre> If it is in different schema or any part of the reference contains a dot: <pre class="prettyprint"> "mappings": { "product.name": { "schema": "sales", "table": "dm_products", "column": "product_name" } } </pre> Disadvantage of the explicit way is it's verbosity and the fact that developer has to write more metadata, obviously. Both, explicit and implicit mappings have ability to specify default database schema (if you are using Oracle, PostgreSQL or any other DB which supports schemas). The mapping process process is like this: ![](http://media.tumblr.com/tumblr_m3akrsmX9b1qgmvbu.png) Implicit Mapping ---------------- With implicit mapping one can match a database schema with logical model and does not have to specify additional mapping metadata. Expected structure is star schema with one table per (denormalized) dimension. Basic rules: * fact table should have same name as represented cube * dimension table should have same name as the represented dimension, for example: `product` (singular) * references without dimension name in them are expected to be in the fact table, for example: `amount`, `discount` (see note below for simple flat dimensions) * column name should have same name as dimension attribute: `name`, `code`, `description` * if attribute is localized, then there should be one column per localization and should have locale suffix: `description_en`, `description_sk`, `description_fr` (see below for more information) This means, that by default `product.name` is mapped to the table `product` and column `name`. Measure `amount` is mapped to the table `sales` and column `amount` What about dimensions that have only one attribute, like one would not have a full date but just a `year`? In this case it is kept in the fact table without need of separate dimension table. The attribute is treated in by the same rule as measure and is referenced by simple `year`. This is applied to all dimensions that have only one attribute (representing key as well). This dimension is referred to as *flat and without details*. Note for advanced users: this behavior can be disabled by setting `simplify_dimension_references` to `False` in the mapper. In that case you will have to have separate table for the dimension attribute and you will have to reference the attribute by full name. This might be useful when you know that your dimension will be more detailed. Localization ------------ Despite localization taking place first in the mapping process, we talk about it at the end, as it might be not so commonly used feature. From physical point of view, the data localization is very trivial and requires language denormalization - that means that each language has to have its own column for each attribute. In the logical model, some of the attributes may contain list of locales that are provided for the attribute. For example product category can be in English, Slovak or German. It is specified in the model like this: <pre class="prettyprint"> attributes = [{ "name" = "category", "locales" = [en, sk, de], }] </pre> During the mapping process, localized logical reference is created first: ![](http://media.tumblr.com/tumblr_m3aksf89Zb1qgmvbu.png) In short: if attribute is localizable and locale is requested, then locale suffix is added. If no such localization exists then default locale is used. Nothing happens to non-localizable attributes. For such attribute, three columns should exist in the physical model. There are two ways how the columns should be named. They should have attribute name with locale suffix such as `category_sk` and `category_en` (_underscore_ because it is more common in table column names), if implicit mapping is used. You can name the columns as you like, but you have to provide explicit mapping in the mapping dictionary. The key for the localized logical attribute should have `.locale` suffix, such as `product.category.sk` for Slovak version of category attribute of dimension product. Here the _dot_ is used because dots separate logical reference parts. Customization of the Implicit ----------------------------- The implicit mapping process has a little bit of customization as well: * *dimension table prefix*: you can specify what prefix will be used for all dimension tables. For example if the prefix is `dim_` and attribute is `product.name` then the table is going to be `dim_product`. * *fact table prefix*: used for constructing fact table name from cube name. Example: having prefix `ft_` all fact attributes of cube `sales` are going to be looked up in table `ft_sales` * *fact table name*: one can explicitly specify fact table name for each cube separately The Big Picture =============== Here is the whole mapping schema, after localization: ![](http://media.tumblr.com/tumblr_m3akttdCmK1qgmvbu.png) Links ===== The commented mapper source is [here](https://github.com/Stiivi/cubes/blob/master/cubes/backends/sql/common.py). * [github sources](https://github.com/Stiivi/cubes) * [Documentation](http://packages.python.org/cubes/) * [Mailing List](http://groups.google.com/group/cubes-discuss/) * [Submit issues](https://github.com/Stiivi/cubes/issues) * IRC channel [#databrewery](irc://irc.freenode.net/#databrewery) on irc.freenode.net <file_sep>Cubes Tutorial 2 - Model and Mappings ===================================== In the [first tutorial](http://blog.databrewery.org/post/12966527920/cubes-tutorial-1-getting-started) we talked about how to construct model programmatically and how to do basic aggregations. In this tutorial we are going to learn: * how to use model description file * why and how to use logical to physical mappings Data used are the same as in the first tutorial, [IBRD Balance Sheet](https://raw.github.com/Stiivi/cubes/master/tutorial/data/IBRD_Balance_Sheet__FY2010.csv) taken from [The World Bank](https://finances.worldbank.org/Accounting-and-Control/IBRD-Balance-Sheet-FY2010/e8yz-96c6). However, for purpose of this tutorial, the file was little bit manually edited: the column "Line Item" is split into two: _Subcategory_ and _Line Item_ to provide two more levels to total of three levels of hierarchy. Logical Model ------------- The Cubes framework uses a logical model. Logical model describes the data from user’s or analyst’s perspective: data how they are being measured, aggregated and reported. Model creates an abstraction layer therefore making reports independent of physical structure of the data. More information can be found in the [framework documentation](http://packages.python.org/cubes/model.html) The model description file is a JSON file containing a dictionary: <pre class="prettyprint"> { "dimensions": [ ... ], "cubes": { ... } } </pre> First we define the dimensions. They might be shared by multiple cubes, therefore they belong to the model space. There are two dimensions: _item_ and _year_ in our dataset. The _year_ dimension is flat, contains only one level and has no details. The dimension _item_ has three levels: _category_, _subcategory_ and _line item_. It looks like this: ![](http://media.tumblr.com/tumblr_lv67lezyq31qgmvbu.png) We define them as: <pre class="prettyprint"> { "dimensions": [ {"name":"item", "levels": ["category", "subcategory", "line_item"] }, {"name":"year"} ], "cubes": {...} } </pre> The levels of our tutorial dimensions are simple, with no details. There is little bit of implicit construction going on behind the scenes of dimension initialization, but that will be described later. In short: default hierarchy is created and for each level single attribute is created with the same name as the level. Next we define the cubes. The cube is in most cases specified by list of dimensions and measures: <pre class="prettyprint"> { "dimensions": [...], "cubes": { "irbd_balance": { "dimensions": ["item", "year"], "measures": ["amount"] } } } </pre> And we are done: we have dimensions and a cube. Well, almost done: we have to tell the framework, which attributes are going to be used. Attribute Naming ---------------- As mentioned before, cubes uses logical model to describe the data used in the reports. To assure consistency with dimension attribute naming, cubes uses sheme: <code>dimension.attribute</code> for non-flat dimensions. Why? Firstly, it decreases doubt to which dimension the attribute belongs. Secondly the <code>item.category</code> will always be <code>item.category</code> in the report, regardless of how the field will be named in the source and in which table the field exists. Imagine a snowflake schema: fact table in the middle with references to multiple tables containing various dimension data. There might be a dimension spanning through multiple tables, like product category in one table, product subcategory in another table. We should not care about what table the attribute comes from, we should care only that the attribute is called <code>category</code> and belongs to a dimension <code>product</code> for example. Another reason is, that in localized data, the analyst will use <code>item.category_label</code> and appropriate localized physical attribute will be used. Just to name few reasons. Knowing the naming scheme we have following cube attribute names: * <code>year</code> (it is flat dimension) * <code>item.category</code> * <code>item.subcategory</code> * <code>item.line_item</code> Problem is, that the table does not have the columns with the names. That is what mapping is for: maps logical attributes in the model into physical attributes in the table. Mapping ======= The source table looks like this: ![](http://media.tumblr.com/tumblr_lv67uvnhtJ1qgmvbu.png) We have to tell how the dimension attributes are mapped to the table columns. It is a simple dictionary where keys are dimension attribute names and values are physical table column names. <pre class="prettyprint"> { ... "cubes": { "irbd_balance": { ... "mappings": { "item.line_item": "line_item", "item.subcategory": "subcategory", "item.category": "category" } } } } </pre> _Note:_ The mapping values might be backend specific. They are physical table column names for the current implementation of the SQL backend. Full model looks like this: <pre class="prettyprint"> { "dimensions": [ {"name":"item", "levels": ["category", "subcategory", "line_item"] }, {"name":"year"} ], "cubes": { "irbd_balance": { "dimensions": ["item", "year"], "measures": ["amount"], "mappings": { "item.line_item": "line_item", "item.subcategory": "subcategory", "item.category": "category" } } } } </pre> Example ======= Now we have the model, saved for example in the <code>models/model_02.json</code>. Let's do some preparation: Define table names and a view name to be used later. The view is going to be used as logical abstraction. <pre class="prettyprint"> FACT_TABLE = "ft_irbd_balance" FACT_VIEW = "vft_irbd_balance" </pre> Load the data, as in the previous example, using the tutorial helper function (again, do not use that in production): <pre class="prettyprint"> engine = sqlalchemy.create_engine('sqlite:///:memory:') tutorial.create_table_from_csv(engine, "data/IBRD_Balance_Sheet__FY2010-t02.csv", table_name=FACT_TABLE, fields=[ ("category", "string"), ("subcategory", "string"), ("line_item", "string"), ("year", "integer"), ("amount", "integer")], create_id=True ) connection = engine.connect() </pre> The new data sheet is in the [github repository](https://github.com/Stiivi/cubes/raw/master/tutorial/data/IBRD_Balance_Sheet__FY2010-t02.csv). Load the model, get the cube and specify where cube's source data comes from: <pre class="prettyprint"> model = cubes.load_model("models/model_02.json") cube = model.cube("irbd_balance") cube.fact = FACT_TABLE </pre> We have to prepare the logical structures used by the browser. Currenlty provided is simple data denormalizer: creates one wide view with logical column names (optionally with localization). Following code initializes the denomralizer and creates a view for the cube: <pre class="prettyprint"> dn = cubes.backends.sql.SQLDenormalizer(cube, connection) dn.create_view(FACT_VIEW) </pre> And from this point on, we can continue as usual: <pre class="prettyprint"> browser = cubes.backends.sql.SQLBrowser(cube, connection, view_name = FACT_VIEW) cell = browser.full_cube() result = browser.aggregate(cell) print "Record count: %d" % result.summary["record_count"] print "Total amount: %d" % result.summary["amount_sum"] </pre> The tutorial sources can be found in the [Cubes github repository](https://github.com/Stiivi/cubes/tree/master/tutorial). Requires current git clone. Next: Drill-down through deep hierarchy. If you have any questions, suggestions, comments, let me know.<file_sep>#! /usr/bin/env python # # Mixpanel, Inc. -- http://mixpanel.com/ # # Python API client library to consume mixpanel.com analytics data. import hashlib import urllib import time try: import json except ImportError: import simplejson as json class MixpanelError(Exception): pass class Mixpanel(object): ENDPOINT = 'http://mixpanel.com/api' DATA_ENDPOINT = 'http://data.mixpanel.com/api' VERSION = '2.0' def __init__(self, api_key, api_secret): self.api_key = api_key self.api_secret = api_secret def request(self, methods, params, format='json', is_data=False): """ methods - List of methods to be joined, e.g. ['events', 'properties', 'values'] will give us http://mixpanel.com/api/2.0/events/properties/values/ params - Extra parameters associated with method """ params['api_key'] = self.api_key params['expire'] = int(time.time()) + 600 # Grant this request 10 minutes. params['format'] = format if 'sig' in params: del params['sig'] params['sig'] = self.hash_args(params) endpoint = self.DATA_ENDPOINT if is_data else self.ENDPOINT request_url = '/'.join([endpoint, str(self.VERSION)] + methods) + '/?' + self.unicode_urlencode(params) response = urllib.urlopen(request_url) # Standard response or error response is a JSON. Data response is one # JSON per line if not is_data or response.getcode() != 200: result = json.loads(response.read()) if "error" in result: raise MixpanelError(result["error"]) else: return result else: return _MixpanelDataIterator(response) def unicode_urlencode(self, params): """ Convert lists to JSON encoded strings, and correctly handle any unicode URL parameters. """ if isinstance(params, dict): params = params.items() for i, param in enumerate(params): if isinstance(param[1], list): params[i] = (param[0], json.dumps(param[1]),) return urllib.urlencode( [(k, isinstance(v, unicode) and v.encode('utf-8') or v) for k, v in params] ) def hash_args(self, args, secret=None): """ Hashes arguments by joining key=value pairs, appending a secret, and then taking the MD5 hex digest. """ for a in args: if isinstance(args[a], list): args[a] = json.dumps(args[a]) args_joined = '' for a in sorted(args.keys()): if isinstance(a, unicode): args_joined += a.encode('utf-8') else: args_joined += str(a) args_joined += '=' if isinstance(args[a], unicode): args_joined += args[a].encode('utf-8') else: args_joined += str(args[a]) hash = hashlib.md5(args_joined) if secret: hash.update(secret) elif self.api_secret: hash.update(self.api_secret) return hash.hexdigest() class _MixpanelDataIterator(object): def __init__(self, data): self.line_iterator = iter(data) def __iter__(self): return self def next(self): # From Mixpanel Documentation: # # One event per line, sorted by increasing timestamp. Each line is a # JSON dict, but the file itself is not valid JSON because there is no # enclosing object. Timestamps are in project time but expressed as # Unix time codes (but from_date and to_date are still interpreted in # project time). # # Source: https://mixpanel.com/docs/api-documentation/exporting-raw-data-you-inserted-into-mixpanel # line = next(self.line_iterator) return json.loads(line) if __name__ == '__main__': api = Mixpanel( api_key = 'YOUR KEY', api_secret = 'YOUR SECRET' ) data = api.request(['events'], { 'event' : ['pages',], 'unit' : 'hour', 'interval' : 24, 'type': 'general' }) print data <file_sep>import os import shutil import cubes from cubes.common import to_unicode_string try: from whoosh import index from whoosh.fields import Schema, TEXT, KEYWORD, ID, STORED, NUMERIC from whoosh.qparser import QueryParser from whoosh.query import Term from whoosh.sorting import FieldFacet except ImportError: from cubes.common import MissingPackage m = MissingPackage('whoosh', "search engine backend") Schema = index = m class WhooshIndexer(object): """Create a SQL index for Sphinx""" def __init__(self, browser, config=None): """Creates a cube indexer - object that will provide xmlpipe2 data source for Sphinx search engine (http://sphinxsearch.com). :Attributes: * `browser` - configured AggregationBrowser instance Generated attributes: * id * dimension * (hierarchy) - assume default * level * level key * dimension attribute * attribute value Config has to have section `search` with option `index_path` which is root path to indexes - one subdirectory per cube. """ super(WhooshIndexer, self).__init__() self.root_path = config.get("search", "index_path") self.browser = browser self.cube = browser.cube self.path = os.path.join(self.root_path, str(self.cube)) self.logger = self.browser.logger # FIXME: this is redundant, make one index per dimension or something # FIXME: the above requirement needs cubes browser to provide list of # all dimension values, which is not currently implemented nor in the # API definition def index(self, locales, init=False, **options): """Create index records for all dimensions in the cube""" # FIXME: this works only for one locale - specified in browser if init: self.initialize() if not index.exists_in(self.path): raise Exception("Index is not initialized in '%s'" % self.path) ix = index.open_dir(self.path) self.writer = ix.writer() # for dimension in self.cube.dimensions: options = options or {} cube = self.browser.cube for locale_tag, locale in enumerate(locales): for dim_tag, dimension in enumerate(cube.dimensions): self.index_dimension(dimension, dim_tag, locale=locale, locale_tag=locale_tag, **options) self.writer.commit() def index_dimension(self, dimension, dimension_tag, locale, locale_tag, **options): """Create dimension index records. If `Attribute.info` has key `no_search` set to `True`, then the field is skipped """ print "indexing %s, locale: %s" % (dimension, locale) hierarchy = dimension.hierarchy() # Switch browser locale self.browser.set_locale(locale) cell = cubes.Cell(self.cube) for depth_m1, level in enumerate(hierarchy.levels): depth = depth_m1 + 1 levels = hierarchy.levels[0:depth] keys = [level.key.ref() for level in levels] level_key = keys[-1] level_label = (level.label_attribute.ref()) if options.get("labels_only"): attributes = [level.label_attribute] else: attributes = [] for attr in level.attributes: if not attr.info or \ (attr.info and not attr.info.get("no_search")): attributes.append(attr) for record in self.browser.values(cell, dimension, depth): print "Dimension value: %s" % record path = [record[key] for key in keys] path_string = cubes.string_from_path(path) for attr in attributes: ref = to_unicode_string(attr.ref()) self.writer.add_document( locale=to_unicode_string(locale), dimension=dimension.name, level=level.name, depth=depth, path=path_string, level_key=record[level_key], level_label=record[level_label], attribute=attr.name, value=to_unicode_string(record[ref]) ) def initialize(self): if index.exists_in(self.path): self.logger.info("removing old index at '%s'" % self.path) shutil.rmtree(self.path) if not os.path.exists(self.path): self.logger.info("creating index at '%s'" % self.path) os.mkdir(self.path) schema = Schema( locale=TEXT(stored=True), dimension=TEXT(stored=True), level=STORED, depth=STORED, path=STORED, level_key=STORED, level_label=STORED, attribute=STORED, value=TEXT(stored=True) ) ix = index.create_in(self.path, schema) class WhooshSearcher(object): def __init__(self, browser, locales=None, index_path=None, default_limit=None, **options): super(WhooshSearcher, self).__init__() self.browser = browser self.cube = self.browser.cube self.root_path = index_path self.path = os.path.join(self.root_path, str(self.cube)) self.options = options self.index = index.open_dir(self.path) self.searcher = self.index.searcher() self.default_limit = default_limit or 20 self.locales = locales or [] def search(self, query, dimension=None, locale=None, limit=None): """Peform search using Whoosh. If `dimension` is set then only the one dimension will be searched.""" print "SEARCH IN %s QUERY '%s' LOCALE:%s" % (str(dimension), query, locale) qp = QueryParser("value", schema=self.index.schema) q = qp.parse(query) if dimension: q = q & Term('dimension', str(dimension)) if locale: q = q & Term('locale', str(locale)) # FIXME: set locale filter facet = FieldFacet("value") limit = limit or self.default_limit print "QUERY: %s" % q results = self.searcher.search(q, limit=limit, sortedby=facet) print "FOUND: %s results" % len(results) return WhooshSearchResult(self.browser, results) class WhooshSearchResult(object): def __init__(self, browser, results): super(WhooshSearchResult, self).__init__() self.browser = browser self.results = results self.total_found = len(results) self.error = None self.warning = None # @property # def dimensions(self): # return self.dimension_paths.keys() def dimension_matches(self, dimension): matches = [] dim_name = str(dimension) for match in self.results: if match["dimension"] == dim_name: dup = dict(match) path_str = match["path"] path = cubes.path_from_string(path_str) dup["path"] = path dup["path_string"] = path_str matches.append(dup) return matches def values(self, dimension, zipped=False): """Return values of search result. Attributes: * `zipped` - (experimental, might become standard) if ``True`` then returns tuples: (`path`, `record`) """ raise NotImplementedError("Fetching values for search matches is not implemented") cell = self.browser.full_cube() paths = [] for match in self.matches: if match["dimension"] == dimension: path_str = match["path"] path = cubes.path_from_string(path_str) paths.append(path) if paths: cut = cubes.SetCut(dimension, paths) cell.cuts = [cut] values = self.browser.values(cell, dimension) if zipped: # return 0 return [ {"meta": r[0], "record":r[1]} for r in zip(self.matches, values) ] else: return values else: return [] <file_sep>############################### Extension Developer's Reference ############################### This part of documentation is for developers that would like to develop various cubes extensions, such as browsers, stores, formatters and more. Contents: .. toctree:: :maxdepth: 2 backends providers auth <file_sep>############### Drill-down Tree ############### Goal: Create a tree by aggregating every level of a dimension. Level: Advanced. Drill-down ---------- Drill-down is an action that will provide more details about data. Drilling down through a dimension hierarchy will expand next level of the dimension. It can be compared to browsing through your directory structure. We create a function that will recursively traverse a dimension hierarchy and will print-out aggregations (count of records in this example) at the actual browsed location. **Attributes** * cell - cube cell to drill-down * dimension - dimension to be traversed through all levels * path - current path of the `dimension` Path is list of dimension points (keys) at each level. It is like file-system path. .. code-block:: python def drill_down(cell, dimension, path=[]): Get dimension's default hierarchy. Cubes supports multiple hierarchies, for example for date you might have year-month-day or year-quarter-month-day. Most dimensions will have one hierarchy, thought. .. code-block:: python hierarchy = dimension.hierarchy() *Base path* is path to the most detailed element, to the leaf of a tree, to the fact. Can we go deeper in the hierarchy? .. code-block:: python if hierarchy.path_is_base(path): return Get the next level in the hierarchy. `levels_for_path` returns list of levels according to provided path. When `drilldown` is set to `True` then one more level is returned. .. code-block:: python levels = hierarchy.levels_for_path(path,drilldown=True) current_level = levels[-1] We need to know name of the level key attribute which contains a path component. If the model does not explicitly specify key attribute for the level, then first attribute will be used: .. code-block:: python level_key = dimension.attribute_reference(current_level.key) For prettier display, we get name of attribute which contains label to be displayed for the current level. If there is no label attribute, then key attribute is used. .. code-block:: python level_label = dimension.attribute_reference(current_level.label_attribute) We do the aggregation of the cell... .. note:: Shell analogy: Think of ``ls $CELL`` command in commandline, where ``$CELL`` is a directory name. In this function we can think of ``$CELL`` to be same as current working directory (``pwd``) .. code-block:: python result = browser.aggregate(cell, drilldown=[dimension]) for record in result.drilldown: print "%s%s: %d" % (indent, record[level_label], record["record_count"]) ... And now the drill-down magic. First, construct new path by key attribute value appended to the current path: .. code-block:: python drill_path = path[:] + [record[level_key]] Then get a new cell slice for current path: .. code-block:: python drill_down_cell = cell.slice(dimension, drill_path) And do recursive drill-down: .. code-block:: python drill_down(drill_down_cell, dimension, drill_path) The whole recursive drill down function looks like this: .. figure:: images/cubes-tutorial03-drilldown_explained.png :align: center :width: 550px Recursive drill-down explained Whole working example can be found in the ``tutorial`` sources. Get the full cube (or any part of the cube you like): .. code-block:: python cell = browser.full_cube() And do the drill-down through the item dimension: .. code-block:: python drill_down(cell, cube.dimension("item")) The output should look like this:: a: 32 da: 8 Borrowings: 2 Client operations: 2 Investments: 2 Other: 2 dfb: 4 Currencies subject to restriction: 2 Unrestricted currencies: 2 i: 2 Trading: 2 lo: 2 Net loans outstanding: 2 nn: 2 Nonnegotiable, nonintrest-bearing demand obligations on account of subscribed capital: 2 oa: 6 Assets under retirement benefit plans: 2 Miscellaneous: 2 Premises and equipment (net): 2 Note that because we have changed our source data, we see level codes instead of level names. We will fix that later. Now focus on the drill-down. See that nice hierarchy tree? Now if you slice the cell through year 2010 and do the exact same drill-down: .. code-block:: python cell = cell.slice("year", [2010]) drill_down(cell, cube.dimension("item")) you will get similar tree, but only for year 2010 (obviously). Level Labels and Details ------------------------ Codes and ids are good for machines and programmers, they are short, might follow some scheme, easy to handle in scripts. Report users have no much use of them, as they look cryptic and have no meaning for the first sight. Our source data contains two columns for category and for subcategory: column with code and column with label for user interfaces. Both columns belong to the same dimension and to the same level. The key column is used by the analytical system to refer to the dimension point and the label is just decoration. Levels can have any number of detail attributes. The detail attributes have no analytical meaning and are just ignored during aggregations. If you want to do analysis based on an attribute, make it a separate dimension instead. So now we fix our model by specifying detail attributes for the levels: .. figure:: images/cubes-tutorial03-hierarchy-detail.png :align: center :width: 400px Attribute details. The model description is: .. code-block:: javascript "levels": [ { "name":"category", "label":"Category", "label_attribute": "category_label", "attributes": ["category", "category_label"] }, { "name":"subcategory", "label":"Sub-category", "label_attribute": "subcategory_label", "attributes": ["subcategory", "subcategory_label"] }, { "name":"line_item", "label":"Line Item", "attributes": ["line_item"] } ] } Note the `label_attribute` keys. They specify which attribute contains label to be displayed. Key attribute is by-default the first attribute in the list. If one wants to use some other attribute it can be specified in `key_attribute`. Because we added two new attributes, we have to add mappings for them: .. code-block:: javascript "mappings": { "item.line_item": "line_item", "item.subcategory": "subcategory", "item.subcategory_label": "subcategory_label", "item.category": "category", "item.category_label": "category_label" } Now the result will be with labels instead of codes:: Assets: 32 Derivative Assets: 8 Borrowings: 2 Client operations: 2 Investments: 2 Other: 2 Due from Banks: 4 Currencies subject to restriction: 2 Unrestricted currencies: 2 Investments: 2 Trading: 2 Loans Outstanding: 2 Net loans outstanding: 2 Nonnegotiable: 2 Nonnegotiable, nonintrest-bearing demand obligations on account of subscribed capital: 2 Other Assets: 6 Assets under retirement benefit plans: 2 Miscellaneous: 2 Premises and equipment (net): 2 <file_sep>from .blueprint import slicer, API_VERSION from .base import run_server, create_server from .auth import Authenticator, NotAuthenticated from .local import workspace <file_sep># -*- coding=utf -*- import unittest from sqlalchemy import create_engine, MetaData, Table, Integer, String, Column from cubes import * from ...common import CubesTestCaseBase from json import dumps def printable(obj): return dumps(obj, indent=4) class JoinsTestCaseBase(CubesTestCaseBase): sql_engine = "sqlite:///" def setUp(self): super(JoinsTestCaseBase, self).setUp() self.facts = Table("facts", self.metadata, Column("id", Integer), Column("id_date", Integer), Column("id_city", Integer), Column("amount", Integer) ) self.dim_date = Table("dim_date", self.metadata, Column("id", Integer), Column("year", Integer), Column("month", Integer), Column("day", Integer) ) self.dim_city = Table("dim_city", self.metadata, Column("id", Integer), Column("name", Integer), Column("country_code", Integer) ) self.dim_country = Table("dim_country", self.metadata, Column("code", String), Column("name", Integer) ) self.metadata.create_all() data = [ # Master-detail Match ( 1, 20130901, 1, 20), ( 2, 20130902, 1, 20), ( 3, 20130903, 1, 20), ( 4, 20130910, 1, 20), ( 5, 20130915, 1, 20), # -------- # ∑ 100 # No city dimension ( 6, 20131001, 9, 200), ( 7, 20131002, 9, 200), ( 8, 20131004, 9, 200), ( 9, 20131101, 7, 200), (10, 20131201, 7, 200), # -------- # ∑ 1000 # ======== # ∑ 1100 ] self.load_data(self.facts, data) data = [ (1, "Bratislava", "sk"), (2, "New York", "us") ] self.load_data(self.dim_city, data) data = [ ("sk", "Slovakia"), ("us", "United States") ] self.load_data(self.dim_country, data) data = [] for day in range(1, 31): row = (20130900+day, 2013, 9, day) data.append(row) self.load_data(self.dim_date, data) self.workspace = Workspace() self.workspace.register_default_store("sql", engine=self.engine, dimension_prefix="dim_") self.workspace.add_model(self.model_path("joins.json")) self.cube = self.workspace.cube("facts") self.workspace.logger.setLevel("DEBUG") self.engine.echo = "debug" class JoinsTestCase(JoinsTestCaseBase): def setUp(self): super(JoinsTestCase, self).setUp() self.day_drilldown = [("date", "default", "day")] self.month_drilldown = [("date", "default", "month")] self.year_drilldown = [("date", "default", "year")] self.city_drilldown = [("city")] def test_empty(self): browser = self.workspace.browser("facts") result = browser.aggregate() self.assertEqual(1100, result.summary["amount_sum"]) def aggregate_summary(self, cube, *args, **kwargs): browser = self.workspace.browser(cube) result = browser.aggregate(*args, **kwargs) return result.summary def aggregate_cells(self, cube, *args, **kwargs): browser = self.workspace.browser(cube) result = browser.aggregate(*args, **kwargs) return list(result.cells) def test_cell_count_match(self): cells = self.aggregate_cells("facts", drilldown=self.city_drilldown) self.assertEqual(1, len(cells)) self.assertEqual(100, cells[0]["amount_sum"]) self.assertEqual("Bratislava", cells[0]["city.name"]) def test_cell_count_master(self): cells = self.aggregate_cells("facts_master", drilldown=self.city_drilldown) summary = self.aggregate_summary("facts_master", drilldown=self.city_drilldown) self.assertEqual(1100, summary["amount_sum"]) cells = self.aggregate_cells("facts_master", drilldown=self.city_drilldown) self.assertEqual(2, len(cells)) names = [cell["city.name"] for cell in cells] self.assertSequenceEqual([None, "Bratislava"], names) amounts = [cell["amount_sum"] for cell in cells] self.assertSequenceEqual([1000, 100], amounts) def test_cell_count_detail(self): summary = self.aggregate_summary("facts_detail_city", drilldown=self.city_drilldown) self.assertEqual(100, summary["amount_sum"]) cells = self.aggregate_cells("facts_detail_city", drilldown=self.city_drilldown) self.assertEqual(2, len(cells)) names = [cell["city.name"] for cell in cells] self.assertSequenceEqual(["Bratislava", "New York"], names) amounts = [cell["amount_sum"] for cell in cells] self.assertSequenceEqual([100, 0], amounts) def test_cell_count_detail_not_found(self): cube = self.workspace.cube("facts_detail_city") cell = Cell(cube, [PointCut("city", [2])]) browser = self.workspace.browser(cube) result = browser.aggregate(cell, drilldown=[("city", None, "city")]) cells = list(result.cells) # We have one cell – one city from dim (nothing from facts) self.assertEqual(1, len(cells)) # ... however, we have no facts with that city. self.assertEqual(0, result.summary["record_count"]) # The summary should be coalesced to zero self.assertEqual(0, result.summary["amount_sum"]) names = [cell["city.name"] for cell in cells] self.assertSequenceEqual(["New York"], names) def test_three_tables(self): summary = self.aggregate_summary("threetables", drilldown=self.city_drilldown) self.assertEqual(100, summary["amount_sum"]) drilldown = self.city_drilldown+self.year_drilldown cells = self.aggregate_cells("threetables", drilldown=drilldown) self.assertEqual(1, len(cells)) def test_condition_and_drilldown(self): cube = self.workspace.cube("condition_and_drilldown") cell = Cell(cube, [PointCut("city", [2])]) dd = [("date", None, "day")] cells = self.aggregate_cells("condition_and_drilldown", cell=cell, drilldown=dd) # We want every day from the date table self.assertEqual(30, len(cells)) self.assertIn("record_count", cells[0]) self.assertIn("amount_sum", cells[0]) self.assertIn("date.year", cells[0]) self.assertIn("date.month", cells[0]) self.assertIn("date.day", cells[0]) self.assertNotIn("city.id", cells[0]) def test_split(self): cube = self.workspace.cube("condition_and_drilldown") split = Cell(cube, [RangeCut("date", [2013, 9, 1], [2013, 9, 3])]) cells = self.aggregate_cells("condition_and_drilldown", split=split) # We want every day from the date table self.assertEqual(2, len(cells)) self.assertIn(SPLIT_DIMENSION_NAME, cells[0]) # Both: master and detail split cube = self.workspace.cube("condition_and_drilldown") split = Cell(cube, [ RangeCut("date", [2013, 9, 1], [2013, 9, 3]), PointCut("city", [1]) ]) cells = self.aggregate_cells("condition_and_drilldown", split=split) # We want every day from the date table self.assertEqual(2, len(cells)) self.assertIn(SPLIT_DIMENSION_NAME, cells[0]) @unittest.skip("not yet") class JoinAggregateCompositionTestCase(JoinsTestCaseBase): def setUp(self): super(JoinAggregateCompositionTestCase, self).setUp() self.cube = self.workspace.cube("matchdetail") MD = [("date_master", "default", "day")] DD = [("date_detail", "default", "day")] MC = Cell(self.cube, [PointCut("city_master", [2])]) DC = Cell(self.cube, [PointCut("city_detail", [2])]) cases = [ { "args": (None, None, None, None), "cells": 0 }, { "args": ( MD, None, None, None), "cells": 5 }, { "args": (None, MC, None, None), "cells": 0 }, { "args": ( MD, MC, None, None), "cells": 0 }, { "args": (None, None, DD, None), "cells": 0 }, { "args": ( MD, None, DD, None), "cells": 0 }, { "args": (None, MC, DD, None), "cells": 0 }, { "args": ( MD, MC, DD, None), "cells": 0 }, { "args": (None, None, None, DC), "cells": 0 }, { "args": ( MD, None, None, DC), "cells": 0 }, { "args": (None, MC, None, DC), "cells": 0 }, { "args": ( MD, MC, None, DC), "cells": 0 }, { "args": (None, None, DD, DC), "cells": 0 }, { "args": ( MD, None, DD, DC), "cells": 0 }, { "args": (None, MC, DD, DC), "cells": 0 }, { "args": ( MD, MC, DD, DC), "cells": 0 } ] def test_all(self): pass <file_sep>######### Reference ######### Contents: .. toctree:: :maxdepth: 2 workspace model providers browser formatter backends server auth common <file_sep># -*- coding=utf -*- from contextlib import contextmanager from collections import namedtuple import datetime import time import csv import io from ..extensions import get_namespace, initialize_namespace from ..logging import get_logger from ..errors import * __all__ = [ "create_request_log_handler", "configured_request_log_handlers", "RequestLogger", "RequestLogHandler", "DefaultRequestLogHandler", "CSVFileRequestLogHandler", "QUERY_LOG_ITEMS" ] REQUEST_LOG_ITEMS = [ "timestamp", "method", "cube", "cell", "identity", "elapsed_time", "attributes", "split", "drilldown", "page", "page_size", "format", "headers" ] def create_request_log_handler(type_, *args, **kwargs): """Gets a new instance of a query logger.""" ns = get_namespace("request_log_handlers") if not ns: ns = initialize_namespace("request_log_handlers", root_class=RequestLogHandler, suffix="_request_log_handler", option_checking=True) try: factory = ns[type_] except KeyError: raise ConfigurationError("Unknown request log handler '%s'" % type_) return factory(*args, **kwargs) def configured_request_log_handlers(config, prefix="query_log", default_logger=None): """Returns configured query loggers as defined in the `config`.""" handlers = [] for section in config.sections(): if section.startswith(prefix): options = dict(config.items(section)) type_ = options.pop("type") if type_ == "default": logger = default_logger or get_logger() handler = create_request_log_handler("default", logger) else: handler = create_request_log_handler(type_, **options) handlers.append(handler) return handlers class RequestLogger(object): def __init__(self, handlers=None): if handlers: self.handlers = list(handlers) else: self.handlers = [] @contextmanager def log_time(self, method, browser, cell, identity=None, **other): start = time.time() yield elapsed = time.time() - start self.log(method, browser, cell, identity, elapsed, **other) def log(self, method, browser, cell, identity=None, elapsed=None, **other): record = { "timestamp": datetime.datetime.now(), "method": method, "cube": browser.cube.name, "identity": identity, "elapsed_time": elapsed or 0 } record.update(other) record["cell"] = str(cell) if cell is not None else None if "split" in record and record["split"] is not None: record["split"] = str(record["split"]) for handler in self.handlers: handler.write_record(record) class RequestLogHandler(object): def write_record(self, record): pass class DefaultRequestLogHandler(RequestLogHandler): def __init__(self, logger=None, **options): self.logger = logger def write_record(self, record): if record.get("cell"): cell_str = "'%s'" % record["cell"] else: cell_str = "none" if record.get("identity"): identity_str = "'%s'" % str(record["identity"]) else: identity_str = "none" self.logger.info("method:%s cube:%s cell:%s identity:%s time:%s" % (record["method"], record["cube"], cell_str, identity_str, record["elapsed_time"])) class CSVFileRequestLogHandler(RequestLogHandler): def __init__(self, path=None, **options): self.path = path def write_record(self, record): out = [] for key in REQUEST_LOG_ITEMS: item = record.get(key) if item is not None: item = unicode(item) out.append(item) with io.open(self.path, 'ab') as f: writer = csv.writer(f) writer.writerow(out) <file_sep>Architecture ============ What is inside the Cubes Python OLAP Framework? Here is a brief overview of the core modules, their purpose and functionality. The lightweight framework Cubes is composed of four public modules: ![](http://media.tumblr.com/tumblr_lzr33cGIx41qgmvbu.png) * *model* - Description of data (*metadata*): dimensions, hierarchies, attributes, labels, localizations. * *browser* - Aggregation browsing, slicing-and-dicing, drill-down. * *backends* - Actual aggregation implementation and utility functions. * *server* - WSGI HTTP server for Cubes Model ===== Logical model describes the data from user’s or analyst’s perspective: data how they are being measured, aggregated and reported. Model is independent of physical implementation of data. This physical independence makes it easier to focus on data instead on ways of how to get the data in understandable form. Cubes model is described by: ![](http://media.tumblr.com/tumblr_lzr33wXsWd1qgmvbu.png) * model object ([doc](http://packages.python.org/cubes/model.html#cubes.model.Model)) * list of cubes * dimensions of cubes (they are shared with all cubes within model) ([doc](http://packages.python.org/cubes/api/cubes.html#cubes.Dimension)) ([doc](http://packages.python.org/cubes/api/cubes.html#cubes.Dimension)) * hierarchies ([doc](http://packages.python.org/cubes/api/cubes.html#cubes.Hierarchy)) and hierarchy levels ([doc](http://packages.python.org/cubes/api/cubes.html#cubes.Level)) of dimensions (such as *category-subcategory*, *country-region-city*) * optional mappings from logical model to the physical model ([doc](http://packages.python.org/cubes/model.html#attribute-mappings)) * optional join specifications for star schemas, used by the SQL denormalizing backend ([doc](http://packages.python.org/cubes/model.html#joins)) There is a utility function provided for loading the model from a JSON file: <code>load_model</code>. The model module object are capable of being localized (see [Model Localization](http://packages.python.org/cubes/localization.html) for more information). The cubes provides localization at the metadata level (the model) and functionality to have localization at the data level. See also: [Model Documentation](http://packages.python.org/cubes/model.html) Browser ======= Core of the Cubes analytics functionality is the aggregation browser. The <code>browser</code> module contains utility classes and functions for the browser to work. ![](http://media.tumblr.com/tumblr_lzr34qlXN11qgmvbu.png) The module components are: * **Cell** – specification of the portion of the cube to be explored, sliced or drilled down. Each cell is specified by a set of cuts. A cell without any cuts represents whole cube. * **Cut** – definition where the cell is going to be sliced through single dimension. There are three types of cuts: point, range and set. The types of cuts: * **Point Cut** – Defines one single point on a dimension where the cube is going to be sliced. The point might be at any level of hierarchy. The point is specified by "path". Examples of point cut: <code>[2010]</code> for *year* level of Date dimension, <code>[2010,1,7]</code> for full date point. * **Range Cut** – Defines two points (dimension paths) on a sortable dimension between whose the cell is going to be sliced from cube. * **Set Cut** – Defines list of multiple points (dimension paths) which are going to be included in the sliced cell. Example of point cut effect: ![](http://media.tumblr.com/tumblr_lzr35pNwxo1qgmvbu.png) The module provides couple utility functions: * <code>path_from_string</code> - construct a dimension path (point) from a string * <code>string_from_path</code> - get a string representation of a dimension path (point) * <code>string_from_cuts</code> and <code>cuts_from_string</code> are for conversion between string and list of cuts. (Currently only list of point cuts are supported in the string representation) The aggregation browser can: * aggregate a cell (<code>aggregate(cell)</code>) * drill-down through multiple dimensions and aggregate (<code>aggregate(cell, drilldown="date")</code>) * get all detailed facts within the cell (<code>facts(cell)</code>) * get single fact (<code>fact(id)</code>) There is convenience function <code>report(cell, report)</code> that can be implemented by backend in more efficient way to get multiple aggregation queries in single call. More about aggregated browsing can be found in the [Cubes documentation](http://packages.python.org/cubes/api/cubes.html#aggregate-browsing). Backends ======== Actual aggregation is provided by the backends. The backend should implement aggregation browser interface. ![](http://media.tumblr.com/tumblr_lzr37ayQWJ1qgmvbu.png) Cubes comes with built-in [ROLAP](http://en.wikipedia.org/wiki/ROLAP) backend which uses SQL database through SQLAlchemy. The backend has two major components: * *aggregation browser* that works on single denormalized view or a table * *SQL denormalizer* helper class that converts [star schema](http://en.wikipedia.org/wiki/Star_schema) into a denormalized view or table (kind of materialisation). There was an attempt to write a [Mongo DB backend](https://github.com/Stiivi/cubes/tree/master/cubes/backends/mongo), but it does not work any more, it is included in the sources only as reminder, that there should be a mongo backend sometime in the future. Anyone can write a backend. If you are interested, drop me a line. Server ====== Cubes comes with Slicer - a WSGI HTTP OLAP server with API for most of the cubes framework functionality. The server is based on the Werkzeug framework. ![](http://media.tumblr.com/tumblr_lzr37v5B6G1qgmvbu.png) Intended use of the slicer is basically as follows: * application prepares the cell to be aggregated, drilled, listed... The *cell* might be whole cube. * HTTP request is sent to the server * the server uses appropriate aggregation browser backend (note that currently there is only one: SQL denormalized) to compute the request * Slicer returns a JSON reply to the application For more information, please refer to the Cubes [Slicer server documentation](http://packages.python.org/cubes/server.html). One more thing... ================= There are plenty things to get improved, of course. Current focus is not on performance, but on achieving simple usability. The Cubes sources can be found on Github: https://github.com/stiivi/cubes. There is also a IRC channel #databrewery on irc.freenode.net (I try to be there during late evening CET). Issues can be reported on the [github project page](https://github.com/stiivi/cubes/issues?sort=created&direction=desc&state=open). If you have any questions, suggestions, recommendations, just let me know. <file_sep>******** Backends ******** Backend is a collection of objects that provide Cubes functionality for various types of data stores, browsers or model providers. Included backends: Contents: .. toctree:: :maxdepth: 2 sql mongo mixpanel slicer <file_sep>from .base import create_searcher <file_sep>******************************** Authentication and Authorization ******************************** .. seealso:: :doc:`../auth` Authentication -------------- .. autoclass:: cubes.server.auth.Authorizer .. autoclass:: cubes.server.auth.SimpleAuthorizer Authorization ------------- .. autoclass:: cubes.auth.Authenticator <file_sep># -*- coding=utf -*- from flask import current_app from werkzeug.local import LocalProxy # Application Context # =================== # # Readability proxies def _get_workspace(): return current_app.cubes_workspace def _get_logger(): return current_app.cubes_workspace.logger workspace = LocalProxy(_get_workspace) logger = LocalProxy(_get_logger) <file_sep>import re from functools import partial import pytz from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta, SA from utils import now import logging _NOOP = lambda x: '||%s||' % x # FIXME: Warning: this kills all multiple argument occurences # This function removes all duplicates of query parameters that can be # obtained through args.getlist() (such as "?drilldown=x&drilldown=y") def proc_wildcards(args): copy = args.copy() for k, v in args.iterlists(): k = op(k) v = [ op(ve) for ve in v ] copy.setlist(k, v) return copy def op(target): matches = re.finditer(r'\|\|([\w\d]+)\|\|', target) for mk in matches: token = mk.group(1) new_val = transform_token(token) target = target.replace(mk.group(), new_val) logging.debug("Replaced wildcard with %s", target) return target def truncated_now(unit): d = now() d = d.replace(minute=0, second=0, microsecond=0) if unit == 'hour': pass elif unit == 'day': d = d.replace(hour=0) elif unit == 'week': d = d.replace(hour=0) # calc most recent week beginning # TODO make week beginning configurable #d = d - timedelta(days=( d.weekday() + 2 if d.weekday() < 5 else d.weekday() - 5 )) d = d + relativedelta(days=-6, weekday=SA) elif unit == 'month': d = d.replace(day=1, hour=0) elif unit == 'quarter': d = d.replace(day=1, hour=0) # TODO calc most recent beginning of a quarter d = d - relativedelta(months=((d.month - 1) % 3)) elif unit == 'year': d = d.replace(month=1, day=1, hour=0) else: raise ValueError("Unrecognized unit: %s" % unit) return d def subtract_units(d, amt, unit): tdargs = {} if unit == 'hour': tdargs['hours'] = amt elif unit == 'day': tdargs['days'] = amt elif unit == 'week': tdargs['days'] = amt * 7 elif unit == 'month': tdargs['months'] = amt elif unit == 'quarter': tdargs['months'] = amt * 3 elif unit == 'year': tdargs['years'] = amt return d - relativedelta(**tdargs) _the_n_regex = re.compile(r'^last(\d+)(\w+)?$') _UNITS = set(['hour', 'day', 'week', 'month', 'quarter', 'year']) def lastN(token, amt=14, unit="day", format='%Y,%m,%d', tzinfo='America/NewYork'): m = _the_n_regex.search(token) if m: munit = m.group(2).lower() if m.group(2) is not None else '' if munit in _UNITS: unit = munit elif munit[:-1] in _UNITS: unit = munit[:-1] mamt = int(m.group(1)) if mamt >= 0: amt = mamt # start with now() truncated to most recent instance of the unit n = truncated_now(unit) n = subtract_units(n, amt, unit) if unit == 'hour': format = format + ",%H" return n.strftime(format) def transform_token(token): if _wildcards.has_key(token): return _wildcards[token](token) for func in _regex_wildcards: tx = func(token) if tx is not None: return tx return _NOOP _wildcards = { 'today': partial(lastN, amt=0, unit='day', format='%Y,%m,%d'), 'yesterday': partial(lastN, amt=1, unit='day', format='%Y,%m,%d') } _regex_wildcards = ( lastN, ) if __name__ == '__main__': cuts = ( 'event_date:||last7||-||yesterday||', 'event_date:||last7weeks||-||today||', 'event_date:||last0month||-||yesterday||', 'event_date:||last7month||-||yesterday||', 'event_date:||last7quarters||-||yesterday||', 'event_date:||last7years||-||yesterday||', ) for cut in cuts: a = { 'cut': cut } a2 = proc_wildcards(a) print "%-40s %s" % (cut, a2) <file_sep>################### Cubes Release Notes ################### .. toctree:: :maxdepth: 2 1.0 0.6-0.10 <file_sep>*************** MongoDB Backend *************** Requirements: `pymongo`:: pip install pymongo Store Configuration =================== Type is ``mongo2`` * ``url`` – Mongo database URL, for example ``mongodb://localhost:37017/`` * ``database`` – name of the Mongo database * ``collection`` – name of mongo collection where documents are facts Example:: [datastore] type: mongo2 url: mongodb://localhost:37017/ database: MongoBI collection: activations Mappings ======== Custom aggregate with function provided in the mapping: .. code-block:: javascript "aggregates": [ { "name": "subtotal", } ], "mappings": { "subtotas": { "field": "cart_subtotal", "group": { "$sum": "$subtotal" } } } Collection Filter ================= To apply a filter for the whole collection: .. code-block:: javascript "browser_options": { "filter": { "type": "only_this_type", "category": 1 } } <file_sep># This example is using the hello_world data and model [workspace] models_path: ../hello_world log_level: info [server] host: localhost port: 5000 reload: yes prettyprint: yes [models] main: model.json [datastore] type: sql url: sqlite:///../hello_world/data.sqlite <file_sep>"""Multidimensional searching using Sphinx search engine WARNING: This is just preliminary prototype, use at your own risk of having your application broken later. """ import cubes import sphinxapi import xml.sax.saxutils from xml.sax.xmlreader import AttributesImpl from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey import sqlalchemy import collections EMPTY_ATTRS = AttributesImpl({}) def get_locale_tag(locale, locales): try: tag = locales.index(locale) except ValueError: tag = 0 return tag class SphinxSearchResult(object): def __init__(self, browser): super(SphinxSearchResult, self).__init__() self.browser = browser self.matches = None # self.dimension_paths = collections.OrderedDict() self.total_found = 0 self.error = None self.warning = None # @property # def dimensions(self): # return self.dimension_paths.keys() def dimension_matches(self, dimension): matches = [] for match in self.matches: if match["dimension"] == dimension: dup = dict(match) path_str = match["path"] path = cubes.path_from_string(path_str) dup["path"] = path dup["path_string"] = path_str matches.append(dup) return matches def values(self, dimension, zipped=False): """Return values of search result. Attributes: * `zipped` - (experimental, might become standard) if ``True`` then returns tuples: (`path`, `record`) """ raise NotImplementedError("Fetching values for search matches is not implemented") cell = self.browser.full_cube() paths = [] for match in self.matches: if match["dimension"] == dimension: path_str = match["path"] path = cubes.path_from_string(path_str) paths.append(path) if paths: cut = cubes.SetCut(dimension, paths) cell.cuts = [cut] values = self.browser.values(cell, dimension) if zipped: # return 0 return [ {"meta": r[0], "record":r[1]} for r in zip(self.matches, values) ] else: return values else: return [] class SphinxSearcher(object): """docstring for SphinxSearch""" def __init__(self, browser, locales=None, host=None, port=None, **options): """Create sphing search object. :Parameters: * `browser` - Aggregation browser * `host` - host where searchd is running (optional) * `port` - port where searchd is listening (optional) """ super(SphinxSearcher, self).__init__() self.browser = browser self.host = host self.port = port self.options = options self.locales = locales or [] def _dimension_tag(self, dimension): """Private method to get integer value from dimension name. Currently it uses index in ordered list of dimensions of the browser's cube""" names = [dim.name for dim in self.browser.cube.dimensions] try: tag = names.index(str(dimension)) except ValueError: tag = None return tag def search(self, query, dimension=None, locale=None): """Peform search using Sphinx. If `dimension` is set then only the one dimension will be searched.""" print "SEARCH IN %s QUERY '%s' LOCALE:%s" % (str(dimension), query, locale) locale_tag = get_locale_tag(locale, self.locales) sphinx = sphinxapi.SphinxClient(**self.options) if self.host: sphinx.SetServer(self.host, self.port) if dimension: tag = self._dimension_tag(dimension) if tag is None: raise Exception("No dimension %s" % dimension) sphinx.SetFilter("dimension_tag", [tag]) if locale_tag is not None: sphinx.SetFilter("locale_tag", [locale_tag]) # FIXME: Quick hack for <NAME> sphinx.SetLimits(0, 1000) index_name = self.browser.cube.name sphinx.SetSortMode(sphinxapi.SPH_SORT_ATTR_ASC, "attribute_value") results = sphinx.Query(query, index = str(index_name)) result = SphinxSearchResult(self.browser) if not results: return result result.total_found = results["total_found"] grouped = collections.OrderedDict() result.matches = [match["attrs"] for match in results["matches"]] result.error = sphinx.GetLastError() result.warning = sphinx.GetLastWarning() return result class XMLSphinxIndexer(object): """Create a SQL index for Sphinx""" def __init__(self, browser, options=None, out=None): """Creates a cube indexer - object that will provide xmlpipe2 data source for Sphinx search engine (http://sphinxsearch.com). :Attributes: * `browser` - configured AggregationBrowser instance Generated attributes: * id * dimension * dimension_tag: integer identifying a dimension * (hierarchy) - assume default * level * level key * dimension attribute * attribute value """ super(XMLSphinxIndexer, self).__init__() self.browser = browser self.cube = browser.cube self.options = options self.output = xml.sax.saxutils.XMLGenerator(out=out, encoding = 'utf-8') self._counter = 1 def initialize(self): self.output.startDocument() self.output.startElement( u'sphinx:docset', EMPTY_ATTRS) # START schema self.output.startElement( u'sphinx:schema', EMPTY_ATTRS) fields = ["value"] attributes = [ ("locale_tag", "int"), ("dimension", "string"), ("dimension_tag", "int"), ("level", "string"), ("depth", "int"), ("path", "string"), ("attribute", "string"), ("attribute_value", "string"), ("level_key", "string"), ("level_label", "string")] for field in fields: attrs = AttributesImpl({"name":field}) self.output.startElement(u'sphinx:field', attrs) self.output.endElement(u'sphinx:field') for (name, ftype) in attributes: attrs = AttributesImpl({"name":name, "type":ftype}) self.output.startElement(u'sphinx:attr', attrs) self.output.endElement(u'sphinx:attr') # END schema self.output.endElement(u'sphinx:schema') def finalize(self): self.output.endElement( u'sphinx:docset') self.output.endDocument() def index(self, locales, **options): """Create index records for all dimensions in the cube""" # FIXME: this works only for one locale - specified in browser # for dimension in self.cube.dimensions: self.initialize() for locale in locales: locale_tag = get_locale_tag(locale, locales) for dim_tag, dimension in enumerate(self.cube.dimensions): self.index_dimension(dimension, dim_tag, locale=locale, locale_tag= locale_tag, **options) self.finalize() def index_dimension(self, dimension, dimension_tag, locale, locale_tag, **options): """Create dimension index records.""" hierarchy = dimension.hierarchy() # Switch browser locale self.browser.set_locale(locale) cell = cubes.Cell(self.cube) label_only = bool(options.get("labels_only")) for depth_m1, level in enumerate(hierarchy.levels): depth = depth_m1 + 1 levels = hierarchy.levels[0:depth] keys = [level.key.ref() for level in levels] level_key = keys[-1] level_label = (level.label_attribute.ref()) for record in self.browser.values(cell, dimension, depth): path = [record[key] for key in keys] path_string = cubes.string_from_path(path) for attr in level.attributes: if label_only and str(attr) != str(level.label_attribute): continue fname = attr.ref() irecord = { "locale_tag": locale_tag, "dimension": dimension.name, "dimension_tag": dimension_tag, "level": level.name, "depth": depth, "path": path_string, "attribute": attr.name, "value": record[fname], "level_key": record[level_key], "level_label": record[level_label] } self.add(irecord) def add(self, irecord): """Emits index record (sphinx document) to the output XML stream.""" attrs = AttributesImpl({"id":str(self._counter)}) self._counter += 1 self.output.startElement( u'sphinx:document', attrs) record = dict(irecord) record["attribute_value"] = record["value"] attrs = AttributesImpl({}) for key, value in record.items(): self.output.startElement( key, attrs) self.output.characters(unicode(value)) self.output.endElement(key) self.output.endElement( u'sphinx:document') <file_sep>import unittest import os import json import re import sqlalchemy import datetime from ...common import CubesTestCaseBase from sqlalchemy import Table, Column, Integer, Float, String, MetaData, ForeignKey from sqlalchemy import create_engine from cubes.backends.sql.mapper import coalesce_physical from cubes.backends.sql.browser import * from cubes import * from cubes.errors import * class StarSQLTestCase(CubesTestCaseBase): def setUp(self): super(StarSQLTestCase, self).setUp() self.engine = sqlalchemy.create_engine('sqlite://') metadata = sqlalchemy.MetaData(bind=self.engine) table = Table('sales', metadata, Column('id', Integer, primary_key=True), Column('amount', Float), Column('discount', Float), Column('fact_detail1', String), Column('fact_detail2', String), Column('flag', String), Column('date_id', Integer), Column('product_id', Integer), Column('category_id', Integer) ) table = Table('dim_date', metadata, Column('id', Integer, primary_key=True), Column('day', Integer), Column('month', Integer), Column('month_name', String), Column('month_sname', String), Column('year', Integer) ) table = Table('dim_product', metadata, Column('id', Integer, primary_key=True), Column('category_id', Integer), Column('product_name', String), ) table = Table('dim_category', metadata, Column('id', Integer, primary_key=True), Column('category_name_en', String), Column('category_name_sk', String), Column('subcategory_id', Integer), Column('subcategory_name_en', String), Column('subcategory_name_sk', String) ) self.metadata = metadata self.metadata.create_all(self.engine) self.workspace = self.create_workspace({"engine":self.engine}, "sql_star_test.json") # self.workspace = Workspace() # self.workspace.register_default_store("sql", engine=self.engine) # self.workspace.add_model() self.cube = self.workspace.cube("sales") store = self.workspace.get_store("default") self.browser = SnowflakeBrowser(self.cube,store=store, dimension_prefix="dim_") self.browser.debug = True self.mapper = self.browser.mapper @unittest.skip("Obsolete") class QueryContextTestCase(StarSQLTestCase): def setUp(self): super(QueryContextTestCase, self).setUp() def test_denormalize(self): statement = self.browser.denormalized_statement() cols = [column.name for column in statement.columns] self.assertEqual(18, len(cols)) def test_denormalize_locales(self): """Denormalized view should have all locales expanded""" statement = self.browser.denormalized_statement(expand_locales=True) cols = [column.name for column in statement.columns] self.assertEqual(20, len(cols)) # TODO: move this to tests/browser.py def test_levels_from_drilldown(self): cell = Cell(self.cube) dim = self.cube.dimension("date") l_year = dim.level("year") l_month = dim.level("month") l_day = dim.level("day") drilldown = [("date", None, "year")] result = levels_from_drilldown(cell, drilldown) self.assertEqual(1, len(result)) dd = result[0] self.assertEqual(dim, dd.dimension) self.assertEqual(dim.hierarchy(), dd.hierarchy) self.assertSequenceEqual([l_year], dd.levels) self.assertEqual(["date.year"], dd.keys) # Try "next level" cut = PointCut("date", [2010]) cell = Cell(self.cube, [cut]) drilldown = [("date", None, "year")] result = levels_from_drilldown(cell, drilldown) self.assertEqual(1, len(result)) dd = result[0] self.assertEqual(dim, dd.dimension) self.assertEqual(dim.hierarchy(), dd.hierarchy) self.assertSequenceEqual([l_year], dd.levels) self.assertEqual(["date.year"], dd.keys) drilldown = ["date"] result = levels_from_drilldown(cell, drilldown) self.assertEqual(1, len(result)) dd = result[0] self.assertEqual(dim, dd.dimension) self.assertEqual(dim.hierarchy(), dd.hierarchy) self.assertSequenceEqual([l_year, l_month], dd.levels) self.assertEqual(["date.year", "date.month"], dd.keys) # Try with range cell # cut = RangeCut("date", [2009], [2010]) # cell = Cell(self.cube, [cut]) # drilldown = ["date"] # expected = [(dim, dim.hierarchy(), [l_year, l_month])] # self.assertEqual(expected, levels_from_drilldown(cell, drilldown)) # drilldown = [("date", None, "year")] # expected = [(dim, dim.hierarchy(), [l_year])] # self.assertEqual(expected, levels_from_drilldown(cell, drilldown)) # cut = RangeCut("date", [2009], [2010, 1]) # cell = Cell(self.cube, [cut]) # drilldown = ["date"] # expected = [(dim, dim.hierarchy(), [l_year, l_month, l_day])] # self.assertEqual(expected, levels_from_drilldown(cell, drilldown)) # Try "last level" cut = PointCut("date", [2010, 1,2]) cell = Cell(self.cube, [cut]) drilldown = [("date", None, "day")] result = levels_from_drilldown(cell, drilldown) dd = result[0] self.assertSequenceEqual([l_year, l_month, l_day], dd.levels) self.assertEqual(["date.year", "date.month", "date.id"], dd.keys) drilldown = ["date"] with self.assertRaisesRegexp(HierarchyError, "has only 3 levels"): levels_from_drilldown(cell, drilldown) class RelevantJoinsTestCase(StarSQLTestCase): def setUp(self): super(RelevantJoinsTestCase, self).setUp() self.joins = [ {"master":"fact.date_id", "detail": "dim_date.id"}, {"master":["fact", "product_id"], "detail": "dim_product.id"}, {"master":"fact.contract_date_id", "detail": "dim_date.id", "alias":"dim_contract_date"}, {"master":"dim_product.subcategory_id", "detail": "dim_subcategory.id"}, {"master":"dim_subcategory.category_id", "detail": "dim_category.id"} ] self.mapper._collect_joins(self.joins) self.mapper.mappings.update( { "product.subcategory": "dim_subcategory.subcategory_id", "product.subcategory_name.en": "dim_subcategory.subcategory_name_en", "product.subcategory_name.sk": "dim_subcategory.subcategory_name_sk" } ) self.logger = get_logger() self.logger.setLevel("DEBUG") def attributes(self, *attrs): return self.cube.get_attributes(attrs) def test_basic_joins(self): relevant = self.mapper.relevant_joins(self.attributes("date.year")) self.assertEqual(1, len(relevant)) self.assertEqual("dim_date", relevant[0].detail.table) self.assertEqual(None, relevant[0].alias) relevant = self.mapper.relevant_joins(self.attributes("product.name")) self.assertEqual(1, len(relevant)) self.assertEqual("dim_product", relevant[0].detail.table) self.assertEqual(None, relevant[0].alias) @unittest.skip("missing model") def test_alias(self): relevant = self.mapper.relevant_joins(self.attributes("date.year")) self.assertEqual(1, len(relevant)) self.assertEqual("dim_date", relevant[0].detail.table) self.assertEqual("dim_contract_date", relevant[0].alias) def test_snowflake(self): relevant = self.mapper.relevant_joins(self.attributes("product.subcategory")) self.assertEqual(2, len(relevant)) test = sorted([r.detail.table for r in relevant]) self.assertEqual(["dim_product","dim_subcategory"], test) self.assertEqual([None, None], [r.alias for r in relevant]) relevant = self.mapper.relevant_joins(self.attributes("product.category_name")) self.assertEqual(3, len(relevant)) test = sorted([r.detail.table for r in relevant]) self.assertEqual(["dim_category", "dim_product","dim_subcategory"], test) self.assertEqual([None, None, None], [r.alias for r in relevant]) class MapperTestCase(unittest.TestCase): def test_coalesce_physical(self): def assertPhysical(expected, actual, default=None): ref = coalesce_physical(actual, default) self.assertEqual(expected, ref) assertPhysical((None, "table", "column", None, None, None, None), "table.column") assertPhysical((None, "table", "column.foo", None, None, None, None), "table.column.foo") assertPhysical((None, "table", "column", None, None, None, None), ["table", "column"]) assertPhysical(("schema", "table", "column", None, None, None, None), ["schema", "table", "column"]) assertPhysical((None, "table", "column", None, None, None, None), {"column": "column"}, "table") assertPhysical((None, "table", "column", None, None, None, None), {"table": "table", "column": "column"}) assertPhysical(("schema", "table", "column", None, None, None, None), {"schema": "schema", "table": "table", "column": "column"}) assertPhysical(("schema", "table", "column", "day", None, None, None), {"schema": "schema", "table": "table", "column": "column", "extract": "day"}) class StarSQLBrowserTestCase(StarSQLTestCase): def setUp(self): super(StarSQLBrowserTestCase, self).setUp() fact = { "id":1, "amount":100, "discount":20, "fact_detail1":"foo", "fact_detail2":"bar", "flag":1, "date_id":20120308, "product_id":1, "category_id":10 } date = { "id": 20120308, "day": 8, "month": 3, "month_name": "March", "month_sname": "Mar", "year": 2012 } product = { "id": 1, "category_id": 10, "product_name": "Cool Thing" } category = { "id": 10, "category_id": 10, "category_name_en": "Things", "category_name_sk": "Veci", "subcategory_id": 20, "subcategory_name_en": "Cool Things", "subcategory_name_sk": "Super Veci" } ftable = self.table("sales") self.engine.execute(ftable.insert(), fact) table = self.table("dim_date") self.engine.execute(table.insert(), date) ptable = self.table("dim_product") self.engine.execute(ptable.insert(), product) table = self.table("dim_category") self.engine.execute(table.insert(), category) for i in range(1, 10): record = dict(product) record["id"] = product["id"] + i record["product_name"] = product["product_name"] + str(i) self.engine.execute(ptable.insert(), record) for j in range(1, 10): for i in range(1, 10): record = dict(fact) record["id"] = fact["id"] + i + j *10 record["product_id"] = fact["product_id"] + i self.engine.execute(ftable.insert(), record) def table(self, name): return sqlalchemy.Table(name, self.metadata, autoload=True) def test_get_fact(self): """Get single fact""" self.assertEqual(True, self.mapper.simplify_dimension_references) fact = self.browser.fact(1) self.assertIsNotNone(fact) self.assertEqual(18, len(fact.keys())) def test_get_facts(self): """Get single fact""" # TODO: remove this when happy self.browser.logger.setLevel("DEBUG") self.assertEqual(True, self.mapper.simplify_dimension_references) facts = list(self.browser.facts()) result = self.engine.execute(self.table("sales").count()) count = result.fetchone()[0] self.assertEqual(82, count) self.assertIsNotNone(facts) self.assertEqual(82, len(facts)) self.assertEqual(18, len(facts[0])) attrs = ["date.year", "amount"] facts = list(self.browser.facts(fields=attrs)) self.assertEqual(82, len(facts)) # We get 3: fact key + 2 self.assertEqual(3, len(facts[0])) def test_get_members(self): """Get dimension values""" members = list(self.browser.members(None,"product",1)) self.assertIsNotNone(members) self.assertEqual(1, len(members)) members = list(self.browser.members(None,"product",2)) self.assertIsNotNone(members) self.assertEqual(1, len(members)) members = list(self.browser.members(None,"product",3)) self.assertIsNotNone(members) self.assertEqual(10, len(members)) def test_cut_details(self): cut = PointCut("date", [2012]) details = self.browser.cut_details(cut) self.assertEqual([{"date.year":2012, "_key":2012, "_label":2012}], details) cut = PointCut("date", [2013]) details = self.browser.cut_details(cut) self.assertEqual(None, details) cut = PointCut("date", [2012,3]) details = self.browser.cut_details(cut) self.assertEqual([{"date.year":2012, "_key":2012, "_label":2012}, {"date.month_name":"March", "date.month_sname":"Mar", "date.month":3, "_key":3, "_label":"March"}], details) @unittest.skip("test model is not suitable") def test_cell_details(self): cell = Cell(self.cube, [PointCut("date", [2012])]) details = self.browser.cell_details(cell) self.assertEqual(1, len(details)) cell = Cell(self.cube, [PointCut("product", [10])]) details = self.browser.cell_details(cell) self.assertEqual(1, len(details)) def test_aggregate(self): self.browser.logger.setLevel("DEBUG") result = self.browser.aggregate() keys = sorted(result.summary.keys()) self.assertEqual(4, len(keys)) self.assertEqual(["amount_min", "amount_sum", "discount_sum", "record_count"], keys) result = self.browser.aggregate(None, measures=["amount"]) keys = sorted(result.summary.keys()) self.assertEqual(2, len(keys)) self.assertEqual(["amount_min", "amount_sum"], keys) result = self.browser.aggregate(None, measures=["discount"]) keys = sorted(result.summary.keys()) self.assertEqual(1, len(keys)) self.assertEqual(["discount_sum"], keys) class HierarchyTestCase(CubesTestCaseBase): def setUp(self): super(HierarchyTestCase, self).setUp() engine = create_engine("sqlite:///") metadata = MetaData(bind=engine) d_table = Table("dim_date", metadata, Column('id', Integer, primary_key=True), Column('year', Integer), Column('quarter', Integer), Column('month', Integer), Column('week', Integer), Column('day', Integer)) f_table = Table("ft_cube", metadata, Column('id', Integer, primary_key=True), Column('date_id', Integer)) metadata.create_all() start_date = datetime.date(2000, 1, 1) end_date = datetime.date(2001, 1,1) delta = datetime.timedelta(1) date = start_date d_insert = d_table.insert() f_insert = f_table.insert() i = 1 while date < end_date: record = { "id": int(date.strftime('%Y%m%d')), "year": date.year, "quarter": (date.month-1)//3+1, "month": date.month, "week": int(date.strftime("%U")), "day": date.day } engine.execute(d_insert.values(record)) # For each date insert one fact record record = {"id": i, "date_id": record["id"] } engine.execute(f_insert.values(record)) date = date + delta i += 1 workspace = self.create_workspace({"engine": engine}, "hierarchy.json") self.cube = workspace.cube("cube") self.browser = SnowflakeBrowser(self.cube, store=workspace.get_store("default"), dimension_prefix="dim_", fact_prefix="ft_") self.browser.debug = True self.browser.logger.setLevel("DEBUG") def test_cell(self): cell = Cell(self.cube) result = self.browser.aggregate(cell) self.assertEqual(366, result.summary["record_count"]) cut = PointCut("date", [2000, 2]) cell = Cell(self.cube, [cut]) result = self.browser.aggregate(cell) self.assertEqual(29, result.summary["record_count"]) cut = PointCut("date", [2000, 2], hierarchy="ywd") cell = Cell(self.cube, [cut]) result = self.browser.aggregate(cell) self.assertEqual(7, result.summary["record_count"]) cut = PointCut("date", [2000, 1], hierarchy="yqmd") cell = Cell(self.cube, [cut]) result = self.browser.aggregate(cell) self.assertEqual(91, result.summary["record_count"]) def test_drilldown(self): cell = Cell(self.cube) result = self.browser.aggregate(cell, drilldown=["date"]) self.assertEqual(1, result.total_cell_count) result = self.browser.aggregate(cell, drilldown=["date:month"]) self.assertEqual(12, result.total_cell_count) result = self.browser.aggregate(cell, drilldown=[("date", None, "month")]) self.assertEqual(12, result.total_cell_count) result = self.browser.aggregate(cell, drilldown=[("date", None, "day")]) self.assertEqual(366, result.total_cell_count) # Test year-quarter-month-day hier = self.cube.dimension("date").hierarchy("yqmd") result = self.browser.aggregate(cell, drilldown=[("date", "yqmd", "day")]) self.assertEqual(366, result.total_cell_count) result = self.browser.aggregate(cell, drilldown=[("date", "yqmd", "quarter")]) self.assertEqual(4, result.total_cell_count) def test_range_drilldown(self): cut = RangeCut("date", [2000, 1], [2000,3]) cell = Cell(self.cube, [cut]) result = self.browser.aggregate(cell, drilldown=["date"]) # This should test that it does not drilldown on range self.assertEqual(1, result.total_cell_count) def test_implicit_level(self): cut = PointCut("date", [2000]) cell = Cell(self.cube, [cut]) result = self.browser.aggregate(cell, drilldown=["date"]) self.assertEqual(12, result.total_cell_count) result = self.browser.aggregate(cell, drilldown=["date:month"]) self.assertEqual(12, result.total_cell_count) result = self.browser.aggregate(cell, drilldown=[("date", None, "month")]) self.assertEqual(12, result.total_cell_count) result = self.browser.aggregate(cell, drilldown=[("date", None, "day")]) self.assertEqual(366, result.total_cell_count) def test_hierarchy_compatibility(self): cut = PointCut("date", [2000]) cell = Cell(self.cube, [cut]) with self.assertRaises(HierarchyError): self.browser.aggregate(cell, drilldown=[("date", "yqmd", None)]) cut = PointCut("date", [2000], hierarchy="yqmd") cell = Cell(self.cube, [cut]) result = self.browser.aggregate(cell, drilldown=[("date", "yqmd", None)]) self.assertEqual(4, result.total_cell_count) cut = PointCut("date", [2000], hierarchy="yqmd") cell = Cell(self.cube, [cut]) self.assertRaises(HierarchyError, self.browser.aggregate, cell, drilldown=[("date", "ywd", None)]) cut = PointCut("date", [2000], hierarchy="ywd") cell = Cell(self.cube, [cut]) result = self.browser.aggregate(cell, drilldown=[("date", "ywd", None)]) self.assertEqual(54, result.total_cell_count) class SQLBrowserTestCase(CubesTestCaseBase): sql_engine = "sqlite:///" def setUp(self): model = { "cubes": [ { "name": "facts", "dimensions": ["date", "country"], "measures": ["amount"] } ], "dimensions": [ { "name": "date", "levels": ["year", "month", "day"] }, { "name": "country", }, ], "mappings": { "date.year": "year", "date.month": "month", "date.day": "day" } } super(SQLBrowserTestCase, self).setUp() self.facts = Table("facts", self.metadata, Column("id", Integer), Column("year", Integer), Column("month", Integer), Column("day", Integer), Column("country", String), Column("amount", Integer) ) self.metadata.create_all() data = [ ( 1,2012,1,1,"sk",10), ( 2,2012,1,2,"sk",10), ( 3,2012,2,3,"sk",10), ( 4,2012,2,4,"at",10), ( 5,2012,3,5,"at",10), ( 6,2012,3,1,"uk",100), ( 7,2012,4,2,"uk",100), ( 8,2012,4,3,"uk",100), ( 9,2012,5,4,"uk",100), (10,2012,5,5,"uk",100), (11,2013,1,1,"fr",1000), (12,2013,1,2,"fr",1000), (13,2013,2,3,"fr",1000), (14,2013,2,4,"fr",1000), (15,2013,3,5,"fr",1000) ] self.load_data(self.facts, data) workspace = self.create_workspace(model=model) self.browser = workspace.browser("facts") self.browser.logger.setLevel("DEBUG") self.cube = self.browser.cube def test_aggregate_empty_cell(self): result = self.browser.aggregate() self.assertIsNotNone(result.summary) self.assertEqual(1, len(result.summary.keys())) self.assertEqual("amount_sum", result.summary.keys()[0]) self.assertEqual(5550, result.summary["amount_sum"]) def test_aggregate_condition(self): cut = PointCut("date", [2012]) cell = Cell(self.cube, [cut]) result = self.browser.aggregate(cell) self.assertIsNotNone(result.summary) self.assertEqual(1, len(result.summary.keys())) self.assertEqual("amount_sum", result.summary.keys()[0]) self.assertEqual(550, result.summary["amount_sum"]) cells = list(result.cells) self.assertEqual(0, len(cells)) def test_aggregate_drilldown(self): drilldown = [("date", None, "year")] result = self.browser.aggregate(drilldown=drilldown) cells = list(result.cells) self.assertEqual(2, len(cells)) self.assertItemsEqual(["date.year", "amount_sum"], cells[0].keys()) self.assertEqual(550, cells[0]["amount_sum"]) self.assertEqual(2012, cells[0]["date.year"]) self.assertEqual(5000, cells[1]["amount_sum"]) self.assertEqual(2013, cells[1]["date.year"]) def test_aggregate_drilldown_order(self): drilldown = [("country", None, "country")] result = self.browser.aggregate(drilldown=drilldown) cells = list(result.cells) self.assertEqual(4, len(cells)) self.assertItemsEqual(["country", "amount_sum"], cells[0].keys()) values = [cell["country"] for cell in cells] self.assertSequenceEqual(["at", "fr", "sk", "uk"], values) order = [("country", "desc")] result = self.browser.aggregate(drilldown=drilldown, order=order) cells = list(result.cells) values = [cell["country"] for cell in cells] self.assertSequenceEqual(["uk", "sk", "fr", "at"], values) # test_drilldown_pagination # test_split # test_drilldown_selected_attributes # drilldown high cardinality # Test: <file_sep># -*- coding=utf -*- from ...server.logging import RequestLogHandler, REQUEST_LOG_ITEMS from sqlalchemy import create_engine, Table, MetaData, Column from sqlalchemy import Integer, Sequence, DateTime, String, Float from sqlalchemy.exc import NoSuchTableError class SQLRequestLogHandler(RequestLogHandler): def __init__(self, url=None, table=None, **options): self.url = url self.engine = create_engine(url) metadata = MetaData(bind=self.engine) try: self.table = Table(table, metadata, autoload=True) except NoSuchTableError: columns = [ Column('id', Integer, Sequence(table+"_seq"), primary_key=True), Column('timestamp', DateTime), Column('method', String), Column('cube', String), Column('cell', String), Column('identity', String), Column('elapsed_time', Float), Column('attributes', String), Column('split', String), Column('drilldown', String), Column('page', Integer), Column('page_size', Integer), Column('format', String), Column('header', String), ] self.table = Table(table, metadata, extend_existing=True, *columns) self.table.create() def write_record(self, record): insert = self.table.insert().values(record) self.engine.execute(insert) <file_sep>import unittest import cubes import os from common import DATA_PATH @unittest.skip class CombinationsTestCase(unittest.TestCase): def setUp(self): self.nodea = ('a', (1,2,3)) self.nodeb = ('b', (99,88)) self.nodec = ('c',('x','y')) self.noded = ('d', ('m')) def test_levels(self): combos = cubes.common.combine_nodes([self.nodea]) self.assertEqual(len(combos), 3) combos = cubes.common.combine_nodes([self.nodeb]) self.assertEqual(len(combos), 2) combos = cubes.common.combine_nodes([self.noded]) self.assertEqual(len(combos), 1) def test_combos(self): combos = cubes.common.combine_nodes([self.nodea, self.nodeb]) self.assertEqual(len(combos), 11) combos = cubes.common.combine_nodes([self.nodea, self.nodeb, self.nodec]) self.assertEqual(len(combos), 35) def test_required_one(self): nodes = [self.nodea, self.nodeb, self.nodec] required = [self.nodea] combos = cubes.common.combine_nodes(nodes, required) self.assertEqual(len(combos), 27) for combo in combos: flag = False for item in combo: if tuple(item[0]) == self.nodea: flag = True break self.assertTrue(flag, "All combinations should contain required node") def test_required_more(self): nodes = [self.nodea, self.nodeb, self.nodec, self.noded] required = [self.nodea, self.nodeb] combos = cubes.common.combine_nodes(nodes, required) self.assertEqual(len(combos), 36) for combo in combos: flag = False for item in combo: if tuple(item[0]) == self.nodea or tuple(item[0]) == self.nodeb: flag = True break self.assertTrue(flag, "All combinations should contain both required nodes") @unittest.skip class CuboidsTestCase(unittest.TestCase): def setUp(self): self.model_path = os.path.join(DATA_PATH, 'model.json') self.model = cubes.model_from_path(self.model_path) self.cube = self.model.cubes.get("contracts") def test_combine_dimensions(self): dims = self.cube.dimensions results = cubes.common.all_cuboids(dims) # for r in results: # print "=== COMBO:" # for c in r: # print "--- %s: %s" % (c[0][0].name, c[1]) self.assertEqual(len(results), 863) dim = self.cube.dimension("date") results = cubes.common.all_cuboids(dims, [dim]) self.assertEqual(len(results), 648) def test_should_not_accept_unknown_dimension(self): foo_desc = { "name": "foo", "levels": {"level": {"key": "boo"}}} foo_dim = cubes.create_dimension(foo_desc) self.assertRaises(AttributeError, cubes.common.all_cuboids, self.cube.dimensions, [foo_dim]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(CombinationsTestCase)) suite.addTest(unittest.makeSuite(CuboidsTestCase)) return suite <file_sep>**************** Mixpanel Backend **************** The Mixpanel backends provides mixpanel events as cubes and event properties as dimensions. Features: * two measure aggregates: `total` and `unique` * two derived measure aggregates: `total_sma` and `unique_sma` (simple moving average) * time dimension with two hierarchies: * `ymdh` (default): `year`, `month`, `day` and `hour` * `wdh`: `week`, `day` and `hour` * aggregation at year or top level * drill-down without the time dimension (approximation) * list of facts Store Configuration and Model ============================= Type is ``mixpanel`` * ``api_key`` – your Mixpanel API key * ``api_secret`` – Mixpanel API secret To obtain your API key log-in to the Mixpanel, go to Account, then Projects – you will see a list of key/secret pairs for your projects. Example:: [datastore] type: mixpanel api_key: <KEY> api_secret: <KEY> Model ----- Mixpanel backend generates the model on-the-fly. You have to specify that the provider is ``mixpanel`` not the static model file itself: .. code-block:: javascript { "name": "mixpanel", "provider": "mixpanel" } Model Customization ------------------- It is possible to customize various properties of a cube or a dimension. The customizable properties are: `name`, `label`, `description`, `category` and `info`. For example to customize `search engine` dimension: .. code-block:: javascript "dimensions": [ { "name": "search_engine", "label": "Search Engine", "description": "The search engine a user came from" } ] Limit the Dimensions ~~~~~~~~~~~~~~~~~~~~ The list of dimensions can be limited by using a browser option ``allowed_dimensions`` or ``denied_dimensions``: Following will allow only one dimension: .. code-block:: javascript "browser_options": { "allowed_dimensions": "search_engine" } The ``browser_options`` can be specified at the model level – applies to all cubes, or just at a cube level – applies only to that cube. Dimension names ~~~~~~~~~~~~~~~ By default dimension names are the same as property names. If a property name contains a special character such as space or ``$`` it is replaced by a underscore. To use a different, custom dimension name add the dimension-to-property mapping: .. code-block:: javascript "mappings": { "city": "$city", "initial_referrer": "$initial_referrer" } And define the dimension in the model as above. Built-in dimension models with simplifiend name and with labels: * `initial_referrer` * `initial_referring_domain` * `search_engine` * `keyword` * `os` * `browser` * `referrer` * `referring_domain` * `country_code` * `city` Source: `Mixpanel Special or reserved properties`_. .. _Mixpanel Special or reserved properties: https://mixpanel.com/docs/properties-or-segments/special-or-reserved-properties Cube Names ~~~~~~~~~~ By default, cube names are the same as event names. To use a custom cube name add a mapping for ``cube:CUBENAME``: .. code-block:: json "mappings": { "cube:campaign_delivery": "$campaign_delivery" } Example ======= Create a ``slicer.ini``: .. code-block:: ini [workspace] model: model.json [datastore] type: mixpanel api_key: YOUR_API_KEY api_secret: YOUR_API_SECRET [server] prettyprint: true Create a ``model.json``: .. code-block:: json { "provider": "mixpanel" } Run the server: .. code-block:: sh slicer serve slicer.ini Get a list of cubes: .. codeb-block:: sh curl "http://localhost:5000/cubes" Notes ===== .. important:: It is not possible to specify a cut for the `time` dimension at the hour level. This is the Mixpanel's limitation – it expects the from-to range to be at day granularity. <file_sep>++++++++ Backends ++++++++ <file_sep>++++++++ Backends ++++++++ Two objects play major role in Cubes backends: * `aggregation browser` – responsible for aggregations, fact listing, dimension member listing * `store` – represents a database connection, shared by multiple browsers Store ===== Data for cubes are provided by a `data store` – every cube has one. Stores have to be subclasses of `Store` for cubes to be able to find them. .. figure:: images/cubes-backend_store.png :align: center :width: 400px Backend data store. Required methods: * `__init__(**options)` – initialize the store with `options`. Even if you use named arguments, you have to include the `**options`. * `close()` – release all resources associated with the store, close database connections * `default_browser_name` – a class variable with browser name that will be created for a cube, if not specified otherwise A `Store` class: .. code-block:: python from cubes import Store class MyStore(Store): default_browser_name = "my" def __init__(self, **options): super(MyStore, self).__init__(**options) # configure the store here ... .. note:: The custom store has to be a subclass of `Store` so Cubes can find it. The name will be derived from the class name: `MyStore` will become `my`, `AnotherSQLStore` will become `another_sql`. To explicitly specify a store name, set the `__identifier__` class variable. Configuration ------------- The store is configured from a `slicer.ini` file. The store instance receives all options from it's configuration file section as arguments to the `__init__()` method. It is highly recommended that the store provides a class variable named `__options__` which is a list of parameter description dictionaries. The list is used for properly configuring the store from end-user tools, such as Slicer. It also provides information about how to convert options into appropriate data types. Example: .. code-block:: python class MyStore(Store): default_browser_name = "my" __options__ = [ { "name": "collection", "type": "string", "description": "Name of data collection" }, { "name": "unfold", "type": "bool", "description": "Unfold nested structures" } } def __init__(self, collection=None, unfold=Flase, **options): super(MyStore, self).__init__(**options) self.collection = collection self.unfold = unfold An example configuration for this store would look like: .. code-block:: ini [store] type: my collection: data unfold: true Aggregation Browser =================== Browser retrieves data from a `store` and works in a context of a `cube` and `locale`. .. figure:: images/cubes-backend_browser.png :align: center :width: 400px Backend data store. Methods to be implemented: * `__init__(cube, store, locale)` – initialize the browser for `cube` stored in a `store` and use model and data `locale`. * `features()` – return a dictionary with browser's features * `aggregate()`, `facts()`, `fact()`, `members()` – all basic browser actions that take a cell as first argument. See :class:`AggregationBrowser` for more information. For example: .. code-block:: python class SnowflakeBrowser(AggregationBrowser): def __init__(self, cube, store, locale=None, **options): super(SnowflakeBrowser, self).__init__(cube, store, locale) # browser initialization... Name of the example store will be ``snowflake``. To explicitly set the browser name set the `__identifier__` class property: .. code-block:: python class SnowflakeBrowser(AggregationBrowser): __identifier__ = "sql" In this case, the browser will be known by the name ``sql``. .. note:: The current `AggregationBrowser` API towards the extension development is provisional and will verylikely change. The change will mostly involve removal of requirements for preparation of arguments and return value. Aggregate --------- Arguments: * `cell` – cube cell to be aggregated * `aggregates` – list of aggregates to be considered (needs to be prepared) * `drilldown` – drill-down specification (needs to be prepared, see :class:`cubes.Drilldown`) * `split` (optional browser feature) – virtual cell-based dimension to split the aggregation cell into two: within the split cell or outside of the split cell * `page`, `page_size` – page number and size of the page for paginated results * `order` – order specification (needs to be prepared) .. code-block:: python def aggregate(self, cell=None, aggregates=None, drilldown=None, split=None, attributes=None, page=None, page_size=None, order=None, **options): # Preparation of arguments: if not cell: cell = Cell(self.cube) aggregates = self.prepare_aggregates(aggregates) drilldown = Drilldown(drilldown, cell) order = self.prepare_order(order, is_aggregate=True) # # ... do the aggregation here ... # result = AggregationResult(cell=cell, aggregates=aggregates) # Set the result cells iterator (required) result.cells = ... result.labels = ... # Optional: result.total_cell_count = ... result.summary = ... return result Facts ----- .. code-block:: python def facts(self, cell=None, fields=None, order=None, page=None, page_size=None): cell = cell or Cell(self.cube) attributes = self.cube.get_attributes(fields) order = self.prepare_order(order, is_aggregate=False) # # ... fetch the facts here ... # # facts = ... an iterable ... # result = Facts(facts, attributes) return result Browser and Cube Features ------------------------- The browser features for all or a particuliar cube (if there are differences) are returned by the :meth:`cubes.AggregationBrowser.features` method. The method is expected to return at least one key in the dictionary: ``actions`` with list of browser actions that the browser supports. Browser actions are: ``aggregate``, ``fact``, ``facts``, ``members`` and ``cell``. Optional but recommended is setting the list of ``aggregate_functions`` – functions for measures computed in the browser's engine. The other is ``post_aggregate_functions`` – list of fucntions used as post-aggregation outside of the browser. Configuration ------------- The browser is configured by merging: * model's `options` property * cube's `options` property * store's configuration options (from ``slicer.ini``) The browser instance receives the options as parameters to the `__init__()` method. <file_sep># -*- coding=utf -*- import unittest from sqlalchemy import create_engine, MetaData, Table, Integer, String, Column from cubes import * from cubes.errors import * from ...common import CubesTestCaseBase from json import dumps def printable(obj): return dumps(obj, indent=4) class AggregatesTestCase(CubesTestCaseBase): sql_engine = "sqlite:///" def setUp(self): super(AggregatesTestCase, self).setUp() self.facts = Table("facts", self.metadata, Column("id", Integer), Column("year", Integer), Column("amount", Integer), Column("price", Integer), Column("discount", Integer) ) self.metadata.create_all() data = [ ( 1, 2010, 1, 100, 0), ( 2, 2010, 2, 200, 10), ( 3, 2010, 4, 300, 0), ( 4, 2010, 8, 400, 20), ( 5, 2011, 1, 500, 0), ( 6, 2011, 2, 600, 40), ( 7, 2011, 4, 700, 0), ( 8, 2011, 8, 800, 80), ( 9, 2012, 1, 100, 0), (10, 2012, 2, 200, 0), (11, 2012, 4, 300, 0), (12, 2012, 8, 400, 10), (13, 2013, 1, 500, 0), (14, 2013, 2, 600, 0), (15, 2013, 4, 700, 0), (16, 2013, 8, 800, 20), ] self.load_data(self.facts, data) self.workspace = self.create_workspace(model="aggregates.json") self.workspace.logger.setLevel("DEBUG") def test_unknown_function(self): browser = self.workspace.browser("unknown_function") with self.assertRaisesRegexp(ArgumentError, "Unknown.*function"): browser.aggregate() def test_explicit(self): browser = self.workspace.browser("default") result = browser.aggregate() summary = result.summary self.assertEqual(60, summary["amount_sum"]) self.assertEqual(16, summary["count"]) def test_post_calculation(self): browser = self.workspace.browser("postcalc_in_measure") result = browser.aggregate(drilldown=["year"]) cells = list(result.cells) aggregates = sorted(cells[0].keys()) self.assertSequenceEqual(['amount_sma', 'amount_sum', 'count', 'year'], aggregates) <file_sep>*************** Data Formatters *************** Data and metadata from aggregation result can be transformed to one of multiple forms using formatters: .. code-block:: python formatter = cubes.create_formatter("text_table") result = browser.aggregate(cell, drilldown="date") print formatter.format(result, "date") Available formmaters: * `text_table` – text output for result of drilling down through one dimension * `simple_data_table` – returns a dictionary with `header` and `rows` * `simple_html_table` – returns a HTML table representation of result table cells * `cross_table` – cross table structure with attributes `rows` – row headings, `columns` – column headings and `data` with rows of cells * `html_cross_table` – HTML version of the `cross_table` formatter .. seealso:: :doc:`reference/formatter` Formatter reference <file_sep>*************** Model Reference *************** Model - Cubes meta-data objects and functionality for working with them. :doc:`../model` .. seealso:: :doc:`providers` Model providers – objects for constructing model objects from other kinds of sources, even during run-time. Creating model objects from metadata ==================================== Following methods are used to create model objects from a metadata dicitonary. .. autofunction:: cubes.create_cube .. autofunction:: cubes.create_dimension .. autofunction:: cubes.create_level .. autofunction:: cubes.create_attribute .. autofunction:: cubes.create_measure .. autofunction:: cubes.create_measure_aggregate .. autofunction:: cubes.attribute_list Model components ================ .. note:: The `Model` class is no longer publicly available and should not be used. For more information, please see :class:`cubes.Workspace`. Cube ---- .. autoclass:: cubes.Cube Dimension, Hierarchy and Level ------------------------------ .. autoclass:: cubes.Dimension .. autoclass:: cubes.Hierarchy .. autoclass:: cubes.Level Attributes, Measures and Aggregates ----------------------------------- .. autoclass:: cubes.AttributeBase .. autoclass:: cubes.Attribute .. autoclass:: cubes.Measure .. autoclass:: cubes.MeasureAggregate .. exception:: ModelError Exception raised when there is an error with model and its structure, mostly during model construction. .. exception:: ModelIncosistencyError Raised when there is incosistency in model structure, mostly when model was created programatically in a wrong way by mismatching classes or misonfiguration. .. exception:: NoSuchDimensionError Raised when a dimension is requested that does not exist in the model. .. exception:: NoSuchAttributeError Raised when an unknown attribute, measure or detail requested. <file_sep>++++++++++++ Installation ++++++++++++ There are two options how to install cubes: basic common installation - recommended mostly for users starting with Cubes. Then there is customized installation with requirements explained. Basic Installation ================== The cubes has optional requirements: * `SQLAlchemy`_ for SQL database aggregation browsing backend (version >= 0.7.4) * `Flask`_ for Slicer OLAP HTTP server .. note:: If you never used Python before, you might have to get the `pip installer`_ first, if you do not have it already. .. note:: The command-line tool :doc:`Slicer<slicer>` does not require knowledge of Python. You do not need to know the language if you just want to :doc:`serve<server>` OLAP data. For quick satisfaction of requirements install the packages:: pip install pytz python-dateutil pip install sqlalchemy flask Then install the Cubes:: pip install cubes .. _SQLAlchemy: http://www.sqlalchemy.org/download.html .. _Werkzeug: http://flask.pocoo.org/ Quick Start or Hello World! =========================== Download the sources from the `Cubes Github repository`_. Go to the ``examples/hello_world`` folder:: git clone git://github.com/Stiivi/cubes.git cd cubes cd examples/hello_world Prepare data and run the :doc:`OLAP server<server>`:: python prepare_data.py slicer serve slicer.ini And try to do some queries:: curl "http://localhost:5000/aggregate" curl "http://localhost:5000/aggregate?drilldown=year" curl "http://localhost:5000/aggregate?drilldown=item" curl "http://localhost:5000/aggregate?drilldown=item&cut=item:e" .. _Cubes Github repository: https://github.com/Stiivi/cubes Customized Installation ======================= The project sources are stored in the `Github repository`_. .. _Github repository: https://github.com/Stiivi/cubes Download from Github:: git clone git://github.com/Stiivi/cubes.git The requirements for SQLAlchemy_ and Werkzeug_ are optional and you do not need them if you are going to use another kind of backend. Install:: cd cubes pip install -r requirements.txt pip install -r requirements-optional.txt python setup.py install <file_sep>Last time I was talking about how [logical attributes are mapped to the physical table columns](http://blog.databrewery.org/post/22119118550) in the Star Browser. Today I will describe how joins are formed and how denormalization is going to be used. The Star Browser is new aggregation browser in for the [Cubes](https://github.com/Stiivi/cubes) – lightweight Python OLAP Framework. Star, Snowflake, Master and Detail ================================= Star browser supports a star: ![](http://media.tumblr.com/tumblr_m3ajfbXcHo1qgmvbu.png) ... and snowflake database schema: ![](http://media.tumblr.com/tumblr_m3ajfn8QYt1qgmvbu.png) The browser should know how to construct the star/snowflake and that is why you have to specify the joins of the schema. The join specification is very simple: <pre class="prettyprint"> "joins" = [ { "master": "fact_sales.product_id", "detail": "dim_product.id" } ] </pre> Joins support only single-column keys, therefore you might have to create surrogate keys for your dimensions. As in mappings, if you have specific needs for explicitly mentioning database schema or any other reason where `table.column` reference is not enough, you might write: <pre class="prettyprint"> "joins" = [ { "master": "fact_sales.product_id", "detail": { "schema": "sales", "table": "dim_products", "column": "id" } ] </pre> What if you need to join same table twice? For example, you have list of organizations and you want to use it as both: supplier and service consumer. It can be done by specifying alias in the joins: <pre class="prettyprint"> "joins" = [ { "master": "contracts.supplier_id", "detail": "organisations.id", "alias": "suppliers" }, { "master": "contracts.consumer_id", "detail": "organisations.id", "alias": "consumers" } ] </pre> In the mappings you refer to the table by alias specified in the joins, not by real table name: <pre class="prettyprint"> "mappings": { "supplier.name": "suppliers.org_name", "consumer.name": "consumers.org_name" } </pre> ![](http://media.tumblr.com/tumblr_m3ajian3sA1qgmvbu.png) Relevant Joins and Denormalization ---------------------------------- The new mapper joins only tables that are relevant for given query. That is, if you are browsing by only one dimension, say *product*, then only product dimension table is joined. Joins are slow, expensive and the denormalization can be helpful: ![](http://media.tumblr.com/tumblr_m3ajglKwV11qgmvbu.png) The old browser is based purely on the denormalized view. Despite having a performance gain, it has several disadvantages. From the join/performance perspective the major one is, that the denormalization is required and it is not possible to browse data in a database that was "read-only". This requirements was also one unnecessary step for beginners, which can be considered as usability problem. Current implementation of the *Mapper* and *StarBrowser* allows denormalization to be integrated in a way, that it might be used based on needs and situation: ![](http://media.tumblr.com/tumblr_m3d4ctMm6K1qgmvbu.png) It is not yet there and this is what needs to be done: * function for denormalization - similar to the old one: will take cube and view name and will create denormalized view (or a table) * make mapper accept the view and ignore joins Goal is not just to slap denormalization in, but to make it a configurable alternative to default star browsing. From user's perspective, the workflow will be: 1. browse star/snowflake until need for denormalization arises 2. configure denormalization and create denormalized view 3. browse the denormalized view The proposed options are: `use_denormalization`, `denormalized_view_prefix`, `denormalized_view_schema`. The Star Browser is half-ready for the denormalization, just few changes are needed in the mapper and maybe query builder. These changes have to be compatible with another, not-yet-included feature: SQL pre-aggregation. Conclusion ========== The new way of joining is very similar to the old one, but has much more cleaner code and is separated from mappings. Also it is more transparent. New feature is the ability to specify a database schema. Planned feature to be integrated is automatic join detection based on foreign keys. In the next post, the last post about the new *StarBrowser*, you are going to learn about aggregation improvements and changes. Links ===== Relevant source code is [this one] (https://github.com/Stiivi/cubes/blob/master/cubes/backends/sql/common.py) (github). See also [Cubes at github](https://github.com/Stiivi/cubes), [Cubes Documentation](http://packages.python.org/cubes/), [Mailing List](http://groups.google.com/group/cubes-discuss/) and [Submit issues](https://github.com/Stiivi/cubes/issues). Also there is an IRC channel [#databrewery](irc://irc.freenode.net/#databrewery) on irc.freenode.net <file_sep>"""Exceptions used in Cubes. The base exception calss is :class:`.CubesError`.""" class CubesError(Exception): """Generic error class.""" class UserError(CubesError): """Superclass for all errors caused by the cubes and slicer users. Error messages from this error might be safely passed to the front-end. Do not include any information that you would not like to be public""" class InternalError(CubesError): """Superclass for all errors that happened internally: configuration issues, connection problems, model inconsistencies...""" class ConfigurationError(InternalError): """Raised when there is a problem with workspace configuration assumed.""" class BackendError(InternalError): """Raised by a backend. Should be handled separately, for example: should not be passed to the client from the server due to possible internal schema exposure. """ class WorkspaceError(InternalError): """Backend Workspace related exception.""" class BrowserError(InternalError): """AggregationBrowser related exception.""" pass class ModelError(InternalError): """Model related exception.""" # TODO: necessary? or rename to PhysicalModelError class MappingError(ModelError): """Raised when there are issues by mapping from logical model to physical database schema. """ # TODO: change all instances to ModelError class ModelInconsistencyError(ModelError): """Raised when there is incosistency in model structure.""" class TemplateRequired(ModelError): """Raised by a model provider which can provide a dimension, but requires a template. Signals to the caller that the creation of a dimension should be retried when the template is available.""" def __init__(self, template): self.template = template def __str__(self): return self.template class MissingObjectError(UserError): def __init__(self, message=None, name=None): self.name = name self.message = message def __str__(self): return self.message or self.name class NoSuchDimensionError(MissingObjectError): """Raised when an unknown dimension is requested.""" class NoSuchCubeError(MissingObjectError): """Raised when an unknown cube is requested.""" class NoSuchAttributeError(UserError): """Raised when an unknown attribute, measure or detail requested.""" class ArgumentError(UserError): """Raised when an invalid or conflicting function argument is supplied. """ class HierarchyError(UserError): """Raised when attemt to get level deeper than deepest level in a hierarchy""" <file_sep>import os import unittest from cubes import Workspace from sqlalchemy import create_engine, MetaData import json TESTS_PATH = os.path.dirname(os.path.abspath(__file__)) DATA_PATH = os.path.join(TESTS_PATH, 'data') class CubesTestCaseBase(unittest.TestCase): sql_engine = None def setUp(self): self._models_path = os.path.join(TESTS_PATH, 'models') self._data_path = os.path.join(TESTS_PATH, 'data') if self.sql_engine: self.engine = create_engine(self.sql_engine) self.metadata = MetaData(bind=self.engine) else: self.engine = None self.metadata = None def model_path(self, model): return os.path.join(self._models_path, model) def model_metadata(self, model): path = self.model_path(model) with open(path) as f: md = json.load(f) return md def data_path(self, file): return os.path.join(self._data_path, file) def create_workspace(self, store=None, model=None): """Create shared workspace. Add default store specified in `store` as a dictionary and `model` which can be a filename relative to ``tests/models`` or a moel dictionary. If no store is provided but class has an engine or `sql_engine` set, then the existing engine will be used as the default SQL store.""" workspace = Workspace() if store: store = dict(store) store_type = store.pop("type", "sql") workspace.register_default_store(store_type, **store) elif self.engine: workspace.register_default_store("sql", engine=self.engine) if model: if isinstance(model, basestring): model = self.model_path(model) workspace.add_model(model) return workspace def load_data(self, table, data): self.engine.execute(table.delete()) for row in data: insert = table.insert().values(row) self.engine.execute(insert) <file_sep>import unittest import os from cubes import Workspace from cubes.errors import * import cubes.browser @unittest.skipIf("TEST_SLICER" not in os.environ, "No TEST_SLICER environment variable set.") class SlicerTestCase(unittest.TestCase): def setUp(self): self.w = Workspace() self.w.add_slicer("myslicer", "http://localhost:5010") self.cube_list = self.w.list_cubes() def first_date_dim(self, cube): for d in cube.dimensions: if ( d.info.get('is_date') ): return d raise BrowserError("No date dimension in cube %s" % cube.name) def test_basic(self): for c in self.cube_list: if c.get('category') is not None and 'Mix' in c.get('category', ''): continue print ("Doing %s..." % c.get('name')), cube = self.w.cube(c.get('name')) date_dim = self.first_date_dim(cube) cut = cubes.browser.RangeCut(date_dim, [ 2013, 9, 25 ], None) cell = cubes.browser.Cell(cube, [ cut ]) drill = cubes.browser.Drilldown([(date_dim, None, date_dim.level('day'))], cell) b = self.w.browser(cube) try: attr_dim = cube.dimension("attr") split = cubes.browser.PointCut(attr_dim, ['paid', 'pnb']) except: split = None try: kw = {} if cube.aggregates: kw['aggregates'] = [cube.aggregates[0]] elif cube.measures: kw['measures'] = [ cube.measures[0] ] else: raise ValueError("Cube has neither aggregates nor measures") result = b.aggregate(cell, drilldown=drill, split=split, **kw) print result.cells except: import sys print sys.exc_info() <file_sep># -*- coding=utf -*- from flask import Blueprint, Flask, Response, request, g, current_app from functools import wraps import ConfigParser from ..workspace import Workspace from ..auth import NotAuthorized from ..browser import Cell, cuts_from_string, SPLIT_DIMENSION_NAME from ..errors import * from .utils import * from .errors import * from .local import * from ..calendar import CalendarMemberConverter from contextlib import contextmanager # Utils # ----- def prepare_cell(argname="cut", target="cell", restrict=False): """Sets `g.cell` with a `Cell` object from argument with name `argname`""" # Used by prepare_browser_request and in /aggregate for the split cell # TODO: experimental code, for now only for dims with time role converters = { "time": CalendarMemberConverter(workspace.calendar) } cuts = [] for cut_string in request.args.getlist(argname): cuts += cuts_from_string(g.cube, cut_string, role_member_converters=converters) if cuts: cell = Cell(g.cube, cuts) else: cell = None if restrict: if workspace.authorizer: cell = workspace.authorizer.restricted_cell(g.auth_identity, cube=g.cube, cell=cell) setattr(g, target, cell) def requires_cube(f): @wraps(f) def wrapper(*args, **kwargs): cube_name = request.view_args.get("cube_name") try: g.cube = authorized_cube(cube_name) except NoSuchCubeError: raise NotFoundError(cube_name, "cube", "Unknown cube '%s'" % cube_name) return f(*args, **kwargs) return wrapper def requires_browser(f): """Prepares three global variables: `g.cube`, `g.browser` and `g.cell`. Also athorizes the cube using `authorize()`.""" @wraps(f) def wrapper(*args, **kwargs): cube_name = request.view_args.get("cube_name") if cube_name: cube = authorized_cube(cube_name) else: cube = None g.cube = cube g.browser = workspace.browser(g.cube) prepare_cell(restrict=True) if "page" in request.args: try: g.page = int(request.args.get("page")) except ValueError: raise RequestError("'page' should be a number") else: g.page = None if "pagesize" in request.args: try: g.page_size = int(request.args.get("pagesize")) except ValueError: raise RequestError("'pagesize' should be a number") else: g.page_size = None # Collect orderings: # order is specified as order=<field>[:<direction>] # g.order = [] for orders in request.args.getlist("order"): for order in orders.split(","): split = order.split(":") if len(split) == 1: g.order.append( (order, None) ) else: g.order.append( (split[0], split[1]) ) return f(*args, **kwargs) return wrapper # Get authorized cube # =================== def authorized_cube(cube_name): """Returns a cube `cube_name`. Handle cube authorization if required.""" try: cube = workspace.cube(cube_name, g.auth_identity) except NotAuthorized: raise NotAuthorizedError("Authorization of cube '%s' failed for " "'%s'" % (cube_name, g.auth_identity)) return cube # Query Logging # ============= def log_request(action, attrib_field="attributes"): def decorator(f): @wraps(f) def wrapper(*args, **kwargs): rlogger = current_app.slicer.request_logger other = { "split": request.args.get("split"), "drilldown": request.args.get("drilldown"), "page": g.page, "page_size": g.page_size, "format": request.args.get("format"), "header": request.args.get("header"), "attributes": request.args.get(attrib_field) } with rlogger.log_time(action, g.browser, g.cell, g.auth_identity, **other): retval = f(*args, **kwargs) return retval return wrapper return decorator <file_sep>++++++++++++++++ Developing Cubes ++++++++++++++++ This chapter describes some guidelines how to contribute to the Cubes. General ======= * If you are puzzled why is something implemented certain way, ask before complaining. There might be a reason that is not explained and that should be described in documentation. Or there might not even be a reason for current implementation at all, and you suggestion might help. * Until 1.0 the interface is not 100% decided and might change * Focus is on usability, simplicity and understandability. There might be places where this might not be completely achieved and this feature of code should be considered as bug. For example: overcomplicated interface, too long call sequence which can be simplified, required over-configuration,... * Magic is not bad, if used with caution and the mechanic is well documented. Also there should be a way how to do it manually for every magical feature. New or changed feature checklist ================================ * add/change method * add docstring documentation * reflect documentation * are any examples affected? * commit <file_sep>*********** SQL Backend *********** The SQL backend is using the `SQLAlchemy`_ which supports following SQL database dialects: * Drizzle * Firebird * Informix * Microsoft SQL Server * MySQL * Oracle * PostgreSQL * SQLite * Sybase .. _SQLAlchemy: http://www.sqlalchemy.org/download.html Store Configuration =================== Data store: * ``url`` *(required)* – database URL in form: ``adapter://user:password@host:port/database`` * ``schema`` *(optional)* – schema containing denormalized views for relational DB cubes * ``dimension_prefix`` *(optional)* – used by snowflake mapper to find dimension tables when no explicit mapping is specified * ``dimension_schema`` – use this option when dimension tables are stored in different schema than the fact tables * ``fact_prefix`` *(optional)* – used by the snowflake mapper to find fact table for a cube, when no explicit fact table name is specified * ``use_denormalization`` *(optional)* – browser will use dernormalized view instead of snowflake * ``denormalized_view_prefix`` *(optional, advanced)* – if denormalization is used, then this prefix is added for cube name to find corresponding cube view * ``denormalized_view_schema`` *(optional, advanced)* – schema wehere denormalized views are located (use this if the views are in different schema than fact tables, otherwise default schema is going to be used) Database Connection ~~~~~~~~~~~~~~~~~~~ *(advanced topic)* To fine-tune the SQLAlchemy database connection some of the `create_engine()` parameters can be specified as ``sqlalchemy_PARAMETER``: * ``sqlalchemy_case_sensitive`` * ``sqlalchemy_convert_unicode`` * ``sqlalchemy_pool_size`` * ``sqlalchemy_pool_recycle`` * ``sqlalchemy_pool_timeout`` * ``sqlalchemy_...`` ... Please refer to the create_engine_ documentation for more information. .. _create_engine: http://docs.sqlalchemy.org/en/rel_0_8/core/engines.html?highlight=engine#sqlalchemy.create_engine Mappings ======== One of the important parts of proper OLAP on top of the relational database is the mapping of logical attributes to their physical counterparts. In SQL database the physical attribute is stored in a column, which belongs to a table, which might be part of a database schema. .. figure:: ../images/mapping_logical_to_physical.png :align: center :width: 400px For example, take a reference to an attribute *name* in a dimension *product*. What is the column of what table in which schema that contains the value of this dimension attribute? .. figure:: ../images/mapping-example1.png :align: center :width: 400px For data browsing, the Cubes framework has to know where those logical (reported) attributes are physically stored. It needs to know which tables are related to the cube and how they are joined together so we get whole view of a fact. The process is done in two steps: 1. joining relevant star/snowflake tables 2. mapping logical attribute to table + column There are two ways how the mapping is being done: *implicit* and *explicit*. The simplest, straightforward and most customizable is the explicit way, where the actual column reference is provided in a mapping dictionary of the cube description. Implicit Mapping ---------------- With implicit mapping one can match a database schema with logical model and does not have to specify additional mapping metadata. Expected structure is star schema with one table per (denormalized) dimension. Facts ~~~~~ Cubes looks for fact table with the same name as cube name. You might specify prefix for every fact table with ``fact_table_prefix``. Example: * Cube is named `contracts`, framework looks for a table named `contracts`. * Cubes are named `contracts`, `invoices` and fact table prefix is ``fact_`` then framework looks for tables named ``fact_contracts`` and ``fact_invoices`` respectively. Dimensions ~~~~~~~~~~ By default, dimension tables are expected to have same name as dimensions and dimension table columns are expected to have same name as dimension attributes: .. figure:: ../images/dimension_attribute_implicit_map.png :align: center It is quite common practice that dimension tables have a prefix such as ``dim_`` or ``dm_``. Such prefix can be specified with ``dimension_prefix`` option. .. figure:: ../images/dimension_attribute_prefix_map.png :align: center The rules are: * fact table should have same name as represented cube: `fact table name` = `fact table prefix` + `fact table name` * dimension table should have same name as the represented dimension, for example: `product` (singular): `dimension table name` = `dimension prefix` + `dimension name` * column name should have same name as dimension attribute: `name`, `code`, `description` * references without dimension name in them are expected to be in the fact table, for example: `amount`, `discount` (see note below for simple flat dimensions) * if attribute is localized, then there should be one column per localization and should have locale suffix: `description_en`, `description_sk`, `description_fr` (see below for more information) Flat dimension without details ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What about dimensions that have only one attribute, like one would not have a full date but just a `year`? In this case it is kept in the fact table without need of separate dimension table. The attribute is treated in by the same rule as measure and is referenced by simple `year`. This is applied to all dimensions that have only one attribute (representing key as well). This dimension is referred to as *flat and without details*. .. note:: The simplification of the flat references can be disabled by setting ``simplify_dimension_references`` to ``False`` in the mapper. In that case you will have to have separate table for the dimension attribute and you will have to reference the attribute by full name. This might be useful when you know that your dimension will be more detailed. Database Schemas ---------------- For databases that support schemas, such as PostgreSQL, option ``schema`` can be used to specify default database schema where all tables are going to be looked for. In case you have dimensions stored in separate schema than fact table, you can specify that in ``dimension_schema``. All dimension tables are going to be searched in that schema. .. _explicit_mapping: Explicit Mapping ---------------- If the schema does not match expectations of cubes, it is possible to explicitly specify how logical attributes are going to be mapped to their physical tables and columns. `Mapping dictionary` is a dictionary of logical attributes as keys and physical attributes (columns, fields) as values. The logical attributes references look like: * `dimensions_name.attribute_name`, for example: ``geography.country_name`` or ``category.code`` * `fact_attribute_name`, for example: ``amount`` or ``discount`` Following mapping maps attribute `name` of dimension `product` to the column `product_name` of table `dm_products`. .. code-block:: javascript "mappings": { "product.name": "dm_products.product_name" } .. note:: Note that in the mappings the table names should be spelled as they are in the database even the table prefix is specified. If it is in different schema or any part of the reference contains a dot: .. code-block:: javascript "mappings": { "product.name": { "schema": "sales", "table": "dm_products", "column": "product_name" } } Both, explicit and implicit mappings have ability to specify default database schema (if you are using Oracle, PostgreSQL or any other DB which supports schemas). The mapping process process is like this: .. figure:: ../images/mapping-overview.png :align: center :width: 500px Date Data Type ~~~~~~~~~~~~~~ Date datatype column can be turned into a date dimension by extracting date parts in the mapping. To do so, for each date attribute specify a ``column`` name and part to be extracted with value for ``extract`` key. .. code-block:: javascript "mappings": { "date.year": {"column":"date", "extract":"year"}, "date.month": {"column":"date", "extract":"month"}, "date.day": {"column":"date", "extract":"day"} } According to SQLAlchemy, you can extract in most of the databases: ``month``, ``day``, ``year``, ``second``, ``hour``, ``doy`` (day of the year), ``minute``, ``quarter``, ``dow`` (day of the week), ``week``, ``epoch``, ``milliseconds``, ``microseconds``, ``timezone_hour``, ``timezone_minute``. Please refer to your database engine documentation for more information. .. note:: It is still recommended to have a date dimension table. Localization ------------ From physical point of view, the data localization is very trivial and requires language denormalization - that means that each language has to have its own column for each attribute. Localizable attributes are those attributes that have ``locales`` specified in their definition. To map logical attributes which are localizable, use locale suffix for each locale. For example attribute `name` in dimension `category` has two locales: Slovak (``sk``) and English (``en``). Or for example product category can be in English, Slovak or German. It is specified in the model like this: .. code-block:: javascript attributes = [ { "name" = "category", "locales" = ["en", "sk", "de"] } ] During the mapping process, localized logical reference is created first: .. figure:: ../images/mapping-to_localized.png :align: center :width: 600px In short: if attribute is localizable and locale is requested, then locale suffix is added. If no such localization exists then default locale is used. Nothing happens to non-localizable attributes. For such attribute, three columns should exist in the physical model. There are two ways how the columns should be named. They should have attribute name with locale suffix such as ``category_sk`` and ``category_en`` (_underscore_ because it is more common in table column names), if implicit mapping is used. You can name the columns as you like, but you have to provide explicit mapping in the mapping dictionary. The key for the localized logical attribute should have ``.locale`` suffix, such as ``product.category.sk`` for Slovak version of category attribute of dimension product. Here the _dot_ is used because dots separate logical reference parts. .. note:: Current implementation of Cubes framework requires a star or snowflake schema that can be joined into fully denormalized normalized form just by simple one-key based joins. Therefore all localized attributes have to be stored in their own columns. In other words, you have to denormalize the localized data before using them in Cubes. Read more about :doc:`../localization`. Mapping Process Summary ----------------------- Following diagram describes how the mapping of logical to physical attributes is done in the star SQL browser (see :class:`cubes.backends.sql.StarBrowser`): .. figure:: ../images/mapping-logical_to_physical.png :align: center :width: 600px logical to physical attribute mapping The "red path" shows the most common scenario where defaults are used. Joins ===== The SQL backend supports a star: .. figure:: ../images/schema_star.png :align: center :width: 300px and a snowflake database schema: .. figure:: ../images/schema_snowflake.png :align: center :width: 300px If you are using either of the two schemas (star or snowflake) in relational database, Cubes requires information on how to join the tables. Tables are joined by matching single-column – surrogate keys. The framework needs the join information to be able to transform following snowflake: .. figure:: ../images/snowflake_schema.png :align: center :width: 400px to appear as a denormalized table with all cube attributes: .. figure:: ../images/denormalized_schema.png :align: center :width: 400px .. note:: The SQL backend performs only joins that are relevant to the given query. If no attributes from a table are used, then the table is not joined. Join Description ---------------- Joins are defined as an ordered list (order is important) for every cube separately. The join description consists of reference to the `master` table and a table with `details`. Fact table is example of master table, dimension is example of a detail table (in a star schema). .. note:: Only single column – surrogate keys are supported for joins. The join specification is very simple, you define column reference for both: master and detail. The table reference is in the form `table`.`column`: .. code-block:: javascript "joins" = [ { "master": "fact_sales.product_key", "detail": "dim_product.key" } ] As in mappings, if you have specific needs for explicitly mentioning database schema or any other reason where `table.column` reference is not enough, you might write: .. code-block:: javascript "joins" = [ { "master": "fact_sales.product_id", "detail": { "schema": "sales", "table": "dim_products", "column": "id" } ] Aliases ------- What if you need to join same table twice or more times? For example, you have list of organizations and you want to use it as both: supplier and service consumer. .. figure:: ../images/joins-in_physical.png :align: center :width: 500px It can be done by specifying alias in the joins: .. code-block:: javascript "joins" = [ { "master": "contracts.supplier_id", "detail": "organisations.id", "alias": "suppliers" }, { "master": "contracts.consumer_id", "detail": "organisations.id", "alias": "consumers" } ] Note that with aliases, in the mappings you refer to the table by alias specified in the joins, not by real table name. So after aliasing tables with previous join specification, the mapping should look like: .. code-block:: javascript "mappings": { "supplier.name": "suppliers.org_name", "consumer.name": "consumers.org_name" } For example, we have a fact table named ``fact_contracts`` and dimension table with categories named ``dm_categories``. To join them we define following join specification: .. code-block:: javascript "joins" = [ { "master": "fact_contracts.category_id", "detail": "dm_categories.id" } ] .. _sql-outer-joins: Join Methods and Outer Joins ---------------------------- *(advanced topic)* Cubes supports three join methods: * `match` (default) – the keys from both master and detail tables have to match – INNER JOIN * `master` – the master might contain more keys than the detail, for example the fact table (as a master) might contain unknown or new dimension entries not in the dimension table yet. This is also known as LEFT OUTER JOIN. * `detail` – every member of the detail table will be always present. For example every date from a date dimension table. Alskoknown as RIGHT OUTER JOIN. To join a date dimension table so that every date will be present in the output reports, regardless whether there are any facts or not for given date dimension member: .. code-block:: javascript "joins" = [ { "master": "fact_contracts.contract_date_id", "detail": "dim_date.id", "method": "detail" } ] The `detail` Method and its Limitations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ *(advanced topic)* When at least one table is joined using the outer `detail` method during aggregation, the statement is composed from two nested statements or two join zones: `master fact` and `outer detail`. .. figure:: ../images/cubes-outer_join_aggregate_statement.png :align: center :width: 500px Aggregate statement composition The query builder analyses the schema and assigns a relationship of a table towards the fact. If a table is joined as `detail` or is behind a `detail` join it is considered to have a `detail` relationship towards the fact. Otherwise it has `master/match` relationship. When this composed setting is used, then: * aggregate functions are wrapped using ``COALESCE()`` to always return non-NULL values * ``count`` aggregates are changed to count non-empty facts instead of all rows .. note:: There should be no cut (path) that has some attributes in tables joined as `master` and others in a table joined as `detail`. Every cut (all the cut's attributes) should fall into one of the two table zones: either the master or the outer detail. There might be cuts from different join zones, though. Take this into account when designing the dimension hierarchies. <file_sep>import sys from setuptools import setup, find_packages requirements = ["pytz", "python-dateutil"] setup( name = "cubes", version = '0.11.2', # Project uses reStructuredText, so ensure that the docutils get # installed or upgraded on the target machine install_requires = requirements, packages = find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), package_data = { # If any package contains *.txt or *.rst files, include them: '': ['*.txt', '*.rst'], 'cubes': [ 'templates/*.html', 'templates/*.js' ], 'cubes.server': ['templates/*.html'], 'cubes.backends.mixpanel': ['*.json'] }, scripts = ['bin/slicer'], classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Topic :: Database', 'Topic :: Scientific/Engineering', 'Topic :: Utilities' ], test_suite = "tests", # metadata for upload to PyPI author = "<NAME>", author_email = "<EMAIL>", description = "Lightweight framework for Online Analytical Processing (OLAP) and multidimensional analysis", license = "MIT license with following addition: If your version of the Software supports interaction with it remotely through a computer network, the above copyright notice and this permission notice shall be accessible to all users.", keywords = "olap multidimensional data analysis", url = "http://databrewery.org" # could also include long_description, download_url, classifiers, etc. ) <file_sep># -*- coding=utf -*- from common import CubesTestCaseBase from cubes.errors import * from cubes.calendar import * from datetime import datetime class DateTimeTestCase(CubesTestCaseBase): def setUp(self): super(DateTimeTestCase,self).setUp() self.workspace = self.create_workspace(model="datetime.json") self.cal = Calendar() def test_empty(self): dim = self.workspace.dimension("default_date") self.assertEqual("date", dim.role) self.assertIsNone(dim.level("year").role) def test_implicit_roles(self): dim = self.workspace.dimension("default_date") elements = calendar_hierarchy_units(dim.hierarchy("ymd")) self.assertSequenceEqual(["year", "month", "day"], elements) def test_explicit_roles(self): dim = self.workspace.dimension("explicit_date") elements = calendar_hierarchy_units(dim.hierarchy("ymd")) self.assertSequenceEqual(["year", "month", "day"], elements) def test_no_roles(self): dim = self.workspace.dimension("invalid_date") with self.assertRaises(ArgumentError): calendar_hierarchy_units(dim.hierarchy("ymd")) def test_time_path(self): date = datetime(2012, 12, 24) self.assertEqual([], self.cal.path(date, [])) self.assertEqual([2012], self.cal.path(date, ["year"])) self.assertEqual([12, 24], self.cal.path(date, ["month", "day"])) self.assertEqual([2012, 4], self.cal.path(date, ["year", "quarter"])) def test_path_weekday(self): # This is monday: date = datetime(2013, 10, 21) self.assertEqual([0], self.cal.path(date, ["weekday"])) # Week start: Sunday self.cal.first_weekday = 6 self.assertEqual([1], self.cal.path(date, ["weekday"])) # Week start: Saturday self.cal.first_weekday = 5 self.assertEqual([2], self.cal.path(date, ["weekday"])) # Reference for the named relative test # 2012 # # Január Február Marec Apríl # po 2 9 16 23 30 6 13 20 27 5*12 19 26 2 9 16 23 30 # ut 3 10 17 24 31 7 14 21 28 6 13 20 27 3 10 17 24 # st 4 11 18 25 1 8 15 22 29 7 14 21 28 4 11 18 25 # št 5 12 19 26 2 9 16 23 *1 8 15 22 29 5 12 19 26 # pi 6 13 20 27 3 10 17 24 2 9 16 23 30 6 13 20 27 # so 7 14 21 28 4 11 18 25 3 10 17 24 31 7 14 21 28 # ne 1 8 15 22 29 5 12 19 26 4 11 18 25 1 8 15 22 29 def test_named_relative(self): date = datetime(2012, 3, 1) units = ["year", "month", "day"] path = self.cal.named_relative_path("tomorrow", units, date) self.assertEqual([2012, 3, 2], path) path = self.cal.named_relative_path("yesterday", units, date) self.assertEqual([2012, 2, 29], path) path = self.cal.named_relative_path("weekago", units, date) self.assertEqual([2012, 2, 23], path) path = self.cal.named_relative_path("3weeksago", units, date) self.assertEqual([2012, 2, 9], path) date = datetime(2012, 3, 12) path = self.cal.named_relative_path("monthago", units, date) self.assertEqual([2012, 2, 12], path) path = self.cal.named_relative_path("12monthsago", units, date) self.assertEqual([2011, 3, 12], path) path = self.cal.named_relative_path("monthforward", units, date) self.assertEqual([2012, 4, 12], path) path = self.cal.named_relative_path("12monthsforward", units, date) self.assertEqual([2013, 3, 12], path) def test_named_relative_truncated(self): date = datetime(2012, 3, 1, 10, 30) units = ["year", "month", "day", "hour"] path = self.cal.named_relative_path("lastweek", units, date) self.assertEqual([2012, 2, 20, 0], path) path = self.cal.named_relative_path("last3weeks", units, date) self.assertEqual([2012, 2, 6, 0], path) date = datetime(2012, 3, 12) path = self.cal.named_relative_path("lastmonth", units, date) self.assertEqual([2012, 2, 1, 0], path) path = self.cal.named_relative_path("last12months", units, date) self.assertEqual([2011, 3, 1, 0], path) path = self.cal.named_relative_path("nextmonth", units, date) self.assertEqual([2012, 4, 1, 0], path) path = self.cal.named_relative_path("next12months", units, date) self.assertEqual([2013, 3, 1,0 ], path) path = self.cal.named_relative_path("lastquarter", units, date) self.assertEqual([2012, 1, 1, 0], path) path = self.cal.named_relative_path("lastyear", units, date) self.assertEqual([2011, 1, 1,0 ], path) <file_sep>************************** Logical Model and Metadata ************************** Logical model describes the data from user's or analyst's perspective: data how they are being measured, aggregated and reported. Model is independent of physical implementation of data. This physical independence makes it easier to focus on data instead on ways of how to get the data in understandable form. .. seealso:: :doc:`schemas` Example database schemas and their respective models. :doc:`reference/model` Reference of model classes and fucntions. Introduction ============ The logical model enables users to: * see the data from the business perspective * hide physical structure of the data ("how application's use it") * specify concept hierarchies of attributes, such as: * `product category > product > subcategory > product` * `country > region > county > town`. * provide more descriptive attribute labels for display in the applications or reports * transparent localization of metadata and data Analysts or report writers do not have to know where name of an organisation or category is stored, nor he does not have to care whether customer data is stored in single table or spread across multiple tables (customer, customer types, ...). They just ask for `customer.name` or `category.code`. In addition to abstraction over physical model, localization abstraction is included. When working in multi-lingual environment, only one version of report/query has to be written, locales can be switched as desired. If requesting "contract type name", analyst just writes `constract_type.name` and Cubes framework takes care about appropriate localisation of the value. Example: Analysts wants to report contract amounts by geography which has two levels: country level and region level. In original physical database, the geography information is normalised and stored in two separate tables, one for countries and another for regions. Analyst does not have to know where the data are stored, he just queries for `geography.country` and/or `geography.region` and will get the proper data. How it is done is depicted on the following image: .. figure:: logical-to-physical.png :align: center :width: 500px Mapping from logical model to physical data. The logical model describes dimensions `geography` in which default hierarchy has two levels: `country` and `region`. Each level can have more attributes, such as code, name, population... In our example report we are interested only in geographical names, that is: `country.name` and `region.name`. .. How the physical attributes are located is described in the :doc:`mapping` .. chapter. Model ===== The logical model is described using `model metadata dictionary`. The content is description of logical objects, physical storage and other additional information. .. figure:: images/cubes-model_metadata.png :align: center :width: 300px Logical model metadata Logical part of the model description: * ``name`` – model name * ``label`` – human readable model label *(optional)* * ``description`` – human readable description of the model *(optional)* * ``locale`` – locale the model metadata are written in *(optional, used for localizable models)* * ``cubes`` – list of cubes metadata (see below) * ``dimensions`` – list of dimension metadata (see below) * ``public_dimensions`` – list of dimension names that will be exported from the model as public and might be shared by cubes from other models. By default, all model's dimensions are considered public. Physical part of the model description: * ``store`` – name of the datastore where model's cubes are stored. Default is ``default``. See :doc:`workspace` for more information. * ``mappings`` - backend-specific logical to physical mapping dictionary. This dictionary is inherited by every cube in the model. * ``joins`` - backend-specific join specification (used for example in the SQL backend). It should be a list of dictionaries. This list is inherited by the cubes in the model. * ``browser_options`` – options passed to the browser. The options are merged with options in the cubes. Example model snippet: .. code-block:: javascript { "name": "public_procurements", "label": "Public Procurements of Slovakia", "description": "Contracts of public procurement winners in Slovakia" "cubes": [...] "dimensions": [...] } Mappings and Joins ------------------ One can specify shared mappings and joins on the model-level. Those mappings and joins are inherited by all the cubes in the model. The ``mappigns`` dictionary of a cube is merged with model's global mapping dictionary. Cube's values overwrite the model's values. The ``joins`` can be considered as named templates. They should contain ``name`` property that will be referenced by a cube. Vsibility: The joins and mappings are local to a single model. They are not shared within the workspace. Inheritance ~~~~~~~~~~~ .. TODO: move this into recipes Cubes in a model will inherint mappings and joins from the model. The mappings are merged in a way that cube's mappings replace existing model's mappings with the same name. Joins are concatenated or merged by their name. Example from the SQL backend: Say you would like to join a date dimension table in ``dim_date`` to every cube. Then you specify the join at the model level as: .. code-block:: json "joins": [ { "name": "date", "detail": "dim_date.date_id", "method": "match" } ] The join has a name specified, which is used to match joins in the cube. Note that the join contains incimplete information: it contains only the ``detail`` part, that is the dimension key. To use the join in a cube which has two date dimensions `start date` and `end date`: .. code-block:: json "joins": [ { "name": "date", "master": "fact_contract.contract_start_date_id", }, { "name": "date", "master": "fact_sales.contract_sign_date_id", } ] The model's joins are searched for a template with given name and then cube completes (or even replaces) the join information. For more information about mappings and joins refer to the :doc:`backend documentation<backends/index>` for your data store, such as :doc:`SQL<backends/sql>` File Representation ------------------- The model can be represented either as a JSON file or as a directory with JSON files. The single-file model specification is just a dictionary with model properties. The model directory bundle should have the following content: * ``model.json`` – model's master metadata – same as single-file model * ``dim_*.json`` – dimension metadata file – single dimension dictionary * ``cube_*.json`` – cube metadata – single cube dictionary The list of dimensions and cubes in the ``model.json`` are merged with the dimensions and cubes in the separate files. Avoid duplicate definitions. Example directory bundle model:: model.cubesmodel/ model.json dim_date.json dim_organization.json dim_category.json cube_contracts.json cube_events.json Model Provider and External Models ---------------------------------- If the model is provided from an external source, such as an API or a database, then name of the provider should be specified in ``provider``. The provider receives the model's metadata and the model's data store (if the provider so desires). Then the provider generates all the cubes and the dimensions. Example of a model that is provided from an external source (:doc:`Mixpanel<backends/mixpanel>`): .. code-block:: javascript { "name": "Events", "provider": "mixpanel" } .. note:: The `cubes` and `dimensions` in the generated model are just informative for the model provider. The provider can yield different set of cubes and dimensions as specified in the metadata. .. seealso:: :func:`cubes.ModelProvider` Load a model from a file or a URL. :func:`cubes.StaticModelProvider` Create model from a dictionary. Dimension Visibility -------------------- All dimensions from a static (file) model are shared in the workspace by default. That means that the dimensions can be reused freely among cubes from different models. One can define a master model with dimensions only and no cubes. Then define one model per cube category, datamart or any other categorization. The models can share the master model dimensions. To expose only certain dimensions from a model specify a list of dimension names in the ``public_dimensions`` model property. Only dimensions from the list can be shared by other cubes in the workspace. .. note:: Some backends, such as Mixpanel, don't share dimensions at all. Cubes ===== Cube descriptions are stored as a dictionary for key ``cubes`` in the model description dictionary or in json files with prefix ``cube_`` like ``cube_contracts``, or ============== ==================================================== Key Description ============== ==================================================== **name** cube name **measures** list of cube measures (recommended, but might be empty for measure-less, record count only cubes) **aggregates** list of aggregated measures **dimensions** list of cube dimension names (recommended, but might be empty for dimension-less cubes) label human readable name - can be used in an application description longer human-readable description of the cube *(optional)* details list of fact details (as Attributes) - attributes that are not relevant to aggregation, but are nice-to-have when displaying facts (might be separately stored) joins specification of physical table joins (required for star/snowflake schema) mappings :doc:`mapping<mapping>` of logical attributes to physical attributes options browser options info custom info, such as formatting. Not used by cubes framework. ============== ==================================================== Example: .. code-block:: javascript { "name": "date", "label": "Dátum", "dimensions": [ "date", ... ] "measures": [...], "aggregates": [...], "details": [...], "fact": "fact_table_name", "mappings": { ... }, "joins": [ ... ] } .. _measures-and-aggregates: Measures and Aggregates ----------------------- .. figure:: images/cubes-measure_vs_aggregate.png :align: center :width: 300px Measure and measure aggregate `Measures` are numerical properties of a fact. They might be represented, for example, as a table column. Measures are aggregated into measure aggregates. The measure is described as: * ``name`` – measure identifier * ``label`` – human readable name to be displayed (localized) * ``info`` – additional custom information (unspecified) * ``aggregates`` – list of aggregate functions that are provided for this measure. This property is for generating default aggregates automatically. It is highly recommended to list the aggregates explicitly and avoid using this property. .. ``formula`` – name of formula .. ``expression`` – arithmetic expression Example: .. code-block:: javascript "measures": [ { "name": "amount", "label": "Sales Amount" }, { "name": "vat", "label": "VAT" } ] `Measure aggregate` is a value computed by aggregating measures over facts. It's properties are: * ``name`` – aggregate identifier, such as: `amount_sum`, `price_avg`, `total`, `record_count` * ``label`` – human readable label to be displayed (localized) * ``measure`` – measure the aggregate is derived from, if it exists or it is known. Might be empty. * ``function`` - name of an aggregate function applied to the `measure`, if known. For example: `sum`, `min`, `max`. * ``info`` – additional custom information (unspecified) Example: .. code-block:: javascript "aggregates": [ { "name": "amount_sum", "label": "Total Sales Amount", "measure": "amount", "function": "sum" }, { "name": "vat_sum", "label": "Total VAT", "measure": "vat", "function": "sum" }, { "name": "item_count", "label": "Item Count", "function": "count" } ] Note the last aggregate ``item_count`` – it counts number of the facts within a cell. No measure required as a source for the aggregate. If no aggregates are specified, Cubes generates default aggregates from the measures. For a measure: .. code-block:: javascript "measures": [ { "name": "amount", "aggregates": ["sum", "min", "max"] } ] The following aggregates are created: .. code-block:: javascript "aggregates" = [ { "name": "amount_sum", "measure": "amount", "function": "sum" }, { "name": "amount_min", "measure": "amount", "function": "min" }, { "name": "amount_max", "measure": "amount", "function": "max" } ] If there is a list of aggregates already specified in the cube explicitly, both lists are merged together. .. note:: To prevent automated creation of default aggregates from measures, there is an advanced cube option ``implicit_aggergates``. Set this property to `False` if you want to keep only explicit list of aggregates. In previous version of Cubes there was omnipresent measure aggregate called ``record_count``. It is no longer provided by default and has to be explicitly defined in the model. The name can be of any choice, it is not a built-in aggregate anymore. To keep the original behavior, the following aggregate should be added: .. code-block:: javascript "aggregates": [ { "name": "record_count", "function": "count" } ] .. note:: Some aggregates do not have to be computed from measures. They might be already provided by the data store as computed aggregate values (for example Mixpanel's `total`). In this case the `measure` and `function` serves only for the backend or for informational purposes. Consult the backend documentation for more information about the aggregates and measures. .. seealso:: :class:`cubes.Cube` Cube class reference. :func:`cubes.create_cube` Create cube from a description dictionary. :class:`cubes.Measure` Measure class reference. :class:`cubes.MeasureAggregate` Measure Aggregate class reference. Dimensions ========== Dimension descriptions are stored in model dictionary under the key ``dimensions``. .. figure:: dimension_desc.png Dimension description - attributes. The dimension description contains keys: ====================== =================================================== Key Description ====================== =================================================== **name** dimension name, used as identifier label human readable name - can be used in an application description longer human-readable description of the dimension *(optional)* levels list of level descriptions hierarchies list of dimension hierarchies hierarchy if dimension has only one hierarchy, you can specify it under this key default_hierarchy_name name of a hierarchy that will be used as default cardinality dimension cardinality (see Level for more info) info custom info, such as formatting. Not used by cubes framework. template name of a dimension that will be used as template ====================== =================================================== Example: .. code-block:: javascript { "name": "date", "label": "Dátum", "levels": [ ... ] "hierarchies": [ ... ] } Use either ``hierarchies`` or ``hierarchy``, using both results in an error. Dimension Templates ------------------- If you are creating more dimensions with the same or similar structure, such as multiple dates or different types of organisational relationships, you might create a template dimension and then use it as base for the other dimensions: .. code-block:: javascript "dimensions" = [ { "name": "date", "levels": [...] }, { "name": "creation_date", "template": "date" }, { "name": "closing_date", "template": "date" } ] All properties from the template dimension will be copied to the new dimension. Properties can be redefined in the new dimension. In that case, the old value is discarded. You might change levels, hierarchies or default hierarchy. There is no way how to add or drop a level from the template, all new levels have to be specified again if they are different than in the original template dimension. However, you might want to just redefine hierarchies to omit unnecessary levels. .. note:: In mappings name of the new dimension should be used. The template dimension was used only to create the new dimension and the connection between the new dimension and the template is lost. In our example above, if cube uses the `creation_date` and `closing_date` dimensions and any mappings would be necessary, then they should be for those two dimensions, not for the `date` dimension. Level ----- Dimension hierarchy levels are described as: ================ ================================================================ Key Description ================ ================================================================ name level name, used as identifier label human readable name - can be used in an application attributes list of other additional attributes that are related to the level. The attributes are not being used for aggregations, they provide additional useful information. key key field of the level (customer number for customer level, region code for region level, year-month for month level). key will be used as a grouping field for aggregations. Key should be unique within level. label_attribute name of attribute containing label to be displayed (customer name for customer level, region name for region level, month name for month level) order_attribute name of attribute that is used for sorting, default is the first attribute (key) cardinality symbolic approximation of the number of level's members info custom info, such as formatting. Not used by cubes framework. ================ ================================================================ Example of month level of date dimension: .. code-block:: javascript { "month", "label": "Mesiac", "key": "month", "label_attribute": "month_name", "attributes": ["month", "month_name", "month_sname"] }, Example of supplier level of supplier dimension: .. code-block:: javascript { "name": "supplier", "label": "Dodávateľ", "key": "ico", "label_attribute": "name", "attributes": ["ico", "name", "address", "date_start", "date_end", "legal_form", "ownership"] } .. seealso:: :class:`cubes.Dimension` Dimension class reference :func:`cubes.create_dimension` Create a dimension object from a description dictionary. :class:`cubes.Level` Level class reference :func:`cubes.create_level` Create level object from a description dictionary. Cardinality ~~~~~~~~~~~ The `cardinality` property is used optionally by backends and front-ends for various purposes. The possible values are: * ``tiny`` – few values, each value can have it's representation on the screen, recommended: up to 5. * ``low`` – can be used in a list UI element, recommended 5 to 50 (if sorted) * ``medium`` – UI element is a search/text field, recommended for more than 50 elements * ``high`` – backends might refuse to yield results without explicit pagination or cut through this level. Hierarchy --------- Hierarchies are described as: ================ ================================================================ Key Description ================ ================================================================ name hierarchy name, used as identifier label human readable name - can be used in an application levels ordered list of level names from top to bottom - from least detailed to most detailed (for example: from year to day, from country to city) ================ ================================================================ Example: .. code-block:: javascript "hierarchies": [ { "name": "default", "levels": ["year", "month"] }, { "name": "ymd", "levels": ["year", "month", "day"] }, { "name": "yqmd", "levels": ["year", "quarter", "month", "day"] } ] Attributes ---------- Dimension level attributes can be specified either as rich metadata or just simply as strings. If only string is specified, then all attribute metadata will have default values, label will be equal to the attribute name. ================ ================================================================ Key Description ================ ================================================================ name attribute name (should be unique within a dimension) label human readable name - can be used in an application, localizable order natural order of the attribute (optional), can be ``asc`` or ``desc`` format application specific display format information missing_value Value to be substituted when there is no value (NULL) in the source (backend has to support this feature) locales list of locales in which the attribute values are available in (optional) info custom info, such as formatting. Not used by cubes framework. ================ ================================================================ The optional `order` is used in aggregation browsing and reporting. If specified, then all queries will have results sorted by this field in specified direction. Level hierarchy is used to order ordered attributes. Only one ordered attribute should be specified per dimension level, otherwise the behavior is unpredictable. This natural (or default) order can be later overridden in reports by explicitly specified another ordering direction or attribute. Explicit order takes precedence before natural order. For example, you might want to specify that all dates should be ordered by default: .. code-block:: javascript "attributes" = [ {"name" = "year", "order": "asc"} ] Locales is a list of locale names. Say we have a `CPV` dimension (common procurement vocabulary - EU procurement subject hierarchy) and we are reporting in Slovak, English and Hungarian. The attributes will be therefore specified as: .. code-block:: javascript "attributes" = [ { "name" = "group_code" }, { "name" = "group_name", "order": "asc", "locales" = ["sk", "en", "hu"] } ] `group name` is localized, but `group code` is not. Also you can see that the result will always be sorted by `group name` alphabetical in ascending order. See :ref:`PhysicalAttributeMappings` for more information about how logical attributes are mapped to the physical sources. In reports you do not specify locale for each localized attribute, you specify locale for whole report or browsing session. Report queries remain the same for all languages. <file_sep>################## Slicing and Dicing ################## .. note:: Examples are in Python and in Slicer HTTP requests. Browser ======= The aggregation, slicing, dicing, browsing of the multi-dimensional data is being done by an AggregationBrowser. .. code-block:: python from cubes import Workspace workspace = Workspace("slicer.ini") browser = workspace.browser() Cell and Cuts ============= Cell defines a point of interest – portion of the cube to be aggergated or browsed. .. figure:: images/cubes-slice_and_dice-cell.png :align: center :width: 300px There are three types of cells: `point` – defines a single point in a dimension at a prticular level; `range` – defines all points of an ordered dimension (such as date) within the range and `set` – collection of points: .. figure:: images/cubes-point-range-set-cut.png :align: center :width: 600px Points are defined as dimension `paths` – list of dimension level keys. For example a date path for 24th of December 2010 would be: ``[2010, 12, 24]``. For December 2010, regardless of day: ``[2010, 12]`` and for the whole year: it would be a single item list ``[2010]``. Similar for other dimensions: ``["sk", "Bratislava"]`` for city `Bratislava` in `Slovakia` (code ``sk``). In Python the cuts for "sales in Slovakia between June 2010 and June 2013" are defined as: .. code-block:: python cuts = [ PointCut("geography", ["sk"]), PointCut("date", [2010, 6], [2012, 6]) ] Same cuts for Slicer: ``cut=geography:sk|date:2010,6-2012,6``. If a different hierarchy than default is desired – "from the second quartal of 2010 to the second quartal of 2012": .. code-block:: python cuts = [ PointCut("date", [2010, 2], [2012, 2], hierarchy="yqmd") ] Slicer: ``cut=date@yqmd:2010,2-2012,2``. Ranges and sets might have unequal depths: from ``[2010]`` to ``[2012,12,24]`` means "from the beginning of the year 2010 to December 24th 2012". .. code-block:: python cuts = [ PointCut("date", [2010], [2012, 12, 24]) ] Slicer: ``cut=date:2010-2012,12,24``. Ranges might be open, such as "everything until Dec 24 2012": .. code-block:: python cuts = [ PointCut("date", None, [2012, 12, 24]) ] Slicer: ``cut=date:-2012,12,24``. Aggregate ========= .. code-block:: python browser = workspace.browser("sales") result = browser.aggregate() print result.summary Slicer: ``/cube/sales/aggregate`` Aggregate of a cell: .. code-block:: python cuts = [ PointCut("geography", ["sk"]) PointCut("date", [2010, 6], [2012, 6]), ] cell = Cell(cube, cuts) result = browser.aggregate(cell) Slicer: ``/cube/sales/aggregate?cut=geography:sk|date:2010,6-2012,6`` Drilldown --------- Drill-down – get more details, group the aggregation by dimension members. For example "sales by month in 2010": .. code-block:: python: cut = PointCut("date", [2010]) cell = Cell(cube, [cut]) result = browser.aggregate(cell, drilldown=["date"]) for row in result: print "%s: %s" % (row["date.year"], row["amount_sum"]) Slicer: ``/cube/sales/aggregate?cut=date:2010&drilldown=date`` .. todo:: * implicit/explicit drilldown * `aggregate(cell, drilldown)` * `aggregate(cell, aggregates, drilldown)` * `aggregate(cell, drilldown, page, page_size)` * ``dim`` * ``dim:level`` * ``dim@hierarchy:level`` Split ----- Provisional: * `aggregate(cell, drilldown, split)` Facts ===== * `facts()` * `facts(cell)` * `facts(cell, fields)` Fact ==== * `fact(id)` Members ======= * `members(cell, dimension)` * `members(cell, dimension, depth)` * `members(cell, dimension, depth, hierarchy)` Cell Details ============ When we are browsing a cube, the cell provides current browsing context. For aggregations and selections to happen, only keys and some other internal attributes are necessary. Those can not be presented to the user though. For example we have geography path (`country`, `region`) as ``['sk', 'ba']``, however we want to display to the user `Slovakia` for the country and `Bratislava` for the region. We need to fetch those values from the data store. Cell details is basically a human readable description of the current cell. For applications where it is possible to store state between aggregation calls, we can use values from previous aggregations or value listings. Problem is with web applications - sometimes it is not desirable or possible to store whole browsing context with all details. This is exact the situation where fetching cell details explicitly might come handy. The cell details are provided by method :func:`cubes.AggregationBrowser.cell_details()` which has Slicer HTTP equivalent ``/cell`` or ``{"query":"detail", ...}`` in ``/report`` request (see the :doc:`server documentation<server>` for more information). For point cuts, the detail is a list of dictionaries for each level. For example our previously mentioned path ``['sk', 'ba']`` would have details described as: .. code-block:: javascript [ { "geography.country_code": "sk", "geography.country_name": "Slovakia", "geography.something_more": "..." "_key": "sk", "_label": "Slovakia" }, { "geography.region_code": "ba", "geography.region_name": "Bratislava", "geography.something_even_more": "...", "_key": "ba", "_label": "Bratislava" } ] You might have noticed the two redundant keys: `_key` and `_label` - those contain values of a level key attribute and level label attribute respectively. It is there to simplify the use of the details in presentation layer, such as templates. Take for example doing only one-dimensional browsing and compare presentation of "breadcrumbs": .. code-block:: python labels = [detail["_label"] for detail in cut_details] Which is equivalent to: .. code-block:: python levels = dimension.hierarchy().levels() labels = [] for i, detail in enumerate(cut_details): labels.append(detail[level[i].label_attribute.ref()]) Note that this might change a bit: either full detail will be returned or just key and label, depending on an option argument (not yet decided). <file_sep># -*- coding=utf -*- import sys from .providers import read_model_metadata, create_model_provider from .auth import create_authorizer from .model import Model from .common import read_json_file from .logging import get_logger from .errors import * from .stores import open_store, create_browser from .calendar import Calendar import os.path import ConfigParser from collections import OrderedDict __all__ = [ "Workspace", # Depreciated "get_backend", "create_workspace", "create_workspace_from_config", "config_items_to_dict", ] SLICER_INFO_KEYS = ( "name", "label", "description", # Workspace model description "copyright", # Copyright for the data "license", # Data license "maintainer", # Name (and maybe contact) of data maintainer "contributors", # List of contributors "visualizers", # List of dicts with url and label of server's visualizers "keywords", # List of keywords describing server's cubes "related" # List of dicts with related servers ) def config_items_to_dict(items): return dict([ (k, interpret_config_value(v)) for (k, v) in items ]) def interpret_config_value(value): if value is None: return value if isinstance(value, basestring): if value.lower() in ('yes', 'true', 'on'): return True elif value.lower() in ('no', 'false', 'off'): return False return value def _get_name(obj, object_type="Object"): if isinstance(obj, basestring): name = obj else: try: name = obj["name"] except KeyError: raise ModelError("%s has no name" % object_type) return name class Workspace(object): def __init__(self, config=None, stores=None): """Creates a workspace. `config` should be a `ConfigParser` or a path to a config file. `stores` should be a dictionary of store configurations, a `ConfigParser` or a path to a ``stores.ini`` file. """ if isinstance(config, basestring): cp = ConfigParser.SafeConfigParser() try: cp.read(config) except Exception as e: raise ConfigurationError("Unable to load config %s. " "Reason: %s" % (config, str(e))) config = cp elif not config: # Read ./slicer.ini config = ConfigParser.ConfigParser() self.store_infos = {} self.stores = {} self.logger = get_logger() if config.has_option("workspace", "log"): formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s %(message)s') handler = logging.FileHandler(config.get("workspace", "log")) handler.setFormatter(formatter) self.logger.addHandler(handler) if config.has_option("workspace", "log_level"): self.logger.setLevel(config.get("workspace", "log_level").upper()) self.locales = [] self.translations = [] self.info = OrderedDict() if config.has_option("workspace", "info"): path = config.get("workspace", "info_file") info = read_json_file(path, "Slicer info") for key in SLICER_INFO_KEYS: self.info[key] = info.get(key) elif config.has_section("info"): info = dict(config.items("info")) if "visualizer" in info: info["visualizers"] = [ {"label": info.get("label", info.get("name", "Default")), "url": info["visualizer"]} ] for key in SLICER_INFO_KEYS: self.info[key] = info.get(key) # # Model objects self._models = [] # Object ownership – model providers will be asked for the objects self.cube_models = {} self.dimension_models = {} # Cache of created global objects self._cubes = {} self._dimensions = {} # Note: providers are responsible for their own caching # Register stores from external stores.ini file or a dictionary if isinstance(stores, basestring): store_config = ConfigParser.SafeConfigParser() try: store_config.read(stores) except Exception as e: raise ConfigurationError("Unable to read stores from %s. " "Reason: %s" % (stores, str(e) )) for store in store_config.sections(): self._register_store_dict(store, dict(store_config.items(store))) elif isinstance(stores, dict): for name, store in stores.items(): self._register_store_dict(name, store) elif stores is not None: raise ConfigurationError("Unknown stores description object: %s" % (type(stores))) # Calendar # ======== if config.has_option("workspace", "timezone"): timezone = config.get("workspace", "timezone") else: timezone = None if config.has_option("workspace", "first_weekday"): first_weekday = config.get("workspace", "first_weekday") else: first_weekday = 0 self.logger.debug("Workspace calendar timezone: %s first week day: %s" % (timezone, first_weekday)) self.calendar = Calendar(timezone=timezone, first_weekday=first_weekday) # Register stores # # * Default store is [datastore] in main config file # * Stores are also loaded from main config file from sections with # name [store_*] (not documented feature) default = None if config.has_section("datastore"): default = dict(config.items("datastore")) elif config.has_section("workspace"): self.logger.warn("No [datastore] configuration found, using old " "backend & [workspace]. Update you config file.") default = {} default = dict(config.items("workspace")) default["type"] = config.get("server", "backend") if config.has_option("server", "backend") else None if not default.get("type"): self.logger.warn("No store type specified, assuming 'sql'") default["type"] = "sql" if default: self._register_store_dict("default",default) # Register [store_*] from main config (not documented) for section in config.sections(): if section.startswith("datastore_"): name = section[10:] self._register_store_dict(name, dict(config.items(section))) elif section.startswith("store_"): name = section[6:] self._register_store_dict(name, dict(config.items(section))) if config.has_section("browser"): self.browser_options = dict(config.items("browser")) else: self.browser_options = {} if config.has_section("main"): self.options = dict(config.items("main")) else: self.options = {} # Authorizer if config.has_option("workspace", "authorization"): auth_type = config.get("workspace", "authorization") options = dict(config.items("authorization")) self.authorizer = create_authorizer(auth_type, **options) else: self.authorizer = None # Load models if config.has_section("model"): self.logger.warn("Section [model] is depreciated. Use 'model' in " "[workspace] for single default model or use " "section [models] to list multiple models.") if config.has_option("model", "path"): source = config.get("model", "path") self.logger.debug("Loading model from %s" % source) self.add_model(source) if config.has_option("workspace", "models_path"): models_path = config.get("workspace", "models_path") else: models_path = None models = [] if config.has_option("workspace", "model"): models.append(config.get("workspace", "model")) if config.has_section("models"): models += [path for name, path in config.items("models")] self._load_models(models_path, models) def _load_models(self, root, paths): """Load `models` with root path `models_path`.""" if root: self.logger.debug("Models root: %s" % root) else: self.logger.debug("Models root set to current directory") for path in paths: self.logger.debug("Loading model %s" % path) if root and not os.path.isabs(path): path = os.path.join(root, path) self.add_model(path) def _register_store_dict(self, name, info): info = dict(info) try: type_ = info.pop("type") except KeyError: try: type_ = info.pop("backend") except KeyError: raise ConfigurationError("Datastore '%s' has no type specified" % name) else: self.logger.warn("'backend' is depreciated, use 'type' for " "datastore (in %s)." % str(name)) self.register_store(name, type_, **info) def register_default_store(self, type_, **config): """Convenience function for registering the default store. For more information see `register_store()`""" self.register_store("default", type_, **config) def register_store(self, name, type_, **config): """Adds a store configuration.""" if name in self.store_infos: raise ConfigurationError("Store %s already registered" % name) self.store_infos[name] = (type_, config) def _store_for_model(self, metadata): """Returns a store for model specified in `metadata`. """ store_name = metadata.get("datastore") if not store_name and "info" in metadata: store_name = metadata["info"].get("datastore") store_name = store_name or "default" return store_name def add_model(self, model, name=None, store=None, translations=None): """Registers the `model` in the workspace. `model` can be a metadata dictionary, filename, path to a model bundle directory or a URL. If `name` is specified, then it is used instead of name in the model. `store` is an optional name of data store associated with the model. Model is added to the list of workspace models. Model provider is determined and associated with the model. Provider is then asked to list public cubes and public dimensions which are registered in the workspace. No actual cubes or dimensions are created at the time of calling this method. The creation is deffered until :meth:`cubes.Workspace.cube` or :meth:`cubes.Workspace.dimension` is called. """ # Model -> Store -> Provider if isinstance(model, basestring): metadata = read_model_metadata(model) elif isinstance(model, dict): metadata = model else: raise ConfigurationError("Unknown model source reference '%s'" % model) model_name = name or metadata.get("name") # Get a provider as specified in the model by "provider" or get the # "default provider" provider_name = metadata.get("provider", "default") provider = create_model_provider(provider_name, metadata) if provider.requires_store(): store_name = store or self._store_for_model(metadata) store = self.get_store(store_name) provider.set_store(store, store_name) model_object = Model(metadata=metadata, provider=provider, translations=translations) model_object.name = metadata.get("name") self._models.append(model_object) # Get list of static or known cubes # "cubes" might be a list or a dictionary, depending on the provider for cube in provider.list_cubes(): name = _get_name(cube, "Cube") # self.logger.debug("registering public cube '%s'" % name) self._register_public_cube(name, model_object) # Register public dimensions for dim in provider.public_dimensions(): if dim: self._register_public_dimension(dim, model_object) def _register_public_dimension(self, name, model): if name in self.dimension_models: model_name = model.name or "(unknown)" previous_name = self.dimension_models[name].name or "(unknown)" raise ModelError("Duplicate public dimension '%s' in model %s, " "previous model: %s" % (name, model_name, previous_name)) self.dimension_models[name] = model def _register_public_cube(self, name, model): if name in self.cube_models: model_name = model.name or "(unknown)" previous_name = self.cube_models[name].name or "(unknown)" raise ModelError("Duplicate public cube '%s' in model %s, " "previous model: %s" % (name, model_name, previous_name)) self.cube_models[name] = model def add_slicer(self, name, url): """Register a slicer as a model and data provider.""" self.register_store(name, "slicer", url=url) model = { "store": name, "provider": "slicer", "datastore": name } self.add_model(model) def list_cubes(self, identity=None): """Get a list of metadata for cubes in the workspace. Result is a list of dictionaries with keys: `name`, `label`, `category`, `info`. The list is fetched from the model providers on the call of this method. If the workspace has an authorizer, then it is used to authorize the cubes for `identity` and only authorized list of cubes is returned. """ all_cubes = [] for model in self._models: all_cubes += model.provider.list_cubes() if self.authorizer: by_name = dict((cube["name"], cube) for cube in all_cubes) names = [cube["name"] for cube in all_cubes] authorized = self.authorizer.authorize(identity, names) all_cubes = [by_name[name] for name in authorized] return all_cubes def cube(self, name, identity=None): """Returns a cube with `name`""" if not isinstance(name, basestring): raise TypeError("Name is not a string, is %s" % type(name)) if self.authorizer: authorized = self.authorizer.authorize(identity, [name]) if not authorized: raise NotAuthorized if name in self._cubes: return self._cubes[name] # Requirements: # all dimensions in the cube should exist in the model # if not they will be created try: model = self.cube_models[name] except KeyError: model = self._model_for_cube(name) provider = model.provider cube = provider.cube(name) if not cube: raise NoSuchCubeError(name, "No cube '%s' returned from " "provider." % name) self.link_cube(cube, model, provider) self._cubes[name] = cube return cube def _model_for_cube(self, name): """Discovers the first model that can provide cube with `name`""" # Note: this will go through all model providers and gets a list of # provider's cubes. Might be a bit slow, if the providers get the # models remotely. model = None for model in self._models: cubes = model.provider.list_cubes() names = [cube["name"] for cube in cubes] if name in names: break if not model: raise ModelError("No model for cube '%s'" % name) return model def link_cube(self, cube, model, provider): """Links dimensions to the cube in the context of `model` with help of `provider`.""" # Assumption: empty cube # Algorithm: # 1. Give a chance to get the dimension from cube's provider # 2. If provider does not have the dimension, then use a public # dimension # # Note: Provider should not raise `TemplateRequired` for public # dimensions # for dim_name in cube.linked_dimensions: try: dim = provider.dimension(dim_name) except NoSuchDimensionError: dim = self.dimension(dim_name) except TemplateRequired as e: # FIXME: handle this special case raise ModelError("Template required in non-public dimension " "'%s'" % dim_name) cube.add_dimension(dim) def dimension(self, name): """Returns a dimension with `name`. Raises `NoSuchDimensionError` when no model published the dimension. Raises `RequiresTemplate` error when model provider requires a template to be able to provide the dimension, but such template is not a public dimension.""" if name in self._dimensions: return self._dimensions[name] # Assumption: all dimensions that are to be used as templates should # be public dimensions. If it is a private dimension, then the # provider should handle the case by itself. missing = set( (name, ) ) while missing: dimension = None deferred = set() name = missing.pop() # Get a model that provides the public dimension. If no model # advertises the dimension as public, then we fail. try: model = self.dimension_models[name] except KeyError: raise NoSuchDimensionError("No public dimension '%s'" % name) try: dimension = model.provider.dimension(name, self._dimensions) except TemplateRequired as e: missing.add(name) if e.template in missing: raise ModelError("Dimension templates cycle in '%s'" % e.template) missing.add(e.template) continue except NoSuchDimensionError: dimension = self._dimensions.get("name") else: # We store the newly created public dimension self._dimensions[name] = dimension if not dimension: raise NoSuchDimensionError("Missing dimension: %s" % name, name) return dimension def _browser_options(self, cube): """Returns browser configuration options for `cube`. The options are taken from the configuration file and then overriden by cube's `browser_options` attribute.""" options = dict(self.browser_options) if cube.browser_options: options.update(cube.browser_options) return options def browser(self, cube, locale=None, identity=None): """Returns a browser for `cube`.""" # TODO: bring back the localization # model = self.localized_model(locale) if isinstance(cube, basestring): cube = self.cube(cube, identity=identity) # TODO: check if the cube is "our" cube store_name = cube.datastore or "default" store = self.get_store(store_name) store_type = self.store_infos[store_name][0] store_info = self.store_infos[store_name][1] options = self._browser_options(cube) # TODO: merge only keys that are relevant to the browser! options.update(store_info) # TODO: Construct options for the browser from cube's options dictionary and # workspece default configuration # browser_name = cube.browser if not browser_name and hasattr(store, "default_browser_name"): browser_name = store.default_browser_name if not browser_name: browser_name = store_type if not browser_name: raise ConfigurationError("No store specified for cube '%s'" % cube) browser = create_browser(browser_name, cube, store=store, locale=locale, **options) return browser def cube_features(self, cube, identity=None): """Returns browser features for `cube`""" # TODO: this might be expensive, make it a bit cheaper # recycle the feature-providing browser or something. Maybe use class # method for that return self.browser(cube, identity).features() def get_store(self, name="default"): """Opens a store `name`. If the store is already open, returns the existing store.""" if name in self.stores: return self.stores[name] try: type_, options = self.store_infos[name] except KeyError: raise ConfigurationError("No info for store %s" % name) store = open_store(type_, **options) self.stores[name] = store return store def close(self): """Closes the workspace with all open stores and other associated resources.""" for store in self.open_stores: store.close() # TODO: Remove following depreciated functions def get_backend(name): raise NotImplementedError("get_backend() is depreciated. " "Use Workspace instead." ) def create_workspace(backend_name, model, **options): raise NotImplemented("create_workspace() is depreciated, " "use Workspace(config) instead") def create_workspace_from_config(config): raise NotImplemented("create_workspace_from_config() is depreciated, " "use Workspace(config) instead") <file_sep># -*- coding=utf -*- """Common objects for slicer server""" import json import os.path import decimal import datetime import csv import codecs import cStringIO from .errors import * TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates') API_VERSION = "2" def str_to_bool(string): """Convert a `string` to bool value. Returns ``True`` if `string` is one of ``["true", "yes", "1", "on"]``, returns ``False`` if `string` is one of ``["false", "no", "0", "off"]``, otherwise returns ``None``.""" if string is not None: if string.lower() in ["true", "yes", "1", "on"]: return True elif string.lower() in["false", "no", "0", "off"]: return False return None def validated_parameter(args, name, values=None, default=None, case_sensitive=False): """Return validated parameter `param` that has to be from the list of `values` if provided.""" param = args.get(name) if param: param = param.lower() else: param = default if not values: return param else: if values and param not in values: list_str = ", ".join(values) raise RequestError("Parameter '%s' should be one of: %s" % (name, list_str) ) return param class SlicerJSONEncoder(json.JSONEncoder): def __init__(self, *args, **kwargs): """Creates a JSON encoder that will convert some data values and also allows iterables to be used in the object graph. :Attributes: * `iterator_limit` - limits number of objects to be fetched from iterator. Default: 1000. """ super(SlicerJSONEncoder, self).__init__(*args, **kwargs) self.iterator_limit = 1000 def default(self, o): if type(o) == decimal.Decimal: return float(o) if type(o) == datetime.date or type(o) == datetime.datetime: return o.isoformat() if hasattr(o, "to_dict") and callable(getattr(o, "to_dict")): return o.to_dict() else: array = None try: # If it is an iterator, then try to construct array and limit number of objects iterator = iter(o) count = self.iterator_limit array = [] for i, obj in enumerate(iterator): array.append(obj) if i >= count: break except TypeError as e: # not iterable pass if array is not None: return array else: return json.JSONEncoder.default(self, o) class CSVGenerator(object): def __init__(self, records, fields, include_header=True, header=None, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.records = records self.include_header = include_header self.header = header self.fields = fields self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.encoder = codecs.getincrementalencoder(encoding)() def csvrows(self): if self.include_header: yield self._row_string(self.header or self.fields) for record in self.records: row = [] for field in self.fields: value = record.get(field) if type(value) == unicode or type(value) == str: row.append(value.encode("utf-8")) elif value is not None: row.append(unicode(value)) else: row.append(None) yield self._row_string(row) def _row_string(self, row): self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # empty queue self.queue.truncate(0) return data class UnicodeCSVWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. From: <http://docs.python.org/lib/csv-examples.html> """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): new_row = [] for value in row: if type(value) == unicode or type(value) == str: new_row.append(value.encode("utf-8")) elif value: new_row.append(unicode(value)) else: new_row.append(None) self.writer.writerow(new_row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) <file_sep>Localization ============ Having origin in multi-lingual Europe one of the main features of the Cubes framework is ability to provide localizable results. There are three levels of localization in each analytical application: 1. Application level - such as buttons or menus 2. Metadata level - such as table header labels 3. Data level - table contents, such as names of categories or procurement types .. figure:: localization_levels.png :align: center :width: 400px Localization levels. The application level is out of scope of this framework and is covered in internationalization (i18n) libraries, such as `gettext`. What is covered in Cubes is metadata and data level. Localization in cubes is very simple: 1. Create master model definition and specify locale the model is in 2. Specify attributes that are localized (see :ref:`explicit_mapping`) 3. Create model translations for each required language 4. Make cubes function or a tool create translated versions the master model To create localized report, just specify locale to the browser and create reports as if the model was not localized. See :ref:`LocalizedReporting`. Metadata Localization --------------------- The metadata are used to display report labels or provide attribute descriptions. Localizable metadata are mostly ``label`` and ``description`` metadata attributes, such as dimension label or attribute description. Say we have three locales: Slovak, English, Hungarian with Slovak being the main language. The master model is described using Slovak language and we have to provide two model translation specifications: one for English and another for Hungarian. The model translation file has the same structure as model definition file, but everything except localizable metadata attributes is ignored. That is, only ``label`` and ``description`` keys are considered in most cases. You can not change structure of mode in translation file. If structure does not match you will get warning or error, depending on structure change severity. There is one major difference between master model file and model translations: all attribute lists, such as cube measures, cube details or dimension level attributes are dictionaries, not arrays. Keys are attribute names, values are metadata translations. Therefore in master model file you will have: .. code-block:: javascript attributes = [ { "name": "name", "label": "Name" }, { "name": "cat", "label": "Category" } ] in translation file you will have: .. code-block:: javascript attributes = { "name": {"label": "Meno"}, "cat": {"label": "Kategoria"} } If a translation of a metadata attribute is missing, then the one in master model description is used. In our case we have following files:: procurements.json procurements_en.json procurements_hu.json .. figure:: localization_model_files.png :align: center :width: 300px Localization master model and translation files. To load a model: .. code-block:: python import cubes model_sk = cubes.load_model("procurements.json", translations = { "en": "procurements_en.json", "hu": "procurements_hu.json", }) To get translated version of a model: .. code-block:: python model_en = model.translate("en") model_hu = model.translate("hu") Or you can get translated version of the model by directly passing translation dictionary: .. code-block:: python handle = open("procurements_en.json") trans = json.load(handle) handle.close() model_en = model.translate("en", trans) Data Localization ----------------- If you have attributes that needs to be localized, specify the locales (languages) in the attribute definition in :ref:`explicit_mapping`. .. note:: Data localization is implemented only for Relational/SQL backend. .. _LocalizedReporting: Localized Reporting ------------------- Main point of localized reporting is: *Create query once, reuse for any language*. Provide translated model and desired locale to the aggregation browser and you are set. The browser takes care of appropriate value selection. Aggregating, drilling, getting list of facts - all methods return localized data based on locale provided to the browser. If you want to get multiple languages at the same time, you have to create one browser for each language you are reporting. <file_sep>++++++++++++ Introduction ++++++++++++ Why cubes? ========== Purpose is to provide a framework for giving analyst or any application end-user understandable and natural way of reporting using concept of data Cubes – multidimensional data objects. It is meant to be used by application builders that want to provide analytical functionality. Features: * logical view of analysed data - how analysts look at data, how they think of data, not not how the data are physically implemented in the data stores * hierarchical dimensions (attributes that have hierarchical dependencies, such as category-subcategory or country-region) * multiple hierarchies in a dimension – date can be split into year, month, day or year, quaryer, month, day; geography can be categorized by country, state, city or country, region, county, city. * localizable metadata and data (see :doc:`localization`) * OLAP and aggregated browsing (default backend is for relational databse - ROLAP) * multidimensional analysis Cube, Dimensions, Facts and Measures ==================================== The framework models the data as a cube with multiple dimensions: .. figure:: images/cube-dims_and_cell.png :align: center :width: 400px a data cube The most detailed unit of the data is a *fact*. Fact can be a contract, invoice, spending, task, etc. Each fact might have a *measure* – an attribute that can be measured, such as: price, amount, revenue, duration, tax, discount, etc. The *dimension* provides context for facts. Is used to: * filter queries or reporst * controls scope of aggregation of facts * used for ordering or sorting * defines master-detail relationship Dimension can have multiple *hierarchies*, for example the date dimension might have year, month and day levels in a hierarchy. Feature Overview ================ Core cube features: * **Workspace** – Cubes analytical workspace (see :doc:`docs<workspace>`, :doc:`reference<reference/workspace>`) * **Model** - Description of data (*metadata*): cubes, dimensions, concept hierarchies, attributes, labels, localizations. (see :doc:`docs<model>`, :doc:`reference<reference/model>`) * **Browser** - Aggregation browsing, slicing-and-dicing, drill-down. (see :doc:`docs<browser>`, :doc:`reference<reference/browser>`) * **Backend** - Actual aggregation implementation and utility functions. (see :doc:`docs<backends/index>`, :doc:`reference<reference/backends>`) * **Server** - WSGI HTTP server for Cubes (see :doc:`docs<server>`, :doc:`reference<reference/server>`) * **Formatters** - Data formatters (see :doc:`docs<formatters>`, :doc:`reference<reference/formatter>`) * :doc:`slicer` - command-line tool Model ----- Logical model describes the data from user’s or analyst’s perspective: data how they are being measured, aggregated and reported. Model is independent of physical implementation of data. This physical independence makes it easier to focus on data instead on ways of how to get the data in understandable form. More information about logical model can be found in the chapter :doc:`model`. See also developer's :doc:`reference<reference/model>`. Browser ------- Core of the Cubes analytics functionality is the aggregation browser. The browser module contains utility classes and functions for the browser to work. More information about browser can be found in the chapter :doc:`aggregate`. See also programming :doc:`reference<reference/browser>`. Backends -------- Backends provide the actual data aggregation and browsing functionality. Cubes comes with built-in `ROLAP`_ backend which uses SQL database using `SQLAlchemy`_. Framework has modular nature and supports multiple database backends, therefore different ways of cube computation and ways of browsing aggregated data. See also the backends programming reference :doc:`reference<reference/model>`. .. _ROLAP: http://en.wikipedia.org/wiki/ROLAP .. _SQLAlchemy: http://www.sqlalchemy.org/download.html Server ------ Cubes comes with built-in WSGI HTTP OLAP server called :doc:`slicer` and provides json API for most of the cubes framework functionality. The server is based on the Werkzeug WSGI framework. More information about the Slicer server requests can be found in the chapter :doc:`server`. See also programming reference of the :mod:`server` module. .. seealso:: :doc:`schemas` Example database schemas and use patterns with their respective models. <file_sep>################# Utility functions ################# .. automodule:: cubes.common :members: <file_sep>import whoosh_engine import sphinx def create_searcher(engine, browser, **options): if engine == 'sphinx': iclass = sphinx.SphinxSearcher elif engine == 'whoosh': iclass = whoosh_engine.WhooshSearcher else: raise Exception('Unknown search engine %s' % engine) return iclass(browser, **options) <file_sep># This example is using the hello_world data and model [workspace] models_path: ../hello_world log_level: info [models] main: model.json [datastore] type: sql url: sqlite:///../hello_world/data.sqlite <file_sep># -*- coding=utf -*- import unittest from cubes import __version__ import json from .common import CubesTestCaseBase from sqlalchemy import MetaData, Table, Column, Integer, String from werkzeug.test import Client from werkzeug.wrappers import BaseResponse from cubes.server import create_server import csv class SlicerTestCaseBase(CubesTestCaseBase): def setUp(self): super(SlicerTestCaseBase, self).setUp() self.slicer = create_server() self.slicer.debug = True self.server = Client(self.slicer, BaseResponse) self.logger = self.slicer.logger self.logger.setLevel("DEBUG") def get(self, path, *args, **kwargs): if not path.startswith("/"): path = "/" + path response = self.server.get(path, *args, **kwargs) try: result = json.loads(response.data) except ValueError: result = response.data return (result, response.status_code) def assertHasKeys(self, d, keys): for key in keys: self.assertIn(key, d) class SlicerTestCase(SlicerTestCaseBase): def test_version(self): response, status = self.get("version") self.assertEqual(200, status) self.assertIsInstance(response, dict) self.assertIn("version", response) self.assertEqual(__version__, response["version"]) def test_unknown(self): response, status = self.get("this_is_unknown") self.assertEqual(404, status) class SlicerModelTestCase(SlicerTestCaseBase): sql_engine = "sqlite:///" def setUp(self): super(SlicerModelTestCase, self).setUp() ws = self.create_workspace() self.slicer.cubes_workspace = ws # Satisfy browser with empty tables # TODO: replace this once we have data store = ws.get_store("default") table = Table("sales", store.metadata) table.append_column(Column("id", Integer)) table.create() ws.add_model(self.model_path("model.json")) ws.add_model(self.model_path("sales_no_date.json")) def test_cube_list(self): response, status = self.get("cubes") self.assertIsInstance(response, list) self.assertEqual(2, len(response)) for info in response: self.assertIn("name", info) self.assertIn("label", info) self.assertNotIn("dimensions", info) names = [c["name"] for c in response] self.assertItemsEqual(["contracts", "sales"], names) def test_no_cube(self): response, status = self.get("cube/unknown_cube/model") self.assertEqual(404, status) self.assertIsInstance(response, dict) self.assertIn("error", response) self.assertRegexpMatches(response["error"]["message"], "Unknown cube") def test_get_cube(self): response, status = self.get("cube/sales/model") self.assertEqual(200, status) self.assertIsInstance(response, dict) self.assertNotIn("error", response) self.assertIn("name", response) self.assertIn("measures", response) self.assertIn("aggregates", response) self.assertIn("dimensions", response) # We should not get internal info self.assertNotIn("mappings", response) self.assertNotIn("joins", response) self.assertNotIn("options", response) self.assertNotIn("browser_options", response) self.assertNotIn("fact", response) # Propert content aggregates = response["aggregates"] self.assertIsInstance(aggregates, list) self.assertEqual(4, len(aggregates)) names = [a["name"] for a in aggregates] self.assertItemsEqual(["amount_sum", "amount_min", "discount_sum", "record_count"], names) def test_cube_dimensions(self): response, status = self.get("cube/sales/model") # Dimensions print "===RESPONSE: ", response dims = response["dimensions"] self.assertIsInstance(dims, list) self.assertIsInstance(dims[0], dict) for dim in dims: self.assertIn("name", dim) self.assertIn("levels", dim) self.assertIn("default_hierarchy_name", dim) self.assertIn("hierarchies", dim) self.assertIn("is_flat", dim) self.assertIn("has_details", dim) names = [d["name"] for d in dims] self.assertItemsEqual(["date", "flag", "product"], names) # Test dim flags self.assertEqual(True, dims[1]["is_flat"]) self.assertEqual(False, dims[1]["has_details"]) self.assertEqual(False, dims[0]["is_flat"]) self.assertEqual(True, dims[0]["has_details"]) class SlicerAggregateTestCase(SlicerTestCaseBase): sql_engine = "sqlite:///" def setUp(self): super(SlicerAggregateTestCase, self).setUp() self.workspace = self.create_workspace(model="server.json") self.cube = self.workspace.cube("aggregate_test") self.slicer.cubes_workspace = self.workspace self.facts = Table("facts", self.metadata, Column("id", Integer), Column("id_date", Integer), Column("id_item", Integer), Column("amount", Integer) ) self.dim_date = Table("date", self.metadata, Column("id", Integer), Column("year", Integer), Column("month", Integer), Column("day", Integer) ) self.dim_item = Table("item", self.metadata, Column("id", Integer), Column("name", String) ) self.metadata.create_all() data = [ # Master-detail Match ( 1, 20130901, 1, 20), ( 2, 20130902, 1, 20), ( 3, 20130903, 1, 20), ( 4, 20130910, 1, 20), ( 5, 20130915, 1, 20), # -------- # ∑ 100 # No city dimension ( 6, 20131001, 2, 200), ( 7, 20131002, 2, 200), ( 8, 20131004, 2, 200), ( 9, 20131101, 3, 200), (10, 20131201, 3, 200), # -------- # ∑ 1000 # ======== # ∑ 1100 ] self.load_data(self.facts, data) data = [ (1, "apple"), (2, "pear"), (3, "garlic"), (4, "carrod") ] self.load_data(self.dim_item, data) data = [] for day in range(1, 31): row = (20130900+day, 2013, 9, day) data.append(row) self.load_data(self.dim_date, data) def test_aggregate_csv_headers(self): # Default = labels url = "cube/aggregate_test/aggregate?drilldown=date&format=csv" response, status = self.get(url) reader = csv.reader(response.split("\n")) header = reader.next() self.assertSequenceEqual(["Year", "Total Amount", "Item Count"], header) # Labels - explicit url = "cube/aggregate_test/aggregate?drilldown=date&format=csv&header=labels" response, status = self.get(url) reader = csv.reader(response.split("\n")) header = reader.next() self.assertSequenceEqual(["Year", "Total Amount", "Item Count"], header) # Names url = "cube/aggregate_test/aggregate?drilldown=date&format=csv&header=names" response, status = self.get(url) reader = csv.reader(response.split("\n")) header = reader.next() self.assertSequenceEqual(["date.year", "amount_sum", "count"], header) # None url = "cube/aggregate_test/aggregate?drilldown=date&format=csv&header=none" response, status = self.get(url) reader = csv.reader(response.split("\n")) header = reader.next() self.assertSequenceEqual(["2013", "100", "5"], header) <file_sep># -*- coding=utf -*- # Package imports import cubes import logging import ConfigParser # Werkzeug - soft dependency try: from werkzeug.routing import Map, Rule from werkzeug.wrappers import Request, Response from werkzeug.wsgi import ClosingIterator from werkzeug.exceptions import HTTPException, NotFound import werkzeug.serving except ImportError: from ..common import MissingPackage _missing = MissingPackage("werkzeug", "Slicer server") Map = Rule = Request = ClosingIterator = HTTPException = _missing Response = werkzeug = _missing try: import pytz except ImportError: from ..common import MissingPackage _missing = MissingPackage("pytz", "Time zone support in the server") from ..workspace import Workspace from ..common import * from .common import * from .errors import * from .controllers import * from .utils import local_manager, set_default_tz # TODO: this deserves Flask! rules = Map([ Rule('/', endpoint=(ApplicationController, 'index')), Rule('/version', endpoint=(ApplicationController, 'version')), Rule('/locales', endpoint=(ApplicationController, 'get_locales')), # # Model requests # Rule('/model', endpoint=(ModelController, 'show')), Rule('/cubes', endpoint=(ModelController, 'list_cubes')), Rule('/model/cubes', endpoint=(ModelController, 'list_cubes')), Rule('/model/cube', endpoint=(ModelController, 'get_default_cube')), Rule('/model/cube/<string:cube_name>', endpoint=(ModelController, 'get_cube')), Rule('/model/dimension/<string:dim_name>', endpoint=(ModelController, 'dimension')), # # Aggregation browser requests # Rule('/cube/<string:cube_name>/model', endpoint=(ModelController, 'get_cube')), Rule('/cube/<string:cube>/aggregate', endpoint=(CubesController, 'aggregate')), Rule('/cube/<string:cube>/facts', endpoint=(CubesController, 'facts')), Rule('/cube/<string:cube>/fact/<string:fact_id>', endpoint=(CubesController, 'fact')), Rule('/cube/<string:cube>/dimension/<string:dimension_name>', endpoint=(CubesController, 'values')), Rule('/cube/<string:cube>/report', methods = ['POST'], endpoint=(CubesController, 'report')), Rule('/cube/<string:cube>/cell', endpoint=(CubesController, 'cell_details')), Rule('/cube/<string:cube>/details', endpoint=(CubesController, 'details')), Rule('/cube/<string:cube>/build', endpoint=(CubesController, 'build')), # Use default cube (specified in config as: [model] cube = ... ) Rule('/aggregate', endpoint=(CubesController, 'aggregate'), defaults={"cube":None}), Rule('/facts', endpoint=(CubesController, 'facts'), defaults={"cube":None}), Rule('/fact/<string:fact_id>', endpoint=(CubesController, 'fact'), defaults={"cube":None}), Rule('/dimension/<string:dimension_name>', endpoint=(CubesController, 'values'), defaults={"cube":None}), Rule('/report', methods = ['POST'], endpoint=(CubesController, 'report'), defaults={"cube":None}), Rule('/cell', endpoint=(CubesController, 'cell_details'), defaults={"cube":None}), Rule('/details', endpoint=(CubesController, 'details'), defaults={"cube":None}), # # Other utility requests # Rule('/cube/<string:cube>/search', endpoint = (SearchController, 'search')), Rule('/search', endpoint = (SearchController, 'search'), defaults={"cube":None}), ]) class Slicer(object): def __init__(self, config=None): """Create a WSGI server for providing OLAP web service. You might provide ``config`` as ``ConfigParser`` object. """ self.config = config or ConfigParser.ConfigParser() self.initialize_logger() self.workspace = Workspace(config=config) self.locales = self.workspace.locales def initialize_logger(self): # Configure logger self.logger = get_logger() if self.config.has_option("server", "log"): formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s %(message)s') handler = logging.FileHandler(self.config.get("server", "log")) handler.setFormatter(formatter) self.logger.addHandler(handler) if self.config.has_option("server", "log_level"): level_str = self.config.get("server", "log_level").lower() levels = { "info": logging.INFO, "debug": logging.DEBUG, "warn":logging.WARN, "error": logging.ERROR} if level_str not in levels: self.logger.warn("Unknown logging level '%s', keeping default" % level_str) else: self.logger.setLevel(levels[level_str]) if self.config.has_option("server", "debug_exceptions"): self.debug_exceptions = True else: self.debug_exceptions = False def wsgi_app(self, environ, start_response): request = Request(environ) urls = rules.bind_to_environ(environ) try: endpoint, params = urls.match() (ctrl_class, action) = endpoint response = self.dispatch(ctrl_class, action, request, params) except HTTPException, e: response = e return ClosingIterator(response(environ, start_response), [local_manager.cleanup]) def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response) def dispatch(self, ctrl_class, action_name, request, params): controller = ctrl_class(request.args, workspace=self.workspace, logger=self.logger, config=self.config) controller.request = request action = getattr(controller, action_name) if self.debug_exceptions: # Don't handle exceptions, just throw-up response = action(**params) else: try: response = action(**params) except cubes.MissingObjectError as e: raise NotFoundError(e.name, message=str(e)) except cubes.UserError as e: raise RequestError(str(e)) else: response.headers.add("Access-Control-Allow-Origin", "*") return response def create_server(config_file): """Returns a WSGI server application. `config_file` is a path to an `.ini` file with slicer server configuration.""" try: config = ConfigParser.SafeConfigParser() config.read(config_file) except Exception as e: raise Exception("Unable to load configuration: %s" % e) return Slicer(config) def run_server(config): """Run OLAP server with configuration specified in `config`""" if config.has_option("server", "host"): host = config.get("server", "host") else: host = "localhost" if config.has_option('server', 'tz'): set_default_tz(pytz.timezone(config.get("server", "tz"))) if config.has_option("server", "port"): port = config.getint("server", "port") else: port = 5000 if config.has_option("server", "reload"): use_reloader = config.getboolean("server", "reload") else: use_reloader = False if config.has_option('server', 'processes'): processes = config.getint('server', 'processes') else: processes = 1 application = Slicer(config) werkzeug.serving.run_simple(host, port, application, processes=processes, use_reloader=use_reloader) <file_sep>sqlalchemy pytz pymongo werkzeug jinja2 python-dateutil whoosh>=2.4.1 <file_sep>from .browser import * from .store import * <file_sep>Cubes - Online Analytical Processing Framework for Python ========================================================= About ----- Cubes is a light-weight Python framework and set of tools for Online Analytical Processing (OLAP), multidimensional analysis and browsing of aggregated data. *Focus on data analysis, in human way* Purpose is to provide a framework for giving analyst or any application end-user understandable and natural way of presenting the multidimensional data. One of the main features is the logical model, which serves as abstraction over physical data to provide end-user layer. Features: * OLAP and aggregated browsing (default backend is for relational databse - ROLAP) * multidimensional analysis * logical view of analysed data - how analysts look at data, how they think of data, not not how the data are physically implemented in the data stores * hierarchical dimensions (attributes that have hierarchical dependencies, such as category-subcategory or country-region) * localizable metadata and data * OLAP server (WSGI HTTP server with JSON API based on Wergzeug) Documentation ------------- Documentation can be found at: http://packages.python.org/cubes See `examples` directory for simple examples and use-cases. Also see: https://github.com/stiivi/cubes-examples for more complex examples. Source ------ Github source repository: https://github.com/Stiivi/cubes Requirements ------------ Developed using python 2.7. Most of the requirements are soft (optional) and need to be satisfied only if certain parts of cubes are being used. * SQLAlchemy from http://www.sqlalchemy.org/ version >= 0.7.4 - for SQL backend * Werkzeug from http://werkzeug.pocoo.org/ for Slicer server * Jinja2 from http://jinja.pocoo.org/docs/ for HTML presenters * PyMongo for mongo and mongo2 backend * pytz for mongo2 backend Support ======= If you have questions, problems or suggestions, you can send a message to the Google group or write to the author. * Google group: http://groups.google.com/group/cubes-discuss * IRC channel #databrewery on server irc.freenode.net Report bugs using github issue tracking: https://github.com/Stiivi/cubes/issues Development ----------- If you are browsing the code and you find something that: * is over-complicated or not obvious * is redundant * can be done in better Python-way ... please let it be known. Authors ======= Cubes is written and maintained by <NAME> (@Stiivi on Twitter) <<EMAIL>> and various contributors. See AUTHORS file for more information. License ======= Cubes is licensed under MIT license with following addition: If your version of the Software supports interaction with it remotely through a computer network, the above copyright notice and this permission notice shall be accessible to all users. Simply said, that if you use it as part of software as a service (SaaS) you have to provide the copyright notice in an about, legal info, credits or some similar kind of page or info box. For full license see the LICENSE file. <file_sep>import unittest from cubes.browser import * from cubes.errors import * from common import CubesTestCaseBase class CutsTestCase(CubesTestCaseBase): def setUp(self): super(CutsTestCase, self).setUp() self.workspace = self.create_workspace(model="browser_test.json") self.cube = self.workspace.cube("transactions") self.dim_date = self.cube.dimension("date") def test_cut_depth(self): dim = self.cube.dimension("date") self.assertEqual(1, PointCut(dim, [1]).level_depth()) self.assertEqual(3, PointCut(dim, [1, 1, 1]).level_depth()) self.assertEqual(1, RangeCut(dim, [1], [1]).level_depth()) self.assertEqual(3, RangeCut(dim, [1, 1, 1], [1]).level_depth()) self.assertEqual(1, SetCut(dim, [[1], [1]]).level_depth()) self.assertEqual(3, SetCut(dim, [[1], [1], [1, 1, 1]]).level_depth()) def test_cut_from_dict(self): # d = {"type":"point", "path":[2010]} # self.assertRaises(Exception, cubes.cut_from_dict, d) d = {"type": "point", "path": [2010], "dimension": "date", "level_depth": 1, "hierarchy": None, "invert": False, "hidden": False} cut = cut_from_dict(d) tcut = PointCut("date", [2010]) self.assertEqual(tcut, cut) self.assertEqual(dict(d), tcut.to_dict()) self._assert_invert(d, cut, tcut) d = {"type": "range", "from": [2010], "to": [2012, 10], "dimension": "date", "level_depth": 2, "hierarchy": None, "invert": False, "hidden": False} cut = cut_from_dict(d) tcut = RangeCut("date", [2010], [2012, 10]) self.assertEqual(tcut, cut) self.assertEqual(dict(d), tcut.to_dict()) self._assert_invert(d, cut, tcut) d = {"type": "set", "paths": [[2010], [2012, 10]], "dimension": "date", "level_depth": 2, "hierarchy": None, "invert": False, "hidden": False} cut = cut_from_dict(d) tcut = SetCut("date", [[2010], [2012, 10]]) self.assertEqual(tcut, cut) self.assertEqual(dict(d), tcut.to_dict()) self._assert_invert(d, cut, tcut) self.assertRaises(ArgumentError, cut_from_dict, {"type": "xxx"}) def _assert_invert(self, d, cut, tcut): cut.invert = True tcut.invert = True d["invert"] = True self.assertEqual(tcut, cut) self.assertEqual(dict(d), tcut.to_dict()) class StringConversionsTestCase(unittest.TestCase): def test_cut_string_conversions(self): cut = PointCut("foo", ["10"]) self.assertEqual("foo:10", str(cut)) self.assertEqual(cut, cut_from_string("foo:10")) cut = PointCut("foo", ["123_abc_", "10", "_"]) self.assertEqual("foo:123_abc_,10,_", str(cut)) self.assertEqual(cut, cut_from_string("foo:123_abc_,10,_")) cut = PointCut("foo", ["123_ abc_"]) self.assertEqual(r"foo:123_ abc_", str(cut)) self.assertEqual(cut, cut_from_string("foo:123_ abc_")) cut = PointCut("foo", ["a-b"]) self.assertEqual("foo:a\-b", str(cut)) self.assertEqual(cut, cut_from_string("foo:a\-b")) cut = PointCut("foo", ["a+b"]) self.assertEqual("foo:a+b", str(cut)) self.assertEqual(cut, cut_from_string("foo:a+b")) def test_special_characters(self): self.assertEqual('\\:q\\-we,a\\\\sd\\;,100', string_from_path([":q-we", "a\\sd;", 100])) def test_string_from_path(self): self.assertEqual('qwe,asd,100', string_from_path(["qwe", "asd", 100])) self.assertEqual('', string_from_path([])) self.assertEqual('', string_from_path(None)) def test_path_from_string(self): self.assertEqual(["qwe", "asd", "100"], path_from_string('qwe,asd,100')) self.assertEqual([], path_from_string('')) self.assertEqual([], path_from_string(None)) def test_set_cut_string(self): cut = SetCut("foo", [["1"], ["2", "3"], ["qwe", "asd", "100"]]) self.assertEqual("foo:1;2,3;qwe,asd,100", str(cut)) self.assertEqual(cut, cut_from_string("foo:1;2,3;qwe,asd,100")) # single-element SetCuts cannot go round trip, they become point cuts cut = SetCut("foo", [["a+b"]]) self.assertEqual("foo:a+b", str(cut)) self.assertEqual(PointCut("foo", ["a+b"]), cut_from_string("foo:a+b")) cut = SetCut("foo", [["a-b"]]) self.assertEqual("foo:a\-b", str(cut)) self.assertEqual(PointCut("foo", ["a-b"]), cut_from_string("foo:a\-b")) def test_range_cut_string(self): cut = RangeCut("date", ["2010"], ["2011"]) self.assertEqual("date:2010-2011", str(cut)) self.assertEqual(cut, cut_from_string("date:2010-2011")) cut = RangeCut("date", ["2010"], None) self.assertEqual("date:2010-", str(cut)) cut = cut_from_string("date:2010-") if cut.to_path: self.fail('there should be no to path, is: %s' % (cut.to_path, )) cut = RangeCut("date", None, ["2010"]) self.assertEqual("date:-2010", str(cut)) cut = cut_from_string("date:-2010") if cut.from_path: self.fail('there should be no from path is: %s' % (cut.from_path, )) cut = RangeCut("date", ["2010", "11", "12"], ["2011", "2", "3"]) self.assertEqual("date:2010,11,12-2011,2,3", str(cut)) self.assertEqual(cut, cut_from_string("date:2010,11,12-2011,2,3")) cut = RangeCut("foo", ["a+b"], ["1"]) self.assertEqual("foo:a+b-1", str(cut)) self.assertEqual(cut, cut_from_string("foo:a+b-1")) cut = RangeCut("foo", ["a-b"], ["1"]) self.assertEqual(r"foo:a\-b-1", str(cut)) self.assertEqual(cut, cut_from_string(r"foo:a\-b-1")) def test_hierarchy_cut(self): cut = PointCut("date", ["10"], "dqmy") self.assertEqual("date@dqmy:10", str(cut)) self.assertEqual(cut, cut_from_string("date@dqmy:10")) class BrowserTestCase(CubesTestCaseBase): def setUp(self): super(BrowserTestCase, self).setUp() self.workspace = self.create_workspace(model="model.json") self.cube = self.workspace.cube("contracts") class AggregationBrowserTestCase(BrowserTestCase): def setUp(self): super(AggregationBrowserTestCase, self).setUp() self.browser = AggregationBrowser(self.cube) def test_cutting(self): full_cube = Cell(self.cube) self.assertEqual(self.cube, full_cube.cube) self.assertEqual(0, len(full_cube.cuts)) cell = full_cube.slice(PointCut("date", [2010])) self.assertEqual(1, len(cell.cuts)) cell = cell.slice(PointCut("supplier", [1234])) cell = cell.slice(PointCut("cpv", [50, 20])) self.assertEqual(3, len(cell.cuts)) self.assertEqual(self.cube, cell.cube) # Adding existing slice should result in changing the slice properties cell = cell.slice(PointCut("date", [2011])) self.assertEqual(3, len(cell.cuts)) def test_multi_slice(self): full_cube = Cell(self.cube) cuts_list = ( PointCut("date", [2010]), PointCut("cpv", [50, 20]), PointCut("supplier", [1234])) cell_list = full_cube.multi_slice(cuts_list) self.assertEqual(3, len(cell_list.cuts)) self.assertRaises(CubesError, full_cube.multi_slice, {}) def test_get_cell_dimension_cut(self): full_cube = Cell(self.cube) cell = full_cube.slice(PointCut("date", [2010])) cell = cell.slice(PointCut("supplier", [1234])) cut = cell.cut_for_dimension("date") self.assertEqual(str(cut.dimension), "date") self.assertRaises(NoSuchDimensionError, cell.cut_for_dimension, "someunknown") cut = cell.cut_for_dimension("cpv") self.assertEqual(cut, None) def test_hierarchy_path(self): dim = self.cube.dimension("cpv") hier = dim.hierarchy() levels = hier.levels_for_path([]) self.assertEqual(len(levels), 0) levels = hier.levels_for_path(None) self.assertEqual(len(levels), 0) levels = hier.levels_for_path([1, 2, 3, 4]) self.assertEqual(len(levels), 4) names = [level.name for level in levels] self.assertEqual(names, ['division', 'group', 'class', 'category']) self.assertRaises(HierarchyError, hier.levels_for_path, [1, 2, 3, 4, 5, 6, 7, 8]) def test_hierarchy_drilldown_levels(self): dim = self.cube.dimension("cpv") hier = dim.hierarchy() levels = hier.levels_for_path([], drilldown=True) self.assertEqual(len(levels), 1) self.assertEqual(levels[0].name, 'division') levels = hier.levels_for_path(None, drilldown=True) self.assertEqual(len(levels), 1) self.assertEqual(levels[0].name, 'division') def test_slice_drilldown(self): cut = PointCut("date", []) original_cell = Cell(self.cube, [cut]) cell = original_cell.drilldown("date", 2010) self.assertEqual([2010], cell.cut_for_dimension("date").path) cell = cell.drilldown("date", 1) self.assertEqual([2010, 1], cell.cut_for_dimension("date").path) cell = cell.drilldown("date", 2) self.assertEqual([2010, 1, 2], cell.cut_for_dimension("date").path) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(AggregationBrowserTestCase)) suite.addTest(unittest.makeSuite(CellsAndCutsTestCase)) return suite <file_sep>******** Tutorial ******** This chapter describes step-by-step how to use the Cubes. You will learn: * model preparation * measure aggregation * drill-down through dimensions * how to slice&dice the dube The tutorial contains examples for both: standard tool use and Python use. You don't need to know Python to follow this tutorial. Data Preparation ================ The example data used are IBRD Balance Sheet taken from `The World Bank`_. Backend used for the examples is ``sql.browser``. .. _The World Bank: https://finances.worldbank.org/Accounting-and-Control/IBRD-Balance-Sheet-FY2010/e8yz-96c6) Create a tutorial directory and download :download:`this example file <files/IBRD_Balance_Sheet__FY2010.csv>`. Start with imports: >>> from sqlalchemy import create_engine >>> from cubes.tutorial.sql import create_table_from_csv .. note:: Cubes comes with tutorial helper methods in ``cubes.tutorial``. It is advised not to use them in production, they are provided just to simplify learner's life. Prepare the data using the tutorial helpers. This will create a table and populate it with contents of the CSV file: >>> engine = create_engine('sqlite:///data.sqlite') ... create_table_from_csv(engine, ... "data.csv", ... table_name="irbd_balance", ... fields=[ ... ("category", "string"), ... ("category_label", "string"), ... ("subcategory", "string"), ... ("subcategory_label", "string"), ... ("line_item", "string"), ... ("year", "integer"), ... ("amount", "integer")], ... create_id=True ... ) Model ===== ... Analytical Workspace ==================== Everything in Cubes happens in an `analytical workspace`. It contains cubes, maintains connections to the data stores (with cube data), provides connection to external cubes and more. .. figure:: images/cubes-workspace_simplified.png :align: center :width: 500px Analytical workspace and it's content The workspace properties are specified in a configuration file `slicer.ini` (default name). First thing we have to do is to specify a data store – database where are the cube's data: .. code-block:: ini [datastore] type: sql url: sqlite:///data.sqlite In Python it would be: .. code-block:: python from cubes import Workspace workspace = Workspace() workspace.register_default_store("sql", url="sqlite:///data.sqlite") Or alternatively, you can use the `slicer.ini` file in Python as well: .. code-block:: python workspace = Workspace(config="slicer.ini") Model ----- Download the :download:`example model<files/model.json>` and save it as ``model.json``. In the `slicer.ini` file specify the model: .. code-block:: ini [workspace] model: model.json For more information how to add more models to the workspace see the :doc:`configuration documentation<configuration>`. Equivalent in Python is: >>> workspace.load_model("model.json") You might call :meth:`load_model()<cubes.Workspace.load_model` with as many models as you need. Only limitation is that the public cubes and public dimensions should have unique names. Aggregations ------------ Browser is an object that does the actual aggregations and other data queries for a cube. To obtain one: >>> browser = workspace.browser("ibrd_balance") Compute the aggregate. Measure fields of :class:`aggregation result<cubes.AggregationResult>` have aggregation suffix. Also a total record count within the cell is included as ``record_count``. >>> result = browser.aggregate() >>> result.summary["record_count"] 62 >>> result.summary["amount_sum"] 1116860 Now try some drill-down by `year` dimension: >>> result = browser.aggregate(cell, drilldown=["year"]) >>> for record in result.drilldown: ... print record {u'record_count': 31, u'amount_sum': 550840, u'year': 2009} {u'record_count': 31, u'amount_sum': 566020, u'year': 2010} Drill-dow by item category: >>> result = browser.aggregate(cell, drilldown=["item"]) >>> for record in result.drilldown: ... print record {u'item.category': u'a', u'item.category_label': u'Assets', u'record_count': 32, u'amount_sum': 558430} {u'item.category': u'e', u'item.category_label': u'Equity', u'record_count': 8, u'amount_sum': 77592} {u'item.category': u'l', u'item.category_label': u'Liabilities', u'record_count': 22, u'amount_sum': 480838} >>> cube = workspace.cube("ibrd_balance") :class:`cell<cubes.Cell>` defines context of interest - part of the cube we are looking at. We start with whole cube: <file_sep>Model Browser ============= Example Flask web application for browsing a model. Use: python application.py slicer.ini Where slicer.ini should contain absolute paths for model, translations. If you are using sqlite database then URL should be absolute as well. You can try it with the hello_world example: cd ../hellow_world python ../model_browser/application.py slicer.ini And then navigate your browser to: http://localhost:5000 <file_sep>############################### Publishing Open Data with Cubes ############################### Cubes and Slicer were built with Open Data or rather Open Analytical Data in mind. Read more about Open Data: * `Open Data <http://en.wikipedia.org/wiki/Open_data>`_ (Wikipedia) * `Defining Open Data <http://blog.okfn.org/2013/10/03/defining-open-data/>`_ (OKFN) * `What is Open Data <http://opendatahandbook.org/en/what-is-open-data/>`_ (Open Data Handbook) With Cubes you can have a server that provides raw detailed data (denormalized facts) and grouped and aggregated data (aggregates). It is possible to serve multiple datasets which might share properties (dimensions). Serving Open Data ================= Just create a public :doc:`Slicer server<../server>`. To provide more metadata add a ``info.json`` file with the following contents: * ``label`` – server's name or label * ``description`` – description of the served data * ``copyright`` – copyright of the data, if any * ``license`` – data license, such as `Creative Commons <http://creativecommons.org>`_, Public Domain or `other <http://opendatacommons.org/licenses/>`_ * ``maintainer`` – name of the data maintainer, might be in format ``Name Surname <<EMAIL>>`` * ``contributors`` - list of contributors (if any) * ``keywords`` – list of keywords that describe the data * ``related`` – list of related or "friendly" Slicer servers with other open data * ``visualizations`` – list of links to prepared visualisations of the server's data Create a ``info.json`` file: .. code-block:: json { "description": "Some Open Data", "license": "Public Domain", "keywords": ["budget", "financial"], } Include `info` option in the slicer configuration:: [workspace] info: info.json Related Servers --------------- For better open data discoverability you might add links to other servers: .. figure:: images/cubes-open_data_related_servers.png :align: center :width: 500px Related slicers. .. code-block:: json { "related": [ { "label": "Slicer – Germany", "url": "http://slicer.somewhere.de", }, { "label": "Slicer – Slovakia", "url": "http://slicer.somewhere.sk", } ] } <file_sep>#################### Formatters Reference #################### .. autofunction:: cubes.create_formatter .. autofunction:: cubes.register_formatter Formatters ========== .. autoclass:: cubes.TextTableFormatter .. autoclass:: cubes.SimpleDataTableFormatter .. autoclass:: cubes.SimpleHTMLTableFormatter .. autoclass:: cubes.CrossTableFormatter .. autoclass:: cubes.HTMLCrossTableFormatter .. seealso:: :doc:`formatters` Formatters documentation. <file_sep>+++++++++++ OLAP Server +++++++++++ Cubes framework provides easy to install web service WSGI server with API that covers most of the Cubes logical model metadata and aggregation browsing functionality. For more information about how to run the server, please refer to the :mod:`server` module. Server Requests =============== Version ------- Request: ``GET /version`` Return a server version. .. code-block:: javascript { "version": "1.0" } Info ---- Request: ``GET /info`` Return an information about the server and server's data. Content related keys: * ``label`` – server's name or label * ``description`` – description of the served data * ``copyright`` – copyright of the data, if any * ``license`` – data license * ``maintainer`` – name of the data maintainer, might be in format ``Name Surname <<EMAIL>>`` * ``contributors`` - list of contributors * ``keywords`` – list of keywords that describe the data * ``related`` – list of related or "friendly" Slicer servers with other open data – a dictionary with keys ``label`` and ``url``. * ``visualizations`` – list of links to prepared visualisations of the server's data – a dictionary with keys ``label`` and ``url``. Server related keys: * ``authentication`` – authentication method, might be ``none``, ``pass_parameter``, ``http_basic_proxy`` or other. See :doc:`auth` for more information * ``json_record_limit`` - maximum number of records yielded for JSON responses * ``cubes_version`` – Cubes framework version Example: .. code-block:: json { "description": "Some Open Data", "license": "Public Domain", "keywords": ["budget", "financial"], "authentication": "none", "json_record_limit": 1000, "cubes_version": "0.11.2" } Model ===== List of Cubes ------------- Request: ``GET /cubes`` Get list of basic informatiob about served cubes. The cube description dictionaries contain keys: `name`, `label`, `description` and `category`. .. code-block:: javascript [ { "name": "contracts", "label": "Contracts", "description": "...", "category": "..." } ] Cube Model ---------- Request: ``GET /cube/<name>/model`` Get model of a cube `name`. Returned structure is a dictionary with keys: * ``name`` – cube name – used as server-wide cube identifier * ``label`` – human readable name of the cube – to be displayed to the users (localized) * ``description`` – optional textual cube description (localized) * ``dimensions`` – list of dimension description dictionaries (see below) * ``aggregates`` – list of measures aggregates (mostly computed values) that can be computed. Each item is a dictionary. * ``measures`` – list of measure attributes (properties of facts). Each item is a dictionary. Example of a measure is: `amount`, `price`. * ``details`` – list of attributes that contain fact details. Those attributes are provided only when getting a fact or a list of facts. * ``info`` – a dictionary with additional metadata that can be used in the front-end. The contents of this dictionary is defined by the model creator and interpretation of values is left to the consumer. * ``features`` (advanced) – a dictionary with features of the browser, such as available actions for the cube ("is fact listing possible?") Aggregate is the key numerical property of the cube from reporting perspective. It is described as a dictionary with keys: * ``name`` – aggregate identifier, such as: `amount_sum`, `price_avg`, `total`, `record_count` * ``label`` – human readable label to be displayed (localized) * ``measure`` – measure the aggregate is derived from, if it exists or it is known. Might be empty. * ``function`` - name of an aggregate function applied to the `measure`, if known. For example: `sum`, `min`, `max`. * ``info`` – additional custom information (unspecified) Aggregate names are used in the ``aggregates`` parameter of the ``/aggregate`` request. Measure dictionary contains: * ``name`` – measure identifier * ``label`` – human readable name to be displayed (localized) * ``aggregates`` – list of aggregate functions that are provided for this measure * ``info`` – additional custom information (unspecified) .. note:: Compared to previous versions of Cubes, the clients do not have to construct aggregate names (as it used to be ``amount``+``_sum``). Clients just get the aggrergate ``name`` property and use it right away. See more information about measures and aggregates in the ``/aggregate`` request description. Example cube: .. code-block:: javascript { "name": "contracts", "info": {}, "label": "Contracts", "aggregates": [ { "name": "amount_sum", "label": "Amount sum", "info": {}, "function": "sum" }, { "name": "record_count", "label": "Record count", "info": {}, "function": "count" } ], "measures": [ { "name": "amount", "label": "Amount", "info": {}, "aggregates": [ "sum" ] } ], "details": [...], "dimensions": [...] } The dimension description dictionary: * ``name`` – dimension identifier * ``label`` – human readable dimension name (localized) * ``is_flat`` – `True` if the dimension has only one level, otherwise `False` * ``has_details`` – `True` if the dimension has more than one attribute * ``default_hierarchy_name`` - name of default dimension hierarchy * ``levels`` – list of level descriptions * ``hierarchies`` – list of dimension hierarchies * ``info`` – additional custom information (unspecified) The level description: * ``name`` – level identifier (within dimension context) * ``label`` – human readable level name (localized) * ``attributes`` – list of level's attributes * ``key`` – name of level's key attribute (mostly the first attribute) * ``label_attribute`` – name of an attribute that contains label for the level's members (mostly the second attribute, if present) * ``order_attribute`` – name of an attribute that the level should be ordered by (optional) * ``order`` – order direction ``asc``, ``desc`` or none. * ``cardinality`` – symbolic approximation of the number of level's members * ``info`` – additional custom information (unspecified) Cardinality values and their meaning: * ``tiny`` – few values, each value can have it's representation on the screen, recommended: up to 5. * ``low`` – can be used in a list UI element, recommended 5 to 50 (if sorted) * ``medium`` – UI element is a search/text field, recommended for more than 50 elements * ``high`` – backends might refuse to yield results without explicit pagination or cut through this level. .. note:: Use ``attribute["ref"]`` to access aggreegation result records. Each level (dimension) attribute description contains two properties: `name` and `ref`. `name` is identifier within the dimension context. The key reference `ref` is used for retrieving aggregation or browing results. It is not recommended to create any dependency by parsing or constructing the `ref` property at the client's side. Aggregation and Browsing ======================== The core data and analytical functionality is accessed through the following requests: * ``/cube/<name>/aggregate`` – aggregate measures, provide summary, generate drill-down, slice&dice, ... * ``/cube/<name>/dimension/<dim>`` – list dimension members * ``/cube/<name>/facts`` – list facts within a cell * ``/cube/<name>/fact`` – return a single fact * ``/cube/<name>/cell`` – describe the cell If the model contains only one cube or default cube name is specified in the configuration, then the ``/cube/<name>`` part might be omitted and you can write only requests like ``/aggregate``. Cells and Cuts -------------- The cell - part of the cube we are aggregating or we are interested in - is specified by cuts. The cut in URL are given as single parameter ``cut`` which has following format: Examples:: date:2004 date:2004,1 date:2004,1|class:5 date:2004,1,1|category:5,10,12|class:5 To specify a range where keys are sortable:: date:2004-2005 date:2004,1-2005,5 Open range:: date:2004,1,1- date:-2005,5,10 Set cuts:: date:2005;2007 Dimension name is followed by colon ``:``, each dimension cut is separated by ``|``, and path for dimension levels is separated by a comma ``,``. Set cuts are separated by semicolons ``;``. To specify other than default hierarchy use format `dimension@hierarchy`, the path then should contain values for specified hierarchy levels:: date@ywd:2004,25 Following image contains examples of cuts in URLs and how they change by browsing cube aggregates: .. figure:: url_cutting.png Example of how cuts in URL work and how they should be used in application view templates. Special Characters ~~~~~~~~~~~~~~~~~~ To pass reserved characters as a dimension member path value escape it with the backslash ``\`` character: * ``category:10\-24`` is a point cut for `category` with value ``10-24``, not a range cut * ``city:Nové\ Mesto\ nad\ Váhom`` is a city ``Nové Mesto nad Váhom`` .. _named_relative_time: Calendar and Relative Time ~~~~~~~~~~~~~~~~~~~~~~~~~~ If a dimension is a date or time dimension (the dimension role is ``time``) the members can be specified by a name referring to a relative time. For example: * ``date=yesterday`` * ``expliration_date=lastmonth-next2months`` – all facts with `expiration date` within last month (whole) and next 2 months (whole) * ``date=yearago`` – all facts since the same day of the year last year The keywords and patterns are: * ``today``, ``yesterday`` and ``tomorrow`` * ``...ago`` and ``...forward`` as in ``3weeksago`` (current day minus 3 weeks) and ``2monthsforward`` (current day plus 2 months) – relative offset with fine granularity * ``last...`` and ``next...`` as in ``last3months`` (beginning of the third month before current month) and ``nextyear`` (end of next year) – relative offset of specific (more coarse) granularity. Aggregate --------- .. _serveraggregate: Request: ``GET /cube/<cube>/aggregate`` Return aggregation result as JSON. The result will contain keys: `summary` and `drilldown`. The summary contains one row and represents aggregation of whole cell specified in the cut. The `drilldown` contains rows for each value of drilled-down dimension. If no arguments are given, then whole cube is aggregated. Parameters: * `cut` - specification of cell, for example: ``cut=date:2004,1|category:2|entity:12345`` * `drilldown` - dimension to be drilled down. For example ``drilldown=date`` will give rows for each value of next level of dimension date. You can explicitly specify level to drill down in form: ``dimension:level``, such as: ``drilldown=date:month``. To specify a hierarchy use ``dimension@hierarchy`` as in ``drilldown=date@ywd`` for implicit level or ``drilldown=date@ywd:week`` to explicitly specify level. * `aggregates` – list of aggregates to be computed, separated by ``|``, for example: ``aggergates=amount_sum|discount_avg|count`` * `measures` – list of measures for which their respecive aggregates will be computed (see below). Separated by ``|``, for example: ``aggergates=proce|discount`` * `page` - page number for paginated results * `pagesize` - size of a page for paginated results * `order` - list of attributes to be ordered by .. note:: You can specify either `aggregates` or `measures`. `aggregates` is a concrete list of computed values. `measures` yields their respective aggregates. For example: ``measures=amount`` might yield ``amount_sum`` and ``amount_avg`` if defined in the model. Use of `aggregates` is preferred, as it is more explicit and the result is well defined. .. TODO: not implemented * `limit` - limit number of results in form `limit`[,`measure`[,`order_direction`]]: ``limit=5:received_amount_sum:asc`` (this might not be implemented in all backends) Response: A dictionary with keys: * ``summary`` - dictionary of fields/values for summary aggregation * ``cells`` - list of drilled-down cells with aggregated results * ``total_cell_count`` - number of total cells in drilldown (after `limit`, before pagination). This value might not be present if it is disabled for computation on the server side. * ``aggregates`` – list of aggregate names that were considered in the aggragation query * ``cell`` - list of dictionaries describing the cell cuts * ``levels`` – a dictionary where keys are dimension names and values is a list of levels the dimension was drilled-down to Example for request ``/aggregate?drilldown=date&cut=item:a``: .. code-block:: javascript { "summary": { "count": 32, "amount_sum": 558430 } "cells": [ { "count": 16, "amount_sum": 275420, "date.year": 2009 }, { "count": 16, "amount_sum": 283010, "date.year": 2010 } ], "aggregates": [ "amount_sum", "count" ], "total_cell_count": 2, "cell": [ { "path": [ "a" ], "type": "point", "dimension": "item", "invert": false, "level_depth": 1 } ], "levels": { "date": [ "year" ] } } If pagination is used, then ``drilldown`` will not contain more than ``pagesize`` cells. Note that not all backengs might implement ``total_cell_count`` or providing this information can be configurable therefore might be disabled (for example for performance reasons). Facts ----- Request: ``GET /cube/<cube>/facts`` Return all facts within a cell. Parameters: * `cut` - see ``/aggregate`` * `page`, `pagesize` - paginate results * `order` - order results * `format` - result format: ``json`` (default; see note below), ``csv`` or ``json_lines``. * `fields` - comma separated list of fact fields, by default all fields are returned * `header` – specify what kind of headers should be present in the ``csv`` output: ``names`` – raw field names (default), ``labels`` – human readable labels or ``none`` The JSON response is a list of dictionaries where keys are attribute references (`ref` property of an attribute). To use JSON formatted repsonse but don't have the record limit ``json_lines`` format can be used. The result is one fact record in JSON format per line – JSON dictionaries separated by newline `\n` character. .. note:: Number of facts in JSON is limited to configuration value of ``json_record_limit``, which is 1000 by default. To get more records, either use pages with size less than record limit or use alternate result format, such as ``csv``. Single Fact ----------- Request: ``GET /cube/<cube>/fact/<id>`` Get single fact with specified `id`. For example: ``/fact/1024``. The response is a dictionary where keys are attribute references (`ref` property of an attribute). Dimension members ----------------- Request: ``GET /cube/<cube>/dimension/<dimension>`` Get values for attributes of a `dimension`. **Parameters:** * `cut` - see ``/aggregate`` * `depth` - specify depth (number of levels) to retrieve. If not specified, then all levels are returned * `hierarchy` – name of hierarchy to be considered, if not specified, then dimension's default hierarchy is used * `page`, `pagesize` - paginate results * `order` - order results **Response:** dictionary with keys ``dimension`` – dimension name, ``depth`` – level depth and ``data`` – list of records. Example for ``/dimension/item?depth=1``: .. code-block:: javascript { "dimension": "item" "depth": 1, "hierarchy": "default", "data": [ { "item.category": "a", "item.category_label": "Assets" }, { "item.category": "e", "item.category_label": "Equity" }, { "item.category": "l", "item.category_label": "Liabilities" } ], } Cell ---- Get details for a cell. Request: ``GET /cube/<cube>/cell`` **Parameters:** * `cut` - see ``/aggregate`` **Response:** a dictionary representation of a ``cell`` (see :meth:`cubes.Cell.as_dict`) with keys ``cube`` and ``cuts``. `cube` is cube name and ``cuts`` is a list of dictionary representations of cuts. Each cut is represented as: .. code-block:: javascript { // Cut type is one of: "point", "range" or "set" "type": cut_type, "dimension": cut_dimension_name, "level_depth": maximal_depth_of_the_cut, // Cut type specific keys. // Point cut: "path": [ ... ], "details": [ ... ] // Range cut: "from": [ ... ], "to": [ ... ], "details": { "from": [...], "to": [...] } // Set cut: "paths": [ [...], [...], ... ], "details": [ [...], [...], ... ] } Each element of the ``details`` path contains dimension attributes for the corresponding level. In addition in contains two more keys: ``_key`` and ``_label`` which (redundantly) contain values of key attribute and label attribute respectively. Example for ``/cell?cut=item:a`` in the ``hello_world`` example: .. code-block:: javascript { "cube": "irbd_balance", "cuts": [ { "type": "point", "dimension": "item", "level_depth": 1 "path": ["a"], "details": [ { "item.category": "a", "item.category_label": "Assets", "_key": "a", "_label": "Assets" } ], } ] } .. _serverreport: Report ------ Request: ``GET /cube/<cube>/report`` Process multiple request within one API call. The data should be a JSON containing report specification where keys are names of queries and values are dictionaries describing the queries. ``report`` expects ``Content-type`` header to be set to ``application/json``. See :ref:`serverreport` for more information. Search ------ .. warning:: Experimental feature. .. note:: Requires a search backend to be installed. Request: ``GET /cube/<cube>/search/dimension/<dimension>/<query>`` Search values of `dimensions` for `query`. If `dimension` is ``_all`` then all dimensions are searched. Returns search results as list of dictionaries with attributes: :Search result: * `dimension` - dimension name * `level` - level name * `depth` - level depth * `level_key` - value of key attribute for level * `attribute` - dimension attribute name where searched value was found * `value` - value of dimension attribute that matches search query * `path` - dimension hierarchy path to the found value * `level_label` - label for dimension level (value of label_attribute for level) Parameters that can be used in any request: * `prettyprint` - if set to ``true``, space indentation is added to the JSON output Reports ======= Report queries are done either by specifying a report name in the request URL or using HTTP ``POST`` request where posted data are JSON with report specification. .. If report name is specified in ``GET`` request instead, then .. server should have a repository of named report specifications. Keys: * `queries` - dictionary of named queries .. * `formatters` - dictionary of formatter configurations Query specification should contain at least one key: `query` - which is query type: ``aggregate``, ``cell_details``, ``values`` (for dimension values), ``facts`` or ``fact`` (for multiple or single fact respectively). The rest of keys are query dependent. For more information see AggregationBrowser documentation. .. note:: Note that you have to set the content type to ``application/json``. Result is a dictionary where keys are the query names specified in report specification and values are result values from each query call. Example report JSON file with two queries: .. code-block:: javascript { "queries": { "summary": { "query": "aggregate" }, "by_year": { "query": "aggregate", "drilldown": ["date"], "rollup": "date" } } } Request:: curl -H "Content-Type: application/json" --data-binary "@report.json" \ "http://localhost:5000/cube/contracts/report?prettyprint=true&cut=date:2004" Reply: .. code-block:: javascript { "by_year": { "total_cell_count": 6, "drilldown": [ { "record_count": 4390, "requested_amount_sum": 2394804837.56, "received_amount_sum": 399136450.0, "date.year": "2004" }, ... { "record_count": 265, "requested_amount_sum": 17963333.75, "received_amount_sum": 6901530.0, "date.year": "2010" } ], "summary": { "record_count": 33038, "requested_amount_sum": 2412768171.31, "received_amount_sum": 2166280591.0 } }, "summary": { "total_cell_count": null, "drilldown": {}, "summary": { "date.year": "2004", "requested_amount_sum": 2394804837.56, "received_amount_sum": 399136450.0, "record_count": 4390 } } } Explicit specification of a cell (the cuts in the URL parameters are going to be ignored): .. code-block:: javascript { "cell": [ { "dimension": "date", "type": "range", "from": [2010,9], "to": [2011,9] } ], "queries": { "report": { "query": "aggregate", "drilldown": {"date":"year"} } } } Roll-up ------- Report queries might contain ``rollup`` specification which will result in "rolling-up" one or more dimensions to desired level. This functionality is provided for cases when you would like to report at higher level of aggregation than the cell you provided is in. It works in similar way as drill down in ``/aggregate`` but in the opposite direction (it is like ``cd ..`` in a UNIX shell). Example: You are reporting for year 2010, but you want to have a bar chart with all years. You specify rollup: .. code-block:: javascript ... "rollup": "date", ... Roll-up can be: * a string - single dimension to be rolled up one level * an array - list of dimension names to be rolled-up one level * a dictionary where keys are dimension names and values are levels to be rolled up-to Running and Deployment ====================== Local Server ------------ To run your local server, prepare server configuration ``grants_config.ini``:: [server] host: localhost port: 5000 reload: yes log_level: info [workspace] url: postgres://localhost/mydata" [model] path: grants_model.json Run the server using the Slicer tool (see :doc:`/slicer`):: slicer serve grants_config.ini Apache mod_wsgi deployment -------------------------- Deploying Cubes OLAP Web service server (for analytical API) can be done in four very simple steps: 1. Create server configuration json file 2. Create WSGI script 3. Prepare apache site configuration 4. Reload apache configuration Create server configuration file ``procurements.ini``:: [server] backend: sql.browser [model] path: /path/to/model.json [workspace] view_prefix: mft_ schema: datamarts url: postgres://localhost/transparency [translations] en: /path/to/model-en.json hu: /path/to/model-hu.json .. note:: the `path` in `[model]` has to be full path to the model, not relative to the configuration file. Place the file in the same directory as the following WSGI script (for convenience). Create a WSGI script ``/var/www/wsgi/olap/procurements.wsgi``: .. code-block:: python import os.path import cubes CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) # Set the configuration file name (and possibly whole path) here CONFIG_PATH = os.path.join(CURRENT_DIR, "slicer.ini") application = cubes.server.create_server(CONFIG_PATH) Apache site configuration (for example in ``/etc/apache2/sites-enabled/``):: <VirtualHost *:80> ServerName olap.democracyfarm.org WSGIScriptAlias /vvo /var/www/wsgi/olap/procurements.wsgi <Directory /var/www/wsgi/olap> WSGIProcessGroup olap WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> ErrorLog /var/log/apache2/olap.democracyfarm.org.error.log CustomLog /var/log/apache2/olap.democracyfarm.org.log combined </VirtualHost> Reload apache configuration:: sudo /etc/init.d/apache2 reload And you are done. Server requests --------------- Example server request to get aggregate for whole cube:: $ curl http://localhost:5000/cube/procurements/aggregate?cut=date:2004 Reply:: { "drilldown": {}, "summary": { "received_amount_sum": 399136450.0, "requested_amount_sum": 2394804837.56, "record_count": 4390 } } <file_sep>################################## Integration With Flask Application ################################## Objective: Add Cubes Slicer to your application to provide raw analytical data. Cubes Slicer Server can be integrated with your application very easily. The Slicer is provided as a flask Blueprint – a module that can be plugged-in. The following code will add all Slicer's end-points to your application: .. code-block:: python from flask import Flask from cubes.server import slicer app = Flask(__name__) app.register_blueprint(slicerm, config="slicer.ini") To have a separate sub-path for Slicer add `url_prefix`: .. code-block:: python app.register_blueprint(slicer, url_prefix="/slicer", config="slicer.ini") .. seealso:: `Flask – Modular Applications with Blueprints <http://flask.pocoo.org/docs/blueprints/>`_ :doc:`../reference/server` <file_sep>import unittest import os # from .model import * # from .browser import * # from .combinations import * # from .default_sql_backend import * # from .sql_star_browser import * # from cubes.common import get_logger # import logging # # logger = get_logger() # logger.setLevel(logging.DEBUG) # def suite(): # suite = unittest.TestSuite() # # suite.addTest(model.suite()) # suite.addTest(browser.suite()) # suite.addTest(combinations.suite()) # suite.addTest(default_sql_backend.suite()) # suite.addTest(sql_star_browser.suite()) # # return suite <file_sep>Hierarchies, levels and drilling-down ===================================== Goals: * how to create a hierarchical dimension * how to do drill-down through a hierarchy * detailed level description Level: basic. We are going to use very similar data as in the previous examples. Difference is in two added columns: category code and sub-category code. They are simple letter codes for the categories and subcategories. Download :download:`this example file <files/IBRD_Balance_Sheet__FY2010.csv>`. Hierarchy --------- Some :class:`dimensions<cubes.model.Dimension>` can have multiple :class:`levels<cubes.model.Level>` forming a :class:`hierarchy<cubes.model.Hierarchy>`. For example dates have year, month, day; geography has country, region, city; product might have category, subcategory and the product. .. note: Cubes supports multiple hierarchies, for example for date you might have year-month-day or year-quarter-month-day. Most dimensions will have one hierarchy, though. In our example we have the `item` dimension with three levels of hierarchy: *category*, *subcategory* and *line item*: .. figure:: images/cubes-tutorial03-hierarchy.png :align: center :width: 400px `Item` dimension hierarchy. The levels are defined in the model: .. code-block:: javascript "levels": [ { "name":"category", "label":"Category", "attributes": ["category"] }, { "name":"subcategory", "label":"Sub-category", "attributes": ["subcategory"] }, { "name":"line_item", "label":"Line Item", "attributes": ["line_item"] } ] .. comment: FIXME: the following paragraph is referencing some "previous one", that is something from second tutorial blog post. You can see a slight difference between this model description and the previous one: we didn't just specify level names and didn't let cubes to fill-in the defaults. Here we used explicit description of each level. `name` is level identifier, `label` is human-readable label of the level that can be used in end-user applications and `attributes` is list of attributes that belong to the level. The first attribute, if not specified otherwise, is the key attribute of the level. Other level description attributes are `key` and `label_attribute``. The `key` specifies attribute name which contains key for the level. Key is an id number, code or anything that uniquely identifies the dimension level. `label_attribute` is name of an attribute that contains human-readable value that can be displayed in user-interface elements such as tables or charts. Preparation ----------- .. comment: FIXME: include the data loading code here Again, in short we need: * data in a database * logical model (see :download:`model file<files/model_03.json>`) prepared with appropriate mappings * denormalized view for aggregated browsing (optional) Implicit hierarchy ------------------ Try to remove the last level *line_item* from the model file and see what happens. Code still works, but displays only two levels. What does that mean? If metadata - logical model - is used properly in an application, then application can handle most of the model changes without any application modifications. That is, if you add new level or remove a level, there is no need to change your reporting application. Summary ------- * hierarchies can have multiple levels * a hierarchy level is identifier by a key attribute * a hierarchy level can have multiple detail attributes and there is one special detail attribute: label attribute used for display in user interfaces Multiple Hierarchies ==================== Dimension can have multiple hierarchies defined. To use specific hierarchy for drilling down: .. code-block:: python result = browser.aggregate(cell, drilldown = [("date", "dmy", None)]) The `drilldown` argument takes list of three element tuples in form: (`dimension`, `hierarchy`, `level`). The `hierarchy` and `level` are optional. If `level` is ``None``, as in our example, then next level is used. If `hierarchy` is ``None`` then default hierarchy is used. To sepcify hierarchy in cell cuts just pass `hierarchy` argument during cut construction. For example to specify cut through week 15 in year 2010: .. code-block:: python cut = cubes.PointCut("date", [2010, 15], hierarchy="ywd") .. note:: If drilling down a hierarchy and asking cubes for next implicit level the cuts should be using same hierarchy as drilldown. Otherwise exception is raised. For example: if cutting through year-month-day and asking for next level after year in year-week-day hierarchy, exception is raised. <file_sep>import unittest import os import json import re from cubes.errors import * from cubes.workspace import * from cubes.model import * from cubes.extensions import get_namespace from common import CubesTestCaseBase # FIXME: remove this once satisfied class WorkspaceTestCaseBase(CubesTestCaseBase): def default_workspace(self, model_name=None): model_name = model_name or "model.json" ws = Workspace(config=self.data_path("slicer.ini")) ws.add_model(self.model_path("model.json")) return ws class WorkspaceStoresTestCase(WorkspaceTestCaseBase): def test_empty(self): """Just test whether we can create empty workspace""" ws = Workspace() self.assertEqual(0, len(ws.store_infos)) def test_stores(self): ws = Workspace(stores={"default":{"type":"imaginary"}}) self.assertTrue("default" in ws.store_infos) ws = Workspace(stores=self.data_path("stores.ini")) self.assertEqual(3, len(ws.store_infos) ) ws = Workspace(config=self.data_path("slicer.ini")) self.assertEqual(2, len(ws.store_infos)) self.assertTrue("default" in ws.store_infos) self.assertTrue("production" in ws.store_infos) def test_duplicate_store(self): with self.assertRaises(CubesError): ws = Workspace(config=self.data_path("slicer.ini"), stores=self.data_path("stores.ini")) class WorkspaceModelTestCase(WorkspaceTestCaseBase): def test_get_cube(self): ws = self.default_workspace() cube = ws.cube("contracts") self.assertEqual("contracts", cube.name) # self.assertEqual(6, len(cube.dimensions)) self.assertEqual(1, len(cube.measures)) def test_get_dimension(self): ws = self.default_workspace() dim = ws.dimension("date") self.assertEqual("date", dim.name) def test_template(self): ws = Workspace() ws.add_model(self.model_path("templated_dimension.json")) dim = ws.dimension("date") self.assertEqual("date", dim.name) self.assertEqual(3, len(dim.levels)) dim = ws.dimension("start_date") self.assertEqual("start_date", dim.name) self.assertEqual(3, len(dim.levels)) dim = ws.dimension("end_date") self.assertEqual("end_date", dim.name) def test_external_template(self): ws = Workspace() ws.add_model(self.model_path("templated_dimension.json")) ws.add_model(self.model_path("templated_dimension_ext.json")) dim = ws.dimension("another_date") self.assertEqual("another_date", dim.name) self.assertEqual(3, len(dim.levels)) def test_duplicate_dimension(self): ws = Workspace() ws.add_model(self.model_path("templated_dimension.json")) model = {"dimensions": [{"name": "date"}]} with self.assertRaises(ModelError): ws.add_model(model) def test_local_dimension(self): # Test whether we can use local dimension with the same name as the # public one ws = Workspace() ws.add_model(self.model_path("model_public_dimensions.json")) ws.add_model(self.model_path("model_private_dimensions.json")) dim = ws.dimension("date") self.assertEqual(3, len(dim.levels)) self.assertEqual(["year", "month", "day"], dim.level_names) cube = ws.cube("events") dim = cube.dimension("date") self.assertEqual(["year", "month", "day"], dim.level_names) cube = ws.cube("lonely_yearly_events") dim = cube.dimension("date") self.assertEqual(["lonely_year"], dim.level_names) <file_sep># -*- coding=utf -*- import pytz from flask import Request, Response, g from time import gmtime, strftime from datetime import datetime import ConfigParser import cStringIO import datetime import decimal import codecs import json import csv from .errors import * tz_utc = pytz.timezone('UTC') default_tz = pytz.timezone(strftime("%Z", gmtime())) def set_default_tz(tz): default_tz = tz def get_default_tz(): return default_tz def now(tzinfo=default_tz): n = datetime.utcnow() n = tz_utc.localize(n) return n.astimezone(tzinfo) def str_to_bool(string): """Convert a `string` to bool value. Returns ``True`` if `string` is one of ``["true", "yes", "1", "on"]``, returns ``False`` if `string` is one of ``["false", "no", "0", "off"]``, otherwise returns ``None``.""" if string is not None: if string.lower() in ["true", "yes", "1", "on"]: return True elif string.lower() in["false", "no", "0", "off"]: return False return None def validated_parameter(args, name, values=None, default=None, case_sensitive=False): """Return validated parameter `param` that has to be from the list of `values` if provided.""" param = args.get(name) if param: param = param.lower() else: param = default if not values: return param else: if values and param not in values: list_str = ", ".join(values) raise RequestError("Parameter '%s' should be one of: %s" % (name, list_str) ) return param class SlicerJSONEncoder(json.JSONEncoder): def __init__(self, *args, **kwargs): """Creates a JSON encoder that will convert some data values and also allows iterables to be used in the object graph. :Attributes: * `iterator_limit` - limits number of objects to be fetched from iterator. Default: 1000. """ super(SlicerJSONEncoder, self).__init__(*args, **kwargs) self.iterator_limit = 1000 def default(self, o): if type(o) == decimal.Decimal: return float(o) if type(o) == datetime.date or type(o) == datetime.datetime: return o.isoformat() if hasattr(o, "to_dict") and callable(getattr(o, "to_dict")): return o.to_dict() else: array = None try: # If it is an iterator, then try to construct array and limit number of objects iterator = iter(o) count = self.iterator_limit array = [] for i, obj in enumerate(iterator): array.append(obj) if i >= count: break except TypeError as e: # not iterable pass if array is not None: return array else: return json.JSONEncoder.default(self, o) class CSVGenerator(object): def __init__(self, records, fields, include_header=True, header=None, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.records = records self.include_header = include_header self.header = header self.fields = fields self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.encoder = codecs.getincrementalencoder(encoding)() def csvrows(self): if self.include_header: yield self._row_string(self.header or self.fields) for record in self.records: row = [] for field in self.fields: value = record.get(field) if type(value) == unicode or type(value) == str: row.append(value.encode("utf-8")) elif value is not None: row.append(unicode(value)) else: row.append(None) yield self._row_string(row) def _row_string(self, row): self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # empty queue self.queue.truncate(0) return data class JSONLinesGenerator(object): def __init__(self, iterable, separator='\n'): """Creates a generator that yields one JSON record per record from `iterable` separated by a newline character..""" self.iterable = iterable self.separator = separator self.encoder = SlicerJSONEncoder(indent=None) def __iter__(self): for obj in self.iterable: string = self.encoder.encode(obj) yield "%s%s" % (string, self.separator) class UnicodeCSVWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. From: <http://docs.python.org/lib/csv-examples.html> """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): new_row = [] for value in row: if type(value) == unicode or type(value) == str: new_row.append(value.encode("utf-8")) elif value: new_row.append(unicode(value)) else: new_row.append(None) self.writer.writerow(new_row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) class CustomDict(dict): def __getattr__(self, attr): try: return super(CustomDict, self).__getitem__(attr) except KeyError: return super(CustomDict, self).__getattribute__(attr) def __setattr__(self, attr, value): self.__setitem__(attr,value) # Utils # ===== def jsonify(obj): """Returns a ``application/json`` `Response` object with `obj` converted to JSON.""" if g.prettyprint: indent = 4 else: indent = None encoder = SlicerJSONEncoder(indent=indent) encoder.iterator_limit = g.json_record_limit data = encoder.iterencode(obj) return Response(data, mimetype='application/json') def read_server_config(config): if not config: return ConfigParser.SafeConfigParser() elif isinstance(config, basestring): try: path = config config = ConfigParser.SafeConfigParser() config.read(path) except Exception as e: raise Exception("Unable to load configuration: %s" % e) return config <file_sep># -*- coding=utf -*- from .errors import * from StringIO import StringIO from .common import collect_subclasses, decamelize, to_identifier from collections import namedtuple try: import jinja2 except ImportError: from .common import MissingPackage jinja2 = MissingPackage("jinja2", "Templating engine") __all__ = [ "create_formatter", "register_formatter", "TextTableFormatter", "SimpleDataTableFormatter", "SimpleHTMLTableFormatter", "CrossTableFormatter", "HTMLCrossTableFormatter" ] _formatters = {} def register_formatter(formatter_type, factory): """Register formatter factory with type name `formatter_type`""" _formatters[formatter_type] = factory def create_formatter(formatter_type, convert_options=False, **options): """Create a formatter of type `formatter_type` with initialization `options`. If `convert_values` is ``True`` then values are considered to be strings and are converted into their respective types as specified in the formatter metadata. This should be used as convenience conversion from web server, for example. """ global _formatters if not _formatters: _formatters = collect_subclasses(Formatter, "_formatter") try: formatter_factory = _formatters[formatter_type] except KeyError: raise CubesError("unknown formatter '%s'" % formatter_type) if convert_options: options = convert_formatter_options(formatter_factory, options) return formatter_factory(**options) def create_formatters(description, convert_options=False): """Initialize formatters from `description` dictionary where keys are formatter identifiers used in reports and values are formatter options passed to the formatter's initialization method. By default formatter of the same type as contents of the identifier string is created. You can specify formatter type in ``type`` key of the formatter options. For example: .. code-block: javascript { "csv": { "delimiter": "|" }, "csv_no_headers": {"type":"csv", "headers": False} } Returns a dictionary with formatter identifiers as keys and formatter instances as values. Use this method to create dictionary of formatters from a configuration file, web server configuration, database or any other user facing application that does not require (or does not allow) Python to be used by users. """ formatters = {} for name, options in config: if "type" in options: formatter_type = options["type"] options = dict(options) del options["type"] else: formatter_type = name formatter = create_formatter(name, convert_options=convert_options, **options) formatters[name] = formatter return formatters def convert_formatter_options(formatter, options): """Convert options according to type specification of formatter parameters.""" new_options = {} parameters = {} for parameter in formatter.parameters: parameters[parameter["name"]] = parameter if "short_name" in "parameter": parameters[parameter["short_name"]] = parameter for key, string_value in options: try: parameter = parameters[key] except KeyError: raise ArgumentError("Unknown parameter %s for formatter %s" % (key, formatter_type)) value_type = parameter.get("type", "string") value = string_to_value(string_value, parameter_type, key) new_options[key] = value return new_options def _jinja_env(): """Create and return cubes jinja2 environment""" loader = jinja2.PackageLoader('cubes', 'templates') env = jinja2.Environment(loader=loader) return env def parse_format_arguments(formatter, args, prefix="f:"): """Parses dictionary of `args` for formatter""" class Formatter(object): """Empty class for the time being. Currently used only for finding all built-in subclasses""" def __call__(self, *args, **kwargs): return self.format(*args, **kwargs) class TextTableFormatter(Formatter): parameters = [ { "name": "aggregate_format", "type": "string", "label": "Aggregate format" }, { "name": "dimension", "type": "string", "label": "Dimension to drill-down by" }, { "name": "measures", "type": "list", "label": "list of measures" } ] mime_type = "text/plain" def __init__(self, aggregate_format=None): super(TextTableFormatter, self).__init__() self.agg_format = aggregate_format or {} def format(self, result, dimension, aggregates=None, hierarchy=None): cube = result.cell.cube aggregates = cube.get_aggregates(aggregates) rows = [] label_width = 0 aggregate_widths = [0] * len(aggregates) for row in result.table_rows(dimension, hierarchy=hierarchy): display_row = [] label_width = max(label_width, len(row.label)) display_row.append( (row.label, '<') ) for i, aggregate in enumerate(aggregates): if aggregate.function in ["count", "count_nonempty"]: default_fmt = "d" else: default_fmt = ".2f" fmt = self.agg_format.get(aggregate.ref(), default_fmt) text = format(row.record[aggregate.ref()], fmt) aggregate_widths[i] = max(aggregate_widths[i], len(text)) display_row.append( (text, '>') ) rows.append(display_row) widths = [label_width] + aggregate_widths stream = StringIO() for row in rows: for i, fvalue in enumerate(row): value = fvalue[0] alignment = fvalue[1] text = format(value, alignment + "%ds" % (widths[i]+1)) stream.write(text) stream.write("\n") value = stream.getvalue() stream.close() return value class SimpleDataTableFormatter(Formatter): parameters = [ { "name": "dimension", "type": "string", "label": "dimension to consider" }, { "name": "aggregates", "short_name": "aggregates", "type": "list", "label": "list of aggregates" } ] mime_type = "application/json" def __init__(self, levels=None): """Creates a formatter that formats result into a tabular structure. """ super(SimpleDataTableFormatter, self).__init__() def format(self, result, dimension, hierarchy=None, aggregates=None): cube = result.cell.cube aggregates = cube.get_aggregates(aggregates) dimension = cube.dimension(dimension) hierarchy = dimension.hierarchy(hierarchy) cut = result.cell.cut_for_dimension(dimension) if cut: rows_level = hierarchy[cut.level_depth()+1] else: rows_level = hierarchy[0] is_last = hierarchy.is_last(rows_level) rows = [] for row in result.table_rows(dimension): rheader = { "label":row.label, "key":row.key} # Get values for aggregated measures data = [row.record[str(agg)] for agg in aggregates] rows.append({"header":rheader, "data":data, "is_base": row.is_base}) labels = [agg.label or agg.name for agg in aggregates] hierarchy = dimension.hierarchy() header = [rows_level.label or rows_level.name] header += labels data_table = { "header": header, "rows": rows } return data_table; class TextTableFormatter2(Formatter): parameters = [ { "name": "measure_format", "type": "string", "label": "Measure format" }, { "name": "dimension", "type": "string", "label": "dimension to consider" }, { "name": "measures", "type": "list", "label": "list of measures" } ] mime_type = "text/plain" def __init__(self): super(TextTableFormatter, self).__init__() def format(self, result, dimension, measures): cube = result.cube dimension = cube.dimension(dimension) if not result.has_dimension(dimension): raise CubesError("Result was not drilled down by dimension " "'%s'" % str(dimension)) raise NotImplementedError table_formatter = SimpleDataTableFormatter() CrossTable = namedtuple("CrossTable", ["columns", "rows", "data"]) class CrossTableFormatter(Formatter): parameters = [ { "name": "aggregates_on", "type": "string", "label": "Localtion of aggregates. Can be columns, rows or " "cells", "scope": "formatter", }, { "name": "onrows", "type": "attributes", "label": "List of dimension attributes to be put on rows" }, { "name": "oncolumns", "type": "attributes", "label": "List of attributes to be put on columns" }, { "name": "aggregates", "short_name": "aggregates", "type": "list", "label": "list of aggregates" } ] mime_type = "application/json" def __init__(self, aggregates_on=None): """Creates a cross-table formatter. Arguments: * `aggregates_on` – specify how to put aggregates in the table. Might be one of ``rows``, ``columns`` or ``cells`` (default). If aggregates are put on rows or columns, then respective row or column is added per aggregate. The data contains single aggregate values. If aggregates are put in the table as cells, then the data contains tuples of aggregates in the order as specified in the `aggregates` argument of `format()` method. """ super(CrossTableFormatter, self).__init__() self.aggregates_on = aggregates_on def format(self, result, onrows=None, oncolumns=None, aggregates=None, aggregates_on=None): """ Creates a cross table from a drilldown (might be any list of records). `onrows` contains list of attribute names to be placed at rows and `oncolumns` contains list of attribute names to be placet at columns. `aggregates` is a list of aggregates to be put into cells. If aggregates are not specified, then only ``record_count`` is used. Returns a named tuble with attributes: * `columns` - labels of columns. The tuples correspond to values of attributes in `oncolumns`. * `rows` - labels of rows as list of tuples. The tuples correspond to values of attributes in `onrows`. * `data` - list of aggregate data per row. Each row is a list of aggregate tuples. """ # Use formatter's default, if set aggregates_on = aggregates_on or self.aggregates_on cube = result.cell.cube aggregates = cube.get_aggregates(aggregates) matrix = {} row_hdrs = [] column_hdrs = [] labels = [agg.label for agg in aggregates] agg_refs = [agg.ref() for agg in aggregates] if aggregates_on is None or aggregates_on == "cells": for record in result.cells: # Get table coordinates hrow = tuple(record[f] for f in onrows) hcol = tuple(record[f] for f in oncolumns) if not hrow in row_hdrs: row_hdrs.append(hrow) if not hcol in column_hdrs: column_hdrs.append(hcol) matrix[(hrow, hcol)] = tuple(record[a] for a in agg_refs) else: for record in result.cells: # Get table coordinates base_hrow = [record[f] for f in onrows] base_hcol = [record[f] for f in oncolumns] for i, agg in enumerate(aggregates): if aggregates_on == "rows": hrow = tuple(base_hrow + [agg.label or agg.name]) hcol = tuple(base_hcol) elif aggregates_on == "columns": hrow = tuple(base_hrow) hcol = tuple(base_hcol + [agg.label or agg.name]) if not hrow in row_hdrs: row_hdrs.append(hrow) if not hcol in column_hdrs: column_hdrs.append(hcol) matrix[(hrow, hcol)] = record[agg.ref()] data = [] for hrow in row_hdrs: row = [matrix.get((hrow, hcol)) for hcol in column_hdrs] data.append(row) return CrossTable(column_hdrs, row_hdrs, data) class HTMLCrossTableFormatter(CrossTableFormatter): parameters = [ { "name": "aggregates_on", "type": "string", "label": "Localtion of measures. Can be columns, rows or " "cells", "scope": "formatter", }, { "name": "onrows", "type": "attributes", "label": "List of dimension attributes to be put on rows" }, { "name": "oncolumns", "type": "attributes", "label": "List of attributes to be put on columns" }, { "name": "aggregates", "short_name": "aggregates", "type": "list", "label": "list of aggregates" }, { "name": "table_style", "description": "CSS style for the table" } ] mime_type = "text/html" def __init__(self, aggregates_on="cells", measure_labels=None, aggregation_labels=None, measure_label_format=None, count_label=None, table_style=None): """Create a simple HTML table formatter. See `CrossTableFormatter` for information about arguments.""" if aggregates_on not in ["columns", "rows", "cells"]: raise ArgumentError("aggregates_on sohuld be either 'columns' " "or 'rows', is %s" % aggregates_on) super(HTMLCrossTableFormatter, self).__init__(aggregates_on) self.env = _jinja_env() self.template = self.env.get_template("cross_table.html") self.table_style = table_style def format(self, result, onrows=None, oncolumns=None, aggregates=None): table = super(HTMLCrossTableFormatter, self).format(result, onrows=onrows, oncolumns=oncolumns, aggregates=aggregates) output = self.template.render(table=table, table_style=self.table_style) return output class SimpleHTMLTableFormatter(Formatter): parameters = [ { "name": "dimension", "type": "string", "label": "dimension to consider" }, { "name": "aggregates", "short_name": "aggregates", "type": "list", "label": "list of aggregates" } ] mime_type = "text/html" def __init__(self, create_links=True, table_style=None): """Create a simple HTML table formatter""" super(SimpleHTMLTableFormatter, self).__init__() self.env = _jinja_env() self.formatter = SimpleDataTableFormatter() self.template = self.env.get_template("simple_table.html") self.create_links = create_links self.table_style = table_style def format(self, result, dimension, aggregates=None, hierarchy=None): cube = result.cell.cube dimension = cube.dimension(dimension) hierarchy = dimension.hierarchy(hierarchy) aggregates = cube.get_aggregates(aggregates) cut = result.cell.cut_for_dimension(dimension) if cut: is_last = cut.level_depth() >= len(hierarchy) else: is_last = False table = self.formatter.format(result, dimension, aggregates=aggregates) output = self.template.render(cell=result.cell, dimension=dimension, table=table, create_links=self.create_links, table_style=self.table_style, is_last=is_last) return output class RickshawSeriesFormatter(Formatter): """Presenter for series to be used in Rickshaw JavaScript charting library. Library URL: http://code.shutterstock.com/rickshaw/""" def format(self, result, aggregate): data = [] for x, row in enumerate(result): data.append({"x":x, "y":row[str(aggregate)]}) return data _default_ricshaw_palette = ["mediumorchid", "steelblue", "turquoise", "mediumseagreen", "gold", "orange", "tomato"] class RickshawMultiSeriesFormatter(Formatter): """Presenter for series to be used in Rickshaw JavaScript charting library. Library URL: http://code.shutterstock.com/rickshaw/""" def format(self, result, series_dimension, values_dimension, aggregate, color_map=None, color_palette=None): """Provide multiple series. Result is expected to be ordered. Arguments: * `result` – AggregationResult object * `series_dimension` – dimension used for split to series * `value_dimension` – dimension used to get values * `aggregated_measure` – measure attribute to be plotted * `color_map` – The dictionary is a map between dimension keys and colors, the map keys should be strings. * `color_palette` – List of colors that will be cycled for each series. Note: you should use either color_map or color_palette, not both. """ if color_map and color_palette: raise CubesError("Use either color_map or color_palette, not both") color_map = color_map or {} color_palette = color_palette or _default_ricshaw_palette cube = result.cell.cube series_dimension = cube.dimension(series_dimension) values_dimension = cube.dimension(values_dimension) try: series_level = result.levels[str(series_dimension)][-1] except KeyError: raise CubesError("Result was not drilled down by dimension '%s'" \ % str(series_dimension)) try: values_level = result.levels[str(values_dimension)][-1] except KeyError: raise CubesError("Result was not drilled down by dimension '%s'" \ % str(values_dimension)) series = [] rows = [series_level.key.ref(), series_level.label_attribute.ref()] columns = [values_level.key.ref(), values_level.label_attribute.ref()] cross_table = result.cross_table(onrows=rows, oncolumns=columns, aggregates=[aggregate]) color_index = 0 for head, row in zip(cross_table.rows, cross_table.data): data = [] for x, value in enumerate(row): data.append({"x":x, "y":value[0]}) # Series label is in row heading at index 1 series_dict = { "data": data, "name": head[1] } # Use dimension key for color if color_map: series_dict["color"] = color_map.get(str(head[0])) elif color_palette: color_index = (color_index + 1) % len(color_palette) series_dict["color"] = color_palette[color_index] series.append(series_dict) return series <file_sep>************************* Model Providers Reference ************************* .. seealso:: :doc:`model` Loading Model Metadata ====================== .. autofunction:: cubes.read_model_metadata .. autofunction:: cubes.read_model_metadata_bundle Model Providers =============== .. autofunction:: cubes.create_model_provider .. autoclass:: cubes.ModelProvider .. autoclass:: cubes.StaticModelProvider <file_sep>******************* Workspace Reference ******************* Workspace manages all cubes, their data stores and model providers. .. autoclass:: cubes.Workspace <file_sep>from mongo2 import * from sql import * from slicer import * <file_sep>+++++++++++++++++++++++++++++++++ Logical to Physical Model Mapping +++++++++++++++++++++++++++++++++ One of the most important parts of proper OLAP on top of the relational database is the mapping of logical attributes to their physical counterparts. In SQL database the physical attribute is stored in a column, which belongs to a table, which might be part of a database schema. .. figure:: images/mapping_logical_to_physical.png :align: center :width: 400px .. note:: StarBrowser (SQL) is used as an example. .. note:: Despite this chapter describes examples mostly in the relational database backend, the principles are the same, or very similar, in other backends as well. For example, take a reference to an attribute *name* in a dimension *product*. What is the column of what table in which schema that contains the value of this dimension attribute? .. figure:: images/mapping-example1.png :align: center :width: 400px For data browsing, the Cubes framework has to know where those logical (reported) attributes are physically stored. It needs to know which tables are related to the cube and how they are joined together so we get whole view of a fact. The process is done in two steps: 1. joining relevant star/snowflake tables 2. mapping logical attribute to table + column There are two ways how the mapping is being done: *implicit* and *explicit*. The simplest, straightforward and most customizable is the explicit way, where the actual column reference is provided in a mapping dictionary of the cube description. Implicit Mapping ---------------- With implicit mapping one can match a database schema with logical model and does not have to specify additional mapping metadata. Expected structure is star schema with one table per (denormalized) dimension. **Fact table:** Cubes looks for fact table with the same name as cube name. You might specify prefix for every fact table with ``fact_table_prefix``. Example: * Cube is named `contracts`, framework looks for a table named `contracts`. * Cubes are named `contracts`, `invoices` and fact table prefix is ``fact_`` then framework looks for tables named ``fact_contracts`` and ``fact_invoices`` respectively. Dimension tables ---------------- By default, dimension tables are expected to have same name as dimensions and dimension table columns are expected to have same name as dimension attributes: .. figure:: images/dimension_attribute_implicit_map.png :align: center It is quite common practice that dimension tables have a prefix such as ``dim_`` or ``dm_``. Such prefix can be specified with ``dimension_prefix`` option. .. figure:: images/dimension_attribute_prefix_map.png :align: center Basic rules: * fact table should have same name as represented cube * dimension table should have same name as the represented dimension, for example: `product` (singular) * column name should have same name as dimension attribute: `name`, `code`, `description` * references without dimension name in them are expected to be in the fact table, for example: `amount`, `discount` (see note below for simple flat dimensions) * if attribute is localized, then there should be one column per localization and should have locale suffix: `description_en`, `description_sk`, `description_fr` (see below for more information) **Flat dimension without details:** What about dimensions that have only one attribute, like one would not have a full date but just a `year`? In this case it is kept in the fact table without need of separate dimension table. The attribute is treated in by the same rule as measure and is referenced by simple `year`. This is applied to all dimensions that have only one attribute (representing key as well). This dimension is referred to as *flat and without details*. Note for advanced users: this behavior can be disabled by setting ``simplify_dimension_references`` to ``False`` in the mapper. In that case you will have to have separate table for the dimension attribute and you will have to reference the attribute by full name. This might be useful when you know that your dimension will be more detailed. .. note:: In other than SQL backends, the implicit mapping might be implemented differently. Refer to the respective backend documentation to learn how the mapping is done. Database Schemas ---------------- For databases that support schemas, such as PostgreSQL, option ``schema`` can be used to specify default database schema where all tables are going to be looked for. In case you have dimensions stored in separate schema than fact table, you can specify that in ``dimension_schema``. All dimension tables are going to be searched in that schema. .. _explicit_mapping: Explicit Mapping ---------------- If the schema does not match expectations of cubes, it is possible to explicitly specify how logical attributes are going to be mapped to their physical tables and columns. `Mapping dictionary` is a dictionary of logical attributes as keys and physical attributes (columns, fields) as values. The logical attributes references look like: * `dimensions_name.attribute_name`, for example: ``geography.country_name`` or ``category.code`` * `fact_attribute_name`, for example: ``amount`` or ``discount`` For example: .. code-block:: javascript "mappings": { "product.name": "dm_products.product_name" } If it is in different schema or any part of the reference contains a dot: .. code-block:: javascript "mappings": { "product.name": { "schema": "sales", "table": "dm_products", "column": "product_name" } } Both, explicit and implicit mappings have ability to specify default database schema (if you are using Oracle, PostgreSQL or any other DB which supports schemas). The mapping process process is like this: .. figure:: images/mapping-overview.png :align: center :width: 500px .. note:: In other than SQL backends, the value in the mapping dictionary can be interpreted differently. The (`schema`, `table`, `column`) tuple is used as an example from SQL browser. Date Data Type -------------- Date datatype column can be turned into a date dimension by extracting date parts in the mapping. To do so, for each date attribute specify a ``column`` name and part to be extracted with value for ``extract`` key. .. code-block:: javascript "mappings": { "date.year": {"column":"date", "extract":"year"}, "date.month": {"column":"date", "extract":"month"}, "date.day": {"column":"date", "extract":"day"} } According to SQLAlchemy, you can extract in most of the databases: ``month``, ``day``, ``year``, ``second``, ``hour``, ``doy`` (day of the year), ``minute``, ``quarter``, ``dow`` (day of the week), ``week``, ``epoch``, ``milliseconds``, ``microseconds``, ``timezone_hour``, ``timezone_minute``. Please refer to your database engine documentation for more information. .. note:: It is still recommended to have a date dimension table. Localization ------------ Despite localization taking place first in the mapping process, we talk about it at the end, as it might be not so commonly used feature. From physical point of view, the data localization is very trivial and requires language denormalization - that means that each language has to have its own column for each attribute. Localizable attributes are those attributes that have ``locales`` specified in their definition. To map logical attributes which are localizable, use locale suffix for each locale. For example attribute `name` in dimension `category` has two locales: Slovak (``sk``) and English (``en``). Or for example product category can be in English, Slovak or German. It is specified in the model like this: .. code-block:: javascript attributes = [ { "name" = "category", "locales" = ["en", "sk", "de"] } ] During the mapping process, localized logical reference is created first: .. figure:: images/mapping-to_localized.png :align: center :width: 600px In short: if attribute is localizable and locale is requested, then locale suffix is added. If no such localization exists then default locale is used. Nothing happens to non-localizable attributes. For such attribute, three columns should exist in the physical model. There are two ways how the columns should be named. They should have attribute name with locale suffix such as ``category_sk`` and ``category_en`` (_underscore_ because it is more common in table column names), if implicit mapping is used. You can name the columns as you like, but you have to provide explicit mapping in the mapping dictionary. The key for the localized logical attribute should have ``.locale`` suffix, such as ``product.category.sk`` for Slovak version of category attribute of dimension product. Here the _dot_ is used because dots separate logical reference parts. .. note:: Current implementation of Cubes framework requires a star or snowflake schema that can be joined into fully denormalized normalized form just by simple one-key based joins. Therefore all localized attributes have to be stored in their own columns. In other words, you have to denormalize the localized data before using them in Cubes. Read more about :doc:`localization`. Customization of the Implicit ----------------------------- The implicit mapping process has a little bit of customization as well: * `dimension_table_prefix`: you can specify what prefix will be used for all dimension tables. For example if the prefix is ``dim_`` and attribute is `product.name` then the table is going to be ``dim_product``. * `fact_table_prefix`: used for constructing fact table name from cube name. Example: having prefix ``ft_`` all fact attributes of cube `sales` are going to be looked up in table ``ft_sales`` * `fact_table_name`: one can explicitly specify fact table name for each cube separately See also: :class:`cubes.backends.sql.mapper.SnowflakeMapper` Mapping Process Summary ----------------------- Following diagram describes how the mapping of logical to physical attributes is done in the star SQL browser (see :class:`cubes.backends.sql.StarBrowser`): .. figure:: images/mapping-logical_to_physical.png :align: center :width: 600px logical to physical attribute mapping The "red path" shows the most common scenario where defaults are used. Joins ===== Star browser supports a star: .. figure:: images/schema_star.png :align: center :width: 300px and snowflake database schema: .. figure:: images/schema_snowflake.png :align: center :width: 300px If you are using either of the two schemas (star or snowflake) in relational database, Cubes requires information on how to join the tables. Tables are joined by matching single-column – surrogate keys. The framework needs the join information to be able to transform following snowflake: .. figure:: images/snowflake_schema.png :align: center :width: 400px to appear as this (denormalized table) with all cube attributes: .. figure:: images/denormalized_schema.png :align: center :width: 400px Join ---- The single join description consists of reference to the `master` table and a table with `details`. Fact table is example of master table, dimension is example of a detail table (in star schema). .. note:: As mentioned before, only single column – surrogate keys are supported for joins. The join specification is very simple, you define column reference for both: master and detail. The table reference is in the form `table`.`column`: .. code-block:: javascript "joins" = [ { "master": "fact_sales.product_key", "detail": "dim_product.key" } ] As in mappings, if you have specific needs for explicitly mentioning database schema or any other reason where `table.column` reference is not enough, you might write: .. code-block:: javascript "joins" = [ { "master": "fact_sales.product_id", "detail": { "schema": "sales", "table": "dim_products", "column": "id" } ] Aliases ------- What if you need to join same table twice or more times? For example, you have list of organizations and you want to use it as both: supplier and service consumer. .. figure:: images/joins-in_physical.png :align: center :width: 500px It can be done by specifying alias in the joins: .. code-block:: javascript "joins" = [ { "master": "contracts.supplier_id", "detail": "organisations.id", "alias": "suppliers" }, { "master": "contracts.consumer_id", "detail": "organisations.id", "alias": "consumers" } ] Note that with aliases, in the mappings you refer to the table by alias specified in the joins, not by real table name. So after aliasing tables with previous join specification, the mapping should look like: .. code-block:: javascript "mappings": { "supplier.name": "suppliers.org_name", "consumer.name": "consumers.org_name" } For example, we have a fact table named ``fact_contracts`` and dimension table with categories named ``dm_categories``. To join them we define following join specification: .. code-block:: javascript "joins" = [ { "master": "fact_contracts.category_id", "detail": "dm_categories.id" } ] <file_sep># -*- coding=utf -*- import unittest from cubes import * from .common import CubesTestCaseBase from json import dumps def printable(obj): return dumps(obj, indent=4) class AuthTestCase(CubesTestCaseBase): def setUp(self): self.sales_cube = Cube("sales") self.churn_cube = Cube("churn") def test_empty(self): self.auth = SimpleAuthorizer() self.assertEqual([], self.auth.authorize("john", [self.sales_cube])) def test_authorize(self): rights = { "john": {"allow_cubes": ["sales"]} } self.auth = SimpleAuthorizer(rights=rights) self.assertEqual([self.sales_cube], self.auth.authorize("john", [self.sales_cube])) self.assertEqual([], self.auth.authorize("ivana", [self.churn_cube])) def test_deny(self): rights = { "john": {"deny_cubes": ["sales"]} } self.auth = SimpleAuthorizer(rights=rights) self.assertEqual([self.churn_cube], self.auth.authorize("john", [self.churn_cube])) self.assertEqual([self.sales_cube], self.auth.authorize("john", [self.sales_cube])) self.assertEqual([], self.auth.authorize("ivana", [self.churn_cube])) def test_role(self): roles = { "marketing": {"allow_cubes": ["sales"]} } rights = { "john": {"roles": ["marketing"]} } self.auth = SimpleAuthorizer(rights=rights, roles=roles) self.assertEqual([self.sales_cube], self.auth.authorize("john", [self.sales_cube])) def test_role_inheritance(self): roles = { "top": {"allow_cubes": ["sales"]}, "marketing": {"roles": ["top"]} } rights = { "john": {"roles": ["marketing"]} } self.auth = SimpleAuthorizer(rights=rights, roles=roles) self.assertEqual([self.sales_cube], self.auth.authorize("john", [self.sales_cube])) <file_sep># -*- coding=utf -*- """Logical model model providers.""" import json import os import re import urllib2 import urlparse import copy import shutil from .common import IgnoringDictionary, to_label from .logging import get_logger from .errors import * from .extensions import get_namespace, initialize_namespace from .model import * __all__ = [ "read_model_metadata", "read_model_metadata_bundle", "create_model_provider", "ModelProvider", "StaticModelProvider", # FIXME: Depreciated "load_model", "model_from_path", "create_model", "merge_models", ] def create_model_provider(name, metadata): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("model_providers") if not ns: # FIXME: depreciated. affected: formatter.py ns = initialize_namespace("model_providers", root_class=ModelProvider, suffix="_model_provider") ns["default"] = StaticModelProvider try: factory = ns[name] except KeyError: raise CubesError("Unable to find model provider of type '%s'" % name) return factory(metadata) def _json_from_url(url): """Opens `resource` either as a file with `open()`or as URL with `urllib2.urlopen()`. Returns opened handle. """ parts = urlparse.urlparse(url) if parts.scheme in ('', 'file'): handle = open(parts.path) else: handle = urllib2.urlopen(url) try: desc = json.load(handle) except ValueError as e: raise SyntaxError("Syntax error in %s: %s" % (url, e.args)) finally: handle.close() return desc def read_model_metadata(source): """Reads a model description from `source` which can be a filename, URL, file-like object or a path to a directory. Returns a model description dictionary.""" if isinstance(source, basestring): parts = urlparse.urlparse(source) if parts.scheme in ('', 'file') and os.path.isdir(parts.path): source = parts.path return read_model_metadata_bundle(source) else: return _json_from_url(source) else: return json.load(source) def read_model_metadata_bundle(path): """Load logical model a directory specified by `path`. Returns a model description dictionary. Model directory bundle has structure: * ``model.cubesmodel/`` * ``model.json`` * ``dim_*.json`` * ``cube_*.json`` The dimensions and cubes lists in the ``model.json`` are concatenated with dimensions and cubes from the separate files. """ if not os.path.isdir(path): raise ArgumentError("Path '%s' is not a directory.") info_path = os.path.join(path, 'model.json') if not os.path.exists(info_path): raise ModelError('main model info %s does not exist' % info_path) model = _json_from_url(info_path) # Find model object files and load them if not "dimensions" in model: model["dimensions"] = [] if not "cubes" in model: model["cubes"] = [] for dirname, dirnames, filenames in os.walk(path): for filename in filenames: if os.path.splitext(filename)[1] != '.json': continue split = re.split('_', filename) prefix = split[0] obj_path = os.path.join(dirname, filename) if prefix in ('dim', 'dimension'): desc = _json_from_url(obj_path) try: name = desc["name"] except KeyError: raise ModelError("Dimension file '%s' has no name key" % obj_path) if name in model["dimensions"]: raise ModelError("Dimension '%s' defined multiple times " % "(in '%s')" % (name, obj_path) ) model["dimensions"].append(desc) elif prefix == 'cube': desc = _json_from_url(obj_path) try: name = desc["name"] except KeyError: raise ModelError("Cube file '%s' has no name key" % obj_path) if name in model["cubes"]: raise ModelError("Cube '%s' defined multiple times " "(in '%s')" % (name, obj_path) ) model["cubes"].append(desc) return model def write_model_metadata_bundle(path, metadata, replace=False): """Writes a model metadata bundle into new directory `target` from `metadata`. Directory should not exist.""" if os.path.exists(path): if not os.path.isdir(path): raise CubesError("Target exists and is a file, " "can not replace") elif not os.path.exists(os.path.join(path, "model.json")): raise CubesError("Target is not a model directory, " "can not replace.") if replace: shutil.rmtree(path) else: raise CubesError("Target already exists. " "Remove it or force replacement.") os.makedirs(path) metadata = dict(metadata) dimensions = metadata.pop("dimensions", []) cubes = metadata.pop("cubes", []) for dim in dimensions: name = dim["name"] filename = os.path.join(path, "dim_%s.json" % name) with open(filename, "w") as f: json.dump(dim, f, indent=4) for cube in cubes: name = cube["name"] filename = os.path.join(path, "cube_%s.json" % name) with open(filename, "w") as f: json.dump(cube, f, indent=4) filename = os.path.join(path, "model.json") with open(filename, "w") as f: json.dump(metadata, f, indent=4) def load_model(resource, translations=None): raise Exception("load_model() was replaced by Workspace.add_model(), " "please refer to the documentation for more information") class ModelProvider(object): """Abstract class. Currently empty and used only to find other model providers.""" def __init__(self, metadata=None): """Base class for model providers. Initializes a model provider and sets `metadata` – a model metadata dictionary. Instance variable `store` might be populated after the initialization. If the model provider requires an open store, it should advertise it through `True` value returned by provider's `requires_store()` method. Otherwise no store is opened for the model provider. `store_name` is also set. Subclasses should call this method at the beginning of the custom `__init__()`. If a model provider subclass has a metadata that should be pre-pended to the user-provided metadta, it should return it in `default_metadata()`. Subclasses should implement at least: :meth:`cubes.ModelProvider.cube`, :meth:`cubes.ModelProvider.dimension` and :meth:`cubes.ModelProvider.list_cubes` """ self.store = None self.store_name = None # Get provider's defaults and pre-pend it to the user provided # metadtata. defaults = self.default_metadata() self.metadata = self._merge_metadata(defaults, metadata) # TODO: check for duplicates self.dimensions_metadata = {} for dim in self.metadata.get("dimensions", []): self.dimensions_metadata[dim["name"]] = dim self.cubes_metadata = {} for cube in self.metadata.get("cubes", []): self.cubes_metadata[cube["name"]] = cube # TODO: decide which one to use self.options = self.metadata.get("options", {}) self.options.update(self.metadata.get("browser_options", {})) def _merge_metadata(self, metadata, other): """See `default_metadata()` for more information.""" metadata = dict(metadata) other = dict(other) cubes = metadata.pop("cubes", []) + other.pop("cubes", []) if cubes: metadata["cubes"] = cubes dims = metadata.pop("dimensions", []) + other.pop("dimensions", []) if dims: metadata["dimensions"] = dims joins = metadata.pop("joins", []) + other.pop("joins",[]) if joins: metadata["joins"] = joins mappings = metadata.pop("mappings", {}) mappings.update(other.pop("mappings", {})) if mappings: metadata["mappings"] = mappings metadata.update(other) return metadata def default_metadata(self, metadata=None): """Returns metadata that are prepended to the provided model metadata. `metadata` is user-provided metadata and might be used to decide what kind of default metadata are returned. The metadata are merged as follows: * cube lists are concatenated (no duplicity checking) * dimension lists are concatenated (no duplicity checking) * joins are concatenated * default mappings are updated with the model's mappings Default implementation returns empty metadata. """ return {} def requires_store(self): """Return `True` if the provider requires a store. Subclasses might override this method. Default implementation returns `False`""" return False def set_store(self, store, store_name): """Set's the provider's `store` and `store_name`. The store can be used to retrieve model's metadata. The store name is a handle that can be passed to the Cube objects for workspace to know where to find cube's data.""" self.store = store self.store_name = store_name self.initialize_from_store() def initialize_from_store(self): """Sets provider's store and store name. This method is called after the provider's `store` and `store_name` were set. Override this method if you would like to perform post-initialization from the store.""" pass def cube_options(self, cube_name): """Returns an options dictionary for cube `name`. The options dictoinary is merged model `options` metadata with cube's `options` metadata if exists. Cube overrides model's global (default) options.""" options = dict(self.options) if cube_name in self.cubes_metadata: cube = self.cubes_metadata[cube_name] # TODO: decide which one to use options.update(cube.get("options", {})) options.update(cube.get("browser_options", {})) return options def dimension_metadata(self, name): """Returns a metadata dictionary for dimension `name`.""" return self.dimensions_metadata[name] def cube_metadata(self, name): """Returns a cube metadata by combining model's global metadata and cube's metadata. Merged metadata dictionaries: `browser_options`, `mappings`, `joins`. """ if name in self.cubes_metadata: metadata = dict(self.cubes_metadata[name]) else: raise NoSuchCubeError("Unknown cube '%s'" % name, name) # merge datastore from model if datastore not present if not metadata.get("datastore"): metadata['datastore'] = self.metadata.get("datastore") # merge browser_options browser_options = self.metadata.get('browser_options', {}) if metadata.get('browser_options'): browser_options.update(metadata.get('browser_options')) metadata['browser_options'] = browser_options # Merge model and cube mappings # model_mappings = self.metadata.get("mappings") cube_mappings = metadata.pop("mappings", {}) if model_mappings: mappings = copy.deepcopy(model_mappings) mappings.update(cube_mappings) else: mappings = cube_mappings metadata["mappings"] = mappings # Merge model and cube joins # model_joins = self.metadata.get("joins", []) cube_joins = metadata.pop("joins", []) # model joins, if present, should be merged with cube's overrides. # joins are matched by the "name" key. if cube_joins and model_joins: model_join_map = {} for join in model_joins: try: jname = join['name'] except KeyError: raise ModelError("Missing required 'name' key in " "model-level joins.") if jname in model_join_map: raise ModelError("Duplicate model-level join 'name': %s" % jname) model_join_map[jname] = copy.deepcopy(join) # Merge cube's joins with model joins by their names. merged_joins = [] for join in cube_joins: name = join.get('name') if name: try: model_join = model_join_map[join.get('name')] except KeyError: raise ModelError("No model join template '%s' found" % join.get('name')) model_join = dict(model_join) else: model_join = {} model_join.update(join) merged_joins.append(model_join) else: merged_joins = cube_joins # Validate joins: for join in merged_joins: if "master" not in join: raise ModelError("No master in join for cube '%s' " "(join name: %s)" % (name, join.get("name"))) if "detail" not in join: raise ModelError("No detail in join for cube '%s' " "(join name: %s)" % (name, join.get("name"))) metadata["joins"] = merged_joins return metadata def public_dimensions(self): """Returns a list of public dimension names. Default implementation returs all dimensions defined in the model metadata. If ``public_dimensions`` model property is set, then this list is used. Subclasses might override this method for alternative behavior. For example, if the backend uses dimension metadata from the model, but does not publish any dimension it can return an empty list.""" # Get list of exported dimensions # By default all explicitly mentioned dimensions are exported. # try: return self.metadata["public_dimensions"] except KeyError: dimensions = self.metadata.get("dimensions", []) names = [dim["name"] for dim in dimensions] return names def list_cubes(self): """Get a list of metadata for cubes in the workspace. Result is a list of dictionaries with keys: `name`, `label`, `category`, `info`. The list is fetched from the model providers on the call of this method. Subclassees should implement this method. """ raise NotImplementedError("Subclasses should implement list_cubes()") return [] def cube(self, name): """Returns a cube with `name` provided by the receiver. If receiver does not have the cube `ModelError` exception is raised. Returned cube has no dimensions assigned. You should assign the dimensions according to the cubes `linked_dimensions` list of dimension names. Subclassees should implement this method. """ raise NotImplementedError("Subclasses should implement cube() method") def dimension(self, name, dimensions=[]): """Returns a dimension with `name` provided by the receiver. `dimensions` is a dictionary of dimension objects where the receiver can look for templates. If the dimension requires a template and the template is missing, the subclasses should raise `TemplateRequired(template)` error with a template name as an argument. If the receiver does not provide the dimension `NoSuchDimension` exception is raised. Subclassees should implement this method. """ raise NotImplementedError("Subclasses are required to implement this") class StaticModelProvider(ModelProvider): dynamic_cubes = False dynamic_dimensions = False def __init__(self, *args, **kwargs): super(StaticModelProvider, self).__init__(*args, **kwargs) def list_cubes(self): """Returns a list of cubes from the metadata.""" cubes = [] for cube in self.metadata.get("cubes", []): info = { "name": cube["name"], "label": cube.get("label", cube["name"]), "category": (cube.get("category") or cube.get("info", {}).get("category")), "info": cube.get("info", {}) } cubes.append(info) return cubes def cube(self, name): """ Creates a cube `name` in context of `workspace` from provider's metadata. The created cube has no dimensions attached. You sohuld link the dimensions afterwards according to the `linked_dimensions` property of the cube. """ metadata = self.cube_metadata(name) return create_cube(metadata) def dimension(self, name, dimensions=None): """Create a dimension `name` from provider's metadata within `context` (usualy a `Workspace` object).""" # Old documentation """Creates a `Dimension` instance from `obj` which can be a `Dimension` instance or a string or a dictionary. If it is a string, then it represents dimension name, the only level name and the only attribute. Keys of a dictionary representation: * `name`: dimension name * `levels`: list of dimension levels (see: :class:`cubes.Level`) * `hierarchies` or `hierarchy`: list of dimension hierarchies or list of level names of a single hierarchy. Only one of the two should be specified, otherwise an exception is raised. * `default_hierarchy_name`: name of a hierarchy that will be used when no hierarchy is explicitly specified * `label`: dimension name that will be displayed (human readable) * `description`: human readable dimension description * `info` - custom information dictionary, might be used to store application/front-end specific information (icon, color, ...) * `template` – name of a dimension to be used as template. The dimension is taken from `dimensions` argument which should be a dictionary of already created dimensions. **Defaults** * If no levels are specified during initialization, then dimension name is considered flat, with single attribute. * If no hierarchy is specified and levels are specified, then default hierarchy will be created from order of levels * If no levels are specified, then one level is created, with name `default` and dimension will be considered flat String representation of a dimension ``str(dimension)`` is equal to dimension name. Class is not meant to be mutable. Raises `ModelInconsistencyError` when both `hierarchy` and `hierarchies` is specified. """ try: metadata = dict(self.dimensions_metadata[name]) except KeyError: raise NoSuchDimensionError(name) return create_dimension(metadata, dimensions, name) # TODO: is this still necessary? def merge_models(models): """Merge multiple models into one.""" dimensions = {} all_cubes = {} name = None label = None description = None info = {} locale = None for model in models: if name is None and model.name: name = model.name if label is None and model.label: label = model.label if description is None and model.description: description = model.description if info is None and model.info: info = copy.deepcopy(model.info) if locale is None and model.locale: locale = model.locale # dimensions, fail on conflicting names for dim in model.dimensions: if dimensions.has_key(dim.name): raise ModelError("Found duplicate dimension named '%s', cannot merge models" % dim.name) dimensions[dim.name] = dim # cubes, fail on conflicting names for cube in model.cubes.values(): if all_cubes.has_key(cube.name): raise ModelError("Found duplicate cube named '%s', cannot merge models" % cube.name) model.remove_cube(cube) if cube.info is None: cube.info = {} cube.info.update(model.info if model.info else {}) all_cubes[cube.name] = cube return Model(name=name, label=label, description=description, info=info, dimensions=dimensions.values(), cubes=all_cubes.values()) def create_model(source): raise NotImplementedError("create_model() is depreciated, use Workspace.add_model()") def model_from_path(path): """Load logical model from a file or a directory specified by `path`. Returs instance of `Model`. """ raise NotImplementedError("model_from_path is depreciated. use Workspace.add_model()") # TODO: modernize def simple_model(cube_name, dimensions, measures): """Create a simple model with only one cube with name `cube_name`and flat dimensions. `dimensions` is a list of dimension names as strings and `measures` is a list of measure names, also as strings. This is convenience method mostly for quick model creation for denormalized views or tables with data from a single CSV file. Example: .. code-block:: python model = simple_model("contracts", dimensions=["year", "supplier", "subject"], measures=["amount"]) cube = model.cube("contracts") browser = workspace.create_browser(cube) """ dim_instances = [] for dim_name in dimensions: dim_instances.append(create_dimension(dim_name)) cube = Cube(cube_name, dim_instances, measures) return Model(cubes=[cube]) <file_sep>Flask Dimension Browser ======================= Simple browser of dimension hierarchy served with Flask web microframework. The application displays an aggregated table where user can drill down through dimension levels. Requirements ------------ Prepare the `hello_world` data in ``../hello_world`` by running: python prepare_data.py Use --- Run the server:: python application.py And navigate your browser to http://localhost:5000/ You can also access the raw data using the Slicer at http://localhost:5000/slicer Files ----- This directory contains following files: * application.py - the web application (see commends in the file) * templates/report.html - HTML template that shows the simple table report (see comments in the file) * static/ - just static files, such as Twitter Bootstrap css so it can be pretty Credits ------- The example data used are IBRD Balance Sheet taken from The World Bank: https://finances.worldbank.org/Accounting-and-Control/IBRD-Balance-Sheet-FY2010/e8yz-96c6 <file_sep>"""Cubes SQL backend utilities, mostly to be used by the slicer command.""" from sqlalchemy.sql.expression import Executable, ClauseElement from sqlalchemy.ext.compiler import compiles import sqlalchemy.sql as sql __all__ = [ "CreateTableAsSelect", "InsertIntoAsSelect", "condition_conjunction", "order_column" ] class CreateTableAsSelect(Executable, ClauseElement): def __init__(self, table, select): self.table = table self.select = select @compiles(CreateTableAsSelect) def visit_create_table_as_select(element, compiler, **kw): preparer = compiler.dialect.preparer(compiler.dialect) full_name = preparer.format_table(element.table) return "CREATE TABLE %s AS (%s)" % ( element.table, compiler.process(element.select) ) class InsertIntoAsSelect(Executable, ClauseElement): def __init__(self, table, select, columns=None): self.table = table self.select = select self.columns = columns @compiles(InsertIntoAsSelect) def visit_insert_into_as_select(element, compiler, **kw): preparer = compiler.dialect.preparer(compiler.dialect) full_name = preparer.format_table(element.table) if element.columns: qcolumns = [preparer.format_column(c) for c in element.columns] col_list = "(%s) " % ", ".join([str(c) for c in qcolumns]) else: col_list = "" stmt = "INSERT INTO %s %s(%s)" % ( full_name, col_list, compiler.process(element.select) ) return stmt def condition_conjunction(conditions): """Do conjuction of conditions if there are more than one, otherwise just return the single condition.""" if not conditions: return None elif len(conditions) == 1: return conditions[0] else: return sql.expression.and_(*conditions) def order_column(column, order): """Orders a `column` according to `order` specified as string.""" if not order: return column elif order.lower().startswith("asc"): return column.asc() elif order.lower().startswith("desc"): return column.desc() else: raise ArgumentError("Unknown order %s for column %s") % (order, column) <file_sep>How-to: hierarchies, levels and drilling-down ============================================= In this Cubes OLAP how-to we are going to learn: * how to create a hierarchical dimension * how to do drill-down through a hierarchy * detailed level description In the [previous tutorial](http://blog.databrewery.org/post/13255558153/cubes-tutorial-2-model-and-mappings) we learned how to use model descriptions in a JSON file and how to do physical to logical mappings. Data used are similar as in the second tutorial, manually modified [IBRD Balance Sheet](https://raw.github.com/Stiivi/cubes/master/tutorial/data/IBRD_Balance_Sheet__FY2010-t03.csv) taken from [The World Bank](https://finances.worldbank.org/Accounting-and-Control/IBRD-Balance-Sheet-FY2010/e8yz-96c6). Difference between second tutorial and this one is added two columns: category code and sub-category code. They are simple letter codes for the categories and subcategories. Hierarchy --------- Some dimensions can have multiple levels forming a hierarchy. For example dates have year, month, day; geography has country, region, city; product might have category, subcategory and the product. Note: Cubes supports multiple hierarchies, for example for date you might have year-month-day or year-quarter-month-day. Most dimensions will have one hierarchy, thought. In our example we have the ``item`` dimension with three levels of hierarchy: _category_, _subcategory_ and _line item_: ![](http://media.tumblr.com/tumblr_lvdr0nIHgl1qgmvbu.png) The levels are defined in the model: <pre class="prettyprint"> "levels": [ { "name":"category", "label":"Category", "attributes": ["category"] }, { "name":"subcategory", "label":"Sub-category", "attributes": ["subcategory"] }, { "name":"line_item", "label":"Line Item", "attributes": ["line_item"] } ] </pre> You can see a slight difference between this model description and the previous one: we didn't just specify level names and didn't let cubes to fill-in the defaults. Here we used explicit description of each level. <code>name</code> is level identifier, <code>label</code> is human-readable label of the level that can be used in end-user applications and <code>attributes</code> is list of attributes that belong to the level. The first attribute, if not specified otherwise, is the key attribute of the level. Other level description attributes are <code>key</code> and <code>label_attribute</code>. The <code>key</code> specifies attribute name which contains key for the level. Key is an id number, code or anything that uniquely identifies the dimension level. <code>label_attribute</code> is name of an attribute that contains human-readable value that can be displayed in user-interface elements such as tables or charts. Preparation ----------- In this how-to we are going to skip all off-topic code, such as data initialization. The full example can be found in the [tutorial sources](https://github.com/Stiivi/cubes/tree/master/tutorial) with suffix <code>03</code>. In short we need: * data in a database * logical model (see <code>model_03.json</code>) prepared with appropriate mappings * denormalized view for aggregated browsing (for current simple SQL browser implementation) Drill-down ---------- Drill-down is an action that will provide more details about data. Drilling down through a dimension hierarchy will expand next level of the dimension. It can be compared to browsing through your directory structure. We create a function that will recursively traverse a dimension hierarchy and will print-out aggregations (count of records in this example) at the actual browsed location. **Attributes** * cell - cube cell to drill-down * dimension - dimension to be traversed through all levels * path - current path of the `dimension` Path is list of dimension points (keys) at each level. It is like file-system path. <pre class="prettyprint"> def drill_down(cell, dimension, path = []): </pre> Get dimension's default hierarchy. Cubes supports multiple hierarchies, for example for date you might have year-month-day or year-quarter-month-day. Most dimensions will have one hierarchy, thought. <pre class="prettyprint"> hierarchy = dimension.default_hierarchy </pre> _Base path_ is path to the most detailed element, to the leaf of a tree, to the fact. Can we go deeper in the hierarchy? <pre class="prettyprint"> if hierarchy.path_is_base(path): return </pre> Get the next level in the hierarchy. <code>levels_for_path</code> returns list of levels according to provided path. When <code>drilldown</code> is set to <code>True</code> then one more level is returned. <pre class="prettyprint"> levels = hierarchy.levels_for_path(path,drilldown=True) current_level = levels[-1] </pre> We need to know name of the level key attribute which contains a path component. If the model does not explicitly specify key attribute for the level, then first attribute will be used: <pre class="prettyprint"> level_key = dimension.attribute_reference(current_level.key) </pre> For prettier display, we get name of attribute which contains label to be displayed for the current level. If there is no label attribute, then key attribute is used. <pre class="prettyprint"> level_label = dimension.attribute_reference(current_level.label_attribute) </pre> We do the aggregation of the cell... Think of <code>ls $CELL</code> command in commandline, where <code>$CELL</code> is a directory name. In this function we can think of <code>$CELL</code> to be same as current working directory (<code>pwd</code>) <pre class="prettyprint"> result = browser.aggregate(cell, drilldown=[dimension]) for record in result.drilldown: print "%s%s: %d" % (indent, record[level_label], record["record_count"]) ... </pre> And now the drill-down magic. First, construct new path by key attribute value appended to the current path: <pre class="prettyprint"> drill_path = path[:] + [record[level_key]] </pre> Then get a new cell slice for current path: <pre class="prettyprint"> drill_down_cell = cell.slice(dimension, drill_path) </pre> And do recursive drill-down: <pre class="prettyprint"> drill_down(drill_down_cell, dimension, drill_path) </pre> The function looks like this: ![](http://media.tumblr.com/tumblr_lvdrsbS5VW1qgmvbu.png) Working function example <code>03</code> can be found in the [tutorial sources](https://github.com/Stiivi/cubes/blob/master/tutorial/tutorial_03.py). Get the full cube (or any part of the cube you like): <pre class="prettyprint"> cell = browser.full_cube() </pre> And do the drill-down through the item dimension: <pre class="prettyprint"> drill_down(cell, cube.dimension("item")) </pre> The output should look like this: <pre> a: 32 da: 8 Borrowings: 2 Client operations: 2 Investments: 2 Other: 2 dfb: 4 Currencies subject to restriction: 2 Unrestricted currencies: 2 i: 2 Trading: 2 lo: 2 Net loans outstanding: 2 nn: 2 Nonnegotiable, nonintrest-bearing demand obligations on account of subscribed capital: 2 oa: 6 Assets under retirement benefit plans: 2 Miscellaneous: 2 Premises and equipment (net): 2 </pre> Note that because we have changed our source data, we see level codes instead of level names. We will fix that later. Now focus on the drill-down. See that nice hierarchy tree? Now if you slice the cell through year 2010 and do the exact same drill-down: <pre class="prettyprint"> cell = cell.slice("year", [2010]) drill_down(cell, cube.dimension("item")) </pre> you will get similar tree, but only for year 2010 (obviously). Level Labels and Details ------------------------ Codes and ids are good for machines and programmers, they are short, might follow some scheme, easy to handle in scripts. Report users have no much use of them, as they look cryptic and have no meaning for the first sight. Our source data contains two columns for category and for subcategory: column with code and column with label for user interfaces. Both columns belong to the same dimension and to the same level. The key column is used by the analytical system to refer to the dimension point and the label is just decoration. Levels can have any number of detail attributes. The detail attributes have no analytical meaning and are just ignored during aggregations. If you want to do analysis based on an attribute, make it a separate dimension instead. So now we fix our model by specifying detail attributes for the levels: ![](http://media.tumblr.com/tumblr_lvdr2aHJRJ1qgmvbu.png) The model description is: <pre class="prettyprint"> "levels": [ { "name":"category", "label":"Category", "label_attribute": "category_label", "attributes": ["category", "category_label"] }, { "name":"subcategory", "label":"Sub-category", "label_attribute": "subcategory_label", "attributes": ["subcategory", "subcategory_label"] }, { "name":"line_item", "label":"Line Item", "attributes": ["line_item"] } ] } </pre> Note the <code>label_attribute</code> keys. They specify which attribute contains label to be displayed. Key attribute is by-default the first attribute in the list. If one wants to use some other attribute it can be specified in <code>key_attribute</code>. Because we added two new attributes, we have to add mappings for them: <pre class="prettyprint"> "mappings": { "item.line_item": "line_item", "item.subcategory": "subcategory", "item.subcategory_label": "subcategory_label", "item.category": "category", "item.category_label": "category_label" } </pre> In the example tutorial, which can be found in the Cubes sources under <code>tutorial/</code> directory, change the model file from <code>model/model_03.json</code> to <code>model/model_03-labels.json</code> and run the code again. Or fix the file as specified above. Now the result will be: <pre> Assets: 32 Derivative Assets: 8 Borrowings: 2 Client operations: 2 Investments: 2 Other: 2 Due from Banks: 4 Currencies subject to restriction: 2 Unrestricted currencies: 2 Investments: 2 Trading: 2 Loans Outstanding: 2 Net loans outstanding: 2 Nonnegotiable: 2 Nonnegotiable, nonintrest-bearing demand obligations on account of subscribed capital: 2 Other Assets: 6 Assets under retirement benefit plans: 2 Miscellaneous: 2 Premises and equipment (net): 2 </pre> Implicit hierarchy ------------------ Try to remove the last level _line_item_ from the model file and see what happens. Code still works, but displays only two levels. What does that mean? If metadata - logical model - is used properly in an application, then application can handle most of the model changes without any application modifications. That is, if you add new level or remove a level, there is no need to change your reporting application. Summary ------- * hierarchies can have multiple levels * a hierarchy level is identifier by a key attribute * a hierarchy level can have multiple detail attributes and there is one special detail attribute: label attribute used for display in user interfaces Next: slicing and dicing or slicer server, not sure yet. If you have any questions, suggestions, comments, let me know. <file_sep># Formatters example # # Requirements: # Go to the ../hello_world directory and do: python prepare_data.py # # Instructions: # # Just run this file: # # python table.py # Output: # * standard input – text table # * table.html # * cross_table.html # from cubes import Workspace, create_formatter workspace = Workspace("slicer.ini") # Create formatters text_formatter = create_formatter("text_table") html_formatter = create_formatter("simple_html_table") html_cross_formatter = create_formatter("html_cross_table") # Get the browser and data browser = workspace.browser("irbd_balance") result = browser.aggregate(drilldown=["item"]) result = result.cached() # # 1. Create text output # print "Text output" print "-----------" print text_formatter(result, "item") # # 2. Create HTML output (see table.html) # with open("table.html", "w") as f: data = html_formatter(result, "item") f.write(data) # # 3. Create cross-table to cross_table.html # result = browser.aggregate(drilldown=["item", "year"]) with open("cross_table.html", "w") as f: data = html_cross_formatter(result, onrows=["year"], oncolumns=["item.category_label"]) f.write(data) print "Check also table.html and cross_table.html files" <file_sep>from .errors import * from .browser import AggregationBrowser from .extensions import get_namespace, initialize_namespace __all__ = ( "open_store", "Store" ) def open_store(name, **options): """Gets a new instance of a model provider with name `name`.""" ns = get_namespace("stores") if not ns: ns = initialize_namespace("stores", root_class=Store, suffix="_store", option_checking=True) try: factory = ns[name] except KeyError: raise ConfigurationError("Unknown store '%s'" % name) return factory(**options) def create_browser(type_, cube, store, locale, **options): """Creates a new browser.""" ns = get_namespace("browsers") if not ns: ns = initialize_namespace("browsers", root_class=AggregationBrowser, suffix="_browser", option_checking=True) try: factory = ns[type_] except KeyError: raise ConfigurationError("Unable to find browser of type '%s'" % type_) return factory(cube=cube, store=store, locale=locale, **options) def register_browser(type_, class_, options=None): """Register a browser class `class_`. If no `options` are specified, then `__cubes_options__` class attribute is used.""" class Store(object): """Abstract class to find other stores through the class hierarchy.""" pass <file_sep># -*- coding=utf -*- import urllib2 import json import logging import urllib from ...logging import get_logger from ...browser import * class SlicerBrowser(AggregationBrowser): """Aggregation browser for Cubes Slicer OLAP server.""" def __init__(self, cube, store, locale=None, **options): """Browser for another Slicer server. """ super(SlicerBrowser, self).__init__(cube, store, locale) self.logger = get_logger() self.cube = cube self.locale = locale self.store = store def features(self): features = { "actions": ["aggregate", "facts"], } return features def aggregate(self, cell=None, aggregates=None, drilldown=None, split=None, page=None, page_size=None, order=None): params = {} cell = cell or Cell(self.cube) if cell: params["cut"] = string_from_cuts(cell.cuts) if drilldown: drilldown = Drilldown(drilldown, cell) params["drilldown"] = ",".join(drilldown.items_as_strings()) if split: params["split"] = str(split) if aggregates: names = [a.name for a in aggregates] params["aggregates"] = ",".join(names) if order: params["order"] = self._order_param(order) if page is not None: params["page"] = str(page) if page_size is not None: params["page_size"] = str(page_size) response = self.store.cube_request("aggregate", self.cube.name, params) result = AggregationResult() result.cells = response.get('cells', []) if "summary" in response: result.summary = response.get('summary') result.levels = response.get('levels', {}) result.labels = response.get('labels', []) result.cell = cell result.aggregates = response.get('aggregates', []) return result def facts(self, cell=None, fields=None, order=None, page=None, page_size=None): cell = cell or Cell(self.cube) if fields: attributes = self.cube.get_attributes(fields) else: attributes = [] order = self.prepare_order(order, is_aggregate=False) params = {} if cell: params["cut"] = string_from_cuts(cell.cuts) if order: params["order"] = self._order_param(order) if page is not None: params["page"] = str(page) if page_size is not None: params["page_size"] = str(page_size) if attributes: params["fields"] = ",".join(str(attr) for attr in attributes) params["format"] = "json_lines" response = self.store.cube_request("facts", self.cube.name, params, is_lines=True) return Facts(response, attributes) def _order_param(self, order): """Prepare an order string in form: ``attribute:direction``""" string = ",".join("%s:%s" % (o[0], o[1]) for o in order) return string def fact(self, key): raise NotImplementedError <file_sep>+++++++++++++ Configuration +++++++++++++ Cubes workspace configuration is stored in a ``.ini`` file with sections: * ``[workspace]`` – Cubes workspace configuration * ``[server]`` - server related configuration, such as host, port * ``[models]`` - list of models to be loaded * ``[datastore]`` – default datastore configuration * ``[translations]`` - model translation files, option keys in this section are locale names and values are paths to model translation files. See :doc:`localization` for more information. * ``[model]`` (depreciated) - model and cube configuration .. note:: The configuration has changed. Since Cubes supports multiple data stores, their type (backend) is specifien in the datastore configuration as ``type`` property, for example ``type=sql``. Quick Start =========== Simple configuration might look like this:: [workspace] model: model.json [datastore] type: sql url: postgresql://localhost/database Workspace ========= * ``stores`` – path to a file containing store descriptions – every section is a store with same name as the section * ``models_path`` – path to a directory containing models. If this is set to non-empty value, then all model paths specified in ``[models]`` are prefixed with this path * ``log`` - path to a log file * ``log_level`` - level of log details, from least to most: ``error``, ``warn``, ``info``, ``debug`` * ``timezone`` - name of default time zone. Used in date and time operations, such as :ref:`named relative time <named_relative_time>`_. * ``first_weekday`` – name of first day of the week. It can also be a number where 0 is Monday, 6 is Sunday * ``authorization`` – authorization method to be used Models ====== Section ``[models]`` contains list of models. The property names are model identifiers within the configuration (see ``[translations]`` for example) and the values are paths to model files. Example:: [models] main: model.json mixpanel: mixpanel.json If root ``models_path`` is specified in ``[workspace]`` then the relative model paths are combined with the root. Example:: [workspace] models_path: /dwh/cubes/models [models] main: model.json events: events.json The models are loaded from ``/dwh/cubes/models/model.json`` and ``/dwh/cubes/models/events.json``. Server ====== * ``json_record_limit`` - number of rows to limit when generating JSON output with iterable objects, such as facts. Default is 1000. It is recommended to use alternate response format, such as CSV, to get more records. * ``modules`` - space separated list of modules to be loaded (only used if run by the ``slicer`` command) * ``prettyprint`` - default value of ``prettyprint`` parameter. Set to ``true`` for demonstration purposes. * ``host`` - host where the server runs, defaults to ``localhost`` * ``port`` - port on which the server listens, defaults to ``5000`` * ``authentication`` – authentication method (see below for more information) Model ===== .. note:: This section is depreciated. Use `model` in ``[workspace]`` for single model file or ``[models]`` for multiple models. * ``path`` - path to model .json file * ``locales`` - comma separated list of locales the model is provided in. Currently this variable is optional and it is used only by experimental sphinx search backend. Data stores =========== There might be one or more datastores configured. The section ``[datastore]`` of the ``cubes.ini`` file describes the default store. Multiple stores are configured in a separate ``stores.ini`` file. The path to the stores configuration file might be specified in a variable ``stores`` of the ``[workspace]`` section The store configuration has to have at least one property: ``type``. Rest of the properties are handled by the actual data store. SQL store --------- Example SQL store:: [datastore] type: sql url: postgresql://localhost/data schema: cubes For more information and configuration options see :doc:`backends/sql`. Example ======= Example configuration file:: [workspace] model: ~/models/contracts_model.json [server] reload: yes log: /var/log/cubes.log log_level: info [datastore] type: sql url: postgresql://localhost/data schema: cubes Authentication and Authorization ================================ Cubes provides mechanisms for authentication at the server side and authorization at the workspace side. Configure authorization: .. code-block:: ini [workspace] authorization: simple [authorization] rights_file: /path/to/access_rights.json Built-in authorization methods: * ``none`` – no authorization * ``simple`` – uses a JSON file with per-user access rights Configure authentication: .. code-block:: ini [server] authentication: parameter [authentication] # additional authentication parameters Built-in server authentication methods: * ``none`` – no authentication * ``http_basic_proxy`` – HTTP basic authentication. Will pass the `username` to the authorizer * ``pass_parameter`` – authentication withot verification, just a way of passing an URL parameter to the authorizer. Default parameter name is ``api_key`` .. note:: When you have authorization method specified and is based on an users's indentity, then you have to specify the authentication method in the server. Otherwise the authorizer will not receive any identity and might refuse any access. <file_sep>###################### Cubes - OLAP Framework ###################### Cubes is a light-weight Python framework and set of tools for development of reporting and analytical applications, Online Analytical Processing (OLAP), multidimensional analysis and browsing of aggregated data. It is part of `Data Brewery`_. .. _Data Brewery: http://databrewery.org/ Getting Started --------------- .. toctree:: :maxdepth: 2 introduction install tutorial Data Modeling ------------- .. toctree:: :maxdepth: 2 model schemas localization Aggregation, Slicing and Dicing ------------------------------- .. toctree:: :maxdepth: 2 slicing_dicing formatters Analytical Workspace -------------------- .. toctree:: :maxdepth: 2 workspace configuration Slicer Server and Tool ---------------------- .. toctree:: :maxdepth: 2 server slicer Backends -------- .. toctree:: :maxdepth: 2 backends/index Recipes ------- .. toctree:: :maxdepth: 2 recipes/index Extension Development --------------------- .. toctree:: :maxdepth: 2 extensions/index Developer's Reference --------------------- .. toctree:: :maxdepth: 2 reference/index Release Notes ------------- .. toctree:: :maxdepth: 2 releases/index Contact and Getting Help ======================== If you have questions, problems or suggestions, you can send a message to `Google group`_ or `write to the author`_ (<NAME>). Report bugs in `github issues`_ tracking .. _github issues: https://github.com/Stiivi/cubes/issues .. _Google group: http://groups.google.com/group/cubes-discuss .. _write to the author: <EMAIL> There is an IRC channel ``#databrewery`` on server ``irc.freenode.net``. License ------- Cubes is licensed under MIT license with small addition:: Copyright (c) 2011-2012 <NAME>, see AUTHORS for more details Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. If your version of the Software supports interaction with it remotely through a computer network, the above copyright notice and this permission notice shall be accessible to all users. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Simply said, that if you use it as part of software as a service (SaaS) you have to provide the copyright notice in an about, legal info, credits or some similar kind of page or info box. Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` <file_sep>******* Recipes ******* How-to guides with code snippets for various use-cases. .. toctree:: :maxdepth: 2 flask_integration opendata <file_sep>Cubes Tutorial 1 - Getting started ================================== In this tutorial you are going to learn how to start with cubes. The example shows: * how to build a model programatically * how to create a model with flat dimensions * how to aggregate whole cube * how to drill-down and aggregate through a dimension The example data used are [IBRD Balance Sheet](https://raw.github.com/Stiivi/cubes/master/tutorial/data/IBRD_Balance_Sheet__FY2010.csv) taken from [The World Bank](https://finances.worldbank.org/Accounting-and-Control/IBRD-Balance-Sheet-FY2010/e8yz-96c6) Create a tutorial directory and download the file: <pre> curl -O https://raw.github.com/Stiivi/cubes/master/tutorial/data/IBRD_Balance_Sheet__FY2010.csv </pre> Create a ``tutorial_01.py``: <pre class="prettyprint"> import sqlalchemy import cubes import cubes.tutorial.sql as tutorial </pre> Cubes package contains tutorial helper methods. It is advised not to use them in production, they are provided just to simplify learner's life. Prepare the data using the tutorial helper methods: <pre class="prettyprint"> engine = sqlalchemy.create_engine('sqlite:///:memory:') tutorial.create_table_from_csv(engine, "IBRD_Balance_Sheet__FY2010.csv", table_name="irbd_balance", fields=[ ("category", "string"), ("line_item", "string"), ("year", "integer"), ("amount", "integer")], create_id=True ) </pre> Now, create a model: <pre class="prettyprint"> model = cubes.Model() </pre> Add dimensions to the model. Reason for having dimensions in a model is, that they might be shared by multiple cubes. <pre class="prettyprint"> model.add_dimension(cubes.Dimension("category")) model.add_dimension(cubes.Dimension("line_item")) model.add_dimension(cubes.Dimension("year")) </pre> Define a cube and specify already defined dimensions: <pre class="prettyprint"> cube = cubes.Cube(name="irbd_balance", model=model, dimensions=["category", "line_item", "year"], measures=["amount"] ) </pre> Create a browser and get a cell representing the whole cube (all data): <pre class="prettyprint"> browser = cubes.backends.sql.SQLBrowser(cube, engine.connect(), view_name = "irbd_balance") cell = browser.full_cube() </pre> Compute the aggregate. Measure fields of aggregation result have aggregation suffix, currenlty only ``_sum``. Also a total record count within the cell is included as ``record_count``. <pre class="prettyprint"> result = browser.aggregate(cell) print "Record count: %d" % result.summary["record_count"] print "Total amount: %d" % result.summary["amount_sum"] </pre> Now try some drill-down by category: <pre class="prettyprint"> print "Drill Down by Category" result = browser.aggregate(cell, drilldown=["category"]) print "%-20s%10s%10s" % ("Category", "Count", "Total") for record in result.drilldown: print "%-20s%10d%10d" % (record["category"], record["record_count"], record["amount_sum"]) </pre> Drill-dow by year: <pre class="prettyprint"> print "Drill Down by Year:" result = browser.aggregate(cell, drilldown=["year"]) print "%-20s%10s%10s" % ("Year", "Count", "Total") for record in result.drilldown: print "%-20s%10d%10d" % (record["year"], record["record_count"], record["amount_sum"]) </pre> All tutorials with example data and models will be stored together with [cubes sources](https://github.com/Stiivi/cubes) under the ``tutorial/`` directory. Next: Model files and hierarchies. If you have any questions, comments or suggestions, do not hesitate to ask.<file_sep># -*- coding=utf -*- from .common import decamelize, to_identifier, coalesce_options from collections import defaultdict _default_modules = { "stores": { "sql":"cubes.backends.sql.store", "mongo":"cubes.backends.mongo", "mongo2":"cubes.backends.mongo2", "mixpanel":"cubes.backends.mixpanel.store", "slicer":"cubes.backends.slicer.store", }, "browsers": { "snowflake":"cubes.backends.sql.browser", "snapshot": "cubes.backends.sql.browser", "mixpanel":"cubes.backends.mixpanel.browser", "slicer":"cubes.backends.slicer.browser", }, "model_providers": { "mixpanel":"cubes.backends.mixpanel.store", "slicer":"cubes.backends.slicer.store", }, "request_log_handlers": { "sql":"cubes.backends.sql.logging", }, "authorizers": { } } class Namespace(dict): def __init__(self, name, objects=None, root_class=None, suffix=None, option_checking=False): self.name = name self.root_class = root_class self.suffix = suffix self.option_checking = option_checking if objects: self.update(objects) def discover_objects(self): if self.root_class: objects = collect_subclasses(self.root_class, self.suffix) if self.option_checking: # Convert classes to factories for name, class_ in objects.items(): objects[name] = _FactoryOptionChecker(class_) self.update(objects) def __getattr__(self, value): return self.__getitem__(value) def __getitem__(self, value): try: return super(Namespace, self).__getitem__(value) except KeyError: # Lazily load module that might contain the object modules = _default_modules.get(self.name) if modules and value in modules: _load_module(modules[value]) self.discover_objects() # Retry after loading return super(Namespace, self).__getitem__(value) class _FactoryOptionChecker(object): def __init__(self, class_, options=None): """Creates a factory wrapper for `class_`. Calling the object createds an instance of `class_` and configures it according to `options`. If not options are specified, then the class variable `__options__` is used. The options is a list of dictionaries with keys: * `name` – option name * `type` – option data type * `description` – description (optional) * `label` – human readable label (optional) * `values` – valid values for the option.""" if not options and hasattr(class_, "__options__"): options = class_.__options__ self.options = {} self.option_types = {} for option in options or []: name = option["name"] self.options[name] = option self.option_types[name] = option.get("type", "string") self.class_ = class_ def __call__(self, *args, **kwargs): # TODO: move this to a metaclass options = dict(kwargs) options = coalesce_options(dict(kwargs), self.option_types) return self.class_(*args, **options) _namespaces = {} def get_namespace(name): """Gets a namespace `name` dictionary.""" return _namespaces.get(name) def initialize_namespace(name, objects=None, root_class=None, suffix=None, option_checking=False): """Initializes the namespace `name` with `objects` dictionary and subclasses of `root_class` where the class name is decamelized, changet do an identifier and with `suffix` removed.""" ns = Namespace(name, objects, root_class, suffix, option_checking=option_checking) ns.discover_objects() _namespaces[name] = ns return ns def collect_subclasses(parent, suffix=None): """Collect all subclasses of `parent` and return a dictionary where keys are object names. Obect name is decamelized class names transformed to identifiers and with `suffix` removed. If a class has class attribute `__identifier__` then the attribute is used as name.""" subclasses = {} for c in subclass_iterator(parent): if hasattr(c, "__identifier__"): name = getattr(c, "__identifier__") else: name = to_identifier(decamelize(c.__name__)) if suffix and name.endswith(suffix): name = name[:-len(suffix)] subclasses[name] = c return subclasses def subclass_iterator(cls, _seen=None): """ Generator over all subclasses of a given class, in depth first order. Source: http://code.activestate.com/recipes/576949-find-all-subclasses-of-a-given-class/ """ if not isinstance(cls, type): raise TypeError('_subclass_iterator must be called with ' 'new-style classes, not %.100r' % cls) _seen = _seen or set() try: subs = cls.__subclasses__() except TypeError: # fails only when cls is type subs = cls.__subclasses__(cls) for sub in subs: if sub not in _seen: _seen.add(sub) yield sub for sub in subclass_iterator(sub, _seen): yield sub def _load_module(modulepath): mod = __import__(modulepath) path = [] for token in modulepath.split(".")[1:]: path.append(token) mod = getattr(mod, token) return mod <file_sep>****************** Schemas and Models ****************** This section contains example database schemas and their respective models with description. The examples are for the SQL backend. Please refer to the backend documentation of your choice for more information about non-SQL setups. .. seealso:: :doc:`model` Logical model description. :doc:`backends/index` Backend references. :doc:`reference/model` Developer's reference of model classes and fucntions. Basic Schemas ============= Simple Star Schema ------------------ *Synopsis: Fact table has the same name as the cube, dimension tables have same names as dimensions.* Fact table is called `sales`, has one measure `amount` and two dimensions: `store` and `product`. Each dimension has two attributes. .. image:: images/schemas/schema-default.png :align: center .. code-block:: javascript "cubes": [ { "name": "sales", "dimensions": ["product", "store"], "joins": [ {"master":"product_id", "detail":"product.id"}, {"master":"store_id", "detail":"store.id"} ] } ], "dimensions": [ { "name": "product", "attributes": ["code", "name"] }, { "name": "store", "attributes": ["code", "address"] } ] Simple Dimension ---------------- *Synopsis: Dimension is represented only by one attribute, has no details, neither hierarchy.* Similar schema as `Simple Star Schema`_ Note the dimension `year` which is represented just by one numeroc attribute. It is important that no attributes are specified for the dimension. There dimension will be referenced just by its name and dimension label is going to be used as attribute label as well. .. image:: images/schemas/schema-flat_dimension.png :align: center .. code-block:: javascript "cubes": [ { "name": "sales", "dimensions": ["product", "store", "year"], "joins": [ {"master":"product_id", "detail":"product.id"}, {"master":"store_id", "detail":"store.id"} ] } ], "dimensions": [ { "name": "product", "attributes": ["code", "name"] }, { "name": "store", "attributes": ["code", "address"] } { "name": "year" } ] Table Prefix ------------ *Synopsis: dimension tables share a common prefix, fact tables share common prefix.* .. image:: images/schemas/schema-prefix.png :align: center In our example the dimension tables have prefix ``dim_`` as in ``dim_product`` or ``dim_store`` and facts have prefix ``fact_`` as in ``fact_sales``. There is no need to change the model, only the data store configuration. In Python code we specify the prefix during the data store registration in :meth:`cubes.Workspace.register_store`: .. code-block:: python workspace = Workspace() workspace.register_store("default", "sql", url=DATABASE_URL, dimension_prefix="dim_", fact_prefix="fact_") When using the :doc:`server` we specify the prefixes in the ``[datastore]`` section of the `slicer.ini` configuration file: .. code-block:: ini [datastore] ... dimension_prefix="dim_" fact_prefix="fact_" Not Default Database Schema --------------------------- *Synopsis: all tables are stored in one common schema that is other than default database schema.* .. image:: images/schemas/schema-common_db_schema.png :align: center To specify database schema (in our example ``sales_datamart``) in Python pass it in the `schema` argument of :meth:`cubes.Workspace.register_store`: .. code-block:: python workspace = Workspace() workspace.register_store("default", "sql", url=DATABASE_URL, schema="sales_datamart") For the :doc:`server` the schema is specifiedn in the ``[datastore]`` section of the `slicer.ini` configuration file: .. code-block:: ini [datastore] ... schema="sales_datamart" Separate Dimension Schema ------------------------- *Synopsis: dimension tables share one database schema and fact tables share another database schema* .. image:: images/schemas/schema-different_db_schemas.png :align: center Dimensions can be stored in a different database schema than the fact table schema. To specify database schema of dimensions (in our example ``dimensions``) in Python pass it in the `dimension_schema` argument of :meth:`cubes.Workspace.register_store`: .. code-block:: python workspace = Workspace() workspace.register_store("default", "sql", url=DATABASE_URL, schema="facts", dimension_schema="dimensions") For the :doc:`server` the dimension schema is specifiedn in the ``[datastore]`` section of the `slicer.ini` configuration file: .. code-block:: ini [datastore] ... schema="facts" dimension_schema="dimensions" Mappings ======== Following patterns use the :ref:`explicit_mapping`. Basic Attribute Mapping ----------------------- *Synopsis: table column has different name than a dimension attribute or a measure.* .. image:: images/schemas/schema-mapping.png :align: center In our example we have a flat dimension called `year`, but the physical table column is “sales_year”. In addition we have a measure `amount` however respective physical column is named `total_amount`. We define the `mappings` within a cube: .. code-block:: javascript "cubes": [ { "dimensions": [..., "year"], "measures": ["amount"], "mappings": { "year":"sales_year", "amount":"total_amount"] } } ], "dimensions": [ ... { "name": "year" } ] Shared Dimension Table ---------------------- *Synopsis: multiple dimensions share the same dimension table* .. image:: images/schemas/schema-alias.png :align: center Clients and suppliers might share one table with all organisations and companies. We have to specify a table alias in the `joins` part of the cube definition. The table aliases should follow the same naming pattern as the other tables – that is, if we are using dimension prefix, then the alias should include the prefix as well: If the alias follows dimension naming convention, as in the example, then no mapping is required. .. code-block:: javascript "cubes": [ { "name": "sales" "dimensions": ["supplier", "client"], "measures": ["amount"], "joins": [ { "master":"supplier_id", "detail":"dim_organisation.id", "alias":"dim_supplier" }, { "master":"client_id", "detail":"dim_organisation.id", "alias":"dim_client" } ] } ], "dimensions": [ { "name": "supplier", "attributes": ["id", "name", "address"] }, { "name": "client", "attributes": ["id", "name", "address" } ] Hierarchies =========== Following patterns show how to specify one or multiple dimension hierarchies. Simple Hierarchy ---------------- *Synopsis: Dimension has more than one level.* .. image:: images/schemas/schema-hierarchy1.png :align: center `Product` dimension has two levels: `product category` and `product`. The `product category` level is represented by two attributes ``category_code`` (as key) and ``category``. The `product` has also two attributes: ``product_code`` and ``name``. .. code-block:: javascript "cubes": [ { "dimensions": ["product", ...], "measures": ["amount"], "joins": [ {"master":"product_id", "detail":"product.id"} ] } ], "dimensions": [ { "name": "product", "levels": [ { "name":"category", "attributes": ["category_code", "category"] }, { "name":"product", "attributes": ["code", "name"] } ] } ] Multiple Hierarchies -------------------- *Synopsis: Dimension has multiple ways how to organise levels into hierarchies.* .. image:: images/schemas/schema-hierarchy2.png :align: center Dimensions such as `date` (depicted below) or `geography` might have multiple ways of organizing their attributes into a hierarchy. The date can be composed of `year-month-day` or `year-quarter-month-day`. To define multiple hierarchies, first define all possible levels. Then create list of hierarchies where you specify order of levels for that particular hierarchy. The code example below is in the “dimensions” section of the model: .. code-block:: javascript { "name":"date", "levels": [ { "name": "year", "attributes": ["year"] }, { "name": "quarter", "attributes": ["quarter"] }, { "name": "month", "attributes": ["month", "month_name"] }, { "name": "week", "attributes": ["week"] }, { "name": "weekday", "attributes": ["weekday"] }, { "name": "day", "attributes": ["day"] } ], "hierarchies": [ {"name": "ymd", "levels":["year", "month", "day"]}, {"name": "ym", "levels":["year", "month"]}, {"name": "yqmd", "levels":["year", "quarter", "month", "day"]}, {"name": "ywd", "levels":["year", "week", "weekday"]} ], "default_hierarchy_name": "ymd" } The ``default_hierarchy_name`` specifies which hierarchy will be used if not mentioned explicitly. User-oriented Metadata ====================== Model Labels ------------ *Synopsis: Labels for parts of model that are to be displayed to the user* .. image:: images/schemas/schema-labels.png :align: center Labels are used in report tables as column headings or as filter descriptions. Attribute (and column) names should be used only for report creation and despite being readable and understandable, they should not be presented to the user in the raw form. Labels can be specified for any model object (cube, dimension, level, attribute) with the `label` attribute: .. code-block:: javascript "cubes": [ { "name": "sales", "label": "Product Sales", "dimensions": ["product", ...] } ], "dimensions": [ { "name": "product", "label": "Product", "attributes": [ {"name": "code", "label": "Code"}, {"name": "name", "label": "Product"}, {"name": "price", "label": "Unit Price"}, ] } ] Key and Label Attribute ----------------------- *Synopsis: specify which attributes are going to be used for flitering (keys) and which are going to be displayed in the user interface (labels)* .. image:: images/schemas/schema-label_attributes.png :align: center .. code-block:: javascript "dimensions": [ { "name": "product", "levels": [ { "name": "product", "attributes": ["code", "name", "price"] "key": "code", "label_attribute": "name" } ] } ] Example use: .. code-block:: python result = browser.aggregate(drilldown=["product"]) for row in result.table_rows("product"): print "%s: %s" % (row.label, row.record["amount_sum"]) Localization ============ Localized Data -------------- *Synopsis: attributes might have values in multiple languages* .. image:: images/schemas/schema-localized_data.png :align: center Dimension attributes might have language-specific content. In cubes it can be achieved by providing one column per language (denormalized localization). The default column name should be the same as the localized attribute name with locale suffix, for example if the reported attribute is called `name` then the columns should be `name_en` for English localization and `name_hu` for Hungarian localization. .. code-block:: javascript "dimensions": [ { "name": "product", "label": "Product", "attributes": [ {"name": "code", "label": "Code"}, { "name": "name", "label": "Product", "locales": ["en", "fr", "es"] } ] } ] Use in Python: .. code-block:: python browser = workspace.browser(cube, locale="fr") The `browser` instance will now use only the French localization of attributes if available. In slicer server requests language can be specified by the ``lang=`` parameter in the URL. The dimension attributes are referred in the same way, regardless of localization. No change to reports is necessary when a new language is added. Notes: * only one locale per browser instance – either switch the locale or create another browser * when non-existing locale is requested, then the default (first in the list of the localized attribute) locale is used Localized Model Labels ---------------------- *Synopsis: Labels of model objects, such as dimensions, levels or attributes are localized.* .. image:: images/schemas/schema-localized_labels.png :align: center .. note:: Way how model is localized is not yet decided, the current implementation might be changed. We have a reporting site that uses two languages: English and Slovak. We want all labels to be available in both of the languages. Also we have a product name that has to be localized. First we define the model and specify that the default locale of the model is English (for this case). Note the `locale` property of the model, the `label` attributes and the locales of `product.name` attribute: .. code-block:: javascript { "locale": "en", "cubes": [ { "name": "sales", "label": "Product Sales", "dimensions": ["product"], "measures": [ {"name": "amount", "label": "Amount"} ] } ], "dimensions": [ { "name": "product", "label": "Product", "attributes": [ { "name": "code", "label": "Code" }, { "name": "name", "label": "Product", "locales": ["en", "sk"] }, { "name": "price", "label": "Unit Price" } ] } ] } Next we create a separate translation dictionary for the other locale, in our case it is Slovak or ``sk``. If we are translating only labels, no descriptions or any other information, we can use the simplified form: .. code-block:: javascript { "locale": "sk", "dimensions": { "product”: { "levels": { "product" : "Produkt" }, "attributes" : { "code": "Kód produktu", "name": "Produkt", "price": "Jednotková cena" } } }, "cubes": { "sales": { "measures": { "amount": "Suma" } } } } Full localization with detailed dictionaries looks like this: .. code-block:: javascript { "locale": "sk", "dimensions": { "product”: { "levels": { "product" : { "label" : "Produkt"} }, "attributes" : { "code": {"label": "Kód produktu"}, "name": {"label": "Produkt"}, "price": {"label": "Jednotková cena"} } } }, "cubes": { "sales": { "measures": { "amount": {"label": "Suma"} } } } } To create a model with translations: .. code-block:: python translations = {"sk": "model-sk.json"} model = create_model("model.json", translations) The model created this way will be in the default locale. To get localized version of the master model: .. code-block:: python localized_model = model.localize("sk") .. note:: The :meth:`cubes.Workspace.browser` method creates a browser with appropriate model localization, no explicit request for localization is needed. .. seealso:: :func:`cubes.load_model` Designated model loading function which accepts model translations. :meth:`cubes.Model.localize` Get localized version of the model. <file_sep># -*- coding=utf -*- from __future__ import absolute_import from logging import getLogger, Formatter, StreamHandler from .errors import * __all__ = [ "logger_name", "get_logger", "create_logger", ] logger_name = "cubes" logger = None def get_logger(): """Get brewery default logger""" global logger if logger: return logger else: return create_logger() def create_logger(level=None): """Create a default logger""" global logger logger = getLogger(logger_name) formatter = Formatter(fmt='%(asctime)s %(levelname)s %(message)s') handler = StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler) if level: logger.setLevel(level.upper()) return logger <file_sep>############# Slicer Server ############# It is possible to plug-in cubes from other slicer servers using the Slicer Server backend. .. figure:: cubes-slicer_backend.png :align: center :width: 500px Slicer backend .. note:: If the server has a JSON record limit set, then the backend will receive only limited number of facts. Store Configuration and Model ============================= Type is ``slicer`` * ``url`` – Slicer URL * ``authentication`` – authentication method of the source server (supported only ``none`` and ``pass_parameter``) * ``auth_identity`` – authentication identity (or API key) for ``pass_parameter`` authentication. Example:: [datastore] type: slicer url: http://slicer.databrewery.org/webshop-example For more than one slicer define one datastore per source Slicer server. Model ----- Slicer backend generates the model on-the-fly from the source server. You have to specify that the provider is ``slicer``: .. code-block:: javascript { "provider": "slicer" } For more than one slicer, create one file per source Slicer server and specify the data store: .. code-block:: javascript { "provider": "slicer", "datastore": "slicer_2" } Example ======= Create a ``model.json``: .. code-block:: json { "provider": "slicer" } Create a ``slicer.ini``: .. code-block:: ini [workspace] model: slicer_model.json [datastore] type: slicer url: http://slicer.databrewery.org/webshop-example [server] prettyprint: true Run the server: .. code-block:: sh slicer serve slicer.ini Get a list of cubes: .. codeb-block:: sh curl "http://localhost:5000/cubes" <file_sep># -*- coding=utf -*- import json try: from werkzeug.exceptions import HTTPException except: # No need to bind objects here to dependency-sink, as the user # will be notified when he tries to use Slicer or run_server about # the missing package HTTPException = object class ServerError(HTTPException): code = 500 error_type = "default" def __init__(self, message=None, exception=None, **details): super(ServerError, self).__init__() self.message = message self.exception = exception self.details = details self.help = None def get_body(self, environ): error = { "message": self.message, "type": self.__class__.error_type } if self.exception: error["reason"] = str(self.exception) if self.details: error.update(self.details) string = json.dumps({"error": error}, indent=4) return string def get_headers(self, environ): """Get a list of headers.""" return [('Content-Type', 'application/json')] class RequestError(ServerError): error_type = "request" code = 400 class NotAuthorizedError(ServerError): code = 403 error_type = "not_authorized" class NotAuthenticatedError(ServerError): code = 401 error_type = "not_authenticated" def __init__(self, message=None, exception=None, realm=None, **details): super(NotAuthenticatedError, self).__init__(message, exception, **details) self.message = message self.exception = exception self.details = details self.help = None self.realm = realm or "Default" def get_headers(self, environ): """Get a list of headers.""" headers = super(NotAuthenticatedError, self).get_headers(environ) headers.append(('WWW-Authenticate', 'Basic realm="%s"' % self.realm)) return headers class NotFoundError(ServerError): code = 404 error_type = "not_found" def __init__(self, obj, objtype=None, message=None): super(NotFoundError, self).__init__(message) self.details = { "object": obj } if objtype: self.details["object_type"] = objtype if not message: self.message = "Object '%s' of type '%s' was not found" % (obj, objtype) else: self.message = message class AggregationError(ServerError): code = 400 <file_sep># -*- coding=utf -*- from ...model import * from ...browser import * from ...stores import Store from ...providers import ModelProvider from ...errors import * from ...logging import get_logger import json import urllib2 import urllib DEFAULT_SLICER_URL = "http://localhost:5000" class SlicerStore(Store): def __init__(self, url=None, authentication=None, auth_identity=None, auth_parameter=None, **options): url = url or DEFAULT_SLICER_URL self.url = url self.logger = get_logger() if authentication and authentication not in ["pass_parameter", "none"]: raise ConfigurationError("Unsupported authentication method '%s'" % authentication) self.authentication = authentication self.auth_identity = auth_identity self.auth_parameter = auth_parameter or "api_key" # TODO: cube prefix # TODO: model mappings as in mixpanel def request(self, action, params=None, is_lines=False): """ * `action` – server action (path) # `params` – request parameters """ params = dict(params) if params else {} if self.authentication == "pass_parameter": params[self.auth_parameter] = self.auth_identity params_str = urllib.urlencode(params) request_url = '%s/%s' % (self.url, action) if params_str: request_url += '?' + params_str self.logger.debug("slicer request: %s" % (request_url, )) response = urllib.urlopen(request_url) if response.getcode() == 404: raise MissingObjectError elif response.getcode() != 200: raise BackendError("Slicer request error (%s): %s" % (response.getcode(), response.read())) if is_lines: return _JSONLinesIterator(response) else: try: result = json.loads(response.read()) except: result = {} return result def cube_request(self, action, cube, params=None, is_lines=False): action = "cube/%s/%s" % (cube, action) return self.request(action, params, is_lines) class _JSONLinesIterator(object): def __init__(self, stream): self.stream = stream def __iter__(self): for line in self.stream: yield json.loads(line) class SlicerModelProvider(ModelProvider): def requires_store(self): return True def list_cubes(self): return self.store.request('cubes') def cube(self, name): try: cube_desc = self.store.cube_request("model", name) except MissingObjectError: raise NoSuchCubeError("Unknown cube '%s'" % name, name) # create_cube() expects dimensions to be a list of names and linked # later, the Slicer returns whole dimension descriptions dimensions = cube_desc.pop("dimensions") cube_desc['datastore'] = self.store_name cube = create_cube(cube_desc) for dim in dimensions: dim = create_dimension(dim) cube.add_dimension(dim) return cube def dimension(self, name): raise NoSuchDimensionError(name) <file_sep># -*- coding=utf -*- from .blueprint import slicer from flask import Flask import ConfigParser from .utils import * __all__ = ( "create_server", "run_server" ) # Server Instantiation and Running # ================================ def _read_config(config): if not config: return ConfigParser.SafeConfigParser() elif isinstance(config, basestring): try: path = config config = ConfigParser.SafeConfigParser() config.read(path) except Exception as e: raise Exception("Unable to load configuration: %s" % e) return config def create_server(config=None): """Returns a Flask server application. `config` is a path to a ``slicer.ini`` file with Cubes workspace and server configuration.""" config = read_server_config(config) app = Flask("slicer") app.register_blueprint(slicer, config=config) return app def run_server(config, debug=False): """Run OLAP server with configuration specified in `config`""" config = read_server_config(config) app = create_server(config) if config.has_option("server", "host"): host = config.get("server", "host") else: host = "localhost" if config.has_option("server", "port"): port = config.getint("server", "port") else: port = 5000 if config.has_option("server", "reload"): use_reloader = config.getboolean("server", "reload") else: use_reloader = False if config.has_option('server', 'processes'): processes = config.getint('server', 'processes') else: processes = 1 # TODO :replace this with [workspace]timezone in future calendar module if config.has_option('server', 'tz'): set_default_tz(pytz.timezone(config.get("server", "tz"))) app.run(host, port, debug=debug, processes=processes, use_reloader=use_reloader) <file_sep>Development Notes +++++++++++++++++ This chapter contains notes related to Cubes development, such as: * unresolved design decisions * suggestions * proposals for changes * explaination for certain design decisions I've included this document as part of documentation to get more feedback or to help understanding why certain things are done in certain way at the time being. Fact Table ========== Currently all models are required to specify fact table. This can be somehow discovered from model and model mapping. Or from database schema itself. <file_sep>******************************* HTTP WSGI OLAP Server Reference ******************************* .. module:: server :synopsis: HTTP WSGI Server Light-weight HTTP WSGI server based on the `Werkzeug`_ framework. For more information about using the server see :doc:`../server`. .. _Werkzeug: http://werkzeug.pocoo.org/ .. autofunction:: cubes.server.run_server .. autoclass:: cubes.server.Slicer <file_sep>####################### Cubes 1.0 release notes ####################### These release notes cover the new features and changes (some of them backward incompatible). Overview ======== The biggest new feature in cubes is the "pluggable" model. You are no longer limited to one one model, one type of data store (database) and one set of cubes. The new `Workspace` is now famework-level controller object that manages models (model sources), cubes and datastores. To the future more features will be added to the workspace. .. figure:: ../images/cubes-analytical-workspace-overview.png :align: center :width: 300px Analytical Workspace Overview New Workspace related objects: * model provider – creates model objects from a model source (might be a foreign API/service or custom database) * store – provides access and connection to cube's data For more information see the :doc:`Workspace <../workspace>` documentation. Other notable new features in Cubes 1.0 are: * Rewritten Slicer server in `Flask <http://flask.pocoo.org>`_ as a reusable `Blueprint <http://flask.pocoo.org/docs/blueprints/>`_. * New :doc:`server API <../server>`. * support for :ref:`outer joins <sql-outer-joins>` in the :doc:`SQL backend <../backends/sql>`. * Distinction between :ref:`measures and aggregates <measures-and-aggregates>` * Extensible :doc:`authorization and authentication <../auth>` Analytical Workspace -------------------- The old backend architecture was limiting. It allowed only one store to be used, the model had to be known before the server started, it was not possible to get the model from a remote source. For more details about the new workspace see the :doc:`../workpsace` documentation. Configuration ------------- The `slicer.ini` configuration has changed to reflect new features. The section ``[workspace]`` now contains global configuration of a cubes workspace session. The database connection has moved into ``[store]`` (or similar, if there are more). The database connection is specified either in the ``[store]`` section or in a separate ``stores.ini`` file where one section is one store, section name is store name (as referenced from cube models). If there is only one model, it can be specified either in the ``[workspace]`` section as ``model``. Multiple models are specified in the ``[models]`` section. To sum it up: * ``[server] backend`` is now ``[store] type`` for every store * ``[server] log`` and ``log_level`` has moved to ``[workspace]`` * ``[model]`` is now either ``model`` option of ``[workspace]`` or list of multiple models in the ``[models]`` section The old configuration: .. code-block:: ini [server] host: localhost port: 5000 reload: yes log_level: info [workspace] url: postgres://localhost/mydata" [model] path: grants_model.json Is now: .. code-block:: ini [workspace] log_level: info model: grants_model.json [server] host: localhost port: 5000 reload: yes [store] type: sql url: postgres://localhost/mydata Check your configuration files. .. seealso:: :doc:`../configuration` Server ------ Slicer server is now a `Flask <http://flask.pocoo.org>`_ application and a reusable `Blueprint <http://flask.pocoo.org/docs/blueprints/>`_. It is possible to include the Slicer in your application at an end-point of your choice. For more information, see the :doc:`recipe <../recipes/flask_integration>`. Other server changes: * do not expose internal exceptions, only user exceptions * added simple authentication methods: HTTP Basic (behind a proxy) and parameter-based identity. Both are permissive and serve just for passing an identity to the authorizer. HTTP Server API --------------- Server end-points have changed. New end-points: * ``/version`` * ``/info`` * ``/cubes`` * ``/cube/<cube>/model`` * ``/cube/<cube>/aggregate`` * ``/cube/<cube>/facts`` * ``/cube/<cube>/fact`` * ``/cube/<cube>/dimension/<dimension>`` * ``/cube/<cube>/cell`` * ``/cube/<cube>/report`` Removed end-points: * ``/model`` – without replacement doe to the new concepts of workspace. Alternative is to get list of basic cube info using ``/cubes``. * ``/model/cubes`` – without replacement, use ``/cubes`` * ``/model/cube/<cube>`` – use ``/cube/<cube>/model`` instead * ``/model/dimension/*`` – without replacement due to the new concepts of workspace * all top-level browser actions such as ``/aggregate`` – now the cube name has to be explicit Parameter changes: * ``/aggregate`` uses ``aggregates=``, does not accept ``measure=`` any more * ``/aggregate`` now accepts ``format=`` to generate CSV output * new parameter ``headers=`` for CSV output: with headers as attribute names, headers as attribute labels (human readable) or no headers at all * it is now possible to specify multiple drilldowns, separated by ``|`` in one ``drilldown=`` parameter Response changes: * ``/cubes`` (as alternative replacement for ``/model``) returns a list of basic cubes info: `name`, `label`, `description` and `category`. It does not return full cube description with dimensions. * ``/cube/<cube>/model`` has new keys: ``aggregates`` and ``features`` .. sealso:: :doc:`../server` Outer Joins ----------- Support for thee types of joins was added to the SQL backend: `match` (inner), `master` (left outer) and `detail` (right outer). The *outer joins* allows for example to use whole ``date`` dimension table and have "empty cells" for dates where there are no facts. When an right outer join (``detail`` method) is present, then aggregate values are coalesced to zero (based on the function either the values or the result is coalesced). For example: AVG coalesces values: ``AVG(COALESCE(c, 0))``, SUM coalesces result: ``COALESCE(SUM(c), 0)``. .. seealso:: :ref:`SQL Backend – Outer Joins Documentation<sql-outer-joins>` Statutils --------- Module with statistical aggregate functions such as simple moving average or weighted moving average. Provided functions: * ``wma`` – weighted moving average * ``sma`` – simple moving average * ``sms`` – simple moving sum * ``smstd`` – simple moving st. deviation * ``smrsd`` – simple moving relative st. deviation * ``smvar`` – simple moving variance The function are applied on the already computed aggregation results. Backends migh handle the function internally if they can. Browser ------- * invert, split Slicer ------ * added ``slicer model convert`` to convert between json ⇔ directory bundle Model ===== Model and modeling related changes are: * new concept of model providers (see details below) * measure aggregates (see details below) * cardinality of dimensions and dimension levels * dimension roles * attribute missing values * `format` property of a measure and aggregate Model Providers --------------- The models of cubes are now being created by the *model providers*. Model provider is an object that creates `Cubes` and `Dimension` instances from it's source. Built-in model provider is :class:`cubes.StaticModelProvider` which creates cubes objects from JSON files and dictionaries. .. seealso:: :doc:`../extensions/providers`, :doc:`../reference/providers` Measures and Aggregates ----------------------- Cubes now distinguishes between *measures* and *aggregates*. *measure* represents a numerical fact property, *aggregate* represents aggregated value (applied aggregate function on a property, or provided natively by the backend). This new approach of *aggregates* makes development of backends and cliends much easier. There is no need to construct and guess aggregate measures or splitting the names from the functions. Backends receive concrete objects with sufficient information to perform the aggregation (either by a function or fetch already computed value). Functionality additions and changes: * New model objects: :class:`cubes.Attribute` (for dimension or detail), :class:`cubes.Measure` and :class:`cubes.MeasureAggregate`. * New model creation/helper functions: :func:`cubes.create_measure_aggregate`, :func:`cubes.create_measure` * :func:`cubes.create_cube` is back * :meth:`cubes.Cube.aggregates_for_measure` – return all aggregates referring the measure * :meth:`cubes.Cube.get_aggregates` – get a list of aggregates according to names * :meth:`cubes.Measure.default_aggregates` – create a list of default aggregates for the measure * :func:`calculators_for_aggregates` in statutils – returns post-aggregation calculators * Added a cube metadata flag to control creation of default aggregates: `implicit_aggregates`. Default is ``True`` * Cube initialization has no creation of defaults – it should belong to the model provider or :func:`create_cube` function * If there is no function specified, we consider the aggregate to be specified in the mappings TODO: escaped characters, characters in cuts, ... record_count ------------ Implicit aggregate `record_count` is no longer provided for every cube. It has to be explicitly defined as an aggregate: .. code-block:: json "aggregates": [ { "name": "item_count", "label": "Total Items", "function": "count" } ] It can be named and labelled in any way. .. seealso:: :ref:`Measures and Aggregates Documentation <measures-and-aggregates>`, :doc:`../model` Backends ======== SQL Backend ----------- * New module ``functions`` with new AggregationFunction objects * Added get_aggregate_function() and available_aggregate_functions() * Renamed ``star`` module to ``browser`` * Updated the code to use the new aggregates instead of old measures. Affected parts of the code are now cleaner and more understandable * Moved calculated_aggregations_for_measure to library-level statutils module as calculators_for_aggregates * function dictionary is no longer used New Backends ------------ * `Mixpanel`: :doc:`../backends/mixpanel` * `Slicer`: :doc:`../backends/slicer` * `Mongo`: :doc:`../backends/mongo` Other Minor Changes =================== * Cell.contains_level(dim, level, hierarhy) – returns ``True`` when the cell contains level ``level`` of dimension ``dim`` * renamed `AggregationBrowser.values()` to :meth:`cubes.AggregationBrowser.members` * `AggregationResult.measures` changed to `AggregationResult.aggregates` (see :class:`AggregationResult`) * browser's `__init__` signature has changed to include the store * changed the exception hierarchy. Now has two branches: ``UserError`` and ``InternalError`` – the ``UserError`` can be returned to the client, the ``InternalError`` should remain privade on the server side. * ``to_dict()`` of model objects returns an ordered dictionary for nicer JSON output * New class :class:`cubes.Facts` that should be returned by :meth:`cubes.AggregationBrowser.facts` * :func:`cubes.cuts_from_string` has two new arguments `member_converters` and `role_member_converters` * New class :class:`cubes.Drilldown` to get more information about the drilldown <file_sep>############### Model Providers ############### Model providers create :class:`cubes.Cube` and :class:`cubes.Dimension` objects from a metadata or an external description. .. figure:: images/cubes-model_providers.png :align: center :width: 600px Context of Model Providers. To implement a custom model provider subclass the :class:`cubes.ModelProvider` class. It is required that the `__init__` method calls the super's `__init__` with the `metadata` argument. Required methods to be implemented: * `list_cubes()` – return a list of cubes that the provider provides. Return value should be a dictionary with keys: ``name``, ``label``, ``description`` and ``info``. * `cube(name)` – return a :class:`cubes.Cube` object * `dimension(name, dimensions)` – return a :class:`cubes.Dimension` object. `dimensions` is a dictionary of public dimensions that can be used as templates. If a template is missing the method should raise `TemplateRequired(template)` error. Optional: * `public_dimensions()` – list of provided dimension names that can be shared by cubes in other models or by other providers * `requires_store()` – return `True` in this method if the provider requires a data store (database connection, API credentials, ...). .. seealso:: :doc:`../reference/model`, :doc:`../reference/providers`, :class:`cubes.ModelProvider`, :class:`cubes.StaticModelProvider`, :func:`cubes.create_cube`, :func:`cubes.create_dimension` Cube ---- To provide a cube implement `cube(name)` method. The method should raise `NoSuchCubeError` when a cube is not provided by the provider. To set cube's dimension you can either set dimension's name in `linked_dimensions` or directly a `Dimension` object in `dimensions`. The rule is: * `linked_dimensions` – shared dimensions, might be defined in external model, might be even own dimension that is considered public * `dimensions` – private dimensions, dimensions with public name conflicts .. note:: It is recommended to use the `linked_dimensions` name list. The `dimensions` is considered an advanced feature. Example of a provider which provides just a simple cube with date dimension and a measure `amount` and two aggregates `amount_sum` and `record_count`. Knows three cubes: `activations`, `churn` and `sales`: .. code-block:: python from cubes import ModelProvider, create_cube class SimpleModelProvider(ModelProvider): def __init__(self, metadata=None): super(DatabaseModelProvider, self).__init__(metadata) self.known_cubes = ["activations", "churn", "sales"] def list_cubes(self): cubes = [] for name in self.known_cubes: info = {"name": name} cubes.append(info) return cubes def cube(self, name): if not name in self.known_cubes: raise NoSuchCubeError("Unknown cube '%s'" % name, name) metadata = { "name": name, "linked_dimensions": ["date"], "measures": ["amount"], "aggregats": [ {"name": "amount_sum", "measure": "amount", "function": "sum"}, {"name": "record_count", "function": "count"} ] } return create_cube(metadata) The above provider assumes that some other object providers the `date` dimension. Store ----- Some providers might require a database connection or an API credentials that might be shared by the data store containing the actual cube data. In this case the model provider should implement method `requires_store()` and return ``True``. The provider's `initialize_from_store()` will be called back at some point before first cube is retrieved. The provider will have `store` instance variable available with :class:`cubes.Store` object instance. Example: .. code-block:: python from cubes import ModelProvider, create_cube from sqlalchemy import sql import json class DatabaseModelProvider(ModelProvider): def requires_store(self): return True def initialize_from_store(self): self.table = self.store.table("cubes_metadata") self.engine = self.store.engine def cube(self, name): self.engine.execute(select) # Let's assume that we have a SQLalchemy table with a JSON string # with cube metadata and columns: name, metadata condition = self.table.c.name == name statement = sql.expression.select(self.table.c.metadata, from_obj=self.table, where=condition) result = list(self.engine.execute(statement)) if not result: raise NoSuchCubeError("Unknown cube '%s'" % name, name) cube = json.loads(result[0]) return create_cube(cube) <file_sep>################################# Cubes 0.6 to 0.10.2 Release Notes ################################# 0.10.2 ====== Summary: * many improvements in handling multiple hierarchies * more support of multiple hierarchies in the slicer server either as parameter or with syntax ``dimension@hierarchy``: - dimension values: ``GET /dimension/date?hierarchy=dqmy`` - cut: get first quarter of 2012 ``?cut=date@dqmy:2012,1`` - drill-down on hierarchy with week on implicit (next) level: ``?drilldown=date@ywd`` - drill-down on hierarchy with week with exlpicitly specified week level: ``?drilldown=date@ywd:week`` * order and order attribute can now be specified for a Level * optional safe column aliases (see docs for more info) for databases that have non-standard requirements for column labels even when quoted Thanks: * <NAME> (@jjmontesl) * <NAME> * <NAME> (@rquevedo) New Features ------------ * added `order` to Level object - can be ``asc``, ``desc`` or None for unspecified order (will be ignored) * added `order_attribute` to Level object - specifies attribute to be used for ordering according to `order`. If not specified, then first attribute is going to be used. * added hierarchy argument to `AggregationResult.table_rows()` * `str(cube)` returns cube name, useful in functions that can accept both cube name and cube object * added cross table formatter and its HTML variant * ``GET /dimension`` accepts hierarchy parameter * added `create_workspace_from_config()` to simplify workspace creation directly from slicer.ini file (this method might be slightly changed in the future) * `to_dict()` method of model objects now has a flag `create_label` which provides label attribute derived from the object's name, if label is missing * #95: Allow charset to be specified in Content-Type header SQL: * added option to SQL workspace/browser ``safe_labels`` to use safe column labels for databases that do not support characters like ``.`` in column names even when quoted (advanced feature, does not work with denormalization) * browser accepts include_cell_count and include_summary arguments to optionally disable/enable inclusion of respective results in the aggregation result object * added implicit ordering by levels to aggregate and dimension values methods (for list of facts it is not yet decided how this should work) * #97: partially implemented sort_key, available in `aggregate()` and `values()` methods Server: * added comma separator for ``order=`` parameter * reflected multiple search backend support in slicer server Other: * added vim syntax highlighting goodie Changes ------- * AggregationResult.cross_table is depreciated, use cross table formatter instead * `load_model()` loads and applies translations * slicer server uses new localization methods (removed localization code from slicer) * workspace context provides proper list of locales and new key 'translations' * added base class Workspace which backends should subclass; backends should use workspace.localized_model(locale) * `create_model()` accepts list of translations Fixes ----- * browser.set_locale() now correctly changes browser's locale * #97: Dimension values call cartesians when cutting by a different dimension * #99: Dimension "template" does not copy hierarchies 0.10.1 ====== Quick Summary: * multiple hierarchies: * Python: ``cut = PointCut("date", [2010,15], hierarchy='ywd')`` * Server: ``GET /aggregate?cut=date@ywd:2010,15`` * Server drilldown: ``GET /aggregate?drilldown=date@ywd:week`` * added experimental result formatters (API might change) * added experimental pre-aggregations New Features ------------ * added support for multiple hierarchies * added ``dimension_schema`` option to star browser – use this when you have all dimensions grouped in a separate schema than fact table * added `HierarchyError` - used for example when drilling down deeper than possible within that hierarchy * added result formatters: simple_html_table, simple_data_table, text_table * added create_formatter(formatter_type, options ...) * AggregationResult.levels is a new dictionary containing levels that the result was drilled down to. Keys are dimension names, values are levels. * AggregationResult.table_rows() output has a new variable ``is_base`` to denote whether the row is base or not in regard to table_rows dimension. * added ``create_server(config_path)`` to simplify wsgi script * added aggregates: avg, stddev and variance (works only in databases that support those aggregations, such as PostgreSQL) * added preliminary implemenation of pre-aggregation to sql worskspace: * `create_conformed_rollup()` * `create_conformed_rollups()` * `create_cube_aggregate()` Server: * multiple drilldowns can be specified in single argument: ``drilldown=date,product`` * there can be multiple ``cut`` arguments that will be appended into single cell * added requests: ``GET /cubes`` and ``GET /cube/NAME/dimensions`` Changes ------- * **Important:** Changed string representation of a set cut: now using semicolon ';' as a separator instead of a plus symbol '+' * aggregation browser subclasses should now fill result's ``levels`` variable with ``coalesced_drilldown()`` output for requested drill-down levels. * Moved coalesce_drilldown() from star browser to cubes.browser module to be reusable by other browsers. Method might be renamed in the future. * if there is only one level (default) in a dimension, it will have same label as the owning dimension * hierarchy definition errors now raise ModelError instead of generic exception Fixes ----- * order of joins is preserved * fixed ordering bug * fixed bug in generating conditions from range cuts * ``AggregationResult.table_rows`` now works when there is no point cut * get correct reference in ``table_rows`` – now works when simple denormalized table is used * raise model exception when a table is missing due to missing join * search in slicer updated for latest changes * fixed bug that prevented using cells with attributes in aliased joined tables 0.10 ==== Quick Summary ------------- * Dimension defition can have a "template". For example: { "name": "contract_date", "template": "date" } * added table_rows() and cross_table() * added simple_model(cube_name, dimension_names, measures) *Incompatibilities:* use ``create_model()`` instead of ``Model(**dict)``, if you were using just ``load_model()``, you are fine. New Features ------------ * To address issue #8 create_model(dict) was added as replacement for Model(dict). Model() from now on will expect correctly constructed model objects. ``create_model()`` will be able to handle various simplifications and defaults during the construction process. * added ``info`` attribute to all model objects. It can be used to store custom, application or front-end specific information * preliminary implementation of ``cross_table()`` (interface might be changed) * ``AggregationResult.table_rows()`` - new method that iterates through drill-down rows and returns a tuple with key, label, path, and rest of the fields. * dimension in model description can specify another template dimension – all properties from the template will be inherited in the new dimension. All dimension properties specified in the new dimension completely override the template specification * added `point_cut_for_dimension` * added `simple_model(cube_name, dimensions, measures)` – creates a single-cube model with flat dimensions from a list of dimension names and measures from a list of measure names. For example: ``model = simple_model("contracts", ["year","contractor", "type"], ["amount"])`` *Slicer Server:* * ``/cell`` – return cell details (replaces ``/details``) Changes ------- * creation of a model from dictionary through Model(dict) is depreciated, use `create_model(dict)` instead. All initialization code will be moved there. Depreciation warnings were added. Old functionality retained for the time being. (**important**) * Replaced `Attribute.full_name()` with `Attribute.ref()` * Removed `Dimension.attribute_reference()` as same can be achieved with dim(attr).ref() * `AggregationResult.drilldown` renamed to `AggregationResults.cells` Planned Changes: * `str(Attribute)` will return `ref()` instead of attribute name as it is more useful Fixes ----- * order of dimensions is now preserved in the Model 0.9.1 ===== **Summary**: Range cuts, denormalize with slicer tool, cells in ``/report`` query New Features ------------ * `cut_from_string()`: added parsing of range and set cuts from string; introduced requirement for key format: Keys should now have format "alphanumeric character or underscore" if they are going to be converted to strings (for example when using slicer HTTP server) * `cut_from_dict()`: create a cut (of appropriate class) from a dictionary description * `Dimension.attribute(name)`: get attribute instance from name * added exceptions: `CubesError`, `ModelInconsistencyError`, `NoSuchDimensionError`, `NoSuchAttributeError`, `ArgumentError`, `MappingError`, `WorkspaceError` and `BrowserError` *StarBrowser:* * implemented RangeCut conditions *Slicer Server:* * ``/report`` JSON now accepts ``cell`` with full cell description as dictionary, overrides URL parameters *Slicer tool:* * ``denormalize`` option for (bulk) denormalization of cubes (see the the slicer documentation for more information) Changes ------- * all ``/report`` JSON requests should now have queries wrapped in the key ``queries``. This was originally intended way of use, but was not correctly implemented. A descriptive error message is returned from the server if the key ``queries`` is not present. Despite being rather a bug-fix, it is listed here as it requires your attention for possible change of your code. * warn when no backend is specified during slicer context creation Fixes ----- * Better handling of missing optional packages, also fixes #57 (now works without slqalchemy and without werkzeug as expected) * see change above about ``/report`` and ``queries`` * push more errors as JSON responses to the requestor, instead of just failing with an exception Version 0.9 =========== Important Changes ----------------- Summary of most important changes that might affect your code: **Slicer**: Change all your slicer.ini configuration files to have ``[workspace]`` section instead of old ``[db]`` or ``[backend]``. Depreciation warning is issued, will work if not changed. **Model**: Change ``dimensions`` in ``model`` to be an array instead of a dictionary. Same with ``cubes``. Old style: ``"dimensions" = { "date" = ... }`` new style: ``"dimensions" = [ { "name": "date", ... } ]``. Will work if not changed, just be prepared. **Python**: Use Dimension.hierarchy() instead of Dimension.default_hierarchy. New Features ------------ * `slicer_context()` - new method that holds all relevant information from configuration. can be reused when creating tools that work in connected database environment * added `Hierarchy.all_attributes()` and `.key_attributes()` * `Cell.rollup_dim()` - rolls up single dimension to a specified level. this might later replace the Cell.rollup() method * `Cell.drilldown()` - drills down the cell * `create_workspace()` - new top-level method for creating a workspace by name of a backend and a configuration dictionary. Easier to create browsers (from possible browser pool) programmatically. The browser name might be full module name path or relative to the cubes.backends, for example ``sql.browser`` for default SQL denormalized browser. * `get_backend()` - get backend by name * AggregationBrowser.cell_details(): New method returning values of attributes representing the cell. Preliminary implementation, return value might change. * AggregationBrowser.cut_details(): New method returning values of attributes representing a single cut. Preliminary implementation, return value might change. * Dimension.validate() now checks whether there are duplicate attributes * Cube.validate() now checks whether there are duplicate measures or details SQL backend: * new StarBrowser implemented: * StarBrowser supports snowflakes or denormalization (optional) * for snowflake browsing no write permission is required (does not have to be denormalized) * new `DenormalizedMapper` for mapping logical model to denormalized view * new `SnowflakeMapper` for mapping logical model to a snowflake schema * `ddl_for_model()` - get schema DDL as string for model * join finder and attribute mapper are now just Mapper - class responsible for finding appropriate joins and doing logical-to-physical mappings * `coalesce_attribute()` - new method for coalescing multiple ways of describing a physical attribute (just attribute or table+schema+attribute) * dimension argument was removed from all methods working with attributes (the dimension is now required attribute property) * added `create_denormalized_view()` with options: materialize, create_index, keys_only Slicer: * slicer ddl - generate schema DDL from model * slicer test - test configuration and model against database and report list of issues, if any * Backend options are now in [workspace], removed configurability of custom backend section. Warning are issued when old section names [db] and [backend] are used * server responds to /details which is a result of AggregationBrowser.cell_details() Examples: * added simple Flask based web example - dimension aggregation browser Changes ------- * in Model: dimension and cube dictionary specification during model initialization is depreciated, list should be used (with explicitly mentioned attribute "name") -- **important** * **important**: Now all attribute references in the model (dimension attributes, measures, ...) are required to be instances of Attribute() and the attribute knows it's dimension * removed `hierarchy` argument from `Dimension.all_attributes()` and `Dimension.key_attributes()` * renamed builder to denormalizer * Dimension.default_hierarchy is now depreciated in favor of Dimension.hierarchy() which now accepts no arguments or argument None - returning default hierarchy in those two cases * metadata are now reused for each browser within one workspace - speed improvement. Fixes ----- * Slicer version should be same version as Cubes: Original intention was to have separate server, therefore it had its own versioning. Now there is no reason for separate version, moreover it can introduce confusion. * Proper use of database schema in the Mapper Version 0.8 =========== New Features ------------ * Started writing StarBrowser - another SQL aggregation browser with different approach (see code/docs) Slicer Server: * added configuration option ``modules`` under ``[server]`` to load additional modules * added ability to specify backend module * backend configuration is in [backend] by default, for SQL it stays in [db] * added server config option for default ``prettyprint`` value (useful for demontration purposes) Documentation: * Changed license to MIT + small addition. Please refer to the LICENSE file. * Updated documentation - added missing parts, made reference more readable, moved class and function reference docs from descriptive part to reference (API) part. * added backend documentation * Added "Hello World!" example Changed Features ---------------- * removed default SQL backend from the server * moved worskpace creation into the backend module Fixes ----- * Fixed create_view to handle not materialized properly (thanks to deytao) * Slicer tool header now contains #!/usr/bin/env python Version 0.7.1 ============= Added tutorials in tutorials/ with models in tutorials/models/ and data in tutorials/data/: * Tutorial 1: * how to build a model programatically * how to create a model with flat dimensions * how to aggregate whole cube * how to drill-down and aggregate through a dimension * Tutorial 2: * how to create and use a model file * mappings * Tutorial 3: * how hierarhies work * drill-down through a hierarchy * Tutorial 4 (not blogged about it yet): * how to launch slicer server New Features ------------ * New method: `Dimension.attribute_reference`: returns full reference to an attribute * str(cut) will now return constructed string representation of a cut as it can be used by Slicer Slicer server: * added /locales to slicer * added locales key in /model request * added Access-Control-Allow-Origin for JS/jQuery Changes ------- * Allow dimensions in cube to be a list, not only a dictionary (internally it is ordered dictionary) * Allow cubes in model to be a list, not only a dictionary (internally it is ordered dictionary) Slicer server: * slicer does not require default cube to be specified: if no cube is in the request then try default from config or get first from model Fixes ----- * Slicer not serves right localization regardless of what localization was used first after server was launched (changed model localization copy to be deepcopy (as it should be)) * Fixes some remnants that used old Cell.foo based browsing to Browser.foo(cell, ...) only browsing * fixed model localization issues; once localized, original locale was not available * Do not try to add locale if not specified. Fixes #11: https://github.com/Stiivi/cubes/issues/11 Version 0.7 =========== WARNING: Minor backward API incompatibility - Cuboid renamed to Cell. Changes ------- * Class 'Cuboid' was renamed to more correct 'Cell'. 'Cuboid' is a part of cube with subset of dimensions. * all APIs with 'cuboid' in their name/arguments were renamed to use 'cell' instead * Changed initialization of model classes: Model, Cube, Dimension, Hierarchy, Level to be more "pythony": instead of using initialization dictionary, each attribute is listed as parameter, rest is handled from variable list of key word arguments * Improved handling of flat and detail-less dimensions (dimensions represented just by one attribute which is also a key) Model Initialization Defaults: * If no levels are specified during initialization, then dimension name is considered flat, with single attribute. * If no hierarchy is specified and levels are specified, then default hierarchy will be created from order of levels * If no levels are specified, then one level is created, with name ``default`` and dimension will be considered flat Note: This initialization defaults might be moved into a separate utility function/class that will populate incomplete model New features ------------ Slicer server: * changed to handle multiple cubes within model: you have to specify a cube for /aggregate, /facts,... in form: /cube/<cube_name>/<browser_action> * reflect change in configuration: removed ``view``, added ``view_prefix`` and ``view_suffix``, the cube view name will be constructed by concatenating ``view prefix`` + ``cube name`` + ``view suffix`` * in aggregate drill-down: explicit dimension can be specified with ``drilldown=dimension:level``, such as: ``date:month`` This change is considered final and therefore we can mark it is as API version 1. Version 0.6 =========== New features ------------ Cubes: * added 'details' to cube - attributes that might contain fact details which are not relevant to aggregation, but might be interesting when displaying facts * added ordering of facts in aggregation browser * SQL denormalizer can now add indexes to key columns, if requested * one detail table can be used more than once in SQL denomralizer (such as an organisation for both - receiver and donor), added key ````alias```` to ````joins```` in model description Slicer server: * added ``log`` a and ``log_level`` configuration options (under ``[server]``) * added ``format=`` parameter to ``/facts``, accepts ``json`` and ``csv`` * added ``fields=`` parameter to ``/facts`` - comma separated list of returned fields in CSV * share single sqlalchemy engine within server thread * limit number of facts returned in JSON (configurable by ``json_record_limit`` in ``[server]`` section) Experimental: (might change or be removed, use with caution) * added cubes searching frontend for separate cubes_search experimenal Sphinx backend (see https://bitbucket.org/Stiivi/cubes-search) Fixes ----- * fixed localization bug in fact(s) - now uses proper attribute name without locale suffix * fixed passing of pagination and ordering parameters from server to aggregation browser when requesting facts * fixed bug when using multiple conditions in SQL aggregator * make host/port optional separately <file_sep><table > <thead> <tr> <th></th> <th>Assets</th><th>Equity</th><th>Liabilities</th> </tr> </thead> <tbody> <tr> <th>2009</th> <td>(275420, 16)</td><td>(40037, 4)</td><td>(235383, 11)</td> </tr> <tr> <th>2010</th> <td>(283010, 16)</td><td>(37555, 4)</td><td>(245455, 11)</td> </tr> </tbody> </table> <file_sep>################################ Authorization and Authentication ################################ Cubes provides simple but extensible mechanism for authorization through an `Authorizer` and for authentication through an `Authenticator`. Authentication in cubes: determining and confirirming the user's identity, for example using a user name and password, some secret key or using an external service. Authorization: providing (or denying) access to cubes based on user's identity. .. figure:: cubes-slicer_authorization_and_authentication_overview.png :align: center :width: 500px Overview of authorization and authentication process in Slicer Authorization ============= The authorization principle in cubes is based on user's rights to a cube and restriction within a cube. If user has a "right to a cube" he can access the cube, the cube will be visible to him. Restriction within a cube is cell based: users might have access only to a certain cell within a cube. For example a shop manager might have access only to sales cube and dimension point equal to his own shop. Authorization is configured at the workspace level. In ``slicer.ini`` it is specified as: .. code-block:: ini [workspace] authorization: simple [authorization] rights_file: access_rights.json There is only one build-in authorizer called ``simple``. Simple Authorization -------------------- Simple authorization based on JSON files: `rights` and `roles`. The `rights` file contains a dictionary with keys as user identities (user names, API keys, ...) and values as right descriptions. The user right is described as: * ``roles`` – list of of user's role – user inherits the restrictions from the role * ``allowed_cubes`` – list of cubes that the user can access (and no other cubes) * ``denied_cubes`` – list of cubes that the user can not access (he can access the rest of cubes) * ``cube_restrictions`` – a dictionary where keys are cube names and values are lists of cuts The roles file has the same structure as the rights file, instead of users it defines inheritable roles. The roles can inherit properties from other roles. Example of roles file: .. code-block:: javascript { "retail": { "allowed_cubes": ["sales"] } } Rights file: .. code-block:: javascript { "martin": { "roles": ["retail"], } } Authentication ============== Authentication is handled at the server level. Built-in authentication methods: * ``none`` – no authentication * ``pass_parameter`` – permissive authentication that just passes an URL parameter to the authorizer. Default parameter name is ``api_key`` * ``http_basic_proxy`` – permissive authentication using HTTP Basic method. Assumes that the slicer is behind a proxy and that the password was already verified. Passes the user name to the authorizer. <file_sep>Flask Dimension Browser ======================= Simple browser of dimension hierarchy served with Flask web microframework. The application displays an aggregated table where user can drill down through dimension levels. Requirements ------------ Install flask:: pip install flask You also need jinja2 which should be installed together with flask as its dependency. Flask home page: http://flask.pocoo.org/ Quick start ----------- Prepare data:: python prepare_data.py Run the server:: python application.py And navigate your browser to http://127.0.0.1:5000/ Files ----- This directory contains following files: * model.json - logical model * data.csv - source data * prepare_data.py - script for preparing the data: load them into database and create a view * application.py - the web application (see commends in the file) * templates/report.html - HTML template that shows the simple table report (see comments in the file) * static/ - just static files, such as Twitter Bootstrap css so it can be pretty Examples for the new StarBrowser are with suffix `*_star` (compare the report templates with diff). Credits ------- The example data used are IBRD Balance Sheet taken from The World Bank: https://finances.worldbank.org/Accounting-and-Control/IBRD-Balance-Sheet-FY2010/e8yz-96c6
66d87613398ce808e6da40749d26064203921dd1
[ "HTML", "reStructuredText", "Markdown", "INI", "Python", "Text" ]
111
Python
Squarespace/cubes
cbde63ea61b66ed5f599068e2686f9dcfab39edf
58f70d3ecf4c2a9ec12b5e159f0bbf29fad49546
refs/heads/master
<file_sep> <?php //Ausgabe: Wilkommen echo "Wilkommen"; ?><file_sep><?php //Varaible a initalisierung $a="Am I alive?"; //Varaible b initalisierung $b='a'; //Variable b ruft variable a auf Ausgabe: Am I alive echo $$b; ?>
d92831ff8c5a044f6a080873404f53d72db10348
[ "PHP" ]
2
PHP
RobinWilliamAvci/Website2
38221e150c6378d413efd2af57458f97e6297110
ace863d7807339512a0db2f0f0065a53c2e304ec
refs/heads/master
<file_sep>from django.shortcuts import render # Create your views here. context = {'nome' :[ 'gabrieu', 'bruno', 'camila' ], 'vazio' : False 'teste' : 'teste' } return render(request, 'index.hmtl',context) def index(request): return render(request, 'index.html',{'minhavar' : '2'}) <file_sep> alert("carregado")
1f470e36cd4cebfba3aa8e946cdf5f6a1336ae12
[ "JavaScript", "Python" ]
2
Python
Gabrieul/python-sexta-feira
7e401f882cd8475a70608b3035beb8af7985e0c0
fec22d478452870f57fdced193bbf2c1efcbc4f8
refs/heads/master
<file_sep># gravatar HTML and JS to create gravatar hash for use with emails <file_sep>function hash() { var array = $('#email').val().trim().toLowerCase().split("\n"); for (var i = 0; i < array.length; i++) { var gravatar = $('<img>').attr({src: 'http://www.gravatar.com/avatar/' + CryptoJS.MD5(array[i]) + '?d=blank'}); $("#my_whatever").append(gravatar).append('<br />' + array[i] + '<br />' + i + '<br />' + gravatar.attr("src") + '<br><br />'); } return false; }
5807d598a00e4f5dc510d8e8254347d8a29992c3
[ "Markdown", "JavaScript" ]
2
Markdown
stuartsantos/gravatar
d3d280eec547e844e3d83e2dca8aba61966419bc
1a4c8dc6657522400e2d118a8431b910b7837091
refs/heads/main
<file_sep>package com.ladnyik; import java.io.IOException; import org.apache.pdfbox.text.PDFTextStripper; import org.apache.pdfbox.text.TextPosition; public class PageParser extends PDFTextStripper { public PageParser() throws IOException { super(); } @Override protected void processTextPosition(TextPosition text) { super.processTextPosition(text); if (text.getUnicode().trim().length() > 0) { /*System.out.println(String.format("%s %f %f %f", text.getUnicode(), text.getX(), text.getY(), text.getTextMatrix().getTranslateX() ));*/ //System.out.println(text.getTextMatrix()); } } }
4574213ee556d777ff89424be49f062152b0b56a
[ "Java" ]
1
Java
ladnyik/pdftest
bd5f39ada1548182e475170a09186c0bf1bc5b7d
4dc94372a18e1acbbc1080e30b925374dd57913d
refs/heads/master
<file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Makes this Transform, being rendered from an orthographic (2D) camera, appear to /// follow a target being rendered by another camera, in another space. /// /// This is perfect for use with most sprite-based GUI plugins to make a GUI element /// follow a 3D object. For example, a life bar can be setup to stay above the head of /// enemies. /// </summary> [AddComponentMenu("Path-o-logical/UnityConstraints/Constraint- World To 2D Camera")] public class WorldTo2DCameraConstraint : TransformConstraint { /// <summary> /// If false, the billboard will only rotate along the upAxis. /// </summary> public bool vertical = true; /// <summary> /// The camera used to render the target /// </summary> public Camera targetCamera; /// <summary> /// The camera the output object will be constrained to. /// </summary> public Camera orthoCamera; /// <summary> /// Offset the screen position. The z value is depth from the camera. /// </summary> public Vector3 offset; /// <summary> /// Determines when to apply the offset. /// WorldSpace - Applies the X and Y offset relative to the target object, in world- /// space, before converting to the ortheCamera's viewport-space. The /// offset values are used for world units /// ViewportSpace - Applies the X and Y offset in the ortheCamera's viewport-space. /// The offset values are in viewport space, which is normalized 0-1. /// </summary> public enum OFFSET_MODE { WorldSpace, ViewportSpace }; /// <summary> /// Determines when to apply the offset. In world-space or view-port space /// </summary> public OFFSET_MODE offsetMode = OFFSET_MODE.WorldSpace; /// <summary> /// Determines what happens when the target moves offscreen /// Constraint - Continues to track the target the same as it does on-screen /// Limit - Stops at the edge of the frame but continues to track the target /// DoNothing - Stops calculating the constraint /// </summary> public enum OFFSCREEN_MODE { Constrain, Limit, DoNothing }; /// <summary> /// Determines what happens when the target moves offscreen /// </summary> public OFFSCREEN_MODE offScreenMode = OFFSCREEN_MODE.Constrain; /// <summary> /// Offsets the behavior determined by offscreenMode. /// e.g. 0.1 to 0.9 would stop 0.1 from the edge of the screen on both sides /// </summary> public Vector2 offscreenThreasholdW = new Vector2(0, 1); /// <summary> /// Offsets the behavior determined by offscreenMode. /// e.g. 0.1 to 0.9 would stop 0.1 from the edge of the screen on both sides /// </summary> public Vector2 offscreenThreasholdH = new Vector2(0, 1); protected override void Awake() { base.Awake(); // Defaults... // This is done in the inspector as well, but needs to be in both places // so any application is covered. var cameras = FindObjectsOfType(typeof(Camera)) as Camera[]; // Default to the first ortho camera that is set to render this object foreach (Camera cam in cameras) { if (!cam.orthographic) continue; if ((cam.cullingMask & 1 << this.gameObject.layer) > 0) { this.orthoCamera = cam; break; } } // Default to the first camera that is set to render the target if (this.target != null) { foreach (Camera cam in cameras) { if ((cam.cullingMask & 1 << this.target.gameObject.layer) > 0) { this.targetCamera = cam; break; } } } } /// <summary> /// Runs each frame while the constraint is active /// </summary> protected override void OnConstraintUpdate() { // Ignore position work in the base class bool constrainPositionSetting = this.constrainPosition; this.constrainPosition = false; base.OnConstraintUpdate(); // Handles rotation and scale // Set back to the user setting this.constrainPosition = constrainPositionSetting; if (!this.constrainPosition) return; // Note: pos is reused and never destroyed this.pos = this.target.position; if (this.offsetMode == WorldTo2DCameraConstraint.OFFSET_MODE.WorldSpace) { this.pos.x += this.offset.x; this.pos.y += this.offset.y; } this.pos = this.targetCamera.WorldToViewportPoint(this.pos); if (this.offsetMode == WorldTo2DCameraConstraint.OFFSET_MODE.ViewportSpace) { this.pos.x += this.offset.x; this.pos.y += this.offset.y; } switch (this.offScreenMode) { case OFFSCREEN_MODE.DoNothing: // The pos is normalized so if it is between 0 and 1 in x and y, it is on screen. bool isOnScreen = ( this.pos.z > 0f && this.pos.x > this.offscreenThreasholdW.x && this.pos.x < this.offscreenThreasholdW.y && this.pos.y > this.offscreenThreasholdH.x && this.pos.y < this.offscreenThreasholdH.y ); if (!isOnScreen) return; // Quit else break; // It is on screen, so continue... case OFFSCREEN_MODE.Constrain: break; // Nothing modified. Continue... case OFFSCREEN_MODE.Limit: // pos is normalized so if it is between 0 and 1 in x and y, it is on screen. // Clamp will do nothing unless the target is offscreen this.pos.x = Mathf.Clamp ( this.pos.x, this.offscreenThreasholdW.x, this.offscreenThreasholdW.y ); this.pos.y = Mathf.Clamp ( this.pos.y, this.offscreenThreasholdH.x, this.offscreenThreasholdH.y ); break; } this.pos = this.orthoCamera.ViewportToWorldPoint(this.pos); this.pos.z = this.offset.z; // Output only if wanted, otherwise use the transform's current value if (!this.outputPosX) this.pos.x = this.position.x; if (!this.outputPosY) this.pos.y = this.position.y; if (!this.outputPosZ) this.pos.z = this.position.z; this.transform.position = pos; } } }<file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; public class LaserMachine : MonoBehaviour { public float hp, length, movSpeed, rotSpeed, waitTime, standTime; bool moved; Animator ani; void Start() { ani = transform.parent.GetComponent<Animator>(); StartCoroutine("Use"); } void OnEnabled() { StartCoroutine("Use"); } void HpManager(float num) { hp += num; if (hp <= 0) { transform.root.gameObject.SetActive(false); } } // Update is called once per frame void Update() { if (moved) { transform.root.Translate(movSpeed * Time.deltaTime * Vector2.right); transform.parent.Rotate(Vector3.forward * rotSpeed); } } IEnumerator Use() { moved = true; yield return new WaitForSeconds(waitTime); moved = false; ani.SetBool("On", true); yield return new WaitForSeconds(standTime); ani.SetBool("On", false); Destroy(transform.root.gameObject); //transform.root.gameObject.SetActive(false); } void OnTriggerEnter2D(Collider2D col) { if (col.CompareTag("Bullet_Boss")) { if (col.GetComponent<Bullet>() == null) col.GetComponent<PlacedBullet>().HpManager(-1000); else col.GetComponent<Bullet>().HpManager(-1000); HpManager(-1); } } } <file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; namespace PathologicalGames { /// <description> /// The base class for all constraints /// </description> [AddComponentMenu("")] // Hides from Unity4 Inspector menu public class ConstraintBaseClass : ConstraintFrameworkBaseClass { /// <summary> /// The object to constrain to /// </summary> public Transform _target; // For the inspector public Transform target { get { if (this.noTargetMode == UnityConstraints.NO_TARGET_OPTIONS.SetByScript) return this.internalTarget; return this._target; } set { this._target = value; } } // Used if the noTargetMode is set to SetByScript protected virtual Transform internalTarget { get { if (this._internalTarget != null) return this._internalTarget; // Create a GameObject to use as the target for the constraint // Setting the name is really only for debugging and unexpected errors var go = new GameObject(this.name + "_InternalConstraintTarget"); go.hideFlags = HideFlags.HideInHierarchy; // Hide from the hierarchy this._internalTarget = go.transform; // Make a sibling so this object and the reference exist in the same space // and reset this._internalTarget.position = this.transform.position; this._internalTarget.rotation = this.transform.rotation; this._internalTarget.localScale = this.transform.localScale; return this._internalTarget; } } protected Transform _internalTarget; /// <summary> /// Set the position this constraint will use if the noTargetMode is set to /// SetByScript. Usage is determined by script. /// </summary> public Vector3 position { get { return this.internalTarget.position; } set { this.internalTarget.position = value; } } /// <summary> /// Set the rotaion this constraint will use if the noTargetMode is set to /// SetByScript. Usage is determined by script. /// </summary> public Quaternion rotation { get { return this.internalTarget.rotation; } set { this.internalTarget.rotation = value; } } /// <summary> /// Set the localScale this constraint will use if the noTargetMode is set to /// SetByScript. Usage is determined by script. /// </summary> public Vector3 scale { get { return this.internalTarget.localScale; } set { this.internalTarget.localScale = value; } } /// <summary> /// Determines the behavior if no target is available /// </summary> // Public backing field for the inspector (The underscore will not show up) public UnityConstraints.NO_TARGET_OPTIONS _noTargetMode = UnityConstraints.NO_TARGET_OPTIONS.DoNothing; public UnityConstraints.NO_TARGET_OPTIONS noTargetMode { get { return this._noTargetMode; } set { this._noTargetMode = value; } } /// <summary> /// The current mode of the constraint. /// Setting the mode will start or stop the constraint coroutine, so if /// 'alignOnce' is chosen, the constraint will align once then go to sleep. /// </summary> // Public backing field for the inspector (The underscore will not show up) public UnityConstraints.MODE_OPTIONS _mode = UnityConstraints.MODE_OPTIONS.Constrain; public UnityConstraints.MODE_OPTIONS mode { get { return this._mode; } set { this._mode = value; this.InitConstraint(); } } protected Vector3 pos; // Reused for temp calculations protected Vector3 scl; // Reused for temp calculations protected Quaternion rot; // Reused for temp calculations // Clean-up private void OnDestroy() { // Destroy the internalTarget if one was created. if (this._internalTarget != null) { if (!Application.isPlaying) DestroyImmediate(this._internalTarget.gameObject); else Destroy(this._internalTarget.gameObject); } } /// <summary> /// Activate the constraint again if this object was disabled then enabled. /// Also runs immediatly after Awake() /// </summary> protected override sealed void InitConstraint() { switch (this.mode) { case UnityConstraints.MODE_OPTIONS.Align: this.OnOnce(); break; case UnityConstraints.MODE_OPTIONS.Constrain: this.StartCoroutine("Constrain"); break; } } /// <summary> /// Runs as long as the component is active. /// </summary> /// <returns></returns> protected override sealed IEnumerator Constrain() { // Start on the next frame incase some init still needs to occur. //yield return null; // While in Constrain mode handle this.target even if null. while (this.mode == UnityConstraints.MODE_OPTIONS.Constrain) { // If null, handle then continue to the next frame to test again. if (this.target == null) { // While the target is null, handle using the noTargetMode options switch (noTargetMode) { case UnityConstraints.NO_TARGET_OPTIONS.Error: var msg = string.Format("No target provided. \n{0} on {1}", this.GetType().Name, this.transform.name); Debug.LogError(msg); // Spams like Unity yield return null; continue; // All done this frame, try again next. case UnityConstraints.NO_TARGET_OPTIONS.DoNothing: yield return null; continue; // All done this frame, try again next. case UnityConstraints.NO_TARGET_OPTIONS.ReturnToDefault: this.NoTargetDefault(); yield return null; continue; // All done this frame, try again next. // Could omit. Kept for completeness //case UnityConstraints.NO_TARGET_OPTIONS.SetByScript: // // Handled as normal. Pass-through. // break; } } // Attempt the constraint... // Just incase the target is lost during the frame prior to this point. if (this.target == null) continue; // CONSTRAIN... this.OnConstraintUpdate(); yield return null; } } /// <summary> /// Runs when the noTarget mode is set to ReturnToDefault. /// Derrived constraints should just override and not run this /// </summary> protected virtual void NoTargetDefault() { // Use in child classes to do something when there is no target } /// <summary> /// Runs when the "once" option is chosen /// </summary> private void OnOnce() { this.OnConstraintUpdate(); } #if UNITY_EDITOR /// <summary> /// The base class has the ExecuteInEditMode attribute, so this is Update() called /// anytime something is changed in the editor. See: /// http://docs.unity3d.com/Documentation/ScriptReference/ExecuteInEditMode.html /// This function exists in the UNITY_EDITOR preprocessor directive so it /// won't be compiled for the final game. It includes an Application.isPlaying /// check to ensure it is bypassed when in the Unity Editor /// </summary> protected override void Update() { if (this.target == null) return; base.Update(); } #endif } }<file_sep>using UnityEngine; using System.Collections; using PathologicalGames; public class SpawnCtrl : MonoBehaviour { static SpawnCtrl instance; public static SpawnCtrl Instance { get { return instance; } } public static SpawnPool spawnPool = null; Transform tr; void Awake() { tr = GetComponent<Transform>(); } void Start() { if (spawnPool == null) { spawnPool = PoolManager.Pools["Test"]; } } public void SetTimeDespawn(float time) { StartCoroutine("Delay", time); } void OnSpawned() { tr.localScale = new Vector3(1, 1, 1); } public void SetActives() { spawnPool.Despawn(tr); tr.localScale = new Vector3(1, 1, 1); } void OnBecameInvisible() { if (gameObject.activeSelf) { spawnPool.Despawn(tr); tr.localScale = new Vector3(1, 1, 1); } } IEnumerator Delay(float time) { yield return new WaitForSeconds(time); SetActives(); } } <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using PathologicalGames; [CustomEditor(typeof(Targetable)), CanEditMultipleObjects] public class TargetableInspector : Editor { protected SerializedProperty debugLevel; protected SerializedProperty isTargetable; protected void OnEnable() { this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.isTargetable = this.serializedObject.FindProperty("_isTargetable"); } public override void OnInspectorGUI() { this.serializedObject.Update(); GUIContent content; EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; Object[] targetObjs = this.serializedObject.targetObjects; Targetable curEditTarget; EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Is Targetable", "Indicates whether this object is targetable. If the Targetable is being tracked " + "when this is set to false, it will be removed from all Areas. When set to " + "true, it will be added to any Perimieters it is inside of, if applicable." ); EditorGUILayout.PropertyField(this.isTargetable, content); // If changed, trigger the property setter for all objects being edited // Only trigger logic if the game is playing. Otherwise, the backing field setting is enough if (EditorGUI.EndChangeCheck() & Application.isPlaying) { string undo_message = targetObjs[0].GetType() + " isTargetable"; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (Targetable)targetObjs[i]; Undo.RecordObject(curEditTarget, undo_message); curEditTarget.isTargetable = this.isTargetable.boolValue; } } //GUILayout.Space(4); // Use if more controls are added content = new GUIContent ( "Debug Level", "Set it higher to see more verbose information." ); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// A TargetTracker that detects Targetables that are physically in contact with the /// Tracker GameObject's collider (Rigidbody.isTrigger = False);. To detect Targetables /// in range, use an AreaTargetTracker. This also works with Compound Colliders which Unity /// doesn't support for triggers. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Collision TargetTracker")] public class CollisionTargetTracker : TargetTracker { /// <summary> /// A list of sorted targets. The contents depend on numberOfTargets requested /// (-1 for all targets in the Area), and the sorting style used. /// </summary> public override TargetList targets { get { // Start with an empty list each pass. this._targets.Clear(); // If none are wanted, quit if (this.numberOfTargets == 0) return this._targets; // Filter for any targets that are no longer active before returning them var validTargets = new List<Target>(this.allTargets); foreach (Target target in this.allTargets) if (target.gameObject == null || !target.gameObject.activeInHierarchy) validTargets.Remove(target); // If no targets available, quit if (validTargets.Count == 0) return this._targets; // None == Area-of-effect, so get everything in range, otherwise, // Get the first item(s). Since everything is sorted based on the // sortingStyle, the first item(s) will always work if (this.numberOfTargets == -1) { this._targets.AddRange(validTargets); } else { // Grab the first item(s) int num = Mathf.Clamp(this.numberOfTargets, 0, validTargets.Count); for (int i = 0; i < num; i++) this._targets.Add(validTargets[i]); } if (this.onPostSortDelegates != null) this.onPostSortDelegates(this, this._targets); #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Normal) // All higher than normal { string msg = string.Format("returning targets: {0}", this._targets.ToString()); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif return _targets; } } protected TargetList allTargets = new TargetList(); public Collider coll; public Collider2D coll2D; protected override void Awake() { base.Awake(); this.coll = this.GetComponent<Collider>(); this.coll2D = this.GetComponent<Collider2D>(); if (this.coll == null && this.coll2D == null) { string msg = "No 2D or 3D collider or compound (child) collider found."; throw new MissingComponentException(msg); } // Make sure the collider used is not set to be a trigger. if ((this.coll != null && this.coll.isTrigger) || (this.coll2D != null && this.coll2D.isTrigger)) { throw new Exception ( "CollisionTargetTrackers do not work with trigger colliders." + "It is designed to work with Physics OnCollider events only." ); } } #region Events /// <summary> /// 3D Collider Event /// </summary> protected void OnCollisionEnter(Collision collisionInfo) { this.OnCollisionEnterAny(collisionInfo.gameObject); } /// <summary> /// 3D Collider Event /// </summary> protected void OnCollisionExit(Collision collisionInfo) { // Will only work if there is something to remove. Debug logging inside too. this.OnCollisionExitAny(collisionInfo.gameObject); } /// <summary> /// 2D Collider Event /// </summary> protected void OnCollisionEnter2D(Collision2D collisionInfo) { this.OnCollisionEnterAny(collisionInfo.gameObject); } /// <summary> /// 2D Collider Event /// </summary> protected void OnCollisionExit2D(Collision2D collisionInfo) { // Will only work if there is something to remove. Debug logging inside too. this.OnCollisionExitAny(collisionInfo.gameObject); } /// <summary> /// Handles 2D or 3D event the same way /// </summary> protected void OnCollisionEnterAny(GameObject otherGo) { if (!this.IsInLayerMask(otherGo)) return; // Get a target struct which will also cache information, such as the Transfrom, // GameObject and ITargetable component var target = new Target(otherGo.transform, this); if (target == Target.Null) return; // Ignore if isTargetable is false if (!target.targetable.isTargetable) return; // Give delegates the chance to ignore this Target. if (this.IsIgnoreTargetOnNewDetectedDelegatesExecute(target)) return; if (!this.allTargets.Contains(target)) this.allTargets.Add(target); // TODO: TRIGGER ON DETECTED #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = string.Format ( "OnCollisionEnter detected target: {0} | All Targets = [{1}]", target.targetable.name, this.allTargets.ToString() ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif } /// <summary> /// Handles 2D or 3D event the same way /// </summary> protected void OnCollisionExitAny(GameObject otherGO) { // Note: Iterating and comparing cached data should be the fastest way... var target = new Target(); foreach (Target currentTarget in this.allTargets) if (currentTarget.gameObject == otherGO) target = currentTarget; if (target == Target.Null) return; this.StartCoroutine(this.DelayRemove(target)); #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) // All higher than normal { string msg = string.Format ( "OnCollisionExit no longer tracking target: {0} | All Targets = [{1}]", target.targetable.name, this.allTargets.ToString() ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif } #endregion Events protected IEnumerator DelayRemove(Target target) { yield return null; if (this.allTargets.Contains(target)) this.allTargets.Remove(target); } #region protected Utilities /// <summary> /// Checks if a GameObject is in a LayerMask /// </summary> /// <param name="obj">GameObject to test</param> /// <param name="layerMask">LayerMask with all the layers to test against</param> /// <returns>True if in any of the layers in the LayerMask</returns> protected bool IsInLayerMask(GameObject obj) { // Convert the object's layer to a bit mask for comparison LayerMask objMask = 1 << obj.layer; LayerMask targetMask = this.targetLayers; if ((targetMask.value & objMask.value) == 0) // Extra brackets required! return false; else return true; } #endregion protected Utilities } }<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(WorldTo2DCameraConstraint)), CanEditMultipleObjects] public class WorldTo2DCameraConstraintInspector : TransformConstraintInspector { // Singleton cache to set some defaults on inspection Camera[] cameras; protected override void OnInspectorGUIUpdate() { var script = (WorldTo2DCameraConstraint)target; script.targetCamera = PGEditorUtils.ObjectField<Camera>("Target Camera", script.targetCamera); script.orthoCamera = PGEditorUtils.ObjectField<Camera>("Output Camera", script.orthoCamera); EditorGUILayout.Space(); script.offsetMode = PGEditorUtils.EnumPopup<WorldTo2DCameraConstraint.OFFSET_MODE> ( "Offset Mode", script.offsetMode ); script.offset = EditorGUILayout.Vector3Field("Offset", script.offset); EditorGUILayout.Space(); script.offScreenMode = PGEditorUtils.EnumPopup<WorldTo2DCameraConstraint.OFFSCREEN_MODE> ( "Offscreen Mode", script.offScreenMode ); EditorGUI.indentLevel += 2; if (script.offScreenMode != WorldTo2DCameraConstraint.OFFSCREEN_MODE.Constrain) { script.offscreenThreasholdH = EditorGUILayout.Vector2Field("Height Threashold", script.offscreenThreasholdH); script.offscreenThreasholdW = EditorGUILayout.Vector2Field("Width Threashold", script.offscreenThreasholdW); } EditorGUI.indentLevel -= 2; EditorGUILayout.Space(); base.OnInspectorGUIUpdate(); // Set some singletone defaults (will only run once).. // This will actually run when the inspector changes, but still better than // running every update if (this.cameras == null) this.cameras = FindObjectsOfType(typeof(Camera)) as Camera[]; // Default to the first ortho camera that is set to render this object if (script.orthoCamera == null) { foreach (Camera cam in cameras) { if (!cam.orthographic) continue; if ((cam.cullingMask & 1 << script.gameObject.layer) > 0) { script.orthoCamera = cam; break; } } } // Default to the first camera that is set to render the target if (script.target != null && script.targetCamera == null) { foreach (Camera cam in cameras) { if ((cam.cullingMask & 1 << script.target.gameObject.layer) > 0) { script.targetCamera = cam; break; } } } } } }<file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; namespace PathologicalGames { /// <description> /// Constrain this transform to a target's scale, rotation and/or translation. /// </description> [AddComponentMenu("Path-o-logical/UnityConstraints/Constraint - Transform - Smooth")] public class SmoothTransformConstraint : TransformConstraint { public float positionSpeed = 0.1f; public float rotationSpeed = 1; public float scaleSpeed = 0.1f; public UnityConstraints.INTERP_OPTIONS interpolation = UnityConstraints.INTERP_OPTIONS.Spherical; public enum INTERP_OPTIONS_POS { Linear, Damp, DampLimited } public float positionMaxSpeed = 0.1f; public INTERP_OPTIONS_POS position_interpolation = INTERP_OPTIONS_POS.Linear; private Vector3 curDampVelocity = Vector3.zero; /// <summary> /// Runs each frame while the constraint is active /// </summary> protected override void OnConstraintUpdate() { if (this.constrainScale) this.SetWorldScale(target); this.OutputRotationTowards(this.target.rotation); this.OutputPositionTowards(this.target.position); } /// <summary> /// Runs when the noTarget mode is set to ReturnToDefault /// </summary> protected override void NoTargetDefault() { if (this.constrainScale) this.transform.localScale = Vector3.one; this.OutputRotationTowards(Quaternion.identity); this.OutputPositionTowards(this.target.position); } /// <summary> /// Runs when the constraint is active or when the noTarget mode is set to /// ReturnToDefault /// </summary> private void OutputPositionTowards(Vector3 destPos) { // Faster exit if there is nothing to do. if (!this.constrainPosition) return; switch (this.position_interpolation) { case INTERP_OPTIONS_POS.Linear: this.pos = Vector3.Lerp(this.transform.position, destPos, this.positionSpeed); break; case INTERP_OPTIONS_POS.Damp: this.pos = Vector3.SmoothDamp ( this.transform.position, destPos, ref this.curDampVelocity, this.positionSpeed ); break; case INTERP_OPTIONS_POS.DampLimited: this.pos = Vector3.SmoothDamp ( this.transform.position, destPos, ref this.curDampVelocity, this.positionSpeed, this.positionMaxSpeed ); break; } // Output only if wanted - faster to invert and set back to current. if (!this.outputPosX) this.pos.x = this.transform.position.x; if (!this.outputPosY) this.pos.y = this.transform.position.y; if (!this.outputPosZ) this.pos.z = this.transform.position.z; this.transform.position = pos; } /// <summary> /// Runs when the constraint is active or when the noTarget mode is set to /// ReturnToDefault /// </summary> private void OutputRotationTowards(Quaternion destRot) { // Faster exit if nothing to do. if (!this.constrainRotation) return; UnityConstraints.InterpolateRotationTo ( this.transform, destRot, this.interpolation, this.rotationSpeed ); UnityConstraints.MaskOutputRotations(this.transform, this.output); } /// <summary> /// Sets this transform's scale to equal the target in world space. /// </summary> /// <param name="sourceXform"></param> public override void SetWorldScale(Transform sourceXform) { // Set the scale now that both Transforms are in the same space this.transform.localScale = Vector3.Lerp ( this.transform.localScale, this.GetTargetLocalScale(sourceXform), this.scaleSpeed ); } } }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; using System; namespace PathologicalGames { /// <summary> /// This class is a custom implimentation of the IList interface so it is a custom /// list that can take advantage of Unity's collider OnTrigger events to add and remove /// Targets (and much more). This is tightly coupled with the TargetTracker instance /// which creates it and cannot be used standalone. /// </summary> [AddComponentMenu("")] // I hope this is an OK way to hide from Inspector Add menues public class Area : MonoBehaviour, IList<Target> { /// <summary> /// The targetTracker which created this Area /// </summary> public AreaTargetTracker targetTracker; /// <summary> /// The primary data List for the Area. /// </summary> internal TargetList targets = new TargetList(); // Cache public GameObject go; public Collider coll; public Rigidbody rbd; public Collider2D coll2D; public Rigidbody2D rbd2D; #region Init, Sort, Utilities /// <summary> /// Cache /// </summary> protected void Awake() { this.go = this.gameObject; // Protection. Should be added by AreaTargetTracker before adding this script. if (this.GetComponent<Rigidbody>() == null && this.GetComponent<Rigidbody2D>() == null) { string msg = "Areas must have a Rigidbody or Rigidbody2D."; throw new MissingComponentException(msg); } // Note: Coliders are set after Awake during creation by AreaTargetTrackers this.rbd2D = this.GetComponent<Rigidbody2D>(); this.coll2D = this.GetComponent<Collider2D>(); this.rbd = this.GetComponent<Rigidbody>(); this.coll = this.GetComponent<Collider>(); } /// <summary> /// Uses a physics test based on the largest bounds dimension to see if the targetable's /// collider is in range of this Area. /// This has to use the largest dimension for non-uniform sized colliders. It avoids /// situations where the object is inside but not added. the check is still a radius /// though, so a long object that is oriented in a way that doesn't cross in to the /// Area will still return true. /// </summary> /// <returns> /// <param name='targetable'> /// Targetable. /// </param> public bool IsInRange(Targetable targetable) { if (this.coll != null) { Vector3 size = this.coll.bounds.size; float testSize = Mathf.Max(Mathf.Max(size.x, size.y), size.z); var colls = new List<Collider>(Physics.OverlapSphere(this.transform.position, testSize)); return colls.Contains(this.coll); } else if (this.coll2D != null) { var coll2Ds = new List<Collider2D>(); var box2d = this.coll2D as BoxCollider2D; if (box2d != null) { var pos2D = new Vector2(this.transform.position.x, this.transform.position.y); Vector2 worldPos2D = box2d.offset + pos2D; Vector2 extents = box2d.size * 0.5f; var pntA = worldPos2D + extents; var pntB = worldPos2D - extents; coll2Ds.AddRange(Physics2D.OverlapAreaAll(pntA, pntB)); } else { var circ2D = this.coll2D as CircleCollider2D; if (circ2D != null) { coll2Ds.AddRange ( Physics2D.OverlapCircleAll(this.transform.position, circ2D.radius * 2) ); } } return coll2Ds.Contains(this.coll2D); } Debug.Log("IsInRange returning false due to no collider set. This may be fine."); return false; } #endregion Init, Sort, Utilities #region Events /// <summary> /// 3D Collider Event /// </summary> protected void OnTriggerEnter(Collider other) { this.OnTriggerEntered(other); } /// <summary> /// 3D Collider Event /// </summary> protected void OnTriggerExit(Collider other) { // Will only work if there is something to remove. Debug logging inside too. this.OnTriggerExited(other); } /// <summary> /// 2D Collider Event /// </summary> protected void OnTriggerEnter2D(Collider2D other) { this.OnTriggerEntered(other); } /// <summary> /// 2D Collider Event /// </summary> protected void OnTriggerExit2D(Collider2D other) { // Will only work if there is something to remove. Debug logging inside too. this.OnTriggerExited(other); } /// <summary> /// Uses the Collider and Collider2D base class to handle any collider event. /// </summary> protected void OnTriggerEntered(Component other) { // Do Add() only if this is ITargetable var targetable = other.GetComponent<Targetable>(); if (targetable == null) return; // Add for targetables will perform checks and then process the addition this.Add(targetable); } /// <summary> /// Uses the Collider and Collider2D base class to handle any collider event. /// </summary> protected void OnTriggerExited(Component other) { // Will only work if there is something to remove. Debug logging inside too. this.Remove(other.transform); } #endregion Events #region List Interface public void Add(Target target) { // Cheapest quickest check to exit first. if (!target.targetable.isTargetable || !this.go.activeInHierarchy || this.targets.Contains(target)) return; // Is it a layer this targetable detects? if (!this.IsInLayerMask(target.targetable.go)) return; // Give delegates the chance to ignore this Target. if (this.targetTracker.IsIgnoreTargetOnNewDetectedDelegatesExecute(target)) return; this.targets.Add(target); // ADD #if UNITY_EDITOR if (this.targetTracker.debugLevel > DEBUG_LEVELS.Off) // If on at all Debug.Log(string.Format ( "{0} : Target ADDED - {1}", this.targetTracker, target.targetable )); #endif // Trigger the delegate execution for this event target.targetable.OnDetected(this.targetTracker); // Trigger target update: Sorting, filtering, events. // This uses AddRange internally to copy the targets so '=' is safe this.targetTracker.targets = this.targets; } /// <summary> /// Add the specified targetable. /// Performs some checks to make sure the targetable is valid for the Area. /// </summary> /// <param name='targetable'> /// If set to <c>true</c> targetable. /// </param> public void Add(Targetable targetable) { // Get a target struct which will also cache information, such as the Transfrom, // GameObject and ITargetable component // Note this uses the targetable overload which has no component lookups so this // is light. var target = new Target(targetable, this.targetTracker); // Run the main Add overload. this.Add(target); } /// <summary> /// Remove an object from the list explicitly. /// This works even if the object is still in range, effectivley hiding it from the /// perimiter. /// </summary> /// <param name="xform">The transform component of the target to remove</param> /// <returns>True if somethign was removed</returns> public bool Remove(Transform xform) { return this.Remove(new Target(xform, this.targetTracker)); } /// <summary> /// Remove a Targetable /// </summary> /// <param name="xform">The transform component of the target to remove</param> /// <returns>True if somethign was removed</returns> public bool Remove(Targetable targetable) { return this.Remove(new Target(targetable, this.targetTracker)); } /// <summary> /// Remove an object from the list explicitly. /// This works even if the object is still in range, effectivley hiding it from the /// perimiter. /// </summary> /// <param name="target">The Target to remove</param> /// <returns>True if somethign was removed</returns> public bool Remove(Target target) { // Quit if nothing was removed if (!this.targets.Remove(target)) return false; // Silence errors on game exit / unload clean-up if (target.transform == null || this.transform == null || this.transform.parent == null) return false; #if UNITY_EDITOR if (this.targetTracker.debugLevel > DEBUG_LEVELS.Off) // If on at all Debug.Log(string.Format ( "{0} : Target Removed - {1}", this.targetTracker, target.targetable )); #endif // Trigger the delegate execution for this event if (this.targetTracker.onNotDetectedDelegates != null) this.targetTracker.onNotDetectedDelegates(this.targetTracker, target); target.targetable.OnNotDetected(this.targetTracker); // Trigger target update: Sorting, filtering, events. // This uses AddRange internally to copy the targets so '=' is safe this.targetTracker.targets = this.targets; return true; } /// <summary> /// Read-only index access /// </summary> /// <param name="index">int address of the item to get</param> /// <returns></returns> public Target this[int index] { get { return this.targets[index]; } set { throw new System.NotImplementedException("Read-only."); } } /// <summary> /// Clears the entire list explicitly /// This works even if the object is still in range, effectivley hiding it from the /// perimiter. /// </summary> public void Clear() { // Trigger the delegate execution for this event foreach (Target target in this.targets) { if (this.targetTracker.onNotDetectedDelegates != null) this.targetTracker.onNotDetectedDelegates(this.targetTracker, target); target.targetable.OnNotDetected(this.targetTracker); } this.targets.Clear(); #if UNITY_EDITOR if (this.targetTracker.debugLevel > DEBUG_LEVELS.Normal) // If on at all Debug.Log(string.Format ( "{0} : All Targets Cleared!", this.targetTracker )); #endif // Trigger target update: Sorting, filtering, events. // This uses AddRange internally to copy the targets so '=' is safe this.targetTracker.targets = this.targets; } /// <summary> /// Tests to see if an item is in the list /// </summary> /// <param name="item">The transform component of the target to test</param> /// <returns>True of the item is in the list, otherwise false</returns> public bool Contains(Transform transform) { return this.targets.Contains(new Target(transform, this.targetTracker)); } /// <summary> /// Tests to see if an item is in the list /// </summary> /// <param name="target">The target object to test</param> /// <returns>True of the item is in the list, otherwise false</returns> public bool Contains(Target target) { return this.targets.Contains(target); } /// <summary> /// Impliments the ability to use this list in a foreach loop /// </summary> /// <returns></returns> public IEnumerator<Target> GetEnumerator() { for (int i = 0; i < this.targets.Count; i++) yield return this.targets[i]; } // Non-generic version? Not sure why this is used by the interface IEnumerator IEnumerable.GetEnumerator() { for (int i = 0; i < this.targets.Count; i++) yield return this.targets[i]; } /// <summary> /// Used by OTHERList.AddRange() /// This adds this list to the passed list /// </summary> /// <param name="array">The list AddRange is being called on</param> /// <param name="arrayIndex"> /// The starting index for the copy operation. AddRange seems to pass the last index. /// </param> public void CopyTo(Target[] array, int arrayIndex) { this.targets.CopyTo(array, arrayIndex); } // Not implimented from iList public int IndexOf(Target item) { throw new System.NotImplementedException(); } public void Insert(int index, Target item) { throw new System.NotImplementedException(); } public void RemoveAt(int index) { throw new System.NotImplementedException(); } public bool IsReadOnly { get { throw new System.NotImplementedException(); } } #endregion List Interface #region List Utilities /// <summary> /// Returns the number of items in this (the collection). Readonly. /// </summary> public int Count { get { return this.targets.Count; } } /// <summary> /// Returns a string representation of this (the collection) /// </summary> public override string ToString() { // Build an array of formatted strings then join when done string[] stringItems = new string[this.targets.Count]; string stringItem; int i = 0; // Index counter foreach (Target target in this.targets) { // Protection against async destruction. if (target.transform == null) { stringItems[i] = "null"; i++; continue; } stringItem = string.Format("{0}:Layer={1}", target.transform.name, LayerMask.LayerToName(target.gameObject.layer)); // Finish the string for this target based on the target style switch (this.targetTracker.sortingStyle) { case AreaTargetTracker.SORTING_STYLES.None: // Do nothing break; case AreaTargetTracker.SORTING_STYLES.Nearest: case AreaTargetTracker.SORTING_STYLES.Farthest: float d; d = target.targetable.GetSqrDistToPos(this.transform.position); stringItem += string.Format(",Dist={0}", d); break; case AreaTargetTracker.SORTING_STYLES.NearestToDestination: case AreaTargetTracker.SORTING_STYLES.FarthestFromDestination: stringItem += string.Format(",DistToDest={0}", target.targetable.distToDest); break; } stringItems[i] = stringItem; i++; } // Return a comma-sperated list inside square brackets (Pythonesque) return string.Format("[{0}]", System.String.Join(", ", stringItems)); } #endregion List Utilities #region protected Utilities /// <summary> /// Checks if a GameObject is in a LayerMask /// </summary> /// <param name="obj">GameObject to test</param> /// <param name="layerMask">LayerMask with all the layers to test against</param> /// <returns>True if in any of the layers in the LayerMask</returns> protected bool IsInLayerMask(GameObject obj) { // Convert the object's layer to a bit mask for comparison LayerMask objMask = 1 << obj.layer; LayerMask targetMask = this.targetTracker.targetLayers; if ((targetMask.value & objMask.value) == 0) // Extra brackets required! return false; else return true; } #endregion protected Utilities } }<file_sep>using UnityEngine; using System.Collections; public class MoveBackground : MonoBehaviour { public float scrollSpeed = 0.01f; public int backGroundType; public Texture back1; public Texture back2; public Texture back3; Material myMaterial; void Start () { myMaterial = GetComponent<Renderer> ().material; if(backGroundType == 1) myMaterial.mainTexture = back1; else if(backGroundType == 2) myMaterial.mainTexture = back2; else if(backGroundType == 3) myMaterial.mainTexture = back3; myMaterial.mainTextureOffset = new Vector2 (0, 0); } void Update () { float newOffsetY = myMaterial.mainTextureOffset.y + scrollSpeed * Time.deltaTime; myMaterial.mainTextureOffset = new Vector2 (0, newOffsetY); } } <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// A TargetTracker which uses an Area, a child game object generated at runtime /// used to detect and manage Targetables in range. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Area TargetTracker")] public class AreaTargetTracker : TargetTracker { #region Parameters #region Inspector Fields /// <summary> /// The range in which targets will be found. /// The size from the center to the edge of the Area in x, y and z for any /// shape. Depending on the shape some values may be ignored. E.g. Spheres only /// use X for radius /// </summary> public Vector3 range { get { return this._range; } set { // Store the passed Vector3 then process the range per collider type this._range = value; if (this.area != null) this.UpdateAreaRange(); } } [SerializeField] // protected backing fields must be SerializeField. For instances. protected Vector3 _range = Vector3.one; /// <summary> /// Area shape options /// </summary> public enum AREA_SHAPES { Capsule, Box, Sphere, Box2D, Circle2D } /// <summary> /// Returns true if the Area shape in use is one of the 2D collider types. /// </summary> /// <value> public bool is2D { get { int shapes = (int)(AREA_SHAPES.Box2D | AREA_SHAPES.Circle2D); return System.Enum.IsDefined(typeof(AREA_SHAPES), shapes); } } /// <summary> /// The shape of the Area used to detect targets in range /// </summary> public AREA_SHAPES areaShape { get { return this._areaShape; } set { this._areaShape = value; // Just in case this is called before Awake runs. if (this.area == null) return; this.StartCoroutine(this.UpdateAreaShape()); } } [SerializeField] // protected backing fields must be SerializeField. For instances. protected AREA_SHAPES _areaShape = AREA_SHAPES.Sphere; /// <summary> /// An optional position offset for the Area. /// For example, if you have an object resting on the ground which has a range of /// 4, a position offset of Vector3(0, 4, 0) will place your Area so it is /// also sitting on the ground /// </summary> public Vector3 areaPositionOffset { get { return this._areaPositionOffset; } set { this._areaPositionOffset = value; // Just in case this is called before Awake runs. if (this.area == null) return; this.area.transform.localPosition = value; } } [SerializeField] // protected backing fields must be SerializeField. For instances. protected Vector3 _areaPositionOffset = Vector3.zero; /// <summary> /// An optional rotational offset for the Area. /// </summary> public Vector3 areaRotationOffset { get { return this._areaRotationOffset; } set { this._areaRotationOffset = value; // Just in case this is called before Awake runs. if (this.area == null) return; // TODO: Does this work for 2D circles? this.area.transform.localRotation = Quaternion.Euler(value); } } [SerializeField] // protected backing fields must be SerializeField. For instances. protected Vector3 _areaRotationOffset = Vector3.zero; /// <summary> /// The layer to put the Area in. 0 is the default layer. /// </summary> public int areaLayer { get { return this._areaLayer; } set { this._areaLayer = value; // Just in case this is called before Awake runs. if (this.area == null) return; this.area.gameObject.layer = value; } } [SerializeField] // protected backing fields must be SerializeField. For instances. protected int _areaLayer = 0; #endregion Inspector Fields /// <summary> /// Access to the Area component/list /// </summary> public override Area area { get; protected set; } /// <summary> /// Used by this and derived AreaTargetTrackers to determine if their Area should detect /// Targets right away. Set this to false in a derived type's Awake() method just before /// calling base.Awake() to override the state. EventTriggers do this, for exmaple, so they /// don't detect targets unless in AreaHit mode and only when they are triggered. /// </summary> protected bool areaColliderEnabledAtStart = true; #endregion Perameters #region Cache and Setup protected override void Awake() { base.Awake(); #region Build Perimter // PERINETER GAME OBJECT // Create the Area object at run-time. The name is really just for debugging var areaGO = new GameObject(this.name + "_Area"); areaGO.transform.parent = this.transform; //areaGO.hideFlags = HideFlags.HideInHierarchy; areaGO.SetActive(false); areaGO.SetActive(true); // These are set by properties but need to be synced when first generated areaGO.transform.localPosition = this.areaPositionOffset; areaGO.transform.localRotation = Quaternion.Euler(this.areaRotationOffset); areaGO.layer = this.areaLayer; // PERINETER PHYSICS... // Adds collider and rigidbody. Needed by Area Awake below. so keep up here. this.StartCoroutine(this.UpdateAreaShape(areaGO)); // Co-routine for after Awake() // Set collider state before adding Area component // 'areaColliderEnabledAtStart' may be set by derived types before this Awake() runs. this.setAreaColliderEnabled(areaGO, this.areaColliderEnabledAtStart); // AREA COMPONENT... // Add the Area script and return it this.area = areaGO.AddComponent<Area>(); // Will also start "disabled" this.area.targetTracker = this; // INIT OTHER... this.UpdateAreaRange(); // Sets the collider's size #endregion Build Perimter } /// <summary> /// Update the Area range buy removing the old collider and making a new one. /// This is a coroutine but it always runs right away unless the rigidbody has to /// be destroyed to change from 2D to 3D or back, in which case it needs a frame /// to process the destroy request. /// </summary> protected IEnumerator UpdateAreaShape() { this.StartCoroutine(this.UpdateAreaShape(this.area.go)); yield break; } protected IEnumerator UpdateAreaShape(GameObject areaGO) { // Remove the old collider, or quit if already the right shape Collider oldCol = areaGO.GetComponent<Collider>(); Collider2D oldCol2D = areaGO.GetComponent<Collider2D>(); switch (this.areaShape) { case AREA_SHAPES.Sphere: if (oldCol is SphereCollider) yield break; break; case AREA_SHAPES.Box: if (oldCol is BoxCollider) yield break; break; case AREA_SHAPES.Capsule: if (oldCol is CapsuleCollider) yield break; break; case AREA_SHAPES.Box2D: if (oldCol2D is BoxCollider2D) yield break; break; case AREA_SHAPES.Circle2D: if (oldCol2D is CircleCollider2D) yield break; break; default: throw new System.Exception("Unsupported collider type."); } if (oldCol != null) Destroy(oldCol); if (oldCol2D != null) Destroy(oldCol2D); // If the shape is changing from a 2D shape to a 3D shape, swap RigidBodies too // If there is no rigidbody, add it (usually only needed during initilization. switch (this.areaShape) { case AREA_SHAPES.Sphere: case AREA_SHAPES.Box: case AREA_SHAPES.Capsule: if (areaGO.GetComponent<Rigidbody2D>() != null) { Destroy(areaGO.GetComponent<Rigidbody2D>()); yield return null; } if (areaGO.GetComponent<Rigidbody>() == null) { var rbd = areaGO.AddComponent<Rigidbody>(); rbd.isKinematic = true; } break; case AREA_SHAPES.Box2D: case AREA_SHAPES.Circle2D: if (areaGO.GetComponent<Rigidbody>() != null) { Destroy(areaGO.GetComponent<Rigidbody>()); yield return null; } if (areaGO.GetComponent<Rigidbody2D>() == null) { var rbd2D = areaGO.AddComponent<Rigidbody2D>(); rbd2D.isKinematic = true; // BUG looks solved: http://issuetracker.unity3d.com/issues/rigidbody2d-with-kinematic-rigidbody-will-not-cause-ontriggerenter2d //rbd2D.gravityScale = 0; // hack work-around for the above bug } break; } // Add the new collider Collider coll = null; Collider2D coll2D = null; switch (this.areaShape) { case AREA_SHAPES.Sphere: coll = areaGO.AddComponent<SphereCollider>(); coll.isTrigger = true; break; case AREA_SHAPES.Box: coll = areaGO.AddComponent<BoxCollider>(); coll.isTrigger = true; break; case AREA_SHAPES.Capsule: coll = areaGO.AddComponent<CapsuleCollider>(); coll.isTrigger = true; break; case AREA_SHAPES.Box2D: coll2D = areaGO.AddComponent<BoxCollider2D>(); coll2D.isTrigger = true; break; case AREA_SHAPES.Circle2D: coll2D = areaGO.AddComponent<CircleCollider2D>(); coll2D.isTrigger = true; break; default: throw new System.Exception("Unsupported collider type."); } // No collisions. Trigger only if (coll != null) { coll.isTrigger = true; // Update area cached reference if (this.area != null) this.area.coll = coll; } else if (coll2D != null) { coll2D.isTrigger = true; // Update area cached reference if (this.area != null) this.area.coll2D = coll2D; } this.UpdateAreaRange(coll, coll2D); yield break; } /// <summary> /// Sets the range based on this._range and the collider type. /// </summary> protected void UpdateAreaRange() { Collider col = this.area.coll; Collider2D col2D = this.area.coll2D; this.UpdateAreaRange(col, col2D); } /// <summary> /// Overload to skip the need for an Area to exist so this can be used during setup. /// </summary> protected void UpdateAreaRange(Collider col, Component col2D) // Component is for 4.0 compatability { Vector3 normRange = this.GetNormalizedRange(); if (col is SphereCollider) { var collider = (SphereCollider)col; collider.radius = normRange.x; } else if (col is BoxCollider) { var collider = (BoxCollider)col; collider.size = normRange; } else if (col is CapsuleCollider) { var collider = (CapsuleCollider)col; collider.radius = normRange.x; collider.height = normRange.y; } else if (col2D is CircleCollider2D) { var collider = (CircleCollider2D)col2D; collider.radius = normRange.x; } else if (col2D is BoxCollider2D) { var collider = (BoxCollider2D)col2D; collider.size = new Vector2(normRange.x, normRange.y); } else { string colType; string colName; if (col != null) { colType = col.GetType().Name; colName = col.name; } else if (col2D != null) { colType = col2D.GetType().Name; colName = col2D.name; } else { throw new System.NullReferenceException("No Collider Found!"); } Debug.LogWarning ( string.Format ( "Unsupported collider type '{0}' for collider '{1}'.", colType, colName ) ); } } /// <summary> /// Calculate the range based on the collider shape. The user input creates /// different results depending on the shape used. A sphere radius is different /// than a box width. This function creates a mapping which normalizes the result. /// The shape is a string so this can be used before the collider exits /// </summary> /// <returns>Vector3</returns> public Vector3 GetNormalizedRange() { Vector3 normRange = Vector3.zero; switch (this.areaShape) { case AREA_SHAPES.Circle2D: // Fallthrough normRange = new Vector3 ( this._range.x, this._range.x, 0 ); break; case AREA_SHAPES.Sphere: normRange = new Vector3 ( this._range.x, this._range.x, this._range.x ); break; case AREA_SHAPES.Box2D: normRange = new Vector3 ( this._range.x * 2, this._range.y * 2, 0 ); break; case AREA_SHAPES.Box: normRange = new Vector3 ( this._range.x * 2, this._range.y, // Not x2 because measured from base to top, nothing "below-ground" this._range.z * 2 ); break; case AREA_SHAPES.Capsule: normRange = new Vector3 ( this._range.x, this._range.y * 2, // Capsules work this way this._range.x ); break; } return normRange; } /// <summary> /// Read-only convienince property to find out of the Tracker's Area is currently /// able to detect targets based on the state of its collider. Use /// <see cref="PathologicalGames.AreaTargetTracker.setAreaColliderEnabled"/> to set /// this state. /// </summary> /// <value><c>true</c> if area collider enabled; otherwise, <c>false</c>.</value> public bool areaColliderEnabled { get { if (this.area != null) { if (this.area.coll != null) { return this.area.coll.enabled; } else if (this.area.coll2D != null) { return this.area.coll2D.enabled; } } return false; } } /// <summary> /// Sets the area collider enabled/disabled. When disabled, no Targets are detected. /// </summary> /// <param name="enable">If set to <c>true</c> enable.</param> public void setAreaColliderEnabled(bool enable) { this.setAreaColliderEnabled(this.area.go, enable); } /// <summary> /// Sets the area collider enabled/disabled. When disabled, no Targets are detected. /// This overload used internally by this AreaTargetTracker, or derived classes, to set /// the state of the Area GameObject's collider before the area component is added. If /// the GameObject does already have an Area, however, the area cached components are /// used directly. /// </summary> /// <param name="areaGO">Area GameObject to check for colliders</param> /// <param name="enable">If set to <c>true</c> enable.</param> protected void setAreaColliderEnabled(GameObject areaGO, bool enable) { // Old way. It is more work to toggle the collider instead, but it allows for normal // operation of the gameObject while preventing premature target detection. //areaGO.SetActive(enable); Collider coll; if (this.area != null) // Indirect logic. use this area or fallback to GO. { coll = this.area.coll; } else { coll = areaGO.GetComponent<Collider>(); } if (coll != null) { coll.enabled = enable; return; } else { Collider2D coll2D; if (this.area != null) { coll2D = this.area.coll2D; } else { coll2D = areaGO.GetComponent<Collider2D>(); } if (coll2D != null) { coll2D.enabled = enable; return; } } throw new System.Exception("Unexpected Error: No area collider found."); } protected override void OnEnable() { base.OnEnable(); if (this.area != null) this.area.go.SetActive(true); } protected virtual void OnDisable() { // Needed to avoid error when stoping the game or if the Area was destroyed // for some reason. if (this.area == null) return; this.area.Clear(); this.area.go.SetActive(false); } #endregion Cache and Setup } }<file_sep>/// <Licensing> /// � 2011(Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License(the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Explcictly ignore Targets. Useful when a TargetTracker prefab is also a Target on the /// same layer as other Targets. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Modifier - Ignore Tags")] [RequireComponent(typeof(TargetTracker))] public class IgnoreTagModifier : TriggerEventProModifier { public List<string> ignoreList = new List<string>(); public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; protected TargetTracker tracker; // Cache protected string currentTag; // Loop Cache protected void Awake() { this.tracker = this.GetComponent<TargetTracker>(); } protected void OnEnable() { this.tracker.AddOnNewDetectedDelegate(this.OnNewDetected); } protected void OnDisable() { if (this.tracker != null) // For when levels or games are dumped this.tracker.RemoveOnNewDetectedDelegate(this.OnNewDetected); } protected bool OnNewDetected(TargetTracker targetTracker, Target target) { #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Normal) { string msg = string.Format ( "Testing target '{0}' with tag '{1}' against ignore tags: '{2}'", target.gameObject.name, target.gameObject.tag, string.Join("', '", this.ignoreList.ToArray()) ); Debug.Log(string.Format("IgnoreTagModifier ({0}): {1}", this.name, msg)); } #endif for (int i = 0; i < this.ignoreList.Count; i++) { this.currentTag = this.ignoreList[i]; if (target.gameObject.tag == this.currentTag) { #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = string.Format( "Ignoring target '{0}' due to tag: '{1}'", target.gameObject.name, this.currentTag ); Debug.Log(string.Format("IgnoreTagModifier ({0}): {1}", this.name, msg)); } #endif return false; // Stop looking and ignore } } return true; } } }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> // for information about using the POOLMANAGER_INSTALLED or USE_OTHER_POOLING global Custom // Defines, See the section "Platform Custom Defines" here: // https://docs.unity3d.com/Documentation/Manual/PlatformDependentCompilation.html // Or you may wish to use *.rsp files. #if POOLMANAGER_INSTALLED && USE_OTHER_POOLING #error Do not use both Custome Defines POOLMANAGER_INSTALLED *and* USE_OTHER_POOLING. Pick one. #endif using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Options used to print a stream of messages for the implimenting conponent /// </summary> public enum DEBUG_LEVELS { Off, Normal, High } /// <summary> /// Methods which interface with PoolManager if installed and the preprocessor /// directive at the top of this file is uncommented. Otherwise will run /// Unity's Instantiate() and Destroy() based functionality. /// </summary> public static class InstanceManager { /// <summary> /// Can be used to test if a pooling preprocessor directive is enabled. /// </summary> #if USE_OTHER_POOLING || POOLMANAGER_INSTALLED public static bool POOLING_ENABLED = true; #else public static bool POOLING_ENABLED = false; #endif #if USE_OTHER_POOLING || POOLMANAGER_INSTALLED public delegate Transform OnSpawn ( string poolName, Transform prefab, Vector3 pos, Quaternion rot ); public delegate Transform OnDespawn(string poolName, Transform instance); public static OnSpawn OnSpawnDelegates; public static OnDespawn OnDepawnDelegates; #endif #region Static Methods /// <summary> /// Creates a new instance. /// /// If PoolManager is installed and the pre-proccessor directive is /// uncommented at the top of TargetTracker.cs, this will use PoolManager to /// pool ammo instances. /// /// If the pool doesn't exist before this is used, it will be created. /// /// Otherwise, Unity's Object.Instantiate() is used. /// </summary> /// <param name="prefab">The prefab to spawn an instance from</param> /// <param name="pos">The position to spawn the instance</param> /// <param name="rot">The rotation of the new instance</param> /// <returns></returns> public static Transform Spawn(string poolName, Transform prefab, Vector3 pos, Quaternion rot) { #if POOLMANAGER_INSTALLED || USE_OTHER_POOLING if (poolName == "") // Overload use of poolName to toggle pooling return (Transform)Object.Instantiate(prefab, pos, rot); #endif #if POOLMANAGER_INSTALLED // If the pool doesn't exist, it will be created before use if (!PoolManager.Pools.ContainsKey(poolName)) (new GameObject(poolName)).AddComponent<SpawnPool>(); return PoolManager.Pools[poolName].Spawn(prefab, pos, rot); #elif USE_OTHER_POOLING InstanceManager.OnSpawnDelegates(poolName, prefab, pos, rot); #else return (Transform)Object.Instantiate(prefab, pos, rot); #endif } /// <summary> /// Despawnsan instance. /// /// If PoolManager is installed and the pre-proccessor directive is /// uncommented at the top of TargetTracker.cs, this will use PoolManager /// to despawn pooled ammo instances. /// /// Otherwise, Unity's Object.Destroy() is used. /// </summary> public static void Despawn(string poolName, Transform instance) { #if POOLMANAGER_INSTALLED || USE_OTHER_POOLING if (poolName == "") // Overload use of poolName to toggle pooling { Object.Destroy(instance.gameObject); return; } #endif #if POOLMANAGER_INSTALLED PoolManager.Pools[poolName].Despawn(instance); #elif USE_OTHER_POOLING InstanceManager.OnDespawnDelegates(poolName, instance); #else Object.Destroy(instance.gameObject); #endif } } #endregion Static Methods #region Classes, Structs, Interfaces /// <summary> /// Carries information about a target including a reference to its Targetable /// component (targetable), Transform (transform) and GameObject (gameObject) as /// well as the source TargetTracker (targetTracker) and /// FireController (fireController) components. FireController is null if not used. /// </summary> public struct Target : System.IComparable<Target> { // Target cache public GameObject gameObject; public Transform transform; public Targetable targetable; // Source cache for easy access/reference passing/etc public TargetTracker targetTracker; public EventFireController fireController; public EventTrigger eventTrigger; public Collider collider; public Collider2D collider2D; /// <summary> /// A cached "empty" Target struct which can be used for null-like 'if' checks /// </summary> public static Target Null { get { return _Null; } } private static Target _Null = new Target(); /// <summary> /// Initializes a new instance of the <see cref="PathologicalGames.Target"/> struct. /// </summary> /// <param name='transform'> /// Transform that has a Targetable component /// </param> /// <param name='targetTracker'> /// Target tracker that detected this Target /// </param> public Target(Transform transform, TargetTracker targetTracker) { // Subtle but important difference with this constructure overload is // it allows targetable to be 'null' which is used to avoid missing // component exceptions in Area. this.gameObject = transform.gameObject; this.transform = transform; this.targetable = transform.GetComponent<Targetable>(); this.targetTracker = targetTracker; // The targetTracker arg could also be a derived type. If it is. populate more. // Also handle colliders to make the struct easier to use when trying to figure // out what collider triggered the OnHit event. this.eventTrigger = null; this.collider = null; this.collider2D = null; this.eventTrigger = targetTracker as EventTrigger; if (this.eventTrigger != null) { this.collider = this.eventTrigger.coll; this.collider2D = this.eventTrigger.coll2D; } this.fireController = null; } /// <summary> /// Initializes a new instance of the <see cref="PathologicalGames.Target"/> struct. /// This is the most efficient constructor because it just stores references to /// caches that the Targetable already holds. /// </summary> /// <param name='targetable'> /// Targetable. /// </param> /// <param name='targetTracker'> /// Target tracker that detected the targetable. /// </param> public Target(Targetable targetable, TargetTracker targetTracker) { this.gameObject = targetable.go; this.transform = targetable.transform; this.targetable = targetable; this.targetTracker = targetTracker; // The targetTracker arg could also be serived type. If it is. populate more. // Also handle colliders to make the struct easier to use when trying to figure // out what collider triggered the OnHit event. this.eventTrigger = null; this.collider = null; this.collider2D = null; this.eventTrigger = targetTracker as EventTrigger; if (this.eventTrigger != null) { this.collider = this.eventTrigger.coll; this.collider2D = this.eventTrigger.coll2D; } this.fireController = null; } // Init by copy public Target(Target otherTarget) { this.gameObject = otherTarget.gameObject; this.transform = otherTarget.transform; this.targetable = otherTarget.targetable; this.targetTracker = otherTarget.targetTracker; this.fireController = otherTarget.fireController; this.eventTrigger = otherTarget.eventTrigger; this.collider = otherTarget.collider; this.collider2D = otherTarget.collider2D; } public static bool operator ==(Target tA, Target tB) { return tA.gameObject == tB.gameObject; } public static bool operator !=(Target tA, Target tB) { return tA.gameObject != tB.gameObject; } // These are required to shut the cimpiler up when == or != is overriden // This are implimented as recomended by the msdn documentation. public override int GetHashCode(){ return base.GetHashCode(); } public override bool Equals(System.Object other) { if (other == null) return false; return this == (Target)other; // Uses overriden == } /// <summary> /// Returns true if the target is in a spawned state. Spawned means the target /// is not null (not destroyed) and it IS enabled (not despawned by an instance /// pooling system like PoolManager) /// </summary> public bool isSpawned { get { // Null means destroyed so false, if pooled, disabled is false return this.gameObject == null ? false : this.gameObject.activeInHierarchy; } } /// <summary> /// For internal use only. /// The default for IComparable. Will test if this target is equal to another /// by using the GameObject reference equality test /// </summary> public int CompareTo(Target obj) { return this.gameObject == obj.gameObject ? 1 : 0; } } /// <summary> /// A custom List implimentation to allow for user-friendly usage and ToString() /// representation as well as an extra level of abstraction for future /// extensibility /// </summary> public class TargetList : List<Target> { // Impliment both constructors to enable the 1 arg copy-style constructor public TargetList() : base() { } public TargetList(TargetList targetList) : base(targetList) { } public TargetList(Area area) : base(area) { } public override string ToString() { string[] names = new string[base.Count]; int i = 0; Target target; IEnumerator<Target> enumerator = base.GetEnumerator(); while (enumerator.MoveNext()) { target = enumerator.Current; if (target.transform == null) continue; names[i] = target.transform.name; i++; } return string.Join(", ", names); } } /// <summary> /// Used to pass information to a target when it is hit /// </summary> public struct EventInfo { public string name; public float value; public float duration; public float hitTime; /// <summary> /// Copy constructor to populate a new struct with an old /// </summary> /// <param name="eventInfo"></param> public EventInfo(EventInfo eventInfo) { this.name = eventInfo.name; this.value = eventInfo.value; this.duration = eventInfo.duration; this.hitTime = eventInfo.hitTime; } /// <summary> /// This returns how much of the duration is left based on the current time /// and the hitTime (time stamped by Targetable OnHit) /// </summary> public float deltaDurationTime { get { // If smaller than 0, return 0. return Mathf.Max((hitTime + duration) - Time.time, 0); } } public override string ToString() { return string.Format ( "(name '{0}', value {1}, duration {2}, hitTime {3}, deltaDurationTime {4})", this.name, this.value, this.duration, this.hitTime, this.deltaDurationTime ); } } /// <summary> /// The base class for all Modifiers. This class is abstract so it can only be /// inherited and implimented, not used directly. However it can still be used for /// Type detection when trying to figure out if a component is a Modifier. /// Requested by user. /// </summary> public abstract class TriggerEventProModifier : MonoBehaviour { } /// <summary> /// A custom List implimentation to allow for user-friendly usage and ToString() /// representation as well as an extra later of abstraction for futre /// extensibility /// </summary> public class EventInfoList : List<EventInfo> { // Impliment both constructors to enable the 1 arg copy-style initilizer public EventInfoList() : base() { } public EventInfoList(EventInfoList eventInfoList) : base(eventInfoList) { } /// <summary> /// Print a nice message showing the contents of this list. /// </summary> public override string ToString() { string[] infoStrings = new string[base.Count]; int i = 0; EventInfo info; IEnumerator<EventInfo> enumerator = base.GetEnumerator(); while (enumerator.MoveNext()) { info = enumerator.Current; infoStrings[i] = info.ToString(); i++; } return System.String.Join(", ", infoStrings); } /// <summary> /// Get a copy of this list with effectInfo.hitTime set to 'now'. /// </summary> /// <returns>EventInfoList</returns> public EventInfoList CopyWithHitTime() { var newlist = new EventInfoList(); EventInfo info; IEnumerator<EventInfo> enumerator = base.GetEnumerator(); while (enumerator.MoveNext()) { info = enumerator.Current; info.hitTime = Time.time; newlist.Add(info); } return newlist; } } /// <summary> /// Used by the Editor custom Inspector to get user input /// </summary> [System.Serializable] public class EventInfoListGUIBacker { public string name = "<Event Name>"; public float value = 0; public float duration; /// <summary> /// Create a new EventInfoListGUIBacker with default values /// </summary> /// <returns></returns> public EventInfoListGUIBacker() { } /// <summary> /// Create a new EventInfoListGUIBacker from a HitEffect struct /// </summary> /// <returns></returns> public EventInfoListGUIBacker(EventInfo info) { this.name = info.name; this.value = info.value; this.duration = info.duration; } /// <summary> /// Return an EventInfo struct. /// </summary> /// <returns></returns> public EventInfo GetEventInfo() { return new EventInfo { name = this.name, value = this.value, duration = this.duration, }; } } #endregion Classes, Structs, Interfaces }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using PathologicalGames; [CustomEditor(typeof(FireDistanceModifier)), CanEditMultipleObjects] public class FireDistanceModifierInspector : Editor { protected SerializedProperty debugLevel; protected SerializedProperty drawGizmo; protected SerializedProperty gizmoColor; protected SerializedProperty maxDistance; protected SerializedProperty minDistance; protected SerializedProperty originMode; protected void OnEnable() { this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.drawGizmo = this.serializedObject.FindProperty("drawGizmo"); this.gizmoColor = this.serializedObject.FindProperty("gizmoColor"); this.maxDistance = this.serializedObject.FindProperty("maxDistance"); this.minDistance = this.serializedObject.FindProperty("minDistance"); this.originMode = this.serializedObject.FindProperty("originMode"); } public override void OnInspectorGUI() { this.serializedObject.Update(); Object[] targetObjs = this.serializedObject.targetObjects; FireDistanceModifier curEditTarget; GUIContent content; GUIStyle style; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; EditorGUI.indentLevel = 1; content = new GUIContent ( "Origin Mode", "The origin is the point from which the distance is measuered." ); EditorGUILayout.PropertyField(this.originMode, content); var noLabel = new GUIContent(""); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Distance:", GUILayout.MaxWidth(70)); EditorGUILayout.LabelField("Min", GUILayout.MaxWidth(40)); EditorGUILayout.PropertyField(this.minDistance, noLabel, GUILayout.MinWidth(40)); EditorGUILayout.LabelField("Max", GUILayout.MaxWidth(40)); EditorGUILayout.PropertyField(this.maxDistance, noLabel, GUILayout.MinWidth(40)); EditorGUILayout.EndHorizontal(); // GIZMO... EditorGUILayout.BeginHorizontal(); GUILayout.Space(12); // For some reason the button won't indent. So fake it. content = new GUIContent ( "Gizmo", "Visualize the distance in the Editor by turning this on." ); PGEditorUtils.ToggleButton(this.drawGizmo, content, 50); if (this.drawGizmo.boolValue) { EditorGUILayout.PropertyField(this.gizmoColor, noLabel, GUILayout.MinWidth(60)); style = EditorStyles.miniButton; style.alignment = TextAnchor.MiddleCenter; style.fixedWidth = 52; if (GUILayout.Button("Reset", style)) { for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (FireDistanceModifier)targetObjs[i]; curEditTarget.gizmoColor = curEditTarget.defaultGizmoColor; } } } EditorGUILayout.EndHorizontal(); GUILayout.Space(4); content = new GUIContent ( "Debug Level", "Set it higher to see more verbose information." ); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } } class FireDistanceModifierGizmo { static GameObject spaceCalculator; [DrawGizmo(GizmoType.Selected | GizmoType.NotInSelectionHierarchy)] static void RenderGizmo(FireDistanceModifier mod, GizmoType gizmoType) { if (!mod.drawGizmo || !mod.enabled || mod.overrideGizmoVisibility) return; // In the Editor, this may not be cached yet. Required component, so WILL exist if (mod.fireCtrl == null) mod.fireCtrl = mod.GetComponent<EventFireController>(); TargetTracker tt = mod.fireCtrl.targetTracker; if (tt == null) tt = mod.fireCtrl.GetComponent<TargetTracker>(); Transform xform = mod.transform; switch (mod.originMode) { case FireDistanceModifier.ORIGIN_MODE.TargetTracker: xform = tt.transform; break; case FireDistanceModifier.ORIGIN_MODE.TargetTrackerArea: var perimterTT = tt as AreaTargetTracker; if (perimterTT == null) throw new System.Exception ( "TargetTracker not a AreaTargetTracker. Use a different origin " + "mode than 'TargetTrackerArea'" ); // Set the space everything is drawn in. if (FireDistanceModifierGizmo.spaceCalculator == null) { FireDistanceModifierGizmo.spaceCalculator = new GameObject(); FireDistanceModifierGizmo.spaceCalculator.hideFlags = HideFlags.HideAndDontSave; } xform = FireDistanceModifierGizmo.spaceCalculator.transform; xform.position = ( (perimterTT.transform.rotation * perimterTT.areaPositionOffset) + perimterTT.transform.position ); break; case FireDistanceModifier.ORIGIN_MODE.FireController: // Already defaulted above. break; case FireDistanceModifier.ORIGIN_MODE.FireControllerEmitter: if (mod.fireCtrl.spawnEventTriggerAtTransform != null) xform = mod.fireCtrl.spawnEventTriggerAtTransform; //else // Already defaulted above. // xform = mod.transform; break; } Gizmos.matrix = xform.localToWorldMatrix; Vector3 pos = Vector3.zero; // We set the sapce relative above Color color = mod.gizmoColor; color.a = 0.2f; Gizmos.color = color; Gizmos.DrawWireSphere(pos, mod.maxDistance); color.a = 0.05f; Gizmos.color = color; Gizmos.DrawSphere(pos, mod.maxDistance); Gizmos.matrix = Matrix4x4.zero; // Just to be clean } } <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using PathologicalGames; [CustomEditor(typeof(LineOfSightModifier)), CanEditMultipleObjects] public class LineOfSightModifierInspector : Editor { protected SerializedProperty debugLevel; protected SerializedProperty fireControllerLayerMask; protected SerializedProperty targetTrackerLayerMask; protected SerializedProperty testMode; protected void OnEnable() { this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.fireControllerLayerMask = this.serializedObject.FindProperty("fireControllerLayerMask"); this.targetTrackerLayerMask = this.serializedObject.FindProperty("targetTrackerLayerMask"); this.testMode = this.serializedObject.FindProperty("testMode"); } public override void OnInspectorGUI() { this.serializedObject.Update(); Object[] targetObjs = this.serializedObject.targetObjects; LineOfSightModifier curEditTarget; GUIContent content; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; EditorGUI.indentLevel = 1; // Display some information GUILayout.Space(6); EditorGUILayout.HelpBox ( "Add layers of obsticles to activate LOS filtering.\n" + " - Target Tracker to ignore targets\n" + " - Fire Controller to hold fire\n" + "If any options don't appear it is because this GameObject doesn't have " + "one or both components.", MessageType.None ); // Try to do some setup automation and track some info for display below bool anyHaveTracker = false; bool anyHaveFireCtrl = false; bool allHaveTracker = true; bool allHaveFireCtrl = true; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (LineOfSightModifier)targetObjs[i]; // Attempt init... if (curEditTarget.tracker == null) curEditTarget.tracker = curEditTarget.GetComponent<AreaTargetTracker>(); if (curEditTarget.fireCtrl == null) curEditTarget.fireCtrl = curEditTarget.GetComponent<EventFireController>(); // Track what exists... if (curEditTarget.tracker != null) anyHaveTracker = true; else allHaveTracker = false; if (curEditTarget.fireCtrl != null) anyHaveFireCtrl = true; else allHaveFireCtrl = false; } // Leave a blank GUI if BOTH are still missing if (!anyHaveTracker && !anyHaveFireCtrl) { EditorGUILayout.HelpBox ( "Add a FireController or TargetTracker to see options.", MessageType.Warning ); return; } if (anyHaveTracker) { content = new GUIContent ( "Target Tracker Mask", "Layers of obsticales to block line-of-sight." ); EditorGUILayout.PropertyField(this.targetTrackerLayerMask, content); if (!allHaveTracker) { EditorGUI.indentLevel += 1; EditorGUILayout.HelpBox ( "Multi-Edit Note: 1 or more selected GameObjects do not have a TargetTracker.\n" + "This is just a note, not an error. The option above will still apply to " + "GameObjects which do have a TargetTracker", MessageType.Info ); EditorGUI.indentLevel -= 1; } } if (anyHaveFireCtrl) { content = new GUIContent ( "Fire Controller Mask", "Layers of obsticales to block line-of-sight." ); EditorGUILayout.PropertyField(this.fireControllerLayerMask, content); if (!allHaveFireCtrl) { EditorGUI.indentLevel += 1; EditorGUILayout.HelpBox ( "Multi-Edit Note: 1 or more selected GameObjects do not have a FireController.\n" + "This is just a note, not an error. The option above will still apply to " + "GameObjects which do have a FireController", MessageType.Info ); EditorGUI.indentLevel -= 1; } } GUILayout.Space(6); content = new GUIContent ( "LOS Test Mode", "Choose a test mode." ); EditorGUILayout.PropertyField(this.testMode, content); GUILayout.Space(4); content = new GUIContent ( "Debug Level", "Set it higher to see more verbose information." ); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } }<file_sep>using UnityEngine; using System.Collections; public class BulletPlayer : MonoBehaviour { public int basicHP, hp; public float angle = 0; public float angleRate = 0; public float speed = 0; public float speedRate = 0; float rad; Transform tr; SpawnCtrl sc; void Awake() { tr = GetComponent<Transform>(); sc = GetComponent<SpawnCtrl>(); } void OnEnable() { hp = basicHP; } public void HpManager(int num) { hp += num; if (hp <= 0) { sc.SetActives(); } float percent = (hp / (float)basicHP) * 100; if (percent > 0) { tr.localScale = new Vector3(1 * percent / 100, 1 * percent / 100, 1); } } void Update() { rad = angle * Mathf.PI * 2; tr.position += new Vector3((speed * Mathf.Cos(rad) * Time.deltaTime), (speed * Mathf.Sin(rad) * Time.deltaTime), 0); angle += angleRate; speed += speedRate; } void OnTriggerEnter2D(Collider2D col) { if (col.tag.Contains ("Bullet") && (gameObject.tag != col.tag)) { if (col.GetComponent<Bullet> () == null) col.GetComponent<PlacedBullet> ().HpManager (-hp); else col.GetComponent<Bullet> ().HpManager (-hp); HpManager (-hp); } if (col.CompareTag ("Boss")) { col.GetComponent<BossInfo> ().HpManager (-hp); sc.SetActives (); } } } <file_sep>using UnityEngine; using System.Collections; public class PlayerControl : MonoBehaviour { public static PlayerControl instance; //이동을 제어합니다. public float h, v; public bool inputed = true; //이동 속도 public float basicSpeed, moveSpeed; //총알 정보 public Transform bulletPos; DirectionalShooter dr; Transform tr; Rigidbody2D ri; //Animator ani; void Awake() { if (instance == null) instance = this; tr = GetComponent<Transform>(); ri = GetComponent<Rigidbody2D>(); dr = GetComponent<DirectionalShooter>(); //ani = GetComponent<Animator>(); } void Update() { if (inputed) { //4방향 키를 기준을 이동합니다. if (Input.GetKey(KeyCode.W)) { print("1"); h = 1; } else if (Input.GetKey(KeyCode.S)) { print("-1"); h = -1; } else { h = 0; } if (Input.GetKey(KeyCode.A)) { v = -1; } else if (Input.GetKey(KeyCode.D)) { v = 1; } else { v = 0; } if (Input.GetKey(KeyCode.Space)) { dr.canShoot = true; } } } void FixedUpdate() { if (inputed) { Move(); } } void Move() { tr.position += new Vector3(v * moveSpeed * Time.deltaTime, h * moveSpeed * Time.deltaTime, 0); } public void SetInputed(bool b) { inputed = b; } }<file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System.Collections.Generic; using UnityEngine; namespace EnergyBarToolkit { public class EnergyBarOnGUIInspectorBase : EnergyBarInspectorBase { protected List<Texture2D> BackgroundTextures() { return TexturesOf((target as EnergyBarOnGUIBase).texturesBackground); } protected List<Texture2D> ForegroundTextures() { return TexturesOf((target as EnergyBarOnGUIBase).texturesForeground); } } } // namespace<file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// This enemy will change size and color depending on one of three states: /// 1. Not detected: red (or original color) /// 2. Detected by a TargetTracker Area: yellow /// 3. The active target of a TargetTracker determined by sort and number: green /// </summary> public class DemoEnemyMultiState : MonoBehaviour { public int life = 100; public ParticleSystem explosion; // States protected enum STATES { Dead, NotDetected, Detected, ActiveTarget } protected STATES currentState = STATES.NotDetected; protected bool isUpdateWhileTrackedRunning = false; // Cache... protected Vector3 activeTargetScale = new Vector3(2, 2, 2); protected Color startingColor; protected Targetable targetable; protected List<TargetTracker> detectingTrackers = new List<TargetTracker>(); protected void Awake() { this.startingColor = this.GetComponent<Renderer>().material.color; this.targetable = this.GetComponent<Targetable>(); this.targetable.AddOnDetectedDelegate(this.OnDetected); this.targetable.AddOnNotDetectedDelegate(this.OnNotDetected); this.targetable.AddOnHitDelegate(this.OnHit); } protected void OnHit(EventInfoList infoList, Target target) { // If dead, then all done! Will also interupt the co-routine. if (this.currentState == STATES.Dead) return; if (target.collider != null) Debug.Log(this.name + " was hit by 3D collider on " + target.collider.name); #if (!UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2) // Unity 4.3+ only... if (target.collider2D != null) Debug.Log(this.name + " was hit by 2D collider on " + target.collider2D.name); #endif foreach (EventInfo info in infoList) { switch (info.name) { case "Damage": this.life -= (int)info.value; break; } } if (this.life <= 0) { this.SetState(STATES.Dead); Instantiate ( this.explosion.gameObject, this.transform.position, this.transform.rotation ); Destroy(this.gameObject); } } protected void OnDetected(TargetTracker source) { this.detectingTrackers.Add(source); // Start a co-routine for each TargetTracker that detects this if (!this.isUpdateWhileTrackedRunning) this.StartCoroutine(this.UpdateWhileTracked()); } protected void OnNotDetected(TargetTracker source) { this.detectingTrackers.Remove(source); } protected void SetState(STATES state) { // Only process state changes. // Once dead, never process state changes again. if (this.currentState == state || this.currentState == STATES.Dead) return; switch (state) { case STATES.Dead: // Just here to be explicit. Once Dead, this won't run again. See above. break; case STATES.NotDetected: this.transform.localScale = Vector3.one; this.GetComponent<Renderer>().material.color = this.startingColor; break; case STATES.Detected: this.GetComponent<Renderer>().material.color = Color.yellow; this.transform.localScale = this.activeTargetScale * 0.75f; break; case STATES.ActiveTarget: this.GetComponent<Renderer>().material.color = Color.green; this.transform.localScale = this.activeTargetScale; break; } this.currentState = state; } protected IEnumerator UpdateWhileTracked() { this.isUpdateWhileTrackedRunning = true; // Track the state change to figure out when not detected bool switchedToActive; // Quit if the targetable is no longer being tracked while (this.detectingTrackers.Count > 0) { if (this.currentState == STATES.Dead) yield break; // If dead, then all done! // If 1 TargetTracker is focused on this it is enough to // trigger the active state and break the loop. switchedToActive = false; foreach (TargetTracker tracker in this.detectingTrackers) { if (tracker.targets.Contains(new Target(this.targetable, tracker))) { this.SetState(STATES.ActiveTarget); switchedToActive = true; break; } } if (!switchedToActive) this.SetState(STATES.Detected); yield return null; } this.SetState(STATES.NotDetected); this.isUpdateWhileTrackedRunning = false; } } }<file_sep>using UnityEngine; using System.Collections; using System; using UnityEngine.UI; [Serializable] public class SkillInfo { public int idx; public bool isActive = false; public Sprite sprSkillActiveImage; public Sprite sprSkillDeActiveImage; public Image imgSkillSlot; public int coolTime; public SkillCalculator skillCalculator; public ISkill skill; } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System; using System.Collections.Generic; using UnityEngine; namespace EnergyBarToolkit { [SelectionBase] [ExecuteInEditMode] [RequireComponent(typeof(EnergyBar))] public class RepeatedRendererUGUI : EnergyBarUGUIBase { #region Public Fields public SpriteTex spriteIcon = new SpriteTex(); public SpriteTex spriteSlot = new SpriteTex(); public int repeatCount = 5; public Vector2 repeatPositionDelta = new Vector2(32, 0); public GrowType growType; public GrowDirection growDirection; // blink effect public bool effectBlink = false; public float effectBlinkValue = 0.2f; public float effectBlinkRatePerSecond = 1f; public Color effectBlinkColor = new Color(1, 1, 1, 0); public BlinkOperator effectBlinkOperator = BlinkOperator.LessOrEqual; /// <summary> /// Set this to true if you want your bar blinking regardless of blinking effect configuration. /// Bar will be blinking until this value is set to false. /// </summary> public bool forceBlinking { get; set; } #endregion #region Private Fields [SerializeField] private int lastRebuildHash; private bool dirty; [SerializeField] private List<Image2> slotImages = new List<Image2>(32); [SerializeField] private List<Image2> iconImages = new List<Image2>(32); [SerializeField] private List<Vector2> originPositions = new List<Vector2>(32); [SerializeField] private Vector2 sizeOrigin; [SerializeField] private Vector2 scaleRatio = Vector2.one; private bool Blink { get; set; } // return current bar color based on color settings and effect private float _effectBlinkAccum; #endregion #region Properties private Color IconTintTransparent { get { return new Color(spriteIcon.color.r, spriteIcon.color.g, spriteIcon.color.g, 0); } } #endregion #region Public Methods public override void SetNativeSize() { if (spriteIcon == null) { // try to create the bar now Rebuild(); if (spriteIcon == null) { Debug.LogWarning("Cannot resize bar that has not been created yet"); return; } } var nativeSize = ComputeNativeSize(); SetSize(rectTransform, nativeSize); } private Vector2 ComputeNativeSize() { if (spriteIcon.sprite == null) { return Vector2.zero; } int iw = Mathf.RoundToInt(spriteIcon.sprite.rect.width); int ih = Mathf.RoundToInt(spriteIcon.sprite.rect.height); int w = (int) (iw + Mathf.Abs(repeatPositionDelta.x * (repeatCount - 1))); int h = (int) (ih + Mathf.Abs(repeatPositionDelta.y * (repeatCount - 1))); return new Vector2(w, h); } /// <summary> /// Gets the generated icon image. Note that if you want to modify the image, you have to do it /// after this component Update() function. To do this, please adjust script execution order: /// http://docs.unity3d.com/Manual/class-ScriptExecution.html /// </summary> /// <param name="index">Icon index</param> /// <returns>Icon image.</returns> public Image2 GetIconImage(int index) { return iconImages[index]; } /// <summary> /// Gets the generated slot image. Note that if you want to modify the image, you have to do it /// after this component Update() function. To do this, please adjust script execution order: /// http://docs.unity3d.com/Manual/class-ScriptExecution.html /// </summary> /// <param name="index">Slot index</param> /// <returns>Slot image.</returns> public Image2 GetSlotImage(int index) { return slotImages[index]; } /// <summary> /// Gets total icon count. /// </summary> /// <returns>Total icon count.</returns> public int GetIconCount() { return repeatCount; } /// <summary> /// Gets the number of icons painted at full visibility (full value). /// </summary> /// <returns>Full visiblity icon count.</returns> public int GetFullyVisibleIconCount() { float displayIconCountF = ValueF2 * repeatCount; return (int)Mathf.Floor(displayIconCountF); // icons painted at full visibility } /// <summary> /// Gets the number of icons painted including the last one that can be not fully visible. /// </summary> /// <returns>Get the number of painted icons.</returns> public int GetVisibleIconCount() { float displayIconCountF = ValueF2 * repeatCount; return (int)Mathf.Ceil(displayIconCountF); } #endregion #region Unity Methods protected override void Update() { base.Update(); UpdateRebuild(); UpdateBar(); UpdateBlinkEffect(); UpdateVisible(); UpdateSize(); } void OnValidate() { repeatCount = Mathf.Max(1, repeatCount); } #endregion #region Update Methods void UpdateBar() { if (iconImages.Count == 0) { return; } float displayIconCountF = ValueF2 * repeatCount; int visibleIconCount = (int)Mathf.Floor(displayIconCountF); // icons painted at full visibility float middleIconValue = displayIconCountF - visibleIconCount; for (int i = 0; i < repeatCount; ++i) { var icon = iconImages[i]; if (slotImages.Count > 0) { var slot = slotImages[i]; UpdateSlot(slot); } if (i < visibleIconCount) { // this is visible sprite SetIconVisible(icon); } else if (i > visibleIconCount) { // this is invisible sprite SetIconInvisible(icon); } else { // this is partly-visible sprite switch (growType) { case GrowType.None: if (Mathf.Approximately(middleIconValue, 0)) { SetIconInvisible(icon); } else { SetIconVisible(icon); } break; case GrowType.Fade: SetIconVisible(icon); icon.color = Color.Lerp(IconTintTransparent, spriteIcon.color, middleIconValue); break; case GrowType.Grow: SetIconVisible(icon, middleIconValue); break; case GrowType.Fill: SetIconVisible(icon); icon.growDirection = growDirection; icon.fillValue = middleIconValue; break; default: Debug.Log("Unknown grow type: " + growType); break; } } } } void UpdateSize() { if (spriteIcon.sprite == null) { return; } var nativeSize = ComputeNativeSize(); var currentSize = rectTransform.rect.size; scaleRatio = new Vector2(currentSize.x / nativeSize.x, currentSize.y / nativeSize.y); var spriteRect = spriteIcon.sprite.rect; for (int i = 0; i < iconImages.Count; i++) { var originPosition = originPositions[i]; var iconImage = iconImages[i]; UpdateSpriteSize(originPosition, iconImage, spriteRect); } for (int i = 0; i < slotImages.Count; i++) { var originPosition = originPositions[i]; var slotImage = slotImages[i]; UpdateSpriteSize(originPosition, slotImage, spriteRect); } } private void UpdateSpriteSize(Vector2 originPosition, Image2 image, Rect spriteRect) { float posX = originPosition.x * scaleRatio.x; float posY = originPosition.y * scaleRatio.y; MadTransform.SetLocalPosition(image.rectTransform, new Vector3(posX, posY)); SetSize(image.rectTransform, new Vector2(spriteRect.width * scaleRatio.x, spriteRect.height * scaleRatio.y)); } void SetIconVisible(Image2 image, float scale = 1) { image.color = ComputeColor(spriteIcon.color); image.fillValue = 1; MadTransform.SetLocalScale(image.transform, new Vector3(scale, scale, scale)); image.enabled = true; } void UpdateSlot(Image2 image) { if (image != null) { image.color = ComputeColor(spriteSlot.color); } } void SetIconInvisible(Image2 image) { image.enabled = false; } void UpdateVisible() { bool visible = IsVisible(); if (!visible) { // make all sprites invisible // no need to make the oposite, sprites are visible by default for (int i = 0; i < iconImages.Count; ++i) { var iconImage = iconImages[i]; iconImage.enabled = false; } for (int i = 0; i < slotImages.Count; i++) { var slotImage = slotImages[i]; slotImage.enabled = false; } } else { // set icons visibility based on blinking effect if (Blink) { for (int i = 0; i < iconImages.Count; ++i) { var iconImage = iconImages[i]; iconImage.enabled = false; } } } } private void UpdateBlinkEffect() { if (forceBlinking) { Blink = EnergyBarCommons.Blink(effectBlinkRatePerSecond, ref _effectBlinkAccum); } else if (CanBlink()) { Blink = EnergyBarCommons.Blink(effectBlinkRatePerSecond, ref _effectBlinkAccum); } else { Blink = false; } } private bool CanBlink() { if (!effectBlink) { return false; } switch (effectBlinkOperator) { case BlinkOperator.LessThan: return ValueF2 < effectBlinkValue; case BlinkOperator.LessOrEqual: return ValueF2 <= effectBlinkValue; case BlinkOperator.GreaterThan: return ValueF2 > effectBlinkValue; case BlinkOperator.GreaterOrEqual: return ValueF2 >= effectBlinkValue; default: throw new ArgumentOutOfRangeException(); } } #endregion #region Rebuild Methods private void UpdateRebuild() { if (RebuildNeeded()) { Rebuild(); } } private bool RebuildNeeded() { if (iconImages.Count == 0 && spriteIcon != null && repeatCount != 0) { return true; } if (iconImages.Count > 0 && iconImages[0] == null) { // this can happen when user executes a undo operation return true; } int ch = MadHashCode.FirstPrime; ch = MadHashCode.Add(ch, spriteIcon); ch = MadHashCode.Add(ch, spriteSlot); ch = MadHashCode.Add(ch, repeatCount); ch = MadHashCode.Add(ch, repeatPositionDelta); ch = MadHashCode.Add(ch, rectTransform.pivot); if (ch != lastRebuildHash || dirty) { lastRebuildHash = ch; dirty = false; return true; } else { return false; } } private void Rebuild() { RemoveCreatedChildren(); iconImages.Clear(); slotImages.Clear(); originPositions.Clear(); BuildIconsAndSlots(); MoveLabelToTop(); } private void BuildIconsAndSlots() { Vector2 min = Vector2.zero; Vector2 max = Vector2.zero; bool hasMinMax = false; for (int i = 0; i < repeatCount; ++i) { // slot if (spriteSlot.sprite != null) { var slot = CreateChild<Image2>(string.Format("slot_{0:D2}", i + 1)); slot.sprite = spriteSlot.sprite; slot.color = spriteSlot.color; slot.material = spriteSlot.material; slot.transform.localPosition = repeatPositionDelta * i; //slot.transform.localPosition += LocalIconOffset slotImages.Add(slot); Expand(ref min, ref max, ref hasMinMax, slot.rectTransform); } // icon if (spriteIcon.sprite != null) { var icon = CreateChild<Image2>(string.Format("icon_{0:D2}", i + 1)); icon.sprite = spriteIcon.sprite; icon.color = spriteIcon.color; icon.material = spriteIcon.material; icon.transform.localPosition = repeatPositionDelta * i; iconImages.Add(icon); Expand(ref min, ref max, ref hasMinMax, icon.rectTransform); } } // set the size sizeOrigin = ComputeNativeSize(); SetNativeSize(); // compute offset Vector2 offset = new Vector2( 0.5f * sizeOrigin.x - (rectTransform.pivot.x * sizeOrigin.x), 0.5f * sizeOrigin.y - (rectTransform.pivot.y * sizeOrigin.y)); Vector2 startPos = -repeatPositionDelta * (repeatCount - 1) * 0.5f; // reposition again for (int i = 0; i < slotImages.Count; i++) { var slotImage = slotImages[i]; slotImage.rectTransform.localPosition = repeatPositionDelta * i + (startPos + offset); } for (int i = 0; i < iconImages.Count; i++) { var iconImage = iconImages[i]; iconImage.rectTransform.localPosition = repeatPositionDelta * i + (startPos + offset); originPositions.Add(iconImage.rectTransform.localPosition); } if (scaleRatio != Vector2.one) { var targetSize = rectTransform.rect.size; targetSize.x *= scaleRatio.x; targetSize.y *= scaleRatio.y; SetSize(rectTransform, targetSize); UpdateSize(); } } private void Expand(ref Vector2 min, ref Vector2 max, ref bool hasMinMax, RectTransform tr) { var rect = tr.rect; float xMin = rect.xMin + tr.localPosition.x; float xMax = rect.xMax + tr.localPosition.x; float yMin = rect.yMin + tr.localPosition.y; float yMax = rect.yMax + tr.localPosition.y; if (!hasMinMax) { min.x = xMin; min.y = yMin; max.x = xMax; max.y = yMax; hasMinMax = true; } else { if (xMin < min.x) { min.x = xMin; } if (yMin < min.y) { min.y = yMin; } if (xMax > max.x) { max.x = xMax; } if (yMax > max.y) { max.y = yMax; } } } #endregion #region Inner Types public enum GrowType { None, Grow, Fade, Fill } public enum BlinkOperator { LessThan, LessOrEqual, GreaterThan, GreaterOrEqual, } #endregion } } // namespace<file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Combines multiple TargetTrackers in to one. This is great for creating more complex shapes /// such as cross-streets or irregular structures. /// /// Simply create AreaTargetTrackers and add them to the targetTrackers list to combine them so /// they behave as a single Area. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Compound TargetTracker")] public class CompoundTargetTracker : TargetTracker { /// <summary> /// The TargetTrackers whos targets will be combined by this CompoundTargetTracker /// </summary> public List<TargetTracker> targetTrackers = new List<TargetTracker>(); /// <summary> /// A combined list of sorted targets from all of this CompoundTargetTracker's /// TargetTracker-members. The contents depend on numberOfTargets requested /// (-1 for all targets in the Area), any modifications done by any /// onPostSortDelegates, and the sorting style used. /// Getting targets every frame has virtually no overhead because all sorting is /// done when targets are set (TargetTracker is "dirty"). This can be triggered /// by a user, Area or internal co-routine. If at least 2 /// targets are available a co-routine is started to update the sort based on /// the sort interval. The co-routine will stop if the number of targets falls /// back under 2 /// </summary> public override TargetList targets { get { return base.targets; } set { this.combinedTargets.Clear(); for (int i = 0; i < this.targetTrackers.Count; i++) this.combinedTargets.AddRange(this.targetTrackers[i].targets); base.targets = this.combinedTargets; } } protected TargetList combinedTargets = new TargetList(); /// <summary> /// Refresh targets, sorting, event memberships, etc. /// Setting this to false does nothing. /// </summary> /// <value> /// Always false because setting to true is handled immediatly. /// </value> public override bool dirty { get { return false; } set { #if UNITY_EDITOR // Stop inspector logic from running this if (!Application.isPlaying) return; #endif // Make sure all trackers have events registered. Events are only added once. for (int i = 0; i < this.targetTrackers.Count; i++) { this.targetTrackers[i].AddOnTargetsChangedDelegate(this.OnTargetsChanged); this.targetTrackers[i].AddOnNewDetectedDelegate(this.OnTrackersNew); } // Trigger re-sort, etc (runs this.targets setter) base.dirty = value; } } /// <summary> /// CompoundTargetTrackers do not support targetLayers because they delegate detection /// to their list of TargetTrackers /// </summary> /// <exception cref='System.NotImplementedException'> /// Is thrown when get or set. /// </exception> public new LayerMask targetLayers { get { string msg = "CompoundTargetTrackers do not support targetLayers because they " + "delegate detection to their list of TargetTrackers"; throw new System.NotImplementedException(msg); } set { string msg = "CompoundTargetTrackers do not support targetLayers because they " + "delegate detection to their list of TargetTrackers"; throw new System.NotImplementedException(msg); } } /// <summary> /// When this CompoundTargetTracker is enabled, which also runs right after Awake(), /// cause it to refresh its targets, sorting, event memberships, etc /// </summary> protected override void OnEnable() { this.dirty = true; } /// <summary> /// If this CompoundTargetTracker is disabled, un-register its delegates from all /// of its targetTrackers; /// </summary> protected void OnDisable() { for (int i = 0; i < this.targetTrackers.Count; i++) { this.targetTrackers[i].RemoveOnTargetsChangedDelegate(this.OnTargetsChanged); this.targetTrackers[i].RemoveOnNewDetectedDelegate(this.OnTrackersNew); } } /// <summary> /// Causes this CompoundTargetTracker to refresh its targets, sorting, event /// memberships, etc. when any of its trackers trigger this delegate /// </summary> protected void OnTargetsChanged(TargetTracker source) { this.batchDirty = true; } /// <summary> /// Provide the same event interface as other TargetTrackers. This one is triggerd /// when any of its trackers are triggered. /// </summary> /// <param name='source'> /// The TargetTracker that triggered the current call. /// </param> /// <param name='target'> /// The Target that was detected and triggered the current call. /// </param> protected bool OnTrackersNew(TargetTracker source, Target target) { if (this.onNewDetectedDelegates == null) return true; // If keeping the target, the post sort delegate will trigger this.dirty = true; return this.onNewDetectedDelegates(this, target); } } }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Adds Line-of-Sight (LOS) filtering to TargetPRO components. Line of sight means /// events are based on whether or not a target can be "seen". This visibility test /// is done by ray casting against a given layer. If the ray is broken before hitting /// the target, the target is not in LOS. /// /// If added to the same GameObject as a TargetTracker it can filter out any targets /// which are not currently in LOS. /// /// If added to the same GameObject as a FireController it can prevent firing on any /// targets which are not currently in LOS. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Modifier - Line of Sight")] public class LineOfSightModifier : TriggerEventProModifier { #region Parameters public LayerMask targetTrackerLayerMask; public LayerMask fireControllerLayerMask; public enum TEST_MODE { SinglePoint, BoundingBox } public TEST_MODE testMode = TEST_MODE.SinglePoint; public float radius = 1.0f; public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; #endregion Parameters #region Cache // Public for reference and Inspector logic public TargetTracker tracker; public EventFireController fireCtrl; #endregion Cache protected void Awake() { this.tracker = this.GetComponent<TargetTracker>(); this.fireCtrl = this.GetComponent<EventFireController>(); } // OnEnable and OnDisable add the check box in the inspector too. protected void OnEnable() { if (this.tracker != null) this.tracker.AddOnPostSortDelegate(this.FilterTrackerTargetList); if (this.fireCtrl != null) this.fireCtrl.AddOnPreFireDelegate(this.FilterFireTargetList); } protected void OnDisable() { if (this.tracker != null) this.tracker.RemoveOnPostSortDelegate(this.FilterTrackerTargetList); if (this.fireCtrl != null) this.fireCtrl.RemoveOnPreFireDelegate(this.FilterFireTargetList); } protected void FilterTrackerTargetList(TargetTracker source, TargetList targets) { // Quit if the mask is set to nothing == OFF if (this.targetTrackerLayerMask.value == 0) return; Vector3 fromPos; if (this.tracker.area != null) fromPos = this.tracker.area.transform.position; else fromPos = this.tracker.transform.position; LayerMask mask = this.targetTrackerLayerMask; this.FilterTargetList(targets, mask, fromPos, Color.red); } protected void FilterFireTargetList(TargetList targets) { // Quit if the mask is set to nothing == OFF if (this.fireControllerLayerMask.value == 0) return; Vector3 fromPos; if (this.fireCtrl.spawnEventTriggerAtTransform != null) fromPos = this.fireCtrl.spawnEventTriggerAtTransform.position; else fromPos = this.fireCtrl.transform.position; LayerMask mask = this.fireControllerLayerMask; this.FilterTargetList(targets, mask, fromPos, Color.yellow); } protected void FilterTargetList(TargetList targets, LayerMask mask, Vector3 fromPos, Color debugLineColor) { #if UNITY_EDITOR var debugRemoveNames = new List<string>(); #endif Vector3 toPos; bool isNotLOS; var iterTargets = new List<Target>(targets); Collider2D targetColl2D; Collider targetColl; Vector3 ext; bool use2d; foreach (Target target in iterTargets) { use2d = target.targetable.coll2D != null; isNotLOS = false; if (this.testMode == TEST_MODE.BoundingBox) { if (use2d) { targetColl2D = target.targetable.coll2D; ext = targetColl2D.bounds.extents * 0.5f; } else { targetColl = target.targetable.coll; ext = targetColl.bounds.extents * 0.5f; } // This solution works with rotation pretty well Matrix4x4 mtx = target.targetable.transform.localToWorldMatrix; var bboxPnts = new Vector3[8]; bboxPnts[0] = mtx.MultiplyPoint3x4(ext); bboxPnts[1] = mtx.MultiplyPoint3x4(new Vector3(-ext.x, ext.y, ext.z)); bboxPnts[2] = mtx.MultiplyPoint3x4(new Vector3(ext.x, ext.y, -ext.z)); bboxPnts[3] = mtx.MultiplyPoint3x4(new Vector3(-ext.x, ext.y, -ext.z)); bboxPnts[4] = mtx.MultiplyPoint3x4(new Vector3(ext.x, -ext.y, ext.z)); bboxPnts[5] = mtx.MultiplyPoint3x4(new Vector3(-ext.x, -ext.y, ext.z)); bboxPnts[6] = mtx.MultiplyPoint3x4(new Vector3(ext.x, -ext.y, -ext.z)); bboxPnts[7] = mtx.MultiplyPoint3x4(-ext); for (int i = 0; i < bboxPnts.Length; i++) { if (use2d) isNotLOS = Physics2D.Linecast(fromPos, bboxPnts[i], mask); else isNotLOS = Physics.Linecast(fromPos, bboxPnts[i], mask); // Quit loop at first positive test if (isNotLOS) { #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine(fromPos, bboxPnts[i], debugLineColor, 0.01f); #endif continue; } else break; } } else { toPos = target.targetable.transform.position; if (use2d) isNotLOS = Physics2D.Linecast(fromPos, toPos, mask); else isNotLOS = Physics.Linecast(fromPos, toPos, mask); #if UNITY_EDITOR if (isNotLOS && this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine(fromPos, toPos, debugLineColor, 0.01f); #endif } if (isNotLOS) { targets.Remove(target); #if UNITY_EDITOR debugRemoveNames.Add(target.targetable.name); #endif } } #if UNITY_EDITOR if (this.debugLevel == DEBUG_LEVELS.High && debugRemoveNames.Count > 0) Debug.Log("Holding fire for LOS: " + string.Join(",", debugRemoveNames.ToArray())); #endif } } }<file_sep>using UnityEngine; using System.Collections; public class Skill2GusleMaker : MonoBehaviour, ISkill { public status skillset; public float movSpeed, waitTime, standTime; public GameObject gusle; GameObject tmp; Gulse ltmp; void Start() { //StartCoroutine("Delay"); UseSkill(); } public void SetSkill(int damage, float range, float reload, float movSpeed, float waitTime, float standTime) { skillset.damage = damage; skillset.distance = range; skillset.reload = reload; this.movSpeed = movSpeed; this.waitTime = waitTime; this.standTime = standTime; } public void UseSkill() { for (int i = 0; i < 2; i++) { tmp = Instantiate(gusle, transform.position, Quaternion.Euler(0,0,180 * i)) as GameObject; ltmp = tmp.GetComponent<Gulse>(); ltmp.dmg = skillset.damage; ltmp.range = skillset.distance; ltmp.movSpeed = movSpeed; ltmp.waitTime = waitTime; ltmp.standTime = standTime; } } IEnumerator Delay() { while (true) { yield return new WaitForSeconds(skillset.reload); UseSkill(); } } } <file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using PathologicalGames; [CustomEditor(typeof(CompoundTargetTracker)), CanEditMultipleObjects] public class CompoundTargetTrackerInspector : Editor { protected SerializedProperty debugLevel; protected SerializedProperty numberOfTargets; protected SerializedProperty sortingStyle; protected SerializedProperty updateInterval; protected SerializedProperty targetTrackers; protected void OnEnable() { this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.numberOfTargets = this.serializedObject.FindProperty("numberOfTargets"); this.sortingStyle = this.serializedObject.FindProperty("_sortingStyle"); this.updateInterval = this.serializedObject.FindProperty("updateInterval"); this.targetTrackers = this.serializedObject.FindProperty("targetTrackers"); } public override void OnInspectorGUI() { this.serializedObject.Update(); GUIContent content; EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; Object[] targetObjs = this.serializedObject.targetObjects; CompoundTargetTracker curEditTarget; EditorGUILayout.PropertyField(this.numberOfTargets, new GUIContent("Targets (-1 for all)")); EditorGUI.BeginChangeCheck(); content = new GUIContent("Sorting Style", "The style of sorting to use"); EditorGUILayout.PropertyField(this.sortingStyle, content); var sortingStyle = (TargetTracker.SORTING_STYLES)this.sortingStyle.enumValueIndex; // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (CompoundTargetTracker)targetObjs[i]; Undo.RecordObject(curEditTarget, targetObjs[0].GetType() + " sortingStyle"); curEditTarget.sortingStyle = sortingStyle; } } if (sortingStyle != TargetTracker.SORTING_STYLES.None) { EditorGUI.indentLevel += 1; content = new GUIContent( "Minimum Interval", "How often the target list will be sorted. If set to 0, " + "sorting will only be triggered when Targets enter or exit range." ); EditorGUILayout.PropertyField(this.updateInterval, content); EditorGUI.indentLevel -= 1; } GUILayout.Space(8); // If multi-selected, use Unity's display. Much easier in this case. if (serializedObject.isEditingMultipleObjects) { content = new GUIContent ( "TargetTrackers", "The TargetTrackers whos targets will be combined by this CompoundTargetTracker." ); EditorGUILayout.PropertyField(this.targetTrackers, content, true); } else { curEditTarget = (CompoundTargetTracker)targetObjs[0]; // Track changes so we only register undo entries when needed. EditorGUI.BeginChangeCheck(); var targetTrackersCopy = new List<TargetTracker>(curEditTarget.targetTrackers); PGEditorUtils.FoldOutObjList<TargetTracker> ( "TargetTrackers", targetTrackersCopy, true ); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(curEditTarget, targetObjs[0].GetType() + " targetTrackers"); curEditTarget.targetTrackers.Clear(); curEditTarget.targetTrackers.AddRange(targetTrackersCopy); } } GUILayout.Space(4); EditorGUILayout.BeginHorizontal(); content = new GUIContent ( "Show All Gizmos", "Click to force all TargetTracker gizmos to be visibile to visualize the Area " + "in the Editor." ); this.GizmoVisibilityButton(targetObjs, content, true); content = new GUIContent ( "Hide All Gizmos", "Click to force all TargetTracker gizmos to be hidden." ); this.GizmoVisibilityButton(targetObjs, content, false); EditorGUILayout.EndHorizontal(); GUILayout.Space(8); content = new GUIContent("Debug Level", "Set it higher to see more verbose information."); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } protected void GizmoVisibilityButton(Object[] targetObjs, GUIContent content, bool show) { bool pressed = GUILayout.Button(content); if (pressed) { List<TargetTracker> subtrackers = new List<TargetTracker>(); for (int i = 0; i < targetObjs.Length; i++) { var tracker = (CompoundTargetTracker)targetObjs[i]; subtrackers.AddRange(tracker.targetTrackers); } foreach (TargetTracker subtracker in subtrackers) { Undo.RecordObject(subtracker, subtracker.name + " drawGizmo"); subtracker.drawGizmo = show; } } } } <file_sep>using UnityEngine; using System.Collections; using PathologicalGames; /// <description> /// Some examples using the API. /// </description> public class ScriptedExample : MonoBehaviour { public float moveSpeed = 1; public float turnSpeed = 1; public float newDirectionInterval = 3; // Cache private SmoothLookAtConstraint lookCns; private TransformConstraint xformCns; private Transform xform; private void Awake() { this.xform = this.transform; // Cache // Add a transform constraint this.xformCns = this.gameObject.AddComponent<TransformConstraint>(); this.xformCns.noTargetMode = UnityConstraints.NO_TARGET_OPTIONS.SetByScript; this.xformCns.constrainRotation = false; // Add a smooth lookAt constraint this.lookCns = this.gameObject.AddComponent<SmoothLookAtConstraint>(); this.lookCns.noTargetMode = UnityConstraints.NO_TARGET_OPTIONS.SetByScript; this.lookCns.pointAxis = Vector3.up; this.lookCns.upAxis = Vector3.forward; this.lookCns.speed = this.turnSpeed; // Start some co-routines to illustrate SetByScript this.StartCoroutine(this.LookAtRandom()); this.StartCoroutine(this.MoveRandom()); } private IEnumerator MoveRandom() { // Wait one time for the other o-routine to start up yield return new WaitForSeconds(this.newDirectionInterval + 0.001f); while (true) { yield return null; // Lets do something a little tricky and move towards the position // set in the lookat constraint. This will change when the other // co-routine does. // Note this doesn't create a smooth-follow where the object takes a // nice rounded path to the target position. That would be better // accomplished by moving straght forward and letting the // SmoothLookAt constraint change the orientation over time. // Get a vector from here to the target position Vector3 targetDirection = this.lookCns.position - this.xform.position; Vector3 moveVect = targetDirection.normalized * this.moveSpeed * 0.1f; this.xformCns.position = this.xform.position + moveVect; Debug.DrawRay(this.xform.position, this.xform.up*2, Color.grey); Debug.DrawRay(this.xform.position, targetDirection.normalized * 2, Color.green); } } // Look in a different (random) direction every X seconds... private IEnumerator LookAtRandom() { while (true) { yield return new WaitForSeconds(this.newDirectionInterval); // Get a random position in a sphere volume // *100 will set the result farther away for the other co-routine's use Vector3 randomPosition = Random.insideUnitSphere * 100; // Set the constraints internal target position // Move the random result so it is based around this object this.lookCns.position = randomPosition + this.xform.position; } } } <file_sep>/// <Licensing> /// ©2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; using PathologicalGames; namespace PathologicalGames { /// <summary> /// Handles target notification directly, or by spawning an EventTrigger instance, when the /// given parameters are met. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO EventFireController")] public class EventFireController : MonoBehaviour { #region Public Parameters /// <summary> /// The interval in seconds between firing. /// </summary> public float interval; /// <summary> /// When true this controller will fire immediately when it first finds a target, then /// continue to count the interval normally. /// </summary> public bool initIntervalCountdownAtZero = true; /// <summary> /// Sets the target notification behavior. Telling targets they are hit is optional /// for situations where a delayed response is required, such as launching a projectile, /// or for custom handling. /// /// MODES: /// \par Off /// Do not notify anything. delegates can still be used for custom handling /// \par Direct /// OnFire targets will be notified of this controllers eventInfo /// \par PassInfoToEventTrigger /// OnFire, For every Target hit, a new EventTrigger will be spawned and passed /// this EventTrigger's EventInfo. /// \par UseEventTriggerInfo /// Same as PassInfoToEventTrigger but the new EventTrigger will use its own /// EventInfo (this EventFireController's EventInfo will be ignored). /// </summary> public NOTIFY_TARGET_OPTIONS notifyTargets = NOTIFY_TARGET_OPTIONS.Direct; public enum NOTIFY_TARGET_OPTIONS { Off, Direct, PassInfoToEventTrigger, UseEventTriggerInfo } /// <summary> /// An optional EventTrigger to spawn OnFire depending on notifyTarget's /// NOTIFY_TARGET_OPTIONS. /// </summary> public EventTrigger eventTriggerPrefab; /// <summary> /// If false, do not add the new instance to a pool. Use Unity's Instantiate/Destroy /// </summary> public bool usePooling = true; /// <summary> /// The name of a pool to be used with PoolManager or other pooling solution. /// If not using pooling, this will do nothing and be hidden in the Inspector. /// WARNING: If poolname is set to "", Pooling will be disabled and Unity's /// Instantiate will be used. /// </summary> public string eventTriggerPoolName = "EventTriggers"; /// <summary> /// If an eventTriggerPrefab is spawned, setting this to true will override the /// EventTrigger's poolName and use this instead. The instance will also be passed /// this FireController's eventTriggerPoolName to be used when the EventTrigger is /// desapwned. /// </summary> public bool overridePoolName = false; /// <summary> /// A list of EventInfo structs which hold one or more descriptions /// of how a Target can be affected. To alter this from code. Get the list, edit it, then /// set the whole list back. (This cannot be edited "in place"). /// </summary> // Encodes / Decodes EventInfos to and from EventInfoGUIBackers public EventInfoList eventInfoList { get { var returnInfoList = new EventInfoList(); foreach (EventInfoListGUIBacker infoBacker in this._eventInfoList) { // Create and add a struct-form of the backing-field instance returnInfoList.Add ( new EventInfo { name = infoBacker.name, value = infoBacker.value, duration = infoBacker.duration, } ); } return returnInfoList; } set { // Clear and set the backing-field list also used by the GUI this._eventInfoList.Clear(); EventInfoListGUIBacker eventInfoBacker; foreach (var info in value) { eventInfoBacker = new EventInfoListGUIBacker(info); this._eventInfoList.Add(eventInfoBacker); } } } /// <summary> /// Public for Inspector use only. /// </summary> public List<EventInfoListGUIBacker> _eventInfoList = new List<EventInfoListGUIBacker>(); /// <summary> /// This transform is optionally used as the position at which an EventTrigger prefab is /// spawned from. Some Utility components may also use this as a position reference if /// chosen. /// </summary> public Transform spawnEventTriggerAtTransform { get { if (this._spawnEventTriggerAtTransform == null) return this.transform; else return this._spawnEventTriggerAtTransform; } set { this._spawnEventTriggerAtTransform = value; } } [SerializeField] // protected backing fields must be serializeable. protected Transform _spawnEventTriggerAtTransform = null; // Explicit for clarity /// <summary> /// Turn this on to print a stream of messages to help you see what this /// FireController is doing /// </summary> public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; /// <summary> /// The current counter used for firing. Gets reset at the interval when /// successfully fired, otherwise will continue counting down in to negative /// numbers /// </summary> public float fireIntervalCounter = 99999; /// <summary> /// This FireController's TargetTracker. Defaults to one on the same GameObject. /// </summary> public TargetTracker targetTracker; // Delegate type declarations public delegate void OnStartDelegate(); public delegate void OnUpdateDelegate(); public delegate void OnTargetUpdateDelegate(TargetList targets); public delegate void OnIdleUpdateDelegate(); public delegate void OnStopDelegate(); public delegate void OnPreFireDelegate(TargetList targets); public delegate void OnFireDelegate(TargetList targets); public delegate void OnEventTriggerSpawnedDelegate(EventTrigger eventTrigger); // Keeps the state of each individual foldout item during the editor session public Dictionary<object, bool> _editorListItemStates = new Dictionary<object, bool>(); #endregion Public Parameters #region cache protected TargetList targets = new TargetList(); protected TargetList targetsCopy = new TargetList(); // Emtpy delegate used for collection of user added/removed delegates protected OnStartDelegate onStartDelegates; protected OnUpdateDelegate onUpdateDelegates; protected OnTargetUpdateDelegate onTargetUpdateDelegates; protected OnIdleUpdateDelegate onIdleUpdateDelegates; protected OnStopDelegate onStopDelegates; protected OnPreFireDelegate onPreFireDelegates; protected OnFireDelegate onFireDelegates; protected OnEventTriggerSpawnedDelegate onEventTriggerSpawnedDelegates; #endregion Pcache #region Events protected bool keepFiring = false; /// <summary> /// Turn on the firing system when this component is enabled, which includes /// creation /// </summary> protected void OnEnable() { this.StartCoroutine(this.FiringSystem()); // Start event is inside this } /// <summary> /// Turn off the firing system if this component is disabled or destroyed /// </summary> protected void OnDisable() { // This has to be here because if it is in the TargetingSystem coroutine // when the coroutine is stopped, it will get skipped, not ran last. this.OnStop(); // EVENT TRIGGER } /// <summary> /// Runs once when when the targeting system starts up. This happens OnEnable(), /// which includes destroying this component /// </summary> protected void OnStart() { #if UNITY_EDITOR // Higest level debug if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = "Starting Firing System..."; Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif if (this.onStartDelegates != null) this.onStartDelegates(); } /// <summary> /// Runs each frame while the targeting system is active, no matter what. /// </summary> protected void OnUpdate() { if (this.onUpdateDelegates != null) this.onUpdateDelegates(); } /// <summary> /// Runs each frame while tracking a target. This.targets is not empty! /// </summary> protected void OnTargetUpdate(TargetList targets) { if (this.onTargetUpdateDelegates != null) this.onTargetUpdateDelegates(targets); } /// <summary> /// Runs each frame while tower is idle (no targets) /// </summary> protected void OnIdleUpdate() { if (this.onIdleUpdateDelegates != null) this.onIdleUpdateDelegates(); } /// <summary> /// Runs once when when the targeting system is stopped. This happens OnDisable(), /// which includes destroying this component /// </summary> protected void OnStop() { #if UNITY_EDITOR // Higest level debug if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = "stopping Firing System..."; Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif if (this.onStopDelegates != null) this.onStopDelegates(); this.keepFiring = false; // Actually stops the firing system } /// <summary> /// Fire on the targets /// </summary> protected void Fire() { #if UNITY_EDITOR // Log a message to show what is being fired on if (this.debugLevel > DEBUG_LEVELS.Off) { string[] names = new string[this.targets.Count]; for (int i = 0; i < this.targets.Count; i++) names[i] = this.targets[i].transform.name; string msg = string.Format ( "Firing on: {0}\nEventInfo: {1}", string.Join(", ", names), this.eventInfoList.ToString() ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif // // Create a new list of targets which have this fire controller reference. // var targetCopies = new TargetList(); Target newTarget; foreach (Target target in this.targets) { // Can't edit a struct in a foreach loop, so need to copy and store newTarget = new Target(target); newTarget.fireController = this; // Add reference. null before this targetCopies.Add(newTarget); } // Write the result over the old target list. This is for output so targets // which are handled at all by this target tracker are stamped with a // reference. this.targets = targetCopies; // // Hnadle delivery // foreach (Target target in this.targets) { switch (this.notifyTargets) { case NOTIFY_TARGET_OPTIONS.Direct: target.targetable.OnHit(this.eventInfoList, target); break; case NOTIFY_TARGET_OPTIONS.PassInfoToEventTrigger: this.SpawnEventTrigger(target, true); break; case NOTIFY_TARGET_OPTIONS.UseEventTriggerInfo: this.SpawnEventTrigger(target, false); break; } } #if UNITY_EDITOR // When in the editor, if debugging, draw a line to each hit target. if (this.debugLevel > DEBUG_LEVELS.Off && this.notifyTargets > NOTIFY_TARGET_OPTIONS.Off) { foreach (Target target in this.targets) Debug.DrawLine(this.spawnEventTriggerAtTransform.position, target.transform.position, Color.red); } #endif // Trigger the delegates if (this.onFireDelegates != null) this.onFireDelegates(this.targets); } protected void SpawnEventTrigger(Target target, bool passInfo) { // This is optional. If no eventTriggerPrefab is set, quit quietly if (this.eventTriggerPrefab == null) return; string poolName; if (!this.usePooling) poolName = ""; // Overloaded string "" to = pooling off else if (!this.overridePoolName) poolName = this.eventTriggerPrefab.poolName; else poolName = this.eventTriggerPoolName; Transform inst = PathologicalGames.InstanceManager.Spawn ( poolName, this.eventTriggerPrefab.transform, this.spawnEventTriggerAtTransform.position, this.spawnEventTriggerAtTransform.rotation ); var eventTrigger = inst.GetComponent<EventTrigger>(); // Pass informaiton eventTrigger.fireController = this; eventTrigger.target = target; eventTrigger.poolName = poolName; // Will be the correct pool name due to test above. if (passInfo) eventTrigger.eventInfoList = this.eventInfoList; if (this.onEventTriggerSpawnedDelegates != null) this.onEventTriggerSpawnedDelegates(eventTrigger); } #region Delegate Add/Set/Remove methods #region OnStartDelegates Add/Set/Remove /// <summary> /// Add a new delegate to be triggered when the firing system first starts up. /// This happens on OnEnable (which is also run after Awake when first instanced) /// The delegate signature is: delegate() /// See TargetTracker documentation for usage of the provided '...' /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnStartDelegate</param> public void AddOnStartDelegate(OnStartDelegate del) { this.onStartDelegates -= del; // Cheap way to ensure unique (add only once) this.onStartDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnStartDelegate() /// </summary> /// <param name="del">An OnStartDelegate</param> public void SetOnStartDelegate(OnStartDelegate del) { this.onStartDelegates = del; } /// <summary> /// Removes a OnDetectedDelegate /// See docs for AddOnStartDelegate() /// </summary> /// <param name="del">An OnStartDelegate</param> public void RemoveOnStartDelegate(OnStartDelegate del) { this.onStartDelegates -= del; } #endregion OnDetectedDelegates Add/Set/Remove #region OnUpdateDelegates Add/Set/Remove /// <summary> /// Add a new delegate to be triggered everyframe while active, no matter what. /// There are two events which are more specific to the two states of the system: /// 1. When Idle (No Target) - See the docs for OnIdleUpdateDelegate() /// 2. When There IS a target - See the docs for OnTargetUpdateDelegate() /// The delegate signature is: delegate() /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnUpdateDelegate</param> public void AddOnUpdateDelegate(OnUpdateDelegate del) { this.onUpdateDelegates -= del; // Cheap way to ensure unique (add only once) this.onUpdateDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for () /// </summary> /// <param name="del">An OnUpdateDelegate</param> public void SetOnUpdateDelegate(OnUpdateDelegate del) { this.onUpdateDelegates = del; } /// <summary> /// Removes a OnDetectedDelegate /// See docs for () /// </summary> /// <param name="del">An OnUpdateDelegate</param> public void RemoveOnUpdateDelegate(OnUpdateDelegate del) { this.onUpdateDelegates -= del; } #endregion OnUpdateDelegates Add/Set/Remove #region OnTargetUpdateDelegates Add/Set/Remove /// <summary> /// Add a new delegate to be triggered each frame when a target is being tracked. /// For other 'Update' events, see the docs for OnUpdateDelegates() /// The delegate signature is: delegate(TargetList targets) /// See TargetTracker documentation for usage of the provided 'Target' in this list. /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnTargetUpdateDelegate</param> public void AddOnTargetUpdateDelegate(OnTargetUpdateDelegate del) { this.onTargetUpdateDelegates -= del; // Cheap way to ensure unique (add only once) this.onTargetUpdateDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for () /// </summary> /// <param name="del">An OnTargetUpdateDelegate</param> public void SetOnTargetUpdateDelegate(OnTargetUpdateDelegate del) { this.onTargetUpdateDelegates = del; } /// <summary> /// Removes a OnDetectedDelegate /// See docs for () /// </summary> /// <param name="del">An OnTargetUpdateDelegate</param> public void RemoveOnTargetUpdateDelegate(OnTargetUpdateDelegate del) { this.onTargetUpdateDelegates -= del; } #endregion OnTargetUpdateDelegates Add/Set/Remove #region OnIdleUpdateDelegates Add/Set/Remove /// <summary> /// Add a new delegate to be triggered every frame when there is no target to track. /// The delegate signature is: delegate() /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnIdleUpdateDelegate</param> public void AddOnIdleUpdateDelegate(OnIdleUpdateDelegate del) { this.onIdleUpdateDelegates -= del; // Cheap way to ensure unique (add only once) this.onIdleUpdateDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for () /// </summary> /// <param name="del">An OnIdleUpdateDelegate</param> public void SetOnIdleUpdateDelegate(OnIdleUpdateDelegate del) { onIdleUpdateDelegates = del; } /// <summary> /// Removes a OnDetectedDelegate /// See docs for () /// </summary> /// <param name="del">An OnIdleUpdateDelegate</param> public void RemoveOnIdleUpdateDelegate(OnIdleUpdateDelegate del) { onIdleUpdateDelegates -= del; } #endregion OnIdleUpdateDelegates Add/Set/Remove #region OnStopDelegates Add/Set/Remove /// <summary> /// Add a new delegate to be triggered when the firing system is stopped. /// This is caused by destroying the object which has this component or if /// the object or component are disabled (The system will restart when /// enabled again) /// The delegate signature is: delegate() /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnStopDelegate</param> public void AddOnStopDelegate(OnStopDelegate del) { this.onStopDelegates -= del; // Cheap way to ensure unique (add only once) this.onStopDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for () /// </summary> /// <param name="del">An OnStopDelegate</param> public void SetOnStopDelegate(OnStopDelegate del) { this.onStopDelegates = del; } /// <summary> /// Removes a OnDetectedDelegate /// See docs for () /// </summary> /// <param name="del">An OnStopDelegate</param> public void RemoveOnStopDelegate(OnStopDelegate del) { this.onStopDelegates -= del; } #endregion OnStopDelegates Add/Set/Remove #region OnPreFireDelegates Add/Set/Remove /// <summary> /// Runs just before any OnFire target checks to allow custom target list /// manipulation and other pre-fire logic. /// The delegate signature is: delegate(TargetList targets) /// See TargetTracker documentation for usage of the provided '...' /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnPreFireDelegate</param> public void AddOnPreFireDelegate(OnPreFireDelegate del) { this.onPreFireDelegates -= del; // Cheap way to ensure unique (add only once) this.onPreFireDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnPreFireDelegate() /// </summary> /// <param name="del">An OnPreFireDelegate</param> public void SetOnPreFireDelegate(OnPreFireDelegate del) { this.onPreFireDelegates = del; } /// <summary> /// Removes a OnPostSortDelegate /// See docs for AddOnPreFireDelegate() /// </summary> /// <param name="del">An OnPreFireDelegate</param> public void RemoveOnPreFireDelegate(OnPreFireDelegate del) { this.onPreFireDelegates -= del; } #endregion OnPreFireDelegates Add/Set/Remove #region OnFireDelegates Add/Set/Remove /// <summary> /// Add a new delegate to be triggered when it is time to fire/notify a target(s). /// The delegate signature is: delegate(TargetList targets) /// See TargetTracker documentation for usage of the provided 'Target' in this list. /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnFireDelegate</param> public void AddOnFireDelegate(OnFireDelegate del) { this.onFireDelegates -= del; // Cheap way to ensure unique (add only once) this.onFireDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for () /// </summary> /// <param name="del">An OnFireDelegate</param> public void SetOnFireDelegate(OnFireDelegate del) { this.onFireDelegates = del; } /// <summary> /// Removes a OnDetectedDelegate /// See docs for () /// </summary> /// <param name="del">An OnFireDelegate</param> public void RemoveOnFireDelegate(OnFireDelegate del) { this.onFireDelegates -= del; } #endregion OnFireDelegates Add/Set/Remove #region OnEventTriggerSpawnedDelegates Add/Set/Remove /// <summary> /// Add a new delegate to be triggered when an EventTrigger is spawned. This only happens /// if the notification option is not off or 'Direct'. /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnEventTriggerSpawnedDelegate</param> public void AddOnEventTriggerSpawnedDelegate(OnEventTriggerSpawnedDelegate del) { this.onEventTriggerSpawnedDelegates -= del; // Cheap way to ensure unique (add only once) this.onEventTriggerSpawnedDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for () /// </summary> /// <param name="del">An OnEventTriggerSpawnedDelegate</param> public void SetOnEventTriggerSpawnedDelegate(OnEventTriggerSpawnedDelegate del) { this.onEventTriggerSpawnedDelegates = del; } /// <summary> /// Removes a OnDetectedDelegate /// See docs for () /// </summary> /// <param name="del">An OnEventTriggerSpawnedDelegate</param> public void RemoveOnEventTriggerSpawnedDelegate(OnEventTriggerSpawnedDelegate del) { this.onEventTriggerSpawnedDelegates -= del; } #endregion OnFireDelegates Add/Set/Remove #endregion Delegate Add/Set/Remove methods #endregion Events #region Public Methods /// <summary> /// Can be run to trigger this FireController to fire immediately regardless of /// counter or other settings. /// /// This still executes any PreFireDelegates /// </summary> /// <param name="resetIntervalCounter">Should the count be reset or continue?</param> public void FireImmediately(bool resetIntervalCounter) { if (resetIntervalCounter) this.fireIntervalCounter = this.interval; // Can alter this.targets if (this.onPreFireDelegates != null) this.onPreFireDelegates(this.targets); this.Fire(); } #endregion Public Methods #region protected Methods /// <summary> /// Handles all firing events including target aquisition and firing. /// Events are: /// OnStart() : /// Runs once when the firing system first becomes active /// OnUpdate() : /// Runs each frame while the firing system is active /// OnTargetUpdate() : /// Runs each frame while tracking a target (there is at least one target.) /// OnIdleUpdate() : /// Runs each frame while the firing system is idle (no targets) /// OnFire() : /// Runs when it is time to fire. /// /// Counter Behavior Notes: /// * If there are no targets. the counter will keep running up. /// This means the next target to enter will be fired upon /// immediatly. /// /// * The counter is always active so if the last target exits, then a /// new target enters right after that, there may still be a wait. /// </summary> protected IEnumerator FiringSystem() { if (this.targetTracker == null) { this.targetTracker = this.GetComponent<TargetTracker>(); if (this.targetTracker == null) { // Give it a frame to see if this.targetTracker is being set by code. yield return null; if (this.targetTracker == null) throw new MissingComponentException ( "FireControllers must be on the same GameObject as a TargetTracker " + "or have it's targetTracker property set by code or drag-and-drop " + "in the inspector." ); } } // While (true) because of the timer, we want this to run all the time, not // start and stop based on targets in range if (this.initIntervalCountdownAtZero) this.fireIntervalCounter = 0; else this.fireIntervalCounter = this.interval; this.targets.Clear(); this.OnStart(); // EVENT TRIGGER this.keepFiring = true; // Can be turned off elsewhere to kill the firing system while (this.keepFiring) { // if there is no target, counter++, handle idle behavior, and // try next frame. // Will init this.targets for child classes as well. this.targets = new TargetList(this.targetTracker.targets); if (this.targets.Count != 0) { if (this.fireIntervalCounter <= 0) { // Let the delegate filter a copy of the list just for the OnFire // Test. We still want this.targets to remain as is. // Do this in here to still trigger OnTargetUpdate this.targetsCopy.Clear(); this.targetsCopy.AddRange(this.targets); if (targetsCopy.Count != 0 && this.onPreFireDelegates != null) this.onPreFireDelegates(this.targetsCopy); // If all is right, fire // Check targetsCopy incase of pre-fire delegate changes if (targetsCopy.Count != 0) { this.Fire(); this.fireIntervalCounter = this.interval; // Reset } } // Update event while tracking a target this.OnTargetUpdate(this.targets); // EVENT TRIGGER } else { // Update event while NOT tracking a target this.OnIdleUpdate(); // EVENT TRIGGER } this.fireIntervalCounter -= Time.deltaTime; // Update event no matter what this.OnUpdate(); // EVENT TRIGGER // Stager calls to get Target (the whole system actually) yield return null; } // Wipe out the target list when stopped this.targets.Clear(); } #endregion protected Methods } }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using PathologicalGames; [CustomEditor(typeof(IgnoreModifier)), CanEditMultipleObjects] public class IgnoreModifierInspector : Editor { protected SerializedProperty debugLevel; protected SerializedProperty ignoreList; protected void OnEnable() { this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.ignoreList = this.serializedObject.FindProperty("_ignoreList"); } public override void OnInspectorGUI() { this.serializedObject.Update(); Object[] targetObjs = this.serializedObject.targetObjects; GUIContent content; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; EditorGUI.indentLevel = 1; // Build a cache dict to use after the control is displayed for user input var ignoreCache = new Dictionary<IgnoreModifier, List<Targetable>>(); IgnoreModifier curEditTarget; List<Targetable> curIgnoreCacheList; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (IgnoreModifier)targetObjs[i]; curIgnoreCacheList = new List<Targetable>(); // Update the cache to compare later curIgnoreCacheList.AddRange(curEditTarget._ignoreList); // Store to cache dict ignoreCache[curEditTarget] = curIgnoreCacheList; } // If multiple objects are being edited display the default control. Otherwise // The pretty control is displayed below when there is only 1 object in the targetObjs if (this.serializedObject.isEditingMultipleObjects) { content = new GUIContent ( "Targetables to ignore", "Drag and drop Targetables to make the TargetTracker ignore them." ); EditorGUILayout.PropertyField(this.ignoreList, content, true); // Update the backing list or the cache handling won't do anything below. this.serializedObject.ApplyModifiedProperties(); } foreach (KeyValuePair<IgnoreModifier, List<Targetable>> kvp in ignoreCache) { curEditTarget = kvp.Key; curIgnoreCacheList = kvp.Value; // See the note above on editing multi objects and control visibility // Note: If this is true then there will only be 1 item I the cache dict here. if (!this.serializedObject.isEditingMultipleObjects) { GUILayout.Space(4); PGEditorUtils.FoldOutObjList<Targetable> ( "Targetables to ignore", curEditTarget._ignoreList, true // Force the fold-out state ); } // Detect a change to trigger ignore refresh logic if the game is playing // Note: Don't use counts since new item can be null then later // drag&dropped, skipping logic. if (Application.isPlaying) { // Sync newly added foreach (Targetable targetable in new List<Targetable>(curEditTarget._ignoreList)) { if (targetable == null) continue; if (!curIgnoreCacheList.Contains(targetable)) curEditTarget.Add(targetable); } // Sync newly removed foreach (Targetable targetable in new List<Targetable>(curIgnoreCacheList)) { if (targetable == null) continue; if (!curEditTarget._ignoreList.Contains(targetable)) curEditTarget.Remove(targetable); } } } GUILayout.Space(4); content = new GUIContent ( "Debug Level", "Set it higher to see more verbose information." ); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } } class IgnoreModifierGizmo { [DrawGizmo(GizmoType.Selected | GizmoType.NotInSelectionHierarchy)] static void RenderGizmo(IgnoreModifier mod, GizmoType gizmoType) { if (mod.debugLevel == DEBUG_LEVELS.Off || !mod.enabled) return; Color color = Color.red; color.a = 0.2f; foreach (Targetable targetable in mod._ignoreList) { if (targetable == null) continue; Gizmos.matrix = targetable.transform.localToWorldMatrix; color.a = 0.5f; Gizmos.color = color; Gizmos.DrawWireSphere(Vector3.zero, 1); color.a = 0.2f; Gizmos.color = color; Gizmos.DrawSphere(Vector3.zero, 1); } Gizmos.matrix = Matrix4x4.zero; // Just to be clean } } <file_sep>using UnityEngine; using System.Collections; using PathologicalGames; public class PatternShooter : MonoBehaviour { public float ShotAngle; public float ShotAngleRange; public float ShotSpeed; public int Interval; private string[] Pattern; private int Width; private int Height; private int Timer = 0; private int ptcnt; public bool oneShoot = true; public bool canShoot = true; public int patternType = 1; public GameObject bullet; static SpawnPool spawnPool = null; Transform tmp, tr; Bullet tBullet; public int bulletMoney; public float bulletHp; void Awake() { tr = GetComponent<Transform>(); } void Start () { if (spawnPool == null) { spawnPool = PoolManager.Pools ["Test"]; } if (patternType == 1) { Width = 41; Height = 23; } ptcnt = 0; Pattern = new string[23] { "# # ##### ##### # # ##### # # #### ", "# # # # # # # ## # # #", "# # # #### #### ## #### # # # # #", "# # # # # # # # # ## # #", " # # ##### ##### # # ##### # # #### ", " ", " ", " ", " ", " #### ### # # ##### ", " # # # # # # # ", " # ## ##### # # # ##### ", " # # # # # # # ", " #### # # # # ##### ", " ", " ", " ", " ", " ### # # #### ### ##### ", " # ## # # # # # ", " # # # # # # # #### ", " # # ## # # # # ", " ### # # #### ### ##### " }; } void Update () { if (Timer % Interval == 0 && canShoot) { for (int i = Width - 1; i >= 0; i--) { if (Pattern [Height - 1 - ptcnt] [i] != ' ') { tmp = spawnPool.Spawn (bullet, Vector3.zero, Quaternion.identity); tBullet = tmp.GetComponent<Bullet> (); tmp.transform.position = tr.position; tBullet.speed = ShotSpeed; tBullet.angle = ShotAngle + ShotAngleRange * ((float)i / (Width - 1) - 0.5f); tBullet.speedRate = 0; tBullet.angleRate = 0; tBullet.basicHP = bulletHp; tBullet.hp = bulletHp; tBullet.money = bulletMoney; } } ptcnt++; if (ptcnt == Height) { canShoot = false; ptcnt = 0; } } if (canShoot) Timer = (Timer + 1) % (Interval * Height); if (!canShoot) Timer = 0; } } <file_sep>using UnityEngine; using System.Collections; using PathologicalGames; public class EnemyLib : MonoBehaviour { public static EnemyLib instance; static SpawnPool spawnPool = null; Transform tmp, tr; Bullet tBullet; void Awake() { if (instance == null) instance = this; } void Start() { if (spawnPool == null) { spawnPool = PoolManager.Pools["Test"]; } } public float GetPlayerAngle(Vector2 pos) { return Mathf.Atan2(PlayerControl.instance.transform.position.y - pos.y,PlayerControl.instance.transform.position.x - pos.x) / Mathf.PI / 2; } public void ShootNWay(Vector2 pos, float angle, float angleRange, float speed, int count, float angleRate, float speedRate, GameObject bullet, int bulletMoney, float bulletHp) { for (int i = 0; i < count; i++) { tmp = spawnPool.Spawn(bullet); Bullet tBullet = tmp.GetComponent<Bullet> (); tmp.transform.position = pos; tBullet.speed = speed; tBullet.angle = angle + angleRange * ((float)i / (count - 1) - 0.5f); tBullet.angleRate = angleRate; tBullet.speedRate = speedRate; tBullet.money = bulletMoney; tBullet.basicHP = bulletHp; tBullet.hp = bulletHp; } } public void ShootPlacedNWay(Vector2 pos, float angle, float angleRange, float speed, int count, int moveTime, int stopTime, GameObject bullet, int bulletMoney, float bulletHp) { for (int i = 0; i < count; i++) { tmp = spawnPool.Spawn(bullet); PlacedBullet tBullet = tmp.GetComponent<PlacedBullet> (); tmp.transform.position = pos; tBullet.angle = angle + angleRange * ((float)i / (count - 1) - 0.5f); tBullet.speed = speed; tBullet.InitialSpeed = speed; tBullet.MoveTime = moveTime; tBullet.StopTime = stopTime; tBullet.speedRate = 0; tBullet.angleRate = 0; tBullet.basicHP = bulletHp; tBullet.hp = bulletHp; tBullet.money = bulletMoney; } } } <file_sep>/// <Licensing> /// ©2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; using PathologicalGames; namespace PathologicalGames { /// <summary> /// Contains only an EventInfoList list, like EventFireControllers have, but for easy use by /// any script. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/Utilities/EventInfoList (Standalone)")] public class EventInfoListStandalone : MonoBehaviour { /// <summary> /// A list of EventInfo structs which hold one or more descriptions /// of how a Target can be affected. To alter this from code. Get the list, edit it, then /// set the whole list back. (This cannot be edited "in place"). /// </summary> // Encodes / Decodes EventInfos to and from EventInfoGUIBackers public EventInfoList eventInfoList { get { var returnInfoList = new EventInfoList(); foreach (var infoBacker in this._eventInfoListGUIBacker) { // Create and add a struct-form of the backing-field instance returnInfoList.Add ( new EventInfo { name = infoBacker.name, value = infoBacker.value, duration = infoBacker.duration, } ); } return returnInfoList; } set { // Clear and set the backing-field list also used by the GUI this._eventInfoListGUIBacker.Clear(); EventInfoListGUIBacker infoBacker; foreach (var info in value) { infoBacker = new EventInfoListGUIBacker(info); this._eventInfoListGUIBacker.Add(infoBacker); } } } /// <summary> /// Public for Inspector use only. /// </summary> public List<EventInfoListGUIBacker> _eventInfoListGUIBacker = new List<EventInfoListGUIBacker>(); // Keeps the state of each individual foldout item during the editor session public Dictionary<object, bool> _inspectorListItemStates = new Dictionary<object, bool>(); } }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Adding this component to a gameObject will make it detectable to TargetTrackers, recieve /// EventInfo and expose event delegates to run attached custom compponent methods. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Targetable")] public class Targetable : MonoBehaviour { #region Public Parameters /// <summary> /// Indicates whether this <see cref="PathologicalGames.Targetable"/> is targetable. /// If the Targetable is being tracked when this is set to false, it will be removed /// from all Areas. When set to true, it will be added to any Perimieters it is /// inside of, if applicable. /// </summary> public bool isTargetable { get { // Don't allow targeting if disabled in any way. // If both are false and then the gameobject becomes active, Perimieters will // detect this rigidbody enterig. Returning false will prevent this odd behavior. if (!this.go.activeInHierarchy || !this.enabled) return false; return this._isTargetable; } set { // Singleton. Only do something if value changed if (this._isTargetable == value) return; this._isTargetable = value; // Don't execute logic if this is disabled in any way. if (!this.go.activeInHierarchy || !this.enabled) return; if (!this._isTargetable) this.CleanUp(); else this.BecomeTargetable(); } } public bool _isTargetable = true; // Public for inspector use public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; internal List<TargetTracker> trackers = new List<TargetTracker>(); // Delegate type declarations //! [snip_OnDetectedDelegate] public delegate void OnDetectedDelegate(TargetTracker source); //! [snip_OnDetectedDelegate] //! [snip_OnNotDetectedDelegate] public delegate void OnNotDetectedDelegate(TargetTracker source); //! [snip_OnNotDetectedDelegate] //! [snip_OnHit] public delegate void OnHitDelegate(EventInfoList eventInfoList, Target target); //! [snip_OnHit] #endregion Public Parameters #region protected Parameters public GameObject go; public Collider coll; public Collider2D coll2D; // Internal lists for each delegate type protected OnDetectedDelegate onDetectedDelegates; protected OnNotDetectedDelegate onNotDetectedDelegates; protected OnHitDelegate onHitDelegates; #endregion protected Parameters #region Events protected void Awake() { // Cache this.go = this.gameObject; this.coll = this.GetComponent<Collider>(); this.coll2D = this.GetComponent<Collider2D>(); } protected void OnDisable() { this.CleanUp(); } protected void OnDestroy() { this.CleanUp(); } protected void CleanUp() { if (!Application.isPlaying) return; // Game was stopped. var copy = new List<TargetTracker>(this.trackers); foreach (TargetTracker tt in copy) { // Protect against async destruction if (tt == null || tt.area == null || tt.area.Count == 0) continue; tt.area.Remove(this); #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) Debug.Log(string.Format ( "Targetable ({0}): On Disabled, Destroyed or !isTargetable- " + "Removed from {1}.", this.name, tt.name )); #endif } this.trackers.Clear(); } protected void BecomeTargetable() { // Toggle the collider, only if it was enabled to begin with, to let the physics // systems refresh. if (this.coll != null && this.coll.enabled) { this.coll.enabled = false; this.coll.enabled = true; } #if (!UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1 && !UNITY_4_2) else if (this.coll2D != null && this.coll2D.enabled) { this.coll2D.enabled = false; this.coll2D.enabled = true; } #endif } /// <summary> /// Triggered when a target is hit /// </summary> /// <param name="source">The EventInfoList to send</param> /// <param name="source"> /// The target struct used to cache this target when sent /// </param> public void OnHit(EventInfoList eventInfoList, Target target) { #if UNITY_EDITOR // Normal level debug and above if (this.debugLevel > DEBUG_LEVELS.Off) { Debug.Log ( string.Format ( "Targetable ({0}): EventInfoList[{1}]", this.name, eventInfoList.ToString() ) ); } #endif // Set the hitTime for all eventInfos in the list. eventInfoList = eventInfoList.CopyWithHitTime(); if (this.onHitDelegates != null) this.onHitDelegates(eventInfoList, target); } /// <summary> /// Triggered when a target is first found by an Area /// </summary> /// <param name="source">The TargetTracker which triggered this event</param> internal void OnDetected(TargetTracker source) { #if UNITY_EDITOR // Higest level debug if (this.debugLevel > DEBUG_LEVELS.Normal) { string msg = "Detected by " + source.name; Debug.Log(string.Format("Targetable ({0}): {1}", this.name, msg)); } #endif this.trackers.Add(source); if (this.onDetectedDelegates != null) this.onDetectedDelegates(source); } /// <summary> /// Triggered when a target is first found by an Area /// </summary> /// <param name="source">The TargetTracker which triggered this event</param> internal void OnNotDetected(TargetTracker source) { #if UNITY_EDITOR // Higest level debug if (this.debugLevel > DEBUG_LEVELS.Normal) { string msg = "No longer detected by " + source.name; Debug.Log(string.Format("Targetable ({0}): {1}", this.name, msg)); } #endif this.trackers.Remove(source); if (this.onNotDetectedDelegates != null) this.onNotDetectedDelegates(source); } #endregion Events #region Target Tracker Members public float strength { get; set; } /// <summary> /// Waypoints is just a list of positions used to determine the distance to /// the final destination. See distToDest. /// </summary> [HideInInspector] public List<Vector3> waypoints = new List<Vector3>(); /// <summary> /// Get the distance from this GameObject to the nearest waypoint and then /// through all remaining waypoints. /// Set wayPoints (List of Vector3) to use this feature. /// The distance is kept as a sqrMagnitude for faster performance and /// comparison. /// </summary> /// <returns>The distance as sqrMagnitude</returns> public float distToDest { get { if (this.waypoints.Count == 0) return 0; // if no points, return // First get the distance to the first point from the current position float dist = this.GetSqrDistToPos(waypoints[0]); // Add the distance to each point from the one before. for (int i = 0; i < this.waypoints.Count - 2; i++) // -2 keeps this in bounds dist += (waypoints[i] - waypoints[i + 1]).sqrMagnitude; return dist; } } /// <summary> /// Get the distance from this Transform to another position in space. /// The distance is returned as a sqrMagnitude for faster performance and /// comparison /// </summary> /// <param name="other">The position to find the distance to</param> /// <returns>The distance as sqrMagnitude</returns> public float GetSqrDistToPos(Vector3 other) { return (this.transform.position - other).sqrMagnitude; } /// <summary> /// Get the distance from this Transform to another position in space. /// The distance is returned as a float for simple min/max testing, etc. /// For distance comparisons, use GetSqrDistToPos(...) /// </summary> /// <param name="other">The position to find the distance to</param> /// <returns>The distance as a simple float</returns> public float GetDistToPos(Vector3 other) { return (this.transform.position - other).magnitude; } #region Delegate Add/Set/Remove Functions #region OnDetectedDelegates /// <summary> /// Add a new delegate to be triggered when a target is first found by an Area. /// The delegate signature is: delegate(TargetTracker source) /// See TargetTracker documentation for usage of the provided 'source' /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del"></param> public void AddOnDetectedDelegate(OnDetectedDelegate del) { this.onDetectedDelegates -= del; // Cheap way to ensure unique (add only once) this.onDetectedDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnDetectedDelegate() /// </summary> /// <param name="del"></param> public void SetOnDetectedDelegate(OnDetectedDelegate del) { this.onDetectedDelegates = del; } /// <summary> /// Removes a OnDetectedDelegate /// See docs for AddOnDetectedDelegate() /// </summary> /// <param name="del"></param> public void RemoveOnDetectedDelegate(OnDetectedDelegate del) { this.onDetectedDelegates -= del; } #endregion OnDetectedDelegates #region OnNotDetectedDelegate /// <summary> /// Add a new delegate to be triggered when a target is dropped by a perimieter for /// any reason; leaves or is removed. /// The delegate signature is: delegate(TargetTracker source) /// See TargetTracker documentation for usage of the provided 'source' /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del"></param> public void AddOnNotDetectedDelegate(OnNotDetectedDelegate del) { this.onNotDetectedDelegates -= del; // Cheap way to ensure unique (add only once) this.onNotDetectedDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnNotDetectedDelegate() /// </summary> /// <param name="del"></param> public void SetOnNotDetectedDelegate(OnNotDetectedDelegate del) { this.onNotDetectedDelegates = del; } /// <summary> /// Removes a OnNotDetectedDelegate /// See docs for AddOnNotDetectedDelegate() /// </summary> /// <param name="del"></param> public void RemoveOnNotDetectedDelegate(OnNotDetectedDelegate del) { this.onNotDetectedDelegates -= del; } #endregion OnNotDetectedDelegate #region OnHitDelegate /// <summary> /// Add a new delegate to be triggered when the target is hit. /// The delegate signature is: delegate(EventInfoList eventInfoList, Target target) /// See EventInfoList documentation for usage. /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del"></param> public void AddOnHitDelegate(OnHitDelegate del) { this.onHitDelegates -= del; // Cheap way to ensure unique (add only once) this.onHitDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnHitDelegate() /// </summary> /// <param name="del"></param> public void SetOnHitDelegate(OnHitDelegate del) { this.onHitDelegates = del; } /// <summary> /// Removes a OnHitDelegate /// See docs for AddOnHitDelegate() /// </summary> /// <param name="del"></param> public void RemoveOnHitDelegate(OnHitDelegate del) { this.onHitDelegates -= del; } #endregion OnHitDelegate #endregion Delegate Add/Set/Remove Functions #endregion Target Tracker Members } }<file_sep>using UnityEngine; using System.Collections; public class Transform_Demo : MonoBehaviour { public Vector3 rotate = new Vector3(0, 3, 0); private Transform xform; private bool moveForward = true; private float speed = 5f; private float duration = 0.6f; private float delay = 1.5f; Vector3 bigScale = new Vector3(2, 2, 2); Vector3 smallScale = new Vector3(1, 1, 1); void Awake() { this.xform = this.transform; } // Use this for initialization void Start () { this.StartCoroutine(this.MoveTarget()); this.StartCoroutine(this.RotateTarget()); } private IEnumerator RotateTarget() { yield return new WaitForSeconds(delay); while (true) { this.xform.Rotate(this.rotate); yield return null; } } private IEnumerator MoveTarget() { while (true) { yield return new WaitForSeconds(delay); float savedTime = Time.time; while ((Time.time - savedTime) < duration) { if (moveForward) { this.xform.Translate(Vector3.up * (Time.deltaTime * speed)); this.xform.localScale = Vector3.Lerp(this.xform.localScale, bigScale, (Time.deltaTime * 4.75f)); } else { this.xform.Translate(Vector3.down * (Time.deltaTime * speed)); this.xform.localScale = Vector3.Lerp(this.xform.localScale, smallScale, (Time.deltaTime * 4.75f)); } yield return null; } moveForward = moveForward ? false : true; } } } <file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; namespace PathologicalGames { /// <summary> /// Manages a "turntable" component which will rotate the owner in the Y access at /// a constant speed while on. This will start itself and stop itself when enabled /// or disabled as well as directly through the "on" bool property. /// </summary> [AddComponentMenu("Path-o-logical/UnityConstraints/Constraint - Turntable")] public class TurntableConstraint : ConstraintFrameworkBaseClass { /// <summary> /// The speed at which the turn table will turn /// </summary> public float speed = 1; /// <summary> /// The speed at which the turn table will turn /// </summary> public bool randomStart = false; protected override void OnEnable() { base.OnEnable(); #if UNITY_EDITOR if (Application.isPlaying) { #endif // It isn't helpful to have this run in the editor. // This if statement won't compile with the game if (Application.isPlaying && this.randomStart) this.transform.Rotate(0, Random.value * 360, 0); #if UNITY_EDITOR } #endif } /// <summary> /// Runs each frame while the constraint is active /// </summary> protected override void OnConstraintUpdate() { // Note: Do not run base.OnConstraintUpdate. It is not implimented #if UNITY_EDITOR // It isn't helpful to have this run in the editor. // This if statement won't compile with the game if (Application.isPlaying) { #endif // Add a rotation == this.speed per frame this.transform.Rotate(0, this.speed, 0); #if UNITY_EDITOR } #endif } } }<file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Adds the ability to only fire on Targets within a distance range of a TargetTracker. /// This is like having a second spherical Area. Useful when you want objects to be /// "detected" but not actually able to be fired on until they get closer. /// </summary> [RequireComponent(typeof(EventFireController))] public class WaitForAlignmentModifier : TriggerEventProModifier { /// <summary> /// The transform used to determine alignment. If not used, this will be the /// transform of the GameObject this component is attached to. /// </summary> public Transform origin { get { if (this._origin == null) return this.transform; else return this._origin; } set { this._origin = value; } } [SerializeField] protected Transform _origin = null; // Explicit for clarity /// <summary> /// The angle, in degrees, to use for checks. /// </summary> public float angleTolerance = 5; /// <summary> /// If false the actual angles will be compared for alignment (More precise. origin /// must point at target). If true, only the direction matters. (Good when turning /// in a direction but perfect alignment isn't needed, e.g. lobing bombs as opposed /// to shooting AT something) /// </summary> public bool flatAngleCompare = false; public enum COMPARE_AXIS {X, Y, Z} /// <summary> /// Determines the axis to use when doing angle comparisons. /// </summary> public COMPARE_AXIS flatCompareAxis = COMPARE_AXIS.Z; public enum FILTER_TYPE {IgnoreTargetTracking, WaitToFireEvent} /// <summary> /// Determines if filtering will be performed on a TargetTracker's targets or an /// EventTrigger's targets. See the component description for more detail. This is /// ignored unless a its GameObject has both. Otherwise the mode will be auto-detected. /// </summary> public FILTER_TYPE filterType = FILTER_TYPE.WaitToFireEvent; public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; protected EventFireController fireCtrl; protected TargetTracker tracker; protected Target currentTarget; // Loop cache protected List<Target> iterTargets = new List<Target>(); // Loop cache #region CHANGED AWAKE TO MIMIC OLD VERSION OF THIS COMPONENT protected void Awake() { Debug.LogWarning(string.Format( "WaitForAlignementModifier on GameObject {0} has been deprecated. Replace the " + "component with AngleLimitModifier (with the filterType set to 'Wait to Fire " + "Event'). You can do this without losing your other settings by switching the " + "Inspector tab to 'Debug' and changing the script field.", this.name )); this.fireCtrl = this.GetComponent<EventFireController>(); // Force because this old component could only do this this.filterType = FILTER_TYPE.WaitToFireEvent; } #endregion CHANGED AWAKE TO MIMIC OLD VERSION OF THIS COMPONENT // OnEnable and OnDisable add the check box in the inspector too. protected void OnEnable() { if (this.tracker != null) this.tracker.AddOnPostSortDelegate(this.FilterTrackerTargetList); if (this.fireCtrl != null) this.fireCtrl.AddOnPreFireDelegate(this.FilterFireCtrlTargetList); } protected void OnDisable() { if (this.tracker != null) this.tracker.RemoveOnPostSortDelegate(this.FilterTrackerTargetList); if (this.fireCtrl != null) this.fireCtrl.RemoveOnPreFireDelegate(this.FilterFireCtrlTargetList); } protected void FilterFireCtrlTargetList(TargetList targets) { if (this.filterType == FILTER_TYPE.WaitToFireEvent) this.FilterTargetList(targets); // Else do nothing. } protected void FilterTrackerTargetList(TargetTracker source, TargetList targets) { if (this.filterType == FILTER_TYPE.IgnoreTargetTracking) this.FilterTargetList(targets); // Else do nothing. } protected void FilterTargetList(TargetList targets) { #if UNITY_EDITOR var debugRemoveNames = new List<string>(); #endif this.iterTargets.Clear(); this.iterTargets.AddRange(targets); for (int i = 0; i < iterTargets.Count; i++) { this.currentTarget = iterTargets[i]; if (this.IsInAngle(this.currentTarget)) continue; // This target is good. Don't ignore it. Continue. #if UNITY_EDITOR debugRemoveNames.Add(this.currentTarget.targetable.name); #endif targets.Remove(this.currentTarget); } #if UNITY_EDITOR if (this.debugLevel == DEBUG_LEVELS.High && debugRemoveNames.Count > 0) { string msg = string.Format ( "Holding fire due to misalignment: {0}", string.Join(", ", debugRemoveNames.ToArray()) ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif } protected bool IsInAngle(Target target) { Vector3 targetDir = target.transform.position - this.origin.position; Vector3 forward = this.origin.forward; if (this.flatAngleCompare) { switch (this.flatCompareAxis) { case COMPARE_AXIS.X: targetDir.x = forward.x = 0; // Flatten Vectors break; case COMPARE_AXIS.Y: targetDir.y = forward.y = 0; // Flatten Vectors break; case COMPARE_AXIS.Z: targetDir.z = forward.z = 0; // Flatten Vectors break; } } bool isInAngle = Vector3.Angle(targetDir, forward) < this.angleTolerance; #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) { // Multiply the direction Vector by distance to make the line longer forward = this.origin.forward * targetDir.magnitude; if (isInAngle) { Debug.DrawRay(this.origin.position, forward, Color.green, 0.01f); } else { Debug.DrawRay(this.origin.position, forward, Color.red, 0.01f); Debug.DrawRay(this.origin.position, targetDir, Color.yellow, 0.01f); } } #endif return isInAngle; } } }<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(BillboardConstraint)), CanEditMultipleObjects] public class BillboardConstraintInspector : LookAtBaseClassInspector { protected SerializedProperty vertical; // Singleton cache to set some defaults on inspection private Camera[] cameras; protected override void OnEnable() { base.OnEnable(); this.vertical = this.serializedObject.FindProperty("vertical"); } protected override void OnInspectorGUIUpdate() { var script = (BillboardConstraint)target; var content = new GUIContent("Vertical", "If false, the billboard will only rotate along the upAxis."); EditorGUILayout.PropertyField(this.vertical, content); base.OnInspectorGUIUpdate(); // Set some singletone defaults (will only run once).. // This will actually run when the inspector changes, but still better than // running every update if (this.cameras == null) this.cameras = FindObjectsOfType(typeof(Camera)) as Camera[]; // Default to the first ortho camera that is set to render this object if (script.target == null) { foreach (Camera cam in cameras) { if ((cam.cullingMask & 1 << script.gameObject.layer) > 0) { script.target = cam.transform; break; } } } } } }<file_sep>/// <Licensing> /// � 2011(Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License(the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace PathologicalGames { /// <summary> /// Explcictly ignore Targets. Useful when a TargetTracker prefab is also a Target on the /// same layer as other Targets. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Modifier - Ignore Targetables")] [RequireComponent(typeof(TargetTracker))] public class IgnoreModifier : MonoBehaviour { /// <summary> /// DO NOT USE DIRECTLY. This is only public for inspector use. /// Use Add, Remove or Clear methods instead. /// </summary> public List<Targetable> _ignoreList = new List<Targetable>(); public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; // Cache and re-use protected TargetTracker tracker; protected Targetable currentTargetable; protected void Awake() { this.tracker = this.GetComponent<TargetTracker>(); } protected void OnEnable() { this.tracker.AddOnNewDetectedDelegate(this.OnNewDetected); if (this._ignoreList.Count == 0) return; // Unless this is a AreaTargetTracker. Stop here. if (this.tracker.area == null) return; // Sync the ignore list with the TargetTracker by removing any ignore targetables. var areaListCopy = new TargetList(this.tracker.area); for (int i = 0; i < areaListCopy.Count; i++) { this.currentTargetable = areaListCopy[i].targetable; if (this.currentTargetable == null) continue; if (this._ignoreList.Contains(this.currentTargetable)) { this.tracker.area.Remove(this.currentTargetable); } } } protected void OnDisable() { if (this.tracker != null) // For when levels or games are dumped this.tracker.RemoveOnNewDetectedDelegate(this.OnNewDetected); // If this isn't an AreaTargetTracker stop here. if (this.tracker.area == null) return; foreach (Targetable targetable in this._ignoreList) { if (targetable != null && this.tracker.area != null && this.tracker.area.IsInRange(targetable)) { this.tracker.area.Add(targetable); } } } protected bool OnNewDetected(TargetTracker targetTracker, Target target) { #if UNITY_EDITOR // Print the target.gameObject's name name and list of ignore targetables if (this.debugLevel > DEBUG_LEVELS.Normal) { string[] names = new string[this._ignoreList.Count]; for (int i = 0; i < this._ignoreList.Count; i++) names[i] = this._ignoreList[i].name; string msg = string.Format ( "Testing target '{0}' against ignore list: '{1}'", target.gameObject.name, string.Join("', '", names) ); Debug.Log(string.Format("IgnoreModifier ({0}): {1}", this.name, msg)); } #endif if (this._ignoreList.Contains(target.targetable)) { #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = string.Format("Ignoring target '{0}'", target.gameObject.name); Debug.Log(string.Format("IgnoreModifier ({0}): {1}", this.name, msg)); } #endif return false; // Stop looking and ignore } return true; } /// <summary> /// Use like List<Targetable>.Add() to add the passed targetable to the ignore /// list and remove it from the TargetTracker /// </summary> /// <param name='targetable'> /// Targetable. /// </param> public void Add(Targetable targetable) { if (targetable == null) return; // Only add this once. if (!this._ignoreList.Contains(targetable)) this._ignoreList.Add(targetable); // Don't affect the TargetTracker if this is disabled. It will sync OnEnable if (this.enabled && this.tracker != null && this.tracker.area != null && targetable.trackers.Contains(this.tracker)) { // Removing multiple times doesn't hurt and lets the inspector use this. this.tracker.area.Remove(targetable); } } /// <summary> /// Use like List<Targetable>.Remove to remove the passed targetable from the ignore /// list and add it to the TargetTracker /// </summary> /// <param name='targetable'> /// Targetable. /// </param> public void Remove(Targetable targetable) { if (targetable == null) return; // Does nothing if there is nothing to remove. this._ignoreList.Remove(targetable); // Don't affect the TargetTracker if this is disabled. If disabled, all // are added back to the Area anyway and OnEnable only Remove is done. if (this.enabled && this.tracker.area != null) // The TargetTracker will handle preventing multiples from being added this.tracker.area.Add(targetable); } /// <summary> /// Clear the ignore list. Remove all targetables from the TargetTracker /// </summary> public void Clear() { foreach (Targetable targetable in this._ignoreList) this.Remove(targetable); } } }<file_sep>using UnityEngine; using System.Collections; using PathologicalGames; public class DirectionalShooter : MonoBehaviour { public float angle; public float shotSpeed; private float shotDelayTimer; public float shotDelay; public bool canShoot = true; public GameObject bullet; public int bulletMoney; public float bulletHp; public bool isPlayer = false, playerShoot = false, skill = false; public float bulletStandTime; public int bulletDmg, bulletCnt; static SpawnPool spawnPool = null; Transform tmp, tr; Bullet tBullet; BulletPlayer pBullet; void Awake() { tr = GetComponent<Transform>(); } void Start() { if (spawnPool == null) { spawnPool = PoolManager.Pools["Test"]; } } void Update () { if (skill && canShoot) { StartCoroutine("SpawnObject3"); } else if(canShoot && !isPlayer) { StartCoroutine("SpawnObject"); } else if (canShoot && isPlayer && !playerShoot) { StartCoroutine("SpawnObject2"); } } IEnumerator SpawnObject() { canShoot = false; tmp = spawnPool.Spawn(bullet, Vector3.zero, Quaternion.identity); tBullet = tmp.GetComponent<Bullet>(); tmp.transform.position = tr.position; tBullet.speed = shotSpeed; tBullet.angle = angle; tBullet.basicHP = bulletHp; tBullet.hp = bulletHp; tBullet.money = bulletMoney; yield return new WaitForSeconds(shotDelay); canShoot = true; } IEnumerator SpawnObject2() { canShoot = false; playerShoot = true; tmp = spawnPool.Spawn(bullet, PlayerControl.instance.bulletPos.localPosition, Quaternion.identity); pBullet = tmp.GetComponent<BulletPlayer>(); tmp.transform.position = PlayerControl.instance.bulletPos.position; pBullet.hp = bulletHp; pBullet.basicHP = bulletHp; pBullet.speed = shotSpeed; pBullet.angle = angle; yield return new WaitForSeconds(shotDelay); playerShoot = false; } IEnumerator SpawnObject3() { canShoot = false; skill = false; for (int i = 0; i < bulletCnt; i++) { tmp = spawnPool.Spawn(bullet, transform.position, Quaternion.identity); pBullet = tmp.GetComponent<BulletPlayer>(); tmp.transform.position = transform.position; pBullet.speed = shotSpeed; pBullet.angle = angle; pBullet.basicHP = bulletDmg; pBullet.GetComponent<SpawnCtrl>().SetTimeDespawn(bulletStandTime); yield return new WaitForSeconds(shotDelay); } gameObject.SetActive(false); } } <file_sep>using UnityEngine; using System.Collections; public class GapShooter : MonoBehaviour { public float angleRange; public float speed; public int count; public int Interval; private int Timer; public GameObject bullet; public bool canShoot = true; public int bulletMoney; public float bulletHp; void Update () { if (Timer == 0 && canShoot) { EnemyLib.instance.ShootNWay( transform.position, Random.Range(0.0f, 1f), angleRange, speed, count, 0, 0, bullet, bulletMoney, bulletHp); } if (canShoot) Timer = (Timer + 1) % Interval; if (!canShoot) Timer = 0; } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; namespace EnergyBarToolkit { public class EnergyBarUGUISlider : MonoBehaviour { private EnergyBar[] allBars; // Use this for initialization void Start () { allBars = FindObjectsOfType<EnergyBar>(); } public void OnValueChanged() { var slider = GetComponent<Slider>(); var val = slider.normalizedValue; for (int i = 0; i < allBars.Length; i++) { var bar = allBars[i]; bar.ValueF = val; } } } } // namespace<file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System; using EnergyBarToolkit; using UnityEditor; using UnityEngine; using PropertyDrawer = UnityEditor.PropertyDrawer; [CustomPropertyDrawer(typeof(ObjectFinder))] public class ObjectFinderEditor : PropertyDrawer { private float lineHeight; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { GUI.Label(GetLineRect(position, 0), label); EditorGUI.indentLevel++; EditorGUI.PropertyField(GetLineRect(position, 1), property.FindPropertyRelative("chosenMethod"), new GUIContent("Lookup Method")); EditorGUI.indentLevel++; var method = GetChosenMethod(property); switch (method) { case ObjectFinder.Method.ByPath: EditorGUI.PropertyField( GetLineRect(position, 2), property.FindPropertyRelative("path"), new GUIContent("Path")); break; case ObjectFinder.Method.ByTag: EditorGUI.PropertyField( GetLineRect(position, 2), property.FindPropertyRelative("tag"), new GUIContent("Tag")); break; case ObjectFinder.Method.ByType: #if UNITY_WINRT EditorGUI.HelpBox( GetLineRect(position, 2, lineHeight * 2), "Lookup by type not supported for Windows Store Apps", MessageType.Error); #endif break; case ObjectFinder.Method.ByReference: EditorGUI.PropertyField( GetLineRect(position, 2), property.FindPropertyRelative("reference"), new GUIContent("Camera")); break; default: throw new ArgumentOutOfRangeException(); } EditorGUI.indentLevel -= 2; } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { lineHeight = base.GetPropertyHeight(property, label); return lineHeight * GetLineCount(property); } private Rect GetLineRect(Rect rect, int index, float height = -1) { float space = lineHeight; return new Rect(rect.min.x, rect.min.y + index * space, rect.width, height < 0 ? lineHeight : height); } private int GetLineCount(SerializedProperty property) { var method = GetChosenMethod(property); switch (method) { case ObjectFinder.Method.ByPath: return 3; case ObjectFinder.Method.ByTag: return 3; case ObjectFinder.Method.ByType: #if UNITY_WINRT return 4; #else return 2; #endif case ObjectFinder.Method.ByReference: return 3; default: throw new ArgumentOutOfRangeException(); } } private ObjectFinder.Method GetChosenMethod(SerializedProperty property) { var index = property.FindPropertyRelative("chosenMethod").enumValueIndex; Array values = Enum.GetValues(typeof(ObjectFinder.Method)); return (ObjectFinder.Method) values.GetValue(index); } }<file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using EnergyBarToolkit; using UnityEditor; using UnityEngine; [InitializeOnLoad] public class UpgradeWindow : EditorWindow { private const string LastQueryTime = "LastQueryTime"; private const string DoNotShow = "DoNotShow"; private const string QueryVersion = "QueryVersion"; public static string queryVersion { get { return EditorPrefs.GetString(QueryVersion, "0"); } set { EditorPrefs.SetString(QueryVersion, value); } } public static bool doNotShow { get { return EditorPrefs.GetBool(DoNotShow, false); } set { EditorPrefs.SetBool(DoNotShow, value); } } public static float lastQueryTime { get { return EditorPrefs.GetFloat(LastQueryTime, float.MaxValue); } set { EditorPrefs.SetFloat(LastQueryTime, value);} } static UpgradeWindow() { EditorApplication.delayCall += () => { if (CanShow()) { ShowWindow(); } }; } public static void ShowWindow() { var w = GetWindow<UpgradeWindow>(true, "EBT Upgrade", true); w.minSize = new Vector2(540, 380); } private static bool CanShow() { try { if (queryVersion != Version.current) { return true; // always show if version is different } if (doNotShow) { return false; // the same version, do not show } if (EditorApplication.timeSinceStartup > lastQueryTime) { // most probably tring to show more than once in current editor instance return false; } return true; } finally { lastQueryTime = (float) EditorApplication.timeSinceStartup; queryVersion = Version.current; } } #if EBT_DEBUG [MenuItem("Tools/EBT Debug/Upgrade Window/Show")] public static void DebugShow() { ShowWindow(); } [MenuItem("Tools/EBT Debug/Upgrade Window/Reset")] public static void DebugReset() { doNotShow = false; lastQueryTime = float.MaxValue; } [MenuItem("Tools/EBT Debug/Upgrade Window/Can show?")] public static void DebugCanShow() { EditorUtility.DisplayDialog("Can Show?", CanShow() ? "Yes!" : "No!", "OK"); } #endif void OnGUI() { var style = new GUIStyle(GUI.skin.label); style.fontSize = 25; style.normal.textColor = Color.white; //style.fontStyle = FontStyle.Bold; GUI.color = new Color(1, 61 / 255f, 61 / 255f); GUI.DrawTexture(new Rect(0, 0, Screen.width, 50), Texture2D.whiteTexture); GUI.color = Color.white; GUILayout.Space(10); GUILayout.Label("Energy Bar Toolkit Upgrade Info", style); EditorGUILayout.Space(); EditorGUILayout.Space(); style = new GUIStyle(GUI.skin.label); GUILayout.Label("Thank you for upgrading Energy Bar Toolkit to " + Version.current + "!"); EditorGUILayout.Space(); style.fontSize = 15; GUILayout.Label("Important!", style); MadGUI.Error("Remember to backup your project before upgrading Energy Bar Toolkit to newer version!"); GUILayout.Label("Remember that...", style); MadGUI.Warning("If you see errors after upgrading Energy Bar Toolkit, please remove Energy Bar Toolkit " + "directory and import it again."); MadGUI.Warning("OnGUI bars will not work with Unity 5 and those are no longer maintained."); GUILayout.Label("Tips", style); MadGUI.Info("Mesh bars are now deprecated. We strongly recommend to use new uGUI bars!"); GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); doNotShow = EditorGUILayout.ToggleLeft("Do not show again until next upgrade", doNotShow); if (GUILayout.Button("Changelog")) { Application.OpenURL(string.Format("http://energybartoolkit.madpixelmachine.com/doc/{0}/changelog.html", Version.current)); } EditorGUILayout.EndHorizontal(); } }<file_sep>/* * Energy Bar Toolkit by Mad Pixel Machine * http://www.madpixelmachine.com */ using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; namespace EnergyBarToolkit { public class MenuItems : ScriptableObject { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== static Transform ActiveParentOrPanel() { Transform parentTransform = null; var transforms = Selection.transforms; if (transforms.Length > 0) { var firstTransform = transforms[0]; if (MadTransform.FindParent<MadPanel>(firstTransform) != null) { parentTransform = firstTransform; } } if (parentTransform == null) { var panel = MadPanel.UniqueOrNull(); if (panel != null) { parentTransform = panel.transform; } } return parentTransform; } static T Create<T>(string name) where T : Component { var parent = Selection.activeTransform; var component = MadTransform.CreateChild<T>(parent, name); Selection.activeObject = component.gameObject; return component; } [MenuItem("GameObject/UI/Energy Bar Toolkit/Filled Bar", false, 0)] [MenuItem("Tools/Energy Bar Toolkit/uGUI/Create Filled Bar", false, 0)] static void CreateFilledUGUI() { UGUIBarsBuilder.CreateFilled(); } [MenuItem("GameObject/UI/Energy Bar Toolkit/Sliced Bar", false, 1)] [MenuItem("Tools/Energy Bar Toolkit/uGUI/Create Sliced Bar", false, 1)] static void CreateSlicedUGUI() { UGUIBarsBuilder.CreateSliced(); } [MenuItem("GameObject/UI/Energy Bar Toolkit/Repeated Bar", false, 2)] [MenuItem("Tools/Energy Bar Toolkit/uGUI/Create Repeated Bar", false, 2)] static void CreateRepeatedUGUI() { UGUIBarsBuilder.CreateRepeated(); } [MenuItem("GameObject/UI/Energy Bar Toolkit/Sequence Bar", false, 3)] [MenuItem("Tools/Energy Bar Toolkit/uGUI/Create Sequence Bar", false, 3)] static void CreateSequenceUGUI() { UGUIBarsBuilder.CreateSequence(); } [MenuItem("GameObject/UI/Energy Bar Toolkit/Transform Bar", false, 4)] [MenuItem("Tools/Energy Bar Toolkit/uGUI/Create Transform Bar", false, 4)] static void CreateTransformUGUI() { UGUIBarsBuilder.CreateTransform(); } [MenuItem("Tools/Energy Bar Toolkit/uGUI/Add Components/Follow Object", false, 50)] static void AttachFollowObject() { if (Selection.activeGameObject != null && Selection.activeGameObject.GetComponent<EnergyBarUGUIBase>()) { Selection.activeGameObject.AddComponent<EnergyBarFollowObject>(); } else { EditorUtility.DisplayDialog("Select uGUI Bar First", "You have to select uGUI bar first!", "OK"); } } [MenuItem("Tools/Energy Bar Toolkit/uGUI/Add Components/Spawner", false, 51)] static void AttachSpawner() { Selection.activeGameObject.AddComponent<EnergyBarSpawnerUGUI>(); } [MenuItem("Tools/Energy Bar Toolkit/Online Resources/Online Manual", false, 101)] static void OnlineManual() { Application.OpenURL( "http://energybartoolkit.madpixelmachine.com/documentation.html"); } [MenuItem("Tools/Energy Bar Toolkit/Online Resources/Examples", false, 102)] static void Examples() { Application.OpenURL( "http://energybartoolkit.madpixelmachine.com/demo.html"); } [MenuItem("Tools/Energy Bar Toolkit/Online Resources/Change Log", false, 103)] static void ReleaseNotes() { Application.OpenURL( "http://energybartoolkit.madpixelmachine.com/doc/latest/changelog.html"); } [MenuItem("Tools/Energy Bar Toolkit/Online Resources/MadPixelMachine", false, 104)] static void MadPixelMachine() { Application.OpenURL( "http://madpixelmachine.com"); } [MenuItem("Tools/Energy Bar Toolkit/Online Resources/Support", false, 150)] static void Support() { Application.OpenURL( "http://energybartoolkit.madpixelmachine.com/doc/latest/support.html"); } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/Initialize", false, 1000)] static void InitTool() { MadInitTool.ShowWindow(); } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/Create Atlas", false, 1050)] static void CreateAtlas() { MadAtlasBuilder.CreateAtlas(); } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/Create Font", false, 1051)] static void CreateFont() { MadFontBuilder.CreateFont(); } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/UI/Sprite", false, 1100)] static void CreateSprite() { var sprite = MadTransform.CreateChild<MadSprite>(ActiveParentOrPanel(), "sprite"); Selection.activeGameObject = sprite.gameObject; } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/UI/Text", false, 1101)] static void CreateText() { var text = MadTransform.CreateChild<MadText>(ActiveParentOrPanel(), "text"); Selection.activeGameObject = text.gameObject; } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/UI/Anchor", false, 1102)] static void CreateAnchor() { var anchor = MadTransform.CreateChild<MadAnchor>(ActiveParentOrPanel(), "Anchor"); Selection.activeGameObject = anchor.gameObject; } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/Filled", false, 1200)] static void CreateMeshFillRenderer() { FilledRenderer3DBuilder.Create(); } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/Repeated", false, 1201)] static void CreateMeshRepeatRenderer() { RepeatRenderer3DBuilder.Create(); } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/Sequence", false, 1202)] static void CreateMeshSequenceRenderer() { SequenceRenderer3DBuilder.Create(); } [MenuItem("Tools/Energy Bar Toolkit/Old/Mesh Bars/Transform", false, 1203)] static void CreateMeshTransformRenderer() { TransformRenderer3DBuilder.Create(); } [MenuItem("Tools/Energy Bar Toolkit/Old/OnGUI Bars/Fill Renderer", false, 1210)] static void CreateFillRendererOnGUI() { Create<EnergyBarRenderer>("fill renderer"); } [MenuItem("Tools/Energy Bar Toolkit/Old/OnGUI Bars/Repeat Renderer", false, 1211)] static void CreateRepeatRendererOnGUI() { Create<EnergyBarRepeatRenderer>("repeat renderer"); } [MenuItem("Tools/Energy Bar Toolkit/Old/OnGUI Bars/Sequence Renderer", false, 1212)] static void CreateSequenceRendererOnGUI() { Create<EnergyBarSequenceRenderer>("sequence renderer"); } [MenuItem("Tools/Energy Bar Toolkit/Old/OnGUI Bars/Transform Renderer", false, 1213)] static void CreateTransformRendererOnGUI() { Create<EnergyBarTransformRenderer>("transform renderer"); } // =========================================================== // Static Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } } // namespace<file_sep>using UnityEngine; using System.Collections; using DG.Tweening; public class SkillManager : MonoBehaviour { static SkillManager instance; public static SkillManager Instance { get { return instance; } } public SkillInfo[] arrSkillInfo; void Awake() { if(instance == null) instance = this; } // Use this for initialization void Start () { GameObject player = GameObject.FindGameObjectWithTag("Player"); print (player.name); arrSkillInfo[0].skill = player.GetComponent<Skill1ShoutingOut>(); arrSkillInfo[1].skill = player.GetComponent<Skill2GusleMaker>(); arrSkillInfo[2].skill = player.GetComponent<Skill3HungryAttacking>(); arrSkillInfo[3].skill = player.GetComponent<Skill4AngryAttacking>(); arrSkillInfo[4].skill = player.GetComponent<Skill5PlazmaMaker>(); arrSkillInfo[5].skill = player.GetComponent<Skill6LaserRotation>(); for (int i = 0; i < arrSkillInfo.Length; i++) { arrSkillInfo[i].skillCalculator.skillInfo = arrSkillInfo[i]; } AllSKillEventRegiste(); InGameManager.Instance.EventTimeLimitBegin += StartUseAllSkill; InGameManager.Instance.EventTimeLimitEnd += StopUseAllSKill; } public void StartUseAllSkill() { for (int i = 0; i < arrSkillInfo.Length; i++) { if(arrSkillInfo[i].isActive) OnUseSkill(arrSkillInfo[i]); } } public void StopUseAllSKill() { for (int i = 0; i < arrSkillInfo.Length; i++) { if(arrSkillInfo[i].isActive) OnStopSkill(arrSkillInfo[i]); } } //스킬 이벤트 등록 public void AllSKillEventRegiste() { for (int i = 0; i < arrSkillInfo.Length; i++) { SkillInfo info = arrSkillInfo[i]; if (info.skill != null) info.isActive = true; info.skillCalculator.EventCoolTimeDone -= OnUseSkill; if(info.isActive) { info.skillCalculator.EventCoolTimeDone += OnUseSkill; info.imgSkillSlot.sprite = info.sprSkillActiveImage; } else { info.imgSkillSlot.sprite = info.sprSkillDeActiveImage; } } } private void OnUseSkill(SkillInfo info) { //위치 리셋 info.skillCalculator.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, -20f); info.imgSkillSlot.transform.DOPunchScale(new Vector3(0.4f,0.4f,0.4f), 0.2f, 0); //스킬 사용 info.skill.UseSkill(); //다시 쿨타임 계산 info.skillCalculator.BeginCalculateCoolTime(); } void OnStopSkill(SkillInfo info) { info.skillCalculator.StopCalculateCoolTime(); } // Update is called once per frame void Update () { } } <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using PathologicalGames; [CustomEditor(typeof(AngleLimitModifier)), CanEditMultipleObjects] public class AngleLimitModifierInspector : Editor { protected SerializedProperty debugLevel; protected SerializedProperty origin; protected SerializedProperty angle; protected SerializedProperty flatAngleCompare; protected SerializedProperty flatCompareAxis; protected SerializedProperty filterType; protected void OnEnable() { this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.origin = this.serializedObject.FindProperty("_origin"); this.angle = this.serializedObject.FindProperty("angle"); this.flatAngleCompare = this.serializedObject.FindProperty("flatAngleCompare"); this.flatCompareAxis = this.serializedObject.FindProperty("flatCompareAxis"); this.filterType = this.serializedObject.FindProperty("filterType"); } public override void OnInspectorGUI() { this.serializedObject.Update(); Object[] targetObjs = this.serializedObject.targetObjects; AngleLimitModifier curEditTarget; GUIContent content; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; EditorGUI.indentLevel = 0; EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Origin", "The transform used to determine alignment. If not used, this will be the transform " + "of the GameObject this component is attached to." ); EditorGUILayout.PropertyField(this.origin, content); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (AngleLimitModifier)targetObjs[i]; Undo.RecordObject(curEditTarget, targetObjs[0].GetType() + " origin"); curEditTarget.origin = (Transform)this.origin.objectReferenceValue; } } EditorGUILayout.BeginHorizontal(); EditorGUIUtility.labelWidth = 106; content = new GUIContent ( "Angle Tolerance", "If waitForAlignment is true: If the emitter is pointing towards " + "the target within this angle in degrees, the target can be fired on." ); EditorGUILayout.PropertyField(this.angle, content); EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; content = new GUIContent ( "Flat Comparison", "If false the actual angles will be compared for alignment. " + "(More precise. Emitter must point at target.)\n" + "If true, only the direction matters. " + "(Good when turning in a direction but perfect alignment isn't needed.)" ); PGEditorUtils.ToggleButton(this.flatAngleCompare, content, 88); EditorGUILayout.EndHorizontal(); if (this.flatAngleCompare.boolValue) { EditorGUI.indentLevel += 1; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); // To make the rest of the row right-justified content = new GUIContent ( "Flatten Axis", "The axis to flatten when comparing angles to see if alignment has occurred. " + "For example, for a 2D game, this should be Z. For a 3D game that wants to " + "ignore altitude, set this to Y." ); EditorGUILayout.PropertyField(this.flatCompareAxis, content, GUILayout.Width(228)); EditorGUILayout.EndHorizontal(); EditorGUI.indentLevel -= 1; } content = new GUIContent ( "Filter Type", "Determines if filtering will be performed on a TargetTracker's targets or an " + "EventTrigger's targets. See the component description for more detail. This is" + "ignored unless a its GameObject has both. Otherwise the mode will be " + "auto-detected." ); EditorGUILayout.PropertyField(this.filterType, content); GUILayout.Space(4); content = new GUIContent ( "Debug Level", "Set it higher to see more verbose information." ); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } }<file_sep>/* * Energy Bar Toolkit by Mad Pixel Machine * http://www.madpixelmachine.com */ using UnityEngine; using System.Collections; using System.Collections.Generic; namespace EnergyBarToolkit { [ExecuteInEditMode] public class EnergyBarPresentationColorize : MonoBehaviour { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public Rect position; public EnergyBarRenderer b1, b2, b3, b4, b5, b6; public bool colorized; public Color b1a, b1b, b2a, b2b, b3a, b3b, b4a, b4b, b5a, b5b, b6a, b6b; // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== void Start() { } void Update() { } void OnGUI() { if (colorized = GUI.Toggle(position, colorized, "Colorize!")) { b1.textureForegroundColor = b1a; b1.textureBarColor = b1b; b2.textureForegroundColor = b2a; b2.textureBarColor = b2b; b3.textureForegroundColor = b3a; b3.textureBarColor = b3b; b4.textureForegroundColor = b4a; b4.textureBarColor = b4b; b5.textureForegroundColor = b5a; b5.textureBarColor = b5b; b6.textureForegroundColor = b6a; b6.textureBarColor = b6b; } else { foreach (var b in new EnergyBarRenderer[] { b1, b2, b3, b4, b5, b6 }) { b.textureBarColor = Color.white; b.textureForegroundColor = Color.white; } } } // =========================================================== // Static Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } } // namespace <file_sep>using UnityEngine; using System.Collections; public class WavingNwayShooter : MonoBehaviour { public float ShotAngle; public float ShotAngleRange; public float WavingAngleRange; public float ShotSpeed; public int ShotCount; public int Interval; public int Cycle; private int Timer; public bool canShoot = true; public GameObject bullet; public int bulletMoney; public float bulletHp; Transform tr; void Awake() { tr = GetComponent<Transform>(); } void Update () { if (Timer%Interval == 0 && canShoot) { EnemyLib.instance.ShootNWay( tr.position, ShotAngle + WavingAngleRange * Mathf.Sin(Mathf.PI * 2 * Timer / Cycle), ShotAngleRange, ShotSpeed, ShotCount, 0, 0, bullet, bulletMoney, bulletHp); } if (canShoot) Timer = (Timer + 1) % Cycle; if (!canShoot) Timer = 0; } } <file_sep>using UnityEngine; using System.Collections; using PathologicalGames; public class DemoAreaTargetTrackerOnNotDetected : MonoBehaviour { protected TargetTracker tracker; protected void Awake() { this.tracker = this.GetComponent<TargetTracker>(); } // OnEnable and OnDisable add the check box in the inspector too. protected void OnEnable() { if (this.tracker != null) this.tracker.AddOnNotDetectedDelegate(this.OnNotDetected); } protected void OnDisable() { if (this.tracker != null) this.tracker.RemoveOnNotDetectedDelegate(this.OnNotDetected); } protected void OnNotDetected(TargetTracker source, Target target) { Debug.Log ( string.Format("OnNotDetected triggered for tracker '{0}' by target '{1}'.", source, target) ); } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System.Collections.Generic; using UnityEngine; namespace EnergyBarToolkit { [ExecuteInEditMode] public class InstantiateRandom : MonoBehaviour { #region Public Fields public EnergyBarSpawnerUGUI prefab; public Bounds bounds; #endregion #region Private Fields private List<GameObject> instances = new List<GameObject>(); #endregion #region Unity Methods void OnGUI() { if (!Application.isPlaying) { GUILayout.Label("Hit the Play button!"); } else { if (GUILayout.Button("Instantiate Now")) { var instance = (EnergyBarSpawnerUGUI) Instantiate(prefab, RandomPosition(), Quaternion.identity); instances.Add(instance.gameObject); } if (GUILayout.Button("Destroy Any") && instances.Count > 0) { int index = Random.Range(0, instances.Count); var go = instances[index]; Destroy(go); instances.RemoveAt(index); } } } private Vector3 RandomPosition() { return new Vector3( Random.Range(bounds.min.x, bounds.max.x), Random.Range(bounds.min.y, bounds.max.y), Random.Range(bounds.min.z, bounds.max.z)); } #endregion } } // namespace<file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System; using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace EnergyBarToolkit { public class ColorBind : MonoBehaviour { #region Fields public EnergyBarBase.Tex tex; private MadSprite sprite; #endregion #region Slots void OnEnable() { sprite = GetComponent<MadSprite>(); } void Update() { if (tex != null) { sprite.tint = tex.color; } } #endregion } }<file_sep>/* * Copyright (c) Mad <NAME> * http://www.madpixelmachine.com/ */ namespace EnergyBarToolkit { public class Version { public static string current { get { return "3.0.3"; } } } } // namespace<file_sep>using UnityEngine; using System.Collections; public class Skill4AngryAttacking : MonoBehaviour, ISkill { public status skillset; public float intervalTime, shotIntervalTime, bulletSpeed; public int shotCnt; public DirectionalShooter[] shots; void Start() { StartCoroutine("Delay"); UseSkill(); } public void SetSkill(int damage, float reload, int bulletCnt, float bulletStandTime, float bulletSpeed, float skillIntervalTime, float shotIntervalTime) { skillset.damage = damage; skillset.distance = bulletStandTime; skillset.reload = reload; this.shotCnt = bulletCnt; this.intervalTime = skillIntervalTime; this.shotIntervalTime = shotIntervalTime; this.bulletSpeed = bulletSpeed; } public void UseSkill() { StartCoroutine("Shot"); } IEnumerator Shot() { for (int i = 0; i < shots.Length; i+=2) { shots[i].canShoot = true; shots[i].skill = true; shots[i].shotDelay = shotIntervalTime; shots[i].shotSpeed = bulletSpeed; shots[i].bulletStandTime = skillset.distance; shots[i].bulletDmg = skillset.damage; shots[i].bulletCnt = shotCnt; shots[i].gameObject.SetActive(true); shots[i+1].canShoot = true; shots[i+1].skill = true; shots[i+1].shotDelay = shotIntervalTime; shots[i+1].shotSpeed = bulletSpeed; shots[i+1].bulletStandTime = skillset.distance; shots[i+1].bulletDmg = skillset.damage; shots[i+1].bulletCnt = shotCnt; shots[i+1].gameObject.SetActive(true); yield return new WaitForSeconds(intervalTime); shots[i].gameObject.SetActive(false); shots[i + 1].gameObject.SetActive(false); } for (int i = shots.Length - 1 ; i > -1; i -= 2) { print("asd"); shots[i].canShoot = true; shots[i].skill = true; shots[i].shotDelay = shotIntervalTime; shots[i].shotSpeed = bulletSpeed; shots[i].bulletStandTime = skillset.distance; shots[i].bulletDmg = skillset.damage; shots[i].bulletCnt = shotCnt; shots[i].gameObject.SetActive(true); shots[i - 1].canShoot = true; shots[i - 1].skill = true; shots[i - 1].shotDelay = shotIntervalTime; shots[i - 1].shotSpeed = bulletSpeed; shots[i - 1].bulletStandTime = skillset.distance; shots[i - 1].bulletDmg = skillset.damage; shots[i - 1].bulletCnt = shotCnt; shots[i - 1].gameObject.SetActive(true); yield return new WaitForSeconds(intervalTime); shots[i].gameObject.SetActive(false); shots[i - 1].gameObject.SetActive(false); } } IEnumerator Delay() { while (true) { yield return new WaitForSeconds(skillset.reload); UseSkill(); } } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System.Collections.Generic; using UnityEditor.AnimatedValues; using UnityEditorInternal; using UnityEngine; using UnityEditor; using System.Collections; namespace EnergyBarToolkit { public class EnergyBarUGUIInspectorBase : EnergyBarInspectorBase { protected SerializedProperty spritesBackground; protected SerializedProperty spritesForeground; protected SerializedProperty label; protected SerializedProperty debugMode; private ReorderableList backgroundList; private ReorderableList foregroundList; private AnimBool formatHelpAnimBool = new AnimBool(); public override void OnEnable() { base.OnEnable(); spritesBackground = serializedObject.FindProperty("spritesBackground"); spritesForeground = serializedObject.FindProperty("spritesForeground"); label = serializedObject.FindProperty("label"); debugMode = serializedObject.FindProperty("debugMode"); backgroundList = CreateLayerList(spritesBackground, "Background Sprites"); foregroundList = CreateLayerList(spritesForeground, "Foreground Sprites"); formatHelpAnimBool.valueChanged.AddListener(Repaint); } protected ReorderableList CreateLayerList(SerializedProperty sprites, string label) { var list = new ReorderableList(serializedObject, sprites, true, true, true, true); list.drawHeaderCallback += rect => GUI.Label(rect, label); list.drawElementCallback += (rect, index, active, focused) => { rect.height = 16; rect.y += 2; FieldSprite(rect, sprites.GetArrayElementAtIndex(index), "Sprite"); }; list.onAddCallback += l => { sprites.arraySize++; var lastElement = sprites.GetArrayElementAtIndex(list.count - 1); var color = lastElement.FindPropertyRelative("color"); color.colorValue = Color.white; }; return list; } protected void FieldBackgroundSprites() { backgroundList.DoLayoutList(); } protected void FieldForegroundSprites() { //FieldSprites((target as EnergyBarUGUIBase).spritesForeground); foregroundList.DoLayoutList(); } protected void FieldSetNativeSize() { if (MadGUI.Button("Set Native Size")) { var b = (EnergyBarUGUIBase) target; MadUndo.RecordObject2(b.gameObject, "Set Native Size"); b.SetNativeSize(); } } protected void SectionDebugMode() { GUILayout.Label("Debug", "HeaderLabel"); using (MadGUI.Indent()) { MadGUI.PropertyField(debugMode, "Debug Mode"); } } private void FieldSprites(List<EnergyBarUGUIBase.SpriteTex> sprites) { var arrayList = new MadGUI.ArrayList<EnergyBarUGUIBase.SpriteTex>(sprites, tex => { FieldSprite(tex, ""); return tex; }); arrayList.onAdd += tex => tex.color = Color.white; if (arrayList.Draw()) { EditorUtility.SetDirty((target as EnergyBarUGUIBase).gameObject); } } public void FieldSprite(SerializedProperty p, string label) { FieldSprite(p, label, property => true); } public void FieldSprite(Rect rect, SerializedProperty p, string label) { FieldSprite(rect, p, label, property => true); } public void FieldSprite(SerializedProperty p, string label, MadGUI.Validator validator) { var sprite = p.FindPropertyRelative("sprite"); var color = p.FindPropertyRelative("color"); EditorGUILayout.BeginHorizontal(); MadGUI.PropertyField(sprite, label, validator); EditorGUILayout.PropertyField(color, new GUIContent(""), GUILayout.Width(90)); //MadGUI.PropertyField(color, ""); EditorGUILayout.EndHorizontal(); } public void FieldSprite(Rect rect, SerializedProperty p, string label, MadGUI.Validator validator) { var sprite = p.FindPropertyRelative("sprite"); var color = p.FindPropertyRelative("color"); var material = p.FindPropertyRelative("material"); //GUILayout.BeginArea(rect); //GUILayout.Label("Test"); // //EditorGUILayout.BeginHorizontal(); //MadGUI.PropertyField(sprite, label, validator); Rect r1, r2, r3; HorizSplit(rect, 0.7f, out r1, out r3); HorizSplit(r1, 0.5f, out r1, out r2); EditorGUI.PropertyField(r1, sprite, new GUIContent("")); EditorGUI.PropertyField(r2, material, new GUIContent("")); EditorGUI.PropertyField(r3, color, new GUIContent("")); // EditorGUILayout.PropertyField(color, new GUIContent(""), GUILayout.Width(90)); // //MadGUI.PropertyField(color, ""); // //EditorGUILayout.EndHorizontal(); //GUILayout.EndArea(); } private void HorizSplit(Rect inRect, float split, out Rect outRect1, out Rect outRect2) { outRect1 = new Rect(inRect.xMin, inRect.yMin, inRect.width * split, inRect.height); outRect2 = new Rect(outRect1.xMax, inRect.yMin, inRect.width - outRect1.width, inRect.height); } public void FieldSprite(EnergyBarUGUIBase.SpriteTex tex, string label) { EditorGUILayout.BeginHorizontal(); tex.sprite = (Sprite) EditorGUILayout.ObjectField(label, tex.sprite, typeof (Sprite), false); tex.color = EditorGUILayout.ColorField(tex.color); EditorGUILayout.EndHorizontal(); } protected void FieldLabel2() { MadGUI.PropertyField(label, "Label"); using (MadGUI.EnabledIf((target as EnergyBarUGUIBase).label != null)) { using (MadGUI.Indent()) { MadGUI.PropertyField(labelFormat, "Format"); formatHelpAnimBool.target = MadGUI.Foldout("Label Format Help", false); if (EditorGUILayout.BeginFadeGroup(formatHelpAnimBool.faded)) { EditorGUILayout.HelpBox(FormatHelp, MessageType.None); } EditorGUILayout.EndFadeGroup(); } } } protected void EnsureReadable(SerializedProperty spriteObject) { if (spriteObject.objectReferenceValue != null) { var sprite = spriteObject.objectReferenceValue as Sprite; if (!Utils.IsReadable(sprite.texture)) { if (EditorUtility.DisplayDialog("Set texture as readable?", string.Format("Texture '{0}' must be set as readable. Do it now?", sprite.name), "OK", "Cancel")) { Utils.SetReadable(sprite.texture); } else { spriteObject.objectReferenceValue = null; } } } } } } // namespace <file_sep>/* * Energy Bar Toolkit by Mad Pixel Machine * http://www.madpixelmachine.com */ using UnityEngine; using System.Collections; using System.Collections.Generic; namespace EnergyBarToolkit { [ExecuteInEditMode] public class AnimationPlayer : MonoBehaviour { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int x = 100; public int y = 100; public Animation anim; public EnergyBar[] animatedBars; // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== void Start() { } void Update() { } void OnGUI() { if (GUI.Button(new Rect(x, y, 150, 40), "Play Animation")) { foreach (var bar in animatedBars) { bar.animationEnabled = true; } anim.Play(); } if (GUI.Button(new Rect(x, y + 50, 150, 40), "Stop Animation")) { foreach (var bar in animatedBars) { bar.animationEnabled = false; } anim.Stop(); } } // =========================================================== // Static Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== } } // namespace <file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(TransformConstraint)), CanEditMultipleObjects] public class TransformConstraintInspector : ConstraintBaseInspector { protected SerializedProperty position; protected SerializedProperty outputPosX; protected SerializedProperty outputPosY; protected SerializedProperty outputPosZ; protected SerializedProperty rotation; protected SerializedProperty output; protected SerializedProperty scale; protected override void OnEnable() { base.OnEnable(); this.position = this.serializedObject.FindProperty("constrainPosition"); this.outputPosX = this.serializedObject.FindProperty("outputPosX"); this.outputPosY = this.serializedObject.FindProperty("outputPosY"); this.outputPosZ = this.serializedObject.FindProperty("outputPosZ"); this.rotation = this.serializedObject.FindProperty("constrainRotation"); this.output = this.serializedObject.FindProperty("output"); this.scale = this.serializedObject.FindProperty("constrainScale"); } protected override void OnInspectorGUIUpdate() { base.OnInspectorGUIUpdate(); GUIContent content; GUILayout.BeginHorizontal(); content = new GUIContent("Position", "Option to match the target's position."); EditorGUILayout.PropertyField(this.position, content); if (this.position.boolValue) { PGEditorUtils.ToggleButton(this.outputPosX, new GUIContent("X", "Toggle Costraint for this axis."), 24); PGEditorUtils.ToggleButton(this.outputPosY, new GUIContent("Y", "Toggle Costraint for this axis."), 24); PGEditorUtils.ToggleButton(this.outputPosZ, new GUIContent("Z", "Toggle Costraint for this axis."), 24); } GUILayout.EndHorizontal(); content = new GUIContent("Rotation", "Option to match the target's rotation."); EditorGUILayout.PropertyField(this.rotation, content); if (this.rotation.boolValue) { EditorGUI.indentLevel += 1; content = new GUIContent("Output", "Used to alter the way the rotations are set."); EditorGUILayout.PropertyField(this.output, content); EditorGUI.indentLevel -= 1; } content = new GUIContent("Scale", "Option to match the target's scale."); EditorGUILayout.PropertyField(this.scale, content); } } }<file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using UnityEngine; namespace EnergyBarToolkit { public class GoCircles : MonoBehaviour { #region Public Fields public float distance = 3; public float speed = 100; #endregion #region Private Fields private Vector3 startPosition; private float angle; #endregion #region Public Methods #endregion #region Unity Methods void Start() { startPosition = transform.position; } void Update() { float x = Mathf.Cos(Mathf.Deg2Rad * angle) * distance; float z = Mathf.Sin(Mathf.Deg2Rad * angle) * distance; transform.position = startPosition + new Vector3(x, 0, z); angle += Time.deltaTime * speed; } #endregion #region Private Methods #endregion #region Inner and Anonymous Classes #endregion } } // namespace<file_sep>using UnityEngine; using System.Collections; public class PlayerInfo : MonoBehaviour { public float hp; void HpManager(float num) { hp += num; } void OnTriggerEnter2D(Collider2D col) { if (col.CompareTag("Bullet_Boss")) { HpManager(-1); } } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; using UnityEngine.UI; public enum eCharType { None = -1, CharA, CharB, CharC } public enum eBossType { None = -1, BossA, BossB, BossC } public enum eBossLevel { None = -1, Low, Midium, High } public class GameManager : MonoBehaviour { static GameManager instance; public static GameManager Instance { get { return instance; } } public Scene currentScene; public int startSceneIdx = 0; public eBossType bossType; public eBossLevel bossLevel; public eCharType charType; public float onceAddGoldBonus = 0.1f; public int addGoldBonusPlusTime = 10; public float goldBonus = 0; public int totalGold = 0; //SelectBossScene Button[] arrBtnBoss; Button[] arrBtnLevel; //SelectCharScene Button[] arrBtnChar; Button btnBeginInGame; void Awake() { if (instance == null) instance = this; else Destroy(this.gameObject); } void Start() { DontDestroyOnLoad(this.gameObject); //GameObject.Find("BtnGameStart").GetComponent<Button>().onClick.AddListener(OnBtnGameStartClicked); SceneManager.sceneLoaded += OnSceneLoaded; SceneManager.LoadScene(startSceneIdx); //SelectBossScene arrBtnBoss = new Button[3]; arrBtnLevel = new Button[3]; //SelectCharScene arrBtnChar = new Button[3]; Init(); } void Init() { for (int i = 0; i < 3; i++) { arrBtnLevel[i] = null; } bossType = eBossType.None; bossLevel = eBossLevel.None; charType = eCharType.None; } private void OnSceneLoaded(Scene scene, LoadSceneMode mode) { currentScene = scene; print(mode); switch (scene.name) { case "TitleScene": { Debug.Log("TitleSceneLoaded"); GameObject.Find("BtnGameStart").GetComponent<Button>().onClick.AddListener(OnBtnGameStartClicked); } break; case "SelectBossScene": { Debug.Log("SelectBossSceneLoaded"); //GameObject.Find("ImgBossA").GetComponent<Button>().onClick.AddListener() bossType = eBossType.None; arrBtnBoss[(int)eBossType.BossA] = GameObject.Find("BtnBossA").GetComponent<Button>(); arrBtnBoss[(int)eBossType.BossB] = GameObject.Find("BtnBossB").GetComponent<Button>(); arrBtnBoss[(int)eBossType.BossC] = GameObject.Find("BtnBossC").GetComponent<Button>(); arrBtnBoss[(int)eBossType.BossA].onClick.AddListener(OnBtnBossAClicked); arrBtnBoss[(int)eBossType.BossB].onClick.AddListener(OnBtnBossBClicked); arrBtnBoss[(int)eBossType.BossC].onClick.AddListener(OnBtnBossCClicked); /* arrBtnLevel[(int)eBossLevel.Low] = GameObject.Find("BtnLowLevelBoss").GetComponent<Button>(); arrBtnLevel[(int)eBossLevel.Midium] = GameObject.Find("BtnMidiumLevelBoss").GetComponent<Button>(); arrBtnLevel[(int)eBossLevel.High] = GameObject.Find("BtnHighLevelBoss").GetComponent<Button>(); arrBtnLevel[(int)eBossLevel.Low].onClick.AddListener(OnBtnLowLevelBossClicked); arrBtnLevel[(int)eBossLevel.Midium].onClick.AddListener(OnBtnMidiumLevelBossClicked); arrBtnLevel[(int)eBossLevel.High].onClick.AddListener(OnBtnHighLevelBossClicked); */ } break; case "SelectCharScene": { Debug.Log("SelectCharSceneLoaded"); charType = eCharType.None; btnBeginInGame = GameObject.Find("BtnBeginInGame").GetComponent<Button>(); btnBeginInGame.onClick.AddListener(OnBtnBeginInGameClicked); GameObject.Find("BtnBackToTitle").GetComponent<Button>().onClick.AddListener(OnBtnBackToTitleClicked); arrBtnChar[(int)eCharType.CharA] = GameObject.Find("BtnCharA").GetComponent<Button>(); arrBtnChar[(int)eCharType.CharB] = GameObject.Find("BtnCharB").GetComponent<Button>(); arrBtnChar[(int)eCharType.CharC] = GameObject.Find("BtnCharC").GetComponent<Button>(); arrBtnChar[(int)eCharType.CharA].onClick.AddListener(OnBtnCharAClicked); arrBtnChar[(int)eCharType.CharB].onClick.AddListener(OnBtnCharBClicked); arrBtnChar[(int)eCharType.CharC].onClick.AddListener(OnBtnCharCClicked); } break; default: break; } } //TitleScene void OnBtnGameStartClicked() { Debug.Log("shit"); SceneManager.LoadScene("SelectBossScene"); } void OnBtnBossAClicked() { //velButtonInteractable(eBossType.BossA); bossType = eBossType.BossA; LoadSceneSelectCharScene(); } void OnBtnBossBClicked() { //velButtonInteractable(eBossType.BossB); bossType = eBossType.BossB; LoadSceneSelectCharScene(); } void OnBtnBossCClicked() { //LevelButtonInteractable(eBossType.BossC); bossType = eBossType.BossC; LoadSceneSelectCharScene(); } /* void LevelButtonInteractable(eBossType type) { if (bossType == type) return; for (int i = 0; i < 3; i++) { arrBtnLevel[i].interactable = true; } GameObject.Find("ImgSelector").transform.position = arrBtnBoss[(int)type].transform.position; } */ //SelectBossScene void OnBtnLowLevelBossClicked() { LoadSceneSelectCharScene(); bossLevel = eBossLevel.Low; } void OnBtnMidiumLevelBossClicked() { LoadSceneSelectCharScene(); bossLevel = eBossLevel.Midium; } void OnBtnHighLevelBossClicked() { LoadSceneSelectCharScene(); bossLevel = eBossLevel.High; } void LoadSceneSelectCharScene() { SceneManager.LoadScene("SelectCharScene"); } //SelectCharScene void OnBtnCharAClicked() { CharButtonInteractable(eCharType.CharA); charType = eCharType.CharA; } void OnBtnCharBClicked() { CharButtonInteractable(eCharType.CharB); charType = eCharType.CharB; } void OnBtnCharCClicked() { CharButtonInteractable(eCharType.CharC); charType = eCharType.CharC; } void CharButtonInteractable(eCharType type) { if (charType == type) return; btnBeginInGame.interactable = true; GameObject.Find("ImgSelector").transform.position = arrBtnChar[(int)type].transform.position; } void OnBtnBeginInGameClicked() { Debug.Log("BossType : " + bossType); Debug.Log("BossLevel : " + bossLevel); Debug.Log("Character Type : " + charType); switch (bossType) { case eBossType.BossA: SceneManager.LoadScene("Stage1"); break; case eBossType.BossB: SceneManager.LoadScene("Stage2"); break; case eBossType.BossC: SceneManager.LoadScene("Stage3"); break; default: break; } SceneManager.LoadScene("InGameScene",LoadSceneMode.Additive); } void OnBtnBackToTitleClicked() { SceneManager.LoadScene("SelectBossScene"); } } <file_sep>using UnityEngine; using System.Collections; public class AimingNwayShooter : MonoBehaviour { public float ShotAngleRange; public float ShotSpeed; public int Interval; private int Timer; public int ShotCount; public int MoveTime; public int StopTime; public bool canShoot = true; public GameObject bullet; public int bulletMoney; public float bulletHp; Transform tr; void Awake() { tr = GetComponent<Transform>(); } void Update () { if (Timer == 0 && canShoot) EnemyLib.instance.ShootPlacedNWay(tr.position, EnemyLib.instance.GetPlayerAngle(transform.position), ShotAngleRange, ShotSpeed, ShotCount, MoveTime, StopTime, bullet, bulletMoney, bulletHp); Timer = (Timer + 1) % Interval; } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System; using System.Reflection; using UnityEngine; using Object = UnityEngine.Object; namespace EnergyBarToolkit { [Serializable] public class ObjectFinder { #region Public Fields public Method chosenMethod = Method.ByType; public string path; public string tag; public GameObject reference; public string typeString; public string assembly; #endregion #region Private Fields #endregion #region Public Methods public ObjectFinder(Type type, string defaultPath = "", string defaultTag = "", Method defaultMethod = Method.ByType) { path = defaultPath; tag = defaultTag; chosenMethod = defaultMethod; typeString = type.ToString(); #if !UNITY_WINRT assembly = Assembly.GetExecutingAssembly().FullName; #endif } public T Lookup<T>(Object parent) where T : Component { switch (chosenMethod) { case Method.ByPath: { var go = GameObject.Find(path); if (go != null) { return GetComponent<T>(go); } else { Debug.LogError("Cannot find object on path " + path, parent); return null; } } case Method.ByTag: { var go = GameObject.FindWithTag(tag); if (go != null) { return GetComponent<T>(go); } else { Debug.LogError("Cannot find object by tag " + tag, parent); return null; } } case Method.ByType: { #if !UNITY_WINRT Type type = GetType(); var component = Object.FindObjectOfType(type); if (component == null) { Debug.LogError("Cannot find object of type " + type, parent); } return component as T; #else Debug.LogError("Lookup by type not supported for Windows Store Apps"); return null; #endif } case Method.ByReference: return GetComponent<T>(reference); default: throw new ArgumentOutOfRangeException(); } } private T GetComponent<T>(GameObject go) where T : Component { var component = go.GetComponent<T>(); if (component == null) { Debug.LogError("Cannot find component " + typeString + " on " + go, go); } return component; } private new Type GetType() { return Type.GetType(typeString + ", " + assembly); } #endregion #region Inner and Anonymous Classes [Flags] public enum Method { ByPath = 1, ByTag = 2, ByType = 4, ByReference = 8, } #endregion } } // namespace<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(LookAtBaseClass)), CanEditMultipleObjects] public class LookAtBaseClassInspector : ConstraintBaseInspector { protected SerializedProperty pointAxis; protected SerializedProperty upAxis; protected override void OnEnable() { base.OnEnable(); this.pointAxis = this.serializedObject.FindProperty("pointAxis"); this.upAxis = this.serializedObject.FindProperty("upAxis"); } protected override void OnInspectorGUIUpdate() { base.OnInspectorGUIUpdate(); GUIContent content; content = new GUIContent ( "Point Axis", "The axis used to point at the target." ); EditorGUILayout.PropertyField(this.pointAxis, content); content = new GUIContent ( "Up Axis", "The axis to stabalize the look-at result so it does roll on the point axis. This should never be the " + "same as the point axis." ); EditorGUILayout.PropertyField(this.upAxis, content); } } }<file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; namespace PathologicalGames { /// <description> /// Constrain this transform to a target's scale, rotation and/or translation. /// </description> [AddComponentMenu("Path-o-logical/UnityConstraints/Constraint - Transform (Postion, Rotation, Scale)")] public class TransformConstraint : ConstraintBaseClass { /// <summary> /// Option to match the target's position /// </summary> public bool constrainPosition = true; /// <summary> /// If false, the rotation in this axis will not be affected /// </summary> public bool outputPosX = true; /// <summary> /// If false, the rotation in this axis will not be affected /// </summary> public bool outputPosY = true; /// <summary> /// If false, the rotation in this axis will not be affected /// </summary> public bool outputPosZ = true; /// <summary> /// Option to match the target's rotation /// </summary> public bool constrainRotation = false; /// <summary> /// Used to alter the way the rotations are set /// </summary> public UnityConstraints.OUTPUT_ROT_OPTIONS output = UnityConstraints.OUTPUT_ROT_OPTIONS.WorldAll; /// <summary> /// Option to match the target's scale. This is a little more expensive performance /// wise and not needed very often so the default is false. /// </summary> public bool constrainScale = false; // Cache... internal Transform parXform; /// <summary> /// Cache as much as possible before starting the co-routine /// </summary> protected override void Awake() { base.Awake(); this.parXform = this.transform.parent; } /// <summary> /// Runs each frame while the constraint is active /// </summary> protected override void OnConstraintUpdate() { // Note: Do not run base.OnConstraintUpdate. It is not implimented if (this.constrainScale) this.SetWorldScale(target); if (this.constrainRotation) { this.transform.rotation = this.target.rotation; UnityConstraints.MaskOutputRotations(this.transform, this.output); } if (this.constrainPosition) { this.pos = this.transform.position; // Output only if wanted if (this.outputPosX) this.pos.x = this.target.position.x; if (this.outputPosY) this.pos.y = this.target.position.y; if (this.outputPosZ) this.pos.z = this.target.position.z; this.transform.position = pos; } } /// <summary> /// Runs when the noTarget mode is set to ReturnToDefault /// </summary> protected override void NoTargetDefault() { if (this.constrainScale) this.transform.localScale = Vector3.one; if (this.constrainRotation) this.transform.rotation = Quaternion.identity; if (this.constrainPosition) this.transform.position = Vector3.zero; } /// <summary> /// A transform used for all Perimeter Gizmos to calculate the final /// position and rotation of the drawn gizmo /// </summary> internal static Transform scaleCalculator; /// <summary> /// Sets this transform's scale to equal the target in world space. /// </summary> /// <param name="sourceXform"></param> public virtual void SetWorldScale(Transform sourceXform) { // Set the scale now that both Transforms are in the same space this.transform.localScale = this.GetTargetLocalScale(sourceXform); } /// <summary> /// Sets this transform's scale to equal the target in world space. /// </summary> /// <param name="sourceXform"></param> internal Vector3 GetTargetLocalScale(Transform sourceXform) { // Singleton: Create a hidden empty gameobject to use for scale calculations // All instances will this. A single empty game object is so small it will // never be an issue. Ever. if (TransformConstraint.scaleCalculator == null) { string name = "TransformConstraint_spaceCalculator"; // When the game starts and stops the reference can be lost but the transform // still exists. Re-establish the reference if it is found. var found = GameObject.Find(name); if (found != null) { TransformConstraint.scaleCalculator = found.transform; } else { var scaleCalc = new GameObject(name); scaleCalc.gameObject.hideFlags = HideFlags.HideAndDontSave; TransformConstraint.scaleCalculator = scaleCalc.transform; } } // Store the source's lossyScale, which is Unity's estimate of "world scale", // to this seperate Transform which doesn't have a parent (it is in world space) Transform refXform = TransformConstraint.scaleCalculator; // Cast the reference transform in to the space of the source Xform using // Parenting, then cast it back to set. refXform.parent = sourceXform; refXform.localRotation = Quaternion.identity; // Stablizes this solution refXform.localScale = Vector3.one; // Parent the reference transform to this object so they are in the same // space, now we have a local scale to use. refXform.parent = this.parXform; return refXform.localScale; } } }<file_sep>using UnityEngine; using System.Collections; using PathologicalGames; public enum PlayState { None = -1, Init, Play, BalanceAccounts, Store } public class InGameManager : MonoBehaviour { public event CallbackGameBegin EventGameBegin; public event CallbackGameEnd EventGameEnd; public event Callback EventPauseGame; public event Callback EventResumeGame; public event Callback EventTimeLimitBegin; public event Callback EventTimeLimitEnd; public event Callback EventReBoot; public event Callback EventBalanceAccounts; public event Callback EventEnterStore; public event Callback EventExitStore; static InGameManager instance; static public InGameManager Instance { get { return instance; } } void Awake() { if (instance == null) { instance = this; } } public UIManager uiManager; public int maxTimeLimit; public int leftTime; public bool isTimeLimitUpdating; public int[] skillBuild; public PlayState playState; public bool isPuaseGame = false; public int bossHp = 0; public int[] arrBossHp; public BossInfo bossInfo; void Start() { //Event EventGameBegin += GameBegin; EventGameEnd += GameEnd; EventPauseGame += PauseGame; EventResumeGame += ResumeGame; EventTimeLimitBegin += TimeLimitBegin; EventTimeLimitEnd += TimeLimitEnd; EventReBoot += ReBoot; EventBalanceAccounts += BalanceAccounts; EventEnterStore += EnterStore; EventExitStore += ExitStore; Init(); OnGameBegin(); } void Init() { GameManager.Instance.bossType = eBossType.BossC; switch (GameManager.Instance.bossType) { case eBossType.BossA: bossHp = arrBossHp [0]; break; case eBossType.BossB: bossHp = arrBossHp[1]; break; case eBossType.BossC: bossHp = arrBossHp[2]; break; } uiManager.SetMaxSliderBossHP (bossHp); bossInfo = GameObject.FindGameObjectWithTag ("Boss").GetComponent<BossInfo>(); bossInfo.hp = bossHp; leftTime = maxTimeLimit; uiManager.SetMaxSliderLimitTime(maxTimeLimit); isTimeLimitUpdating = false; playState = PlayState.Init; } void Update() { if(Input.GetKeyDown(KeyCode.Return)) { if(playState == PlayState.Play) OnReBoot(); } if (Input.GetKeyDown(KeyCode.P)) { if (isPuaseGame == false) OnPauseGame(); else OnResumeGame(); } } public void OnGameBegin() { if (EventGameBegin == null) Debug.Log("EventGameBegin is Empty"); else EventGameBegin(); } void GameBegin() { StartCoroutine(CoGameBegin()); } IEnumerator CoGameBegin() { yield return new WaitForSeconds(1f); playState = PlayState.Play; OnTimeLimitBegin(); } public void OnGameEnd(bool isWin) { if (EventGameEnd == null) Debug.Log("EventGameEnd is Empty"); else EventGameEnd(isWin); } void GameEnd(bool isWin) { Debug.Log("GameOver is Win : " + isWin); StartCoroutine(CoGameEnd()); } IEnumerator CoGameEnd() { yield return null; } public void OnPauseGame() { if (EventPauseGame == null) Debug.Log("EventPauseGame is Empty"); else EventPauseGame(); } void PauseGame() { Debug.Log("PauseGame"); isPuaseGame = true; } public void OnResumeGame() { if (EventResumeGame == null) Debug.Log("EventResumeGame is Empty"); else EventResumeGame(); } void ResumeGame() { Debug.Log("ResumeGame"); isPuaseGame = false; } public void OnTimeLimitBegin() { if (EventTimeLimitBegin == null) Debug.Log("EventTimeLimitBegin is Empty"); else { isTimeLimitUpdating = true; EventTimeLimitBegin(); } } void TimeLimitBegin() { Debug.Log("TimeLimitBegin"); StartCoroutine(CoTimeLimitUpdate()); } IEnumerator CoTimeLimitUpdate() { StartCoroutine(uiManager.CoUIUpdateLeftTime()); while (isTimeLimitUpdating) { if(isPuaseGame == false) { leftTime -= 1; if (leftTime < 0) { OnTimeLimitEnd(); } } yield return new WaitForSeconds(1f); } } public void OnTimeLimitEnd() { if(EventTimeLimitEnd == null) { Debug.Log("EventTimeLimitEnd is Empty"); } else { isTimeLimitUpdating = false; EventTimeLimitEnd(); } } void TimeLimitEnd() { Debug.Log("TimeLimitEnd"); OnGameEnd(false); } public void OnReBoot() { if (EventReBoot == null) Debug.Log("EventReBoot is Empty"); else EventReBoot(); } void ReBoot() { Debug.Log("ReBoot"); OnPauseGame(); StartCoroutine(CoReBoot()); } IEnumerator CoReBoot() { yield return null; //리붓 연출 PoolManager.Pools["Test"].DespawnAll(); yield return StartCoroutine(uiManager.CoUIReBoot()); OnBalanceAccounts(); } public void OnBalanceAccounts() { if (EventBalanceAccounts == null) Debug.Log("EventBalanceAccounts is Empty"); else EventBalanceAccounts(); } void BalanceAccounts() { Debug.Log("BalanceAccounts"); StartCoroutine(CoBalanceAccounts()); } IEnumerator CoBalanceAccounts() { yield return null; yield return StartCoroutine(uiManager.CoUIEnterBalanceAccounts()); yield return StartCoroutine(uiManager.CoUIExitBalanceAccounts()); OnEnterStore(); } public void OnEnterStore() { if (EventEnterStore == null) Debug.Log("EventEnterStore is Empty"); else EventEnterStore(); } void EnterStore() { Debug.Log("EnterStore"); StartCoroutine(CoEnterStore()); } IEnumerator CoEnterStore() { yield return null; yield return StartCoroutine(uiManager.CoUIEnterScore()); playState = PlayState.Store; } public void OnExitStore() { if (EventExitStore == null) Debug.Log("EventExitStore is Empty"); else EventExitStore(); } void ExitStore() { Debug.Log("ExitStore"); StartCoroutine(CoExitStore()); } IEnumerator CoExitStore() { yield return null; yield return StartCoroutine(uiManager.CoUIExitScore()); OnResumeGame(); playState = PlayState.Play; } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; using DG.Tweening; public class UIManager : MonoBehaviour { static UIManager instance; static public UIManager Instance { get { return instance; } } InGameManager inGameManager; void Awake() { instance = this; } public Text textTotalGold; public Text textBossHP; public EnergyBar sliderBossHP; public Text textLeftTime; public EnergyBar sliderLimitTime; public Image imgPlayerChar; public RectTransform panelStoreUI; public GameObject goImgReBoot; bool isPause = false; void Start() { inGameManager = GameObject.Find("InGameManager").GetComponent<InGameManager>(); SetTextTotalGold(0); SetMaxSliderBossHP(100); SetTextLeftTime(InGameManager.Instance.maxTimeLimit); } public IEnumerator CoUIUpdateLeftTime() { yield return new WaitForSeconds(1f); if(inGameManager.isPuaseGame == false) { SetTextLeftTime(inGameManager.leftTime); sliderLimitTime.SetValueCurrent(inGameManager.leftTime); } StartCoroutine(CoUIUpdateLeftTime()); } public IEnumerator CoUIReBoot() { yield return null; //연출 goImgReBoot.SetActive(true); yield return new WaitForSeconds(1f); goImgReBoot.SetActive(false); } public IEnumerator CoUIEnterBalanceAccounts() { yield return null; } public IEnumerator CoUIExitBalanceAccounts() { yield return null; } public IEnumerator CoUIEnterScore() { yield return null; panelStoreUI.DOAnchorPos(Vector2.zero, 1f); } public IEnumerator CoUIExitScore() { yield return null; panelStoreUI.DOAnchorPos(new Vector2(0f, -500f), 1f); } public void SetTextTotalGold(int totalGold) { textTotalGold.text = totalGold.ToString(); } //UI 보스 최대 체력값 설정 public void SetMaxSliderBossHP(int maxBossHp) { sliderBossHP.SetValueMax(maxBossHp); sliderBossHP.SetValueCurrent(maxBossHp); } public void SetTextBossHP(int bossHP) { textBossHP.text = bossHP.ToString(); } //UI 최대 남은 시간 설정 public void SetMaxSliderLimitTime(int limitTime) { sliderLimitTime.SetValueMax(limitTime); sliderLimitTime.SetValueCurrent(limitTime); } public void SetTextLeftTime(int leftTime) { if (leftTime < 0) return; textLeftTime.text = leftTime.ToString("##0."); } } <file_sep>using UnityEngine; using System.Collections; public class Shout : MonoBehaviour { public float dmg, range; void OnTriggerEnter2D(Collider2D col) { if (col.CompareTag("Bullet_Boss")) { if (col.GetComponent<Bullet>() == null) col.GetComponent<PlacedBullet>().HpManager(-1000); else col.GetComponent<Bullet>().HpManager(-1000); } } } <file_sep>using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; public class Table : MonoBehaviour { public List<RotationLaser> rotationLaserTable; public List<CirclePlazma> circlePlazmaTable; public List<Marble> marbleTable; public List<ShoutAttack> shoutAttackTable; public List<HungryAttack> hungryAttackTable; public List<AngryAttack> angryAttackTable; public GameObject buyBtn; public GameObject atkBuyBtn; public GameObject lenBuyBtn; public GameObject coTBuyBtn; public int haveSkills,skillIndex,buildIndex,atkBuy,lenBuy,cotBuy; public int[] buyAddition; public int atkAdditionCnt; public int lenAdditionCnt; public int cotAdditionCnt; public void SkillSelect(int index) { skillIndex = index; int build = InGameManager.Instance.skillBuild[index-1]; if (build == -1 && GameManager.Instance.totalGold >= buyAddition[haveSkills]) { buyBtn.SetActive(true); buyBtn.transform.GetChild(0).GetComponent<Text>().text = "획득\n" + buyAddition[haveSkills] + "Gold"; } else { buyBtn.SetActive(false); if (GameManager.Instance.totalGold >= atkBuy + (atkBuy * atkAdditionCnt)) { atkBuyBtn.SetActive(true); atkBuyBtn.transform.GetChild(0).GetComponent<Text>().text = "공격력 증가\n" +(atkBuy + (atkBuy * atkAdditionCnt))+"Gold"; } else atkBuyBtn.SetActive(false); if (GameManager.Instance.totalGold >= lenBuy + (lenBuy * lenAdditionCnt)) { lenBuyBtn.SetActive(true); lenBuyBtn.transform.GetChild(0).GetComponent<Text>().text = "사거리 증가\n" + lenBuy + (lenBuy * lenAdditionCnt) + "Gold"; } else lenBuyBtn.SetActive(false); if (GameManager.Instance.totalGold >= cotBuy + (cotBuy * cotAdditionCnt)) { coTBuyBtn.SetActive(true); coTBuyBtn.transform.GetChild(0).GetComponent<Text>().text = "쿨타임 감소\n" + cotBuy + (cotBuy * cotAdditionCnt) + "Gold"; } else coTBuyBtn.SetActive(false); } } public void Buy() { ++InGameManager.Instance.skillBuild[skillIndex]; GameManager.Instance.totalGold -= buyAddition[haveSkills]; UIManager.Instance.SetTextTotalGold(GameManager.Instance.totalGold); SkillSelect(skillIndex); } public void AtkBuy() { ++atkAdditionCnt; GameManager.Instance.totalGold -= atkBuy + (atkBuy * atkAdditionCnt); switch (skillIndex) { case 1: ++ShoutAttack.atkBuild; break; case 2: ++Marble.atkBuild; break; case 3: ++HungryAttack.atkBuild; break; case 4: ++AngryAttack.atkBuild; break; case 5: ++CirclePlazma.atkBuild; break; case 6: ++RotationLaser.atkBuild; break; default: break; } SkillSelect(skillIndex); } public void LenBuy() { ++lenAdditionCnt; GameManager.Instance.totalGold -= lenBuy + (lenBuy * lenAdditionCnt); switch (skillIndex) { case 1: ++ShoutAttack.lenBuild; break; case 2: ++Marble.lenBuild; break; case 3: ++HungryAttack.lenBuild; break; case 4: ++AngryAttack.lenBuild; break; case 5: ++CirclePlazma.lenBuild; break; case 6: ++RotationLaser.lenBuild; break; default: break; } SkillSelect(skillIndex); } public void CotBuy() { ++cotAdditionCnt; GameManager.Instance.totalGold -= cotBuy + (cotBuy * cotAdditionCnt); switch (skillIndex) { case 1: ++ShoutAttack.cotBuild; break; case 2: ++Marble.cotBuild; break; case 3: ++HungryAttack.cotBuild; break; case 4: ++AngryAttack.cotBuild; break; case 5: ++CirclePlazma.cotBuild; break; case 6: ++RotationLaser.cotBuild; break; default: break; } SkillSelect(skillIndex); } } [System.Serializable] public class RotationLaser { public float hp, length, reload, movSpeed, minRot, maxRot, waitTime, standTime; public int machineCnt; public static int buyMoney,buildMoney, atkBuild,lenBuild,cotBuild; } [System.Serializable] public class CirclePlazma { public float hp, length, reload, rotSpeed, waitTime, standTime; public static int buyMoney, buildMoney, atkBuild, lenBuild, cotBuild; } [System.Serializable] public class Marble { public float damage, range, reload, movSpeed, waitTime, standTime; public static int buyMoney, buildMoney, atkBuild, lenBuild, cotBuild; } [System.Serializable] public class ShoutAttack { public float damage, range, reload, ShoutDelay; public static int buyMoney, buildMoney, atkBuild, lenBuild, cotBuild; } [System.Serializable] public class AngryAttack { public float damage, reload, bulletCnt, bulletStandTime, bulletSpeed, skillIntervalTime, shotIntervalTime; public static int buyMoney, buildMoney, atkBuild, lenBuild, cotBuild; } [System.Serializable] public class HungryAttack { public float damage, reload, bulletCnt, bulletStandTime, bulletSpeed, skillIntervalTime, shotIntervalTime; public static int buyMoney, buildMoney, atkBuild, lenBuild, cotBuild; } <file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; namespace PathologicalGames { /// <summary> /// Billboarding is when an object is made to face a camera, so that no matter /// where it is on screen, it looks flat (not simply a "look-at" constraint, it /// keeps the transform looking parallel to the target - usually a camera). This /// is ideal for sprites, flat planes with textures that always face the camera. /// </summary> [AddComponentMenu("Path-o-logical/UnityConstraints/Constraint - Look At - Smooth")] public class SmoothLookAtConstraint : LookAtConstraint { /// <summary> /// The rotation interpolation solution to use. /// </summary> public UnityConstraints.INTERP_OPTIONS interpolation = UnityConstraints.INTERP_OPTIONS.Spherical; /// <summary> /// How fast the constrant can rotate. The result depends on the interpolation chosen. /// </summary> public float speed = 1; /// <summary> /// What axes and space to output the result to. /// </summary> public UnityConstraints.OUTPUT_ROT_OPTIONS output = UnityConstraints.OUTPUT_ROT_OPTIONS.WorldAll; // Reused every frame (probably overkill, but can't hurt...) private Quaternion lookRot; private Quaternion usrLookRot; private Quaternion curRot; private Vector3 angles; private Vector3 lookVectCache; /// <summary> /// Runs each frame while the constraint is active /// </summary> protected override void OnConstraintUpdate() { // Note: Do not run base.OnConstraintUpdate. It is not implimented this.lookVectCache = Vector3.zero; this.lookVectCache = this.lookVect; // Property, so cache result if (this.lookVectCache == Vector3.zero) return; this.lookRot = Quaternion.LookRotation(this.lookVectCache, this.upVect); this.usrLookRot = this.GetUserLookRotation(this.lookRot); this.OutputTowards(usrLookRot); } /// <summary> /// Runs when the noTarget mode is set to ReturnToDefault /// </summary> protected override void NoTargetDefault() { UnityConstraints.InterpolateLocalRotationTo ( this.transform, Quaternion.identity, this.interpolation, this.speed ); } /// <summary> /// Runs when the constraint is active or when the noTarget mode is set to /// ReturnToDefault /// </summary> private void OutputTowards(Quaternion destRot) { UnityConstraints.InterpolateRotationTo ( this.transform, destRot, this.interpolation, this.speed ); UnityConstraints.MaskOutputRotations(this.transform, this.output); } } }<file_sep>using UnityEngine; using System.Collections; public class Gulse : MonoBehaviour { public float dmg , range, movSpeed, waitTime, standTime; public bool moved = false; void OnEnabled() { StartCoroutine("Use"); } void Start() { StartCoroutine("Use"); } void Update() { if (moved) { transform.Translate(Vector3.right * movSpeed * Time.deltaTime); } } IEnumerator Use() { moved = true; transform.localScale = new Vector2(range, range); yield return new WaitForSeconds(waitTime); moved = false; //펑 yield return new WaitForSeconds(standTime); Destroy(transform.root.gameObject); //transform.root.gameObject.SetActive(false); } void Bump() { //터짐 } void OnTriggerEnter2D(Collider2D col) { if (col.CompareTag("Boss")) { //보스 데미지 StopCoroutine("Use"); Bump(); } else if (col.CompareTag("Bullet_Boss")) { if (col.GetComponent<Bullet>() == null) col.GetComponent<PlacedBullet>().HpManager(-dmg); else col.GetComponent<Bullet>().HpManager(-dmg); } } } <file_sep>public delegate void Callback(); public delegate void CallbackGameBegin(); public delegate void CallbackGameEnd(bool isWin); public delegate void CallbackUseSkill(SkillInfo info);<file_sep>using UnityEngine; using System.Collections; public class Skill1ShoutingOut : MonoBehaviour, ISkill { public status skillset; public float ShoutDelay; public Shout[] shouts; void Start() { //StartCoroutine("Delay"); UseSkill(); } public void SetSkill(int damage, float range, float reload, float ShoutDelay) { skillset.damage = damage; skillset.distance = range; skillset.reload = reload; this.ShoutDelay = ShoutDelay; } public void UseSkill() { StartCoroutine("Shout"); } IEnumerator Shout() { shouts[0].dmg = skillset.damage; shouts[0].transform.localScale = new Vector2(skillset.distance, skillset.distance); shouts[0].gameObject.SetActive(true); yield return new WaitForSeconds(ShoutDelay); shouts[0].gameObject.SetActive(false); shouts[1].dmg = skillset.damage; shouts[1].transform.localScale = new Vector2(skillset.distance, skillset.distance); shouts[1].gameObject.SetActive(true); shouts[2].dmg = skillset.damage; shouts[2].transform.localScale = new Vector2(skillset.distance, skillset.distance); shouts[2].gameObject.SetActive(true); yield return new WaitForSeconds(ShoutDelay); shouts[1].gameObject.SetActive(false); shouts[2].gameObject.SetActive(false); shouts[3].dmg = skillset.damage; shouts[3].transform.localScale = new Vector2(skillset.distance, skillset.distance); shouts[3].gameObject.SetActive(true); shouts[4].dmg = skillset.damage; shouts[4].transform.localScale = new Vector2(skillset.distance, skillset.distance); shouts[4].gameObject.SetActive(true); yield return new WaitForSeconds(ShoutDelay); shouts[3].gameObject.SetActive(false); shouts[4].gameObject.SetActive(false); shouts[5].dmg = skillset.damage; shouts[5].transform.localScale = new Vector2(skillset.distance, skillset.distance); shouts[5].gameObject.SetActive(true); shouts[6].dmg = skillset.damage; shouts[6].transform.localScale = new Vector2(skillset.distance, skillset.distance); shouts[6].gameObject.SetActive(true); yield return new WaitForSeconds(ShoutDelay); shouts[5].gameObject.SetActive(false); shouts[6].gameObject.SetActive(false); shouts[7].dmg = skillset.damage; shouts[7].transform.localScale = new Vector2(skillset.distance, skillset.distance); shouts[7].gameObject.SetActive(true); yield return new WaitForSeconds(ShoutDelay); shouts[7].gameObject.SetActive(false); } IEnumerator Delay() { while (true) { yield return new WaitForSeconds(skillset.reload); UseSkill(); } } } <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Handles information delivery with a lot of flexibility to create various behaviors. For /// example, you could attach this to a projectile and use it to trigger detonation when it /// hits a target, target layer or after a time limit, depending on the settings you choose. /// You could use the duration and startRange settings to create a shockwave that expands /// over time to notify targets it hits. You could also set the duration to -1 to create a /// persistant area trigger where you can subscribe to the AddOnHitTargetDelegate event /// delegate to respond to each new target that enters range. /// /// This will only hit each target in range once, unless the target leaves and comes back in /// to range. Use an EventFireController to notify targets in range multiple times. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO EventTrigger")] public class EventTrigger : AreaTargetTracker { #region Parameters /// <summary> /// Holds the target passed by the EventFireController on launch or set directly by script. /// </summary> public Target target; /// <summary> /// This is used internally to provide an interface in the inspector and to store /// structs as serialized objects. /// </summary> public List<EventInfoListGUIBacker> _eventInfoList = new List<EventInfoListGUIBacker>(); /// <summary> /// A list of EventInfo structs which hold one or more descriptions /// of how a Target can be affected. To alter this from code. Get the list, edit it, then /// set the whole list back. (This cannot be edited "in place"). /// </summary> // Encodes / Decodes EventInfos to and from EventInfoGUIBackers public EventInfoList eventInfoList { get { var returnEventInfos = new EventInfoList(); foreach (var infoBacker in this._eventInfoList) { // Create and add a struct-form of the backing-field instance returnEventInfos.Add ( new EventInfo { name = infoBacker.name, value = infoBacker.value, duration = infoBacker.duration, } ); } return returnEventInfos; } set { // Clear and set the backing-field list also used by the GUI this._eventInfoList.Clear(); EventInfoListGUIBacker infoBacker; foreach (var info in value) { infoBacker = new EventInfoListGUIBacker(info); this._eventInfoList.Add(infoBacker); } } } /// <summary> /// If true, more than just the primary target will be affected when this EventTrigger /// fires. Use the range options to determine the behavior. /// </summary> public bool areaHit = true; /// <summary> /// If this EventTrigger has a rigidbody, setting this to true will cause it to /// fire if it falls asleep. /// See Unity's docs for more information on how this happens. /// </summary> public bool fireOnRigidBodySleep = true; /// <summary> /// Determines what should cause this EventTrigger to fire. /// TargetOnly /// Only a direct hit will trigger the OnFire event. /// HitLayers /// Contact with any colliders in any of the layers in the HitLayers mask /// will trigger the OnFire event. /// </summary> public HIT_MODES hitMode = HIT_MODES.HitLayers; public enum HIT_MODES { TargetOnly, HitLayers } /// <summary> /// An optional timer to allow this EventTrigger to timeout and self-destruct. When set /// to a value above zero, when this reaches 0, the Fire coroutine will be started and /// anything in range may be hit (depending on settings). This can be used to give /// a projectile a max amount of time it can fly around before it dies, or a time-based /// land mine or pick-up. /// </summary> public float listenTimeout = 0; /// <summary> /// An optional duration to control how long this EventTrigger stays active. Each target /// will only be hit once with the event notification unless the Target leaves and then /// re-enters range. Set this to -1 to keep it alive forever. /// </summary> public float duration = 0; /// <summary> /// When duration is greater than 0 this can be used have the range change over the course /// of the duration. This is used for things like a chockwave from a large explosion, which /// grows over time. /// </summary> public Vector3 startRange = Vector3.zero; /// <summary> /// TThe same as range, but when duration is used, range may change over time while this /// will remain static. /// </summary> public Vector3 endRange { get { return this._endRange; } //set; } internal Vector3 _endRange = Vector3.zero; /// <summary> /// Sets the target notification behavior. Telling targets they are hit is optional /// for situations where a delayed response is required, such as launching a projectile, /// or for custom handling /// /// MODES: /// \par Off /// Do not notify anything. delegates can still be used for custom handling /// \par Direct /// OnFire targets will be notified immediately /// \par PassInfoToEventTrigger /// For every Target hit, a new EventTrigger will be spawned and passed this /// EventTrigger's EventInfo. PassToEventTriggerOnce is more commonly used when /// a secondary EventTrigger is needed, but this can be used for some creative /// or edge use-cases. /// \par PassInfoToEventTriggerOnce /// OnFire a new EventTrigger will be spawned and passed this EventTrigger's /// EventInfo. Only 1 will be spawned. This is handy for making bombs where only /// the first Target would trigger the event and only 1 EventTrigger would be /// spawned to expand over time (using duration and start range attributes). /// \par UseEventTriggerInfo /// Same as PassInfoToEventTrigger but the new EventTrigger will use its own /// EventInfo (this EventTrigger's EventInfo will be ignored). /// \par UseEventTriggerInfoOnce /// Same as PassInfoToEventTriggerOnce but the new EventTrigger will use its own /// EventInfo (this EventTrigger's EventInfo will be ignored). /// </summary> public NOTIFY_TARGET_OPTIONS notifyTargets = NOTIFY_TARGET_OPTIONS.Direct; public enum NOTIFY_TARGET_OPTIONS { Off, Direct, PassInfoToEventTrigger, PassInfoToEventTriggerOnce, UseEventTriggerInfo, UseEventTriggerInfoOnce } /// <summary> /// An optional prefab to instance another EventTrigger. This can be handy if you want /// to use a 'one-shot' event trigger to then spawn one that expands over time using the /// duration and startRange to simulate a huge explosion. /// </summary> public EventTrigger eventTriggerPrefab; /// <summary> /// The FireController which spawned this EventTrigger /// </summary> public EventFireController fireController; /// <summary> /// If true, the event will be fired as soon as this EventTrigger is spawned by /// instantiation or pooling. /// </summary> public bool fireOnSpawn = false; /// <summary> /// If false, do not add the new instance to a pool. Use Unity's Instantiate/Destroy /// </summary> public bool usePooling = true; /// <summary> /// If an eventTriggerPrefab is spawned, setting this to true will override the /// EventTrigger's poolName and use this instead. The instance will also be passed /// this EventTrigger's eventTriggerPoolName to be used when the EventTrigger is /// desapwned. /// </summary> public bool overridePoolName = false; /// <summary> /// The name of a pool to be used with PoolManager or other pooling solution. /// If not using pooling, this will do nothing and be hidden in the Inspector. /// WARNING: If poolname is set to "", Pooling will be disabled and Unity's /// Instantiate will be used. /// </summary> public string eventTriggerPoolName = "EventTriggers"; /// <summary> /// The name of a pool to be used with PoolManager or other pooling solution. /// If not using pooling, this will do nothing and be hidden in the Inspector. /// </summary> public string poolName = "EventTriggers"; #endregion Parameters #region Cache // Keeps the state of each individual foldout item during the editor session - tiny data public Dictionary<object, bool> _editorListItemStates = new Dictionary<object, bool>(); protected float curTimer; // Target notification handling... protected bool blockNotifications = false; protected TargetList detectedTargetsCache = new TargetList(); // Physics... public Rigidbody rbd; public Collider coll; public Rigidbody2D rbd2D; public Collider2D coll2D; #endregion Cache protected override void Awake() { // Override starting state this.areaColliderEnabledAtStart = false; base.Awake(); // if (!this.fireOnSpawn && this.rigidbody == null && this.rigidbody2D == null) // if (!this.fireOnSpawn && this.rigidbody2D == null) // { // string msg = "EventTriggers must have a Rigidbody or Rigidbody2D."; // throw new MissingComponentException(msg); // } this.rbd2D = this.GetComponent<Rigidbody2D>(); this.coll2D = this.GetComponent<Collider2D>(); // Cache used by other components and Target this.rbd = this.GetComponent<Rigidbody>(); this.coll = this.GetComponent<Collider>(); // Cache used by other components and Target } protected override void OnEnable() { base.OnEnable(); this._endRange = this.range; // This is also used in OnDisable to ensure a state reset for pooling if (this.fireOnSpawn) { this.StartCoroutine(this.Fire()); } else { this.StartCoroutine(this.Listen()); } this.AddOnNewDetectedDelegate(this.OnNewTargetHandler); } /// <summary> /// This is important for pooling as it leaves some states clean for reuse. /// </summary> protected override void OnDisable() { base.OnDisable(); // // Clean-up... // // Mostly in case pooling is used // this.target = Target.Null; // Originally set OnFire. Set it back to be sure of a perfect state if canceled by deactivating this.range = this._endRange; this.RemoveOnNewDetectedDelegate(this.OnNewTargetHandler); } protected IEnumerator Listen() { #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Normal) { string msg = "Listening for Targets..."; Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif // Reset this.curTimer = this.listenTimeout; // Wait for next frame to begin to be sure targets have been propegated // This also makes this loop easier to manage. //yield return new WaitForFixedUpdate(); // Seems logical but doesn't work. yield return null; // START EVENT if (this.OnListenStartDelegates != null) this.OnListenStartDelegates(); // The timer can exit the loop if used while (true) { // If depsawned by deactivation (pooling for example), drop the Target // just like if it was destroyed. if (!this.target.isSpawned) { this.target = Target.Null; } // UPDATE EVENT if (this.OnListenUpdateDelegates != null) this.OnListenUpdateDelegates(); // Fire if rigidbody falls asleep - optional. if (this.fireOnRigidBodySleep && (this.rbd != null && this.rbd.IsSleeping()) || (this.rbd2D != null && this.rbd2D.IsSleeping())) { break; } // Only work with the timer if the user entered a value over 0 if (this.listenTimeout > 0) { if (this.curTimer <= 0) break; this.curTimer -= Time.deltaTime; } //yield return new WaitForFixedUpdate(); // Seems logical but doesn't work. yield return null; } // Any break will start Fire. Use 'yield return break' to skip. this.StartCoroutine(this.Fire()); } /// <summary> /// Destroys the EventTrigger on impact with target or if no target, a collider /// in the layermask, or anything: depends on the chosen HIT_MODES /// </summary> protected void OnTriggered(GameObject other) { switch (this.hitMode) { case HIT_MODES.HitLayers: // LayerMask compare if (((1 << other.layer) & this.targetLayers) != 0) { // If this was set to hit layers but still not an area hit, try to hit the target. if (!this.areaHit) { var targetable = other.GetComponent<Targetable>(); // If the collider's gameObject doesn't have a targetable // component, it can't be a valid target, so ignore it if (targetable != null) this.target = new Target(targetable, this); } this.StartCoroutine(this.Fire()); } return; case HIT_MODES.TargetOnly: if (this.target.isSpawned && this.target.gameObject == other) // Target was hit this.StartCoroutine(this.Fire()); return; } // else keep flying... } // 3D protected void OnTriggerEnter(Collider other) { this.OnTriggered(other.gameObject); } // 2D protected void OnTriggerEnter2D(Collider2D other) { this.OnTriggered(other.gameObject); } /// <summary> /// Triggered when the Area detects a target. If false is returned, the /// target will be ignored unless detected again. Since an EventTrigger is like /// an expanding shockwave, if a target is fast enough to get hit, leave and then /// re-enter it makes sense to process it again. /// </summary> /// <param name='targetTracker'> /// The TargetTracker whose Area triggered the event. Since this EventTrigger /// IS the target tracker. This is ignored. It is for event recievers that use /// more than one TargetTracker. /// </param> /// <param name='target'> /// The target Detected /// </param> protected bool OnNewTargetHandler(TargetTracker targetTracker, Target target) { // Null detection is for direct calls rather than called-as-delegate if (target == Target.Null) return false; #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Normal) { string msg = string.Format("Processing detected Target: {0}", target.transform.name); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif var updatedTarget = new Target(target.targetable, this); this.detectedTargetsCache.Add(updatedTarget); if (!this.blockNotifications) this.HandleNotifyTarget(target); return false; // Force ignore } protected void HandleNotifyTarget(Target target) { #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) { string msg = string.Format ( "Handling notification of '{0}' with notifyTargets option '{1}'", target.transform.name, this.notifyTargets.ToString() ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif switch (this.notifyTargets) { case NOTIFY_TARGET_OPTIONS.Direct: target.targetable.OnHit(this.eventInfoList, target); if (this.OnHitTargetDelegates != null) this.OnHitTargetDelegates(target); break; case NOTIFY_TARGET_OPTIONS.UseEventTriggerInfoOnce: this.SpawnOnFirePrefab(false); break; case NOTIFY_TARGET_OPTIONS.PassInfoToEventTriggerOnce: this.SpawnOnFirePrefab(true); break; } } /// <summary> /// Despawns this EventTrigger on impact, timeout or sleep (depending on options) /// and notifies objects in range with EventInfo. /// </summary> public virtual IEnumerator Fire() { // Prevent being run more than once in a frame where it has already // been despawned. if (!this.gameObject.activeInHierarchy) yield break; if (this.duration > 0) this.range = this.startRange; // This TargetList collects targets that are notified below the this.detectedTargetsCache.Clear(); // Prevent the Area event from notifying targets in this.OnTargetDetectedNotify() this.blockNotifications = true; if (this.areaHit) { // This is turned back off OnDisable() (base class) // Also triggers OnDetected via an event to handle all targets found when enabled! this.setAreaColliderEnabled(true); // Need to wait a frame to let Unity send the physics Enter events to the Area. // Wait for next frame to begin to be sure targets have been propegated // This also makes this loop easier to manage. //yield return new WaitForFixedUpdate(); // This seems logical but doesn't work yield return null; } else { this.OnNewTargetHandler(this, this.target); } // Let future detections notifiy targets (in case duration is != 0) // This HAS to be bellow the yield or it will only work sometimes. this.blockNotifications = false; // Trigger delegates BEFORE processing notifications in case a delegate modifies the // list of targets if (this.OnFireDelegates != null) this.OnFireDelegates(this.detectedTargetsCache); foreach (Target processedTarget in this.detectedTargetsCache) this.HandleNotifyTarget(processedTarget); this.detectedTargetsCache.Clear(); // Just to be clean. if (this.notifyTargets == NOTIFY_TARGET_OPTIONS.PassInfoToEventTrigger) this.SpawnOnFirePrefab(true); // Hnadle keeping this EventTrigger alive and the range change over time. // Any new targets from this point on will be handled by OnNewDetected, which // is triggered by AreaTargetTracker logic. if (this.duration != 0) { // Determine which while() statement is needed. One that runs out after a // certain duration or one that runs forever while this component is active. if (this.duration < 0) { while (true) { // UPDATE EVENT if (this.OnFireUpdateDelegates != null) this.OnFireUpdateDelegates(-1); //yield return new WaitForFixedUpdate(); // Seems logical but doesn't work. yield return null; } } else { float timer = 0; float progress = 0; // Normalized value that will be 0-1 while (progress < 1) { // UPDATE EVENT if (this.OnFireUpdateDelegates != null) this.OnFireUpdateDelegates(progress); timer += Time.deltaTime; progress = timer / this.duration; this.range = this._endRange * progress; //yield return new WaitForFixedUpdate(); // Seems logical but doesn't work. yield return null; } this.range = this._endRange; // for percision } } // // Handle despoawn... // // Do this check again due to duration. // Prevent being run more than once in a frame where it has already // been despawned. if (!this.gameObject.activeInHierarchy) yield break; InstanceManager.Despawn(this.poolName, this.transform); yield return null; } /// <summary> /// Spawns a prefab if this.eventTriggerPrefab is not null. /// It is optionally passed this EventTriggers eventInfo and range. /// </summary> /// <param name="passInfo"> /// True to pass eventInfo and range to the spawned instance EventTriger. /// </param> protected void SpawnOnFirePrefab(bool passInfo) { // This is optional. If no ammo prefab is set, quit quietly if (this.eventTriggerPrefab == null) return; string poolName; if (!this.usePooling) poolName = ""; // Overloaded string "" to = pooling off else if (!this.overridePoolName) poolName = this.eventTriggerPrefab.poolName; else poolName = this.eventTriggerPoolName; Transform inst = PathologicalGames.InstanceManager.Spawn ( poolName, this.eventTriggerPrefab.transform, this.transform.position, this.transform.rotation ); // Pass info... // If this is null a parent may have been spawned. Try children. var otherEventTrigger = inst.GetComponent<EventTrigger>(); otherEventTrigger.poolName = poolName; // Will be correct pool name due to test above otherEventTrigger.fireController = this.fireController; if (passInfo) { otherEventTrigger.areaShape = this.areaShape; otherEventTrigger.range = this.range; otherEventTrigger.eventInfoList = this.eventInfoList; } } #region OnListenStart Delegates /// <summary> /// Runs when this EventTrigger is spawned and starts to listen for Targets /// </summary> public delegate void OnListenStart(); protected OnListenStart OnListenStartDelegates; public void AddOnListenStartDelegate(OnListenStart del) { this.OnListenStartDelegates += del; } public void SetOnListenStartDelegate(OnListenStart del) { this.OnListenStartDelegates = del; } public void RemoveOnListenStartDelegate(OnListenStart del) { this.OnListenStartDelegates -= del; } #endregion OnListenStart Delegates #region OnListenUpdate Delegates /// <summary> /// Runs every frame /// </summary> public delegate void OnListenUpdate(); protected OnListenUpdate OnListenUpdateDelegates; public void AddOnListenUpdateDelegate(OnListenUpdate del) { this.OnListenUpdateDelegates += del; } public void SetOnListenUpdateDelegate(OnListenUpdate del) { this.OnListenUpdateDelegates = del; } public void RemoveOnListenUpdateDelegate(OnListenUpdate del) { this.OnListenUpdateDelegates -= del; } #endregion OnListenUpdate Delegates #region OnFire Delegates /// <summary> /// Runs when this EventTrigger starts the Fire coroutine. /// </summary> /// <param name="targets"></param> public delegate void OnFire(TargetList targets); protected OnFire OnFireDelegates; public void AddOnFireDelegate(OnFire del) { this.OnFireDelegates += del; } public void SetOnFireDelegate(OnFire del) { this.OnFireDelegates = del; } public void RemoveOnFireDelegate(OnFire del) { this.OnFireDelegates -= del; } #endregion OnFire Delegates #region OnFireUpdate Delegates /// <summary> /// Runs every frame while this EventTrigger is actively firing due to the use of /// the duration attribute. /// </summary> public delegate void OnFireUpdate(float progress); protected OnFireUpdate OnFireUpdateDelegates; public void AddOnFireUpdateDelegate(OnFireUpdate del) { this.OnFireUpdateDelegates += del; } public void SetOnFireUpdateDelegate(OnFireUpdate del) { this.OnFireUpdateDelegates = del; } public void RemoveOnFireUpdateDelegate(OnFireUpdate del) { this.OnFireUpdateDelegates -= del; } #endregion OnFire Delegates #region OnHitTarget Delegates /// <summary> /// Runs every frame while this EventTrigger is actively firing due to the use of /// the duration attribute. /// </summary> public delegate void OnHitTarget(Target target); protected OnHitTarget OnHitTargetDelegates; public void AddOnHitTargetDelegate(OnHitTarget del) { this.OnHitTargetDelegates += del; } public void SetOnHitTargetDelegate(OnHitTarget del) { this.OnHitTargetDelegates = del; } public void RemoveOnHitTargetDelegate(OnHitTarget del) { this.OnHitTargetDelegates -= del; } #endregion OnHitTarget Delegates } }<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(SmoothTransformConstraint)), CanEditMultipleObjects] public class SmoothTransformConstraintInspector : ConstraintBaseInspector { protected SerializedProperty position; protected SerializedProperty outputPosX; protected SerializedProperty outputPosY; protected SerializedProperty outputPosZ; protected SerializedProperty pos_interp; protected SerializedProperty positionSpeed; protected SerializedProperty positionMaxSpeed; protected SerializedProperty rotation; protected SerializedProperty output; protected SerializedProperty interpolation; protected SerializedProperty rotationSpeed; protected SerializedProperty scale; protected SerializedProperty scaleSpeed; protected override void OnEnable() { base.OnEnable(); this.position = this.serializedObject.FindProperty("constrainPosition"); this.outputPosX = this.serializedObject.FindProperty("outputPosX"); this.outputPosY = this.serializedObject.FindProperty("outputPosY"); this.outputPosZ = this.serializedObject.FindProperty("outputPosZ"); this.pos_interp = this.serializedObject.FindProperty("position_interpolation"); this.positionSpeed = this.serializedObject.FindProperty("positionSpeed"); this.positionMaxSpeed = this.serializedObject.FindProperty("positionMaxSpeed"); this.rotation = this.serializedObject.FindProperty("constrainRotation"); this.output = this.serializedObject.FindProperty("output"); this.interpolation = this.serializedObject.FindProperty("interpolation"); this.rotationSpeed = this.serializedObject.FindProperty("rotationSpeed"); this.scale = this.serializedObject.FindProperty("constrainScale"); this.scaleSpeed = this.serializedObject.FindProperty("scaleSpeed"); } protected override void OnInspectorGUIUpdate() { base.OnInspectorGUIUpdate(); GUIContent content; GUILayout.BeginHorizontal(); content = new GUIContent("Position", "Option to match the target's position."); EditorGUILayout.PropertyField(this.position, content); if (this.position.boolValue) { PGEditorUtils.ToggleButton(this.outputPosX, new GUIContent("X", "Toggle Costraint for this axis."), 24); PGEditorUtils.ToggleButton(this.outputPosY, new GUIContent("Y", "Toggle Costraint for this axis."), 24); PGEditorUtils.ToggleButton(this.outputPosZ, new GUIContent("Z", "Toggle Costraint for this axis."), 24); GUILayout.EndHorizontal(); EditorGUI.indentLevel += 1; content = new GUIContent("interpolation Mode", "Option to match the target's position."); EditorGUILayout.PropertyField(this.pos_interp, content); var posInterp = (SmoothTransformConstraint.INTERP_OPTIONS_POS)this.pos_interp.enumValueIndex; switch (posInterp) { case SmoothTransformConstraint.INTERP_OPTIONS_POS.DampLimited: content = new GUIContent("Time", "roughly how long it takes to match the target (lag)."); EditorGUILayout.PropertyField(this.positionSpeed, content); content = new GUIContent("Max Speed", "The speed limit. Causes more constant motion."); EditorGUILayout.PropertyField(this.positionMaxSpeed, content); break; case SmoothTransformConstraint.INTERP_OPTIONS_POS.Damp: content = new GUIContent("Time", "roughly how long it takes to match the target (lag)."); EditorGUILayout.PropertyField(this.positionSpeed, content); break; default: content = new GUIContent("Percent", "Controls lag."); EditorGUILayout.PropertyField(this.positionSpeed, content); break; } EditorGUI.indentLevel -= 1; } else { GUILayout.EndHorizontal(); } content = new GUIContent("Rotation", "Option to match the target's rotation."); EditorGUILayout.PropertyField(this.rotation, content); if (this.rotation.boolValue) { EditorGUI.indentLevel += 1; content = new GUIContent("Output", "Used to alter the way the rotations are set."); EditorGUILayout.PropertyField(this.output, content); content = new GUIContent ( "Interpolation Mode", "The type of rotation calculation to use. Linear is faster but spherical is more stable when " + "rotations make large adjustments.." ); EditorGUILayout.PropertyField(this.interpolation, content); content = new GUIContent("Speed", "How fast to rotate. Appears different depending on Mode."); EditorGUILayout.PropertyField(this.rotationSpeed, content); EditorGUI.indentLevel -= 1; } content = new GUIContent("Scale", "Option to match the target's scale."); EditorGUILayout.PropertyField(this.scale, content); if (this.scale.boolValue) { EditorGUI.indentLevel += 1; content = new GUIContent("Percent", "Controls lag."); EditorGUILayout.PropertyField(this.scaleSpeed, content); EditorGUI.indentLevel -= 1; } } // protected override void OnInspectorGUIUpdate() // { // base.OnInspectorGUIUpdate(); // // var script = (SmoothTransformConstraint)target; // // GUILayout.BeginHorizontal(); // // script.constrainPosition = EditorGUILayout.Toggle("Position", script.constrainPosition); // // if (script.constrainPosition) // { // GUIStyle style = EditorStyles.toolbarButton; // style.alignment = TextAnchor.MiddleCenter; // style.stretchWidth = true; // // script.outputPosX = GUILayout.Toggle(script.outputPosX, "X", style); // script.outputPosY = GUILayout.Toggle(script.outputPosY, "Y", style); // script.outputPosZ = GUILayout.Toggle(script.outputPosZ, "Z", style); // } // GUILayout.EndHorizontal(); // // if (script.constrainPosition) // { // EditorGUI.indentLevel = 2; // // script.position_interpolation = PGEditorUtils.EnumPopup<SmoothTransformConstraint.INTERP_OPTIONS_POS> // ( // "Interpolation Mode", // script.position_interpolation // ); // // switch (script.position_interpolation) // { // case SmoothTransformConstraint.INTERP_OPTIONS_POS.DampLimited: // script.positionSpeed = EditorGUILayout.FloatField("Time", script.positionSpeed); // script.positionMaxSpeed = EditorGUILayout.FloatField("Max Speed", script.positionMaxSpeed); // break; // // case SmoothTransformConstraint.INTERP_OPTIONS_POS.Damp: // script.positionSpeed = EditorGUILayout.FloatField("Time", script.positionSpeed); // break; // // default: // script.positionSpeed = EditorGUILayout.FloatField("Percent", script.positionSpeed); // break; // } // // // EditorGUI.indentLevel = 0; // EditorGUILayout.Space(); // } // // GUILayout.BeginHorizontal(); // script.constrainRotation = EditorGUILayout.Toggle("Rotation", script.constrainRotation); // if (script.constrainRotation) // script.output = PGEditorUtils.EnumPopup<UnityConstraints.OUTPUT_ROT_OPTIONS>(script.output); // GUILayout.EndHorizontal(); // // if (script.constrainRotation) // { // EditorGUI.indentLevel = 2; // script.interpolation = PGEditorUtils.EnumPopup<UnityConstraints.INTERP_OPTIONS> // ( // "Interpolation Mode", // script.interpolation // ); // script.rotationSpeed = EditorGUILayout.FloatField("Speed", script.rotationSpeed); // // EditorGUI.indentLevel = 0; // EditorGUILayout.Space(); // } // // script.constrainScale = EditorGUILayout.Toggle("Scale", script.constrainScale); // if (script.constrainScale) // { // EditorGUI.indentLevel = 2; // script.scaleSpeed = EditorGUILayout.FloatField("Percent", script.scaleSpeed); // EditorGUI.indentLevel = 0; // EditorGUILayout.Space(); // } // // } } }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using PathologicalGames; using System.Collections.Generic; [CustomEditor(typeof(AreaTargetTracker)), CanEditMultipleObjects] public class AreaTargetTrackerInspector : Editor { protected SerializedProperty areaLayer; protected SerializedProperty areaPositionOffset; protected SerializedProperty areaRotationOffset; protected SerializedProperty areaShape; protected SerializedProperty drawGizmo; protected SerializedProperty debugLevel; protected SerializedProperty gizmoColor; protected SerializedProperty numberOfTargets; protected SerializedProperty range; protected SerializedProperty sortingStyle; protected SerializedProperty targetLayers; protected SerializedProperty updateInterval; protected bool showArea = true; protected virtual void OnEnable() { this.areaLayer = this.serializedObject.FindProperty("_areaLayer"); this.areaPositionOffset = this.serializedObject.FindProperty("_areaPositionOffset"); this.areaRotationOffset = this.serializedObject.FindProperty("_areaRotationOffset"); this.areaShape = this.serializedObject.FindProperty("_areaShape"); this.drawGizmo = this.serializedObject.FindProperty("drawGizmo"); this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.gizmoColor = this.serializedObject.FindProperty("gizmoColor"); this.numberOfTargets = this.serializedObject.FindProperty("numberOfTargets"); this.range = this.serializedObject.FindProperty("_range"); this.sortingStyle = this.serializedObject.FindProperty("_sortingStyle"); this.targetLayers = this.serializedObject.FindProperty("targetLayers"); this.updateInterval = this.serializedObject.FindProperty("updateInterval"); } public override void OnInspectorGUI() { this.serializedObject.Update(); GUIContent content; EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; Object[] targetObjs = this.serializedObject.targetObjects; AreaTargetTracker curEditTarget; content = new GUIContent( "Targets (-1 for all)", "The number of targets to return. Set to -1 to return all targets" ); EditorGUILayout.PropertyField(this.numberOfTargets, content); content = new GUIContent ( "Target Layers", "The layers in which the area is allowed to find targets." ); EditorGUILayout.PropertyField(this.targetLayers, content); EditorGUI.BeginChangeCheck(); content = new GUIContent("Sorting Style", "The style of sorting to use"); EditorGUILayout.PropertyField(this.sortingStyle, content); var sortingStyle = (TargetTracker.SORTING_STYLES)this.sortingStyle.enumValueIndex; // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (AreaTargetTracker)targetObjs[i]; Undo.RecordObject(curEditTarget, targetObjs[0].GetType() + " sortingStyle"); curEditTarget.sortingStyle = sortingStyle; } } if (sortingStyle != TargetTracker.SORTING_STYLES.None) { EditorGUI.indentLevel += 1; content = new GUIContent( "Minimum Interval", "How often the target list will be sorted. If set to 0, " + "sorting will only be triggered when Targets enter or exit range." ); EditorGUILayout.PropertyField(this.updateInterval, content); EditorGUI.indentLevel -= 1; } this.showArea = EditorGUILayout.Foldout(this.showArea, "Area Settings"); if (this.showArea) { EditorGUI.indentLevel += 1; EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Area Layer", "The layer to put the area in." ); content = EditorGUI.BeginProperty(new Rect(0, 0, 0, 0), content, this.areaLayer); int layer = EditorGUILayout.LayerField(content, this.areaLayer.intValue); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (AreaTargetTracker)targetObjs[i]; Undo.RecordObject(curEditTarget, targetObjs[0].GetType() + " areaLayer"); curEditTarget.areaLayer = layer; } } EditorGUI.EndProperty(); EditorGUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Area Shape", "The shape of the area used to detect targets in range" ); EditorGUILayout.PropertyField(this.areaShape, content); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { var shape = (AreaTargetTracker.AREA_SHAPES)this.areaShape.enumValueIndex; string undo_message = targetObjs[0].GetType() + " areaShape"; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (AreaTargetTracker)targetObjs[i]; if (curEditTarget.area != null) // Only works at runtime. { // // This would have happened anyway, but this way is undoable // if (curEditTarget.area.coll != null) // { // Undo.DestroyObjectImmediate(curEditTarget.area.coll); // } // else if (curEditTarget.area.coll2D != null) // { // Undo.DestroyObjectImmediate(curEditTarget.area.coll2D); // } Undo.RecordObject(curEditTarget.area.transform, undo_message); } Undo.RecordObject(curEditTarget, undo_message); // Property. Handles collider changes at runtime. curEditTarget.areaShape = shape; } } Area area; bool ok; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (AreaTargetTracker)targetObjs[i]; area = curEditTarget.area; ok = false; if (area == null) continue; if (area.coll != null) { switch (curEditTarget.areaShape) { case AreaTargetTracker.AREA_SHAPES.Sphere: if (area.coll is SphereCollider) ok = true; break; case AreaTargetTracker.AREA_SHAPES.Box: if (area.coll is BoxCollider) ok = true; break; case AreaTargetTracker.AREA_SHAPES.Capsule: if (area.coll is CapsuleCollider) ok = true; break; } } else if (area.coll2D != null) { switch (curEditTarget.areaShape) { case AreaTargetTracker.AREA_SHAPES.Box2D: if (area.coll2D is BoxCollider2D) ok = true; break; case AreaTargetTracker.AREA_SHAPES.Circle2D: if (area.coll2D is CircleCollider2D) ok = true; break; } } if (!ok) { var shape = (AreaTargetTracker.AREA_SHAPES)this.areaShape.enumValueIndex; curEditTarget.areaShape = shape; } } content = new GUIContent ( "Gizmo ", "Visualize the area in the Editor by turning this on." ); PGEditorUtils.ToggleButton(this.drawGizmo, content, 50); //script.drawGizmo = EditorGUILayout.Toggle(script.drawGizmo, GUILayout.MaxWidth(47)); EditorGUILayout.EndHorizontal(); if (this.drawGizmo.boolValue) { EditorGUI.indentLevel += 1; EditorGUILayout.BeginHorizontal(); content = new GUIContent ( "Gizmo Color", "The color of the gizmo when displayed" ); EditorGUILayout.PropertyField(this.gizmoColor, content); // If clicked, reset the color to the default GUIStyle style = EditorStyles.miniButton; style.alignment = TextAnchor.MiddleCenter; style.fixedWidth = 52; if (GUILayout.Button("Reset", style)) { for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (AreaTargetTracker)targetObjs[i]; curEditTarget.gizmoColor = curEditTarget.defaultGizmoColor; } } EditorGUILayout.EndHorizontal(); EditorGUI.indentLevel -=1; GUILayout.Space(4); } this.displayRange<AreaTargetTracker>(targetObjs); EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Position Offset", "An optional position offset for the area. For example, if you have an" + "object resting on the ground which has a range of 4, a position offset of" + "Vector3(0, 4, 0) will place your area so it is also sitting on the ground." ); EditorGUILayout.PropertyField(this.areaPositionOffset, content); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { string undo_message = targetObjs[0].GetType() + " areaPositionOffset"; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (AreaTargetTracker)targetObjs[i]; Undo.RecordObject(curEditTarget, undo_message); if (curEditTarget.area != null) // Only works at runtime. { Undo.RecordObject(curEditTarget.area.transform, undo_message); } curEditTarget.areaPositionOffset = this.areaPositionOffset.vector3Value; } } EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Rotation Offset", "An optional rotational offset for the area." ); EditorGUILayout.PropertyField(this.areaRotationOffset, content); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { string undo_message = targetObjs[0].GetType() + " areaPositionOffset"; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (AreaTargetTracker)targetObjs[i]; Undo.RecordObject(curEditTarget, undo_message); if (curEditTarget.area != null) // Only works at runtime. { Undo.RecordObject(curEditTarget.area.transform, undo_message); } curEditTarget.areaRotationOffset = this.areaRotationOffset.vector3Value; } } } EditorGUI.indentLevel -= 1; GUILayout.Space(8); content = new GUIContent ( "Debug Level", "Set it higher to see more verbose information." ); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } protected void displayRange<T>(Object[] targetObjs) where T : AreaTargetTracker { var content = new GUIContent ( "Range", "The range of the area from the center to the outer edge." ); content = EditorGUI.BeginProperty(new Rect(0, 0, 0, 0), content, this.range); EditorGUI.BeginChangeCheck(); Vector3 range = this.range.vector3Value; switch ((AreaTargetTracker.AREA_SHAPES)this.areaShape.enumValueIndex) { case AreaTargetTracker.AREA_SHAPES.Circle2D: // Fallthrough case AreaTargetTracker.AREA_SHAPES.Sphere: range.x = EditorGUILayout.FloatField(content, range.x); range.y = range.x; range.z = range.x; break; case AreaTargetTracker.AREA_SHAPES.Box2D: float oldZ = range.z; range = EditorGUILayout.Vector2Field(content.text, range); range.z = oldZ; // Nice to maintain if switching between 2D and 3D break; case AreaTargetTracker.AREA_SHAPES.Box: range = EditorGUILayout.Vector3Field(content.text, range); break; case AreaTargetTracker.AREA_SHAPES.Capsule: range = EditorGUILayout.Vector2Field(content.text, range); range.z = range.x; break; } // Only assign the value back if it was actually changed by the user. // Otherwise a single value will be assigned to all objects when multi-object editing, // even when the user didn't touch the control. if (EditorGUI.EndChangeCheck()) { this.range.vector3Value = range; string undo_message = targetObjs[0].GetType() + " range"; T curEditTarget; List<Object> undoObjs = new List<Object>(); Area curArea; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (T)targetObjs[i]; undoObjs.Add(curEditTarget); // Have to manage collider undo because it is set by the range property curArea = curEditTarget.area; if (curArea) { if (curArea.GetComponent<Collider>() != null) undoObjs.Add(curArea.GetComponent<Collider>()); else if (curArea.GetComponent<Collider2D>() != null) undoObjs.Add(curArea.GetComponent<Collider2D>()); } Undo.RecordObjects(undoObjs.ToArray(), undo_message); curEditTarget.range = this.range.vector3Value; } } EditorGUI.EndProperty(); } } class AreaGizmo { static GameObject spaceCalculator; [DrawGizmo(GizmoType.Selected | GizmoType.NotInSelectionHierarchy | GizmoType.Active | GizmoType.InSelectionHierarchy)] static void RenderAreaGizmo(AreaTargetTracker tt, GizmoType gizmoType) { if (!tt.drawGizmo || !tt.enabled || tt.overrideGizmoVisibility) return; // Hide the gizmo of the collider is disabled during run-time if (Application.isPlaying && tt.area != null && ((tt.area.coll != null && !tt.area.coll.enabled) || (tt.area.coll2D != null && !tt.area.coll2D.enabled))) return; Color color = tt.gizmoColor; Gizmos.color = color; // Set the space everything is drawn in. if (AreaGizmo.spaceCalculator == null) { AreaGizmo.spaceCalculator = new GameObject(); AreaGizmo.spaceCalculator.hideFlags = HideFlags.HideAndDontSave; } Transform xform = AreaGizmo.spaceCalculator.transform; xform.position = (tt.transform.rotation * tt.areaPositionOffset) + tt.transform.position; var rotOffset = Quaternion.Euler(tt.areaRotationOffset); xform.rotation = tt.transform.rotation * rotOffset; Gizmos.matrix = xform.localToWorldMatrix; Vector3 range = tt.GetNormalizedRange(); Vector3 pos = Vector3.zero; // We set the space relative above Vector3 capsuleBottomPos = pos; Vector3 capsuleTopPos = pos; switch (tt.areaShape) { case AreaTargetTracker.AREA_SHAPES.Circle2D: // Fallthrough pos = xform.position; Handles.color = color; Handles.DrawWireDisc(pos, xform.forward, range.x); break; case AreaTargetTracker.AREA_SHAPES.Sphere: Gizmos.DrawWireSphere(pos, range.x); break; case AreaTargetTracker.AREA_SHAPES.Box2D: // Fallthrough case AreaTargetTracker.AREA_SHAPES.Box: Gizmos.DrawWireCube(pos, range); break; case AreaTargetTracker.AREA_SHAPES.Capsule: float delta = (range.y * 0.5f) - range.x; capsuleTopPos.y += Mathf.Clamp(delta, 0, delta); Gizmos.DrawWireSphere(capsuleTopPos, range.x); capsuleBottomPos.y -= Mathf.Clamp(delta, 0, delta); Gizmos.DrawWireSphere(capsuleBottomPos, range.x); // Draw 4 lines to connect the two spheres to make a capsule Vector3 startLine; Vector3 endLine; startLine = capsuleTopPos; endLine = capsuleBottomPos; startLine.x += range.x; endLine.x += range.x; Gizmos.DrawLine(startLine, endLine); startLine = capsuleTopPos; endLine = capsuleBottomPos; startLine.x -= range.x; endLine.x -= range.x; Gizmos.DrawLine(startLine, endLine); startLine = capsuleTopPos; endLine = capsuleBottomPos; startLine.z += range.x; endLine.z += range.x; Gizmos.DrawLine(startLine, endLine); startLine = capsuleTopPos; endLine = capsuleBottomPos; startLine.z -= range.x; endLine.z -= range.x; Gizmos.DrawLine(startLine, endLine); break; } color.a = color.a * 0.5f; Gizmos.color = color; switch (tt.areaShape) { case AreaTargetTracker.AREA_SHAPES.Circle2D: // Fallthrough color.a = color.a * 0.5f; // 50% again Handles.color = color; Handles.DrawSolidDisc(pos, xform.forward, range.x); break; case AreaTargetTracker.AREA_SHAPES.Sphere: Gizmos.DrawSphere(pos, range.x); break; case AreaTargetTracker.AREA_SHAPES.Box2D: // Fallthrough case AreaTargetTracker.AREA_SHAPES.Box: Gizmos.DrawCube(pos, range); break; case AreaTargetTracker.AREA_SHAPES.Capsule: Gizmos.DrawSphere(capsuleTopPos, range.x); // Set above Gizmos.DrawSphere(capsuleBottomPos, range.x); // Set above break; } Gizmos.matrix = Matrix4x4.zero; // Just to be clean } } <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using PathologicalGames; [CustomEditor(typeof(TriggerEventProMessenger)), CanEditMultipleObjects] public class TriggerEventProMessengerInspector : Editor { protected SerializedProperty debugLevel; protected SerializedProperty otherTarget; protected SerializedProperty messageMode; protected SerializedProperty forComponent; protected List<SerializedProperty> fireControllerProps = new List<SerializedProperty>(); protected List<SerializedProperty> eventTriggerProps = new List<SerializedProperty>(); protected List<SerializedProperty> targetableProps = new List<SerializedProperty>(); protected List<SerializedProperty> targetTrackerProps = new List<SerializedProperty>(); protected void OnEnable() { this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.forComponent = this.serializedObject.FindProperty("forComponent"); this.messageMode = this.serializedObject.FindProperty("messageMode"); this.otherTarget = this.serializedObject.FindProperty("otherTarget"); fireControllerProps.Add(this.serializedObject.FindProperty("fireController_OnStart")); fireControllerProps.Add(this.serializedObject.FindProperty("fireController_OnUpdate")); fireControllerProps.Add(this.serializedObject.FindProperty("fireController_OnTargetUpdate")); fireControllerProps.Add(this.serializedObject.FindProperty("fireController_OnIdleUpdate")); fireControllerProps.Add(this.serializedObject.FindProperty("fireController_OnFire")); fireControllerProps.Add(this.serializedObject.FindProperty("fireController_OnStop")); eventTriggerProps.Add(this.serializedObject.FindProperty("eventTrigger_OnListenStart")); eventTriggerProps.Add(this.serializedObject.FindProperty("eventTrigger_OnListenUpdate")); eventTriggerProps.Add(this.serializedObject.FindProperty("eventTrigger_OnFire")); eventTriggerProps.Add(this.serializedObject.FindProperty("eventTrigger_OnFireUpdate")); eventTriggerProps.Add(this.serializedObject.FindProperty("eventTrigger_OnTargetHit")); targetableProps.Add(this.serializedObject.FindProperty("targetable_OnHit")); targetableProps.Add(this.serializedObject.FindProperty("targetable_OnHitCollider")); targetableProps.Add(this.serializedObject.FindProperty("targetable_OnDetected")); targetableProps.Add(this.serializedObject.FindProperty("targetable_OnNotDetected")); targetTrackerProps.Add(this.serializedObject.FindProperty("targetTracker_OnPostSort")); targetTrackerProps.Add(this.serializedObject.FindProperty("targetTracker_OnNewDetected")); targetTrackerProps.Add(this.serializedObject.FindProperty("targetTracker_OnTargetsChanged")); } public override void OnInspectorGUI() { this.serializedObject.Update(); //Object[] targetObjs = this.serializedObject.targetObjects; GUIContent content; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; EditorGUI.indentLevel = 0; content = new GUIContent ( "Other Message Target (Optional)", "An optional GameObject to message instead of this component's GameObject" ); EditorGUILayout.PropertyField(this.otherTarget, content); content = new GUIContent("Message Mode", "SendMessage will only send to this GameObject"); EditorGUILayout.PropertyField(this.messageMode, content); EditorGUI.BeginChangeCheck(); content = new GUIContent("For Component", "Choose which component's events to use"); content = EditorGUI.BeginProperty(new Rect(0, 0, 0, 0), content, this.forComponent); // EnumMaskField returns an Enum that has to be cast back to our type before casting to int var forCompFlags = (TriggerEventProMessenger.COMPONENTS)this.forComponent.intValue; System.Enum result = EditorGUILayout.EnumMaskField(content, forCompFlags); int forCompInt = (int)(TriggerEventProMessenger.COMPONENTS)result; // Only set the property if there was a change to avoid instantly setting all selected. if (EditorGUI.EndChangeCheck()) { this.forComponent.intValue = forCompInt; } EditorGUI.EndProperty(); // Change the label spacing EditorGUIUtility.labelWidth = 240; EditorGUI.indentLevel += 1; List<SerializedProperty> props = new List<SerializedProperty>(); forCompFlags = (TriggerEventProMessenger.COMPONENTS)this.forComponent.intValue; if ((forCompFlags & TriggerEventProMessenger.COMPONENTS.FireController) == TriggerEventProMessenger.COMPONENTS.FireController) { props.AddRange(this.fireControllerProps); } if ((forCompFlags & TriggerEventProMessenger.COMPONENTS.EventTrigger) == TriggerEventProMessenger.COMPONENTS.EventTrigger) { props.AddRange(this.eventTriggerProps); } if ((forCompFlags & TriggerEventProMessenger.COMPONENTS.Targetable) == TriggerEventProMessenger.COMPONENTS.Targetable) { props.AddRange(this.targetableProps); } if ((forCompFlags & TriggerEventProMessenger.COMPONENTS.TargetTracker) == TriggerEventProMessenger.COMPONENTS.TargetTracker) { props.AddRange(this.targetTrackerProps); } foreach (SerializedProperty prop in props) { // Help in debugging if (prop == null) throw new System.NullReferenceException("Property is null. Inspector typo?"); EditorGUILayout.PropertyField(prop, new GUIContent(prop.name.Capitalize())); } EditorGUI.indentLevel -= 1; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; GUILayout.Space(4); content = new GUIContent ( "Debug Level", "Set it higher to see more verbose information." ); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } } <file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; namespace PathologicalGames { /// <description> /// The base class for all constraints /// </description> [ExecuteInEditMode] // WARNING: Runs components in the Editor!! [AddComponentMenu("")] // Hides from Unity4 Inspector menu public class ConstraintFrameworkBaseClass : MonoBehaviour { /// <summary> /// Cache as much as possible before starting the co-routine /// </summary> protected virtual void Awake() { // Pre-Unity5 this stored a cache to this.transform, which is no longer necessary // This Awake was kept to avoid changing sub-class accessors. No harm keeping this // in case it is needed in the future. } /// <summary> /// Activate the constraint again if this object was disabled then enabled. /// Also runs immediatly after Awake() /// </summary> protected virtual void OnEnable() { this.InitConstraint(); } /// <summary> /// Activate the constraint again if this object was disabled then enabled. /// Also runs immediatly after Awake() /// </summary> protected virtual void OnDisable() { this.StopCoroutine("Constrain"); } /// <summary> /// Activate the constraint again if this object was disabled then enabled. /// Also runs immediatly after Awake() /// </summary> protected virtual void InitConstraint() { this.StartCoroutine("Constrain"); } /// <summary> /// Runs as long as the component is active. /// </summary> /// <returns></returns> protected virtual IEnumerator Constrain() { while (true) { this.OnConstraintUpdate(); yield return null; } } /// <summary> /// Impliment on child classes /// Runs each frame while the constraint is active /// </summary> protected virtual void OnConstraintUpdate() { throw new System.NotImplementedException(); } #if UNITY_EDITOR /// <summary> /// This class has the ExecuteInEditMode attribute, so this Update() is called /// anytime something is changed in the editor. See: /// http://docs.unity3d.com/Documentation/ScriptReference/ExecuteInEditMode.html /// This function exists in the UNITY_EDITOR preprocessor directive so it /// won't be compiled for the final game. It includes an Application.isPlaying /// check to ensure it is bypassed when in the Unity Editor /// </summary> protected virtual void Update() { if (Application.isPlaying) return; // The co-routines are started even in Editor mode, but it isn't perfectly // consistent. They don't always seem to restart when the game is stopped, // for example. So just stop them and run the Update using this Editor- // driven Update() this.StopAllCoroutines(); this.OnConstraintUpdate(); } #endif } }<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(ConstraintFrameworkBaseClass)), CanEditMultipleObjects] public class ConstraintFrameworkBaseInspector : Editor { protected virtual void OnEnable() { } // This is Unity's. Block from sub-classes - Use header, update and footer callbacks callbacks public override void OnInspectorGUI() { // Used like a header to set a global label width EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; this.serializedObject.Update(); this.OnInspectorGUIHeader(); this.OnInspectorGUIUpdate(); EditorGUILayout.Space(); this.OnInspectorGUIFooter(); // Flag Unity to save the changes to to the prefab to disk serializedObject.ApplyModifiedProperties(); if (GUI.changed) EditorUtility.SetDirty(target); } // Three functions to inherit instead of one for greater flexibility. protected virtual void OnInspectorGUIHeader() { } protected virtual void OnInspectorGUIUpdate() { } protected virtual void OnInspectorGUIFooter() { } } }<file_sep>using UnityEngine; using System.Collections; public interface ISkill { void UseSkill(); } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System; using System.Collections.Generic; using UnityEngine; namespace EnergyBarToolkit { [ExecuteInEditMode] [RequireComponent(typeof(EnergyBar))] public class SequenceRendererUGUI : EnergyBarUGUIBase { #region Public Fields public RenderMethod renderMethod = RenderMethod.Grid; public SpriteTex gridSprite = new SpriteTex(); public int gridWidth = 3; public int gridHeight = 3; public bool frameCountAuto = true; public int frameCount; public List<SpriteTex> sequenceSprites = new List<SpriteTex>(); public Color sequenceTint = Color.white; #endregion #region Private Fields [SerializeField] private int lastRebuildHash; private bool dirty; [SerializeField] private Image2 barImage; #endregion #region Public Methods public override void SetNativeSize() { switch (renderMethod) { case RenderMethod.Grid: SetNativeSizeGrid(); break; case RenderMethod.Sequence: SetNativeSizeSequence(); break; default: throw new ArgumentOutOfRangeException(); } } private void SetNativeSizeGrid() { if (gridSprite.sprite == null) { // try to create the bar now Rebuild(); if (gridSprite.sprite == null) { Debug.LogWarning("Cannot resize bar that has not been created yet"); return; } } var rect = gridSprite.sprite.rect; float w = rect.width / gridWidth; float h = rect.height / gridHeight; SetSize(rectTransform, w, h); } private void SetNativeSizeSequence() { if (sequenceSprites.Count == 0) { // try to create the bar now Rebuild(); if (sequenceSprites.Count == 0) { Debug.LogWarning("Cannot resize bar that has not been created yet"); return; } } var sprite = sequenceSprites[0]; if (sprite == null || sprite.sprite == null) { return; } var rect = sprite.sprite.rect; SetSize(rectTransform, rect.width, rect.height); } #endregion #region Unity Methods protected override void Update() { base.Update(); if (RebuildNeeded()) { Rebuild(); } UpdateNonIntrusive(); } #endregion #region Update Methods private void UpdateNonIntrusive() { UpdateSize(); UpdateValue(); // UpdateBlinkEffect(); // UpdateBurnEffect(); UpdateColor(); } private void UpdateSize() { var thisRectTransform = GetComponent<RectTransform>(); for (int i = 0; i < createdChildren.Count; ++i) { var child = createdChildren[i]; var otherRectTransform = child.GetComponent<RectTransform>(); SetSize(otherRectTransform, thisRectTransform.rect.size); } } private void UpdateValue() { switch (renderMethod) { case RenderMethod.Grid: UpdateValueGrid(); break; case RenderMethod.Sequence: UpdateValueSequence(); break; default: throw new ArgumentOutOfRangeException(); } } private void UpdateValueGrid() { float val = ValueF2; var frameIndex = GetFrameIndex(val); barImage.uvTiling = GetTilling(); barImage.uvOffset = GetOffset(frameIndex); barImage.sprite = gridSprite.sprite; barImage.color = gridSprite.color; barImage.material = gridSprite.material; barImage.SetAllDirty(); } private void UpdateColor() { switch (renderMethod) { case RenderMethod.Grid: barImage.color = ComputeColor(gridSprite.color); break; case RenderMethod.Sequence: barImage.color = ComputeColor(sequenceTint); break; default: throw new ArgumentOutOfRangeException(); } } private Vector2 GetOffset(int frameIndex) { var tilling = GetTilling(); int y = frameIndex / gridWidth; int x = frameIndex - (y * gridWidth); return new Vector2(tilling.x * x, 1 - tilling.y * y - tilling.y); } private Vector2 GetTilling() { return new Vector2(1f / gridWidth, 1f / gridHeight); } private void UpdateValueSequence() { if (GetFrameCount() == 0) { return; } float val = ValueF2; var frameIndex = GetFrameIndex(val); var sprite = sequenceSprites[frameIndex]; barImage.sprite = sprite.sprite; barImage.color = sprite.color; barImage.material = sprite.material; barImage.uvOffset = Vector2.zero; barImage.uvTiling = Vector2.one; barImage.SetAllDirty(); } private int GetFrameIndex(float progress) { var count = GetFrameCount(); int frameIndex = Mathf.FloorToInt((count - 1) * progress); return frameIndex; } private int GetFrameCount() { switch (renderMethod) { case RenderMethod.Grid: if (frameCountAuto) { return gridWidth * gridHeight; } return frameCount; case RenderMethod.Sequence: return sequenceSprites.Count; default: throw new ArgumentOutOfRangeException(); } } #endregion #region Rebuild Methods private bool RebuildNeeded() { int ch = MadHashCode.FirstPrime; ch = MadHashCode.AddList(ch, spritesBackground); ch = MadHashCode.AddList(ch, spritesForeground); if (ch != lastRebuildHash || dirty) { lastRebuildHash = ch; dirty = false; return true; } else { return false; } } private void Rebuild() { RemoveCreatedChildren(); BuildBackgroundImages(); BuildBar(); BuildForegroundImages(); UpdateSize(); MoveLabelToTop(); } private void BuildBar() { barImage = CreateChild<Image2>("bar"); } #endregion #region Inner and Anonymous Classes public enum RenderMethod { Grid, Sequence, } #endregion } } // namespace<file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using UnityEngine; [ExecuteInEditMode] public class FadeUGUI : MonoBehaviour { #region Public Fields public float invisibleDistance = 100; public float fadeDistance = 70; public Transform target; private EnergyBarBase energyBarBase; #endregion #region Private Fields #endregion #region Public Methods #endregion #region Unity Methods void OnEnable() { energyBarBase = GetComponent<EnergyBarBase>(); } void Update() { if (target == null) { return; } float distance = (Camera.main.transform.position - target.position).magnitude; if (distance < fadeDistance) { SetAlpha(1); } else if (distance > invisibleDistance) { SetAlpha(0); } else { SetAlpha((distance - fadeDistance) / (invisibleDistance - fadeDistance)); } } private void SetAlpha(float alpha) { energyBarBase.tint = new Color(1, 1, 1, alpha); } #endregion #region Private Methods #endregion #region Inner and Anonymous Classes #endregion }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using PathologicalGames; [CustomEditor(typeof(EventFireController)), CanEditMultipleObjects] public class EventFireControllerInspector : Editor { protected SerializedProperty debugLevel; protected SerializedProperty eventTriggerPoolName; protected SerializedProperty eventInfoList; protected SerializedProperty eventTriggerPrefab; protected SerializedProperty spawnEventTriggerAtTransform; protected SerializedProperty initIntervalCountdownAtZero; protected SerializedProperty interval; protected SerializedProperty notifyTargets; protected SerializedProperty overridePoolName; protected SerializedProperty targetTracker; protected SerializedProperty usePooling; public bool expandEventInfoList = true; protected void OnEnable() { this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.eventTriggerPoolName = this.serializedObject.FindProperty("eventTriggerPoolName"); this.eventInfoList = this.serializedObject.FindProperty("_eventInfoList"); this.eventTriggerPrefab = this.serializedObject.FindProperty("eventTriggerPrefab"); this.spawnEventTriggerAtTransform = this.serializedObject.FindProperty("_spawnEventTriggerAtTransform"); this.initIntervalCountdownAtZero = this.serializedObject.FindProperty("initIntervalCountdownAtZero"); this.interval = this.serializedObject.FindProperty("interval"); this.overridePoolName = this.serializedObject.FindProperty("overridePoolName"); this.notifyTargets = this.serializedObject.FindProperty("notifyTargets"); this.targetTracker = this.serializedObject.FindProperty("targetTracker"); this.usePooling = this.serializedObject.FindProperty("usePooling"); } public override void OnInspectorGUI() { this.serializedObject.Update(); GUIContent content; EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; Object[] targetObjs = this.serializedObject.targetObjects; EventFireController curEditTarget; // Try and init the TargetTracker field for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (EventFireController)targetObjs[i]; if (curEditTarget.targetTracker == null) curEditTarget.targetTracker = curEditTarget.GetComponent<TargetTracker>();// null OK } content = new GUIContent("Interval", "Fire every X seconds"); EditorGUILayout.PropertyField(this.interval, content); content = new GUIContent ( "Init Countdown at 0", "Able to fire immediatly when first spawned, before interval count begins" ); EditorGUILayout.PropertyField(this.initIntervalCountdownAtZero, content); content = new GUIContent ( "Notify Targets", "Sets the target notification behavior. Telling targets they are hit is optional " + "for situations where a delayed response is required, such as launching a , " + "projectile or for custom handling.\n" + "\n" + "MODES\n" + " Off\n" + " Do not notify anything. delegates can still be used\n" + " for custom handling\n" + " Direct\n" + " OnFire targets will be notified immediately\n" + " PassInfoToEventTrigger\n" + " OnFire, for each Target hit, a new EventTrigger will\n" + " be spawned and passed this EventFireController's \n" + " EventInfo.\n" + " UseEventTriggerInfo\n" + " Same as PassInfoToEventTrigger but the new\n" + " EventTrigger will use its own EventInfo (this \n" + " EventTrigger's EventInfo will be ignored). " ); EditorGUILayout.PropertyField(this.notifyTargets, content); // // If using an EventTrigger Prefab... // EventFireController.NOTIFY_TARGET_OPTIONS curOption; curOption = (EventFireController.NOTIFY_TARGET_OPTIONS)this.notifyTargets.enumValueIndex; if (curOption > EventFireController.NOTIFY_TARGET_OPTIONS.Direct) { EditorGUI.indentLevel += 1; content = new GUIContent ( "Spawn At Transform", "This transform is optionally used as the position at which an EventTrigger " + "prefab is spawned from. Some Utility components may also use this as a " + "position reference if chosen." ); EditorGUILayout.PropertyField(this.spawnEventTriggerAtTransform, content); if (curOption == EventFireController.NOTIFY_TARGET_OPTIONS.PassInfoToEventTrigger || curOption == EventFireController.NOTIFY_TARGET_OPTIONS.UseEventTriggerInfo) { content = new GUIContent ( "EventTrigger Prefab", "An optional EventTrigger to spawn OnFire depending on notifyTarget's " + "NOTIFY_TARGET_OPTIONS." ); EditorGUILayout.PropertyField(this.eventTriggerPrefab, content); } if (InstanceManager.POOLING_ENABLED) { if (this.eventTriggerPrefab.objectReferenceValue != null) { content = new GUIContent ( "Use Pooling", "If false, do not add the new instance to a pool. Use Unity's " + "Instantiate/Destroy" ); EditorGUILayout.PropertyField(this.usePooling, content); if (this.usePooling.boolValue) { EditorGUI.indentLevel += 1; content = new GUIContent ( "Override Pool", "If an eventTriggerPrefab is spawned, setting this to true will " + "override the EventTrigger's poolName and use this instead. The " + "instance will also be passed this EventFireController's " + "eventTriggerPoolName to be used when the EventTrigger is " + "desapwned." ); EditorGUILayout.PropertyField(this.overridePoolName, content); if (this.overridePoolName.boolValue) { content = new GUIContent ( "Pool Name", "The name of a pool to be used with PoolManager or other " + "pooling solution. If not using pooling, this will do " + "nothing and be hidden in the Inspector.\n" + "WARNING: If poolname is set to '', Pooling will be disabled " + "and Unity's Instantiate will be used." ); EditorGUILayout.PropertyField(this.eventTriggerPoolName, content); } EditorGUI.indentLevel -= 1; } } else { this.overridePoolName.boolValue = false; // Reset } } EditorGUI.indentLevel -= 1; } if (curOption != EventFireController.NOTIFY_TARGET_OPTIONS.UseEventTriggerInfo) { content = new GUIContent ( "Event Info List", "A list of event descriptions to be passed by struct to Targets" ); if (this.serializedObject.isEditingMultipleObjects) { EditorGUILayout.PropertyField(this.eventInfoList, content, true); } else { EditorGUI.indentLevel += 2; curEditTarget = (EventFireController)targetObjs[0]; this.expandEventInfoList = PGEditorUtils.SerializedObjFoldOutList<EventInfoListGUIBacker> ( content.text, curEditTarget._eventInfoList, this.expandEventInfoList, ref curEditTarget._editorListItemStates, true ); EditorGUI.indentLevel -= 2; } } // Init with the TargetTracker found on the same GameObject if possible for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (EventFireController)targetObjs[i]; if (curEditTarget.targetTracker == null) curEditTarget.targetTracker = curEditTarget.GetComponent<AreaTargetTracker>(); } GUILayout.Space(6); content = new GUIContent ( "TargetTracker", "This FireController's TargetTracker. Defaults to one on the same GameObject." ); EditorGUILayout.PropertyField(this.targetTracker, content); GUILayout.Space(8); content = new GUIContent("Debug Level", "Set it higher to see more verbose information."); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } } <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using PathologicalGames; [CustomEditor(typeof(SpawnOnFire)), CanEditMultipleObjects] public class SpawnOnFireInspector : Editor { protected SerializedProperty altSource; protected SerializedProperty poolName; protected SerializedProperty prefab; protected SerializedProperty spawnAtMode; protected SerializedProperty spawnAtTransform; protected SerializedProperty usePooling; protected void OnEnable() { this.altSource = this.serializedObject.FindProperty("altSource"); this.poolName = this.serializedObject.FindProperty("poolName"); this.prefab = this.serializedObject.FindProperty("prefab"); this.spawnAtMode = this.serializedObject.FindProperty("spawnAtMode"); this.spawnAtTransform = this.serializedObject.FindProperty("spawnAtTransform"); this.usePooling = this.serializedObject.FindProperty("usePooling"); } public override void OnInspectorGUI() { this.serializedObject.Update(); //Object[] targetObjs = this.serializedObject.targetObjects; //SpawnOnFire curEditTarget; GUIContent content; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; EditorGUI.indentLevel = 0; content = new GUIContent("Prefab", "The prefab to spawn Instances from."); EditorGUILayout.PropertyField(this.prefab, content); content = new GUIContent ( "Spawn At", "The origin is the point from which the distance is measuered." ); EditorGUILayout.PropertyField(this.spawnAtMode, content); var curSpawnAtMode = (SpawnOnFire.SPAWN_AT_MODE)this.spawnAtMode.enumValueIndex; if (curSpawnAtMode == SpawnOnFire.SPAWN_AT_MODE.OtherTransform) { EditorGUI.indentLevel += 1; content = new GUIContent ( "Spawn At", "This Transform's position and rotation will be used to spawn the instance if the" + "origin mode is set to 'OtherTransform'." ); EditorGUILayout.PropertyField(this.spawnAtTransform, content); EditorGUI.indentLevel -= 1; } if (InstanceManager.POOLING_ENABLED) { content = new GUIContent ( "Use Pooling", "If false, do not add the new instance to a pool. Use Unity's " + "Instantiate/Destroy" ); EditorGUILayout.PropertyField(this.usePooling, content); if (this.usePooling.boolValue) { EditorGUI.indentLevel += 1; content = new GUIContent ( "PoolName", "The name of a pool to be used with PoolManager or other pooling solution. If " + "not using pooling, this will do nothing and be hidden in the Inspector. " ); EditorGUILayout.PropertyField(this.poolName, content); EditorGUI.indentLevel -= 1; } } content = new GUIContent ( "Alternate Event Source", "Use this when the FireController or EventTrigger with OnFire event is on another GameObject" ); EditorGUILayout.PropertyField(this.altSource, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } } <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using PathologicalGames; [CustomEditor(typeof(SetConstraintTarget)), CanEditMultipleObjects] public class SetConstraintTargetInspector : Editor { protected SerializedProperty unityConstraint; protected SerializedProperty targetSource; protected void OnEnable() { this.unityConstraint = this.serializedObject.FindProperty("unityConstraint"); this.targetSource = this.serializedObject.FindProperty("_targetSource"); } public override void OnInspectorGUI() { this.serializedObject.Update(); Object[] targetObjs = this.serializedObject.targetObjects; SetConstraintTarget curEditTarget; GUIContent content; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; EditorGUI.indentLevel = 0; // Try and init the unityConstrant field. If still null after this. That is OK. for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (SetConstraintTarget)targetObjs[i]; if (curEditTarget.unityConstraint == null) curEditTarget.unityConstraint = curEditTarget.GetComponent<ConstraintBaseClass>(); } // Try and init the targetSource field. If still null after this. That is OK. for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (SetConstraintTarget)targetObjs[i]; if (curEditTarget.targetSource == null) curEditTarget.targetSource = curEditTarget.GetComponent<EventFireController>(); if (curEditTarget.targetSource == null) curEditTarget.targetSource = curEditTarget.GetComponent<EventTrigger>(); } content = new GUIContent ( "Unity Constraint", "A UnityConstraint to set targets for." ); EditorGUILayout.PropertyField(this.unityConstraint, content); EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Target Source", "A FireController whose events will set the target of the attached UnityConstraint." ); EditorGUILayout.PropertyField(this.targetSource, content); serializedObject.ApplyModifiedProperties(); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (SetConstraintTarget)targetObjs[i]; Undo.RecordObject(curEditTarget, targetObjs[0].GetType() + " targetSource"); var obj = (Component)this.targetSource.objectReferenceValue; if (obj != null) { var fireCtrl = obj.GetComponent<EventFireController>(); if (fireCtrl != null) { curEditTarget.targetSource = fireCtrl; } else { var eventTrigger = obj.GetComponent<EventTrigger>(); if (eventTrigger != null) { curEditTarget.targetSource = eventTrigger; } else { curEditTarget.targetSource = null; Debug.LogError ( "FireController or EventTrigger not found on dropped GameObject." ); } } } else { curEditTarget.targetSource = null; } } } serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } } <file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; namespace PathologicalGames { /// <description> /// Holds system-wide members for UnityConstraints /// </description> [AddComponentMenu("")] // Hides from Unity4 Inspector menu public static class UnityConstraints { /// <summary> /// Constraint Mode options. /// </summary> public enum MODE_OPTIONS { Align, Constrain } /// <summary> /// Constraint Mode options. /// </summary> public enum NO_TARGET_OPTIONS { Error, DoNothing, ReturnToDefault, SetByScript } /// <summary> /// Rotation interpolation options /// </summary> public enum INTERP_OPTIONS { Linear, Spherical, SphericalLimited } /// <summary> /// Rotations can't output to a combination of axis reliably so this is an enum. /// </summary> public enum OUTPUT_ROT_OPTIONS { WorldAll, WorldX, WorldY, WorldZ, LocalX, LocalY, LocalZ } private static float lastRealtimeSinceStartup = 0; // Used for Editor work /// <summary> /// Gets a rotation interpolated toward a target rotation based on the given interpolation /// method. /// </summary> /// <param name='currentRot'> /// The starting rotation. /// </param> /// <param name='targetRot'> /// Target rot to rotate toward. /// </param> /// <param name='interpolation'> /// Interpolation mode determined by the INTERP_OPTIONS enum. /// </param> /// <param name='speed'> /// Speed to rotate. This may be used differently by each interpolation mode. /// </param> public static Quaternion GetInterpolateRotationTo(Quaternion currentRot, Quaternion targetRot, INTERP_OPTIONS interpolation, float speed) { Quaternion newRot = Quaternion.identity; float deltaTime; #if UNITY_EDITOR if (Application.isPlaying) // deltaTime doesn't work in the editor { #endif deltaTime = Time.deltaTime; #if UNITY_EDITOR } else { float lastTime = UnityConstraints.lastRealtimeSinceStartup; deltaTime = Time.realtimeSinceStartup - lastTime; UnityConstraints.lastRealtimeSinceStartup = Time.realtimeSinceStartup; } #endif switch (interpolation) { case INTERP_OPTIONS.Linear: newRot = Quaternion.Lerp(currentRot, targetRot, deltaTime * speed); break; case INTERP_OPTIONS.Spherical: newRot = Quaternion.Slerp(currentRot, targetRot, deltaTime * speed); break; case INTERP_OPTIONS.SphericalLimited: newRot = Quaternion.RotateTowards(currentRot, targetRot, speed * Time.timeScale); break; } return newRot; } /// <summary> /// Rotates a Transform toward a target rotation based on the given interpolation /// method in world space. /// </summary> /// </summary> /// <param name='xform'> /// Transform to rotate. /// </param> /// <param name='targetRot'> /// Target rot to rotate toward. /// </param> /// <param name='interpolation'> /// Interpolation mode determined by the INTERP_OPTIONS enum. /// </param> /// <param name='speed'> /// Speed to rotate. This may be used differently by each interpolation mode. /// </param> public static void InterpolateRotationTo(Transform xform, Quaternion targetRot, INTERP_OPTIONS interpolation, float speed) { xform.rotation = GetInterpolateRotationTo ( xform.rotation, targetRot, interpolation, speed ); } /// <summary> /// Rotates a Transform toward a target rotation based on the given interpolation /// method in world space. /// </summary> /// <param name='xform'> /// Transform to rotate. /// </param> /// <param name='targetRot'> /// Target rot to rotate toward. /// </param> /// <param name='interpolation'> /// Interpolation mode determined by the INTERP_OPTIONS enum. /// </param> /// <param name='speed'> /// Speed to rotate. This may be used differently by each interpolation mode. /// </param> public static void InterpolateLocalRotationTo(Transform xform, Quaternion targetRot, INTERP_OPTIONS interpolation, float speed) { xform.localRotation = GetInterpolateRotationTo ( xform.localRotation, targetRot, interpolation, speed ); } /// <summary> /// Applies the rotation options to a passed transform. The rotation should /// already be set. This just returns axis to 0 depending on the constraint /// OUTPUT_ROT_OPTIONS /// </summary> /// <param name="xform">The transform to process for</param> /// <param name="option">The UnityConstraints.OUTPUT_ROT_OPTIONS to use</param> public static void MaskOutputRotations(Transform xform, OUTPUT_ROT_OPTIONS option) { Vector3 angles; switch (option) { case UnityConstraints.OUTPUT_ROT_OPTIONS.WorldAll: // Already done break; case UnityConstraints.OUTPUT_ROT_OPTIONS.WorldX: angles = xform.eulerAngles; angles.y = 0; angles.z = 0; xform.eulerAngles = angles; break; case UnityConstraints.OUTPUT_ROT_OPTIONS.WorldY: angles = xform.eulerAngles; angles.x = 0; angles.z = 0; xform.eulerAngles = angles; break; case UnityConstraints.OUTPUT_ROT_OPTIONS.WorldZ: angles = xform.eulerAngles; angles.x = 0; angles.y = 0; xform.eulerAngles = angles; break; case UnityConstraints.OUTPUT_ROT_OPTIONS.LocalX: angles = xform.localEulerAngles; angles.y = 0; angles.z = 0; xform.localEulerAngles = angles; break; case UnityConstraints.OUTPUT_ROT_OPTIONS.LocalY: angles = xform.localEulerAngles; angles.x = 0; angles.z = 0; xform.localEulerAngles = angles; break; case UnityConstraints.OUTPUT_ROT_OPTIONS.LocalZ: angles = xform.localEulerAngles; angles.x = 0; angles.y = 0; xform.localEulerAngles = angles; break; } } } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System.Collections.Generic; using EnergyBarToolkit; using UnityEngine; using UnityEngine.UI; namespace EnergyBarToolkit { [RequireComponent(typeof(EnergyBar))] [ExecuteInEditMode] public class TransformRendererUGUI : EnergyBarUGUIBase { #region Public Fields public SpriteTex spriteObject = new SpriteTex(); public Vector2 spriteObjectPivot = new Vector2(0.5f, 0.5f); public bool transformTranslate; public bool transformRotate; public bool transformScale; public TranslateFunction translateFunction = new TranslateFunction(); public RotateFunction rotateFunction = new RotateFunction(); public ScaleFunction scaleFunction = new ScaleFunction(); #endregion #region Private Fields // this field is increased when changes done by maintainer requires // this bar object to be rebuilt on update [SerializeField] private const int BuildVersion = 1; [SerializeField] private int lastRebuildHash; [SerializeField] private bool dirty; [SerializeField] private Image imageObject; [SerializeField] private Transform imageObjectContainer; #endregion #region Public Methods public override void SetNativeSize() { Vector2? computeNativeSize = ComputeNativeSize(); if (computeNativeSize.HasValue) { SetSize(rectTransform, computeNativeSize.Value); } } private Vector2? ComputeNativeSize() { var sprite = FirstBackgroundOrForegroundSprite(); if (sprite == null) { // try to create the bar now Rebuild(); if (sprite == null) { Debug.LogWarning("Cannot resize bar that has not been created yet"); return null; } } return new Vector2(sprite.rect.width, sprite.rect.height); } private Sprite FirstBackgroundOrForegroundSprite() { for (int i = 0; i < spritesBackground.Count; i++) { var spriteTex = spritesBackground[i]; if (spriteTex != null && spriteTex.sprite != null) { return spriteTex.sprite; } } for (int i = 0; i < spritesForeground.Count; i++) { var spriteTex = spritesForeground[i]; if (spriteTex != null && spriteTex.sprite != null) { return spriteTex.sprite; } } return null; } #endregion #region Unity Methods protected override void Update() { base.Update(); UpdateRebuild(); if (IsValid()) { UpdateColor(); UpdateAnchor(); UpdateSize(); UpdateTransform(); } } private void UpdateAnchor() { imageObject.rectTransform.pivot = spriteObjectPivot; } #endregion #region Update Methods private void UpdateSize() { var thisRectTransform = GetComponent<RectTransform>(); for (int i = 0; i < createdChildren.Count; ++i) { var child = createdChildren[i]; if (child.gameObject == imageObject.gameObject) { continue; } var otherRectTransform = child.GetComponent<RectTransform>(); if (otherRectTransform != null) { SetSize(otherRectTransform, thisRectTransform.rect.size); } } // update container scale Vector2 nativeSize; if (TryGetNativeSize(out nativeSize)) { Vector2 ratio = new Vector2( thisRectTransform.rect.width / nativeSize.x, thisRectTransform.rect.height / nativeSize.y); MadTransform.SetLocalScale(imageObjectContainer.transform, ratio); } } private bool TryGetNativeSize(out Vector2 nativeSize) { for (int i = 0; i < createdChildren.Count; ++i) { var child = createdChildren[i]; if (child.gameObject == imageObject.gameObject) { continue; } var image = child.GetComponent<Image>(); if (image != null) { nativeSize = image.sprite.rect.size; return true; } } nativeSize = Vector2.zero; return false; } private void UpdateColor() { if (imageObject != null) { imageObject.color = ComputeColor(spriteObject.color); imageObject.material = spriteObject.material; } } private void UpdateTransform() { if (transformTranslate) { Vector2 translate = translateFunction.Value(ValueF2); Vector2 size; if (TryGetNativeSize(out size)) { imageObject.transform.localPosition = new Vector2( translate.x * size.x, translate.y * size.y); } } if (transformRotate) { Quaternion rotate = rotateFunction.Value(ValueF2); var localRotation = Quaternion.identity * Quaternion.Inverse(rotate); // ReSharper disable once RedundantCheckBeforeAssignment if (imageObject.transform.localRotation != localRotation) { imageObject.transform.localRotation = localRotation; } } if (transformScale) { Vector3 scale = scaleFunction.Value(ValueF2); MadTransform.SetLocalScale(imageObject.transform, scale); } } #endregion #region Rebuild Methods private void UpdateRebuild() { if (!IsValid()) { RemoveCreatedChildren(); } if (RebuildNeeded()) { Rebuild(); } } private bool IsValid() { return spriteObject.sprite != null; } private bool RebuildNeeded() { int ch = MadHashCode.FirstPrime; ch = MadHashCode.Add(ch, BuildVersion); ch = MadHashCode.Add(ch, spriteObject != null ? spriteObject.GetHashCode() : 0); ch = MadHashCode.AddList(ch, spritesBackground); ch = MadHashCode.AddList(ch, spritesForeground); ch = MadHashCode.Add(ch, spriteObjectPivot); ch = MadHashCode.Add(ch, label); ch = MadHashCode.Add(ch, effectBurn); ch = MadHashCode.Add(ch, effectBurnSprite); ch = MadHashCode.Add(ch, rectTransform.pivot); if (ch != lastRebuildHash || dirty) { lastRebuildHash = ch; dirty = false; return true; } else { return false; } } private void Rebuild() { if (!IsValid()) { return; } RemoveCreatedChildren(); BuildBackgroundImages(); BuildObject(); BuildForegroundImages(); UpdateSize(); MoveLabelToTop(); } private void BuildObject() { imageObjectContainer = CreateChild<Transform>("container"); imageObject = CreateChild<Image>("bar", imageObjectContainer); imageObject.sprite = spriteObject.sprite; imageObject.SetNativeSize(); } #endregion #region Inner and Anonymous Classes #endregion } } // namespace<file_sep>using UnityEngine; using System.Collections; public class PlazmaMachine : MonoBehaviour { public float hp, length, rotSpeed, waitTime, standTime; public bool roted = false; void OnEnabled() { StartCoroutine("Use"); } void Start() { StartCoroutine("Use"); } void HpManager(float num) { hp += num; if (hp <= 0) { transform.root.gameObject.SetActive(false); } } void Update() { if (roted) { transform.Rotate(Vector3.forward * rotSpeed * Time.deltaTime); } } IEnumerator Use() { transform.localScale = new Vector2(4, length); yield return new WaitForSeconds(waitTime); roted = true; yield return new WaitForSeconds(standTime); Destroy(transform.root.gameObject); //transform.root.gameObject.SetActive(false); } void OnTriggerEnter2D(Collider2D col) { if (col.CompareTag("Bullet_Boss")) { if (col.GetComponent<Bullet>() == null) col.GetComponent<PlacedBullet>().HpManager(-1000); else col.GetComponent<Bullet>().HpManager(-1000); HpManager(-1); } } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using EnergyBarToolkit; using UnityEditor; using UnityEngine; [CanEditMultipleObjects] [CustomEditor(typeof (EnergyBar))] public class EnergyBarInspector : Editor { #region Fields private SerializedProperty valueCurrent; private SerializedProperty valueMin; private SerializedProperty valueMax; #endregion #region Methods void OnEnable() { valueCurrent = serializedObject.FindProperty("_valueCurrent"); valueMin = serializedObject.FindProperty("valueMin"); valueMax = serializedObject.FindProperty("valueMax"); } public override void OnInspectorGUI() { serializedObject.UpdateIfDirtyOrScript(); EditorGUILayout.IntSlider(valueCurrent, valueMin.intValue, valueMax.intValue, "Value Current"); EditorGUILayout.Space(); MadGUI.PropertyField(valueMin, "Value Min"); MadGUI.PropertyField(valueMax, "Value Max"); if (valueMin.intValue >= valueMax.intValue) { MadGUI.Error("Value Min should be lower than Value Max."); } serializedObject.ApplyModifiedProperties(); } #endregion }<file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System.Collections; using UnityEngine; namespace EnergyBarToolkit { /// <summary> /// This is only a example script that is ugin Repeated Renderer UGUI API to get and animate last /// visible icon in sequence. /// </summary> public class RepeatedUGUILastIconAnimator : MonoBehaviour { #region Public Fields public float animationTime = 2; public float scaleFrom = 1; public float scaleTo = 2; public float alphaFrom = 1; public float alphaTo = 0; private MadiTween.EaseType scaleEaseType = MadiTween.EaseType.easeOutCubic; #endregion #region Private Fields private RepeatedRendererUGUI barRenderer; public MadiTween.EaseType easeType { get { return scaleEaseType; } set { scaleEaseType = value; } } #endregion #region Unity Methods void Start() { barRenderer = GetComponent<RepeatedRendererUGUI>(); // Doing the animation in coroutine have two advantages: // 1 - You don't have to set script execution order, because Coroutines are executed after Update() functions // 2 - Coroutines are usually easy to read StartCoroutine(Anim()); } #endregion #region Private Methods public IEnumerator Anim() { while (enabled) { // infinite animation coroutine var visibleCount = barRenderer.GetVisibleIconCount(); if (visibleCount > 0) { var image = barRenderer.GetIconImage(visibleCount - 1); // make a copy var clone = (Image2) Instantiate(image); // changing the name, because "generated_*" icons are treated in a special way and this may lead to errors clone.name = "anim icon"; clone.transform.SetParent(image.transform.parent, false); clone.transform.position = image.transform.position; clone.transform.SetSiblingIndex(image.transform.GetSiblingIndex()); // do the animation float startTime = Time.time; float endTime = Time.time + animationTime; var easingFunction = MadiTween.GetEasingFunction(scaleEaseType); while (Time.time < endTime) { float f = (Time.time - startTime) / animationTime; var scale = easingFunction.Invoke(scaleFrom, scaleTo, f); clone.transform.localScale = new Vector3(scale, scale, scale); var alpha = easingFunction.Invoke(alphaFrom, alphaTo, f); clone.color = new Color(clone.color.r, clone.color.g, clone.color.b, alpha); yield return null; // next frame } // remove Destroy(clone.gameObject); } else { // if there's no last icon, just wait yield return new WaitForSeconds(animationTime); } } } #endregion #region Inner and Anonymous Classes #endregion } } // namespace<file_sep>using UnityEngine; using System.Collections; public class BossInfo : MonoBehaviour { InGameManager inGameManager; UIManager uiManager; public int hp; void Start() { uiManager = UIManager.Instance; inGameManager = InGameManager.Instance; print (hp); } public void HpManager(int num) { inGameManager.bossHp += num; uiManager.SetTextBossHP (inGameManager.bossHp); uiManager.SetMaxSliderBossHP (inGameManager.bossHp); if (inGameManager.bossHp <= 0) this.gameObject.SetActive (false); } }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using PathologicalGames; [CustomEditor(typeof(EventInfoListStandalone)), CanEditMultipleObjects] public class EventInfoListStandaloneInspector : Editor { protected SerializedProperty eventInfoList; public bool expandInfo = true; protected void OnEnable() { this.eventInfoList = this.serializedObject.FindProperty("_eventInfoListInspectorBacker"); } public override void OnInspectorGUI() { this.serializedObject.Update(); GUIContent content; EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; Object[] targetObjs = this.serializedObject.targetObjects; EventInfoListStandalone curEditTarget; content = new GUIContent ( "Event Info List", "A list of event descriptions to be passed by struct to Targets" ); if (this.serializedObject.isEditingMultipleObjects) { EditorGUILayout.PropertyField(this.eventInfoList, content, true); } else { GUILayout.Space(6); EditorGUI.indentLevel += 2; curEditTarget = (EventInfoListStandalone)targetObjs[0]; this.expandInfo = PGEditorUtils.SerializedObjFoldOutList<EventInfoListGUIBacker> ( content.text, curEditTarget._eventInfoListGUIBacker, this.expandInfo, ref curEditTarget._inspectorListItemStates, true ); EditorGUI.indentLevel -= 2; GUILayout.Space(4); } serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System; using System.Collections.Generic; using UnityEngine; using System.Collections; using UnityEngine.UI; namespace EnergyBarToolkit { public abstract class EnergyBarUGUIBase : EnergyBarBase { #region Public Fields public List<SpriteTex> spritesBackground = new List<SpriteTex>(); public List<SpriteTex> spritesForeground = new List<SpriteTex>(); public Text label; // burn effect public SpriteTex effectBurnSprite; public bool debugMode; #endregion #region Private Fields [SerializeField] protected List<GameObject> createdChildren = new List<GameObject>(32); [SerializeField] protected List<SpriteBind> backgroundBinds = new List<SpriteBind>(16); [SerializeField] protected List<SpriteBind> foregroundBinds = new List<SpriteBind>(16); protected RectTransform rectTransform; #endregion #region Properties public override Rect DrawAreaRect { get { return new Rect(); } } #endregion #region Public Methods public abstract void SetNativeSize(); #endregion #region Lifecycle Methods protected override void OnEnable() { base.OnEnable(); rectTransform = GetComponent<RectTransform>(); } protected override void Update() { base.Update(); UpdateLabel(); UpdateBackgroundForegroundColor(); if (Application.isEditor) { UpdateDebugMode(debugMode); } } private void UpdateBackgroundForegroundColor() { UpdateColor(backgroundBinds, spritesBackground); UpdateColor(foregroundBinds, spritesForeground); } private void UpdateColor(List<SpriteBind> binds, List<SpriteTex> sprites) { for (int i = 0; i < binds.Count; i++) { var bind = binds[i]; var image = bind.image; int index = bind.index; if (sprites.Count > index) { var spriteTex = sprites[index]; image.color = ComputeColor(spriteTex.color); } } } private void UpdateLabel() { if (label != null) { label.text = LabelFormatResolve(labelFormat); } } #endregion #region Build Methods protected void BuildBackgroundImages() { BuildImagesFromList(spritesBackground, "bg_", ref backgroundBinds); } protected void BuildForegroundImages() { BuildImagesFromList(spritesForeground, "fg_", ref foregroundBinds); } private void BuildImagesFromList(List<SpriteTex> sprites, string prefix, ref List<SpriteBind> store) { for (int i = 0; i < sprites.Count; ++i) { var spriteTex = sprites[i]; var sprite = spriteTex.sprite; if (sprite == null) { continue; } var image = CreateChild<Image>(prefix + (i + 1)); image.sprite = sprite; image.material = spriteTex.material; image.SetNativeSize(); image.type = GetImageType(); image.color = spriteTex.color; store.Add(new SpriteBind(image, i)); } } protected virtual Image.Type GetImageType() { return Image.Type.Simple; } protected T CreateChild<T>(string childName) where T : Component { return CreateChild<T>(childName, transform); } protected T CreateChild<T>(string childName, Transform parent) where T : Component { var child = MadTransform.CreateChild<T>(parent, "generated_" + childName); createdChildren.Add(child.gameObject); SetAsLastGenerated(child.transform); ApplyDebugMode(child.gameObject, debugMode); return child; } private void SetAsLastGenerated(Transform child) { var lowestNonGenerated = NonGeneratedLowestIndex(); if (lowestNonGenerated != -1) { child.SetSiblingIndex(lowestNonGenerated); } else { child.SetAsLastSibling(); } } // searches for non generated child and returns it index. Returns -1 if not found private int NonGeneratedLowestIndex() { int lowestIndex = int.MaxValue; for (int i = 0; i < transform.childCount; i++) { var child = transform.GetChild(i); if (!IsGenerated(child)) { lowestIndex = Mathf.Min(child.GetSiblingIndex(), lowestIndex); } } if (lowestIndex == int.MaxValue) { return -1; } return lowestIndex; } private bool IsGenerated(Transform child) { return child.name.StartsWith("generated_"); // cheap method, but will do } protected void RemoveCreatedChildren() { for (int i = 0; i < createdChildren.Count; ++i) { MadGameObject.SafeDestroy(createdChildren[i]); } // scan for generated children that were not removed // this is needed when user performs an undo operation var existingChildren = MadTransform.FindChildren<Transform>(transform, c => c.name.StartsWith("generated_"), 0); for (int i = 0; i < existingChildren.Count; i++) { var child = existingChildren[i]; MadGameObject.SafeDestroy(child.gameObject); } createdChildren.Clear(); backgroundBinds.Clear(); foregroundBinds.Clear(); } protected void SetSize(RectTransform rt, float w, float h) { SetSize(rt, new Vector2(w, h)); } protected void SetSize(RectTransform rt, Vector2 size) { var rect = rt.rect; if (!Mathf.Approximately(rect.width, size.x)) { rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, size.x); } if (!Mathf.Approximately(rect.height, size.y)) { rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, size.y); } } protected override bool IsVisible() { if (!base.IsVisible()) { return false; } if (rectTransform.rect.size.x <= 0 || rectTransform.rect.size.y <= 0) { return false; } return true; } protected void MoveLabelToTop() { if (label == null) { return; } if (label.transform.parent == transform) { label.transform.SetAsLastSibling(); } } private void UpdateDebugMode(bool value) { for (int i = 0; i < createdChildren.Count; i++) { var createdChild = createdChildren[i]; if (createdChild != null) { ApplyDebugMode(createdChild.gameObject, value); } } } private void ApplyDebugMode(GameObject gameObject, bool enabled) { gameObject.hideFlags = enabled ? HideFlags.None : HideFlags.HideInHierarchy; } #endregion #region Inner Types [Serializable] public class SpriteTex : AbstractTex { public Sprite sprite; public Material material; public SpriteTex() { } public SpriteTex(Sprite sprite) { this.sprite = sprite; } public override int GetHashCode() { int ch = MadHashCode.FirstPrime; ch = MadHashCode.Add(ch, sprite != null ? sprite.GetInstanceID() : 0); ch = MadHashCode.Add(ch, material != null ? material.GetInstanceID() : 0); ch = MadHashCode.Add(ch, color); return ch; } } [Serializable] public class SpriteBind { public Image image; public int index; public SpriteBind(Image image, int index) { this.image = image; this.index = index; } } #endregion } } // namespace<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(ConstraintBaseClass)), CanEditMultipleObjects] public class ConstraintBaseInspector : ConstraintFrameworkBaseInspector { protected SerializedProperty constraintTarget; protected SerializedProperty mode; protected SerializedProperty noTargetMode; protected override void OnEnable() { base.OnEnable(); this.constraintTarget = this.serializedObject.FindProperty("_target"); this.mode = this.serializedObject.FindProperty("_mode"); this.noTargetMode = this.serializedObject.FindProperty("_noTargetMode"); } protected override void OnInspectorGUIHeader() { base.OnInspectorGUIHeader(); var content = new GUIContent ( "Target", "The constraining object for this constraint." ); EditorGUILayout.PropertyField(this.constraintTarget, content); } protected override void OnInspectorGUIFooter() { GUIContent content; content = new GUIContent ( "Mode", "The current mode of the constraint. Setting the mode will start or stop the " + "constraint coroutine, so if 'Align' is chosen, the constraint will align " + "once then go to sleep." ); EditorGUILayout.PropertyField(this.mode, content); content = new GUIContent ( "No-Target Mode", "Determines the behavior when no target is available." ); EditorGUILayout.PropertyField(this.noTargetMode, content); base.OnInspectorGUIFooter(); } } }<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(LookAtConstraint)), CanEditMultipleObjects] public class LookAtConstraintInspector : LookAtBaseClassInspector { protected SerializedProperty upTarget; protected override void OnEnable() { base.OnEnable(); this.upTarget = this.serializedObject.FindProperty("upTarget"); } protected override void OnInspectorGUIUpdate() { base.OnInspectorGUIUpdate(); var content = new GUIContent ( "Up Target (Optional)", "An optional target just for the upAxis. The upAxis may not point directly at this. " + "See the online docs for more info" ); EditorGUILayout.PropertyField(this.upTarget, content); } } }<file_sep>/// <Licensing> /// � 2011(Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License(the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Put this on the same GameObject as any UnityConstraint to have a FireController set the /// constraint's target when the FireController target changes. This is great for using /// constraints to track or look-at a target. For example, a "locked on target" sprite could /// track the current target of a missile, or a turret could look at its current target. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Utility - Set Unity Constraint Target")] public class SetConstraintTarget : MonoBehaviour { public ConstraintBaseClass unityConstraint; /// <summary> /// A FireController Or EventTrigger whose events will set the target of the attached UnityConstraint /// </summary> public Component targetSource { get { return this._targetSource; } set { // // Clear all states before processing new value... // // If there was a FireController before, unregister the delegates if (this.fireCtrl != null) { this.fireCtrl.RemoveOnTargetUpdateDelegate(this.OnFireCtrlTargetUpdate); this.fireCtrl.RemoveOnIdleUpdateDelegate(this.OnOnFireCtrlIdleUpdate); } // If there was an EventTrigger before, unregister the delegates if (this.eventTrigger != null) { this.eventTrigger.RemoveOnListenUpdateDelegate(this.OnEventTriggerListenStart); } // Reset states to ensure sync this._targetSource = null; this.eventTrigger = null; this.fireCtrl = null; // // Process value... // if (value == null) return; // Accept the first matching component... this.fireCtrl = value as EventFireController; if (this.fireCtrl != null) { this._targetSource = this.fireCtrl; this.fireCtrl.AddOnTargetUpdateDelegate(this.OnFireCtrlTargetUpdate); this.fireCtrl.AddOnIdleUpdateDelegate(this.OnOnFireCtrlIdleUpdate); return; } this.eventTrigger = value as EventTrigger; if (this.eventTrigger != null) { this._targetSource = this.eventTrigger; this.eventTrigger.AddOnListenUpdateDelegate(this.OnEventTriggerListenStart); return; } throw new System.InvalidCastException ( "Component not a supported type. Use a FireController or EventTrigger." ); } } [SerializeField] protected Component _targetSource; protected EventFireController fireCtrl; protected EventTrigger eventTrigger; protected void Awake() { // Constraint componant not required by this class because of the use of the // base class. So, instead, test for null and notify the user if not found. if (this.unityConstraint == null) { this.unityConstraint = this.GetComponent<ConstraintBaseClass>(); if (this.unityConstraint == null) throw new MissingComponentException ( string.Format("No UnityConstraint was found on GameObject '{0}'", this.name) ); } // Trigger property logic if a FireController is found or on this GameObject if (this._targetSource == null) { EventFireController ctrl = this.GetComponent<EventFireController>(); if (ctrl != null) this.targetSource = ctrl; } else { this.targetSource = this._targetSource; } } protected void OnEventTriggerListenStart() { if (this.eventTrigger.target.isSpawned) { this.unityConstraint.target = this.eventTrigger.target.transform; } else { this.unityConstraint.target = null; } } protected void OnFireCtrlTargetUpdate(List<Target> targets) { this.unityConstraint.target = targets[0].transform; } protected void OnOnFireCtrlIdleUpdate() { this.unityConstraint.target = null; } } }<file_sep>using UnityEngine; namespace PathologicalGames { public class DemoEnemy : MonoBehaviour { public int life = 100; public ParticleSystem explosion; protected Color startingColor; protected bool isDead = false; protected void Awake() { this.startingColor = this.GetComponent<Renderer>().material.color; var targetable = this.GetComponent<Targetable>(); targetable.AddOnDetectedDelegate(this.MakeMeBig); targetable.AddOnDetectedDelegate(this.MakeMeGreen); targetable.AddOnNotDetectedDelegate(this.MakeMeNormal); targetable.AddOnNotDetectedDelegate(this.ResetColor); targetable.AddOnHitDelegate(this.OnHit); } protected void OnHit(EventInfoList infoList, Target target) { if (this.isDead) return; foreach (EventInfo info in infoList) { Debug.Log("@@@" + info.name + ": " + info.value); switch (info.name) { case "Damage": this.life -= (int)info.value; break; } } if (this.life <= 0) { this.isDead = true; Instantiate ( this.explosion.gameObject, this.transform.position, this.transform.rotation ); this.gameObject.SetActive(false); } } protected void MakeMeGreen(TargetTracker source) { if (this.isDead) return; this.GetComponent<Renderer>().material.color = Color.green; } protected void ResetColor(TargetTracker source) { if (this.isDead) return; this.GetComponent<Renderer>().material.color = this.startingColor; } protected void MakeMeBig(TargetTracker source) { if (this.isDead) return; this.transform.localScale = new Vector3(2, 2, 2); } protected void MakeMeNormal(TargetTracker source) { if (this.isDead) return; this.transform.localScale = Vector3.one; } } }<file_sep>using UnityEngine; using System.Collections; public class Boss2 : MonoBehaviour { OvertakingShooter[] overTaking = new OvertakingShooter[2]; WavingNwayShooter wavingNway; RandomSpreadingShooter randomSpreading; GapShooter gap; BentSpiralShooter bentSpiral; bool isNormal = true; int patternCount = 0; void Awake() { overTaking = GetComponents<OvertakingShooter> (); wavingNway = GetComponent<WavingNwayShooter> (); randomSpreading = GetComponent<RandomSpreadingShooter> (); gap = GetComponent<GapShooter> (); bentSpiral = GetComponent<BentSpiralShooter> (); } void LevelUp() { if (isNormal && patternCount == 0) { gap.angleRange += 0.05f; ++overTaking[0].ShotCount; bentSpiral.BulletAngleRate -= 0.0005f; bentSpiral.BulletSpeedRate += 0.003f; bentSpiral.ShotCount += 1; } else if (!isNormal) { ++overTaking[0].ShotCount; randomSpreading.ShotCount += 5; } else { wavingNway.ShotCount += 1; } } void Start () { StartCoroutine (TrensformManage ()); } IEnumerator ChangeFace() { int count = 0; while (count < 180) { count += 5; transform.rotation = Quaternion.Euler (0, 0, transform.rotation.z + count); yield return null; } transform.rotation = Quaternion.Euler (0, 0, 180); } IEnumerator ChangeNormal() { int count = 180; while (count > 0) { count -= 5; transform.rotation = Quaternion.Euler (0, 0, transform.rotation.z - count); yield return null; } transform.rotation = Quaternion.Euler (0, 0, 0); } IEnumerator TrensformManage() { while(true) { yield return new WaitForSeconds(15); if (isNormal && patternCount == 0) { gap.canShoot = false; overTaking[0].canShoot = false; bentSpiral.canShoot = false; overTaking [1].canShoot = true; randomSpreading.canShoot = true; } else if (isNormal && patternCount == 1) { StartCoroutine (ChangeFace ()); isNormal = false; overTaking [1].canShoot = false; randomSpreading.canShoot = false; wavingNway.canShoot = true; } else { StartCoroutine (ChangeNormal ()); isNormal = true; gap.canShoot = true; overTaking[0].canShoot = true; bentSpiral.canShoot = true; wavingNway.canShoot = false; } LevelUp (); ++patternCount; if (patternCount >= 3) patternCount = 0; } } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System; using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif namespace EnergyBarToolkit { public class LoadingScript : MonoBehaviour { #region Public Fields public float animSpeed = 1; private FilledRenderer3D filled; #endregion #region Public Properties #endregion #region Slots void OnEnable() { filled = GetComponent<FilledRenderer3D>(); } void Update() { filled.radialOffset += animSpeed * Time.deltaTime; } #endregion #region Public Static Methods #endregion #region Inner and Anonymous Classes #endregion } }<file_sep>using UnityEngine; using System.Collections; public class Boss1 : MonoBehaviour { IntervalMultipleSpiralShooter interMul; RandomSpreadingShooter randSpreading; BentSpiralShooter[] bentSpiral = new BentSpiralShooter[2]; PlacedMultipleSpiralShooter placedMul; OvertakingShooter overTaking; public Sprite Normal; public Sprite Red; SpriteRenderer sR; bool isNormal = true; int patternCount = 0; void Awake() { sR = GetComponent<SpriteRenderer> (); interMul = GetComponent<IntervalMultipleSpiralShooter> (); randSpreading = GetComponent<RandomSpreadingShooter> (); bentSpiral = GetComponents<BentSpiralShooter> (); overTaking = GetComponent<OvertakingShooter> (); placedMul = GetComponent<PlacedMultipleSpiralShooter> (); } void LevelUp() { if (isNormal && patternCount == 0) { interMul.shotCount++; randSpreading.ShotCount += 10; } else if (!isNormal) { overTaking.GroupCount++; } else { for(int i = 0; i < 2; i++) { bentSpiral [i].ShotCount += 2; if(i == 0) bentSpiral [i].BulletAngleRate += 0.0005f; else bentSpiral [i].BulletAngleRate -= 0.0005f; bentSpiral [i].BulletSpeedRate += 0.007f; } } } void Start () { StartCoroutine (TrensformManage ()); } IEnumerator TrensformManage() { while (true) { yield return new WaitForSeconds (15); if (isNormal && patternCount == 0) { placedMul.canShoot = true; overTaking.canShoot = true; interMul.canShoot = false; randSpreading.canShoot = false; } else if (isNormal && patternCount == 1) { isNormal = false; sR.sprite = Red; bentSpiral [0].canShoot = true; bentSpiral [1].canShoot = true; placedMul.canShoot = false; overTaking.canShoot = false; } else { isNormal = true; sR.sprite = Normal; bentSpiral [0].canShoot = false; bentSpiral [1].canShoot = false; interMul.canShoot = true; randSpreading.canShoot = true; } LevelUp (); patternCount++; if (patternCount >= 3) patternCount = 0; } } } <file_sep>using UnityEngine; using System.Collections; public class MoveTargetDemo : MonoBehaviour { private Transform xform; private bool moveForward = true; private float speed = 20f; private float duration = 0.6f; private float delay = 3.0f; // Use this for initialization void Start () { this.xform = this.transform; this.StartCoroutine(this.MoveTarget()); } private IEnumerator MoveTarget() { yield return new WaitForSeconds(delay); float savedTime = Time.time; while ((Time.time - savedTime) < duration) { if (moveForward) { this.xform.Translate(Vector3.forward * (Time.deltaTime * speed)); } else { this.xform.Translate(Vector3.back * (Time.deltaTime * speed)); } yield return null; } moveForward = moveForward ? false : true; this.StartCoroutine(MoveTarget()); } } <file_sep>using UnityEngine; using System.Collections; public class RollingNwayShooter : MonoBehaviour { public float ShotAngle; public float ShotAngleRange; public float ShotAngleRate; public float ShotSpeed; public int ShotCount; public int NWayCount; public int Interval; private int Timer; public bool canShoot = true; public GameObject bullet; public int bulletMoney; public float bulletHp; void Update () { if (Timer == 0 && canShoot) { for (int i = 0; i < NWayCount; i++) { EnemyLib.instance.ShootNWay( transform.position, ShotAngle + (float)i / NWayCount, ShotAngleRange, ShotSpeed, ShotCount, 0, 0, bullet, bulletMoney, bulletHp); } ShotAngle += ShotAngleRate; ShotAngle -= Mathf.Floor(ShotAngle); } Timer = (Timer + 1) % Interval; } } <file_sep>using UnityEngine; using System.Collections; using DG.Tweening; public class SkillCalculator : MonoBehaviour { public event CallbackUseSkill EventCoolTimeDone; public SkillInfo skillInfo; RectTransform rectTransform; // Use this for initialization void Start() { rectTransform = GetComponent<RectTransform>(); } public void BeginCalculateCoolTime() { StartCoroutine(CoCalculateCoolTime()); } IEnumerator CoCalculateCoolTime() { rectTransform.DOAnchorPos(new Vector2(0f, -175f), skillInfo.coolTime).SetEase(Ease.Linear); yield return new WaitForSeconds(skillInfo.coolTime); EventCoolTimeDone(skillInfo); } public void StopCalculateCoolTime() { DOTween.Clear(); StopAllCoroutines(); } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System.Collections; using UnityEngine; namespace EnergyBarToolkit { public class RandomInstantiatedValueChanger : MonoBehaviour { private EnergyBarSpawnerUGUI spawner; #region Public Fields public float interval = 2; #endregion #region Private Fields #endregion #region Public Methods #endregion #region Unity Methods void Start() { spawner = GetComponent<EnergyBarSpawnerUGUI>(); StartCoroutine(Work()); } #endregion #region Private Methods private IEnumerator Work() { while (true) { float value = Random.Range(0f, 1f); var energyBar = spawner.instance.GetComponent<EnergyBar>(); energyBar.ValueF = value; yield return new WaitForSeconds(interval); } } #endregion #region Inner and Anonymous Classes #endregion } } // namespace<file_sep>using UnityEngine; using System.Collections; public class OvertakingShooter : MonoBehaviour { public float ShotAngleRange; public float ShotSpeed; public int Interval; public float GroupSpeed; public float GroupAngle; public int ShotCount; public int GroupCount; public int GroupInterval; public float ShotAngle; private int Timer; public GameObject bullet; public bool canShoot = true; public int bulletMoney; public float bulletHp; Transform tr; void Awake() { tr = GetComponent<Transform>(); } void Update () { int i = Timer / GroupInterval; if (canShoot) { if (Timer == 0) { ShotAngle = EnemyLib.instance.GetPlayerAngle (tr.position); GroupAngle *= -1; }if (i < GroupCount && Timer % GroupInterval == 0) { EnemyLib.instance.ShootNWay( tr.position,ShotAngle + GroupAngle * i, ShotAngleRange, ShotSpeed + GroupSpeed * i, ShotCount, 0, 0, bullet, bulletMoney, bulletHp); } Timer = (Timer + 1) % Interval; } else Timer = 0; } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System; using UnityEngine; using UnityEngine.Serialization; #if UNITY_EDITOR using UnityEditor; #endif namespace EnergyBarToolkit { /// <summary> /// Makes the object follow another world object. /// </summary> [ExecuteInEditMode] public class EnergyBarFollowObject : MonoBehaviour { #region Public Fields public GameObject followObject; public Vector3 offset; [FormerlySerializedAs("barRotation")] public Vector3 rotation; public ObjectFinder worldCamera = new ObjectFinder(typeof(Camera), "/Main Camera", "MainCamera", ObjectFinder.Method.ByTag); public bool lookAtCamera = true; public bool updateLookupReference; #endregion #region Private Fields [SerializeField] [HideInInspector] private Camera renderCamera; private Camera cameraReference; private Canvas canvas; #endregion #region Public Methods public bool IsPossiblyVisible() { if (followObject != null && cameraReference != null) { Vector3 heading = followObject.transform.position - cameraReference.transform.position; float dot = Vector3.Dot(heading, cameraReference.transform.forward); return dot >= 0; } Debug.LogError("Cannot determine visibility of this bar.", this); return false; } #endregion #region Unity Methods void OnEnable() { #if UNITY_EDITOR if (renderCamera != null) { worldCamera.chosenMethod = ObjectFinder.Method.ByReference; worldCamera.reference = renderCamera.gameObject; renderCamera = null; EditorUtility.SetDirty(this); } #endif } void Start() { } void Update() { if (followObject != null) { if (!Application.isPlaying || canvas == null) { canvas = GetComponentInParent<Canvas>(); if (canvas == null) { Debug.LogError("This object should be placed under a canvas", this); } } if (!Application.isPlaying || cameraReference == null || updateLookupReference) { cameraReference = worldCamera.Lookup<Camera>(this); } UpdateFollowObject(); bool visible = IsPossiblyVisible(); var energyBarBase = GetComponent<EnergyBarBase>(); energyBarBase.opacity = visible ? 1 : 0; if (cameraReference != null && canvas != null) { if (canvas.renderMode == RenderMode.WorldSpace && lookAtCamera) { energyBarBase.transform.rotation = Quaternion.LookRotation(energyBarBase.transform.position - cameraReference.transform.position); } else { energyBarBase.transform.rotation = Quaternion.Euler(rotation); } } } } #endregion #region Private Methods private void UpdateFollowObject() { switch (canvas.renderMode) { case RenderMode.ScreenSpaceOverlay: UpdateFollowObjectScreenSpaceOverlay(); break; case RenderMode.ScreenSpaceCamera: UpdateFollowObjectScreenSpaceCamera(); break; case RenderMode.WorldSpace: UpdateFollowObjectWorldSpace(); break; default: throw new ArgumentOutOfRangeException(); } } private void UpdateFollowObjectScreenSpaceOverlay() { UpdateScreenSpace(); } private void UpdateFollowObjectScreenSpaceCamera() { UpdateScreenSpace(); } private void UpdateScreenSpace() { if (cameraReference == null) { Debug.LogError("Render Camera must be set for the follow script to work.", this); return; } var rect = canvas.pixelRect; var w2 = rect.width / 2; var h2 = rect.height / 2; var screenPoint = cameraReference.WorldToScreenPoint(followObject.transform.position); var pos = screenPoint + offset - new Vector3(w2, h2); pos = new Vector3(pos.x / canvas.scaleFactor, pos.y / canvas.scaleFactor); MadTransform.SetLocalPosition(transform, pos); } private void UpdateFollowObjectWorldSpace() { MadTransform.SetPosition(transform, followObject.transform.position + offset); } #endregion #region Inner and Anonymous Classes #endregion } } // namespace<file_sep>/// <Licensing> /// � 2011(Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License(the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Spawn any instance when a FireController fires. This includes options to decide where /// the new instance should be placed. Also offers pooling options if enabled. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Utility - Spawn On Fire (FireController)")] public class SpawnOnFire : MonoBehaviour { /// <summary> /// The prefab to spawn Instances from. /// </summary> public Transform prefab; /// <summary> /// This Transform's position and rotation will be used to spawn the instance if the /// origin mode is set to 'OtherTransform'. /// </summary> public Transform spawnAtTransform; /// <summary> /// The name of a pool to be used with PoolManager or other pooling solution. /// If not using pooling, this will do nothing and be hidden in the Inspector. /// </summary> public string poolName = ""; /// <summary> /// If false, do not add the new instance to a pool. Use Unity's Instantiate/Destroy /// </summary> public bool usePooling = true; /// <summary> /// Use this when the FireController or EventTrigger with OnFire event is on another GameObject /// </summary> public GameObject altSource; public enum SPAWN_AT_MODE { FireControllerSpawnAt, FireControllerTargetTracker, Area, ThisTransform, OtherTransform } /// <summary> /// The origin is the point from which the distance is measuered. /// </summary> public SPAWN_AT_MODE spawnAtMode = SPAWN_AT_MODE.ThisTransform; /// <summary> /// The Transform used for spawn position and rotation. /// </summary> public Transform origin { get { Transform xform = this.transform; switch (this.spawnAtMode) { case SPAWN_AT_MODE.FireControllerTargetTracker: if (this.fireCtrl == null) throw new MissingComponentException ( "Must have a FireController to use the 'FireControllerTargetTracker' option" ); xform = this.fireCtrl.targetTracker.transform; break; case SPAWN_AT_MODE.Area: Area area; if (this.fireCtrl != null) { area = this.fireCtrl.targetTracker.area; if (area == null) throw new MissingReferenceException(string.Format ( "FireController {0}'s TargetTracker doesn't have a Area. " + "If by design, such as a CollisionTargetTracker, use the " + "'TargetTracker' or other Origin Mode option.", this.fireCtrl.name )); } else { if (!this.eventTrigger.areaHit) throw new MissingReferenceException(string.Format ( "EventTrigger {0} areaHit is false. Turn this on before using the 'Area' option", this.eventTrigger.name )); area = this.eventTrigger.area; } xform = area.transform; break; case SPAWN_AT_MODE.FireControllerSpawnAt: if (this.fireCtrl == null) throw new MissingComponentException ( "Must have a FireController to use the FireControllerTargetTracker option" ); // If there is no emitter set, use this (same as FireController). if (this.fireCtrl.spawnEventTriggerAtTransform == null) throw new MissingReferenceException(string.Format ( "FireController {0} doesn't have an emitter set. " + "Add one or use the 'Fire Controller' Origin Mode option.", this.fireCtrl.name )); xform = this.fireCtrl.spawnEventTriggerAtTransform; break; case SPAWN_AT_MODE.ThisTransform: xform = this.transform; break; case SPAWN_AT_MODE.OtherTransform: xform = this.spawnAtTransform; break; } return xform; } set {} } protected EventFireController fireCtrl = null; protected EventTrigger eventTrigger = null; void Awake() { GameObject source; if (this.altSource) source = this.altSource; else source = this.gameObject; var ctrl = source.GetComponent<EventFireController>(); if (ctrl != null) { this.fireCtrl = ctrl; this.fireCtrl.AddOnFireDelegate(this.OnFire); } else { var eventTrigger = source.GetComponent<EventTrigger>(); if (eventTrigger != null) { this.eventTrigger = eventTrigger; this.eventTrigger.AddOnFireDelegate(this.OnFire); } } if (this.fireCtrl == null && this.eventTrigger == null) throw new MissingComponentException("Must have either an EventFireController or EventTrigger."); } protected void OnFire(List<Target> targets) { if (this.prefab == null) return; InstanceManager.Spawn ( this.poolName, this.prefab, this.origin.position, this.origin.rotation ); } } } <file_sep>/* * Energy Bar Toolkit by Mad Pixel Machine * http://www.madpixelmachine.com */ using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using EnergyBarToolkit; #if UNITY_EDITOR using UnityEditor; #endif public abstract class EnergyBarBase : MonoBehaviour { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== [SerializeField] protected int version = 169; // EBT version number to help updating properties // Label public bool labelEnabled; public Vector2 labelPosition; public bool labelPositionNormalized = true; public string labelFormat = "{cur}/{max}"; public Color labelColor = Color.white; // smooth effect public bool effectSmoothChange = false; // smooth change value display over time public float effectSmoothChangeSpeed = 0.5f; // value bar width percentage per second public SmoothDirection effectSmoothChangeDirection = SmoothDirection.Both; public Notify effectSmoothChangeFinishedNotify = new Notify(); private bool effectSmoothChangeWorking = false; // burn effect public bool effectBurn = false; // bar draining will display 'burn' effect public Texture2D effectBurnTextureBar; public string atlasEffectBurnTextureBarGUID = ""; public Color effectBurnTextureBarColor = Color.red; public Notify effectBurnFinishedNotify = new Notify(); public BurnDirection effectBurnDirection = BurnDirection.OnlyWhenDecreasing; private bool effectBurnWorking = false; // reference to actual bar component protected EnergyBar energyBar { get { if (_energyBar == null) { _energyBar = GetComponent<EnergyBar>(); MadDebug.Assert(_energyBar != null, "Cannot access energy bar?!"); } return _energyBar; } } private EnergyBar _energyBar; protected float ValueFBurn; protected float ValueF2; // =========================================================== // Getters / Setters // =========================================================== public abstract Rect DrawAreaRect { get; } public bool isBurning { get { return effectBurn && Math.Abs(ValueF2 - ValueFBurn) > 0.001f; } } protected float ValueF { get { return energyBar.ValueF; } } protected Vector2 LabelPositionPixels { get { var rect = DrawAreaRect; Vector2 v; if (labelPositionNormalized) { v = new Vector2(rect.x + labelPosition.x * rect.width, rect.y + labelPosition.y * rect.height); } else { v = new Vector2(rect.x + labelPosition.x, rect.y + labelPosition.y); } return v; } } /// <summary> /// Currently displayed value by the renderer (after applying effects) /// </summary> public float displayValue { get { return ValueF2; } } /// <summary> /// Global opacity value. /// </summary> public float opacity { get { return _tint.a; } set { _tint.a = Mathf.Clamp01(value); } } /// <summary> /// Global tint value /// </summary> public Color tint { get { return _tint; } set { _tint = value; } } [SerializeField] Color _tint = Color.white; /// <summary> /// If the bar is currently burning /// </summary> public bool burning { get { return effectBurn && ValueF2 != ValueFBurn; } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== /// <summary> /// Resets animations state, so bar value can be changed without any animation. /// It's useful for objects pooling when you want to reuse bars. Should be executed /// after setting the value, but before displaying. /// </summary> public virtual void ResetAnimations() { ValueF2 = ValueF; ValueFBurn = ValueF; } protected virtual void OnEnable() { ValueF2 = ValueF; } protected virtual void OnDisable() { // do nothing } protected virtual void Start() { // do nothing } protected virtual void Update() { UpdateAnimations(); } void UpdateAnimations() { UpdateBarValue(); UpdateBurnValue(); } void UpdateBurnValue() { EnergyBarCommons.SmoothDisplayValue( ref ValueFBurn, ValueF2, effectSmoothChangeSpeed); ValueFBurn = Mathf.Max(ValueFBurn, ValueF2); switch (effectBurnDirection) { case BurnDirection.Both: if (ValueF > ValueF2) { ValueFBurn = ValueF; } else if (ValueF < ValueF2) { EnergyBarCommons.SmoothDisplayValue( ref ValueFBurn, ValueF, effectSmoothChangeSpeed); } else { ValueFBurn = Mathf.Max(ValueFBurn, ValueF2); } break; case BurnDirection.OnlyWhenDecreasing: if (ValueF < ValueF2) { EnergyBarCommons.SmoothDisplayValue( ref ValueFBurn, ValueF, effectSmoothChangeSpeed); } else { ValueFBurn = Mathf.Max(ValueFBurn, ValueF2); } break; case BurnDirection.OnlyWhenIncreasing: if (ValueF > ValueF2) { ValueFBurn = ValueF; } else { ValueFBurn = ValueF2; } break; default: throw new ArgumentOutOfRangeException(); } if (!Mathf.Approximately(ValueFBurn, ValueF2)) { effectBurnWorking = true; } else if (effectBurnWorking) { effectBurnFinishedNotify.Execute(this); effectBurnWorking = false; } } void UpdateBarValue() { if (effectBurn) { if (effectSmoothChange) { // in burn mode smooth primary bar only when it's increasing bool canGoUp = effectSmoothChangeDirection == SmoothDirection.Both || effectSmoothChangeDirection == SmoothDirection.OnlyWhenIncreasing; if (ValueF > ValueF2 && canGoUp) { EnergyBarCommons.SmoothDisplayValue(ref ValueF2, ValueF, effectSmoothChangeSpeed); } else { ValueF2 = energyBar.ValueF; } if (!Mathf.Approximately(ValueF, ValueF2)) { effectSmoothChangeWorking = true; } else if (effectSmoothChangeWorking) { effectSmoothChangeFinishedNotify.Execute(this); effectSmoothChangeWorking = false; } } else { ValueF2 = energyBar.ValueF; } } else { if (effectSmoothChange) { bool canGoUp = effectSmoothChangeDirection == SmoothDirection.Both || effectSmoothChangeDirection == SmoothDirection.OnlyWhenIncreasing; bool canGoDown = effectSmoothChangeDirection == SmoothDirection.Both || effectSmoothChangeDirection == SmoothDirection.OnlyWhenDecreasing; if ((ValueF > ValueF2 && canGoUp) || (ValueF < ValueF2 && canGoDown)) { EnergyBarCommons.SmoothDisplayValue(ref ValueF2, ValueF, effectSmoothChangeSpeed); } else { ValueF2 = energyBar.ValueF; } if (!Mathf.Approximately(ValueF, ValueF2)) { effectSmoothChangeWorking = true; } else if (effectSmoothChangeWorking) { effectSmoothChangeFinishedNotify.Execute(this); effectSmoothChangeWorking = false; } } else { ValueF2 = energyBar.ValueF; } } } protected bool RepaintPhase() { return Event.current.type == EventType.Repaint; } protected string LabelFormatResolve(string format) { format = format.Replace("{cur}", "" + energyBar.valueCurrent); format = format.Replace("{min}", "" + energyBar.valueMin); format = format.Replace("{max}", "" + energyBar.valueMax); format = format.Replace("{cur%}", string.Format("{0:00}", energyBar.ValueF * 100)); format = format.Replace("{cur2%}", string.Format("{0:00.0}", energyBar.ValueF * 100)); return format; } protected Vector4 ToVector4(Rect r) { return new Vector4(r.xMin, r.yMax, r.xMax, r.yMin); } protected Vector2 Round(Vector2 v) { return new Vector2(Mathf.Round(v.x), Mathf.Round (v.y)); } protected virtual bool IsVisible() { if (opacity == 0) { return false; } return true; } protected Color PremultiplyAlpha(Color c) { return new Color(c.r * c.a, c.g * c.a, c.b * c.a, c.a); } protected virtual Color ComputeColor(Color localColor) { Color outColor = Multiply(localColor, tint); return outColor; } // =========================================================== // Static Methods // =========================================================== protected static Color Multiply(Color c1, Color c2) { return new Color(c1.r * c2.r, c1.g * c2.g, c1.b * c2.b, c1.a * c2.a); } protected static int HashAdd(int current, bool obj) { return MadHashCode.Add(current, obj); } protected static int HashAdd(int current, int obj) { return MadHashCode.Add(current, obj); } protected static int HashAdd(int current, float obj) { return MadHashCode.Add(current, obj); } protected static int HashAdd(int current, UnityEngine.Object obj) { if (obj != null) { return MadHashCode.Add(current, obj.GetInstanceID()); } else { return MadHashCode.Add(current, null); } } protected static int HashAdd(int current, object obj) { return MadHashCode.Add(current, obj); } protected static int HashAddTexture(int current, Texture texture) { #if UNITY_EDITOR string path = AssetDatabase.GetAssetPath(texture); string guid = AssetDatabase.AssetPathToGUID(path); return MadHashCode.Add(current, guid); #else return MadHashCode.Add(current, texture); #endif } protected static int HashAddArray(int current, object[] arr) { return MadHashCode.AddArray(current, arr); } protected static int HashAddTextureArray(int current, Texture[] arr, string name = "") { #if UNITY_EDITOR for (int i = 0; i < arr.Length; ++i) { string path = AssetDatabase.GetAssetPath(arr[i]); string guid = AssetDatabase.AssetPathToGUID(path); current = MadHashCode.Add(current, guid); } return current; #else return MadHashCode.AddArray(current, arr); #endif } protected Rect FindBounds(Texture2D texture) { int left = -1, top = -1, right = -1, bottom = -1; bool expanded = false; Color32[] pixels; try { pixels = texture.GetPixels32(); } catch (UnityException) { // catch not readable return new Rect(); } int w = texture.width; int h = texture.height; int x = 0, y = h - 1; for (int i = 0; i < pixels.Length; ++i) { var c = pixels[i]; if (c.a != 0) { Expand(x, y, ref left, ref top, ref right, ref bottom); expanded = true; } if (++x == w) { y--; x = 0; } } MadDebug.Assert(expanded, "bar texture has no visible pixels"); var pixelsRect = new Rect(left, top, right - left + 1, bottom - top + 1); var normalizedRect = new Rect( pixelsRect.xMin / texture.width, 1 - pixelsRect.yMax / texture.height, pixelsRect.xMax / texture.width - pixelsRect.xMin / texture.width, 1 - pixelsRect.yMin / texture.height - (1 - pixelsRect.yMax / texture.height)); return normalizedRect; } protected void Expand(int x, int y, ref int left, ref int top, ref int right, ref int bottom) { if (left == -1) { left = right = x; top = bottom = y; } else { if (left > x) { left = x; } else if (right < x) { right = x; } if (top > y) { top = y; } else if (bottom == -1 || bottom < y) { bottom = y; } } } // =========================================================== // Static Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== public enum Pivot { TopLeft, Top, TopRight, Right, BottomRight, Bottom, BottomLeft, Left, Center, } [System.Serializable] public class Tex : AbstractTex { public virtual int width { get { return texture.width; } } public virtual int height { get { return texture.height; } } public virtual bool Valid { get { return texture != null; } } public Texture2D texture; public override int GetHashCode() { int hash = MadHashCode.FirstPrime; hash = HashAddTexture(hash, texture); //hash = HashAdd(hash, color); return hash; } } public class AbstractTex { public Color color = Color.white; } public enum GrowDirection { LeftToRight, RightToLeft, BottomToTop, TopToBottom, RadialCW, RadialCCW, ExpandHorizontal, ExpandVertical, ColorChange, } public enum ColorType { Solid, Gradient, } public enum SmoothDirection { Both, OnlyWhenDecreasing, OnlyWhenIncreasing, } public enum BurnDirection { Both, OnlyWhenDecreasing, OnlyWhenIncreasing, } public abstract class TransformFunction { public AnimationCurve animationCurve = new AnimationCurve(new Keyframe(0f, 0f, 0f, 1f), new Keyframe(1f, 1f, 1f, 0f)); } [System.Serializable] public class TranslateFunction : TransformFunction { public Vector2 startPosition; public Vector2 endPosition; public Vector2 Value(float progress) { progress = Mathf.Clamp01(progress); progress = animationCurve.Evaluate(progress); var result = new Vector2( startPosition.x + (endPosition.x - startPosition.x) * progress, startPosition.y + (endPosition.y - startPosition.y) * progress ); return result; } public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is TranslateFunction)) { return false; } return GetHashCode() == obj.GetHashCode(); } public override int GetHashCode() { int hash = 17; hash = hash * 23 + startPosition.GetHashCode(); hash = hash * 23 + endPosition.GetHashCode(); return hash; } } [System.Serializable] public class ScaleFunction : TransformFunction { public Vector2 startScale = Vector3.one; public Vector2 endScale = Vector3.one; public Vector3 Value(float progress) { progress = Mathf.Clamp01(progress); progress = animationCurve.Evaluate(progress); var result = new Vector2( startScale.x + (endScale.x - startScale.x) * progress, startScale.y + (endScale.y - startScale.y) * progress ); return new Vector3(result.x, result.y, 1); } public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is ScaleFunction)) { return false; } return GetHashCode() == obj.GetHashCode(); } public override int GetHashCode() { int hash = 17; hash = hash * 23 + startScale.GetHashCode(); hash = hash * 23 + endScale.GetHashCode(); return hash; } } [System.Serializable] public class RotateFunction : TransformFunction { public float startAngle; public float endAngle; public Quaternion Value(float progress) { progress = Mathf.Clamp01(progress); progress = animationCurve.Evaluate(progress); float angle = startAngle + (endAngle - startAngle) * progress; var result = Quaternion.Euler(0, 0, angle); return result; } public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is RotateFunction)) { return false; } return GetHashCode() == obj.GetHashCode(); } public override int GetHashCode() { int hash = 17; hash = hash * 23 + startAngle.GetHashCode(); hash = hash * 23 + endAngle.GetHashCode(); return hash; } } [Serializable] public class Notify { public MonoBehaviour receiver; public string methodName; public event Action<EnergyBarBase> eventReceiver; public void Execute(EnergyBarBase sender) { if (receiver != null && !string.IsNullOrEmpty(methodName)) { receiver.SendMessage(methodName, sender); } if (eventReceiver != null) { eventReceiver(sender); } } } } <file_sep>using UnityEngine; using System.Collections; public class Boss3 : MonoBehaviour { SpriteRenderer sR; public Sprite Normal; public Sprite Red; RandomNwayShooter randNway; OvertakingShooter overTaking; WavingNwayShooter wavingNway; RollingNwayShooter rollingNway; RandomSpreadingShooter randomSpreading; GapShooter gap; PlacedMultipleSpiralShooter placedMulSpiral; PatternShooter patternS; bool isNormal = true; bool isStarted = false; int patternCount = 0; void Awake() { sR = GetComponent<SpriteRenderer> (); patternS = GetComponent<PatternShooter> (); randNway = GetComponent<RandomNwayShooter> (); overTaking = GetComponent<OvertakingShooter> (); wavingNway = GetComponent<WavingNwayShooter> (); randomSpreading = GetComponent<RandomSpreadingShooter> (); rollingNway = GetComponent<RollingNwayShooter> (); gap = GetComponent<GapShooter> (); placedMulSpiral = GetComponent<PlacedMultipleSpiralShooter> (); } void LevelUp() { if (isNormal && patternCount == 0) { ++randNway.ShotCount; } else if (isNormal && patternCount == 1) { ++wavingNway.ShotCount; randomSpreading.ShotCount += 5; } else if (!isNormal) { ++overTaking.ShotCount; wavingNway.ShotCount += 1; rollingNway.ShotSpeed += 0.02f; randomSpreading.ShotCount += 5; } } void Update () { if (!isStarted && !patternS.canShoot) { StartCoroutine (TrensformManage ()); isStarted = true; } } IEnumerator TrensformManage() { while (true) { if(!isNormal) { isNormal = true; sR.sprite = Normal; overTaking.canShoot = false; rollingNway.canShoot = false; randomSpreading.canShoot = false; patternS.canShoot = true; patternCount = 0; } if (isNormal && patternCount == 0) { randNway.canShoot = true; placedMulSpiral.canShoot = true; } else if (isNormal && patternCount == 1) { randNway.canShoot = false; placedMulSpiral.canShoot = false; gap.canShoot = true; wavingNway.canShoot = true; } else if (isNormal && patternCount == 2) { isNormal = false; sR.sprite = Red; gap.canShoot = false; wavingNway.canShoot = false; overTaking.canShoot = true; rollingNway.canShoot = true; randomSpreading.canShoot = true; } yield return new WaitForSeconds (15); LevelUp (); ++patternCount; } } void Reset() { patternCount = 0; } } <file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using System; using UnityEditor; using UnityEditor.AnimatedValues; using UnityEditorInternal; using UnityEngine; namespace EnergyBarToolkit { [CustomEditor(typeof(SequenceRendererUGUI))] public class SequenceRendererUGUIInspector : EnergyBarUGUIInspectorBase { #region Fields private SerializedProperty renderMethod; private SerializedProperty gridSprite; private SerializedProperty gridWidth; private SerializedProperty gridHeight; private SerializedProperty frameCountAuto; private SerializedProperty frameCount; private SerializedProperty sequenceSprites; private SerializedProperty sequenceTint; private SequenceRendererUGUI renderer; private AnimBool showFrameCount = new AnimBool(); private ReorderableList sequenceSpritesList; #endregion #region Unity Methods public override void OnEnable() { base.OnEnable(); renderMethod = serializedObject.FindProperty("renderMethod"); gridSprite = serializedObject.FindProperty("gridSprite"); gridWidth = serializedObject.FindProperty("gridWidth"); gridHeight = serializedObject.FindProperty("gridHeight"); frameCountAuto = serializedObject.FindProperty("frameCountAuto"); frameCount = serializedObject.FindProperty("frameCount"); sequenceSprites = serializedObject.FindProperty("sequenceSprites"); sequenceTint = serializedObject.FindProperty("sequenceTint"); renderer = (SequenceRendererUGUI) target; showFrameCount.value = !frameCountAuto.boolValue; showFrameCount.valueChanged.AddListener(Repaint); sequenceSpritesList = CreateLayerList(sequenceSprites, "Sequence Sprites"); } public override void OnInspectorGUI() { serializedObject.UpdateIfDirtyOrScript(); SectionTextures(); SectionAppearance(); SectionEffects(); SectionDebugMode(); serializedObject.ApplyModifiedProperties(); } #endregion #region Private Methods private void SectionTextures() { GUILayout.Label("Textures", "HeaderLabel"); using (MadGUI.Indent()) { FieldBackgroundSprites(); EditorGUILayout.Space(); MadGUI.PropertyFieldEnumPopup(renderMethod, "Render Method"); switch (renderer.renderMethod) { case SequenceRendererUGUI.RenderMethod.Grid: FieldSprite(gridSprite, "Sprite", MadGUI.ObjectIsSet); using (MadGUI.Indent()) { MadGUI.PropertyField(gridSprite.FindPropertyRelative("material"), "Material"); } using (MadGUI.Indent()) { MadGUI.PropertyField(gridWidth, "Grid Width"); MadGUI.PropertyField(gridHeight, "Grid Height"); MadGUI.PropertyField(frameCountAuto, "Frame Count Auto"); showFrameCount.target = !frameCountAuto.boolValue; if (EditorGUILayout.BeginFadeGroup(showFrameCount.faded)) { if (renderer.frameCountAuto) { frameCount.intValue = gridWidth.intValue * gridHeight.intValue; } MadGUI.PropertyField(frameCount, "Frame Count"); } EditorGUILayout.EndFadeGroup(); } break; case SequenceRendererUGUI.RenderMethod.Sequence: sequenceSpritesList.DoLayoutList(); MadGUI.PropertyField(sequenceTint, "Tint"); break; default: throw new ArgumentOutOfRangeException(); } EditorGUILayout.Space(); //serializedObject.UpdateIfDirtyOrScript(); // MadGUI.PropertyField(spriteBar, "Bar"); //serializedObject.ApplyModifiedProperties(); EditorGUILayout.Space(); FieldForegroundSprites(); } } private void SectionAppearance() { GUILayout.Label("Appearance", "HeaderLabel"); using (MadGUI.Indent()) { FieldSetNativeSize(); EditorGUILayout.Space(); FieldLabel2(); } } private void SectionEffects() { GUILayout.Label("Effects", "HeaderLabel"); using (MadGUI.Indent()) { FieldSmoothEffect(); } } #endregion #region Inner and Anonymous Classes #endregion } } // namespace<file_sep>/// <Licensing> /// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using PathologicalGames; [CustomEditor(typeof(EventTrigger)), CanEditMultipleObjects] public class EventTriggerInspector : AreaTargetTrackerInspector { protected SerializedProperty areaHit; protected SerializedProperty duration; protected SerializedProperty eventInfoList; protected SerializedProperty eventTriggerPrefab; protected SerializedProperty eventTriggerPoolName; protected SerializedProperty fireOnRigidBodySleep; protected SerializedProperty fireOnSpawn; protected SerializedProperty hitMode; protected SerializedProperty listenTimeout; protected SerializedProperty notifyTargets; protected SerializedProperty overridePoolName; protected SerializedProperty overrideGizmoVisibility; protected SerializedProperty poolName; protected SerializedProperty startRange; protected SerializedProperty usePooling; public bool expandEventInfo = true; protected override void OnEnable() { this.areaHit = this.serializedObject.FindProperty("areaHit"); this.areaLayer = this.serializedObject.FindProperty("_areaLayer"); this.areaPositionOffset = this.serializedObject.FindProperty("_areaPositionOffset"); this.areaRotationOffset = this.serializedObject.FindProperty("_areaRotationOffset"); this.areaShape = this.serializedObject.FindProperty("_areaShape"); this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.drawGizmo = this.serializedObject.FindProperty("drawGizmo"); this.duration = this.serializedObject.FindProperty("duration"); this.eventInfoList = this.serializedObject.FindProperty("_eventInfoList"); this.eventTriggerPoolName = this.serializedObject.FindProperty("eventTriggerPoolName"); this.eventTriggerPrefab = this.serializedObject.FindProperty("eventTriggerPrefab"); this.fireOnRigidBodySleep = this.serializedObject.FindProperty("fireOnRigidBodySleep"); this.fireOnSpawn = this.serializedObject.FindProperty("fireOnSpawn"); this.hitMode = this.serializedObject.FindProperty("hitMode"); this.listenTimeout = this.serializedObject.FindProperty("listenTimeout"); this.gizmoColor = this.serializedObject.FindProperty("gizmoColor"); this.notifyTargets = this.serializedObject.FindProperty("notifyTargets"); this.numberOfTargets = this.serializedObject.FindProperty("numberOfTargets"); this.overridePoolName = this.serializedObject.FindProperty("overridePoolName"); this.overrideGizmoVisibility = this.serializedObject.FindProperty("overrideGizmoVisibility"); this.poolName = this.serializedObject.FindProperty("poolName"); this.range = this.serializedObject.FindProperty("_range"); this.sortingStyle = this.serializedObject.FindProperty("_sortingStyle"); this.updateInterval = this.serializedObject.FindProperty("updateInterval"); this.startRange = this.serializedObject.FindProperty("startRange"); this.targetLayers = this.serializedObject.FindProperty("targetLayers"); this.usePooling = this.serializedObject.FindProperty("usePooling"); } public override void OnInspectorGUI() { this.serializedObject.Update(); GUIContent content; EditorGUI.indentLevel = 0; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; Object[] targetObjs = this.serializedObject.targetObjects; EventTrigger curEditTarget; if (InstanceManager.POOLING_ENABLED) { content = new GUIContent ( "PoolName", "The name of a pool to be used with PoolManager or other pooling solution. If " + "not using pooling, this will do nothing and be hidden in the Inspector. " ); EditorGUILayout.PropertyField(this.poolName, content); } content = new GUIContent ( "Hit Layers", "The layers in which the Area is allowed to find targets." ); EditorGUILayout.PropertyField(this.targetLayers, content); content = new GUIContent ( "Hit Mode", "Determines what should cause this EventTrigger to fire.\n" + " TargetOnly\n" + " Only a direct hit will trigger the OnFire event\n" + " HitLayers\n" + " Contact with any colliders in any of the layers in\n" + " the HitLayers mask will trigger the OnFire event." ); EditorGUILayout.PropertyField(this.hitMode, content); content = new GUIContent ( "listenTimeout (0 = OFF)", "An optional timer to allow this EventTrigger to timeout and self-destruct. When " + "set to a value above zero, when this reaches 0, the Fire coroutine will be " + "started and anything in range may be hit (depending on settings). This can be " + "used to give a projectile a max amount of time it can fly around before it " + "dies, or a time-based land mine or pick-up." ); EditorGUILayout.PropertyField(this.listenTimeout, content); content = new GUIContent ( "Fire On Spawn", "If true, the event will be fired as soon as this EventTrigger is spawned by " + "instantiation or pooling." ); EditorGUILayout.PropertyField(this.fireOnSpawn, content); content = new GUIContent ( "Fire On Sleep", "If this EventTrigger has a rigidbody, setting this to true will cause it to " + "fire if it falls asleep. See Unity's docs for more information on how " + "this happens." ); EditorGUILayout.PropertyField(this.fireOnRigidBodySleep, content); content = new GUIContent ( "Area Hit", "If true, more than just the primary target will be affected when this EventTrigger " + "fires. Use the range options to determine the behavior." ); EditorGUILayout.PropertyField(this.areaHit, content); // To make the gizmo delay work correctly, update the GUI here. serializedObject.ApplyModifiedProperties(); if (this.areaHit.boolValue) { this.overrideGizmoVisibility.boolValue = false; EditorGUI.indentLevel += 1; content = new GUIContent( "Targets (-1 = all)", "The number of targets to return. Set to -1 to return all targets" ); EditorGUILayout.PropertyField(this.numberOfTargets, content); content = new GUIContent("Sorting Style", "The style of sorting to use"); EditorGUILayout.PropertyField(this.sortingStyle, content); var sortingStyle = (EventTrigger.SORTING_STYLES)this.sortingStyle.enumValueIndex; if (sortingStyle != EventTrigger.SORTING_STYLES.None) { EditorGUI.indentLevel += 1; content = new GUIContent( "Minimum Interval", "How often the target list will be sorted. If set to 0, " + "sorting will only be triggered when Targets enter or exit range." ); EditorGUILayout.PropertyField(this.updateInterval, content); EditorGUI.indentLevel -= 1; } EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Area Layer", "The layer to put the Area in." ); content = EditorGUI.BeginProperty(new Rect(0, 0, 0, 0), content, this.areaLayer); int layer = EditorGUILayout.LayerField(content, this.areaLayer.intValue); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (EventTrigger)targetObjs[i]; Undo.RecordObject(curEditTarget, targetObjs[0].GetType() + " Area Layer"); curEditTarget.areaLayer = layer; } } EditorGUI.EndProperty(); EditorGUILayout.BeginHorizontal(); EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Area Shape", "The shape of the Area used to detect targets in range" ); EditorGUILayout.PropertyField(this.areaShape, content); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { var shape = (AreaTargetTracker.AREA_SHAPES)this.areaShape.enumValueIndex; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (EventTrigger)targetObjs[i]; Undo.RecordObject(curEditTarget, targetObjs[0].GetType() + " areaShape"); curEditTarget.areaShape = shape; } } content = new GUIContent ( "Gizmo ", "Visualize the Area in the Editor by turning this on." ); PGEditorUtils.ToggleButton(this.drawGizmo, content, 50); EditorGUILayout.EndHorizontal(); if (this.drawGizmo.boolValue) { EditorGUI.indentLevel += 1; EditorGUILayout.BeginHorizontal(); content = new GUIContent ( "Gizmo Color", "The color of the gizmo when displayed" ); EditorGUILayout.PropertyField(this.gizmoColor, content); // If clicked, reset the color to the default GUIStyle style = EditorStyles.miniButton; style.alignment = TextAnchor.MiddleCenter; style.fixedWidth = 52; if (GUILayout.Button("Reset", style)) { for (int i = 0; i < this.serializedObject.targetObjects.Length; i++) { curEditTarget = (EventTrigger)this.serializedObject.targetObjects[i]; curEditTarget.gizmoColor = curEditTarget.defaultGizmoColor; } } EditorGUILayout.EndHorizontal(); EditorGUI.indentLevel -= 1; GUILayout.Space(4); } content = new GUIContent ( "Duration (<0 = stay)", "An optional duration to control how long this EventTrigger stays active. " + "Each target will only be hit once with the event notification unless the " + "Target leaves and then re-enters range. Set this to -1 to keep it alive " + "forever." ); EditorGUILayout.PropertyField(this.duration, content); serializedObject.ApplyModifiedProperties(); if (this.duration.floatValue > 0) { EditorGUI.indentLevel += 1; content = new GUIContent ( "Start Range", "When duration is greater than 0 this can be used have the range change " + "over the course of the duration. This is used for things like a " + "chockwave from a large explosion, which grows over time. " ); content = EditorGUI.BeginProperty(new Rect(0, 0, 0, 0), content, this.startRange); EditorGUI.BeginChangeCheck(); Vector3 startRange = this.startRange.vector3Value; switch ((AreaTargetTracker.AREA_SHAPES)this.areaShape.enumValueIndex) { case AreaTargetTracker.AREA_SHAPES.Circle2D: // Fallthrough case AreaTargetTracker.AREA_SHAPES.Sphere: startRange.x = EditorGUILayout.FloatField(content, startRange.x); startRange.y = startRange.x; startRange.z = startRange.x; break; case AreaTargetTracker.AREA_SHAPES.Box2D: float oldZ = startRange.z; startRange = EditorGUILayout.Vector2Field(content.text, startRange); startRange.z = oldZ; // Nice to maintain if switching between 2D and 3D break; case AreaTargetTracker.AREA_SHAPES.Box: startRange = EditorGUILayout.Vector3Field(content.text, startRange); break; case AreaTargetTracker.AREA_SHAPES.Capsule: startRange = EditorGUILayout.Vector2Field(content.text, startRange); startRange.z = startRange.x; break; } // Only assign the value back if it was actually changed by the user. // Otherwise a single value will be assigned to all objects when multi-object // editing, even when the user didn't touch the control. if (EditorGUI.EndChangeCheck()) { this.startRange.vector3Value = startRange; } EditorGUI.EndProperty(); EditorGUI.indentLevel -= 1; } this.displayRange<EventTrigger>(targetObjs); EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Position Offset", "An optional position offset for the Area. For example, if you have an" + "object resting on the ground which has a range of 4, a position offset of" + "Vector3(0, 4, 0) will place your Area so it is also sitting on the ground." ); EditorGUILayout.PropertyField(this.areaPositionOffset, content); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { string undo_message = targetObjs[0].GetType() + " areaPositionOffset"; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (EventTrigger)targetObjs[i]; Undo.RecordObject(curEditTarget, undo_message); curEditTarget.areaPositionOffset = this.areaPositionOffset.vector3Value; } } EditorGUI.BeginChangeCheck(); content = new GUIContent ( "Rotation Offset", "An optional rotational offset for the Area." ); EditorGUILayout.PropertyField(this.areaRotationOffset, content); // If changed, trigger the property setter for all objects being edited if (EditorGUI.EndChangeCheck()) { string undo_message = targetObjs[0].GetType() + " areaPositionOffset"; for (int i = 0; i < targetObjs.Length; i++) { curEditTarget = (EventTrigger)targetObjs[i]; Undo.RecordObject(curEditTarget, undo_message); curEditTarget.areaRotationOffset = this.areaRotationOffset.vector3Value; } } GUILayout.Space(8); } else { this.overrideGizmoVisibility.boolValue = true; } content = new GUIContent ( "Notify Targets", "Sets the target notification behavior. Telling targets they are hit is optional " + "for situations where a delayed response is required, such as launching a , " + "projectile or for custom handling.\n" + "\n" + "MODES\n" + " Off\n" + " Do not notify anything. delegates can still be used\n" + " for custom handling\n" + " Direct\n" + " OnFire targets will be notified immediately\n" + " PassInfoToEventTrigger\n" + " For every Target hit, a new EventTrigger will be\n" + " spawned and passed this EventTrigger's \n" + " EventInfo. PassToEventTriggerOnce is more \n" + " commonly used when secondary EventTrigger is\n" + " needed, but this can be used for some creative\n" + " or edge use-cases.\n" + " PassInfoToEventTriggerOnce\n" + " OnFire a new EventTrigger will be spawned and\n" + " passed this EventTrigger's EventInfo. Only 1 will\n" + " be spawned. This is handy for making bombs \n" + " where only the first Target would trigger the \n" + " event and only 1 EventTrigger would be spawned\n" + " to expand over time (using duration and start\n" + " range attributes).\n" + " UseEventTriggerInfo\n" + " Same as PassInfoToEventTrigger but the new\n" + " EventTrigger will use its own EventInfo (this \n" + " EventTrigger's EventInfo will be ignored).\n" + " UseEventTriggerInfoOnce\n" + " Same as PassInfoToEventTriggerOnce but the new\n" + " EventTrigger will will used its own EventInfo\n" + " (this EventTrigger's EventInfo will be ignored)." ); EditorGUILayout.PropertyField(this.notifyTargets, content); // // If using EventTrigger... // EventTrigger.NOTIFY_TARGET_OPTIONS curOption; curOption = (EventTrigger.NOTIFY_TARGET_OPTIONS)this.notifyTargets.enumValueIndex; if (curOption > EventTrigger.NOTIFY_TARGET_OPTIONS.Direct) { EditorGUI.indentLevel += 1; content = new GUIContent ( "EventTrigger Prefab", "An optional prefab to instance another EventTrigger. This can be handy if you " + "want to use a 'one-shot' event trigger to then spawn one that expands over " + "time using the duration and startRange to simulate a huge explosion." ); EditorGUILayout.PropertyField(this.eventTriggerPrefab, content); if (InstanceManager.POOLING_ENABLED) { EditorGUI.indentLevel += 1; if (this.eventTriggerPrefab.objectReferenceValue != null) { content = new GUIContent ( "Use Pooling", "If false, do not add the new instance to a pool. Use Unity's " + "Instantiate/Destroy" ); EditorGUILayout.PropertyField(this.usePooling, content); if (this.usePooling.boolValue) { content = new GUIContent ( "Override Pool Name", "If an eventTriggerPrefab is spawned, setting this to true will " + "override the EventTrigger's poolName and use this instead. The " + "instance will also be passed this EventTrigger's " + "eventTriggerPoolName to be used when the EventTrigger is " + "desapwned." ); EditorGUILayout.PropertyField(this.overridePoolName, content); if (this.overridePoolName.boolValue) { content = new GUIContent ( "Pool Name", "The name of a pool to be used with PoolManager or other " + "pooling solution. If not using pooling, this will do " + "nothing and be hidden in the Inspector.\n" + "WARNING: If poolname is set to '', Pooling will be " + "disabled and Unity's Instantiate will be used." ); EditorGUILayout.PropertyField(this.eventTriggerPoolName, content); } } EditorGUI.indentLevel -= 1; } else { this.overridePoolName.boolValue = false; // Reset } } EditorGUI.indentLevel -= 1; } if (curOption < EventTrigger.NOTIFY_TARGET_OPTIONS.UseEventTriggerInfo) { if (this.serializedObject.isEditingMultipleObjects) { content = new GUIContent ( "Event Info List", "A list of EventInfo structs which hold one or more event descriptions of how " + "this EventTrigger can affect a Target." ); EditorGUILayout.PropertyField(this.eventInfoList, content, true); } else { EditorGUI.indentLevel += 2; curEditTarget = (EventTrigger)targetObjs[0]; this.expandEventInfo = PGEditorUtils.SerializedObjFoldOutList<EventInfoListGUIBacker> ( "Event Info List", curEditTarget._eventInfoList, this.expandEventInfo, ref curEditTarget._editorListItemStates, true ); EditorGUI.indentLevel -= 2; } } GUILayout.Space(4); content = new GUIContent ( "Debug Level", "Set it higher to see more verbose information." ); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } }<file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Adds Angle filtering to TargetPRO components. Angle filtering is defined as a target /// being in a specific firing arc or it is ignored. /// /// If added to the same GameObject as a TargetTracker it can filter out any targets /// which are not currently in the arc. /// /// If added to the same GameObject as a FireController it can prevent firing on any /// targets which are not currently in the arc. When the angle is set low, 5 degrees, /// 5 degrees for example, it can be used to only fire when something is in front of /// the origin. This can be handy for creating things which need to turn before firing, /// such as turrets and enimies. Or it can be used for triggering things like booby traps /// and detecting when something enters an area or room. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Modifier - Angle Limit Modifier")] public class AngleLimitModifier : TriggerEventProModifier { /// <summary> /// The transform used to determine alignment. If not used, this will be the /// transform of the GameObject this component is attached to. /// </summary> public Transform origin { get { if (this._origin == null) return this.transform; else return this._origin; } set { this._origin = value; } } [SerializeField] protected Transform _origin = null; // Explicit for clarity /// <summary> /// The angle, in degrees, to use for checks. /// </summary> public float angle = 5; /// <summary> /// If false the actual angles will be compared for alignment (More precise. origin /// must point at target). If true, only the direction matters. (Good when turning /// in a direction but perfect alignment isn't needed, e.g. lobing bombs as opposed /// to shooting AT something) /// </summary> public bool flatAngleCompare = false; public enum COMPARE_AXIS {X, Y, Z} /// <summary> /// Determines the axis to use when doing angle comparisons. /// </summary> public COMPARE_AXIS flatCompareAxis = COMPARE_AXIS.Z; public enum FILTER_TYPE {IgnoreTargetTracking, WaitToFireEvent} /// <summary> /// Determines if filtering will be performed on a TargetTracker's targets or an /// EventTrigger's targets. See the component description for more detail. This is /// ignored unless a its GameObject has both. Otherwise the mode will be auto-detected. /// </summary> public FILTER_TYPE filterType = FILTER_TYPE.WaitToFireEvent; public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; protected EventFireController fireCtrl; protected TargetTracker tracker; protected Target currentTarget; // Loop cache protected List<Target> iterTargets = new List<Target>(); // Loop cache protected void Awake() { this.fireCtrl = this.GetComponent<EventFireController>(); // If a fireController was found it is cheaper to use its cached reference to get the // TargetTracker if (this.fireCtrl != null) this.tracker = this.fireCtrl.targetTracker; else this.tracker = this.GetComponent<TargetTracker>(); // Just in case if (this.fireCtrl == null && this.tracker == null) { throw new MissingComponentException ( "Must have at least a TargetTracker or EventFireController" ); } // If only 1 is set, force the filterType if (this.fireCtrl == null || this.tracker == null) { if (this.fireCtrl != null) this.filterType = FILTER_TYPE.WaitToFireEvent; else this.filterType = FILTER_TYPE.IgnoreTargetTracking; } } // OnEnable and OnDisable add the check box in the inspector too. protected void OnEnable() { if (this.tracker != null) this.tracker.AddOnPostSortDelegate(this.FilterTrackerTargetList); if (this.fireCtrl != null) this.fireCtrl.AddOnPreFireDelegate(this.FilterFireCtrlTargetList); } protected void OnDisable() { if (this.tracker != null) this.tracker.RemoveOnPostSortDelegate(this.FilterTrackerTargetList); if (this.fireCtrl != null) this.fireCtrl.RemoveOnPreFireDelegate(this.FilterFireCtrlTargetList); } protected void FilterFireCtrlTargetList(TargetList targets) { if (this.filterType == FILTER_TYPE.WaitToFireEvent) this.FilterTargetList(targets); // Else do nothing. } protected void FilterTrackerTargetList(TargetTracker source, TargetList targets) { if (this.filterType == FILTER_TYPE.IgnoreTargetTracking) this.FilterTargetList(targets); // Else do nothing. } protected void FilterTargetList(TargetList targets) { #if UNITY_EDITOR var debugRemoveNames = new List<string>(); #endif this.iterTargets.Clear(); this.iterTargets.AddRange(targets); for (int i = 0; i < iterTargets.Count; i++) { this.currentTarget = iterTargets[i]; if (this.IsInAngle(this.currentTarget)) continue; // This target is good. Don't ignore it. Continue. #if UNITY_EDITOR debugRemoveNames.Add(this.currentTarget.targetable.name); #endif targets.Remove(this.currentTarget); } #if UNITY_EDITOR if (this.debugLevel == DEBUG_LEVELS.High && debugRemoveNames.Count > 0) { string msg = string.Format ( "Holding fire due to misalignment: {0}", string.Join(", ", debugRemoveNames.ToArray()) ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif } protected bool IsInAngle(Target target) { Vector3 targetDir = target.transform.position - this.origin.position; Vector3 forward = this.origin.forward; if (this.flatAngleCompare) { switch (this.flatCompareAxis) { case COMPARE_AXIS.X: targetDir.x = forward.x = 0; // Flatten Vectors break; case COMPARE_AXIS.Y: targetDir.y = forward.y = 0; // Flatten Vectors break; case COMPARE_AXIS.Z: targetDir.z = forward.z = 0; // Flatten Vectors break; } } bool isInAngle = Vector3.Angle(targetDir, forward) < this.angle; #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) { // Multiply the direction Vector by distance to make the line longer forward = this.origin.forward * targetDir.magnitude; if (isInAngle) { Debug.DrawRay(this.origin.position, forward, Color.green, 0.01f); } else { Debug.DrawRay(this.origin.position, forward, Color.red, 0.01f); Debug.DrawRay(this.origin.position, targetDir, Color.yellow, 0.01f); } } #endif return isInAngle; } } }<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(TurntableConstraint)), CanEditMultipleObjects] public class TurntableConstraintInspector : ConstraintFrameworkBaseInspector { protected SerializedProperty randomStart; protected SerializedProperty speed; protected override void OnEnable() { base.OnEnable(); this.randomStart = this.serializedObject.FindProperty("randomStart"); this.speed = this.serializedObject.FindProperty("speed"); } protected override void OnInspectorGUIUpdate() { base.OnInspectorGUIUpdate(); GUIContent content; content = new GUIContent ( "Speed", "How fast the constrant can rotate." ); EditorGUILayout.PropertyField(this.speed, content); content = new GUIContent ( "Random Start", "If true, each time the constraint is enabled it will start from a new and random " + "angle of rotation. This is helpful when several objects start rotating on the " + "same frame but you do not want them to all rotate insync with each other " + "visually." ); EditorGUILayout.PropertyField(this.randomStart, content); } } } <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; using PathologicalGames; [CustomEditor(typeof(IgnoreTagModifier)), CanEditMultipleObjects] public class IgnoreTagModifierInspector : Editor { protected SerializedProperty debugLevel; protected SerializedProperty ignoreList; protected void OnEnable() { this.debugLevel = this.serializedObject.FindProperty("debugLevel"); this.ignoreList = this.serializedObject.FindProperty("ignoreList"); } public override void OnInspectorGUI() { this.serializedObject.Update(); Object[] targetObjs = this.serializedObject.targetObjects; IgnoreTagModifier curEditTarget; GUIContent content; EditorGUIUtility.labelWidth = PGEditorUtils.CONTROLS_DEFAULT_LABEL_WIDTH; EditorGUI.indentLevel = 1; GUILayout.Space(6); if (this.serializedObject.isEditingMultipleObjects) { content = new GUIContent("Tags to Ignore", "List of tags to ignore."); EditorGUILayout.PropertyField(this.ignoreList, content, true); } else { curEditTarget = (IgnoreTagModifier)targetObjs[0]; // Display and get user changes PGEditorUtils.FoldOutTextList ( "Tags to ignore", curEditTarget.ignoreList, true // Force the fold-out state ); } GUILayout.Space(4); content = new GUIContent ( "Debug Level", "Set it higher to see more verbose information." ); EditorGUILayout.PropertyField(this.debugLevel, content); serializedObject.ApplyModifiedProperties(); // Flag Unity to save the changes to to the prefab to disk // This is needed to make the gizmos update immediatly. if (GUI.changed) EditorUtility.SetDirty(target); } } <file_sep>using UnityEngine; using System.Collections; using System.Collections.Generic; //공격력 사거리 재장전 public class Skill6LaserRotation : MonoBehaviour, ISkill { public status skillset; public float movSpeed,minRot, maxRot, waitTime, standTime; public int machineCnt; public List<GameObject> machineList; public GameObject machine; GameObject tmp; LaserMachine ltmp; void Start() { //StartCoroutine("Delay"); //UseSkill(); } public void SetSkill(int hp, float length, float reload, float movSpeed, float minRot, float maxRot, float waitTime, float standTime, int machineCnt) { skillset.damage = hp; skillset.distance = length; skillset.reload = reload; this.movSpeed = movSpeed; this.minRot = minRot; this.maxRot = maxRot; this.waitTime = waitTime; this.standTime = standTime; this.machineCnt = machineCnt; } public void UseSkill() { float rad = (float)(360f / machineCnt); for (int i = 0; i < machineCnt; i++) { tmp = Instantiate(machine,transform.position,Quaternion.identity) as GameObject; tmp.transform.rotation = Quaternion.Euler(0,0, (rad * i) ); machineList.Add(tmp); ltmp = tmp.transform.GetChild(0).transform.GetChild(0).GetComponent<LaserMachine>(); ltmp.hp = skillset.damage; ltmp.length = skillset.distance; ltmp.movSpeed = movSpeed; ltmp.rotSpeed = Random.Range(minRot, maxRot); ltmp.waitTime = waitTime; ltmp.standTime = standTime; } } IEnumerator Delay() { while (true) { yield return new WaitForSeconds(skillset.reload); UseSkill(); } } } <file_sep>using UnityEngine; using System.Collections; using PathologicalGames; public class PlacedMultipleSpiralShooter : MonoBehaviour { public float shotAngle; public float shotAngleRate; public float shotSpeed; public float shotDelay; public int shotCount; public bool canShoot = true; public int MoveTime; public int StopTime; public GameObject bullet; public int bulletMoney; public float bulletHp; static SpawnPool spawnPool = null; Transform tmp, tr; PlacedBullet tBullet; void Awake() { tr = GetComponent<Transform>(); } void Start() { if (spawnPool == null) { spawnPool = PoolManager.Pools ["Test"]; } StartCoroutine ("SpawnObject"); } IEnumerator SpawnObject() { while (true) { if (canShoot) { if (shotAngle >= 1) shotAngle = 0; shotAngle += shotCount * shotAngleRate; for (int i = 0; i < shotCount; i++) { tmp = spawnPool.Spawn (bullet, Vector3.zero, Quaternion.identity); tBullet = tmp.GetComponent<PlacedBullet> (); tmp.transform.position = tr.position; tBullet.speed = shotSpeed; tBullet.InitialSpeed = shotSpeed; tBullet.angle = shotAngle + (float)i / shotCount; tBullet.speedRate = 0; tBullet.angleRate = 0; tBullet.MoveTime = MoveTime; tBullet.StopTime = StopTime; tBullet.Timer = 0; tBullet.basicHP = bulletHp; tBullet.hp = bulletHp; tBullet.money = bulletMoney; } } yield return new WaitForSeconds (shotDelay); } } } <file_sep>/* * Energy Bar Toolkit by Mad Pixel Machine * http://www.madpixelmachine.com */ using UnityEngine; using System.Collections; using System.Collections.Generic; namespace EnergyBarToolkit { [ExecuteInEditMode] public class MultiBarSliders : MonoBehaviour { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public Bar[] bars; public Rect area = new Rect(10, 10, 140, 400); // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== void Start() { } void Update() { } void OnGUI() { if (bars == null) { return; } GUILayout.BeginArea(area); foreach (Bar bar in bars) { GUILayout.Label(bar.label); float val = 0; if (bar.bar != null) { val = bar.bar.ValueF; } val = GUILayout.HorizontalSlider(val, 0, 1); if (Application.isPlaying) { bar.bar.ValueF = val; } } GUILayout.EndArea(); } // =========================================================== // Static Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== [System.Serializable] public class Bar { public EnergyBar bar; public string label = "Edit Me!"; } } } // namespace <file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Provides messaging for event delegates primarily for use with UnityScript since only /// C# has delegates. /// /// To use: /// 1. Add this component to the same GameObject as the component you want to send event /// messages for. /// 2. Set the "For Component" to match the component on the GameObject to display the /// events available. /// 3. Choose the events you want to use. /// 4. In a script, simply create a function of the same name as the message and it will /// be triggered. If the script is on another GameObject, drag and drop it on to Other /// Message Target. /// /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Messenger")] public class TriggerEventProMessenger : MonoBehaviour { [System.Flags] public enum COMPONENTS { FireController = 1, EventTrigger = 2, // Breaking alpha-order for backwards compatability Targetable = 4, TargetTracker = 8 } public COMPONENTS forComponent = 0; public enum MESSAGE_MODE { Send, Broadcast } public MESSAGE_MODE messageMode; /// <summary> /// An optional GameObject to message instead of this component's GameObject /// </summary> public GameObject otherTarget = null; public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; // TargetTracker Events public bool targetTracker_OnPostSort = false; public bool targetTracker_OnNewDetected = false; public bool targetTracker_OnTargetsChanged = false; // FireController Events public bool fireController_OnStart = false; public bool fireController_OnUpdate = false; public bool fireController_OnTargetUpdate = false; public bool fireController_OnIdleUpdate = false; public bool fireController_OnPreFire = false; public bool fireController_OnFire = false; public bool fireController_OnStop = false; // EventTrigger Events public bool eventTrigger_OnListenStart = false; public bool eventTrigger_OnListenUpdate = false; public bool eventTrigger_OnFire = false; public bool eventTrigger_OnFireUpdate = false; public bool eventTrigger_OnHitTarget = false; // Targetable Events public bool targetable_OnHit = false; public bool targetable_OnHitCollider = false; public bool targetable_OnDetected = false; public bool targetable_OnNotDetected = false; protected void Awake() { // Register all to allow run-time changes to individual events // The delegates don't send messages unless the bool is true anyway. this.RegisterTargetTracker(); this.RegisterFireController(); this.RegisterEventTrigger(); this.RegisterTargetable(); } /// <summary> /// Generic message handler to process options. /// </summary> /// <param name="msg"></param> protected void handleMsg(string msg) { GameObject GO; if (this.otherTarget == null) GO = this.gameObject; else GO = this.otherTarget; if (this.debugLevel > DEBUG_LEVELS.Off) Debug.Log(string.Format("Sending message '{0}' to '{1}'", msg, GO)); if (this.messageMode == MESSAGE_MODE.Send) GO.SendMessage(msg, SendMessageOptions.DontRequireReceiver); else GO.BroadcastMessage(msg, SendMessageOptions.DontRequireReceiver); } /// <summary> /// Generic message handler to process options. /// </summary> /// <param name="msg"></param> protected void handleMsg<T>(string msg, T arg) { GameObject GO; if (this.otherTarget == null) GO = this.gameObject; else GO = this.otherTarget; if (this.debugLevel > DEBUG_LEVELS.Off) Debug.Log ( string.Format("Sending message '{0}' to '{1}' with argument {2}", msg, GO, arg) ); if (this.messageMode == MESSAGE_MODE.Send) GO.SendMessage(msg, arg, SendMessageOptions.DontRequireReceiver); else GO.BroadcastMessage(msg, arg, SendMessageOptions.DontRequireReceiver); } # region TargetTracker protected void RegisterTargetTracker() { // There is no need to initialize delegates if there is no component var component = this.GetComponent<TargetTracker>(); if (component == null) return; component.AddOnPostSortDelegate(this.OnPostSortDelegate); component.AddOnNewDetectedDelegate(this.OnNewDetectedDelegate); component.AddOnTargetsChangedDelegate(this.OnTargetsChangedDelegate); } protected void OnPostSortDelegate(TargetTracker source, TargetList targets) { if (this.targetTracker_OnPostSort == false) return; // Pack the data in to a struct since we can only pass one argument var data = new MessageData_TargetTrackerEvent(source, targets); this.handleMsg<MessageData_TargetTrackerEvent>("TargetTracker_OnPostSort", data); } protected bool OnNewDetectedDelegate(TargetTracker source, Target target) { if (this.targetTracker_OnNewDetected == false) return true; // Pack the data in to a struct since we can only pass one argument var data = new MessageData_TargetTrackerEvent(source, target); this.handleMsg<MessageData_TargetTrackerEvent>("TargetTracker_OnNewDetected", data); return true; } protected void OnTargetsChangedDelegate(TargetTracker source) { if (this.targetTracker_OnTargetsChanged == false) return; this.handleMsg<TargetTracker>("TargetTracker_OnTargetsChanged", source); } # endregion TargetTracker # region FireController protected void RegisterFireController() { // There is no need to initialize delegates if there is no component var component = this.GetComponent<EventFireController>(); if (component == null) return; component.AddOnStartDelegate(this.OnStartDelegate); component.AddOnUpdateDelegate(this.OnUpdateDelegate); component.AddOnTargetUpdateDelegate(this.OnTargetUpdateDelegate); component.AddOnIdleUpdateDelegate(this.OnIdleUpdateDelegate); component.AddOnPreFireDelegate(this.OnPreFireDelegate); component.AddOnFireDelegate(this.OnFireDelegate); component.AddOnStopDelegate(this.OnStopDelegate); } protected void OnStartDelegate() { if (this.fireController_OnStart == false) return; this.handleMsg("FireController_OnStart"); } protected void OnUpdateDelegate() { if (this.fireController_OnUpdate == false) return; this.handleMsg("FireController_OnUpdate"); } protected void OnTargetUpdateDelegate(TargetList targets) { if (this.fireController_OnTargetUpdate == false) return; this.handleMsg<TargetList>("FireController_OnTargetUpdate", targets); } protected void OnIdleUpdateDelegate() { if (this.fireController_OnIdleUpdate == false) return; this.handleMsg("FireController_OnIdleUpdate"); } protected void OnPreFireDelegate(TargetList targets) { if (this.fireController_OnPreFire == false) return; this.handleMsg<TargetList>("FireController_OnPreFire", targets); } protected void OnFireDelegate(TargetList targets) { if (this.fireController_OnFire == false) return; this.handleMsg<TargetList>("FireController_OnFire", targets); } protected void OnStopDelegate() { if (this.fireController_OnStop == false) return; this.handleMsg("FireController_OnStop"); } # endregion FireController # region EventTrigger protected void RegisterEventTrigger() { // There is no need to initialize delegates if there is no component var component = this.GetComponent<EventTrigger>(); if (component == null) return; component.AddOnListenStartDelegate(this.OnListenStartDelegate); component.AddOnListenUpdateDelegate(this.OnListenUpdateDelegate); component.AddOnFireDelegate(this.EventTrigger_OnFireDelegate); component.AddOnFireUpdateDelegate(this.OnFireUpdateDelegate); component.AddOnHitTargetDelegate(this.OnHitTargetDelegate); } protected void OnListenStartDelegate() { if (this.eventTrigger_OnListenStart == false) return; this.handleMsg("EventTrigger_OnListenStart"); } protected void OnListenUpdateDelegate() { if (this.eventTrigger_OnListenUpdate == false) return; this.handleMsg("EventTrigger_OnListenUpdate"); } protected void EventTrigger_OnFireDelegate(TargetList targets) { if (this.eventTrigger_OnFire == false) return; this.handleMsg<TargetList>("EventTrigger_OnFire", targets); } protected void OnFireUpdateDelegate(float progress) { if (this.eventTrigger_OnFireUpdate == false) return; this.handleMsg<float>("EventTrigger_OnFireUpdate", progress); } protected void OnHitTargetDelegate(Target target) { if (this.eventTrigger_OnHitTarget == false) return; this.handleMsg<Target>("EventTrigger_OnHitTarget", target); } # endregion EventTrigger # region Targetable protected void RegisterTargetable() { // There is no need to initialize delegates if there is no component var component = this.GetComponent<Targetable>(); if (component == null) return; component.AddOnHitDelegate(this.OnHitDelegate); component.AddOnDetectedDelegate(this.OnDetectedDelegate); component.AddOnNotDetectedDelegate(this.OnNotDetectedDelegate); } protected void OnHitDelegate(EventInfoList eventInfoList, Target target) { if (this.targetable_OnHit == false) return; // Pack the data in to a struct since we can only pass one argument var data = new MessageData_TargetableOnHit(eventInfoList, target); this.handleMsg<MessageData_TargetableOnHit>("Targetable_OnHit", data); } protected void OnHitColliderDelegate(EventInfoList eventInfoList, Target target, Collider other) { if (this.targetable_OnHit == false) return; // Pack the data in to a struct since we can only pass one argument var data = new MessageData_TargetableOnHit(eventInfoList, target, other); this.handleMsg<MessageData_TargetableOnHit>("Targetable_OnHitCollider", data); } protected void OnDetectedDelegate(TargetTracker source) { if (targetable_OnDetected == false) return; this.handleMsg<TargetTracker>("Targetable_OnDetected", source); } protected void OnNotDetectedDelegate(TargetTracker source) { if (this.targetable_OnNotDetected == false) return; this.handleMsg<TargetTracker>("Targetable_OnNotDetected", source); } # endregion Targetable } /// <summary> /// This is used to pass arguments for the Targetable OnHit events because Unity's /// SendMessage only takes a single argument /// </summary> public struct MessageData_TargetableOnHit { public EventInfoList eventInfoList; public Target target; public Collider collider; public MessageData_TargetableOnHit(EventInfoList eventInfoList, Target target) { this.eventInfoList = eventInfoList; this.target = target; this.collider = null; } public MessageData_TargetableOnHit(EventInfoList eventInfoList, Target target, Collider other) { this.eventInfoList = eventInfoList; this.target = target; this.collider = other; } } /// <summary> /// This is used to pass arguments for the TargetTracker events because Unity's /// SendMessage only takes a single argument /// </summary> public struct MessageData_TargetTrackerEvent { public TargetTracker targetTracker; public Target target; public TargetList targets; public MessageData_TargetTrackerEvent(TargetTracker targetTracker, Target target) { this.targetTracker = targetTracker; this.target = target; this.targets = new TargetList(); } public MessageData_TargetTrackerEvent(TargetTracker targetTracker, TargetList targets) { this.targetTracker = targetTracker; this.target = Target.Null; this.targets = targets; } } }<file_sep>[System.Serializable] public struct status { public int damage; public float distance; public float reload; }<file_sep>using UnityEngine; using System.Collections; using PathologicalGames; public class RandomNwayShooter : MonoBehaviour { public float ShotAngleRange; public float ShotSpeed; public int ShotCount; public int Interval; private int Timer; public GameObject bullet; public bool canShoot = true; public int bulletMoney; public float bulletHp; static SpawnPool spawnPool = null; Transform tmp, tr; Bullet tBullet; void Awake() { tr = GetComponent<Transform>(); } void Start() { if (spawnPool == null) { spawnPool = PoolManager.Pools["Test"]; } } void Update() { if (Timer == 0 && canShoot) { for (int i = 0; i < ShotCount; i++) { tmp = spawnPool.Spawn(bullet); tBullet = tmp.GetComponent<Bullet>(); tmp.transform.position = tr.position; tBullet.speed = ShotSpeed; tBullet.speedRate = 0; tBullet.angleRate = 0; tBullet.angle = EnemyLib.instance.GetPlayerAngle(transform.position) + ShotAngleRange * (Random.Range(0.0f, 1.0f) - 0.5f); tBullet.basicHP = bulletHp; tBullet.hp = bulletHp; tBullet.money = bulletMoney; } } if (canShoot) Timer = (Timer + 1) % Interval; if (!canShoot) Timer = 0; } } <file_sep>/* * Energy Bar Toolkit by Mad Pixel Machine * http://www.madpixelmachine.com */ using UnityEngine; using System.Collections; using System.Collections.Generic; [ExecuteInEditMode] public class BarOptionsGUIMulti : MonoBehaviour { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public Rect position = new Rect(10, 100, 200, 100); public GameObject[] energyBars; public GUISkin skin; public float valueF = 0.25f; // =========================================================== // Constructors (Including Static Constructors) // =========================================================== // =========================================================== // Getters / Setters // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== void Start() { } void Update() { } void OnGUI() { GUILayout.BeginArea(position); GUILayout.Label("Change Value:"); valueF = GUILayout.HorizontalSlider(valueF, 0.0f, 1.0f); GUILayout.EndArea(); foreach (var go in energyBars) { var bar = go.GetComponent<EnergyBar>(); bar.ValueF = valueF; } } // =========================================================== // Methods // =========================================================== // =========================================================== // Static Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }<file_sep>using UnityEngine; namespace PathologicalGames { [RequireComponent(typeof(Targetable))] public class DemoPlayer : MonoBehaviour { public int life = 100; public ParticleSystem explosion; protected bool isDead = false; protected void Awake() { var targetable = this.GetComponent<Targetable>(); targetable.AddOnHitDelegate(this.OnHit); } protected void OnHit(EventInfoList infoList, Target target) { if (this.isDead) return; foreach (EventInfo info in infoList) { switch (info.name) { case "Life": this.life += (int)info.value; break; case "Damage": this.life -= (int)info.value; break; } } if (this.life <= 0) { this.isDead = true; Instantiate ( this.explosion.gameObject, this.transform.position, this.transform.rotation ); this.gameObject.SetActive(false); } } protected void OnGUI() { GUI.Label(new Rect(10, 10, 100, 20), "LIFE: " + this.life); } } }<file_sep>/// <Licensing> /// ©2011-2014 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; namespace PathologicalGames { /// <summary> /// Adds the ability to only fire on Targets within a distance range of a TargetTracker. /// This is like having a second spherical Area. Useful when you want objects to be /// "detected" but not actually able to be fired on until they get closer. /// </summary> [AddComponentMenu("Path-o-logical/TriggerEventPRO/TriggerEventPRO Modifier - Fire Distance")] [RequireComponent(typeof(EventFireController))] public class FireDistanceModifier : TriggerEventProModifier { public enum ORIGIN_MODE { TargetTracker, TargetTrackerArea, FireController, FireControllerEmitter } /// <summary> /// The origin is the point from which the distance is measuered. /// </summary> public ORIGIN_MODE originMode = ORIGIN_MODE.FireController; public float minDistance = 0; public float maxDistance = 1; public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; #if UNITY_EDITOR // Inspector-Only public bool drawGizmo = true; public Color gizmoColor = new Color(0, 0.7f, 1, 1); // Cyan-blue mix public Color defaultGizmoColor { get { return new Color(0, 0.7f, 1, 1); } } public bool overrideGizmoVisibility = false; #endif // Public for reference and Inspector logic public EventFireController fireCtrl; public Transform origin { get { Transform xform = this.transform; switch (this.originMode) { case ORIGIN_MODE.TargetTracker: xform = this.fireCtrl.targetTracker.transform; break; case ORIGIN_MODE.TargetTrackerArea: // If there is no Area, use the TargetTracker itself Area area = this.fireCtrl.targetTracker.area; if (area == null) throw new MissingReferenceException(string.Format ( "FireController {0}'s TargetTracker doesn't have an Area" + "If by design, such as a CollisionTargetTracker, use the " + "'TargetTracker' or other Origin Mode option.", this.fireCtrl.name )); xform = area.transform; break; case ORIGIN_MODE.FireController: xform = this.origin = this.transform; break; case ORIGIN_MODE.FireControllerEmitter: // If there is no emitter set, use this (same as FireController). if (this.fireCtrl.spawnEventTriggerAtTransform == null) throw new MissingReferenceException(string.Format ( "FireController {0} doesn't have an emitter set. " + "Add one or use the 'Fire Controller' Origin Mode option.", this.fireCtrl.name )); xform = this.fireCtrl.spawnEventTriggerAtTransform; break; } return xform; } set {} } protected Target currentTarget; // Loop cache protected List<Target> iterTargets = new List<Target>(); // Loop cache protected void Awake() { this.fireCtrl = this.GetComponent<EventFireController>(); } // OnEnable and OnDisable add the check box in the inspector too. protected void OnEnable() { this.fireCtrl.AddOnPreFireDelegate(this.FilterFireTargetList); } protected void OnDisable() { if (this.fireCtrl != null) // For when levels or games are dumped this.fireCtrl.RemoveOnPreFireDelegate(this.FilterFireTargetList); } protected void FilterFireTargetList(TargetList targets) { // Get the position expected to be used to fire from. Vector3 fromPos = this.origin.position; #if UNITY_EDITOR var debugRemoveNames = new List<string>(); #endif this.iterTargets.Clear(); this.iterTargets.AddRange(targets); float dist; for (int i = 0; i < iterTargets.Count; i++) { this.currentTarget = iterTargets[i]; dist = this.currentTarget.targetable.GetDistToPos(fromPos); // Skip if the target is in the distance range if (dist > this.minDistance && dist < this.maxDistance) { #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine ( fromPos, this.currentTarget.targetable.transform.position, Color.green, 0.01f ); #endif continue; } #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) Debug.DrawLine ( fromPos, this.currentTarget.targetable.transform.position, Color.red, 0.01f ); #endif targets.Remove(this.currentTarget); #if UNITY_EDITOR debugRemoveNames.Add(this.currentTarget.targetable.name); #endif } #if UNITY_EDITOR if (this.debugLevel == DEBUG_LEVELS.High && debugRemoveNames.Count > 0) { string msg = string.Format ( "Holding fire due to distance: {0}", string.Join(", ", debugRemoveNames.ToArray()) ); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif } } }<file_sep>/* * Copyright (c) Mad Pixel Machine * http://www.madpixelmachine.com/ */ using EnergyBarToolkit; using UnityEditor; using UnityEngine; namespace EnergyBarToolkit { [CustomEditor(typeof(TransformRendererUGUI))] public class TransformRendererUGUIInspector : EnergyBarUGUIInspectorBase { #region Fields private SerializedProperty spriteObject; private SerializedProperty spriteObjectPivot; private SerializedProperty transformTranslate; private SerializedProperty transformRotate; private SerializedProperty transformScale; private SerializedProperty translateFunction; private SerializedProperty rotateFunction; private SerializedProperty scaleFunction; private SerializedProperty translateFunctionStart; private SerializedProperty translateFunctionEnd; private SerializedProperty translateAnimation; private SerializedProperty rotateFunctionStart; private SerializedProperty rotateFunctionEnd; private SerializedProperty rotateAnimation; private SerializedProperty scaleFunctionStart; private SerializedProperty scaleFunctionEnd; private SerializedProperty scaleAnimation; #endregion #region Methods public override void OnEnable() { base.OnEnable(); spriteObject = serializedObject.FindProperty("spriteObject"); spriteObjectPivot = serializedObject.FindProperty("spriteObjectPivot"); transformTranslate = serializedObject.FindProperty("transformTranslate"); transformRotate = serializedObject.FindProperty("transformRotate"); transformScale = serializedObject.FindProperty("transformScale"); translateFunction = serializedObject.FindProperty("translateFunction"); rotateFunction = serializedObject.FindProperty("rotateFunction"); scaleFunction = serializedObject.FindProperty("scaleFunction"); translateFunctionStart = translateFunction.FindPropertyRelative("startPosition"); translateFunctionEnd = translateFunction.FindPropertyRelative("endPosition"); translateAnimation = translateFunction.FindPropertyRelative("animationCurve"); rotateFunctionStart = rotateFunction.FindPropertyRelative("startAngle"); rotateFunctionEnd = rotateFunction.FindPropertyRelative("endAngle"); rotateAnimation = rotateFunction.FindPropertyRelative("animationCurve"); scaleFunctionStart = scaleFunction.FindPropertyRelative("startScale"); scaleFunctionEnd = scaleFunction.FindPropertyRelative("endScale"); scaleAnimation = scaleFunction.FindPropertyRelative("animationCurve"); } public override void OnInspectorGUI() { serializedObject.UpdateIfDirtyOrScript(); SectionTextures(); SectionAppearance(); EditorGUILayout.Space(); SectionObjectTransform(); EditorGUILayout.Space(); SectionEffects(); SectionDebugMode(); serializedObject.ApplyModifiedProperties(); } private void SectionTextures() { GUILayout.Label("Textures", "HeaderLabel"); using (MadGUI.Indent()) { FieldBackgroundSprites(); EditorGUILayout.Space(); FieldSprite(spriteObject, "Object Sprite", MadGUI.ObjectIsSet); using (MadGUI.Indent()) { MadGUI.PropertyField(spriteObject.FindPropertyRelative("material"), "Material"); } MadGUI.PropertyFieldVector2(spriteObjectPivot, "Object Pivot"); EditorGUILayout.Space(); FieldForegroundSprites(); } } private void SectionAppearance() { GUILayout.Label("Appearance", "HeaderLabel"); using (MadGUI.Indent()) { FieldSetNativeSize(); EditorGUILayout.Space(); FieldLabel2(); GUI.enabled = true; } } private void SectionObjectTransform() { GUILayout.Label("Object Transform", "HeaderLabel"); using (MadGUI.Indent()) { MadGUI.PropertyFieldToggleGroup2(transformTranslate, "Translate", () => { MadGUI.Indent(() => { MadGUI.PropertyFieldVector2(translateFunctionStart, "Start Point"); MadGUI.PropertyFieldVector2(translateFunctionEnd, "End Point"); MadGUI.PropertyField(translateAnimation, "Curve"); }); }); MadGUI.PropertyFieldToggleGroup2(transformRotate, "Rotate", () => { MadGUI.Indent(() => { MadGUI.PropertyField(rotateFunctionStart, "Start Angle"); MadGUI.PropertyField(rotateFunctionEnd, "End Angle"); MadGUI.PropertyField(rotateAnimation, "Curve"); }); }); MadGUI.PropertyFieldToggleGroup2(transformScale, "Scale", () => { MadGUI.Indent(() => { MadGUI.PropertyFieldVector2(scaleFunctionStart, "Start Scale"); MadGUI.PropertyFieldVector2(scaleFunctionEnd, "End Scale"); MadGUI.PropertyField(scaleAnimation, "Curve"); }); }); } } private void SectionEffects() { GUILayout.Label("Effects", "HeaderLabel"); using (MadGUI.Indent()) { FieldSmoothEffect(); } } #endregion #region Inner and Anonymous Classes #endregion } } // namespace<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; using System.Collections.Generic; using System; namespace PathologicalGames { /// <summary> /// TargetTracker event that allows filtering the target list before it is passed on. /// </summary> public delegate void OnPostSortDelegate(TargetTracker source, TargetList targets); /// <summary> /// TargetTrackers with Areas should provide this event for Areas to trigger. /// Return false to block a target from being detected. /// </summary> public delegate bool OnNewDetectedDelegate(TargetTracker source, Target target); /// <summary> /// TargetTrackers with Areas should provide this event for Areas to trigger. /// Triggered everytime a target leaves an area. Targets already recieve a callback /// targetable.OnNotDetected() /// </summary> public delegate void OnNotDetectedDelegate(TargetTracker source, Target target); /// <summary> /// TargetTracker event that Runs when there is a change to the TargetTracker's target list /// or when it is set to dirty for any reason, commonly to trigger a re-sort. This will run /// after the dirty state or update is handled, and after the post sort delgates are done. /// </summary> public delegate void OnTargetsChangedDelegate(TargetTracker source); /// <summary> /// The base class for all TargetTrackers. This class is abstract so it can only be /// inherited and implimented, not used directly. /// </summary> /// <exception cref='System.NotImplementedException'> /// Is thrown when a requested operation is not implemented for a given type. /// </exception> public abstract class TargetTracker : MonoBehaviour, ITargetTracker { /// <summary> /// The number of targets to return. Set to -1 to return all targets /// </summary> public int numberOfTargets = 1; /// <summary> /// The layers in which the Area is allowed to find targets. /// </summary> public LayerMask targetLayers; /// <summary> /// The style of sorting to use /// </summary> public SORTING_STYLES sortingStyle { get { return this._sortingStyle; } set { // Only trigger logic if this changed if (this._sortingStyle == value) return; this._sortingStyle = value; // Trigger sorting due to this change this.dirty = true; } } [SerializeField] // protected backing fields must be SerializeField. For instances. protected SORTING_STYLES _sortingStyle = SORTING_STYLES.Nearest; /// <summary> /// How often the target list will be sorted. If set to 0, sorting will only be /// triggered when Targets enter or exit range. /// </summary> public float updateInterval = 0.1f; /// <summary> /// Set this to true to force the Area to sort and other refresh actions, if /// applicable. /// Setting this to false does nothing. /// </summary> /// <value> /// Always false because setting to true is handled immediatly. /// </value> public virtual bool dirty { get { return false; } // Always instantly processed and back to false set { #if UNITY_EDITOR // Stop inspector logic from running this if (!Application.isPlaying) return; #endif if (!value) return; // Trigger re-sort, events, etc. // WARNING!!! Copy this or "value" in the targets setter will be // this list (not a copy) and it will clear before trying to // AddRange to itself! (The list will be cleared forever) this.targets = new TargetList(this._unfilteredTargets); } } /// <summary> /// Setting this to true is like setting dirty to true except it can be set /// many times and will only set the true dirty state once at the end of the /// frame. /// This is used internally to handle situations when multiple trackers /// overlap and trigger dirty multiple times for the same event. /// </summary> public bool batchDirty { get { return this.batchDirtyRunning; } set { // Singleton. Quit one is already running if (this.batchDirtyRunning) return; this.StartCoroutine(this.RunBatchDirty()); } } protected bool batchDirtyRunning = false; protected IEnumerator RunBatchDirty() { this.batchDirtyRunning = true; yield return new WaitForEndOfFrame(); this.batchDirtyRunning = false; this.dirty = true; } /// <summary> /// A list of sorted targets. The contents depend on numberOfTargets requested /// (-1 for all targets in the Area), any modifications done by any /// onPostSortDelegates, and the sorting style used. /// Getting targets every frame has virtually no overhead because all sorting is /// done when targets are set (TargetTracker is "dirty"). This can be triggered /// by a user, Area or internal co-routine. If at least 2 /// targets are available a co-routine is started to update the sort based on /// the sort interval. The co-routine will stop if the number of targets falls /// back under 2 /// /// IMPORTANT: Setting this equal to another list will replace targets in this /// targets list, like a copy operation but using AddRange internally. It will NOT /// make this targets list equal to the other list. This is important protection. /// </summary> public virtual TargetList targets { get { return _targets; } set { // Start with an empty list each pass. this._unfilteredTargets.Clear(); this._targets.Clear(); // If none are wanted or no targets available, quit if (this.numberOfTargets == 0 || value.Count == 0) { if (this.onTargetsChangedDelegates != null) this.onTargetsChangedDelegates(this); return; } // Start with the un-filtered list for internal logic use. // This enables targets to be "detected" even if they are modified below // to be ignored further and so the sort update co-routine can keep running. // It is also used by this.dirty to re-run all this. this._unfilteredTargets.AddRange(value); this._targets.AddRange(this._unfilteredTargets); if (this.sortingStyle != SORTING_STYLES.None) { if (this._unfilteredTargets.Count > 1) // Don't bother with the overhead untill 2+) { var comparer = new TargetTracker.TargetComparer ( this.sortingStyle, this.transform ); this._targets.Sort(comparer); #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Normal) Debug.Log(string.Format ( "{0} : SORTED: {1}", this, this._targets.ToString() )); #endif } // Start coroutine to trigger periodic sorting? // This has to happen before delegates and numberOfTargets to be // able to respond to changes. // Only If not already running. // Will do nothing if there aren't at least 2 targets. // Will wait at least 1 frame, so sorting won't happen twice if (!this.isUpdateTargetsUpdateRunning && this.sortingStyle != AreaTargetTracker.SORTING_STYLES.None) { this.StartCoroutine(this.UpdateTargets()); } } if (this.onPostSortDelegates != null) this.onPostSortDelegates(this, this._targets); // If not -1 (all), get the first X item(s). Since everything is sorted based on // the sortingStyle, the first item(s) will always work if (this.numberOfTargets > -1) { // Grab the first item(s) int count = this._targets.Count; int num = Mathf.Clamp(this.numberOfTargets, 0, count); this._targets.RemoveRange(num, count - num); } #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Normal) // All higher than normal { string msg = string.Format("Updated targets to: {0}", this._targets.ToString()); Debug.Log(string.Format("{0}: {1}", this, msg)); } #endif if (this.onTargetsChangedDelegates != null) this.onTargetsChangedDelegates(this); } } protected TargetList _targets = new TargetList(); /// <summary> /// Makes the update co-routine a singleton. /// </summary> protected bool isUpdateTargetsUpdateRunning = false; /// <summary> /// Start with the un-filtered list for internal logic use. /// This enables targets to be "detected" even if they are modified below /// to be ignored further and so the sort update co-routine can keep running. /// It is also used by this.dirty to re-run all this. /// </summary> protected TargetList _unfilteredTargets = new TargetList(); /// <summary> /// Runs a sort when the list is dirty (has been changed) or when the timer expires. /// This co-routine will stop if there are no targets. and must be restarted when a /// target enters. /// </summary> /// <returns></returns> protected IEnumerator UpdateTargets() { this.isUpdateTargetsUpdateRunning = true; #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) // If on at all Debug.Log(string.Format("{0} : Starting update timer co-routine.", this)); #endif while (this._unfilteredTargets.Count > 0) // Quit if there aren't any targets { // Have to wait at least 1 frame to avoid an infinte loop. So if // the update interval is 0, wait the minimum...1 frame. if (this.updateInterval == 0) yield return null; else yield return new WaitForSeconds(this.updateInterval); this.dirty = true; } #if UNITY_EDITOR if (this.debugLevel > DEBUG_LEVELS.Off) // If on at all Debug.Log(string.Format("{0} : Ended update timer co-routine. Target count < 2", this)); #endif this.isUpdateTargetsUpdateRunning = false; } /// <summary> /// Not all TargetTrackers have Area. This is implemented to make it easy and /// cheap test for. Otherwise casting tests would be needed. /// </summary> public virtual Area area { get { return null; } protected set {} } /// <summary> /// Set to get visual and log feedback of what is happening in this TargetTracker /// and Area /// </summary> public DEBUG_LEVELS debugLevel = DEBUG_LEVELS.Off; #if UNITY_EDITOR /// <summary> /// Used by the Inspector to displays gizmos if applicable. /// </summary> public bool drawGizmo = true; /// <summary> /// The color of the gizmo when displayed /// </summary> public Color gizmoColor = new Color(0, 0.7f, 1, 0.5f); // Cyan-blue mix public Color defaultGizmoColor { get { return new Color(0, 0.7f, 1, 0.5f); } } // Used by inspector scripts as an override to hide the gizmo public bool overrideGizmoVisibility = false; #endif protected virtual void Awake() { // Pre-Unity5 this stored a cache to this.transform, which is no longer necessary // This Awake was kept to avoid changing sub-class accessors. No harm keeping this // in case it is needed in the future. } /// <summary> /// Set to dirty and manage events if applicable. Enable Area or if /// inheriting and not using a Area, override to leave it out. /// </summary> protected virtual void OnEnable() { this.dirty = true; } #region Utilities /// <summary> /// onNewDetectedDelegates can determine if a target is ignored entirely by returning /// false. Otherwise, the target is tracked. This will return true if the given target /// should be ignored (which means at least 1 of the delegates returned false). /// </summary> /// <returns> /// Returns true (ignore the target) if *any* onNewDetectedDelegates return false. /// If there are no delegates this function returns false (nothing to ignore). /// </returns> internal bool IsIgnoreTargetOnNewDetectedDelegatesExecute(Target target) { if (this.onNewDetectedDelegates == null) return false; // This executes onNewDetectedDelegates by iterating over them. If the delegates were // not executed by iterating, only the return value of the last one would count and // order is not guarnateed either. Delegate[] dels = this.onNewDetectedDelegates.GetInvocationList(); foreach (OnNewDetectedDelegate del in dels) if (!del(this, target)) return true; return false; } #endregion #region Delegates #region OnPostSortDelegates Add/Set/Remove internal protected OnPostSortDelegate onPostSortDelegates; /// <summary> /// Runs just before returning the targets list to allow for custom sorting. /// The delegate signature is: delegate(TargetList targets) /// See TargetTracker documentation for usage of the provided '...' /// This will only allow a delegate to be added once. /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnPostSortDelegate</param> public void AddOnPostSortDelegate(OnPostSortDelegate del) { this.onPostSortDelegates -= del; // Cheap way to ensure unique (add only once) this.onPostSortDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnPostSortDelegate() /// </summary> /// <param name="del">An OnPostSortDelegate</param> public void SetOnPostSortDelegate(OnPostSortDelegate del) { this.onPostSortDelegates = del; } /// <summary> /// Removes a OnPostSortDelegate /// See docs for AddOnPostSortDelegate() /// </summary> /// <param name="del">An OnPostSortDelegate</param> public void RemoveOnPostSortDelegate(OnPostSortDelegate del) { this.onPostSortDelegates -= del; } #endregion OnPostSortDelegates Add/Set/Remove #region OnTargetsChangedDelegates Add/Set/Remove internal protected OnTargetsChangedDelegate onTargetsChangedDelegates; /// <summary> /// Runs when there is a change to the TargetTracker's target list or when it is set /// to dirty for any reason, commonly to trigger a re-sort. This will run after the /// dirty state or update is handled. /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del">An OnTargetsChangedDelegate</param> public void AddOnTargetsChangedDelegate(OnTargetsChangedDelegate del) { this.onTargetsChangedDelegates -= del; // Cheap way to ensure unique (add only once) this.onTargetsChangedDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnTargetsChangedDelegate() /// </summary> /// <param name="del">An OnTargetsChangedDelegate</param> public void SetOnTargetsChangedDelegate(OnTargetsChangedDelegate del) { this.onTargetsChangedDelegates = del; } /// <summary> /// Removes a OnTargetsChangedDelegate /// See docs for AddOnTargetsChangedDelegate() /// </summary> /// <param name="del">An OnTargetsChangedDelegate</param> public void RemoveOnTargetsChangedDelegate(OnTargetsChangedDelegate del) { this.onTargetsChangedDelegates -= del; } #endregion OnTargetsChangedDelegates Add/Set/Remove #region OnDetectedDelegates internal protected OnNewDetectedDelegate onNewDetectedDelegates; // Executed by Area /// <summary> /// Add a new delegate to be triggered when a target is first found by an Area. /// The delegate signature is: bool delegate(TargetTracker source, Target target) /// Return true to have no effect on the TargetTracker functioning /// Return false to cause the TargetTracker to ignore the new target entirely. /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del"></param> public void AddOnNewDetectedDelegate(OnNewDetectedDelegate del) { this.onNewDetectedDelegates -= del; // Cheap way to ensure unique (add only once) this.onNewDetectedDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnNewDetectedDelegate() /// </summary> /// <param name="del"></param> public void SetOnNewDetectedDelegate(OnNewDetectedDelegate del) { this.onNewDetectedDelegates = del; } /// <summary> /// Removes a OnDetectedDelegate /// See docs for AddOnDetectedDelegate() /// </summary> /// <param name="del"></param> public void RemoveOnNewDetectedDelegate(OnNewDetectedDelegate del) { this.onNewDetectedDelegates -= del; } #endregion OnDetectedDelegates #region OnNotDetectedDelegates internal protected OnNotDetectedDelegate onNotDetectedDelegates; // Executed by Area /// <summary> /// Add a new delegate to be triggered when a target is first found by an Area. /// The delegate signature is: bool delegate(TargetTracker source, Target target) /// Return true to have no effect on the TargetTracker functioning /// Return false to cause the TargetTracker to ignore the new target entirely. /// **This will only allow a delegate to be added once.** /// </summary> /// <param name="del"></param> public void AddOnNotDetectedDelegate(OnNotDetectedDelegate del) { this.onNotDetectedDelegates -= del; // Cheap way to ensure unique (add only once) this.onNotDetectedDelegates += del; } /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnNotDetectedDelegate() /// </summary> /// <param name="del"></param> public void SetOnNotDetectedDelegate(OnNotDetectedDelegate del) { this.onNotDetectedDelegates = del; } /// <summary> /// Removes a OnNotDetectedDelegate /// See docs for AddOnNotDetectedDelegate() /// </summary> /// <param name="del"></param> public void RemoveOnNotDetectedDelegate(OnNotDetectedDelegate del) { this.onNotDetectedDelegates -= del; } #endregion OnNotDetectedDelegates #endregion Delegates #region Sorting Options and Functionality /// <summary> /// Target Style Options used to keep targets sorted /// </summary> public enum SORTING_STYLES { None = 0, // Also good for area-of-effects where no sort is needed Nearest = 1, // Closest to the perimter's center (localPostion) Farthest = 2, // Farthest from the perimter's center (localPostion) NearestToDestination = 3, // Nearest to a destination along waypoints FarthestFromDestination = 4, // Farthest from a destination along waypoints MostPowerful = 5, // Most powerful based on a iTargetable parameter LeastPowerful = 6, // Least powerful based on a iTargetable parameter } #endregion Sorting Options and Functionality #region Comparers for Perimter.Sort() /// <summary> /// The interface for all target comparers. /// </summary> public interface iTargetComparer : IComparer<Target> { new int Compare(Target targetA, Target targetB); } /// <summary> /// Returns a comparer based on a targeting style. /// </summary> public class TargetComparer : iTargetComparer { protected Transform xform; protected TargetTracker.SORTING_STYLES sortStyle; /// <summary> /// Constructor /// </summary> /// <param name="sortStyle">The target style used to return a comparer</param> /// <param name="xform">Position for distance-based sorting</param> public TargetComparer(TargetTracker.SORTING_STYLES sortStyle, Transform xform) { this.xform = xform; this.sortStyle = sortStyle; } /// <summary> /// Used by List.Sort() to custom sort the targets list. /// </summary> /// <param name="targetA">The first object for comparison</param> /// <param name="targetB">The second object for comparison</param> /// <returns></returns> public int Compare(Target targetA, Target targetB) { switch (this.sortStyle) { case SORTING_STYLES.Farthest: float na = targetA.targetable.GetSqrDistToPos(this.xform.position); float nb = targetB.targetable.GetSqrDistToPos(this.xform.position); return nb.CompareTo(na); case SORTING_STYLES.Nearest: float fa = targetA.targetable.GetSqrDistToPos(this.xform.position); float fb = targetB.targetable.GetSqrDistToPos(this.xform.position); return fa.CompareTo(fb); case SORTING_STYLES.FarthestFromDestination: return targetB.targetable.distToDest.CompareTo( targetA.targetable.distToDest); case SORTING_STYLES.NearestToDestination: return targetA.targetable.distToDest.CompareTo( targetB.targetable.distToDest); case SORTING_STYLES.LeastPowerful: return targetA.targetable.strength.CompareTo( targetB.targetable.strength); case SORTING_STYLES.MostPowerful: return targetB.targetable.strength.CompareTo( targetA.targetable.strength); case AreaTargetTracker.SORTING_STYLES.None: // Only in error throw new System.NotImplementedException("Unexpected option. " + "SORT_OPTIONS.NONE should bypass sorting altogether."); } // Anything unexpected throw new System.NotImplementedException( string.Format("Unexpected option '{0}'.", this.sortStyle)); } } #endregion Target Comparers for Perimter.Sort() } /// <summary> /// The minimum interface for TargetTrackers /// </summary> interface ITargetTracker { /// <summary> /// A list of sorted targets. The contents depend on numberOfTargets requested /// (-1 for all targets in the Area), and the sorting style userd. /// </summary> TargetList targets { get; set; } /// <summary> /// Set this to true to force the Area to sort and other refresh actions, if /// applicable. /// Setting this to false does nothing. /// </summary> /// <value> /// Always false because setting to true is handled immediatly. /// </value> bool dirty { get; set; } /// <summary> /// Not all TargetTrackers have Areas. This is implemented to make it easy and /// cheap test for. Otherwise casting tests would be needed. /// </summary> Area area { get; } /// <summary> /// Runs just before returning the targets list to allow for custom sorting. /// The delegate signature is: delegate(TargetList targets) /// See TargetTracker documentation for usage of the provided '...' /// </summary> /// <param name="del">An OnPostSortDelegate</param> void AddOnPostSortDelegate(OnPostSortDelegate del); /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnPostSortDelegate() /// </summary> /// <param name="del">An OnPostSortDelegate</param> void SetOnPostSortDelegate(OnPostSortDelegate del); /// <summary> /// Removes a OnPostSortDelegate /// See docs for AddOnPostSortDelegate() /// </summary> /// <param name="del">An OnPostSortDelegate</param> void RemoveOnPostSortDelegate(OnPostSortDelegate del); /// <summary> /// Add a new delegate to be triggered when a target is first found by a Area. /// Return true to have no effect on the TargetTracker functioning /// Return false to cause the TargetTracker to ignore the new target entirely. /// </summary> /// <param name="del"></param> void AddOnNewDetectedDelegate(OnNewDetectedDelegate del); /// <summary> /// This replaces all older delegates rather than adding a new one to the list. /// See docs for AddOnNewDetectedDelegate() /// </summary> /// <param name="del"></param> void SetOnNewDetectedDelegate(OnNewDetectedDelegate del); /// <summary> /// Removes a OnDetectedDelegate /// See docs for AddOnDetectedDelegate() /// </summary> /// <param name="del"></param> void RemoveOnNewDetectedDelegate(OnNewDetectedDelegate del); } }<file_sep>/* * Energy Bar Toolkit by Mad Pixel Machine * http://www.madpixelmachine.com */ using UnityEngine; using System.Collections; using System.Collections.Generic; using EnergyBarToolkit; [ExecuteInEditMode] public class BarOptionsGUI : MonoBehaviour { // =========================================================== // Constants // =========================================================== public const string FormatHelp = @"Format Help: {cur} - current int value {min} - minimal value {max} - maximum value {cur%} - current % value (0 - 100) {cur2%} - current % value with precision of tens (0.0 - 100.0) Examples: {cur}/{max} - 27/100 {cur%} % - 27 %"; // =========================================================== // Fields // =========================================================== public GameObject bar; public Rect position = new Rect(10, 100, 200, 100); public GUISkin skin; public bool allowBurn = true; public bool allowChangeBarColor = false; public bool changeBurnCollorAuto = true; public bool allowChangeDirection = false; private EnergyBar energyBar; private EnergyBarRenderer energyBarRenderer; // =========================================================== // Constructors (Including Static Constructors) // =========================================================== // =========================================================== // Getters / Setters // =========================================================== // =========================================================== // Methods // =========================================================== void Start() { } void OnGUI() { GUI.skin = skin; energyBar = bar.GetComponent<EnergyBar>(); energyBarRenderer = bar.GetComponent<EnergyBarRenderer>(); GUILayout.BeginArea(position); GUILayout.Label("Change Value:"); energyBar.valueCurrent = (int) GUILayout.HorizontalSlider(energyBar.valueCurrent, energyBar.valueMin, energyBar.valueMax); if (energyBarRenderer != null) { if (allowBurn) { energyBarRenderer.effectBurn = GUILayout.Toggle(energyBarRenderer.effectBurn, "Burn Effect (on subtraction)", skin.toggle); } energyBarRenderer.effectSmoothChange = GUILayout.Toggle(energyBarRenderer.effectSmoothChange, "Smooth Change", skin.toggle); energyBarRenderer.effectBlink = GUILayout.Toggle(energyBarRenderer.effectBlink, "Blink when energy is low (NEW!)", skin.toggle); if (allowChangeBarColor) { GUILayout.Space(10); GUILayout.BeginHorizontal(); if (GUILayout.Toggle(energyBarRenderer.textureBarColorType == EnergyBarRenderer.ColorType.Solid, "Solid Color")) { energyBarRenderer.textureBarColorType = EnergyBarRenderer.ColorType.Solid; } if (GUILayout.Toggle(energyBarRenderer.textureBarColorType == EnergyBarRenderer.ColorType.Gradient, "Gradient (NEW!)")) { energyBarRenderer.textureBarColorType = EnergyBarRenderer.ColorType.Gradient; } GUILayout.EndHorizontal(); GUI.enabled = energyBarRenderer.textureBarColorType == EnergyBarRenderer.ColorType.Solid; GUILayout.BeginHorizontal(); GUILayout.Label("R:"); energyBarRenderer.textureBarColor.r = GUILayout.HorizontalSlider(energyBarRenderer.textureBarColor.r, 0, 1); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("G:"); energyBarRenderer.textureBarColor.g = GUILayout.HorizontalSlider(energyBarRenderer.textureBarColor.g, 0, 1); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("B:"); energyBarRenderer.textureBarColor.b = GUILayout.HorizontalSlider(energyBarRenderer.textureBarColor.b, 0, 1); GUILayout.EndHorizontal(); GUI.enabled = false; if (changeBurnCollorAuto) { energyBarRenderer.effectBurnTextureBarColor = energyBarRenderer.textureBarColor; energyBarRenderer.effectBurnTextureBarColor.a = 0.5f; } } if (allowChangeDirection) { GUILayout.Space(10); GUILayout.Label("Direction: "); GUILayout.BeginHorizontal(); if (GUILayout.Toggle(energyBarRenderer.growDirection == EnergyBarRenderer.GrowDirection.LeftToRight, "L -> R")) { energyBarRenderer.growDirection = EnergyBarRenderer.GrowDirection.LeftToRight; } if (GUILayout.Toggle(energyBarRenderer.growDirection == EnergyBarRenderer.GrowDirection.TopToBottom, "T -> B")) { energyBarRenderer.growDirection = EnergyBarRenderer.GrowDirection.TopToBottom; } if (GUILayout.Toggle(energyBarRenderer.growDirection == EnergyBarRenderer.GrowDirection.RightToLeft, "R -> L")) { energyBarRenderer.growDirection = EnergyBarRenderer.GrowDirection.RightToLeft; } if (GUILayout.Toggle(energyBarRenderer.growDirection == EnergyBarRenderer.GrowDirection.BottomToTop, "B -> T")) { energyBarRenderer.growDirection = EnergyBarRenderer.GrowDirection.BottomToTop; } GUILayout.EndHorizontal(); } if (energyBarRenderer.labelEnabled) { GUILayout.Space(20); GUILayout.Label("Label Format:"); energyBarRenderer.labelFormat = GUILayout.TextField(energyBarRenderer.labelFormat); GUILayout.Label(FormatHelp); } } GUILayout.EndArea(); GUI.skin = null; } // =========================================================== // Static Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }<file_sep>/* * Energy Bar Toolkit by Mad Pixel Machine * http://www.madpixelmachine.com */ using UnityEngine; using System.Collections; using System.Collections.Generic; [ExecuteInEditMode] public class BarPresentation : MonoBehaviour { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int currentSlideNum = 1; public GameObject slidesBar; public Slide[] slides; private Slide currentSlide; private EnergyBar bar; // =========================================================== // Constructors (Including Static Constructors) // =========================================================== // =========================================================== // Getters / Setters // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== void Start() { bar = slidesBar.GetComponent<EnergyBar>(); bar.valueMax = slides.Length; HideAll(); } void Update() { if (slides.Length == 0) { return; } else if (currentSlide == null) { ChangeSlide(currentSlideNum); } currentSlideNum = Mathf.Clamp(currentSlideNum, 1, slides.Length); bar.valueCurrent = currentSlideNum; } void OnGUI() { if (slides.Length == 0) { return; } // // draw default controls // if (currentSlideNum != 1) { if (GUI.Button(new Rect(140, 15, 80, 30), "<< Prev")) { PreviousSlide(); } } if (currentSlideNum != slides.Length) { if (GUI.Button(new Rect(580, 15, 80, 30), "Next >>")) { NextSlide(); } } if (currentSlideNum > slides.Length) { return; } } // =========================================================== // Methods // =========================================================== private void HideAll() { foreach (Slide slide in slides) { slide.Hide(); } } private void NextSlide() { ChangeSlide(currentSlideNum + 1); } private void PreviousSlide() { ChangeSlide(currentSlideNum - 1); } private void ChangeSlide(int num) { if (currentSlide != null) { currentSlide.Hide(); } currentSlide = slides[num - 1]; currentSlide.Show(); currentSlideNum = num; } // =========================================================== // Static Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== [System.Serializable] public class Slide { public GameObject gameObject; public void Show() { gameObject.SetActive(true); } public void Hide() { gameObject.SetActive(false); } } }<file_sep>/// <Licensing> /// © 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEditor; using UnityEngine; using System.Collections; namespace PathologicalGames { [CustomEditor(typeof(SmoothLookAtConstraint)), CanEditMultipleObjects] public class SmoothLookAtConstraintInspector : LookAtConstraintInspector { protected SerializedProperty interpolation; protected SerializedProperty output; protected SerializedProperty speed; protected override void OnEnable() { base.OnEnable(); this.interpolation = this.serializedObject.FindProperty("interpolation"); this.output = this.serializedObject.FindProperty("output"); this.speed = this.serializedObject.FindProperty("speed"); } protected override void OnInspectorGUIUpdate() { base.OnInspectorGUIUpdate(); GUIContent content; content = new GUIContent ( "Interpolation", "The rotation interpolation solution to use." ); EditorGUILayout.PropertyField(this.interpolation, content); content = new GUIContent ( "Speed", "How fast the constrant can rotate. The result depends on the interpolation chosen." ); EditorGUILayout.PropertyField(this.speed, content); content = new GUIContent ( "Output", "What axes and space to output the result to." ); EditorGUILayout.PropertyField(this.output, content); } } }<file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; namespace PathologicalGames { /// <summary> /// This is the base class for all look-at based constraints including billboarding. /// </summary> [AddComponentMenu("")] // Hides from Unity4 Inspector menu public class LookAtBaseClass : ConstraintBaseClass { /// <summary> /// The axis used to point at the target. /// This is public for user input only, should not be used by derrived classes /// </summary> public Vector3 pointAxis = -Vector3.back; /// <summary> /// The axis to point up in world space. /// This is public for user input only, should not be used by derrived classes /// </summary> public Vector3 upAxis = Vector3.up; /// <summary> /// Runs when the noTarget mode is set to ReturnToDefault /// </summary> protected override void NoTargetDefault() { this.transform.rotation = Quaternion.identity; } protected override Transform internalTarget { get { // Note: This backing field is in the base class if (this._internalTarget != null) return this._internalTarget; Transform target = base.internalTarget; // Will init internalTarget GO // Set the internal target to 1 unit away in the direction of the pointAxis // this.target will be the internalTarget due to SetByScript target.position = (this.transform.rotation * this.pointAxis) + this.transform.position; return this._internalTarget; } } /// <summary> /// Processes the user's 'pointAxis' and 'upAxis' to look at the target. /// </summary> /// <param name="lookVect">The direction in which to look</param> /// <param name="upVect"> /// The secondary axis will point along a plane in this direction /// </param> protected Quaternion GetUserLookRotation(Quaternion lookRot) { // Get the look at rotation and a rotation representing the user input var userAxisRot = Quaternion.LookRotation(this.pointAxis, this.upAxis); // offset the look-at by the user input to get the final result return lookRot * Quaternion.Inverse(userAxisRot); } } }<file_sep>using UnityEngine; using System.Collections; public class Skill5PlazmaMaker : MonoBehaviour, ISkill { public status skillset; public float rotSpeed, waitTime, standTime; public GameObject machine; GameObject tmp; PlazmaMachine ltmp; void Start() { //StartCoroutine("Delay"); //UseSkill(); } public void SetSkill(int hp, float length, float reload, float rotSpeed, float waitTime, float standTime) { skillset.damage = hp; skillset.distance = length; skillset.reload = reload; this.rotSpeed = rotSpeed; this.waitTime = waitTime; this.standTime = standTime; } public void UseSkill() { tmp = Instantiate(machine, transform.position, Quaternion.identity) as GameObject; ltmp = tmp.transform.GetChild(0).GetComponent<PlazmaMachine>(); ltmp.hp = skillset.damage; ltmp.length = skillset.distance; ltmp.rotSpeed = rotSpeed; ltmp.waitTime = waitTime; ltmp.standTime = standTime; } IEnumerator Delay() { while (true) { yield return new WaitForSeconds(skillset.reload); UseSkill(); } } } <file_sep>using UnityEngine; using System.Collections; namespace PathologicalGames { [RequireComponent(typeof(EventTrigger))] public class GrowWithShockwave : MonoBehaviour { public EventTrigger eventTrigger; void Update() { Vector3 scl = this.eventTrigger.range * 2.1f; // Let geo move ahead of real range scl.y *= 0.2f; // More cenematic hieght. this.transform.localScale = scl; // Blend the alpha channel of the color off as the range expands. Color col = this.GetComponent<Renderer>().material.GetColor("_TintColor"); col.a = Mathf.Lerp(0.7f, 0, this.eventTrigger.range.x / this.eventTrigger.endRange.x); this.GetComponent<Renderer>().material.SetColor("_TintColor", col); } } }<file_sep>using UnityEngine; using System.Collections; //오브젝트풀 사용을 위한 모듈 추가 using PathologicalGames; public class OPSpawnManager : MonoBehaviour { public Transform spawnPrefab; //스폰딜레이 sec public float delay = 1f; } <file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; namespace PathologicalGames { /// <summary> /// The base class for all constraints that use a target and mode /// </summary> [AddComponentMenu("Path-o-logical/UnityConstraints/Constraint - Look At")] public class LookAtConstraint : LookAtBaseClass { /// <summary> /// An optional target just for the upAxis. The upAxis may not point directly /// at this. See the online docs for more info /// </summary> public Transform upTarget; // Get the lookVector protected virtual Vector3 lookVect { get { return this.target.position - this.transform.position; } } // Get the upvector. Factors in any options. protected Vector3 upVect { get { Vector3 upVect; if (this.upTarget == null) upVect = Vector3.up; else upVect = this.upTarget.position - this.transform.position; return upVect; } } /// <summary> /// Runs each frame while the constraint is active /// </summary> protected override void OnConstraintUpdate() { // Note: Do not run base.OnConstraintUpdate. It is not implimented var lookRot = Quaternion.LookRotation(this.lookVect, this.upVect); this.transform.rotation = this.GetUserLookRotation(lookRot); } } }<file_sep>/// <Licensing> /// � 2011 (Copyright) Path-o-logical Games, LLC /// If purchased from the Unity Asset Store, the following license is superseded /// by the Asset Store license. /// Licensed under the Unity Asset Package Product License (the "License"); /// You may not use this file except in compliance with the License. /// You may obtain a copy of the License at: http://licensing.path-o-logical.com /// </Licensing> using UnityEngine; using System.Collections; namespace PathologicalGames { /// <summary> /// Billboarding is when an object is made to face a camera, so that no matter /// where it is on screen, it looks flat (not simply a "look-at" constraint, it /// keeps the transform looking parallel to the target - usually a camera). This /// is ideal for sprites, flat planes with textures that always face the camera. /// </summary> [AddComponentMenu("Path-o-logical/UnityConstraints/Constraint - Billboard")] public class BillboardConstraint : LookAtBaseClass { /// <summary> /// If false, the billboard will only rotate along the upAxis. /// </summary> public bool vertical = true; protected override void Awake() { base.Awake(); var cameras = FindObjectsOfType(typeof(Camera)) as Camera[]; // Allow for a default if no target is given // Default to the first ortho camera that is set to render this object // This is done in the inspector as well, but needs to be in both places // so any application is covered. foreach (Camera cam in cameras) { if ((cam.cullingMask & 1 << this.gameObject.layer) > 0) { this.target = cam.transform; break; } } } /// <summary> /// Runs each frame while the constraint is active /// </summary> protected override void OnConstraintUpdate() { // Note: Do not run base.OnConstraintUpdate. It is not implimented // This is based on the Unity wiki script which keeps this look-at // vector parrallel with the camera, rather than right at the center Vector3 lookPos = this.transform.position + this.target.rotation * Vector3.back; Vector3 upVect = Vector3.up; // If the billboarding will happen vertically as well, then the upvector needs // to be derrived from the target's up vector to remain parallel // If not billboarding vertically, then keep the defaul upvector and set the // lookPos to be level with this object so it doesn't rotate in x or z if (this.vertical) upVect = this.target.rotation * Vector3.up; else lookPos.y = this.transform.position.y; // Get the final direction to look for processing with user input axis settings Vector3 lookVect = lookPos - this.transform.position; var lookRot = Quaternion.LookRotation(lookVect, upVect); this.transform.rotation = this.GetUserLookRotation(lookRot); } } }<file_sep>using UnityEngine; using System.Collections; public class Skill3HungryAttacking : MonoBehaviour, ISkill { public status skillset; public float intervalTime, shotIntervalTime, bulletSpeed; public int shotCnt; public DirectionalShooter[] shots; void Start() { //StartCoroutine("Delay"); UseSkill(); } public void SetSkill(int damage, float reload, int bulletCnt, float bulletStandTime, float bulletSpeed, float skillIntervalTime, float shotIntervalTime) { skillset.damage = damage; skillset.distance = bulletStandTime; skillset.reload = reload; this.shotCnt = bulletCnt; this.intervalTime = skillIntervalTime; this.shotIntervalTime = shotIntervalTime; this.bulletSpeed = bulletSpeed; } public void UseSkill() { StartCoroutine("Shot"); } IEnumerator Shot() { for (int i = 0; i < shots.Length; i++) { shots[i].canShoot = true; shots[i].skill = true; shots[i].shotDelay = shotIntervalTime; shots[i].shotSpeed = bulletSpeed; shots[i].bulletStandTime = skillset.distance; shots[i].bulletDmg = skillset.damage; shots[i].bulletCnt = shotCnt; shots[i].gameObject.SetActive(true); yield return new WaitForSeconds(intervalTime); } } IEnumerator Delay() { while (true) { yield return new WaitForSeconds(skillset.reload); UseSkill(); } } }
010df730acb8732c5ea5bf4d135aef70b277fcc3
[ "C#" ]
132
C#
6HanJo/Client
dc6c76d90e5e0b187272e86317b00e34004ec9b4
f917bb340a1d96eafba4266c077869c187b4aae3
refs/heads/master
<repo_name>kiromic/DeepLearningCyTOF<file_sep>/aging-cytof/automated/plots.py import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [12,8] fig, ax = plt.subplots() ax.plot([1,2,3,4],[1,4,3,2]) plt.savefig('example.png')<file_sep>/aging-cytof/automated/run.py import subprocess def run(phenotype): args = ['python','train.py',phenotype,'2>&1'] print(args) proc = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) with open(f'stdout/{phenotype}.txt','wb') as wf: wf.write(proc.stdout) if __name__ == '__main__': from pathlib import Path from multiprocessing import Pool import matplotlib.pyplot as plt import pickle import numpy as np with open('pheno-cols.txt') as f: phenos = f.read().split('\n') pool = Pool(4) pool.map(run, phenos) pool.close() pool.terminate() results_dir = Path('result') results_dir.mkdir(exist_ok=True) results = {} for pheno in phenos: d = results_dir/pheno result_pkl = d/'results.pkl' if not result_pkl.exists(): continue with open(d/'results.pkl','rb') as f: results[pheno] = pickle.load(f) phenos = sorted(results.keys()) # Train history fig, axes = plt.subplots(5,8, figsize=(30,20)) flaxes = [axis for _ in axes for axis in _] for i, pheno in enumerate(phenos): ax = flaxes[i] train_hist = results[pheno]['history']['mean_absolute_error'] valid_hist = results[pheno]['history']['val_mean_absolute_error'] ax.plot(train_hist) ax.plot(valid_hist) ax.set_title(pheno) fig.supylabel('Loss') fig.supxlabel('Epoch') plt.tight_layout() fig.savefig('training-history.png') # Pred vs True fig, axes = plt.subplots(5,8, figsize=(30,20)) flaxes = [axis for _ in axes for axis in _] for i, pheno in enumerate(phenos): ax = flaxes[i] vals_true = results[pheno]['y_valid'] vals_pred = results[pheno]['y_scores'] ax.plot(vals_true, vals_pred, 'b.') limits = (min(min(vals_true), min(vals_pred)), max(max(vals_true), max(vals_pred))) limits = (limits[0] - 0.1*(limits[1] - limits[0]), limits[1] + 0.1*(limits[1] - limits[0])) ax.set_xlim(limits) ax.set_ylim(limits) ax.set_title(pheno) ax.plot(limits,limits,'--k') coef = np.polyfit(vals_true, vals_pred, 1) poly1d_fn = np.poly1d(coef) ax.plot(limits, poly1d_fn(limits), '--b') fig.supylabel('True Value') fig.supxlabel('Predicted Value') plt.tight_layout() fig.savefig('pred-vs-true.png')<file_sep>/aging-cytof/automated/train.py import tensorflow as tf from tensorflow.keras.layers import Dense, Flatten, BatchNormalization, Activation, Conv2D, AveragePooling2D, Input, Softmax from tensorflow.keras.models import load_model, Model, Sequential from tensorflow.keras.optimizers import Adam from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping from tensorflow.keras.losses import SparseCategoricalCrossentropy from tensorflow.keras import backend as K from tensorflow.keras.utils import plot_model import pickle import pandas as pd import numpy as np from numpy.random import seed; seed(111) import random import matplotlib.pyplot as plt import seaborn as sns from tensorflow.random import set_seed; set_seed(111) from sklearn.metrics import roc_curve, auc from sklearn.preprocessing import normalize from six import StringIO from sklearn.tree import export_graphviz, DecisionTreeRegressor from sklearn.model_selection import train_test_split from scipy.stats import ttest_ind from IPython.display import Image import pydotplus import time from pathlib import Path import sys import math from sklearn.preprocessing import StandardScaler, MinMaxScaler # Larger matplotlib plots plt.rcParams['figure.figsize'] = [12,8] # Use only needed GPU mem gpus = tf.config.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(gpus[0], True) # Load training data aging_dir = Path('/home/ubuntu/a/aging') with open(aging_dir/'aging-cytof-data.obj', 'rb') as f: allData = pickle.load(f) samples = allData["samples"] cyto_data = allData['expr_list'] cyto_data = cyto_data[ :, :int(10e3)] markers = allData['marker_names'] # Check for selected phenotyp phenotype = sys.argv[1] if phenotype not in samples.columns: print('phenotype not found') exit(1) print(samples[phenotype].describe()) # Create output dirs result_dir = Path('result') if not result_dir.exists(): result_dir.mkdir() out_dir = result_dir/phenotype if not out_dir.exists(): out_dir.mkdir() # Create train and validation data sets x = [] y = [] for i, row in samples.iterrows(): if math.isnan(row[phenotype]): continue phenval = row[phenotype] x.append(cyto_data[i]) y.append(phenval) x = np.asarray(x) y_raw = np.asarray(y) x_train, x_valid, y_train, y_valid = train_test_split(x, y_raw, train_size=0.9) y_train = y_train.reshape(-1,1) y_valid = y_valid.reshape(-1,1) scaler = MinMaxScaler() scaler.fit(y_train) y_train = scaler.transform(y_train).reshape(1,-1)[0] y_valid = scaler.transform(y_valid).reshape(1,-1)[0] print(x_train.shape, x_valid.shape) print(f""" Data dimensionality train = {x_train.shape} valid = {x_valid.shape} """.strip()) # Create model model = Sequential([ Input(shape=x[0].shape), Conv2D(3, kernel_size = (1, x.shape[2]), activation=None), BatchNormalization(), Activation('relu'), Conv2D(6, kernel_size = (1,1), activation=None), BatchNormalization(), Activation('relu'), AveragePooling2D(pool_size = (x.shape[1], 1)), Flatten(), Dense(3, activation=None), BatchNormalization(), Activation('relu'), Dense(1, activation=None), ]) model.compile( loss='mean_absolute_error', optimizer='adam', metrics=['mean_absolute_error'] ) print(model.summary()) # Train model model_store = out_dir/'best_model.hdf5' checkpointer = ModelCheckpoint( filepath=model_store, monitor='val_loss', verbose=0, save_best_only=True ) # Early stopping is assuming data normalized to [0-1] range early_stopper = tf.keras.callbacks.EarlyStopping( monitor='val_loss', patience=50, min_delta = 0.01, ) st = time.time() model.fit([x_train], y_train, batch_size=60, epochs=500, verbose=1, callbacks=[checkpointer, early_stopper], validation_data=([x_valid], y_valid)) rt = time.time()-st print(f'Runtime: {rt}') # Plot model training history history = model.history.history plt.plot(pd.Series(history['mean_absolute_error'])) plt.plot(pd.Series(history['val_mean_absolute_error'])) plt.title('model train vs validation loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'validation'], loc='upper right') plt.savefig(out_dir/'train-history.png') # Get final validation predictions y_scores = model.predict([x_valid]) y_scores = y_scores.reshape(y_scores.shape[0]) vals_true = pd.Series(scaler.inverse_transform(y_valid.reshape(-1,1)).reshape(1,-1)[0]) vals_pred = pd.Series(scaler.inverse_transform(y_scores.reshape(-1,1)).reshape(1,-1)[0]) errors = vals_pred - vals_true errors.describe() # Plot distribution of errors fig, ax = plt.subplots() ax.hist(errors, bins=np.linspace(min(errors),max(errors),num=20)) ax.set_title('Error Distribution') ax.set_xlabel('Predicted value - True value') plt.savefig(out_dir/'errors-dist.png') # Plot True vs Predicted values plt.plot(vals_true, vals_pred,'b.') plt.axis('square') limits = (min(min(vals_true), min(vals_pred)), max(max(vals_true), max(vals_pred))) limits = (limits[0] - 0.1*(limits[1] - limits[0]), limits[1] + 0.1*(limits[1] - limits[0])) plt.xlim(limits) plt.ylim(limits) plt.xlabel('True value') plt.ylabel('Predicted value') plt.title('Prediction vs True') plt.plot(limits,limits,'--k') coef = np.polyfit(vals_true, vals_pred, 1) poly1d_fn = np.poly1d(coef) plt.plot(limits, poly1d_fn(limits), '--b') plt.savefig(out_dir/'pred-vs-true.png') # Export out = { 'history': history, 'y_valid': y_valid, 'y_scores': y_scores, 'vals_pred': vals_pred, 'vals_true': vals_true, 'scaler': scaler, } with open(out_dir/'results.pkl','wb') as wf: pickle.dump(out, wf)<file_sep>/aging-cytof/automated/mpl-txt.py import matplotlib.pyplot as plt fig, ax = plt.subplots() text = ''' This is a test of happy and sad music When you hear the [happy] music play your [rhythm sticks] or [clap] JUST AS YOU DID BEFORE ''' ax.text(1,0, text) plt.axis('off') plt.savefig('text.png') fig, ax = plt.subplots() data = [ ['first','kyle'], ['last','moad'] ] ax.table(cellText=data) plt.axis('off') plt.savefig('table.png')
3b738d1abb221d53329482aba8f8b06df12e4ea7
[ "Python" ]
4
Python
kiromic/DeepLearningCyTOF
521f29bfc2fa7a65c2c27de0f82e938abd8c452e
b64e01e8987452ca880d3fb82291dc882355e7cd
refs/heads/master
<file_sep>let peopleSalary = [ { id: "1001", fristname: "Luke", lastname: "Skywalker", company: "Walt Disney", salary: "40000" }, { id: "1002", fristname: "Tony", lastname: "Stark", company: "Marvel", salary: "1000000" }, { id: "1003", fristname: "Somchai", lastname: "Jaidee ", company: "Love2work", salary: "20000" }, { id: "1004", fristname: "<NAME>", lastname: "Luffee", company: "One Piece", salary: "9000000" } ] // console.log("peopleSalary", peopleSalary) let new_peopleSalary = []; for (const item in peopleSalary) { let new_json = { id: peopleSalary[item].id, fristname: peopleSalary[item].fristname, lastname: peopleSalary[item].lastname, salary: peopleSalary[item].salary } new_peopleSalary.push(new_json) } console.log("new_peopleSalary", new_peopleSalary)
3a0f20ca125103763d2f82bafc2e929fe93527b8
[ "JavaScript" ]
1
JavaScript
micotosung/Front-end-Bootcamp
5045fc25f8ff1df11678d0d6f6222f905de957eb
bdaba5063dc6ed14524b47d587d5e0645df4803f
refs/heads/master
<file_sep>#!/bin/bash .bundle/binstubs/rspec-puppet-init <file_sep>CODE_DIR=/Users/dennisleon/code alias java_ls='/usr/libexec/java_home -V 2>&1 | grep -E "\d.\d.\d[,_]" | cut -d , -f 1 | colrm 1 4 | grep -v Home' function java_use() { export JAVA_HOME=$(/usr/libexec/java_home -v $1) export PATH=$JAVA_HOME/bin:$PATH java -version } p() { local project_looking_for project_found project_looking_for=$1 project_found=$(find $CODE_DIR -name "$project_looking_for" -type d -maxdepth 1) cd $project_found } _p() { _files -W $CODE_DIR -/; } compdef _p p idea () { local project_looking_for project_found project_looking_for=$1 idea_version=15 if [[ -e `pwd`/$project_looking_for ]] then open -a IntelliJ\ IDEA\ $idea_version -e `pwd`/$project_looking_for fi if [[ -e `pwd`/pom.xml && $project_looking_for = "pom.xml" ]] then open -a IntelliJ\ IDEA\ $idea_version -e `pwd`/pom.xml fi project_found=$(find $CODE_DIR -name "$project_looking_for" -type d -maxdepth 1) if [ -e $project_found/pom.xml ] then open -a IntelliJ\ IDEA\ $idea_version -e $project_found/pom.xml else idea_proj_file="`basename $project_found`.ipr" open -a IntelliJ\ IDEA\ $idea_version -e $project_found/$idea_proj_file fi } _idea() { _files -W $CODE_DIR -/; } compdef _idea idea <file_sep>#!/bin/bash set -e set -x set -u SIZE_IN_MB=$1 old_vmdk=$(vboxmanage showvminfo boot2docker-vm --details | grep -E "vmdk|vdi" | grep -oE "/.*(vmdk|vdi)") new_vdi_image=$(dirname "$old_vmdk") new_vdi=$new_vdi_image/boot2dockernew.vdi vboxmanage clonehd "$old_vmdk" "$new_vdi" --format VDI --variant Standard vboxmanage modifyhd "$new_vdi" --resize $SIZE_IN_MB VBoxManage storageattach boot2docker-vm \ --storagectl "SATA" \ --device 0 \ --port 0 \ --type dvddrive \ --medium "/Users/dennis.leon/.boot2docker/boot2docker.iso" VBoxManage storageattach boot2docker-vm \ --storagectl "SATA" \ --device 0 \ --port 1 \ --type hdd \ --medium "$new_vdi" curl -L -v -ogparted.iso http://downloads.sourceforge.net/gparted/gparted-live-0.22.0-1-i586.iso VBoxManage storagectl boot2docker-vm --name IDE --add ide --bootable on sleep 2 VBoxManage storageattach "boot2docker-vm" --storagectl IDE --port 0 --device 0 --type dvddrive --medium "gparted.iso" echo 'resize using gparted: follow https://docs.docker.com/articles/b2d_volume_resize/' echo 'when done remove gparted dvd by running: VBoxManage storagectl boot2docker-vm --name IDE --remove' <file_sep>#!/bin/bash "/Applications/VMware Fusion.app/Contents/Library/vmrun" -T fusion list <file_sep>require 'spec_helper' # Rename this file to classname_spec.rb # Check other boxen modules for examples # or read http://rspec-puppet.com/tutorial/ describe 'commonscripts' do let(:params) { {:username => 'bob'} } it do should contain_class('commonscripts') #should contain_anchor('Hello_World') should contain_file('/Users/bob/config') end end <file_sep>#!/bin/bash alias grep='grep --color=auto' alias l='ls -ltra' alias mci='mvn clean install' alias mcis='mvn clean install -DskipTests' alias mjr='mvn jetty:run' alias scan_for_wireless_ssids='/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport scan' <file_sep>#!/bin/bash if [[ $# != 1 ]]; then echo "usage: [vmx path]" exit 1 fi "/Applications/VMware Fusion.app/Contents/Library/vmrun" -T fusion start "$@" nogui "/Applications/VMware Fusion.app/Contents/Library/vmrun" -T fusion list nmap -v -sn 172.16.110.1/24
2a0ec690a8ed58ba687e01ee4ccb633add3c26a8
[ "Ruby", "Shell" ]
7
Shell
DennisDenuto/puppet-commonscripts
800759a9a6a12ff20a1f2d94224bceacd8c9b741
42556d11d738c8396ff02885d2cb4e954e0c8786
refs/heads/master
<repo_name>MonsterGfx/pi-music<file_sep>/libraries/Image.php <?php class Image { /** * Convert an image file to a data URL * * @param string $path * The path to the file * * @return string * The formatted data URL string */ public static function toDataUrl($path, $mime='image/jpg') { $result = null; // load the image data if(file_exists($path)) { $img = file_get_contents($path); if($img) { $result = base64_encode($img); $result = "data:{$mime};base64,{$result}"; } } return $result; } }<file_sep>/migrations/MigrationBase.php <?php /** * The base class for Migrations */ abstract class MigrationBase { /** * The up method */ abstract public static function up(); /** * The down method */ abstract public static function down(); } <file_sep>/routes/playlist.php <?php // Routes for playlist requests // playlist - list of playlists // page head='Playlist', list head=null // // playlist/1/song - list of songs for playlist=1 // page head=playlist.name, list head=null // // playlist/1/song/2 - load all songs for playlist=1, start playing song=2, go to nowplaying // playlist - list of playlists // $klein->respond('GET', '/playlist', function($request, $response){ // get the list of playlists $list = Playlist::getList(); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k){ $v = array( 'name' => $v, 'url' => '/playlist/'.Music::encode($v).'/song', ); }); return ListPage::render('Playlists', null, false, false, $list); }); // playlist/1/song - list of songs for playlist=1 // $klein->respond('GET', '/playlist/[:playlist]/song', function($request, $response){ // get the params $playlist = Music::decode($request->param('playlist')); // get the list of songs $list = Playlist::getSongs($playlist); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k) use ($playlist) { $v = array( 'name' => $v['Title'], 'url' => '/playlist/'.Music::encode($playlist).'/song/'.Music::encode($v['file']), ); }); // build the "previous" link data $previous = array( 'path' => '/playlist', 'text' => 'Playlists', ); // build the shuffle link $shuffle = '/playlist/'.Music::encode($playlist).'/song/shuffle'; return ListPage::render($playlist, $previous, $shuffle, false, $list); }); // playlist/1/song/2 - load all songs for playlist=1, start playing song=2, go to nowplaying // $klein->respond('GET', '/playlist/[:playlist]/song/[:song]', function($request, $response){ // get the params $playlist = Music::decode($request->param('playlist')); $song = $request->param('song'); $song = $song=='shuffle' ? 'shuffle' : Music::decode($song); // clear the playlist Music::send('clear'); // get the list of songs $songs = Playlist::getSongs($playlist); // load the playlist with the requested songs (and figure out the current // song position) $pos = 0; for($i=0; $i<count($songs); $i++) { Music::send('add', $songs[$i]['file']); if($songs[$i]['file']==$song) $pos = $i; } // turn off "shuffle" Music::shuffle(false); // is the current song "shuffle" if($song=='shuffle') { // choose a random song $pos = rand(0,count($songs)-1); // turn on shuffle Music::shuffle(true); } // start playing the selected song Music::send('play', $pos); // redirect to "now playing" header('Location: /'); die; }); <file_sep>/libraries/Scan.php <?php class Scan { /** * Extract the image data (if any) from a file * * @param string $filename * * @return Image|null */ private static function getImage($filename) { // check the file if(!file_exists($filename)) return null; // scan the file $getID3 = new getID3; // Analyze file and store returned data in $ThisFileInfo $file_info = $getID3->analyze($filename); // try to extract the album artwork (if any) // find the artwork in the $file_info structure $artwork = null; // try the different places in which I've found artwork if(isset($file_info['comments']['picture'][0]['data'])) { $artwork = $file_info['comments']['picture'][0]['data']; } else if(isset($file_info['id3v2']['APIC'][0]['data'])) { $artwork = $file_info['id3v2']['APIC'][0]['data']; } // did we find some artwork? if(!$artwork) return null; // create the image object and return it return imagecreatefromstring($artwork); } /** * Resize an image * * @param Image $image * @param int $resolution * @return Image */ private static function resizeImage($image, $resolution) { // create a resized image $copy = imagecreatetruecolor($resolution, $resolution); // copy the image imagecopyresampled($copy, $image, 0, 0, 0, 0, $resolution, $resolution, imagesx($image), imagesy($image)); // return the resulting copy return $copy; } /** * Scan the albums & artists in the music database and create artwork for * them. */ public static function scanAll() { // get some config items $artwork_folder = Config::get('app.music-artwork-path'); $artwork_sizes = array(180,320); // get the music directory path $music_directory = Config::get('app.music-path'); // get the list of artists $artists = Artist::getList(); // step through the artists foreach($artists as $artist) { // get the list of albums for the current artist $albums = Artist::getAlbums($artist); // step through the albums foreach($albums as $album) { // create a file name for the artist/album combination $image_file = md5($artist.$album['album']); // does the file already exist? if(!file_exists($artwork_folder.$image_file.'.jpg')) { // No! we need to extract the artwork from a song file for // this artist/album // get the list of songs $songs = Album::getSongs($artist, $album['album']); // step through the songs & attempt to extract the image //data foreach($songs as $song) { // get the music file name $music_file = $music_directory.$song['file']; // make sure we have a music file to check if(file_exists($music_file)) { // get the image data (if we can) $image = static::getImage($music_file); // make sure we got an image if($image) { // save the "untouched" image file // save the original as a JPEG imagejpeg($image, Config::get('app.music-artwork-path').$image_file.".jpg", 100); // loop through the required sizes foreach($artwork_sizes as $s) { // resize to the appropriate size $i = static::resizeImage($image, $s); // and save if($i) imagejpeg($i, Config::get('app.music-artwork-path').$image_file."-{$s}.jpg", 100); } // END loop through the required sizes // all done with this one! // break out of the song loop (since we // don't need to scan any more songs from // this album) break; } // END make sure we got an image } // END make sure we have a music file to check } // END step through the songs } // END does the file already exist? } // END step through the albums } // END step through the artists } }<file_sep>/config/cli.php <?php return array( /** * The commands defined for the command line tool. * * These commands are defined simply as * 'command' => 'method' * where 'command' is the command entered on the command line and 'method' * is the method to call. */ 'commands' => array( 'migrate:up' => 'Migrate::up', 'migrate:down' => 'Migrate::down', 'music:scan' => 'Scan::scanAll', ), );<file_sep>/migrations/Migration_001_add_initial_scheme.php <?php class Migration_001_add_initial_scheme extends MigrationBase { /** * Migrate the database up to this version */ public static function up() { // create the artists table $query = <<<QUERY CREATE TABLE artists ( id INTEGER PRIMARY KEY ASC, name TEXT ); QUERY; Database::execute($query); Database::execute("CREATE INDEX idx_artists_name ON artists( name );"); // create the albums table $query = <<<QUERY CREATE TABLE albums ( id INTEGER PRIMARY KEY ASC, name TEXT, artists_id INTEGER, year INTEGER ); QUERY; Database::execute($query); Database::execute("CREATE INDEX idx_albums_name ON albums( name );"); Database::execute("CREATE INDEX idx_albums_artist_id ON albums( artists_id );"); // create the genres table $query = <<<QUERY CREATE TABLE genres ( id INTEGER PRIMARY KEY ASC, name TEXT ); QUERY; Database::execute($query); Database::execute("CREATE INDEX idx_genres_name ON genres( name );"); // create the songs table $query = <<<QUERY CREATE TABLE songs ( id INTEGER PRIMARY KEY ASC, filenamepath TEXT, filesize INTEGER, fileformat TEXT, dataformat TEXT, codec TEXT, sample_rate REAL, channels INTEGER, bits_per_sample INTEGER, lossless TEXT, channelmode TEXT, bitrate REAL, playtime_seconds REAL, name TEXT, artists_id INTEGER, album_artist TEXT, albums_id INTEGER, genres_id INTEGER, track_number TEXT, disc_number TEXT, compilation TEXT, bpm TEXT, rating TEXT, created_at INTEGER, updated_at INTEGER ); QUERY; // execute the query Database::execute($query); // create some indices $indexes = array( // a unique index on the filenamepath column "CREATE UNIQUE INDEX idx_songs_filenamepath ON songs ( filenamepath );", // indices on important values "CREATE INDEX idx_songs_name ON songs ( name );", "CREATE INDEX idx_songs_artists_id ON songs ( artists_id );", "CREATE INDEX idx_songs_album_artist ON songs ( album_artist );", "CREATE INDEX idx_songs_albums_id ON songs ( albums_id );", "CREATE INDEX idx_songs_genres_id ON songs ( genres_id );", ); foreach($indexes as $i) Database::execute($i); } /** * Revert the database to the previous version by reversing the effects of * the up method. */ public static function down() { // drop the table Database::execute("DROP TABLE songs;"); } }<file_sep>/routes/song.php <?php // Routes for song requests // song - list of all songs // page head='Songs', list head=null // // song/1 - load ALL songs, play song=1, go to nowplaying // song - list of all songs // $klein->respond('GET', '/song', function($request, $response){ // get the list of songs $list = Song::getList(); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k){ $v = array( 'name' => $v['Title'], 'url' => '/song/'.Music::encode($v['file']), ); }); $list = array_filter($list, function($v){ return $v['name'] ? true : false; }); usort($list, function($a, $b){ if(array_key_exists('name', $a) && array_key_exists('name', $b)) { return $a['name']<$b['name'] ? -1 : 1; } return 0; }); // build the shuffle link $shuffle = '/song/shuffle'; return ListPage::render('Songs', null, $shuffle, false, $list); }); // song/1 - load ALL songs, play song=1, go to nowplaying // $klein->respond('GET', '/song/[:song]', function($request, $response){ // get parameter $song = $request->param('song'); $song = $song=='shuffle' ? 'shuffle' : Music::decode($song); // clear the playlist Music::send('clear'); // get the list of songs $songs = Song::getList(); // load the playlist with the requested songs (and figure out the current // song position) $pos = 0; for($i=0; $i<count($songs); $i++) { Music::send('add', $songs[$i]['file']); if($songs[$i]['file']==$song) $pos = $i; } // turn off "shuffle" Music::shuffle(false); // is the current song "shuffle" if($song=='shuffle') { // choose a random song $pos = rand(0,count($songs)-1); // turn on shuffle Music::shuffle(true); } // start playing the selected song Music::send('play', $pos); // redirect to "now playing" header('Location: /'); die; }); <file_sep>/public/assets/js/msx.js /** * Javascript code for the application */ (function($){ // call the following as soon as the page is initialized $(document).on('pageinit', function(){ // bind events for the prev/play/next buttons $('a.playback-control').on('vclick', function(e){ // stop event propagation e.stopPropagation(); // handle the event clickControlButton(e.currentTarget.id); }); // bind events for the volume slider $('input#volume-slider').on('slidestop', function(){ console.log('vol = '+$('input#volume-slider').val()); $.get('/action-volume/'+$('input#volume-slider').val() ); }); // start page refresh event if we're on the "now playing" page if($('a.playback-control').length) refreshPage(); }); function clickControlButton(action) { // figure out what action it is if(action=='prev') { // submit request for "previous" action $.get('/action-prev'); } else if(action=='next') { // submit request for "next" action $.get('/action-next'); } else if(action=="play") { // submit request for "play" action $.get('/action-toggle-play', { }, function(data){ // update the play button toggle (with my custom icons) if(data=='play') $('a#play span.ui-icon').removeClass('ui-icon-msx-play').addClass('ui-icon-msx-pause'); else $('a#play span.ui-icon').removeClass('ui-icon-msx-pause').addClass('ui-icon-msx-play'); }); } else { // unrecognized action. Just bail out return; } } function refreshPage() { // refresh the information on the page // submit an AJAX request for update info $.get('/now-playing-update', { }, function(data){ // parse the result data = $.parseJSON(data); // insert info into the DOM $('#artist-name').text(data['artist']); $('#title-name').text(data['title']); $('#album-name').text(data['album']); // update the artwork $('#artwork').attr('src', data['artwork']); // update the volume slider $('input#volume-slider').val(data['volume']); $('input#volume-slider').slider('refresh'); // update the play state if(data['state']=='play') $('a#play span.ui-icon').removeClass('ui-icon-msx-play').addClass('ui-icon-msx-pause'); else $('a#play span.ui-icon').removeClass('ui-icon-msx-pause').addClass('ui-icon-msx-play'); // schedule another refresh if we're on the "now playing" page if($('a.playback-control').length) setTimeout(refreshPage, 200); }); } })(jQuery); <file_sep>/public/index.php <?php try { // include the autoload file, which will include any other required files // require_once __DIR__.'/../vendor/autoload.php'; // handle any "bootstrapping" - application-wide configuration tasks // require_once __DIR__.'/../bootstrap.php'; // start the route processor // require_once __DIR__.'/../routes.php'; } catch(Exception $e) { // oh no! echo "<h1>Unhandled Exception!</h1>"; echo "\n<!--\n\n"; print_r($e); echo "-->\n\n"; // dump the exception Kint::dump($e); // if database logging is enabled... if(Config::get('database.logging')) { // try to get the last query (or a "none" message if there isn't one) $last = ORM::get_last_query() ?: '-- none --'; // report the last query echo "<h2>Last Query</h2>"; echo "<pre>$last</pre>"; } } <file_sep>/views/NowPlayingPage.php <?php /** * The view class for the "now playing" page */ class NowPlayingPage extends View { /** * Render a list page * * @param Song $song * The song that is currently playing * * @return string * The HTML of the rendered page */ public static function render($song, $previous) { // instantiate the template engine $parser = new Rain\Tpl; // get the image data for the song $image_data = Song::getImageData($song['Artist'], $song['Album'], 320); // assign the values to the template parser $parser->assign(array( 'image' => $image_data, 'song' => $song, 'volume' => Music::getVolume(), 'previous' => $previous, )); // return the HTML return $parser->draw( "now-playing-page", true ); } }<file_sep>/routes/now-playing.php <?php // The "Now Playing" routes // the "now playing" page // $klein->respond('GET','/', function($request){ // @todo get the previous page (from the session?) $previous = array( 'path' => '/artist', 'text' => 'Artists', ); // return the message return NowPlayingPage::render(Music::getCurrentSong(), $previous); }); // the "skip to previous song" action // $klein->respond('GET','/action-prev', function(){ Music::previous(); }); // the "skip to next song" action // $klein->respond('GET','/action-next', function(){ Music::next(); }); // the "toggle play/pause" action // $klein->respond('GET','/action-toggle-play', function(){ return Music::togglePlay(); }); // the "adjust volume" action // $klein->respond('GET','/action-volume/[i:volume]', function($request){ Music::setVolume( $request->volume ); }); // the "now playing update" request // $klein->respond('GET','/now-playing-update', function(){ return json_encode(Music::updateNowPlaying()); }); <file_sep>/cli.php <?php // load the autoloader require_once 'vendor/autoload.php'; require_once 'bootstrap.php'; // get the arguments from the command line $args = $argv; // remove the first element (which is the script name) array_shift($args); // load the list of commands $commands = Config::get('cli.commands'); // build the request // here I'm "tricking" the routing system into routing a non-HTTP request $request = new \Klein\Request(array(), array(), array(), array('REQUEST_URI' => '/'.implode('/',$args))); // instantiate the Klein router $klein = new \Klein\Klein; // now add the commands to the router foreach($commands as $value=>$method) { // set up a responder // This responder will handle any URI of the form /$value/x/y/z/.... and // will pass any arguments to the specified method. $klein->respond('GET', "/{$value}/[*]?", function($request,$response) use ($method) { // get the arguments $args = array(); if($request->uri()) { // explode the arguments $args = explode('/',$request->uri()); // remove any empty values $args = array_values(array_filter($args)); // remove the first element (which is the command) array_shift($args); } // call the requested method with any arguments that were passed call_user_func_array($method, $args); }); } // add a "not found" response in case it's an invalid command $klein->respond('404', function($request){ // explode the arguments $args = explode('/',$request->uri()); // remove any empty values $args = array_values(array_filter($args)); // output the error message echo "\nCommand not found: {$args[0]}\n"; }); $klein->dispatch($request); <file_sep>/models/Album.php <?php class Album { /** * Get the list of all albums in the database * * @return array */ public static function getList() { // get the list $result = Music::send('listallinfo'); // extract the values $result = Music::buildSongList($result['values']); // build an array of artists & albums $list = array(); foreach($result as $s) { if(isset($s['Artist']) && isset($s['Album'])) { $l = array( 'artist' => $s['Artist'], 'album' => $s['Album'], ); if(!in_array($l,$list)) $list[] = $l; } } // and return the result return $list; } /** * Get the list of songs for the requested album * * @param string $artist * The encoded name of the artist * * @param string $album * The encoded name of the album * * @return array */ public static function getSongs($artist, $album) { // query the MPD database $result = Music::send('search', 'artist', $artist, 'album', $album); // get the list of songs return Music::buildSongList($result['values']); } }<file_sep>/libraries/Debug.php <?php class Debug { public static function pre($obj) { echo "<pre>".print_r($obj,true)."</pre>"; die; } }<file_sep>/libraries/QueryCache.php <?php class QueryCache { /** * Get a value from the query cache (or false if it doesn't exist) * * @param array $query * The query to retrieve * * @return mixed|bool * The values from the cache, or false if the file does not exist */ public static function get($args) { // return false if we don't have valid arguments if(!$args || !is_array($args)) return false; // attempt to load the query file $filename = Config::get('app.query-cache-path').implode('-',$args).'.qcache'; if(file_exists($filename)) return unserialize(file_get_contents($filename)); return false; } /** * Save the results of a query to the cache * * @param array $args * The query arguments * * @param mixed $value * The value to save */ public static function save($args, $value) { // only save if the "query-cache" flag is true if(!Config::get('app.query-caching')) return; // create the filename $filename = Config::get('app.query-cache-path').implode('-',$args).'.qcache'; // write the value file_put_contents($filename, serialize($value)); } public static function cleanup($dirty) { // replace the '/'' character in $d with a '-' $dirty = str_replace('/','-',$dirty); // get the cache folder $folder = Config::get('app.query-cache-path'); // build a list of files $files = scandir($folder); // step through the items in the cache folder foreach($files as $f) { // ignore any that do not end in '.qcache' if(!preg_match('/^.*\.qcache$/',$f)) continue; // check each of the items in the dirty list foreach($dirty as $d) { if(strstr($f, $d)) { if(file_exists($folder.$f)) unlink($folder.$f); } } } // if there are any items in the dirty array, that means that there is // at least one song that has changed. We need to remove the cached // 'song', 'artist', 'album', and 'genre' queries if that's the case if(count($dirty)) { if(file_exists($folder.'song.qcache')) unlink($folder.'song.qcache'); if(file_exists($folder.'artist.qcache')) unlink($folder.'artist.qcache'); if(file_exists($folder.'album.qcache')) unlink($folder.'album.qcache'); if(file_exists($folder.'genre.qcache')) unlink($folder.'genre.qcache'); } } } <file_sep>/config/migrations.php <?php return array( /** * The migrations available * * When new migrations are developed, they must be added to this array. The * format is simply the migration number (each of which must succeed the * previous value) and the name of the migration class (which must be * defined and must extend MigrationBase). */ 'migrations' => array( '1' => 'Migration_001_add_initial_scheme', '2' => 'Migration_002_add_playlist_tables', '3' => 'Migration_003_add_artwork_filename_to_songs', ), );<file_sep>/config/app.php <?php return array( /** * The path to the music files */ 'music-path' => '/media/music/', /** * The path to the folder where artwork will be saved */ 'music-artwork-path' => dirname(__FILE__).'/../storage/artwork/', /** * The path to templates */ 'template-path' => dirname(__FILE__).'/../views/templates/', /** * The path to the template cache */ 'template-cache-path' => dirname(__FILE__).'/../storage/cache/', /** * The MPD connection string */ 'mpd-connection' => 'unix:///var/run/mpd/socket', /** * Should the system cache queries? * * This is set to false while developing. It should be set to true in a * production system. */ 'query-caching' => false, /** * The query cache storage location */ 'query-cache-path' => dirname(__FILE__).'/../storage/cache/', );<file_sep>/libraries/QueryBuilder.php <?php class QueryBuilder { /** * The regex used for routing queries * * queries look like this: * * playlist - list of playlists * page head='Playlist', list head=null * * playlist/1/song - list of songs for playlist=1 * page head=playlist.name, list head=null * * playlist/1/song/2 - load all songs for playlist=1, start playing song=2, go to nowplaying * * * artist - list of artists * page head='Artists', list head=null * * artist/1/album - list of albums for artist=1 * page head=artist.artist, list head=null * * artist/1/album/2/song - list of songs for artist=1, album=2 * page head=artist.artist, list head=album+stats * * artist/1/album/2/song/3 - load all songs for artist=1, album=2, play song=3, go to nowplaying * * artist/1/song - list of all songs for artist=1 * page head=artist.artist, list head=null * * * song - list of all songs * page head='Songs', list head=null * * song/1 - load ALL songs, play song=1, go to nowplaying * * * album - list all albums * page head='Albums', list head=null * * album/1/song - list of songs for album=1 * page head=album.title, list head=album+stats * * album/1/song/2 - load all songs for album=1, play song=2, go to nowplaying * * * genre - list all genres * page head='Genres', list head=null * * genre/1/artist - list of artists for genre=1 * page head=genre.name, list head=null * * genre/1/artist/2/album - list of albums for genre=1, artist=2 * page head=artist.artist, list head=null * * genre/1/artist/2/album/3/song - list of songs for genre=1, artist=2, album=3 * page head=artist.artist, list head=album+stats * * * genre/1/artist/2/album/3/song/4 - load all songs for genre=1, artist=2, album=3, play song=4, go to nowplaying * * In addition, any path ending in song/# can also end song/shuffle, in * which case all songs are loaded and play shuffled. */ private static $allowed_query_regex = "^(/([a-zA-Z]+)/([0-9]+)){0,5}(/([a-zA-Z]+)(/([0-9]+|shuffle))?)[/]?$"; /** * A "getter" for the routing regex * @return string */ public static function regex() { return static::$allowed_query_regex; } /** * Get the results of a "query" * * A "query" in this context is the sequence of arguments passed to the * router which describes the information the user is looking for. Above is * a set of examples of all the possible types of queries. * * @param type $arguments * @return type */ public static function get($arguments) { // instantiate the result array $results = array( 'items' => null, 'page_title' => null, 'previous_page' => null, 'album_stats' => null, ); // save the original arguments $original_args = $arguments; // the Model object $obj = null; // the list of pages we pass through on the way. This will be used to // determine the title of the previous page for the "back" button $pages = array(); // loop through the arguments while(count($arguments)) { // get the next argument off the front of the array $arg = array_shift($arguments); // has the model already been created? if(!$obj) { // no. I need to instantiate an object $obj = Model::factory(ucfirst(strtolower($arg))); // set the page title $results['page_title'] = ucfirst(strtolower($arg)).'s'; } else { // yes. we have an object, so the next step is to look for a //relationship $method = $arg.'s'; $obj = $obj->$method(); } // add this argument to the list of pages $pages[] = ucfirst(strtolower($a)).'s'; // are there any more items on the stack? if(count($arguments)) { // Yes! The next one must be an ID value $id = array_shift($arguments); // is it "shuffle"? if($id=='shuffle') { // Yes! we're shuffling a list of songs. Order it by track // number then alphabetically by name $obj = $obj->order_by_asc('track_number')->order_by_asc('name'); // and get the list of objects $obj = $obj->find_many(); } else { // no, it's an ID value // find the object with that ID $obj = $obj->find_one($id); // is it an Album object? if(get_class($obj)=='Album') { // Yes! Save the album stats $results['album_stats'] = $obj->getStats(); } // update the page title with the name of this object $results['page_title'] = $obj->name; } } else { // there are no more arguments, so what we're left with is a // list (of songs, albums, artists, whatever) // are we looking at a list of songs? if($arg=='song') { // Yes. order it by track number then alphabetically by name $obj = $obj->order_by_asc('track_number')->order_by_asc('name'); } // are we looking for a list of albums? if($arg=='album') { // Yes. Order the list by release year, then alphabetically // by name $obj = $obj->order_by_asc('year')->order_by_asc('name'); } // and get the list of objects $obj = $obj->find_many(); } // some final cleanup of the list of pages - does the current object // have a name? if(isset($obj->name)) { // Yes! remove the last item from the list array_pop($pages); // and add the object name in its place $pages[] = $obj->name; } } // add the object to the results $results['items'] = $obj; // now figure out the previous page path & text // add the first argument back onto the list of pages array_unshift($pages, ucfirst(strtolower($original_args[0])).'s'); // the base index to work from $i = count($original_args)-1; // the page $previous_page = $i/2-1; $previous_page = $previous_page>=0 ? $pages[$previous_page] : null; // the path $previous_path = $i-2; $previous_path = $previous_path>=0 ? '/'.implode('/',array_chunk($original_args,$previous_path+1)[0]) : null; // finally, put the previous info together $previous = null; if($previous_page && $previous_path) $previous = array( 'text' => $previous_page, 'path' => $previous_path, ); // add the previous page info to the results $results['previous_page'] = $previous; // and return the results return $results; } /* * artist - list of artists * page head='Artists', list head=null * * artist/1/album - list of albums for artist=1 * page head=artist.artist, list head=null * * artist/1/album/2/song - list of songs for artist=1, album=2 * page head=artist.artist, list head=album+stats * * artist/1/album/2/song/3 - load all songs for artist=1, album=2, play song=3, go to nowplaying * * artist/1/song - list of all songs for artist=1 * page head=artist.artist, list head=null */ /** * Build a list of entries for a given key value. * * This is used to parse the output from MPD, which is an array of strings * of the form "key: value\n". Given a list of strings and a key value, this * method will extract the values corresponding to that key. * * @param string $key * @param array $list * @return array */ private static function buildListOfKeys($key, $list) { $result = array(); foreach($list as $l) { // a little kludge here to handle names, etc. with colons in them. // Explode the string with colons, shift off the first item (the // key), then implode the rest with colons to rebuild $a = explode(':', $l); $b = array_shift($a); $a = array( $b, implode(':', $a)); if(count($a)>=2) { $k = strtolower(trim($a[0])); $v = trim($a[1]); if($k==strtolower($key)) { if(!in_array($v,$result)) $result[] = $v; } } } sort($result, SORT_NATURAL|SORT_FLAG_CASE); return $result; } /** * Build a list of artists from a query * * @param array $query * The URI, parsed into an array of elements * * @return array */ public static function query($query=array()) { // artist - list of artist // list: artist // artist/1/album - list of albums for artist=1 // search: artist, ID - extract album names // artist/1/album/2/song - list of songs for artist=1, album=2 // search: artist, ID, album, ID - extract song names // artist/1/album/2/song/3 - load all songs for artist=1, album=2, play song=3, go to nowplaying // search: artist, ID, album, ID, song, ID - get song info & start playing // artist/1/song - list of all songs for artist=1 // search: artist, ID - get song titles // chop the array up into pairs of entries $query = array_chunk($query,2); // start building the command $command = null; $args = null; // step through the chunks while(count($query)>0) { $a = array_shift($query); // is it a single element array with the value 'artist'? if(count($a)==1 && $a[0]=='artist') { // Yes! update the command and exit the loop $command = 'list'; $args = array('artist'); break; } // No. add to the command $command = 'search'; $args[] = $a[0]; if(isset($a[1])) $args[] = Music::decode($a[1]); // $args[] = $a[1]; } // at this point, the last item in the $args array tells us what kind // of list we want $list = array_pop($args); // is the $list values actually "song"? if($list=='song') { // Yes! We actually want the "title" tag from the results $list = 'title'; } // run the command $result = Music::send($command, $args); Kint::dump($result['values']); // build the appropriate type of list return static::buildListOfKeys($list, $result['values']); } }<file_sep>/libraries/Config.php <?php class Config { /** * Get a configuration value * * The configuration key is a string of the form "file.key" where the "file" * part is the name (minus the .php extension) of a file in the "config" * folder. * * @param type $key * @return type */ public static function get($key) { // validate the key if(!$key || !is_string($key)) throw new Exception("Invalid configuration key: $key"); // parse the key $parts = explode('.',$key); $file = array_shift($parts); $key = implode(',',$parts); // load the appropriate config file $values = include dirname(__FILE__)."/../config/{$file}.php"; // check to see if the key exists $value = false; if(array_key_exists($key,$values)) $value = $values[$key]; // return the result return $value; } } <file_sep>/migrations/Migration_002_add_playlist_tables.php <?php class Migration_002_add_playlist_tables extends MigrationBase { /** * Migrate the database up to this version */ public static function up() { // create the playlists table $query = <<<QUERY CREATE TABLE playlists ( id INTEGER PRIMARY KEY ASC, name TEXT, created_at INTEGER, updated_at INTEGER ); QUERY; Database::execute($query); Database::execute("CREATE INDEX idx_playlists_name ON playlists( name );"); // create the playlists_songs table $query = <<<QUERY CREATE TABLE playlists_songs ( id INTEGER PRIMARY KEY ASC, playlists_id INTEGER, songs_id INTEGER, sort_order INTEGER ); QUERY; Database::execute($query); Database::execute("CREATE INDEX idx_playlists_songs_playlists_id ON playlists_songs( playlists_id );"); Database::execute("CREATE INDEX idx_playlists_songs_songs_id ON playlists_songs( songs_id );"); Database::execute("CREATE INDEX idx_playlists_songs_sort_order ON playlists_songs( sort_order );"); } /** * Revert the database to the previous version by reversing the effects of * the up method. */ public static function down() { // drop the table Database::execute("DROP TABLE playlists_songs;"); Database::execute("DROP TABLE playlists;"); } }<file_sep>/views/ListPage.php <?php /** * The view class for a page containing a list of items. */ class ListPage extends View { /** * Render a list page * * @param string $page_title * The page title (displayed in the top bar) * * @param array|null $album_stats * The album stats, if this is a list of songs from an album * * @param array $list_items * The list of items to display * * @return string * The HTML of the rendered page */ public static function render($page_title, $previous, $shuffle, $allsongs, $list) { // instantiate the template engine $parser = new Rain\Tpl; // assign the values to the template parser $parser->assign(array( 'page_title' => $page_title, 'list' => $list, 'previous' => $previous, 'shuffle' => $shuffle, 'all_songs' => $allsongs, 'now_playing' => Music::isPlayingOrPaused(), 'album_stats' => $album_stats, 'include_all_songs' => $include_all_songs, 'base_uri' => static::$base_uri, 'object_type' => $type, )); // return the HTML return $parser->draw( "list-page", true ); } }<file_sep>/models/Genre.php <?php class Genre { /** * Get the list of genres * * @return array */ public static function getList() { // get the list $result = Music::send('list', 'genre'); // start building the list $list = array(); // step through the results foreach($result['values'] as $v) { if(substr($v,0,6)=='Genre:') { $g = trim(substr($v,6)); if($g) $list[] = $g; } } // sort the list sort($list); // and return it return $list; } /** * Get the list of artists for the genre * * @param string $genre * The genre * * @return array */ public static function getArtists($genre) { // query the MPD database $result = Music::send('search', 'genre', $genre); // get the list of songs $songs = Music::buildSongList($result['values']); // extract the album information from the list $list = array(); foreach($songs as $s) { if(isset($s['Artist'])) { $l = array( 'artist' => $s['Artist'], ); if(!in_array($l, $list)) $list[] = $l; } } return $list; } /** * Get the list of albums for a genre & artist * * @param string $genre * @param string $artist * @return array */ public static function getAlbums($genre, $artist) { // query the MPD database $result = Music::send('search', 'genre', $genre, 'artist', $artist); // get the list of songs $songs = Music::buildSongList($result['values']); // extract the album information from the list $list = array(); foreach($songs as $s) { if(isset($s['Artist']) && isset($s['Album'])) { $l = array( 'artist' => $s['Artist'], 'album' => $s['Album'], ); if(!in_array($l, $list)) $list[] = $l; } } return $list; } /** * Get the list of songs for a genre, artist, and album * * @param string $genre * @param string $artist * @param string $album * @return array */ public static function getSongs($genre, $artist, $album) { // query the MPD database if($album) $result = Music::send('search', 'genre', $genre, 'artist', $artist, 'album', $album); else $result = Music::send('search', 'genre', $genre, 'artist', $artist); // get the list of songs return Music::buildSongList($result['values']); } }<file_sep>/models/Song.php <?php class Song { public static function getList() { // get the list $result = Music::send('listallinfo'); // return the values return Music::buildSongList($result['values']); } /** * Get the image data as a data URL for an artist & album * * @param string $artist * @param string $album * @param int $size * @return string */ public static function getImageData($artist, $album, $size) { // build the expected file name $image_file = Config::get('app.music-artwork-path').md5($artist.$album)."-{$size}.jpg"; // does the file exist? if(file_exists($image_file)) { // convert it to a string & return it return Image::toDataURL($image_file); } // couldn't find the artwork, return the default artwork switch($size) { case 180: return Image::toDataURL(Config::get('app.music-artwork-path').'default-album-180.jpg'); case 320: return Image::toDataURL(Config::get('app.music-artwork-path').'default-album-320.jpg'); default: return Image::toDataURL(Config::get('app.music-artwork-path').'default-album.jpg'); } } }<file_sep>/bootstrap.php <?php // bootstrap configuration // initialize the template folder Rain\Tpl::configure('tpl_dir', Config::get('app.template-path')); Rain\Tpl::configure('tpl_ext', 'tpl'); Rain\Tpl::configure('cache_dir', Config::get('app.template-cache-path')); <file_sep>/models/Playlist.php <?php class Playlist { /** * Get the list of playlists * * @return array */ public static function getList() { // send the command to MPD $results = Music::send('listplaylists'); // start building a list $list = array(); // step through the values returned by MPD foreach($results['values'] as $r) { // is it a playlist line? if(substr($r,0,9)=='playlist:') { // yes! extract the playlist name and add it to the list $list[] = trim(substr($r,9)); } } // sort the list sort($list); // and return it return $list; } public static function getSongs($playlist) { // send the command to MPD $results = Music::send('listplaylistinfo', $playlist); // return the list of songs return Music::buildSongList($results['values']); } } <file_sep>/libraries/Music.php <?php use \PHPMPDClient\MPD as MPD; class Music { /** * A flag to indicate whether we're connected to MPD */ private static $is_connected = false; private static function connect() { if(!static::$is_connected) { // connect to MPD MPD::connect('', Config::get('app.mpd-connection'), null); static::$is_connected = true; } } /** * Encode a value for transmission as part of a URL * * @param string $data * @return string */ public static function encode($data) { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); } /** * Decode a value encoded with the function above * * @param string $data * @return string */ public static function decode($data) { return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); } private static function getSongList($args) { // discard the last item in the args, since that's the actual song ID array_pop($args); // get the list of songs $query = QueryBuilder::get($args); return $query['items']; } public static function send() { // connect to MPD static::connect(); // get the arguments $args = func_get_args(); // the first argument is the method $method = array_shift($args); // send the command $values = MPD::send($method, $args); return $values; } public static function replacePlaylist($args, $shuffle=false) { // connect to MPD static::connect(); // get the songs as defined by the arguments $songs = Music::getSongList($args); // get the ID of the song to play $song_id = array_pop($args); // clear the current playlist MPD::clear(); // a variable to save the ID of the song to play $mpd_id = null; // step through the songs foreach($songs as $s) { // add each song to the playlist $values = MPD::send('addid', 'file://'.$s->filenamepath); // does this song correspond to the the song to play? if($values['status']=='OK' && $s->id==$song_id) $mpd_id = trim(substr($values['values'][0],3)); } // start playing the selected song if(!$shuffle && $mpd_id) { // turn off random play MPD::send('random', 0); // play the requested song MPD::send('playid', $mpd_id); } else { // turn on random play MPD::send('random', 1); // start playing MPD::send('play'); } } public static function getCurrentSong() { // connect to MPD static::connect(); // get the song info $currentsong = MPD::send('currentsong'); return static::buildSongList($currentsong['values'])[0]; } /** * Get the status of MPD * * @return array * The array of status values */ public static function getStatus() { // connect to MPD static::connect(); // get the status $status = MPD::status(); // now parse the values so they're a little more usable if(isset($status['values'])) { // the status values are strings in the format "key: value". I'm // going to parse this into an associative array $newvalues = array(); foreach($status['values'] as $v) { $new = explode(':', $v); $newvalues[trim($new[0])] = trim($new[1]); } $status['values'] = $newvalues; } // and return the results return $status; } /** * Check to see if MPD is currently playing a song * * @return bool * True if a song is playing, false otherwise */ public static function isPlaying() { // get the status $status = static::getStatus(); // do we have some status values? if( isset($status['values']) && isset($status['values']['state']) && $status['values']['state']=='play') return true; // the status does not include "state: play" return false; } /** * Check to see if MPD is currently paused * * @return bool * True if a song is paused, false otherwise */ public static function isPaused() { // get the status $status = static::getStatus(); // do we have some status values? if( isset($status['values']) && isset($status['values']['state']) && $status['values']['state']=='pause') return true; // the status does not include "state: play" return false; } /** * Check to see if MPD is currently playing or paused * * @return bool * True if a song is playing or paused, false otherwise */ public static function isPlayingOrPaused() { // get the status $status = static::getStatus(); // do we have some status values? if( isset($status['values']) && isset($status['values']['state']) && ($status['values']['state']=='play' || $status['values']['state']=='pause')) return true; // the status does not include "state: play" return false; } /** * Jump to the previous song */ public static function previous() { // connect to MPD static::connect(); MPD::send('previous'); } /** * Jump to the next song */ public static function next() { // connect to MPD static::connect(); MPD::send('next'); } /** * Toggle between play/pause states */ public static function togglePlay() { static::connect(); MPD::send('pause', static::isPlaying() ? 1 : 0); return static::isPlaying() ? 'play' : 'pause'; } /** * Get the current volume * * @return int */ public static function getVolume() { // get the player status $status = static::getStatus(); if(isset($status['values']) && isset($status['values']['volume'])) return $status['values']['volume']; return false; } /** * Set the current volume * * @param int $volume * A volume value between 0 and 100 */ public static function setVolume($volume) { if(!is_numeric($volume)) $volume = 0; if($volume<0) $volume = 0; if($volume>100) $volume = 100; static::connect(); MPD::send('setvol', $volume); } public static function updateNowPlaying() { // get the current status of the player $status = static::getStatus(); $results['volume'] = $status['values']['volume']; $results['state'] = $status['values']['state']; // get the current song $song = static::getCurrentSong(); $results['title'] = $song ? $song['Title'] : null; $results['artist'] = $song ? $song['Artist'] : null; $results['album'] = $song ? $song['Album'] : null; // get the image data $results['artwork'] = Song::getImageData($song['Artist'], $song['Album'], 320); // return the data return $results; } public static function buildSongList($list) { // instantiate an array for results $results = array(); // instantiate a variable for the current song $current = array(); // step through the list foreach($list as $l) { // parse the line $x = explode(':',$l); $tag = trim(array_shift($x)); $value = trim(implode(':',$x)); // is it a "file" tag? if($tag=='file') { // Yes! add the current song to the results (if it exists) if(count($current)) $results[] = $current; // and reset the current song $current = array(); } $current[$tag] = $value; } // add the last "current" song to the results if(count($current)) $results[] = $current; // and return the results return $results; } public static function shuffle($state) { static::send('random', $state ? 1 : 0 ); } } <file_sep>/README.md pi-music ======== Introduction ------------ Pi-Music is a web-based client for the MPD application. It is modelled after the Music application on IOS and is intended to run on a Raspberry Pi. Requirements ------------ * MPD 0.16.5 or higher (it may work on earlier version, but I haven't tested it). * A web server (Apache or Lighttpd) * PHP 5.4.x or greated (I _think_ it will run on PHP 5.3.x, but I haven't tested it). Installation ------------ The easiest way is via Composer. I'll be setting up a page on packagist.org shortly. <file_sep>/models/Artist.php <?php class Artist { /** * Get the list of artists * * @return array */ public static function getList() { // get the list $result = Music::send('list', 'artist'); // start building the list $list = array(); // step through the results foreach($result['values'] as $v) { if(substr($v,0,7)=='Artist:') $list[] = trim(substr($v,7)); } // sort the list sort($list); // and return it return $list; } /** * Get the list of albums for an artist * * @param string $artist * The artist name * * @return array */ public static function getAlbums($artist) { // query the MPD database $result = Music::send('search', 'artist', $artist); // get the list of songs $songs = Music::buildSongList($result['values']); // extract the album information from the list $list = array(); foreach($songs as $s) { if(isset($s['Album'])) { $l = array( 'artist' => $artist, 'album' => $s['Album'], ); if(!in_array($l, $list)) $list[] = $l; } } return $list; } /** * Get all the songs for an artist * * @param string $artist * * @return array */ public static function getSongs($artist) { // query the MPD database $result = Music::send('search', 'artist', $artist); // get the list of songs return Music::buildSongList($result['values']); } }<file_sep>/routes.php <?php /** * The router for the application * * This looks like a good spot to write some TODOs * * * list page: fix toolbar at bottom * * list page: fix toolbar at top * * list page: add "back" button in upper left * * list page: add buttons to bottom toolbar * * list page: render album details when appropriate * * * ******************** bump version 0.0.2-alpha * * * implement playlists * * * ******************** bump version 0.0.3-alpha * * * scan music: remove missing files * * * ******************** bump version 0.0.4-alpha * * * album artwork * * * ******************** bump version 0.0.5-alpha * * * query caching system * * * ******************** bump version 0.0.6-alpha * * * install MPD * * implement MPD interface * * * ******************** bump version 0.0.7-alpha * * * bugfix: correct song order in query * * * ******************** bump version 0.0.8-alpha * * * implement "now playing" page * * redirect from query page to now playing page * * add "now playing" button to list page * * add "back" button to now playing page * * add control buttons to now playing page * * add volume control to now playing page * * toggle play/pause icons on now playing page * * * ******************** bump version 0.0.9-alpha * * * bugfix: songs not added in expected order * * * ******************** bump version 0.0.10-alpha * * * add "shuffle" buttons to song lists * * * ******************** bump version 0.0.11-alpha * * * add custom play/pause icons to play button * * * ******************** bump version 0.0.12-alpha * * * add update functionality to now-playing page * * * ******************** bump version 0.0.13-alpha * * * make "now playing" the default route * * * ******************** bump version 0.0.14-alpha * * ------------------------- this will get us to a point where the player works! * * * refactor query route handling to simplify it * * correct/clarify "back" route (button) * * rewrite to use MPD song database * * * ******************** bump version 0.0.15-alpha * * * add default artwork * * * ******************** bump version 0.0.16-alpha * * @todo fix "previous" button/route on now playing page * * @todo ******************** bump version 0.0.17-alpha * * @todo playlist editor * * @todo ******************** bump version 0.0.18-alpha * * @todo testing * * @todo ******************** bump version 0.1.0-beta * * ------------------------- future enhancements * * @todo add scrubbing control to now playing page * @todo desktop pc layout * */ use \PHPMPDClient\MPD as MPD; // @todo remove this line // clear the template cache array_map( "unlink", glob( Config::get('app.template-cache-path') . "*.rtpl.php" ) ); // instantiate the router class // $klein = new \Klein\Klein; // load the artist routes require_once 'routes/artist.php'; // load the album routes require_once 'routes/album.php'; // load the genre routes require_once 'routes/genre.php'; // load the song routes require_once 'routes/song.php'; // load the playlist routes require_once 'routes/playlist.php'; // load the "now playing" routes require_once 'routes/now-playing.php'; $klein->respond('GET','/show-tables', function(){ Kint::dump(Database::query("SELECT name FROM sqlite_master WHERE type='table';")); }); $klein->respond('GET','/nuke-db', function(){ $tables = Database::query("SELECT name FROM sqlite_master WHERE type='table';"); Kint::dump($tables); foreach($tables as $t) { Kint::dump("dropping {$t['name']}"); Database::execute("drop table if exists {$t['name']};"); } Kint::dump("database nuked"); }); $klein->respond('GET','/empty-db', function(){ Database::execute("delete from artists;"); Database::execute("delete from albums;"); Database::execute("delete from genres;"); Database::execute("delete from songs;"); Database::execute("delete from playlists;"); Database::execute("delete from playlists_songs;"); Kint::dump("database emptied"); }); $klein->respond('GET','/view-db', function($request,$response){ $tables = Database::query("SELECT name FROM sqlite_master WHERE type='table';"); foreach($tables as $t) { Kint::dump(Database::query("SELECT * FROM {$t['name']};")); } }); $klein->respond('GET','/test-route', function($request,$response){ $files = array( '/home/dave/temp/default-album-180.png', '/home/dave/temp/default-album-320.png', '/home/dave/temp/default-album.png', ); foreach($files as $f) { Kint::dump($f); $dataurl = Image::toDataURL($f); Kint::dump($dataurl); if($dataurl) file_put_contents($f.'.txt', $dataurl); } }); // Handle a 404 - route not found // $klein->respond('404', function($request){ $r = "<h1>Uh-oh. 404!</h1>"; $r .= "<p>The path '".$request->uri()."' does not exist.</p>"; return $r; }); // Execute! // $klein->dispatch(); <file_sep>/libraries/Database.php <?php /** * The database connection and utility class */ class Database { /** * The PDO database connection object */ private static $db = null; /** * Get the PDO object, initializing it if necessary * * @return PDO */ public static function pdo() { // check & see if the connection is already open if(!Database::$db) { Database::$db = new PDO(Config::get('database.dsn')); Database::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } return Database::$db; } /** * Check to see if a table exists in the database * * @param string $table * The table name to check * * @return bool * True if the table exists, false otherwise */ public static function tableExists($table) { // the query to run $query = "SELECT name FROM sqlite_master WHERE type='table' AND name=:name;"; // run the query return count(Database::query($query, array(':name'=>$table)))>0 ? true : false; } /** * Execute an arbitrary query with (optional) named parameters * * @param string $query * The query to execute * * @param array $parameters * The parameters, as an associative array of parameter names=>values * * @return bool * True on success, false on failure */ public static function execute($query, $parameters=null) { // prepare the statement $stmt = Database::pdo()->prepare($query); // bind the parameters if($parameters) { foreach($parameters as $key=>$value) { $stmt->bindValue($key, $value); } } // execute & return the result return $stmt->execute(); } /** * Execute a query and return the result set as an array of rows * * @param string $query * The query to execute * * @param array $parameters * The parameters, as an associative array of parameter names=>values * * @return array|bool * The array of rows returned or false if the query fails */ public static function query($query, $parameters=null) { // prepare the statement $stmt = Database::pdo()->prepare($query); // bind the parameters if($parameters) { foreach($parameters as $key=>$value) $stmt->bindValue($key,$value); } $success = $stmt->execute(); if(!$success) return false; // get the result set return $stmt->fetchAll(PDO::FETCH_ASSOC); } } <file_sep>/controllers/Query.php <?php class Query { public static function build($params) { return new ListPage($params); } } <file_sep>/routes/artist.php <?php // Routes for artist requests // // artist - list of artists // page head='Artists', list head=null // // artist/1/album - list of albums for artist=1 // page head=artist.artist, list head=null // // artist/1/album/2/song - list of songs for artist=1, album=2 // page head=artist.artist, list head=album+stats // // artist/1/album/2/song/3 - load all songs for artist=1, album=2, play song=3, go to nowplaying // // artist/1/song - list of all songs for artist=1 // page head=artist.artist, list head=null // artist - list of artists // $klein->respond('GET', '/artist', function($request, $response){ // get the list of artists $list = Artist::getList(); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k){ $v = array( 'name' => $v, 'url' => '/artist/'.Music::encode($v).'/album', ); }); $list = array_filter($list, function($v){ return $v['name'] ? true : false; }); return ListPage::render('Artists', null, false, false, $list); }); // artist/1/album - list of albums for artist=1 // $klein->respond('GET', '/artist/[:artist]/album', function($request, $response){ // get the artist name $artist = Music::decode($request->param('artist')); // get the list of albums $list = Artist::getAlbums($artist); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k) use ($artist) { $v = array( 'name' => $v['album'], 'url' => '/artist/'.Music::encode($artist).'/album/'.Music::encode($v['album']).'/song', ); }); // the "all songs" link $allsongs ='/artist/'.Music::encode($artist).'/song'; // build the "previous" link data $previous = array( 'path' => '/artist', 'text' => 'Artists', ); return ListPage::render($artist, $previous, false, $allsongs, $list); }); // artist/1/album/2/song - list of songs for artist=1, album=2 // $klein->respond('GET', '/artist/[:artist]/album/[:album]/song', function($request, $response){ // get the parameters $artist = Music::decode($request->param('artist')); $album = Music::decode($request->param('album')); // get the song list $list = Album::getSongs($artist, $album); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k) use ($artist, $album) { $v = array( 'name' => $v['Title'], 'url' => '/album/'.Music::encode($artist.'|'.$album).'/song/'.Music::encode($v['file']), ); }); // build the "previous" link data $previous = array( 'path' => '/artist/'.$request->param('artist').'/album', 'text' => $artist, ); // build the shuffle link $shuffle = '/album/'.Music::encode($artist.'|'.$album).'/song/shuffle'; return ListPage::render($album, $previous, $shuffle, false, $list); }); // artist/1/album/2/song/3 - load all songs for artist=1, album=2, play song=3, go to nowplaying // $klein->respond('GET', '/artist/[:artist]/album/[:album]/song/[:song]', function($request, $response){ // get the parameters // get the artist & album values $artist = Music::decode($request->param('artist')); $album = Music::decode($request->param('album')); $song = $request->param('song'); $song = $song=='shuffle' ? 'shuffle' : Music::decode($song); // clear the playlist Music::send('clear'); // get the list of songs $songs = Album::getSongs($artist,$album); // load the playlist with the requested songs (and figure out the current // song position) $pos = 0; for($i=0; $i<count($songs); $i++) { Music::send('add', $songs[$i]['file']); if($songs[$i]['file']==$song) $pos = $i; } // turn off "shuffle" Music::shuffle(false); // is the current song "shuffle" if($song=='shuffle') { // choose a random song $pos = rand(0,count($songs)-1); // turn on shuffle Music::shuffle(true); } // start playing the selected song Music::send('play', $pos); // redirect to "now playing" header('Location: /'); die; }); // artist/1/song - list of all songs for artist=1 // $klein->respond('GET', '/artist/[:artist]/song', function($request, $response){ // get the parameters $artist = Music::decode($request->param('artist')); // get the song list $list = Artist::getSongs($artist); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k) use ($artist) { $v = array( 'name' => $v['Title'], 'url' => '/artist/'.Music::encode($artist).'/song/'.Music::encode($v['file']), ); }); // build the "previous" link data $previous = array( 'path' => '/artist', 'text' => 'Artists', ); // build the shuffle link $shuffle = '/artist/'.Music::encode($artist).'/song/shuffle'; return ListPage::render($artist, $previous, $shuffle, false, $list); }); <file_sep>/migrations/Migration_003_add_artwork_filename_to_songs.php <?php class Migration_003_add_artwork_filename_to_songs extends MigrationBase { /** * Migrate the database up to this version */ public static function up() { // drop the existing table Database::execute("DROP TABLE IF EXISTS songs;"); // create the songs table $query = <<<QUERY CREATE TABLE songs ( id INTEGER PRIMARY KEY ASC, filenamepath TEXT, filesize INTEGER, fileformat TEXT, dataformat TEXT, codec TEXT, sample_rate REAL, channels INTEGER, bits_per_sample INTEGER, lossless TEXT, channelmode TEXT, bitrate REAL, playtime_seconds REAL, name TEXT, artists_id INTEGER, album_artist TEXT, albums_id INTEGER, genres_id INTEGER, track_number TEXT, disc_number TEXT, compilation TEXT, bpm TEXT, rating TEXT, artwork TEXT, created_at INTEGER, updated_at INTEGER ); QUERY; // execute the query Database::execute($query); // create some indices $indexes = array( // a unique index on the filenamepath column "CREATE UNIQUE INDEX idx_songs_filenamepath ON songs ( filenamepath );", // indices on important values "CREATE INDEX idx_songs_name ON songs ( name );", "CREATE INDEX idx_songs_artists_id ON songs ( artists_id );", "CREATE INDEX idx_songs_album_artist ON songs ( album_artist );", "CREATE INDEX idx_songs_albums_id ON songs ( albums_id );", "CREATE INDEX idx_songs_genres_id ON songs ( genres_id );", ); foreach($indexes as $i) Database::execute($i); } /** * Migrate the database down to the previous */ public static function down() { // drop the existing table Database::execute("DROP TABLE IF EXISTS songs;"); // create the songs table $query = <<<QUERY CREATE TABLE songs ( id INTEGER PRIMARY KEY ASC, filenamepath TEXT, filesize INTEGER, fileformat TEXT, dataformat TEXT, codec TEXT, sample_rate REAL, channels INTEGER, bits_per_sample INTEGER, lossless TEXT, channelmode TEXT, bitrate REAL, playtime_seconds REAL, name TEXT, artists_id INTEGER, album_artist TEXT, albums_id INTEGER, genres_id INTEGER, track_number TEXT, disc_number TEXT, compilation TEXT, bpm TEXT, rating TEXT, created_at INTEGER, updated_at INTEGER ); QUERY; // execute the query Database::execute($query); // create some indices $indexes = array( // a unique index on the filenamepath column "CREATE UNIQUE INDEX idx_songs_filenamepath ON songs ( filenamepath );", // indices on important values "CREATE INDEX idx_songs_name ON songs ( name );", "CREATE INDEX idx_songs_artists_id ON songs ( artists_id );", "CREATE INDEX idx_songs_album_artist ON songs ( album_artist );", "CREATE INDEX idx_songs_albums_id ON songs ( albums_id );", "CREATE INDEX idx_songs_genres_id ON songs ( genres_id );", ); foreach($indexes as $i) Database::execute($i); } }<file_sep>/config/database.php <?php return array( /** * The DSN to the SQLite3 Database */ 'dsn' => 'sqlite:'.dirname(__FILE__).'/../database/musix.sqlite3', /** * Turn on query logging */ 'logging' => true, );<file_sep>/libraries/Migrate.php <?php class Migrate { /** * The table name for the migrations. * * If the migration table does not exist the first time a migration is run, * it will be created. */ private static $table_name = 'sys_migrations'; /** * Migrate the database up to the greatest defined value */ public static function up() { // check to see if the "migration" table exists if(!Database::tableExists(static::$table_name)) { // if not, create it Database::execute("CREATE TABLE ".static::$table_name." (id INTEGER PRIMARY KEY ASC, last INTEGER);"); // initialize the value Database::execute("INSERT INTO ".static::$table_name." VALUES ( 1, 0 );"); } // get the current migration counter $value = Database::query("SELECT last FROM ".static::$table_name." WHERE id=1;"); $value = $value[0]['last']; // get the list of migration classes from the config $migrations = Config::get('migrations.migrations'); // make a list of classes to rollback, just in case of error $rollback = array(); // do the following in a try/catch block so we can roll back if need be try { while($value<max(array_keys($migrations))) { // increment the counter $value++; // if a migration exists for the incremented counter, then run it if(array_key_exists($value,$migrations)) { // get the class name $class = $migrations[$value]; if($class) { // run the migration "up" method $class::up(); // add this class to the list of rollbacks, just in case $rollback[] = $class; } else throw new Exception("Missing migration class '$class' for entry $value"); } else throw new Exception("Missing migration number: $value"); } } catch(Exception $e) { // we need to rollback // reverse the rollback array, since items were added to the end $rollback = array_reverse($rollback); // step through and roll back foreach($rollback as $class) { $class::down(); } // and rethrow the exception throw $e; } // if we get here, then everything succeeded // save the last migration counter Database::execute("UPDATE ".static::$table_name." SET last=:last WHERE id=1;", array(':last'=>$value)); } /** * Migrate the database down to the specified value (or 0 if no value given) * * @param int $down_to * The database version to migrate down to (default 0) */ public static function down($down_to=0) { // get the current migration counter $value = Database::query("SELECT last FROM ".static::$table_name." WHERE id=1;"); $value = $value[0]['last']; // get the list of migration classes from the config $migrations = Config::get('migrations.migrations'); // make a list of classes to rollback, just in case of error $rollback = array(); // do the following in a try/catch block so we can roll back if need be try { while($value>$down_to) { // if a migration exists for the incremented counter, then run it if(array_key_exists($value,$migrations)) { // get the class name $class = $migrations[$value]; if($class) { // run the migration "up" method $class::down(); // add this class to the list of rollbacks, just in case $rollback[] = $class; } else throw new Exception("Missing migration class '$class' for entry $value"); } else throw new Exception("Missing migration number: $value"); // decrement the counter $value--; } } catch(Exception $e) { // we need to rollback // reverse the rollback array, since items were added to the end $rollback = array_reverse($rollback); // step through and roll back foreach($rollback as $class) { $class::up(); } // and rethrow the exception throw $e; } // if we get here, then everything succeeded // save the last migration counter Database::execute("UPDATE ".static::$table_name." SET last=:last WHERE id=1;", array(':last'=>$value)); } }<file_sep>/routes/genre.php <?php // Routes for genre requests // genre - list all genres // page head='Genres', list head=null // // genre/1/artist - list of artists for genre=1 // page head=genre.name, list head=null // // genre/1/artist/2/album - list of albums for genre=1, artist=2 // page head=artist.artist, list head=null // // genre/1/artist/2/album/3/song - list of songs for genre=1, artist=2, album=3 // page head=artist.artist, list head=album+stats // // // genre/1/artist/2/album/3/song/4 - load all songs for genre=1, artist=2, album=3, play song=4, go to nowplaying // genre - list all genres // $klein->respond('GET', '/genre', function($request, $response){ // get the list of albums $list = Genre::getList(); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k){ $v = array( 'name' => $v, 'url' => '/genre/'.Music::encode($v).'/artist', ); }); return ListPage::render('Genres', null, false, false, $list); }); // genre/1/artist - list of artists for genre=1 // $klein->respond('GET', '/genre/[:genre]/artist', function($request, $response){ // get the parameter $genre = Music::decode($request->param('genre')); // get the list $list = Genre::getArtists($genre); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k) use ($genre) { $v = array( 'name' => $v['artist'], 'url' => '/genre/'.Music::encode($genre).'/artist/'.Music::encode($v['artist']).'/album', ); }); // build the "previous" link data $previous = array( 'path' => '/genre', 'text' => 'Genres', ); return ListPage::render($genre, $previous, false, false, $list); }); // genre/1/artist/2/album - list of albums for genre=1, artist=2 // $klein->respond('GET', '/genre/[:genre]/artist/[:artist]/album', function($request, $response){ // get the parameter $genre = Music::decode($request->param('genre')); $artist = Music::decode($request->param('artist')); // get the list $list = Genre::getAlbums($genre, $artist); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k) use ($genre) { $v = array( 'name' => $v['album'], 'url' => '/genre/'.Music::encode($genre).'/artist/'.Music::encode($v['artist']).'/album/'.Music::encode($v['album']).'/song', ); }); // build the "all songs" link $allsongs = '/genre/'.Music::encode($genre).'/artist/'.Music::encode($artist).'/song'; // build the "previous" link data $previous = array( 'path' => '/genre/'.$request->param('genre').'/artist', 'text' => 'Artists', ); return ListPage::render($artist, $previous, false, $allsongs, $list); }); // genre/1/artist/2/album/3/song - list of songs for genre=1, artist=2, album=3 // $klein->respond('GET', '/genre/[:genre]/artist/[:artist]/album/[:album]/song', function($request, $response){ // get the parameter $genre = Music::decode($request->param('genre')); $artist = Music::decode($request->param('artist')); $album = Music::decode($request->param('album')); // get the list $list = Genre::getSongs($genre, $artist, $album); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k) use ($genre) { $v = array( 'name' => $v['Title'], 'url' => '/genre/'.Music::encode($genre).'/artist/'.Music::encode($v['Artist']).'/album/'.Music::encode($v['Album']).'/song/'.Music::encode($v['file']), ); }); // build the "previous" link data $previous = array( 'path' => '/genre/'.$request->param('genre').'/artist/'.$request->param('artist').'/album', 'text' => $artist, ); // build the shuffle link $shuffle = '/genre/'.Music::encode($genre).'/artist/'.Music::encode($artist).'/album/'.Music::encode($album).'/song/shuffle'; return ListPage::render($album, $previous, $shuffle, false, $list); }); // genre/1/artist/2/album/3/song/4 - load all songs for genre=1, artist=2, album=3, play song=4, go to nowplaying // $klein->respond('GET', '/genre/[:genre]/artist/[:artist]/album/[:album]/song/[:song]', function($request, $response){ // get the parameter $genre = Music::decode($request->param('genre')); $artist = Music::decode($request->param('artist')); $album = Music::decode($request->param('album')); $song = $request->param('song'); $song = $song=='shuffle' ? 'shuffle' : Music::decode($song); // clear the playlist Music::send('clear'); // get the list $songs = Genre::getSongs($genre, $artist, $album); // load the playlist with the requested songs (and figure out the current // song position) $pos = 0; for($i=0; $i<count($songs); $i++) { Music::send('add', $songs[$i]['file']); if($songs[$i]['file']==$song) $pos = $i; } // turn off "shuffle" Music::shuffle(false); // is the current song "shuffle" if($song=='shuffle') { // choose a random song $pos = rand(0,count($songs)-1); // turn on shuffle Music::shuffle(true); } // start playing the selected song Music::send('play', $pos); // redirect to "now playing" header('Location: /'); die; }); $klein->respond('GET', '/genre/[:genre]/artist/[:artist]/song', function($request, $response){ // get the parameter $genre = Music::decode($request->param('genre')); $artist = Music::decode($request->param('artist')); // get the list $list = Genre::getSongs($genre, $artist, null); // walk the array and construct URLs // The encoded URL value is actually "artist name|album title". The artist // name is included to ensure that albums with the same name are not // conflated and the pipe character is a delimiter array_walk($list, function(&$v, $k) use ($genre) { $v = array( 'name' => $v['Title'], 'url' => '/genre/'.Music::encode($genre).'/artist/'.Music::encode($v['Artist']).'/song/'.Music::encode($v['file']), ); }); // build the "previous" link data $previous = array( 'path' => '/genre/'.$request->param('genre').'/artist', 'text' => 'Artists', ); // build the shuffle link $shuffle = '/genre/'.Music::encode($genre).'/artist/'.Music::encode($artist).'/song/shuffle'; return ListPage::render($album, $previous, $shuffle, false, $list); }); $klein->respond('GET', '/genre/[:genre]/artist/[:artist]/song/[:song]', function($request, $response){ // get the parameter $genre = Music::decode($request->param('genre')); $artist = Music::decode($request->param('artist')); $song = $request->param('song'); $song = $song=='shuffle' ? 'shuffle' : Music::decode($song); // clear the playlist Music::send('clear'); // get the list $songs = Genre::getSongs($genre, $artist, null); // load the playlist with the requested songs (and figure out the current // song position) $pos = 0; for($i=0; $i<count($songs); $i++) { Music::send('add', $songs[$i]['file']); if($songs[$i]['file']==$song) $pos = $i; } // turn off "shuffle" Music::shuffle(false); // is the current song "shuffle" if($song=='shuffle') { // choose a random song $pos = rand(0,count($songs)-1); // turn on shuffle Music::shuffle(true); } // start playing the selected song Music::send('play', $pos); // redirect to "now playing" header('Location: /'); die; }); <file_sep>/views/View.php <?php class View { protected static $base_uri = ''; public static function setBaseUri($uri) { static::$base_uri = $uri; } }
9c19366214d14660bf433c53be488e20e3b11ea1
[ "JavaScript", "Markdown", "PHP" ]
37
PHP
MonsterGfx/pi-music
a0eeedfae2d604fbe8e40f382002dff986d8c52e
977bcddd02939d157742069bd00eb7121fbe75e6
refs/heads/master
<file_sep>public class Main { public static void main(String[] args) { System.out.println("Programozás alapok Udemy kurzus"); // 1. Írassuk egy egy int és egy string adattípus értékét! /* int x = 3; x = x++; String szoveg = "alma"; System.out.println(x); System.out.println(szoveg); if(x == 5) { System.out.println("Az értéke 5."); } else { System.out.println("Az értéke nem 5."); } for (int i=0; i<10; i++) { System.out.print(i); if(i<9) { System.out.print(','); } else { System.out.println(); } } */ // 2. Irassuk ki 0-100-ig a 7-tel osztható számokat! /* for(int szam=1; szam<100; szam++) { if(szam%7==0) { System.out.println(szam + " osztható 7-tel."); } } */ // 3. Irassuk ki 0-100-ig a 7-tel osztható számok számát! /* int[] lista = new int[50]; int szamlalo = 0; for(int i=0; i<100; i++) { if(i%7==0) { lista[szamlalo] = i; szamlalo = szamlalo +1; } } System.out.println(szamlalo + " db 7-tel osztható szám van 0-100-ig"); */ // 4. Kérjünk be egy számlistát, és adjuk vissza a számok összegét! /* int[] lista = {5, 12, 4, 6, 3, 7, 15, 9, 2}; int szamlalo = lista.length; System.out.println(szamlalo); int osszeg = 0; for(int i=0; i < lista.length; i++) { osszeg = osszeg + lista[i]; } System.out.println(osszeg + " a lista összege."); */ // 5. Kérjünk be egy számlistát, és adjuk vissza a páratlan számainak számát. /* int[] lista = {5, 12, 4, 6, 3, 7, 15, 9, 2}; int szamlalo = lista.length; System.out.println(szamlalo); int osszeg = 0; for(int i=0; i < lista.length; i = i+1) { osszeg = osszeg + lista[i]; } System.out.println(osszeg + " a lista osszege."); int darab = 0; for(int i = 0; i<lista.length; i++) { if(lista[i]%2 == 1) { darab = darab + 1; } } System.out.println(darab + " darab páratlan szám van."); */ // 6. Irassuk ki, hogy egy adott szám szerepel-e a listában! /* int[] lista = {5, 12, 4, 6, 3, 7, 15, 9, 2}; int szamlalo = lista.length; System.out.println(szamlalo); int osszeg = 0; for(int i=0; i < lista.length; i = i+1) { osszeg = osszeg + lista[i]; } System.out.println(); int ki = 11; boolean van = false; for(int i=0; i<lista.length; i++) { if(lista[i] == ki) { van = true; } } if(van) { System.out.println(ki + " szerepel a listában."); } else { System.out.println(ki + " nem szerepel a listában."); }*/ // 7. Irassuk ki egy adott elem helyét a listában! /* int[] lista = {5, 12, 4, 6, 3, 7, 15, 9, 2}; int mi = 6; int hol = -1; for(int i=0; i<lista.length; i++) { if(lista[i] == mi) { hol = 1; } } System.out.println("A " + mi + " elem a listában van itt: " + hol); */ // 8. Ha egy elem a listában van, irassuk ki a helyét! /* int[] lista = {5, 12, 4, 6, 3, 7, 15, 9, 2}; int ezt = 15; int holvan = -1; for(int i=0; i<lista.length; i++) { if(lista[i] == ezt) { holvan = i + 1; } } if(holvan == -1) { System.out.println(ezt + " elem nincs a lsitában"); } else { System.out.print(ezt + " elem itt van: " + holvan); } */ // 9. Irassuk ki a listából a legnagyobb számot és a helyét! /* int[] lista = {5, 12, 4, 6, 3, 7, 15, 9, 2}; /* int maximumErtek = -1; int maximumHely = -1; for(int i=0; i<lista.length; i++) { if(lista[i]>maximumErtek) { maximumErtek = lista[i]; maximumHely = i + 1; } } System.out.println("A lista maximuma: " + maximumErtek + " a(z) " + maximumHely + ". helyen."); */ // 10. A lista tartalmát másoljuk át, duplázzuk, és irassuk ki a 10-nél nagyobb elemeit! /* int[] lista = {5, 12, 4, 6, 3, 7, 15, 9, 2}; int[] lista2 = new int[20]; // létrehozok egy maximum 20 elemű új listát (konstans, nem kötelező konstansnak lennie) int szamlalo2 = 0; // az új lista számlálójának kezdeti értéke 0 for(int i=0; i<lista.length; i++) { // a másoláshoz a lista1-et használom, mert annak tudom a hosszát, a lista2-ét még nem lista2[szamlalo2] = 2*lista[i]; // a második lista soron következő elemének meg kell egyeznie a lista i-edik elemével (sima másolás) szamlalo2++; // megszámoljuk a második lista elemeit is } int szamlalo = lista.length; int[] rendezettLista = new int[szamlalo]; // a harmadik lista elemszáma megegyezik a korábbi listák elemszámával (nem konstans) int szamlalo3 = 0; for(int i=0; i<szamlalo2; i++) { if(lista2[i]>10) { // a második lista 2-vel szorzott elemei közül csak a 10-nél nagyobbakat rakjuk a rendezett listába rendezettLista[szamlalo3] = lista2[i]; szamlalo3++; } } for(int i=0; i<szamlalo3; i++) { System.out.print(rendezettLista[i]); System.out.print(", "); } */ // 11. Rendezzük növekvő sorrendbe a lista elemit! (buborék - nem gyors, de egyszerű > végigmegy a tömbön és a legkisebb elemet választja) /* int[] lista = {5, 12, 4, 6, 3, 7, 15, 9, 2}; for (int i=0; i<lista.length-1; i++) { // végigmegy a listán az utolsó előtti elemig for (int j = i+1; j<lista.length; j++) { // csak az i+1-től megy végig a még nem rendezett elemeken if(lista[i]>lista[j]) { int temp = lista[i]; lista[i] = lista[j]; lista[j] = temp; } } } for(int i=0; i<lista.length;i++) { System.out.print(lista[i]); System.out.print(", "); } */ } } <file_sep>class PersonSchema { String name; int age; void speak() { System.out.println("I speak."); } int calculateYearsToRetirement() { int yearsToRetirement = 65 - age; return yearsToRetirement; } int getAge() { return age; } // Function with parameter public void saySomething(String whatYouSay){ System.out.println(whatYouSay); } public void tellAddress(String address){ System.out.println(address); } public void jump(String direction, double distance){ System.out.println("Jumping to " + direction + " " + distance + " meters."); } public void height (int height){ System.out.println("My height is: " + height + " cm."); } } public class Person { public static void main(String[] args) { PersonSchema person1 = new PersonSchema(); person1.name = "Joe"; person1.age = 35; person1.speak(); int yearsToRetirement = person1.calculateYearsToRetirement(); System.out.println("Years till retirement: " + yearsToRetirement); int age = person1.getAge(); System.out.println("Age: " + age); // Function with parameter person1.saySomething("I say something."); String address = "2089 Telki, Búzavirág u. 2."; person1.tellAddress("My address is " + address); person1.jump("north", 2.3); person1.height(165); } }
698c1f0e1e82176518a2090cdd2c06d651b0e605
[ "Java" ]
2
Java
selectAlizFromBudapest/Java
cb379e4c6847f51e2096d43b89e8c9c999511330
09979a1b8028f791b9cae7f3e0e7a7b7c7838f88
refs/heads/master
<file_sep># MachineLearningCoursera Repo used for programming assignments for the Coursera Machine Learning course ## Running Octave Octave is run using docker. Further details can be found at [Github](https://github.com/ymatsunaga/docker-octave) ### Octave on Jupiter Server ```console docker run --rm -p 8888:8888 -v $(pwd):/home/jovyan/work ymatsunaga/octave ``` ### Octave Shell ```console docker run -it --rm -v $(pwd):/home/jovyan/work ymatsunaga/octave octave ``` <file_sep>docker run -it --rm -v $(pwd):/home/jovyan/work ymatsunaga/octave octave
08468faeeeff966cb7573d17804fd9119ce61f21
[ "Markdown", "Shell" ]
2
Markdown
oskarvip/MachineLearningCoursera
5d1ebc0703a71c12bae2d24ceff2de3b403dfe6b
3c1e42dce20ab015486bb57d6917403522a3bd8f
refs/heads/master
<repo_name>CompRhys/ornstein-zernike<file_sep>/sim/core/parse.py import argparse def parse_input(): parser = argparse.ArgumentParser() parser.add_argument('--table', type=str) parser.add_argument('--rho', type=float) parser.add_argument('--temp', type=float) parser.add_argument('--dt', type=float) parser.add_argument('--dr', type=float) parser.add_argument('--burn_steps', type=int) parser.add_argument('--burn_iter_max', type=int) # parser.add_argument('--bulk_part', type=int) parser.add_argument('--box_size', type=float) parser.add_argument('--bulk_steps', type=int) parser.add_argument('--bulk_iter', type=int) parser.add_argument('--output', type=str) args = parser.parse_args() return args <file_sep>/sim/core/henderson.py from __future__ import print_function import sys import os import re import espressomd import numpy as np import time import timeit from sklearn.metrics import pairwise_distances as pdist2 def sample_henderson(syst, dt, iterations, steps, n_part, mu_repeat, r, dr, bins, input_file): """ repeat the cavity sampling for a given number of iterations returns: cav = (cav) array(iterations,bins) mu = (mu) array(iterations) """ print("\nSampling Cavity\n") tables = np.loadtxt(input_file) start = timeit.default_timer() syst.time_step = dt cav = np.zeros((iterations, bins)) mu = np.zeros(iterations) cav_repeat = np.ceil(10 * r**2).astype(int) for q in range(iterations): print('sample run {}/{}'.format(q + 1, iterations)) mu[q]= get_mu(syst, n_part, mu_repeat, tables) cav[q, :] = get_cavity(syst, n_part, cav_repeat, dr, bins, tables) syst.integrator.run(steps) now = timeit.default_timer() print('sample run {}/{} (real time = {:.1f})'.format( q + 1, iterations, now - start)) return cav, mu def get_cavity(syst, n_part, n_repeat, dr, bins, tables): E = syst.analysis.energy() curtemp = E['kinetic'] / (1.5 * (n_part)) # fast calculation of the Cavity correlation true_pos = np.vstack(np.copy(syst.part[:].pos_folded)) # true_pos = np.vstack(syst.part[:].pos) # true_pos = np.mod(true_pos, syst.box_l[0]) cav_fast = np.zeros(bins) for k in range(bins): for i, true_r in enumerate(true_pos): ghost_pos = np.mod(vec_on_sphere(n_repeat[k]) * k * dr + true_r, syst.box_l[0]) gt_dist = pdist2(np.delete(true_pos, i, axis=0), ghost_pos) E_fast = np.sum(np.interp(gt_dist, tables[0, :], tables[1, :]), axis = 0) cav_fast[k] += np.mean(np.exp(-E_fast/curtemp), axis = 0) cav_fast = cav_fast/n_part # # slow calculation of the Cavity correlation # cav = np.zeros(bins) # cav_count = np.zeros(bins) # # for j in range(n_part): # for j in range(10): # orig_pos = np.array(syst.part[j].pos) # syst.part[j].type = 1 # E_j = syst.analysis.energy()["non_bonded"] # syst.part[j].type = 0 # for k in range(bins): # for l in range(n_repeat[k]): # syst.part[j].pos = np.ravel(orig_pos + vec_on_sphere() * k * dr).tolist() # E_refj = syst.analysis.energy()["non_bonded"] # cav[k] += np.exp(-(E_refj - E_j) / curtemp) # cav_count[k] += 1 # if ((j+1) % 128) == 0: # print(('checking particle {}/{}').format(j+1, n_part)) # syst.part[j].pos = orig_pos # cav_slow = cav / cav_count # exit() return cav_fast def vec_on_sphere(n_repeat=1): vec = np.random.randn(3,n_repeat) vec /= np.linalg.norm(vec, axis=0) return vec.T def remove_diag(x): x_no_diag = np.ndarray.flatten(x) x_no_diag = np.delete(x_no_diag, range(0, len(x_no_diag), len(x) + 1), axis=0) x_no_diag = x_no_diag.reshape(len(x), len(x) - 1) return x_no_diag def get_mu(syst, n_part, n_repeat, tables): """ currently mu fast is 10 times larger?""" E_ref = syst.analysis.energy() curtemp = E_ref['kinetic'] / (1.5 * n_part) start = timeit.default_timer() # fast calculation of chemical potential true_pos = np.vstack(np.copy(syst.part[:].pos_folded)) # true_pos = np.vstack(syst.part[:].pos) # true_pos = np.mod(true_pos, syst.box_l[0]) ghost_pos = np.random.random((n_repeat, 3)) * syst.box_l gt_dist = pdist2(true_pos, ghost_pos) E_fast = np.sum(np.interp(gt_dist, tables[0, :], tables[1, :]), axis = 0) mu_fast = np.mean(np.exp(-E_fast/curtemp), axis = 0) end_fast = timeit.default_timer() # # slow calculation of chemical potential # E_slow = np.zeros_like(E_fast) # syst.part.add(id=n_part + 1, pos=syst.box_l / 2., type=0) # for i in range(n_repeat): # syst.part[n_part + 1].pos = ghost_pos[i,:] # E_slow[i] = syst.analysis.energy()["non_bonded"] - E_ref["non_bonded"] # syst.part[n_part + 1].remove() # mu_slow = np.mean(np.exp(-E_slow/curtemp), axis = 0) # end_slow = timeit.default_timer() # # print results # print("fast {}, time {}".format(mu_fast, start-end_fast)) # print("slow {}, time {}".format(mu_slow, end_fast-end_slow)) return mu_fast def get_pos_vel(syst, timestep, iterations, steps): """ save the unfolded particle positions and velocity """ print("\nSampling\n") start = timeit.default_timer() n_part = len(syst.part.select()) syst.time_step = timestep pos = np.zeros((iterations, 3*n_part)) vel = np.zeros((iterations, 3*n_part)) temp = np.zeros(iterations) time = np.zeros(iterations) for i in range(iterations): syst.integrator.run(steps) pos[i,:] = np.copy(syst.part[:].pos).reshape(-1) vel[i,:] = np.copy(syst.part[:].v).reshape(-1) temp[i - 1] = syst.analysis.energy()['kinetic'] / (1.5 * n_part) time[i - 1] = syst.time if (i % 128) == 0: now = timeit.default_timer() print(('sample run {}/{}, temperature = {:.3f}, ' 'system time = {:.1f} (real time = {:.1f})').format( i, iterations, temp[i - 1], syst.time, now - start)) return pos, vel, temp, time - time[0]<file_sep>/process/bulk-plot.py from __future__ import print_function import sys import re import os import numpy as np from core import block, transforms, parse import matplotlib import matplotlib.pyplot as plt from scipy.interpolate import interp1d from scipy.integrate import cumtrapz from scipy.signal import savgol_filter matplotlib.rcParams.update({'font.size': 12}) def plot_funcs( r, phi, avg_tcf, err_tcf, fd_gr, fd_gr_sg, avg_dcf, err_dcf, avg_icf, err_icf, avg_grad_icf, err_grad_icf, avg_dcf_dir, err_dcf_dir, avg_dcf_fft, err_dcf_fft, avg_br, err_br): plt.plot(r, fd_gr) plt.plot(r, fd_gr_sg) plt.ylim((0,1e-3)) fig, axes = plt.subplots(2, 3, figsize=(18, 8)) # Plot g(r) axes[0, 0].plot(r, avg_tcf + 1) axes[0, 0].fill_between(r, avg_tcf + err_tcf + 1, avg_tcf - err_tcf + 1, alpha=0.3) axes[0, 0].plot((r[0],r[-1]), np.ones(2), '--', color="tab:blue") axes[0, 0].set_xlabel('r/$\sigma$') axes[0, 0].set_ylabel('$g(r)$') # Plot c(r) axes[0, 1].plot(r, avg_dcf_fft, label='$c_{fft}(r)$') axes[0, 1].fill_between(r, avg_dcf_fft + err_dcf_fft, avg_dcf_fft - err_dcf_fft, alpha=0.2) axes[0, 1].plot(r, avg_dcf, label='$c_{sw}(r)$') axes[0, 1].fill_between(r, avg_dcf + err_dcf, avg_dcf - err_dcf, alpha=0.2) axes[0, 1].plot((r[0],r[-1]), np.zeros(2), '--', color="tab:blue") axes[0, 1].set_xlabel('r/$\sigma$') axes[0, 1].set_ylabel('$c(r)$') axes[0, 1].legend() ## plot y(r) axes[0, 2].plot(r, avg_icf, label='$c_{sw}(r)$') axes[0, 2].fill_between(r, avg_icf + err_icf, avg_icf - err_icf, alpha=0.2) axes[0, 2].plot((r[0],r[-1]), np.zeros(2), '--', color="tab:blue") axes[0, 2].set_xlabel('r/$\sigma$') axes[0, 2].set_ylabel('$\gamma(r)$') axes[0, 2].legend() ## plot y'(r) axes[1, 2].plot(r, avg_grad_icf) axes[1, 2].fill_between(r, avg_grad_icf + err_grad_icf, avg_grad_icf - err_grad_icf, alpha=0.2) axes[1, 2].plot((r[0],r[-1]), np.zeros(2), '--', color="tab:blue") axes[1, 2].set_xlabel('r/$\sigma$') axes[1, 2].set_ylabel('$\gamma\'(r)$') axes[1, 2].legend() # Plot phi(r) axes[1, 0].plot(r, phi) axes[1, 0].plot((r[0],r[-1]), np.zeros(2), '--', color="tab:blue") axes[1, 0].set_ylim([-3, 8]) axes[1, 0].set_xlabel('r/$\sigma$') axes[1, 0].set_ylabel('$\phi(r)$') # # Plot b(r) ind = len(r)-len(avg_br) axes[1, 1].plot(r[ind:], avg_br, label='$b_{sw}(r)$') axes[1, 1].fill_between(r[ind:], avg_br + err_br, avg_br - err_br, alpha=0.2) axes[1, 1].plot((r[0],r[-1]), np.zeros(2), '--', color="tab:blue") # axes[1, 2].set_xlim([0, 3.5]) axes[1, 1].set_xlabel('r/$\sigma$') axes[1, 1].set_ylabel('$B(r)$') axes[1, 1].legend(loc=4) fig.tight_layout() return def plot_sq_compare(q, switch, avg_sq, err_sq, avg_sq_fft, err_sq_fft, avg_sq_switch, err_sq_switch, block_sq): # Plot s(q) matplotlib.rcParams.update({'font.size': 16}) fig, axes = plt.subplots(2, figsize=(6,6), sharex=True, gridspec_kw={'height_ratios':[8, 3]},) axes[0].plot(q, avg_sq, linewidth=1, marker='x', label='$S_{dir}(q)$') # axes[0].plot(q, block_sq.T, linewidth=1, marker='x', alpha=0.2) axes[0].fill_between(q, avg_sq + err_sq, avg_sq - err_sq, alpha=0.2) axes[0].plot(q, avg_sq_fft, color='tab:orange', linewidth=1, marker='o', mfc='none', label='$S_{fft}(q)$') axes[0].fill_between(q, avg_sq_fft + err_sq_fft, avg_sq_fft - err_sq_fft, alpha=0.2) axes[0].plot(q, avg_sq_switch, color='g', marker='+', linewidth=1, label='$S_{sw}(q)$') axes[0].fill_between(q, avg_sq_switch + err_sq_switch, avg_sq_switch - err_sq_switch, alpha=0.2) axes[0].plot(q, switch, color='r',linewidth=1, marker='*', label='W(q)') axes[0].set_xlim([0, 12.5]) # axes[1, 0].set_ylim([-.5, 4.0]) axes[0].set_ylabel('$S(q), W(q)$', labelpad=12) axes[0].legend(markerscale=1, fontsize=12, frameon=False) axes[1].plot(q, (- avg_sq + avg_sq_fft), linewidth=1, marker='x', label='$\Delta S(q)$') axes[1].fill_between(q, (- avg_sq + avg_sq_fft) + err_sq, (- avg_sq + avg_sq_fft) - err_sq, alpha=0.2) axes[1].plot((0,13), (0,0), 'k-.', linewidth=0.5) axes[1].set_xlabel('$q/\sigma^{-1}$') axes[1].set_ylabel('$\Delta S(q)$', labelpad=0) axes[1].set_xlim([0, 12.5]) axes[1].set_yticks([-0.1, 0.2]) axes[1].set_ylim([-0.15, 0.3]) # axes[1].legend() fig.tight_layout() fig.subplots_adjust(hspace=0) return if __name__ == "__main__": inputs = ' '.join(sys.argv[1:]) opt = parse.parse_input(inputs) input_path = opt.output _, pot_type, pot_number = opt.table.split("_") pot_number = re.findall('\d+', pot_number)[-1] input_size = opt.box_size input_density = opt.rho input_temp = opt.temp print("potential {}_{}, density {}".format(pot_type, pot_number, input_density)) n_part = int(input_density * (input_size**3.)) rdf_path = '{}rdf_{}_{}_p{}_n{}_t{}.dat'.format( input_path, pot_type, pot_number, input_density, n_part, input_temp) sq_path = '{}sq_{}_{}_p{}_n{}_t{}.dat'.format( input_path, pot_type, pot_number, input_density, n_part, input_temp) phi_path = '{}phi_{}_{}.dat'.format(input_path, pot_type, pot_number) real, fourier = transforms.process_inputs(input_size, input_temp, input_density, "plot", rdf_path=rdf_path, sq_path=sq_path, phi_path=phi_path) plot_funcs(*real) plot_sq_compare(*fourier) plt.show() <file_sep>/learn/split_dataset.py import os import re import sys import numpy as np from tqdm import tqdm from sklearn.model_selection import train_test_split, LeaveOneGroupOut # from sklearn.preprocessing import StandardScaler labels = ['lj', 'morse', # single minima 'soft', 'yukawa', 'wca', # repulsive 'dlvo', 'exp-well', # double minima 'step', 'csw', 'rssaw', # step potentials 'gaussian', 'hat', 'hertzian', # soft 'llano'] hard = [0, 1, 4] soft = [2, 3] core = [5, 6, 7, 8, 9] overlap = [10, 11, 12] def take_group(data, axis, group=[]): """ Extract a sub-section from an array based on matching given criteria. """ mask = np.argwhere(np.isin(data[:,axis], group)).ravel() test_set = np.take(data, mask, axis=0) train_set = np.delete(data, mask, axis=0) print("TRAIN: {} TEST: {}".format(np.unique(train_set[:,axis]), np.unique(test_set[:,axis]))) return test_set, train_set def main(path): """ """ names = ["pot_type", "pot_id", "density", "r", "phi", "avg_tcf", "err_tcf", "avg_dcf", "err_dcf", "avg_icf", "err_icf", "avg_grad_icf", "err_grad_icf", "fd_gr", "avg_br", "err_br"] np.loadtxt(path+'whole.csv', data, delimiter=',', header=names) assert len(names) == data.shape[1] hard_potentials, soft_potentials = take_group(data, 0, hard+core) print(hard_potentials.shape, soft_potentials.shape) hard_train, hard_test = train_test_split( hard_potentials, test_size=0.2, random_state=123) soft_train, soft_test = train_test_split(soft_potentials, test_size=0.2, random_state=123) whole_train = np.vstack((hard_train, soft_train)) whole_test = np.vstack((hard_test, soft_test)) np.savetxt(path+'random-train.csv', whole_train, delimiter=',', header=names) np.savetxt(path+'random-test.csv', whole_test, delimiter=',', header=names) train_size = min(hard_train.shape[0], soft_train.shape[0]) test_size = min(hard_test.shape[0], soft_test.shape[0]) np.savetxt(path+'hard-train.csv', hard_train[:train_size,:], delimiter=',', header=names) np.savetxt(path+'hard-test.csv', hard_test[:test_size,:], delimiter=',', header=names) np.savetxt(path+'soft-train.csv', soft_train[:train_size,:], delimiter=',', header=names) np.savetxt(path+'soft-test.csv', soft_test[:test_size,:], delimiter=',', header=names) density_test, density_train = take_group(data, 2, [0.8]) np.savetxt(path+'density-train.csv', density_train, delimiter=',', header=names) np.savetxt(path+'density-test.csv', density_test, delimiter=',', header=names) if __name__ == '__main__': path = sys.argv[1] main(path) <file_sep>/sim/test-multi.py import sys import os import re import espressomd import timeit import numpy as np from core import setup, initialise, sample, parse import signal # import matplotlib.pyplot as plt def main(output_path): dt = 0.005 temperature = 1.0 burn_steps = 2048 burn_iterations_max = 16 sampling_iterations = 1024 sampling_steps = 16 box_size = 20 density = 0.8 # Control the density n_part = int(density * (box_size**3.)) n_solv = n_part # box_size = np.power(n_part / rho, 1.0 / 3.0) print('Density={:.2f} \nNumber of Particles={} \nBox Size={:.1f}' .strip().format(density, n_part, box_size)) # Box setup system = espressomd.System(box_l=[box_size] * 3) system.cell_system.skin = 0.2 * 3.0 # Hardcode PRNG seed system.seed = 42 np.random.seed() # Setup Real Particles for i in range(n_part): system.part.add(id=i, pos=np.random.random(3) * system.box_l, type=0) for i in range(n_solv): system.part.add(id=i+n_part, pos=np.random.random(3) * system.box_l, type=1) lj_eps = 1.0 lj_sig = 1.0 system.non_bonded_inter[0, 0].lennard_jones.set_params( epsilon=lj_eps, sigma=lj_sig, cutoff=2.5, shift='auto') # Mixture of LJ particles system.non_bonded_inter[1, 0].lennard_jones.set_params( epsilon=lj_eps*1.1, sigma=lj_sig*0.75, cutoff=2.5, shift='auto') system.non_bonded_inter[1, 1].lennard_jones.set_params( epsilon=lj_eps, sigma=lj_sig*0.5, cutoff=1.5, shift='auto') # Disperse Particles to energy minimum initialise.disperse_energy(system, temperature, dt, n_types=2) # Integrate the system to warm up to specified temperature initialise.equilibrate_system(system, dt, temperature, burn_steps, burn_iterations_max) # Sample the RDF for the system rdf, r, sq, q, temp, t = sample.get_bulk(system, dt, sampling_iterations, sampling_steps) # save rdf f_rdf = os.path.join(output_path,'rdf_ss_wca_p{}_b{}_t{}.dat'.format( density, box_size, temperature)) if os.path.isfile(f_rdf): rdf_out = rdf else: rdf_out = np.vstack((r, rdf)) with open(f_rdf, 'ab') as f: np.savetxt(f, rdf_out) # save sq f_sq = os.path.join(output_path,'sq_ss_wca_p{}_b{}_t{}.dat'.format( density, box_size, temperature)) if os.path.isfile(f_sq): sq_out = sq else: sq_out = np.vstack((q, sq)) with open(f_sq, 'ab') as f: np.savetxt(f, sq_out) # save temp f_temp = os.path.join(output_path,'temp_ss_wca_p{}_b{}_t{}.dat'.format( density, box_size, temperature)) if os.path.isfile(f_temp): temp_old = np.loadtxt(f_temp) t_end = temp_old[0,-1] t += t_end + 1 else: pass with open(f_temp, 'ab') as f: t_out = np.column_stack((t, temp)) np.savetxt(f, t_out) if __name__ == "__main__": output_path = sys.argv[1] main(output_path) <file_sep>/sim/core/initialise.py from __future__ import print_function import espressomd import numpy as np from itertools import combinations_with_replacement as cmb def disperse_energy(syst, temp, timestep, n_types=1): """ This routine moves the particles via gradient descent to a local energy minimium. The parameters f_max, gamma and max_displacement are necessary to stop particles shooting off to infinity. The values have been taken from a sample script and are used without thought to their justification. """ print("\nDisperse Particles by Minimization of Energy\n") syst.time_step = timestep # Thermostat syst.thermostat.set_langevin(kT=temp, gamma=1.0, seed=123) n_part = len(syst.part.select()) syst.thermostat.suspend() types = range(n_types) comb = list(cmb(types, 2)) act_min_dist = np.zeros(len(comb)) for j in range(len(comb)): act_min_dist[j] = syst.analysis.min_dist( p1=[comb[j][0]], p2=[comb[j][1]]) energy = syst.analysis.energy()['non_bonded'] print("Before Minimization: Energy={:.3e}, Min Dist={}" .strip().format(energy, act_min_dist)) # Relax structure syst.integrator.set_steepest_descent( f_max=10., gamma=0.1, max_displacement=0.005) syst.integrator.run(2000) syst.integrator.set_vv() # remove force capping syst.force_cap = 0 for j in range(len(comb)): act_min_dist[j] = syst.analysis.min_dist( p1=[comb[j][0]], p2=[comb[j][1]]) energy = syst.analysis.energy()['non_bonded'] print("After Minimization: Energy={:.3e}, Min Dist={}" .strip().format(energy, act_min_dist)) # recover thermostat syst.thermostat.recover() # return min_dist pass def equilibrate_system(syst, timestep, final_temp, burn, iterations): """ The system is integrated using a small timestep such that the thermostat noise causes the system to warm-up. We define the convergence of this equilibration integration as the point at which the mean and standard deviation of the last three samples overlaps the target temperature. """ print("\nEquilibration\n") syst.time_step = timestep n_part = len(syst.part.select()) n_test = 5 eq_temp = np.full(n_test, np.nan) avg_temp = 0. err_temp = 0. syst.integrator.run(burn) temp = syst.analysis.energy()['kinetic'] / (1.5 * n_part) print("Initial Temperature after burn-in period = {:.3f}".format(temp)) i = 0 while np.abs(avg_temp - final_temp) > err_temp and i < iterations: syst.integrator.run(burn) kine_energy = syst.analysis.energy()['kinetic'] eq_temp[i % n_test] = kine_energy / (1.5 * n_part) avg_temp = np.nanmean(eq_temp) # can't have ddof = 1 err_temp = np.nanstd(eq_temp) / np.sqrt(min(i + 1, n_test)) if np.abs(avg_temp - final_temp) > err_temp: print("Equilibration not converged, Temperature = {:.3f} +/- {:.3f}" .format(avg_temp, err_temp)) np.roll(eq_temp, -1) i += 1 if i == iterations: print("\nSystem failed to equilibrate") print('\nTemperature at end of equilibration = {:.3f} +/- {:.3f}' .format(avg_temp, err_temp)) print('System time at end of equilibration {:.1f}' .format(syst.time)) <file_sep>/inputs/tables.py ''' Script for generating the input tables for the different potentials used. ''' import os import sys import numpy as np def main(output_path): r_min = 0.0 r_max = 3.0 dr = 0.01 r = np.arange(r_min, r_max, dr) lj(output_path, r) # single minima morse(output_path, r) soft(output_path, r) # repulsive yukawa(output_path, r) wca(output_path, r) dlvo(output_path, r) # double minima exp_well(output_path, r) step(output_path, r) # step potentials csw(output_path, r) rssaw(output_path, r) gaussian(output_path, r) # soft potentials hat(output_path, dr) hertzian(output_path, dr) # llano(output_path, dr) pass def lj(path, r): ptype = 'lj' energy = [0.65, 0.6, 0.55, 0.5] test_number = 0 r6 = np.zeros_like(r) r6[1:] = np.power(1. / r[1:], 6.) r6[0] = 2 * r6[1] - r6[2] r12 = np.power(r6, 2.) for p2 in energy: potential = 4 * p2 * (r12 - r6) save_table(path, ptype, test_number, r, potential) test_number += 1 def soft(path, r): ptype = 'soft' energy = [1.0, 0.6] exponent = [4.0, 6.0, 8.0, 10.0] test_number = 0 for p3 in energy: for p5 in exponent: potential = np.zeros_like(r) potential[1:] = p3 * (1. / r[1:])**p5 potential[0] = 2 * potential[1] - potential[2] save_table(path, ptype, test_number, r, potential) test_number += 1 def morse(path, r): ptype = 'morse' energy = [0.65, 0.6, 0.55] minimum = [1.0] alpha = [5.0, 9.0] test_number = 0 for p2 in energy: for p3 in minimum: for p4 in alpha: exp1 = np.exp(-2. * p4 * (r - p3)) exp2 = np.exp(-p4 * (r - p3)) potential = p2 * (exp1 - 2. * exp2) save_table(path, ptype, test_number, r, potential) test_number += 1 def yukawa(path, r): ptype = 'yukawa' alpha = [2., 4., 6.] kappa = [2.5, 3.5] delta = 0.8 test_number = 0 potential = np.zeros_like(r) for p2 in alpha: for p3 in kappa: potential[1:] = p2 * np.exp(-p3 * (r[1:] - delta)) / r[1:] potential[0] = 2. * potential[1] - potential[2] save_table(path, ptype, test_number, r, potential) test_number += 1 def wca(path, r): ptype = 'wca' energy = [1.0, 0.6] powers = [[50, 49], [12, 6]] test_number = 0 r_min = 0.0 potential = np.zeros_like(r) for i in np.arange(len(powers)): alpha = powers[i][0] beta = powers[i][1] r_max = np.power(alpha / beta, 1 / (alpha - beta)) rwca = np.arange(r_min, r_max, r[1]) rs = np.zeros_like(rwca) rh = np.zeros_like(rwca) rs[1:] = np.power(1. / rwca[1:], beta) rs[0] = 2 * rs[1] - rs[2] rh[1:] = rs[1:] * np.power(1 / rwca[1:], alpha - beta) rh[0] = 2 * rh[1] - rh[2] prefactor = alpha * np.power(alpha / beta, beta) for p2 in energy: potential[:len(rs)] = prefactor * p2 * (rh - rs) potential[:len(rs)] -= potential[len(rs)-1] save_table(path, ptype, test_number, r, potential) test_number += 1 def step(path, r): ptype = 'step' diameter = [.7] exponent = 12. energy = [1.0] kappa = [1.0, 3.0, 5.0, 7.0] sigma = [1.0, 1.5, 2.0] cutoff = 0.001 test_number = 0 for p2 in energy: for p4 in sigma: for p5 in kappa: phi_step = p2 / (1. + np.exp(2 * p5 * (r - p4))) phi_hard = np.zeros_like(r) phi_hard[1:] = np.power((1. / r[1:]), exponent) phi_hard[0] = 2. * phi_hard[1] - phi_hard[2] potential = phi_step + phi_hard save_table(path, ptype, test_number, r, potential) test_number += 1 def csw(path, r): ptype = 'csw' kappa = [15.0, 5.0] offset_r = [1.2, 1.6] # offset_r is scaling factor from sigma == 1 energy_r = [1.] energy_a = [2.0] delta_a = [0.1, 0.2] # delta_a is scaling factor from sigma offset_a = [2.] # offset_a is scaling factor from sigma test_number = 0 for p2 in energy_a: for p4 in kappa: for p5 in offset_r: for p6 in energy_r: for p7 in delta_a: for p8 in offset_a: phi_hard = np.zeros_like(r) phi_hard[1:] = np.power((1. / r[1:]), 12) phi_hard[0] = 2. * phi_hard[1] - phi_hard[2] phi_step = p2 / (1. + np.exp(p4 * (r - p5))) phi_gauss = p6 * \ np.exp(-0.5 * np.square((r - p8) / (p7))) potential = phi_step + phi_hard - phi_gauss save_table(path, ptype, test_number, r, potential) test_number += 1 def rssaw(path, r): ptype = 'rssaw' sigma1 = [0.8, 1.15, 1.5] sigma2 = [1.0, 1.35] lamda1 = [0.5] lamda2 = [0.3] test_number = 0 for p2 in lamda1: for p4 in lamda2: for p5 in sigma1: for p6 in sigma2: phi_hard = np.zeros_like(r) phi_hard[1:] = np.power((1. / r[1:]), 14) phi_hard[0] = 2. * phi_hard[1] - phi_hard[2] phi_step = p2 * np.tanh(10 * (r - p5)) phi_well = p4 * np.tanh(10 * (r - p6)) potential = phi_step + phi_hard - phi_well save_table(path, ptype, test_number, r, potential) test_number += 1 def dlvo(path, r): ptype = 'dlvo' energy = [0.185, 0.2, 0.215, 0.23, 0.245] test_number = 0 r4 = np.zeros_like(r) r4[1:] = np.power((1. / r[1:]), 4.) r4[0] = 2 * r4[1] - r4[2] r8 = np.square(r4) r12 = np.power(r4, 3.) for p3 in energy: potential = p3 * r12 - r8 + r4 save_table(path, ptype, test_number, r, potential) test_number += 1 def exp_well(path, r): ptype = 'exp-well' energy = [3.0, 5.0, 7.0] # 0.5 - 11.0 kappa = [10., 20., 30.] # 0.5 - 30.0 # kappa = np.arange(0.5, 30.0, 0.5).tolist() shift = 0.3 test_number = 0 r4 = np.power((1. / (r + shift)), 4.) r4[0] = 2 * r4[1] - r4[2] r8 = np.square(r4) r12 = np.power(r4, 3.) for p3 in energy: for p5 in kappa: rexp = np.exp(-p5 * np.power((r - 1. + shift), 4)) / (r + shift) rexp[0] = 2 * rexp[1] - rexp[2] potential = p3 * (r12 - r8) + rexp save_table(path, ptype, test_number, r, potential) test_number += 1 def gaussian(path, r): ptype = 'gaussian' energy = [4.0, 6.0, 8.0, 10.0] inv_sigma = [1.0, 1.5, 2.0] test_number = 0 for p3 in energy: for p2 in inv_sigma: potential = p3 * np.exp(-.5 * np.power((r * p2), 2)) save_table(path, ptype, test_number, r, potential) test_number += 1 def hat(path, dr): ptype = 'hat' force = [4.0, 6.0, 8.0, 10.0] cutoff = [2.0, 3.0] # don't make sigma too small test_number = 0 r_min = 0.0 samples = 4096 for p3 in force: for r_max in cutoff: r = np.linspace(r_min, r_max, samples) potential = p3 * (r - r_max) * ((r + r_max) / (2 * r_max) - 1.) save_table(path, ptype, test_number, r, potential) test_number += 1 def hertzian(path, dr): ptype = 'hertzian' energy = [4.0, 6.0, 8.0, 10.0] cutoff = [2.0, 3.0] # don't make sigma too small test_number = 0 r_min = 0.0 for p3 in energy: for r_max in cutoff: r = np.arange(r_min,r_max,dr) potential = p3 * np.power((1. - r / r_max), 2.5) save_table(path, ptype, test_number, r, potential) test_number += 1 def llano(path, dr): ptype = 'llano' energy = [2./3.] test_number = 0 r_min = 0.0 r_max = 2.5 r = np.arange(r_min,r_max,dr) r6 = np.zeros_like(r) r6[1:] = np.power(1. / r[1:], 6.) r6[0] = 2 * r6[1] - r6[2] r12 = np.power(r6, 2.) for p2 in energy: potential = 4 * p2 * (r12 - r6) save_table(path, ptype, test_number, r, potential) test_number += 1 def make_output(phi, r): """ shift and augement the potential to remove discontinuities """ force = - np.gradient(phi, r[1]) phi = phi - force[-1] * r[-1] phi = phi - phi[-1] # shift phi force = force - force[-1] output = np.vstack((r, phi, force)) return output def save_table(path, ptype, number, radius, field): labels = ['lj', 'morse', # single minima 'soft', 'yukawa', 'wca', # repulsive 'dlvo', 'exp-well', # double minima 'step', 'csw', 'rssaw', # step potentials 'gaussian', 'hat', 'hertzian', # soft 'llano'] output = make_output(field, radius) # ref = str(labels.index(ptype) + 1) ref = ptype index = format(number, "02") np.savetxt('{}input_{}_{}.dat'.format(path, ref, index), output) if __name__ == '__main__': output_path = sys.argv[1] main(output_path) <file_sep>/process/core/block.py import numpy as np import warnings def block_data(series, length): """ This function takes the data an combines it into blocks. Only works with powers of 2. """ return np.mean(series.reshape(-1, length, series.shape[-1]), 1) def block_transformation(series): """ Do a single step of fp block averaging. Parameters ---------- series : ndarray Things we want to average: e.g. squared displacements to calculate the mean squared displacement of a Brownian particle. Returns ------- blocked_series : ndarray an array of half the length of series with adjacent terms averaged Notes ----- Flyvbjerg & Peterson 1989, equation 20 """ n_steps = series.shape[0] if n_steps & 1: n_steps = n_steps - 1 indices = np.arange(0, n_steps, 2) blocked_series = (np.take(series, indices, axis=0) + np.take(series, indices + 1, axis=0)) / 2. return blocked_series def calculate_blocked_variances(series, npmin=4): """ Compute a series of blocks and variances. Parameters ---------- series : ndarray the thing we want to average: e.g. squared displacements for a Brownian random walk. npmin : int cutoff number of points to stop blocking Returns ------- output_var, var_stderr : ndarray The variance and stderr of the variance at each blocking level Notes ----- Flyvbjerg & Peterson suggest continuing blocking down to 2 points, but the last few blocks are very noisy, so we default to cutting off before that. """ n_steps = series.shape[0] def block_var(d, n): # see eq. 27 of FP paper return np.var(d, axis=0) / (n - 1) def stderr_var(n): # see eq. 27 of FP paper return np.sqrt(2. / (n - 1)) output_var = np.array([block_var(series, n_steps)]) # initialize var_stderr = np.array([stderr_var(n_steps)]) while n_steps > npmin: series = block_transformation(series) n_steps = series.shape[0] # TODO: precompute size of output_var and var_stderr from n_steps # rather than appending x = block_var(series, n_steps) y = stderr_var(n_steps) output_var = np.vstack((output_var, x)) var_stderr = np.append(var_stderr, y) return output_var, var_stderr def detect_fixed_point(fp_nvar, fp_sev, full_output=False): """ Find whether the block averages decorrelate the data series to a fixed point. Parameters ---------- fp_var: ndarray FP blocked variance fp_sev: ndarray FP standard error of the variance. Returns ------- best_var : float best estimate of the variance best_length : int best estimate of the block length converged : bool did the series converge to a fixed point? bounds : (int, int) only if full_output is True range of fp_var averaged to compute best_var Notes ----- Expects both fp_var and fp_sev will have been truncated to cut off points with an overly small n_p and correspondingly large standard error of the variance. """ n_trans = fp_nvar.shape[0] # number of block transformations and index n_samples = fp_nvar.shape[1] # number of variables left_index = np.zeros(n_samples, dtype=int) right_index = np.zeros(n_samples, dtype=int) best_index = np.zeros(n_samples, dtype=int) best_var = np.zeros(n_samples) best_length = 1 converged = np.zeros(n_samples, dtype=bool) for i in np.arange(n_samples): fp_var = fp_nvar[:, i] # Detect left edge for j in np.arange(n_trans) - 1: # ith point inside error bars of next point if np.abs(fp_var[j + 1] - fp_var[j]) < fp_var[j + 1] * fp_sev[j + 1]: left_index[i] = j break # Check right edge for k in np.arange(n_trans)[::-1]: if np.abs(fp_var[k] - fp_var[k - 1]) < fp_var[k - 1] * fp_sev[k - 1]: right_index[i] = k break # if search succeeds if (left_index[i] >= 0) and (right_index[i] >= 0) and (right_index[i] >= left_index[i]): best_index[i] = np.average(np.arange(left_index[i], right_index[i] + 1), weights=1. / fp_sev[left_index[i]:right_index[i] + 1]).astype(np.int) best_length = max(best_length, np.power(2, best_index[i])) converged[i] = True else: converged[i] = False # print(left_index) # print(best_index) # print(right_index) if full_output is True: return best_length, converged, (left_index, right_index) else: return best_length, converged def fp_block_length(data, conv_output=False): ''' Compute standard error using Flyvbjerg-Petersen blocking. Computes the standard error on the mean of a possibly correlated timeseries of measurements. Parameters ---------- data: ndarray data whose mean is to be calculated, and for which we need a standard error on the mean Returns ------- stderr : float Standard error on the mean of data Notes ----- Uses the technique described in <NAME> and <NAME>, "Error estimates on correlated data", J. Chem. Phys. 91, 461--466 (1989). section 3. ''' data = np.atleast_1d(data) if len(data.shape) > 2: raise ValueError("invalid dimensions, input 2d or 1d array") block_trans_var, block_trans_sev = calculate_blocked_variances(data) len_block, conv = detect_fixed_point( block_trans_var, block_trans_sev, False) if not np.any(conv): warnings.warn("Fixed point not found for all samples") if conv_output is True: return len_block, conv else: return len_block <file_sep>/sim/core/setup.py from __future__ import print_function import espressomd import numpy as np import argparse def setup_box(input_file, rho, box_l, n_test=0): """ Initialises the system based off an input file """ # Control the density n_part = int(rho * (box_l**3.)) # box_l = np.power(n_part / rho, 1.0 / 3.0) print('Potential={} \nDensity={:.2f} \nNumber of Particles={} \nBox Size={:.1f}' .strip().format(input_file, rho, n_part, box_l)) # Box setup syst = espressomd.System(box_l=[box_l] * 3) # Hardcode PRNG seed syst.seed = 42 # Setup Real Particles for i in range(n_part): syst.part.add(id=i, pos=np.random.random(3) * syst.box_l, type=0) bulk_potentials(syst, input_file) return syst def bulk_potentials(system, input_file): """ """ tables = np.loadtxt(input_file) system.force_cap = 0. # Hard coded # skin depth; 0.2 is common choice see pg 556 Frenkel & Smit, system.cell_system.skin = 0.2 * tables[0, -1] system.non_bonded_inter[0, 0].tabulated.set_params( min=tables[0, 0], max=tables[0, -1], energy=tables[1, :], force=tables[2, :]) <file_sep>/sim/test-coarse.py import sys import os import re import argparse import espressomd import timeit import numpy as np from core import setup, initialise, sample, parse def main(input_file, density, temperature, dr, dt, burn_steps, burn_iterations_max, box_size, sampling_steps, sampling_iterations, output_path): assert os.path.isdir(output_path), "Output Path Not Found {}".format(output_path) assert os.path.isfile(input_file), "Input File Not Found {}".format(input_file) # Setup Espresso Environment system = setup.setup_box(input_file, density, box_size) # Disperse Particles to energy minimum initialise.disperse_energy(system, temperature, dt) # Integrate the system to warm up to specified temperature initialise.equilibrate_system(system, dt, temperature, burn_steps, burn_iterations_max) # Sample the RDF for the system rdf, r, sq, q, temp, t = sample.get_bulk(system, dt, sampling_iterations, sampling_steps) # save the results _, approx_type, mix_type = input_file.split("_") mix_type, _ = mix_type.split(".") # save rdf f_rdf = os.path.join(output_path,'rdf_{}_{}_p{}_b{}_t{}.dat'.format( approx_type, mix_type, density, box_size, temperature)) if os.path.isfile(f_rdf): rdf_out = rdf else: rdf_out = np.vstack((r, rdf)) with open(f_rdf, 'ab') as f: np.savetxt(f, rdf_out) # save sq f_sq = os.path.join(output_path,'sq_{}_{}_p{}_b{}_t{}.dat'.format( approx_type, mix_type, density, box_size, temperature)) if os.path.isfile(f_sq): sq_out = sq else: sq_out = np.vstack((q, sq)) with open(f_sq, 'ab') as f: np.savetxt(f, sq_out) # save temp f_temp = os.path.join(output_path,'temp_{}_{}_p{}_b{}_t{}.dat'.format( approx_type, mix_type, density, box_size, temperature)) if os.path.isfile(f_temp): temp_old = np.loadtxt(f_temp) t_end = temp_old[0,-1] t += t_end + 1 else: pass with open(f_temp, 'ab') as f: t_out = np.column_stack((t, temp)) np.savetxt(f, t_out) if __name__ == "__main__": opt = parse.parse_input() pot_path = os.path.abspath(opt.table) output_path = os.path.abspath(opt.output) main(pot_path, opt.rho, opt.temp, opt.dr, opt.dt, opt.burn_steps, opt.burn_iter_max, opt.box_size, opt.bulk_steps, opt.bulk_iter, output_path) <file_sep>/learn/make_datasets.py import os import re import sys import numpy as np from tqdm import tqdm from sklearn.model_selection import train_test_split, LeaveOneGroupOut # from sklearn.preprocessing import StandardScaler labels = ['lj', 'morse', # single minima 'soft', 'yukawa', 'wca', # repulsive 'dlvo', 'exp-well', # double minima 'step', 'csw', 'rssaw', # step potentials 'gaussian', 'hat', 'hertzian', # soft 'llano'] hard = [0, 1, 4] soft = [2, 3] core = [5, 6, 7, 8, 9] overlap = [10, 11, 12] def get_data(directory): """ """ data = None print("Collecting together data\n") for dirpath, _, filenames in os.walk(directory): for file in tqdm(filenames): path_to_file = os.path.abspath(os.path.join(dirpath, file)) _, pot_type, pot_id, density, _, _ = file.split("_") test_case = np.loadtxt(path_to_file, delimiter=',') start = test_case.shape[0] - np.argmax(np.flip(np.isnan(test_case[:,-1]))) start_fg = test_case.shape[0] - np.argmax(np.flip(np.isnan(test_case[:,-1]))) test_case[:,-3] *= np.sqrt(int(float(density[1:]) * (20.**3.))) pot_type = labels.index(pot_type) * np.ones((test_case.shape[0])) pot_id = float(pot_id) * np.ones((test_case.shape[0])) density = float(density[1:]) * np.ones((test_case.shape[0])) output = np.column_stack((pot_type[start:],pot_id[start:],density[start:],test_case[start:,:])) if data is not None: data = np.vstack((data, output)) else: data = output return data def main(directory, path): """ """ data = get_data(directory) names = ["pot_type", "pot_id", "density", "r", "phi", "avg_tcf", "err_tcf", "avg_dcf", "err_dcf", "avg_icf", "err_icf", "avg_grad_icf", "err_grad_icf", "fd_gr", "avg_br", "err_br"] assert len(names) == data.shape[1] names = ','.join(names) np.savetxt(path+'whole.csv', data, delimiter=',', header=names) if __name__ == '__main__': directory = sys.argv[1] path = sys.argv[2] main(directory, path) <file_sep>/process/multi-potential.py import sys import re import os import numpy as np from core import block, transforms, parse import matplotlib import matplotlib.pyplot as plt from tensorflow import keras from tensorflow.python.keras.models import load_model from scipy.signal import savgol_filter, butter from scipy.optimize import curve_fit matplotlib.rcParams.update({'font.size': 12}) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' def backstrapolate(r, phi): assert len(r.shape) == len(phi.shape), "dimensions are not correct" cav = r.shape[0] - phi.shape[0] phi_ex = np.zeros_like(r) def polynom(r, a, b, c): return a * np.exp(b*r) + c popt, pcov = curve_fit(polynom, r[cav:cav+20], phi[:20]) phi_ex[cav:] = phi phi_ex[:cav] = polynom(r[:cav], *popt) return r, phi_ex def plot_funcs(r, avg_tcf, err_tcf, avg_dcf, err_dcf, avg_grad_icf, err_grad_icf, fd_gr,): """ plot some stuff """ mask_var = fd_gr.shape[0]- np.sum(np.isfinite(fd_gr)) mask_avg = np.argmax(avg_tcf + 1.> 1e-8) print(mask_avg, mask_var, r[mask_var]) mask = np.max((mask_avg, mask_var)) X_down = np.vstack((avg_tcf[mask:], avg_dcf[mask:], fd_gr[mask:], avg_grad_icf[mask:])).T # Get IBI potential phi_ibi = -np.log(avg_tcf[mask:] + 1.) # Get HNC potential phi_hnc = avg_tcf[mask:] - avg_dcf[mask:] + phi_ibi ## Get Non-Local Closure Potential non_local = load_model('learn/models/non-local-400.h5', compile=False) br_nla = non_local.predict(X_down[:,0:4]).ravel() phi_nla = phi_hnc + br_nla br_nla_s = savgol_filter(br_nla, window_length=21, polyorder=2, deriv=0, delta=r[1]-r[0]) phi_nla_s = phi_hnc + br_nla_s r, phi_ibi = backstrapolate(r, phi_ibi) r, phi_hnc = backstrapolate(r, phi_hnc) r, phi_nla_s = backstrapolate(r, phi_nla_s) r, phi_nla = backstrapolate(r, phi_nla) f_ibi = -np.gradient(phi_ibi, r[1]-r[0]) f_hnc = -np.gradient(phi_hnc, r[1]-r[0]) f_nla = -np.gradient(phi_nla, r[1]-r[0]) # f_nla_s = -np.gradient(phi_nla_s, r[1]-r[0]) # f_ibi = -savgol_filter(phi_ibi, window_length=31, polyorder=2, deriv=1, delta=r[1]-r[0]) # f_hnc = -savgol_filter(phi_hnc, window_length=31, polyorder=2, deriv=1, delta=r[1]-r[0]) f_nla_s = -savgol_filter(phi_nla_s, window_length=7, polyorder=2, deriv=1, delta=r[1]-r[0]) #Save the potentials output_path = "data/test/down/" r_cut_ind = np.argmin(r<3) # save phi mix_type = "lj-mix" file_ibi = os.path.join(output_path,'phi_ibi_{}.dat'.format(mix_type)) file_hnc = os.path.join(output_path,'phi_hnc_{}.dat'.format(mix_type)) file_nla = os.path.join(output_path,'phi_nla_{}.dat'.format(mix_type)) file_nla_n = os.path.join(output_path,'phi_nla_n_{}.dat'.format(mix_type)) out_ibi = np.vstack((r[:r_cut_ind], phi_ibi[:r_cut_ind], f_ibi[:r_cut_ind])) np.savetxt(file_ibi, out_ibi) out_hnc = np.vstack((r[:r_cut_ind], phi_hnc[:r_cut_ind], f_hnc[:r_cut_ind])) np.savetxt(file_hnc, out_hnc) out_nla = np.vstack((r[:r_cut_ind], phi_nla_s[:r_cut_ind], f_nla_s[:r_cut_ind])) np.savetxt(file_nla, out_nla) out_nla_n = np.vstack((r[:r_cut_ind], phi_nla[:r_cut_ind], f_nla[:r_cut_ind])) np.savetxt(file_nla_n, out_nla_n) # plot fig, axes = plt.subplots(2, 3, figsize=(18, 8)) # Plot g(r) axes[0, 0].plot(r, avg_tcf + 1) axes[0, 0].fill_between(r, avg_tcf + err_tcf + 1, avg_tcf - err_tcf + 1, alpha=0.3) axes[0, 0].plot((r[0],r[-1]), np.ones(2), '--', color="tab:blue") axes[0, 0].set_xlabel('r/$\sigma$') axes[0, 0].set_ylabel('$g(r)$') # Plot c(r) axes[0, 1].plot(r, avg_dcf, label='$c_{sw}(r)$') axes[0, 1].fill_between(r, avg_dcf + err_dcf, avg_dcf - err_dcf, alpha=0.2) axes[0, 1].plot((r[0],r[-1]), np.zeros(2), '--', color="tab:blue") axes[0, 1].set_xlabel('r/$\sigma$') axes[0, 1].set_ylabel('$c(r)$') axes[0, 1].legend() # plot y'(r) axes[1, 1].plot(r, avg_grad_icf) axes[1, 1].fill_between(r, avg_grad_icf + err_grad_icf, avg_grad_icf - err_grad_icf, alpha=0.2) axes[1, 1].set_xlabel('r/$\sigma$') axes[1, 1].set_ylabel('$\gamma\'(r)$') # plot b(r) axes[0, 2].plot(r, np.zeros_like(r), label="HNC") axes[0, 2].plot(r[mask:], br_nla, label="NLA") axes[0, 2].plot(r[mask:], br_nla_s, label="NLA-SG") axes[0, 2].set_xlabel('r/$\sigma$') axes[0, 2].set_ylabel('$b(r)$') axes[0, 2].legend() # Phi(r) axes[1, 2].plot(r,phi_ibi, label="IBI") axes[1, 2].plot(r,phi_hnc, label="HNC") axes[1, 2].plot(r,phi_nla, label="NLA", alpha=0.3) axes[1, 2].plot(r,phi_nla_s, label="NLA-SG") axes[1, 2].set_xlim((0,3)) axes[1, 2].set_ylim((-2,6)) axes[1, 2].set_xlabel('r/$\sigma$') axes[1, 2].set_ylabel('$\phi(r)$') axes[1, 2].legend() ## f(r) axes[1, 0].plot(r,f_ibi, label="IBI") axes[1, 0].plot(r,f_hnc, label="HNC") axes[1, 0].plot(r,f_nla, label="NLA", alpha=0.3) axes[1, 0].plot(r,f_nla_s, label="NLA-SG") # axes[1, 0].plot(r,f_nla_sg, '--', label="NLA-SG") axes[1, 0].set_xlim((0,3)) axes[1, 0].set_ylim((-20,50)) axes[1, 0].set_xlabel('r/$\sigma$') axes[1, 0].set_ylabel('$f(r)$') axes[1, 0].legend() fig.tight_layout() plt.show() return if __name__ == "__main__": input_size = 20. input_density = 0.8 input_temp = 1.0 rdf_path = sys.argv[1] sq_path = sys.argv[2] real = transforms.process_inputs(input_size, input_temp, input_density, "invert", rdf_path=rdf_path, sq_path=sq_path) plot_funcs(*real) plt.show() <file_sep>/sim/core/sample.py from __future__ import print_function import sys import os import re import espressomd import numpy as np import time import timeit def sec_to_str(sec): m, s = divmod(sec, 60) h, m = divmod(m, 60) return u"{}:{:02d}:{:02d}".format(int(h),int(m),int(s)) def ProgressBar(it, refresh=10): """ refresh=10: refresh the time estimate at least every 10 sec. """ L = len(it) steps = {x:y for x, y in zip(np.linspace(0,L, min(100,L), endpoint=False, dtype=int), np.linspace(0,100,min(100,L), endpoint=False, dtype=int))} block = u"\u2588" partial_block = ["", u"\u258E",u"\u258C",u"\u258A"] # quarter and half block chars start = now = time.time() timings = " [0:00:00, -:--:--]" for nn,item in enumerate(it): if nn in steps: done = block*int(steps[nn]/4.0) + partial_block[int(steps[nn]%4)] todo = " "*(25-len(done)) bar = u"{}% |{}{}|".format(steps[nn], done, todo) if nn>0: now = time.time() timings = " [{}, {}]".format(sec_to_str(now-start), sec_to_str((now-start)*(L/float(nn)-1))) sys.stdout.write("\r"+bar+timings) sys.stdout.flush() elif time.time()-now > refresh: now = time.time() timings = " [{}, {}]".format(sec_to_str(now-start), sec_to_str((now-start)*(L/float(nn)-1))) sys.stdout.write("\r"+bar+timings) sys.stdout.flush() yield item bar = u"{:d}% |{}|".format(100, block*25) timings = " [{}, 0:00:00]\n".format(sec_to_str(time.time()-start)) sys.stdout.write("\r"+bar+timings) sys.stdout.flush() def get_bulk(syst, timestep, iterations, steps, type_part=[0]): """ This function samples the radial distribution function between the two lists of particle types a and b. The size of the radius over which we sample is the minimum of the box length divided by two or five times the cutoff radius of the potential. We also use the inbuild structure factor scheme in order to calculate s(q) """ print("\nSampling\n") start = timeit.default_timer() n_part = len(syst.part.select()) r_max = syst.box_l[0] * 0.5 bins = 1024 dr = r_max / bins r_min = dr / 2. r_max = r_max + r_min syst.time_step = timestep rdf_data = np.zeros((iterations, bins)) sq_data = np.zeros((iterations, bins)) temp = np.zeros(iterations) time = np.zeros(iterations) time_int = 0. time_sq = 0. time_rdf = 0. try: for i in ProgressBar(range(1, iterations + 1), 40): start_int = timeit.default_timer() syst.integrator.run(steps) start_rdf = timeit.default_timer() time_int += start_rdf - start_int r, rdf = syst.analysis.rdf(rdf_type="rdf", type_list_a=type_part, type_list_b=type_part, r_min=r_min, r_max=r_max, r_bins=bins) start_sq = timeit.default_timer() time_rdf += start_sq - start_rdf # q, s_q = syst.analysis.structure_factor_uniform( q, s_q = syst.analysis.structure_factor_fast( # q, s_q = syst.analysis.structure_factor( sf_types=type_part, sf_order=bins) # sf_types=type_part, sf_order=order) time_sq += timeit.default_timer() - start_sq sq_data[i - 1, :] = s_q rdf_data[i - 1, :] = rdf temp[i - 1] = syst.analysis.energy()['kinetic'] / (1.5 * n_part) time[i - 1] = syst.time except KeyboardInterrupt: pass tot = time_int + time_rdf + time_sq print('\nTotal Time: {}, Split: Integration- {:.2f}, RDF- {:.2f}, SQ- {:.2f}'.format(sec_to_str(tot),time_int/tot, time_rdf/tot, time_sq/tot)) return rdf_data, r, sq_data, q, temp, time - time[0] def get_phi(syst, radius, type_a=0, type_b=0): """ This Function clears the system and then places particles individually at the sampling points so that we end up with a potential function phi(r) that has the same discritisation as our correlation functions g(r) and c(r). """ print("\nSampling Phi\n") # Remove Particles syst.part.clear() bins = len(radius) # Place particles and measure interaction energy centre = (np.array([0.5, 0.5, 0.5]) * syst.box_l) phi = np.zeros_like(radius) for i in range(0, bins - 1): syst.part.add(pos=centre, id=1, type=type_a) syst.part.add(pos=centre + (radius[i], 0.0, 0.0), id=2, type=type_b) energies = syst.analysis.energy() # phi[i] = energies['total'] - energies['kinetic'] phi[i] = energies['non_bonded'] syst.part.clear() # syst.part[2].remove() return phi <file_sep>/process/process.py from __future__ import print_function import sys import re import os import numpy as np from core import transforms, parse from tqdm import tqdm if __name__ == "__main__": filename = sys.argv[1] pass_path = sys.argv[2] fail_path = sys.argv[3] with open(filename) as f: lines = f.read().splitlines() for line in tqdm(lines): # for line in lines: opt = parse.parse_input(line) raw_path = opt.output _, pot_type, pot_number = opt.table.split("_") pot_number = re.findall('\d+', pot_number)[-1] input_size = opt.box_size input_density = opt.rho input_temp = opt.temp n_part = int(input_density * (input_size**3.)) temp_path = '{}temp_{}_{}_p{}_n{}_t{}.dat'.format( raw_path, pot_type, pot_number, input_density, n_part, input_temp) rdf_path = '{}rdf_{}_{}_p{}_n{}_t{}.dat'.format( raw_path, pot_type, pot_number, input_density, n_part, input_temp) sq_path = '{}sq_{}_{}_p{}_n{}_t{}.dat'.format( raw_path, pot_type, pot_number, input_density, n_part, input_temp) phi_path = '{}phi_{}_{}.dat'.format(raw_path, pot_type, pot_number) passed, data = transforms.process_inputs(input_size, input_temp, input_density, "process", rdf_path=rdf_path, sq_path=sq_path, phi_path=phi_path, temp_path=temp_path) output = np.vstack(data).T names = ["r", "phi", "avg_tcf", "err_tcf", "avg_dcf", "err_dcf", "avg_icf", "err_icf", "avg_grad_icf", "err_grad_icf", "fd_gr", "avg_br", "err_br"] assert len(names) == output.shape[1], "{} {}".format(len(names), output.shape) names = ','.join(names) if passed: np.savetxt('{}processed_{}_{}_p{}_n{}_t{}.csv'.format( pass_path, pot_type, pot_number, input_density, n_part, input_temp), output, delimiter=',', header=names) else: np.savetxt('{}processed_{}_{}_p{}_n{}_t{}.csv'.format( fail_path, pot_type, pot_number, input_density, n_part, input_temp), output, delimiter=',', header=names) <file_sep>/inputs/system.py import os import re import sys import itertools def file_paths(directory): for dirpath, _, filenames in os.walk(directory): for f in filenames: # yield os.path.abspath(os.path.join(dirpath, f)) yield os.path.join(dirpath, f) def main(pot_path, raw_path): tables = file_paths(pot_path) rho = [0.4, 0.5, 0.6, 0.7, 0.8] temp = [1.] dt = [0.005] dr = [0.02] box_size = [20] bulk_steps = [16] bulk_iter = [1024] burn_steps = [2048] burn_iter_max = [16] comb = itertools.product(tables, rho, temp, dt, dr, box_size, bulk_steps, bulk_iter, burn_steps, burn_iter_max) outfilename = 'inputs.txt' with open(outfilename, 'w') as f: for li in comb: f.write(('--table {} --rho {} --temp {} --dt {} --dr {} ' '--box_size {} --bulk_steps {} --bulk_iter {} ' '--burn_steps {} --burn_iter_max {} --output {}\n').format(*li, raw_path)) if __name__ == '__main__': pot_path = sys.argv[1] raw_path = sys.argv[2] main(pot_path, raw_path) <file_sep>/process/core/transforms.py import numpy as np from scipy.fftpack import dst, idst from core import block from scipy.signal import savgol_filter def hr_to_cr(bins, rho, data, radius, error=None, axis=1): """ This function takes h(r) and uses the OZ equation to find c(r) this is done via a 3D fourier transform that is detailed in LADO paper. The transform is the the DST of f(r)*r. The function is rearranged in fourier space to find c(k) and then the inverse transform is taken to get back to c(r). """ # setup scales dk = np.pi / radius[-1] k = dk * np.arange(1, bins + 1, dtype=np.float) # Transform into fourier components FT = dst(data * radius[0:bins], type=1, axis=axis) normalisation = 2 * np.pi * radius[0] / k H_k = normalisation * FT # Rearrange to find direct correlation function C_k = H_k / (1 + rho * H_k) # # Transform back to real space iFT = idst(C_k * k, type=1) normalisation = k[-1] / (4 * np.pi**2 * radius[0:bins]) / (bins + 1) c_r = normalisation * iFT return c_r, radius def hr_to_sq(bins, rho, data, radius, axis=1): """ this function takes h(r) and takes the fourier transform to find s(k) """ # setup scales dk = np.pi/radius[-1] k = dk * np.arange(1, bins + 1, dtype=np.float) # Transform into fourier components FT = dst(data * radius[0:bins], type=1, axis=axis) # radius[0] is dr as the bins are spaced equally. normalisation = 2 * np.pi * radius[0] / k H_k = normalisation * FT S_k = 1 + rho * H_k return S_k, k def sq_to_hr(bins, rho, S_k, k, axis=1): """ Takes the structure factor s(q) and computes the real space total correlation function h(r) """ # setup scales dr = np.pi / (k[0] * bins) radius = dr * np.arange(1, bins + 1, dtype=np.float) # Rearrange to find total correlation function from structure factor H_k = (S_k - 1.) / rho # # Transform back to real space iFT = idst(H_k * k[:bins], type=1, axis=axis) normalisation = bins * k[0] / (4 * np.pi**2 * radius) / (bins + 1) h_r = normalisation * iFT return h_r, radius def sq_to_cr(bins, rho, S_k, k, axis=1): """ Takes the structure factor s(q) and computes the direct correlation function in real space c(r) """ # setup scales dr = np.pi / (bins * k[0]) radius = dr * np.arange(1, bins + 1, dtype=np.float) # Rearrange to find direct correlation function from structure factor # C_k = (S_k-1.)/(S_k) # 1.-(1./S_k) what is better C_k = (S_k - 1.) / (rho * S_k) # # Transform back to real space iFT = idst(k[:bins] * C_k, type=1, axis=axis) normalisation = bins * k[0] / (4 * np.pi**2 * radius) / (bins + 1) c_r = normalisation * iFT return c_r, radius def sq_and_hr_to_cr(bins, rho, hr, r, S_k, k, axis=1): """ Takes the structure factor s(q) and computes the direct correlation function in real space c(r) """ # setup scales dr = np.pi / (bins * k[0]) radius = dr * np.arange(1, bins + 1, dtype=np.float) assert(np.all(np.abs(radius-r)<1e-12)) iFT = idst(k[:bins] * np.square(S_k - 1.)/(rho * S_k), type=1, axis=axis) cr = hr - iFT return cr def smooth_function(f): """ five point smoothing as detailed on page 204 of Computer Simulation of Liquids. """ g = np.zeros_like(f) g[:, 0] = 1. / 70. * (69 * f[:, 0] + 4 * f[:, 1] - 6 * f[:, 2] + 4 * f[:, 3] - f[:, 4]) g[:, 1] = 1. / 35. * (2 * f[:, 0] + 27 * f[:, 1] + 12 * f[:, 2] - 8 * f[:, 3] + 2 * f[:, 4]) g[:, -2] = 1. / 35. * (2 * f[:, -1] + 27 * f[:, -2] + 12 * f[:, -4] - 8 * f[:, -4] + 2 * f[:, -5]) g[:, -1] = 1. / 70. * (69 * f[:, -1] + 4 * f[:, -2] - 6 * f[:, -3] + 4 * f[:, -4] - f[:, -5]) for i in np.arange(2, f.shape[1] - 2): g[:, i] = 1. / 35. * (-3 * f[:, i - 2] + 12 * f[:, i - 1] + 17 * f[:, i] + 12 * f[:, i + 1] - 3 * f[:, i + 2]) return g def process_inputs(box_size, temp, input_density, output="process", **paths): """ """ if output == "invert": assert len(paths) == 2, "rdf_path and sq_path must be provided" elif output == "plot": assert len(paths) == 3, "rdf_path, sq_path and phi_path must be provided" elif output == "process": assert len(paths) == 4, "rdf_path, sq_path, phi_path and temp_path must be provided" else: raise ValueError("Unknown output given - direct/plot/process") n_part = int(input_density * (box_size**3.)) density = n_part / (box_size**3.) rdf = np.loadtxt(paths.get('rdf_path')) sq = np.loadtxt(paths.get('sq_path')) r = rdf[0, :] r_bins = len(r) tcf = rdf[1:, :] - 1. q = sq[0, :] sq = sq[1:, :] # Find block size to remove correlations block_size_tcf = block.fp_block_length(tcf) block_size_sq = block.fp_block_length(sq) block_size = np.max((block_size_tcf, block_size_sq)) # print("number of observations is {}, \nblock size is {}. \npercent {}%.".format(rdf.shape[0]-1, block_size, block_size/rdf.shape[0]*100)) # block_size = 256 block_tcf = block.block_data(tcf, block_size) block_sq = block.block_data(sq, block_size) # TCF avg_tcf = np.mean(block_tcf, axis=0) err_tcf = np.sqrt(np.var(block_tcf, axis=0, ddof=1) / block_tcf.shape[0]) fd_gr = np.var(block_tcf, axis=0, ddof=1)/(avg_tcf+1.) mask = np.where(np.isfinite(fd_gr)) fd_gr_sg = np.copy(fd_gr) * np.sqrt(n_part) fd_gr_sg[mask] = savgol_filter(fd_gr[mask], window_length=9, polyorder=1, deriv=0, delta=r[1]-r[0]) # s(q) avg_sq = np.mean(block_sq, axis=0) err_sq = np.sqrt(np.var(block_sq, axis=0, ddof=1) / block_sq.shape[0]) # s(q) from fft sq_fft, q_fft = hr_to_sq(r_bins, density, block_tcf, r) assert np.all(np.abs(q-q_fft)<1e-10), "The fft and sq wave-vectors do not match" avg_sq_fft = np.mean(sq_fft, axis=0) err_sq_fft = np.sqrt(np.var(sq_fft, axis=0, ddof=1) / sq_fft.shape[0]) # Switching function w(q) peak = np.median(np.argmax(block_sq.T > 0.75*np.max(block_sq, axis=1), axis=0)).astype(int) after = len(q_fft) - peak switch = (1 + np.cbrt(np.cos(np.pi * q[:peak] / q[peak]))) / 2. switch = np.pad(switch, (0, after), 'constant', constant_values=(0)) # Corrected s(q) using switch sq_switch = switch * block_sq + (1. - switch) * sq_fft avg_sq_switch = np.mean(sq_switch, axis=0) err_sq_switch = np.sqrt(np.var(sq_switch, axis=0, ddof=1) / sq_switch.shape[0]) ## Evaluate c(r) # evaluate c(r) from corrected s(q) dcf_swtch, r_swtch = sq_to_cr(r_bins, density, sq_switch, q_fft) avg_dcf = np.mean(dcf_swtch, axis=0) err_dcf = np.sqrt(np.var(dcf_swtch, axis=0, ddof=1) / dcf_swtch.shape[0]) # # c(r) by fourier inversion of just convolved term for comparision # dcf_both = transforms.sq_and_hr_to_cr(r_bins, input_density, block_tcf, r, block_sq, q) # avg_dcf_both = np.mean(dcf_both, axis=0) # err_dcf_both = np.sqrt(np.var(dcf_both, axis=0, ddof=1) / dcf_both.shape[0]) ## Evaluate y'(r) block_icf = block_tcf - dcf_swtch avg_icf = np.mean(block_icf, axis=0) err_icf = np.sqrt(np.var(block_icf, axis=0, ddof=1) / block_icf.shape[0]) r_peak = r[np.argmax(block_tcf, axis=1)] grad_icf = np.gradient(block_icf.T*r_peak, r, axis=0).T avg_grad_icf = np.mean(grad_icf, axis=0) err_grad_icf = np.sqrt(np.var(grad_icf, axis=0, ddof=1) / block_icf.shape[0]) # signs = np.where(np.sign(avg_tcf[:-1]) != np.sign(avg_tcf[1:]))[0] + 1 if output == "plot": # evaluate c(r) from h(r) dcf_fft, _ = hr_to_cr(r_bins, density, block_tcf, r) avg_dcf_fft = np.mean(dcf_fft, axis=0) err_dcf_fft = np.sqrt(np.var(dcf_fft, axis=0, ddof=1) / dcf_fft.shape[0]) # evaluate c(r) from s(q) dcf_dir, _ = sq_to_cr(r_bins, density, block_sq, q) avg_dcf_dir = np.mean(dcf_dir, axis=0) err_dcf_dir = np.sqrt(np.var(dcf_dir, axis=0, ddof=1) / dcf_dir.shape[0]) ## Evaluate B(r) if output == "invert": return (r, avg_tcf, err_tcf, avg_dcf, err_dcf, avg_grad_icf, err_grad_icf, fd_gr_sg,) phi = np.loadtxt(paths.get('phi_path')) assert np.all(np.abs(r-phi[0,:])<1e-10), "the rdf and phi radii do not match" phi = phi[1,:] ind = np.median(np.argmax(block_tcf + 1. > 0.01, axis=1)).astype(int) block_br = np.log((block_tcf[:,ind:] + 1.)) + np.repeat(phi[ind:].reshape(-1,1), block_tcf.shape[0], axis=1).T- block_tcf[:,ind:] + dcf_swtch[:,ind:] avg_br = np.mean(block_br, axis=0) err_br = np.sqrt(np.var(block_br, axis=0, ddof=1) / block_br.shape[0]) if output == "plot": return (r, phi, avg_tcf, err_tcf, fd_gr, fd_gr_sg, avg_dcf, err_dcf, avg_icf, err_icf, avg_grad_icf, err_grad_icf, avg_dcf_dir, err_dcf_dir, avg_dcf_fft, err_dcf_fft, avg_br, err_br), \ (q, switch, avg_sq, err_sq, avg_sq_fft, err_sq_fft, avg_sq_switch, err_sq_switch, block_sq) else: avg_br = np.pad(avg_br, (ind,0), "constant", constant_values=np.NaN) err_br = np.pad(err_br, (ind,0), "constant", constant_values=np.NaN) # Check if data satifies our cleaning heuristics T = np.loadtxt(paths.get('temp_path'))[:,1] block_T = block.block_data(T.reshape((-1,1)), block_size) err = np.std(block_T) res = np.abs(np.mean(block_T - temp)) if res > err: passed = False elif avg_sq_switch[0] > 1.0: passed = False elif np.max(avg_sq) > 2.8: passed = False elif np.max(avg_sq_fft) > 2.8: passed = False else: passed = True return passed, (r, phi, avg_tcf, err_tcf, avg_dcf, err_dcf, avg_icf, err_icf, avg_grad_icf, err_grad_icf, fd_gr_sg, avg_br, err_br) <file_sep>/README.md # Closure Machine Learning to infer improved closure relationships for the Ornstein-Zernike equation The following collections of code were used to first generate then analyse data on the structures of simple liquids. The data was generated by performing forward molecular dynamics simulations for specified potentials. From this the radial distribution function and then the direct correlation function were extracted. This data was then used as an input for the inverse problem of solving to find the interaction potential given structural infomation about the system. Various machine learning algorithms were applied in order to do this. # Instructions for local use: * Install comprhys/espresso.git * Run tables.py to generate the tables * Run system.py to build the input file * Use input="`awk "NR==<row>" <input_file>`" to grab a row from the input file * Run bulk.py to get the bulk properties ## Cite this work That work is availiable on arxiv here: [Coarse-graining and designing liquids with the Ornstein-Zernike equation and machine learnt closures](https://arxiv.org/abs/2004.09114) ## Neurips Workshop An early abstract for this work was published as a [workshop submission](https://ml4physicalsciences.github.io/files/NeurIPS_ML4PS_2019_33.pdf) at the Neurips Machine Learning for Physical Sciences Workshop. Since this additional work has been carried out exploring the problem in more depth. The notebooks here have been updated to reflect the more recent work not as it stood at the time of the workshop submission.
d674452066702f9d83cc24858bbda16760f288f1
[ "Markdown", "Python" ]
17
Python
CompRhys/ornstein-zernike
ed17e8aa57a0a470752eb440137b7b527adcce27
7a5afad2780cb89d85d1656f9399f0cd580a5842
refs/heads/master
<repo_name>Jianwei-Wang/learning-python<file_sep>/net/tcpClient.py from socket import * HOST = '192.168.127.12' PORT = 54321 BUFSIZE = 1024 ADDR = HOST, PORT cs = socket(AF_INET, SOCK_STREAM) cs.connect(ADDR) while True: data = raw_input('> ') if not data: break cs.send(data) data = cs.recv(BUFSIZE) if not data: break print data cs.close() <file_sep>/net/udpClient.py from socket import * HOST = '192.168.3.11' PORT = 54321 BUFSIZE = 1024 ADDR = (HOST, PORT) cs = socket(AF_INET, SOCK_DGRAM) while True: data = raw_input('> ') if not data: break cs.sendto(data, ADDR) data, ADDR = cs.recvfrom(BUFSIZE) if not data: break print data cs.close() <file_sep>/ex34.py animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus'] print "The animal at 1 is the %dst animal and is a %s" % (1 + 1, animals[1]) print "The 3st animal is at %d and is a %s" % (3 - 1, animals[3 - 1]) print "The 1st animal is at %d and is a %s" % (1 - 1, animals[1 - 1]) print "The animal at 3 is the %dst animal and is a %s" % (3 + 1, animals[3]) print "The 5st animal is at %d and is a %s" % (5 - 1, animals[5 - 1]) print "The animal at 2 is the %dst animal and is a %s" % (2 + 1, animals[2]) print "The 6st animal is at %d and is a %s" % (6 - 1, animals[6 - 1]) print "The animal at 4 is the %dst animal and is a %s" % (4 + 1, animals[4]) <file_sep>/project-01/a.py import sys print "%s" %sys.stdin <file_sep>/ex17.py from sys import argv from os.path import exists script, file_from, file_to = argv print "Copying from %s to %s" % (file_from, file_to) input = open(file_from); indata = input.read() print "The input file is %d bytes long" % len(indata) print "Does the output file exist? %r" % exists(file_to) print "Ready, hit RETURN to containue, Ctrl-C to abort." raw_input() output = open(file_to, 'w') output.write(indata) print "Alright, all done." output.close() input.close() <file_sep>/ex25_test.py import ex25 #print break_words("djsafauroew fj dklasj jfdl ajsfl ldj ls") #print sort_words("dflajfkld f falj dlsa lj lfsald jfla") #print_first_word([3, 4, 5, 6, 7]) #print_last_word([3, 4, 5, 6, 7]) #print sort_sentence("dflajfkld f falj dlsa lj lfsald jfla") ex25.print_first_and_last("dflajfkld f falj dlsa lj lfsald jfla") ex25.print_first_and_last_sorted("dflajfkld f falj dlsa lj lfsald jfla") help(ex25.break_words) <file_sep>/ex42.py from sys import exit from random import randint class Game(object): def __init__(self, start): self.quips = [ "You died. You kinda suck at this.", "Your mom would be proud. If she were smarter.", "Such a luser.", "I have a small puppy that's better at this." ] self.start = start def play(self): next = self.start while True: print "\n--------" room = getattr(self, next) next = room() def death(self): print self.quips[randint(0, len(self.quips) - 1)] exit(1) def central_corridor(self): print 'In central_corridor function.' action = raw_input('> ') if action == '1': return 'death' elif action == '2': return 'death' elif action == '8': return 'laser_weapon_armory' else: print "DOES NOT COMPUTE!" return 'central_corridor' def laser_weapon_armory(self): print 'In laser_weapon_armory function.' action = raw_input('> ') if action == '8': return 'the_bridge' else: return 'death' def the_bridge(self): print 'In the bridge function.' action = raw_input('> ') if action == '1': return 'death' elif action == '8': return 'escape_pod' else: print "DOES NOT COMPUTE!" return 'the_bridge' def escape_pod(self): print 'In the escape_pod function' action = raw_input('> ') if action == '8': print "time. You won!" exit(0) else: return 'death' a_game = Game("central_corridor") a_game.play() <file_sep>/net/udpServer.py from socket import * from time import ctime HOST = '172.16.58.3' PORT = 54321 BUFSIZE = 1024 ADDR = HOST, PORT ss = socket(AF_INET, SOCK_DGRAM) ss.bind(ADDR) while True: print 'Waiting for message...' data, addr = ss.recvfrom(BUFSIZE) ss.sendto('[%s] %s' % (ctime(), data), addr) print '...received from and returned to:', addr ss.close() <file_sep>/project-02/sun.py from urllib import urlopen from reportlab.lib import colors from reportlab.graphics.shapes import * from reportlab.graphics.charts.lineplots import LinePlot from reportlab.graphics import renderPDF URL = "ftp://wangjw:[email protected]/ftp_server/data.txt" drawing = Drawing(400, 200) data = [] for line in urlopen(URL).readlines(): if not line.isspace() and not line[0] in '#:': data.append([float(n) for n in line.split()]) pred = [row[2] for row in data] high = [row[3] for row in data] low = [row[4] for row in data] rad_pred = [row[5] for row in data] rad_high = [row[6] for row in data] rad_low = [row[7] for row in data] times = [row[0] + row[1] / 12.0 for row in data] lp = LinePlot() lp.x = 50 lp.y = 50 lp.height = 125 lp.width = 300 lp.data = [zip(times, pred), zip(times, high), zip(times, low), \ zip(times, rad_pred), zip(times, rad_high), zip(times, rad_low)] lp.lines[0].strokeColor = colors.blue lp.lines[1].strokeColor = colors.red lp.lines[2].strokeColor = colors.green lp.lines[3].strokeColor = colors.yellow lp.lines[4].strokeColor = colors.black lp.lines[5].strokeColor = colors.brown drawing.add(lp) drawing.add(String(250, 150, 'Sunspots', fontSize = 14, fillColor = colors.red)) renderPDF.drawToFile(drawing, 'report2.pdf', 'Sunspots') <file_sep>/test/test1.py class Dispatcher: def unknown(self, cmd): print 'Unknown command: "%s"' % cmd def dispatch(self, line): if not line.strip(): return parts = line.split(' ', 1) try: line = parts[1].strip() except IndexError: line = '' cmd = 'do_' + parts[0] method = getattr(self, cmd, None) print method class Room(Dispatcher): def do_aaa(self): pass def do_bbb(self): pass d = Room() d.dispatch('aaa') d.dispatch('aaa ') d.dispatch('bbb') d.dispatch('bbb ') <file_sep>/net/tcpServer.py from socket import * from time import ctime HOST = '' PORT = 54321 BUFSIZE = 1024 ADDR = (HOST, PORT) ss = socket(AF_INET, SOCK_STREAM) ss.bind(ADDR) ss.listen(5) while True: print 'Waiting for connection...' cs, addr = ss.accept() print '...connected from:', addr while True: data = cs.recv(BUFSIZE) if not data: break cs.send('[%s] %s' % (ctime(), data)) cs.close() ss.close()
35f200bb6463d87fc9125c2d6a7b6ce73b00c105
[ "Python" ]
11
Python
Jianwei-Wang/learning-python
17017443a70f9b3655c70cf0628e4eef3e68bf3b
074e8b28fb482450353d6bab5f8d0d6f91e81863
refs/heads/master
<repo_name>danielgilroy/TerminalChat<file_sep>/chat_server/src/server_utils.c #include "server_utils.h" size_t prepare_client_message(char *client_message, ssize_t *recv_status){ //Replace ending \n with \0 or ending \r\n with \0\0 if they exist for(size_t i = 0; i < MESSAGE_SIZE; i++){ if(client_message[i] == MESSAGE_END || client_message[i] == '\0'){ return i + 1; }else if(client_message[i] == '\n'){ client_message[i] = '\0'; return i + 1; }else if(client_message[i] == '\r'){ client_message[i] = '\0'; client_message[i + 1] = '\0'; return i + 2; } } //Nul terminate end of message if no ending characters were found client_message[*recv_status] = '\0'; (*recv_status)++; return (size_t) (*recv_status); } char *add_username_to_message(const char *message, const char *username, const char *postfix){ //NOTE: Calling function must call free on the allocated memory size_t length = 1 + USERNAME_SIZE + strlen(postfix) + MESSAGE_SIZE + 1; char *message_result = calloc(length, sizeof(char)); if(message_result == NULL){ fprintf(stderr, "Error allocating memory"); exit(EXIT_FAILURE); } //Add a control character to start of message so we know when it's a new message message_result[0] = MESSAGE_START; message_result[1] = '\0'; strncat(message_result, username, length); strncat(message_result, postfix, length); strncat(message_result, message, length); message_result[length - 1] = '\0'; //Ensure NULL termination return message_result; } ssize_t send_message(int socket, const char *message, size_t message_length){ ssize_t bytes_sent = 0; int tries = 24; while(message_length > 0){ bytes_sent = send(socket, message, message_length, 0); if(bytes_sent == -1){ if(bytes_sent == EWOULDBLOCK || bytes_sent == EAGAIN){ //Wait for send buffer to have available space //This essentially replicates a blocking send so a time out is added if(tries){ struct timespec wait_time = {0, 125000000L}; //0.125 seconds nanosleep(&wait_time, NULL); tries--; }else{ //Number of tries exceeded: 24 tries * 0.125 seconds = 3 seconds total wait fprintf(stderr, "Sending message to socket %d has timed out\n", socket); return bytes_sent; } }else{ fprintf(stderr, "Error sending message to socket %d: %s\n", socket, strerror(errno)); return bytes_sent; } }else{ message += bytes_sent; //Point to the remaining portion that was not sent message_length -= bytes_sent; //Calculate the remaining bytes to be sent } } return bytes_sent; } ssize_t send_message_to_all(int room_id, const char *message, size_t message_length){ //Prevent messages from being sent to everyone in the lobby room if(room_id == LOBBY_ROOM_ID){ return -1; } ssize_t status = 0; table_entry_t *user; for(user = active_users[room_id]; user != NULL; user = user->hh.next){ status = send_message(user->socket_fd, message, message_length); } return status; } void get_username_and_passwords(int cmd_length, char *client_message, char **new_name, char **password, char **password2){ if(new_name == NULL){ return; } //Skip over command in client's message *new_name = client_message + cmd_length; //Force the first letter to be uppercase (*new_name)[0] = toupper((*new_name)[0]); if(password == NULL){return;} //Calling function doesn't want password //Check if the user entered a password *password = memchr(*new_name, ' ', USERNAME_SIZE); if(*password){ //Null terminate username and get pointer to password (*password)[0] = '\0'; (*password)++; if(password2 == NULL){return;} //Calling function doesn't want a second password //Check if the user entered a second password *password2 = memchr(*password, ' ', PASSWORD_SIZE_MAX); if(*password2){ //Null terminate previous password and get pointer to next password (*password2)[0] = '\0'; (*password2)++; } }else{ if(password2){ //Caller wants a second password but first password failed *password2 = NULL; //Ensure password2 doesn't point to garbage values } } } int get_admin_password(char *admin_password){ int character = 0; int pos = 0; while((character = getchar()) != '\n'){ if(pos > 0 && character == 0x7F){ pos--; }else if(pos < PASSWORD_SIZE_MAX - 1 && character >= 0x20 && character <= 0x7E){ admin_password[pos] = character; pos++; } } admin_password[pos] = '\0'; return pos + 1; //Return size of string } bool are_passwords_invalid(const char *password1, const char *password2, char *error_message){ //Check if password1 exists if(password1 == NULL || password2 == NULL){ sprintf(error_message, SERVER_PREFIX "The command requires a password be entered twice"); return true; } //Check if password1 is invalid if(is_password_invalid(password1, error_message)){ return true; } //Check if password2 is invalid if(is_password_invalid(password2, error_message)){ return true; } //Check is both passwords match if(strcmp(password1, password2) != 0){ sprintf(error_message, SERVER_PREFIX "The two entered passwords do not match"); return true; } return false; } bool is_password_invalid(const char *password, char *error_message){ if(password == NULL){ sprintf(error_message, SERVER_PREFIX "The command requires a password"); return true; } //Check if blank if(password[0] == '\0'){ sprintf(error_message, SERVER_PREFIX "Password is blank"); return true; } //Check if too long if(!memchr(password, '\0', PASSWORD_SIZE_MAX)){ sprintf(error_message, SERVER_PREFIX "Password is too long (max %d characters)", PASSWORD_SIZE_MAX - 1); return true; } //Check if any whitespace if(strpbrk(password, " \<PASSWORD>")){ sprintf(error_message, SERVER_PREFIX "Passwords with spaces are restricted"); return true; } //Check if too short if(memchr(password, '\0', PASSWORD_SIZE_MIN)){ sprintf(error_message, SERVER_PREFIX "Password is too short (min %d characters)", PASSWORD_SIZE_MIN); return true; } return false; } bool is_password_incorrect(const char *username, const char *password, const char *db_hashed_password){ char *query = NULL; sqlite3_stmt *stmt; char hashed_password[crypto_pwhash_STRBYTES]; //Compare database password with client password using libsodium if(crypto_pwhash_str_verify(db_hashed_password, password, strlen(password)) != 0){ return true; //Password is incorrect } //Check if hashed password needs to be rehashed if(crypto_pwhash_str_needs_rehash(db_hashed_password, PWHASH_OPSLIMIT, PWHASH_MEMLIMIT) != 0){ //Hash password with libsodium if(crypto_pwhash_str(hashed_password, password, strlen(password), PWHASH_OPSLIMIT, PWHASH_MEMLIMIT) != 0){ fprintf(stderr, "Ran out of memory during hash function\n"); return false; } //Update the rehashed password for the registered user query = "UPDATE users SET password = ?1 WHERE id = ?2;"; sqlite3_prepare(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, hashed_password, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 2, username, -1, SQLITE_STATIC); if(sqlite3_step(stmt) != SQLITE_DONE){ fprintf(stderr, "SQL error while updating password: %s\n", sqlite3_errmsg(user_db)); sqlite3_finalize(stmt); return false; } sqlite3_finalize(stmt); } return false; } bool is_username_invalid(const char *username, char *error_message){ //Check if username exists if(username == NULL){ sprintf(error_message, SERVER_PREFIX "The command requires a username"); return true; } //Check if blank if(strcmp(username, "") == 0){ sprintf(error_message, SERVER_PREFIX "Usernames cannot be blank"); return true; } //Check if too long if(!memchr(username, '\0', USERNAME_SIZE)){ sprintf(error_message, SERVER_PREFIX "Username is too long (max %d characters)", USERNAME_SIZE - 1); return true; } //Check if any whitespace if(strpbrk(username, " \t\n\v\f\r")){ sprintf(error_message, SERVER_PREFIX "Usernames cannot have spaces"); return true; } return false; } bool is_username_restricted(const char *username, char *error_message){ char *restricted_starts[] = RESTRICTED_STARTS; char *restricted_contains[] = RESTRICTED_CONTAINS; char *restricted_word = NULL; //Check if username starts with a restricted keyword for(int i = 0; i < sizeof(restricted_starts) / sizeof(restricted_starts[0]); i++){ restricted_word = restricted_starts[i]; if(strncmp_case_insensitive(username, restricted_starts[i], strlen(restricted_word)) == 0){ sprintf(error_message, SERVER_PREFIX "Usernames starting with \"%s\" are restricted", restricted_word); return true; } } //Check if username contains a restricted keyword for(int i = 0; i < sizeof(restricted_contains) / sizeof(restricted_contains[0]); i++){ restricted_word = restricted_contains[i]; if(string_contains(username, restricted_word)){ sprintf(error_message, SERVER_PREFIX "Usernames containing \"%s\" are restricted", restricted_word); return true; } } return false; } void rebuild_who_message(char **who_messages, int room_id){ size_t who_message_size; static size_t allocated_lengths[MAX_ROOMS]; if(who_messages == NULL){ fprintf(stderr, "Error in rebuild_who_message(): who_messages is NULL\n"); return; } //Perform initial allocation of memory if needed if(who_messages[room_id] == NULL){ who_messages[room_id] = malloc(WHO_MESSAGE_SIZE * sizeof(**who_messages)); if(who_messages[room_id] == NULL){ fprintf(stderr, "Error allocating memory for room #%d who_message\n", room_id); exit(EXIT_FAILURE); } allocated_lengths[room_id] = WHO_MESSAGE_SIZE; who_messages[room_id][0] = '\0'; //Set who_message to rebuild state } //Check if the list of users needs to be rebuilt if(who_messages[room_id][0] == '\0'){ //Insert MESSAGE_START character who_messages[room_id][0] = MESSAGE_START; sprintf(who_messages[room_id] + 1, "Room #%02d: ", room_id); //Check if chat room has users int room_user_count = HASH_COUNT(active_users[room_id]); if(room_user_count > 0){ //Get who_message string length - Add extra 1 for null character who_message_size = strlen(who_messages[room_id]) + (room_user_count * USERNAME_SIZE) + 1; //Allocate memory for the string if it's longer than initial allocated size if(who_message_size > allocated_lengths[room_id]){ char *new_ptr = realloc(who_messages[room_id], who_message_size * sizeof(**who_messages)); if(new_ptr == NULL){ fprintf(stderr, "Error allocating memory for who_message\n"); exit(0); } who_messages[room_id] = new_ptr; allocated_lengths[room_id] = who_message_size; } //Iterate through the hash table and append usernames table_entry_t *user; for(user = active_users[room_id]; user != NULL; user = user->hh.next){ strncat(who_messages[room_id], user->id, who_message_size); strncat(who_messages[room_id], " ", who_message_size); } } } } void remove_user(table_entry_t **user){ int index = (*user)->index; //Clear spam timeout and message count so new users using the same spot aren't affected pthread_mutex_lock(&spam_lock); spam_message_count[index] = 0; spam_timeout[index] = 0; pthread_mutex_unlock(&spam_lock); //Close the client socket check_status(close((*user)->socket_fd), "Error closing client socket"); //Set FD to ignore state, decrement socket count, and set who_message for rebuild socket_fds[index].fd = -1; socket_count--; //Remove user from active_user hash table delete_user(user); } table_entry_t * add_user(const char *username, bool is_admin, int room_id, size_t index, int client_fd, char *ip, unsigned short port){ table_entry_t *new_user; new_user = malloc(sizeof(table_entry_t)); if(new_user == NULL){ perror("Error allocating hash table memory for new user"); exit(EXIT_FAILURE); } strncpy(new_user->id, username, USERNAME_SIZE); new_user->is_admin = is_admin; new_user->room_id = room_id; new_user->index = index; new_user->socket_fd = client_fd; strncpy(new_user->ip, ip, INET_ADDRSTRLEN); new_user->port = port; new_user->message = NULL; new_user->message_size = 1; //Set to 1 for empty string size "\0" HASH_ADD_STR(active_users[room_id], id, new_user); //id: name of key field HASH_SRT(hh, active_users[room_id], id_compare); return new_user; } table_entry_t *get_user(int room_id, char *username){ table_entry_t *user = NULL; HASH_FIND_STR(active_users[room_id], username, user); //user: output pointer return user; } table_entry_t *find_user(const char *username){ table_entry_t *user = NULL; for(int room_index = 0; room_index < MAX_ROOMS; room_index++){ HASH_FIND_STR(active_users[room_index], username, user); //user: output pointer if(user){ return user; } } return NULL; } table_entry_t * change_username(table_entry_t **user, char *username){ table_entry_t *tmp = NULL; tmp = add_user(username, (*user)->is_admin, (*user)->room_id, (*user)->index, (*user)->socket_fd, (*user)->ip, (*user)->port); delete_user(user); *user = tmp; return *user; } void delete_user(table_entry_t **user){ int room_id = (*user)->room_id; HASH_DEL(active_users[room_id], *user); free(*user); *user = NULL; } int id_compare(table_entry_t *a, table_entry_t *b){ return (strncmp_case_insensitive(a->id, b->id, USERNAME_SIZE)); } int strncmp_case_insensitive(const char *a, const char *b, size_t n){ int a_char, b_char; do{ a_char = (unsigned char) *a++; b_char = (unsigned char) *b++; a_char = tolower(toupper(a_char)); //Round-trip conversion for issues where the uppercase char b_char = tolower(toupper(b_char)); //does not have a 1-to-1 mapping with lowercase ones n--; }while(a_char == b_char && a_char != '\0' && n > 0); return a_char - b_char; } bool string_contains(const char *string, const char *substring){ const char *substring_ptr = substring; int character = 0; do{ character = (unsigned char) *string; if(tolower(toupper(character)) == *substring_ptr){ substring_ptr++; }else if(substring_ptr != substring){ //Reset substring_ptr and test current string character again substring_ptr = substring; continue; } string++; }while(*string != '\0' && *substring_ptr != '\0'); if(*substring_ptr == '\0'){ return true; } return false; } void print_time(){ time_t raw_time = time(NULL); struct tm *cur_time; //Get local time time(&raw_time); cur_time = localtime(&raw_time); //Print time to terminal printf("%02d:%02d ", cur_time->tm_hour, cur_time->tm_min); } int check_status(int status, char *error){ if(status == -1){ perror(error); } return status; } //Function used to clear passwords from memory void secure_zero(volatile void *p, size_t n){ if(p == NULL){ return; } volatile uint8_t *ptr = p; //Use volatile to prevent compiler optimization while(n > 0){ *ptr = 0; ptr++; n--; } }<file_sep>/chat_client/src/client_tcp.c #include "client_tcp.h" int network_socket; int join_server(char *ip, unsigned int port, char *response){ int status; //Specify an address and port for the socket to use struct sockaddr_in server_address; server_address.sin_family = AF_INET; server_address.sin_port = htons(port); if(inet_pton(AF_INET, ip, &(server_address.sin_addr)) <= 0){ //Converts IP string to type "struct in_addr" strcpy(response, "-Error converting IP address string to struct in_addr-"); return -1; } memset(server_address.sin_zero, 0, sizeof(server_address.sin_zero)); //Create Socket network_socket = socket(PF_INET, SOCK_STREAM, 0); check_status(network_socket, "Error creating network socket"); //Perform the connection using the socket and address struct status = connect(network_socket, (struct sockaddr *) &server_address, sizeof(server_address)); //Check for connection errors if(status){ close_socket(network_socket); strcpy(response, " -Error connecting to the chat server-"); return status; } //Receive welcome message from the server status = recv(network_socket, response, MESSAGE_SIZE, 0); check_status(status, "Error receiving welcome message from server"); return status; } int receive_message(char *message, int message_length){ int recv_status; recv_status = recv(network_socket, message, message_length, 0); if(recv_status <= 0){ close_socket(network_socket); } return recv_status; } int send_message(char *client_message, int client_message_size){ int bytes_sent = 0; int message_size = client_message_size + 1; //Add 1 for Start-of-Text character char message[message_size]; char *message_ptr = message; if(!strcmp(client_message, "/q") || !strcmp(client_message, "/quit") || !strcmp(client_message, "/exit\n")){ close_socket(network_socket); }else{ //Add a control character to the start and end of the message so the server knows when it's //received a complete message since the message may be split up over multiple packets message[0] = MESSAGE_START; strncpy(message + 1, client_message, client_message_size); message[message_size - 1] = MESSAGE_END; do{ bytes_sent = send(network_socket, message_ptr, message_size, 0); if(bytes_sent < 0){ break; } message_ptr += bytes_sent; //Point to the remaining portion that was not sent message_size -= bytes_sent; //Calculate the remaining bytes to be sent }while(message_size); } return bytes_sent; } int close_socket(int socket){ int status = close(socket); check_status(status, "Error closing network socket"); return status; } int check_status(int status, char *error){ if(status == -1){ perror(error); } return status; }<file_sep>/chat_client/src/client_tcp.h #ifndef TCP_CLIENT_H #define TCP_CLIENT_H #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #define DEFAULT_PORT_NUMBER 9852 #define DEFAULT_IP_ADDRESS "127.0.0.1" #define MESSAGE_SIZE 256 //Must be less than or equal to server's message length #define MESSAGE_START 0x02 //Start of Text control character #define MESSAGE_END 0x03 //End of text control character int join_server(char *, unsigned int, char *); int receive_message(char *, int); int send_message(char *, int); int close_socket(int); int check_status(int status, char *error); #endif<file_sep>/chat_server/src/server.h #ifndef CHAT_SERVER_VALUES_H #define CHAT_SERVER_VALUES_H #include <string.h> #include <ctype.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <fcntl.h> #include <signal.h> #include "server_shared.h" #include "server_commands.h" #include "server_utils.h" #define DEFAULT_PORT_NUMBER 9852 //Default port number to try before automatically finding an unused port #define LISTEN_BACKLOG 10 #define MAX_SOCKETS 256 //Max FD limit on linux is set to 1024 by default but can be changed #define SPAM_MESSAGE_LIMIT 10 //Max messages within spam interval window #define SPAM_INTERVAL_WINDOW 10 //Interval window (in seconds) for max message limit #define SPAM_TIMEOUT_LENGTH 15 //Timeout period (in seconds) for detected spammer to wait void open_database(); void create_admin(); void start_server(); void *spam_timer(); void monitor_connections(int); void accept_clients(int, char *, char **); void process_clients(char *, char **); int check_for_spamming(table_entry_t *, char *); void private_message(table_entry_t *, char *, size_t, char *); void public_message(table_entry_t *, char *, size_t); void remove_client(table_entry_t *, char *, char **); static void terminate_server(int sig_num); void shutdown_server(char **); #endif<file_sep>/Makefile #Compilation flags CC = gcc CFLAGS = -I. DEBUG = -g -O0 #Variables for charserver SRCDIRS = chat_server/src OBJDIRS = chat_server/obj SRCS = $(SRCDIRS)/server.c $(SRCDIRS)/server_utils.c $(SRCDIRS)/server_commands.c DEPS = $(SRCDIRS)/server.h $(SRCDIRS)/server_utils.h $(SRCDIRS)/server_commands.h $(SRCDIRS)/server_shared.h OBJS = $(OBJDIRS)/server.o $(OBJDIRS)/server_utils.o $(OBJDIRS)/server_commands.o LIBS = -lpthread -lsqlite3 -lsodium #Variables for chatclient SRCDIRC = chat_client/src OBJDIRC = chat_client/obj SRCC = $(SRCDIRC)/client.c $(SRCDIRC)/client_tcp.c DEPC = $(SRCDIRC)/client.h $(SRCDIRC)/client_tcp.h OBJC = $(OBJDIRC)/client.o $(OBJDIRC)/client_tcp.o LIBC = -lpthread -lncurses .PHONY: all all: chatserver chatclient #Build object for chatserver $(OBJDIRS)/%.o: $(SRCDIRS)/%.c $(DEPS) $(CC) $(DEBUG) -c -o $@ $< chatserver: $(OBJS) $(CC) $(DEBUG) -Wall -pedantic -o $@ $^ $(LIBS) #Build object for chatclient $(OBJDIRC)/%.o: $(SRCDIRC)/%.c $(DEPC) $(CC) $(DEBUG) -c -o $@ $< chatclient: $(OBJC) $(CC) $(DEBUG) -Wall -pedantic -o $@ $^ $(LIBC) .PHONY: clean clean: rm -r chatserver chatclient $(OBJDIRS) $(OBJDIRC) #Create obj folders for client and server $(shell mkdir -p $(OBJDIRS)) $(shell mkdir -p $(OBJDIRC)) <file_sep>/chat_client/src/client.h #ifndef CHAT_CLIENT_H #define CHAT_CLIENT_H #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <string.h> #include <time.h> #include <pthread.h> #include <signal.h> #include <ncurses.h> #include "client_tcp.h" #define INPUT_INDICATOR "Send> " #define INPUT_START 6 //Adjust this based on INPUT_INDICATOR void initialize_chat(); void initialize_connection(char *, int); void *incoming_messages(); void outgoing_messages(); bool get_user_message(char *, size_t *, int *); void local_commands(char *, size_t); void print_to_chat(char *, size_t *); void print_time(); void secure_zero(volatile void *, size_t ); void shutdown_chat(); static void shutdown_handler(int); #endif<file_sep>/chat_server/src/server_utils.h #ifndef CHAT_SERVER_UTILS_H #define CHAT_SERVER_UTILS_H #include "server_shared.h" #define RESTRICTED_STARTS {"client", "server"} #define RESTRICTED_CONTAINS {"admin", "moderator"} size_t prepare_client_message(char *, ssize_t *); char *add_username_to_message(const char *, const char *, const char *); ssize_t send_message(int, const char *, size_t); ssize_t send_message_to_all(int, const char *, size_t); void get_username_and_passwords(int, char *, char **, char **, char **); int get_admin_password(char *); bool are_passwords_invalid(const char *, const char *, char *); bool is_password_invalid(const char *, char *); bool is_password_incorrect(const char *, const char *, const char *); bool is_username_invalid(const char *, char *); bool is_username_restricted(const char *, char *); void rebuild_who_message(char **, int); void remove_user(table_entry_t **); table_entry_t *add_user(const char *, bool, int, size_t, int, char *, unsigned short); table_entry_t *get_user(int, char *); table_entry_t *find_user(const char *); table_entry_t *change_username(table_entry_t **, char *); void delete_user(table_entry_t **); int id_compare(table_entry_t *, table_entry_t *); int strncmp_case_insensitive(const char *, const char *, size_t); bool string_contains(const char *, const char *); void print_time(); int check_status(int, char *); void secure_zero(volatile void *, size_t); #endif<file_sep>/chat_client/Makefile CC = gcc CFLAGS = -I. DEBUG = -g -O0 DEPS = client.h client_tcp.h OBJ = $(OBJDIR)/client.o $(OBJDIR)/client_tcp.o LIBS = -lpthread -lncurses VPATH = src OBJDIR = obj $(OBJDIR)/%.o: %.c $(DEPS) $(CC) $(DEBUG) -c -o $@ $< $(CFLAGS) chatclient: $(OBJ) $(CC) $(DEBUG) -Wall -pedantic -o $@ $^ $(CFLAGS) $(LIBS) .PHONY: clean clean: rm -r chatclient $(OBJDIR) $(shell mkdir -p $(OBJDIR))<file_sep>/README.md # Description Linux terminal chat server and client that were programmed in C and make use of C socket programming (TCP protocol), POSIX threads, ncurses, libsodium, and SQLite3. The project compiles into two executables ("chatserver" and "chatclient") which are used for hosting the chat server and connecting to the chat server respectively. - Multiple chat rooms, direct messaging, username registration, account types, spam filtering, and user kicking - Utilizes C socket programming (TCP protocol) to make connections and send/receive messages - Handles multiple messages in one packet and incomplete message split up over multiple packets - Server-side storage of usernames and libsodium-hashed passwords within a local SQLite3 database - Client application uses ncurses to display separate text areas for incoming chat text and outgoing user input - Custom user-input echoing with password protection and last message sent history recall # Table of Contents - [Description](#description) - [Libraries Used](#libraries-used) - [Building](#building) - [Application Usage](#application-usage) - [Private Messaging](#private-messaging) - [Commands](#commands) # Libraries Used The following libraries were used and will be required to run the chat server and chat client. Installation instructions are provided for your convenience. The displayed versions are the latest versions tested. >## [ncurses](https://www.gnu.org/software/ncurses/) v6.1 sudo apt-get update sudo apt-get install libncurses5-dev libncursesw5-dev >## [uthash](https://troydhanson.github.io/uthash/) v2.1.0 sudo apt-get update sudo apt-get install uthash-dev >## [SQLite](https://www.sqlite.org/index.html) v3.22.0 sudo apt-get update sudo apt-get install sqlite3 libsqlite3-dev >## [Libsodium](https://libsodium.gitbook.io/doc/) v1.0.18 Download a [tarball of libsodium](https://download.libsodium.org/libsodium/releases/), preferably the latest stable version, then perform the following: ./configure make && make check sudo make install # Building This application was developed for Linux and makes use of POSIX threads. Therefore, Windows is not natively supported due to the lack of pthreads on Windows operating systems. For use on Windows, you can use the Windows Subsystem for Linux (WSL) or Cygwin. - Developed on Ubuntu v18.04.2 LTS - Compiled with GCC v7.4.0 To build the chatserver and chatclient applications, install the [required libraries mentioned above](#libraries-used) and then perform the compilation by running the Makefile in the root directory. make If for some reason you only want to compile one of the applications, you can run the application-specific Makefile located in each of the subdirectories. # Application Usage >## Chat Server The chat server can be launched without any arguments, which will result in the default port number being used, or one can be manually specified. If either the default port or the user-specified port is already in use, the server will automatically find an unused port to use and display it on the terminal. ./chatserver ./chatserver <port_number> The first time the chat server is launched, a main-admin account with the username "*admin*" will be created. Simply enter the desired password twice and it will register the admin account in the local database. The local database is stored as a SQLite database named "*users.db*" and can be deleted at anytime to clear all the registered usernames and passwords. >## Chat Client The chat client can be launched without any arguments, which will result in the default IP address and port number being used, or they can be manually specified by the user. ./chatclient ./chatclient <IP_address> <port_number> ./chatclient <IP_address> ./chatclient <port_number> # Private Messaging >## @ Private messages can be sent to users by inserting the '@' symbol before their username. Note that private messaging works across the whole server so it doesn't matter if the two users are in the same chat room or not. When a user receives a private message, the senders username will be followed by ">>" to let the user know it's a private message. @<username> <private_message> # Commands The following commands are entered in the chat client once connected to the chat server >## clear The "*clear*" command is used to clear the screen to a blank state. /clear >## color The "*color*" command enables colors for the chat client window. You can use the command without arguments to toggle between modes or specify "*on*" / "*off*" as an argument. The British English spelling "*colour*" is also supported. /color /colour /color <on/off> /colour <on/off> >## join The "*join*" command is used to join the specified chat room. Enter the desired room number as an argument to join that room. /join <room_number> >## nick The "*nick*" command is used to change your nickname. If no argument is given, then the server will echo back your own username. If the specified nickname has been previously registered, then the password for that nickname must be entered before you can use it. /nick /nick <username> /nick <username> <password> >## register The "*register*" command allows you to register a username so only you have access to it. Enter your desired username and repeat the password twice. If a username is already registered, an error is returned. /register <username> <password> <password> >## unregister The "*unregister*" command is used to unregister a username that is no longer needed. Enter the username and password as arguments for the username you wish to unregister. Admin account types are not required to enter a password which gives admins full control over the registered usernames. /unregister <username> <password> /unregister <username> >## whois The "*whois*" command displays the ip and port information about a user. If no argument is given, it will display information about yourself. If a username argument is given, it will return information about the specified user. Note that only admins can get information about other users. /whois /whois <username> >## who The "*who*" command displays the current users on the server. If no argument is given, then a list of all users in every chat room will be printed to the screen. If a room number is given, then only the users in the specified chat room will be displayed. /who /who <room_number> >## where The "*where*" command is used to display which chat room the specified user is currently in. If no argument is given, then the room you are currently in will be displayed. /where /where <username> >## kick The "*kick*" command is used to kick the specified user from the chat server: Note that only admins can use this command. /kick <username> >## admin The "*admin*" command is used to toggle the user type of the specified user between a regular user and an admin user. Note that only the main-admin account with the username "*admin*" can change user types. The main-admin account is created the first time the server is started. /admin <username> >## die The "*die*" command is used to send a shutdown signal to the server. Note that only admins can use this command. /die <file_sep>/chat_server/src/server.c #include "server.h" #include <termios.h> /* Extern Definitions */ int socket_count = 0; struct pollfd socket_fds[MAX_SOCKETS]; table_entry_t *active_users[MAX_ROOMS] = {NULL}; short spam_message_count[MAX_SOCKETS]; //Spam message counters for each client short spam_timeout[MAX_SOCKETS]; //Spam timeout for each client pthread_mutex_t spam_lock; sqlite3 *user_db; /* ----------------- */ pthread_attr_t spam_tattr; pthread_t spam_tid; bool shutdown_server_flag = false; unsigned int port_number = DEFAULT_PORT_NUMBER; int main(int argc, char* argv[]){ //Setup signal handlers to properly close server signal(SIGINT, terminate_server); //CTRL + C signal(SIGQUIT, terminate_server); //CTRL + BACKSLASH signal(SIGSEGV, terminate_server); //Memory access violation //Get port number from argument if(argc > 1){ port_number = atoi(argv[1]); } //Turn off input echoing struct termios oldtc, newtc; tcgetattr(STDIN_FILENO, &oldtc); newtc = oldtc; newtc.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newtc); pthread_mutex_init(&spam_lock, NULL); printf("**Opening Database**\n"); open_database(); printf("**Starting Server**\n"); start_server(); printf("**Shutting Down Server**\n"); //Turn echoing back on tcsetattr(STDIN_FILENO, TCSANOW, &oldtc); pthread_mutex_destroy(&spam_lock); return 0; } void open_database(){ int status; const char *query; sqlite3_stmt *stmt; //Open database of registered users or create one if it doesn't already exist if(sqlite3_open("users.db", &user_db) != SQLITE_OK){ fprintf(stderr, "Error opening database: %s\n", sqlite3_errmsg(user_db)); sqlite3_close(user_db); } //Create "users" table if it doesn't already exist query = "CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY NOT NULL, password TEXT NOT NULL, type TEXT NOT NULL);"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); if(sqlite3_step(stmt) != SQLITE_DONE){ fprintf(stderr, "SQL error while creating table: %s\n", sqlite3_errmsg(user_db)); exit(EXIT_FAILURE); } sqlite3_finalize(stmt); //Check if initial admin account has already been created query = "SELECT 1 FROM users WHERE type = 'admin';"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); if((status = sqlite3_step(stmt)) == SQLITE_ROW){ sqlite3_finalize(stmt); return; //Initial admin account already exists }else if(status != SQLITE_DONE){ fprintf(stderr, "SQL error while checking for admin: %s\n", sqlite3_errmsg(user_db)); exit(EXIT_FAILURE); } sqlite3_finalize(stmt); //Create initial admin account create_admin(); } void create_admin(){ char admin_password[MESSAGE_SIZE]; char admin_password2[MESSAGE_SIZE]; char hashed_password[crypto_pwhash_STRBYTES]; char password_error[MESSAGE_SIZE]; char *matching_error = NULL; const char *query; sqlite3_stmt *stmt; printf("**Creating Admin Account**\n"); //Get admin password from server administrator do{ //Reset password_error for new iteration password_error[0] = '\0'; //Print error message from previous iteration if(matching_error){ printf("%s\n\n", matching_error); } do{ if(*password_error){ //Print error message if not blank printf("%s\n\n", password_error + strlen(SERVER_PREFIX)); //Skip over SERVER_PREFIX } printf("Enter password for \"Admin\" account: "); get_admin_password(admin_password); printf("\n"); }while(is_password_invalid(admin_password, password_error)); printf("Retype the same password: "); get_admin_password(admin_password2); printf("\n"); //Set matching_error message for next loop iteration matching_error = "The entered passwords do not match"; }while(strncmp(admin_password, <PASSWORD>_<PASSWORD>, PASSWORD_SIZE_MAX) != 0); //Hash password with libsodium if(crypto_pwhash_str(hashed_password, admin_password, strlen(admin_password), PWHASH_OPSLIMIT, PWHASH_MEMLIMIT) != 0){ /* out of memory */ fprintf(stderr, "Ran out of memory during hash function\n"); exit(EXIT_FAILURE); } //Clear the plain-text passwords from memory secure_zero(admin_password, PASSWORD_SIZE_MAX); secure_zero(admin_password2, PASSWORD_SIZE_MAX); //Register admin account into database with specified password query = "INSERT INTO users(id, password, type) VALUES('Admin', ?1, '<PASSWORD>');"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, hashed_password, -1, SQLITE_STATIC); if(sqlite3_step(stmt) != SQLITE_DONE){ fprintf(stderr, "SQL error while inserting admin account: %s\n", sqlite3_errmsg(user_db)); exit(EXIT_FAILURE); }else{ printf("**Admin Account Created**\n"); } sqlite3_finalize(stmt); } void start_server(){ int status; int flags; //Define the server's IP address and port struct sockaddr_in server_address; server_address.sin_family = AF_INET; server_address.sin_port = htons(port_number); server_address.sin_addr.s_addr = htonl(INADDR_ANY); memset(server_address.sin_zero, 0, sizeof(server_address.sin_zero)); //Create the server socket to use for a connection int server_socket; server_socket = socket(PF_INET, SOCK_STREAM, 0); check_status(server_socket, "Error creating server socket"); //Set server socket to nonblocking flags = fcntl(server_socket, F_GETFL, NULL); check_status(flags, "Error getting flags for server socket"); status = fcntl(server_socket, F_SETFL, flags | O_NONBLOCK); check_status(status, "Error setting server socket to nonblocking"); //Bind the socket to our specified IP address and port status = bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address)); if(check_status(status, "\nError binding server socket")){ fprintf(stderr, "Server will select an unused port instead of port %d\n", port_number); server_address.sin_port = 0; //Set port to automatically find an unused port status = bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address)); check_status(status, "Error binding server socket"); } //Print the server port to the terminal socklen_t len = sizeof(server_address); if(getsockname(server_socket, (struct sockaddr *)&server_address, &len) == -1){ perror("getsockname error"); return; } port_number = ntohs(server_address.sin_port); printf("Server is using port number: %d\n", port_number); //Set the socket up to listen for connections status = listen(server_socket, LISTEN_BACKLOG); check_status(status, "Error listening on server socket"); //Initialize struct pollfd array to zeros memset(socket_fds, 0, sizeof(socket_fds)); //Set server file descriptor and event type socket_fds[0].fd = server_socket; socket_fds[0].events = POLLIN; socket_count++; //Set ignore state for client file descriptors and event type for(size_t i = 1; i < MAX_SOCKETS; i++){ socket_fds[i].fd = -1; socket_fds[i].events = POLLIN; } //Create thread for spam timer in a detached state if(pthread_attr_init(&spam_tattr)){ perror("Error initializing pthread attribute"); exit(EXIT_FAILURE); } if(pthread_attr_setdetachstate(&spam_tattr, PTHREAD_CREATE_DETACHED)){ perror("Error setting pthread detach state"); exit(EXIT_FAILURE); } if(pthread_create(&spam_tid, &spam_tattr, spam_timer, NULL)){ perror("Error creating pthread"); exit(EXIT_FAILURE); } if(pthread_attr_destroy(&spam_tattr)){ perror("Error destroying pthread attribute"); exit(EXIT_FAILURE); } //Call method for processing clients monitor_connections(server_socket); //Close the server socket check_status(close(server_socket), "Error closing server socket"); //Close database of registered users status = sqlite3_close(user_db); if(status != SQLITE_OK){ fprintf(stderr, "Error closing database: %s\n", sqlite3_errmsg(user_db)); } } void *spam_timer(){ int current_interval = 0; //Current interval within spam interval window while(1){ //Each interval is one second long sleep(1); current_interval++; //Reset spam message counters to be used in new spam interval window if(current_interval % SPAM_INTERVAL_WINDOW == 0){ pthread_mutex_lock(&spam_lock); memset(spam_message_count, 0, sizeof(spam_message_count)); pthread_mutex_unlock(&spam_lock); current_interval = 0; } //Reduce every client's timeout period by one second until it's zero pthread_mutex_lock(&spam_lock); for(size_t i = 1; i < MAX_SOCKETS; i++){ if(spam_timeout[i] > 0){ spam_timeout[i]--; } } pthread_mutex_unlock(&spam_lock); } } void monitor_connections(int server_socket){ int status; char server_msg_prefixed[MESSAGE_SIZE + 1]; char *server_msg = server_msg_prefixed + 1; char *who_messages[MAX_ROOMS] = {NULL}; //Add control character to the start of message so we know when it's a //new message since the message may be split up over multiple packets server_msg_prefixed[0] = MESSAGE_START; //Perform initial allocation/build of who_messages for(int room_id = 0; room_id < MAX_ROOMS; room_id++){ rebuild_who_message(who_messages, room_id); } printf("**Awaiting Clients**\n"); while(1){ //Monitor FDs for any activated events status = poll(socket_fds, MAX_SOCKETS, -1); //Check if a poll error has occurred if(status == -1){ perror("Poll Error"); continue; } /* ------------------------------------------ */ /* Event has occurred: Check server socket */ /* ------------------------------------------ */ if(socket_fds[0].revents & POLLIN){ accept_clients(server_socket, server_msg_prefixed, who_messages); } /* ----------------------------------------------------------------- */ /* Event has occurred: Check all active clients in every chat room */ /* ----------------------------------------------------------------- */ process_clients(server_msg_prefixed, who_messages); //Check if server has been flagged for shutdown if(shutdown_server_flag){ break; } } /* --------------- */ /* Shutdown server */ /* --------------- */ shutdown_server(who_messages); } void accept_clients(int server_socket, char *server_msg_prefixed, char **who_messages){ int status, flags; int client_socket; static size_t index = 0; char username[USERNAME_SIZE]; char *server_msg = server_msg_prefixed + 1; const char *server_msg_literal = NULL; struct sockaddr_in client_addr; socklen_t client_addr_size = sizeof(client_addr); char ip_str[INET_ADDRSTRLEN]; unsigned short port; while(1){ //Check for any pending connections client_socket = accept(server_socket, (struct sockaddr *) &client_addr, &client_addr_size); //Accept all pending connections until queue is empty or an error occurs if(client_socket == -1){ if(errno != EWOULDBLOCK && errno != EAGAIN){ perror("Error accepting new client"); }else{ //No more pending connections } return; } //Check if server is full if(socket_count >= MAX_SOCKETS){ printf("**Server has reached the maximum of %d clients**\n", MAX_SOCKETS - 1); sprintf(server_msg, SERVER_PREFIX "The server has reached the maximum of %d clients", MAX_SOCKETS - 1); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); status = close(client_socket); check_status(status, "Error closing client socket"); continue; } //Increment socket count and set lobby who_messages for rebuild socket_count++; who_messages[LOBBY_ROOM_ID][0] = '\0'; //Set client socket to nonblocking flags = fcntl(client_socket, F_GETFL, NULL); check_status(flags, "Error getting flags for client socket"); status = fcntl(client_socket, F_SETFL, flags | O_NONBLOCK); check_status(status, "Error setting client socket to nonblocking"); //Get the ip address and port number of the connecting user inet_ntop(AF_INET, &(client_addr.sin_addr), ip_str, sizeof(ip_str)); port = ntohs(client_addr.sin_port); //Find an available spot in the client FD array while(socket_fds[index].fd > 0){ index = (index + 1) % MAX_SOCKETS; } //Assign the socket to the client FD socket_fds[index].fd = client_socket; //Create client's default username sprintf(username, "Client%zu", index); //Add client to the lobby room in active_users hash table add_user(username, false, LOBBY_ROOM_ID, index, client_socket, ip_str, port); //Send server welcome messages to client sprintf(server_msg, SERVER_PREFIX "Welcome to the server - Default username is \"%s\"", username); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Use the /nick command to change your username"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Use the /join command to join a chat room"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); //Print client joining message to the server's terminal printf("**Client%lu on socket %d (%s:%hu) joined the server**\n", index, client_socket, ip_str, port); } } void process_clients(char *server_msg_prefixed, char **who_messages){ ssize_t recv_status = 0; size_t msg_size = 0; size_t index = 0; int client_socket = 0; int cmd_length = 0; bool expect_ending_char = false; char *server_msg = server_msg_prefixed + 1; const char *server_msg_literal = NULL; static bool message_recv[MAX_SOCKETS]; static char client_msg[MESSAGE_SIZE + 1]; static char packet_msg[MESSAGE_SIZE + 1]; //Fail-safe to ensure NUL terminated client message client_msg[MESSAGE_SIZE] = '\0'; packet_msg[MESSAGE_SIZE] = '\0'; char *packet_ptr = packet_msg; memset(message_recv, false, sizeof(message_recv)); //Iterate through every chat room for(int room_index = 0; room_index < MAX_ROOMS; room_index++){ //Iterate through all users in the chat room table_entry_t *user, *tmp; HASH_ITER(hh, active_users[room_index], user, tmp){ //Uthash deletion-safe iteration //Get index and socket from user entry index = user->index; client_socket = user->socket_fd; //Check if user has already been processed if(message_recv[index]){ continue; } //Continue if no active event for FD if(!(socket_fds[index].revents & POLLIN)){ continue; } //Receive messages from client sockets with active events recv_status = recv(client_socket, packet_msg, MESSAGE_SIZE, 0); if(recv_status == -1){ if(errno != EWOULDBLOCK && errno != EAGAIN){ perror("Error receiving message from client socket"); } continue; } //Check if client has left the server if(recv_status == 0){ remove_client(user, server_msg_prefixed, who_messages); continue; } //Mark socket as messaged received message_recv[index] = true; //Point to first message in packet and reset flag packet_ptr = packet_msg; expect_ending_char = false; while(recv_status > 0){ //Copy packet message to client message if(packet_ptr[0] == MESSAGE_START){ //Skip over message-start control character packet_ptr++; recv_status--; //Copy the new message strncpy(client_msg, packet_ptr, recv_status); client_msg[recv_status] = '\0'; expect_ending_char = true; }else if(user->message){ //Copy the old incomplete message strncpy(client_msg, user->message, user->message_size); //Concatenate the new message strncat(client_msg, packet_ptr, recv_status); expect_ending_char = true; }else{ //Handle message normally strncpy(client_msg, packet_ptr, recv_status); expect_ending_char = false; } //Prepare client message for processing msg_size = prepare_client_message(client_msg, &recv_status); //Check if message is completed or not if(client_msg[msg_size - 1] == MESSAGE_END){ //Change MESSAGE_END ending to "\0" and process message client_msg[msg_size - 1] = '\0'; //Reset flag for next message expect_ending_char = false; }else if(expect_ending_char){ //Store incomplete message for later processing char *incomplete_msg = user->message; if(incomplete_msg == NULL){ incomplete_msg = malloc(MESSAGE_SIZE * sizeof (*incomplete_msg)); if(incomplete_msg == NULL){ perror("Error allocating incomplete message for user"); exit(EXIT_FAILURE); } } //Copy incomplete message to user's message buffer strncpy(incomplete_msg, client_msg, msg_size); user->message = incomplete_msg; user->message_size = msg_size; //Adjust recv_status to remaining bytes and point to next message if(msg_size > 1){ recv_status -= (ssize_t) (msg_size - 1); packet_ptr += (msg_size - 1); }else{ //Subtract 1 if there is only a single control character remaining //Fail safe to prevent infinite loop on bad input recv_status -= 1; packet_ptr += 1; } continue; } if(client_msg[0] == '\0'){ /* ----------------------------- */ /* Ignore client's empty message */ /* ----------------------------- */ }else if(client_msg[0] == '/'){ /* ------------------------------- */ /* Process client's server command */ /* ------------------------------- */ if(strcmp(client_msg, "/whois") == 0){ //Return the client's IP address and port cmd_length = 6; whois_cmd(cmd_length, user, client_msg); } //Fallthrough to targeted /whois command if(strncmp(client_msg, "/whois ", cmd_length = 7) == 0){ //Return the targeted user's IP address and port whois_arg_cmd(cmd_length, user, client_msg, server_msg_prefixed); }else if(strcmp(client_msg, "/who") == 0){ //List who's in every chat room who_cmd(client_socket, who_messages); }else if(strncmp(client_msg, "/who ", cmd_length = 5) == 0){ //List who's in the specified chat room who_arg_cmd(cmd_length, client_socket, client_msg, server_msg_prefixed, who_messages); }else if(strcmp(client_msg, "/join") == 0){ //Inform client of /join usage join_cmd(client_socket); }else if(strncmp(client_msg, "/join ", cmd_length = 6) == 0){ //Join the user-specified chat room join_arg_cmd(cmd_length, &user, client_msg, server_msg_prefixed, who_messages); }else if(strcmp(client_msg, "/nick") == 0){ //Echo back the client's username nick_cmd(user, server_msg_prefixed); }else if(strncmp(client_msg, "/nick ", cmd_length = 6) == 0){ //Change the client's username nick_arg_cmd(cmd_length, &user, client_msg, server_msg_prefixed, who_messages); //Clear passwords from every buffer secure_zero(packet_msg, msg_size); secure_zero(client_msg, msg_size); secure_zero(user->message, msg_size); }else if(strcmp(client_msg, "/where") == 0){ //Return the chat room you are currently in where_cmd(user, server_msg_prefixed); }else if(strncmp(client_msg, "/where ", cmd_length = 7) == 0){ //Return the room number that has the specified-user where_arg_cmd(cmd_length, client_socket, client_msg, server_msg_prefixed); }else if(strcmp(client_msg, "/kick") == 0){ //Inform client of /kick usage kick_cmd(client_socket); }else if(strncmp(client_msg, "/kick ", cmd_length = 6) == 0){ //Kick specified user from the server kick_arg_cmd(cmd_length, user, &tmp, client_msg, server_msg_prefixed, who_messages); }else if(strcmp(client_msg, "/register") == 0){ //Inform client of /register usage register_cmd(client_socket); }else if(strncmp(client_msg, "/register ", cmd_length = 10) == 0){ //Register username in user database register_arg_cmd(cmd_length, user, client_msg, server_msg_prefixed); //Clear passwords from every buffer secure_zero(packet_msg, msg_size); secure_zero(client_msg, msg_size); secure_zero(user->message, msg_size); }else if(strcmp(client_msg, "/unregister") == 0){ //Inform client of /unregister usage unregister_cmd(client_socket); }else if(strncmp(client_msg, "/unregister ", cmd_length = 12) == 0){ //Unregister username from user database unregister_arg_cmd(cmd_length, user, client_msg, server_msg_prefixed); //Clear passwords from every buffer secure_zero(packet_msg, msg_size); secure_zero(client_msg, msg_size); secure_zero(user->message, msg_size); }else if(strcmp(client_msg, "/admin") == 0){ //Inform client of /admin usage admin_cmd(client_socket); }else if(strncmp(client_msg, "/admin ", cmd_length = 7) == 0){ //Change account type of targeted user admin_arg_cmd(cmd_length, user, client_msg, server_msg_prefixed); }else if(strcmp(client_msg, "/die") == 0){ //Trigger server shutdown if admin if(die_cmd(user)){ shutdown_server_flag = true; break; } }else{ //Remove arguments after the command if they exist char *arguments = memchr(client_msg, ' ', msg_size); if(arguments){ arguments[0] = '\0'; } //Inform client of invalid command sprintf(server_msg, SERVER_PREFIX "\"%s\" is not a valid command", client_msg); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } }else{ /* --------------------- */ /* Send client's message */ /* --------------------- */ //Check for and handle spamming clients if(check_for_spamming(user, server_msg_prefixed)){ //User has spam timeout break; }else{ //Increment spam message count for client pthread_mutex_lock(&spam_lock); spam_message_count[index]++; pthread_mutex_unlock(&spam_lock); } if(client_msg[0] == '@'){ /* ------------------------------------- */ /* Send private message to targeted user */ /* ------------------------------------- */ private_message(user, client_msg, msg_size, server_msg_prefixed); }else if(user->room_id == LOBBY_ROOM_ID){ //Inform client they aren't in a chat room server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "You're not in a chat room - Use the /join command"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); }else{ /* -------------------------------- */ /* Send public message to chat room */ /* -------------------------------- */ public_message(user, client_msg, msg_size); } } //Adjust recv_status to remaining bytes not yet processed recv_status -= (ssize_t) (msg_size - (user->message_size - 1)); //Point to next message in the packet packet_ptr += (msg_size - (user->message_size - 1)); //Reset user's message buffer if(user->message){ free(user->message); user->message = NULL; user->message_size = 1; //Set to 1 for empty string size "\0" } } } } } int check_for_spamming(table_entry_t *user, char *server_msg_prefixed){ int index = user->index; int client_socket = user->socket_fd; char *server_msg = server_msg_prefixed + 1; pthread_mutex_lock(&spam_lock); if(spam_timeout[index] != 0){ //Client currently has a timeout period sprintf(server_msg, "Spam Timeout: Please wait %d seconds", spam_timeout[index]); pthread_mutex_unlock(&spam_lock); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return 1; }else if(spam_message_count[index] > SPAM_MESSAGE_LIMIT){ //Give client a timeout period spam_timeout[index] = SPAM_TIMEOUT_LENGTH; pthread_mutex_unlock(&spam_lock); sprintf(server_msg, "Spam Timeout: Please wait %d seconds", SPAM_TIMEOUT_LENGTH); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return 1; } pthread_mutex_unlock(&spam_lock); return 0; } void private_message(table_entry_t *user, char *client_msg, size_t msg_size, char *server_msg_prefixed){ int client_socket = user->socket_fd; char *server_msg = server_msg_prefixed + 1; char target_username[USERNAME_SIZE]; size_t target_username_length = strcspn(client_msg + 1, " "); //Check if targeted username is too long if(target_username_length > USERNAME_SIZE - 1){ sprintf(server_msg, SERVER_PREFIX "Username is too long (max %d characters)", USERNAME_SIZE - 1); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Copy targeted username from client's message strncpy(target_username, client_msg + 1, target_username_length); target_username[target_username_length] = '\0'; //NUL terminate username target_username[0] = toupper(target_username[0]); //Capitalize username //Look for user in all chat rooms table_entry_t *target_user = find_user(target_username); //Inform client if user was not found if(target_user == NULL){ sprintf(server_msg, SERVER_PREFIX "The user \"%s\" does not exist", target_username); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Remove '@' character, username, and empty space from client's message char *message = client_msg + 1 + target_username_length + 1; msg_size -= (1 + target_username_length + 1); //Check if message to user is blank if(message[0] == '\0' || message[-1] != ' '){ sprintf(server_msg, SERVER_PREFIX "The message to \"%s\" was blank", target_username); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Add sender's username to message char *username = user->id; char *postfix = PRIVATE_PREFIX; message = add_username_to_message(message, username, postfix); size_t additional_length = strlen(username) + strlen(postfix) + 1; //Add one for MESSAGE_START //Send message to target user and sender send_message(target_user->socket_fd, message, msg_size + additional_length); if(target_user->socket_fd != client_socket){ send_message(client_socket, message, msg_size + additional_length); } free(message); message = NULL; } void public_message(table_entry_t *user, char *client_msg, size_t msg_size){ int room_id = user->room_id; char *username = user->id; //Add sender's username to message char *postfix = PUBLIC_PREFIX; char *message = add_username_to_message(client_msg, username, postfix); size_t additional_length = strlen(username) + strlen(postfix) + 1; //Add one for MESSAGE_START //Send message to all clients send_message_to_all(room_id, message, msg_size + additional_length); //Print client's message to server console print_time(); printf("#%d ", room_id); printf("%s\n", message + 1); //Add one to skip MESSAGE_START character free(message); message = NULL; } void remove_client(table_entry_t *user, char *server_msg_prefixed, char **who_messages){ int room_id = user->room_id; char *username = user->id; char *server_msg = server_msg_prefixed + 1; //Print message to server terminal printf("**%s in room #%d left the server**\n", username, room_id); //Print message to chat room sprintf(server_msg, SERVER_PREFIX "%s left the server", username); send_message_to_all(room_id, server_msg_prefixed, strlen(server_msg_prefixed) + 1); //Remove user entry from server and set who_messages for rebuild remove_user(&user); who_messages[room_id][0] = '\0'; } static void terminate_server(int sig_num){ //Turn echoing back on struct termios tc; tcgetattr(STDIN_FILENO, &tc); tc.c_lflag |= (ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &tc); exit(EXIT_SUCCESS); } void shutdown_server(char **who_messages){ int client_socket = 0; int message_size = 0; table_entry_t *user, *tmp; const char *server_msg_literal = NULL; //Create server-shutdown message server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "The server has been shutdown by an admin"; message_size = strlen(server_msg_literal) + 1; //Free user messages, close client sockets, and delete users from hash table for(int room_id = 0; room_id < MAX_ROOMS; room_id++){ HASH_ITER(hh, active_users[room_id], user, tmp){ //Uthash deletion-safe iteration if(user->message){ free(user->message); user->message = NULL; } client_socket = user->socket_fd; send_message(client_socket, server_msg_literal, message_size); check_status(close(client_socket), "Error closing client socket"); delete_user(&user); } } //Free who_message strings for(int i = 0; i < MAX_ROOMS; i++){ free(who_messages[i]); who_messages[i] = NULL; } }<file_sep>/chat_server/src/server_shared.h #ifndef CHAT_SERVER_COMMON_H #define CHAT_SERVER_COMMON_H #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <errno.h> #include <stdint.h> #include <ctype.h> #include <time.h> #include <pthread.h> #include <netinet/in.h> #include <poll.h> #include <sqlite3.h> #include <sodium.h> #include <uthash.h> #define MAX_ROOMS 11 #define LOBBY_ROOM_ID 0 #define USERNAME_SIZE 16 #define PASSWORD_SIZE_MIN 4 #define PASSWORD_SIZE_MAX 16 #define MESSAGE_SIZE 256 #define WHO_MESSAGE_SIZE 32 //NOTE: Array will be reallocated if needed #define MESSAGE_END 0x03 //End-of-Text control character #define MESSAGE_START 0x02 //Start-of-Text control character #define MESSAGE_START_STR "\x02" //Start-of-Text control character as a string #define SERVER_PREFIX "Server: " //Message prefix for server messages #define PUBLIC_PREFIX ": " //Message prefix for public messages #define PRIVATE_PREFIX ">> " //Message prefix for private messages #define PWHASH_OPSLIMIT crypto_pwhash_OPSLIMIT_INTERACTIVE //Use crypto_pwhash_OPSLIMIT_MODERATE for higher security #define PWHASH_MEMLIMIT crypto_pwhash_MEMLIMIT_INTERACTIVE //Use crypto_pwhash_MEMLIMIT_MODERATE for higher security typedef struct { char id[USERNAME_SIZE]; bool is_admin; int room_id; size_t index; int socket_fd; char ip[INET_ADDRSTRLEN]; unsigned short port; char *message; size_t message_size; UT_hash_handle hh; } table_entry_t; extern int socket_count; extern struct pollfd socket_fds[]; extern table_entry_t *active_users[]; extern short spam_message_count[]; //Spam message counters for each client extern short spam_timeout[]; //Spam timeout for each client extern pthread_mutex_t spam_lock; extern sqlite3 *user_db; #endif<file_sep>/chat_server/src/server_commands.h #ifndef CHAT_SERVER_COMMANDS_H #define CHAT_SERVER_COMMANDS_H #include "server_shared.h" #include "server_utils.h" void whois_cmd(int, table_entry_t *, char *); void whois_arg_cmd(int, table_entry_t *, char *, char *); void who_cmd(int, char **); void who_arg_cmd(int, int, char *, char *, char **); void join_cmd(int); void join_arg_cmd(int, table_entry_t **, char *, char *, char **); void nick_cmd(table_entry_t *, char *); void nick_arg_cmd(int, table_entry_t **, char *, char *, char **); void where_cmd(table_entry_t *, char *); void where_arg_cmd(int, int, char *, char *); void kick_cmd(int); void kick_arg_cmd(int, table_entry_t *, table_entry_t **, char *, char *, char **); void register_cmd(int); void register_arg_cmd(int, table_entry_t *, char *, char *); void unregister_cmd(int); void unregister_arg_cmd(int, table_entry_t *, char *, char *); void admin_cmd(int); void admin_arg_cmd(int, table_entry_t *, char *, char *); bool die_cmd(table_entry_t *); #endif<file_sep>/chat_client/src/client.c #include "client.h" WINDOW *chat_win; WINDOW *text_win; pthread_attr_t incoming_tattr; pthread_t incoming_tid; pthread_mutex_t connected_lock; pthread_mutex_t incoming_lock; pthread_cond_t incoming_cond; int input_length = 0; /*------Thread shared variables------*/ bool connected = false; ssize_t bytes_recv = 0; char server_message[MESSAGE_SIZE + 1]; /*-----------------------------------*/ int main(int argc, char *argv[]){ server_message[MESSAGE_SIZE] = '\0'; char *ip = DEFAULT_IP_ADDRESS; unsigned int port = DEFAULT_PORT_NUMBER; //Setup signal handlers to properly close ncurses signal(SIGINT, shutdown_handler); //CTRL + C signal(SIGQUIT, shutdown_handler); //CTRL + BACKSLASH signal(SIGSEGV, shutdown_handler); //Memory access violation //Get user-specified IP and port from CLI arguments if(argc > 2){ ip = argv[1]; port = atoi(argv[2]); }else if(argc > 1){ //Check if the first argument is an IP address char *first_argument = argv[1]; if(strchr(first_argument, '.') || strchr(first_argument, ':')){ ip = first_argument; }else{ port = atoi(first_argument); } } initialize_chat(); initialize_connection(ip, port); //Initialize mutex locks pthread_mutex_init(&connected_lock, NULL); pthread_mutex_init(&incoming_lock, NULL); pthread_cond_init(&incoming_cond, NULL); //Create thread for incoming messages in a detached state if(pthread_attr_init(&incoming_tattr)){ perror("Error initializing pthread attribute"); exit(EXIT_FAILURE); } if(pthread_attr_setdetachstate(&incoming_tattr, PTHREAD_CREATE_DETACHED)){ perror("Error setting pthread detach state"); exit(EXIT_FAILURE); } if(pthread_create(&incoming_tid, &incoming_tattr, incoming_messages, NULL)){ perror("Error creating pthread"); exit(EXIT_FAILURE); } if(pthread_attr_destroy(&incoming_tattr)){ perror("Error destroying pthread attribute"); exit(EXIT_FAILURE); } outgoing_messages(); pthread_mutex_destroy(&connected_lock); pthread_mutex_destroy(&incoming_lock); pthread_cond_destroy(&incoming_cond); shutdown_chat(); return 0; } void initialize_chat(){ initscr(); check_status(noecho(), "Error setting noecho state for ncurses"); check_status(cbreak(), "Error setting cbreak state for ncurses"); //Create new windows for chat text and text entry chat_win = newwin(LINES - 1, COLS, 0, 0); text_win = newwin(1, COLS, LINES - 1, 0); //Enable scrolling for chat window idlok(chat_win, TRUE); scrollok(chat_win, TRUE); //Disable scrolling for text-entry window and enable keypad scrollok(text_win, FALSE); check_status(keypad(text_win, TRUE), "Error enabling keypad for text window"); wtimeout(text_win, 50); //Lower timeout if incoming messages print too slow //Print text-input prompt message mvwprintw(text_win, 0, 0, INPUT_INDICATOR); //Get maximum input length from either screen size or buffer if((COLS - 11) < (MESSAGE_SIZE - 2)){ input_length = COLS - 11; }else{ input_length = MESSAGE_SIZE - 2; //Remove 2 for start and end control characters } //Refresh windows so they appear on screen wrefresh(chat_win); wrefresh(text_win); } void initialize_connection(char *ip, int port){ //int bytes_recv; char response[MESSAGE_SIZE]; bytes_recv = join_server(ip, port, response); if(bytes_recv < 0){ wprintw(chat_win, "\n\n %s\n", response); wprintw(chat_win, " -Ensure IP address and port number are correct-\n"); wprintw(chat_win, " -The chat client will close shortly-\n"); wrefresh(chat_win); wrefresh(text_win); //Move cursor back to text window sleep(10); shutdown_chat(); } connected = true; print_to_chat(response, &bytes_recv); } void *incoming_messages(){ ssize_t status; char message[MESSAGE_SIZE + 1]; message[MESSAGE_SIZE] = '\0'; while(1){ status = receive_message(message, MESSAGE_SIZE); if(status <= 0){ pthread_mutex_lock(&connected_lock); connected = false; pthread_mutex_unlock(&connected_lock); if(status == 0){ wprintw(chat_win, "\n\n -The connection to the server has been lost-\n"); wprintw(chat_win, " -The chat client will close shortly-\n"); }else{ wprintw(chat_win, "\n\n -An unknown error has occurred-\n"); wprintw(chat_win, " -The chat client will close shortly-\n"); } wrefresh(chat_win); wrefresh(text_win); //Move cursor back to text window sleep(10); shutdown_chat(); } //Copy message to ncurses buffer to be printed pthread_mutex_lock(&incoming_lock); bytes_recv = status; memcpy(server_message, message, bytes_recv); pthread_cond_wait(&incoming_cond, &incoming_lock); pthread_mutex_unlock(&incoming_lock); } } void outgoing_messages(){ int status = 0; int cmd_length = 0; int password_index = 0; size_t message_size = 1; //Size one to hold NUL character char client_message[MESSAGE_SIZE]; client_message[0] = '\0'; do{ pthread_mutex_lock(&incoming_lock); if(bytes_recv > 0){ //Print received message to chat window print_to_chat(server_message, &bytes_recv); //Signal incoming_messages to receive next message pthread_cond_signal(&incoming_cond); } pthread_mutex_unlock(&incoming_lock); //Ignore blank and incomplete messages if(!get_user_message(client_message, &message_size, &password_index)){ continue; } if(client_message[0] == '/'){ /* --------------------- */ /* Process local command */ /* --------------------- */ local_commands(client_message, message_size); //Or fall through to send command to server } /* --------------------------- */ /* Send user message to server */ /* --------------------------- */ status = send_message(client_message, message_size); check_status(status, "Error sending message to server"); //Clear message if it contains a password if(password_index){ secure_zero(client_message + password_index, message_size - password_index); message_size = password_index + 1; //Plus one to include the NUL character password_index = 0; } }while(strcmp(client_message, "/q") && strcmp(client_message, "/quit") && strcmp(client_message, "/exit")); wprintw(chat_win, "\n -Leaving chat server-\n"); wrefresh(chat_win); wrefresh(text_win); //Move cursor back to text window } bool get_user_message(char *message, size_t *message_size, int *password_index){ static char buffer[MESSAGE_SIZE]; static char display[MESSAGE_SIZE]; static char *password_ptr = NULL; static int buffer_char; static int display_char; static int cmd_length; static int pos; //Current position static int end; //End position //Ignore user input if not connected to server pthread_mutex_lock(&connected_lock); if(!connected){ pthread_mutex_unlock(&connected_lock); sleep(10); //Wait for chat server to close } pthread_mutex_unlock(&connected_lock); //Get character from user buffer_char = wgetch(text_win); if(buffer_char == ERR){ //Return so incoming messages can be printed return false; }else if(buffer_char == KEY_LEFT){ //Move cursor left if(pos > 0){ pos--; wmove(text_win, 0, INPUT_START + pos); } }else if(buffer_char == KEY_RIGHT){ //Move cursor right if(pos < end){ pos++; wmove(text_win, 0, INPUT_START + pos); } }else if(buffer_char == KEY_UP){ //Insert previous sent message into buffer end = *message_size - 1; pos = end; for(int i = 0; i < end; i++){ buffer_char = message[i]; buffer[i] = buffer_char; mvwprintw(text_win, 0, INPUT_START + i, "%c", buffer_char); } buffer[end] = '\0'; if(*password_index){ *password_index = 0; } wmove(text_win, 0, INPUT_START + pos); wclrtoeol(text_win); }else if(buffer_char == KEY_DOWN){ //Clear the current buffer end = 0; pos = 0; buffer[end] = '\0'; if(*password_index){ *password_index = 0; } wmove(text_win, 0, INPUT_START); wclrtoeol(text_win); }else if(buffer_char == KEY_BACKSPACE){ //Erase character to left of cursor if(pos > 0){ //Shift remaining characters to the left for(int i = pos; i < end; i++){ buffer[i - 1] = buffer[i]; display[i - 1] = display[i]; mvwprintw(text_win, 0, INPUT_START + i - 1, "%c", display[i]); } //Insert empty character at the end of the message pos--; end--; buffer[end] = '\0'; if(*password_index && end <= *password_index){ *password_index = 0; } mvwprintw(text_win, 0, INPUT_START + end, " "); wmove(text_win, 0, INPUT_START + pos); } }else if(buffer_char == KEY_DC){ //Erase character to right of cursor if(pos < end){ //Shift remaining characters to the left for(int i = pos; i < end - 1; i++){ buffer[i] = buffer[i + 1]; display[i] = display[i + 1]; mvwprintw(text_win, 0, INPUT_START + i, "%c", display[i + 1]); } //Insert empty character at the end of the message end--; buffer[end] = '\0'; if(*password_index && end <= *password_index){ *password_index = 0; } mvwprintw(text_win, 0, INPUT_START + end, " "); wmove(text_win, 0, INPUT_START + pos); } }else if(end < input_length && (buffer_char >= 0x20 && buffer_char <= 0x7E)){ //Write character to buffer //Shift remaining characters to the right for(int i = end; i > pos; i--){ buffer[i] = buffer[i - 1]; display[i] = display[i - 1]; mvwprintw(text_win, 0, INPUT_START + i, "%c", display[i]); } //Hide on-screen passwords with asterisks display_char = buffer_char; if(buffer_char != ' '){ if(*password_index){ display_char = '*'; }else if(strncmp(buffer, "/nick ", cmd_length = 6) == 0 || strncmp(buffer, "/register ", cmd_length = 10) == 0 || strncmp(buffer, "/unregister ", cmd_length = 12) == 0){ //Due to short circuiting, cmd_length will have the correct value if(password_ptr = memchr(buffer + cmd_length, ' ', end - cmd_length + 1)){ *password_index = password_ptr + 1 - buffer; display_char = '*'; } } } //Insert new character at the cursor position wmove(text_win, 0, INPUT_START + pos); wprintw(text_win, "%c", display_char); buffer[pos] = buffer_char; display[pos] = display_char; pos++; end++; buffer[end] = '\0'; }else if(end > 0 && buffer_char == '\n'){ //Process completed message //Copy buffer to external message and set message_size buffer[end] = '\0'; *message_size = end + 1; strncpy(message, buffer, *message_size); //Clear buffer if it contains a password if(*password_index){ secure_zero(buffer + *password_index, *message_size - *password_index); } //Move cursor to starting position and clear the line wmove(text_win, 0, INPUT_START); wclrtoeol(text_win); wrefresh(text_win); //Reset buffers and positions for next message buffer[0] = '\0'; display[0] = '\0'; pos = 0; end = 0; //Return true so caller knows to process the completed message return true; } wrefresh(text_win); //Return false on incomplete/empty buffer so caller doesn't process it return false; } void local_commands(char *user_message, size_t message_size){ int cmd_length = 0; //Clear chat window if(strcmp(user_message, "/clear") == 0){ werase(chat_win); wrefresh(chat_win); wrefresh(text_win); //Move cursor back to text window return; } //Change window colours if(strncmp(user_message, "/colour", 7) == 0){ //Convert british spelling "colour" to "color" for(int i = 5; i < message_size; i++){ user_message[i] = user_message[i+1]; } } if(strncmp(user_message, "/color", cmd_length = 6) == 0){ if(!has_colors()){ return; } use_default_colors(); start_color(); init_pair(0, -1, -1); //Default colours init_pair(1, COLOR_WHITE, COLOR_BLUE); init_pair(2, COLOR_WHITE, COLOR_BLACK); static int color = 0; if(user_message[cmd_length] == '\0'){ color = (color + 1) % 2; wbkgd(chat_win, COLOR_PAIR(color)); //Colour pair 0 or 1 wbkgd(text_win, COLOR_PAIR(color * 2)); //Colour pair 0 or 2 }else if(strncmp(user_message + cmd_length + 1, "off", 4) == 0){ wbkgd(chat_win, COLOR_PAIR(0)); wbkgd(text_win, COLOR_PAIR(0)); color = 0; }else if(strncmp(user_message + cmd_length + 1, "on", 3) == 0){ wbkgd(chat_win, COLOR_PAIR(1)); wbkgd(text_win, COLOR_PAIR(2)); color = 1; }else{ return; } wrefresh(chat_win); wrefresh(text_win); return; } } void print_to_chat(char *message, size_t *bytes){ int pos = 0; int character = '\0'; while(*bytes > 0){ character = message[pos]; if(character == MESSAGE_START){ wprintw(chat_win, "\n"); print_time(); //Print timestamp to chat window }else{ wprintw(chat_win, "%c", character); } message++; (*bytes)--; } wrefresh(chat_win); wrefresh(text_win); //Move cursor back to text window } void print_time(){ time_t raw_time = time(NULL); struct tm *cur_time; //Get local time time(&raw_time); cur_time = localtime(&raw_time); //Print time to chat window at current cursor location wprintw(chat_win, "%02d:%02d ", cur_time->tm_hour, cur_time->tm_min); wrefresh(chat_win); wrefresh(text_win); //Move cursor back to text window } //Function used to clear passwords from memory void secure_zero(volatile void *s, size_t n){ if(s == NULL){return;} volatile uint8_t *p = s; //Use volatile to prevent compiler optimization while(n > 0){ *p = 0; p++; n--; } } void shutdown_chat(){ check_status(endwin(), "Error closing ncurses"); exit(0); } static void shutdown_handler(int sig_num){ shutdown_chat(); } <file_sep>/chat_server/src/server_commands.c #include "server_commands.h" void whois_cmd(int cmd_length, table_entry_t *user, char *client_msg){ if(user == NULL){ return; } char *username = user->id; //Setup "/whois" command with the client's own username client_msg[cmd_length] = ' '; client_msg[cmd_length + 1] = '\0'; strncat(client_msg, username, MESSAGE_SIZE); } void whois_arg_cmd(int cmd_length, table_entry_t *user, char *client_msg, char *server_msg_prefixed){ if(user == NULL){ return; } int client_socket = user->socket_fd; char *username = user->id; char *server_msg = server_msg_prefixed + 1; const char *server_msg_literal = NULL; char *target_username = NULL; //Get username from client's message get_username_and_passwords(cmd_length, client_msg, &target_username, NULL, NULL); //Check if the username is valid if(is_username_invalid(target_username, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } if(strcmp(target_username, username) == 0){ sprintf(server_msg, SERVER_PREFIX "Your address is %s:%d", user->ip, user->port); }else{ //Check if client isn't an admin if(!user->is_admin){ server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Only server admins can use the /whois command"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return; } //Get user from active_users hash table table_entry_t *target = find_user(target_username); if(target == NULL){ //Username does not exist sprintf(server_msg, SERVER_PREFIX "The user \"%s\" does not exist", target_username); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } sprintf(server_msg, SERVER_PREFIX "The address of \"%s\" is %s:%d", target_username, target->ip, target->port); } send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } void who_cmd(int client_socket, char **who_messages){ for(int i = 1; i < MAX_ROOMS; i++){ //i = 1 to skip lobby //Rebuild who_messages strings if necessary rebuild_who_message(who_messages, i); //Send message containing current users in room #i send_message(client_socket, who_messages[i], strlen(who_messages[i]) + 1); } } void who_arg_cmd(int cmd_length, int client_socket, char *client_msg, char *server_msg_prefixed, char **who_messages){ char *server_msg = server_msg_prefixed + 1; //Check if argument after /who is valid if(!isdigit(client_msg[cmd_length])){ sprintf(server_msg, SERVER_PREFIX "Enter a valid room number (1 to %d) after /who", MAX_ROOMS - 1); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Get room number from user char *target_room = client_msg + cmd_length; int target_room_id = atoi(target_room); //Check if chat room is valid if(target_room_id >= MAX_ROOMS || target_room_id < 0){ sprintf(server_msg, SERVER_PREFIX "Specified room doesn't exist (valid rooms are 1 to %d)", MAX_ROOMS - 1); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Rebuild who_messages strings if necessary rebuild_who_message(who_messages, target_room_id); //Send message containing current users in the specified room send_message(client_socket, who_messages[target_room_id], strlen(who_messages[target_room_id]) + 1); } void join_cmd(int client_socket){ const char *server_msg_literal = NULL; server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Type \"/join <room_number>\" to join a room"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); } void join_arg_cmd(int cmd_length, table_entry_t **user, char *client_msg, char *server_msg_prefixed, char **who_messages){ if(user == NULL || *user == NULL){ return; } int room_id = (*user)->room_id; int client_socket = (*user)->socket_fd; char *username = (*user)->id; char *server_msg = server_msg_prefixed + 1; //Check if argument after /join is valid if(!isdigit(client_msg[cmd_length])){ sprintf(server_msg, SERVER_PREFIX "Enter a valid room number (0 to %d) after /join", MAX_ROOMS - 1); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Get new room number from user char *new_room = client_msg + cmd_length; int new_room_id = atoi(new_room); //Check if chat room is valid if(new_room_id >= MAX_ROOMS || new_room_id < 0){ sprintf(server_msg, SERVER_PREFIX "Specified room doesn't exist (valid rooms are 0 to %d)", MAX_ROOMS - 1); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Check if already in the room if(room_id == new_room_id){ sprintf(server_msg, SERVER_PREFIX "You are already in room #%d", room_id); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Print client joining message to the server's terminal printf("**%s changed from room #%d to room #%d**\n", username, room_id, new_room_id); //Send message letting clients in new room know someone joined the room sprintf(server_msg, SERVER_PREFIX "User \"%s\" joined the chat room", username); send_message_to_all(new_room_id, server_msg_prefixed, strlen(server_msg_prefixed) + 1); //Move user to the new chat room table_entry_t *tmp = NULL; tmp = add_user(username, (*user)->is_admin, new_room_id, (*user)->index, (*user)->socket_fd, (*user)->ip, (*user)->port); delete_user(user); *user = tmp; //Send message letting clients in old chat room know someone changed rooms sprintf(server_msg, SERVER_PREFIX "User \"%s\" switched to chat room #%d", username, new_room_id); send_message_to_all(room_id, server_msg_prefixed, strlen(server_msg_prefixed) + 1); //Send message to client who just joined the room sprintf(server_msg, SERVER_PREFIX "You have joined chat room #%d", new_room_id); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); //Set both room's who_messages for rebuild who_messages[room_id][0] = '\0'; who_messages[new_room_id][0] = '\0'; } void nick_cmd(table_entry_t *user, char *server_msg_prefixed){ int client_socket = user->socket_fd; char *username = user->id; char *server_msg = server_msg_prefixed + 1; sprintf(server_msg, SERVER_PREFIX "Your username is \"%s\"", username); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } void nick_arg_cmd(int cmd_length, table_entry_t **user, char *client_msg, char *server_msg_prefixed, char **who_messages){ if(user == NULL || *user == NULL){ return; } int room_id = (*user)->room_id; int client_socket = (*user)->socket_fd; char *server_msg = server_msg_prefixed + 1; const char *server_msg_literal = NULL; int status; char *query = NULL; sqlite3_stmt *stmt = NULL; char old_name[USERNAME_SIZE]; char *new_name = NULL; char *user_type = NULL; char *password = NULL; char *db_hashed_password = NULL; strncpy(old_name, (*user)->id, USERNAME_SIZE); //Get username and one password from client's message get_username_and_passwords(cmd_length, client_msg, &new_name, &password, NULL); //Check if username is invalid if(is_username_invalid(new_name, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Check if client already has the username if(strcmp(old_name, new_name) == 0){ sprintf(server_msg, SERVER_PREFIX "Your username is already \"%s\"", new_name); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Check if username is registered in database query = "SELECT password FROM users WHERE id = ?1;"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, new_name, -1, SQLITE_STATIC); if((status = sqlite3_step(stmt)) == SQLITE_ROW){ db_hashed_password = strdup((char *) sqlite3_column_text(stmt, 0)); }else if(status != SQLITE_DONE){ fprintf(stderr, "SQL error while getting password: %s\n", sqlite3_errmsg(user_db)); return; } sqlite3_finalize(stmt); if(db_hashed_password){ //Username requires a password //Return error message if client did not specify a password if(password == NULL){ sprintf(server_msg, SERVER_PREFIX "The username \"%s\" requires a password", new_name); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); free(db_hashed_password); db_hashed_password = <PASSWORD>; return; } //Check if password is valid if(is_password_invalid(password, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); free(db_hashed_password); db_hashed_password = <PASSWORD>; return; } //Check if password is incorrect if(is_password_incorrect(new_name, password, db_hashed_password)){ server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "The specified password was incorrect"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return; } free(db_hashed_password); db_hashed_password = <PASSWORD>; //Get user type from the database query = "SELECT type FROM users WHERE id = ?1;"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, new_name, -1, SQLITE_STATIC); if((status = sqlite3_step(stmt)) == SQLITE_ROW){ user_type = strdup((char *) sqlite3_column_text(stmt, 0)); }else if(status != SQLITE_DONE){ fprintf(stderr, "SQL error while getting user type: %s\n", sqlite3_errmsg(user_db)); } sqlite3_finalize(stmt); }else{ //If not registered, check if username is restricted if(is_username_restricted(new_name, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } } //Check if username is already in use on the server if(find_user(new_name)){ sprintf(server_msg, SERVER_PREFIX "The username \"%s\" is currently in use", new_name); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Check if database returned an admin user type if(user_type && strcmp(user_type, "admin") == 0){ (*user)->is_admin = true; }else{ (*user)->is_admin = false; } free(user_type); user_type = NULL; //Change username in active_users hash table change_username(user, new_name); //Set who_messages for rebuild who_messages[room_id][0] = '\0'; //Print name change message to server's terminal printf("**%s on socket %d changed username to %s**\n", old_name, client_socket, new_name); //Send name change message to all clients if not in lobby if(room_id == LOBBY_ROOM_ID){ sprintf(server_msg, SERVER_PREFIX "Your username has changed to \"%s\"", new_name); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); }else{ sprintf(server_msg, SERVER_PREFIX "%s changed their name to %s", old_name, new_name); send_message_to_all(room_id, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } } void where_cmd(table_entry_t *user, char *server_msg_prefixed){ int client_socket = user->socket_fd; int room_id = user->room_id; char *server_msg = server_msg_prefixed + 1; const char *server_msg_literal = NULL; if(room_id == 0){ server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "You are currently in the lobby"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); }else{ sprintf(server_msg, SERVER_PREFIX "You are currently in chat room #%d", room_id); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } } void where_arg_cmd(int cmd_length, int client_socket, char *client_msg, char *server_msg_prefixed){ char *server_msg = server_msg_prefixed + 1; char *target_username = NULL; //Get username from client message get_username_and_passwords(cmd_length, client_msg, &target_username, NULL, NULL); //Check if the username is invalid if(is_username_invalid(target_username, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Look for target user and return their location table_entry_t *target_user = find_user(target_username); if(target_user){ int room_id = target_user->room_id; if(room_id == LOBBY_ROOM_ID){ sprintf(server_msg, SERVER_PREFIX "\"%s\" is currently in the lobby", target_username); }else{ sprintf(server_msg, SERVER_PREFIX "\"%s\" is currently in chat room #%d", target_username, room_id); } }else{ sprintf(server_msg, SERVER_PREFIX "\"%s\" is currently not on the server", target_username); } //Inform client about the specified user send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } void kick_cmd(int client_socket){ const char *server_msg_literal = NULL; server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Type \"/kick <username>\" to kick users"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); } void kick_arg_cmd(int cmd_length, table_entry_t *user, table_entry_t **tmp, char *client_msg, char *server_msg_prefixed, char **who_messages){ if(user == NULL || tmp == NULL){ return; } int room_id = user->room_id; int client_socket = user->socket_fd; char *username = user->id; char *server_msg = server_msg_prefixed + 1; const char *server_msg_literal = NULL; char *target_username = NULL; //Check if client isn't an admin if(!user->is_admin){ server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Only server admins can use the /kick command"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return; } //Get username from client's message get_username_and_passwords(cmd_length, client_msg, &target_username, NULL, NULL); //Check if the username is invalid if(is_username_invalid(target_username, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Prevent client from kicking themself if(strcmp(username, target_username) == 0){ server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Using /kick on yourself is prohibited"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return; } //Look for user and perform the kick if located int target_room = 0; table_entry_t *target_user = find_user(target_username); if(target_user){ target_room = target_user->room_id; //Get tmp's hh.next for hash table iteration if removing tmp if(*tmp == target_user){ *tmp = (*tmp)->hh.next; //Avoids accessing removed user } //Inform target_user that they have been kicked server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "You have been kicked from the server"; send_message(target_user->socket_fd, server_msg_literal, strlen(server_msg_literal) + 1); //Remove client entry from server remove_user(&target_user); //Set who_messages for rebuild who_messages[target_room][0] = '\0'; //Print kick message to server's terminal printf("**%s in room #%d kicked from the server**\n", target_username, target_room); //Inform the chat room about the kick sprintf(server_msg, SERVER_PREFIX "\"%s\" has been kicked from the server", target_username); send_message_to_all(target_room, server_msg_prefixed, strlen(server_msg_prefixed) + 1); //Also inform client if they are in a different room or the lobby if(room_id != target_room || target_room == LOBBY_ROOM_ID){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } }else{ //Inform client that user was not found sprintf(server_msg, SERVER_PREFIX "\"%s\" is currently not on the server", target_username); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } } void register_cmd(int client_socket){ const char *server_msg_literal = NULL; server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Type \"/register <username> <password> <password>\" to register"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); } void register_arg_cmd(int cmd_length, table_entry_t *user, char *client_msg, char *server_msg_prefixed){ if(user == NULL){ return; } int client_socket = user->socket_fd; char *username = user->id; char *server_msg = server_msg_prefixed + 1; const char *server_msg_literal = NULL; int status; char *query = NULL; sqlite3_stmt *stmt; char *new_name = NULL; char *password = NULL; char *password2 = NULL; char hashed_password[crypto_pwhash_STRBYTES]; bool user_exists = false; bool is_new_user = false; //Get username and passwords from client's message get_username_and_passwords(cmd_length, client_msg, &new_name, &password, &password2); //Check if username is invalid if(is_username_invalid(new_name, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //If not an admin, check if username is restricted if(!user->is_admin && is_username_restricted(new_name, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Check if username already exists in database query = "SELECT id FROM users WHERE id = ?1;"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, new_name, -1, SQLITE_STATIC); if((status = sqlite3_step(stmt)) == SQLITE_ROW){ user_exists = true; }else if(status != SQLITE_DONE){ fprintf(stderr, "SQL error while checking if username exists: %s\n", sqlite3_errmsg(user_db)); return; } sqlite3_finalize(stmt); if(user_exists){ //Check if client is the registered database user if(strcmp(username, new_name) == 0){ //Setup query for changing a registered user's password query = "UPDATE users SET password = ?2 WHERE id = ?1;"; is_new_user = false; }else{ //Inform client that username is already registered sprintf(server_msg, SERVER_PREFIX "The username \"%s\" is already registered", new_name); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } }else{ //Setup query for registering a new user query = "INSERT INTO users(id, password, type) VALUES(?1, ?2, 'user');"; is_new_user = true; } //Check if passwords are valid if(are_passwords_invalid(password, password2, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Hash password with libsodium if(crypto_pwhash_str(hashed_password, password, strlen(password), PWHASH_OPSLIMIT, PWHASH_MEMLIMIT) != 0){ fprintf(stderr, "Ran out of memory during hash function\n"); return; } //Perform SQL query for either new user or password change sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, new_name, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 2, hashed_password, -1, SQLITE_STATIC); status = sqlite3_step(stmt); sqlite3_finalize(stmt); if(is_new_user){ if(status != SQLITE_DONE){ fprintf(stderr, "SQL error while registering username: %s\n", sqlite3_errmsg(user_db)); return; }else{ //Print username registration message to server's terminal printf("**%s on socket %d registered username %s**\n", username, client_socket, new_name); //Inform client of username registration sprintf(server_msg, SERVER_PREFIX "You have registered the username \"%s\"", new_name); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } }else{ if(status != SQLITE_DONE){ fprintf(stderr, "SQL error while changing user password: %s\n", sqlite3_errmsg(user_db)); return; }else{ //Print password change message to server's terminal printf("**%s on socket %d changed their password**\n", username, client_socket); //Inform client of password change server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Your username password has changed"; send_message(client_socket, server_msg_literal, strlen(server_msg_prefixed) + 1); } } } void unregister_cmd(int client_socket){ const char *server_msg_literal = NULL; server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Type \"/unregister <username> <password>\" to unregister"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); } void unregister_arg_cmd(int cmd_length, table_entry_t *user, char *client_msg, char *server_msg_prefixed){ if(user == NULL){ return; } int client_socket = user->socket_fd; char *username = user->id; char *server_msg = server_msg_prefixed + 1; const char *server_msg_literal = NULL; int status; char *query = NULL; sqlite3_stmt *stmt; char *target_username = NULL; char *password = NULL; char *password2 = NULL; char *db_hashed_password = NULL; char hashed_password[crypto_pwhash_STRBYTES]; //Get username and passwords from client's message get_username_and_passwords(cmd_length, client_msg, &target_username, &password, &password2); //Check if username is invalid if(is_username_invalid(target_username, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Prevent unregistering main admin account if(strcmp(target_username, "Admin") == 0){ server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Unregistering the main admin account is prohibited"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return; } //Check if username is registered in database query = "SELECT password FROM users WHERE id = ?1;"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, target_username, -1, SQLITE_STATIC); if((status = sqlite3_step(stmt)) == SQLITE_ROW){ db_hashed_password = strdup((char *) sqlite3_column_text(stmt, 0)); }else if(status != SQLITE_DONE){ fprintf(stderr, "SQL error while getting password: %s\n", sqlite3_errmsg(user_db)); return; } sqlite3_finalize(stmt); if(!db_hashed_password){ //Inform client that username is not registered sprintf(server_msg, SERVER_PREFIX "The username \"%s\" is not registered", target_username); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Check password if not an admin if(!user->is_admin){ //Check if password is valid if(is_password_invalid(password, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Check if password is incorrect if(is_password_incorrect(target_username, password, db_hashed_password)){ server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "The specified password was incorrect"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return; } free(db_hashed_password); db_hashed_password = NULL; } //Perform SQL query for unregistering a username query = "DELETE FROM users WHERE id = ?1;"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, target_username, -1, SQLITE_STATIC); status = sqlite3_step(stmt); sqlite3_finalize(stmt); if(status != SQLITE_DONE){ fprintf(stderr, "SQL error while unregistering username: %s\n", sqlite3_errmsg(user_db)); return; } //Print username unregistration message to server's terminal printf("**%s on socket %d unregistered username %s**\n", username, client_socket, target_username); //Inform client and target user of username unregistration table_entry_t *target_user = NULL; if(strncmp(username, target_username, USERNAME_SIZE) == 0){ target_user = user; sprintf(server_msg, SERVER_PREFIX "You have unregistered your username \"%s\"", target_username); }else{ target_user = find_user(target_username); if(target_user){ sprintf(server_msg, SERVER_PREFIX "Your username \"%s\" has been unregistered", target_username); send_message(target_user->socket_fd, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } sprintf(server_msg, SERVER_PREFIX "You have unregistered the username \"%s\"", target_username); } send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); //Change user type to "user" if it is "admin" if(target_user && target_user->is_admin){ target_user->is_admin = false; } } void admin_cmd(int client_socket){ const char *server_msg_literal = NULL; server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Type \"/admin <username>\" to change account type"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); } void admin_arg_cmd(int cmd_length, table_entry_t *user, char *client_msg, char *server_msg_prefixed){ if(user == NULL){ return; } int client_socket = user->socket_fd; char *username = user->id; char *server_msg = server_msg_prefixed + 1; const char *server_msg_literal = NULL; int status; char *query = NULL; sqlite3_stmt *stmt; char *target_username = NULL; char *user_type = NULL; char *type_change = NULL; //Allow usage for main admin account only if(strcmp(username, "Admin") != 0){ server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Only the \"Admin\" account can use the /admin command"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return; } //Get username from client's message get_username_and_passwords(cmd_length, client_msg, &target_username, NULL, NULL); //Check if the username is invalid if(is_username_invalid(target_username, server_msg)){ send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); return; } //Check if target user is the client if(strcmp(target_username, username) == 0){ //Inform client that changing their own account is prohibited server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Changing your own account type is prohibited"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return; } //Check if target user is the main admin account if(strcmp(target_username, "Admin") == 0){ //Inform client that changing the main admin account is prohibited server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Changing the main admin account type is prohibited"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return; } //Check if username is registered in database and get user type query = "SELECT type FROM users WHERE id = ?1;"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, target_username, -1, SQLITE_STATIC); if((status = sqlite3_step(stmt)) == SQLITE_ROW){ user_type = strdup((char *) sqlite3_column_text(stmt, 0)); }else if(status != SQLITE_DONE){ fprintf(stderr, "SQL error while getting user type: %s\n", sqlite3_errmsg(user_db)); return; } sqlite3_finalize(stmt); if(user_type){ //Get the account type to switch to if(strcmp(user_type, "admin") == 0){ type_change = "user"; }else{ type_change = "admin"; } free(user_type); user_type = NULL; //Switch target user's account type in database query = "UPDATE users SET type = ?1 WHERE id = ?2;"; sqlite3_prepare_v2(user_db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, type_change, -1, SQLITE_STATIC); sqlite3_bind_text(stmt, 2, target_username, -1, SQLITE_STATIC); if(sqlite3_step(stmt) != SQLITE_DONE){ fprintf(stderr, "SQL error while changing user type: %s\n", sqlite3_errmsg(user_db)); sqlite3_finalize(stmt); return; } sqlite3_finalize(stmt); //Look for user on server and change account type if located table_entry_t *target_user = find_user(target_username); if(target_user){ //Switch account type target_user->is_admin = !target_user->is_admin; //Inform target user of account type change sprintf(server_msg, SERVER_PREFIX "Your account type has changed to \"%s\"", type_change); send_message(target_user->socket_fd, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } //Print account type change message to server's terminal printf("**Account \"%s\" changed to \"%s\" type**\n", target_username, type_change); //Inform client of account type change sprintf(server_msg, SERVER_PREFIX "Account \"%s\" changed to \"%s\" type", target_username, type_change); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); }else{ //Inform client that target user is not registered sprintf(server_msg, SERVER_PREFIX "The username \"%s\" is not registered", target_username); send_message(client_socket, server_msg_prefixed, strlen(server_msg_prefixed) + 1); } } bool die_cmd(table_entry_t *user){ if(user == NULL){ return false; } int client_socket = user->socket_fd; const char *server_msg_literal = NULL; //Check if user isn't an admin if(!user->is_admin){ server_msg_literal = MESSAGE_START_STR SERVER_PREFIX "Only server admins can use the /die command"; send_message(client_socket, server_msg_literal, strlen(server_msg_literal) + 1); return false; } //Flag server for shutdown return true; }<file_sep>/chat_server/Makefile CC = gcc CFLAGS = -I. DEBUG = -g -O0 DEPS = server.h server_utils.h server_commands.h server_shared.h OBJ = $(OBJDIR)/server.o $(OBJDIR)/server_utils.o $(OBJDIR)/server_commands.o LIBS = -lpthread -lsqlite3 -lsodium VPATH = src OBJDIR = obj $(OBJDIR)/%.o: %.c $(DEPS) $(CC) $(DEBUG) -c -o $@ $< $(CFLAGS) chatserver: $(OBJ) $(CC) $(DEBUG) -Wall -pedantic -o $@ $^ $(CFLAGS) $(LIBS) .PHONY: clean clean: rm -r chatserver $(OBJDIR) $(shell mkdir -p $(OBJDIR))
894e18c0799b6a51dd99cd9a9693b64b79b4347c
[ "Markdown", "C", "Makefile" ]
15
C
danielgilroy/TerminalChat
8d4d539a8b2d6b8cb3915b6079057a2d2cf66fc8
fb6ada6d7e4ee3ea2284470f84fcde9c86fbd992
refs/heads/main
<repo_name>danielzt12/s26_flyscan<file_sep>/README.md # flyscan control script at sector 26 APS using labjack python API <file_sep>/flyxy_eiger.py import sys import epics import epics.devices import numpy as np import time import h5py import netCDF4 import os import fabio from ljm_functions import * from multiprocessing import Process from readMDA import * scanrecord = "26idbSOFT" ljm_scaler = T7_ID26(3) ljm_fluo = T7_ID26(2) ljm_mpx = T7_ID26(1) ljm_eiger = T7_ID26(4) def get_detector_flags(): flag_fluo = 0 flag_eiger = 0 for i in range(1,5): det_name = epics.caget("26idbSOFT:scan1.T{0}PV".format(i)) if "XMAP" in det_name or "scanH" in det_name: flag_fluo = 1 elif 's26_eiger' in det_name: flag_eiger = 1 return flag_fluo, flag_eiger def flyxy_head(n_line, pts_per_line): flag_fluo, flag_eiger = get_detector_flags() epics.caput("26idaWBS:sft01:ph01:ao06.VAL", 1, wait=True) # set fly flag = 1 epics.caput("26idpvc:userCalc3.SCAN", 0, wait=True) # disable Martin's samy watchdog t0 = time.time() pathname = epics.caget(scanrecord+':saveData_fullPathName',as_string=True)[:-4] scannum = epics.caget(scanrecord+':saveData_scanNumber') epics.caput(scanrecord+':saveData_scanNumber', scannum+1) if not flag_eiger: # have to create the h5 file if eiger is not doing it pathname_h5 = os.path.join(pathname,"h5") filenum = epics.caget("s26_eiger_cnm:HDF1:FileNumber_RBV") h5file = os.path.join(pathname, "h5", "scan_{0}_{1:06d}.h5".format(scannum,filenum)) h5 = h5py.File(h5file, "w-") h5.close() print ("starting flyscan {0}\nactivating detectors....".format(scannum)), if flag_eiger: if epics.caget("s26_eiger_cnm:HDF1:FilePath", as_string=True) != (pathname+'h5/'): epics.caput("s26_eiger_cnm:HDF1:FilePath",os.path.join(pathname,'h5/'), wait=True) if epics.caget("s26_eiger_cnm:HDF1:EnableCallbacks") == 0: epics.caput("s26_eiger_cnm:HDF1:EnableCallbacks",1, wait=True) if epics.caget("s26_eiger_cnm:cam1:TriggerMode") != 3: epics.caput("s26_eiger_cnm:cam1:TriggerMode",3, wait=True) epics.caput("s26_eiger_cnm:HDF1:FileName",'scan_'+str(scannum), wait=True) epics.caput("s26_eiger_cnm:HDF1:NumCapture", n_line*pts_per_line, wait=True) epics.caput("s26_eiger_cnm:cam1:NumTriggers", n_line*pts_per_line, wait=True) epics.caput("s26_eiger_cnm:HDF1:Capture", 1) epics.caput("s26_eiger_cnm:cam1:Acquire", 1) time.sleep(0.1) epics.caput("s26_eiger_cnm:Stats1:TS:TSNumPoints", n_line*pts_per_line, wait=True) epics.caput("s26_eiger_cnm:Stats2:TS:TSNumPoints", n_line*pts_per_line, wait=True) epics.caput("s26_eiger_cnm:Stats3:TS:TSNumPoints", n_line*pts_per_line, wait=True) epics.caput("s26_eiger_cnm:Stats4:TS:TSNumPoints", n_line*pts_per_line, wait=True) epics.caput("s26_eiger_cnm:Stats1:TS:TSAcquire", 1) time.sleep(0.1) epics.caput("s26_eiger_cnm:Stats2:TS:TSAcquire", 1) time.sleep(0.1) epics.caput("s26_eiger_cnm:Stats3:TS:TSAcquire", 1) time.sleep(0.1) epics.caput("s26_eiger_cnm:Stats4:TS:TSAcquire", 1) time.sleep(0.1) else: epics.caput('s26_eiger_cnm:HDF1:FileNumber', filenum+1, wait=True) # increment filenum +1 if eiger not saved #epics.caput("26idc:3820:scaler1.CONT", 1) # enable scaler auto count for normalization #epics.caput("26idc:3820:scaler1.TP", 1) epics.caput("26idc:3820:ChannelAdvance", 1, wait=True) # set scaler to external trigger epics.caput("26idc:3820:Channel1Source", 1, wait=True) epics.caput("26idc:3820:InputMode", 3, wait=True) # set scaler input mode to 3 epics.caput("26idc:3820:NuseAll", pts_per_line, wait=True) # set channel to use to the nbpoints per line epics.caput("26idc:3820:PresetReal", 10000, wait=True) # set it to very long epics.caput("26idc:3820:scaler1.CONT", 0) # disable auto count, or it will get stuck if flag_fluo: epics.caput("26idcXMAP:CollectMode", 1, wait=True) #mca mapping epics.caput("26idcXMAP:PixelsPerRun", pts_per_line, wait=True) epics.caput("26idcXMAP:IgnoreGate", 0, wait=True) #very important pathname_fluo = os.path.join(pathname, "fluo") if not os.path.isdir(pathname_fluo): os.mkdir(pathname_fluo) os.chmod(pathname_fluo, 0o777) pathname_fluo = "T:"+pathname_fluo[5:] epics.caput("26idcXMAP:netCDF1:EnableCallbacks", 1, wait=True) # enable netcdf saving epics.caput("26idcXMAP:netCDF1:FilePath", pathname_fluo, wait=True) epics.caput("26idcXMAP:netCDF1:FileName", "scan_"+str(scannum), wait=True) epics.caput("26idcXMAP:netCDF1:FileTemplate", "%s%s_%6.6d.nc", wait=True) epics.caput("26idcXMAP:netCDF1:FileWriteMode", 2, wait=True) # stream epics.caput("26idcXMAP:netCDF1:NumCapture", n_line, wait=True) epics.caput("26idcXMAP:netCDF1:Capture", 1, wait=False) # capture fluo epics.caput("26idcXMAP:netCDF1:AutoIncrement", 1, wait=False) epics.caput("26idcXMAP:StartAll", 1) time.sleep(0.1) while((epics.caget("s26_eiger_cnm:HDF1:Capture")==0 and flag_eiger) or\ (epics.caget("26idcXMAP:netCDF1:Capture_RBV")==0 and flag_fluo)): time.sleep(1) ljm_scaler.write("DAC0", 3.3) # scaler is active low, need to set it to high at the beginning epics.caput("26idc:filter:Fi1:Set",0, wait=True) time.sleep(0.1) print ("completed in {0:.1f} sec".format(time.time()-t0)) def flyxy_tail(fastmotor, fastmotorvalues, slowmotor, slowmotorvalues, dwelltime, data_scaler): flag_fluo, flag_eiger = get_detector_flags() print ("returning config to normal...") pathname = epics.caget(scanrecord+':saveData_fullPathName',as_string=True)[:-4] epics.caput("26idc:filter:Fi1:Set",1) time.sleep(.1) ljm_scaler.write("DAC0", 0) epics.caput("26idc:3820:ChannelAdvance", 0, wait=True) # set scaler to internal trigger epics.caput("26idc:3820:Channel1Source", 0, wait=True) epics.caput("26idc:3820:PresetReal", 1, wait=True) if flag_eiger: if epics.caget("s26_eiger_cnm:HDF1:Capture_RBV"): print("It seems that Eiger did not capture all the expected images, did you interrupt?") epics.caput("s26_eiger_cnm:HDF1:Capture", 0) time.sleep(.1) if epics.caget("s26_eiger_cnm:cam1:Acquire") == 1: epics.caput("s26_eiger_cnm:cam1:Acquire", 0) time.sleep(.1) if epics.caget("s26_eiger_cnm:Stats1:TS:TSAcquiring"): epics.caput("s26_eiger_cnm:Stats1:TS:TSAcquire", 0) time.sleep(0.1) if epics.caget("s26_eiger_cnm:Stats2:TS:TSAcquiring"): epics.caput("s26_eiger_cnm:Stats2:TS:TSAcquire", 0) time.sleep(0.1) if epics.caget("s26_eiger_cnm:Stats3:TS:TSAcquiring"): epics.caput("s26_eiger_cnm:Stats3:TS:TSAcquire", 0) time.sleep(0.1) if epics.caget("s26_eiger_cnm:Stats4:TS:TSAcquiring"): epics.caput("s26_eiger_cnm:Stats4:TS:TSAcquire", 0) time.sleep(0.1) if flag_fluo: epics.caput("26idcXMAP:netCDF1:Capture", 0) # capture fluo time.sleep(.1) epics.caput("26idcXMAP:StopAll", 1) time.sleep(.1) epics.caput("26idcXMAP:netCDF1:EnableCallbacks", 0, wait=True) # disable netcdf saving epics.caput("26idcXMAP:IgnoreGate", 1, wait=True) epics.caput("26idcXMAP:CollectMode", 0, wait=True) # has to be put in last or it does not work it seems print ("appending metadata in h5..."), t0 = time.time() pathname = epics.caget(scanrecord+':saveData_fullPathName',as_string=True)[:-4] scannum = epics.caget(scanrecord+':saveData_scanNumber')-1 filenum = epics.caget("s26_eiger_cnm:HDF1:FileNumber_RBV")-1 h5file = os.path.join(pathname, "h5", "scan_{0}_{1:06d}.h5".format(scannum,filenum)) h5 = h5py.File(os.path.join(pathname, "h5", "scan_{0}_{1:06d}.h5".format(scannum,filenum)), "r+") if flag_eiger: inst_grp = h5["/entry/instrument"] else: inst_grp = h5.create_group("/entry/instrument") sr_grp = inst_grp.create_group("Storage Ring") sr_grp.create_dataset("SR current", data=epics.caget('S:SRcurrentAI')) ida_grp = inst_grp.create_group("26-ID-A") for i in range(1,5): ida_grp.create_dataset(epics.caget('26idaWBS:m{0}.DESC'.format(i)), data=epics.caget('26idaWBS:m{0}.RBV'.format(i))) for i in range(1,9): ida_grp.create_dataset(epics.caget('26idaMIR:m{0}.DESC'.format(i)), data=epics.caget('26idaMIR:m{0}.RBV'.format(i))) for i in range(1,5): ida_grp.create_dataset(epics.caget('26idaBDA:m{0}.DESC'.format(i)), data=epics.caget('26idaBDA:m{0}.RBV'.format(i))) idb_grp = inst_grp.create_group("26-ID-B") for i in range(1,9): idb_grp.create_dataset(epics.caget('26idbDCM:sm{0}.DESC'.format(i)), data=epics.caget('26idbDCM:sm{0}.RBV'.format(i))) for i in range(1,5): idb_grp.create_dataset(epics.caget('26idbPBS:m{0}.DESC'.format(i)), data=epics.caget('26idbPBS:m{0}.RBV'.format(i))) idc_grp = inst_grp.create_group("26-ID-C") idc_grp.create_dataset("count_time", data=dwelltime) for i in range(3,6): idc_grp.create_dataset(epics.caget('26idcSOFT:sm{0}.DESC'.format(i)), data=epics.caget('26idcSOFT:sm{0}.RBV'.format(i))) for i in range(1,13): idc_grp.create_dataset(epics.caget('26idcDET:m{0}.DESC'.format(i)), data=epics.caget('26idcDET:m{0}.RBV'.format(i))) for i in range(1,5): idc_grp.create_dataset(epics.caget('atto2:m{0}.DESC'.format(i)), data=epics.caget('atto2:m{0}.RBV'.format(i))) for i in range(1,18): idc_grp.create_dataset(epics.caget('26idcnpi:m{0}.DESC'.format(i)), data=epics.caget('26idcnpi:m{0}.RBV'.format(i))) for i in range(34,36): idc_grp.create_dataset(epics.caget('26idcnpi:m{0}.DESC'.format(i)), data=epics.caget('26idcnpi:m{0}.RBV'.format(i))) idc_grp.create_dataset(epics.caget('atto2:PIC867:1:m1.DESC'.format(i)), data=epics.caget('atto2:PIC867:1:m1.RBV'.format(i))) idc_grp.create_dataset(epics.caget('26idcnpi:Y_HYBRID_SP.DESC'.format(i)), data=epics.caget('26idcnpi:Y_HYBRID_SP.VAL'.format(i))) idc_grp.create_dataset(epics.caget('26idcnpi:X_HYBRID_SP.DESC'.format(i)), data=epics.caget('26idcnpi:X_HYBRID_SP.VAL'.format(i))) idc_grp.create_dataset('NES H Slit', data=epics.caget('26idcNES:Slit1Hsize.VAL')) idc_grp.create_dataset('NES V Slit', data=epics.caget('26idcNES:Slit1Vsize.VAL')) ny, nx = fastmotorvalues.shape dim = [{}] rank = 2 dim[0]['version'] = 1.3 dim[0]['scan_number'] = scannum dim[0]['rank'] = rank dim[0]['dimensions'] = [ny, nx] dim[0]['isRegular'] = 1 dim[0]['time'] = 0 dim[0]['ourKeys'] = ['ourKeys', 'version', 'scan_number', 'rank', 'dimensions', 'isRegular', 'time'] for i in range(1,rank+1): dim.append(scanDim()) dim[i].dim = i dim[i].rank = rank-i+1 dim[i].scan_name = '26idbSOFT:scan{0}'.format(i) dim[i].np = 1 dim[i].time = "whatever" dim[1].nd = 0 dim[1].npts = ny dim[1].curr_pt = ny dim[1].p.append(scanPositioner()) if slowmotor == "hybridy": dim[1].p[0].name = "26idcnpi:Y_HYBRID_SP.VAL" dim[1].p[0].desc = 'Hybrid Piezo Y' elif slowmotor == "attoz": dim[1].p[0].name = "26idbATTO:m3.VAL" dim[1].p[0].desc = 'ATTO SAM Z' else: dim[1].p[0].name = "26idbATTO:m4.VAL" dim[1].p[0].desc = 'ATTO SAM X' dim[1].p[0].data = slowmotorvalues dim[2].p.append(scanPositioner()) dim[2].npts = nx dim[2].nd = 70 dim[2].curr_pt = nx if fastmotor == "hybridx": dim[2].p[0].name = "26idcnpi:X_HYBRID_SP.VAL" dim[2].p[0].desc = 'Hybrid Piezo X' else: dim[2].p[0].name = "26idcnpi:m17.VAL" dim[2].p[0].desc = 'Sample Y' dim[2].p[0].data = fastmotorvalues print("completed in {0:0.1f} sec".format(time.time()-t0)) t0 = time.time() if flag_fluo: print("extracting fluo spectra from netcdf..."), fluonum = epics.caget("26idcXMAP:netCDF1:FileNumber_RBV")-1 f_fluo = os.path.join(pathname, "fluo", "scan_{0}_{1:06d}.nc".format(scannum,fluonum)) os.chmod(f_fluo, 0o777) netcdffile = netCDF4.Dataset(f_fluo, "r") data_mca_ib = (netcdffile.variables['array_data'][:,0,256:].reshape(ny, 124, 256+2048*4)[:,:nx,256:].reshape(ny,nx,4,2048)) data_mca_ob = (netcdffile.variables['array_data'][:,1,256:].reshape(ny, 124, 256+2048*4)[:,:nx,256:].reshape(ny,nx,4,2048))[:,:,-1] netcdffile.close() print("completed in {0:0.1f} sec".format(time.time()-t0)) t0 = time.time() print("calculating roi stats for h5..."), pos_grp = h5.create_group("/entry/scan/Positioner") h5["/entry/scan"].attrs["dimensions"] = (ny,nx) dset = pos_grp.create_dataset(slowmotor, data=slowmotorvalues) dset = pos_grp.create_dataset(fastmotor, data=fastmotorvalues) dset = pos_grp.create_dataset("dwelltime", data=dwelltime) det_grp = h5.create_group("/entry/scan/Detector") for i in range(70): name = epics.caget("26idbSOFT:scan1.D{0:02d}PV".format(i+1)) dset = det_grp.create_dataset("D{0:02d}:{1}".format(i+1, name), data=np.zeros(fastmotorvalues.shape), dtype="f8") dim[2].d.append(scanDetector()) dim[2].d[i].name = name dim[2].d[i].number = i if "s26_eiger_cnm:Stats" in name: i_roi = name[19] xmin = epics.caget("s26_eiger_cnm:ROI{0}:MinX".format(i_roi)) xmax = min(epics.caget("s26_eiger_cnm:ROI{0}:SizeX".format(i_roi)) + xmin, 1027) ymin = epics.caget("s26_eiger_cnm:ROI{0}:MinY".format(i_roi)) ymax = min(epics.caget("s26_eiger_cnm:ROI{0}:SizeY".format(i_roi)) + ymin, 1061) dset.attrs['xmin'] = xmin dset.attrs['xmax'] = xmax dset.attrs['ymin'] = ymin dset.attrs['ymax'] = ymax if "Total" in name: dset[...] = epics.caget("s26_eiger_cnm:Stats{0}:TSTotal".format(i_roi))[:ny*nx].reshape(ny,nx) elif "CentroidX" in name: dset[...] = epics.caget("s26_eiger_cnm:Stats{0}:TSCentroidX".format(i_roi))[:ny*nx].reshape(ny,nx) elif "CentroidY" in name: dset[...] = epics.caget("s26_eiger_cnm:Stats{0}:TSCentroidY".format(i_roi))[:ny*nx].reshape(ny,nx) elif "userCalcOut" in name and flag_fluo: i_roi = int(name[21:23]) xmin = epics.caget("26idcXMAP:mca1.R{0}LO".format(i_roi)) xmax = epics.caget("26idcXMAP:mca1.R{0}HI".format(i_roi)) dset.attrs["xmin"] = xmin dset.attrs["xmax"] = xmax dset.attrs["line"] = epics.caget("26idcXMAP:mca1.R{0}NM".format(i_roi)) dset[...] = data_mca_ib[:,:,:,xmin:xmax+1].sum(2).sum(2) elif "mca8.R" in name and flag_fluo: i_roi = name[16:] xmin = epics.caget("26idcXMAP:mca8.R{0}LO".format(i_roi)) xmax = epics.caget("26idcXMAP:mca8.R{0}HI".format(i_roi)) dset.attrs["xmin"] = xmin dset.attrs["xmax"] = xmax dset.attrs["line"] = epics.caget("26idcXMAP:mca8.R{0}NM".format(i_roi)) dset[...] = data_mca_ob[:,:,xmin:xmax+1].sum(2) elif "scaler1_cts1.B" in name: dset[...] = data_scaler[0] elif "scaler1_cts1.C" in name: dset[...] = data_scaler[1] dim[2].d[i].data = dset[()] data_mca_ib = None data_mca_ob = None h5.close() print("completed in {0:0.1f} sec".format(time.time()-t0)) f_mda = os.path.join(pathname, "mda", "26idbSOFT_{0:04d}.mda".format(scannum)) writeMDA(dim, f_mda) print("{0} is now available.".format(f_mda)), epics.caput("26idaWBS:sft01:ph01:ao06.VAL", 0, wait=True) # set fly flag = 0 epics.caput("26idpvc:userCalc3.SCAN", 6, wait=True) # enable Martin's samy watchdog def flyxy_sample(dx0, dx1, nx, dy0, dy1, ny, dwelltime, delaytime=0.0, velofactor=0.92, slowmotor='attoz'): data_scaler = np.zeros((2,nx,ny)) flag_fluo, flag_eiger = get_detector_flags() if ny>124 and flag_fluo: sys.exit("number of points must be smaller than 124 for the fast axis...") if nx*ny > 16000: sys.exit("number of total points must be smaller than 16000...") fm_spd = np.abs(dy0-dy1)*1./ny/dwelltime if fm_spd < 10 or fm_spd > 50: sys.exit("hybridx motor speed must be between 10 and 50 um/s, currently {0:.1f}".format(fm_spd)) while(epics.caget("PA:26ID:SCS_BLOCKING_BEAM.VAL") or epics.caget("PA:26ID:FES_BLOCKING_BEAM.VAL")): print("it seems that either the A or the C hutch shutter is closed, checking again in 1 minute") time.sleep(60) if epics.caget("26idc:1:userCalc7.VAL") or epics.caget("26idc:1:userCalc5.VAL"): sys.exit("please unlock hybrid before performing this kind of scan") if slowmotor == 'attoz': xorigin = epics.caget("atto2:m3.VAL") elif slowmotor == 'attox': xorigin = epics.caget("atto2:m4.VAL") xstart = dx0 + xorigin xend = dx1 + xorigin yorigin = epics.caget("26idcnpi:m17.VAL") ystart = dy0 + yorigin yend = dy1 + yorigin epics.caput("26idcnpi:m17.VAL", ystart, wait=True) if slowmotor == 'attoz': epics.caput("atto2:m3.VAL", xstart, wait=True) # turns out the wait works, no need to add DMOV elif slowmotor == 'attox': epics.caput("atto2:m4.VAL", xstart, wait=True) # turns out the wait works, no need to add DMOV epics.caput("26idcnpi:m17.VELO", np.fabs(dy0-dy1)/ny/dwelltime*velofactor, wait=True) abs_x = np.linspace(xstart, xend, nx) abs_y = np.linspace(ystart, yend, ny) flyxy_head(nx, ny) hiccups = [] print("scanning line"), def process1(): time.sleep(delaytime+0.005) # before this got launched first ljm_fluo.send_fakedigital_singlebuffer(np.ones(ny), t1=dwelltime, out_num=0, dac_num=0, t0=0.005) def process2(): time.sleep(delaytime) ljm_scaler.send_fakedigital_singlebuffer(np.ones(ny+1), t1=dwelltime, out_num=0, dac_num=0, t0=0.005, inverted=True) def process3(): time.sleep(delaytime) ljm_mpx.send_fakedigital_singlebuffer(np.ones(ny), t1=dwelltime, out_num=0, dac_num=0, t0=0.01) def process4(): time.sleep(delaytime) ljm_eiger.send_fakedigital_singlebuffer(np.ones(ny), t1=dwelltime, out_num=0, dac_num=0, t0=0.005) for i_x in range(nx): epics.caput("26idc:3820:EraseStart",1) time.sleep(0.1) hiccup = 0 print("{0:03d}/{1:03d}".format(i_x+1,nx)+"\b"*8), p1 = Process(target=process1) p4 = Process(target=process4) p2 = Process(target=process2) if flag_fluo: p1.start() if flag_eiger: p4.start() p2.start() epics.caput("26idcnpi:m17.VAL", yend, wait=True) #time.sleep(nx * dwelltime+.2) flag_break = False while(1): if flag_fluo: if epics.caget("26idcXMAP:Acquiring"): hiccup += 1 print("waiting on fluo") time.sleep(dwelltime) flag_break = True if flag_eiger: num_cap = epics.caget("s26_eiger_cnm:HDF1:NumCaptured_RBV") if num_cap != (i_x+1)*ny: hiccup += 1 print("waiting on eiger ", num_cap) time.sleep(dwelltime) flag_break = True if epics.caget("26idc:3820:Acquiring"): hiccup += 1 print("waiting on scaler") time.sleep(dwelltime) flag_break = True if hiccup > 20: print("stopping scaler") epics.caput("26idc:3820:StopAll",1) if not flag_break: break flag_break = False if slowmotor == 'attoz': epics.caput("atto2:m3.VAL", abs_x[i_x]) elif slowmotor == 'attox': epics.caput("atto2:m4.VAL", abs_x[i_x]) epics.caput("26idcnpi:m17.VELO", 200, wait=True) epics.caput("26idcnpi:m17.VAL", ystart, wait=True) epics.caput("26idcnpi:m17.VELO", np.fabs(dy0-dy1)/ny/dwelltime*velofactor, wait=True) #time.sleep(0.5) # to make sure that the data is saved, putting 0 will cause some data to not be updated!!!! if hiccup: hiccups+=[[i_x, hiccup]] for i_scaler in range(2): data_scaler[i_scaler, i_x] = epics.caget('26idc:3820:mca{0}'.format(i_scaler+2))[:ny] if flag_fluo: epics.caput("26idcXMAP:StartAll", 1) epics.caput("26idcnpi:m17.VELO", 200, wait=True) ljm_fluo.stop_streaming() ljm_scaler.stop_streaming() #ljm_mpx.stop_streaming() ljm_eiger.stop_streaming() epics.caput("26idcnpi:m17.VAL", yorigin, wait=True) if slowmotor == 'attoz': epics.caput("atto2:m3.VAL", xorigin, wait=True) elif slowmotor == 'attox': epics.caput("atto2:m4.VAL", xorigin, wait=True) print(" ") if len(hiccups): for hiccup in hiccups: print("number of bad points in line {0} : {1}".format(hiccup[0], hiccup[1])) xx, yy = np.meshgrid(abs_x, abs_y) flyxy_tail("samy", yy.T, slowmotor, abs_x, dwelltime, data_scaler) ############################################################################################################### def flyxy_beam(dx0, dx1, nx, dy0, dy1, ny, dwelltime, delaytime=0.0, velofactor=0.92): data_scaler = np.zeros((2,ny,nx)) flag_fluo, flag_eiger = get_detector_flags() if nx>124 and flag_fluo: sys.exit("number of points must be smaller than 124 for the fast axis...") if nx*ny > 16000: sys.exit("number of total points must be smaller than 16000...") fm_spd = np.abs(dx0-dx1)*1./nx/dwelltime if fm_spd < 0.1 or fm_spd > 5: sys.exit("hybridx motor speed must be between 0.1 and 5 um/s, currently {0:.1f}".format(fm_spd)) while(epics.caget("PA:26ID:SCS_BLOCKING_BEAM.VAL") or epics.caget("PA:26ID:FES_BLOCKING_BEAM.VAL")): print("it seems that either the A or the C hutch shutter is closed, checking again in 1 minute") time.sleep(60) if not(epics.caget("26idc:1:userCalc5.VAL")): # and epics.caget("26idc:1:userCalc7.VAL")): sys.exit("please lock hybrid before performing this kind of scan") xorigin = epics.caget("26idcnpi:m34.VAL") xstart = dx0 + xorigin xend = dx1 + xorigin yorigin = epics.caget("26idcnpi:m35.VAL") ystart = dy0 + yorigin yend = dy1 + yorigin # epics.caput("26idcnpi:m35.VELO", 200, wait=True) epics.caput("26idcnpi:m35.VAL", ystart, wait=True) epics.caput("26idcnpi:m34.VAL", xstart, wait=True) epics.caput("26idcnpi:m34.VELO", np.fabs(dx0-dx1)/nx/dwelltime*velofactor, wait=True) abs_y = np.linspace(ystart, yend, ny) abs_x = np.linspace(xstart, xend, nx) flyxy_head(ny, nx) hiccups = [] print("scanning line"), def process1(): time.sleep(delaytime+0.005) # before this got launched first ljm_fluo.send_fakedigital_singlebuffer(np.ones(nx), t1=dwelltime, out_num=0, dac_num=0, t0=0.005) def process2(): time.sleep(delaytime) ljm_scaler.send_fakedigital_singlebuffer(np.ones(nx+1), t1=dwelltime, out_num=0, dac_num=0, t0=0.005, inverted=True) # need nx+1 to add one falling edge, draw the TTL diagram and you will understand why it is needed def process3(): time.sleep(delaytime) ljm_mpx.send_fakedigital_singlebuffer(np.ones(nx), t1=dwelltime, out_num=0, dac_num=0, t0=0.01) def process4(): time.sleep(delaytime) ljm_eiger.send_fakedigital_singlebuffer(np.ones(nx), t1=dwelltime, out_num=0, dac_num=0, t0=0.005) for i_y in range(ny): epics.caput("26idc:3820:EraseStart",1) time.sleep(0.1) hiccup = 0 print("{0:03d}/{1:03d}".format(i_y+1,ny)+"\b"*8), p1 = Process(target=process1) p4 = Process(target=process4) p2 = Process(target=process2) # using processes the delay between two processes is <5 ms # if sequentially launch one after another, it is >150 ms if flag_fluo: p1.start() if flag_eiger: p4.start() p2.start() epics.caput("26idcnpi:m34.VAL", xend, wait=True) #time.sleep(nx * dwelltime+.2) flag_break = False while(1): if flag_fluo: if epics.caget("26idcXMAP:Acquiring"): hiccup += 1 print("waiting on fluo") time.sleep(dwelltime) flag_break = True if flag_eiger: num_cap = epics.caget("s26_eiger_cnm:HDF1:NumCaptured_RBV") if num_cap != (i_y+1)*nx: hiccup += 1 print("waiting on eiger ", num_cap) time.sleep(dwelltime) flag_break = True if epics.caget("26idc:3820:Acquiring"): hiccup += 1 print("waiting on scaler") time.sleep(dwelltime) flag_break = True if hiccup > 20: print("stopping scaler") epics.caput("26idc:3820:StopAll",1) if not flag_break: break flag_break = False epics.caput("26idcnpi:m35.VAL", abs_y[i_y]) epics.caput("26idcnpi:m34.VELO", 200, wait=True) epics.caput("26idcnpi:m34.VAL", xstart, wait=True) epics.caput("26idcnpi:m34.VELO", np.fabs(dx0-dx1)/nx/dwelltime*velofactor, wait=True) #time.sleep(0.5) if hiccup: hiccups+=[[i_y, hiccup]] for i_scaler in range(2): data_scaler[i_scaler, i_y] = epics.caget('26idc:3820:mca{0}'.format(i_scaler+2))[:nx] if flag_fluo: epics.caput("26idcXMAP:StartAll", 1) #time.sleep(0.5) # new for fei epics.caput("26idcnpi:m34.VELO", 200, wait=True) ljm_fluo.stop_streaming() ljm_scaler.stop_streaming() #ljm_mpx.stop_streaming() ljm_eiger.stop_streaming() epics.caput("26idcnpi:m35.VAL", yorigin) epics.caput("26idcnpi:m34.VAL", xorigin) print(" ") if len(hiccups): for hiccup in hiccups: print("number of bad points in line {0} : {1}".format(hiccup[0], hiccup[1])) xx, yy = np.meshgrid(abs_x, abs_y) flyxy_tail("hybridx", xx, "hybridy", abs_y, dwelltime, data_scaler) ############################################################################################################################################# def flyxy_cleanup(): flag_fluo, flag_eiger = get_detector_flags() ljm_fluo.stop_streaming() ljm_scaler.stop_streaming() ljm_mpx.stop_streaming() ljm_eiger.stop_streaming() epics.caput("26idcnpi:m17.VELO", 200, wait=True) epics.caput("26idcnpi:m34.VELO", 200, wait=True) epics.caput("26idc:filter:Fi1:Set",1) time.sleep(.1) epics.caput("s26_eiger_cnm:cam1:Acquire", 0) time.sleep(.1) epics.caput("s26_eiger_cnm:HDF1:Capture", 0) # End Capture time.sleep(.1) epics.caput("s26_eiger_cnm:Stats1:TS:TSAcquire", 0) time.sleep(.1) epics.caput("s26_eiger_cnm:Stats2:TS:TSAcquire", 0) time.sleep(.1) epics.caput("s26_eiger_cnm:Stats3:TS:TSAcquire", 0) time.sleep(.1) epics.caput("s26_eiger_cnm:Stats4:TS:TSAcquire", 0) time.sleep(.1) epics.caput("26idc:3820:StopAll", 1) # stop scaler acquisition time.sleep(.1) epics.caput("26idc:3820:ChannelAdvance", 0, wait=True) # set scaler to internal trigger epics.caput("26idc:3820:Channel1Source", 0, wait=True) epics.caput("26idc:3820:PresetReal", 1, wait=True) epics.caput("26idcXMAP:StopAll", 1) time.sleep(.1) epics.caput("26idcXMAP:netCDF1:Capture", 0) # capture fluo time.sleep(.1) epics.caput("26idcXMAP:netCDF1:EnableCallbacks", 0, wait=True) # disable netcdf saving epics.caput("26idcXMAP:IgnoreGate", 1, wait=True) epics.caput("26idcXMAP:CollectMode", 0, wait=True) # spectrum mapping epics.caput("26idaWBS:sft01:ph01:ao06.VAL", 0, wait=True) # set fly flag = 0 epics.caput("26idpvc:userCalc3.SCAN", 6, wait=True) # enable Martin's samy watchdog if epics.caget("26idc:1:userCalc7.VAL") or epics.caget("26idc:1:userCalc5.VAL"): if np.abs(epics.caget("26idcnpi:m35.RBV")-epics.caget("26idcnpi:Y_HYBRID_SP.VAL"))>0.5: print("returning hybrid motors to their original positions") epics.caput("26idcnpi:X_HYBRID_SP.VAL", epics.caget("26idcnpi:X_HYBRID_SP.VAL")+0.001) time.sleep(.1) epics.caput("26idcnpi:Y_HYBRID_SP.VAL", epics.caget("26idcnpi:Y_HYBRID_SP.VAL")+0.001) time.sleep(.1) <file_sep>/ljm_functions.py from labjack import ljm import time import numpy as np from fractions import gcd ljm.loadConstantsFromFile("ljm_constants.json") def listallT7(): result = ljm.listAll(7,3) print("found {0} devices".format(result[0])) for i in range(result[0]): print ("device {0} : SN [{1}] IP [{2}]".format(i, result[3][i], ljm.numberToIP(result[4][i]))) class T7_ID26: def fprintf(self, ports, ScanRate, filename, max_length = 1000, ScansPerRead = 1, verbose = False): self.stop_streaming() if not isinstance(ports, (list,)): ports = [ports] NumAddr = len(ports) Addr = [] for port in ports: Addr += [ljm.nameToAddress(port)[0]] output_file = open(filename, "w") ljm.eStreamStart(self.handle, ScansPerRead, NumAddr, Addr, ScanRate) while(max_length): # which means if you put a negative value, it will run forever newline = ljm.eStreamRead(self.handle) output_file.write(" ".join(str(el) for el in newline[0])+"\n") if verbose: print max_length, newline max_length -= 1 ljm.eStreamStop(self.handle) output_file.close() def start_streaming(self, ports): if not isinstance(ports, (list,)): ports = [ports] NumAddr = len(ports) Addr = [] for port in ports: Addr += [ljm.nameToAddress(port)[0]] for i in range(NumAddr): r = self.write("STREAM_SCANLIST_ADDRESS{0}".format(i), Addr[i]) # print Addr[i], r # print("writing to scan list [{0}]...{1} ".format(i, r == Addr[i])) r = self.write("STREAM_NUM_ADDRESSES", NumAddr) # print("writing number of address = {0}".format(r)) r = self.write("STREAM_ENABLE", 1) # print("stream enabled...{0}".format(r==1)) def stop_streaming(self): r = self.read("STREAM_ENABLE") if r == 0: pass # print "stream was not running" else: r = self.write("STREAM_ENABLE", 0) # print "disabling stream just in case...", r==0 # print "clean up the scan list just in case" for i in range(128): if self.write("STREAM_SCANLIST_ADDRESS{0}".format(i), 0) != 0: # print "problem!!!" pass #print "setting DACs to 0..." #self.write("DAC0", 0) #self.write("DAC1", 0) def send_digital(self, data, t1, buffersize=4096): t0 = 0.01 ScanRate = 2e3/(gcd(t0*1000,t1*1000)) if ScanRate > 1000: # print "ScanRate too high :", ScanRate return 0 if len(data.shape) == 1: data = (data[np.newaxis, :]>0) self.stop_streaming() r = self.write("STREAM_SCANRATE_HZ", ScanRate) # print("setting scan rate to {0}".format(r)) data = (data * np.arange(data.shape[0])[:,np.newaxis]).astype(int) # print data.dtype data = np.left_shift(1,data).sum(0) data = (np.array([1]*int((t1-t0)*ScanRate)+[0]*int(t0*ScanRate)) * np.c_[data]).flatten() data = data * np.ones(2,dtype=int).reshape(2,1) # print data data_inhib = 0x7FFFFF - data # print "Total data to be transmitted: {0}x{1} at {2} Hz".format(data.shape[0], data.shape[1], ScanRate) self.map_stream_output(0, "FIO_STATE", buffersize=buffersize) self.map_stream_output(1, "FIO_DIRECTION", buffersize=buffersize) #self.map_stream_output(2, "DIO_INHIBIT", buffersize=buffersize) self.start_streaming(["STREAM_OUT0", "STREAM_OUT1"]) self.data_to_buffer([0, 1], data, buffertype = "U16") self.stop_streaming() def send_fakedigital_ringbuffer(self, data_raw, t1, t0 = None, out_num = 0, dac_num = 0, buffersize = 4096, vmax = 3.3): if t0 == None: t0 = t1 - 0.005 # up time has been fixed to 5 ms ScanRate = 1000 # ScanRate has been fixed to 1kHz #ScanRate = 5e3/(gcd(t0*1000,t1*1000)) if not isinstance(out_num, (list,)): out_num = [out_num]; dac_num = [dac_num]; data_raw = data_raw[np.newaxis,:] envelop = np.array([1]*int((t1-t0)*ScanRate)+[0]*int(t0*ScanRate)) data = np.zeros((data_raw.shape[0], data_raw.shape[1]*envelop.shape[0])) for i in range(data.shape[0]): data[i] = (envelop * np.c_[data_raw[i]>0]).flatten()*vmax self.send_analog_ringbuffer(data, ScanRate, out_num, dac_num, buffersize) def send_analog_ringbuffer(self, data, ScanRate, out_num = 0, dac_num = 0, buffersize = 4096): if not isinstance(out_num, (list,)): out_num = [out_num]; dac_num = [dac_num]; data = data[np.newaxis,:] self.stop_streaming() # print "Total data to be transmitted: {0}x{1} at {2} Hz".format(data.shape[0], data.shape[1], ScanRate) r = self.write("STREAM_SCANRATE_HZ", ScanRate) # print("setting scan rate to {0}".format(r)) for i in range(data.shape[0]): self.map_stream_output(out_num[i], "DAC{0}".format(dac_num[i]), buffersize=buffersize) self.start_streaming(" ".join(map("STREAM_OUT{0}".format, out_num)).split()) self.data_to_ringbuffer(out_num, data, buffertype = "F32") def send_fakedigital_singlebuffer(self, data_raw, t1, t0 = 0.005, out_num = 0, dac_num = 0, vmax = 3.3, inverted = False): n_data = data_raw.shape[0] n_total = int(16382/2/n_data) n_down = max(int(round(t0/t1*n_total,0)), 1) n_up = int(n_total - n_down) ScanRate = 1/t1*n_total # trigger at rise edge data = (np.ones((n_data,n_total))*np.array([1]*n_up+[0]*n_down)).flatten() data = np.append(np.zeros(1), data) data = np.append(data, np.zeros(16382/2-n_total*n_data))*vmax if inverted: data = vmax - data self.send_analog_singlebuffer(data, ScanRate, out_num, dac_num) def send_analog_singlebuffer(self, data, ScanRate, out_num = 0, dac_num = 0): self.stop_streaming() r = self.write("STREAM_SCANRATE_HZ", ScanRate) #print("setting scan rate to {0}".format(r)) self.map_stream_output(out_num, "DAC{0}".format(dac_num), buffersize=16384) self.start_streaming("STREAM_OUT{0}".format(out_num)) self.data_to_singlebuffer(out_num, data, buffertype = "F32") def data_to_singlebuffer(self, out_num, data, buffertype = "F32"): bytesperdata = int(buffertype[1:])/16 buffersize = int(self.read("STREAM_OUT{0}_BUFFER_ALLOCATE_NUM_BYTES".format(out_num))) # print("buffersize on OUTPUT{0} is {1} bytes".format(out_num, buffersize)) r = self.read("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num)) if r != 0: # print("loop size is non-zero, setting it to zero") r = self.write("STREAM_OUT{0}_ENABLE".format(out_num), 0) # print("Disabling output{0}...{1}".format(out_num, r==0)) r = self.write("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num), 0) r = self.write("STREAM_OUT{0}_ENABLE".format(out_num), 1) # print("Enabling output{0}...{1}".format(out_num, r==1)) # print("Writing data into buffer") # very important ! has to be dne after setting nloop self.writearray("STREAM_OUT{0}_BUFFER_{1}".format(out_num, buffertype), data) self.write("STREAM_OUT{0}_SET_LOOP".format(out_num), 1, writeonly = True) # print("Transferring data immediately") # will be replaced by trigger def data_to_ringbuffer(self, out_num, data, buffertype = "F32"): bytesperdata = int(buffertype[1:])/16 buffersize = int(self.read("STREAM_OUT{0}_BUFFER_ALLOCATE_NUM_BYTES".format(out_num[0]))) # print("buffersize on OUTPUT{0} is {1} bytes".format(out_num[0], buffersize)) # print("yourdata in {0} is {1} bytes".format(buffertype, data.shape[1]*bytesperdata)) if buffersize > data.shape[1]*bytesperdata: for i in range(data.shape[0]): # print("Infinite loop over existing data") r = self.write("STREAM_OUT{0}_ENABLE".format(out_num[i]), 0) # print("Disabling output{0}...{1}".format(out_num[i], r==0)) r = self.write("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num[i]), data.shape[1]) r = self.write("STREAM_OUT{0}_ENABLE".format(out_num[i]), 1) # print("Enabling output{0}...{1}".format(out_num[i], r==1)) r = self.read("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num[i])) # print("setting loop size to {0} values / {1} bytes".format(r, r*bytesperdata)) # print("Writing data into buffer") # very important ! has to be dne after setting nloop self.writearray("STREAM_OUT{0}_BUFFER_{1}".format(out_num[i], buffertype), data[i]) self.write("STREAM_OUT{0}_SET_LOOP".format(out_num[i]), 2, writeonly = True) # print("Transferring data immediately") # will be replaced by trigger else: if data.shape[1]%(buffersize/4): ndata = (data.shape[1]/(buffersize/4)+1) * (buffersize/4) # print("appending data with zeros") data = np.append(data, np.zeros((data.shape[0],ndata-data.shape[1])), axis=1) else: ndata = data.shape[1] data = data.reshape(data.shape[0], ndata/(buffersize/4), buffersize/4) # print("stream will loop {0} times with size of {1}".format(data.shape[1], data.shape[2])) for i in range(data.shape[0]): r = self.write("STREAM_OUT{0}_ENABLE".format(out_num[i]), 1) self.writearray("STREAM_OUT{0}_BUFFER_{1}".format(out_num[i], buffertype), np.zeros(buffersize/2)) self.writearray("STREAM_OUT{0}_BUFFER_{1}".format(out_num[i], buffertype), data[i,0]) # this is important, if not disabled, we cannot affect loop size! r = self.write("STREAM_OUT{0}_ENABLE".format(out_num[i]), 0) # print("Disabling output{0}...{1}".format(out_num[i], r==0)) r = self.write("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num[i]), buffersize/4) r = self.write("STREAM_OUT{0}_ENABLE".format(out_num[i]), 1) # print("Enabling output{0}...{1}".format(out_num[i], r==1)) r = self.read("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num[i])) # print("setting loop size to {0} values / {1} bytes".format(r, r*bytesperdata)) # print("Writing initial data into half of the buffer") self.write("STREAM_OUT{0}_SET_LOOP".format(out_num[i]), 1, writeonly = True) # print("Transferring data immediately") # will be replaced by trigger scanrate = self.read("STREAM_SCANRATE_HZ") check_interval = 1/scanrate time.sleep(check_interval*10) for j in range(1, data.shape[1]): emptybuffer = self.read("STREAM_OUT{0}_BUFFER_STATUS".format(out_num[0])) while emptybuffer*2 <buffersize/2: emptybuffer = self.read("STREAM_OUT{0}_BUFFER_STATUS".format(out_num[0])) nn = int(50*emptybuffer*2/buffersize) #print("\r{0:05d}/{1:05d} [".format(j,data.shape[1])+"|"*nn+" "*(50-nn)+"]"), time.sleep(check_interval) # print("\rWriting data into buffer"), for i in range(data.shape[0]): self.writearray("STREAM_OUT{0}_BUFFER_{1}".format(out_num[i], buffertype), data[i,j]) self.write("STREAM_OUT{0}_SET_LOOP".format(out_num[i]), 1, writeonly = True) time.sleep(check_interval*10) self.stop_streaming() def data_streamout(self): self.write("STREAM_OUT3_SET_LOOP", 3, writeonly = True) def map_stream_output(self, out_num, target, buffersize=4096): r = self.write("STREAM_OUT{0}_ENABLE".format(out_num), 0) # print("Disabling output{0}...{1}".format(out_num, r==0)) target_addr = ljm.nameToAddress(target)[0] r = self.write("STREAM_OUT{0}_TARGET".format(out_num), target_addr) # print("Setting output{0} to {1}...{2}".format(out_num, target, r==target_addr)) r = self.write("STREAM_OUT{0}_BUFFER_ALLOCATE_NUM_BYTES".format(out_num), buffersize) # print("Setting buffersize to {0}".format(r)) r = self.write("STREAM_OUT{0}_ENABLE".format(out_num), 1) # print("Enabling output{0}...{1}".format(out_num, r==1)) def writearray(self, name, array): addr, typ = ljm.nameToAddress(name) ljm.eWriteAddressArray(self.handle, addr, typ, len(array), array) def write(self, name, value, writeonly = False): ljm.eWriteName(self.handle, name, value) if not writeonly: return ljm.eReadName(self.handle, name) def read(self, name): return ljm.eReadName(self.handle, name) def close(self): ljm.close(self.handle) def __init__(self, IP): if isinstance(IP, int): IP = "172.16.31.10{0}".format(IP) try: self.handle = ljm.open(7,3,IP) except Exception as e: print e print "Accepted variables are IPs or integers 1 2 3 4" print "type listallT7() to list the IPs" info = ljm.getHandleInfo(self.handle) print("T7 device connected") print("SN : {0}".format(info[2])) print("IP : {0}".format(ljm.numberToIP(info[3]))) print("Port : {0}".format(info[4])) print("MaxBytesPerMB : {0}".format(info[5])) """ #r = self.write("STREAM_SAMPLES_PER_PACKET", 1) #print("setting sample per package to {0}".format(r)) # this has no effect anyway #r = self.write("STREAM_TRIGGER_INDEX", 0) #print("setting streaming scanning to start when stream is enabled...{0}".format(r==0)) #r = self.write("STREAM_CLOCK_SOURCE", 0) #print("setting clock source to internal crystal...{0}".format(r==0)) def data_to_buffer(self, out_num, data, buffertype = "F32"): bytesperdata = int(buffertype[1:])/16 buffersize = int(self.read("STREAM_OUT{0}_BUFFER_ALLOCATE_NUM_BYTES".format(out_num[0]))) print("buffersize on OUTPUT{0} is {1} bytes".format(out_num[0], buffersize)) print("yourdata in {0} is {1} bytes".format(buffertype, data.shape[1]*bytesperdata)) if buffersize > data.shape[1]*bytesperdata: for i in range(data.shape[0]): r = self.write("STREAM_OUT{0}_ENABLE".format(out_num[i]), 0) print("Disabling output{0}...{1}".format(out_num[i], r==0)) r = self.write("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num[i]), data.shape[1]) r = self.write("STREAM_OUT{0}_ENABLE".format(out_num[i]), 1) print("Enabling output{0}...{1}".format(out_num[i], r==1)) r = self.read("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num[i])) print("setting loop size to {0} values / {1} bytes".format(r, r*bytesperdata)) print("Writing data into buffer") # very important ! has to be dne after setting nloop self.writearray("STREAM_OUT{0}_BUFFER_{1}".format(out_num[i], buffertype), data[i]) self.write("STREAM_OUT{0}_SET_LOOP".format(out_num[i]), 1, writeonly = True) print("Transferring data immediately") # will be replaced by trigger else: if data.shape[1]%(buffersize/8): ndata = (data.shape[1]/(buffersize/8)+1) * (buffersize/8) print("appending data with zeros") data = np.append(data, np.zeros((data.shape[0],ndata-data.shape[1])), axis=1) else: ndata = data.shape[1] data = data.reshape(data.shape[0], ndata/(buffersize/8), buffersize/8) print("stream will loop {0} times with size of {1}".format(data.shape[1], data.shape[2])) for i in range(data.shape[0]): # this is important, if not disabled, we cannot affect loop size! r = self.write("STREAM_OUT{0}_ENABLE".format(out_num[i]), 0) print("Disabling output{0}...{1}".format(out_num[i], r==0)) r = self.write("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num[i]), buffersize/8) r = self.write("STREAM_OUT{0}_ENABLE".format(out_num[i]), 1) print("Enabling output{0}...{1}".format(out_num[i], r==1)) r = self.read("STREAM_OUT{0}_LOOP_NUM_VALUES".format(out_num[i])) print("setting loop size to {0} values / {1} bytes".format(r, r*2)) print("Writing initial data into half of the buffer") self.writearray("STREAM_OUT{0}_BUFFER_{1}".format(out_num[i], buffertype), data[i,:2].flatten()) self.write("STREAM_OUT{0}_SET_LOOP".format(out_num[i]), 1, writeonly = True) print("Transferring data immediately") # will be replaced by trigger scanrate = self.read("STREAM_SCANRATE_HZ") check_interval = 1/scanrate #buffersize/8/scanrate time.sleep(check_interval*10) for j in range(2, data.shape[1]): emptybuffer = self.read("STREAM_OUT{0}_BUFFER_STATUS".format(out_num[0])) while emptybuffer*2 <buffersize/2: emptybuffer = self.read("STREAM_OUT{0}_BUFFER_STATUS".format(out_num[0])) nn = int(50*emptybuffer*2/buffersize) print("\r{0:05d}/{1:05d} [".format(j,data.shape[1])+"|"*nn+" "*(50-nn)+"]"), time.sleep(check_interval) print("\rWriting data into buffer"), for i in range(data.shape[0]): self.writearray("STREAM_OUT{0}_BUFFER_{1}".format(out_num[i], buffertype), data[i,j]) self.write("STREAM_OUT{0}_SET_LOOP".format(out_num[i]), 1, writeonly = True) time.sleep(check_interval*10) self.stop_streaming() """
91efef9425437f4fe486d963b4589c2f8e5b2cfa
[ "Markdown", "Python" ]
3
Markdown
danielzt12/s26_flyscan
0f9bbf59308e49b069696607ef740cea955e787c
59cf80b83289656253106f2badf743f5dcf4c09c
refs/heads/master
<file_sep>var express = require('express'), jwt = require('jsonwebtoken'), router = express.Router(); controller = require('../controller'); var isAuthenticated = function (req, res, next) { // Check that the request has the JWT in the authorization header var token = req.headers['authorization']; if (!token) { return res.status(401).json({ error: null, msg: 'You have to login first before you can access your lists.', data: null }); } // Verify that the JWT is created using our server secret and that it hasn't expired yet jwt.verify(token, req.app.get('secret'), function (err, decodedToken) { if (err) { return res.status(401).json({ error: err, msg: 'Login timed out, please login again.', data: null }); } req.decodedToken = decodedToken; next(); }); }; var isNotAuthenticated = function (req, res, next) { var token = req.headers.authorization; if (!token) { next(); } else { jwt.verify(token, req.app.get('secret'), (err, decodedToken) => { if (!err) { return res.status(401).json({ error: err, msg: 'You are already logged in.', data: null }); } next(); }); } }; router.post('/user/signup', isNotAuthenticated, controller.signup); router.post('/user/signin', isNotAuthenticated, controller.signin); router.post('/blog/create', isAuthenticated, controller.create); router.get('/blog/getall', isAuthenticated, controller.getall); module.exports = router;<file_sep>import React, { Component } from 'react'; import './App.css'; import axios from 'axios'; class App extends Component { constructor(props) { super(props); this.state = { text: '', }; } submit() { sessionStorage.removeItem("token"); sessionStorage.removeItem("username"); window.location.reload(); } updateText(value) { this.setState({ text: value, }); } async post() { try { var config = { headers: { 'Content-Type': 'application/json', 'authorization': sessionStorage.getItem("token") } }; await axios.post('/api/blog/create', this.state, config); } catch (error) { alert(error.response.data.msg); } window.location.reload(); } render() { if (!sessionStorage.getItem("token")) { return ( <div className="App"> <header className="App-header-sign"> <SignUpForm></SignUpForm> </header> </div> ); } return ( <div className="App"> <header className="App-header"> <div id="signout"> <h3 id="username">{sessionStorage.getItem("username")}</h3> <input type="button" value="Sign Out" onClick={() => { this.submit() }} /> </div> <div> <textarea id="posttext" onChange={(event) => { this.updateText(event.target.value) }} value={this.state.username}></textarea> <input id="postsubmit" type="button" value="Post" onClick={() => { this.post() }} /> <br></br> <hr></hr> </div> <BlogPosts></BlogPosts> </header> </div> ); } } class SignUpForm extends Component { constructor(props) { super(props); this.state = { username: '', password: '' }; } updatePassword(value) { this.setState({ password: value, }); } updateUsername(value) { this.setState({ username: value, }); } async signup() { try { await axios.post('/api/user/signup', this.state); var token = (await axios.post('/api/user/signin', this.state)).data; sessionStorage.setItem("token", token.data); sessionStorage.setItem("username", this.state.username); } catch (error) { alert(error.response.data.msg); } this.setState({ password: '', }); window.location.reload(); } async signin() { try { var token = (await axios.post('/api/user/signin', this.state)).data; sessionStorage.setItem("token", token.data); sessionStorage.setItem("username", this.state.username); } catch (error) { alert(error.response.data.msg); } this.setState({ password: '', }); window.location.reload(); } render() { return ( <form> <h1>Sign Up/In</h1> <input type="text" onChange={(event) => { this.updateUsername(event.target.value) }} value={this.state.username} /> <br></br> <input type="password" password={<PASSWORD>} onChange={(event) => { this.updatePassword(event.target.value) }} /> <br></br> <input type="button" value="Sign Up" onClick={() => { this.signup() }} /> <input type="button" value="Sign In" onClick={() => { this.signin() }} /> </form> ) } } class BlogPosts extends Component { constructor() { super(); this.state = { data: [] }; } componentDidMount() { var config = { headers: { 'Content-Type': 'application/json', 'authorization': sessionStorage.getItem("token") } }; axios.get('/api/blog/getall', config) .then(res => this.setState({ data: res.data.data })); } render() { return ( <div> <h3>Feed</h3> <ul> {this.state.data.map(item => ( <li> <p>{item.text}</p> <small>By {item.user.username}</small> <hr></hr> </li> ))} </ul> </div> ); } } export default App;
cd8cf79d1ff8800f7c44bcc7284c40b2e685030c
[ "JavaScript" ]
2
JavaScript
melnele/react-blog
168f677362c09a25b7ea0e7117b04cd286be72dd
0163b2cae4235dcf552db58d175f1aafdb466f33