diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 85f62703b6786f43a12debab868657eb92fc8633..0000000000000000000000000000000000000000 --- a/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.idea -bullshit-codes.iml -.DS_Store diff --git a/.vs/slnx.sqlite b/.vs/slnx.sqlite deleted file mode 100644 index 5addc6b5fb764f58ba955e6ff6db6eddbeb9dc1d..0000000000000000000000000000000000000000 Binary files a/.vs/slnx.sqlite and /dev/null differ diff --git "a/C++/ P3387 \343\200\220\346\250\241\346\235\277\343\200\221\347\274\251\347\202\271\357\274\210\351\255\224\346\263\225RE\357\274\211.cpp" "b/C++/ P3387 \343\200\220\346\250\241\346\235\277\343\200\221\347\274\251\347\202\271\357\274\210\351\255\224\346\263\225RE\357\274\211.cpp" deleted file mode 100644 index 694a9f069690cd40628d59fa737bd1685b3ffd4d..0000000000000000000000000000000000000000 --- "a/C++/ P3387 \343\200\220\346\250\241\346\235\277\343\200\221\347\274\251\347\202\271\357\274\210\351\255\224\346\263\225RE\357\274\211.cpp" +++ /dev/null @@ -1,125 +0,0 @@ -#include -#include -#include -#include -#include -using namespace std; -struct Edge { - int to; - Edge*nextEdge; -}; -int N, M, DFSIndex; -queueQue; -vectorin; -vectorA; -vectorhead; -vectorvisited; -vectorinST; -vectorDFN; -vectoroldToNew; -vectorsum; -stackrecord; -listedge; -listnewGraph; -vectornewHead; -vectorDP; -inline void Tarjan(const int&n, const int&deepth) { - visited[n] = ++DFSIndex; - inST[n] = 1; - record.push(n); - for (Edge*i = head[n]; i; i = i->nextEdge) { - if (!visited[i->to]) { - Tarjan(i->to, deepth + 1); - DFN[n] = min(DFN[n], DFN[i->to]); - } else { - if (inST[i->to]) { - DFN[n] = min(visited[i->to], DFN[n]); - } - } - } - if (visited[n] == DFN[n]) { - while (record.top() != n) { - oldToNew[record.top()] = newHead.size(); - sum[oldToNew[record.top()]] += A[record.top()]; - inST[record.top()] = 0; - record.pop(); - } - oldToNew[record.top()] = newHead.size(); - sum[oldToNew[record.top()]] += A[record.top()]; - inST[record.top()] = 0; - record.pop(); - newHead.push_back(NULL); - } -} -inline void AddNewEdge(const int&from, const int&to) { - newGraph.push_back({to, newHead[from]}); - newHead[from] = &newGraph.back(); -} -inline void AddEdge(const int&from, const int&to) { - edge.push_back({to, head[from]}); - head[from] = &edge.back(); -} -void F() { - while (!Que.empty()) { - int node = Que.front(); - for (Edge*i = newHead[node]; i; i = i->nextEdge) { - DP[i->to] = max(DP[i->to],DP[node]+sum[i->to]); - in[i->to]--; - if(!in[i->to]){ - Que.push(i->to); - } - } - Que.pop(); - } -} -int main() { - ios::sync_with_stdio(0), cin.tie(0); - cin >> N >> M; - sum.assign(N + 1, 0); - DFN.assign(N + 1, 0x3f3f3f3f); - oldToNew.assign(N + 1, 0); - A.assign(N + 1, 0); - visited.assign(N + 1, 0); - head.assign(N + 1, NULL); - newHead.push_back(NULL); - for (int i = 1; i <= N; i++) { - cin >> A[i]; - } - for (int i = 1; i <= M; i++) { - int a, b; - cin >> a >> b; - AddEdge(a, b); - } - for (int i = 1; i <= N; i++) { - if (!visited[i]) { - inST.assign(N + 1, 0); - while(!record.empty()){ - record.pop(); - } - Tarjan(i, 0); - } - } - in.assign(newHead.size(), 0); - DP.assign(newHead.size(), 0); - for (int i = 1; i <= N; i++) { - DP[i] = sum[i]; - for (Edge*j = head[i]; j; j = j->nextEdge) { - if (oldToNew[i] != oldToNew[j->to]) { - AddNewEdge(oldToNew[i], oldToNew[j->to]); - in[j->to]++; - } - } - } - for (int i = 1; i < newHead.size(); i++) { - if (!in[i]) { - Que.push(i); - } - } - F(); - int Ans=0; - for(int i=1;i -using namespace std; - -/* - * 根据 decltype(i) 推断类型,返回类型为 int - */ -decltype(auto) -fn_1(int i) { - return i; -} - -/* - * 根据 decltype((i)) 推断类型,由于(i)是左值,返回类型为 int& - * 从而产生局部变量的引用 - */ -decltype(auto) -fn_2(int i) { - return (i); -} - -int main() { - cout << fn_1(1) << endl ; // OK - cout << fn_2(1) << endl ; // Segmentation fault -} diff --git a/C++/SwapFunc.cpp b/C++/SwapFunc.cpp deleted file mode 100644 index 554fcd49c89a44bee8b0795226f315a2e11c34b5..0000000000000000000000000000000000000000 --- a/C++/SwapFunc.cpp +++ /dev/null @@ -1,14 +0,0 @@ -//以值传递的方式实现交换接口,并不能达到交换效果 -void Swap(int a,int b) -{ - int nTemp = a; - a = b; - b = temp; -} - -int main() -{ - int a = 11,b = 3; - //a依然是2,b依然是3 - Swap(a,b); -} \ No newline at end of file diff --git a/C++/VectorErase.cpp b/C++/VectorErase.cpp deleted file mode 100644 index 93cec9a4638452a5fb7d626ab68e6d4a0389cc5c..0000000000000000000000000000000000000000 --- a/C++/VectorErase.cpp +++ /dev/null @@ -1,13 +0,0 @@ -#include - -//遍历删除元素会导致core dump -int main() -{ - std::vector vec= {1,2,3,4,5}; - for (auto itr = vec.begin(); itr != vec.end(); ++itr) { - if (*itr == 5) { - vec.erase(itr); - } - } - return 0; -} diff --git a/C++/VirtualDestructor.cpp b/C++/VirtualDestructor.cpp deleted file mode 100644 index 09d2556b00b99ba589720b739b3acb0a895df958..0000000000000000000000000000000000000000 --- a/C++/VirtualDestructor.cpp +++ /dev/null @@ -1,29 +0,0 @@ -//基类的析构函数必须是virtual,否则使用多态后,会造成内存泄漏 -class Base{ - Base() {std::cout << "constructor Base" << std::endl;} - ~Base() {std::cout << "destructor Base" << std::endl;} -}; - -class Derived : public Base{ - Derived() { - m_ptr = new int(1); - std::cout << "constructor Derived" << std::endl; - } - ~Derived() { - if(NULL != m_ptr) - { - delete m_ptr; - m_ptr = NULL; - } - std::cout << "destructor Derived" << std::endl; - } -private: - int* m_ptr; -}; - -int main() -{ - Base* pBase = new Derived(); - delete pBase; - return 0; -} diff --git a/C++/nullpointer.cpp b/C++/nullpointer.cpp deleted file mode 100644 index 18c2a81de39612b1c2c89ed4009ef2e54ea85adb..0000000000000000000000000000000000000000 --- a/C++/nullpointer.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include -class NullPointer { -public: - void PrintStr() - { - std::cout << "PrintValue" << std::endl; - } - - void PrintValue() - { - std::cout << "m_iValue = " << m_iValue << std::endl; - } - -private: - int m_iValue; -}; - -int main() -{ - // NULL 指针也是可以访问成员函数的。 - NullPointer* ptr = NULL; - ptr->PrintStr(); -} \ No newline at end of file diff --git a/C++/pointer_usage.cpp b/C++/pointer_usage.cpp deleted file mode 100644 index f3268be55a83e0761d288ef805a6ad938d6978ce..0000000000000000000000000000000000000000 --- a/C++/pointer_usage.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// run online: https://wandbox.org/permlink/ES1NyCQA6ivaZLZS -#include -#include - -bool is_enable() { - return true; -} - -int main() { - int *p = nullptr; - if (is_enable()) { - // 作用域问题,不应该再定义指针p,引发内存泄漏 - // 分配也可能失败,看情况处理bad_alloc异常 - int *p = new int[1024]; - // sizeof(指针)! - memset(p, 0, sizeof(p)); - // other operation - } - // 1.释放的是p而不是申请的1024内存 - // 2.虽然基本类型用delete和delete[]差不多,但是其他类型就不是了,用智能指针管理更好 - delete p; - return 0; -} \ No newline at end of file diff --git a/C++/whileFalse b/C++/whileFalse deleted file mode 100644 index 15b26b19a82a0834fea58f7dbe411ef4f3baadd3..0000000000000000000000000000000000000000 --- a/C++/whileFalse +++ /dev/null @@ -1,9 +0,0 @@ -#include - int main() - { - int false=1; - while(false){ - printf("hello world!! "); - } - return 0; - } \ No newline at end of file diff --git "a/C/C\350\257\255\350\250\200\346\235\200\344\272\272\347\247\230\346\212\200" "b/C/C\350\257\255\350\250\200\346\235\200\344\272\272\347\247\230\346\212\200" deleted file mode 100644 index 88f756b1eb1a71658fd23df8e7939bb679c68289..0000000000000000000000000000000000000000 --- "a/C/C\350\257\255\350\250\200\346\235\200\344\272\272\347\247\230\346\212\200" +++ /dev/null @@ -1,3 +0,0 @@ -//C语言杀人秘技,令人防不胜防 -#define true false -#define false true diff --git "a/C/\345\265\214\345\205\245\345\274\217C_\346\225\260\346\215\256\347\261\273\345\236\213.md" "b/C/\345\265\214\345\205\245\345\274\217C_\346\225\260\346\215\256\347\261\273\345\236\213.md" deleted file mode 100644 index 59494aa4c9a6d2b7495dfc88485bf73472a6a06a..0000000000000000000000000000000000000000 --- "a/C/\345\265\214\345\205\245\345\274\217C_\346\225\260\346\215\256\347\261\273\345\236\213.md" +++ /dev/null @@ -1,31 +0,0 @@ -# 嵌入式编程中的数据类型 - -举个例子: -``` -void delay(uint8_t i) -{ - uint8_t j = 100; - while(i -- ) - { - while(j -- ); - } -} - -uint8_t sum_func(uint8_t a,uint8_t b) -{ - return a + b; -} - - -void main(void) -{ - - ... - delay(256); - sum = sum_func(200,200); - ... -} - -``` - -**碰到还好,就怕运行的时候所有参数都是在范围之内,其实很大程度上代码已经飞起来了,而且你还不知道。活在梦里** diff --git "a/C/\346\225\260\347\273\204\350\266\212\347\225\214\346\255\273\345\276\252\347\216\257.md" "b/C/\346\225\260\347\273\204\350\266\212\347\225\214\346\255\273\345\276\252\347\216\257.md" deleted file mode 100644 index 142c7b700491bff31222e8d40e25fe34e985627e..0000000000000000000000000000000000000000 --- "a/C/\346\225\260\347\273\204\350\266\212\347\225\214\346\255\273\345\276\252\347\216\257.md" +++ /dev/null @@ -1,21 +0,0 @@ -- **数组越界死循环** - -``` -int main() -{ - int a[10], n; - for (n = 0; n <= 10; n++) { - a[n] = n - 10; - printf("%d\n",a[n]); - } - printf("end\n"); - return 0; -} -``` - -​ - -​ 在内存分配上,按**a[0],a[1],a[2]…a[9],n** 排列 ,在for循环中有数组越界:a[10] = 10 - 10, a[10]对应的内存位置 - -正好是n的位置所在, 把n重新写成了0,所以一直死循环…^-^ - diff --git "a/C/\346\227\240\346\225\214\347\232\204 gnu \346\211\251\345\261\225.c" "b/C/\346\227\240\346\225\214\347\232\204 gnu \346\211\251\345\261\225.c" deleted file mode 100644 index 7434de7370919c966571747e272b57827ac3b3cf..0000000000000000000000000000000000000000 --- "a/C/\346\227\240\346\225\214\347\232\204 gnu \346\211\251\345\261\225.c" +++ /dev/null @@ -1,17 +0,0 @@ -这串代码用来获取用户的家,如果实在获取不到就用 `/etc`。 -获取方式是: -+ $HOME 环境变量 -+ `/etc/passwd` 中的项 -+ `/home/$username` - -但是由于用了无敌的 GNU C 扩展,所以导致代码可能不那么…… - -```c -char *get_default_watch_on(void) -{ - return getenv("HOME") ? : - ({ struct passwd *p; (p = getpwuid(getuid())) ? p->pw_dir : - (({ char p[5 + _POSIX_LOGIN_NAME_MAX]; sprintf(p, "/home/%s", getlogin()); strdup(p); }) ? : - (char *) (fprintf(stderr, "Warning: using /etc as watch-on directory"), "/etc") );}); -} -``` \ No newline at end of file diff --git "a/C/\346\227\240\346\225\214\347\246\273\350\260\261\344\275\215\350\277\220\347\256\227.md" "b/C/\346\227\240\346\225\214\347\246\273\350\260\261\344\275\215\350\277\220\347\256\227.md" deleted file mode 100644 index dc78eecf74ea2bb5a1cd71a25670a263c19d2553..0000000000000000000000000000000000000000 --- "a/C/\346\227\240\346\225\214\347\246\273\350\260\261\344\275\215\350\277\220\347\256\227.md" +++ /dev/null @@ -1,77 +0,0 @@ -某科学的玩具操作系统中的一串用来映射到虚拟内存的代码: -```c - -/* map page s (virtual) to d... okay, what am i doing? */ - -void *__mapto(void *s, void *d, int attr) { -#if CONFIG_64BIT - __archptr_t *lvl1, *lvl2, *lvl3, *p; - __archptr_t dest_addr; - - dest_addr = (__archptr_t) d; - - lvl1 = (__archptr_t *) LVL1_PT[(dest_addr >> 39) & 4095]; - - if (!lvl1) { - if (!(lvl1 = early_kmalloc(4096, 4096))) - panic("mapto: Out of memory\n"); - - LVL1_PT[(dest_addr >> 39) & 4095] = (__archptr_t) lvl1 | DEFAULT_PAGE_ATTR; - memset(lvl1, 0, 4096); - } - - p = (__archptr_t *) ((__archptr_t) lvl1 & ~0xfffu); - lvl2 = (__archptr_t *) p[(dest_addr >> 30) & 4095]; - - if (!lvl2) { - if (!(lvl2 = early_kmalloc(4096, 4096))) - panic("mapto: Out of memory\n"); - - p[(dest_addr >> 30) & 4095] = (__archptr_t) lvl2 | DEFAULT_PAGE_ATTR; - memset(lvl2, 0, 4096); - } - - lvl3 = (__archptr_t *) ((__archptr_t) lvl2 & ~0xfffu); - - if (s) - lvl3[(dest_addr >> 21) & 4095] = (__archptr_t) s | attr; - - else - lvl3[(dest_addr >> 21) & 4095] &= ~0xfffu | attr; - - return d; -#else - - __archptr_t dest_addr = (__archptr_t) d; - __archptr_t *lvl1; - __archptr_t *lvl2; - - dest_addr &= ~PAGE_MASK; - - /* 10 lvl1 10 lvl2 12 offset */ - lvl1 = (__archptr_t *) LVL1_PT[dest_addr >> 22]; - - if (!lvl1) { - if (!(lvl1 = early_kmalloc(4096, 4096))) - panic("mapto: Out of memory\n"); - - LVL1_PT[dest_addr >> 22] = (__archptr_t) lvl1 | DEFAULT_PAGE_ATTR; - memset(lvl1, 0, 4096); - } - - lvl2 = (__archptr_t *) ((__archptr_t) lvl1 & ~0xffu); - - if (!s) - /* clear attributes and then set */ - - lvl2[(dest_addr >> 12) & 1023] &= ~0xff | attr; - - else - lvl2[(dest_addr >> 12) & 1023] = (__archptr_t) s | attr; - - - return (void *) dest_addr; -#endif -} - -``` \ No newline at end of file diff --git "a/C/\346\227\240\347\254\246\345\217\267\346\225\264\346\225\260\351\231\244\346\263\225\345\207\272\351\224\231" "b/C/\346\227\240\347\254\246\345\217\267\346\225\264\346\225\260\351\231\244\346\263\225\345\207\272\351\224\231" deleted file mode 100644 index be3a8d300a294e24d2b3fd131e2e03b6cd9f6465..0000000000000000000000000000000000000000 --- "a/C/\346\227\240\347\254\246\345\217\267\346\225\264\346\225\260\351\231\244\346\263\225\345\207\272\351\224\231" +++ /dev/null @@ -1,10 +0,0 @@ -//在嵌入式开发中,无符号数据常用于计数、与寄存器交互等,有符号数据使用无符号数据计算时需要慎重。 -//有些无符号数据隐藏在结构体中,如果不查看源码,可能会当成有符号数据使用 -int main(){ - unsigned int a=100; - int b=-10000; - b/=a; - printf("%d\n",b); - return 0; -} -//输出 42949572,而不是-100 \ No newline at end of file diff --git "a/C/\346\227\240\350\277\224\345\233\236\345\207\275\346\225\260\345\206\205\351\203\250\345\210\206\351\205\215\345\206\205\345\255\230" "b/C/\346\227\240\350\277\224\345\233\236\345\207\275\346\225\260\345\206\205\351\203\250\345\210\206\351\205\215\345\206\205\345\255\230" deleted file mode 100644 index 97d47c5461341905fc3b9f06909a3eab91a8037d..0000000000000000000000000000000000000000 --- "a/C/\346\227\240\350\277\224\345\233\236\345\207\275\346\225\260\345\206\205\351\203\250\345\210\206\351\205\215\345\206\205\345\255\230" +++ /dev/null @@ -1,12 +0,0 @@ -#include - -void test(char * P){ - p = (char *)malloc(sizeof(char)*100); -} - -int main(){ - char *t=NULL; - test(t); - //test函数运行结束后t并未分配内存,还是NULL - strcpy(t,"Hello");///出现段错误,因为t是NULL -} \ No newline at end of file diff --git "a/C/\346\231\272\350\203\275\347\272\240\351\224\231.c" "b/C/\346\231\272\350\203\275\347\272\240\351\224\231.c" deleted file mode 100644 index f82a1d72b343112903c56de1fd5c994e61ca601c..0000000000000000000000000000000000000000 --- "a/C/\346\231\272\350\203\275\347\272\240\351\224\231.c" +++ /dev/null @@ -1,9 +0,0 @@ -#define ture true - -#define flase false - -#define viod void - -#define mian main - -#define strcut struct \ No newline at end of file diff --git "a/C/\346\237\220\345\220\214\345\255\246\347\232\204\346\234\200\350\277\221\347\202\271\345\257\271\344\273\243\347\240\201.c" "b/C/\346\237\220\345\220\214\345\255\246\347\232\204\346\234\200\350\277\221\347\202\271\345\257\271\344\273\243\347\240\201.c" deleted file mode 100644 index bb6a0240d8cfd79490da71bfbb2550b746c08d72..0000000000000000000000000000000000000000 --- "a/C/\346\237\220\345\220\214\345\255\246\347\232\204\346\234\200\350\277\221\347\202\271\345\257\271\344\273\243\347\240\201.c" +++ /dev/null @@ -1,103 +0,0 @@ -#include -#include -int x[1000001],y[1000001],s[1000001]; -int nth(int *a,int L,int R,int k) -{ - if(L==R)return a[L]; - int mid=(L+R)/2; - int i;int eq=0; - int l1=0,l2=0; - for(i=L;i<=R;i++) - { - if(a[i]a[mid])y[++l2]=a[i]; - else eq++; - } - if(k<=l1) - { - for(i=1;i<=l1;i++)s[i]=x[i]; - return nth(s,1,l1,k); - } - else if(k<=l1+eq)return a[mid]; - else - { - k-=(l1+eq); - for(i=1;i<=l2;i++)s[i]=y[i]; - return nth(s,1,l2,k); - } - } - int cmp(int x,int y) - { - if(x=0)return x-y; - else return y-x; - } -typedef struct{ - int x[1000000]; - int y[1000000]; - int sum; -}point; -point a; -int min(point a) -{ - point b,c; - int i,j; - if(a.sum==2) - { - return sqrt(pow(a.x[0]-a.x[1],2)+pow(a.y[0]-a.y[1],2)); - } - else - { - int midx=nth(a.x,1,a.sum-1,a.sum/2); - b.sum=0; - c.sum=0; - for(i=0;i=0; i--) - { - printf("@_@<-->@_@\n"); - } - - printf("end\n"); -} -``` -end是输出不了。因为死循环了。 \ No newline at end of file diff --git "a/C/\347\245\236\347\272\247\345\256\271\351\224\231" "b/C/\347\245\236\347\272\247\345\256\271\351\224\231" deleted file mode 100644 index b402be46b2aa49d699a08345a9b50e98aff11919..0000000000000000000000000000000000000000 --- "a/C/\347\245\236\347\272\247\345\256\271\351\224\231" +++ /dev/null @@ -1,13 +0,0 @@ - -//神级拼写容错 -#define mian main -#define ture true - - -void mian() { - if(ture){ - print("yes! run success!"); - } -} - -//build success!!!! diff --git a/Java/SummaryDataServcieUtiles.java b/Java/SummaryDataServcieUtiles.java deleted file mode 100644 index 15255721f133319c861b764e940555f53633e3e8..0000000000000000000000000000000000000000 --- a/Java/SummaryDataServcieUtiles.java +++ /dev/null @@ -1,40 +0,0 @@ -@Service -public class SummaryDataServcieUtiles { - /*** - * 核心业务代码省略 - * */ - public static void ValidateSummaryData(Integer orderId,Integer quantity) { - boolean isOrderValid = checkOrder(orderId, quantity); - if (isOrderValid) { - boolean isPaymentSuccessful = processPayment(orderId, quantity); - if (isPaymentSuccessful) { - boolean isInventoryUpdated = updateInventory(orderId, quantity); - if (isInventoryUpdated) { - //此处省略业务逻辑代码35行 - } else { - //此处省略业务逻辑代码15行 - } - } else { - //此处省略业务逻辑代码32行 - } - } else { - //此处省略业务逻辑代码12行 - } - } - - private static boolean checkOrder(Integer orderId, Integer quantity) { - // 此处省略业务逻辑代码15行 - return orderId % quantity == 0; - } - - private static boolean processPayment(Integer orderId, Integer quantity) { - // 此处省略业务逻辑代码32行 - return orderId % quantity != 0; - } - - private static boolean updateInventory(Integer orderId, Integer quantity) { - // 此处省略业务逻辑代码25行 - return orderId % quantity == 0; - } -} - diff --git a/Java/cache-service.java b/Java/cache-service.java deleted file mode 100644 index 14dcde2e57990bf220ccccf21184f6b3ac58d249..0000000000000000000000000000000000000000 --- a/Java/cache-service.java +++ /dev/null @@ -1,24 +0,0 @@ -public class XXXServiceImpl implements XXXService { - - // 某团队的规范 - // 当你想使用缓存的时候,不允许在这里加@Cacheable,必须新增一个cache层 - @Override - public XXX xxx(String id) { - return xxxService.xxx(id); - } -} - - - - -public class XXXCacheServiceImpl implements XXXCacheService { - - @Autowired - private XXXService xxxService; - - @Override - @Cacheable(value = "auth", key = "targetClass.name+'_'+#id", unless = "#result eq null") - public XXX xxx(String id) { - return xxxService.xxx(id); - } -} diff --git a/LICENSE b/LICENSE deleted file mode 100644 index b1f66c6ab8d743a451953ef64234ca9818981744..0000000000000000000000000000000000000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 红薯 - -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. - -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. diff --git a/README.md b/README.md deleted file mode 100644 index dba2dbf938031ec42be3355cb1563ac749ca303b..0000000000000000000000000000000000000000 --- a/README.md +++ /dev/null @@ -1,82 +0,0 @@ -![bullshit](resource/仓库内头图(900*100).png) - -时隔四年,bullshit-codes 仓库再次面向所有开发者征集你们遇到的坑爹代码! - -这四年里,Gitee 见证了各种技术栈的更迭,陪伴了无数开发者的技术成长之路,也看到越来越多的优秀开源项目被人们所熟知。 - -当然,我们也相信,这四年里出现过多少优雅的代码,就出现过多少坑爹的代码。 - -我们坚信:The most bullshit codes are yet to come,把那些让你哭笑不得、怀疑人生、血压升高的代码展示出来吧,庆祝我们的错误,让我们一起从中学习,共同提升。 - -## 「公开处刑」名单 - -- 7月13日「公开处刑」人员 - -@伊成:[为了应付公司每月统计代码行数,同事的写法也是醉了...](https://gitee.com/gitee-community/bullshit-codes/pulls/273) - -@hishuwei:[winform程序路径写log文件](https://gitee.com/gitee-community/bullshit-codes/pulls/272) - -@Lv丶小胖:[这绝对是世上最快的提醒商家发货功能](https://gitee.com/gitee-community/bullshit-codes/pulls/267) - -- 7月12日「公开处刑」人员 - -@卖兔子的小萝卜:[架构怒发冲冠的对我说不懂JVM的机制](https://gitee.com/gitee-community/bullshit-codes/pulls/258) - -@sahooz:[论单机无联网App如何无痛升级数据库:升级数据库就删除所有表然后重建](https://gitee.com/gitee-community/bullshit-codes/pulls/250) - - -## 如何提交坑爹代码 - -1. Fork 本仓库,并创建一个包含坑爹代码的 Pull Request;或直接在对应语言的文件夹下上传/新建文件,创建一个轻量级 Pull Request。 -2. Pull Request 必须包含清晰的标题和说明,描述为什么这段代码是坑爹代码。 -3. 请给提交的文件取一个有意义的文件名及符合对应语言的文件后缀名,描述代码相关信息可以使用注释。具体形式可参考[Demo.java](java/Demo.java)。 -4. Gitee 团队会审核这些 Pull Requests,接受符合要求的提交。 - -## 选出你心目中的坑爹代码 -1. 进入[已合并的 Pull Requests 列表](https://gitee.com/gitee-community/bullshit-codes/pulls?assignee_id=&author_id=&label_ids=&label_text=&milestone_id=&priority=&project_id=gitee-community%2Fbullshit-codes&project_type=&scope=&search=&single_label_id=&single_label_text=&sort=closed_at+desc&status=merged&target_project=&tester_id=)中为你心中的坑爹代码评论及点赞。 -2. 每天被合并 PR 中累计 **评论人数+点赞次数** 最多的 PR 将会获得当天的「公开处刑」资格,并在活动期间工作日的 18:00 正式公布。 - -以下图 PR 为例,评论人数+点赞次数为 2: - -![](resource/eg.jpg) - -## 评选规则 - -- 本次坑爹代码 2.0 收集活动日期为:2023年7月11日至2023年7月21日。 -- 活动期间工作日的 18:00 后提交的 PR 将参与次日的评选,周六及周日提交的 PR 将参与周一的评选。 -- 本次活动不限制编程语言,不限制提交次数。 -- 参赛的代码至少是可运行的代码或者是看似可运行的代码。 -- 所提交代码不包含商业及政治敏感信息,需匿名化作者和公司。 - -## 奖项设置 - -### 「精神抚慰」奖 - - 每天被「公开处刑」的提交者将会获得「精神抚慰」奖 : **技术书籍/马建仓公仔/开源内裤/Gitee 定制马克杯** 任选其一。 - -### 「求求你转行吧」奖 - -活动期间被合并PR数量最多的开发者将会获得「求求你转行吧」奖:**技术书籍/马建仓公仔/开源内裤/Gitee 定制马克杯** 任选其三。 - -### 「还!有!谁!!!」奖 - -活动期间累计获得 **评论人数+点赞次数** 最多的 PR,该 PR 的提交者将会获得「还!有!谁!!!」奖:**技术书籍+马建仓公仔+开源内裤+Gitee 定制马克杯** 。 - - -## 奖品一览 - -### 技术书籍 - -![](resource/book.png) - -### 马建仓公仔 - -![](resource/mjc.png) - -### 开源内裤 - -![](resource/underwear.png) - -### Gitee 定制马克杯 - -![](resource/cup.png) diff --git a/README_old.md b/README_old.md deleted file mode 100644 index 7a6c99b7fb1138a2d2725c49ef53eba9b632942d..0000000000000000000000000000000000000000 --- a/README_old.md +++ /dev/null @@ -1,162 +0,0 @@ -## 没有最坑,只有更坑! - -![bullshit](resource/bullshit.png) - -### 活动简介 - -作为一个程序员,你看过哪些坑爹代码,你又写过多少坑爹代码,还有多少你不知道的坑爹代码?本仓库的目的就是为了收集这些坑爹代码,可以让别人不掉坑或者少掉坑,可以避免自己掉坑,或许哈哈一乐。如果你觉得这个仓库有意思,别忘了给个 Star 哦。 - - -### 提交作品 - -任何人都可以提交代码片段,提交人请 fork 此仓库到个人仓库,完成自己的代码后,通过提交 Pull Requests 来提交作品。 - -关于 Fork 和 Pull Requests 的用法请阅读 [https://gitee.com/help/articles/4128](https://gitee.com/help/articles/4128) - -代码作品规则: - -1. 参与活动的代码可以是任何编程语言 -2. 请给参赛的文件取一个有意义的文件名,文件名长度不得超过 20 个字符(不含扩展名),不能和他人的文件重名(请根据不同的语言存放到对应目录) -3. 提交信息中请写明代码的坑爹之处 -4. 允许提交多个作品 -5. 每段代码请务必给出详细的注释和说明 - -具体形式可参考作品 [Demo.java](java/Demo.java) - - ------------------------------------Gitee 六周年活动----------------------------------------- - - -### 奖项设置(活动已经结束,欢迎继续投递~) - -为了鼓励大家踊跃提交代码,也刚好是Gitee 6 周年 666 之际,我们给大家准备了一些奖品。它们是: - - **霸王防脱洗发液+头皮营养液(程序员专属套装)**,共 **30** 份 - -![输入图片说明](https://images.gitee.com/uploads/images/2019/0520/154609_e88c976b_1899542.png "200-霸王洗发水.png") - - **猫王蓝牙音箱** -![输入图片说明](https://images.gitee.com/uploads/images/2019/0524/104605_3b1116be_1899542.jpeg "300-猫王收音机.jpg") - - **向日葵控控** -![输入图片说明](https://images.gitee.com/uploads/images/2019/0524/104631_a035813f_1899542.png "200-400花生壳盒子.png") - - **码云巨型鼠标垫** -![输入图片说明](https://images.gitee.com/uploads/images/2019/0514/150323_f40a68bf_1899542.jpeg "200鼠标垫.jpg") - - **码云官方T恤** -![输入图片说明](https://images.gitee.com/uploads/images/2019/0514/150102_d100ec5d_1899542.png "200T.png") - - - **PS:请留意活动底部开奖区噢** :sunglasses: - - -### 参与评选 - -你可以点进任何一个参与作品的文件,在评论区对该文件进行点评。 - - -### 评选规则 - -参赛的代码至少是可运行的代码或者是看似可运行的代码。有趣、啰嗦、坑爹的代码可以获得更多的点评。 - -我们将根据参赛代码收获的代码评论人数(请注意这里是人数,而不是评论数)来评选出大家觉得最有“意思”的代码作品。 - -### 活动时间 - -此仓库作为收集坑爹代码的用途将长期进行。但在此期间(2019/5/27 ~ 2019/6/28)提交的作品将根据系统评选的结果,结合活动筹备组成员的评审,给获奖作品的作者颁发奖品,以及从 **评论** 中抽取 10名,随机赠予(码云官方T恤、个推马克杯、Tars公仔、简书笔记本、传智博客技术书籍等)礼品一份。 - - - **周一到周五** 每天下午 18:00会在所有提交的作品中推出一个代码作品,送出 **码云官方T恤+霸王防脱套装** 一套。(作品不会重复推出) - - - **每周** 周五下午18:00 在本周推出的五个作品中评论人数最多的作品将获得 **码云巨型鼠标垫** 一份。( **越早投稿获奖机会越大喔~** ) - - - **截止到6月28日18:00** ,评论人数最多的作品将获得 **猫王收音机+向日葵控控** 一份。 - - - -### 小贴士 - 1.工作人员会在活动结束后的五个工作日内联系您并安排寄出,请留意邮箱或电话。 - 2.关于活动有任何问题可在码云公众号下留言,我们将在1-2个工作日内给予回复。 -![输入图片说明](https://images.gitee.com/uploads/images/2019/0514/151233_a16e7749_1899542.png "150码云公众号二维码.png") - - -### 赞助商 -![输入图片说明](https://images.gitee.com/uploads/images/2019/0603/184947_4e9f93ab_1899542.png "赞助商logo.png") - - - - - --------------------------开奖区------------------------- - - **5月27日** 恭喜 debuglife :[令人发指的新建ID操作](https://gitee.com/oschina/bullshit-codes/blob/master/java/NewId.java) 获得 **码云官方T恤+霸王防脱套装** - - **5月28日** 恭喜 cailong :[论StringBuffer的使用](https://gitee.com/oschina/bullshit-codes/blob/master/java/Append.java) 获得 **码云官方T恤+霸王防脱套装** - - **5月29日** 恭喜 jspp :[大神留步,帮我看个问题](https://gitee.com/oschina/bullshit-codes/blob/master/java/BadCode.java) 获得 **码云官方T恤+霸王防脱套装** - - **5月30日** 恭喜 weijiangbo :[我蒙了,一样的取法为啥获取不到值](https://gitee.com/oschina/bullshit-codes/blob/master/java/ColourType.java) 获得 **码云官方T恤+霸王防脱套装** - - **5月31日** 恭喜 tandy :[刚写完的排序算法就被开除了](https://gitee.com/oschina/bullshit-codes/blob/master/java/ArraySort.java) 获得 **码云官方T恤+霸王防脱套装** - - 同时再次恭喜本周评论人数最多的作品「[论StringBuffer的使用](https://gitee.com/oschina/bullshit-codes/blob/master/java/Append.java)」获得 **码云巨型鼠标垫** - -**6月3日** 恭喜 pftian :[这个无限循环嵌套,只是总循环的一部分。。。我已经绕晕在黄桷湾立交](https://gitee.com/oschina/bullshit-codes/blob/master/java/InfiniteCycle) 获得 **码云官方T恤+霸王防脱套装** - -**6月4日** 恭喜 z77z :[一行代码就可以搞定的,非要写的花里胡哨](https://gitee.com/oschina/bullshit-codes/blob/master/java/AFilter) 获得 **码云官方T恤+霸王防脱套装** - -**6月5日** 恭喜 誓言 :[为了后期优化查询速度你就先休眠一会吧](https://gitee.com/oschina/bullshit-codes/blob/master/java/Sleep.java) 获得 **码云官方T恤+霸王防脱套装** - -**6月6日** 恭喜 看着星空的状态 :[这个try catch可以再大一点~](https://gitee.com/oschina/bullshit-codes/blob/master/java/BadTry.java) 获得 **码云官方T恤+霸王防脱套装** - -**6月7日** 恭喜 shuzheng :[Arrays.asList() 教你重新做人](https://gitee.com/oschina/bullshit-codes/blob/master/java/FuckArrays) 获得 **码云官方T恤+霸王防脱套装** - -同时再次恭喜本周评论人数最多的作品[为了后期优化查询速度你就先休眠一会吧](https://gitee.com/oschina/bullshit-codes/blob/master/java/Sleep.java) 获得 **码云巨型鼠标垫** - -**6月10日** 恭喜 Try :[入职第一天 老板说先优化下网站卡顿, 然后发现了它](https://gitee.com/oschina/bullshit-codes/blob/master/php/%E5%85%A5%E8%81%8C%E7%AC%AC%E4%B8%80%E5%A4%A9.php) 获得 **码云官方T恤+霸王防脱套装** - -**6月11日** 恭喜 李葵 :[js 回调](https://gitee.com/oschina/bullshit-codes/blob/master/js/callback.js) 获得 **码云官方T恤+霸王防脱套装** - -**6月12日** 恭喜 阿提说说 :[Stream 用的66的](https://gitee.com/oschina/bullshit-codes/blob/master/java/NBStream.java) 获得 **码云官方T恤+霸王防脱套装** - -**6月13日** 恭喜 cailong :[tryCatch正确用法 你用对了吗?](https://gitee.com/oschina/bullshit-codes/blob/master/js/tryCatch.js) 获得 **码云官方T恤+霸王防脱套装** - -**6月14日** 恭喜 lay :[keng.java](https://gitee.com/oschina/bullshit-codes/blob/master/java/keng.java) 获得 **码云官方T恤+霸王防脱套装** - -同时再次恭喜本周评论人数最多的作品[js 回调](https://gitee.com/oschina/bullshit-codes/blob/master/js/callback.js) 获得 **码云巨型鼠标垫** - -**6月17日** 恭喜 FunGa :[sql too long](https://gitee.com/oschina/bullshit-codes/blob/master/sql/sql_too_long.sql) 获得 **码云官方T恤+霸王防脱套装** - -**6月18日** 恭喜 yukuncc :[静态异常,都准备好了,随时可以抛?](https://gitee.com/oschina/bullshit-codes/blob/master/java/BadException.java) 获得 **码云官方T恤+霸王防脱套装** - -**6月19日** 恭喜 文文小杰 :[从不面向对象编程,但是却有对象你打我啊?](https://gitee.com/oschina/bullshit-codes/blob/master/java/SayNoToOOP) 获得 **码云官方T恤+霸王防脱套装** - -**6月20日** 恭喜 Joker :[我见过的变量命名](https://gitee.com/oschina/bullshit-codes/blob/master/java/VariableNames.png) 获得 **码云官方T恤+霸王防脱套装** - -**6月21日** 恭喜 残虹 :[论一条语句写完整个报表的sql长度](https://gitee.com/oschina/bullshit-codes/blob/master/sql/report.sql) 获得 **码云官方T恤+霸王防脱套装** - -同时再次恭喜本周评论人数最多的作品[静态异常,都准备好了,随时可以抛?](https://gitee.com/oschina/bullshit-codes/blob/master/java/BadException.java) 获得 **码云巨型鼠标垫** - -**6月24日** 恭喜 ksice :[试试简单的加减乘除](https://gitee.com/oschina/bullshit-codes/blob/master/java/AddCode) 获得 **码云官方T恤+霸王防脱套装** - -**6月25日** 恭喜 liuh1988 :[手机号码验证](https://gitee.com/oschina/bullshit-codes/blob/master/java/PhoneRuleValidate.java) 获得 **码云官方T恤+霸王防脱套装** - -**6月26日** 恭喜 非常君 :[难怪每次系统挂掉,资源基本是让ORACLE占掉](https://gitee.com/oschina/bullshit-codes/blob/master/java/FeeServiceImpl.java) 获得 **码云官方T恤+霸王防脱套装** - -**6月27日** 恭喜 倒霉狐狸 :[添加神级ifelse使用方式](https://gitee.com/oschina/bullshit-codes/blob/master/php/IF_ELSE.php) 获得 **码云官方T恤+霸王防脱套装** 。 - -**6月28日** 恭喜 Joker :[我见过的字段设计](https://gitee.com/oschina/bullshit-codes/blob/master/sql/WechatIMG199.png) 获得 **码云官方T恤+霸王防脱套装** - -同时再次恭喜本周评论人数最多的作品 [手机号码验证](https://gitee.com/oschina/bullshit-codes/blob/master/java/PhoneRuleValidate.java) 获得 **码云巨型鼠标垫** - -最后恭喜本次坑爹代码大赛活动评论人数最多作品 [大神留步,帮我看个问题](https://gitee.com/oschina/bullshit-codes/blob/master/java/BadCode.java) 喜提 **猫王收音机+向日葵控控** - -【评论区开奖】 - - 恭喜[@大武](https://gitee.com/dawuww)、[@stormh](https://gitee.com/stormh)、[@rockrush](https://gitee.com/rockrush)、[@notreami](https://gitee.com/notreami)、[@无知是天堂](https://gitee.com/xunmi)、[@polly](https://gitee.com/pollyduan)、[@FansinZhao](https://gitee.com/fansinZhao)、[@cyper](https://gitee.com/uniquejava)、[@小鹏](https://gitee.com/RocY)、[@dwing](https://gitee.com/dwing)、[@natsume](https://gitee.com/sparklighter)获奖,请将邮寄地址私信给我哟~ - -兑奖有效期:6月28日-7月18日 (过期无效) - - diff --git a/actionscript/99paras.jpeg b/actionscript/99paras.jpeg deleted file mode 100644 index e9450358aac778cf29aa24e55c12f729f76d9337..0000000000000000000000000000000000000000 Binary files a/actionscript/99paras.jpeg and /dev/null differ diff --git a/android/EventBusSample.java b/android/EventBusSample.java deleted file mode 100644 index 434f24ed1c0e8a3cdd827284b42a76ec2ec563fd..0000000000000000000000000000000000000000 --- a/android/EventBusSample.java +++ /dev/null @@ -1,9 +0,0 @@ -public class EventBusSample { - @Subscribe(threadMode = ThreadMode.MAIN) - public void Event(MessageAreaDialog messageEvent) { - //高级写法 - area_tv.setText(MessageAreaDialog.adress); - provinceid = MessageAreaDialog.provinceid; - cityid = MessageAreaDialog.cityid; - } -} diff --git a/android/LoopView.java b/android/LoopView.java deleted file mode 100644 index b0408718b6caf432dcedd8b1f0916de347530d31..0000000000000000000000000000000000000000 --- a/android/LoopView.java +++ /dev/null @@ -1,29 +0,0 @@ - -/** - * 17年我刚入职接手前人的的代码,记得当时android5.0刚普及而已 - * 在他的手机上应该运行正常吧 - */ -public class LoopView extends View { - - public LoopView(Context context) { - this(context, null); - } - - public LoopView(Context context, AttributeSet attrs) { - this(context, attrs, 0); - } - - public LoopView(Context context, AttributeSet attrs, int defStyleAttr) { - this(context, attrs, defStyleAttr, 0);//这骚操作我给满分... - } - - @TargetApi(Build.VERSION_CODES.LOLLIPOP)//这骚操作我给满分... - public LoopView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { - super(context, attrs, defStyleAttr, defStyleRes); - initView(context, attrs); - } - - private void initView(Context context, AttributeSet attrs) { -// ... - } -} \ No newline at end of file diff --git a/android/MultiTableHelper.java b/android/MultiTableHelper.java deleted file mode 100644 index 3cdf354e85cfa43e5ad19fb652eb8dff6f8207c1..0000000000000000000000000000000000000000 --- a/android/MultiTableHelper.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.vellnice.guidelamp.sqlite; - -import android.content.Context; -import android.database.sqlite.SQLiteDatabase; -import android.database.sqlite.SQLiteDatabase.CursorFactory; -import android.database.sqlite.SQLiteOpenHelper; - - -public class MultiTableHelper extends SQLiteOpenHelper { - - // ...... - // 无关代码省略 - - @Override - public void onCreate(SQLiteDatabase db) { - if (db != null) { - if (tableNames != null && sqls != null) { - for (int i = 0; i < tableNames.length; i++) { - db.execSQL("create table if not exists " + tableNames[i] + sqls[i]); - } - } - } - } - - // 数据库一旦升级就把所有数据表删除重新创建 - // 以下注释是原开发者的注释,他很清楚自己在干嘛... - - // 版本更新 - // 用于升级数据库,当Version 变动了,就会调用onUpgrade方法 - @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { - if (db != null) { - if (tableNames != null) { - // 如果表存在就删除 - for (int i = 0; i < tableNames.length; i++) { - db.execSQL("drop table if exists" + tableNames[i]); - } - // 重新初始化 - onCreate(db); - } - } - } - - -} diff --git a/android/NumUtils.java b/android/NumUtils.java deleted file mode 100644 index 5e5183eeea07cf0fddd221dad9be054d07896cbd..0000000000000000000000000000000000000000 --- a/android/NumUtils.java +++ /dev/null @@ -1,12 +0,0 @@ -public class NumUtils{ - //5的倍数,只要位数是0,5就可以 - public static boolean is5PCount(Integer number) { - char lastChar = String.valueOf(number).charAt(String.valueOf(number).length() - 1); - - if (lastChar == '5' || lastChar == '0') { - return true; - } - - return false; - } -} diff --git a/android/ProccessingResponseResult.java b/android/ProccessingResponseResult.java deleted file mode 100644 index 3fd4b7962c254f88ee2fd4b3a9a7d2d6aff62a67..0000000000000000000000000000000000000000 --- a/android/ProccessingResponseResult.java +++ /dev/null @@ -1,17 +0,0 @@ -import java.util.ArrayList; -import java.util.List; - -public class ProccessingResponseResult { - - private List dataSouce = new ArrayList<>(); - - private void processingResponseResult(List result){ - - for (int i = 0; i < result.size(); i++) { - dataSouce.add(result.get(i)); - } - - /*处理网络请求后解析的数据,存在于N个文件,😂*/ - - } -} \ No newline at end of file diff --git a/android/SettingActivity.java b/android/SettingActivity.java deleted file mode 100644 index 9dca7c820ac2c05c070c9e2725ef3e66d3f40c11..0000000000000000000000000000000000000000 --- a/android/SettingActivity.java +++ /dev/null @@ -1,20 +0,0 @@ -public class SettingActivity extends androidx.appcompat.app.AppCompatActivity { - @Override - protected void onCreate(@androidx.annotation.Nullable android.os.Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - clearMemory(); - - } - - // 清理垃圾 - private void clearMemory() { - try { - // 经理说加一个延时效果,时间5秒,让甲方给钱后期便于优化 - Thread.sleep(5000); - android.widget.Toast.makeText(SettingActivity.this, "清理完成!", Toast.LENGTH_SHORT).show(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } -} \ No newline at end of file diff --git a/c#/.keep b/c#/.keep deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/c#/AboutList.cs b/c#/AboutList.cs deleted file mode 100644 index ecc8f1dd7ba74e0408c9d5020a2dffebadd06a14..0000000000000000000000000000000000000000 --- a/c#/AboutList.cs +++ /dev/null @@ -1,21 +0,0 @@ - -using System.Collections.Generic; -using System.Linq; - -namespace Microsoft.Fawvw.HR.Platform.Api.Controllers -{ - public class AboutList - { - /// - /// 判断list是否为空 - /// - public void ChargeList() - { - var list = new List();//正常是请求一个service返回一个list - if (list != null && list.Count > 0) //直接使用list.Any()即可 - { - //继续下面的代码逻辑处理…… - } - } - } -} \ No newline at end of file diff --git a/c#/DeviceManagaController.cs b/c#/DeviceManagaController.cs deleted file mode 100644 index 3ea9c97a42d18a5cf246e99505df8295870af1a4..0000000000000000000000000000000000000000 --- a/c#/DeviceManagaController.cs +++ /dev/null @@ -1,21 +0,0 @@ -// 省略以上代码,只看最搞笑的部分 - -public string DeleteDiviceType(List list) -{ - using lims_hnContext dbContext = new lims_hnContext(); - - dbContext.Set().UpdateRange(list); - dbContext.SaveChanges(); - - return "true"; -} - -// 函数调用 -var data = DeleteDiviceType(list); -var requle = true; -if (data != "true") -{ - requle = false; -} - -return requle; \ No newline at end of file diff --git a/c#/ListInstall.cs b/c#/ListInstall.cs deleted file mode 100644 index d2705dc2b994345e8579552c1d30bbcd68fdcc76..0000000000000000000000000000000000000000 --- a/c#/ListInstall.cs +++ /dev/null @@ -1,17 +0,0 @@ - -using System.Collections.Generic; -using System.Linq; - -namespace Microsoft.Fawvw.HR.Platform.Api.Controllers -{ - public class ListInstall - { - /// - /// ʦһдһList>ʼ2 ˼ڤһд - /// - public ListInstall() - { - List> list = new List>(new List[2].Select(p => new List())); - } - } -} \ No newline at end of file diff --git a/c#/LogUtils.cs b/c#/LogUtils.cs deleted file mode 100644 index 0389eadc5688c9a7754ff732129ef83fcec1b403..0000000000000000000000000000000000000000 --- a/c#/LogUtils.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; - -namespace Grab -{ - public class LogUtils - { - /// - /// 本地log - /// - /// - /// - public static void WriteLog(String log, String type = "info") - { - try - { - string path = AppDomain.CurrentDomain.BaseDirectory + "/log/"; - DirectoryInfo info = new DirectoryInfo(path); - if (!info.Exists) { - info.Create(); - } - StreamWriter sw; - FileInfo fi = new FileInfo(path + type + "_" + DateTime.Now.ToString("yyyyMMdd") + ".log"); - if (!fi.Exists) { - sw = fi.CreateText(); - } else { - sw = File.AppendText(fi.FullName); - } - sw.WriteLine("================" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "================"); - sw.WriteLine(log); - sw.Close(); - sw.Dispose(); - } - catch (Exception e) - { - } - } - - } -} diff --git a/c#/NullPointExceptionValidate b/c#/NullPointExceptionValidate deleted file mode 100644 index 758542a7dead8e5fb8f2f4fb7b93cb2ab5f133f6..0000000000000000000000000000000000000000 --- a/c#/NullPointExceptionValidate +++ /dev/null @@ -1,39 +0,0 @@ -using System; - -namespace TestEnum -{ - internal class Program - { - //这段代码是从项目中提取出来的,来自于团队中一个西南交大的女硕士之手 - //这位女硕士队友喜欢怼天怼地对空气,经常写一些价值千万的代码 - - static void Main(string[] args) - { - UserBusiness userBusiness = new UserBusiness(); - User user = userBusiness.GetUserById(1); - if (user == null)//嗯,非空判断,挺有心的 - { - //咦?TMD,有非空判断的心,没有非空判断的脑,你这价值千万的代码,合着你判断了个寂寞啊? - //写代码前,请确保脑子和手是连上了的 - Console.WriteLine($"用户名为{user.Name}的用户不存在。"); - } - } - } - - class User - { - private int Id { get; set; } - public string Name { get; set; } - public string Password { get; set; } - public string Email { get; set; } - } - - class UserBusiness - { - public User GetUserById (int id) - { - User user=null;//从数据库取数据 - return user; - } - } -} diff --git a/c#/SleepSort.cs b/c#/SleepSort.cs deleted file mode 100644 index f80400f741ceaef01f8efaff0ef889bd2bbb7bd2..0000000000000000000000000000000000000000 --- a/c#/SleepSort.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace E { - class Program { - static void Main (string[] args) { - - var numArray = new int[] { 5, 2, 9, 1 }; - - var sortThreads = new List (); - - foreach (var item in numArray) { - var newThread = new Thread ((data) => { - Thread.Sleep (item * 1000); - Console.WriteLine (item); - }); - sortThreads.Add (newThread); - } - - foreach (var item in sortThreads) { - item.Start (); - } - - Console.ReadKey (); - } - - } -} \ No newline at end of file diff --git a/c#/StringHas.cs b/c#/StringHas.cs deleted file mode 100644 index f745f0ccfedb3c5632542cc739f688b11e472dd8..0000000000000000000000000000000000000000 --- a/c#/StringHas.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; - -namespace C_Sharp -{ - public class StringHas - { - - /// - /// 错误判断 - /// - /// - /// - private bool StringHasF(string str) - { - if (str==null&&str=="") - { - return false; - } - return true; - } - /// - /// 正确的判断 - /// - /// - /// - private bool StringHasT(string str) - { - return string.IsNullOrEmpty(str); - } - - } -} \ No newline at end of file diff --git a/c#/UpdateBug.cs b/c#/UpdateBug.cs deleted file mode 100644 index d4a878047433b554526aba6eb22b0e7bd10736c7..0000000000000000000000000000000000000000 --- a/c#/UpdateBug.cs +++ /dev/null @@ -1,16 +0,0 @@ -try -{ - if(args.IsNull()) - { - return "参数不能为空"; - } - if(args.Id <= 0) - { - return "Id不能为空"; - } - var info = _people.Get(args.Id); - if(info != null) - { - info.Id = args.Id; // 更新人员Id也更新了 - } -} \ No newline at end of file diff --git a/c#/Util.cs b/c#/Util.cs deleted file mode 100644 index 02fba65b7a16c79904761a6e1817ba4b1bdd175b..0000000000000000000000000000000000000000 --- a/c#/Util.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -namespace test -{ - public class Util - { - /// - /// 返回值加三元运算符值 - /// 好像没什么不对 -_-! - /// - /// - /// - /// - public static int GetValue(int inputValue, int type) - { - return inputValue + type == 1 ? 1 : 2; - } - } -} diff --git a/c#/WhichOne.cs b/c#/WhichOne.cs deleted file mode 100644 index ac332a308166b2f33280b358e575bd8b986d0dd1..0000000000000000000000000000000000000000 --- a/c#/WhichOne.cs +++ /dev/null @@ -1,12 +0,0 @@ -public class WhichOne -{ - public static void Guess() - { - var isMe = isMe(5); - } - - public static int isMe(int nums) - { - return nums != 0 ? nums > 0 && nums < 10 ? 1 : nums >= 10 ? 2 : 3 : 0; - } -} \ No newline at end of file diff --git a/c#/foreach.cs b/c#/foreach.cs deleted file mode 100644 index e99338b62e82628fa44c558116370de0065ab0fa..0000000000000000000000000000000000000000 --- a/c#/foreach.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; - -namespace TestForeach -{ - internal class Program - { - //上次摘录了 我们队伍中8年工作经验的、怼天怼地怼空气的西南交大女硕士的非空校验的代码。 - //再来看一段她老人家的大手笔,绝对也是千万级价值的代码 - static void Main(string[] args) - { - DataDao dao = new DataDao();//假设是数据层 - List datas = dao.GetDatas();//从数据库获取数据 - - DataTable table = new DataTable();//这个table已经有一万多条数据了,数据结构和 Data 类一样 - - - List listRows = new List(); - - - //目的:检查table中是否存在 datas的数据,如果没有就加入,如果有就跳过 - - - //价值千万的魔鬼循环来了 - foreach (Data data in datas) - { - foreach (DataRow row in table.Rows) - { - int id = Convert.ToInt32(row[0]); - int count = datas.Where(p => p.Id == id).Count();//注意这一句 - if (count == 0) - { - //我的内心:哟,还不错,不愧是8年工作经验的女硕士, - // 还知道这里不能直接 table.Rows.Add(new object[] { data.Id, data.Filed1, data.Filed2, data.Filed3 }); - // 知道这么干会报错。 - object[] newRow = new object[] { data.Id, data.Filed1, data.Filed2, data.Filed3 }; - listRows.Add(newRow); - } - } - } - - - //再把判定为不存在的数据加到 DataTable中。 - foreach (object[] row in listRows) - { - table.Rows.Add(row); - } - //最后导出到报表 就忽略了。 - - - //测试组的同事说:xxx硕士,你这个功能怎么导出数据要十几分钟啊。 - //女硕士说:没法儿解决,这已经是最快的方式了。(真他妈自信) - //组长受不了了,让我给女硕士处理。 - //我一看,说:你西南交大的教授这么教你写这么辣眼睛的循环的? - // 先不说你这个屎一样的循环,外层循环遍历十几万次,二层循环又要遍历几万次,三层循环又要遍历十几万次。 - //女硕士怼我:什么三层循环啊?我只用了两层。 - //我怒了:你他妈 datas.Where(p => p.Id == id).Count() 这不是循环是什么鬼。 - //女硕士:那就一句代码,怎么就循环了。(好一个“就一句代码,怎么就循环了”) - //我私聊组长:组长,我无能为力,要么让她自己倒腾,要么让她闭嘴。 - //组长:那我让她闭嘴,你改。 - } - } - - class Data - { - public int Id { get; set; } - public string Filed1 { get; set; } - public string Filed2 { get; set; } - public string Filed3 { get; set; } - } - - //数据层 - class DataDao - { - public List GetDatas() - { - //从数据库获取数据 - return new List(); - } - } -} diff --git "a/c#/for\345\276\252\347\216\257\351\230\262\345\276\241\346\200\247\347\274\226\347\250\213.cs" "b/c#/for\345\276\252\347\216\257\351\230\262\345\276\241\346\200\247\347\274\226\347\250\213.cs" deleted file mode 100644 index f5276c170a426005f669e187869c29018eb96b39..0000000000000000000000000000000000000000 --- "a/c#/for\345\276\252\347\216\257\351\230\262\345\276\241\346\200\247\347\274\226\347\250\213.cs" +++ /dev/null @@ -1,29 +0,0 @@ -代码片段 -经过一定简化 -class Obj{ - public int total{get;set;} //total就是rows的行数 - public List rows{get;set;}=new List(); -} -…… -其中某函数中: -Obj obj=new Obj(); //演示,简化过 - -//……obj初始化…… -//通过ORM从数据库中拿数据 - -int have_i=0; -int count=obj.rows.total; -for (int i = 0; i < count; i++) -{ - if (i >= obj.rows.Length) - { - break; - } - if(obj.rows[i]!=null /*&& 其他条件*/){ - have_i++; - //……一些操作…… - } -} -设置总数量的函数(have_i); - -//防御性编程,我直呼内行 \ No newline at end of file diff --git "a/c#/\346\227\266\346\227\266\345\275\251\345\274\200\345\245\226.cs" "b/c#/\346\227\266\346\227\266\345\275\251\345\274\200\345\245\226.cs" deleted file mode 100644 index 53ddc3be975f36172abe047775a7d6379c5e4c63..0000000000000000000000000000000000000000 --- "a/c#/\346\227\266\346\227\266\345\275\251\345\274\200\345\245\226.cs" +++ /dev/null @@ -1,475 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using Lottery.Data; -using System.IO; -using System.Web; -using System.Web.Caching; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Xml; -using EntityFramework.Extensions; -using System.Globalization; -using System.Threading; -using Lottery.Model; -using CountUserDTO = Lottery.WebToService.CountUserDTO; -using CountSendDTO = Lottery.WebToService.CountSendDTO; - -/* -14年的时候写的,看名字就碉堡 -*/ -namespace Lottery.Service -{ - public class 配置文件实体 - { - public long 期号代码 - { - get; - set; - } - public DateTime 开奖日期 - { - get; - set; - } - } - public class 时时彩开奖 - { - - /// - /// 延迟60秒去获取 - /// - public static readonly Int32 延迟读取秒数 = 20; - - public const String 时时彩客户端标识 = "67BE4FB5-9ED4-41B0-90EF-A6FE52E1ECE2"; - public const Int32 时时彩客户端ID = 1; - public System.Timers.Timer 定时器 = new System.Timers.Timer(); - - public static DateTime 当天日期 = DateTime.Today; - public static List<配置文件实体> 开奖列表 = null; - public 时时彩开奖() - { - 开奖列表 = 读取配置文件生产日期(当天日期); - if (开奖列表 == null || 开奖列表.Count == 0) - { - 当天日期 = 当天日期.AddDays(1); - 开奖列表 = 读取配置文件生产日期(当天日期); - } - 定时器.Elapsed += new System.Timers.ElapsedEventHandler(时间到达执行的事件); - 定时器.Enabled = true; - var 下次执行间隔 = (开奖列表[0].开奖日期 - DateTime.Now).TotalMilliseconds; - 定时器.Interval = 下次执行间隔; - 定时器.Start(); - } - - void 时间到达执行的事件(object sender, System.Timers.ElapsedEventArgs e) - { - Console.WriteLine(延迟读取秒数 + "秒后,准备读取开奖信息" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); - Action 异步执行 = (期号) => - { - Thread.Sleep(延迟读取秒数 * 1000); - 读取开奖号和修改数据库开奖信息(期号); - }; - 异步执行.BeginInvoke(开奖列表[0].期号代码, null, null); - lock (开奖列表) - { - 定时器.Stop(); - 开奖列表.RemoveAt(0); - if (开奖列表 == null || 开奖列表.Count == 0) - { - 当天日期 = 当天日期.AddDays(1); - 开奖列表 = 读取配置文件生产日期(当天日期); - } - MyTcpChannel.NoticNextOpenTime(时时彩客户端ID, new NextOpenTime - { - OpenTime = 开奖列表[0].开奖日期, - Expect = 开奖列表[0].期号代码 - }); - var 下次执行间隔 = (开奖列表[0].开奖日期 - DateTime.Now).TotalMilliseconds; - 定时器.Interval = 下次执行间隔; - 定时器.Start(); - } - } - public void 读取开奖号和修改数据库开奖信息(long 期号, Int32 计数 = 0) - { - var 开奖信息 = 开奖获取.读取开奖信息(期号); - if (开奖信息 == null) - { - 计数++; - Console.WriteLine("第{0}次读取,未读取到开奖信息{1}秒后重新读取", 计数, (5 * 计数)); - Thread.Sleep(5000 * 计数); - if (计数 > 10) - { - return; - } - Action 异步执行 = (_期号, _计数) => - { - 读取开奖号和修改数据库开奖信息(_期号, _计数); - }; - 异步执行.BeginInvoke(期号, 计数, null, null); - //TODO:延迟读取 - return; - } - else - { - 修改数据库开奖信息(开奖信息); - - } - } - - public void 修改数据库开奖信息(开奖实体 开奖信息, DateTime? 日期 = null, Boolean Notice = true) - { - if (!日期.HasValue) - { - 日期 = DateTime.Today; - } - var 开奖数组 = 开奖信息.开奖号.Split(','); - var 开奖用户信息 = new List(); - var 当前彩种ID = 0; - using (var 数据库实体 = new LotteryDbContext()) - { - - 数据库实体.Transaction(() => - { - var 彩票类型 = 数据库实体.LotteryTypes.Where(x => x.LotteryTypeGUID.Equals(时时彩客户端标识)).FirstOrDefault(); - var 玩法 = 数据库实体.PlayTypes.Where(x => x.LotteryTypeID.Equals(彩票类型.LotteryTypeID)); - var 数据库当前期号实体 = 数据库实体.LotteryInfos.Where(x => x.LotteryInfoCode.Equals(开奖信息.期号代码)).FirstOrDefault(); - - 当前彩种ID = 彩票类型.LotteryTypeID; - - if (数据库当前期号实体 == null) - { - 数据库当前期号实体 = new LotteryInfos - { - LotteryInfoCode = 开奖信息.期号代码, - LotteryInfoDate = 日期.Value, - LotteryInfoOpenCode = 开奖信息.开奖号, - LotteryInfoOpenTime = null, - LotteryTypeID = 彩票类型.LotteryTypeID - }; - 数据库实体.LotteryInfos.AddObject(数据库当前期号实体); - 数据库实体.SaveChanges(); - } - foreach (var 玩法详细 in 玩法) - { - var 当前玩法开奖号 = new StringBuilder(); - - for (int i = 玩法详细.PlayTypeStartIdx; i <= 玩法详细.PlayTypeEndIdx; i++) - { - 当前玩法开奖号.Append(开奖数组[i]); - } - 当前玩法开奖号.Append("|"); - var 开奖字符串 = 当前玩法开奖号.ToString(); - var 猜中的用户ID = 数据库实体.UserLotterys.Where(x => - x.UserLotteryExpect.Equals(开奖信息.期号代码) - && x.LotteryTypeID.Equals(彩票类型.LotteryTypeID) - && x.Content.Contains(开奖字符串) - && x.PlayTypeID.Equals(玩法详细.PlayTypeID) - && x.IsWin.Equals(0)).Select(x => x.UserId).ToList(); - - if (猜中的用户ID.Count > 0) - { - 数据库实体.UserLotterys.Where(x => - x.UserLotteryExpect.Equals(开奖信息.期号代码) - && x.LotteryTypeID.Equals(彩票类型.LotteryTypeID) - && 猜中的用户ID.Contains(x.UserId) - && x.PlayTypeID.Equals(玩法详细.PlayTypeID) - && x.IsWin.Equals(0)).Update(x => new UserLotterys - { - IsWin = 1 - }); - 数据库实体.SaveChanges(); - foreach (var 用户ID in 猜中的用户ID) - { - 开奖用户信息.Add(new CountUserDTO - { - playTypeId = 玩法详细.PlayTypeID, - playTypeName = 玩法详细.PlayTypeName, - IsWin = 1, - userId = 用户ID, - }); - var 用户统计信息 = 数据库实体.UserCounts.Where(x => - x.userId.Equals(用户ID) - && x.LotteryTypeId.Equals(彩票类型.LotteryTypeID) - && x.PlayTypeId.Equals(玩法详细.PlayTypeID)).FirstOrDefault(); - 用户统计信息.WinNum += 1; - 用户统计信息.MathHistory += "1"; - - } - 数据库实体.SaveChanges(); - } - //.UserRules.Where(x => 猜中的用户ID.Contains(x.UserID)).Update(x => new UserRules - //{ - // UserWinNum = x.UserWinNum + 1 - //}); - - - var 未猜中的用户ID = 数据库实体.UserLotterys.Where(x => - x.UserLotteryExpect.Equals(开奖信息.期号代码) - && x.IsWin.Equals(0) - && x.LotteryTypeID.Equals(彩票类型.LotteryTypeID) - && !x.Content.Contains(开奖字符串) - && x.PlayTypeID.Equals(玩法详细.PlayTypeID)).Select(x => x.UserId).ToList(); - - if (未猜中的用户ID.Count > 0) - { - 数据库实体.UserLotterys.Where(x => - x.UserLotteryExpect.Equals(开奖信息.期号代码) - && 未猜中的用户ID.Contains(x.UserId) - && x.LotteryTypeID.Equals(彩票类型.LotteryTypeID) - && x.PlayTypeID.Equals(玩法详细.PlayTypeID) - && x.IsWin.Equals(0)).Update(x => new UserLotterys - { - IsWin = 2 - }); - 数据库实体.SaveChanges(); - foreach (var 用户ID in 未猜中的用户ID) - { - 开奖用户信息.Add(new CountUserDTO - { - playTypeId = 玩法详细.PlayTypeID, - playTypeName = 玩法详细.PlayTypeName, - IsWin = 2, - userId = 用户ID, - }); - var 用户统计信息 = 数据库实体.UserCounts.Where(x => - x.userId.Equals(用户ID) - && x.LotteryTypeId.Equals(彩票类型.LotteryTypeID) - && x.PlayTypeId.Equals(玩法详细.PlayTypeID)).FirstOrDefault(); - 用户统计信息.MathHistory += "2"; - } - 数据库实体.SaveChanges(); - } - } - }); - } - if (Notice) - { - var 通知开奖实体 = new LotteyInfo - { - Expect = 开奖信息.期号代码, - OpenCode = 开奖信息.开奖号 - }; - var 中奖数据 = from p in 开奖用户信息 - group p by p.userId into g - select new - { - Key = g.Key, - Value = g.Select(x => new CountSendDTO - { - IsWin = x.IsWin, - playTypeId = x.playTypeId, - playTypeName = x.playTypeName - }) - - }; - var 传输参数 = 中奖数据.ToDictionary(x => x.Key, x => x.Value.ToList()); - - MyTcpChannel.OpenLotteyNotic(当前彩种ID, 通知开奖实体, 传输参数); - } - } - public static List<配置文件实体> 读取配置文件生产日期(DateTime? 要生产的日期 = null) - { - var 当天开奖列表 = new List<配置文件实体>(); - var 生产日期 = DateTime.Today; - if (要生产的日期.HasValue) - { - 生产日期 = 要生产的日期.Value; - } - var 数据库实体 = new LotteryDbContext(); - var 彩票类型 = 数据库实体.LotteryTypes.Where(x => x.LotteryTypeGUID.Equals(时时彩客户端标识)).FirstOrDefault(); - using (var 文件流 = new StreamReader(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OTConfig/CQSSC.txt"))) - { - var 一行数据 = 文件流.ReadLine(); - while (!String.IsNullOrEmpty(一行数据)) - { - var 临时变量数组 = 一行数据.Split('|'); - - if (临时变量数组[0] == "120") - { - 当天开奖列表.Add(new 配置文件实体 - { - 期号代码 = Convert.ToInt64(生产日期.AddDays(-1).ToString(彩票类型.LotteryCodeFormat) + 临时变量数组[0]), - 开奖日期 = Convert.ToDateTime(String.Format("{0} {1}:00", 生产日期.ToString("yyyy-MM-dd"), 临时变量数组[1])) - }); - } - else - { - 当天开奖列表.Add(new 配置文件实体 - { - 期号代码 = Convert.ToInt64(生产日期.ToString(彩票类型.LotteryCodeFormat) + 临时变量数组[0]), - 开奖日期 = Convert.ToDateTime(String.Format("{0} {1}:00", 生产日期.ToString("yyyy-MM-dd"), 临时变量数组[1])) - }); - } - 一行数据 = 文件流.ReadLine(); - } - } - 当天开奖列表 = 当天开奖列表.Where(x => x.开奖日期 >= DateTime.Now).ToList(); - return 当天开奖列表; - } - public void 期号补遗() - { - 当天补遗(); - 遗漏开奖(); - new 历史比赛记录().重新计算(); - #region 历史补遗 - var 数据库实体 = new LotteryDbContext(); - var 彩票类型 = 数据库实体.LotteryTypes.Where(x => x.LotteryTypeGUID.Equals(时时彩客户端标识)).Select(x => new { x.LotteryTypeID, x.LotteryMaxNum }).FirstOrDefault(); - var 查询结果 = from 开奖信息 in 数据库实体.LotteryInfos - group 开奖信息 by 开奖信息.LotteryInfoDate into 新集合 - where 新集合.Count() < 100 && - 新集合.Key != DateTime.Today - select new - { - 日期 = 新集合.Key - }; - foreach (var 当天日期 in 查询结果) - { - var 开奖查询结果 = 开奖获取.时时彩500W网站获取(当天日期.日期); - var 数据库当前期号实体 = 数据库实体.LotteryInfos.Where(x => x.LotteryInfoDate == 当天日期.日期 && x.LotteryTypeID.Equals(彩票类型.LotteryTypeID)).Select(x => x.LotteryInfoCode).ToList(); - 开奖查询结果 = 开奖查询结果.Where(x => !数据库当前期号实体.Contains(x.期号代码)).ToList(); - foreach (var 开奖信息 in 开奖查询结果) - { - - 修改数据库开奖信息(开奖信息, 当天日期.日期, false); - - } - } - #endregion 历史补遗 - } - public void 当天补遗() - { - - var 当天日期 = DateTime.Today; - var 开奖查询结果 = 开奖获取.时时彩500W网站获取(当天日期); - var 数据库实体 = new LotteryDbContext(); - var 彩票类型 = 数据库实体.LotteryTypes.Where(x => x.LotteryTypeGUID.Equals(时时彩客户端标识)).Select(x => new { x.LotteryTypeID, x.LotteryMaxNum }).FirstOrDefault(); - var 数据库当前期号实体 = 数据库实体.LotteryInfos.Where(x => x.LotteryInfoDate == 当天日期 && x.LotteryTypeID.Equals(彩票类型.LotteryTypeID)).Select(x => x.LotteryInfoCode).ToList(); - 开奖查询结果 = 开奖查询结果.Where(x => !数据库当前期号实体.Contains(x.期号代码)).ToList(); - foreach (var 开奖信息 in 开奖查询结果) - { - - 修改数据库开奖信息(开奖信息, 当天日期, false); - - } - } - - public void 遗漏开奖() - { - var 数据库实体 = new LotteryDbContext(); - var 彩票类型 = 数据库实体.LotteryTypes.Where(x => x.LotteryTypeGUID.Equals(时时彩客户端标识)).Select(x => new { x.LotteryTypeID, x.LotteryMaxNum }).FirstOrDefault(); - var 查询期号 = from p in 数据库实体.UserLotterys.Where(x => x.LotteryTypeID.Equals(彩票类型.LotteryTypeID) - && x.IsWin == 0) - group p by p.UserLotteryExpect into 新集合 - select 新集合.Key; - foreach (var 期号 in 查询期号) - { - - var 开奖信息 = 开奖获取.读取开奖信息(期号); - if (开奖信息 != null) - { - var 查询时间 = DateTime.ParseExact(期号.ToString().Substring(0, 8), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); - 修改数据库开奖信息(开奖信息, 查询时间, false); - } - } - } - } - public class 开奖实体 - { - public long 期号代码 - { - get; - set; - } - public String 开奖号 - { - get; - set; - } - } - public class 开奖获取 - { - public static 开奖实体 时时彩官网获取(long 期号代码) - { - try - { - var Http访问客户端 = new HttpClient(); - Http访问客户端.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*")); - Http访问客户端.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("zh-cn")); - Http访问客户端.DefaultRequestHeaders.Referrer = new Uri("http://www.cqcp.net/game/ssc/"); - - Http访问客户端.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)"); - var Post提交内容 = new FormUrlEncodedContent(new Dictionary - { - {"idMode","3002"}, - {"iCount","1"} - }); - var Http请求信息 = new HttpRequestMessage(HttpMethod.Post, "http://www.cqcp.net/ajaxhttp/game/getopennumber.aspx"); - Http请求信息.Content = Post提交内容; - Http请求信息.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); - var 返回的HTML = Http访问客户端.SendAsync(Http请求信息).Result.Content.ReadAsStringAsync().Result; - HtmlAgilityPack.HtmlDocument HTML文档解析类 = new HtmlAgilityPack.HtmlDocument(); - HTML文档解析类.LoadHtml(返回的HTML); - var 查找ul标签 = HTML文档解析类.DocumentNode.SelectNodes("ul"); - if (查找ul标签 != null && 查找ul标签.Count > 1) - { - for (var 循环变量i = 1; 循环变量i < 查找ul标签.Count; 循环变量i++) - { - var 当前ul标签 = 查找ul标签[循环变量i]; - var 期号 = Convert.ToInt64("20" + 当前ul标签.SelectSingleNode("li[1]").InnerText); - var 开奖号 = 当前ul标签.SelectSingleNode("li[2]").InnerText.Replace("-", ","); - if (期号 == 期号代码) - { - return new 开奖实体 - { - 期号代码 = 期号, - 开奖号 = 开奖号.Replace("-", ","), - - }; - } - } - } - } - catch { } - return null; - } - - public static 开奖实体 读取开奖信息(long 期号代码) - { - var 返回数据 = 时时彩官网获取(期号代码); - if (返回数据 == null) - { - var 查询时间 = DateTime.ParseExact(期号代码.ToString().Substring(0, 8), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); - var 查询当日的开奖信息 = 时时彩500W网站获取(查询时间); - 返回数据 = 查询当日的开奖信息.Where(x => x.期号代码.Equals(期号代码)).FirstOrDefault(); - } - return 返回数据; - } - public static List<开奖实体> 时时彩500W网站获取(DateTime? 查询时间 = null) - { - if (查询时间 == null) - { - 查询时间 = DateTime.Now; - } - var requestUri = String.Format("http://kaijiang.500.com/static/public/ssc/xml/qihaoxml/{0}.xml", 查询时间.Value.ToString("yyyyMMdd")); - XmlDocument XML文档解析 = new XmlDocument(); - XML文档解析.Load(requestUri); - var 所有开奖节点 = XML文档解析.SelectNodes("xml/row"); - - var 返回数据 = new List<开奖实体>(); - foreach (var 节点明细 in 所有开奖节点) - { - var 节点元素 = (XmlElement)节点明细; - var 开奖实例 = new 开奖实体 - { - 期号代码 = Convert.ToInt64(节点元素.GetAttribute("expect")), - 开奖号 = 节点元素.GetAttribute("opencode"), - }; - 返回数据.Add(开奖实例); - } - return 返回数据; - - } - } -} diff --git a/cpp/asyncsignalsafe.md b/cpp/asyncsignalsafe.md deleted file mode 100644 index 09579328dcd0c0a103d2f932b0bb930a4afe127d..0000000000000000000000000000000000000000 --- a/cpp/asyncsignalsafe.md +++ /dev/null @@ -1,19 +0,0 @@ -# 异步信号安全 BUG. - -在信号回调函数中需要注意异步信号安全问题,不能使用任何非异步信号安全的函数,因为在信号回调函数中,其他代码可能会持有锁,在信号回调函数中再次调用锁导致死锁。此 BUG 曾在 SSHD 中出现,git-srv 也曾出现过此问题。POSIX 系统中,很多软件也没有处理好异步信号安全。 - -```c++ -#include - -void handler(int sig){ - printf ("child exit !\n" ); -} - - -int main(){ - signal(SIGCHLD,handler); - // TODO oter code - return 0; -} - -``` diff --git a/cpp/popennotsafety.md b/cpp/popennotsafety.md deleted file mode 100644 index 90dc279e71ef0e32c186d552489842dd55a93aac..0000000000000000000000000000000000000000 --- a/cpp/popennotsafety.md +++ /dev/null @@ -1,40 +0,0 @@ -# popen 安全注入问题 - -在使用 `popen` 进行进程间通信时,尤其需要注意命令行注入的风险,而 popen 在 Python, Ruby 中均存在,而 Gitee 也大量使用了 popen 读取 git 特定命令输出,因此需要注意。 - -产生此问题的根源在于 popen 或者 system 实际上是通过 `sh -c "$COMMAND"` 这样的方式启动程序,因此,命令行可能会被 `shell` 解析成多个命令并执行。而 OpenSSH 的 sshd 也是使用 `sh -c` 这样的方式执行。 - -解决方案:应当使用 spawn + pipe (fork-exec-pipe) 这样的方式进行进程间通信。 - -```c++ -/// -#include -#include -#include -#define MAXLINE 4096 -int runsomecli(const char *cli) { - auto file = popen(cli, "r"); - if (file == nullptr) { - fprintf(stderr, "%s\n", strerror(errno)); - return 1; - } - char line[MAXLINE]; - for (;;) { - if (fgets(line, MAXLINE, file) == nullptr) { - break; - } - fputs(line, stderr); - } - pclose(file); - return 0; -} - -int main() { - runsomecli( - "touch /tmp/test.log;ls -l /tmp/test.log;/bin/echo -e \"\x1b[31mSafety " - "Warning\x1b[0m\";rm -rf " - "/tmp/test.log;ls -l /tmp/test.log"); - return 0; -} - -``` diff --git a/cpp/safeformat.md b/cpp/safeformat.md deleted file mode 100644 index 8b6b1b99cbb6be25e57732302686468295b7af77..0000000000000000000000000000000000000000 --- a/cpp/safeformat.md +++ /dev/null @@ -1,14 +0,0 @@ -# C 风格格式化类型不匹配 - -在 C,C++ 语言中,`printf` 是被使用很广泛的函数,但也是一些 BUG 的来源,通常如果使用默认的 `printf` `snprintf` `fprintf`,如果格式字符串中期望得到的数据类型与参数类型不一致,编译器通常会报告警告,但如果像下面一样自己封装这样的函数,稍不注意,则容易出现类型不匹配而导致 BUG。 - -```c++ -int my_vsnprintf(char *buf,size_t buflen,const char *fmt,va_list ap); -int my_snprintf(char *buf,size_t buflen, const char *fmt,...); -``` - -此问题的根源在于在使用 `va_arg` 展开参数时,只能根据占位符获得参数类型,参数类型如果不匹配,则可能溢出,或者预期得到字符串,但参数类型却不是 C-Style 字符串,则可能会导致程序崩溃。 - -如果要封装这样的变参函数,应该使用编译器 `attribute` 特性描述函数,或者使用 C++ 变参模板取代 C 风格的变参函数。 - -在 git-srv 中, `wink::StrFormat` 便使用变参模板实现了类型安全的格式化。 diff --git a/cpp/unsigned_intergers.md b/cpp/unsigned_intergers.md deleted file mode 100644 index 5f6ce672b1f82d020bc694319cd4d97e4875ea4c..0000000000000000000000000000000000000000 --- a/cpp/unsigned_intergers.md +++ /dev/null @@ -1,36 +0,0 @@ -## unsigned integers in c/cpp -先看一段代码 -```c++ -/// 通常情况下以下遍历容器代码不会有什么问题 -for (int i = 0; i < container.size(); i++) -{ -/// 但是,编译器会提示提示警告:原因是size()返回的类型是size_t -/// 而size_t 定义为 unsigned integers 的别名 -} - -/// 因此,一般的做法是这样 -/// 将 i 定义为 size_t 类型 -for (size_t i = 0; i < container.size(); i++) -{ -/// 至此没有什么问题 -} - -/// 但是,当反向遍历容器的时候 -/// 代码可能是这样 -for (size_t i = container.size()-1; i >= 0; i--) -{ -/// 而这样,代码就出问题了——死循环 -/// 原因是 integers overflow,这里是 整数下溢 -/// 而,unsigned integers在ISO标准中保证不会下溢(通过modulo wrapping) -/// 所以,编译器会保证 i >= 0 永远成立 -/// modulo wrapping可以简单理解为 i 到0之后,再重新更新为 intergers 表示的最大值(UINT_MAX/ULONG_MAX) -} - -/// 所以,反向遍历容器时 -/// 应该这样 -for (int i = container.size()-1; i >= 0; i--) {} -/// 或者这样 -for (auto it = container.end() -1; it != container.begin(); it--) {} -/// 亦或者这样 -for (auto it = container.rbegin(); it != container.rend(); it++) {} -``` \ No newline at end of file diff --git a/cpp/vector_bad_init.md b/cpp/vector_bad_init.md deleted file mode 100644 index b5786e961cfbd96cb3bbe029e343daf2a95a8a5a..0000000000000000000000000000000000000000 --- a/cpp/vector_bad_init.md +++ /dev/null @@ -1,182 +0,0 @@ -# vector 不正确的初始化 - -```c++ -#ifndef _TOKENIZE_CMDLINE_HPP -#define _TOKENIZE_CMDLINE_HPP -#include -#include -#include -#include -#include -#include - -namespace bela { -namespace cmdline_internal { -constexpr inline bool isWhitespace(char ch) { - return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; -} - -inline std::string_view StripTrailingWhitespace(std::string_view str) { - auto it = std::find_if_not(str.rbegin(), str.rend(), isWhitespace); - return str.substr(0, str.rend() - it); -} - -constexpr inline bool isWhitespaceOrNull(char ch) { - return isWhitespace(ch) || ch == '\0'; -} -constexpr inline bool isQuote(char ch) { return ch == '\"' || ch == '\''; } - -inline void vector_fill_n(std::vector &Token, size_t n, char ch) { - for (size_t i = 0; i < n; i++) { - Token.push_back(ch); - } -} -inline size_t parseBackslash(std::string_view Src, size_t I, - std::vector &Token) { - auto E = Src.size(); - int BackslashCount = 0; - // Skip the backslashes. - do { - ++I; - ++BackslashCount; - } while (I != E && Src[I] == '\\'); - - bool FollowedByDoubleQuote = (I != E && Src[I] == '"'); - if (FollowedByDoubleQuote) { - vector_fill_n(Token, BackslashCount / 2, '\\'); - if (BackslashCount % 2 == 0) { - return I - 1; - } - Token.push_back('"'); - return I; - } - vector_fill_n(Token, BackslashCount, '\\'); - return I - 1; -} -} // namespace cmdline_internal - -class Tokenizer { -public: - Tokenizer() = default; - Tokenizer(const Tokenizer &) = delete; - Tokenizer &operator=(const Tokenizer &) = delete; - ~Tokenizer() { - for (auto a : saver_) { - if (a != nullptr) { - free(a); - } - } - } - bool Tokenize(std::string_view cmdline); - const char *const *Argv() const { return saver_.data(); }; - char **Argv() { return saver_.data(); } - size_t Argc() const { return saver_.size(); } - -private: - std::vector saver_; - void SaveArg(const char *data, size_t len); - void SaveArg(const std::vector &token) { - SaveArg(token.data(), token.size()); - } -}; - -void Tokenizer::SaveArg(const std::vector token(128); *data, size_t len) { - auto size = len + 1; - auto mem = static_cast(malloc(size * sizeof(char))); - if (mem != nullptr) { - memcpy(mem, data, len * sizeof(char)); - mem[len] = '\0'; - saver_.push_back(mem); - } -} - -inline bool Tokenizer::Tokenize(std::string_view src) { - src = cmdline_internal::StripTrailingWhitespace(src); - if (src.empty()) { - return false; - } - std::vector token(128); - // This is a small state machine to consume characters until it reaches the - // end of the source string. - enum { INIT, UNQUOTED, QUOTED } State = INIT; - for (size_t I = 0, E = src.size(); I != E; ++I) { - auto C = src[I]; - - // INIT state indicates that the current input index is at the start of - // the string or between tokens. - if (State == INIT) { - if (cmdline_internal::isWhitespaceOrNull(C)) { - continue; - } - if (C == '"') { - State = QUOTED; - continue; - } - if (C == '\\') { - I = cmdline_internal::parseBackslash(src, I, token); - State = UNQUOTED; - continue; - } - token.push_back(C); - State = UNQUOTED; - continue; - } - - // UNQUOTED state means that it's reading a token not quoted by double - // quotes. - if (State == UNQUOTED) { - // Whitespace means the end of the token. - if (cmdline_internal::isWhitespaceOrNull(C)) { - SaveArg(token); - token.clear(); - State = INIT; - continue; - } - if (C == '"') { - State = QUOTED; - continue; - } - if (C == '\\') { - I = cmdline_internal::parseBackslash(src, I, token); - continue; - } - token.push_back(C); - continue; - } - - // QUOTED state means that it's reading a token quoted by double quotes. - if (State == QUOTED) { - if (C == '"') { - if (I < (E - 1) && src[I + 1] == '"') { - // Consecutive double-quotes inside a quoted string implies one - // double-quote. - token.push_back('"'); - I = I + 1; - continue; - } - State = UNQUOTED; - continue; - } - if (C == '\\') { - I = cmdline_internal::parseBackslash(src, I, token); - continue; - } - token.push_back(C); - } - } - SaveArg(token); - return true; -} - -} // namespace bela - -#endif - -``` - -此函数将命令行拆分成命令行数组,但使用了错误的初始化函数,`std::vector token(128);` 此行将会使用 '\0' 填充数组,所以第一个命令行为空,正确的方案如下: - -```c++ -std::vector token; -token.reserve(128); //allocate 128 -``` diff --git "a/e-language/\347\272\277\347\250\213\351\230\273\345\241\236.e" "b/e-language/\347\272\277\347\250\213\351\230\273\345\241\236.e" deleted file mode 100644 index 90a71c8504e7d4d5780f2ae0a68f1fddba2dd711..0000000000000000000000000000000000000000 Binary files "a/e-language/\347\272\277\347\250\213\351\230\273\345\241\236.e" and /dev/null differ diff --git a/golang/ai.go b/golang/ai.go index 93075d520a144c76390a9a6d63b515a360908690..5fbdd6c9e5318685bba69d08bc9d2a5e8eef1b62 100644 --- a/golang/ai.go +++ b/golang/ai.go @@ -1,22 +1,25 @@ -package main - -import ( - "bufio" - "fmt" - "os" - "strings" -) - -// AI 核心代码, 估值3个亿 -func main() { - scanner := bufio.NewScanner(os.Stdin) - - for scanner.Scan() { - input := scanner.Text() - input = strings.ReplaceAll(input, "吗", "") - input = strings.ReplaceAll(input, "?", "!") - input = strings.ReplaceAll(input, "?", "!") - fmt.Println(input) - fmt.Println() - } -} +package main + +import ( + "bufio" + "fmt" + "os" + "strings" + "time" +) + +// AI 核心代码, 估值3个亿 +func main() { + scanner := bufio.NewScanner(os.Stdin) + + for scanner.Scan() { + input := scanner.Text() + input = strings.ReplaceAll(input, "吗", "") + input = strings.ReplaceAll(input, "?", "!") + input = strings.ReplaceAll(input, "?", "!") + // ai立即回答出来显得太假 + time.Sleep(3 * time.Second) + fmt.Println(input) + fmt.Println() + } +} diff --git a/golang/array_param.go b/golang/array_param.go deleted file mode 100644 index d0d796317138f398c9d41173cc428291b3ecfccc..0000000000000000000000000000000000000000 --- a/golang/array_param.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import "fmt" - - -//from https://books.studygolang.com/advanced-go-programming-book/appendix/appendix-a-trap.html -func main() { - x := [3]int{1, 2, 3} - - //在函数调用参数中,数组是值传递,无法通过修改数组类型的参数返回结果。 - func(arr [3]int) { - arr[0] = 7 - fmt.Println(arr) - }(x) - - fmt.Println(x) -} \ No newline at end of file diff --git a/golang/for_trap.go b/golang/for_trap.go deleted file mode 100644 index 204908e9322f642b7eeb682b7a60fe7a1ff9a914..0000000000000000000000000000000000000000 --- a/golang/for_trap.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "fmt" - "time" -) - -func main() { - for i := 0; i <= 10; i++ { - go func() { - fmt.Println(i) //实际闭包中i是地址 匿名函数和中和外边共享的是同一个变量 - }() - - /*正确方法 - //方法一 - finalI := i //复制一个变量副本 (java写法) - go func() { - fmt.Println(finalI) - }() - - //方法二 - go func(paramI int) { //作为参数传递到匿名函数中(实际也是等同于使用副本) - fmt.Println(paramI) - }(i) - - */ - - } - - time.Sleep(5 * time.Second) -} diff --git a/golang/fuck_ slice b/golang/fuck_ slice deleted file mode 100644 index dac469eb6deb893a5d5070e6b6cdbdff2792fbf7..0000000000000000000000000000000000000000 --- a/golang/fuck_ slice +++ /dev/null @@ -1,60 +0,0 @@ -package main - -import ( - "fmt" -) - -func main() { - TestA() - TestB() - TestC() -} - -func TestC() { - //切片的 copy 函数 - //当使用 copy 函数复制切片时,要确保被复制的长度和容量都小于等于目标切片的长度和容量 - arr1 := []int{1, 2, 3, 4, 5} - var arr2 = make([]int, 2) - // 复制切片时,确保被复制的长度和容量都小于等于目标切片的长度和容量 - copy(arr2, arr1[1:3]) - fmt.Println(arr2) // 输出:[2 3] - // 以下代码会丢失内容 - copy(arr2, arr1[1:]) - fmt.Println(arr2) // 输出:[2 3] - // 以下代码会丢失内容 - var arr3 []int - copy(arr3, arr1[1:]) - fmt.Println(arr3) // 输出:[] -} -func TestB() { - //切片的迭代和修改 - //使用 range 迭代切片时,最好不要修改切片的长度,它的循环次数不会因为修改而改变。 - //如果需要修改切片的长度,建议使用传统的 for 循环实现。 - var arr = []int{1, 2, 3, 4, 5} - for i, i2 := range arr { - fmt.Println(i, i2,arr[i]) - arr = append(arr, i+10) - } - fmt.Println(arr) - //for i, i2 := range arr { - // fmt.Println(i, i2,arr[i]) - // arr = []int{1} - //} -} -func TestA() { - //切片的底层数组共享 - //切片是一种引用数据类型,它本身并不持有数据,而是引用底层数组中的一部分数据。如果创建新的切片时不小心引用到了原有切片的底层数组,那么对其中任意一个切片做修改都可能会影响到其他的切片。 - arr := []int{1, 2, 3, 4, 5} - slice := arr[1:3] - fmt.Println(arr) // 输出:[1 2 3 4 5] - fmt.Println(slice) // 输出:[2 3] - arr[2] = 42 - fmt.Println(arr) // 输出:[1 2 42 4 5] - fmt.Println(slice) // 输出:[2 42] - TestAA(slice) - fmt.Println(slice) // 输出:[52 42] -} - -func TestAA(arr []int) { - arr[0] = 52 -} diff --git a/golang/fuck_defer.go b/golang/fuck_defer.go deleted file mode 100644 index 335e45cb67a34d3844fda31bccd79c7a977f3e18..0000000000000000000000000000000000000000 --- a/golang/fuck_defer.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import "fmt" - -var s = 0 -func main() { - for i := 0; i < 5; i++ { - //正经人不会吧defer写在循环中 - defer printS() - s = i - } -} - -func printS() { - fmt.Println(s) -} - diff --git a/golang/fuck_java.go b/golang/fuck_java.go deleted file mode 100644 index 41b3c380c6f1e8be52570e3e03165eef6b14022b..0000000000000000000000000000000000000000 --- a/golang/fuck_java.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import "fmt" - -// 傻逼 Java 程序员会如下,把代码写成Java格式的异常 - -func main() { - defer Catch() - Foo() -} - -func Foo() { - Exception("fuck java") -} - -func Exception(msg string) { - panic(msg) -} - -func Catch() { - r := recover() - fmt.Println(r) -} diff --git a/golang/fuck_recover.go b/golang/fuck_recover.go deleted file mode 100644 index 4ecc7cbd08761f363a493795a6533cba24b85e0f..0000000000000000000000000000000000000000 --- a/golang/fuck_recover.go +++ /dev/null @@ -1,20 +0,0 @@ -package main - -import "fmt" - -var m = 0 - -func main() { - //defer 方法中的参数方法会被执行时候县渲染。 这个时候返回的是0 而不是1 - defer doSome(getValue()) - m = 1 - fmt.Println("end") -} - -func doSome(value int) { - fmt.Println(value) -} - -func getValue() int { - return m -} diff --git a/golang/json_demo.go b/golang/json_demo.go deleted file mode 100644 index 68ff35f8e131a1a075e73a0103bf6590aded371b..0000000000000000000000000000000000000000 --- a/golang/json_demo.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import ( - "encoding/json" - "fmt" -) - -func main() { - - newMap := make(map[string]interface{}) - - jsonStr := `{ - "name":"ansj", - "age":12 - }` - - //golang json 序列化只支持指针对象 - _ = json.Unmarshal([]byte(jsonStr), newMap) - - fmt.Println(newMap) -} \ No newline at end of file diff --git a/golang/panic_defer.go b/golang/panic_defer.go deleted file mode 100644 index f2dc3e2d48570ee5d51cea9fffdf64c6811527d2..0000000000000000000000000000000000000000 --- a/golang/panic_defer.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import "fmt" - -type Slice []int - -func NewSlice() Slice { - return make(Slice, 0) -} - -func (s *Slice) Add(elem int) *Slice { - *s = append(*s, elem) - fmt.Print(elem) - return s -} - -func main() { - s := NewSlice() - defer s.Add(1).Add(2) // 这里先执行前面的Add,最后一个不执行,函数结束后再执行最后一个Add 执行结果 132 - // defer s.Add(1).Add(2).Add(4) // 这里执行的结果是 1234 - s.Add(3) -} diff --git a/golang/parse_time.go b/golang/parse_time.go deleted file mode 100644 index 5c1c7410bc5ec9734b84beb19fa6506073fa51b4..0000000000000000000000000000000000000000 --- a/golang/parse_time.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import "fmt" -import "time" - -func main(){ - tm := parseTime("2021-02-04") - fmt.Println(tm) -} - -func parseTime(timeStr string) time.Time { - tm, _ := time.Parse(timeStr, "2006-01-02") - return tm -} diff --git a/golang/waht_err.go b/golang/waht_err.go deleted file mode 100644 index 6d59461b1bcabd18f5c44205ec3063c82ee5a451..0000000000000000000000000000000000000000 --- a/golang/waht_err.go +++ /dev/null @@ -1,21 +0,0 @@ -package main - -import "fmt" - -//参考 https://books.studygolang.com/advanced-go-programming-book/appendix/appendix-a-trap.html -func main() { - fmt.Println(errMehthod()) -} - -func errMehthod() (err error) { - if err := Bar(); err != nil { - //在局部作用域中,命名的返回值内同名的局部变量屏蔽: - //这里运行时会报错。编译不报错 - return - } - return -} - -func Bar() error { - return fmt.Errorf("fuck hongshu") -} diff --git a/java/.DS_Store b/java/.DS_Store deleted file mode 100644 index 5008ddfcf53c02e82d7eee2e57c38e5672ef89f6..0000000000000000000000000000000000000000 Binary files a/java/.DS_Store and /dev/null differ diff --git a/java/AFilter b/java/AFilter deleted file mode 100644 index 1dadf6a3d7e1d4d7eed40c1662677d40dddb78bf..0000000000000000000000000000000000000000 --- a/java/AFilter +++ /dev/null @@ -1,19 +0,0 @@ -import java.util.Scanner; - -/** - * 一行代码就可以搞定的,非要写的花里胡哨。 - * - * @author z77z - * - */ -public class AFilter { - private boolean isEligible(int age){ - boolean result; - if(age > 18){ - result = true; - }else{ - result = false; - } - return result; - } -} \ No newline at end of file diff --git a/java/AICustomerServiceSystem.java b/java/AICustomerServiceSystem.java deleted file mode 100644 index 37d38e484d288f160e38c598e77f0a187ce89feb..0000000000000000000000000000000000000000 --- a/java/AICustomerServiceSystem.java +++ /dev/null @@ -1,38 +0,0 @@ -import java.util.Scanner; - -/** - * @Description 智能AI客服服务系统 - * @Author saltfish - * @Date 15:35 2019/6/22 - */ -public class AICustomerServiceSystem { - - - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - String str; - // 待优化 - while (true) { - str = sc.next(); - // 测试环境,正式环境从数据库中获取 - str = str.replace("吗", ""); - str = str.replace("?", "!"); - str = str.replace("?", "!"); - str = str.replace("不", "很"); - str = str.replace("你们", "我们"); - str = str.replace("有", "没有"); - - System.out.println(str); - } - - // test -// 在吗? -// 在! -// 你好! -// 你好! -// 产品有问题啊 -// 产品没有问题啊 -// 你们的服务态度不好 -// 我们的服务态度很好 - } -} \ No newline at end of file diff --git a/java/AJoke b/java/AJoke deleted file mode 100644 index 148572a953303f3d07d0b9a5fd4dd51699c34e17..0000000000000000000000000000000000000000 --- a/java/AJoke +++ /dev/null @@ -1,15 +0,0 @@ -package lalala; - - -public class AJoke { - - - public static void main(String[] args) { - int a = args[0]; - if(a>3 && a<5){ - log.info("hahahahah"); - } - //为什么不用4。。。。哈哈哈哈 - } - -} \ No newline at end of file diff --git a/java/ALineCode.java b/java/ALineCode.java deleted file mode 100644 index 964342dda61f4c94126c8d1cc4de5d2138317461..0000000000000000000000000000000000000000 --- a/java/ALineCode.java +++ /dev/null @@ -1,21 +0,0 @@ -package spring; - - -public class B { - - - public static void main(String[] args) { - System.out.println(isTwoPower(15)); - } - - /** - * 看不懂的代码 - * @param n - * @return - */ - public static boolean isTwo(int n){ - // 其实是用于判断入参是否为2的幂次方 - return (n & n-1) == 0; - } - -} diff --git a/java/ASmellyLongCode b/java/ASmellyLongCode deleted file mode 100644 index fe2239437b0c2f6f83b11984732dc2e8bd6d65ab..0000000000000000000000000000000000000000 --- a/java/ASmellyLongCode +++ /dev/null @@ -1,786 +0,0 @@ - - - -// 省略业务逻辑代码 - -for (TConfigSensor tConfigSensor : configSensorList) { - String fieldName = tConfigSensor.getField(); - int modbusType = tConfigSensor.getModbusType(); - int address = tConfigSensor.getAddress(); - int analyticalMethod = tConfigSensor.getAnalyticalMothod(); - String val = AnalysisUtils.serialDataAnalysis(msg, modbusType, address, analyticalMethod); - - Integer result = Integer.parseInt(val) * (-1); - log.debug("报文解析后的数据: {} --- {}", tConfigSensor.getFieldDescribe(), result); - - if (fieldName.equals(TransformerPartialDischargeGraphType.a0Val.getInfo())) { - transformerPartialDischargeGraph.setA0Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b0Val.getInfo())) { - transformerPartialDischargeGraph.setB0Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c0Val.getInfo())) { - transformerPartialDischargeGraph.setC0Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d0Val.getInfo())) { - transformerPartialDischargeGraph.setD0Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a1Val.getInfo())) { - transformerPartialDischargeGraph.setA1Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b1Val.getInfo())) { - transformerPartialDischargeGraph.setB1Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c1Val.getInfo())) { - transformerPartialDischargeGraph.setC1Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d1Val.getInfo())) { - transformerPartialDischargeGraph.setD1Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a2Val.getInfo())) { - transformerPartialDischargeGraph.setA2Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b2Val.getInfo())) { - transformerPartialDischargeGraph.setB2Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c2Val.getInfo())) { - transformerPartialDischargeGraph.setC2Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d2Val.getInfo())) { - transformerPartialDischargeGraph.setD2Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a3Val.getInfo())) { - transformerPartialDischargeGraph.setA3Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b3Val.getInfo())) { - transformerPartialDischargeGraph.setB3Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c3Val.getInfo())) { - transformerPartialDischargeGraph.setC3Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d3Val.getInfo())) { - transformerPartialDischargeGraph.setD3Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a4Val.getInfo())) { - transformerPartialDischargeGraph.setA4Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b4Val.getInfo())) { - transformerPartialDischargeGraph.setB4Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c4Val.getInfo())) { - transformerPartialDischargeGraph.setC4Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d4Val.getInfo())) { - transformerPartialDischargeGraph.setD4Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a5Val.getInfo())) { - transformerPartialDischargeGraph.setA5Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b5Val.getInfo())) { - transformerPartialDischargeGraph.setB5Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c5Val.getInfo())) { - transformerPartialDischargeGraph.setC5Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d5Val.getInfo())) { - transformerPartialDischargeGraph.setD5Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a6Val.getInfo())) { - transformerPartialDischargeGraph.setA6Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b6Val.getInfo())) { - transformerPartialDischargeGraph.setB6Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c6Val.getInfo())) { - transformerPartialDischargeGraph.setC6Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d6Val.getInfo())) { - transformerPartialDischargeGraph.setD6Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a7Val.getInfo())) { - transformerPartialDischargeGraph.setA7Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b7Val.getInfo())) { - transformerPartialDischargeGraph.setB7Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c7Val.getInfo())) { - transformerPartialDischargeGraph.setC7Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d7Val.getInfo())) { - transformerPartialDischargeGraph.setD7Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a8Val.getInfo())) { - transformerPartialDischargeGraph.setA8Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b8Val.getInfo())) { - transformerPartialDischargeGraph.setB8Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c8Val.getInfo())) { - transformerPartialDischargeGraph.setC8Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d8Val.getInfo())) { - transformerPartialDischargeGraph.setD8Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a9Val.getInfo())) { - transformerPartialDischargeGraph.setA9Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b9Val.getInfo())) { - transformerPartialDischargeGraph.setB9Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c9Val.getInfo())) { - transformerPartialDischargeGraph.setC9Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d9Val.getInfo())) { - transformerPartialDischargeGraph.setD9Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a10Val.getInfo())) { - transformerPartialDischargeGraph.setA10Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b10Val.getInfo())) { - transformerPartialDischargeGraph.setB10Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c10Val.getInfo())) { - transformerPartialDischargeGraph.setC10Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d10Val.getInfo())) { - transformerPartialDischargeGraph.setD10Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a11Val.getInfo())) { - transformerPartialDischargeGraph.setA11Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b11Val.getInfo())) { - transformerPartialDischargeGraph.setB11Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c11Val.getInfo())) { - transformerPartialDischargeGraph.setC11Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d11Val.getInfo())) { - transformerPartialDischargeGraph.setD11Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a12Val.getInfo())) { - transformerPartialDischargeGraph.setA12Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b12Val.getInfo())) { - transformerPartialDischargeGraph.setB12Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c12Val.getInfo())) { - transformerPartialDischargeGraph.setC12Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d12Val.getInfo())) { - transformerPartialDischargeGraph.setD12Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a13Val.getInfo())) { - transformerPartialDischargeGraph.setA13Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b13Val.getInfo())) { - transformerPartialDischargeGraph.setB13Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c13Val.getInfo())) { - transformerPartialDischargeGraph.setC13Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d13Val.getInfo())) { - transformerPartialDischargeGraph.setD13Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a14Val.getInfo())) { - transformerPartialDischargeGraph.setA14Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b14Val.getInfo())) { - transformerPartialDischargeGraph.setB14Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c14Val.getInfo())) { - transformerPartialDischargeGraph.setC14Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d14Val.getInfo())) { - transformerPartialDischargeGraph.setD14Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a15Val.getInfo())) { - transformerPartialDischargeGraph.setA15Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b15Val.getInfo())) { - transformerPartialDischargeGraph.setB15Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c15Val.getInfo())) { - transformerPartialDischargeGraph.setC15Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d15Val.getInfo())) { - transformerPartialDischargeGraph.setD15Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a16Val.getInfo())) { - transformerPartialDischargeGraph.setA16Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b16Val.getInfo())) { - transformerPartialDischargeGraph.setB16Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c16Val.getInfo())) { - transformerPartialDischargeGraph.setC16Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d16Val.getInfo())) { - transformerPartialDischargeGraph.setD16Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a17Val.getInfo())) { - transformerPartialDischargeGraph.setA17Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b17Val.getInfo())) { - transformerPartialDischargeGraph.setB17Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c17Val.getInfo())) { - transformerPartialDischargeGraph.setC17Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d17Val.getInfo())) { - transformerPartialDischargeGraph.setD17Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a18Val.getInfo())) { - transformerPartialDischargeGraph.setA18Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b18Val.getInfo())) { - transformerPartialDischargeGraph.setB18Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c18Val.getInfo())) { - transformerPartialDischargeGraph.setC18Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d18Val.getInfo())) { - transformerPartialDischargeGraph.setD18Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a19Val.getInfo())) { - transformerPartialDischargeGraph.setA19Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b19Val.getInfo())) { - transformerPartialDischargeGraph.setB19Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c19Val.getInfo())) { - transformerPartialDischargeGraph.setC19Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d19Val.getInfo())) { - transformerPartialDischargeGraph.setD19Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a20Val.getInfo())) { - transformerPartialDischargeGraph.setA20Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b20Val.getInfo())) { - transformerPartialDischargeGraph.setB20Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c20Val.getInfo())) { - transformerPartialDischargeGraph.setC20Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d20Val.getInfo())) { - transformerPartialDischargeGraph.setD20Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a21Val.getInfo())) { - transformerPartialDischargeGraph.setA21Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b21Val.getInfo())) { - transformerPartialDischargeGraph.setB21Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c21Val.getInfo())) { - transformerPartialDischargeGraph.setC21Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d21Val.getInfo())) { - transformerPartialDischargeGraph.setD21Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a22Val.getInfo())) { - transformerPartialDischargeGraph.setA22Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b22Val.getInfo())) { - transformerPartialDischargeGraph.setB22Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c22Val.getInfo())) { - transformerPartialDischargeGraph.setC22Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d22Val.getInfo())) { - transformerPartialDischargeGraph.setD22Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a23Val.getInfo())) { - transformerPartialDischargeGraph.setA23Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b23Val.getInfo())) { - transformerPartialDischargeGraph.setB23Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c23Val.getInfo())) { - transformerPartialDischargeGraph.setC23Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d23Val.getInfo())) { - transformerPartialDischargeGraph.setD23Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a24Val.getInfo())) { - transformerPartialDischargeGraph.setA24Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b24Val.getInfo())) { - transformerPartialDischargeGraph.setB24Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c24Val.getInfo())) { - transformerPartialDischargeGraph.setC24Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d24Val.getInfo())) { - transformerPartialDischargeGraph.setD24Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a25Val.getInfo())) { - transformerPartialDischargeGraph.setA25Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b25Val.getInfo())) { - transformerPartialDischargeGraph.setB25Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c25Val.getInfo())) { - transformerPartialDischargeGraph.setC25Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d25Val.getInfo())) { - transformerPartialDischargeGraph.setD25Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a26Val.getInfo())) { - transformerPartialDischargeGraph.setA26Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b26Val.getInfo())) { - transformerPartialDischargeGraph.setB26Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c26Val.getInfo())) { - transformerPartialDischargeGraph.setC26Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d26Val.getInfo())) { - transformerPartialDischargeGraph.setD26Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a27Val.getInfo())) { - transformerPartialDischargeGraph.setA27Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b27Val.getInfo())) { - transformerPartialDischargeGraph.setB27Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c27Val.getInfo())) { - transformerPartialDischargeGraph.setC27Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d27Val.getInfo())) { - transformerPartialDischargeGraph.setD27Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a28Val.getInfo())) { - transformerPartialDischargeGraph.setA28Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b28Val.getInfo())) { - transformerPartialDischargeGraph.setB28Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c28Val.getInfo())) { - transformerPartialDischargeGraph.setC28Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d28Val.getInfo())) { - transformerPartialDischargeGraph.setD28Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a29Val.getInfo())) { - transformerPartialDischargeGraph.setA29Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b29Val.getInfo())) { - transformerPartialDischargeGraph.setB29Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c29Val.getInfo())) { - transformerPartialDischargeGraph.setC29Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d29Val.getInfo())) { - transformerPartialDischargeGraph.setD29Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a30Val.getInfo())) { - transformerPartialDischargeGraph.setA30Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b30Val.getInfo())) { - transformerPartialDischargeGraph.setB30Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c30Val.getInfo())) { - transformerPartialDischargeGraph.setC30Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d30Val.getInfo())) { - transformerPartialDischargeGraph.setD30Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a31Val.getInfo())) { - transformerPartialDischargeGraph.setA31Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b31Val.getInfo())) { - transformerPartialDischargeGraph.setB31Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c31Val.getInfo())) { - transformerPartialDischargeGraph.setC31Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d31Val.getInfo())) { - transformerPartialDischargeGraph.setD31Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a32Val.getInfo())) { - transformerPartialDischargeGraph.setA32Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b32Val.getInfo())) { - transformerPartialDischargeGraph.setB32Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c32Val.getInfo())) { - transformerPartialDischargeGraph.setC32Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d32Val.getInfo())) { - transformerPartialDischargeGraph.setD32Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a33Val.getInfo())) { - transformerPartialDischargeGraph.setA33Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b33Val.getInfo())) { - transformerPartialDischargeGraph.setB33Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c33Val.getInfo())) { - transformerPartialDischargeGraph.setC33Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d33Val.getInfo())) { - transformerPartialDischargeGraph.setD33Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a34Val.getInfo())) { - transformerPartialDischargeGraph.setA34Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b34Val.getInfo())) { - transformerPartialDischargeGraph.setB34Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c34Val.getInfo())) { - transformerPartialDischargeGraph.setC34Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d34Val.getInfo())) { - transformerPartialDischargeGraph.setD34Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a35Val.getInfo())) { - transformerPartialDischargeGraph.setA35Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b35Val.getInfo())) { - transformerPartialDischargeGraph.setB35Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c35Val.getInfo())) { - transformerPartialDischargeGraph.setC35Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d35Val.getInfo())) { - transformerPartialDischargeGraph.setD35Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a36Val.getInfo())) { - transformerPartialDischargeGraph.setA36Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b36Val.getInfo())) { - transformerPartialDischargeGraph.setB36Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c36Val.getInfo())) { - transformerPartialDischargeGraph.setC36Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d36Val.getInfo())) { - transformerPartialDischargeGraph.setD36Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a37Val.getInfo())) { - transformerPartialDischargeGraph.setA37Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b37Val.getInfo())) { - transformerPartialDischargeGraph.setB37Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c37Val.getInfo())) { - transformerPartialDischargeGraph.setC37Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d37Val.getInfo())) { - transformerPartialDischargeGraph.setD37Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a38Val.getInfo())) { - transformerPartialDischargeGraph.setA38Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b38Val.getInfo())) { - transformerPartialDischargeGraph.setB38Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c38Val.getInfo())) { - transformerPartialDischargeGraph.setC38Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d38Val.getInfo())) { - transformerPartialDischargeGraph.setD38Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a39Val.getInfo())) { - transformerPartialDischargeGraph.setA39Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b39Val.getInfo())) { - transformerPartialDischargeGraph.setB39Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c39Val.getInfo())) { - transformerPartialDischargeGraph.setC39Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d39Val.getInfo())) { - transformerPartialDischargeGraph.setD39Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a40Val.getInfo())) { - transformerPartialDischargeGraph.setA40Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b40Val.getInfo())) { - transformerPartialDischargeGraph.setB40Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c40Val.getInfo())) { - transformerPartialDischargeGraph.setC40Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d40Val.getInfo())) { - transformerPartialDischargeGraph.setD40Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a41Val.getInfo())) { - transformerPartialDischargeGraph.setA41Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b41Val.getInfo())) { - transformerPartialDischargeGraph.setB41Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c41Val.getInfo())) { - transformerPartialDischargeGraph.setC41Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d41Val.getInfo())) { - transformerPartialDischargeGraph.setD41Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a42Val.getInfo())) { - transformerPartialDischargeGraph.setA42Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b42Val.getInfo())) { - transformerPartialDischargeGraph.setB42Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c42Val.getInfo())) { - transformerPartialDischargeGraph.setC42Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d42Val.getInfo())) { - transformerPartialDischargeGraph.setD42Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a43Val.getInfo())) { - transformerPartialDischargeGraph.setA43Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b43Val.getInfo())) { - transformerPartialDischargeGraph.setB43Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c43Val.getInfo())) { - transformerPartialDischargeGraph.setC43Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d43Val.getInfo())) { - transformerPartialDischargeGraph.setD43Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a44Val.getInfo())) { - transformerPartialDischargeGraph.setA44Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b44Val.getInfo())) { - transformerPartialDischargeGraph.setB44Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c44Val.getInfo())) { - transformerPartialDischargeGraph.setC44Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d44Val.getInfo())) { - transformerPartialDischargeGraph.setD44Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a45Val.getInfo())) { - transformerPartialDischargeGraph.setA45Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b45Val.getInfo())) { - transformerPartialDischargeGraph.setB45Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c45Val.getInfo())) { - transformerPartialDischargeGraph.setC45Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d45Val.getInfo())) { - transformerPartialDischargeGraph.setD45Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a46Val.getInfo())) { - transformerPartialDischargeGraph.setA46Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b46Val.getInfo())) { - transformerPartialDischargeGraph.setB46Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c46Val.getInfo())) { - transformerPartialDischargeGraph.setC46Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d46Val.getInfo())) { - transformerPartialDischargeGraph.setD46Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a47Val.getInfo())) { - transformerPartialDischargeGraph.setA47Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b47Val.getInfo())) { - transformerPartialDischargeGraph.setB47Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c47Val.getInfo())) { - transformerPartialDischargeGraph.setC47Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d47Val.getInfo())) { - transformerPartialDischargeGraph.setD47Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a48Val.getInfo())) { - transformerPartialDischargeGraph.setA48Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b48Val.getInfo())) { - transformerPartialDischargeGraph.setB48Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c48Val.getInfo())) { - transformerPartialDischargeGraph.setC48Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d48Val.getInfo())) { - transformerPartialDischargeGraph.setD48Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a49Val.getInfo())) { - transformerPartialDischargeGraph.setA49Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b49Val.getInfo())) { - transformerPartialDischargeGraph.setB49Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c49Val.getInfo())) { - transformerPartialDischargeGraph.setC49Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d49Val.getInfo())) { - transformerPartialDischargeGraph.setD49Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a50Val.getInfo())) { - transformerPartialDischargeGraph.setA50Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b50Val.getInfo())) { - transformerPartialDischargeGraph.setB50Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c50Val.getInfo())) { - transformerPartialDischargeGraph.setC50Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d50Val.getInfo())) { - transformerPartialDischargeGraph.setD50Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a51Val.getInfo())) { - transformerPartialDischargeGraph.setA51Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b51Val.getInfo())) { - transformerPartialDischargeGraph.setB51Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c51Val.getInfo())) { - transformerPartialDischargeGraph.setC51Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d51Val.getInfo())) { - transformerPartialDischargeGraph.setD51Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a52Val.getInfo())) { - transformerPartialDischargeGraph.setA52Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b52Val.getInfo())) { - transformerPartialDischargeGraph.setB52Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c52Val.getInfo())) { - transformerPartialDischargeGraph.setC52Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d52Val.getInfo())) { - transformerPartialDischargeGraph.setD52Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a53Val.getInfo())) { - transformerPartialDischargeGraph.setA53Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b53Val.getInfo())) { - transformerPartialDischargeGraph.setB53Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c53Val.getInfo())) { - transformerPartialDischargeGraph.setC53Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d53Val.getInfo())) { - transformerPartialDischargeGraph.setD53Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a54Val.getInfo())) { - transformerPartialDischargeGraph.setA54Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b54Val.getInfo())) { - transformerPartialDischargeGraph.setB54Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c54Val.getInfo())) { - transformerPartialDischargeGraph.setC54Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d54Val.getInfo())) { - transformerPartialDischargeGraph.setD54Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a55Val.getInfo())) { - transformerPartialDischargeGraph.setA55Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b55Val.getInfo())) { - transformerPartialDischargeGraph.setB55Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c55Val.getInfo())) { - transformerPartialDischargeGraph.setC55Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d55Val.getInfo())) { - transformerPartialDischargeGraph.setD55Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a56Val.getInfo())) { - transformerPartialDischargeGraph.setA56Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b56Val.getInfo())) { - transformerPartialDischargeGraph.setB56Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c56Val.getInfo())) { - transformerPartialDischargeGraph.setC56Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d56Val.getInfo())) { - transformerPartialDischargeGraph.setD56Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a57Val.getInfo())) { - transformerPartialDischargeGraph.setA57Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b57Val.getInfo())) { - transformerPartialDischargeGraph.setB57Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c57Val.getInfo())) { - transformerPartialDischargeGraph.setC57Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d57Val.getInfo())) { - transformerPartialDischargeGraph.setD57Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a58Val.getInfo())) { - transformerPartialDischargeGraph.setA58Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b58Val.getInfo())) { - transformerPartialDischargeGraph.setB58Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c58Val.getInfo())) { - transformerPartialDischargeGraph.setC58Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d58Val.getInfo())) { - transformerPartialDischargeGraph.setD58Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a59Val.getInfo())) { - transformerPartialDischargeGraph.setA59Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b59Val.getInfo())) { - transformerPartialDischargeGraph.setB59Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c59Val.getInfo())) { - transformerPartialDischargeGraph.setC59Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d59Val.getInfo())) { - transformerPartialDischargeGraph.setD59Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a60Val.getInfo())) { - transformerPartialDischargeGraph.setA60Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b60Val.getInfo())) { - transformerPartialDischargeGraph.setB60Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c60Val.getInfo())) { - transformerPartialDischargeGraph.setC60Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d60Val.getInfo())) { - transformerPartialDischargeGraph.setD60Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a61Val.getInfo())) { - transformerPartialDischargeGraph.setA61Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b61Val.getInfo())) { - transformerPartialDischargeGraph.setB61Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c61Val.getInfo())) { - transformerPartialDischargeGraph.setC61Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d61Val.getInfo())) { - transformerPartialDischargeGraph.setD61Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a62Val.getInfo())) { - transformerPartialDischargeGraph.setA62Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b62Val.getInfo())) { - transformerPartialDischargeGraph.setB62Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c62Val.getInfo())) { - transformerPartialDischargeGraph.setC62Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d62Val.getInfo())) { - transformerPartialDischargeGraph.setD62Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.a63Val.getInfo())) { - transformerPartialDischargeGraph.setA63Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.b63Val.getInfo())) { - transformerPartialDischargeGraph.setB63Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.c63Val.getInfo())) { - transformerPartialDischargeGraph.setC63Val(result.doubleValue()); - } - if (fieldName.equals(TransformerPartialDischargeGraphType.d63Val.getInfo())) { - transformerPartialDischargeGraph.setD63Val(result.doubleValue()); - } - } - - EhCacheUtil.put(Constants.FOREVER_CACHE, String.format("gis:%s", id), transformerPartialDischargeGraph); \ No newline at end of file diff --git a/java/AddCode b/java/AddCode deleted file mode 100644 index 979bcf666b7a03359988f7c830b252bf145153e6..0000000000000000000000000000000000000000 --- a/java/AddCode +++ /dev/null @@ -1,8 +0,0 @@ -public class AddCode { - - public static void main(String[] args) { - - System.out.println(1 + 5 / 2 + 2 > 5); - //为什么会是false - } - } \ No newline at end of file diff --git a/java/AddOrUpdate.java b/java/AddOrUpdate.java deleted file mode 100644 index 60caaa68078a975b3e3fe38c0c976a9213e44949..0000000000000000000000000000000000000000 --- a/java/AddOrUpdate.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * [新增或修改功能,代码controller层和service层代码贴出来] - * @version 1.0.0 - */ -public class AddOrUpdate { - - public static void main(String[] args) { - // 这里是controller层 - if (id != null){ - // service在下面 - return eqbTemplateBaseService.updateTemplateBase(templateBaseName,projectBaseId,projectBaseName,status,code,id,realName); - }else{ - // service在下面 - return eqbTemplateBaseService.addTemplateBase(templateBaseName,projectBaseId,projectBaseName,status,code,realName); - } - } - - // 这里是service层 - public ApiResponse addTemplateBase(String templateBaseName, Integer projectBaseId, String projectBaseName ,Integer status, String code,String realName) { - AddTemplateBaseReq addTemplateBaseReq = new AddTemplateBaseReq(); - addTemplateBaseReq.setCode(code); - addTemplateBaseReq.setProjectBaseId(projectBaseId); - addTemplateBaseReq.setStatus(status); - addTemplateBaseReq.setTemplateBaseName(templateBaseName); - addTemplateBaseReq.setProjectBaseName(projectBaseName); - addTemplateBaseReq.setRealName(realName); - // 这里调另一个服务的接口 - return eqbTemplateBaseClient.addTemplateBase(addTemplateBaseReq); - } - - // 这里是service层 - public ApiResponse updateTemplateBase(String templateBaseName, Integer projectBaseId,String projectBaseName, Integer status, String code, Integer id,String realName) { - UpdateTemplateBaseReq updateTemplateBaseReq = new UpdateTemplateBaseReq(); - updateTemplateBaseReq.setCode(code); - updateTemplateBaseReq.setProjectBaseId(projectBaseId); - updateTemplateBaseReq.setStatus(status); - updateTemplateBaseReq.setTemplateBaseName(templateBaseName); - updateTemplateBaseReq.setId(id);// 就为了这个id,写了两套 - updateTemplateBaseReq.setProjectBaseName(projectBaseName); - updateTemplateBaseReq.setRealName(realName); - // 这里调另一个服务的接口 - return eqbTemplateBaseClient.updateTemplateBase(updateTemplateBaseReq); - } - - // 明明可以写成一个方法,这个兄弟倒好,整整写成了两套,后面eqbTemplateBaseClient相对应的两套还没有贴出来,那边才是真正的业务开始 - -} \ No newline at end of file diff --git a/java/AiMain.java b/java/AiMain.java deleted file mode 100644 index e0c90563e19c7eefb68b0c6a518bf8732a43c4db..0000000000000000000000000000000000000000 --- a/java/AiMain.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.wang; - -import java.util.Scanner; - -/** - * AI核心代码 价值1个亿~ - * - * @author z77z - * - */ -public class AiMain { - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - String str; - while (true) { - str = sc.next(); - str = str.replace("吗", ""); - str = str.replace("?", "!"); - str = str.replace("?", "!"); - System.out.println(str); - } - } -} \ No newline at end of file diff --git a/java/AnnualLeaveCalculation.java b/java/AnnualLeaveCalculation.java deleted file mode 100644 index 3be9478ad5c6d67c2ca850733e1613969ea6cbc4..0000000000000000000000000000000000000000 --- a/java/AnnualLeaveCalculation.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.wang; - -import java.util.Scanner; - -/** - * 年假计算,认识公司最牛逼的人 - * - * @author fans.fan - * - */ -public class AnnualLeaveCalculation { - - public int calculation(User user) { - if ("xxx".equal(user.getUsername())) { - return 100; - } else { - int year = DateUtil.daysBetween(new Date(), user.getHireDate()) / 365; - if(year == 0) { - return 5; - } else if(year > 1 && year <= 5) { - return 7 - } else if(year > 5 && year <= 10) { - return 9; - } else if(year > 10) { - return 10; - } - } - } - - class User{ - /** 用户名 */ - private String username; - /** 入职日期 */ - private Date hireDate; - } -} \ No newline at end of file diff --git a/java/Append.java b/java/Append.java deleted file mode 100644 index fd1f0f21da62f24b9c6d3a3a4db6a4a03a3e90f9..0000000000000000000000000000000000000000 --- a/java/Append.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Create Time 2019/5/24 - * StringBuffer追加 如痴如醉的写法 - * @author cailong - **/ -public class Append { - public static void main(String[] ares){ - - StringBuffer sb = new StringBuffer(); - //这里都能理解 - sb.append(""); - for (int i = 0; i < 10; i++) { - //为什么到这里就要这样写???既然都用StringBuffer了 (这里省略集合遍历用i代替 意思能懂就行) - sb.append("" + - ""+i+"" + - ""+i+"" + - ""+i+"" + - ""+i+"" + - ""+i+"" + - "sjzs" + - ""+i+"" + - ""); - } - sb.append(""); - System.out.println(sb.toString()); - } -} diff --git a/java/ArraySort.java b/java/ArraySort.java deleted file mode 100644 index 3ff97090daecb78322f79b3c1b9b8f70dd6fddaa..0000000000000000000000000000000000000000 --- a/java/ArraySort.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 刚写完的排序算法就被开除了 - * - * @author Tandy 2019/5/27 9:53 - */ -public class ArraySort implements Runnable { - - private int number; - - public ArraySort(int number) { - this.number = number; - } - - public static void main(String[] args) { - int[] numbers = new int[]{102, 338, 62, 9132, 580, 666}; - for (int number : numbers) { - new Thread(new ArraySort(number)).start(); - } - } - - @Override - public void run() { - try { - Thread.sleep(this.number); - System.out.println(this.number); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } -} diff --git a/java/AutoGetterAndSetter.java b/java/AutoGetterAndSetter.java deleted file mode 100644 index 8e0bdc6f4f878ad2843b048bae3c55942e05fc01..0000000000000000000000000000000000000000 --- a/java/AutoGetterAndSetter.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * boolean类型的字段 如果定义为is*** 自动代码出来的getter and setter 会去掉is - * - * @version 1.0 - * @date 2019/5/31 - */ -public class AutoGetterAndSetter { - - private String isMan; - - private Boolean isPerson; - - - /***以下是自动代码出来的getter and setter ***/ - public String getIsMan() { - return isMan; - } - - public void setIsMan(String isMan) { - this.isMan = isMan; - } - - public Boolean getPerson() { - return isPerson; - } - - public void setPerson(Boolean person) { - isPerson = person; - } -} diff --git a/java/BadCode.java b/java/BadCode.java deleted file mode 100644 index d86f3c28553a9f66beca7a8f332941547eb889cc..0000000000000000000000000000000000000000 --- a/java/BadCode.java +++ /dev/null @@ -1,29 +0,0 @@ - -/** - * 大神留步,帮我看个问题. - * @User: jspp@qq.com - * @Date: 2019/5/27 10:56 - * @Desc - * @Param - */ -public class BadCode { - - /** - * 计算总数 - */ - public void countDemo(){ - int num = 0; - for (int i=0;i<100;i++){ - num = num ++; - /** - * do something - */ - } - System.out.println(num); - } - /** - * 输出结果:num=0 - * 然后 我叫了个大神来我帮我分析下。囧 - */ - -} diff --git a/java/BadException.java b/java/BadException.java deleted file mode 100644 index f3a9b23339caf5836412cb253d7808396b81bf9b..0000000000000000000000000000000000000000 --- a/java/BadException.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 处理业务的异常 - * 居然有一堆静态异常,准备好了随时可以抛?? - * 错误码是字符串 - */ - -public class CommandException extends BaseException { - - private static final long serialVersionUID = -6354513454371927970L; - - public static CommandException PARAM_NULL= new CommandException("Command_assemble_01", "Parameter is Needed But Empty"); - public static CommandException DEVID_NULL = new CommandException("Command_assemble_02", "DevId Cannot Be Null"); - public static CommandException MDCODE_NULL = new CommandException("Command_assemble_03", "Model Code Cannot Be Empty"); - public static CommandException ORDER_NULL = new CommandException("Command_assemble_04", "Order Cannot Be Empty"); - public static CommandException TYPE_NULL = new CommandException("Command_assemble_05", "Upstream / Downstream Type Cannot Be Empty"); - public static CommandException MENUID_NULL = new CommandException("Command_assemble_06", "Menu Id Cannot Be Null"); - public static CommandException CTRLTYPE_NOT_RANGE= new CommandException("Command_assemble_07", "Ctrltype Cannot Be Recognized, Which is not in Range"); - public static CommandException CMD_NULL = new CommandException("Command_analyze_01", "CMD Cannot Be Null"); - public static CommandException PAYLOAD_NULL = new CommandException("Command_analyze_02", "Payload Cannot Be Null"); - public static CommandException FRAMEWORK_FAILED= new CommandException("Command_analyze_03", "Framework Failed to be Checked"); - public static CommandException CHECK_FAILED= new CommandException("Command_analyze_04", "Command Failed to be Checked"); - public static CommandException CONFIGURE_NOT_EXIST = new CommandException("Command_error_1001", "Configure is not Exist"); - public static CommandException REDIS_ERROR = new CommandException("Command_error_1002", "Cache Command in Redis Error", true); - - public CommandException() { - super(); - } - - public CommandException(String errCode, String errMsg, boolean isSystem, Throwable cause) { - super(errCode, errMsg, isSystem, cause); - } - - public CommandException(String errCode, String errMsg) { - super(errCode, errMsg); - } - - public CommandException(String errCode, String errMsg, boolean isSystem) { - super(errCode, errMsg, isSystem); - } - - public CommandException(String errCode, String errMsg, Throwable cause) { - super(errCode, errMsg, cause); - } diff --git a/java/BadTry.java b/java/BadTry.java deleted file mode 100644 index 31ad9c3ba300d0bf40cdc9810cc3063ccb359e6c..0000000000000000000000000000000000000000 --- a/java/BadTry.java +++ /dev/null @@ -1,10 +0,0 @@ -// 背景:和B系统对接,对方需要调用我们A系统获取验证 -//B系统代码大致如下 -try{ -//此处省略500行其他逻辑代码 -//这里有一行调用A系统代码 -}catch(Exception e){ - return "A系统异常,请联系A系统管理员处理"; -} - -//没错,我就是A系统管理员,因此我发现了B系统里那省略的500行代码的3个异常~ 好伟大的我 \ No newline at end of file diff --git a/java/BuildRange b/java/BuildRange deleted file mode 100644 index 025a05f6e51d9932e6bf79e1ae04018a6249751c..0000000000000000000000000000000000000000 --- a/java/BuildRange +++ /dev/null @@ -1,50 +0,0 @@ -public class BuildRange{ - - public static void main(String[] args) { - try { - int[] i = buildInt("2,3,4,6"); - for(int s: i){ - System.out.println(s); - } - - float[] f = buildFloat("-200,-60,20,300"); - for(float s: f){ - System.out.println(s); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - /* - * 将字串转为数值分段处理,供它处调用查找目标值所在区间 - * 如:"-200,-60,20,300" 转换为 { -∞,-200,-60,20,300,∞ } - * 依类型不同分为int和float两个方法 - * 代码删至最简可用 - */ - - // for Int - public static int[] buildInt(String strInt){ - String[] strs = strInt.split(","); - int[] rtnI = new int[strs.length+2]; - for(int i=1;i demo2(JSONObject param) { - - // 查询获取总数 - List list1 = dao.queryForList("rentCar.getUserCars", param); - Map result = new LinkedHashMap<>(); - result.put("total", list1.size()); - result.put("content", dao.queryForList("rentCar.getUserCarsJoinBrand", param)); - return result; - } - - /** - * 示例三:数据入库「大坑:不使用批量插入,使用for 循环一条条处理」 - * - */ - @Override - public void demo3(JSONObject param) { - - List priceList = (List) param.get("priceList"); - for (Map map : priceList) { - map.putAll(param); - checkAddPriceRule(map); // 调用数据校验方法 - - map.put("business_type",business_type); - map.put("description",description); - insertPriceRule(map); // 调用插入数据库方法 - } - } - - /** - * 示例三:获取明天的日期「大坑:我刚刚就被前端坑过,他传了个 2019-06-31 过来」 - * - */ - @Override - public void demo4(JSONObject param) { - String date = getSysStrDate(); - List dateArray = Arrays.asList(date.split("-")); - String year = dateArray.get(0); - String month = dateArray.get(1); - Integer day = Integer.valueOf(dateArray.get(2)) + 1; - String tomorrow = year + "-" + month + "-"+day; - } -} \ No newline at end of file diff --git a/java/BullshitReturn.java b/java/BullshitReturn.java deleted file mode 100644 index c6b2e22c7a79b98d8912162260a9c8a1c455c034..0000000000000000000000000000000000000000 --- a/java/BullshitReturn.java +++ /dev/null @@ -1,15 +0,0 @@ -class BullshitReturnDemo { - //定义特殊的返回值 - public static final String ERROR_MSG = "Error:getHttpByPostBody exception"; - public static String getHttpByPostBody(String url, String data) throws IOException{ - Request request = Request.of(url).setBody(data).setConnectionTimeout(CONNECT_TIMEOUT).setReadTimeout(READ_TIMEOUT); - request.addHeader("Content-type" , HttpConstants.FORM_URLENCODED_WITH_DEFAULT_CHARSET); - Response response = SMART_HTTP_CLIENT.post(request); - if(HttpStatus.HTTP_OK == response.getStatusCode()){ - return response.getBody(); - }else { - ///返回这种特定的值,改变http的语义,很不规范,很不好统一 - return ERROR_MSG; - } - } -} \ No newline at end of file diff --git a/java/BusinessCode.java b/java/BusinessCode.java deleted file mode 100644 index 904a60a6cf6a37144af83f0c2ff040154f5ecea0..0000000000000000000000000000000000000000 --- a/java/BusinessCode.java +++ /dev/null @@ -1,8 +0,0 @@ -/** - * @author imyzt - * @date 2019/5/28 - * @description 这个类是Object的子类 - */ -public class BusinessCode { - -} diff --git a/java/CacheSizes.java b/java/CacheSizes.java deleted file mode 100644 index b470801054ac8287c1aa016d8fef64b595ec0d85..0000000000000000000000000000000000000000 --- a/java/CacheSizes.java +++ /dev/null @@ -1,290 +0,0 @@ -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -public class CacheSizes { - - /** - * Returns the size in bytes of a basic Object. This method should only - * be used for actual Object objects and not classes that extend Object. - * - * @return the size of an Object. - */ - public static int sizeOfObject() { - return 4; - } - - /** - * Returns the size in bytes of a String. - * - * @param string the String to determine the size of. - * @return the size of a String. - */ - public static int sizeOfString(String string) { - if (string == null) { - return 0; - } - return 4 + string.getBytes().length; - } - - /** - * Returns the size in bytes of a primitive int. - * - * @return the size of a primitive int. - */ - public static int sizeOfInt() { - return 4; - } - - /** - * Returns the size in bytes of a primitive char. - * - * @return the size of a primitive char. - */ - public static int sizeOfChar() { - return 2; - } - - /** - * Returns the size in bytes of a primitive boolean. - * - * @return the size of a primitive boolean. - */ - public static int sizeOfBoolean() { - return 1; - } - - /** - * Returns the size in bytes of a primitive long. - * - * @return the size of a primitive long. - */ - public static int sizeOfLong() { - return 8; - } - - /** - * Returns the size in bytes of a primitive double. - * - * @return the size of a primitive double. - */ - public static int sizeOfDouble() { - return 8; - } - - /** - * Returns the size in bytes of a Date. - * - * @return the size of a Date. - */ - public static int sizeOfDate() { - return 12; - } - - /** - * Returns the size in bytes of a Map object. - * - * @param map the Map object to determine the size of. - * @return the size of the Map object. - * @exception Exception exception - */ - public static int sizeOfMap(Map map) - throws Exception { - if (map == null) { - return 0; - } - // Base map object -- should be something around this size. - int size = 36; - Set> set = map.entrySet(); - - // Add in size of each value - for (Map.Entry entry : set) { - size += sizeOfAnything(entry.getKey()); - size += sizeOfAnything(entry.getValue()); - } - return size; - } - - /** - * Returns the size in bytes of a Collection object. Elements are assumed to be - * Strings, Longs or Cacheable objects. - * - * @param list the Collection object to determine the size of. - * @return the size of the Collection object. - * @exception Exception exception - */ - public static int sizeOfCollection(Collection list) - throws Exception { - if (list == null) { - return 0; - } - // Base list object (approximate) - int size = 36; - // Add in size of each value - Object[] values = list.toArray(); - for (int i = 0; i < values.length; i++) { - size += sizeOfAnything(values[i]); - } - return size; - } - - /** - * Returns the size of an object in bytes. Determining size by serialization - * is only used as a last resort. - * @param object object - * @return the size of an object in bytes. - * @exception Exception Exception - */ - public static int sizeOfAnything(Object object) - throws Exception { - // If the object is Cacheable, ask it its size. - if (object == null) { - return 0; - } else if (object instanceof String) { - return sizeOfString((String)object); - } else if (object instanceof Long) { - return sizeOfLong(); - } else if (object instanceof Integer) { - return sizeOfObject() + sizeOfInt(); - } else if (object instanceof Double) { - return sizeOfObject() + sizeOfDouble(); - } else if (object instanceof Boolean) { - return sizeOfObject() + sizeOfBoolean(); - } else if (object instanceof Map) { - return sizeOfMap((Map)object); - } else if (object instanceof long[]) { - long[] array = (long[])object; - return sizeOfObject() + array.length * sizeOfLong(); - } else if (object instanceof Collection) { - return sizeOfCollection((Collection)object); - } else if (object instanceof byte[]) { - byte[] array = (byte[])object; - return sizeOfObject() + array.length; - } else { -// int size; -// // Default to serializing the object out to determine size. -// NullOutputStream out = new NullOutputStream(); -// ObjectOutputStream outObj = new ObjectOutputStream(out); -// outObj.writeObject(object); -// size = out.size(); - - return sizeof(object); - } - } - - /** - * 简单类型元素长度 - * @param clazz clazz - * @return int - */ - private static int sizeofPrimitiveClass(Class clazz) { - return clazz == boolean.class || clazz == byte.class ? 1 : clazz == char.class || clazz == short.class ? 2 - : clazz == int.class || clazz == float.class ? 4 : 8; - } - - /** - * 简单类型数组长度 - * @param object object - * @return int - */ - private static int lengthOfPrimitiveArray(Object object) { - - Class clazz = object.getClass(); - - return clazz == boolean[].class ? ((boolean[]) object).length - : clazz == byte[].class ? ((byte[]) object).length - : clazz == char[].class ? ((char[]) object).length : clazz == short[].class ? ((short[]) object).length - : clazz == int[].class ? ((int[]) object).length : clazz == float[].class ? ((float[]) object).length - : clazz == long[].class ? ((long[]) object).length : ((double[]) object).length; - } - - /** - * 构造器函数 - * @param object object - * @param field field - * @return int - */ - private static int sizeofConstructor(Object object, Field field) { - throw new UnsupportedOperationException("field type Constructor not accessible: " + object.getClass() + " field:" + field); - } - - /** - * 对象大小 - * @param object object - * @return int - */ - public static int sizeof(Object object) { - if (object == null) - return 0; - int size = 8; - Class clazz = object.getClass(); - if (clazz.isArray()) { - size += 16; // length变量是int型 - Class componentType = clazz.getComponentType(); - if (componentType.isPrimitive()) - return size + lengthOfPrimitiveArray(object) * sizeofPrimitiveClass(componentType); - Object[] array = (Object[]) object; - size += 4 * array.length; - for (Object o : array) - size += sizeof(o); - return size; - } - Field[] fields = clazz.getDeclaredFields(); - for (Field field : fields) { - if (Modifier.isStatic(field.getModifiers())) - continue; // 类成员不计 - Class type = field.getType(); - if (type.isPrimitive()) - size += sizeofPrimitiveClass(type); - else { - size += 4; // 一个引用型变量占用4个字节 - try { - field.setAccessible(true); // 可以访问非public类型的变量 - size += sizeof(field.get(object)); - } catch (Exception e) { - size += sizeofConstructor(object, field); - } - } - } - return size; - } - - /** - * 空的输出流(不输出) - * - */ - public static class NullOutputStream extends OutputStream { - - /** - * 数据大小 - */ - int size = 0; - - @Override - public void write(int b) { - size++; - } - - @Override - public void write(byte[] b) { - size += b.length; - } - - @Override - public void write(byte[] b, int off, int len) { - size += len; - } - - /** - * Returns the number of bytes written out through the stream. - * - * @return the number of bytes written to the stream. - */ - public int size() { - return size; - } - } -} diff --git a/java/CarInfo.java b/java/CarInfo.java deleted file mode 100644 index ae4fbfa3f86f8de4eac7ccf363d802afbb58bf14..0000000000000000000000000000000000000000 --- a/java/CarInfo.java +++ /dev/null @@ -1,207 +0,0 @@ -import java.util.Scanner; -import org.junit.Test; - -/*** - * - * һüĴ - * - */ - -public class CarInfo { - public CarInfoOutPut queryAllCatMonitor(Long orderId) throws ParseException { - /**ȡ˵Ϣ**/ - CarMonitorOutPut car = dao.getCar(orderId); - CarTankRecent carTankRecent; - CarInfoOutPut carInfoOutPut = new CarInfoOutPut(); - if(null!=car){ - carTankRecent = carService.getCarTankRecent(car.getTractorPlate()); - /****/ - if(carTankRecent!=null){ - car.setSpeed(carTankRecent.getMph()); - }else{ - car.setSpeed(0D); - } - - List list=new ArrayList(); - List queryALLTask = dao.queryALLTask(orderId); - for (LoadTaskInformationOutPut loadTaskInformationOutPut : queryALLTask) { - if(loadTaskInformationOutPut.getType()==0){ - TaskInformationOutPut one = new TaskInformationOutPut(); - TaskInformationOutPut two = new TaskInformationOutPut(); - TaskInformationOutPut three = new TaskInformationOutPut(); - TaskInformationOutPut four = new TaskInformationOutPut(); - loadTaskInformationOutPut.getArriveTime(); - if(null!=loadTaskInformationOutPut.getArriveTime()){ - one.setTaskInfo("Ѿ"); - one.setTaskType("װҺ"); - one.setSignType(""); - one.setTagName("װҺϢ"); - one.setTime(loadTaskInformationOutPut.getArriveTime()); - one.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - one.setLng(loadTaskInformationOutPut.getLng()); - one.setLat(loadTaskInformationOutPut.getLat()); - car.setState("Ѿ,ǰһ"); - list.add(one); - } - if(loadTaskInformationOutPut.getLoadTime()!=null){ - two.setTaskInfo("ʼװҺ"); - two.setTaskType("װҺ"); - two.setSignType("װҺ"); - two.setTagName("װҺϢ"); - two.setTime(loadTaskInformationOutPut.getLoadTime()); - two.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - two.setLng(loadTaskInformationOutPut.getLng()); - two.setLat(loadTaskInformationOutPut.getLat()); - car.setState("ʼװҺ,ǰһ"); - list.add(two); - } - if(loadTaskInformationOutPut.getLeaveTime()!=null){ - three.setTaskInfo("װҺ"); - three.setTaskType("װҺ"); - three.setSignType("뿪"); - three.setTagName("װҺϢ"); - three.setTime(loadTaskInformationOutPut.getLeaveTime()); - three.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - three.setLng(loadTaskInformationOutPut.getLng()); - three.setLat(loadTaskInformationOutPut.getLat()); - car.setState("װҺ,ǰһ"); - list.add(three); - } - if(loadTaskInformationOutPut.getReceiptTime()!=null&&loadTaskInformationOutPut.getPumpUrl()!=null){ - four.setTaskInfo("װҺص"); - four.setTaskType("װҺ"); - four.setSignType("װҺص"); - four.setTagName("صϢ"); - four.setTime(loadTaskInformationOutPut.getReceiptTime()); - four.setPumpUrl(loadTaskInformationOutPut.getPumpUrl()); - four.setLoadWeigth(loadTaskInformationOutPut.getLoadWeigth()); - four.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - four.setLng(loadTaskInformationOutPut.getLng()); - four.setLat(loadTaskInformationOutPut.getLat()); - car.setState("װҺص,ǰһ"); - list.add(four); - } - - } - if(loadTaskInformationOutPut.getType()==1){ - TaskInformationOutPut one = new TaskInformationOutPut(); - TaskInformationOutPut two = new TaskInformationOutPut(); - TaskInformationOutPut three = new TaskInformationOutPut(); - TaskInformationOutPut four = new TaskInformationOutPut(); - if(loadTaskInformationOutPut.getArriveTime()!=null){ - one.setTaskInfo("Ѿ"); - one.setTaskType("жҺ"); - one.setSignType(""); - one.setTagName("жҺϢ"); - one.setTime(loadTaskInformationOutPut.getArriveTime()); - one.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - one.setLng(loadTaskInformationOutPut.getLng()); - one.setLat(loadTaskInformationOutPut.getLat()); - car.setState("жҺص,ǰһ"); - list.add(one); - } - if(loadTaskInformationOutPut.getLoadTime()!=null){ - two.setTaskInfo("ʼжҺ"); - two.setTaskType("жҺ"); - two.setSignType("жҺ"); - two.setTagName("жҺϢ"); - two.setTime(loadTaskInformationOutPut.getLoadTime()); - two.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - two.setLng(loadTaskInformationOutPut.getLng()); - two.setLat(loadTaskInformationOutPut.getLat()); - list.add(two); - car.setState("ʼжҺ,ǰһ"); - } - if(loadTaskInformationOutPut.getLeaveTime()!=null){ - three.setTaskInfo("жҺ"); - three.setTaskType("жҺ"); - three.setSignType("뿪"); - three.setTagName("жҺϢ"); - three.setTime(loadTaskInformationOutPut.getLeaveTime()); - three.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - three.setLng(loadTaskInformationOutPut.getLng()); - three.setLat(loadTaskInformationOutPut.getLat()); - list.add(three); - car.setState("жҺ,ǰһ"); - } - if(loadTaskInformationOutPut.getReceiptTime()!=null&&loadTaskInformationOutPut.getPumpUrl()!=null){ - four.setTaskInfo("жҺص"); - four.setTaskType("жҺ"); - four.setSignType("жҺص"); - four.setTagName("صϢ"); - four.setPumpUrl(loadTaskInformationOutPut.getPumpUrl()); - four.setLoadWeigth(loadTaskInformationOutPut.getLoadWeigth()); - four.setTime(loadTaskInformationOutPut.getReceiptTime()); - four.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - four.setLng(loadTaskInformationOutPut.getLng()); - four.setLat(loadTaskInformationOutPut.getLat()); - list.add(four); - car.setState("жҺ,ǰһ"); - } - } - if(loadTaskInformationOutPut.getType()==2){ - TaskInformationOutPut one = new TaskInformationOutPut(); - TaskInformationOutPut two = new TaskInformationOutPut(); - TaskInformationOutPut three = new TaskInformationOutPut(); - TaskInformationOutPut four = new TaskInformationOutPut(); - if(loadTaskInformationOutPut.getLoadTime()!=null){ - one.setTaskInfo("Ѿ"); - one.setTaskType("Һ"); - one.setSignType(""); - one.setTagName("ҺϢ"); - one.setTime(loadTaskInformationOutPut.getArriveTime()); - one.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - one.setLng(loadTaskInformationOutPut.getLng()); - one.setLat(loadTaskInformationOutPut.getLat()); - list.add(one); - car.setState("ﵹҺص,ǰһ"); - } - if(loadTaskInformationOutPut.getLoadTime()!=null){ - two.setTaskInfo("ʼҺ"); - two.setTaskType("Һ"); - two.setSignType("Һ"); - two.setTagName("ҺϢ"); - two.setTime(loadTaskInformationOutPut.getLoadTime()); - two.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - two.setLng(loadTaskInformationOutPut.getLng()); - two.setLat(loadTaskInformationOutPut.getLat()); - list.add(two); - car.setState("ʼҺ,ǰһ"); - } - if(loadTaskInformationOutPut.getLeaveTime()!=null){ - three.setTaskInfo("ɵҺ"); - three.setTaskType("Һ"); - three.setSignType("뿪"); - three.setTagName("ҺϢ"); - three.setTime(loadTaskInformationOutPut.getLeaveTime()); - three.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - three.setLng(loadTaskInformationOutPut.getLng()); - three.setLat(loadTaskInformationOutPut.getLat()); - list.add(three); - car.setState("ɵҺ,ǰһ"); - - } - if(loadTaskInformationOutPut.getReceiptTime()!=null&&loadTaskInformationOutPut.getPumpUrl()!=null){ - four.setTaskInfo("Һص"); - four.setTaskType("Һ"); - four.setSignType("Һص"); - four.setTagName("صϢ"); - four.setPumpUrl(loadTaskInformationOutPut.getPumpUrl()); - four.setLoadWeigth(loadTaskInformationOutPut.getLoadWeigth()); - four.setTime(loadTaskInformationOutPut.getReceiptTime()); - four.setCustomerName(loadTaskInformationOutPut.getCustomerName()); - four.setLng(loadTaskInformationOutPut.getLng()); - four.setLat(loadTaskInformationOutPut.getLat()); - list.add(four); - car.setState("Һص,׼"); - } - } - } - carInfoOutPut.setCar(car); - carInfoOutPut.setTask(list); - } - return carInfoOutPut; - } - - -} diff --git a/java/CatchDemo.java b/java/CatchDemo.java deleted file mode 100644 index 7414205b7cc418dc61c90a3cc77f8b5c7790a605..0000000000000000000000000000000000000000 --- a/java/CatchDemo.java +++ /dev/null @@ -1,11 +0,0 @@ -class CatchDemo { - - // 异常捕获,什么事都不做 - static { - try { - gun = Resources.parseModel("images/gun.txt"); - } catch (FileNotFoundException e) { - } catch (IOException e) { - } - } -} \ No newline at end of file diff --git a/java/ChangeString.java b/java/ChangeString.java deleted file mode 100644 index da0dbc7d14ded089402f22c42d99e8e7cbf5d133..0000000000000000000000000000000000000000 --- a/java/ChangeString.java +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Create Time 2019/9/24 - * Long转String - * @author liuyang - **/ -public class ChangeString { - public static void main(String[] ares){ - - Long a=1L; - String b=null; - b=a+""; - } -} diff --git a/java/ChannleSubMerPoolBANKService.java b/java/ChannleSubMerPoolBANKService.java deleted file mode 100644 index f902ed48eda33456051d4f7a78fb3cc7a605a6ea..0000000000000000000000000000000000000000 --- a/java/ChannleSubMerPoolBANKService.java +++ /dev/null @@ -1,241 +0,0 @@ -package service.pay.service; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import service.BaseService; -import service.pay.ChannelSubMerPoolConfig; -import utils.Dao; - -/** - * Created by 80964 on 2018/10/11. - */ -@Service -class ChannleSubMerPoolBANKService extends BaseService{ - private static final Logger log = LoggerFactory.getLogger(ChannleSubMerPoolBANKService.class); - private String index0= "index0"; - private String index1= "index1"; - private String index2= "index2"; - private String index3= "index3"; - private String index4= "index4"; - private String index5= "index5"; - private String index6= "index6"; - private String index7= "index7"; - private String index8= "index8"; - private String index9= "index9"; - private String index10= "index10"; - private String index11= "index11"; - private String index12= "index12"; - private String index13= "index12"; - private String index14= "index14"; - private String index15= "index15"; - private String index16= "index16"; - private String index17= "index17"; - private String index18= "index18"; - private String index19= "index19"; - private String index20= "index20"; - private String indexDef= "indexDef"; - private String IndexPri= "IndexPri"; - - public Map findFastPool(params){ - int Index = 1; - synchronized (IndexPri){ - if(ChannelSubMerPoolConfig.BANKINDEX == 21){ - ChannelSubMerPoolConfig.BANKINDEX = 0; - } - Index = ChannelSubMerPoolConfig.BANKINDEX; - ChannelSubMerPoolConfig.BANKINDEX = ChannelSubMerPoolConfig.BANKINDEX + 1; - } - Map entity = null; - switch (Index){ - case 0: entity = findFastPool0(params); break; - case 1: entity = findFastPool1(params); break; - case 2: entity = findFastPool2(params);break; - case 3: entity = findFastPool3(params);break; - case 4: entity = findFastPool4(params);break; - case 5: entity = findFastPool5(params);break; - case 6: entity = findFastPool6(params);break; - case 7: entity = findFastPool7(params);break; - case 8: entity = findFastPool8(params);break; - case 9: entity = findFastPool9(params);break; - case 10: entity = findFastPool10(params);break; - case 11: entity = findFastPool11(params);break; - case 12: entity = findFastPool12(params);break; - case 13: entity = findFastPool13(params);break; - case 14: entity = findFastPool14(params);break; - case 15: entity = findFastPool15(params);break; - case 16: entity = findFastPool16(params);break; - case 17: entity = findFastPool17(params);break; - case 18: entity = findFastPool18(params);break; - case 19: entity = findFastPool19(params);break; - case 20: entity = findFastPool20(params);break; - default: entity = findFastPoolDef(params);break; - } - return entity; - } - - public Map findFastPoolDef(params){ - synchronized(indexDef){ - Map acqSubMer = findAndUpdata(params,"0"); - return acqSubMer; - } - } - public Map findFastPool0(params){ - synchronized(index0){ - Map acqSubMer = findAndUpdata(params,"0"); - return acqSubMer; - } - } - - public Map findFastPool1(params){ - synchronized(index1){ - Map acqSubMer = findAndUpdata(params,"5"); - return acqSubMer; - } - } - - public Map findFastPool2(params){ - synchronized(index2){ - Map acqSubMer = findAndUpdata(params,"10"); - return acqSubMer; - } - } - - public Map findFastPool3(params){ - synchronized(index3){ - Map acqSubMer = findAndUpdata(params,"15"); - return acqSubMer; - } - } - - public Map findFastPool4(params){ - synchronized(index4){ - Map acqSubMer = findAndUpdata(params,"20"); - return acqSubMer; - } - } - - public Map findFastPool5(params){ - synchronized(index5){ - Map acqSubMer = findAndUpdata(params,"25"); - return acqSubMer; - } - } - public Map findFastPool6(params){ - synchronized(index6){ - Map acqSubMer = findAndUpdata(params,"30"); - return acqSubMer; - } - } - public Map findFastPool7(params){ - synchronized(index7){ - Map acqSubMer = findAndUpdata(params,"35"); - return acqSubMer; - } - } - public Map findFastPool8(params){ - synchronized(index8){ - Map acqSubMer = findAndUpdata(params,"40"); - return acqSubMer; - } - } - public Map findFastPool9(params){ - synchronized(index9){ - Map acqSubMer = findAndUpdata(params,"45"); - return acqSubMer; - } - } - public Map findFastPool10(params){ - synchronized(index10){ - Map acqSubMer = findAndUpdata(params,"50"); - return acqSubMer; - } - } - - public Map findFastPool11(params){ - synchronized(index11){ - Map acqSubMer = findAndUpdata(params,"55"); - return acqSubMer; - } - } - - public Map findFastPool12(params){ - synchronized(index12){ - Map acqSubMer = findAndUpdata(params,"60"); - return acqSubMer; - } - } - - public Map findFastPool13(params){ - synchronized(index13){ - Map acqSubMer = findAndUpdata(params,"65"); - return acqSubMer; - } - } - - public Map findFastPool14(params){ - synchronized(index14){ - Map acqSubMer = findAndUpdata(params,"70"); - return acqSubMer; - } - } - - public Map findFastPool15(params){ - synchronized(index15){ - Map acqSubMer = findAndUpdata(params,"75"); - return acqSubMer; - } - } - public Map findFastPool16(params){ - synchronized(index16){ - Map acqSubMer = findAndUpdata(params,"80"); - return acqSubMer; - } - } - public Map findFastPool17(params){ - synchronized(index17){ - Map acqSubMer = findAndUpdata(params,"85"); - return acqSubMer; - } - } - public Map findFastPool18(params){ - synchronized(index18){ - Map acqSubMer = findAndUpdata(params,"90"); - return acqSubMer; - } - } - public Map findFastPool19(params){ - synchronized(index19){ - Map acqSubMer = findAndUpdata(params,"95"); - return acqSubMer; - } - } - public Map findFastPool20(params){ - synchronized(index20){ - Map acqSubMer = findAndUpdata(params,"100"); - return acqSubMer; - } - } - - public Map findAndUpdata(params,indxe){ - String sql = "select ID,MER_NO,ORG_MER_NO,MER_NAME,BODY,STORE_NO from channel_sub_merchant_pool_bank where AMOUNT_LEVEL = '"+params.get("AMOUNT_LEVEL")+"' "; - if (params.TIME_TYPE && params.TIME_TYPE != "1"){ - sql += " and TIME_TYPE = '${params.TIME_TYPE}' "; - } - sql += " and POOL_MER_TYPE = '"+params.get("POOL_MER_TYPE")+"' and IS_OPEN = '1' and MER_STATUS = 'normal' "; - sql += " and CHANNEL_CODE = '"+params.get("CHANNEL_CODE")+"' ORDER BY CONUT LIMIT "+indxe+",1"; - Map acqSubMer = Dao.db.rows(sql).get(0); - upDataConutUp(acqSubMer); - return acqSubMer; - } - - /** - * 计数 + 1 - * @param entity - */ - private int upDataConutUp(entity){ - def id = entity.get("ID"); - def sql = "UPDATE channel_sub_merchant_pool_bank set CONUT = CONUT+1 ,UPDATE_TIME = now() where ID = "+id; - dao.db.execute(sql.toString()); - } -} diff --git a/java/CheckExist.java b/java/CheckExist.java deleted file mode 100644 index e03cea43a81a05e5da3d9c2d0ba54b1b490f6525..0000000000000000000000000000000000000000 --- a/java/CheckExist.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 是否收藏(有没有感觉这段代码特别特别啰嗦,不够简洁) - * @param articleKey - * @param user - * @return - */ -public boolean isFavorite(String articleKey, User user) { - boolean isFavorite = false; - if (user == null) { - return false; - } - long userId = user.getId(); - Article article = getByArticleKey(articleKey); - if (null == article) { - return false; - } - List list = listAttentionUsers(article); - if (list == null || list.size() <= 0) { - return false; - } - for (Long id : list) { - if (id == userId) { - isFavorite = true; - break; - } - } - return isFavorite; -} diff --git a/java/ChineseCode.png b/java/ChineseCode.png deleted file mode 100644 index dad839987734da9cc34cbde4814e10720a2c9a3a..0000000000000000000000000000000000000000 Binary files a/java/ChineseCode.png and /dev/null differ diff --git a/java/ColourType.java b/java/ColourType.java deleted file mode 100644 index 13d268bd2aabb602b6eea32b46f11ac1ec2c5601..0000000000000000000000000000000000000000 --- a/java/ColourType.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * - */ -package com.jf.common.constant; - -public enum ColourType { - ColourType_R(10,"红"), - ColourType_B(20,"蓝"), - ColourType_G(110,"绿"), - ColourType_Y(1100,"黄"); - - /** - * 数据字典ID - */ - private Integer id; - - /** - * 数据字典名称 - */ - private String name; - - private ColourType(Integer id, String name) { - this.id = id; - this.name = name; - } - - /** - * 通过ID 查找名字 - */ - public static String findName(Integer Id) { - ColourType[] tyList = ColourType.values(); - for (int i = 0; i < tyList.length; i++) { - if (tyList[i] != null && tyList[i].id == Id) { - return tyList[i].name; - } - } - return ""; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public static void main(String[] args) { - Integer idB = 20; - System.out.println("idB对应颜色名:" + ColourType.findName(idB)); - //输出结果:idB对应颜色名:蓝 - - Integer idY = 1100; - System.out.println("idY对应颜色名:" + ColourType.findName(idY)); - //输出结果:idY对应颜色名: - - //我蒙了,大神为啥呀!你们执行好着吗? - } -} diff --git a/java/CommonUtil.java b/java/CommonUtil.java deleted file mode 100644 index 8c628f2dda047f0248270dfd0a2051e32f237c56..0000000000000000000000000000000000000000 --- a/java/CommonUtil.java +++ /dev/null @@ -1,235 +0,0 @@ -package com.kingroad.auditproject.common.util; - -import com.kuiren.auth.AuthContext; -import com.kuiren.auth.User; -import org.apache.commons.lang.StringUtils; -import org.springframework.web.util.HtmlUtils; - -import javax.servlet.http.HttpServletRequest; -import java.util.Random; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class CommonUtil { - - - private static final String USER_KEY = "$USER_INFO_KEY$"; - - /** - * 对面默认为空 -- 空字符串 - * - * @param names - * @return - */ - public static String isNull(Object names) { - if (names == null) { - return ""; - } else { - return names.toString().trim(); - } - } - - - /** - * 对面默认为不为空 -- 空字符串 - * - * @param str - * @return - */ - public static boolean isNotBlank(String str) { - return StringUtils.isNotBlank(str); - } - - - /** - * 对面默认为空 -- 空字符串 - * - * @param str - * @return - */ - public static boolean isBlank(String str) { - return StringUtils.isBlank(str); - } - - - /* - * 判断是否为整数 - * @param str 传入的字符串 - * @return 是整数返回true,否则返回false - */ - public static boolean isInteger(String str) { - Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); - return pattern.matcher(str).matches(); - } - - - /* - * 判断是否为浮点数,包括double和float - * @param str 传入的字符串 - * @return 是浮点数返回true,否则返回false - */ - public static boolean isDouble(String str) { - Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$"); - return pattern.matcher(str).matches(); - } - - //为空就返回一个零 - public static String returnZero(String str){ - if(isNull(str).equals("")){ - return "0"; - }else{ - return str.toString().trim(); - } - } - - /** - * 判断是否是手机端 - * @param requestHeader - * @return - */ - public static boolean isMobileDevice(String requestHeader) - { - String[] deviceArray = new String[] { "android", "mac os", "windows phone" }; - if (requestHeader == null) - { - return false; - } - requestHeader = requestHeader.toLowerCase(); - for (int i = 0; i < deviceArray.length; i++) - { - if (requestHeader.indexOf(deviceArray[i]) > 0) - { - return true; - } - } - return false; - } - - - /** - * 判断是否为数字 - * - * @param str - * @return - */ - public static boolean isNum(String str) { - Pattern p = null; // 正则表达式 - Matcher m = null; // 操作的字符串 - p = Pattern.compile("^(-?\\d+)(\\.\\d+)?$"); - m = p.matcher(str); - return m.matches(); - } - - - /** - * 随机数 - * @param place 定义随机数的位数 - */ - public static String randomGen(int place) { - String base = "qwertyuioplkjhgfdsazxcvbnmQAZWSXEDCRFVTGBYHNUJMIKLOP0123456789"; - StringBuffer sb = new StringBuffer(); - Random rd = new Random(); - for(int i=0;i len) { - str = str.substring(0, len - 1); - } - return str; - } - - - /** - * 获取HTML内的文本,不包含标签 - * - * @param html HTML 代码 - */ - public static String getInnerText(String html) { - if (StringUtils.isNotBlank(html)) { - //去掉 html 的标签 - String content = html.replaceAll("]+>", ""); - // 将多个空格合并成一个空格 - content = content.replaceAll("( )+", " "); - // 反向转义字符 - content = HtmlUtils.htmlUnescape(content); - return content.trim(); - } - return ""; - } - - /** - * 对面默认为空 -- 空字符串 - * - * @param names - * @return - */ - public static int isNullInteger(Integer names) { - if (names == null) { - return 0; - } else { - return names; - } - } - - /** - * 获取当前用户 - * - * @param - * @return - */ - public static User getUser() { - try { - // 定时任务执行时,AuthContext.getCurrentUser() 存在空指针 this.getRequest().getCookies(); - HttpServletRequest request = SpringUtil.getRequest(); - User user = (User)request.getAttribute(USER_KEY); - if(user == null) { - user = AuthContext.getCurrentUser(); - request.setAttribute(USER_KEY, user); - } - return user; - } catch (Exception e) { - return null; - } - } - - /** - * 获取用户当前所在用户 - **/ - public static String getUserName() - { - return getUser().getUserName(); - } - - - /** - * 获取用户当前所在部门 - **/ - public static String getEpsId() - { - return getUser().getAuthOrgId(); - } - - - - -} \ No newline at end of file diff --git a/java/ContactAdmin.java b/java/ContactAdmin.java deleted file mode 100644 index c478c006c3c1355fc786eb71549cd2bc9723a06a..0000000000000000000000000000000000000000 --- a/java/ContactAdmin.java +++ /dev/null @@ -1,17 +0,0 @@ -/** - * 某人(离职)写业务,不留自己的姓名、手机号,留你的信息的时候 - */ -public class ContactAdmin { - - /** - * @author 你的名字(实际是别人写的) - * @param args - */ - public static void main(String[] args) { - try{ - //业务 - }catch (Exception e){ - throw new Business("出错了,请联系管理员XXX,电话189xxxxxxxx") - } - } -} diff --git a/java/CountUserTable.java b/java/CountUserTable.java deleted file mode 100644 index 5a43dfaf8566b663780b2fef0f7df2a4efd98cc3..0000000000000000000000000000000000000000 --- a/java/CountUserTable.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.gitee.bullshit.code; - -import org.nutz.dao.*; -import org.nutz.ioc.loader.annotation.*; -import junit.framework.*; - -/** - 统计用户总数,来源于N年前某个用户抱怨执行效率低,贴出类似逻辑的代码. - @author wendal -*/ -@IocBean -public class CountUserTable { - - @Inject Dao dao; - - @Test - public void test_user_count() { - // 取出全部用户对象(dao.query返回List),然后取list大小就可以啦,是不是很机智 - int count = dao.query(User.class, null).size(); - System.out.println("用户总数是" + count); - } -} \ No newline at end of file diff --git a/java/CreateIncome.java b/java/CreateIncome.java deleted file mode 100644 index 2690cc73536c4b1408f1f4966b7f9c2d81d92789..0000000000000000000000000000000000000000 --- a/java/CreateIncome.java +++ /dev/null @@ -1,10 +0,0 @@ -import java.math.BigDecimal; - -public class CreateIncome { - /** - * 返回支付金额 - */ - public static BigDecimal getPayFee(BigDecimal payFee) { - return payFee.multiply(BigDecimal.TEN); - } -} diff --git a/java/DangerLog.java b/java/DangerLog.java deleted file mode 100644 index 772e87f138075a4ec38d3fbc28019e1c3d32d047..0000000000000000000000000000000000000000 --- a/java/DangerLog.java +++ /dev/null @@ -1,19 +0,0 @@ -public class DangerLog { - public class ReadLog { - int readNum; - - @Override - public String toString() { - // 调用该方法将更改对象的状态,打印或者调试都可能会调用该方法 - readNum++; - return "ReadLog [readNum:" + readNum + ",其他信息]"; - } - } - - public ReadLog getReadLog() { - ReadLog log = new ReadLog(); - // 删除下面不需要的日志代码或者调试时添加监视都会导致业务出错 - System.out.println(log); - return log; - } -} diff --git a/java/Dao.java b/java/Dao.java deleted file mode 100644 index b8218a7424a6ecfe5f923ca9ba84a3cb3e537a88..0000000000000000000000000000000000000000 --- a/java/Dao.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Dao层的方法,Map进,Map出 - * 神啊,求你告诉我这个箱子是干什么的吧 - */ -public Map selRedeemInfo(Map param) { - return Dao.selectOne(basepath + "selRedeemInfo", param); -} \ No newline at end of file diff --git a/java/DateUtil.java b/java/DateUtil.java deleted file mode 100644 index 62dfa229f820b40bea602a9e90705f2047fd2235..0000000000000000000000000000000000000000 --- a/java/DateUtil.java +++ /dev/null @@ -1,18 +0,0 @@ -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * 我觉得我写的很棒,但不知道为什么第二天被辞退了 - */ -public class DateUtil { - - private static String getDateFormater(Date date){ - SimpleDateFormat sf1 = new SimpleDateFormat("yyyy"); - SimpleDateFormat sf2 = new SimpleDateFormat("MM"); - SimpleDateFormat sf3 = new SimpleDateFormat("dd"); - String year = sf1.format(date); - String month = sf2.format(date); - String day = sf3.format(date); - return year+"-"+month+"-"+day; - } -} diff --git a/java/Dayv.java b/java/Dayv.java deleted file mode 100644 index e6fc29ca8bb8b7e41fc7ca65e36b1cd778785ea1..0000000000000000000000000000000000000000 --- a/java/Dayv.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.test.java.enumtest; - - -public class Dayv { - - //记得刚工作的时候踩过这样一个坑 当时debug发现相等数值情况下有时返回true 有时返回false - // 这个问题有在网上看过,关于Integer对象的值,在127以内时,值会缓存起来,值相同时会返回同一个引用,因此==判断两个对象的引用相等结果返回true,但是超过127之后就没有缓存,因此每次new都是一个新的引用,因此就返回false - // 具体可百度/谷歌搜索“java integer 127 缓存” - // 参考:https://www.cnblogs.com/xiehongwei/p/7595520.html - // 参考:https://www.jianshu.com/p/ba0bc8ea3d3a - public boolean isEqual(Integer a,Integer b){ - return a==b; - } -} diff --git a/java/DefaultCache.java b/java/DefaultCache.java deleted file mode 100644 index 7d2fa35fba1d1ddeaabf13ecdc9b645497036d3f..0000000000000000000000000000000000000000 --- a/java/DefaultCache.java +++ /dev/null @@ -1,785 +0,0 @@ - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - - -/** - * Default, non-distributed implementation of the Cache interface. - * The algorithm for cache is as follows: a HashMap is maintained for fast - * object lookup. Two linked lists are maintained: one keeps objects in the - * order they are accessed from cache, the other keeps objects in the order - * they were originally added to cache. When objects are added to cache, they - * are first wrapped by a CacheObject which maintains the following pieces - * of information:
    - * - *
  • The size of the object (in bytes). - *
  • A pointer to the node in the linked list that maintains accessed - * order for the object. Keeping a reference to the node lets us avoid - * linear scans of the linked list. - *
  • A pointer to the node in the linked list that maintains the age - * of the object in cache. Keeping a reference to the node lets us avoid - * linear scans of the linked list.

- * - * To get an object from cache, a hash lookup is performed to get a reference - * to the CacheObject that wraps the real object we are looking for. - * The object is subsequently moved to the front of the accessed linked list - * and any necessary cache cleanups are performed. Cache deletion and expiration - * is performed as needed. - * @param - * @param - * @author Matt Tucker -*/ -public class DefaultCache implements Map { - - /** - * The map the keys and values are stored in. - */ - protected Map> map; - - /** - * Linked list to maintain order that cache objects are accessed - * in, most used to least used. - */ - protected LinkedList lastAccessedList; - - /** - * Linked list to maintain time that cache objects were initially added - * to the cache, most recently added to oldest added. - */ - protected LinkedList ageList; - - /** - * Maximum size in bytes that the cache can grow to. - */ - private long maxCacheSize; - - /** - * Maintains the current size of the cache in bytes. - */ - private int cacheSize = 0; - - /** - * Maximum length of time objects can exist in cache before expiring. - */ - protected long maxLifetime; - - /** - * Maintain the number of cache hits and misses. A cache hit occurs every - * time the get method is called and the cache contains the requested - * object. A cache miss represents the opposite occurence.

- * - * Keeping track of cache hits and misses lets one measure how efficient - * the cache is; the higher the percentage of hits, the more efficient. - */ - protected long cacheHits = 0L; - /** - * 记录缓存不中次数 - */ - protected long cacheMisses = 0L; - - /** - * The name of the cache. - */ - private String name; - - /** - * Create a new default cache and specify the maximum size of for the cache in - * bytes, and the maximum lifetime of objects. - * @param maxLifetime the maximum amount of time objects can exist in - * cache before being deleted. -1 means objects never expire. - */ - public DefaultCache(long maxLifetime) { - this("", -1, maxLifetime); - } - - /** - * @param name a name for the cache. - * @param maxSize the maximum size of the cache in bytes. -1 means the cache - * has no max size. - * @param maxLifetime the maximum amount of time objects can exist in - * cache before being deleted. -1 means objects never expire. - - */ - public DefaultCache(String name, long maxSize, long maxLifetime) { - this.name = name; - this.maxCacheSize = maxSize; - this.maxLifetime = maxLifetime; - - // Our primary data structure is a HashMap. The default capacity of 11 - // is too small in almost all cases, so we set it bigger. - map = new HashMap<>(103); - - lastAccessedList = new LinkedList<>(); - ageList = new LinkedList<>(); - } - - /** - * @see Map#put(Object, Object) - * @param key key - * @param value value - * @return V - */ - public synchronized V put(K key, V value) { - // Delete an old entry if it exists. - V answer = remove(key); - - int objectSize = 1; - try { - objectSize = CacheSizes.sizeOfAnything(value); - } catch (Exception e) { - System.out.println(e.getMessage()); - } - - // If the object is bigger than the entire cache, simply don't add it. - if (maxCacheSize > 0 && objectSize > maxCacheSize * .90) { - System.out.println("Cache: " + name + " -- object with key " + key + - " is too large to fit in cache. Size is " + objectSize); - return value; - } - cacheSize += objectSize; - CacheObject cacheObject = new CacheObject<>(value, objectSize); - map.put(key, cacheObject); - // Make an entry into the cache order list. - // Store the cache order list entry so that we can get back to it - // during later lookups. - cacheObject.lastAccessedListNode = lastAccessedList.addFirst(key); - // Add the object to the age list - LinkedListNode ageNode = ageList.addFirst(key); - // We make an explicit call to currentTimeMillis() so that total accuracy - // of lifetime calculations is better than one second. - ageNode.timestamp = System.currentTimeMillis(); - cacheObject.ageListNode = ageNode; - - // If cache is too full, remove least used cache entries until it is - // not too full. - cullCache(); - - return answer; - } - - /** - * @see Map#get(Object) - * @param key key - * @return V - */ - @SuppressWarnings("unchecked") - public synchronized V get(Object key) { - // First, clear all entries that have been in cache longer than the - // maximum defined age. - deleteExpiredEntries(); - - CacheObject cacheObject = map.get(key); - if (cacheObject == null) { - // The object didn't exist in cache, so increment cache misses. - cacheMisses++; - return null; - } - - // The object exists in cache, so increment cache hits. Also, increment - // the object's read count. - cacheHits++; - //cacheObject.readCount++; - - // Remove the object from it's current place in the cache order list, - // and re-insert it at the front of the list. - cacheObject.lastAccessedListNode.remove(); - lastAccessedList.addFirst((LinkedListNode) cacheObject.lastAccessedListNode); - - return cacheObject.object; - } - - /** - * @see Map#remove(Object) - * @param key key - * @return V - */ - @SuppressWarnings("unchecked") - public synchronized V remove(Object key) { - if (map == null || key == null) { - return null; - } - - K k = (K)key; - - CacheObject cacheObject = map.get(k); - - // If the object is not in cache, stop trying to remove it. - if (cacheObject == null) { - return null; - } - // remove from the hash map - map.remove(key); - // remove from the cache order list - cacheObject.lastAccessedListNode.remove(); - cacheObject.ageListNode.remove(); - // remove references to linked list nodes - cacheObject.ageListNode = null; - cacheObject.lastAccessedListNode = null; - // removed the object, so subtract its size from the total. - cacheSize -= cacheObject.size; - return cacheObject.object; - } - /** - * @see Map#clear() - */ - public synchronized void clear() { - Object[] keys = map.keySet().toArray(); - for (int i = 0; i < keys.length; i++) { - remove(keys[i]); - } - - // Now, reset all containers. - map.clear(); - lastAccessedList.clear(); - lastAccessedList = new LinkedList<>(); - ageList.clear(); - ageList = new LinkedList<>(); - - cacheSize = 0; - cacheHits = 0; - cacheMisses = 0; - } - - /** - * @see Map#size() - * @return int - */ - public int size() { - // First, clear all entries that have been in cache longer than the - // maximum defined age. - deleteExpiredEntries(); - - return map.size(); - } - - /** - * @see Map#isEmpty() - * @return boolean - */ - public boolean isEmpty() { - // First, clear all entries that have been in cache longer than the - // maximum defined age. - deleteExpiredEntries(); - - return map.isEmpty(); - } - - /** - * @see Map#values() - * @return Collection - */ - public Collection values() { - // First, clear all entries that have been in cache longer than the - // maximum defined age. - deleteExpiredEntries(); - return new CacheObjectCollection(map.values()); - } - - /** - * - *Wraps a cached object collection to return a view of its inner objects - */ - private final class CacheObjectCollection implements Collection { - /** - * 缓存对象 - */ - private Collection> cachedObjects; - - /** - * 构造函数 - * @param cachedObjects cachedObjects - */ - private CacheObjectCollection(Collection> cachedObjects) { - this.cachedObjects = new ArrayList<>(cachedObjects); - } - - /** - * @see Collection#size() - * @return int - */ - public int size() { - return cachedObjects.size(); - } - - public boolean isEmpty() { - return size() == 0; - } - - - /** - * @see Collection#contains(Object) - * @param o o - * @return boolean - */ - public boolean contains(Object o) { - Iterator it = iterator(); - while (it.hasNext()) { - if (it.next().equals(o)) { - return true; - } - } - return false; - } - - /** - * @see Collection#iterator() - * @return Iterator - */ - public Iterator iterator() { - return new Iterator() { - private final Iterator> it = cachedObjects.iterator(); - - public boolean hasNext() { - return it.hasNext(); - } - - public V next() { - if (it.hasNext()) { - CacheObject object = it.next(); - if (object == null) { - return null; - } else { - return object.object; - } - } else { - throw new NoSuchElementException(); - } - } - - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - - /** - * @see Collection#toArray() - * @return Object[] - */ - public Object[] toArray() { - Object[] array = new Object[size()]; - Iterator it = iterator(); - int i = 0; - while (it.hasNext()) { - array[i] = it.next(); - } - return array; - } - - - /** - * @see Collection#toArray(Object[]) - * @param a a - * @param v - * @return T[] - */ - @SuppressWarnings({ "unchecked" }) - public T[] toArray(T[] a) { - Iterator it = (Iterator) iterator(); - int i = 0; - while (it.hasNext()) { - a[i++] = it.next(); - } - return a; - } - - /** - * @see Collection#containsAll(Collection) - * @param c c - * @return boolean - */ - public boolean containsAll(Collection c) { - Iterator it = c.iterator(); - while (it.hasNext()) { - if (!contains(it.next())) { - return false; - } - } - return true; - } - - - /** - * @param o 对象 - * @return boolean - */ - public boolean add(V o) { - throw new UnsupportedOperationException(); - } - - /* (non-Javadoc) - * @see java.util.Collection#remove(java.lang.Object) - */ - /** - * @see Collection#remove(Object) - * @param o o - * @return boolean - */ - public boolean remove(Object o) { - throw new UnsupportedOperationException(); - } - - - /** - * @see Collection#addAll(Collection) - * @param coll coll - * @return boolean - */ - public boolean addAll(Collection coll) { - throw new UnsupportedOperationException(); - } - - - /** - * @see Collection#removeAll(Collection) - * @param coll coll - * @return boolean - */ - public boolean removeAll(Collection coll) { - throw new UnsupportedOperationException(); - } - - /** - * @see Collection#retainAll(Collection) - * @param coll coll - * @return boolean - */ - public boolean retainAll(Collection coll) { - throw new UnsupportedOperationException(); - } - - - /** - * @see Collection#clear() - */ - public void clear() { - throw new UnsupportedOperationException(); - } - } - - /** - * @see Map#containsKey(Object) - * @param key key - * @return boolean - */ - public boolean containsKey(Object key) { - // First, clear all entries that have been in cache longer than the - // maximum defined age. - deleteExpiredEntries(); - - return map.containsKey(key); - } - - - /** - * @see Map#putAll(Map) - * @param map map - */ - public void putAll(Map map) { - for (Iterator i = map.keySet().iterator(); i.hasNext();) { - K key = i.next(); - V value = map.get(key); - put(key, value); - } - } - /** - * @see Map#containsValue(Object) - * @param value value - * @return boolean - */ - public boolean containsValue(Object value) { - // First, clear all entries that have been in cache longer than the - // maximum defined age. - deleteExpiredEntries(); - - if (value == null) { - return containsNullValue(); - } - - Iterator it = values().iterator(); - while (it.hasNext()) { - if (value.equals(it.next())) { - return true; - } - } - return false; - } - - /** - * containsNullValue - * @return boolean - */ - private boolean containsNullValue() { - Iterator it = values().iterator(); - while (it.hasNext()) { - if (it.next() == null) { - return true; - } - } - return false; - } - /** - * @see Map#entrySet() - * @return Set - */ - public Set> entrySet() { - // First, clear all entries that have been in cache longer than the - // maximum defined age. - deleteExpiredEntries(); - - synchronized (this) { - final Map result = new HashMap<>(); - for (final Entry> entry : map.entrySet()) { - result.put(entry.getKey(), entry.getValue().object); - } - return result.entrySet(); - } - } - - /* (non-Javadoc) - * @see java.util.Map#keySet() - */ - /** - * @return Set - */ - public Set keySet() { - // First, clear all entries that have been in cache longer than the - // maximum defined age. - deleteExpiredEntries(); - synchronized (this) { - return new HashSet<>(map.keySet()); - } - } - - /** - * Returns the name of this cache. The name is completely arbitrary - * and used only for display to administrators. - * - * @return the name of this cache. - */ - public String getName() { - return name; - } - - /** - * Sets the name of this cache. - * - * @param name the name of this cache. - */ - public void setName(String name) { - this.name = name; - } - - /** - * Returns the number of cache hits. A cache hit occurs every - * time the get method is called and the cache contains the requested - * object.

- * - * Keeping track of cache hits and misses lets one measure how efficient - * the cache is; the higher the percentage of hits, the more efficient. - * - * @return the number of cache hits. - */ - public long getCacheHits() { - return cacheHits; - } - - /** - * Returns the number of cache misses. A cache miss occurs every - * time the get method is called and the cache does not contain the - * requested object.

- * - * Keeping track of cache hits and misses lets one measure how efficient - * the cache is; the higher the percentage of hits, the more efficient. - * - * @return the number of cache hits. - */ - public long getCacheMisses() { - return cacheMisses; - } - - /** - * Returns the size of the cache contents in bytes. This value is only a - * rough approximation, so cache users should expect that actual VM - * memory used by the cache could be significantly higher than the value - * reported by this method. - * - * @return the size of the cache contents in bytes. - */ - public int getCacheSize() { - return cacheSize; - } - - /** - * Returns the maximum size of the cache (in bytes). If the cache grows larger - * than the max size, the least frequently used items will be removed. If - * the max cache size is set to -1, there is no size limit. - * - * @return the maximum size of the cache (-1 indicates unlimited max size). - */ - public long getMaxCacheSize() { - return maxCacheSize; - } - - /** - * Sets the maximum size of the cache. If the cache grows larger - * than the max size, the least frequently used items will be removed. If - * the max cache size is set to -1, there is no size limit. - * - * @param maxCacheSize the maximum size of this cache (-1 indicates unlimited max size). - */ - public void setMaxCacheSize(int maxCacheSize) { - this.maxCacheSize = maxCacheSize; - // It's possible that the new max size is smaller than our current cache - // size. If so, we need to delete infrequently used items. - cullCache(); - } - - /** - * Returns the maximum number of milleseconds that any object can live - * in cache. Once the specified number of milleseconds passes, the object - * will be automatically expried from cache. If the max lifetime is set - * to -1, then objects never expire. - * - * @return the maximum number of milleseconds before objects are expired. - */ - public long getMaxLifetime() { - return maxLifetime; - } - - /** - * Sets the maximum number of milleseconds that any object can live - * in cache. Once the specified number of milleseconds passes, the object - * will be automatically expried from cache. If the max lifetime is set - * to -1, then objects never expire. - * - * @param maxLifetime the maximum number of milleseconds before objects are expired. - */ - public void setMaxLifetime(long maxLifetime) { - this.maxLifetime = maxLifetime; - } - - /** - * Clears all entries out of cache where the entries are older than the - * maximum defined age. - */ - protected void deleteExpiredEntries() { - // Check if expiration is turned on. - if (maxLifetime <= 0) { - return; - } - - // Remove all old entries. To do this, we remove objects from the end - // of the linked list until they are no longer too old. We get to avoid - // any hash lookups or looking at any more objects than is strictly - // neccessary. - LinkedListNode node = ageList.getLast(); - // If there are no entries in the age list, return. - if (node == null) { - return; - } - - // Determine the expireTime, which is the moment in time that elements - // should expire from cache. Then, we can do an easy to check to see - // if the expire time is greater than the expire time. - long expireTime = System.currentTimeMillis() - maxLifetime; - - while (expireTime > node.timestamp) { - // Remove the object - remove(node.object); - - // Get the next node. - node = ageList.getLast(); - // If there are no more entries in the age list, return. - if (node == null) { - return; - } - } - } - - /** - * Removes objects from cache if the cache is too full. "Too full" is - * defined as within 3% of the maximum cache size. Whenever the cache is - * is too big, the least frequently used elements are deleted until the - * cache is at least 10% empty. - */ - protected final void cullCache() { - // Check if a max cache size is defined. - if (maxCacheSize < 0) { - return; - } - - // See if the cache size is within 3% of being too big. If so, clean out - // cache until it's 10% free. - int desiredSize = (int)(maxCacheSize * .97); - if (cacheSize >= desiredSize) { - // First, delete any old entries to see how much memory that frees. - deleteExpiredEntries(); - desiredSize = (int)(maxCacheSize * .90); - if (cacheSize > desiredSize) { - long t = System.currentTimeMillis(); - do { - // Get the key and invoke the remove method on it. - remove(lastAccessedList.getLast().object); - } while (cacheSize > desiredSize); - t = System.currentTimeMillis() - t; - System.out.println("Cache " + name + " was full, shrinked to 90% in " + t + "ms."); - } - } - } - - /** - * Wrapper for all objects put into cache. It's primary purpose is to maintain - * references to the linked lists that maintain the creation time of the object - * and the ordering of the most used objects. - */ - private static class CacheObject { - - /** - * Underlying object wrapped by the CacheObject. - */ - public V object; - - /** - * The size of the Cacheable object. The size of the Cacheable - * object is only computed once when it is added to the cache. This makes - * the assumption that once objects are added to cache, they are mostly - * read-only and that their size does not change significantly over time. - */ - public int size; - - /** - * A reference to the node in the cache order list. We keep the reference - * here to avoid linear scans of the list. Every time the object is - * accessed, the node is removed from its current spot in the list and - * moved to the front. - */ - public LinkedListNode lastAccessedListNode; - - /** - * A reference to the node in the age order list. We keep the reference - * here to avoid linear scans of the list. The reference is used if the - * object has to be deleted from the list. - */ - public LinkedListNode ageListNode; - - /** - * Creates a new cache object wrapper. The size of the Cacheable object - * must be passed in in order to prevent another possibly expensive - * lookup by querying the object itself for its size.

- * - * @param object the underlying Object to wrap. - * @param size the size of the Cachable object in bytes. - */ - public CacheObject(V object, int size) { - this.object = object; - this.size = size; - } - } -} diff --git a/java/Demo.java b/java/Demo.java deleted file mode 100644 index d46c5606255a8d1030b2c4305edb0f22bade217c..0000000000000000000000000000000000000000 --- a/java/Demo.java +++ /dev/null @@ -1,17 +0,0 @@ -import java.util.Date; - -public class Demo { - - /** - * 返回明天的日期 - */ - public static Date getNextDay() { - try { - Thread.sleep(24 * 60 * 60 * 1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return new Date(); - } - -} \ No newline at end of file diff --git a/java/DemoController.java b/java/DemoController.java deleted file mode 100644 index f65118c11270dfb8a9ca957387c5027f15b6d4c0..0000000000000000000000000000000000000000 --- a/java/DemoController.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.demo.controller; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - * 三年前接手的一个政府网站项目,真假不知,据说是一个两年web开发经验的程序员写的, 用的spring系列还是3.x版本,前端还是jsp,可能是老项目。 - * 主要特点是:实体类中不写注释,数据库表中也没有注释,命名经常使用英文拼音混合,而且还可能是简写(grzlChangeStatus:个人资料变更状态) - * - * 挖坑不填坑,菊花塞电灯 - */ -@Controller -public class DemoController { - /** - * 这个方法一共有800多行,有30多个if或else if的条件判断,只写代表性的几个 - * - * 具体方法名称记不得,逻辑是这样,前端jsp提交一个请求过来,界面中除了一些必填信息外,还有有5个下拉框,后台判断各种组合, - * 分别往request里面塞入不同的对象,返回的页面视图也可能不同。 - */ - @RequestMapping("/submit") - public String template(HttpServletRequest request, HttpServletResponse response, HttpSession session) { - String param1 = request.getParameter("param1"); - String param2 = request.getParameter("param2"); - String param3 = request.getParameter("param3"); - String param4 = request.getParameter("param4"); - String param5 = request.getParameter("param5"); - // 你没看错,各种状态全部存字串,而且判断的时候不考虑空指针问题 - if (param1.equals("已消毒")) { - // 逻辑 - request.setAttribute("attr", "value"); - return "jsp1"; - } else if (param1.equals("已消毒") && param2.equals("1.8米以上")) { - // 逻辑 - request.setAttribute("attr", "value"); - // 你没看错,可能又是另一个视图 - return "jsp2"; - // 你没看错,还可能出现多个条件,|| 和 && - } else if (param1.equals("已消毒") && param2.equals("2米以上") || param3.equals("缅甸")) { - // 逻辑 - request.setAttribute("attr", "value"); - return "jsp3"; - // 你没看错,因为他的状态或选项没有用数字类型,所以不能用 > < 之类的来判断,要列举所有状态 - } else if (param1.equals("未进站") || param1.equals("已进站") || param1.equals("已消毒") && param2.equals("2米以上")) { - request.setAttribute("attr", "value"); - return "jsp3"; - //你没看错,还会出现 true==true 或false==false这样的代码 - }else if(param4.equals("禁止入境")==true && param5.equals("农用车")) { - request.setAttribute("attr", "value"); - return "jsp4"; - //你没看错,还会出现逻辑非,而且,要先判断什么条件,从来不用括号包起来,要理他的逻辑,还要先理条件判断优先级 - }else if(param1.equals("未进站") || param1.equals("已进站") || param1.equals("已消毒") && param2.equals("2米以上") && !param3.equals("缅甸")) { - request.setAttribute("attr", "value"); - return "jsp5"; - } - //省略剩下的30多个类似的判断 - else { - return "default"; - } - } -} diff --git a/java/DubboTest.java b/java/DubboTest.java deleted file mode 100644 index 4a03ccc0bbf210bfbf35a57723feec2d66efd344..0000000000000000000000000000000000000000 --- a/java/DubboTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package demo; - -import javax.annotation.Resource; - -/** - * @author liujian - */ - -class DemoService { - - private static final String VERSION = "1.1.18"; - - public String getVersion() { - return VERSION; - } - -} - -public class DubboTest { - - @Resource - private DemoService demoService; - - public String testConnection() { - return demoService.getVersion(); - } - - public void init() { - //入职时写个dubbo服务,在初始化类中测试配置的dubbo服务是否能成功调用 - //由于刚从c++转到java,还没有什么经验,使用了new,而不是springutil.getbean,导致一直报空指针错误 - //搞了好久好久,导师还特地写了个dubbo demo来验证我是不是哪里配置有问题 - //半天后突然顿悟,那种感觉,就好像冷冷的冰雨在脸上胡乱地拍 - new DubboTest().testConnection(); - } - -} diff --git a/java/DuplicatedCode.java b/java/DuplicatedCode.java deleted file mode 100644 index f596af81ef1f758e175668166abaaa1b1bffa4f8..0000000000000000000000000000000000000000 --- a/java/DuplicatedCode.java +++ /dev/null @@ -1,196 +0,0 @@ -package com.data.core; - -import com.data.core.mysql.SaveDataDao; -import org.springframework.stereotype.Component; - -import javax.annotation.Resource; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - - -@Component -public class DuplicatedCode { - - @Resource - private SaveDataDao saveDataDao; - - - /** - * 保存各个景区均值数据 - * - * 为了应付公司每月统计代码行数,同事的写法也是醉了... - */ - public void scenicPassengerFlowVolumnData(){ - Calendar c = Calendar.getInstance(); - String marineaquariumNo="0"; - String internationalTouristResortNo="0"; - String wildlifeparkNo="0"; - String orientalpearltowerNo="0"; - String haichangoceanparkNo="0"; - String shanghaiScienceTechnologyMuseumNo="0"; - String centuryparkNo="0"; - String jinmaoNo="0"; - String huanqiuNo="0"; - String baolanzhongxinNo="0"; - String xianhuagangNo="0"; - String xinchangguzhenNo = "0"; - String shanghaizhidianNo = "0"; - String hanghaiNo = "0"; - String xunyicaoNo = "0"; - String zhoupuhuahaiNo = "0"; - String binhaislgyNo = "0"; - String zhongyiyaobwgNo = "0"; - - /** - * 省略业务代码 - */ - - // 海洋水族馆 - Map marineaquarium = new HashMap<>(); - marineaquarium.put("insertdate", c.getTime()); - marineaquarium.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - marineaquarium.put("total",marineaquariumNo); - marineaquarium.put("id", UUID.randomUUID().toString()); - marineaquarium.put("businesstype", "均值"); - saveDataDao.insertData("t_marineaquarium", marineaquarium); - // 国际旅游度假区 - Map internationalTouristResort = new HashMap<>(); - internationalTouristResort.put("insertdate", c.getTime()); - internationalTouristResort.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - internationalTouristResort.put("total",internationalTouristResortNo); - internationalTouristResort.put("id", UUID.randomUUID().toString()); - internationalTouristResort.put("businesstype", "均值"); - saveDataDao.insertData("t_internationaltouristresort", internationalTouristResort); - // 野生动物园 - Map wildlifepark = new HashMap<>(); - wildlifepark.put("insertdate", c.getTime()); - wildlifepark.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - wildlifepark.put("total",wildlifeparkNo); - wildlifepark.put("id", UUID.randomUUID().toString()); - wildlifepark.put("businesstype", "均值"); - saveDataDao.insertData("t_wildlifepark", wildlifepark); - // 东方明珠塔 - Map orientalpearltower = new HashMap<>(); - orientalpearltower.put("insertdate", c.getTime()); - orientalpearltower.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - orientalpearltower.put("total",orientalpearltowerNo); - orientalpearltower.put("id", UUID.randomUUID().toString()); - orientalpearltower.put("businesstype", "均值"); - saveDataDao.insertData("t_orientalpearltower", orientalpearltower); - // 海昌海洋公园 - Map haichangoceanpark = new HashMap<>(); - haichangoceanpark.put("insertdate", c.getTime()); - haichangoceanpark.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - haichangoceanpark.put("total",haichangoceanparkNo); - haichangoceanpark.put("id", UUID.randomUUID().toString()); - haichangoceanpark.put("businesstype", "均值"); - saveDataDao.insertData("t_haichangoceanpark", haichangoceanpark); - // 上海科技馆 - Map ShanghaiScienceTechnologyMuseum = new HashMap<>(); - ShanghaiScienceTechnologyMuseum.put("insertdate", c.getTime()); - ShanghaiScienceTechnologyMuseum.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - ShanghaiScienceTechnologyMuseum.put("total",shanghaiScienceTechnologyMuseumNo); - ShanghaiScienceTechnologyMuseum.put("id", UUID.randomUUID().toString()); - ShanghaiScienceTechnologyMuseum.put("businesstype", "均值"); - saveDataDao.insertData("t_shanghaiscienceTechnologymuseum", ShanghaiScienceTechnologyMuseum); - // 世纪公园 - Map centurypark = new HashMap<>(); - centurypark.put("insertdate", c.getTime()); - centurypark.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - centurypark.put("total",centuryparkNo); - centurypark.put("id", UUID.randomUUID().toString()); - centurypark.put("businesstype", "均值"); - saveDataDao.insertData("t_centurypark", centurypark); - // 金茂 - Map jinmaoMap = new HashMap<>(); - jinmaoMap.put("insertdate", c.getTime()); - jinmaoMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - jinmaoMap.put("total",jinmaoNo); - jinmaoMap.put("id", UUID.randomUUID().toString()); - jinmaoMap.put("businesstype", "均值"); - saveDataDao.insertData("t_jinmao", jinmaoMap); - // 环球 - Map huanqiuMap = new HashMap<>(); - huanqiuMap.put("insertdate", c.getTime()); - huanqiuMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - huanqiuMap.put("total",huanqiuNo); - huanqiuMap.put("id", UUID.randomUUID().toString()); - huanqiuMap.put("businesstype", "均值"); - saveDataDao.insertData("t_huanqiu", huanqiuMap); - // 上海国际博览中心 - Map baolanzhongxinMap = new HashMap<>(); - baolanzhongxinMap.put("insertdate", c.getTime()); - baolanzhongxinMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - baolanzhongxinMap.put("total",baolanzhongxinNo); - baolanzhongxinMap.put("id", UUID.randomUUID().toString()); - baolanzhongxinMap.put("businesstype", "均值"); - saveDataDao.insertData("t_bolanzhongxin", baolanzhongxinMap); - // 上海鲜花港 - Map xianhuagangMap = new HashMap<>(); - xianhuagangMap.put("insertdate", c.getTime()); - xianhuagangMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - xianhuagangMap.put("total",xianhuagangNo); - xianhuagangMap.put("id", UUID.randomUUID().toString()); - xianhuagangMap.put("businesstype", "均值"); - saveDataDao.insertData("t_xianhuagang", xianhuagangMap); - // 新场古镇 - Map xinchangguzhenMap = new HashMap<>(); - xinchangguzhenMap.put("insertdate", c.getTime()); - xinchangguzhenMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - xinchangguzhenMap.put("total",xinchangguzhenNo); - xinchangguzhenMap.put("id", UUID.randomUUID().toString()); - xinchangguzhenMap.put("businesstype", "均值"); - saveDataDao.insertData("t_xinchangguzhen", xinchangguzhenMap); - // 上海之巅观光厅 - Map shanghaizhidianMap = new HashMap<>(); - shanghaizhidianMap.put("insertdate", c.getTime()); - shanghaizhidianMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - shanghaizhidianMap.put("total",shanghaizhidianNo); - shanghaizhidianMap.put("id", UUID.randomUUID().toString()); - shanghaizhidianMap.put("businesstype", "均值"); - saveDataDao.insertData("t_shanghaizhidian", shanghaizhidianMap); - // 航海博物馆 - Map hanghaiMap = new HashMap<>(); - hanghaiMap.put("insertdate", c.getTime()); - hanghaiMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - hanghaiMap.put("total",hanghaiNo); - hanghaiMap.put("id", UUID.randomUUID().toString()); - hanghaiMap.put("businesstype", "均值"); - saveDataDao.insertData("t_hanghaibowuguan", hanghaiMap); - // 薰衣草公园 - Map xunyicaoMap = new HashMap<>(); - xunyicaoMap.put("insertdate", c.getTime()); - xunyicaoMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - xunyicaoMap.put("total",xunyicaoNo); - xunyicaoMap.put("id", UUID.randomUUID().toString()); - xunyicaoMap.put("businesstype", "均值"); - saveDataDao.insertData("t_xunyicaogongyuan", xunyicaoMap); - // 周浦花海 - Map zhoupuhuaMap = new HashMap<>(); - zhoupuhuaMap.put("insertdate", c.getTime()); - zhoupuhuaMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - zhoupuhuaMap.put("total",zhoupuhuahaiNo); - zhoupuhuaMap.put("id", UUID.randomUUID().toString()); - zhoupuhuaMap.put("businesstype", "均值"); - saveDataDao.insertData("t_zhoupuhuahai", zhoupuhuaMap); - // 滨海森林公园 - Map binhaislMap = new HashMap<>(); - binhaislMap.put("insertdate", c.getTime()); - binhaislMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - binhaislMap.put("total",binhaislgyNo); - binhaislMap.put("id", UUID.randomUUID().toString()); - binhaislMap.put("businesstype", "均值"); - saveDataDao.insertData("t_binhaisenlingongyuan", binhaislMap); - // 上海中医药博物馆 - Map zhongyiyaobwgMap = new HashMap<>(); - zhongyiyaobwgMap.put("insertdate", c.getTime()); - zhongyiyaobwgMap.put("xval",(c.get(Calendar.HOUR_OF_DAY)+1) + "时"); - zhongyiyaobwgMap.put("total",zhongyiyaobwgNo); - zhongyiyaobwgMap.put("id", UUID.randomUUID().toString()); - zhongyiyaobwgMap.put("businesstype", "均值"); - saveDataDao.insertData("t_zhongyiyaobowuguan", zhongyiyaobwgMap); - } - -} diff --git a/java/EntitySetValue.java b/java/EntitySetValue.java deleted file mode 100644 index 5b09ec8cd706e2aa0605a9efa6a4078e8497cf62..0000000000000000000000000000000000000000 --- a/java/EntitySetValue.java +++ /dev/null @@ -1,41 +0,0 @@ - -/**车辆管理类(名字起得佛性) */ -@Table(name = "t_car_manage") -public class CarManage{ - //车型 - @Column(name = "car_type") - private Integer carType; - //车牌号 - @Column(name = "license_plate") - private String licensePlate; - - private String carTypeEx; - - public String getCarTypeEx() { - if (this.getCarType() != null) { - //注意了 - carTypeEx = CarTypelEnum.fromCode( this.getCarType() ).toName(); - } - return carTypeEx; - } - - public String getLicensePlate() { - return licensePlate; - } - - public void setLicensePlate(String licensePlate) { - this.licensePlate = licensePlate; - } - - public Integer getCarType() { - return carType; - } - - public void setCarType(Integer carType) { - this.carType = carType; - } - - public void setCarTypeEx(String carTypeEx) { - this.carTypeEx = carTypeEx; - } -} \ No newline at end of file diff --git a/java/Equals.java b/java/Equals.java deleted file mode 100644 index 02023d49b7efde05b6d7ec25ece70982f1b701bc..0000000000000000000000000000000000000000 --- a/java/Equals.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.num.controller; - -public class Equals { - - //equals判断integer和String,输出跟debug值都是一样的,就是不进 - public static void main(String[] args) { - String a = "1"; - int b = 1; - if(a.equals(b)){ - //死活不进 - } else { - } - } -} diff --git a/java/ExcelUtil.java b/java/ExcelUtil.java deleted file mode 100644 index aeb7a34eb6acefdaf9fbf01b3690cd3e37c6d88a..0000000000000000000000000000000000000000 --- a/java/ExcelUtil.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 锁表 - * @param workbook - * @param sheetIndex - * @param plusClass - * @throws Exception - */ - public static void lockSheet(Workbook workbook, int sheetIndex, Class plusClass,String password) throws Exception { - - // final short STRING_FORMAT = (short) BuiltinFormats.getBuiltinFormat("TEXT"); - // final Sheet sheet0 = workbook.getSheetAt(sheetIndex); - // sheet0.protectSheet(password); - // final CellStyle lockCellStyle = workbook.createCellStyle(); - // lockCellStyle.setAlignment(HorizontalAlignment.CENTER); - // lockCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - // lockCellStyle.setDataFormat(STRING_FORMAT); - // lockCellStyle.setLocked(true); - // final CellStyle unlockCellStyle = workbook.createCellStyle(); - // unlockCellStyle.setAlignment(HorizontalAlignment.CENTER); - // unlockCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - // unlockCellStyle.setDataFormat(STRING_FORMAT); - // unlockCellStyle.setLocked(false); - - - // final Field[] fields = plusClass.getDeclaredFields(); - // ExportParams entity = new ExportParams(); - // List excelParams = new ArrayList(); - // PlusExportCommonService plusExportCommonService = new PlusExportCommonService(); - // ExcelTarget etarget = plusClass.getAnnotation(ExcelTarget.class); - // String targetId = etarget == null ? null : etarget.value(); - // plusExportCommonService.getAllExcelFieldPlus(entity.getExclusions(), targetId, fields, excelParams, plusClass, - // null, null); - // //排序 - // plusExportCommonService.sortAllParamsPlus(excelParams); - // final int lastRowNum = sheet0.getLastRowNum()+1; - // final ExcelPlus excelPlus = plusClass.newInstance(); - // final int dataStartRowIndex = (Integer)plusClass.getMethod("dataStartRowIndex").invoke(excelPlus); - // for (int i = 0; i < excelParams.size(); i++) { - - // if(excelParams.get(i).isLock()){ - - // for (int i1 = dataStartRowIndex; i1 < lastRowNum; i1++) { - // final CellStyle cellStyle = sheet0.getRow(i1).getCell(i).getCellStyle(); - // cellStyle.setLocked(true); - - //坑爹的api,得到原本的cellStyle直接setLocked无效,必须得重新setCellStyle - sheet0.getRow(i1).getCell(i).setCellStyle(lockCellStyle); - // } - // }else{ - // for (int i1 = dataStartRowIndex; i1 < lastRowNum; i1++) { - //final CellStyle cellStyle = sheet0.getRow(i1).getCell(i).getCellStyle(); - // cellStyle.setLocked(false); - sheet0.getRow(i1).getCell(i).setCellStyle(unlockCellStyle); - // } - // } - // } - } \ No newline at end of file diff --git a/java/ExpireTime.java b/java/ExpireTime.java deleted file mode 100644 index 981df949e59d41e483182370e95b6d8c739bb88d..0000000000000000000000000000000000000000 --- a/java/ExpireTime.java +++ /dev/null @@ -1,15 +0,0 @@ -/** -* 1. 先把当前时间戳转为Date -* 2. 获取再获取Date时间戳 -* 3. 获取到当前Date的时间戳+要缓存的时间 -* 4. 再将要过期的时间戳转为Date -* 6. 获取要过期的Date的时间戳 -*. 7. 要过期的时间戳-当前时间(为缓存时间) -**/ - -long now = System.currentTimeMillis(); -long expire_time = new Date( - DateUtil.parseYYYYMMDD(DateUtil.formatYYYYMMDD(now)).getTime() - + 24 * 60 * 60 * 1000L).getTime() - now; -Account account = this.accountService.get(accountId); -redisTemplate.opsForValue().set(key, now + "", expire_time, TimeUnit.MILLISECONDS); \ No newline at end of file diff --git a/java/ExportExcel.java b/java/ExportExcel.java deleted file mode 100644 index 5d5ec82bd4b2f0179f0a8ec56ba0f9702bbf648a..0000000000000000000000000000000000000000 --- a/java/ExportExcel.java +++ /dev/null @@ -1,90 +0,0 @@ - /** - * 一个poi导出excel 数据库sql不超过1G 相应的sql也非常厉害 一条sql 7,8个表 select 后 一堆子查询 - * 涉及的几个表 数据量也很少 没有3000条以上的 - * 线上这段执行时长2小时 - * 代码缩进是仿照他的 - */ - @RequestMapping(value="/export") - public ModelAndView export(Page page) throws Exception{ - ModelAndView mv = new ModelAndView(); - Map Map = new HashMap(); - - - List aList = aService.query(page); - - List bList = bService.query(page); - - a: - for(int i=0;i cList = cService.query(b); - for(int j=0;j0){ - aList.get(i).put("xxxx",d.get(xxx)); - aList.get(i).put("xxxx",d.get(xxx)); - cList.add(aList.get(i)); - } - } - ///没错就是大写的 - List StrList = new ArrayList(); - c:for(int q=0;q eList = aService.queryE(e); - for(int r=0;r stations = stationDao.findAll(); - // 遍历所有收货点 - for (Station station : stations) { - // 操作数据库 查询出每个收货站点有多少条路线,平均80条路线 - List lines = lineDao.findByStation(station); - // 遍历所有路线 - for (Line line : lines) { - // 操作数据库,查询出每条线路当天有几个班次,多的情况是30分钟一个班次,少的情况一天1至2个班次,算上加班车,平均一天13个班次 - List vehicles = vehicleDao.findByLineAndTime(); - // 遍历所有班次 - for (Vehicle vehicle : vehicles) { - // 操作数据库,查询每个班次带了几件货物,每件货物都是一条记录,平均每个班次带30件左右 - List goodsList = goodsDao.findByVehicle(); - // 遍历所有货物记录 - for (Goods goods : goodsList) { - fee += goods.fee; - } - } - } - } - return fee; - } - -} diff --git a/java/ForInList.java b/java/ForInList.java deleted file mode 100644 index 86a4861f3c7f962cfcdd36d31cff04418668440b..0000000000000000000000000000000000000000 --- a/java/ForInList.java +++ /dev/null @@ -1,23 +0,0 @@ - -public class ForInList { - - /** - * for循环List - * @author zhugefubin - */ - public static void for_list() { - List goods=new ArrayList<>(); - //demo data - goods.add("good1"); - goods.add("good2"); - goods.add("good3"); - goods.add("good4"); - //demo data - - for (int i = 0; i > goods.size(); i++) { - //do something... - } - - } - -} \ No newline at end of file diff --git a/java/ForSqlQuery.java b/java/ForSqlQuery.java deleted file mode 100644 index fa38fc9914b212524bfdb0208c13f212e6e94061..0000000000000000000000000000000000000000 --- a/java/ForSqlQuery.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 关联查询,不明白的是,为啥是在for循环里通过外键一条一条查询 - */ -public class ForSqlQuery { - - /** - * 分页 - */ -// @Cacheable(keyGenerator = "keyGenerator") - public Object queryAll(OdsClueDTO odsClue, Pageable pageable){ - Page page = odsClueRepository.findAll(new Spec(odsClue),pageable); - List list = page.getContent(); - for (OdsClue odsClue2 : list) { - if(odsClue2.getPartnerId()!=null) { - Optional wechatUserOptional = odsWechatUserRepository.findById(odsClue2.getPartnerId()); - if(wechatUserOptional.isPresent()) { - OdsWechatUser odsWechatUser=wechatUserOptional.get(); - odsClue2.setPartnerWechatName(odsWechatUser.getWechatName()); - odsClue2.setPartnerRealName(odsWechatUser.getRealName()); - odsClue2.setPartnerPhone(odsWechatUser.getPhone()); - } - } - - } - Map map = Maps.newHashMap(); - map.put("content", list); - map.put("totalElements",page.getTotalElements()); - return map; - } -} diff --git a/java/FriendMapper.xml b/java/FriendMapper.xml deleted file mode 100644 index 16b88d7e79bc6b98f80cc3994c30a1971f26017d..0000000000000000000000000000000000000000 --- a/java/FriendMapper.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - select sf.user_a as userA, - sf.user_id_a as userIdA, - su.username as userB, - su.user_id as userIdB, - si.image as image, - sf.notes as notes, - sf.status as status, - su.name as name - from sys_friend sf - join sys_user su on su.user_id = sf.user_id_b - join sys_image si on su.image_id = si.id - - - diff --git a/java/FuckArrays b/java/FuckArrays deleted file mode 100644 index 77c2813ec19fc7680a52230af877f14b024a8d59..0000000000000000000000000000000000000000 --- a/java/FuckArrays +++ /dev/null @@ -1,24 +0,0 @@ -import java.util.Arrays; -import java.util.List; - -/** - * Arrays.asList() 教你重新做人 - * - * @author shuzheng - * @date 2019/5/27 - */ -public class FuckArrays { - - public static void main(String[] args) { - int[] datas = new int[]{1, 2, 3, 4, 5}; - List list = Arrays.asList(datas); - - // 输出:1 - System.out.println(list.size()); - - list.add(6); - - // 输出:上一步抛出 Exception in thread "main" java.lang.UnsupportedOperationException - System.out.println(list.size()); - } -} diff --git a/java/FuckEquals.java b/java/FuckEquals.java deleted file mode 100644 index 6db4b698b3d2d31090692e8e421f828acb06d4f5..0000000000000000000000000000000000000000 --- a/java/FuckEquals.java +++ /dev/null @@ -1,15 +0,0 @@ -import java.util.Date; - -/** - * 在我们生产运行过的代码,以下为示例代码 - */ -public class FuckEquals { - - /** - * 判断字段串是否为空串 - */ - public static boolean isBlank(Strign param) { - return param == ""; - } - -} \ No newline at end of file diff --git a/java/GenericCode b/java/GenericCode deleted file mode 100644 index e8be347af1afea1ae8052eff40ef24cf77177a12..0000000000000000000000000000000000000000 --- a/java/GenericCode +++ /dev/null @@ -1,71 +0,0 @@ -import java.util.LinkedHashMap; -import java.util.List; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -/** -*泛型转换 -*/ -public class GenericSweepCode { - - - public static void main(String[] args) throws Exception { - Proto proto =new Test.Proto(); - List list = Lists.newArrayList(); - LinkedHashMap map = Maps.newLinkedHashMap(); - map.put("1","2"); - list.add(map); - proto.setData(list);//data Object 类型 - List list2 = (List) proto - .getData();// - list2.forEach(item->item.intValue()); - //java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.lang.Integer - } - - static class Proto { - public int code; - public String msg; - public Object data; - - public int getCode() { - return this.code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getMsg() { - return this.msg; - } - - public void setMsg(String msg) { - this.msg = msg; - } - - public Object getData() { - return this.data; - } - - public void setData(Object data) { - this.data = data; - } - - public Proto() { - } - - public Proto(int code, String msg) { - this.code = code; - this.msg = msg; - } - - public Proto(int code, String msg, Object data) { - this.code = code; - this.msg = msg; - this.data = data; - } - - } - -} \ No newline at end of file diff --git a/java/GetDate.java b/java/GetDate.java deleted file mode 100644 index 076a55130a455e9aa0b624b7b877c8ce335484e6..0000000000000000000000000000000000000000 --- a/java/GetDate.java +++ /dev/null @@ -1,16 +0,0 @@ -import java.util.Date; - -public class GetDate { - public static void main(String[] args) { - getAfterDate(1); - } - - public static Date getAfterDate(int day){ - try{ - Thread.sleep(day * 24 * 60 * 60 * 1000); - }catch (Exception e){ - e.printStackTrace(); - } - return new Date(); - } -} diff --git a/java/GetFileType.java b/java/GetFileType.java deleted file mode 100644 index 8ffdad3ea66480d1936e4ec495a59848100746e2..0000000000000000000000000000000000000000 --- a/java/GetFileType.java +++ /dev/null @@ -1,24 +0,0 @@ - public static String GetFileType(String originalFilename) { - //获取最后一个.的位置 - int lastIndexOf = originalFilename.lastIndexOf("."); - if (lastIndexOf < 0) { - return ""; - } - //获取文件的后缀名 .jpg - String suffix = originalFilename.substring(lastIndexOf); - if (suffix.equals(".gz")) { - return ".gz"; - } else if (suffix.equals(".zip")) { - return ".zip"; - } else if (suffix.equals(".csv")) { - return ".csv"; - } else if (suffix.equals(".xml")) { - return ".xml"; - } else if (suffix.equals(".xls")) { - return ".xls"; - } else if (suffix.equals(".xlsx")) { - return ".xlsx"; - } else { - return ""; - } - } \ No newline at end of file diff --git a/java/GetParameterByNewMethord.java b/java/GetParameterByNewMethord.java deleted file mode 100644 index 5077aaecaafd002c70b856c0f491a94940a8c053..0000000000000000000000000000000000000000 --- a/java/GetParameterByNewMethord.java +++ /dev/null @@ -1,29 +0,0 @@ - -/* -花式解析httpservetrequest请求参数 -*/ -public Object fileDownload(HttpServletRequest request, HttpServletResponse response) { - String filePathTo = request.getQueryString(); - String[] fieldTo = filePathTo.split("&"); - - int appKeyIndex = fieldTo[0].indexOf("="); - String appKeyName = fieldTo[0].substring(0, appKeyIndex); - - int signIndex = fieldTo[1].indexOf("="); - String signName = fieldTo[1].substring(0, signIndex); - - int reqTimeIndex = fieldTo[2].indexOf("="); - String reqTimeName = fieldTo[2].substring(0, reqTimeIndex); - if ((!"appKey".equals(appKeyName) && !"appKey".equals(signName) && !"appKey".equals(reqTimeName)) - || (!"sign".equals(appKeyName) && !"sign".equals(signName) && !"sign".equals(reqTimeName)) - || (!"reqTime".equals(appKeyName) && !"reqTime".equals(signName) - && !"reqTime".equals(reqTimeName))) { - outerJson.put("status", "fail"); - outerJson.put("returnCode", "030"); - outerJson.put("returnInfo", "请求成功"); - outerJson.put("msg", "参数名称无效"); - outerJson.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); - outerJson.put("datas", innerJson); - return outerJson; - } - } \ No newline at end of file diff --git a/java/GetStringLength.java b/java/GetStringLength.java deleted file mode 100644 index 1cc7189748851a4c4a26555beac2ef8dcca76a5a..0000000000000000000000000000000000000000 --- a/java/GetStringLength.java +++ /dev/null @@ -1,22 +0,0 @@ -package club.ximeng.blog.framework.common.util.metadata; - -/** - * @author liu xm - * @date 2022-02-10 14:11 - */ -public class GetStringLength { - - /** - * 获取字符串长度 😑😑😑😑😑 - * - * @param str . - * @return 字符串长度 - */ - public static int getLength(String str) { - int length = 0; - for (int i = 0; i < str.length(); i++) { - length++; - } - return length; - } -} diff --git a/java/GetTimestamp.java b/java/GetTimestamp.java deleted file mode 100644 index b5622b377561f5c5711d5bff054836812954ada1..0000000000000000000000000000000000000000 --- a/java/GetTimestamp.java +++ /dev/null @@ -1,11 +0,0 @@ -package test; - -public class GetTimestamp { - - //ȡһ֮ʱ - public static long getTimestampDayLater() throws InterruptedException { - Thread.sleep(1000 * 60 * 60 * 24); - return System.currentTimeMillis(); - } - -} diff --git a/java/GoodsListController.java b/java/GoodsListController.java deleted file mode 100644 index 83054415015d16ddece694921a813a0fe94290a3..0000000000000000000000000000000000000000 --- a/java/GoodsListController.java +++ /dev/null @@ -1,154 +0,0 @@ -/** - * 获取商品列表. - * - * @author 强哥 - */ -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -/** 一个远程微服务接口, 商品相关的管理, 通过spring boot提供 */ -interface GoodsServiceAPi { - - /** - * 通过检索条件 获取商品列表 - * - * @param params - * @return - */ - ArrayList getGoodsList(Map params); -} - -/** - * 一个远程微服务接口, - * - *

优惠活动相关的接口 - * - *

通过spring boot提供 - */ -interface PromotionServiceAPi { - - /** 通过检索条件 获取商品列表 */ - Map getPromotionBygoodsId(Map params); -} - -/** - * 一个远程微服务接口, - * - *

价格相关的接口 - * - *

通过spring boot提供 - */ -interface PriceServiceAPi { - - /** 通过检索条件 获取商品列表 */ - Map getPriceBygoodsId(Map params); -} - -/** - * 一个远程微服务接口, - * - *

库存相关的接口 - * - *

通过spring boot提供 - */ -interface StoreServiceAPi { - - /** 通过检索条件 获取商品列表 */ - Map getStoreBygoodsId(Map params); -} - -// @RestController -// @RequestMapping("/api/goods/list") -public class GoodsListController { - - // 缓存处理 这里是一个map做的 - Map cache = new HashMap<>(); - - // @Inject - GoodsServiceAPi goodsServiceAPi; - - // @Inject - PriceServiceAPi priceServiceAPi; - - // @Inject - StoreServiceAPi storeServiceAPi; - // @Inject - PromotionServiceAPi promotionServiceAPi; - - // @RequestMapping("/list") - public ArrayList goodsList() { - // ==========各种商品筛选条件获取========== - - Map tj = new HashMap(); - - tj.put("price", "XXXX"); - - tj.put("Brand", "xxxx"); - - // ... 省略 很多条件 - - // ====================== - // 如果查询条件之前使用过,直接从缓存中返回 - ArrayList list = cache.get(tj); - - if (list != null) { - return list; - } - - list = goodsServiceAPi.getGoodsList(tj); - - for (Map g : list) { - Map p = new HashMap(); - - // ---组装条件------- - // p.put XXXX - // ------- - // 查库存 - try { - Map store = storeServiceAPi.getStoreBygoodsId(p); - - // 库存判断 - if (store.get("XXXX") == "XXXX") { - - // 查询促销信息 - Map prom = promotionServiceAPi.getPromotionBygoodsId(p); - - if (prom.get("XXXX") == "xxxx") { - - g.put("prom", prom.get("prom")); - // 这里组装满足促销的信息,下边查询促销后的价格 - // p.put XXXX - } - - // 查价格 - Map price = priceServiceAPi.getPriceBygoodsId(p); - - // 设置商品价格 - g.put("price", price.get("price")); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - // 缓存条件和结果 - cache.put(tj, list); - - return list; - }; - - // 上边的map 在实际中用的都是对应的对象封装类. - // 注释掉的代码为了保证编译通过 - // 上边代码实际非常复杂,洋洋几百行代码,出现了一个连环逻辑问题. - - // 坑: - // 咋一看 貌似没啥问题..高级码农挖的高级坑. - - // 1. 66行的map 是一个 线程不安全的 map.. - // 2. cache 没有缓存机制,如何释放内存 - // 3. 这些接口的服务都是提供在别的服务器上,通过http访问的... 这里写了循环中调用大量微服务,这些微服务内部还有 循环调用其他微服务, - // 把微服务当做简单的类使用了...并发上来后基本都卡死了. - // 4. 由于被缓存挡上了 当商品信息发生变化时候,再也看不到新的数据了. - // 5. 为了防止for循环挂掉添加了一个try.但是,没有考虑到循环中对list的数据进行了修改, list之后被缓存起来了.出现异常的数据,里边价格,促销,等等信息都没有,导致调用该服务的地方挂了. -} diff --git a/java/GoodsServiceImpl.java b/java/GoodsServiceImpl.java deleted file mode 100644 index 3f22a979562e05191a04ef753cab8f9b4b901802..0000000000000000000000000000000000000000 --- a/java/GoodsServiceImpl.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.xxx.sys.goods.service.impl; - -import com.xxx.sys.goods.mapper.GoodsPassMapper; -import com.xxx.sys.goods.mapper.GoodsMapper; -import com.xxx.sys.goods.Model.Goods; -import com.xxx.sys.goods.Model.GoodsPass; - -import java.util.ArrayList; -import java.util.List; - -@Service -@AllArgsConstructor -public class GoodsServiceImpl implements GoodsService { - - private final GoodsPassMapper goodsPassMapper; - private final String s = "数据成功!"; - private final String s1 = "失败!"; - - - @Override - public List getList() { - List goods = null; - try { - //查询出所有商品,并给商品中的passName属性赋值 - goods = baseMapper.getList(); - if (goods==null & goods.size() < 0) { - return new ArrayList<>(); - } - for (Goods good : goods) { - if (GoodsConstant.PASS.getValue() == good.getGoodType) { - GoodsPass goodsPass = goodsPassMapper.getOneById(good.getGoodId()); - good.setPassName(goodsPass.getPassName()); - } - } - } catch (Exception e) { - //防止报错 - return new ArrayList<>(); - } - return goods; - } - - @Override - public String save(List goods) { - if (goods==null & goods.size() < 0) { - return "保存" + s1; - } - try { - //插入多条商品 - for (Goods good : goods) { - bassMapper.insert(good); - } - } catch (Throwable e) { - //防止报错 - return "保存" + s; - } - return "保存" + s; - } - - @Override - public String delById(Long goodId) { - //判断空 - if (goodId.equals(null)) { - return "删除"+s1; - } - baseMapper.delById(goodId); - return "删除" + s; - } - - @Override - public String updateById(Long goodId) { - //判断空 - if (goodId.equals(null)) { - return "修改" + s1; - } - baseMapper.updateById(goodId); - return "修改" + s; - } - - -} diff --git a/java/Great.java b/java/Great.java deleted file mode 100644 index e2122f87b1e408a194b273dd6fd5297884529ae6..0000000000000000000000000000000000000000 --- a/java/Great.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.test.utils; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class Great { - public static void main(String[] args) throws IOException { - Map map = new HashMap<>();//或者JSON - /* - *数据初始化省略 - */ - String str = "new str"; - //满足某个条件时,尝试修改set集合,因为只有对key值的需求,所以并未修改map - Set set = map.keySet(); - if(true){ - //这里会有惊喜 - set.add(str); - } - } -} diff --git a/java/HttpUtil.java b/java/HttpUtil.java deleted file mode 100644 index 1323caee9b7a914250edd4a571abae5cceb99b0c..0000000000000000000000000000000000000000 --- a/java/HttpUtil.java +++ /dev/null @@ -1,1132 +0,0 @@ -package com.kingroad.auditproject.common.util; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import okhttp3.*; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.HttpClient; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.conn.ssl.TrustStrategy; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.ssl.SSLContexts; -import org.apache.http.util.EntityUtils; -import org.springframework.util.CollectionUtils; -import org.springframework.util.StringUtils; - -import javax.net.ssl.*; -import javax.servlet.http.HttpServletRequest; -import java.io.*; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -/** - * @tags: http方法请求工具类 - * @author: ldr - * @create: 2022-09-16 17:00:30 - **/ -@Slf4j -public class HttpUtil { - public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); - public final static int CONNECT_TIMEOUT =60; - public final static int READ_TIMEOUT=100; - public final static int WRITE_TIMEOUT=60; - private static OkHttpClient CLIENT; - - - - /** - * 只有一个实例 - * - * @return OkHttpClient - */ - public static OkHttpClient getInstance() { - - if (CLIENT == null) { - - -// // CLIENT = new OkHttpClient(); -// System.setProperty("javax.net.ssl.keyStore", "/Users/qingfeng/IdeaProjects/Mechatronics/Mechatronics-Boot/src/main/resources/static/jxgsgl.jks"); -// System.setProperty("javax.net.ssl.keyStorePassword", "123456"); -// System.setProperty("javax.net.ssl.keyStoreType", "JKS"); -// System.setProperty("javax.net.ssl.trustStore", "/Users/qingfeng/IdeaProjects/Mechatronics/Mechatronics-Boot/src/main/resources/static/jxgsgl.jks"); -// System.setProperty("javax.net.ssl.trustStorePassword", "123456"); -// System.setProperty("javax.net.ssl.trustType", "JKS"); - CLIENT= new OkHttpClient.Builder() - .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间 - .writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS)//设置写的超时时间 - .connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)//设置连接超时时间 - //.sslSocketFactory(getSslFactory(path,pass),getMyX509TrustManager(path,pass)) - .sslSocketFactory(createSSLSocketFactory(),new TrustAllManager()) - .build(); - } - return CLIENT; - } - - public static SSLSocketFactory getSslFactory() - { - SSLSocketFactory ssf=null; - try { - -try { - SSLContext sslContext = null; - sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { - @Override - public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { - return true; - } - }).build(); - sslContext.init(null, null, new SecureRandom()); - ssf= sslContext.getSocketFactory(); -} catch (NoSuchAlgorithmException e) { - e.printStackTrace(); -} catch (KeyManagementException e) { - e.printStackTrace(); -} catch (KeyStoreException e) { - e.printStackTrace(); -} - } - catch (Exception e) - { - e.printStackTrace(); - } - return ssf; - - } - - - - /** - * 将map中的参数拼接成url - * @param params 参数map - * @return eg: a=1&b=2&c=3 - */ - public static String getUrlFromMap(Map params) { - StringBuffer tempParams = new StringBuffer(); - - try { - int pos = 0; - for (String key : params.keySet()) { - if (pos > 0) { - tempParams.append("&"); - } - - tempParams - .append(String.format("%s=%s", key, URLEncoder.encode((params.get(key)).toString(), "utf-8"))); - pos++; - } - } - catch (Exception e) { - e.printStackTrace(); - } - return tempParams.toString(); - } - - /** - * get() 返回字符串 - * - * @param url get请求的url - * @param params - * @return String - */ - public static String getForString(String url, Map params) { - String rs = ""; - if (StringUtils.isEmpty(url)) { - return ""; - } - if (params != null && params.size()>0) { - url = url + "?" + getUrlFromMap(params); - } - Request request = new Request.Builder().url(url).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - e.printStackTrace(); - } - log.debug("get(): url = {}, rs = {}", url,rs); - return rs; - } - - public static String getForString(String url, Map params, Map headers){ - String rs = ""; - - if (StringUtils.isEmpty(url)) { - return ""; - } - - if (params != null && params.size()>0) { - url = url + "?" + getUrlFromMap(params); - } - Request.Builder builder = new Request.Builder(); - builder.url(url); - if (!CollectionUtils.isEmpty(headers)){ - headers.forEach(builder::addHeader); - } - Request request = builder.get().build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - e.printStackTrace(); - } - log.debug("get(): url = {}, rs = {}", url,rs); - return rs; - } - - /** - * post() 表单提交 返回字符串 - * - * @param url - * @param params - * @return String - */ - @SuppressWarnings("all") - public static String postForString(String url, Map params) { - String rs = ""; - - FormBody.Builder builder = new FormBody.Builder(); - if (params != null) { - for (String key : params.keySet()) { - builder.add(key, params.get(key).toString()); - } - } - RequestBody formBody = builder.build(); - - Request request = new Request.Builder().url(url).post(formBody).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - e.printStackTrace(); - } - log.info("postForString(): url = {}, params = {}, rs = {}", url, params, rs); - return rs; - } - - /** - * delete() 表单提交 返回字符串 - * - * @param url - * @param params - * @return String - */ - @SuppressWarnings("all") - public static String deleteForString(String url, Map params) { - String rs = ""; - FormBody.Builder builder = new FormBody.Builder(); - if (params != null) { - for (String key : params.keySet()) { - builder.add(key, params.get(key).toString()); - } - } - RequestBody formBody = builder.build(); - - Request request = new Request.Builder().url(url).delete(formBody).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - e.printStackTrace(); - } - log.info("deleteForString(): url = {}, params = {}, rs = {}", url, params, rs); - return rs; - } - public static String deleteForString(String url, Map params, Map headers){ - String rs = ""; - if (StringUtils.isEmpty(url)) { - return ""; - } - if (params != null && params.size()>0) { - url = url + "?" + getUrlFromMap(params); - } - Request.Builder builder = new Request.Builder(); - builder.url(url); - if (!CollectionUtils.isEmpty(headers)){ - headers.forEach(builder::addHeader); - } - Request request = builder.delete().build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - e.printStackTrace(); - } - log.info("get(): url = {}, rs = {}", url,rs); - return rs; - } - - /** - * put() 表单提交 返回字符串 - * - * @param url - * @param params - * @return String - */ - @SuppressWarnings("all") - public static String putForString(String url, Map params) { - String rs = ""; - FormBody.Builder builder = new FormBody.Builder(); - if (params != null) { - for (String key : params.keySet()) { - builder.add(key, params.get(key).toString()); - } - } - RequestBody formBody = builder.build(); - - Request request = new Request.Builder().url(url).put(formBody).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - e.printStackTrace(); - } - log.info("putForString(): url = {}, params = {}, rs = {}", url, params, rs); - return rs; - } - - public static String putForStringWithHeader(String url, Map params, Map header) { - String rs = ""; - FormBody.Builder builder = new FormBody.Builder(); - if (params != null && params.size()>0) { - url = url + "?" + getUrlFromMap(params); - } - RequestBody formBody = builder.build(); - - Request.Builder requestBuilder = new Request.Builder().url(url); - for(String key: header.keySet()) { - requestBuilder.addHeader(key,header.get(key)); - } - Request request = requestBuilder.put(formBody).build(); - - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } catch (IOException e) { - e.printStackTrace(); - } - log.info("putForStringWithHeader(): url = {}, header = {}, params = {}, rs = {}",url, header,params,rs); - return rs; - } - - - /** - * 已经拼接好的url, 不需要再传参数map - * - * @param url - * @return - */ - public static JSONObject getForJSON(String url) { - - String resultStr = getForString(url, null); - return JSONObject.parseObject(resultStr); - } - - /** - * get() 返回json对象 - * - * @param url - * @return JSONObject - */ - public static JSONObject getForJSON(String url, Map params) { - - String resultStr = getForString(url, params); - return JSONObject.parseObject(resultStr); - // return JSONObject.parseObject(resultStr); - } - - /** - * post() 返回json对象 - * - * @param url - * @param params - * @return JSONObject - */ - public static JSONObject postForJSON(String url, Map params) { - String resultString = postForString(url, params); - return JSONObject.parseObject(resultString); - } - - /** - * post() json格式 返回字符串 - * - * @param url url - * @param jsonString json字符串 - * @return String - */ - @SuppressWarnings("all") - public static String postJSONForString(String url, String jsonString) { - final MediaType jsonType = MediaType.parse("application/json; charset=utf-8"); - String rs = ""; - - if (StringUtils.isEmpty(url)) { - return ""; - } - - RequestBody requestBody = RequestBody.create(jsonType, jsonString); - Request request = new Request.Builder().url(url).post(requestBody).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs); - return rs; - } - - - public static String postJSONForString(String url, String jsonString, Integer connSecond, Integer readSecond) throws Exception { - OkHttpClient client = new OkHttpClient.Builder() - .connectTimeout(connSecond, TimeUnit.SECONDS) - .readTimeout(readSecond, TimeUnit.SECONDS) - .build(); - final MediaType jsonType = MediaType.parse("application/json; charset=utf-8"); - String rs = ""; - - if (StringUtils.isEmpty(url)) { - return ""; - } - - RequestBody requestBody = RequestBody.create(jsonType, jsonString); - Request request = new Request.Builder().url(url).post(requestBody).build(); - Call call = client.newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (Exception e) { - throw new Exception(e); - } - log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs); - return rs; - } - - /** - * post() json格式 返回字符串 带token请求头 - * - * @param url url - * @param jsonString json字符串 - * @return String - */ - @SuppressWarnings("all") - public static String postJSONForString(String url, String jsonString,String token) { - final MediaType jsonType = MediaType.parse("application/json; charset=utf-8"); - String rs = ""; - - if (StringUtils.isEmpty(url)) { - return ""; - } - - RequestBody requestBody = RequestBody.create(jsonType, jsonString); - Request request = new Request.Builder().url(url).addHeader("token",token).post(requestBody).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs); - return rs; - } - /** - * post() json格式 返回字符串 带token请求头 - * - * @param url url - * @param jsonString json字符串 - * @return String - */ - @SuppressWarnings("all") - public static String postJSONForString(String url, String jsonString ,Map headers) { - final MediaType jsonType = MediaType.parse("application/json; charset=utf-8"); - String rs = ""; - - if (StringUtils.isEmpty(url)) { - return ""; - } - - RequestBody requestBody = RequestBody.create(jsonType, jsonString); - Request.Builder builder = new Request.Builder(); - builder.url(url); - if(!CollectionUtils.isEmpty(headers)){ - headers.forEach((k,v)->builder.addHeader(k,v)); - } - Request request = builder.post(requestBody).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs); - return rs; - } - - public static String postBytesForString(String url, byte[] bytes , Map headers) { - final MediaType jsonType = MediaType.parse("binary/octet-stream; charset=utf-8"); - String rs = ""; - - if (StringUtils.isEmpty(url)) { - return ""; - } - - RequestBody requestBody = RequestBody.create(jsonType, bytes); - Request.Builder builder = new Request.Builder(); - builder.url(url); - if(!CollectionUtils.isEmpty(headers)){ - headers.forEach((k,v)->builder.addHeader(k,v)); - } - Request request = builder.post(requestBody).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, bytes, rs); - return rs; - } - /** - * put() 返回字符串 - * - * @param url - * @param params - * @return String - */ - @SuppressWarnings("all") - public static String putJSONForString(String url,String jsonString, Map headers) { - final MediaType jsonType = MediaType.parse("application/json; charset=utf-8"); - String rs = ""; - RequestBody requestBody = RequestBody.create(jsonType,jsonString); - Request.Builder builder = new Request.Builder(); - builder.url(url); - if(!CollectionUtils.isEmpty(headers)){ - headers.forEach((k,v)->builder.addHeader(k,v)); - } - builder.put(requestBody); - Request request = builder.build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } catch (IOException e) { - throw new RuntimeException(e); - } - log.info("putJSONForString(): url = {}, params = {}, rs = {}, headers {}", url, jsonString, rs,headers); - return rs; - } - - @SuppressWarnings("all") - public static Response getResponseForPost(String url, String jsonString, String[] authBase, boolean isAuth) { - final MediaType jsonType = MediaType.parse("application/json; charset=utf-8"); - if (StringUtils.isEmpty(url)) { - return null; - } - - RequestBody requestBody = RequestBody.create(jsonType, jsonString); - Request request; - if (isAuth){ - final String credential = Credentials.basic(authBase[0], authBase[1]); - request = new Request.Builder().url(url).header("Authorization", credential).post(requestBody).build(); - }else{ - request = new Request.Builder().url(url).post(requestBody).build(); - } - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - } - catch (IOException e) { - throw new RuntimeException(e); - } - log.info("postJSONForString(): url = {}, params = {}", url, jsonString); - return response; - } - - /** - * post请求添加认证信息 - * @Param url:请求地址, params:参数,authBase:认证信息 - * @return String - * @Date 14:03 2019/12/25 - * @Author zhl - **/ - public static String postForAuthorization(String url, HashMap params, String[] authBase){ - final String credential = Credentials.basic(authBase[0], authBase[1]); - String result = ""; - RequestBody fromBody = generateParametersForPost(params).build(); - Request request = new Request.Builder() - .url(url) - .header("Authorization", credential) - .post(fromBody) - .build(); - Call call = CLIENT.newCall(request); - try { - Response response = call.execute(); - result = response.body().string(); - } catch (Exception e) { - log.error("postForAuthorization-请求失败,url:{}, params:{}, authBase:{}",url, params, authBase, e); - } - log.info("postForAuthorization(): url = {}, authBase = {}, params = {}, rs = {}",url, authBase, params, result); - return result; - - } - - public static String doHttpUrlencoded(String strUrl, Map params,String submitType) { - String result = ""; - - try { - String requestBodyString = params.keySet().stream() - .map(x -> x + "=" + URLEncoder.encode(params.get(x).toString())) - .collect(Collectors.joining("&")); - log.info("requestBodyString = {}",requestBodyString); - URL url = new URL(strUrl); - //通过调用url.openConnection()来获得一个新的URLConnection对象,并且将其结果强制转换为HttpURLConnection. - HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); - urlConnection.setRequestMethod(submitType); - //设置连接的超时值为30000毫秒,超时将抛出SocketTimeoutException异常 - urlConnection.setConnectTimeout(30000); - //设置读取的超时值为30000毫秒,超时将抛出SocketTimeoutException异常 - urlConnection.setReadTimeout(30000); - //将url连接用于输出,这样才能使用getOutputStream()。getOutputStream()返回的输出流用于传输数据 - urlConnection.setDoOutput(true); - //设置通用请求属性为默认浏览器编码类型 - urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded"); - //getOutputStream()返回的输出流,用于写入参数数据。 - OutputStream outputStream = urlConnection.getOutputStream(); - outputStream.write(requestBodyString.getBytes()); - outputStream.flush(); - outputStream.close(); - //此时将调用接口方法。getInputStream()返回的输入流可以读取返回的数据。 - InputStream inputStream = urlConnection.getInputStream(); - byte[] data = new byte[1024]; - StringBuilder sb = new StringBuilder(); - //inputStream每次就会将读取1024个byte到data中,当inputSteam中没有数据时,inputStream.read(data)值为-1 - while (inputStream.read(data) != -1) { - String s = new String(data, Charset.forName("utf-8")); - sb.append(s); - } - result = sb.toString(); - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - log.info("postForUrlencoded(): url = {}, params = {}, rs = {}", strUrl, params, result); - return result; - } - - @SuppressWarnings("all") - public static String postUrlEncodeForm(String url,Map map) { - String result = ""; - - //处理请求参数 - List valuePairs = new LinkedList<>(); - map.forEach((key, value) -> valuePairs.add(new BasicNameValuePair(key, value.toString()))); -/* for(Map.Entry entry : map.entrySet()) { - NameValuePair valuePair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString()); - valuePairs.add(valuePair); - }*/ - try { - //设置client参数 - HttpClient client = HttpClientBuilder.create().build(); - - //发送请求 - HttpPost post = new HttpPost(url); - HttpEntity entity = new UrlEncodedFormEntity(valuePairs,"UTF-8"); - post.setEntity(entity); - HttpResponse response = client.execute(post); - - //处理响应结果 - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode != 200) { - throw new RuntimeException("statusCode = [" + statusCode + "]"); - } else { - HttpEntity respEntity = response.getEntity(); - result = EntityUtils.toString(respEntity,"UTF-8"); - } - } catch (IOException e) { - e.getMessage(); - } - log.info("postForUrlencoded(): url = {}, params = {}, rs = {}", url, map, result); - return result; - } - - @SuppressWarnings("all") - public static String putUrlEncodeForm(String url,Map map) { - String result = ""; - - //处理请求参数 - List valuePairs = new LinkedList<>(); - map.forEach((key, value) -> valuePairs.add(new BasicNameValuePair(key, value.toString()))); - try { - //设置client参数 - HttpClient client = HttpClientBuilder.create().build(); - - //发送请求 - HttpPut put = new HttpPut(url); - HttpEntity entity = new UrlEncodedFormEntity(valuePairs,"UTF-8"); - put.setEntity(entity); - HttpResponse response = client.execute(put); - - //处理响应结果 - int statusCode = response.getStatusLine().getStatusCode(); - if (statusCode != 200) { - throw new RuntimeException("statusCode = [" + statusCode + "]"); - } else { - HttpEntity respEntity = response.getEntity(); - result = EntityUtils.toString(respEntity,"UTF-8"); - } - } catch (IOException e) { - e.getMessage(); - } - log.info("putUrlEncodeForm(): url = {}, params = {}, rs = {}", url, map, result); - return result; - } - - - public static String postXmlForString(String url, String xmlString) { - final MediaType xmlType = MediaType.parse("text/xml; charset=utf-8"); - String rs = ""; - - if (StringUtils.isEmpty(url)) { - return ""; - } - - RequestBody requestBody = RequestBody.create(xmlType, xmlString); - Request request = new Request.Builder().url(url).post(requestBody).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - e.printStackTrace(); - } - log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, xmlString, rs); - return rs; - } - - /** - * post() json格式 - * - * @param url url - * @param jsonString json格式字符串 - * @return JSONObject - */ - public static JSONObject postJSONForJSON(String url, String jsonString) { - String resultString = postJSONForString(url, jsonString); - return JSONObject.parseObject(resultString); - } - - - /** - * post() json格式 返回字符串 - * - * @param url url - * @param jsonString json字符串 - * @return String - */ - public static String postJSONForStringGBK(String url, String jsonString) { - final MediaType jsonType = MediaType.parse("application/json; charset=gb2312"); - String rs = ""; - - if (StringUtils.isEmpty(url)) { - return ""; - } - - RequestBody requestBody = RequestBody.create(jsonType, jsonString); - Request request = new Request.Builder().url(url).post(requestBody).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } - catch (IOException e) { - e.printStackTrace(); - } - log.info("postJSONForString(): url = {}, params = {}, rs = {}", url, jsonString, rs); - return rs; - } - - /** - * post() json格式 - * - * @param url url - * @param jsonString json格式字符串 - * @return JSONObject - */ - public static JSONObject postJSONForJSONGBK(String url, String jsonString) { - String resultString = postJSONForStringGBK(url, jsonString); - return JSONObject.parseObject(resultString); - } - - /** - * 获取post json过来的数据 - * - * @param request httpServletRequest对象 - * @return 字符串 - */ - public static String receivePost(HttpServletRequest request) { - String res = ""; - try { - BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); - String line = null; - StringBuilder sb = new StringBuilder(); - while ((line = br.readLine()) != null) { - sb.append(line); - } - res = URLDecoder.decode(sb.toString(), "utf-8"); - } - catch (Exception e) { - e.printStackTrace(); - } - - return res; - } - - public static String receivePostForGbk(HttpServletRequest request){ - String res = ""; - try { - BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); - String line = null; - StringBuilder sb = new StringBuilder(); - while ((line = br.readLine()) != null) { - sb.append(line); - } - res = URLDecoder.decode(sb.toString(), "GBK"); - } - catch (Exception e) { - e.printStackTrace(); - } - - return res; - } - - /** - * Post() 提交带header - * @param url - * @param header - * @param params - * @return - */ - public static String postForStringWithHeader(String url, Map header, Map params) { - String rs = ""; - - FormBody.Builder builder = new FormBody.Builder(); - - if (params != null && !params.isEmpty()) { - for(String key : params.keySet()) { - builder.add(key,params.get(key)); - } - } - - RequestBody formBody = builder.build(); - - Request.Builder requestBuilder = new Request.Builder().url(url);//.post(formBody).build(); - - for(String key: header.keySet()) { - requestBuilder.addHeader(key,header.get(key)); - } - - Request request = requestBuilder.post(formBody).build(); - - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } catch (IOException e) { - e.printStackTrace(); - } - log.info("post(): url = {}, header = {}, params = {}, rs = {}",url, header,params,rs); - return rs; - } - - /** - * post() 提交带header 返回JSON - * @param url - * @param params - * @return - */ - public static JSONObject postForJSONWithHeader(String url, Map header, Map params) { - String resultString = postForStringWithHeader(url,header,params); - return JSONObject.parseObject(resultString); - } - - - public static String receivePostGBK(HttpServletRequest request) { - String res = ""; - String resgbk = ""; - try { - BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); - String line = null; - StringBuilder sb = new StringBuilder(); - while ((line = br.readLine()) != null) { - sb.append(line); - } - log.info("***********to UTF-16BE:{}" ,sb.toString().getBytes()); - - String byte_s=""; - for(byte i:sb.toString().getBytes()) - { - byte_s=byte_s+i; - } - - log.info("***********to sb:{}" ,new String(sb)); - log.info("***********to sb.toString:{}" ,sb.toString()); - log.info("***********to byte_s:{}", byte_s); - log.info("***********to GBK:{}" ,new String(sb.toString().getBytes(),"GBK")); - log.info("***********to GB2312:{}" ,new String(sb.toString().getBytes(),"GB2312")); - log.info("***********to UTF:{}" ,new String(sb.toString().getBytes(),"UTF-8")); - log.info("***********to UTF-16BE:{}" ,new String(sb.toString().getBytes(),"UTF-16BE")); - - - - - - res = URLDecoder.decode(sb.toString(), "GB2312"); - resgbk = URLDecoder.decode(sb.toString(), "GBK"); - log.info("receivePostGBK : URLDecoder res = {}, resgbk = {}, rs = {}", res, resgbk); - } - catch (Exception e) { - e.printStackTrace(); - } - - return res; - } - - private static FormBody.Builder generateParametersForPost(HashMap parameters) { - - FormBody.Builder builder = new FormBody.Builder(); - - if(parameters.size()>0){ - Object[] keys = parameters.keySet().toArray(); - - for(Object key : keys){ - Object ff = parameters.get(key); - String aa = parameters.get(key).toString(); - - builder.add(key.toString(),parameters.get(key).toString()); - } - } - return builder; - } - - - public static String receivePostEncoding(HttpServletRequest request, String CharacterEncoding) { - String res = ""; - try { - BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); - String line = null; - StringBuilder sb = new StringBuilder(); - while ((line = br.readLine()) != null) { - sb.append(line); - } - log.info("***********to CharacterEncoding:{}" ,new String(sb.toString().getBytes(),CharacterEncoding)); - - res = URLDecoder.decode(sb.toString(), CharacterEncoding); - log.info("receivePostEncoding : URLDecoder res = {}", res); - - } - catch (Exception e) { - e.printStackTrace(); - } - - return res; - } - - public static String getRequestBody(HttpServletRequest request) - throws IOException { - StringBuilder httpBody = new StringBuilder(); - BufferedReader br = null; - try { - br = new BufferedReader(new InputStreamReader( - request.getInputStream())); - String line = null; - while ((line = br.readLine()) != null) { - httpBody.append(line); - } - } catch (IOException ex) { - throw ex; - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - } - return httpBody.toString(); - } - - /** - * 同步post json数据 <有头信息> - * @param url - * @param json - * @return - * @throws IOException - */ - public static String post(String url, String json,Map headers) { - String rs = ""; - RequestBody body = RequestBody.create(JSON, json); - Request request = new Request.Builder().headers(Headers.of(headers)).url(url).post(body).build(); - Call call = HttpUtil.getInstance().newCall(request); - Response response = null; - try { - response = call.execute(); - rs = response.body().string(); - } catch (IOException e) { - e.printStackTrace(); - } - return rs; - } - - /** - * 去掉url中的路径,留下请求参数部分 - * @param strURL url地址 - * @return url请求参数部分 - * @author lzf - */ - private static String TruncateUrlPage(String strURL){ - String strAllParam=null; - String[] arrSplit=null; - strURL=strURL.trim().toLowerCase(); - arrSplit=strURL.split("[?]"); - if(strURL.length()>1){ - if(arrSplit.length>1){ - for (int i=1;i urlSplit(String URL){ - Map mapRequest = new HashMap(); - String[] arrSplit=null; - String strUrlParam=TruncateUrlPage(URL); - if(strUrlParam==null){ - return mapRequest; - } - arrSplit=strUrlParam.split("[&]"); - for(String strSplit:arrSplit){ - String[] arrSplitEqual=null; - arrSplitEqual= strSplit.split("[=]"); - //解析出键值 - if(arrSplitEqual.length>1){ - //正确解析 - mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]); - }else{ - if(arrSplitEqual[0]!=""){ - //只有参数没有值,不加入 - mapRequest.put(arrSplitEqual[0], ""); - } - } - } - return mapRequest; - } - -private static SSLSocketFactory createSSLSocketFactory() { - - SSLSocketFactory sSLSocketFactory = null; - - try { - SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(null, new TrustManager[]{new TrustAllManager()}, - new SecureRandom()); - sSLSocketFactory = sc.getSocketFactory(); - } catch (Exception e) { - } - - return sSLSocketFactory; -} - -private static class TrustAllManager implements X509TrustManager { - @Override - public void checkClientTrusted(X509Certificate[] chain, String authType) - throws CertificateException { - } - - @Override - public void checkServerTrusted(X509Certificate[] chain, String authType) - - throws CertificateException { - } - - @Override - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } -} - -private static class TrustAllHostnameVerifier implements HostnameVerifier { - @Override - public boolean verify(String hostname, SSLSession session) { - return true; - } -} - - -} diff --git a/java/HutoolPage.java b/java/HutoolPage.java deleted file mode 100644 index 4e6e3eb1ac6a087dc0193d50cc616421c9c06995..0000000000000000000000000000000000000000 --- a/java/HutoolPage.java +++ /dev/null @@ -1,162 +0,0 @@ -package cn.hutool.db; - -import java.util.Arrays; - -import cn.hutool.core.util.ArrayUtil; -import cn.hutool.core.util.PageUtil; -import cn.hutool.db.sql.Order; - -/** - * 分页对象 - * @author Looly - * - */ -public class Page { - - public static final int DEFAULT_PAGE_SIZE = 20; - - /** 页码 */ - private int pageNumber; - /** 每页结果数 */ - private int pageSize; - /** 排序 */ - private Order[] orders; - - // ---------------------------------------------------------- Constructor start - /** - * 构造 - * - * @param pageNumber 页码 - * @param pageSize 每页结果数 - */ - public Page(int pageNumber, int pageSize) { - this.pageNumber = pageNumber < 0 ? 0 : pageNumber; - this.pageSize = pageSize <= 0 ? DEFAULT_PAGE_SIZE : pageSize; - } - - /** - * 构造 - * - * @param pageNumber 页码 - * @param numPerPage 每页结果数 - * @param order 排序对象 - */ - public Page(int pageNumber, int numPerPage, Order order) { - this(pageNumber, numPerPage); - this.orders = new Order[]{order}; - } - // ---------------------------------------------------------- Constructor start - - // ---------------------------------------------------------- Getters and Setters start - /** - * @return 页码 - */ - public int getPageNumber() { - return pageNumber; - } - - /** - * 设置页码 - * @param pageNumber 页码 - */ - public void setPageNumber(int pageNumber) { - this.pageNumber = pageNumber < 0 ? 0 : pageNumber; - } - - /** - * @return 每页结果数 - * @deprecated 使用 {@link #getPageSize()} 代替 - */ - @Deprecated - public int getNumPerPage() { - return getPageSize(); - } - - /** - * 设置每页结果数 - * - * @param pageSize 每页结果数 - * @deprecated 使用 {@link #setPageSize(int)} 代替 - */ - @Deprecated - public void setNumPerPage(int pageSize) { - setPageSize(pageSize); - } - - /** - * @return 每页结果数 - */ - public int getPageSize() { - return pageSize; - } - - /** - * 设置每页结果数 - * - * @param pageSize 每页结果数 - */ - public void setPageSize(int pageSize) { - this.pageSize = pageSize <= 0 ? DEFAULT_PAGE_SIZE : pageSize; - } - - /** - * @return 排序 - */ - public Order[] getOrders() { - return this.orders; - } - - /** - * 设置排序 - * - * @param orders 排序 - */ - public void setOrder(Order... orders) { - this.orders = orders; - } - - /** - * 设置排序 - * - * @param orders 排序 - */ - public void addOrder(Order... orders) { - if(null != this.orders){ - ArrayUtil.append(this.orders, orders); - } - this.orders = orders; - } - // ---------------------------------------------------------- Getters and Setters end - - /** - * @return 开始位置 - */ - public int getStartPosition() { - return getStartEnd()[0]; - } - - /** - * @return 结束位置 - */ - public int getEndPosition() { - return getStartEnd()[1]; - } - - /** - * 开始位置和结束位置
- * 例如:
- * 页码:1,每页10 =》 [0, 10]
- * 页码:2,每页10 =》 [10, 20]
- * 。。。
- * - * @return 第一个数为开始位置,第二个数为结束位置 - */ - public int[] getStartEnd() { - return PageUtil.transToStartEnd(pageNumber, pageSize); - } - - @Override - public String toString() { - return "Page [page=" + pageNumber + ", pageSize=" + pageSize + ", order=" + Arrays.toString(orders) + "]"; - } -} diff --git a/java/IdUtil.java b/java/IdUtil.java deleted file mode 100644 index 47f98b5697cd72331a55b04b9385bd6871224f81..0000000000000000000000000000000000000000 --- a/java/IdUtil.java +++ /dev/null @@ -1,32 +0,0 @@ -package xx.xx.util; - -import java.util.Random; - -//生成15位的不重复的ID -//不支持集群分布式 -//单项目 15位ID休眠不重复 工具类 -//恐怖的是 这工具类居然满足了项目要求 -public class IdUtil { - public static Object lock = new Object(); - public static Random random = new Random(); - - public static int min = 10; - public static int max= 99; - //每秒最多生成 1000/3位id - public static synchronized long getId(){ - synchronized(lock){ - int num = new Random().nextInt(max-min+1)+min; - long id = System.currentTimeMillis(); - try { - Thread.sleep(3); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return Long.valueOf(String.valueOf(id)+String.valueOf(num)); - } - } - public static void main(String[] args) { - System.out.println(getId()); - System.out.println(String.valueOf(getId()).length()); - } -} diff --git a/java/IfController b/java/IfController deleted file mode 100644 index 43499cd65398110b356cdcf21e01351ce957f4b1..0000000000000000000000000000000000000000 --- a/java/IfController +++ /dev/null @@ -1,247 +0,0 @@ - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -/** - * 5年经验大佬写的controller - */ -public class CmsCustomerController { - @Autowired - private ICustomerService Service; - - @PostMapping("/save") - @ResponseBody - public AjaxResult Save(@Validated CmsCustomer info) { - Integer capitalId = info.getCapitalId() + 1; - String cap = capitalId.toString(); - String t = info.getTradeId() == null ? "" : info.getTradeId().toString(); - String capNo = ""; - String TradeNo = ""; - // if和else if的条件一样,生产环境运行1年无异常 - if (cap.length() == 1) { - capNo = "000" + cap; - } else if (cap.length() == 1) { - capNo = "00" + cap; - } - if (t.length() == 1) { - TradeNo = "000" + cap; - } else if (t.length() == 1) { - TradeNo = "00" + cap; - } - info.setCapitalNo(capNo); - info.setTradeNo(TradeNo); - Service.updateCustomer(info); - return AjaxResult.success(); - } - - @PostMapping("/loaddata4") - @ResponseBody - public TableDataInfo loaddata4(CmsCustomer info) { - List lists = new ArrayList(); - List records = new ArrayList(); - records = Service.selectcustomer4(info); - CmsCustomer list = new CmsCustomer(); - CmsCustomer list1 = new CmsCustomer(); - CmsCustomer list2 = new CmsCustomer(); - CmsCustomer list3 = new CmsCustomer(); - CmsCustomer list4 = new CmsCustomer(); - CmsCustomer list5 = new CmsCustomer(); - CmsCustomer list6 = new CmsCustomer(); - CmsCustomer list7 = new CmsCustomer(); - CmsCustomer list8 = new CmsCustomer(); - CmsCustomer list9 = new CmsCustomer(); - CmsCustomer list10 = new CmsCustomer(); - list.setCompanyName(" "); - list1.setCompanyName("1"); - list2.setCompanyName("2"); - list3.setCompanyName("3"); - list4.setCompanyName("4"); - list5.setCompanyName("5"); - list6.setCompanyName("6"); - list7.setCompanyName("7"); - list8.setCompanyName("8"); - list9.setCompanyName("9"); - list10.setCompanyName("10"); - String project = ""; - int num = 0; - int num1 = 0; - int num2 = 0; - int num3 = 0; - int num4 = 0; - int num5 = 0; - for (CmsCustomer record : records) { - num = num + 1; - if (num == 1) { - list.setNum1(record.getProNm()); - project = record.getProjectType(); - List record1s = getCustomer(project, info); - for (CmsCustomer record1 : record1s) { - num1 = num1 + 1; - if (num1 == 1) { - list1.setNum1(record1.getProNm()); - } else if (num1 == 2) { - list2.setNum1(record1.getProNm()); - } else if (num1 == 3) { - list3.setNum1(record1.getProNm()); - } else if (num1 == 4) { - list4.setNum1(record1.getProNm()); - } else if (num1 == 5) { - list5.setNum1(record1.getProNm()); - } else if (num1 == 6) { - list6.setNum1(record1.getProNm()); - } else if (num1 == 7) { - list7.setNum1(record1.getProNm()); - } else if (num1 == 8) { - list8.setNum1(record1.getProNm()); - } else if (num1 == 9) { - list9.setNum1(record1.getProNm()); - } else if (num1 == 10) { - list10.setNum1(record1.getProNm()); - } - - } - } else if (num == 2) { - list.setNum2(record.getProNm()); - project = record.getProjectType(); - List record1s = getCustomer(project, info); - for (CmsCustomer record1 : record1s) { - num2 = num2 + 1; - if (num2 == 1) { - list1.setNum2(record1.getProNm()); - } else if (num2 == 2) { - list2.setNum2(record1.getProNm()); - } else if (num2 == 3) { - list3.setNum2(record1.getProNm()); - } else if (num2 == 4) { - list4.setNum2(record1.getProNm()); - } else if (num2 == 5) { - list5.setNum2(record1.getProNm()); - } else if (num2 == 6) { - list6.setNum2(record1.getProNm()); - } else if (num2 == 7) { - list7.setNum2(record1.getProNm()); - } else if (num2 == 8) { - list8.setNum2(record1.getProNm()); - } else if (num2 == 9) { - list9.setNum2(record1.getProNm()); - } else if (num2 == 10) { - list10.setNum2(record1.getProNm()); - } - } - } else if (num == 3) { - list.setNum3(record.getProNm()); - project = record.getProjectType(); - List record1s = getCustomer(project, info); - for (CmsCustomer record1 : record1s) { - num3 = num3 + 1; - if (num3 == 1) { - list1.setNum3(record1.getProNm()); - } else if (num3 == 2) { - list2.setNum3(record1.getProNm()); - } else if (num3 == 3) { - list3.setNum3(record1.getProNm()); - } else if (num3 == 4) { - list4.setNum3(record1.getProNm()); - } else if (num3 == 5) { - list5.setNum3(record1.getProNm()); - } else if (num3 == 6) { - list6.setNum3(record1.getProNm()); - } else if (num3 == 7) { - list7.setNum3(record1.getProNm()); - } else if (num3 == 8) { - list8.setNum3(record1.getProNm()); - } else if (num3 == 9) { - list9.setNum3(record1.getProNm()); - } else if (num3 == 10) { - list10.setNum3(record1.getProNm()); - } - } - } else if (num == 4) { - list.setNum4(record.getProNm()); - project = record.getProjectType(); - List record1s = getCustomer(project, info); - for (CmsCustomer record1 : record1s) { - num4 = num4 + 1; - if (num4 == 1) { - list1.setNum4(record1.getProNm()); - } else if (num4 == 2) { - list2.setNum4(record1.getProNm()); - } else if (num4 == 3) { - list3.setNum4(record1.getProNm()); - } else if (num4 == 4) { - list4.setNum4(record1.getProNm()); - } else if (num4 == 5) { - list5.setNum4(record1.getProNm()); - } else if (num4 == 6) { - list6.setNum4(record1.getProNm()); - } else if (num4 == 7) { - list7.setNum4(record1.getProNm()); - } else if (num4 == 8) { - list8.setNum4(record1.getProNm()); - } else if (num4 == 9) { - list9.setNum4(record1.getProNm()); - } else if (num4 == 10) { - list10.setNum4(record1.getProNm()); - } - } - } else if (num == 5) { - list.setNum5(record.getProNm()); - project = record.getProjectType(); - List record1s = getCustomer(project, info); - for (CmsCustomer record1 : record1s) { - num5 = num5 + 1; - if (num5 == 1) { - list1.setNum5(record1.getProNm()); - } else if (num5 == 2) { - list2.setNum5(record1.getProNm()); - } else if (num5 == 3) { - list3.setNum5(record1.getProNm()); - } else if (num5 == 4) { - list4.setNum5(record1.getProNm()); - } else if (num5 == 5) { - list5.setNum5(record1.getProNm()); - } else if (num5 == 6) { - list6.setNum5(record1.getProNm()); - } else if (num5 == 7) { - list7.setNum5(record1.getProNm()); - } else if (num5 == 8) { - list8.setNum5(record1.getProNm()); - } else if (num5 == 9) { - list9.setNum5(record1.getProNm()); - } else if (num5 == 10) { - list10.setNum5(record1.getProNm()); - } - } - } - } - lists.add(list); - lists.add(list1); - lists.add(list2); - lists.add(list3); - lists.add(list4); - lists.add(list5); - lists.add(list6); - lists.add(list7); - lists.add(list8); - lists.add(list9); - lists.add(list10); - return getDataTable(lists); - } - - public List getCustomer(String project, CmsCustomer info) { - List lists = new ArrayList(); - if (project.equals("0")) { - lists = Service.select0(info); - } else if (project.equals("1")) { - lists = Service.select1(info); - } else if (project.equals("2")) { - lists = Service.select2(info); - } else if (project.equals("3")) { - lists = Service.select3(info); - } else if (project.equals("4")) { - lists = Service.select4(info); - } - return lists; - } -} diff --git a/java/IfDemo.java b/java/IfDemo.java deleted file mode 100644 index deee6a3adc65651244b2101aa30480adfe4f23fb..0000000000000000000000000000000000000000 --- a/java/IfDemo.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * - * if 无敌判断,程序被执行了多次,断电也打了,怎么会执行多次。

- * 创建日期:2019年6月27日
- * 修改历史:
- * 修改日期:
- * 修改作者:
- * 修改内容:
- * @version 1.0 - */ -public class IfDemo { - - public static void main(String[] args) { - howOldAreYou(60); - } - - public static void howOldAreYou(int age) { - if (age > 0) { - System.out.println("我是小学生"); - } - if (age > 10) { - System.out.println("我是中学生"); - } - if (age > 20) { - System.out.println("我是大学生"); - } - if (age > 30) { - System.out.println("我是研究生"); - } - if (age > 50) { - System.out.println("我是博士生"); - } - if (age > 100) { - System.out.println("我是老神仙"); - } - } - -} diff --git a/java/InfiniteCycle b/java/InfiniteCycle deleted file mode 100644 index 6af601c36e01a20f22b8c565db9625465759c746..0000000000000000000000000000000000000000 --- a/java/InfiniteCycle +++ /dev/null @@ -1,79 +0,0 @@ -// 这个无限循环嵌套,只是总循环的一部分。。。我已经绕晕在黄桷湾立交 -if (recordList.size() > start) { - for (int i = start; i < end; i++) { - Map map = recordList.get(i); - Map field11 = (Map) map.get("field"); //name -> code - Map record11 = (Map) map.get("record"); // code -> value - String catagory1 = map.get("categoryId").toString(); - // 查询第一种类型对应的其他类型 - SalaryDataVo ss = JSON.parseObject(JSON.toJSONString(map), SalaryDataVo.class); - Page page3 = salaryManagerService.getAllRecordsByCondition(ss); - if (page3.getRecords().size() > 0) { - List> salaryDataVos = page3.getRecords(); - salaryDataVos = this.reSetMap(salaryDataVos,null,null); - for (Map map2 : salaryDataVos) { - Map field2 = (Map) map2.get("field"); - Map record2 = (Map) map2.get("record"); - String catagory2 = map2.get("categoryId").toString(); - List groupList2 = salaryGroupService.getSalaryGroupsItems(this.getUserCorpId(), catagory2); - for (SalaryGroupVO cc : groupList2) { - cc.setCode(cc.getParentId() + cc.getCode()); - } - //计算 - for (Map.Entry entity : field2.entrySet()) { - String keyName = entity.getKey(); - for (SalaryGroupVO s2 : groupList2) { - if ("bigDecimal".equals(s2.getItemType()) && s2.getCode().equals(field2.get(keyName).toString()) && ("部门" != keyName) && ("姓名" != keyName) && StringUtils.isNotEmpty(s2.getItemType())) { - if (field11.containsKey(keyName)) { - if (field11.containsKey(keyName)) { - String code1 = field11.get(keyName).toString(); - Double newValue = 0.0; - Double oldValue=0.0; - if (!record11.get(code1).toString().matches("^[0-9]*$")) { - oldValue = Double.parseDouble(record11.get(code1).toString()); - if (record2.containsKey(entity.getValue().toString()) && (!record2.get(entity.getValue().toString()).toString().matches("^[0-9]*$"))) { - String value2 = record2.get(entity.getValue().toString()).toString(); - newValue = Double.parseDouble(value2); - } - record11.remove(field11.get(keyName).toString()); - } - if (code1.startsWith(catagory1)||code1.startsWith(catagory2)) { - String co = code1.replace(catagory1, "hz"); - field11.put(keyName, co); - record11.put(co , oldValue + newValue); - } - } - } else { - String code=entity.getValue().toString(); - String str=entity.getValue().toString(); - Object value2 = record2.get(entity.getValue().toString()); - if(str.startsWith(catagory1)&&str.replace(catagory1,"").startsWith("hz")){ - code=str.replace(catagory1,""); - }else if(str.startsWith(catagory2)&&str.replace(catagory2,"").startsWith("hz")){ - code= str.replace(catagory2,""); - } - field11.put(keyName, code); - record11.put(code, value2); - } - } - } - } - } - } - List sList=salaryGroupService.getSalaryGroupItemsByParentId(catagory1); - for(SalaryGroupVO s:sList){ - if(field11.containsKey(s.getName())&&s.getCode().startsWith("hz")){ - String k=field11.get(s.getName()).toString(); - - field11.put(s.getName(),s.getCode()); - String value=null; - if(record11.containsKey(k)){ - value=record11.get(k).toString(); - } - record11.put(s.getCode(),value); - } - } - resultList.add(map); - pageInfo.setRecords(resultList); - } - } \ No newline at end of file diff --git a/java/InsertCache.java b/java/InsertCache.java deleted file mode 100644 index 541e9c87598decd53bbe35aafc3f36769753e79e..0000000000000000000000000000000000000000 --- a/java/InsertCache.java +++ /dev/null @@ -1,71 +0,0 @@ - // 每个数据字典 都有 type 属性,分别放到 不同的缓存key里,对数据字典进行任何增加、修改、删除操作,都会删除 所有 缓存 - // 缓存的更新放到 另一个 类里,是根据 type 属性 进行分别更新,这个方法要么重启服务触发,要么由前台调用接口触发 - - - - /** - * 批量删除字典数据信息 - * - * @param dictCodes 需要删除的字典数据ID - * @return 结果 - */ - @Override - public int deleteDictDataByIds(Long[] dictCodes) { - int row = dictDataMapper.deleteDictDataByIds(dictCodes); - if (row > 0) { - DictUtils.clearDictCache();// 清除所有 type 的缓存 - } - return row; - } - - /** - * 新增保存字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - @Override - public int insertDictData(SysDictData dictData) { - int row = dictDataMapper.insertDictData(dictData); - if (row > 0) { - DictUtils.clearDictCache(); - } - return row; - } - - /** - * 修改保存字典数据信息 - * - * @param dictData 字典数据信息 - * @return 结果 - */ - @Override - public int updateDictData(SysDictData dictData) { - int row = dictDataMapper.updateDictData(dictData); - if (row > 0) { - DictUtils.clearDictCache(); - } - return row; - } - -// 更新缓存的 方法,一次只有一个 type,而且是靠前台调用 - /** - * 根据字典类型查询字典数据 - * - * @param dictType 字典类型 - * @return 字典数据集合信息 - */ - @Override - public List selectDictDataByType(String dictType) { - List dictDatas = DictUtils.getDictCache(dictType); - if (StringUtils.isNotEmpty(dictDatas)) { - return dictDatas; - } - dictDatas = dictDataMapper.selectDictDataByType(dictType); - if (StringUtils.isNotEmpty(dictDatas)) { - DictUtils.setDictCache(dictType, dictDatas); - return dictDatas; - } - return null; - } - diff --git a/java/IntEquals.java b/java/IntEquals.java deleted file mode 100644 index 67e29582674a467268647750d47b5bccc0b4c7a5..0000000000000000000000000000000000000000 --- a/java/IntEquals.java +++ /dev/null @@ -1,17 +0,0 @@ -public void getIncrT(String key,Integer minutes,Integer count) { - if(redisTemplate.opsForValue().setIfAbsent(key,"1")) { - if (null != minutes) { - redisTemplate.expire(key, minutes, TimeUnit.MINUTES); - } - return; - }else { - String currentValue = redisTemplate.opsForValue().get(key); - //如果当前数量已经 == 已存数量 则不继续累加 - if(Integer.valueOf(currentValue) == count) { - throw new RuntimeException("超过限流数量"); - }else { - RedisAtomicInteger integer = new RedisAtomicInteger(key, redisTemplate.getConnectionFactory()); - integer.getAndIncrement(); - } - } -} \ No newline at end of file diff --git a/java/IntegerEqual.java b/java/IntegerEqual.java deleted file mode 100644 index 79a26938b9edae0922b047c152ee9b2e1386b668..0000000000000000000000000000000000000000 --- a/java/IntegerEqual.java +++ /dev/null @@ -1,28 +0,0 @@ - -/* - * - * 很多人习惯在Bean中将整数类型定义为包装类,比如int的定义为了Integer,为了方便在使用Mybatis插入的时候做判断,是否为null。 - * 但是,包装类等于比较的时候使用==,这样难道不怕逻辑跑偏吗? - * 如下代码,==两边都是Integer类型,想想,这会不会出bug? - */ -if(processBjd.getBusinessType() == ErpProcessBjd.BUSINESS_TYPE_PROJECT_ROY || processBjd.getBusinessType() == ErpProcessBjd.BUSINESS_TYPE_PROJECT_PROCESS){ -// TODO -} - -/* - *我们都知道包装类的相等比较尽量使用equals而非==。 - * 在包装类中其实是重写了equals方法,比较的是值大写, - * 但是,==是比较地址,其实即使比较值,其中也有一些小坑, - * 看看下面的代码,你觉得结果会是什么? - */ -public class IntegerEqual{ - public static void main(String[] args) { - Integer a = 100; - Integer b = 100; - System.out.println("a == b => "+(a == b)); - Integer c = 3000; - Integer d = 3000; - System.out.println("c == d => "+(c == d));​ - } -} - diff --git a/java/InvokeInterfaceInForLoop.java b/java/InvokeInterfaceInForLoop.java deleted file mode 100644 index b149d87ca9425a34045d888f0706c8c8f1a1d58b..0000000000000000000000000000000000000000 --- a/java/InvokeInterfaceInForLoop.java +++ /dev/null @@ -1,44 +0,0 @@ - - - -/** - * @Description: for循环里面调用rpc接口查询信息导致接口请求超时 - * @Author : yt - * @Date : 2019/05/23 13:30 - */ -public class InvokeInterfceInforLoop { - - @Resource - private UserRemoteService userRemoteService; - - /** - * 查询用户详细信息 - * - * @param userInfoList - * @return - */ - public List queryList(List userInfoList) { - - List result = new ArrayList<>(userInfoList.size()); - - //根据用户id查询用户信息 - for (UserInfo userInfo : userInfoList) { - UserExtInfo = userRemoteService.findByUserId(userInfo.getUserId()); - //设置扩展信息.... - assemble(userInfo, userExtInfo); - } - - - - //建议批量查询,减少网络io请求次数 - Set userIds = userInfoList.stream().map(UserInfo::getUserId ()).collect(Collectors.toSet()); - List =userRemoteService.findByUserIds(userIds); - } - - - private UserDetailDTO assemble(UserInfo userInfo, UserExtInfo userExtInfo) { - // - } - - -} \ No newline at end of file diff --git a/java/IsNullDemo.java b/java/IsNullDemo.java deleted file mode 100644 index 6220a7a456320611bcc5866a0143c2ae0e4db7db..0000000000000000000000000000000000000000 --- a/java/IsNullDemo.java +++ /dev/null @@ -1,14 +0,0 @@ -public class IsNullDemo{ - public static boolean isNull(Example object){ - try { - object.isNull(); - }catch (NullPointerException e){ - return true; - } - return false; - } -} - -class Example{ - public void isNull(){} -} \ No newline at end of file diff --git a/java/Iswu.java b/java/Iswu.java deleted file mode 100644 index cfc4516fafb82bbea9f1b42323e6670cd97f1f67..0000000000000000000000000000000000000000 --- a/java/Iswu.java +++ /dev/null @@ -1,11 +0,0 @@ -public class Iswu { - - public boolean isOrNot() { - // 愣了一分钟,想把写代码的人揪出来爆锤 - if (xxx != false) { - return false; - } else { - return true; - } - } -} \ No newline at end of file diff --git a/java/JavaSwitch.java b/java/JavaSwitch.java deleted file mode 100644 index b224f7611010eb101f8685e5d61366cd9a2da5ea..0000000000000000000000000000000000000000 --- a/java/JavaSwitch.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.pdfengine.pspdfdata.svc; - -import org.dom4j.DocumentHelper; -import org.dom4j.Element; - -import com.pdfengine.pspdfdata.util.DataUtil; - -public class JavaSwitch { - public static void main(String[] args) { - Element studentsEle = DocumentHelper.createDocument().addElement("Students"); - String[] rowNames = new String[] {"xiaoming", "xiaohong", "xiaohua"}; - String[] colNames = new String[] {"Chinese", "English", "Math"}; - for (int i = 0; i < rowNames.length; i++) { - Element studentEle = studentsEle.addElement("Student"); - for (int j = 0; j < colNames.length; j++) { - switch (j) { - case 0: - studentEle.addAttribute(colNames[j], DataUtil.getString(rowNames[i])); - break; - case 1: - studentEle.addAttribute(colNames[j], DataUtil.getString(rowNames[i])); - break; - case 2: - studentEle.addAttribute(colNames[j], DataUtil.getString(rowNames[i])); - break; - default: - break; - } - } - } - } -} diff --git a/java/JudgeBool b/java/JudgeBool deleted file mode 100644 index d925bf8c28321510f074ebc2523d05dc27e32ef7..0000000000000000000000000000000000000000 --- a/java/JudgeBool +++ /dev/null @@ -1,14 +0,0 @@ - -public class JudgeBool{ - - /** - * 来自一名3年编程经验者判断boolean类型 - * @param isTrue - */ - public void judge(Boolean isTrue) { - if(isTrue == true) { - System.out.println("正确"); - } - } - -} \ No newline at end of file diff --git a/java/LinkList.java b/java/LinkList.java deleted file mode 100644 index d8e900f6bdb943939432ace76c6f0a2bd3eba31e..0000000000000000000000000000000000000000 --- a/java/LinkList.java +++ /dev/null @@ -1,100 +0,0 @@ -public class LinkList { - private static class Node{ - Node next; - T data; - Node(Node next, T data) { - this.next = next; - this.data = data; - } - @Override - public String toString() { - if(data == null) { - return "null"; - }else { - return data.toString(); - } - } - - } - private Node header,tail; - private int size; - - /** - * 添加节点 - * @param data - */ - public void addNode(T data) { - /* - * 此处装逼失败本来应该这样写的null==header && tail==null本代码写法导致 - * 每次调用addNode方法的时候导致tail重新赋值到header上检查的时候只关注是否等于null而没有关注到赋值 - * 从而导致链表元素变少,但是size正确 - * */ - - if(null==(header = tail)) { - header = tail = new Node(null, data); - }else { - tail.next = new Node<>(null, data); - tail = tail.next; - } - size++; - } - - /** - * 反转链表 - */ - public void revorse(){ - if(size == 0 || size == 1) { - return; - } - tail = header; - Node pre = null; - Node curNode = header; - Node nextNode = header.next; - while(nextNode != null) { - curNode.next = pre; - pre = curNode; - curNode = nextNode; - nextNode = curNode.next; - } - curNode.next = pre; - header = curNode; - } - - - @Override - public String toString() { - Node curNode = header; - if(curNode == null) { - return "null"; - } - StringBuilder datas = new StringBuilder(); - T data = curNode.data; - if(data == null) { - datas.append("null"); - }else { - datas.append(data.toString()); - } - Node next = curNode.next; - while(next != null) { - data = next.data; - if(data == null) { - datas.append("null"); - }else { - datas.append(data.toString()); - } - next = next.next; - } - return datas.toString(); - } - - public static void main(String[] args) { - LinkList ls = new LinkList<>(); - ls.addNode("a"); - ls.addNode("b"); - ls.addNode("c"); - ls.addNode("d"); - System.out.println(ls); - ls.revorse(); - System.out.println(ls); - } -} diff --git a/java/LinkedList.java b/java/LinkedList.java deleted file mode 100644 index a8b3f8143b4fdf1acafaf47f8ecf79cabdf2698d..0000000000000000000000000000000000000000 --- a/java/LinkedList.java +++ /dev/null @@ -1,114 +0,0 @@ - -public class LinkedList { - - /** - * The root of the list keeps a reference to both the first and last - * elements of the list. - */ - private LinkedListNode head; - - /** - * Creates a new linked list. - */ - public LinkedList() { - head = new LinkedListNode<>(); - } - - /** - * Returns the first linked list node in the list. - * - * @return the first element of the list. - */ - public LinkedListNode getFirst() { - LinkedListNode node = head.next; - if (node == head) { - return null; - } - return node; - } - - /** - * Returns the last linked list node in the list. - * - * @return the last element of the list. - */ - public LinkedListNode getLast() { - LinkedListNode node = head.previous; - if (node == head) { - return null; - } - return node; - } - - /** - * Adds a node to the beginning of the list. - * - * @param node the node to add to the beginning of the list. - */ - public LinkedListNode addFirst(LinkedListNode node) { - return node.insert(head.next, head); - } - - /** - * Adds an object to the beginning of the list by automatically creating a a - * new node and adding it to the beginning of the list. - * - * @param object the object to add to the beginning of the list. - * @return the node created to wrap the object. - */ - public LinkedListNode addFirst(E object) { - return new LinkedListNode<>(object, head.next, head); - } - - /** - * Adds a node to the end of the list. - * - * @param node the node to add to the beginning of the list. - */ - public LinkedListNode addLast(LinkedListNode node) { - return node.insert(head, head.previous); - } - - /** - * Adds an object to the end of the list by automatically creating a a new node and adding it to the end of the list. - * - * @param object the object to add to the end of the list. - * @return the node created to wrap the object. - */ - public LinkedListNode addLast(E object) { - return new LinkedListNode<>(object, head, head.previous); - } - - /** - * Erases all elements in the list and re-initializes it. - */ - public void clear() { - // Remove all references in the list. - LinkedListNode node = getLast(); - while (node != null) { - node.remove(); - node = getLast(); - } - - // Re-initialize. - head.next = head.previous = head; - } - - /** - * Returns a String representation of the linked list with a comma delimited - * list of all the elements in the list. - * - * @return a String representation of the LinkedList. - */ - @Override - public String toString() { - LinkedListNode node = head.next; - StringBuilder buf = new StringBuilder(); - while (node != head) { - buf.append(node.toString()).append(", "); - node = node.next; - } - return buf.toString(); - } - -} diff --git a/java/LinkedListNode.java b/java/LinkedListNode.java deleted file mode 100644 index fdf3b20c02453739e5395c2255f767b7a601a3bf..0000000000000000000000000000000000000000 --- a/java/LinkedListNode.java +++ /dev/null @@ -1,80 +0,0 @@ - -public class LinkedListNode { - - public LinkedListNode previous; - - public LinkedListNode next; - - public E object; - - /** - * This class is further customized for the CoolServlets cache system. It - * maintains a timestamp of when a Cacheable object was first added to - * cache. Timestamps are stored as long values and represent the number of - * milleseconds passed since January 1, 1970 00:00:00.000 GMT. - *

- * The creation timestamp is used in the case that the cache has a maximum - * lifetime set. In that case, when [current time] - [creation time] > - * [max lifetime], the object will be deleted from cache. - *

- */ - public long timestamp; - - /** - * Constructs an self-referencing node. This node acts as a start/end - * sentinel when traversing nodes in a LinkedList. - */ - public LinkedListNode() { - previous = next = this; - } - - /** - * Constructs a new linked list node. - * - * @param object the Object that the node represents. - * @param next a reference to the next LinkedListNode in the list. - * @param previous a reference to the previous LinkedListNode in the list. - */ - public LinkedListNode(E object, LinkedListNode next, LinkedListNode previous) { - if (next != null && previous != null) { - this.insert(next, previous); - } - this.object = object; - } - - /** - * Removes this node from the linked list that it was a part of. - * - * @return This node; next and previous references dropped - */ - public LinkedListNode remove() { - previous.next = next; - next.previous = previous; - previous = next = null; - return this; - } - - /** - * Inserts this node into the linked list that it will be a part of. - * - * @return This node, updated to reflect previous/next changes - */ - public LinkedListNode insert(LinkedListNode next, LinkedListNode previous) { - this.next = next; - this.previous = previous; - this.previous.next = this.next.previous = this; - return this; - } - - /** - * Returns a String representation of the linked list node by calling the - * toString method of the node's object. - * - * @return a String representation of the LinkedListNode. - */ - @Override - public String toString() { - return object == null ? "null" : object.toString(); - } - -} diff --git a/java/ListForeach.java b/java/ListForeach.java deleted file mode 100644 index 5a1a6c762cb59ee4a66b6872bb1d4bbca800d6d7..0000000000000000000000000000000000000000 --- a/java/ListForeach.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 查询list1然后遍历list1赋值 - * 在外面又建了一个全新的list2,然后把遍历赋值过的list1的每一个元素add到list2中 - * 然后返回list2.。。。。。。 为什么不直接把list1遍历后返回,,这是什么骚操作 脱裤子放屁吗-_- - * @author chenjunhan - * @date 2019-06-21 10:50:02 - */ -public class ListForeach { - @Autowired - private CommentsService commentsService; - - /** - * 获取评论详情 - * @param users - * @param uuid 评论uuid - * @return - */ - @GetMapping("/commentInfo/{uuid}") - public R commentInfo(@LoginUser Users users, @PathVariable("uuid") String uuid){ - //根据uuid查询一级评论 - CommentInfoDTO commentInfoDTO = commentsService.getCommentInfoByKey(uuid); - //根据 commentInfoUUid 查询二级评论列表 - List list1 = commentsService.getCommentsListByReplyTo(commentInfoDTO.getUuid()); - /** - * 这list是干啥了 一脸懵逼 - */ - List list2 = Lists.newArrayList(); - list1.forEach(commentsLowerDTO -> { - //二级评论点赞存放地址 - String secondLevelPraiseKey = "Comments:"+ uuid + ; - if (redisUtils.hExists(secondLevelPraiseKey, commentsLowerDTO.getUuid())) { - commentsLowerDTO.setDisplayPraises(redisUtils.hGet(secondLevelPraiseKey, commentsLowerDTO.getUuid()).toString()); - } - if (users != null) { - //判断该用户是否点赞 - String praiseSetKey = CommonConstants.USER_PREFIX + CommonConstants.REDIS_NAMESPACE + users.getId() + CommonConstants.REDIS_NAMESPACE + commentsLowerDTO.getFirstLevelCommentId() + CommonConstants.REDIS_NAMESPACE + CommonConstants.COMMENTS_SUFFIX + CommonConstants.REDIS_NAMESPACE + CommonConstants.PRAISE_SUFFIX + CommonConstants.SHORTVIDEO_SUFFIX + CommonConstants.REDIS_NAMESPACE ; - if (redisUtils.sexist(praiseSetKey, commentsLowerDTO.getUuid())) { - commentsLowerDTO.setHasPraises(true); - } - } - commentsLowerDTO.setDisplayTime(JdttCommonUtils.friendlyFormatByLocalDateTime(commentsLowerDTO.getCreatedAt())); - /** - * 遍历完commentsLowerDTOList 都set过了 然后塞到新list里 - */ - list2.add(commentsLowerDTO); - }); - /** - * 然后把新list2进行setCommentsLowerDTOList,为什么不直接把遍历过的list1 set进去,要再建一个。。。。。。 - */ - commentInfoDTO.setCommentsLowerDTOList(list2); - return new R<>().setMessage("获取评论详情成功").setData(commentInfoDTO); - } - - -} \ No newline at end of file diff --git a/java/LogPrint.java b/java/LogPrint.java deleted file mode 100644 index 01af9c5dcaf54817b6646ce71f3353a5c87d8c0d..0000000000000000000000000000000000000000 --- a/java/LogPrint.java +++ /dev/null @@ -1,14 +0,0 @@ -public class LogPrint { - private static final Logger logger = LoggerFactory.getLogger(LogPrint.class); - - /** - * 只打印异常信息,不打印堆栈信息,出问题找不到错误 - */ - public static void main(String[] args) { - try { - //业务逻辑 - } catch (Exception e){ - logger.error("业务异常:" + e.getMessage()); - } - } -} \ No newline at end of file diff --git a/java/Logger.java b/java/Logger.java deleted file mode 100644 index 59bce8a375aa5d7a10114e2b5e53d79216931003..0000000000000000000000000000000000000000 --- a/java/Logger.java +++ /dev/null @@ -1,381 +0,0 @@ -import org.slf4j.Marker; -// 当时完全不懂包装slf4j什么意思,还以为自己针对市面上的logger进行了封装处理,上次开会的时候这么说,我为了logger的时候像andriod能写个tag,WTF,难道你logger.info('tag:{},xxxxx',tag)这样不行么?为了六个字符创建一个logger和一个loggerFactory -public class Logger { - - /** 日志处理 */ - private org.slf4j.Logger logger; - - public static String separator = " "; - - public Logger(Class clazz) { - logger = org.slf4j.LoggerFactory.getLogger(clazz); - } - - public Logger(String name) { - logger = org.slf4j.LoggerFactory.getLogger(name); - } - - public String getName() { - return logger.getName(); - } - - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - public void trace(String msg) { - logger.trace(msg); - } - - public void trace(String format, Object arg) { - logger.trace(format, arg); - } - - public void trace(String format, Object arg1, Object arg2) { - logger.trace(format, arg1, arg2); - } - - public void trace(String format, Object... arguments) { - logger.trace(format, arguments); - } - - public void trace(String msg, Throwable t) { - logger.trace(msg, t); - } - - public boolean isTraceEnabled(Marker marker) { - return logger.isTraceEnabled(marker); - } - - public void trace(Marker marker, String msg) { - logger.trace(marker, msg); - } - - public void trace(Marker marker, String format, Object arg) { - logger.trace(marker, format, arg); - } - - public void trace(Marker marker, String format, Object arg1, Object arg2) { - logger.trace(marker, format, arg1, arg2); - } - - public void trace(Marker marker, String format, Object... argArray) { - logger.trace(marker, format, argArray); - } - - public void trace(Marker marker, String msg, Throwable t) { - logger.trace(marker, msg, t); - } - - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - public void debug(String msg) { - logger.debug(msg); - } - - public void debug(String format, Object arg) { - logger.debug(format, arg); - } - - public void debug(String format, Object arg1, Object arg2) { - logger.debug(format, arg1, arg2); - } - - public void debug(String format, Object... arguments) { - logger.debug(format, arguments); - } - - public void debug(String msg, Throwable t) { - logger.debug(msg, t); - } - - public boolean isDebugEnabled(Marker marker) { - return logger.isDebugEnabled(marker); - } - - public void debug(Marker marker, String msg) { - logger.debug(marker, msg); - } - - public void debug(Marker marker, String format, Object arg) { - logger.debug(marker, format, arg); - } - - public void debug(Marker marker, String format, Object arg1, Object arg2) { - logger.debug(marker, format, arg1, arg2); - } - - public void debug(Marker marker, String format, Object... arguments) { - logger.debug(marker, format, arguments); - } - - public void debug(Marker marker, String msg, Throwable t) { - logger.debug(marker, msg, t); - } - - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - public void info(String msg) { - logger.info(msg); - } - - public void info(String format, Object arg) { - logger.info(format, arg); - } - - public void info(String format, Object arg1, Object arg2) { - logger.info(format, arg1, arg2); - } - - public void info(String format, Object... arguments) { - logger.info(format, arguments); - } - - public void info(String msg, Throwable t) { - logger.info(msg, t); - } - - public boolean isInfoEnabled(Marker marker) { - return logger.isInfoEnabled(marker); - } - - public void info(Marker marker, String msg) { - logger.info(marker, msg); - } - - public void info(Marker marker, String format, Object arg) { - logger.info(marker, format, arg); - } - - public void info(Marker marker, String format, Object arg1, Object arg2) { - logger.info(marker, format, arg1, arg2); - } - - public void info(Marker marker, String format, Object... arguments) { - logger.info(marker, format, arguments); - } - - public void info(Marker marker, String msg, Throwable t) { - logger.info(marker, msg, t); - } - - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - public void warn(String msg) { - logger.warn(msg); - } - - public void warn(String format, Object arg) { - logger.warn(format, arg); - } - - public void warn(String format, Object... arguments) { - logger.warn(format, arguments); - } - - public void warn(String format, Object arg1, Object arg2) { - logger.warn(format, arg1, arg2); - } - - public void warn(String msg, Throwable t) { - logger.warn(msg, t); - } - - public boolean isWarnEnabled(Marker marker) { - return logger.isWarnEnabled(marker); - } - - public void warn(Marker marker, String msg) { - logger.warn(marker, msg); - } - - public void warn(Marker marker, String format, Object arg) { - logger.warn(marker, format, arg); - } - - public void warn(Marker marker, String format, Object arg1, Object arg2) { - logger.warn(marker, format, arg1, arg2); - } - - public void warn(Marker marker, String format, Object... arguments) { - logger.warn(marker, format, arguments); - } - - public void warn(Marker marker, String msg, Throwable t) { - logger.warn(marker, msg, t); - } - - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - public void error(String msg) { - logger.error(msg); - } - - public void error(String format, Object arg) { - logger.error(format, arg); - } - - public void error(String format, Object arg1, Object arg2) { - logger.error(format, arg1, arg2); - } - - public void error(String format, Object... arguments) { - logger.error(format, arguments); - } - - public void error(String msg, Throwable t) { - logger.error(msg, t); - } - - public boolean isErrorEnabled(Marker marker) { - return logger.isErrorEnabled(marker); - } - - public void error(Marker marker, String msg) { - logger.error(marker, msg); - } - - public void error(Marker marker, String format, Object arg) { - logger.error(marker, format, arg); - } - - public void error(Marker marker, String format, Object arg1, Object arg2) { - logger.error(marker, format, arg1, arg2); - } - - public void error(Marker marker, String format, Object... arguments) { - logger.error(marker, format, arguments); - } - - public void error(Marker marker, String msg, Throwable t) { - logger.error(marker, msg, t); - } - - /** - * trace等级日志,小于debug - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param args 变量对应的参数 - */ - public void trace(Tag tag, String format, Object... args) { - logger.trace(merge(tag, format), args); - } - - /** - * trace等级日志,小于debug - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param e 需在日志中堆栈打印的异常 - */ - public void trace(Tag tag, String format, Throwable e) { - logger.trace(merge(tag, format), e); - } - - /** - * debug等级日志,小于info - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param args 变量对应的参数 - */ - public void debug(Tag tag, String format, Object... args) { - logger.debug(merge(tag, format), args); - } - - /** - * debug等级日志,小于info - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param e 需在日志中堆栈打印的异常 - */ - public void debug(Tag tag, String format, Throwable e) { - logger.debug(merge(tag, format), e); - } - - /** - * info等级日志,小于warn - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param args 变量对应的参数 - */ - public void info(Tag tag, String format, Object... args) { - logger.info(merge(tag, format), args); - } - - /** - * info等级日志,小于warn - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param e 需在日志中堆栈打印的异常 - */ - public void info(Tag tag, String format, Throwable e) { - logger.info(merge(tag, format), e); - } - - /** - * warn等级日志,小于error - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param args 变量对应的参数 - */ - public void warn(Tag tag, String format, Object... args) { - logger.warn(merge(tag, format), args); - } - - /** - * warn等级日志,小于error - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param e 需在日志中堆栈打印的异常 - */ - public void warn(Tag tag, String format, Throwable e) { - logger.warn(merge(tag, format), e); - } - - /** - * error等级日志 - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param args 变量对应的参数 - */ - public void error(Tag tag, String format, Object... args) { - logger.error(merge(tag, format), args); - } - - /** - * error等级日志 - * - * @param tag 日志标签 - * @param format 格式文本,{} 代表变量 - * @param e 需在日志中堆栈打印的异常 - */ - public void error(Tag tag, String format, Throwable e) { - logger.error(merge(tag, format), e); - } - - // 合并 - private String merge(Tag tag, String format) { - if (tag == null) { - return format; - } - - return tag.toString() + separator + format; - } - -} \ No newline at end of file diff --git a/java/LossMoney.java b/java/LossMoney.java deleted file mode 100644 index c394b1c52fd25b055cbfc3d39cb4ff89b417a6a2..0000000000000000000000000000000000000000 --- a/java/LossMoney.java +++ /dev/null @@ -1,48 +0,0 @@ -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import javax.annotation.Resource; - -@Service -public class TryCatchTransaction { - @Resource - private ServiceA serviceA; - @Resource - private ServiceB serviceB; - - @Transactional - public void exchange(){ - //一次操作1000个用户 - for(int i=0;i<1000;i++) { - - serviceA.doExchangeA(); - try { - serviceB.doExchangeB(); - //抛出某个异常 - throw new IllegalArgumentException("抛出某个异常"); - } catch (Exception e) { - - } - - } - - } -} - - -@Service -class ServiceA{ - @Transactional - public void doExchangeA(){ - //发送兑换劵,一张100元 - } - -} - -@Service -class ServiceB{ - @Transactional - public void doExchangeB(){ - //记录数据到B表 - } -} diff --git a/java/NBStream.java b/java/NBStream.java deleted file mode 100644 index 3df1de77ad5ae7852960711869f6a7eafd615900..0000000000000000000000000000000000000000 --- a/java/NBStream.java +++ /dev/null @@ -1,87 +0,0 @@ -//Stream 用的66的 -final EventAction eventAction = redisObj( - EventActionKey + distributionEventId, - () -> Optional - .of(distributionEventId) - .map(eventId -> { - final EventActionExample example = new EventActionExample(); - example.createCriteria() - .andEventIdEqualTo(eventId) - .andTriggerTypeEqualTo(EnumEventTriggerType.DISTRIBUTION_PURCHASE.getCode().byteValue()); - return example; - }) - .map(eventActionMapper::selectByExample) - .filter(StringUtil::isNotEmpty) - .map(e -> e.get(0)).orElseThrow(() -> ExceptionUtil.createParamException("事件触发信息不存在")) - , EventAction.class); - final AwardConfig awardConfig = redisObj(EventConfigKey + eventAction.getId(), - () -> Optional.ofNullable(eventAction.getId()) - .map(actionId -> { - final AwardConfigExample example = new AwardConfigExample(); - example.createCriteria() - .andActionIdEqualTo(actionId); - return example; - }) - .map(awardConfigMapper::selectByExample) - .filter(StringUtil::isNotEmpty) - .map(e -> e.get(0)).orElseThrow(() -> ExceptionUtil.createParamException("xxx")), - AwardConfig.class - ); - Optional.of(req) - .map(e -> e.clueUid) - .map(id -> { - final ClueExample example = new ClueExample(); - example.createCriteria() - .andClueUidEqualTo(id) - .andDeletedEqualTo(false) - .andReceivedEqualTo(false) - .andCreateTimeGreaterThan(now - cluetime); - example.setOrderByClause("create_time asc"); - return example; - }) // 获取该被邀请人所有未过期且未被领取的线索的线索 - .map(clueMapper::selectByExample) - .filter(StringUtil::isNotEmpty) - .ifPresent(clues -> { - final ClueResp clueResp = Optional.of(req) - .filter(c -> { - c.count = clues.size(); - return true; - }) - .map(this::awardValue) - .orElseThrow(() -> ExceptionUtil.createParamException("参数错误")); - final Integer specialId = req.getIsHead() - ? clues.get(0).getId() - : clues.get(clues.size() - 1).getId(); - clues.stream() - .peek(clue -> { - final AwardConfig awardConfigclone = Optional.of(awardConfig) - .map(JSONUtil::obj2Json) - .map(json -> JSONUtil.json2Obj(json, AwardConfig.class)) - .orElseGet(AwardConfig::new); - awardConfigclone.setMoney( - Optional.of(clue.getId()) - .filter(specialId::equals) - .map(e -> clueResp.specialReward.longValue()) - .orElse(clueResp.otherAverageReward.longValue()) - ); - eventActionService.assembleAward( - awardConfigclone, - clue.getAdviserUid(), - clue.getAdviserUid(), - clue.getClueUid(), - eventAction, - new PasMessageParam(), - clue.getId(), - AwardRelationType.Clud.code() - ); - }) - .forEach(clue -> { - clue.setOrderNo(req.orderNo); - clue.setCommodityName(req.commodityName); - clue.setOrderAmount(req.orderAmount); - clue.setReceived(true); - clue.setModifyTime(now); - clueMapper.updateByPrimaryKeySelective(clue); - }); - } - ); \ No newline at end of file diff --git a/java/NewFeatures.java b/java/NewFeatures.java deleted file mode 100644 index f53b055beb97b9cee09068c7f87a604838e3dd42..0000000000000000000000000000000000000000 --- a/java/NewFeatures.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ccservice.ydx.common.authentication; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.stream.Collectors; - -/** - * User:Administrator Date 2019/7/10 Time 17:58 - */ -public class NewFeatures { - - public static void main(String[] args) { - // 创建map - HashMap> map = new HashMap<>(); - List defaultList = Arrays.stream(new int[2]).boxed().collect(Collectors.toList()); - // java8新特性,根据key获取value,key不存在,取默认值 - List listA = map.getOrDefault(1, defaultList); - listA.add(1); - System.out.println("listA:" + listA); - List listB = map.getOrDefault(2, defaultList); - listB.add(2); - System.out.println("listB:" + listB); - } -} diff --git a/java/NewId.java b/java/NewId.java deleted file mode 100644 index f22d24297d3d308eafaf25abafa7999633958f92..0000000000000000000000000000000000000000 --- a/java/NewId.java +++ /dev/null @@ -1,28 +0,0 @@ - -import Java.util.Random; - -class SomeBizOperation { - - /*疯狂到令人发指*/ - public String getNewId() { - - while (true) { - String id = newId(10); - var obj = SomeTableQuery.getById(id); - if (obj == null) { - return obj; - } - } - } - - private String newId(int length) { - String str = "0123456789"; - var random = new Random(); - StringBuffer sb = new StringBuffer(); - for (int i =0; i> queryMoreAssistantSubsidiaryLedger(AssistantSubsidiaryLedgerQueryParam queryParam) { - - Table> resultTable = HashBasedTable.create(); - // 这个 list 有 2w 条数据 - for (Assistant assistant : assistants) { - - //这个 list 从数据库拿,4w 条数据,数据库交互,结合外面的看,2w * 4w,然后加上基础方法 baseQueryAssistantSubsidiaryLedgerRowsMap 的循环,线上直接 OOM 了 - List balances = balanceService.selectFromYear(customerId, accountSetId, PeriodUtils.getYear(fixedBeginPeriod)); - Map> rowMap = baseQueryAssistantSubsidiaryLedgerRowsMap( - titles, - AssistantType.fromCode(queryParam.getAssistantType()), - assistant.getId(), - fixedBeginPeriod, - endPeriod, - null, - balances); - for (Map.Entry> temp : rowMap.entrySet()) { - resultTable.put(temp.getKey(), assistant, temp.getValue()); - } - } - return resultTable; -} - -// 这是个基础方法 -private Map> baseQueryAssistantSubsidiaryLedgerRowsMap( - List titles, - AssistantType assistantType, - Integer assistantId, - String beginPeriod, - String endPeriod, - BookType ledgerType, - List balances) { - Map> resultMap = Maps.newHashMap(); - - List titleCodes = Lists.newArrayList(Lists.transform(titles, new Function() { - @Override - public String apply(CustomerAccountTitle input) { - return input.getCode(); - } - })); - - for (AssistantTitleBalance balance : balances) { - for (String titleCode : titleCodes) { - if (!balance.getAccountTitleCode().startsWith(titleCode)) { - continue; - } - List tempBalances = balanceTable.get(titleCode, year); - if (tempBalances == null) { - tempBalances = new ArrayList(); - balanceTable.put(titleCode, year, tempBalances); - } - tempBalances.add(balance); - } - } - Table> entryTable = HashBasedTable.create(); - // 这里就就恐怖了,每次查询有 2w 条数据,数据库交互 - Map documentMap = documentService.selectFromYear(beginPeriod); - for (AccountDocument document : documentMap.values()) { - // 内层遍历,每次 10 + - for (AccountEntry entry : document.getEntryList()) { - // 再遍历,最外层有 200+ - for (String titleCode : titleCodes) { - if (!entry.isUseAssistant() || AssistantType.fromCode(entry.getAssistantType()) != assistantType || !assistantId.equals(entry.getAssistantId()) || !entry.getAccountTitleCode().startsWith(titleCode)) { - continue; - } - List entries = entryTable.get(titleCode, document.getAccountPeriod()); - if (entries == null) { - entries = new ArrayList(); - entryTable.put(titleCode, document.getAccountPeriod(), entries); - } - entries.add(entry); - } - } - } - List periods = PeriodUtils.getPeriodsUpTo(beginPeriod, endPeriod); - for (CustomerAccountTitle title : titles) { - if (ledgerType != null && AccountTitleUtils.getBookType(title) == ledgerType) { - resultMap.put(title, buildSubsidiaryLedgerRows(periods, title, balanceTable.row(title.getCode()), entryTable.row(title.getCode()), documentMap, ledgerType, PeriodUtils.getIntegerYear(beginPeriod))); - } else if (ledgerType == null) { - resultMap.put(title, buildSubsidiaryLedgerRows(periods, title, balanceTable.row(title.getCode()), entryTable.row(title.getCode()), documentMap, AccountTitleUtils.getBookType(title), PeriodUtils.getIntegerYear(beginPeriod))); - } - } - return resultMap; -} \ No newline at end of file diff --git a/java/OnlineShopBiz.java b/java/OnlineShopBiz.java deleted file mode 100644 index e2e8df205dd0bea6799c67ab42b26e9f7fc403ed..0000000000000000000000000000000000000000 --- a/java/OnlineShopBiz.java +++ /dev/null @@ -1,238 +0,0 @@ -/** - * 线上店铺表 - * - * @author 逻辑鬼才 - * @date 2018-11-06 19:01:04 - */ -@SuppressWarnings("ALL") -@Service -@Slf4j -public class OnlineShopBiz { - - @Autowired - private OnlineShopMapper onlineShopMapper; - @Autowired - private ShopRelationCategoryMapper shopRelationCategoryMapper; - @Autowired - private MerchantMapper merchantMapper; - @Autowired - private OfflineShopMapper offlineShopMapper; - @Autowired - private MerchantAuditMapper merchantAuditMapper; - @Autowired - private MerchantAuditHostoryMapper merchantAuditHostoryMapper; - - @Autowired - private CollectionBankMapper collectionBankMapper; - - @Autowired - private CollectionTreasureMapper collectionTreasureMapper; - - @Autowired - private GetLatAndLon getLatAndLon; - - @Autowired - private CollectionWxpayMapper collectionWxpayMapper; - - @Autowired - private RecommendShopMapper recommendShopMapper; - - @Autowired - private MerchantUserMapper merchantUserMapper; - - public static Integer onlineType = 0; - - /** - * 添加线上店铺接口 - * - * @param addOnlineShopRequestVo - * @author gaolei - * @email gl_code@163.com - * @date 2018-11-06 - */ - @Transactional(rollbackFor = Exception.class) - public ApiResponse addOnlineShop(AddOnlineShopRequestVo addOnlineShopRequestVo) { - OnlineShop onlineShop = new OnlineShop(); - if (addOnlineShopRequestVo.getMerchantUserId() == null) { - return ApiResponse.buildCommonErrorResponse("登录信息错误"); - } - Merchant merchant = merchantMapper.getByMerchantUserId(addOnlineShopRequestVo.getMerchantUserId()); - if (onlineShopMapper.getByMerchantId(merchant.getId()) != null) { - return ApiResponse.buildCommonErrorResponse("同一个商户只能添加一个商铺"); - } - if (addOnlineShopRequestVo.getCategoryId().size()==0||addOnlineShopRequestVo.getCategoryId()==null){ - TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return ApiResponse.buildCommonErrorResponse("请选择经营类目"); - } -// if (!StringUtils.isEmpty(addOnlineShopRequestVo.getCommunicationMerchantId())) { -// if (onlineShopMapper.getCommunicationMerchantIdCount(addOnlineShopRequestVo.getCommunicationMerchantId()) > 0) { -// return ApiResponse.buildCommonErrorResponse("通联商户编号重复"); -// } -// } - boolean isRepeat = addOnlineShopRequestVo.getCategoryId().size() != new HashSet(addOnlineShopRequestVo.getCategoryId()).size(); - if (isRepeat) { - TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return ApiResponse.buildCommonErrorResponse("经营类目重复"); - } - try { - //OnlineShop shop = onlineShopMapper.getByMerchantIdRemove(merchant.getId()); - onlineShop.setId(UUID.randomUUID().toString().replace("-", "")); - onlineShop.setMerchantId(merchant.getId()); - onlineShop.setShopName(addOnlineShopRequestVo.getShopName()); - onlineShop.setAddress(addOnlineShopRequestVo.getAddress()); - onlineShop.setShopContact(addOnlineShopRequestVo.getShopContact()); - onlineShop.setShopContactPhone(addOnlineShopRequestVo.getShopContactPhone()); - onlineShop.setShopLicense(addOnlineShopRequestVo.getShopLicense()); - onlineShop.setBusinessLicense(addOnlineShopRequestVo.getBusinessLicense()); - onlineShop.setStorageStatus(0); - onlineShop.setAuditStatus(1); - onlineShop.setShopAdvert(addOnlineShopRequestVo.getShopAdvert()); - onlineShop.setCommunicationMerchantId(addOnlineShopRequestVo.getCommunicationMerchantId()); - String storeSn = RandomUtil.testNum(7); - onlineShop.setStoreSn(storeSn); - - String provice = onlineShopMapper.selectCityById(addOnlineShopRequestVo.getProvinceId()); - String city = onlineShopMapper.selectCityById(addOnlineShopRequestVo.getCityId()); - String area = onlineShopMapper.selectCityById(addOnlineShopRequestVo.getAreaId()); - onlineShop.setCity(city); - onlineShop.setProvince(provice); - onlineShop.setArea(area); - - String a = getLatAndLon.getResponse(provice + city + area + addOnlineShopRequestVo.getAddress()); - if (a != null) { - String[] longitudeAndLatitude = a.split(","); - onlineShop.setLongitude(longitudeAndLatitude[0]); - onlineShop.setLatitude(longitudeAndLatitude[1]); - } else { - onlineShop.setLongitude("0"); - onlineShop.setLatitude("0"); - } - onlineShop.setCreateBy(addOnlineShopRequestVo.getMerchantUserId()); - onlineShop.setCreateTime(new Date()); - //修改店铺类型 - if (merchant.getShopType() == null) { - merchant.setShopType(addOnlineShopRequestVo.getShopType()); - merchant.setIsRemove(0); - merchant.setUpdateBy(addOnlineShopRequestVo.getMerchantUserId()); - merchant.setUpdateTime(new Date()); - } else { - OnlineShop shop = onlineShopMapper.getByMerchantIdRemove(merchant.getId()); - if (shop!=null){ - onlineShop.setId(shop.getId()); - onlineShopMapper.deleteScore(shop.getId()); - } - onlineShopMapper.deleteByMerchantId(merchant.getId()); - merchantAuditMapper.deleteByMerchantId(merchant.getId()); - shopRelationCategoryMapper.deleteByMerchantId(merchant.getId()); - collectionBankMapper.deleteByMerchantId(merchant.getId()); - collectionTreasureMapper.deleteByMerchantId(merchant.getId()); - collectionWxpayMapper.deleteByMerchantId(merchant.getId()); - merchant.setShopType(addOnlineShopRequestVo.getShopType()); - merchant.setIsRemove(0); - merchant.setUpdateBy(addOnlineShopRequestVo.getMerchantUserId()); - merchant.setUpdateTime(new Date()); - } - merchantMapper.updateShopType(merchant); - //店铺类目关系 - - addOnlineShopRequestVo.getCategoryId().forEach(categoryId -> { - ShopRelationCategory shopRelationCategory = new ShopRelationCategory(); - shopRelationCategory.setId(UUID.randomUUID().toString().replace("-", "")); - shopRelationCategory.setMerchantId(merchant.getId()); - shopRelationCategory.setShopId(onlineShop.getId()); - shopRelationCategory.setCategoryId(categoryId); - shopRelationCategory.setCretaeBy(addOnlineShopRequestVo.getMerchantUserId()); - shopRelationCategory.setCreateTime(new Date()); - shopRelationCategoryMapper.saveRelationCategory(shopRelationCategory); - }); - if (addOnlineShopRequestVo.getPayeeAccount() != null || addOnlineShopRequestVo.getTreasureAppId() != null - || addOnlineShopRequestVo.getPrivateKey() != null || addOnlineShopRequestVo.getPublicKey() != null || addOnlineShopRequestVo.getAlipayRsaType() != null) { - if (addOnlineShopRequestVo.getPayeeAccount() != null && addOnlineShopRequestVo.getTreasureAppId() != null - && addOnlineShopRequestVo.getPrivateKey() != null && addOnlineShopRequestVo.getPublicKey() != null - && addOnlineShopRequestVo.getAlipayRsaType() != null) { - CollectionTreasure collectionTreasure = new CollectionTreasure(); - collectionTreasure.setId(UUID.randomUUID().toString().replace("-", "")); - collectionTreasure.setMerchantId(merchant.getId()); - collectionTreasure.setShopId(onlineShop.getId()); - collectionTreasure.setAppid(addOnlineShopRequestVo.getTreasureAppId()); - collectionTreasure.setPayeeAccount(addOnlineShopRequestVo.getPayeeAccount()); - collectionTreasure.setPrivateKey(addOnlineShopRequestVo.getPrivateKey()); - collectionTreasure.setPublicKey(addOnlineShopRequestVo.getPublicKey()); - collectionTreasure.setAlipayRsaType(addOnlineShopRequestVo.getAlipayRsaType()); - collectionTreasure.setCreateBy(addOnlineShopRequestVo.getMerchantUserId()); - collectionTreasure.setCreateTime(new Date()); - onlineShop.setCollectionTreasureId(collectionTreasure.getId()); - onlineShop.setUpdateBy(addOnlineShopRequestVo.getMerchantUserId()); - onlineShop.setUpdateTime(new Date()); - collectionTreasureMapper.saveCollectionTreasure(collectionTreasure); - } else { - TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return ApiResponse.buildCommonErrorResponse("支付宝参数不完整"); - } - - } - if (addOnlineShopRequestVo.getWxpayAppId() != null || addOnlineShopRequestVo.getMerchantsNumber() != null - || addOnlineShopRequestVo.getSecret() != null || addOnlineShopRequestVo.getWechatAppSecret() != null - || addOnlineShopRequestVo.getWechatCertPwd() != null || addOnlineShopRequestVo.getWechatCertId() != null) { - if (addOnlineShopRequestVo.getWxpayAppId() != null && addOnlineShopRequestVo.getMerchantsNumber() != null - && addOnlineShopRequestVo.getSecret() != null && addOnlineShopRequestVo.getWechatAppSecret() != null - && addOnlineShopRequestVo.getWechatCertPwd() != null && addOnlineShopRequestVo.getWechatCertId() != null) { - CollectionWxpay collectionWxpay = new CollectionWxpay(); - collectionWxpay.setId(UUID.randomUUID().toString().replace("-", "")); - collectionWxpay.setMerchantId(merchant.getId()); - collectionWxpay.setShopId(onlineShop.getId()); - collectionWxpay.setSecret(addOnlineShopRequestVo.getSecret()); - collectionWxpay.setAppId(addOnlineShopRequestVo.getWxpayAppId()); - collectionWxpay.setMerchantsNumber(addOnlineShopRequestVo.getMerchantsNumber()); - collectionWxpay.setWechatAppSecret(addOnlineShopRequestVo.getWechatAppSecret()); - collectionWxpay.setWechatCertId(addOnlineShopRequestVo.getWechatCertId()); - collectionWxpay.setWechatCertPwd(addOnlineShopRequestVo.getWechatCertPwd()); - collectionWxpay.setCreateBy(addOnlineShopRequestVo.getMerchantUserId()); - collectionWxpay.setCreateTime(new Date()); - onlineShop.setCollectionWxpayId(collectionWxpay.getId()); - onlineShop.setUpdateBy(addOnlineShopRequestVo.getMerchantUserId()); - onlineShop.setUpdateTime(new Date()); - collectionWxpayMapper.saveCollectionWxpay(collectionWxpay); - } else { - TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return ApiResponse.buildCommonErrorResponse("微信参数不完整"); - } - - } - if (addOnlineShopRequestVo.getCollectionBank() != null || addOnlineShopRequestVo.getCollectionUser() != null - || addOnlineShopRequestVo.getCollectionBankCard() != null || addOnlineShopRequestVo.getMerchantNo() != null) { - if (addOnlineShopRequestVo.getCollectionBank() != null && addOnlineShopRequestVo.getCollectionUser() != null - && addOnlineShopRequestVo.getCollectionBankCard() != null && addOnlineShopRequestVo.getMerchantNo() != null) { - CollectionBank collectionBank = new CollectionBank(); - collectionBank.setId(UUID.randomUUID().toString().replace("-", "")); - collectionBank.setMerchantId(merchant.getId()); - collectionBank.setShopId(onlineShop.getId()); - collectionBank.setCollectionBank(addOnlineShopRequestVo.getCollectionBank()); - collectionBank.setCollectionUser(addOnlineShopRequestVo.getCollectionUser()); - collectionBank.setCollectionBankCard(addOnlineShopRequestVo.getCollectionBankCard()); - collectionBank.setMerchantsNumber(addOnlineShopRequestVo.getMerchantNo()); - collectionBank.setCreateBy(addOnlineShopRequestVo.getMerchantUserId()); - collectionBank.setCreateTime(new Date()); - onlineShop.setCollectionBankId(collectionBank.getId()); - onlineShop.setUpdateBy(addOnlineShopRequestVo.getMerchantUserId()); - onlineShop.setUpdateTime(new Date()); - collectionBankMapper.saveCollectionBank(collectionBank); - } else { - TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return ApiResponse.buildCommonErrorResponse("银行卡参数不完整"); - } - } - if (addOnlineShopRequestVo.getCollectionBankCard() == null && addOnlineShopRequestVo.getWxpayAppId() == null && addOnlineShopRequestVo.getPayeeAccount() == null) { - TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return ApiResponse.buildCommonErrorResponse("至少一种支付信息"); - } - //保存添加线上店铺审核 - saveOnlineShopAudit(addOnlineShopRequestVo, merchant, onlineShop); - onlineShopMapper.saveOnlineShop(onlineShop); - } catch (Exception e) { - TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return ApiResponse.buildCommonErrorResponse("线上店铺添加失败"); - } - return ApiResponse.buildResponse(200, "线上店铺添加成功"); - } -} \ No newline at end of file diff --git a/java/Page.java b/java/Page.java deleted file mode 100644 index 3adbad466165c9338c8924e37d6d953d66f0b073..0000000000000000000000000000000000000000 --- a/java/Page.java +++ /dev/null @@ -1,40 +0,0 @@ - -/** - * 分页对象 - * @author youao.du@gmail.com - * @time 13:33 - * @params - */ -@Data -class PageDto { - private Integer pageNum = 1; - - private Integer pageSize = 1; - - // 计算起始页 - public void setPageNum(Integer pageNum) { - if (pageNum == null || pageNum <= 0) { - this.pageNum = 1; - } else { - this.pageNum = pageNum; - } - } - - public void calcPageNum() { - // 设置第一个limit参数 - setPageNum((getPageNum() - 1); * getPageSize()) - } -} - - -/** - * 这个问题想了很久。这样就导致了。 - * 第一页永远显示不了数据库中的第一行数据。 - * - * 至于原因。应该很清晰 - * 计算起始坐标 当前页 - 1 * 页面容量 - * 所以第一页 1 - 1 = 0 这个时候调用了set方法。 - * set方法刚进入时进行了判断。<= 0 的话。 直接变1 - * - * 这是我写的代码。当时调这个错误调了一下午。白白浪费了一下午 - */ \ No newline at end of file diff --git a/java/PhoneRuleValidate.java b/java/PhoneRuleValidate.java deleted file mode 100644 index 763134aae5d21915974cb4ebac86dfae110ac1cd..0000000000000000000000000000000000000000 --- a/java/PhoneRuleValidate.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.liuh.study_exam.util; - -/** - * @author liuh - * @date 2018年6月24日 上午9:54:18 - */ -public class PhoneRuleValidate { - - public static void main(String[] args) { - String phoneStr = "13800000001"; - System.out.println(new PhoneRuleValidate().validatePhone(phoneStr)); - } - - public String validatePhone(String phoneStr) { - if (phoneStr != null) { - if (phoneStr.length() == 11) { - if (isNumeric(phoneStr)) { - if (phoneStr.startsWith("130") || phoneStr.startsWith("131") || phoneStr.startsWith("132") - || phoneStr.startsWith("134") || phoneStr.startsWith("135") || phoneStr.startsWith("136") - || phoneStr.startsWith("137") || phoneStr.startsWith("138") || phoneStr.startsWith("139") - || phoneStr.startsWith("140") || phoneStr.startsWith("141") || phoneStr.startsWith("142") - || phoneStr.startsWith("144") || phoneStr.startsWith("145") || phoneStr.startsWith("146") - || phoneStr.startsWith("147") || phoneStr.startsWith("148") || phoneStr.startsWith("149") - || phoneStr.startsWith("150") || phoneStr.startsWith("151") || phoneStr.startsWith("152") - || phoneStr.startsWith("154") || phoneStr.startsWith("155") || phoneStr.startsWith("156") - || phoneStr.startsWith("157") || phoneStr.startsWith("158") || phoneStr.startsWith("159") - || phoneStr.startsWith("170") || phoneStr.startsWith("171") || phoneStr.startsWith("172") - || phoneStr.startsWith("174") || phoneStr.startsWith("175") || phoneStr.startsWith("176") - || phoneStr.startsWith("177") || phoneStr.startsWith("178") || phoneStr.startsWith("179") - || phoneStr.startsWith("180") || phoneStr.startsWith("181") || phoneStr.startsWith("182") - || phoneStr.startsWith("184") || phoneStr.startsWith("185") || phoneStr.startsWith("186") - || phoneStr.startsWith("187") || phoneStr.startsWith("188") || phoneStr.startsWith("189")) { - return "手机号正确"; - } else { - return "手机号规则错误"; - } - } else { - return "手机号必须为数字"; - } - } else { - return "手机号长度必须为11位"; - } - } else { - return "手机号不能为空"; - } - } - - /** - * @note 是否为数字 - * @author liuh - * @date 2018年6月24日 上午10:14:56 - */ - public static boolean isNumeric(String str) { - for (int i = str.length(); --i >= 0;) { - if (!Character.isDigit(str.charAt(i))) { - return false; - } - } - return true; - } -} diff --git a/java/PreAfterList.java b/java/PreAfterList.java deleted file mode 100644 index f73552c0ace26401f73e3f2aff7c11882ca91f21..0000000000000000000000000000000000000000 --- a/java/PreAfterList.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.gitee.bullshit.code; - -import com.baomidou.mybatisplus.core.toolkit.Wrappers; - -public class PreAfterList { - - // 需求:根据 ID 获取指定 ID 文章,包括当前 ID 及上一条和下一条的内容集合 - // 原样贴出天才同事的操作如下,看完肺都气炸了!! 看官们你觉得正确做法是什么?? - public ArticleVO getArticleVO(Long id) { - ArticleVO vo = new ArticleVO(getById(id)); - List
list = articleMapper.selectList(Wrappers.
lambdaQuery().orderByDesc(Article::getCreateTime)); - if (list.size() == 1) { - return vo; - } else if (list.size() == 2) { - if (list.get(0).getId().equals(vo.getId())) { - // first is itself - vo.setAfter(list.get(1)); - } else { - vo.setPre(list.get(0)); - } - } else { - // > 3 - Article pre = list.get(0); - if (pre.getId().equals(vo.getId())) { - vo.setPre(null); - vo.setAfter(list.get(1)); - return vo; - } - for (Article article : list) { - if (article.getId().equals(vo.getId())) { - vo.setPre(pre); - int preIdx = list.indexOf(pre); - if (preIdx + 2 >= list.size()) { - break; - } - vo.setAfter(list.get(preIdx + 2)); - break; - } else { - pre = article; - } - } - } - return vo; - } -} diff --git a/java/PrintEachElementFromVectorInMoreThread.java b/java/PrintEachElementFromVectorInMoreThread.java deleted file mode 100644 index 3025fc2480d5ef406db961c003d2a2d607271732..0000000000000000000000000000000000000000 --- a/java/PrintEachElementFromVectorInMoreThread.java +++ /dev/null @@ -1,108 +0,0 @@ -import java.util.Vector; -import java.util.concurrent.CyclicBarrier; - -/** - *
- *
- * 在多线程的场景下,打印java.util.Vector中的每个元素。
- *
- *      我们都知道,在多线程场景下不能使用ArrayList,应该用Vector,因为别人都告诉我们Vector是线程安全的。
- *      但其实,这里是有坑的!!!>_<啊啊啊啊啊啊啊啊啊~
- *
- *      代码发到生产环境后却发现经常报错:java.util.ConcurrentModificationException
- *
- *      例如在下面的代码中,遍历容器 Vector只是简单的把每个元素打印出来,这就存在并发问题。
- *      那么个问题如何修改呢?大家可以试一下。
- * 
- * - * @author AnXiaole - * @date 2019/6/10 17:17 - */ -public class PrintEachElementFromVectorInMoreThread { - - public static void main(String[] args) throws InterruptedException { - - error(); // 错误情况演示 - - // correct(); // 如果想要尝试修改,可在correct()方法中修改。 - } - - /** - * 执行一下,应该会报如下异常: - *
-     *     Exception in thread "Thread-0" java.util.ConcurrentModificationException
-             at java.util.Vector$Itr.checkForComodification(Vector.java:1184)
-             at java.util.Vector$Itr.next(Vector.java:1137)
-             at PrintEachElementFromVectorInMoreThread.lambda$error$0(PrintEachElementFromVectorInMoreThread.java:36)
-             at java.lang.Thread.run(Thread.java:745)
-     * 
- */ - private static void error() { - // 实际上我的业务代码是没有CyclicBarrier的,CyclicBarrier只是为了演示多个线程'同时'执行的情况。 - // new Thread()的过程比较慢,如果这里不加CyclicBarrier,可能第二个线程还没创建好,第一个线程就执行完了。从而打不到多线程同时执行的目的。 - // 也是因为测试环境并发量比较小导致在测试环境根本就没有发现这个bug。>_< - CyclicBarrier cyclicBarrier = new CyclicBarrier(2); - - - Vector numbers = new Vector<>(); - - new Thread(() -> { - try { - cyclicBarrier.await(); - } catch (Exception e) { - } - - for (int i = 0; i < 1000; i++) { - numbers.add(i); - } - }).start(); - - - new Thread(() -> { - try { - cyclicBarrier.await(); - } catch (Exception e) { - } - - for (int i = 0; i < 10; i++) { - for (Integer number : numbers) { - System.out.println(number); - } - } - }).start(); - } - - /** - * 大家可以尝试再这里修改并提交修改后的代码。 - */ - private static void correct() { - CyclicBarrier cyclicBarrier = new CyclicBarrier(2); - Vector numbers = new Vector<>(); - - - new Thread(() -> { - try { - cyclicBarrier.await(); - } catch (Exception e) { - } - - for (int i = 0; i < 10; i++) { - for (Integer number : numbers) { - System.out.println(number); - } - } - }).start(); - - new Thread(() -> { - try { - cyclicBarrier.await(); - } catch (Exception e) { - } - - for (int i = 0; i < 1000; i++) { - numbers.add(i); - } - }).start(); - } - -} diff --git a/java/QuartzUrgeRepayUserAlloca.java b/java/QuartzUrgeRepayUserAlloca.java deleted file mode 100644 index a13e52d8eece1f3ea64c5f4d046064ff5ab3b95d..0000000000000000000000000000000000000000 --- a/java/QuartzUrgeRepayUserAlloca.java +++ /dev/null @@ -1,376 +0,0 @@ -package com.nmoney.cashloan.manage.job; - -import com.nmoney.cashloan.cl.domain.BorrowRepayLog; -import com.nmoney.cashloan.cl.domain.UrgeRepayOrder; -import com.nmoney.cashloan.cl.domain.UrgeRepayOrderFlow; -import com.nmoney.cashloan.cl.domain.UrgeRepayUserAlloca; -import com.nmoney.cashloan.cl.enums.UrgeRepayType; -import com.nmoney.cashloan.cl.model.UrgeRepayOrderModel; -import com.nmoney.cashloan.cl.service.BorrowRepayLogService; -import com.nmoney.cashloan.cl.service.ClUrgeRepayUserAllocaService; -import com.nmoney.cashloan.cl.service.UrgeRepayOrderFlowService; -import com.nmoney.cashloan.cl.service.UrgeRepayOrderService; -import com.nmoney.cashloan.core.common.context.Global; -import com.nmoney.cashloan.core.common.exception.ServiceException; -import com.nmoney.cashloan.core.domain.User; -import com.nmoney.cashloan.core.service.CloanUserService; -import com.nmoney.cashloan.manage.domain.QuartzInfo; -import com.nmoney.cashloan.manage.domain.QuartzLog; -import com.nmoney.cashloan.manage.service.QuartzInfoService; -import com.nmoney.cashloan.manage.service.QuartzLogService; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Component; -import tool.util.BeanUtil; -import tool.util.DateUtil; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** - * 催收员动态分配 - * - * @author xym - */ -@Component -@Lazy(value = false) -public class QuartzUrgeRepayUserAlloca implements Job { - - private static final Logger logger = LoggerFactory.getLogger(QuartzUrgeRepayUserAlloca.class); - - /** - * 催收员动态分配催收单 - * - * @throws ServiceException - */ - public String urgeUserAlloca() throws ServiceException { - - long startTime = System.currentTimeMillis(); - final UrgeRepayOrderService urgeRepayOrderService = (UrgeRepayOrderService) BeanUtil.getBean("urgeRepayOrderService"); - final UrgeRepayOrderFlowService urgeRepayOrderFlowService = (UrgeRepayOrderFlowService) BeanUtil.getBean("urgeRepayOrderFlowService"); - final BorrowRepayLogService borrowRepayLogService = (BorrowRepayLogService) BeanUtil.getBean("borrowRepayLogService"); - final ClUrgeRepayUserAllocaService urgeRepayUserAllocaService = (ClUrgeRepayUserAllocaService) BeanUtil.getBean("urgeRepayUserAllocaService"); - final CloanUserService cloanUserService = (CloanUserService) BeanUtil.getBean("cloanUserService"); - boolean isDev = "dev".equals(Global.getValue("app_environment")); - //所有催收计划 - List urgeRepayOrders = urgeRepayOrderService.listAll(new HashMap()); - /** - * 前手的规则可以动态调整 - */ - String[] frontHandRule = Global.getValue("urgeRepay_fronthand_rule").split(","); - - /** - * 用户归类分类 - */ - Map> classifyUserMap = new HashMap>(4) {{ - put(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode(), new ArrayList()); - put(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode(), new ArrayList()); - put(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode(), new ArrayList()); - put(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode(), new ArrayList()); - }}; - - Map> classifyVacationUserMap = new HashMap>(4) {{ - put(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode(), new ArrayList()); - put(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode(), new ArrayList()); - put(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode(), new ArrayList()); - put(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode(), new ArrayList()); - }}; - - /** - * 筛选具有权限的用户 - */ - HashMap paramsMap = new HashMap<>(); - paramsMap.put("state", 0); - List urgeRepayUserAllocas = urgeRepayUserAllocaService.selectAll(paramsMap); - if (urgeRepayUserAllocas != null && urgeRepayUserAllocas.size() > 0) { - for (UrgeRepayUserAlloca urgeRepayUserAlloca : urgeRepayUserAllocas) { - boolean isFront = urgeRepayUserAlloca.getAllocastr().contains(String.valueOf(UrgeRepayType.FRONT_HAND.getCode())); - boolean isNew = urgeRepayUserAlloca.getAllocastr().contains(String.valueOf(UrgeRepayType.NEW_CUSTOMER.getCode())); - if (isFront && isNew) { - classifyUserMap.get(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode()).add(urgeRepayUserAlloca); - } else if (isFront && !isNew) { - classifyUserMap.get(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode()).add(urgeRepayUserAlloca); - } else if (!isFront && !isNew) { - classifyUserMap.get(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode()).add(urgeRepayUserAlloca); - } else { - classifyUserMap.get(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode()).add(urgeRepayUserAlloca); - } - } - } - - paramsMap.put("state", 1); - List urgeRepayVacationUserAllocas = urgeRepayUserAllocaService.selectAll(paramsMap); - if (urgeRepayVacationUserAllocas != null && urgeRepayVacationUserAllocas.size() > 0) { - for (UrgeRepayUserAlloca urgeRepayUserAlloca : urgeRepayVacationUserAllocas) { - boolean isFront = urgeRepayUserAlloca.getAllocastr().contains(String.valueOf(UrgeRepayType.FRONT_HAND.getCode())); - boolean isNew = urgeRepayUserAlloca.getAllocastr().contains(String.valueOf(UrgeRepayType.NEW_CUSTOMER.getCode())); - if (isFront && isNew) { - classifyVacationUserMap.get(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode()).add(urgeRepayUserAlloca); - } else if (isFront && !isNew) { - classifyVacationUserMap.get(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode()).add(urgeRepayUserAlloca); - } else if (!isFront && !isNew) { - classifyVacationUserMap.get(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode()).add(urgeRepayUserAlloca); - } else { - classifyVacationUserMap.get(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode()).add(urgeRepayUserAlloca); - } - } - } - - /** - * 催收分类 - */ - Map> classifyUrgeRepayMap = new HashMap>(4) {{ - put(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode(), new ArrayList()); - put(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode(), new ArrayList()); - put(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode(), new ArrayList()); - put(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode(), new ArrayList()); - }}; - - /** - * 筛选单子 - */ - if (null != urgeRepayOrders && urgeRepayOrders.size() > 0) { - List borrowUserList = cloanUserService.listSelective(new HashMap()); - List borrowUserPhoneList = new ArrayList(); - Map phone2IdMap=new HashMap(); - for(User user : borrowUserList){ - borrowUserPhoneList.add(user.getLoginName()); - phone2IdMap.put(user.getLoginName(),user.getId()); - } - - List borrowRepayLogList = borrowRepayLogService.listSelective(new HashMap()); - List borrowUserIdList = new ArrayList(); - for(BorrowRepayLog borrowRepayLog : borrowRepayLogList){ - borrowUserIdList.add(borrowRepayLog.getUserId()); - } - - - for (UrgeRepayOrder urgeRepayOrder : urgeRepayOrders) { - if(UrgeRepayOrderModel.STATE_ORDER_SUCCESS.equals(urgeRepayOrder.getState()) || UrgeRepayOrderModel.STATE_ORDER_LOCK.equals(urgeRepayOrder.getState())) { - continue; - } - -// User borrowUser = cloanUserService.findByPhone(urgeRepayOrder.getPhone()); -// if (null == borrowUser) { - if (!borrowUserPhoneList.contains(urgeRepayOrder.getPhone())) { - logger.error("未找到当前借款用户 {}", urgeRepayOrder.getPhone()); - continue; - } - -// boolean hasRepay = borrowRepayLogService.existByUserId(borrowUser.getId()); - boolean hasRepay=false; - if(borrowUserIdList.contains(phone2IdMap.get(urgeRepayOrder.getPhone()))){ - hasRepay = true; - } - boolean isFront = ((urgeRepayOrder.getPenaltyDay() >= Integer.valueOf(frontHandRule[0]) && urgeRepayOrder.getPenaltyDay() <= Integer.valueOf(frontHandRule[1]))); - if (hasRepay && isFront) { - if("".equals(urgeRepayOrder.getState()) || "10".equals(urgeRepayOrder.getState())){ - classifyUrgeRepayMap.get(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode()).add(urgeRepayOrder); //无状态或者状态为未分配的催单 - }else if(!checkUserExist(urgeRepayOrder.getUserId(),classifyUserMap.get(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode()),classifyVacationUserMap.get(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode()))){ - classifyUrgeRepayMap.get(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode()).add(urgeRepayOrder); //催单员不存在或者状态异常 - } - - } else if (!hasRepay && isFront) { - if("".equals(urgeRepayOrder.getState()) || "10".equals(urgeRepayOrder.getState())){ - classifyUrgeRepayMap.get(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode()).add(urgeRepayOrder); //无状态或者状态为未分配的催单 - }else if(!checkUserExist(urgeRepayOrder.getUserId(),classifyUserMap.get(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode()),classifyVacationUserMap.get(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode()))){ - classifyUrgeRepayMap.get(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode()).add(urgeRepayOrder); //催单员不存在或者状态异常 - } - } else if (hasRepay && !isFront) { - if("".equals(urgeRepayOrder.getState()) || "10".equals(urgeRepayOrder.getState())){ - classifyUrgeRepayMap.get(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode()).add(urgeRepayOrder); //无状态或者状态为未分配的催单 - }else if(!checkUserExist(urgeRepayOrder.getUserId(),classifyUserMap.get(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode()),classifyVacationUserMap.get(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode()))){ - classifyUrgeRepayMap.get(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode()).add(urgeRepayOrder); //催单员不存在或者状态异常 - } else if(urgeRepayOrder.getPenaltyDay().intValue()%Integer.valueOf(frontHandRule[2]) == 0){ - classifyUrgeRepayMap.get(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode()).add(urgeRepayOrder); //达到最大持单时间,重新分配 - } - } else { - if("".equals(urgeRepayOrder.getState()) || "10".equals(urgeRepayOrder.getState())){ - classifyUrgeRepayMap.get(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode()).add(urgeRepayOrder); //无状态或者状态为未分配的催单 - }else if(!checkUserExist(urgeRepayOrder.getUserId(),classifyUserMap.get(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode()),classifyVacationUserMap.get(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode()))){ - classifyUrgeRepayMap.get(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode()).add(urgeRepayOrder); //催单员不存在或者状态异常 - } else if(urgeRepayOrder.getPenaltyDay().intValue()%Integer.valueOf(frontHandRule[2]) == 0){ - classifyUrgeRepayMap.get(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode()).add(urgeRepayOrder); //达到最大持单时间,重新分配 - } - - } - } - } - - - - if (isDev) { - logger.info("开始自动分配催收任务,催收数据明细:"); - logger.info("符合[前手新客]数据条数:{}", classifyUrgeRepayMap.get(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode()).size()); - logger.info("符合[前手老客]数据条数:{}", classifyUrgeRepayMap.get(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode()).size()); - logger.info("符合[后手新客]数据条数:{}", classifyUrgeRepayMap.get(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode()).size()); - logger.info("符合[后手老客]数据条数:{}", classifyUrgeRepayMap.get(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode()).size()); - logger.info("\n\n"); - logger.info("符合[前手新客]用户个数:{}", classifyUserMap.get(UrgeRepayType.FRONT_HAND_NEW_CUSTOMER.getCode()).size()); - logger.info("符合[前手老客]用户个数:{}", classifyUserMap.get(UrgeRepayType.FRONT_HAND_OLD_CUSTOMER.getCode()).size()); - logger.info("符合[后手新客]用户个数:{}", classifyUserMap.get(UrgeRepayType.BACK_HAND_NEW_CUSTOMER.getCode()).size()); - logger.info("符合[后手老客]用户个数:{}", classifyUserMap.get(UrgeRepayType.BACK_HAND_OLD_CUSTOMER.getCode()).size()); - logger.info("\n\n"); - } - ExecutorService executorService = null; - String quartzRemark = null; - try { - /** - * 开启4个线程 - */ - executorService = Executors.newFixedThreadPool(classifyUrgeRepayMap.size()); - final CountDownLatch latch=new CountDownLatch(4); - for (UrgeRepayType urgeRepayType : UrgeRepayType.getGroupClassify()) { - final List urgeRepayOrders1 = classifyUrgeRepayMap.get(urgeRepayType.getCode()); - final List users = classifyUserMap.get(urgeRepayType.getCode()); - //单子和催收员都要有数据 - int usize = users.size(); - int osize = urgeRepayOrders1.size(); - if (usize > 0 && osize > 0) { - //分配 - rectificateProcess(executorService, urgeRepayOrders1, urgeRepayOrderService,urgeRepayOrderFlowService, users,latch); - } else { - logger.info("当前没有要进行分配的逾期单或者催收人员,osize={},usize={}", osize, usize); - latch.countDown(); - continue; - } - } - //当前线程挂起等待 - latch.await(9, TimeUnit.HOURS); - } catch (Exception e) { - e.printStackTrace(); - logger.error("定时扣款计数器出错", e); - } - //线程池中所有任务都执行完毕后,线程池关闭 - executorService.shutdown(); - quartzRemark = "催收单自动分配完毕,当前耗时 " + (System.currentTimeMillis() - startTime) + "ms"; - return quartzRemark; - } - - private Boolean checkUserExist(Long userId, List users, List vacationUsers){ - Boolean ret=false; - for(UrgeRepayUserAlloca user : users){ - if(userId!=null && user.getUserId()!=null && userId.longValue()==user.getUserId().longValue()){ - ret=true; - break; - } - } - for(UrgeRepayUserAlloca user : vacationUsers){ - if(userId!=null && user.getUserId()!=null && userId.longValue()==user.getUserId().longValue()){ - ret=true; - break; - } - } - return ret; - } - - - /** - * 分配均衡时,数量较大,多线程代劳 - * - * @param executorService - * @param urgeRepayOrders - * @param urgeRepayOrderService - * @param users - */ - private void rectificateProcess(ExecutorService executorService, final List urgeRepayOrders, final UrgeRepayOrderService urgeRepayOrderService, final UrgeRepayOrderFlowService urgeRepayOrderFlowService, final List users, final CountDownLatch latch) { - final int osize = urgeRepayOrders.size(); - final int usize = users.size(); - - executorService.submit(new Runnable() { - @Override - public void run() { - List usersIndexList=new ArrayList(); - int m=0; - for (int i = 0; i < osize; i++) { - UrgeRepayOrder order = urgeRepayOrders.get(i); - if(m%usize==0){ - //生成一组随机整数 - usersIndexList= gerateIntArray(usize); - } - - if(UrgeRepayOrderModel.STATE_ORDER_SUCCESS.equals(urgeRepayOrderService.getById(order.getId()).getState())){ - continue; - } - UrgeRepayUserAlloca urgeRepayUserAlloca = users.get(Integer.parseInt(usersIndexList.get(m%usize))); - Map params = new HashMap<>(); - params.put("userId", urgeRepayUserAlloca.getUserId()); - params.put("userName", urgeRepayUserAlloca.getRealName()); - if("".equals(order.getState()) || UrgeRepayOrderModel.STATE_ORDER_PRE.equals(order.getState())){ - params.put("state",UrgeRepayOrderModel.STATE_ORDER_WAIT); - } - params.put("id",order.getId()); - urgeRepayOrderService.orderAllotUser(params); - - UrgeRepayOrderFlow record=new UrgeRepayOrderFlow(); - record.setDueId(order.getId()); - record.setBorrowId(order.getBorrowId()); - record.setUserId(urgeRepayUserAlloca.getUserId()); - record.setUserName(urgeRepayUserAlloca.getRealName()); - record.setCreateTime(DateUtil.getNow()); - record.setState(order.getState()); - record.setPenaltyDay(order.getPenaltyDay()); - urgeRepayOrderFlowService.addflowRecord(record); - m++; - } - latch.countDown(); - } - }); - } - - private List gerateIntArray(int length){ - List retArray=new ArrayList(); - for(int i=0;retArray.size() qiData = new HashMap<>(); - qiData.put("id", quartzInfo.getId()); - - QuartzLog quartzLog = new QuartzLog(); - quartzLog.setQuartzId(quartzInfo.getId()); - quartzLog.setStartTime(DateUtil.getNow()); - try { - String remark = urgeUserAlloca(); - - quartzLog.setTime(DateUtil.getNow().getTime() - quartzLog.getStartTime().getTime()); - quartzLog.setResult("10"); - quartzLog.setRemark(remark); - qiData.put("succeed", quartzInfo.getSucceed() + 1); - } catch (Exception e) { - quartzLog.setResult("20"); - qiData.put("fail", quartzInfo.getFail() + 1); - logger.error(e.getMessage(), e); - } finally { - logger.info("保存定时任务日志"); - quartzLogService.save(quartzLog); - quartzInfoService.update(qiData); - } - } -} diff --git a/java/RedisCache.java b/java/RedisCache.java deleted file mode 100644 index 629b707cec6a800fb7df339288a4567e18ae8e3c..0000000000000000000000000000000000000000 --- a/java/RedisCache.java +++ /dev/null @@ -1,34 +0,0 @@ - -public class RedisCache { - private static final Logger logger = LoggerFactory.getLogger(RedisCache.class); - private static final long MAX_SIZE = 2048; - private static final long EXPIRE = 15; //可适当调大 - private LoadingCache> lanCache; - @PostConstruct - public void init() { - lanCache = CacheBuilder.newBuilder().maximumSize(MAX_SIZE) - .expireAfterWrite(EXPIRE, TimeUnit.MINUTES).build(new CacheLoader>() { - @Override - public Optional load(String key) throws Exception { - // https://blog.csdn.net/codingtu/article/details/89577316 - return loadLanData(key); - - } - }); - } - - private Optional loadLanData(String key) { - - SysLan sysLan = null; - if (null == redisManager) { - return null; - } - String value = redisManager.get("slan:" + key); - if (StringUtils.isNotBlank(value)) { - sysLan = JSONObject.parseObject(value, SysLan.class); - return Optional.of(sysLan); - } - return Optional.empty(); - } - - /****** java.util.NoSuchElementException: No value present *****/ 滥用Optional,本意是想解决 cacheloader returned null for key \ No newline at end of file diff --git a/java/RedisUtil.java b/java/RedisUtil.java deleted file mode 100644 index b62c5418b285399ff2de23cd98566d222732a56b..0000000000000000000000000000000000000000 --- a/java/RedisUtil.java +++ /dev/null @@ -1,169 +0,0 @@ -/** - * - * @Description: spring boot 的redis工具类 - */ -@SuppressWarnings("unchecked") -@Component -public class RedisUtil { - // 引入了两个template完全多余 - @SuppressWarnings("rawtypes") - @Autowired - private RedisTemplate redisTemplate; - - @Autowired - private StringRedisTemplate stringRedisTemplate; - - /** - * 批量删除对应的value - * - * @param keys - */ - public void remove(final String... keys) { - for (String key : keys) { - /* - template完全支持批量删除,底下的方法就用到了,这里偏要一个一个删 - */ - remove(key); - } - } - - /** - * 批量删除key - * - * @param pattern - */ - public void removePattern(final String pattern) { - /* - 暂且不提keys命令大量数据下不可用,ide都提示了可能存在空指针 - */ - Set keys = redisTemplate.keys(pattern); - if (keys.size() > 0) - redisTemplate.delete(keys); - } - - /** - * 删除对应的value - * - * @param key - */ - public void remove(final String key) { - /** - * 这里就完全想不通了,删除命令是有返回值的,删除一个不存在的key没有任何问题 - */ - if (exists(key)) { - redisTemplate.delete(key); - } - } - - /** - * 判断缓存中是否有对应的value - * - * @param key - * @return - */ - public boolean exists(final String key) { - /** - * hasKey返回的是包装类,这里唯一能想到的是给方法一个别名 - */ - return redisTemplate.hasKey(key); - } - - /** - * 读取缓存 - * - * @param key - * @return - */ - public String get(final String key) { - /** - * 啊。。。这。。。。上面的StringRedisTemplate是拿来干嘛的??而且怎么可能每次都new一个 - */ - Object result = null; - redisTemplate.setValueSerializer(new StringRedisSerializer()); - ValueOperations operations = redisTemplate.opsForValue(); - result = operations.get(key); - if (result == null) { - return null; - } - return result.toString(); - } - - /** - * 写入缓存 - * - * @param key - * @param value - * @return - */ - public boolean set(final String key, Object value) { - // 这里只是写得啰嗦了一点,倒不是什么大问题 - boolean result = false; - try { - ValueOperations operations = redisTemplate.opsForValue(); - operations.set(key, value); - result = true; - } catch (Exception e) { - e.printStackTrace(); - } - return result; - } - - /** - * 写入缓存 - * - * @param key - * @param value - * @return - */ - public boolean set(final String key, Object value, Long expireTime) { - // 但凡多按一个逗号,就知道一个命令就能搞定 - boolean result = false; - try { - ValueOperations operations = redisTemplate.opsForValue(); - operations.set(key, value); - redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); - result = true; - } catch (Exception e) { - e.printStackTrace(); - } - return result; - } - - public boolean hmset(String key, Map value) { - boolean result = false; - try { - redisTemplate.opsForHash().putAll(key, value); - result = true; - } catch (Exception e) { - e.printStackTrace(); - } - return result; - } - - public Map hmget(String key) { - Map result = null; - try { - result = redisTemplate.opsForHash().entries(key); - } catch (Exception e) { - e.printStackTrace(); - } - return result; - } - - public void setStr(final String key, final String value, final long expireTime) { - // 恭喜啊,又学到了新知识,学习速度不可想象啊。就是问一句工资是按代码行数算的嘛? - stringRedisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.SECONDS); - } - - public String getStr(final String key){ - return stringRedisTemplate.opsForValue().get(key); - } - - public void delStr(final String key){ - // 对不起,我已经没话说了,只是希望早日治好失忆症 - if(redisTemplate.hasKey(key)){ - redisTemplate.delete(key); - } - } - -} \ No newline at end of file diff --git a/java/Remove.java b/java/Remove.java deleted file mode 100644 index 6f97f24b46a9c80a6b232cf8ce2a2712f56ee5c8..0000000000000000000000000000000000000000 --- a/java/Remove.java +++ /dev/null @@ -1,15 +0,0 @@ -import java.util.List; - -public class Remove { - - /** - * 移除特定元素 - */ - public static void remove(List items){ - for (String item : items) { - if (item.equals("abc")) { - items.remove(item); - } - } - } -} diff --git a/java/Report.java b/java/Report.java deleted file mode 100644 index e40aaec987769ccc5ba69b6e51ab1f1e6bc52d50..0000000000000000000000000000000000000000 --- a/java/Report.java +++ /dev/null @@ -1,173 +0,0 @@ - - -package com.bimcloud.bim.work.entity; - -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; - -import java.math.BigDecimal; -import java.util.List; -import java.util.Map; - -/** - * 报表管理 - */ -@Data -@ApiModel(value = "报表管理") -public class Report { - - private String deptId; - - private String flag; - /** - * 区域类型(1管控2专属) - */ - private String areaType; - @ApiModelProperty(value = "年份") - private int tjYear; - - @ApiModelProperty(value = "查询时间") - private String tjTime; - - @ApiModelProperty(value = "月份") - private String tjMonth; - - private int startMonth; - private int endMonth; - - @ApiModelProperty(value = "开始时间") - private String startTime; - - @ApiModelProperty(value = "结束时间") - private String endTime; - - - /** - * 工单来源 0自动上报1工程师上报2其它人员上报 - */ - private int reportType0; - private int reportType1; - private int reportType2; - /** - * 故障分布(字典:1设备离线2单灯离线3异常亮灯4异常关灯5市电掉电6漏电报警7柜门打开8缺项报警9其他) - */ - - private int faultLevel1; - private int faultLevel2; - private int faultLevel3; - private int faultLevel4; - private int faultLevel5; - private int faultLevel6; - private int faultLevel7; - private int faultLevel8; - private int faultLevel9; - - //每月工单数 - private int[] monthTotal; - - - //待分配工单、待处理工单、已完成工单数量 - private int taskStatus1; - private int taskStatus3; - private int taskStatus7; - - - //巡视任务不同状态数量 0起草中1进行中2已结束 - private int tourStatus0; - private int tourStatus1; - private int tourStatus2; - - private int[] monthTourTotal; - - //巡视任务不同类型数量 0日常巡视1重点保障巡视2特殊巡视 - private int patrolType0; - private int patrolType1; - private int patrolType2; - private int[] patrolTypeTotal; - //不同类型的统计类型统计 - - private int patrolTypeWxs0; - private int patrolTypeEnd0; - private int patrolTypeZ0; - - - private int patrolTypeWxs1; - private int patrolTypeEnd1; - private int patrolTypeZ1; - private int patrolTypeWxs2; - private int patrolTypeEnd2; - private int patrolTypeZ2; - - //进行中 - private int patrolType01; - private int patrolType11; - private int patrolType21; - - //起草中 - private int[] patrolStatusTotal0; - //进行中 - private int[] patrolStatusTotal1; - //已结束 - private int[] patrolStatusTotal2; - - private int taskTotal; - private int tourTotal; - //月份 - private int infoMonth; - - //出入库金额 - private BigDecimal kAmount; - private BigDecimal rkAmount; - private BigDecimal ckAmount; - //年检费用 - private BigDecimal inspectionAmount; - //保费 - private BigDecimal premiumAmount; - //维护费用 - private BigDecimal serviceAmount; - //加油费用 - private BigDecimal fuelAmount; - //灯杆 - private List lightList; - /** - * 巡视数量 - */ - private int tourTaskDetailCount; - - /** - * 工单数量 - */ - private int taskInfoTotalNum; - - private List ids; - - private String userId; - - //区域id - private Long areaId; - private String subCode; - private String areaName; - //围栏 - private String pointsHx; - private int subCodeLength; - /** - * 树级别 - */ - private int treeLeavel; - - private String name; - /** - * 区域中心点 - */ - private String centerPoint; - - private String[] months; - - private String lightId; - - private ListreportList; - - @ApiModelProperty("年月日类型") - private Integer type; -} diff --git a/java/ReportServiceImpl.java b/java/ReportServiceImpl.java deleted file mode 100644 index 7ad65dd14a53afe635dfb335090ecaa43e95eb96..0000000000000000000000000000000000000000 --- a/java/ReportServiceImpl.java +++ /dev/null @@ -1,767 +0,0 @@ -package com.bimcloud.bim.work.service.impl; - -import cn.hutool.core.collection.CollectionUtil; -import cn.hutool.core.date.DateField; -import cn.hutool.core.date.DateTime; -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.util.StrUtil; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.bimcloud.bim.admin.api.entity.SysDictItem; -import com.bimcloud.bim.admin.api.feign.RemoteDictService; -import com.bimcloud.bim.common.core.util.R; -import com.bimcloud.bim.work.Enum.DateTypeEnums; -import com.bimcloud.bim.work.Enum.NumericEnum; -import com.bimcloud.bim.work.entity.BaseArea; -import com.bimcloud.bim.work.entity.Report; -import com.bimcloud.bim.work.entity.vo.DeviceFaultVo; -import com.bimcloud.bim.work.mapper.BaseAreaMapper; -import com.bimcloud.bim.work.mapper.ReportMapper; -import com.bimcloud.bim.work.service.ReportService; -import com.bimcloud.bim.work.util.CommonUtil; -import com.bimcloud.bim.work.util.ConstantUtil; -import com.bimcloud.bim.work.util.DateTimeUtil; -import lombok.AllArgsConstructor; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.util.CollectionUtils; - -import java.math.BigDecimal; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.util.*; -import java.util.stream.Collectors; - -@Service -@AllArgsConstructor -public class ReportServiceImpl extends ServiceImpl implements ReportService { - - private final BaseAreaMapper baseAreaMapper; - - private final RemoteDictService remoteDictService; - - /** - * 工单来源与故障分布 - * - * @return - */ - @Override - public Report getGdAndFaultCount(Report report) { - //spliceTime(report); - - return baseMapper.getGdAndFaultCount(report); - } - - /** - * 统计每月工单总数与处理情况 - * - * @param report - * @return - */ - @Override - public Report getTaskInfoTotal(Report report) { - Report report1 = new Report(); - int taskStatus1 = 0; - int taskStatus3 = 0; - int taskStatus7 = 0; - //时间参数查询 - List reportList = baseMapper.getTaskInfoTotal(report); - if (CollectionUtil.isNotEmpty(reportList)) { - for (Report info : reportList) { - taskStatus1 = taskStatus1 + info.getTaskStatus1(); - taskStatus3 = taskStatus3 + info.getTaskStatus3(); - taskStatus7 = taskStatus7 + info.getTaskStatus7(); - } - } - //处理查询参数 -// int startMonth = getMonth(report); -// getMonthTask(report, report1, startMonth); - report1.setTaskStatus1(taskStatus1); - report1.setTaskStatus3(taskStatus3); - report1.setTaskStatus7(taskStatus7); - return report1; - } - - - /** - * 每日工单数 - * - * @param report - * @return - */ - @Override - public List getTaskInfoTotalDay(Report report) { - - - String startTime = CommonUtil.isNull(report.getStartTime()); - String endTime = CommonUtil.isNull(report.getEndTime()); - - Date d = new Date(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - String curTime = sdf.format(d); - if (startTime.equals("")){ - startTime = curTime; - } - if (endTime.equals("")){ - endTime = curTime; - } - - Calendar c1 = Calendar.getInstance(); - Calendar c2 = Calendar.getInstance(); - try { - c1.setTime(sdf.parse(startTime)); - c2.setTime(sdf.parse(endTime)); - } catch (ParseException e) { - e.printStackTrace(); - } - - - List localDateList = getsAllDatesInTheDateRange( - LocalDate.of(c1.get(Calendar.YEAR), c1.get(Calendar.MARCH) + 1, c1.get(Calendar.DAY_OF_MONTH)), - LocalDate.of(c2.get(Calendar.YEAR), c2.get(Calendar.MARCH) + 1, c2.get(Calendar.DAY_OF_MONTH)) - ); - - - List reportListRtn = new ArrayList(); - if (CollectionUtil.isNotEmpty(localDateList)) { - for (LocalDate localDate : localDateList) { - // System.out.println("当前时间---:"+localDate.toString()); - Report tempBO = new Report(); - tempBO.setTjTime(localDate.toString()); - tempBO.setTaskTotal(0); - reportListRtn.add(tempBO); - } - } - - //时间参数查询 - List reportList = baseMapper.getTaskInfoTotalDay(report); - Map map = new HashMap(); - if (CollectionUtil.isNotEmpty(reportList)) { - for (Report info : reportList) { - map.put(info.getTjTime(),info.getTaskTotal()); - //System.out.println("当前时间---:"+info.getTjTime() + "--"+info.getTaskTotal()); - } - } - - for (Report info : reportListRtn) { - if (map.containsKey(info.getTjTime())){ - info.setTaskTotal(map.get(info.getTjTime())); - } - } - - - return reportListRtn; - } - - /** - * 统计故障数(年月日) - * @param report - * @return - */ - @Override - public Report countTaskInfoTotal(Report report) { - List taskInfoTotalDayList = this.baseMapper.getTaskInfoTotalDay(report); - //计算时间段 - List quantumDateList = DateTimeUtil.getQuantumDate(report.getType(), report.getStartTime(), report.getEndTime()); - //按时间分组 - Map> reportMap = taskInfoTotalDayList.stream().map(e->{ - Report dealReport = new Report(); - String tjTime =""; - if (DateTypeEnums.TYPEYEAR.getCode().equals(report.getType())){ - tjTime = e.getTjTime().substring(0,4); - }else if ((DateTypeEnums.TYPEMONTH.getCode().equals(report.getType()))){ - tjTime =e.getTjTime().substring(0,7); - }else{ - tjTime = e.getTjTime().substring(0,10); - } - dealReport.setTjTime(tjTime); - dealReport.setTaskStatus1(e.getTaskStatus1()); - dealReport.setTaskStatus3(e.getTaskStatus3()); - dealReport.setTaskStatus7(e.getTaskStatus7()); - return dealReport; - }).collect(Collectors.groupingBy(Report::getTjTime)); - List finalList = quantumDateList.stream().map(e -> { - Report filterReport = new Report(); - //taskStatus1 - int taskStatus1Total = 0; - //taskStatus3 - int taskStatus3Total = 0; - //taskStatus1 - int taskStatus7Total = 0; - filterReport.setTjTime(e); - List reportList = reportMap.get(e); - if (CollectionUtil.isNotEmpty(reportList)) { - //taskStatus1 - taskStatus1Total = reportList.stream().mapToInt(Report::getTaskStatus1).sum(); - //taskStatus3 - taskStatus3Total = reportList.stream().mapToInt(Report::getTaskStatus3).sum(); - //taskStatus1 - taskStatus7Total = reportList.stream().mapToInt(Report::getTaskStatus7).sum(); - } - //总任务数 - //int taskTotalNum = taskStatus1Total + taskStatus3Total + taskStatus7Total; - //filterReport.setTaskInfoTotalNum(taskTotalNum); - filterReport.setTaskStatus1(taskStatus1Total); - filterReport.setTaskStatus3(taskStatus3Total); - filterReport.setTaskStatus7(taskStatus7Total); - return filterReport; - }).collect(Collectors.toList()); - Report dealReport = new Report(); - int taskStatus1Total = finalList.stream().mapToInt(Report::getTaskStatus1).sum(); - //taskStatus3 - int taskStatus3Total = finalList.stream().mapToInt(Report::getTaskStatus3).sum(); - //taskStatus1 - int taskStatus7Total = finalList.stream().mapToInt(Report::getTaskStatus7).sum(); - dealReport.setTaskStatus1(taskStatus1Total); - dealReport.setTaskStatus3(taskStatus3Total); - dealReport.setTaskStatus7(taskStatus7Total); - return dealReport; - } - - /** - * 巡视数量对比 - * @param report - * @return - */ - @Override - public Report countTourStatus(Report report) { - //查询巡视任务总数,与不同状态的数量 - List reportList = baseMapper.selectTourStatus(report); - Report dealReport = new Report(); - if (CollectionUtil.isNotEmpty(reportList)){ - int tourStatus0 = reportList.stream().mapToInt(Report::getTourStatus0).sum(); - int tourStatus1 = reportList.stream().mapToInt(Report::getTourStatus1).sum(); - int tourStatus2 = reportList.stream().mapToInt(Report::getTourStatus2).sum(); - dealReport.setTourStatus1(tourStatus1); - dealReport.setTourStatus0(tourStatus0); - dealReport.setTourStatus2(tourStatus2); - } - Report patrolReport = baseMapper.selectPatrolType(report); - if (null!=patrolReport) { - dealReport.setPatrolType0(patrolReport.getPatrolType0()); - dealReport.setPatrolType1(patrolReport.getPatrolType1()); - dealReport.setPatrolType2(patrolReport.getPatrolType2()); - } - return dealReport; - } - /** - * 统计年月日的数据TourTotal - * @param report - * @return - */ - @Override - public List countYearMonthDayTourTotal(Report report) { - List reportList = baseMapper.selectTourStatus(report); - //统计结果按日期分组 - Map> reportMap = reportList.stream().map(e -> { - Report dealReport = new Report(); - String tjTime = ""; - if (DateTypeEnums.TYPEYEAR.getCode().equals(report.getType())) { - tjTime = e.getTjTime().substring(0, 4); - } else if ((DateTypeEnums.TYPEMONTH.getCode().equals(report.getType()))) { - tjTime = e.getTjTime().substring(0, 7); - } else { - tjTime = e.getTjTime().substring(0, 10); - } - dealReport.setTjTime(tjTime); - dealReport.setTourStatus0(e.getTourStatus0()); - dealReport.setTourStatus1(e.getTourStatus1()); - dealReport.setTourStatus2(e.getTourStatus2()); - return dealReport; - }).collect(Collectors.groupingBy(Report::getTjTime)); - //根据日期统计每个状态的数量 - return DateTimeUtil.getQuantumDate(report.getType(),report.getStartTime(),report.getEndTime()) - .stream().map(n->{ - int tourStatus0 = 0; - int tourStatus1 =0; - int tourStatus2 =0; - Report filterReport = new Report(); - filterReport.setTjTime(n); - List reports = reportMap.get(n); - if (CollectionUtil.isNotEmpty(reports)){ - tourStatus0 = reports.stream().mapToInt(Report::getTourStatus0).sum(); - tourStatus1 = reports.stream().mapToInt(Report::getTourStatus1).sum(); - tourStatus2 = reports.stream().mapToInt(Report::getTourStatus2).sum(); - } - filterReport.setTourStatus0(tourStatus0); - filterReport.setTourStatus1(tourStatus1); - filterReport.setTourStatus2(tourStatus2); - return filterReport; - }).collect(Collectors.toList()); - } - - /** - * 工单数量对比 - * @param report - * @return - */ - @Override - public List countMonthTaskTotal(Report report) { - List reportList = baseMapper.getTaskInfoTotal(report); - if (CollectionUtil.isEmpty(reportList)){ - return new ArrayList<>(); - } - //切分日期 - Map> reportMap = reportList.stream().map(taskInfo -> { - Report filterReport = new Report(); - String dateTime[] = taskInfo.getTjTime().split("-"); - StringBuffer stringBuffer = new StringBuffer(); - if (DateTypeEnums.TYPEYEAR.getCode().equals(report.getType())) { - filterReport.setTjTime(stringBuffer.append(dateTime[0]).toString()); - } else if (DateTypeEnums.TYPEMONTH.getCode().equals(report.getType())) { - filterReport.setTjTime(stringBuffer.append(dateTime[0]).append(dateTime[1]).toString()); - } else { - filterReport.setTjTime(stringBuffer.append(dateTime[0]).append(dateTime[1]).append(dateTime[2]).toString()); - } - filterReport.setTaskStatus1(taskInfo.getTaskStatus1()); - filterReport.setTaskStatus3(taskInfo.getTaskStatus3()); - filterReport.setTaskStatus7(taskInfo.getTaskStatus7()); - return filterReport; - }).collect(Collectors.groupingBy(Report::getTjTime)); - //筛选存在的日期 - return DateTimeUtil.getQuantumDate(report.getType(), report.getStartTime(), report.getEndTime()) - .stream().map(quantumDate->{ - Report dealReport = new Report(); - List reports = reportMap.get(quantumDate); - int taskStatus1Total =0; - int taskStatus3Total =0; - int taskStatus7Total =0; - if (CollectionUtil.isNotEmpty(reports)){ - taskStatus1Total = reports.stream().mapToInt(Report::getTaskStatus1).sum(); - taskStatus3Total = reports.stream().mapToInt(Report::getTaskStatus3).sum(); - taskStatus7Total = reports.stream().mapToInt(Report::getTaskStatus7).sum(); - } - int totalTaskNum = taskStatus1Total+taskStatus3Total+taskStatus7Total; - dealReport.setTaskInfoTotalNum(totalTaskNum); - dealReport.setTjTime(quantumDate); - return dealReport; - }).collect(Collectors.toList()); - } - - public static List getsAllDatesInTheDateRange(LocalDate startDate, LocalDate endDate) { - List localDateList = new ArrayList<>(); - // 开始时间必须小于结束时间 - if (startDate.isAfter(endDate)) { - return null; - } - while (startDate.isBefore(endDate)) { - localDateList.add(startDate); - startDate = startDate.plusDays(1); - } - localDateList.add(endDate); - return localDateList; - } - - @Override - public Report getMonthTaskTotal(Report report) { - Report report1 = new Report(); - //处理查询参数 - int startMonth = handleParam(report); - getMonthTask(report, report1, startMonth); - return report1; - } - - private void getMonthTask(Report report, Report report1, int startMonth) { - DateTime endDate = DateUtil.parse(report.getEndTime(), ConstantUtil.SDFDATE); - DateTime startDate = DateUtil.parse(report.getStartTime(), ConstantUtil.SDFDATE); - Long count = DateUtil.betweenMonth(endDate, startDate, false) + 1; - int betweenMonth = count.intValue(); - int endMonth = DateUtil.month(endDate) + 1; - - //初始化数组 - int[] monthTotal = new int[betweenMonth]; - String[] months = new String[betweenMonth]; - for (int i = 0; i < betweenMonth; i++) { - monthTotal[i] = 0; - int month = DateUtil.offsetMonth(startDate, i + 1).getField(DateField.MONTH); - if (month == 0) { - month = 12; - } - months[i] = month + "月"; - } - List reportList2 = baseMapper.getTaskInfoTotal(report); - //一个月最多5周 - if (CollectionUtil.isNotEmpty(reportList2)) { - for (int i = 0; i < reportList2.size(); i++) { - Report info = reportList2.get(i); - int infoMonth = info.getInfoMonth(); - int index = 0; - if (infoMonth <= endMonth) { - index = (betweenMonth - 1) + infoMonth - endMonth; - } else { - //如果大于结束月,说明是上一年 - index = infoMonth - startMonth; - } - monthTotal[index] = info.getTaskTotal(); - } - } - report1.setMonths(months); - report1.setMonthTotal(monthTotal); - } - - //拼接时间后缀 - private void spliceTime(Report report) { - if (StrUtil.isNotBlank(report.getEndTime())) { - report.setEndTime(report.getEndTime() + " 23:59:59"); - } - - } - - private int getMonth(Report report) { - Date date = new Date(); - //前六个月 - DateTime dateTime = DateUtil.offsetMonth(date, -5); - DateTime dateTime1 = DateUtil.endOfMonth(date); - report.setEndTime(DateUtil.format(dateTime1, ConstantUtil.SDFDATETIME)); - //前半年,所以需要减5 - int month = DateUtil.month(dateTime) + 1; - report.setStartTime(DateUtil.format(DateUtil.beginOfMonth(dateTime), ConstantUtil.SDFDATETIME)); - return month; - } - - /** - * 处理参数 - * - * @param report - * @return - */ - private int handleParam(Report report) { - Date date = new Date(); - if (StrUtil.isNotEmpty(report.getStartTime())) { - date = DateUtil.parse( - report.getStartTime(), ConstantUtil.SDFDATE); - } - //前六个月 - DateTime dateTime = null; - if (StrUtil.isBlank(report.getEndTime())) { - dateTime = DateUtil.offsetMonth(date, -5); - DateTime dateTime1 = DateUtil.endOfMonth(date); - report.setEndTime(DateUtil.format(dateTime1, ConstantUtil.SDFDATETIME)); - } else { - dateTime = new DateTime(date.getTime()); - report.setEndTime(report.getEndTime() + " 23:59:59"); - } - //前半年,所以需要减5 - int month = DateUtil.month(dateTime) + 1; - report.setStartTime(DateUtil.format(DateUtil.beginOfMonth(dateTime), ConstantUtil.SDFDATETIME)); - return month; - } - - /** - * 查询车辆相关费用以及出入库金额 - * - * @param report - * @return - */ - @Override - public Report getAmount(Report report) { - //spliceTime(report); - //查询车辆 - Report report1 = baseMapper.getCarAmount(report); - //查询出库入库耗材的金额 - List rkAnCkAmount = baseMapper.getRkAndCkAmount(report); - report1.setRkAmount(rkAnCkAmount.get(0)); - report1.setCkAmount(rkAnCkAmount.get(1)); - - return report1; - } - - /** - * 巡视任务状态统计 - * - * @param report - * @return - */ - @Override - public Report getTourStatus(Report report) { - - if (report.getStartTime() == null) { - report.setStartTime(DateUtil.format(DateUtil.beginOfYear(new Date()), ConstantUtil.SDFDATETIME)); - } - - - spliceTime(report); - Report report1 = new Report(); - int tourStatus0 = 0; - int tourStatus1 = 0; - int tourStatus2 = 0; - List reportList0 = baseMapper.selectTourStatus(report); - if (CollectionUtil.isNotEmpty(reportList0)) { - for (Report report2 : reportList0) { - tourStatus0 = tourStatus0 + report2.getTourStatus0(); - tourStatus1 = tourStatus1 + report2.getTourStatus1(); - tourStatus2 = tourStatus2 + report2.getTourStatus2(); - } - } else { - return report1; - } - - report1.setTourStatus0(tourStatus0); - report1.setTourStatus1(tourStatus1); - report1.setTourStatus2(tourStatus2); - - Report report2 = baseMapper.selectPatrolType(report); - report1.setPatrolType0(report2.getPatrolType0()); - report1.setPatrolType1(report2.getPatrolType1()); - report1.setPatrolType2(report2.getPatrolType2()); - return report1; - } - - @Override - public Report getMonthTourTotal(Report report) { - - Report report1 = new Report(); - //处理查询参数 - int startMonth = getMonth(report); - DateTime endDate = DateUtil.parse(report.getEndTime(), ConstantUtil.SDFDATE); - DateTime startDate = DateUtil.parse(report.getStartTime(), ConstantUtil.SDFDATE); - Long count = DateUtil.betweenMonth(endDate, startDate, false) + 1; - int betweenMonth = count.intValue(); - int endMonth = DateUtil.month(endDate) + 1; - - //初始化数组 - int[] monthTotal = new int[betweenMonth]; - String[] months = new String[betweenMonth]; - for (int i = 0; i < betweenMonth; i++) { - monthTotal[i] = 0; - int month = DateUtil.offsetMonth(startDate, i + 1).getField(DateField.MONTH); - if (month == 0) { - month = 12; - } - months[i] = month + "月"; - } - List reportList = baseMapper.selectTourStatus(report); - //一个月最多5周 - if (CollectionUtil.isNotEmpty(reportList)) { - for (int i = 0; i < reportList.size(); i++) { - Report info = reportList.get(i); - int index; - int infoMonth = info.getInfoMonth(); - if (infoMonth <= endMonth) { - index = (betweenMonth - 1) + infoMonth - endMonth; - } else { - //如果大于结束月,说明是上一年 - index = infoMonth - startMonth; - } - monthTotal[index] = info.getTourTotal(); - } - } - report1.setMonths(months); - report1.setMonthTourTotal(monthTotal); - return report1; - } - - /** - * 查询工单、巡检、灯杆 - * - * @param report - * @return - */ - @Override - public R getLightInfo(Report report) { - //spliceTime(report); - - if (report.getAreaId() != null) { - BaseArea area = baseAreaMapper.getById(report.getAreaId()); - if (area == null) { - return R.ok(); - } - report.setSubCode(area.getSubCode()); - report.setTreeLeavel(area.getTreeLeavel()); - report.setAreaId(area.getId()); - if (report.getAreaType().equals("2")) { - report.setSubCodeLength(report.getSubCode().length()); - } - } else { - if (report.getAreaType().equals(NumericEnum.ONE.getStrCode())) { - return R.ok(); - } - BaseArea bo = new BaseArea(); - bo.setAreaType(report.getAreaType()); - List areaList = baseAreaMapper.getPage(bo); - List reports = new ArrayList<>(); - for (BaseArea area : areaList) { - Report object = new Report(); - object.setSubCode(area.getSubCode()); - object.setTreeLeavel(area.getTreeLeavel()); - object.setAreaId(area.getId()); - object.setSubCodeLength(area.getSubCode().length()); - reports.add(object); - } - report.setReportList(reports); - } - - - - //区域类型(1管控2专属) //flag=gd/xs - if (report.getAreaType().equals("1") && report.getFlag().equals("gd")) { - report.setSubCodeLength(report.getSubCode().length() + 4); - report.setTreeLeavel(report.getTreeLeavel() + 1); - List gkTaskInfCount = baseMapper.getGkTaskInfCount(report); - return R.ok(gkTaskInfCount); - } - if (report.getAreaType().equals("1") && report.getFlag().equals("xs")) { - report.setTreeLeavel(report.getTreeLeavel() + 1); - report.setSubCodeLength(report.getSubCode().length() + 4); - List gkTourCount = baseMapper.getGkTourCount(report); - return R.ok(gkTourCount); - } - if (report.getAreaType().equals("2") && report.getFlag().equals("gd")) { - List zsTaskInfCount = baseMapper.getZsTaskInfCount(report); - return R.ok(zsTaskInfCount); - } - if (report.getAreaType().equals("2") && report.getFlag().equals("xs")) { - List zsTourInfCount = baseMapper.getZsTourInfCount(report); - return R.ok(zsTourInfCount); - } - - return R.ok(); - } - - /** - * 大屏查询 - * - * @param report - * @return - */ - @Override - public Report selectPatrolTotal(Report report) { - Report report1 = new Report(); - //spliceTime(report); - - tourPatrolTotal(report, report1); - return report1; - } - - /** - * 小程序 - * 巡视任务统计 - * - * @param report - * @return - */ - @Override - public Report selectTourType(Report report) { - Report report1 = new Report(); - - handTime(report); - tourPatrolTotal(report, report1); - - return report1; - } - - /** - * 统计不同巡视类型下的不同状态巡视任务数量 - * - * @param report - * @param report1 - */ - private void tourPatrolTotal(Report report, Report report1) { - Report report2 = baseMapper.selectTourType(report); - if (report2 == null) { - return; - } - int[] patrolTypeTotal = new int[3]; - patrolTypeTotal[0] = report2.getPatrolTypeZ0(); - patrolTypeTotal[1] = report2.getPatrolTypeZ1(); - patrolTypeTotal[2] = report2.getPatrolTypeZ2(); - int[] patrolStatusTotal0 = new int[3]; - patrolStatusTotal0[0] = report2.getPatrolTypeWxs0(); - patrolStatusTotal0[1] = report2.getPatrolTypeWxs1(); - patrolStatusTotal0[2] = report2.getPatrolTypeWxs2(); - - //进行中 - int[] patrolStatusTotal1 = new int[3]; - patrolStatusTotal1[0] = report2.getPatrolType01(); - patrolStatusTotal1[1] = report2.getPatrolType11(); - patrolStatusTotal1[2] = report2.getPatrolType21(); - //已结束 - int[] patrolStatusTotal2 = new int[3]; - patrolStatusTotal2[0] = report2.getPatrolTypeEnd0(); - patrolStatusTotal2[1] = report2.getPatrolTypeEnd1(); - patrolStatusTotal2[2] = report2.getPatrolTypeEnd2(); - - report1.setPatrolTypeTotal(patrolTypeTotal); - report1.setPatrolStatusTotal0(patrolStatusTotal0); - report1.setPatrolStatusTotal1(patrolStatusTotal1); - report1.setPatrolStatusTotal2(patrolStatusTotal2); - } - - /** - * 工单来源 与故障分布 - * - * @param report - * @return - */ - @Override - public Report selectFaultLevee(Report report) { - handTime(report); - return baseMapper.selrctUserTaskLogTotal(report); - } - - /** - * 查询工单数与巡检数 - * - * @param report - * @return - */ - @Override - public Report selectTaskAndTour(Report report) { - Report report1 = new Report(); - handTime(report); - //查询个人工单数 - Report report3 = baseMapper.selrctUserTaskLogTotal(report); - BeanUtils.copyProperties(report3, report1); - int count = baseMapper.tourTaskDetailCount(report).intValue(); - //查询巡视数 - report1.setTourTaskDetailCount(count); - return report1; - } - - /** - * 微信退出登录 - * - * @param userId - * @return - */ - @Override - public Object logOut(Long userId) { - return baseMapper.miniLogOut(userId); - } - - /** - * 统计故障分布故障数 - * @param report - * @return - */ - @Override - public List countDeviceFault(Report report) { - spliceTime(report); - List deviceFaultVoList = baseMapper.getDeviceFault(report); - R> serviceDictByType = remoteDictService.getDictByType("early_warning_type"); - List deviceFaultVos = new ArrayList<>(); - if (CollectionUtil.isNotEmpty(serviceDictByType.getData())){ - List sysDictItems = serviceDictByType.getData(); - for (SysDictItem sysDictItem:sysDictItems){ - DeviceFaultVo deviceFaultVo = new DeviceFaultVo(); - deviceFaultVo.setFaultLevel(sysDictItem.getValue()); - Optional deviceFaultVoOptional = deviceFaultVoList.stream().filter(n -> n.getFaultLevel().equals(sysDictItem.getValue())).findFirst(); - deviceFaultVoOptional.ifPresent(faultVo -> deviceFaultVo.setSumCount(faultVo.getSumCount())); - deviceFaultVos.add(deviceFaultVo); - } - } - return deviceFaultVos; - } - - private void handTime(Report report) { - if (CommonUtil.isNotBlank(report.getStartTime())) { - DateTime date = DateUtil.parse( - report.getStartTime(), "yyyy-MM"); - report.setStartTime(DateUtil.format(DateUtil.beginOfMonth(date), ConstantUtil.SDFDATETIME)); - DateTime dateTime1 = DateUtil.endOfMonth(date); - report.setEndTime(DateUtil.format(dateTime1, ConstantUtil.SDFDATETIME)); - } - - } -} diff --git a/java/ReturnNull.java b/java/ReturnNull.java deleted file mode 100644 index 8fbf2e9c7c4d7e02206f6c73f26bc257d4e91178..0000000000000000000000000000000000000000 --- a/java/ReturnNull.java +++ /dev/null @@ -1,8 +0,0 @@ -public Role getOne(String roleId) { - Role role = roleRepository.getOne(roleId); - if (role == null) { - return null; - } else { - return role; - } -} \ No newline at end of file diff --git a/java/RobustA b/java/RobustA deleted file mode 100644 index d872ac7e002c609333bbe7b2e81ef84d5a9a2ccd..0000000000000000000000000000000000000000 --- a/java/RobustA +++ /dev/null @@ -1,19 +0,0 @@ -public class RobustA { - - /** - * 这段代码异常健壮 - */ - public boolean test() { - - //随便写了循环条件 - while (true) { - try { - //业务处理代码 - } catch (Exception e) { - //抓到异常,不处理,继续跑 - continue ; - } - } - - } -} diff --git a/java/RoleService.java b/java/RoleService.java deleted file mode 100644 index d27d68b33925404774fd512c504f004050b4367e..0000000000000000000000000000000000000000 --- a/java/RoleService.java +++ /dev/null @@ -1,22 +0,0 @@ - -@Service -public class ROLEService extends BaseService { - - @Autowired - private JdbcTemplate jdbcTemplate; - - - - public List get(String userId) { - RoleMapper mapper = super.getSqlSession().getMapper(RoleMapper.class); - List right = mapper.get(userId); - return right; - } - public List set(String userId) { - RoleMapper mapper = super.getSqlSession().getMapper(RoleMapper.class); - List right = mapper.set(userId); - return right; - } - - -} \ No newline at end of file diff --git a/java/SameStudents.java b/java/SameStudents.java deleted file mode 100644 index ec317317d354f069c561b801ce0bec3a4cde705f..0000000000000000000000000000000000000000 --- a/java/SameStudents.java +++ /dev/null @@ -1,28 +0,0 @@ -package arrayquestion; - -import java.util.ArrayList; -import java.util.List; - -/** - * 新手程序员:为啥我已经保存了10个不同对象在list中, - * 取出来却发现所有的对象都一样呢 - */ -public class SameStudents { - private Integer age; - - public Integer getAge() { - return age; - } - - public void setAge(Integer age) { - this.age = age; - } - public void saveStudents(){ - List studentsList = new ArrayList<>(); - SameStudents student = new SameStudents(); - for(int i = 0; i < 10; i++) { - student.setAge((int)Math.random()*10); - studentsList.add(student); - } - } -} diff --git a/java/SayNoToOOP b/java/SayNoToOOP deleted file mode 100644 index 3a985dfe123dbf500d579848ef0f03ecbfd70997..0000000000000000000000000000000000000000 --- a/java/SayNoToOOP +++ /dev/null @@ -1,74 +0,0 @@ -@RequestMapping(value = "/list", method = RequestMethod.POST) -public Response questionList(@RequestBody JSONObject param) throws UnsupportedEncodingException { - if(param.size()==0){ - return new Response<>("0", "参数不能为空"); - } - if(param.get("userToken")==null||StringUtils.isBlank(param.get("userToken").toString())){ - return new Response<>("0", "userToken不能为空"); - } - //解密:获取用户信息 - String aesDecrypt = AesDecrypt.aesDecrypt(param.get("userToken").toString()); - if(StringUtils.isEmpty(aesDecrypt)){ - return new Response<>("0", "用户令牌错误"); - } - try { - if(StringUtils.isNumeric(String.valueOf(param.get("pageNo"))) - &&StringUtils.isNumeric(String.valueOf(param.get("numPerPage")))) { - if(Long.valueOf(param.get("pageNo").toString())>0&&Long.valueOf(param.get("numPerPage").toString())>0){ - param.put("numPerPage", param.get("numPerPage").toString()); - param.put("pageNo",String.valueOf(Long.valueOf(param.get("pageNo").toString())-1)); - }else{ - param.put("numPerPage","10"); - param.put("pageNo", "0"); - } - }else{//默认从第一页开始,每页10条 - param.put("numPerPage","10"); - param.put("pageNo", "0"); - } - }catch (Exception e) { - param.put("numPerPage","10"); - param.put("pageNo", "0"); - } - JSONObject user = JSONObject.fromObject(aesDecrypt); - String accessToken=user.get("access_token").toString(); - String branchCode=user.get("branchCode").toString(); - String uid=user.get("userId").toString(); - param.remove("userToken"); - - String result=HttpUtil.postURL(v.getQuestionList, param.toString(), "UTF-8", accessToken, code, uid); - JSONObject pageInfo=new JSONObject(); - if(StringUtils.isNotEmpty(result)&&(JSONObject.fromObject(result).getJSONObject("pageInfo")!=null&& - !JSONObject.fromObject(result).getJSONObject("pageInfo").equals(null))){ - pageInfo=JSONObject.fromObject(result).getJSONObject("pageInfo"); - } - /*param.put("numPerPage","10000"); - param.put("pageNo", "0");//所有题总共7448个 -*/ String resultAll=HttpUtil.postURL(v.getQuestionList, param.toString(), "UTF-8", accessToken, code, uid); - JSONObject pageInfoAll=new JSONObject(); - if(StringUtils.isNotEmpty(resultAll)&&(JSONObject.fromObject(resultAll).getJSONObject("pageInfo")!=null&& - !JSONObject.fromObject(resultAll).getJSONObject("pageInfo").equals(null))){ - pageInfoAll=JSONObject.fromObject(resultAll).getJSONObject("pageInfo"); - } - - List> list=new ArrayList>(); - Map mapAll = new HashMap(); - if(pageInfo!=null&&pageInfo.size()>0){ - JSONArray paperArray=pageInfo.getJSONArray("list"); - System.out.println(paperArray.size()); - for (int i = 0; i < paperArray.size(); i++){ - Map map=new HashMap(); - JSONObject qObj=JSONObject.fromObject(paperArray.get(i).toString()); - map.put("id",qObj.get("questionId"));//获取试卷id - String title=qObj.getString("title").replace("src=\"", "src=\""+v.ImgPrefix+""); - String type=qObj.getString("typelevel"); - map.put("title", title); - map.put("type", type); - list.add(map); - } - //mapAll.put("count",pageInfoAll!=null?pageInfoAll.getJSONArray("list").size():"0"); - mapAll.put("count", pageInfoAll.get("total")!=null? Long.parseLong(pageInfoAll.get("total").toString()):0); - } - mapAll.put("list", list); - - return new Response<>(mapAll); - } \ No newline at end of file diff --git a/java/ShitController.java b/java/ShitController.java deleted file mode 100644 index 925bed0feb3bcb60f9a60a6e9f48dcac754900f2..0000000000000000000000000000000000000000 --- a/java/ShitController.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.hello.xxx.modules.order.web.front; - -@Controller -@RequestMapping("/f/api/order/") -public class OrderController { - - @RequestMapping("createOrder") - public String createOrder(String productId, String num) throws CommonExchellotion { - /** - * 这是一个创建订单的方法,大概有如下三步: - * 1.减少商品数量 - * 2.创建订单 - * 3.创建订单项 - * 问题:坑爹的上一任把所有逻辑写在controller里面,将近200-300行代码,整个controller可读性真的是臭的要死;并且在 - * 这个创建的操作里面,涉及到了商品表,订单表,订单项表的操作,上一个人完全没考虑到事务的问题,每个操作都是用service完 - * 成的!独立开的事务! - */ - return "success"; - } - -} diff --git a/java/ShitJudge.java b/java/ShitJudge.java deleted file mode 100644 index b5b4cd1fc49b3bcd2e2f94515f5e7acb42a3a708..0000000000000000000000000000000000000000 --- a/java/ShitJudge.java +++ /dev/null @@ -1,19 +0,0 @@ -/** - * 判断表单数据是否被发起流程. - * - * @param _formDef 表单对象 - * @param id 表单数据id - * @return - */ -public boolean isFormDataAssocationProcess(FormDef _formDef, Long id) { - String sql = "select count(*) from t_auto_" + _formDef.getId() + " where db_id=:id and processinstanceid_ is not null"; - Map params = new HashMap(); - params.put("id", id); - int count = this.genericJdbcDAO.queryForInt(sql, params); - // 这个判断,一口老血喷出来,一个项目经理写的 - if (count > 0) { - return true; - } else { - return false; - } -} \ No newline at end of file diff --git a/java/ShitNameFunction.java b/java/ShitNameFunction.java deleted file mode 100644 index 0762cd20fcc24f6a3167831e343ab6cc15153bf7..0000000000000000000000000000000000000000 --- a/java/ShitNameFunction.java +++ /dev/null @@ -1,10 +0,0 @@ -/* -* 学生学科评价课程下拉列表加载内容 -* 吐槽一下方法命名,根本就看不懂啥意思,不知道咋写出来的 -*/ -@RequestMapping(value = "/getkcmcxl", method = RequestMethod.POST) -public Object getListData(@RequestBody String str){ - List list = null; - // 一大堆操作 - return list; -} \ No newline at end of file diff --git a/java/ShitNamed.java b/java/ShitNamed.java deleted file mode 100644 index 9739e54b05ef1227975d7877496d899d554e0134..0000000000000000000000000000000000000000 --- a/java/ShitNamed.java +++ /dev/null @@ -1,9 +0,0 @@ -public void shit(){ - // 本身逻辑没什么问题,就这个命名,中英混合 - // 工作流中的 直接办理到结束节点 - // 节点类型是【办到底】 - boolean isbandaodi = confirmMenuindexOfActivityName(processdefinitionid, nextNodeName, "bandaodi"); - if (isbandaodi) { - // 。。。 - } -} \ No newline at end of file diff --git a/java/ShortIsRight.java b/java/ShortIsRight.java deleted file mode 100644 index 423f7f881fd79f458c043dfbd44925ed0b9c5c71..0000000000000000000000000000000000000000 --- a/java/ShortIsRight.java +++ /dev/null @@ -1,13 +0,0 @@ - -/** - * 同事说我写了注释 - * @author mjm - */ - - List purchaseInfoList = sheet.getPurchaseInfoList().stream().filter(purchaseInfo -> - purchaseInfo.getExteriorOperation().getExteriorPart().getExteriorOperationList().stream() - .filter(exteriorOperation -> exteriorOperation.getProcessState().equals(ExteriorOperation.ProcessState.PROCESSING)).count() != 0 - //订单明细中工序对应的工件下的其他工序存在加工中,且已发给供应商且供应商不是当前订单供应商时,需要判断 - && (purchaseInfo.getExteriorOperation().getExteriorPart().getTeamwork() == null || - !purchaseInfo.getExteriorOperation().getExteriorPart().getTeamwork().equals(sheet.getTeamwork())) - ).collect(Collectors.toList()); \ No newline at end of file diff --git a/java/SinletonDemo.java b/java/SinletonDemo.java deleted file mode 100644 index 4269d44c23d1dd50ee921bc5378b9be8cdffa6d4..0000000000000000000000000000000000000000 --- a/java/SinletonDemo.java +++ /dev/null @@ -1,14 +0,0 @@ -class SingletonDemo { - - // 单例写法参加:https://blog.51cto.com/aiilive/2164281 - public static class Singleton { - // 坑人的单例 - static Singleton i = null; - - public static Singleton Instance() { - if (i == null) - i = new Singleton(); - return i; - } - } -} \ No newline at end of file diff --git a/java/Sleep.java b/java/Sleep.java deleted file mode 100644 index fc2575a387bae8f884655054dd24d00927ef2cd8..0000000000000000000000000000000000000000 --- a/java/Sleep.java +++ /dev/null @@ -1,19 +0,0 @@ - - -/*** - * - * Ϊ˺Żѯٶ - * - */ - -public class Sleep { - - public Object getObect(){ - /*** - ѯ - */ - Thread.sleep(5000) - return object; - } - -} diff --git a/java/SleepSort b/java/SleepSort deleted file mode 100644 index 75ebc40146974853e498495126ac58cfbf22bc62..0000000000000000000000000000000000000000 --- a/java/SleepSort +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 睡觉排序法 - * - * @author z77z - * - */ - -public class SleepSort { - public static void main(String[] args) { - int[] ints = { 1, 4, 7, 3, 8, 9, 2, 6, 5 }; - SortThread[] sortThreads = new SortThread[ints.length]; - for (int i = 0; i < sortThreads.length; i++) { - sortThreads[i] = new SortThread(ints[i]); - } - for (int i = 0; i < sortThreads.length; i++) { - sortThreads[i].start(); - } - } -} - -class SortThread extends Thread { - int ms = 0; - - public SortThread(int ms) { - this.ms = ms; - } - - public void run() { - try { - sleep(ms * 10 + 10); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.out.println(ms); - } -} \ No newline at end of file diff --git a/java/SpinAndWaitForStockingIn.java b/java/SpinAndWaitForStockingIn.java deleted file mode 100644 index 3dd0924411f753b5d03e73c0f0af52b519727d5c..0000000000000000000000000000000000000000 --- a/java/SpinAndWaitForStockingIn.java +++ /dev/null @@ -1,30 +0,0 @@ -public class SpinAndFetchSomeData { - - /** - * 下单后通过MQ触发的通知操作,根据订单信息通知用户和其他子系统进行进一步的处理。但是从MQ收到该通知时,订单信息还未入库,而且不知道入库操作和通知操作的时序关系(全是异步操作,通过MQ和回调来触发操作,分析代码无法知道调用顺序) - */ - public void notify(String modelId) { - SomeModel model = this.selectSomeModel(modelId); - - // ...处理逻辑 - } - - /** - * 线程自旋等待 - */ - private SomeModel selectSomeModel(String id) { - SomeModel model; - // to prevent that getting the response is to fast - for (int i = 0; i < 10; i++) { - try { - TimeUnit.MILLISECONDS.sleep(200); - } catch (InterruptedException e) { - logger.error(e.getMessage(), e); - } - model = mapper.selectById(id); - if (null != model) - return model; - } - return new SomeModel(); - } -} \ No newline at end of file diff --git a/java/Split b/java/Split deleted file mode 100644 index b2c051986c7c2e387356f735ca6023490ad0f3c7..0000000000000000000000000000000000000000 --- a/java/Split +++ /dev/null @@ -1,28 +0,0 @@ -/** - * 字符串split使用场景比较频繁,此处有一个极易掉坑的操作 - * - * @author shuzheng - * @date 2019/5/27 - */ -public class Split { - - public static void main(String[] args) { - String param1 = "1,2"; - String param2 = "1,2,"; - String param3 = ",1,2,"; - - System.out.println(param1.split(",").length); - System.out.println(param2.split(",").length); - System.out.println(param3.split(",").length); - } - - /* - * 输出结果: - * 2 - * 2 - * 3 - * - * 惊喜不惊喜?结尾的空字符串被丢弃,可使用重载方法 public String [] split (String regex, int limit) 中 limit 参数控制模式应用的次数,-1 则不会丢弃结尾空字符。 - */ - -} diff --git a/java/SplitTest.java b/java/SplitTest.java deleted file mode 100644 index bdab332a22b1e3448da58bef0779fee4178ce7f6..0000000000000000000000000000000000000000 --- a/java/SplitTest.java +++ /dev/null @@ -1,12 +0,0 @@ -public class SplitTest { - - /** - * split将一个正则表达式作为参数,井根据表达式将字符串分割 - * 成多个字符串。点号 .是表示任何字符的正则表达式。 - * @param args - */ - public static void main(String[] args) { - System.out.println("12.345-6.A".split(".").length);//0 - System.out.println("12.345-6.A".split("\\.").length);//3 - } -} \ No newline at end of file diff --git a/java/StockUpResultServiceImpl.java b/java/StockUpResultServiceImpl.java deleted file mode 100644 index ca210581da9a98a5200bc343c17992bc5539e9b6..0000000000000000000000000000000000000000 --- a/java/StockUpResultServiceImpl.java +++ /dev/null @@ -1,781 +0,0 @@ - -/** - * 公司高级JAVA工程师的业务代码,高!实在是高! - * - */ -@Service -public class StockUpResultServiceImpl{ - - @Override - public void updateCurrentResults(net.sf.json.JSONObject jsonObject) { - Long hour = new Long(LinkUtils.getDateHour(null)); - Long ratingResultId; - String ratingResultName; - boolean empty = StringUtils.isNotEmpty(jsonObject); - StockUpResult stockUpResult; - if (empty) { - ratingResultId = jsonObject.getLong("id"); - ratingResultName = jsonObject.getString("ratingSerialNum"); - stockUpResult = this.getBaseMapper().getStockUpResultByCreateTime(); - if (StringUtils.isNull(stockUpResult)) { - return; - } - } else { - jsonObject = remoteUtilService.queryNewRatingResult(); - ratingResultId = jsonObject.getLong("id"); - ratingResultName = jsonObject.getString("ratingSerialNum"); - if (StringUtils.isNull(jsonObject)) { - return; - } - stockUpResult = new StockUpResult(); - stockUpResult.setResultNumber(getSerialNum()); - stockUpResult.setBelongHour(hour); - } - stockUpResult.setRatingResultId(ratingResultId); - stockUpResult.setRatingResultName(ratingResultName); - Map ratingResultMap = remoteUtilService.queryNewRatingResultById(String.valueOf(ratingResultId)); - - JSONObject params = new JSONObject(); - params.put("type", Constants.CPJJLX); - AjaxResult seasonResult = remoteJctDictionService.listByType(params); - List jctDictions = JSON.parseArray(JSONObject.toJSON(seasonResult.get("data")).toString(), JctDiction.class); - Map seasonTypeCodeMap = new HashMap<>(); - for (JctDiction jctDiction : jctDictions) { - seasonTypeCodeMap.put(String.valueOf(jctDiction.getIdKey()), jctDiction.getValue()); - } - - JctDiction jctDiction = new JctDiction(); - jctDiction.setTypeCode(Constants.SALE_CALCULATE_TOP_LEVEL); - List dictionList = remoteJctDictionService.getListByTypeCodeAndState(jctDiction); - Map dictionMap = new HashMap<>(); - for (JctDiction diction : dictionList) { - dictionMap.put(String.valueOf(diction.getIdKey()), diction.getName()); - } - Map dictionTopMap = new HashMap<>(); - for (JctDiction diction : dictionList) { - dictionTopMap.put(String.valueOf(Integer.parseInt(diction.getValue()) + 1), String.valueOf(diction.getIdKey())); - } - - Map topLevelMap = DictCache.getDictCache("topLevel"); - - - List currentResults = commodityOdsMapper.getCurrentResults(); - - List shopIds = new ArrayList<>(currentResults.stream().map(StockUpResultDetailsDTO::getShopId).collect(Collectors.toSet())); - - List details = commodityJcMapper.getJpSkuInfo(); - - - List transits = remoteStockService.getPurchaseInTransitsByShopIds(shopIds); - - List positions = remoteStockService.getOpenPositionsByShopIds(shopIds); - - Map categoryDeliveryDateMap = remoteStockService.getEstimatedDayBySku(); - - Map calculateDailyAverageMap = settingAvgDayTypeService.publicSettingAvgDayTypeMap(); - Set calculateDailyAverageKeys = calculateDailyAverageMap.keySet(); - - List bbs = remoteStockService.selectBasStorageListByShopIds(shopIds); - - List info = Collections.synchronizedList(new ArrayList<>()); - shopIds.stream().forEach(shopId -> { - JSONObject json = new JSONObject(); - StringBuilder sb = new StringBuilder(); - bbs.stream().filter(bs -> Objects.equals(shopId, bs.getShopId()) && "本地仓库".equals(bs.getStorageSxNm())) - .forEach(bs -> { - sb.append("'" + bs.getParentId() + "-" + bs.getIdKey() + "',"); - }); - String cw = sb.length() > 0 ? sb.substring(0, sb.length() - 1) : null; - if (StringUtils.isNotBlank(cw)) { - json.put("FilterStringSql", "FStockId.FNumber in (" + cw + ")"); - json = JSONObject.parseObject(remotePurchaseService.queryStkInventory(json.toJSONString())); - Boolean flag = json.getBoolean("flag"); - if (flag != null && flag) { - JSONArray infoArray = json.getJSONArray("info"); - info.addAll(infoArray.toJavaList(JSONObject.class)); - } - } - }); - Map> stockMap = new ConcurrentHashMap<>(); - info.stream().forEach(cw -> { - String warehouseId = String.valueOf(cw.getString("warehouse_id")); - Map goodsSkuIdStockMap = LinkUtils.getNewMap(stockMap.get(warehouseId)); - String goodsSkuIdStr = cw.getString("goods_sku_id"); - Long stock = LinkUtils.getZeroLongNotNull(goodsSkuIdStockMap.get(goodsSkuIdStr)); - stock += cw.getLong("s_amounts"); - goodsSkuIdStockMap.put(goodsSkuIdStr, stock); - stockMap.put(warehouseId, goodsSkuIdStockMap); - }); - - Map> salesBySellerSkuMap = listSalesBySellerSku(); - - Map> SalesByOperationCodeSellerSkuYesterdayMap = listSalesByOperationCodeSellerSkuYesterday(); - Map codeYesterdaySumMap = new ConcurrentHashMap<>(); - SalesByOperationCodeSellerSkuYesterdayMap.forEach((key, codeMap) -> { - if (StringUtils.isNotNull(codeMap)) { - String keyof = String.valueOf(key); - LongAdder sum = new LongAdder(); - codeMap.values().stream().forEach(vo -> { - if (Objects.equals(keyof, vo.getOperationCode())) { - sum.add(vo.getSum()); - } - }); - codeYesterdaySumMap.put(keyof, sum); - } - }); - - Map> salesByOperationCodeMap = listSalesByOperationCode(); - Map codeSumMap = new ConcurrentHashMap<>(); - salesByOperationCodeMap.forEach((key, codeMap) -> { - if (StringUtils.isNotNull(codeMap)) { - String keyof = String.valueOf(key); - LongAdder sum = new LongAdder(); - codeMap.values().stream().forEach(vo -> { - if (Objects.equals(keyof, vo.getOperationCode())) { - sum.add(vo.getSum()); - } - }); - codeSumMap.put(keyof, sum); - } - }); - - Map>> salesByOperationCodeSellerSkuMap = listSalesByOperationCodeSellerSku(); - Comparator comparator = (v1, v2) -> Integer.compare(v2.getSum(), v1.getSum()); - - Map> stringObjectMap = listBySeasonType(); - - Map> monthAndOperationCode = listByMonthAndOperationCode(); - - Map stringBigDecimalMap = historyTopLevelService.selectHistoryTopLevelByOperationCodes(); - - List saleLifecycleCurves = saleLifecycleCurveService.selectSaleLifecycleCurveList(); - Map> periodTypeTopCurveMap = new HashMap<>(); - for (SaleLifecycleCurve curve : saleLifecycleCurves) { - String periodType = curve.getPeriodType(); - Map topCurveMap = LinkUtils.getNewMap(periodTypeTopCurveMap.get(periodType)); - topCurveMap.put(String.valueOf(curve.getTopLevelId()), curve); - periodTypeTopCurveMap.put(periodType, topCurveMap); - } - - Map>> combineScoreMap = comUpCombineScoreSetService.getCombineScoreMap(); - - Map> standardRevolveDayMap = stockUpStandardRevolveDaysService.queryStandardRevolveDay(); - Set standardRevolveDayKeys = standardRevolveDayMap.keySet(); - String standardRevolveDayKey = standardRevolveDayKeys.stream().filter(key -> { - String[] split = key.split(","); - long startTime = LinkUtils.parseDay(split[0]).getTime(); - long endTime = LinkUtils.parseDay(split[1]).getTime(); - long time = System.currentTimeMillis(); - return startTime <= time && time <= endTime; - }).findFirst().orElse(null); - Map revolveDayMap = LinkUtils.getNewMap(standardRevolveDayMap.get(standardRevolveDayKey)); - Set revolveDayKeys = revolveDayMap.keySet(); - - Map> outOfMap = stockUpSettingOutOfService.selectStockUpSettingOutOfMap(); - Set outOfKeys = outOfMap.keySet(); - - Map seasonOutMap = stockUpSettingSeasonOutService.selectStockUpSettingSeasonOutMap(); - Map topSeasonOutMap = new HashMap<>(); - for (String key : seasonOutMap.keySet()) { - topSeasonOutMap.put(topLevelMap.get(key), seasonOutMap.get(key)); - } - - - Map seasonMidMap = stockUpSettingSeasonMidService.selectStockUpSettingSeasonMidMap(); - - Map columnNameMap = remoteStockService.getOpcnCloumnNameMapByZero(); - OrderFormula fbaStockFormula = remoteStockService.selectOrderFormulaListByShopIdByZero(FbaStockFormula.FBA_STOCK); - OrderFormula averageDailySalesFormula = remoteStockService.selectOrderFormulaListByShopIdByZero(AverageDailySalesFormula.AVERAGE_DAILY_SALES); - - Map> utilTopMap = remoteStockService.getUtilTopMap(); - Map operationCodeAverageDailySalesWeightingMap = getOperationCodeAverageDailySalesWeighting(salesBySellerSkuMap); - - Map>>>> colorSetMap = stockUpColorSettingService.getColorSetMap(); - - Map>> prepositionRollcallMap = stockUpPrepositionRollcallService.queryPrepositionRollcall(); - - List operationCodeTops = stockUpOperationCodeTopService.getOperationCodeList(); - - Map courierDaysMap = stockUpInitLogisticsDaysService.getCourierDaysMap(); - - currentResults = Collections.synchronizedList(currentResults); - Map codeDh30DaySumMap = new ConcurrentHashMap<>(); - currentResults.stream().forEach(dto -> { - String operationCode = String.valueOf(dto.getOperationCode()); - String sellerSku = dto.getSellerSku(); - Long fulfillable = dto.getFulfillable(); - Long pendingOrders = Constants.ZERO_LONG; - Map sellerSkuMap = LinkUtils.getNewMap(salesBySellerSkuMap.get(String.valueOf(dto.getShopId()))); - SalesBySellerSkuVO vo = sellerSkuMap.get(sellerSku); - if (StringUtils.isNotNull(vo)) { - pendingOrders = (long) vo.getOne(); - } - int salesVolumeDay30Zr = Constants.ZERO; - SalesByOperationCodeVO codeVO = LinkUtils.getNewMap(SalesByOperationCodeSellerSkuYesterdayMap.get(operationCode)).get(sellerSku); - if (StringUtils.isNotNull(codeVO)) { - salesVolumeDay30Zr = codeVO.getSum(); - } - - FormulaDTO fbaStockFormulaDTO = new FormulaDTO(); - fbaStockFormulaDTO.setFormula(fbaStockFormula.getFormula()); - fbaStockFormulaDTO.setColumnNameMap(columnNameMap); - fbaStockFormulaDTO.setFbaStockFormula(new FbaStockFormula(dto.getInbound(), dto.getReserved(), fulfillable, dto.getReceiving(), pendingOrders)); - long fbaStock = remoteStockService.getColumnNameByFormula(fbaStockFormulaDTO).longValue(); - dto.setFbaStock(fbaStock); - - String operationCodeTop = operationCodeTops.stream().filter(code -> Objects.equals(code, operationCode)).findFirst().orElse(null); - if (StringUtils.isNotBlank(operationCodeTop) && fbaStock - dto.getFbaIntransit() <= 0) { - LongAdder longAdder = codeDh30DaySumMap.get(operationCode); - if (StringUtils.isNull(longAdder)) { - longAdder = new LongAdder(); - } - longAdder.add(salesVolumeDay30Zr); - codeDh30DaySumMap.put(operationCode, longAdder); - } - }); - Calendar instance = Calendar.getInstance(); - int year = LinkUtils.getDateYear(instance); - int month = LinkUtils.getDateMonth(instance); - Map codeCurrentTurnoverDaysMap = new ConcurrentHashMap<>(); - currentResults.stream().forEach(dto -> { - Long shelfDay = dto.getShelfDay(); - Long shopId = dto.getShopId(); - String shopIdStr = String.valueOf(shopId); - String operationCode = String.valueOf(dto.getOperationCode()); - BigDecimal topId = stringBigDecimalMap.get(operationCode); - if (StringUtils.isNotNull(topId)) { - dto.setTopHistory(dictionMap.get(topId.toString())); - } - - boolean cxBoolean = false; - boolean qdBoolean = false; - Long goodsSkuId = dto.getGoodsSkuId(); - String goodsSkuIdStr = String.valueOf(goodsSkuId); - StockUpJpSkuInfo detail = details.stream().filter(f -> Objects.equals(goodsSkuId, f.getGoodsSkuId())).findFirst().orElse(null); - - if (StringUtils.isNotNull(detail)) { - String firstOrderDate = dto.getFirstOrderDate(); - String seasonTypeIdStr = String.valueOf(detail.getSeasonTypeId()); - cxBoolean = Objects.equals(Constants.CXK, seasonTypeCodeMap.get(seasonTypeIdStr)); - qdBoolean = Objects.equals(Constants.QDK, seasonTypeCodeMap.get(seasonTypeIdStr)); - - if (Objects.equals(Constants.ZERO_STR, firstOrderDate)) { - dto.setNewOldType(Constants.ONE_STR); - } else { - Date date = LinkUtils.parseDay(firstOrderDate); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - int firstOrderDateYear = LinkUtils.getDateYear(calendar); - if (cxBoolean && ((year - firstOrderDateYear == 1 && month == 12) || (firstOrderDateYear >= year))) { - dto.setNewOldType(Constants.ZERO_STR); - } else if (qdBoolean && (firstOrderDateYear == year)) { - dto.setNewOldType(Constants.ZERO_STR); - } else { - dto.setNewOldType(Constants.ONE_STR); - } - } - String colorIdStr = String.valueOf(detail.getColorId()); - - SalesByOperationCodeVO vo = LinkUtils.getNewMap(salesByOperationCodeMap.get(operationCode)).get(colorIdStr); - if (StringUtils.isNotNull(vo)) { - Long colorDay30 = (long) vo.getSum(); - String seasonTypekey = cxBoolean ? Constants.ONE_STR : qdBoolean ? Constants.TWO_STR : Constants.THREE_STR; - String shelfDayKey = shelfDay <= 45 ? Constants.ONE_STR : Constants.TWO_STR; - colorSetMap.forEach((key, shopIdMap) -> { - if (StringUtils.isNotNull(shopIdMap)) { - Map map = LinkUtils.getNewMap(LinkUtils.getNewMap(LinkUtils.getNewMap(shopIdMap.get(shopIdStr)).get(seasonTypekey)).get(shelfDayKey)); - if (Objects.equals(Constants.ZERO_STR, key)) { - String colorKey = map.keySet().stream().filter(k -> { - String[] split = k.split(","); - return Long.parseLong(split[0]) <= colorDay30 && colorDay30 < Long.parseLong(split[1]); - }).findFirst().orElse(null); - if (StringUtils.isNotNull(colorKey)) { - dto.setColorLevel(map.get(colorKey)); - } - } else { - Double operationCodeSum = Constants.ONE_DOUBLE; - LongAdder longAdder = codeSumMap.get(operationCode); - if (StringUtils.isNotNull(longAdder)) { - operationCodeSum = longAdder.doubleValue(); - } - Double colorBl = colorDay30 / operationCodeSum * Constants.HUNDRED; - String colorKey = map.keySet().stream().filter(k -> { - String[] split = k.split(","); - return Double.parseDouble(split[0]) <= colorBl && colorBl < Double.parseDouble(split[1]); - }).findFirst().orElse(null); - if (StringUtils.isNotNull(colorKey)) { - dto.setColorLevel(map.get(colorKey)); - } - } - } - }); - - dto.setColorDay30(colorDay30); - } - BeanUtils.copyProperties(detail, dto); - } else { - dto.setNewOldType(Constants.ONE_STR); - } - - Map topMap = LinkUtils.getNewMap(utilTopMap.get(shopIdStr)); - LongAdder longAdder = operationCodeAverageDailySalesWeightingMap.get(operationCode); - if (StringUtils.isNull(longAdder)) { - longAdder = new LongAdder(); - } - long weighting = longAdder.longValue(); - - Set topKeys = topMap.keySet(); - String topKey = topKeys.stream().filter(key -> { - String[] split = key.split(","); - return Long.parseLong(split[0]) <= weighting && weighting < Long.parseLong(split[1]); - }).findFirst().orElse(null); - String top = topMap.get(topKey); - dto.setTop(top); - - - Long purchaseInTransit = Constants.ZERO_LONG; - boolean skuTypeBoolean = Constants.ONE_STR.equals(dto.getSkuType()); - if (skuTypeBoolean) { - PurchaseInTransitVO transit = transits.stream().filter(f -> Objects.equals(shopId, f.getShopId()) && Objects.equals(goodsSkuId, f.getGoodsSkuId())).findFirst().orElse(new PurchaseInTransitVO(Constants.ZERO_LONG)); - purchaseInTransit = transit.getSjAmounts(); - } - dto.setPurchaseInTransit(purchaseInTransit); - - String sellerSku = dto.getSellerSku(); - OpenPositionDTO position = positions.stream().filter(f -> Objects.equals(shopId, f.getShopId()) && Objects.equals(sellerSku, f.getSellerSku())).findFirst().orElse(new OpenPositionDTO(Constants.ZERO_LONG)); - Long actualPackingAmounts = position.getActualPackingAmounts(); - dto.setActualPackingAmounts(actualPackingAmounts); - //产品说的,如果拿到小数,就改成整数,用户正常不会写小数 - Double categoryDeliveryDate = categoryDeliveryDateMap.get(goodsSkuIdStr); - dto.setCategoryDeliveryDate(StringUtils.isNotNull(categoryDeliveryDate) ? categoryDeliveryDate.longValue() : null); - LongAdder localStockLong = new LongAdder(); - LongAdder overseasStockLong = new LongAdder(); - if (skuTypeBoolean) { - bbs.stream().filter(bs -> Objects.equals(shopId, bs.getShopId()) && "本地仓库".equals(bs.getStorageSxNm())).forEach(storage -> { - Long stock = LinkUtils.getZeroLongNotNull(LinkUtils.getNewMap(stockMap.get(storage.getParentId() + "-" + storage.getIdKey())).get(goodsSkuIdStr)); - String storageNm = storage.getStorageNm(); - if (storageNm.contains(Constants.XIAMEN)) { - localStockLong.add(stock); - } else if (storageNm.contains(Constants.GUANGZOU)) { - localStockLong.add(stock); - } else if (storageNm.contains(Constants.OVERSEAS_GC)) { - overseasStockLong.add(stock); - } else if (storageNm.contains(Constants.OVERSEAS_GH)) { - overseasStockLong.add(stock); - } else if (storageNm.contains(Constants.OVERSEAS_JF)) { - overseasStockLong.add(stock); - } else if (storageNm.contains(Constants.OVERSEAS_ZY)) { - overseasStockLong.add(stock); - } else if (storageNm.contains(Constants.OVERSEAS_CS)) { - overseasStockLong.add(stock); - } - }); - } - long localStock = localStockLong.longValue(); - long overseasStock = overseasStockLong.longValue(); - dto.setLocalStock(localStock); - dto.setOverseasStock(overseasStock); - - Long pendingOrders = Constants.ZERO_LONG; - Long salesVolumeDay3 = Constants.ZERO_LONG; - Long salesVolumeDay7 = Constants.ZERO_LONG; - Long salesVolumeDay14 = Constants.ZERO_LONG; - Long salesVolumeDay30 = Constants.ZERO_LONG; - Map sellerSkuMap = LinkUtils.getNewMap(salesBySellerSkuMap.get(String.valueOf(shopId))); - SalesBySellerSkuVO vo = sellerSkuMap.get(sellerSku); - if (StringUtils.isNotNull(vo)) { - pendingOrders = (long) vo.getOne(); - salesVolumeDay3 = (long) vo.getThree(); - salesVolumeDay7 = (long) vo.getSeven(); - salesVolumeDay14 = (long) vo.getFourteen(); - salesVolumeDay30 = (long) vo.getThirty(); - } - Long reserved = dto.getReserved(); - Long fulfillable = dto.getFulfillable(); - dto.setAmazonStock(reserved + fulfillable - pendingOrders); - - Long fbaStock = dto.getFbaStock(); - - dto.setSalesVolumeDay30(salesVolumeDay30); - Double averageDailySalesDay3 = Double.parseDouble(Constants.DF_2.format(salesVolumeDay3 / 3.0)); - Double averageDailySalesDay7 = Double.parseDouble(Constants.DF_2.format(salesVolumeDay7 / 7.0)); - Double averageDailySalesDay14 = Double.parseDouble(Constants.DF_2.format(salesVolumeDay14 / 14.0)); - Double averageDailySalesDay30 = Double.parseDouble(Constants.DF_2.format(salesVolumeDay30 / 30.0)); - dto.setAverageDailySalesDay3(averageDailySalesDay3); - dto.setAverageDailySalesDay7(averageDailySalesDay7); - dto.setAverageDailySalesDay14(averageDailySalesDay14); - dto.setAverageDailySalesDay30(averageDailySalesDay30); - Long averageDailySalesWeighting = LinkUtils.getBigDecimalRoundHalfUpByDoubleToLong((averageDailySalesDay3 + averageDailySalesDay7 + averageDailySalesDay14) / 3.0); - dto.setAverageDailySalesWeighting(averageDailySalesWeighting); - - FormulaDTO averageDailySalesFormulaDTO = new FormulaDTO(); - averageDailySalesFormulaDTO.setFormula(averageDailySalesFormula.getFormula()); - averageDailySalesFormulaDTO.setColumnNameMap(columnNameMap); - averageDailySalesFormulaDTO.setAverageDailySalesFormula(new AverageDailySalesFormula(salesVolumeDay3, salesVolumeDay7, salesVolumeDay14, salesVolumeDay30)); - Double averageDailySales = remoteStockService.getColumnNameByFormula(averageDailySalesFormulaDTO); - dto.setAverageDailySales(averageDailySales); - - Long allStock = fbaStock + localStock + purchaseInTransit + actualPackingAmounts + overseasStock; - dto.setAllStock(allStock); - - PublicSettingAvgDayTypeDTO dayTypeDTO = calculateDailyAverageMap.get(calculateDailyAverageKeys.stream().filter(key -> { - String[] split = key.split(","); - return Long.parseLong(split[0]) <= shelfDay && shelfDay <= Long.parseLong(split[1]); - }).findFirst().orElse(null)); - Long calculateDailyAverageNum = null; - if (StringUtils.isNotNull(dayTypeDTO)) { - dto.setCalculateDailyAverageId(dayTypeDTO.getId()); - dto.setCalculateDailyAverageNm(dayTypeDTO.getTypeName()); - JEP jep = new JEP(); - jep.addStandardFunctions(); - jep.addVariable("salesVolumeDay3", salesVolumeDay3); - jep.addVariable("salesVolumeDay7", salesVolumeDay7); - jep.addVariable("salesVolumeDay14", salesVolumeDay14); - jep.addVariable("salesVolumeDay30", salesVolumeDay30); - jep.addVariable("averageDailySales", averageDailySales); - jep.addVariable("averageDailySalesDay3", averageDailySalesDay3); - jep.addVariable("averageDailySalesDay7", averageDailySalesDay7); - jep.addVariable("averageDailySalesDay14", averageDailySalesDay14); - jep.addVariable("averageDailySalesDay30", averageDailySalesDay30); - jep.parseExpression(dayTypeDTO.getFormulaValue()); - calculateDailyAverageNum = LinkUtils.getBigDecimalRoundHalfUpByDoubleNaNToLong(jep.getValue()); - } - dto.setCalculateDailyAverageNum(calculateDailyAverageNum); - - String categoryLabel = null; - String operationCodeTop = operationCodeTops.stream().filter(code -> Objects.equals(code, operationCode)).findFirst().orElse(null); - if (StringUtils.isNotBlank(operationCodeTop)) { - LongAdder dh30DaySum = codeDh30DaySumMap.get(operationCode); - LongAdder codeSum = codeYesterdaySumMap.get(operationCode); - if (StringUtils.isNotNull(codeSum) && StringUtils.isNotNull(dh30DaySum) && dh30DaySum.longValue() / codeSum.doubleValue() >= 0.4) { - categoryLabel = ""; - } - } - - if (StringUtils.isBlank(categoryLabel)) { - if (Objects.equals("", dto.getStyleType())) { - categoryLabel = ""; - } else if (StringUtils.isNotNull(categoryDeliveryDate) && categoryDeliveryDate > 9) { - boolean topBoolean = Objects.equals(Constants.ONE_STR, top) || Objects.equals(Constants.TWO_STR, top); - if ((cxBoolean && ((topBoolean && 3 <= month && month <= 6) || (!topBoolean && 3 <= month && month <= 4))) - || (qdBoolean && ((topBoolean && 9 <= month && month <= 12) || (!topBoolean && 9 <= month && month <= 10)))) { - categoryLabel = ""; - } - } - } - if (StringUtils.isBlank(categoryLabel)) { - categoryLabel = ""; - } - dto.setCategoryLabel(categoryLabel); - - - String attribute = dto.getInventoryAttribute(); - boolean inventoryAttributeBoolean = Objects.equals(Constants.QCK, attribute) || Objects.equals(Constants.PSQC, attribute); - String topHistory = dto.getTopHistory(); - String colorIdStr = String.valueOf(dto.getColorId()); - Long stockQuantityFront = Constants.ZERO_LONG; - if (!inventoryAttributeBoolean && StringUtils.isNotNull(operationCode)) { - Map> fjMap = prepositionRollcallMap.get(operationCode); - if (StringUtils.isNull(fjMap)) { - stockQuantityFront = Constants.ZERO_LONG; - } else { - for (Map.Entry> entry : fjMap.entrySet()) { - Map value = entry.getValue(); - String key = entry.getKey(); - dto.setAntiSeason(key); - if (StringUtils.isNotNull(value)) { - if (Objects.equals(Constants.TWO_STR, key)) { - Long jzDay = seasonMidMap.get(String.valueOf(month)); - if (StringUtils.isNull(jzDay)) { - jzDay = Constants.ZERO_LONG; - } - List codeVos = LinkUtils.getNewMap(salesByOperationCodeSellerSkuMap.get(operationCode)).get(String.valueOf(colorIdStr)); - if (StringUtils.isNotEmpty(codeVos)) { - Collections.sort(codeVos, comparator); - Long codeVoSize = LinkUtils.getRoundUpMultiply(new BigDecimal(codeVos.size()), 0.7); - for (int i = 0; i < codeVoSize; i++) { - if (Objects.equals(operationCode, codeVos.get(i).getOperationCode())) { - stockQuantityFront = averageDailySalesWeighting * jzDay; - break; - } - } - } - } else { - List months = LinkUtils.getIntegerList(topSeasonOutMap.get(topHistory)); - if (StringUtils.isNotEmpty(months)) { - - double sum = 0; - StringBuilder stockMonth = new StringBuilder(); - for (int m : months) { - stockMonth.append(m + ","); - } - dto.setStockMonth(stockMonth.length() > 0 ? stockMonth.substring(0, stockMonth.length() - 1) : null); - SalesBySeason season; - if (qdBoolean) { - season = LinkUtils.getNewMap(stringObjectMap.get(Constants.ONE_STR)).get(operationCode + ":" + sellerSku); - } else { - season = LinkUtils.getNewMap(stringObjectMap.get(Constants.ZERO_STR)).get(operationCode + ":" + sellerSku); - } - if (StringUtils.isNotNull(season)) { - double b = season.getRate(); - for (String referenceLabel : value.keySet()) { - if (Objects.equals(Constants.TWO_STR, referenceLabel)) { - for (int m : months) { - SalesByMonthAndOperationCode sales = LinkUtils.getNewMap(monthAndOperationCode.get(operationCode)).get(String.valueOf(m)); - if (StringUtils.isNotNull(sales)) { - sum += sales.getSum() * b; - } - } - } else { - Map topCurveMap = null; - if (cxBoolean) { - topCurveMap = periodTypeTopCurveMap.get(Constants.XCX); - } else if (qdBoolean) { - topCurveMap = periodTypeTopCurveMap.get(Constants.XQD); - } - SaleLifecycleCurve curve = LinkUtils.getNewMap(topCurveMap).get(dictionTopMap.get(value.get(referenceLabel))); - if (StringUtils.isNotNull(curve)) { - for (int m : months) { - double a = 0; - int day = LinkUtils.getDaysOfMonth(year, m, Constants.ONE); - switch (m) { - case 1: - a = Double.parseDouble(curve.getJanuaryNumber()); - break; - case 2: - a = Double.parseDouble(curve.getFebruaryNumber()); - break; - case 3: - a = Double.parseDouble(curve.getMarchNumber()); - break; - case 4: - a = Double.parseDouble(curve.getAprilNumber()); - break; - case 5: - a = Double.parseDouble(curve.getMayNumber()); - break; - case 6: - a = Double.parseDouble(curve.getJuneNumber()); - break; - case 7: - a = Double.parseDouble(curve.getJulyNumber()); - break; - case 8: - a = Double.parseDouble(curve.getAugustNumber()); - break; - case 9: - a = Double.parseDouble(curve.getSeptemberNumber()); - break; - case 10: - a = Double.parseDouble(curve.getOctoberNumber()); - break; - case 11: - a = Double.parseDouble(curve.getNovemberNumber()); - break; - case 12: - a = Double.parseDouble(curve.getDecemberNumber()); - break; - } - sum += a * day * b; - } - } - } - } - } - stockQuantityFront = LinkUtils.doubleToLong(sum - allStock); - } - } - } - } - } - } - if (stockQuantityFront < 5) { - stockQuantityFront = Constants.ZERO_LONG; - } else { - stockQuantityFront = LinkUtils.getRoundUpDivide(new BigDecimal(stockQuantityFront), 5.0) * 5; - } - dto.setStockQuantityFront(stockQuantityFront); - - - Long stockQuantityRoutine = Constants.ZERO_LONG; - String colorLevel = dto.getColorLevel(); - - if (Objects.equals(Constants.ZERO_LONG, averageDailySalesWeighting)) { - averageDailySalesWeighting = Constants.ONE_LONG; - } - - - if (StringUtils.isNotNull(calculateDailyAverageNum) && !inventoryAttributeBoolean) { - - Long num = calculateDailyAverageNum; - if (Objects.equals(Constants.ZERO_LONG, num)) { - num = Constants.ONE_LONG; - } - Double currentTurnoverDays = allStock * Constants.ONE_DOUBLE / num; - if (currentTurnoverDays < 80) { - DoubleAdder doubleAdder = codeCurrentTurnoverDaysMap.get(operationCode); - if (StringUtils.isNull(doubleAdder)) { - doubleAdder = new DoubleAdder(); - } - doubleAdder.add((80 - currentTurnoverDays) * calculateDailyAverageNum); - codeCurrentTurnoverDaysMap.put(operationCode, doubleAdder); - } - dto.setCurrentTurnoverDays(currentTurnoverDays); - if (shelfDay > 25) { - Long fraction; - Map> topZhMap = LinkUtils.getNewMap(combineScoreMap.get(Constant.TOP_LEVEL_VALUE)); - Map> colorZhMap = LinkUtils.getNewMap(combineScoreMap.get(Constant.COLOR_LEVEL_VALUE)); - String code; - if (shelfDay <= 45) { - code = SalesPeriod.NEW_PRODUCT_PROTECTION_PERIOD.getCode(); - } else { - code = SalesPeriod.DAILY_SALES_PERIOD.getCode(); - } - Map topFsMap = LinkUtils.getNewMap(topZhMap.get(code)); - Map colorFsMap = LinkUtils.getNewMap(colorZhMap.get(code)); - Long topFs = topFsMap.get(top); - Long colorFs = colorFsMap.get(colorLevel); - if (StringUtils.isNull(topFs) || StringUtils.isNull(colorFs)) { - fraction = Constants.ZERO_LONG; - } else { - fraction = topFs * colorFs; - } - String revolveDayKey = revolveDayKeys.stream().filter(key -> { - String[] split = key.split(","); - return Long.parseLong(split[0]) <= fraction && fraction <= Long.parseLong(split[1]); - }).findFirst().orElse(null); - Long turnoverDays = LinkUtils.getZeroLongNotNull(revolveDayMap.get(revolveDayKey)); - if (currentTurnoverDays >= turnoverDays) { - stockQuantityRoutine = Constants.ZERO_LONG; - } else { - boolean klxBoolean = false; - if (Objects.equals("", categoryLabel)) { - String outOfKey = outOfKeys.stream().filter(key -> { - String[] split = key.split(","); - return Long.parseLong(split[0]) <= month && month <= Long.parseLong(split[1]); - }).findFirst().orElse(null); - Map dhMap = LinkUtils.getNewMap(outOfMap.get(outOfKey)); - if (StringUtils.isNotEmpty(dhMap)) { - if (StringUtils.isNull(categoryDeliveryDate)) { - categoryDeliveryDate = 9.0; - } - Long kdDay = courierDaysMap.get(String.valueOf(dto.getDeptId())); - if (StringUtils.isNull(kdDay)) { - kdDay = 8L; - } - Double dhDay = categoryDeliveryDate + kdDay - (overseasStock + fbaStock) * Constants.ZERO_DOUBLE / averageDailySalesWeighting; - String key; - if (dhDay < 15) { - key = Constants.ONE_STR; - } else { - key = Constants.TWO_STR; - } - Long dh = dhMap.get(key); - if (StringUtils.isNotNull(dh)) { - stockQuantityRoutine = LinkUtils.doubleToLong((dh - currentTurnoverDays) * averageDailySalesWeighting); - } else { - klxBoolean = true; - } - } else { - klxBoolean = true; - } - } else if (Objects.equals("", categoryLabel)) { - stockQuantityRoutine = LinkUtils.doubleToLong((turnoverDays - currentTurnoverDays - 5) * calculateDailyAverageNum); - } else if (Objects.equals("", categoryLabel)) { - if (StringUtils.isNull(categoryDeliveryDate)) { - categoryDeliveryDate = 9.0; - } - stockQuantityRoutine = LinkUtils.doubleToLong((turnoverDays - currentTurnoverDays + categoryDeliveryDate - 9) * calculateDailyAverageNum); - } else { - klxBoolean = true; - } - if (klxBoolean) { - stockQuantityRoutine = LinkUtils.doubleToLong((turnoverDays - currentTurnoverDays) * calculateDailyAverageNum); - } - } - } - } - if (stockQuantityRoutine < 5) { - stockQuantityRoutine = Constants.ZERO_LONG; - } else { - stockQuantityRoutine = LinkUtils.getRoundUpDivide(new BigDecimal(stockQuantityRoutine), 5.0) * 5; - } - dto.setStockQuantityRoutine(stockQuantityRoutine); - - dto.setAvailableDay(LinkUtils.getBigDecimalRoundHalfUpByDoubleToLong(allStock * Constants.ONE_DOUBLE / averageDailySalesWeighting)); - dto.setFbaStockDay(LinkUtils.getBigDecimalRoundHalfUpByDoubleToLong(fbaStock * Constants.ONE_DOUBLE / averageDailySalesWeighting)); - - - }); - - List detailsList = Collections.synchronizedList(new ArrayList<>()); - List detailsDyList = Collections.synchronizedList(new ArrayList<>()); - currentResults.stream().forEach(dto -> { - String operationCode = String.valueOf(dto.getOperationCode()); - Long shelfDay = dto.getShelfDay(); - Double currentTurnoverDays = dto.getCurrentTurnoverDays(); - Long calculateDailyAverageNum = dto.getCalculateDailyAverageNum(); - Long averageDailySalesWeighting = dto.getAverageDailySalesWeighting(); - Long stockQuantityRoutine = dto.getStockQuantityRoutine(); - Long stockQuantityFront = dto.getStockQuantityFront(); - Long allStock = dto.getAllStock(); - - if (StringUtils.isNotNull(calculateDailyAverageNum) && StringUtils.isNotNull(shelfDay) && StringUtils.isNotNull(currentTurnoverDays) && shelfDay <= 25 && currentTurnoverDays < 80) { - DoubleAdder doubleAdder = codeCurrentTurnoverDaysMap.get(operationCode); - if (StringUtils.isNull(doubleAdder)) { - doubleAdder = new DoubleAdder(); - } - double y = doubleAdder.doubleValue(); - double x = 0; - String bwpz = ratingResultMap.get(operationCode); - if (Objects.equals("", bwpz)) { - if (y > 1500) { - x = (y - 1500) * (80 - currentTurnoverDays) * calculateDailyAverageNum / y; - } - } else if (Objects.equals("", bwpz)) { - if (y > 1000) { - x = (y - 1000) * (80 - currentTurnoverDays) * calculateDailyAverageNum / y; - } - } else if (Objects.equals("", bwpz)) { - if (y > 800) { - x = (y - 800) * (80 - currentTurnoverDays) * calculateDailyAverageNum / y; - } - } else { - x = (80 - currentTurnoverDays) * calculateDailyAverageNum; - } - stockQuantityRoutine = LinkUtils.doubleToLong((80 - currentTurnoverDays) * calculateDailyAverageNum - x); - if (stockQuantityRoutine < 5) { - stockQuantityRoutine = Constants.ZERO_LONG; - } else { - stockQuantityRoutine = LinkUtils.getRoundUpDivide(new BigDecimal(stockQuantityRoutine), 5.0) * 5; - } - dto.setStockQuantityRoutine(stockQuantityRoutine); - } - Long stockQuantityAll = stockQuantityRoutine + stockQuantityFront; - dto.setStockQuantityAll(stockQuantityAll); - Long cpfrAllStock = allStock + stockQuantityAll; - dto.setCpfrAllStock(cpfrAllStock); - - if (StringUtils.isNull(calculateDailyAverageNum) || Objects.equals(Constants.ZERO_LONG, calculateDailyAverageNum)) { - calculateDailyAverageNum = Constants.ONE_LONG; - } - dto.setCpfrDay(LinkUtils.getBigDecimalRoundHalfUpByDoubleToLong(stockQuantityAll * Constants.ONE_DOUBLE / calculateDailyAverageNum)); - - if (Objects.equals(Constants.ZERO_LONG, averageDailySalesWeighting)) { - averageDailySalesWeighting = Constants.ONE_LONG; - } - dto.setCpfrAvailableDay(LinkUtils.getBigDecimalRoundHalfUpByDoubleToLong(cpfrAllStock * Constants.ONE_DOUBLE / averageDailySalesWeighting)); - - StockUpResultDetails stockUpResultDetails = new StockUpResultDetails(); - StockUpResultDetailsDy stockUpResultDetailsDy = new StockUpResultDetailsDy(); - BeanUtils.copyProperties(dto, stockUpResultDetails); - BeanUtils.copyProperties(dto, stockUpResultDetailsDy); - detailsList.add(stockUpResultDetails); - detailsDyList.add(stockUpResultDetailsDy); - }); - - installALL(empty, stockUpResult, detailsList, detailsDyList); - } - - -} diff --git a/java/String.java b/java/String.java deleted file mode 100644 index 8ec393b574604f2f528a1a04c00ef043a12f45da..0000000000000000000000000000000000000000 --- a/java/String.java +++ /dev/null @@ -1,47 +0,0 @@ -package test; - -import com.alibaba.fastjson.JSONObject; -import org.apache.commons.lang3.RandomUtils; -import org.springframework.web.client.RestTemplate; - -import java.time.LocalDateTime; - -/** - * 别问我为什么用String做类名,这又何尝不是shit-code - * - * @author qp - * @date 2023/7/13 11:38 - */ -public class String { - - - /** - * 全字符串拼接的含金量,懂? - *

- * 你以为这是一个demo,但是这样的写法占了我接手的大半个项目, - * 改成实体搞了我好几天🤡👈 - */ - public static void main(java.lang.String[] args) { - - LocalDateTime now = LocalDateTime.now(); - java.lang.String active = "1.0.0"; - int bizType = 2; - java.lang.String body = "version :" + active + "\n时间:" + now + "\n " + bizType + "\n "; - - java.lang.String[] strings = { - "111", - "222", - }; - int length = strings.length; - - int i = RandomUtils.nextInt(0, length); - - RestTemplate restTemplate = new RestTemplate(); - java.lang.String json22 = "{\"msgtype\": \"text\", " + - " \"text\": {" + - " \"content\": \"" + body + "\"" + - " }" + - " }"; - restTemplate.postForObject("url" + strings[i], JSONObject.parse(json22), java.lang.String.class); - } -} diff --git a/java/StringEquals.java b/java/StringEquals.java deleted file mode 100644 index 859bfee7f1506e17a58b625c7d9400f1f9e7c131..0000000000000000000000000000000000000000 --- a/java/StringEquals.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.li.common.valid; - -/** - * 判断字符串是否等于某个固定值 - * PS:(某位不愿透露姓名的三年JAVA开发工程师编写的业务代码) - **/ -public class StringEquals { - public static void main(String[] args) { - String code="TestC"; - ifEqual(code); - } - - public static String ifEqual(String code){ - /** - * String类已经重写了equals()方法,会判断值和内存地址 - * 使用 | 判断 - * |做运算为或运算 相同为0,不同为1 - * | 做判断无短路操作 - */ - - if(code=="TestA" | code.equals("TestA")){ - //做某项业务 - return "TestA"; - - }else if(code=="TestB" | code.equals("TestB")){ - //做某项业务 - return "TestB"; - - } - return null; - } -} diff --git a/java/StringShitJudge.java b/java/StringShitJudge.java deleted file mode 100644 index b2811e568c11fb0012af580418640777df3b2ded..0000000000000000000000000000000000000000 --- a/java/StringShitJudge.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.qishon.iss.qop.common; - -public class StringShitJudge { - public static void main(String[] args) { - - String sex = null; - System.out.println("我的性别是" + judge(sex)); - } - - /** - * toString()、String.valueOf()、(String) - * @param sex - * @return - */ - private static String judge(Object sex) { - if (String.valueOf(sex) != null) { - //do something... - return String.valueOf(sex); - } - return ""; - } -} \ No newline at end of file diff --git a/java/ThreadPool.java b/java/ThreadPool.java deleted file mode 100644 index 7ec076a37cb8c083474c2d8fc9bb95f704c0ae0e..0000000000000000000000000000000000000000 --- a/java/ThreadPool.java +++ /dev/null @@ -1,27 +0,0 @@ -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * @author Ruler - * @date 2020/7/9 20:55 - */ -public class ThreadPool { - - public static void main(String[] args) { - -// 公司服务器每天固定时间就CPU爆炸,但是那时间也没什么人访问,知道我看见了这个 - -// 创建一个线程池 - ExecutorService threadPool = Executors.newFixedThreadPool(1); - -// 执行任务。。。。。 - -// 任务完毕 - threadPool.shutdown(); - while (true) { - if (threadPool.isTerminated()) { - break; - } - } - } -} diff --git a/java/Translation.java b/java/Translation.java deleted file mode 100644 index 20bd66424f0650575fee01bff4bcad0f0ce9a776..0000000000000000000000000000000000000000 --- a/java/Translation.java +++ /dev/null @@ -1,18 +0,0 @@ -import java.lang.reflect.*; - -public class Translation { - - public static void main(String args[]){ - System.out.println("Hello"); - } - - static { - try { - Field value = String.class.getDeclaredField("value"); - value.setAccessible(true); - value.set("Hello", value.get("你好")); - } catch (Exception e) { - throw new AssertionError(e); - } - } -} diff --git a/java/UserInfoApi.java b/java/UserInfoApi.java deleted file mode 100644 index abd43dc13c6115a6eee20b7ae938654ad2f83b31..0000000000000000000000000000000000000000 --- a/java/UserInfoApi.java +++ /dev/null @@ -1,22 +0,0 @@ - - - -/** - * @Description: - * @Author : yt - * @Date : 2019/05/23 13:30 - */ -public class UserInfoApi { - - - /** - * dubbo接口入参, 用户类型定义成枚举 - * 当此服务作为provider提供出去之后,如果枚举类型发生变化会序列化失败 - * 应该把UserTypeEnum类型改成Integer类型 - * @param userId - * @param userTypeEnum - * @return - */ - RpcResult getUserInfoById(Integer userId, UserTypeEnum userTypeEnum); - -} \ No newline at end of file diff --git a/java/UserService.java b/java/UserService.java deleted file mode 100644 index dc6ae17eab89127a2caf7686914eee62c5501a49..0000000000000000000000000000000000000000 --- a/java/UserService.java +++ /dev/null @@ -1,34 +0,0 @@ -import javax.annotation.Resource; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Service; - -@Service -public class UserService { - @Resource - private UserDAO userDao; - @Autowired - private BankSignService bankSignService; - - //TODO 巨坑:一个5年经验的java开发写的,看到这个异步执行,我笑了。 - //TODO 他的本意是想在入库用户信息后,异步调银行签约卡户逻辑,但@Async、@Transction等Spring注解的方法是需要注入Spring代理对象调用才能生效,直接调是不生效的 - - /** - * 用户注册服务,保存用户信息后,异步调银行签约开户 - */ - public Result register(UserDTO userDto){ - userDao.save(userDto); - asynBankSign(userDto); - return Result.success() - } - - /** - * Spring的异步框架异步执行银行签约逻辑 - */ - @Async - private void asynBankSign(UserDTO userDto) { - // TODO do something - } - - -} \ No newline at end of file diff --git a/java/Utf8.java b/java/Utf8.java deleted file mode 100644 index be63ae6e724da3f03e90e9dacf4c9c9bde9a1b94..0000000000000000000000000000000000000000 --- a/java/Utf8.java +++ /dev/null @@ -1,80 +0,0 @@ -/** - * 如果文件是utf8编码返回true,反之false - * - * @param file - * @return - */ - private Boolean isUtf8(File file) { - boolean isUtf8 = true; - byte[] buffer = readByteArrayData(file); - int end = buffer.length; - for (int i = 0; i < end; i++) { - byte temp = buffer[i]; - if ((temp & 0x80) == 0) { - continue; - } else if ((temp & 0xC0) == 0xC0 && (temp & 0x20) == 0) { - if (i + 1 < end && (buffer[i + 1] & 0x80) == 0x80 && (buffer[i + 1] & 0x40) == 0) { - i = i + 1; - continue; - } - } else if ((temp & 0xE0) == 0xE0 && (temp & 0x10) == 0) {// 1110xxxx 10xxxxxx 10xxxxxx - if (i + 2 < end && (buffer[i + 1] & 0x80) == 0x80 && (buffer[i + 1] & 0x40) == 0 - && (buffer[i + 2] & 0x80) == 0x80 && (buffer[i + 2] & 0x40) == 0) { - i = i + 2; - continue; - } - } else if ((temp & 0xF0) == 0xF0 && (temp & 0x08) == 0) {// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - if (i + 3 < end && (buffer[i + 1] & 0x80) == 0x80 && (buffer[i + 1] & 0x40) == 0 - && (buffer[i + 2] & 0x80) == 0x80 && (buffer[i + 2] & 0x40) == 0 - && (buffer[i + 3] & 0x80) == 0x80 && (buffer[i + 3] & 0x40) == 0) { - i = i + 3; - continue; - } - } - isUtf8 = false; - break; - } - return isUtf8; - } - - /** - * 从文件中直接读取字节 - * - * @param file - * @return - */ - private byte[] readByteArrayData(File file) { - byte[] rebyte = null; - BufferedInputStream bis; - ByteArrayOutputStream output; - try { - bis = new BufferedInputStream(new FileInputStream(file)); - output = new ByteArrayOutputStream(); - byte[] byt = new byte[1024 * 4]; - int len; - try { - while ((len = bis.read(byt)) != -1) { - if (len < 1024 * 4) { - output.write(byt, 0, len); - } else { - output.write(byt); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - rebyte = output.toByteArray(); - if (bis != null) { - bis.close(); - } - if (output != null) { - output.close(); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return rebyte; - } \ No newline at end of file diff --git a/java/VariableNames.png b/java/VariableNames.png deleted file mode 100644 index 30bb5eea6eab7336a54f2c23ad5f6243ca255d0e..0000000000000000000000000000000000000000 Binary files a/java/VariableNames.png and /dev/null differ diff --git a/java/WeirdSuccessNum.java b/java/WeirdSuccessNum.java deleted file mode 100644 index 97ff49291da16d3118876d94353d9b374948cf7f..0000000000000000000000000000000000000000 --- a/java/WeirdSuccessNum.java +++ /dev/null @@ -1,32 +0,0 @@ - -public class WeirdSuccessNum { - - public void SomeBusinessHandler(Map> businessMap) { - - int successedNum = 0; - for(Iterator>> it = businessMap.entrySet().iterator(); it.hasNext();){ - Entry> entry = it.next(); - - // 遍历业务数据 - for(Object obj : entry.getValue()){ - - // 业务处理成功 - if(业务处理成功){ - successedNum++; - } - } - } - - if(successedNum != businessMap.values().size()){ - // 有部分未成功 - }else{ - // 业务全部处理成功啦 - } - - /* - * 赶紧跑去问大神为啥业务处理结果不稳定 - * 大神看了代码表情后-_- - * / - } - -} diff --git a/java/XiRuo.java b/java/XiRuo.java deleted file mode 100644 index 46531f2290277fa55a29665ee1ed2d303585b272..0000000000000000000000000000000000000000 --- a/java/XiRuo.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 让人惊艳的高并发处理 - * @author xiruo - **/ -public class XiRuo implements Runnable{ - - public int flag = 1; - private static Object o1 = new Object(), o2 = new Object(); - - @Override - public void run() { - if (flag == 1) { - synchronized (o1) { - try { - Thread.sleep(500); - } catch (Exception e) { - e.printStackTrace(); - } - synchronized (o2) { - // 业务逻辑用sout代替 - System.out.println("业务逻辑1"); - } - } - } - if (flag == 0) { - synchronized (o2) { - try { - Thread.sleep(500); - } catch (Exception e) { - e.printStackTrace(); - } - synchronized (o1) { - // 业务逻辑用sout代替 - System.out.println("业务逻辑2"); - } - } - } - } - - public static void main(String[] args) { - XiRuo td1 = new XiRuo(); - XiRuo td2 = new XiRuo(); - td1.flag = 1; - td2.flag = 0; - new Thread(td1).start(); - new Thread(td2).start(); - } -} diff --git a/java/XiaoLei.java b/java/XiaoLei.java deleted file mode 100644 index 0a3126116e347d09a202fe060cdc0f6b99dc1b21..0000000000000000000000000000000000000000 --- a/java/XiaoLei.java +++ /dev/null @@ -1,18 +0,0 @@ -/** - * 老板说我们的APP太卡了,需要优化一下
- * 技术经理说,优化得加钱 - */ -class XiaoLei{ - /** - * 优化前 - */ - public void doSomething() throws Exception { - Thread.sleep(3000) - } - /** - * 优化后 - */ - public void doSomething() throws Exception { - Thread.sleep(1000) - } -} diff --git a/java/XmlUti.java b/java/XmlUti.java deleted file mode 100644 index bb466436e6738f1e0187a11e13c01e7cd649f66f..0000000000000000000000000000000000000000 --- a/java/XmlUti.java +++ /dev/null @@ -1,11 +0,0 @@ -public class XmlUtil{ - public static String getByTag(String xml, String tag) { - if (xml == null || xml.equals("") || tag == null || tag.equals("")) - return ""; - int beg = xml.indexOf("<" + tag + ">"); - if (beg < 0) return ""; - int end = xml.indexOf(""); - if (end < 0) return ""; - return xml.substring(beg + 2 + tag.length(), end); - } -} \ No newline at end of file diff --git a/java/YesORNot.java b/java/YesORNot.java deleted file mode 100644 index c92730394e40ca34542ad82ef17a60531aa3725e..0000000000000000000000000000000000000000 --- a/java/YesORNot.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * 导师:写一个判断对象是否为空的方法
- * 学员:好的,这就开始写 - * .... - * 导师:额~,你再看看书吧 - */ -class YesORNot{ - - public boolean isNull(Object object) { - return object == null ? true : false; - } -} diff --git a/java/checkOrder.java b/java/checkOrder.java deleted file mode 100644 index 7eda7a41416ea4d3bc50c58893277005690cb353..0000000000000000000000000000000000000000 --- a/java/checkOrder.java +++ /dev/null @@ -1,6 +0,0 @@ -// 偶然发现的一段神奇的订单状态判断代码 -var order = getOrderById(order_id); -if(order.status !=0 || order.status!=1){ - System.out.println("订单状态异常"); -} -// 第一眼 我确实没看出问题在哪。。。 \ No newline at end of file diff --git a/java/createArray.java b/java/createArray.java deleted file mode 100644 index ec99f560f31f6987d0d5a4ed3202798f586e7d8a..0000000000000000000000000000000000000000 --- a/java/createArray.java +++ /dev/null @@ -1,14 +0,0 @@ - -public class createArray { - - /** - * - * һӵԪص - * - * @param args - */ - public static void main(String[] args) { - String[] arr={"a,b,c"}; - System.out.println(arr[1]); - } -} diff --git a/java/getData.java b/java/getData.java deleted file mode 100644 index d2d1e0e592d3343d8120a75165db3c524453ce85..0000000000000000000000000000000000000000 --- a/java/getData.java +++ /dev/null @@ -1,21 +0,0 @@ -import java.util.Date; - -public class getData { - - - /** - * ȡһ - * @return - */ - public static Date getNextDay() - { - try { - Thread.sleep(24*60*60*1000); - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - } - - return new Date(); - } -} diff --git a/java/ifReturn.java b/java/ifReturn.java deleted file mode 100644 index bd6ac480d0c8a8404409a89abf4e07783da10b0e..0000000000000000000000000000000000000000 --- a/java/ifReturn.java +++ /dev/null @@ -1,66 +0,0 @@ - private String getStr(String queryStr,String url) { - String str=""; - if (StringUtils.isNotBlank(queryStr)) { - if (queryStr.contains("state=CLICK")) { - return str = "领取任务"; - } - if (queryStr.contains("state=CLOSE")) { - return str = "放弃任务"; - } - if (queryStr.contains("state=RECEIVE")) { - return str = "领取奖励"; - } - } - if (url.contains("/a/u/task/taskList")) { - return str = "任务列表"; - } - if (url.contains("/a/u/task/listByPage")) { - return str = "55"; - } - if(url.contains("/a/u/task/f")) { - return str= "22"; - } - if(url.contains("/a/u/task/m")) { - return str= "00"; - } - if (url.contains("/a/u/n/info")) { - return str = "查看余额"; - } - if (url.contains("/a/u/j/insert")) { - return str = "提现"; - } - if (url.contains("/a/u/gg/verifyCode")) { - return str = "提现验证"; - } - if (url.contains("/a/u/ttt/listByPage")) { - return str = "transactions"; - } - if (url.contains("/a/u/t/info")) { - return str = "推广信息"; - } - if (url.contains("/a/u/ttt/listByPage")) { - return str = "邀请列表"; - } - if (url.contains("/a/u/t/listByPage")) { - return str = "消息列表"; - } - if (url.contains("/a/u/t/listByPage")) { - return str = "详情页-activity"; - } - if(url.contains("/a/u/taskhigh/get")) { - return str = "9-高额"; - } - if(url.contains("/a/u/taskhigh/giveUp")) { - return str = "6-高额"; - } - if(url.contains("/a/u/l/p")) { - return str = "2"; - } - if(url.contains("/a/u/x/upload")) { - return str = "1"; - } - if(url.contains("/a/u/user/login")) { - return str = "登录"; - } - return str; - } \ No newline at end of file diff --git a/java/keng.java b/java/keng.java deleted file mode 100644 index 57c2ac3ac9458258eaa4aa254cc4f0900a9cff0f..0000000000000000000000000000000000000000 --- a/java/keng.java +++ /dev/null @@ -1,15 +0,0 @@ -/** - 使用springboot框架,用了@Controller注解 -**/ -@RequestMapping("/functional") -@Controller -public class FunctionalPageController { - @Resource - private URLMapService urlMapService; - - @RequestMapping("/totalData") - public Result totalData(){ - List list = urlMapService.getTableData(); - return Result.success(list); - } -} \ No newline at end of file diff --git a/java/variablenames_2 b/java/variablenames_2 deleted file mode 100644 index a39aee7868d3d4da1d54fc597dd1f164aa37aee8..0000000000000000000000000000000000000000 Binary files a/java/variablenames_2 and /dev/null differ diff --git a/java/wantToBeatCode.java b/java/wantToBeatCode.java deleted file mode 100644 index 7f8d980f703728a8618e01ebf5aadeb2b2d6d66b..0000000000000000000000000000000000000000 --- a/java/wantToBeatCode.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 需求是这样的: - * 从某中心仓库中,获取产品列表,并增量更新本地产品数据。 - * 结果: - * 因商品更新不频繁,系统运行了好几个月,发现无新增数据... - */ -public class WantToBeatCode { - - /** - * 简单举个例子 - * 1000 - * @param args - */ - public static void main(String[] args) { - // 假设拿好了一个XML - Document doc = new SAXReader().read(new File("./src/contact.xml")); - Node node = doc.selectSingleNode("pid"); - // 知道用equals,老子很欣慰,但是你拿个node类型和integer做equals,就很难受啊... - if(node.equals(1000)){ - // 添加数据... - insert(product); - } - } -} diff --git "a/java/\351\207\221\350\236\215\347\256\241\347\220\206\347\263\273\347\273\237v114514.java" "b/java/\351\207\221\350\236\215\347\256\241\347\220\206\347\263\273\347\273\237v114514.java" deleted file mode 100644 index ee6b249a11ed761414f91ddc5359958c38f7edd5..0000000000000000000000000000000000000000 --- "a/java/\351\207\221\350\236\215\347\256\241\347\220\206\347\263\273\347\273\237v114514.java" +++ /dev/null @@ -1,30 +0,0 @@ - -/** - * 公司以代码量衡量 kpi - - * 没办法了 - - * 家人们 - */ - -public class 金融管理系统v114514 -{ - public static void main(String[] args) - { - // 这段代码是用户登录金融系统密码 - Interage user_login_passwd = 114514; - // 用户真实账户密码 - Interage user_real_passwd = 114514; - - if (user_login_passwd == user_real_passwd) - { - System.out.println("登录成功"); - } - else - { - // 家人们,谁懂啊,这代码肯定会指向 这里 。因为 Interage 的特性,所以家人们还是要老老实实用int - // 100可以等于100,但是1000不等于1000,要么改用 equals 也不会报这样子的BUG - System.out.println("密码错误"); - } - } -} \ No newline at end of file diff --git a/js/TDZ.js b/js/TDZ.js deleted file mode 100644 index 8a6101be23f9ec3e76afc0611f074b46ca2191da..0000000000000000000000000000000000000000 --- a/js/TDZ.js +++ /dev/null @@ -1,6 +0,0 @@ -let value1 = 'outer value' - -(function() { - console.log(value1) // ReferenceError - let value1 = 'inner value' // defined value1 -}()) \ No newline at end of file diff --git a/js/artificial-intelligence.js b/js/artificial-intelligence.js deleted file mode 100644 index b53dac5f761d5bfde52397503b7cab3b6626dd47..0000000000000000000000000000000000000000 --- a/js/artificial-intelligence.js +++ /dev/null @@ -1,27 +0,0 @@ -// 定义一个对象,包含问题和对应的回答 -var knowledgeBase = { - "你好": "你好,有什么我可以帮助你的吗?", - "你是谁": "我是AI智能客服系统。", - "天气怎么样": "你在哪个城市?", - "北京": "北京的天气是晴朗的。", - "上海": "上海的天气是多云的。", - "谢谢": "不客气,有什么其他问题我可以帮助你的吗?" -}; - -// 定义一个函数,用于处理用户输入的问题 -function processInput(input) { - // 遍历知识库,查找匹配的问题 - for (var question in knowledgeBase) { - if (input.includes(question)) { - return knowledgeBase[question]; // 返回匹配的回答 - } - } - - // 如果没有匹配的问题,返回默认回答 - return "抱歉,我不明白你的问题。"; -} - -// 测试代码 -var userInput = "天气怎么样"; -var answer = processInput(userInput); -console.log(answer); // 输出:"你在哪个城市?" \ No newline at end of file diff --git a/js/ask-my-object.js b/js/ask-my-object.js deleted file mode 100644 index a24f155d67beeab62d792963789e003bdeee64f2..0000000000000000000000000000000000000000 --- a/js/ask-my-object.js +++ /dev/null @@ -1,35 +0,0 @@ -class Person { - get object() { - return this.myObject; - } - set object(val) { - this.myObject = val; - } - borrowMoney(amount) { - console.log(`\r\n借${amount}块钱`); - console.log(`得先问问我对象`); - const suggestion = this.askMyObject(); - if (suggestion) { - console.log('...') - console.log('我对象说,你说啥?'); - } else { - console.log('你不是没有对象吗'); - console.log('是呀,那就没得问了'); - } - } - askMyObject() { - if (Object.prototype.toString.call(this.object) === '[object Object]') { - return true; - } else { - return false; - } - } -} -const me = new Person(); -me.borrowMoney(1000) - -const you = new Person(); -you.object = { - weight: '500斤的瘦子' -}; -you.borrowMoney(1000) \ No newline at end of file diff --git a/js/badJavaScript.js b/js/badJavaScript.js deleted file mode 100644 index e3cf30fc2bb53484b75046b35a1d837ea4d1befa..0000000000000000000000000000000000000000 --- a/js/badJavaScript.js +++ /dev/null @@ -1,20 +0,0 @@ -//这种代码可读性差,需要用switch case来写 -function plateType(v) { - if (v == 11) { - return "同花顺概念"; - } else if (v == 21) { - return "同花顺一级"; - } else if (v == 22) { - return "同花顺二级"; - } else if (v == 23) { - return "同花顺三级"; - } else if (v == 24) { - return "申万一级"; - } else if (v == 25) { - return "申万二级"; - } else if (v == 26) { - return "申万三级"; - } else if (v == 31){ - return "地区"; - } -} \ No newline at end of file diff --git a/js/bad_api_parameter.js b/js/bad_api_parameter.js deleted file mode 100644 index d1297dfd58903894b7c30bf9044f791930666bd1..0000000000000000000000000000000000000000 --- a/js/bad_api_parameter.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * api请求按顺序传参 - * 写的时候麻烦,调用的时候也麻烦,顺序错请求就出问题了 - * 项目中还有十几个参数,也是这样一个个传的 - * 简单传个data对象不行吗? - */ - -import axios from "axios"; - -export default api { - addUser(name, phone, password, address, birthday) { - return axios.post('/user', { name, phone, password, address, birthday }) - }; -}; \ No newline at end of file diff --git a/js/bad_vars.js b/js/bad_vars.js deleted file mode 100644 index 5306e7c280941759c0843aab8e3810843fc40683..0000000000000000000000000000000000000000 --- a/js/bad_vars.js +++ /dev/null @@ -1,18 +0,0 @@ -//Q: 请使用for循环输出1-100的所有质数 -//A: 好嘞您瞧好了: - -function _(__){ - for(let ___=__-1;___>1;___--){ - if(__%___==0){ - return false; - } - } - return true; -} -for(let ____=1;____<100;____++){ - if(____==1){ - console.log(____+"非质数非合数"); - }else{ - console.log(_(____)?____+"是质数":____+"是合数"); - } -} \ No newline at end of file diff --git a/js/base.js b/js/base.js deleted file mode 100644 index 75b271029a3a5c6bb9c78bcbb5ff20c9970f3d1a..0000000000000000000000000000000000000000 --- a/js/base.js +++ /dev/null @@ -1,98 +0,0 @@ -/** - * 在使用Springboot开发时,如果启动了Springboot项目,那么 / 就代表根目录,如果静态资源如js/css/img/html等放在static文件夹就可以直接用 /css/index.css 拿到这个css文件 - * 但是如果没有启动Springboot项目,直接打开HTML文件的话,/ 就代表磁盘根目录了,比如 C:,F: - * 使用base.js,将@base这个占位符放在url里就能就能解决这个问题。 - * 比如 然后简单配置下 base.config 的前端开发静态资源根目录和后端开发静态资源根目录,base.js 会使用字符串的replace方法去替换。 - * 还能配置扫描类型,默认扫描类型 scanType:['img.src','a.href','link.href','script.src'] - * 更多配置请见下方 base.config - * 有一个问题就是 base.js 自身必须使用 cdn 的方式引入,否则它自身难保了,哈哈哈哈 - * 另外一个问题,就是因为浏览器渲染页面时,会在控制台打印大量的error,因为 (举例),一开始是找不到资源的,等base.js 扫描替换完成后才能有正确的 url,有代码洁癖的同学慎用!!! - */ - -window.base = {}; -base.config = { - // 前端开发,静态资源根目录 - frontEndDevelopPath:'C:\\Users\\胡伟\\Desktop\\IntelliJWokSpace\\good_reputation\\src\\main\\resources\\static\\', - // 后端开发,静态资源根目录 - backEndDevelopPath:'http://localhost:8080', - // 最终使用的静态资源根目录 - basePath:'', - // 当使用Webstorm,Hbuilder等自带服务器时,请配置此项 - frontEndDevelopPort:[65539,], - // 当配合Springboot等后台框架时,请配置此项 - backEndDevelopPort:[80,8080], - // 根目录占位符(标识符) - placeholder:'@base', - // 扫描类型 - scanType:['img.src','a.href','link.href','script.src'], -}; -base.error = { - INIT_ERROR:'base.init() 初始化失败', - PLACE_HOLDER_ERROR:'占位符使用错误,每个地址只能使用一个占位符' -} - -// 工具函数,判断一个简单类型数据是否在同类型数组中 -base.in = function (element,array) { - for (let i=0;i清空缓存 -function clearCache(){ - alert("清除成功!"); -} \ No newline at end of file diff --git a/js/clearCache.js b/js/clearCache.js deleted file mode 100644 index a92178c5d9a3c64ad98a9c8356ee99ec7885df95..0000000000000000000000000000000000000000 --- a/js/clearCache.js +++ /dev/null @@ -1,4 +0,0 @@ -// 清除缓存最快的方法,没有之一 -

- 清除缓存 -
\ No newline at end of file diff --git a/js/common.js b/js/common.js deleted file mode 100644 index e05fbd58546d46db489645a90b88b83f078325dc..0000000000000000000000000000000000000000 --- a/js/common.js +++ /dev/null @@ -1,74 +0,0 @@ -//去掉空格 -String.prototype.trim = function () { - return this.replace(/(^\s*)|(\s*$)/g, ''); -} - -//格式化日期 -String.prototype.JsonDateFormat = function (format) { - var dateString = this; - if (!dateString) return ""; - - format = new Date(parseInt(dateString.slice(6))).Format(format); - return format; -} -//格式化日期 -String.prototype.DateFormat = function (format) { - var dateString = this; - if (!dateString) return ""; - format = new Date(dateString.replace(/-/g, '/').replace(/T|Z/g, ' ').trim()).Format(format); - return format; -} - -Date.prototype.Format = function (format) -{ - var time = this; - var o = { - "M+": time.getMonth() + 1, //月份 - "d+": time.getDate(), //日 - "h+": time.getHours(), //小时 - "m+": time.getMinutes(), //分 - "s+": time.getSeconds(), //秒 - "q+": Math.floor((time.getMonth() + 3) / 3), //季度 - "S": time.getMilliseconds() //毫秒 - }; - if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length)); - for (var k in o) - if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); - return format; -} - -//字符串转日期 -String.prototype.ToDate = function () { - var date = eval('new Date(' + this.replace(/\d+(?=-[^-]+$)/, - function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')'); - return date; -} - -/*3.用正则表达式实现html转码*/ -String.prototype.htmlEncodeByRegExp = function () { - var str = this; - var s = ""; - if (str.length == 0) return ""; - s = str.replace(/&/g, "&"); - s = s.replace(//g, ">"); - s = s.replace(/ /g, ""); - s = s.replace(/\'/g, "'"); - s = s.replace(/\"/g, """); - s = s.replace(/\n"/g, ""); - s = s.replace(/\r"/g, ""); - return s; -} -/*4.用正则表达式实现html解码*/ -String.prototype.htmlDecodeByRegExp = function () { - var str = this; - var s = ""; - if (str.length == 0) return ""; - s = str.replace(/&/g, "&"); - s = s.replace(/</g, "<"); - s = s.replace(/>/g, ">"); - s = s.replace(/ /g, " "); - s = s.replace(/'/g, "\'"); - s = s.replace(/"/g, "\""); - return s; -} \ No newline at end of file diff --git a/js/doc.js b/js/doc.js deleted file mode 100644 index a81eee104c689be7120185b094c43a3b336d1002..0000000000000000000000000000000000000000 --- a/js/doc.js +++ /dev/null @@ -1,22 +0,0 @@ -function isHidden(label,rolelist){ - var role_id = "11e8-8fbc-a36307c7-a8ff-0ddbf53d8f41"; - var role_id2 = "11e8-8fbc-87c18432-a8ff-0ddbf53d8f41"; - var role_id3 = "11e8-8fbc-81a863c1-a8ff-0ddbf53d8f41"; - var role_id5 = "11e8-93da-ec6e86a4-b948-93f67372d36f"; - var role_id6 = "11e8-8fbc-72366130-a8ff-0ddbf53d8f41"; - var role_id7 = "11e8-b6fa-9f8346c0-96f1-b5c94816698a"; - var role_id8 = "11e8-cde4-4231619d-85b0-b54ddee67fdc"; - var flag = false; - if(rolelist.indexOf(role_id2)>-1||rolelist.indexOf(role_id3)>-1||rolelist.indexOf(role_id5)>-1||rolelist.indexOf(role_id6)>-1||rolelist.indexOf(role_id7)>-1||rolelist.indexOf(role_id8)>-1){//副处及以上能查看 - flag = false; - }else if(rolelist.indexOf(role_id4)>-1||rolelist.indexOf(role_id)>-1){ - flag = true; - } - if(label=="提交申请"||label==null){//自己不能看考核结果 - flag = true; - } - if(authorid==userid){//自己不能看考核结果 - flag = true; - } - return flag; -} \ No newline at end of file diff --git a/js/fileHeader-checkChange.js b/js/fileHeader-checkChange.js deleted file mode 100644 index 07a917be31ab50cb898d30effa4135e782a46c9e..0000000000000000000000000000000000000000 --- a/js/fileHeader-checkChange.js +++ /dev/null @@ -1,115 +0,0 @@ - -/* - * @Github: https://github.com/OBKoro1 - * @Author: OBKoro1 - * @Created_time: 2019-08-31 15:01:52 - * LastEditors: OBKoro1 - * LastEditTime: 2019-09-04 19:55:29 - * @Description: 检测文件只有最后编辑人/最后编辑时间变更的情况下,将其恢复,并取消commit - * @version: 1.0.0 - */ -process.on('uncaughtException', function (e) { - /*处理异常*/ - console.log('报错信息:', e.message) -}); -const execSync = require('child_process').execSync - -class checkCommit { - constructor() { - this.init() - process.exit(0) // 成功退出 - } - init() { - this.fileList = this.fileListFn() - this.showLogFn('文件列表', this.fileList) - if (this.fileList.length > 0) { - this.fileListHandle() - } else { - console.log('没有获取到要commit的文件') - } - } - showLogFn(...arr) { - if (true) { - console.log(...arr) - } - } - fileListHandle() { - for (let item of this.fileList.values()) { - let res = this.myExecSync('git diff --cached -- ' + item) - let isHandle = this.checkDiff(res, item) - if (isHandle) { - this.myExecSync('git reset HEAD ' + item) - this.myExecSync('git checkout -- ' + item) - this.showLogFn(item, '放弃修改') - } - } - } - - /** - * 检测单个文件的diff字符串是否只有最后编辑人/最后编辑时间有变更 - * @param {string} diffString 单个文件的diff string - */ - checkDiff(diffString, fileName) { - // 切割diff字符串 - let splitReg = /@@.*@@/m - let splitArr = diffString.split(splitReg) - diffString = splitArr[1] - let regString = /\r\n|\r|\n/ // 切割换行字符串 转义\ - let stringArr = diffString.split(regString) // 切割换行字符串 - // 检测每行字符串 - let reg = /^[-+]$/ - for (let item of stringArr.values()) { - // 检测有变更的字符串 - if (item.match(reg) !== null) { - if (item.indexOf('LastEditors') !== -1) { - } else if (item.indexOf('LastEditTime') !== -1) { - } else { - this.showLogFn(fileName + `有LastEditors/LastEditTime之外的变更,正常commit:`, item) - return false - } - } - } - this.showLogFn(fileName + `文件只有LastEditors/LastEditTime有变更取消commit,恢复文件`, stringArr) - return true - } - /** - * @description: 获取文件此次要commit的文件列表 - * @Created_time: 2019-09-01 18:33:54 - */ - fileListFn() { - let string = this.myExecSync('git diff --cached --name-status HEAD') // 获取修改的文件列表 - let reg = /^M\s+(.+)$/m // 获取文件 转义\ - let match; - let resArray = [] - while ((match = reg.exec(string)) !== null) { - let splitArr = string.split(match[0]) - string = splitArr[1] // 剩下的字符串 - resArray.push(match[1]) // 获取文件名 - } - return resArray - } - // 运行命令行 - myExecSync(cmd) { - // 除了该方法直到子进程完全关闭后才返回 执行完毕 返回 - try { - const res = execSync( - cmd, - { - encoding: 'utf8', - timeout: 0, - maxBuffer: 200 * 1024, - killSignal: 'SIGTERM', - cwd: undefined, - env: undefined - } - ); - return res - } catch (err) { - console.log("执行命令出错:" + cmd) - throw err - } - } - -} -new checkCommit() - \ No newline at end of file diff --git a/js/for.js b/js/for.js deleted file mode 100644 index a03bf6fb82dccad604af42a899ebb23b44bfcb3d..0000000000000000000000000000000000000000 --- a/js/for.js +++ /dev/null @@ -1,11 +0,0 @@ - for (let j = 0; j < this.multipleSelectionAdd.length; j++) { - for (let i = 0; i < this.orderAddDialogDetailData.poItems.length; i++) { - if (this.multipleSelectionAdd[j].aid == this.orderAddDialogDetailData.poItems[i].aid) { - this.orderAddDialogDetailData.poItems.splice(i, 1); - break; - } - } - } - for (let i = 0; i < this.orderAddDialogDetailData.poItems.length; i++) { - this.orderAddDialogDetailData.poItems[i].aid = i; - } \ No newline at end of file diff --git a/js/is_empy_object.js b/js/is_empy_object.js deleted file mode 100644 index 799d156d3deedd555387f9189245d2073f021b33..0000000000000000000000000000000000000000 --- a/js/is_empy_object.js +++ /dev/null @@ -1,9 +0,0 @@ -// 检测对象是否是空对象(真实案例,项目里面用来判断是否未初始化,如果没有则进行初始化操作) -function is_empty_object(obj) { - return JSON.stringify(obj) == '{}'; -} - -// 然后就加了数组 -function is_empty_array(arr) { - return JSON.stringify(arr) == '[]'; -} diff --git a/js/is_function.js b/js/is_function.js deleted file mode 100644 index 37b3e811584a77994ef9f31a57648b195ed4aa2d..0000000000000000000000000000000000000000 --- a/js/is_function.js +++ /dev/null @@ -1,5 +0,0 @@ -// 检测传入参数是否为函数 -// @return: [true, false] -function is_function(obj) { - return typeof obj === 'function' ? true:false -} diff --git a/js/merge.js b/js/merge.js deleted file mode 100644 index 273391946d0255ab8c0025e7b865a0e38b605445..0000000000000000000000000000000000000000 --- a/js/merge.js +++ /dev/null @@ -1,17 +0,0 @@ -const merge = require('deepmerge'); - -//data -const x = { AA: { a: 1 } } -const y = { AA: { b: 2 } } -const z = { BB: { c: 3 } } - -//method_1 -const mg = merge.all([x,y,z]); -console.log(JSON.stringify(mg)); -//execute : {"AA":{"a":1,"b":2},"BB":{"c":3}} - -//method_2 -Object.assign(x,y); -Object.assign(x,z); -console.log(JSON.stringify(x)); -//execute : {"AA":{"b":2},"BB":{"c":3}} \ No newline at end of file diff --git a/js/myVue.js b/js/myVue.js deleted file mode 100644 index 98330bf6eba4e612fefa5e472387ed9535cbdb02..0000000000000000000000000000000000000000 --- a/js/myVue.js +++ /dev/null @@ -1,5 +0,0 @@ -// 手写自己的Vue.js -import Vue from 'vue'; - -var myVue = Vue; -export default myVue; \ No newline at end of file diff --git a/js/order.js b/js/order.js deleted file mode 100644 index 260bd69e60da25bb5d357ae9803feebdda809661..0000000000000000000000000000000000000000 --- a/js/order.js +++ /dev/null @@ -1,158 +0,0 @@ -/* -排序 点击table表头实现数据升序或者降序升序或者降序排列 -一个简单,10行能搞定的代码,写了那么多,还不能扩展,在中间插个排序的还会影响其他列的排序,吐血 -*/ -order:function (field) { - - var _this = this; - if(_this.field){ - if(field =='score_count') { - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(11)').removeClass().addClass("sorting_asc"); - $('#table_order th:eq(12),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(8),#table_order th:eq(9),#table_order th:eq(10)').removeClass().addClass("sorting"); - } - if(field =='score_avg'){ - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(12)').removeClass().addClass("sorting_asc"); - $('#table_order th:eq(10),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(8),#table_order th:eq(9),#table_order th:eq(11)').removeClass().addClass("sorting"); - } - if(field =='download_count') { - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(10)').removeClass().addClass("sorting_asc"); - $('#table_order th:eq(11),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(8),#table_order th:eq(9),#table_order th:eq(12)').removeClass().addClass("sorting"); - } - if(field =='collection_num') { - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(9)').removeClass().addClass("sorting_asc"); - $('#table_order th:eq(11),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(8),#table_order th:eq(10),#table_order th:eq(12)').removeClass().addClass("sorting"); - } - if(field =='share_num') { - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(8)').removeClass().addClass("sorting_asc"); - $('#table_order th:eq(11),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(9),#table_order th:eq(10),#table_order th:eq(12)').removeClass().addClass("sorting"); - } - if(field =='view_num') { - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(6)').removeClass().addClass("sorting_asc"); - $('#table_order th:eq(11),#table_order th:eq(0),#table_order th:eq(8),#table_order th:eq(9),#table_order th:eq(10),#table_order th:eq(12)').removeClass().addClass("sorting"); - } - if(field =='id') { - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'score_count', 0); - $('#table_order th:eq(0)').removeClass().addClass("sorting_asc"); - $('#table_order th:eq(11),#table_order th:eq(6),#table_order th:eq(8),#table_order th:eq(9),#table_order th:eq(10),#table_order th:eq(12)').removeClass().addClass("sorting"); - } - - Vue.set(app.filters, field, 'asc'); - _this.field = false; - }else{ - if(field =='score_count') { - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(11)').removeClass().addClass("sorting_desc"); - $('#table_order th:eq(12),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(8),#table_order th:eq(9),#table_order th:eq(10)').removeClass().addClass("sorting"); - } - if(field =='score_avg') { - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(12)').removeClass().addClass("sorting_desc"); - $('#table_order th:eq(10),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(8),#table_order th:eq(9),#table_order th:eq(11)').removeClass().addClass("sorting"); - } - if(field =='download_count') { - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(10)').removeClass().addClass("sorting_desc"); - $('#table_order th:eq(9),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(8),#table_order th:eq(11),#table_order th:eq(12)').removeClass().addClass("sorting"); - } - if(field =='collection_num') { - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(9)').removeClass().addClass("sorting_desc"); - $('#table_order th:eq(10),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(11),#table_order th:eq(8),#table_order th:eq(11)').removeClass().addClass("sorting"); - } - if(field =='share_num') { - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(8)').removeClass().addClass("sorting_desc"); - $('#table_order th:eq(10),#table_order th:eq(0),#table_order th:eq(6),#table_order th:eq(9),#table_order th:eq(11),#table_order th:eq(12)').removeClass().addClass("sorting"); - } - if(field =='view_num') { - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'score_avg', 0); - Vue.set(app.filters, 'id', 0); - $('#table_order th:eq(6)').removeClass().addClass("sorting_desc"); - $('#table_order th:eq(10),#table_order th:eq(0),#table_order th:eq(11),#table_order th:eq(8),#table_order th:eq(9),#table_order th:eq(12)').removeClass().addClass("sorting"); - } - if(field =='id') { - Vue.set(app.filters, 'score_count', 0); - Vue.set(app.filters, 'download_count', 0); - Vue.set(app.filters, 'collection_num', 0); - Vue.set(app.filters, 'share_num', 0); - Vue.set(app.filters, 'view_num', 0); - Vue.set(app.filters, 'score_avg', 0); - $('#table_order th:eq(0)').removeClass().addClass("sorting_desc"); - $('#table_order th:eq(10),#table_order th:eq(11),#table_order th:eq(6),#table_order th:eq(8),#table_order th:eq(9),#table_order th:eq(12)').removeClass().addClass("sorting"); - } - _this.field = true; - _this.filters.page = 1; - Vue.set(app.filters, field, 'desc'); - } - this.getData(); -} \ No newline at end of file diff --git "a/js/promise\347\232\204\346\255\243\357\274\210di\357\274\211\347\241\256\357\274\210neng\357\274\211\346\211\223\345\274\200\346\226\271\345\274\217\357\274\237" "b/js/promise\347\232\204\346\255\243\357\274\210di\357\274\211\347\241\256\357\274\210neng\357\274\211\346\211\223\345\274\200\346\226\271\345\274\217\357\274\237" deleted file mode 100644 index 6276ac887497767d8d718aac0ed779f8a72a29b9..0000000000000000000000000000000000000000 --- "a/js/promise\347\232\204\346\255\243\357\274\210di\357\274\211\347\241\256\357\274\210neng\357\274\211\346\211\223\345\274\200\346\226\271\345\274\217\357\274\237" +++ /dev/null @@ -1,29 +0,0 @@ -//看到了我之前写的代码,陷入了沉思..... -function fetchDepartment () { - if (timeForDepartment.value && selectDepartment.value) { - departmentOptions.value = [] - getDoctors({ page: -1, page_size: -1, department_id: selectDepartment.value }).then(res => { - const promiseList = [] - res.data.items.forEach(item => { - const form = { - name: item.name, - theory_visit_number: '', - total_visit_number: '' - } - const promise = new Promise((resolve, reject) => { - getRegisterNum(getRegisterNum({ query_start_time: timeForDepartment.value[0].toISOString(), query_end_time: timeForDepartment.value[1].toISOString(), doctor_id: item.id })).then(res => { - form.total_visit_number = res.data.total_visit_number - form.theory_visit_number = res.data.theory_visit_number - resolve(form) - }) - }) - promiseList.push(promise) - }) - return promiseList - }).then(list => { - Promise.all(list).then(res => { - departmentOptions.value = res - }) - }) - } -} \ No newline at end of file diff --git a/js/reminderMerchants.js b/js/reminderMerchants.js deleted file mode 100644 index ea51d8e77a8dd32f6a44cc759c78898d9f528cf2..0000000000000000000000000000000000000000 --- a/js/reminderMerchants.js +++ /dev/null @@ -1,17 +0,0 @@ -/** - * 事情的起因: - * 同事做了一个商城, 马上就要上线了, 客户说还需要增加一个, 提醒商家发货的功能,然后就有了下面一段代码 - * 然后过了几天,客户问: 为什么点击这个提醒商家的功能没什么用呢 - * 我心里想: 这要是有用才是见了鬼了呢 - */ -// 页面按钮 -// - -// 获取按钮元素 -var reminder = document.getElementById("reminder"); - -// 添加点击事件监听器 -reminder.addEventListener("click", function() { - // 弹窗提示 - alert("已提醒商家,尽快为您发货!"); -}); \ No newline at end of file diff --git a/js/ternary-operator.js b/js/ternary-operator.js deleted file mode 100644 index 893d9c21bbde0f63d7b199a9d68223c18a58e076..0000000000000000000000000000000000000000 --- a/js/ternary-operator.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * js三元运算符之我是个什么东西??? - * @param {string} people - */ -function isRole(people = "") { - const user = "user"; - const admin = "admin"; - const vip = "vip"; - return people !== user - ? people !== vip - ? people !== admin - ? "is dog" - : "is admin" - : "is vip" - : "is user"; -} diff --git a/js/terrible_moments.js b/js/terrible_moments.js deleted file mode 100644 index a713352712f87a161b590afabf956ba54b61d147..0000000000000000000000000000000000000000 --- a/js/terrible_moments.js +++ /dev/null @@ -1,129 +0,0 @@ -import moment from 'moment'; - -/** - * 计算以周为单位的日期单元 - * @param {String} dateOfFirst 起始日期 - */ -const weekUnits = (dateOfFirst) => { - const result = []; - let p = moment(dateOfFirst).weekday(0); - do { - const start = format(p); - const end = format(p.add(1, 'weeks')); - p.subtract(1, 'weeks'); - result.push({ - display: getWeekName(p), - start, - end - }); - p.add(1, 'weeks'); - } while (p.isBefore(moment())); - return result; -} - -/** - * 第 n 周 - * @param {Moment} p 日期 - */ -const getWeekName = (p) => { - let resultYear = ''; - const yearOfSaturday = p.weekday(6).year(); - if (yearOfSaturday !== moment().year()) { - resultYear = `${yearOfSaturday}年-`; - } - p.weekday(0); - let resultWeek = ''; - if (p.weekday(7).isSameOrAfter(moment().weekday(0).hour(0).minute(0).second(-1))) { - resultWeek = '上'; - } - p.weekday(-7); - if (p.weekday(7).isAfter(moment())) { - resultWeek = '本'; - } - p.weekday(-7); - if (p.weekday(6) < moment().weekday(-7)) { - resultWeek = p.weekday(0).week(); - } - p.weekday(0); - if (['本', '上'].includes(resultWeek)) { - resultYear = ''; - } - return `${resultYear}${resultWeek}周`; -} - -/** - * 计算以月为单位的日期单元 - * @param {String} dateOfFirst 起始日期 - */ -const monthUnits = (dateOfFirst) => { - const result = []; - let p = moment(dateOfFirst).startOf('month'); - do { - const start = format(p); - const end = format(p.endOf('month').add(1, 'second')); - p.subtract(1, 'months'); - result.push({ - display: getMonthName(p), - start, - end - }); - p.add(1, 'months'); - } while (p.isBefore(moment())); - return result; -} - -/** - * xxxx 年 - * @param {Moment} p 日期 - */ -const getMonthName = (p) => { - let year = ''; - let month = ''; - if (p.year() != moment().year()) { - year = `${p.year()}年-`; - } - if (p.endOf('month').isSameOrAfter(moment().startOf('month').hour(0).minute(0).second(-1))) { - month = '上'; - } - if (p.endOf('month').isSameOrAfter(moment())) { - month = '本'; - } - p.startOf('month'); - if (p.isBefore(moment().startOf('month').subtract(1, 'months'))) { - month = p.month() + 1; - } - if (['本', '上'].includes(month)) { - year = ''; - } - return `${year}${month}月`; -} - -/** - * 计算以年为单位的日期单元 - * @param {String} dateOfFirst 起始日期 - */ -const yearUnits = (dateOfFirst) => { - let p = moment(dateOfFirst).startOf('year'); - const result = []; - do { - const start = format(p); - const end = format(p.add(1, 'year')); - p.subtract(1, 'year'); - result.push({ - display: `${p.year()}年`, - start, - end - }); - p.add(1, 'year'); - } while (p.isBefore(moment())); - return result; -} - -const format = (moment) => moment.format('YYYY-MM-DD'); - -export default { - weekUnits, - monthUnits, - yearUnits, - format -}; diff --git a/js/tryCatch.js b/js/tryCatch.js deleted file mode 100644 index 0f4c6cfe80427c4cf45fac5701c7dfd8ae96b579..0000000000000000000000000000000000000000 --- a/js/tryCatch.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Create Time 2019/5/29 - * tryCatch 高级用法 - * @author cailong - **/ -(function(){ - try{ - something - }catch (e){ - //看似平淡无常 实则惊涛骇浪 - window.open("//www.baidu.com/s?wd=" + e.message, "_blank"); - } -}()); \ No newline at end of file diff --git a/js/view_os_info.js b/js/view_os_info.js deleted file mode 100644 index a4d967c79197903d496642eff2a19550b5eb9c1b..0000000000000000000000000000000000000000 --- a/js/view_os_info.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Created by JamesView on 2019-06-28 14:44. - * 说明: 在node中运行你就可以看到自己的当前操作系统的所有信息,"灰常"的有用呢! - */ -var os = require("os"); -(function see(){ - console.log("===================ViewOSInfo============================") - console.log("Computer-Name:"+os.hostname()) - console.log("---------------------------------------------------------") - console.log("User home dir:"+os.homedir()) - console.log("---------------------------------------------------------") - console.log("OS bit:"+os.arch()) - console.log("---------------------------------------------------------") - console.log("OS platform:"+os.platform()) - console.log("---------------------------------------------------------") - console.log("OS release:"+os.release()) - console.log("---------------------------------------------------------") - console.log("OS tmpdir:"+os.tmpdir()) - console.log("---------------------------------------------------------") - console.log("OS total memory:"+parseInt(os.totalmem()/1024/1024)+"MB") - console.log("---------------------------------------------------------") - console.log("OS free memory:"+parseInt(os.freemem()/1024/1024)+"MB") - console.log("---------------------------------------------------------") - console.log("OS type:"+os.type()) - console.log("---------------------------------------------------------") - console.log("CPU info("+os.cpus().length+" models):") - console.dir(os.cpus()) - console.log("---------------------------------------------------------") - console.log("CPU Type:"+os.endianness()) - console.log("---------------------------------------------------------") - console.log("System activity(Only for Unix):"+os.loadavg()) - console.log("---------------------------------------------------------") - console.log("Network Info:") - console.log("---------------------------------------------------------") - console.log(os.networkInterfaces()) - console.log("=========================================================") -})() \ No newline at end of file diff --git a/js/worst-promise-practice.js b/js/worst-promise-practice.js deleted file mode 100644 index 0a602a1f45506af4f8d20c85a088b77ce9de54d7..0000000000000000000000000000000000000000 --- a/js/worst-promise-practice.js +++ /dev/null @@ -1,23 +0,0 @@ -//看到这些代码已经懒得改了... -export default class ActionInfo extends React.Component{ - emitSubmit=()=>{ - let {state,props} = this; - this.form.getFormData().then(formdata=>{ - this.setState({ - loading:true - }) - request('...',{ - body:formdata, - }).then(res=>{ - this.setState({ - loading:false, - }) - if(res.success){ - message.success('操作成功'); - this.closeModal(); - props.successCallback && props.successCallback(res.data); - } - }) - }) - } -} diff --git "a/js/\344\270\255\346\226\207\347\274\251\345\206\231\345\221\275\345\220\215\346\216\245\345\217\243\345\222\214\345\217\230\351\207\217\357\274\214\347\233\270\345\275\223\347\202\270\350\243\202" "b/js/\344\270\255\346\226\207\347\274\251\345\206\231\345\221\275\345\220\215\346\216\245\345\217\243\345\222\214\345\217\230\351\207\217\357\274\214\347\233\270\345\275\223\347\202\270\350\243\202" deleted file mode 100644 index e5dc2c46b8db441df2bd99c17e2d186525f5ff9f..0000000000000000000000000000000000000000 --- "a/js/\344\270\255\346\226\207\347\274\251\345\206\231\345\221\275\345\220\215\346\216\245\345\217\243\345\222\214\345\217\230\351\207\217\357\274\214\347\233\270\345\275\223\347\202\270\350\243\202" +++ /dev/null @@ -1,100 +0,0 @@ -// 接口返回的字段定义 -export interface Data { - /** - * 实测实量次数 - */ - scsl: number; - /** - * 实测实量合格率 - */ - scslhgl: number; - /** - * 送检次数 - */ - sj: number; - /** - * 送检合格率 - */ - sjhgl: number; - /** - * 实际检测合格率 - */ - sthgl: number; - /** - * 实体检测次数 - */ - stjc: number; - /** - * 整改次数 - */ - zg: number; - /** - * 整改合格率 - */ - zghgl: number; -} - -// 甚至接口本身都是中文缩写哈哈 -/** - * @des 检查类别 | 问题列表 - * @param data - * @returns - */ -export function wtlbGet(data: any): Promise> { - return request({ - url: '/quality/wtlb', - method: 'get', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - data: data, - }) -} - -/** - * @des 逾期提醒 - * @param data - * @returns - */ - export function yqtxGet(data: any): Promise> { - return request({ - url: '/quality/yqtx', - method: 'get', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - data: data, - }) -} - -/** - * @des 检查人排名 - * @param data - * @returns - */ - export function jcGet(data: any): Promise> { - return request({ - url: '/quality/jc', - method: 'get', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - data: data, - }) -} - -/** - * @des 闸机统计 - * @param data - * @returns - */ -export function TongjiRecordListGet(data: Record<"day"|"code",any>) :Promise> { - return request({ - url: '/person/getTongjiRecordList', - method: 'get', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - data: data, - }) -} \ No newline at end of file diff --git a/lua/lua_fool_judgment.lua b/lua/lua_fool_judgment.lua deleted file mode 100644 index 9bfd8e8cce853d599186edb41c2049753a97d971..0000000000000000000000000000000000000000 --- a/lua/lua_fool_judgment.lua +++ /dev/null @@ -1,21 +0,0 @@ -function _logout(self) - local sock = self.sock - if not sock then - return nil, "not initialized" - end - - self.state = nil - if self.state == STATE_CONNECTED then - -- Graceful shutdown - local headers = {} - headers["receipt"] = "disconnect" - sock:send(_build_frame(self, "DISCONNECT", headers, nil)) - sock:receive("*a") - end - return sock:close() -end - ---[[ - 这是一段有史以来我见过最'Graceful'的代码, 上面的注释是作者自己加入进去的. - 出处来源于这里: https://github.com/Loc-Tran/lua-resty-rabbitmqstomp/blob/v0.1/lib/resty/rabbitmqstomp.lua -]] diff --git a/lua/lua_version.lua b/lua/lua_version.lua deleted file mode 100644 index b1925005fe6f4c4061b1a64eee9012aaaecfbc94..0000000000000000000000000000000000000000 --- a/lua/lua_version.lua +++ /dev/null @@ -1,17 +0,0 @@ -local f = function() return function() end end -local t = { - nil, - [false] = 'Lua 5.1', - [true] = 'Lua 5.2', - [1/'-0'] = 'Lua 5.3', - [1] = 'LuaJIT' -} - -local version = t[1] or t[1/0] or t[f()==f()] -print(version) - ---[[ - 网上大神根据lua 各个版本的特性写的 - 通过判断 每个版本的table实现和function 实现的不同 - 来获得运行的lua 版本 -]] \ No newline at end of file diff --git a/lua/nb_mobile_verify.lua b/lua/nb_mobile_verify.lua deleted file mode 100644 index 45597d48aab3ba92a319cb1a32ea50b08f53a1ba..0000000000000000000000000000000000000000 --- a/lua/nb_mobile_verify.lua +++ /dev/null @@ -1,4 +0,0 @@ -FOO.isMobile=function(s_) - local n_ =tonumber(s_) or 0 - return(n_>13000000000 and n_<19999999999) -end \ No newline at end of file diff --git a/makefile/.keep b/makefile/.keep deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/makefile/Makefile b/makefile/Makefile deleted file mode 100644 index 4783505a916e545b3c82d1eb90fb8c0112dd67c8..0000000000000000000000000000000000000000 --- a/makefile/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -PATHPWD=. -# PATHBIN=$(PATHPWD)/bin # 本来需要同时生成可执行文件和库,后来单独只生成库,就吧这行注释掉了 -PATHLIB=$(PATHPWD)/lib -PATHSRC=$(PATHPWD)/src -PATHOBJ=$(PATHPWD)/obj - - -clean: - rm -rf $(PATHBIN)/* $(PATHLIB)/* $(PATHOBJ)/* - -# 在编译服务器上执行make clean 以后可以跑路了 \ No newline at end of file diff --git a/php/Aliyun_FC_OOM.jpeg b/php/Aliyun_FC_OOM.jpeg deleted file mode 100644 index e2f9ae4cbbf234d26f7dcd2cc1fa7797b38d40ae..0000000000000000000000000000000000000000 Binary files a/php/Aliyun_FC_OOM.jpeg and /dev/null differ diff --git a/php/Aliyun_FC_OOM.php b/php/Aliyun_FC_OOM.php deleted file mode 100644 index c6d5875e8ddbc44cd76a9d4dd7d094ab67d33d1b..0000000000000000000000000000000000000000 --- a/php/Aliyun_FC_OOM.php +++ /dev/null @@ -1,14 +0,0 @@ - \ No newline at end of file diff --git a/php/DemoController.php b/php/DemoController.php deleted file mode 100644 index d49c47eb06161cfd183a5aa3b9eef60da492a402..0000000000000000000000000000000000000000 --- a/php/DemoController.php +++ /dev/null @@ -1,17 +0,0 @@ -request->param('name'); - $id = $this->request->param('id'); - - Db::name($name)->where('id',$id)->delete(); - $this->success('删除成功'); - } - -} diff --git a/php/FastProductController.php b/php/FastProductController.php deleted file mode 100644 index af4c59ef8dae12697a21c219a07f4ded0023541b..0000000000000000000000000000000000000000 --- a/php/FastProductController.php +++ /dev/null @@ -1,35 +0,0 @@ -0){ - sleep(10-$sleep); - } - $productId = I('get.productId'); - $userInfo = db('product')->where(['id'=>$productId])->select(); - echo json_encode( - [ - 'state'=>1100, - 'message'=>'查询成功!', - 'data'=>$userInfo - ] - ); - } \ No newline at end of file diff --git a/php/ForMysql.php b/php/ForMysql.php deleted file mode 100644 index a0bfad5d84fe59375df70a68bc8eb426e119e980..0000000000000000000000000000000000000000 --- a/php/ForMysql.php +++ /dev/null @@ -1,34 +0,0 @@ -request->only('XXXXXXXXXX'); - - foreach ($res['XXXXXXXXXX'] as $k => $v) { - Db::name('order')->where('XXXXXXXXXX',$v)->select(); - } - } - - /** - * 这道我这一辈子都不能忘记的写法 - * @author yansong - */ - public function ifTransaction() - { - $XXX = $this->request->only('XXX'); - Db::startTrans(); - $a = Db::name('user')->where('id', $XXX)->update(['is_activity' => 2]); - if ($a) { - Db::commit(); - } else { - Db::rollback(); - } - } -} diff --git a/php/GameController.php b/php/GameController.php deleted file mode 100644 index cce204f223d447759eca04a100cdc31394c50c92..0000000000000000000000000000000000000000 --- a/php/GameController.php +++ /dev/null @@ -1,38 +0,0 @@ -where('id',$id)->setDec('coin',5); - } - - /* 抓取概率在前端,游戏结束点击领奖 - */ - public function gameover() - { - $id = cmf_get_user_id(); - $coin = $this->request->param('coin'); - - if ($coin != 0){ - Db::name('user')->where('id',$id)->setInc('coin', $coin); - } - //给他当面演示注入coin=500以后,改成以下条件 - if ($coin != 0 && $coin <= 100){ //解释说100金币是能转到最大额的 T T - Db::name('user')->where('id',$id)->setInc('coin', $coin); - } - } - - - /* 说到底是年纪小(当时不满21) - * 给他讲不要相信接收的数据、给他讲开始即结束,奈何心里只有+15 - */ - -} - diff --git a/php/GetPost.php b/php/GetPost.php deleted file mode 100644 index 50143ff7f38f51b98918059a021b8dc188a97453..0000000000000000000000000000000000000000 --- a/php/GetPost.php +++ /dev/null @@ -1,7 +0,0 @@ -request_get('https://www.aaaaaa.com/a?app_id=' . $rearr['appid'] . '&udid=' . $rearr['udid'] . '&idfa=' . $rearr['idfa']); - $local_ar = json_decode($local_json, true); - if ($local_ar['code'] == 1 && $local_ar['install'] == 1) { - $this->db->insert('aso_' . $this->date . '_log', array('cpid' => $rearr['cpid'], 'appid' => $rearr['appid'], 'adid' => $rearr['adid'], 'idfa' => $rearr['idfa'], 'json' => $local_json, 'date' => time(), 'udid' => $rearr['udid'], 'status' => 0)); - echo json_encode(array($rearr['idfa'] => '0')); - die; - } -} elseif ($rearr['udid'] == '' && $cpid != 207) { - $local_json = $this->request_get('https://www.aaaa.com/a?app_id=' . $rearr['appid'] . '&idfa=' . $rearr['idfa']); - $local_ar = json_decode($local_json, true); - if ($local_ar['code'] == 1 && $local_ar['install'] == 1) { - $this->db->insert('aso_' . $this->date . '_log', array('cpid' => $rearr['cpid'], 'appid' => $rearr['appid'], 'adid' => $rearr['adid'], 'idfa' => $rearr['idfa'], 'json' => $local_json, 'date' => time(), 'udid' => $rearr['udid'], 'status' => 0)); - echo json_encode(array($rearr['idfa'] => '0')); - die; - } -} \ No newline at end of file diff --git a/php/Lazy.php b/php/Lazy.php deleted file mode 100644 index bac8c659aa482a04bd5df9dbf2be5d34734601d9..0000000000000000000000000000000000000000 --- a/php/Lazy.php +++ /dev/null @@ -1,47 +0,0 @@ - 1,'msg' => '清理缓存成功~~~!!!']; - } -} diff --git a/php/bullshitClass.php b/php/bullshitClass.php deleted file mode 100644 index 8cdc2f429d6b09312c374d390503368fef46c7d4..0000000000000000000000000000000000000000 --- a/php/bullshitClass.php +++ /dev/null @@ -1,90 +0,0 @@ -where(['out_trade_no' => $notifyData['out_trade_no']])->find(); - - if (!$order) {// 订单不存在则不处理 - echo 'SUCCESS'; - die; - } - - if ($notifyData['return_code'] === 'SUCCESS') { // 支付成功了 - // 1.将订单状态更新为已完成 - // 2.给用户的账户加钱 - } - } - - /** - * 示例二:事务的处理 「大坑:return 之后不要有其它代码」 - * - */ - public function demo2() - { - Db::startTrans(); - try { - // 逻辑1 - // 逻辑2 - // ... - return true; - Db::commit(); - } catch (Exception $e) { - return false; - Db::rollback(); - - } - } - - /** - * 示例三:下单api 「大坑:商品实际价格应在后端数据库来获取,不能以前端提交的价格来作为商品价格」 - * 已经过身份认证的用户才可访问该方法 - * @param $productData - * @return array - */ - public function demo3($productData) - { - $product = Db::name('product')->find($productData['product_id']); - if (!$product || ($product->is_on_sell === 'F')) return ['status' => 'error', 'msg' => '商品不存在或已下架']; - - // 判断库存是否充足 TODO - - $orderData = [ - 'user_id' => 'xx',// 当前登录用户 id - 'product_id' => $productData['product_id'], - 'order_sn' => generateOrderSn(), // 生成唯一订单号 - 'product_price' => $productData['product_price'] * $productData['product_num'], - 'status' => 0,// 新订单 - 'create_time' => time() - ]; - // 拉取微信支付数据 - $result = $this->wxpay->order->unify([ - 'body' => '博彩投注', - 'out_trade_no' => $orderData['order_sn'], - 'total_fee' => $orderData['product_price'] * 100, - 'spbill_create_ip' => $_SERVER["REMOTE_ADDR"], // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址 - 'notify_url' => 'http://xxxxxx', // 支付结果通知网址,如果不设置则会使用配置里的默认地址 - 'trade_type' => 'APP', - ]); - - if ($result['return_code'] == 'FAIL') { - return ['status' => 'error', 'msg' => $result['return_msg']]; - } - - // 生成预支付订单 - Db::name('wx_order')->insert($orderData); - return ['status' => 'success', 'msg' => $result]; - } -} \ No newline at end of file diff --git a/php/nb/README.md b/php/nb/README.md deleted file mode 100644 index d6c0d1ade3268b1cd16e9735556a6b0638e8f31e..0000000000000000000000000000000000000000 --- a/php/nb/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# 牛逼代码 - -我就找几个最具代表性的,其实还很多,不过就找这个几个吧,我把其中的企业信息去掉,只留下代码。 -供各位观赏! \ No newline at end of file diff --git a/php/nb/l.php b/php/nb/l.php deleted file mode 100644 index be7c688b57263b8d8c3987307a8007d73c00aad6..0000000000000000000000000000000000000000 --- a/php/nb/l.php +++ /dev/null @@ -1,1177 +0,0 @@ -base_url($url), - 'total_rows'=>$total, - 'per_page'=>$per_page, - 'uri_segment'=>$uri_segment, - 'use_page_numbers'=>TRUE, - 'num_links'=>5, - ); - $this->load->library('customsizepagination'); - $this->customsizepagination->initialize($pgcfg); - return $this->customsizepagination->create_links(); - } - - private function success($data = '', $status = 200, $msg = 'success') { - $result = [ - 'data' => $data, - 'status' => $status, - 'msg' => $msg - ]; - header ( 'Content-Type:application/json; charset=utf-8' ); - echo json_encode ( $result ); - exit(0); - } - - private function error($status = 404, $msg = '') { - $result = [ - 'status' => $status, - 'msg' => $msg, - 'data' => null - ]; - header ( 'Content-Type:application/json; charset=utf-8' ); - echo json_encode ( $result ); - exit(0); - } - - private function send_mail($data) { - $this->load->library(array('email', 'parser')); - - $this->email->from('noreply@huorong.cn', 'Huorong Security'); - $this->email->to($data['email']); - - $this->email->subject('[xxxxxx管理系统] -产品授权'); - $this->email->message($this->parser->parse('mail_lic_info', $data, TRUE)); - - return $this->email->send(FALSE); - } - - private function send_sms ( $phone ) { - $params = array( - 'SignName' => 'xxxx', - 'PhoneNumbers' => $phone, - 'TemplateCode' => 'SMS_123456789', - 'TemplateParam' => array('phone' => '123456789') - ); - - $this->load->library('aliyunsms'); - return $this->aliyunsms->sendSMS($params); - } - - public function index() { - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - redirect(array('esslicense','manage')); - } - - private function fill_lic_dict(&$row) { - global $license,$licensed,$regsrcs; - - if ($row['lictype'] === '0'){ - $row['nowlictype'] = $licensed[1]; - }else{ - $row['nowlictype'] = $licensed[2]; - } - if (array_key_exists($row['lictype'], $license)) { - $row['vlictype']=$license[$row['lictype']]; - } - - if (array_key_exists($row['regsrc'], $regsrcs)) { - $row['regsrc']=$regsrcs[$row['regsrc']]; - } - foreach($row as $k=>$v) { - if ($v==='0000-00-00 00:00:00' || $v==='1000-01-01 00:00:00' || $v==='1970-01-02 00:00:00' || $v==='0') { - $row[$k]='-'; - } else { - $row[$k]=html_escape($v); - } - } - } - - private function _get_filter_condition($where = array()) { - - if ($this->session->has_userdata('flt_license')){ - if (array_key_exists('onlyyou', $this->session->flt_license)) { - $where['uid'] = $this->session->userinfo['id']; - } - - if (array_key_exists('fltcls', $this->session->flt_license) && array_key_exists('flttxt',$this->session->flt_license) && !empty($this->session->flt_license['flttxt'])){ - $this->db->like('c.'.$this->session->flt_license['fltcls'], $this->session->flt_license['flttxt']); - } - } - - $this->load->helper('cookie'); - $lictype_param1 = get_cookie('lictype'); - $lictype_param2 = get_cookie('licensed'); - - if ($lictype_param2 == 0){ - if ($lictype_param1 != 3){ - $where['c.lictype'] = $lictype_param1; - } - }else if ($lictype_param2 == 1){ - if ($lictype_param1 != 1 && $lictype_param1 != 2){ - $where['c.lictype'] = 0; - } - }else if ($lictype_param2 == 2){ - if ($lictype_param1 !== '0' && $lictype_param1 != 3){ - $where['c.lictype'] = $lictype_param1; - }else if ($lictype_param1 == 3){ - $where['c.lictype != '] = 0; - } - } - - if ( ! isset($where['c.lictype'])){ - unset($where['c.lictype']); - } - - return $where; - } - - private function display_manage($state, $where, $pgno,$perpage, $isDesc = false) { - - if ($this->input->method()==='post') { - $this->session->flt_license = $this->input->post(); - } - - $where = $this->_get_filter_condition($where); - - $where['c.state'] = 2; - - if($pgno == 1 || $pgno == 0){ - $start_id = 0; - }else{ - $start_id = $perpage*($pgno-1); - } - - $nav = $this->load->view('ess_manage/license_nav',array('state'=>$state,'flt'=>$this->session->flt_license),TRUE); - - $rows = $this->db->select(array('SQL_CALC_FOUND_ROWS c.*, u.nick'), false)->from('clients as c')->join('user as u','c.uid = u.id', 'left')->where( $where); - - $rows = $isDesc ? $rows->order_by('c.id', 'desc')->limit( $perpage, $start_id)->get() : $rows->order_by('c.id', 'asc')->limit( $perpage, $start_id)->get() ; - - $total = $this->db->query('SELECT FOUND_ROWS() AS `Count`')->row()->Count; - - $pgvw=$this->build_pagination(array('esslicense','manage'), $total, $perpage, 3); - - $results = array(); - - while ($row = $rows->unbuffered_row('array')) { - $this->fill_lic_dict($row); - $results[] = $row; - } - - $this->load->view('ess_manage/license_header', array('flt_license' => $this->session->flt_license, 'pgno' => $pgno)); - $this->load->view('essmgr_main_nav'); - $this->load->view('ess_manage/license_'.$state, array('clients'=>$results,'pgvw'=>$pgvw,'total'=>$total,'manage_nav'=>$nav, 'per_page' => $perpage)); - $this->load->view('ess_manage/footer'); - } - - public function manage($pgno=0,$pagesize=DEFAULT_PAGE_NUMBER) { - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - $this->display_manage('all', array(), $pgno,$pagesize, true); - } - - public function update_pg($id=0) { - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - - $row = $this->db->query("SELECT * FROM `clients` WHERE id=?",array($id))->unbuffered_row('array'); - - if ($row === NULL) { - show_404(); - } - - $row['lic_tk'] = $this->encryption->encrypt(json_encode($row)); - - $this->parser->parse('ess_manage/template/license_update',$row); - } - - private function build_license($clntid) { - - $data = $this->db->select("name,licnodes,licexpire,lictm,serial")->get_where('clients', array('id'=>$clntid))->unbuffered_row('array'); - - $arr = array( - 'to' => $data['name'], - 'type' => 1, - 'nodes_num' => intval($data['licnodes']), - 'expire_time' => strtotime($data['licexpire']), - 'license_time' => strtotime($data['lictm']), - 'serial' => $data['serial'], - ); - - $privatekey = openssl_pkey_get_private(file_get_contents('ess.key'), ""); - $arr_json = json_encode($arr); - openssl_sign($arr_json, $signature, $privatekey, OPENSSL_ALGO_SHA512); - return strtr(base64_encode($signature) . '.' . base64_encode($arr_json), '+/', '-_'); - } - - //生成许可证 - public function update_update() { - // var_dump(json_decode($this->decrypt_data(rawurldecode($this->input->post('token')))));die; - $repass = $this->input->post('repass'); - if(isset($_REQUEST['source'])){ - if($this->input->post('source') == 'preseller'){ - - $token = json_decode($this->decrypt_data(rawurldecode($this->input->post('token'))),TRUE); - - $uid = $this->input->post('uid'); - $email = $token['email']; - if($token == 'error' || $token == ""){ - echo false; - } - $lictype = '2'; - $token['lictype'] = '2'; - - }else{ - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - - if ($this->input->method() !== 'post') { - exit(); - } - $uid = $this->session->userinfo['id']; - $email = trim( $this->input->post('email')); - $token = json_decode($this->encryption->decrypt($this->input->post('token')),TRUE); - $lictype = $this->input->post('lictype'); - } - }else{ - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - - if ($this->input->method() !== 'post') { - exit(); - } - $uid = $this->session->userinfo['id']; - $email = trim( $this->input->post('email')); - $token = json_decode($this->encryption->decrypt($this->input->post('token')),TRUE); - $lictype = $this->input->post('lictype'); - } - - $clnt = array( - 'name'=>$this->input->post('name'), - 'lictm'=>$this->input->post('tm'), - 'lictype'=>$lictype, - 'licexpire'=>$this->input->post('expire'), - 'licnodes'=>$this->input->post('nodes'), - 'licdays'=>$this->input->post('days'), - 'uid'=>$uid - ); - //如果代理商传过来的话 自动为正式版 - if(isset($_REQUEST['source'])){ - $clnt['state'] = 2; - } - - if (empty($email)) { - $email = $token['email']; - } - - $log = array( - 'optm' => date("Y-m-d H:i:s", time()), - 'cid' => $token['id'], - 'name' => $clnt['name'], - 'email' => $email, - 'uid' => $uid, - 'state' => $token['state'], - 'days' => $clnt['licdays'], - 'nodes' => $clnt['licnodes'], - 'memo' => '' - ); - - $this->log_record('更新', $log); - - if (!$this->db->update('clients',$clnt, array('id'=>$token['id']))){ - show_error($this->db->error()); - } - - $clnt['id'] = $token['id']; - - $this->log_record('生成xxx', $log); - if(data) - $clnt['data'] = $this->build_license($token['id']); - - if ( isset($repass) && $repass == 1) { - $passwd = $this->randomPassword(); - $clnt['passwd'] = sha1($passwd); - }else if ($token['lictype'] != '1' && $token['lictype'] != '2' ){ - //根据此客户是否已授权,没有 则 第一次 需要 生成密码; 是 则 不再生成密码 - $passwd = $this->randomPassword(); - $clnt['passwd'] = sha1($passwd); - } - - $this->http_update($clnt); - - if ( isset($repass) && $repass == 1) { - $clnt['passwd'] = $passwd; - $clnt['serial'] = $this->input->post('serial'); - }else if ($token['lictype'] != '1' && $token['lictype'] != '2' ){ - $clnt['passwd'] = $passwd; - $clnt['serial'] = $this->input->post('serial'); - } - - if (!empty($email)) { - $clnt['email'] = $email; - } - - if (!$this->send_mail($clnt)){ - log_message('error', 'SendMail: "'.$clnt['name'].'","'.$email.'", fail,"'.$this->email->print_debugger(array('headers')).'"'); - $this->error(500, $this->email->print_debugger(array('headers'))); - } - - if (!$this->send_sms($token['phone'])){ - $this->error(401, 'system error'); - } - if(!isset($_REQUEST['source'])){ - redirect($_SERVER['HTTP_REFERER']); - }else{ - echo true; - } - } - - private function randomPassword() { - $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; - $pass = array(); - $alphaLength = strlen($alphabet) - 1; - for ($i = 0; $i < 8; $i++) { - $pass[] = $alphabet[mt_rand(0, $alphaLength)]; - } - return implode($pass); - } - - private function log_record($action, $data) { - $data['action'] = $action; - if(!$this->db->insert('record',$data)){ - show_error($this->db->error()); - } - } - private function decrypt_data($ciphertext){ - $key = hex2bin('1d1a0dd573732cf5090738e1935138b3f12604ac6ba1fa127919c7cc85b0179f44cf13f78257261fba6de51a92e2ca29ee76afe3990e3c7cd5b716bd2721d851'); - $c = base64_decode($ciphertext); - $ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC"); - $iv = substr($c, 0, $ivlen); - $hmac = substr($c, $ivlen, $sha2len=32); - $ciphertext_raw = substr($c, $ivlen+$sha2len); - $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv); - $calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true); - if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison - { - return $original_plaintext; - } - return "error"; - } - private function http_update($data) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, "http://".ESSMGR_FRONTEND_IP."/essmgr/esssync/update"); - curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".ESSMGR_FRONTEND_HOST)); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encryption->encrypt(json_encode($data))); - $output = curl_exec($ch); - curl_close($ch); - return $output; - } - private function fill_client_dict(&$row) { - global $nodescnts,$industrys,$provinces,$regsrcs,$states,$license; - if (isset($row['nodes']) && array_key_exists($row['nodes'], $nodescnts)) { - $row['vnodes'] = $nodescnts[$row['nodes']]; - } - if (isset($row['trade']) && array_key_exists($row['trade'], $industrys)) { - $row['vtrade'] = $industrys[$row['trade']]; - } - if (isset($row['province']) && array_key_exists($row['province'], $provinces)) { - $row['vprovince'] = $provinces[$row['province']]; - } - if (isset($row['regsrc']) && array_key_exists($row['regsrc'], $regsrcs)) { - $row['vregsrc'] = $regsrcs[$row['regsrc']]; - } - if (isset($row['state']) && array_key_exists($row['state'], $states)) { - $row['vstate'] = $states[$row['state']]; - } - if (isset($row['lictype']) && array_key_exists($row['lictype'], $license)) { - $row['vlictype'] = $license[$row['lictype']]; - } - $row['nickname'] = $this->get_nickname($row['uid']); - foreach($row as $k=>$v) { - if ($v==='0000-00-00 00:00:00' || $v==='1000-01-01 00:00:00' || $v==='1970-01-02 00:00:00' || $v==='0') { - $row[$k]='-'; - } else { - $row[$k]=html_escape($v); - } - } - } - - private function get_nickname($id) { - $row = $this->db->select('nick')->where('id',$id)->get('user')->unbuffered_row('array'); - if ($row === NULL) { - return '无'; - } - return $row['nick']; - } - - private function fill_record_dict(&$row) { - global $states; - if (array_key_exists($row['state'], $states)) { - $row['state'] = $states[$row['state']]; - } - $row['nickname'] = $this->get_nickname($row['uid']); - foreach($row as $k=>$v) { - if ($v==='0000-00-00 00:00:00' || $v==='1000-01-01 00:00:00' || $v==='1970-01-02 00:00:00' || $v==='0') { - $row[$k]='-'; - } else { - $row[$k]=html_escape($v); - } - } - } - - public function reset_passwd(){ - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - - $id = $this->input->post('id'); - $new_passwd = $this->input->post('newPasswd'); - - $data = $this->db->limit(1)->get_where('clients', array('id'=> $id))->unbuffered_row('array'); - - $data_log = array( - 'cid'=> $data['id'], - 'name'=> $data['name'], - 'email'=> $data['email'], - 'uid'=> $this->session->userinfo['id'], - 'state'=> $data['state'], - 'days'=> $data['licdays'], - 'nodes'=> $data['licnodes'], - 'memo'=> '', - ); - - $this->log_record('修改密码', $data_log); - - $this->http_reset_client_passwd(array('id'=> $id, 'passwd'=> sha1($new_passwd))); - - $data['passwd'] = $new_passwd; - - if (!$this->send_mail($data)){ - log_message('error', 'SendMail: "'.$data['name'].'","'.$data['email'].'", fail,"'.$this->email->print_debugger(array('headers')).'"'); - $this->error(500, $this->email->print_debugger(array('headers'))); - } - - $this->success(); - } - - public function details($clntid = 0, $pgno = 0,$perpage=15){ - - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - - $clnt = $this->db->get_where('clients',array('id'=>$clntid),1)->unbuffered_row('array'); - if ($clnt === NULL) { - show_404(); - } - $this->fill_client_dict($clnt); - if($pgno == 1 || $pgno == 0){ - $start_id = 0; - }else{ - $start_id = $perpage*($pgno-1); - } - $rows = $this->db->select(array('SQL_CALC_FOUND_ROWS *'), false)->order_by('id', 'desc')->get_where( 'record', array('cid'=>$clntid), $perpage, $start_id ); - $total = $this->db->query('SELECT FOUND_ROWS() AS `Count`')->row()->Count; - $pgvw=$this->build_pagination(array('esslicense','details', $clntid), $total, $perpage, 4); - - $records = array(); - while ($row = $rows->unbuffered_row('array')) { - $this->fill_record_dict($row); - $records[] = $row; - } -// //添加查询条件 是否有激活 - $this->db->select(array('SQL_CALC_FOUND_ROWS *'), FALSE); - $this->db->from('clients'); - $this->db->where(array('id'=>intval($clntid))); - $results = $this->db->get(); - $rows=$results->unbuffered_row('array'); - if($rows['licactivitytime']=='0000-00-00' || $rows['licactivitytime']=='1000-01-01 00:00:00' || $rows['licactivitytime']=='1970-01-02' || $rows['licactivitytime']=='0'){ - $returnData = $this->licative_curl(array("serial" => $rows['serial'])); - $returnData = trim($returnData,'"'); - if($returnData !== 'false' && preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $returnData)){ - $where=array( - 'licactivitytime'=>$returnData, - 'licactivitytype'=>1 - ); - $this ->db->where('serial',$rows['serial'])->update('clients',$where); - $rows['licactivitytype'] = 1; - $rows['licactivitytime'] = $returnData; - } - } - if(intval($rows['licactivitytype']) == 1){ - $activesd = '已激活'; - }else if(intval($rows['licactivitytype']) == 0){ - $activesd = '未激活'; - }else{ - $activesd = '内测激活'; - } - - $actives['type'] = $activesd; - $actives['time']= $rows['licactivitytime']; - $actives['types']= $rows['licactivitytype']; - $main_nav = $this->load->view('essmgr_main_nav',array(),TRUE); - $this->load->view('license_detail', array('clnt'=>$clnt, 'records'=> $records,'clntid'=>$clntid, 'pgvw'=>$pgvw, 'main_nav'=>$main_nav,'actives'=>$actives)); - } - - /** - * @param $data - * @return mixed - */ - private function licative_curl($data) { -// var_dump($data);die; - $arrContextOptions=array( - "ssl"=>array( - "verify_peer"=>false, - "verify_peer_name"=>false, - ), - ); - return file_get_contents(HRSTATS_URL."?serial=".$data["serial"],false, stream_context_create($arrContextOptions)); - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, HRSTATS_URL); - curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".ESSMGR_FRONTEND_HOST)); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); - curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 - curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $data); - $output = curl_exec($ch); - curl_close($ch); - return $output; - } - public function activeSubmit(){ - - $id=$_REQUEST['id']; - $actives = $_REQUEST['actives']; - $time = $_REQUEST['time']; - $where=array( - 'licactivitytime'=>$time, - 'licactivitytype'=>$actives - ); - $this ->db->where('id',$id)->update('clients',$where); - $result = [ - 'status' => 200, - 'msg' => 'success' - ]; - header ( 'Content-Type:application/json; charset=utf-8' ); - echo json_encode ( $result ); - } - private function fill_title_dict($title_en_arr){ - global $title_cn; - - $title_cn_arr = array(); - - foreach ($title_en_arr as $key =>$value) { - $v = trim($value,'"'); - if (array_key_exists($v, $title_cn)){ - $title_cn_arr[$key] = $title_cn[$v]; - } - } - return $title_cn_arr; - } - - private function fill_content_dict(&$arr) { - global $nodescnts,$industrys,$provinces,$regsrcs,$states,$license; - - $arr[2] = $this->check($regsrcs,$arr,2); - $arr[4] = $this->check($provinces,$arr,4); - $arr[5] = $this->check($industrys,$arr,5); - $arr[6] = $this->check($nodescnts,$arr,6); - if (trim($arr[10], '"') == '1'){ - $arr[10] = '已激活'; - }else{ - $arr[10] = '未激活'; - } - $arr[13] = $states[trim($arr[13],'"')]; - $arr[16] = $license[trim($arr[16],'"')]; - - foreach($arr as $k=>$v) { - $v = trim($v, '"'); - if ($v==='0000-00-00 00:00:00' || $v==='1000-01-01 00:00:00' || $v==='1970-01-02 00:00:00' || $v==='0') { - $arr[$k]='-'; - } else { - $arr[$k]=html_escape($v); - } - } - } - - public function export2csv(){ - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - - $where = $this->_get_filter_condition(); - - $where['c.state'] = 2; - - $query = $this->db->select('c.*, u.nick')->from('clients as c')->join('user as u','c.uid = u.id', 'left')->where( $where) ->order_by('c.id', 'asc')->get(); - $this->load->dbutil(); - $this->load->helper('file'); - $this->load->helper('download'); - - $delimiter = ","; - $newline = "\r\n"; - $enclosure = '"'; - $data = $this->dbutil->csv_from_result($query, $delimiter, $newline, $enclosure); - - $data = $this->_pretty_data($data); - - $Date = date("YmdHis"); - $Filename = $Date.'.csv'; - force_download($Filename, $data); - } - - private function _pretty_data ($data) { - - $data_arr = explode("\r\n", $data); - - array_pop($data_arr); - - $title_en_arr = explode(',', $data_arr[0]); - - $title_cn_arr = $this->fill_title_dict($title_en_arr); - - $title_cn = implode(',', $title_cn_arr); - - array_shift($data_arr); - array_unshift($data_arr, $title_cn); - - foreach ($data_arr as $key =>$value) { - if ($key == 0){ continue;} - - $v_arr = explode(',', $data_arr[$key]); - - $this->fill_content_dict($v_arr); - - $data_arr[$key] = implode(',', $v_arr); - } - - $data = implode("\r\n", $data_arr); - - return mb_convert_encoding($data,'gb2312','utf-8'); - } - - private function http_reset_client_passwd($data) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, "http://".ESSMGR_FRONTEND_IP."/essmgr/esssync/reset_passwd"); - curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".ESSMGR_FRONTEND_HOST)); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encryption->encrypt(json_encode($data))); - $output = curl_exec($ch); - curl_close($ch); - return $output; - } - /*给sem提供序列号的内容 - * - *@return array serial 返回的序列号 - * */ - public function find_serial_curl(){ - - $data = json_decode($_REQUEST); - $return = []; - foreach($data as$k=> $v) { - //添加查询条件 是否有激活 - $return[$k]['serial'] = $v['serial']; - $this->db->select(array('SQL_CALC_FOUND_ROWS *'), FALSE); - $this->db->from('clients'); - $this->db->where(array('serial' => $v['serial'])); - $results = $this->db->get(); - $rows = $results->unbuffered_row('array'); - if ($rows !== NULL ) { - $return[$k]['licactivitytime'] = $rows['licactivitytime']; - } else { - $return[$k]['licactivitytime'] = ""; - } - } - // 生成json格式数据 - header('Access-Control-Allow-Origin: *'); - echo json_encode($return); - } - /** - * 根据原始数据数组的key获取value作为字典的key得到对应的翻译值 - * @param $ay array 字典 - * @param @arr array 原始值数组 - * @param @index string - * @return string - */ - private function check($ay,$arr,$index){ - $key = isset($arr[$index]) ? trim($arr[$index]) : ""; - $key = str_replace('"',"",$key); - if(array_key_exists($key, $ay)){ - return trim($ay[$key]); - } - return '"'; - } - - - /** - * http_put_client 推送客户端信息到前端 - * - * @param mixed $data - * - * @return void - */ - private function http_put_client($data) { - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, "http://".ESSMGR_FRONTEND_IP."/essmgr/esssync/put_client"); - curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".ESSMGR_FRONTEND_HOST)); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encryption->encrypt(json_encode($data))); - $output = curl_exec($ch); - curl_close($ch); - return $output; - } - - /** - * _build_serial 生成序列号 - * - * @param mixed $province - * @param mixed $company_name - * - * @return void - */ - private function _build_serial($province, $company_name) { - $serial = array( - 'ESV1', - $province.strtoupper(str_pad(dechex(mt_rand(0,255)), 2, '0', STR_PAD_LEFT)), - date('yW'), - strtoupper(str_pad(dechex(crc32($company_name)), 8, '0', STR_PAD_LEFT)), - ); - return implode('-', $serial); - } - - /** - * _build_lic 生成证书 - * - * @return void - */ - public function _build_lic($data) - { - $arr = array( - 'to' => $data['name'], - 'type' => 1, - 'nodes_num' => intval($data['licnodes']), - 'expire_time' => strtotime($data['licexpire']), - 'license_time' => strtotime($data['lictm']), - 'serial' => $data['serial'], - ); - - $privatekey = openssl_pkey_get_private(file_get_contents('ess.key'), ""); - $arr_json = json_encode($arr); - openssl_sign($arr_json, $signature, $privatekey, OPENSSL_ALGO_SHA512); - return strtr(base64_encode($signature) . '.' . base64_encode($arr_json), '+/', '-_'); - } - - /** - * showFormalLic 显示正式证书添加页面 - * - * @return void - */ - public function showFormalLic() - { - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - $this->load->view('ess_manage/template/createFormalLic',array()) ; - } - - /** - * 判断表单数据是否为空 - * - * @param array $fields 判断的字段 - * @param array $data 判断的数据 - * - * @return array - */ - public function isFormEmpty($fields, $data) - { - foreach ($fields as $key => $val) { - if (!isset($data[$val]) || empty($data[$val])) { - // var_dump($val, $data); - return [true, $key]; - } - } - return [false, '']; - } - - /** - * 判断表单数据是否为默认项 - * - * @param array $fields 判断的字段 - * @param array $data 判断的数据 - * - * @return array - */ - public function isFormDefault($fields, $data) - { - if(count($fields) !== 0){ - foreach ($fields as $key => $val) { - if (!isset($data[$val]) || empty($data[$val]) || $data[$val] == 1 ) { - // var_dump($val, $data); - return [true, $key]; - } - } - } - return [false, '']; - } - - /** - * createFormalLic 创建正式证书 - * - * @return void - */ - - - public function createFormalLic() - { - if (!$this->session->is_login) { - redirect(array('essmgr','index')); - } - - // 非表单数据生成 - $now = date("Y-m-d H:i:s", time()); - $post = $this->input->post(); - unset($post['csrf_test_name']); - //判断传入数据 - if(!(isset($post['type_sales']) && isset($post['type_message']))){ - $this->error(401, '字段不正确'); - } - // 拼接字段是否为空和验证字段 - //验证不能为空的数组 - - //验证是否生效的数组 - $fields_checked = []; - - if($post['type_sales'] == "agent"){ - $fields_null = [ - '授权台数' => 'agent_licnodes', - '授权期限' => 'agent_licdays', - '邮箱通知' => 'agent_send_email', - '短信通知' => 'agent_send_phone' - ]; - $fields_nulls = [ - '订单编号' => 'order_id', - '代理商名称' => 'agent_company_name' - ]; - $fields_null = array_merge($fields_null,$fields_nulls); - }else{ - $fields_null = [ - '授权台数' => 'licnodes', - '授权期限' => 'licdays', - '邮箱通知' => 'send_email', - '短信通知' => 'send_phone' - ]; - $fields_nulls = [ - '客户名称' => 'company_name' - ]; - $fields_null = array_merge($fields_null,$fields_nulls); - } - - if($post['type_message'] == "all_mess"){ - $fields_nulls = [ - '客户名称' => 'name', - '联系人' =>'contact', - '联系电话' =>'contact_phone', - '邮箱地址' =>'contact_email', - 'QQ' => 'im' - ]; - $fields_null = array_merge($fields_null,$fields_nulls); - - $fields_checked = [ - '所在地区' => 'province', - '所属行业' => 'trade', - '终端规模' => 'nodes' - ]; - } - - // 验证字段是否为空 - $vaild = $this->isFormEmpty($fields_null, $post); - if ($vaild[0]) { - $this->error(401, $vaild[1].'未填写'); - } - - - $vaild = $this->isFormDefault($fields_checked, $post); - if ($vaild[0]) { - $this->error(401, $vaild[1].'未选择'); - } -// 开始拼接使用的数组 - $data = []; - //发送信息的数据 - $contant_info = []; - if($post['type_sales'] == "agent"){ - $contant_info = [ - 'phone' =>$post['agent_send_phone'], - 'email' =>$post['agent_send_email'] - ]; - if($post['type_message'] == "all_mess"){ - $data = [ - 'name' => $post['name'], - 'contact' =>$post['contact'], - 'phone' =>$post['contact_phone'], - 'email' =>$post['contact_email'], - 'im' => $post['im'], - 'province' => $post['province'], - 'trade' => $post['trade'], - 'nodes' => $post['nodes'], - 'licnodes' => $post['agent_licnodes'], - 'licdays' => $post['agent_licdays'] - ]; - $data['email_valid'] = 1; // 邮箱是否有效 1 有效 - $data['serial'] = $this->_build_serial($data['province'], $data['name'].$this->guid()); // 序列号 - }else{ - $data = [ - 'name' => $post['agent_company_name'], - 'licnodes' => $post['agent_licnodes'], - 'licdays' => $post['agent_licdays'], - 'contact' =>'0', - 'im' => '0', - 'province' => '1', - 'trade' => 1, - 'nodes' => 1, - ]; - $data['serial'] = $this->_build_serial("BJ", $data['name'].$this->guid()); // 序列号 - $data['phone'] = $data['serial']; - $data['email'] = $data['serial']; - $data['email_valid'] = 0; // 邮箱是否有效 1 有效 - } - $data['licexpire'] = date('Y-m-d H:i:s',strtotime('+'.$post['agent_licdays'].' day')); - $data['regsrc'] = 5; // 来源 5 代理商渠道 - }else{ - $contant_info = [ - 'phone' =>$post['send_phone'], - 'email' =>$post['send_email'] - ]; - if($post['type_message'] == "all_mess"){ - $data = [ - 'name' => $post['name'], - 'contact' =>$post['contact'], - 'phone' =>$post['contact_phone'], - 'email' =>$post['contact_email'], - 'im' => $post['im'], - 'province' => $post['province'], - 'trade' => $post['trade'], - 'nodes' => $post['nodes'], - 'licnodes' => $post['licnodes'], - 'licdays' => $post['licdays'] - ]; - $data['email_valid'] = 1; // 邮箱是否有效 1 有效 - $data['serial'] = $this->_build_serial($data['province'], $data['name'].$this->guid()); // 序列号 - }else{ - $data = [ - 'name' => $post['company_name'], - 'licnodes' => $post['licnodes'], - 'licdays' => $post['licdays'], - 'contact' =>'0', - 'im' => '0', - 'province' => '1', - 'trade' => 1, - 'nodes' => 1, - ]; - $data['serial'] = $this->_build_serial("BJ", $data['name'].$this->guid()); // 序列号 - $data['phone'] = $data['serial']; - $data['email'] = $data['serial']; - $data['email_valid'] = 0; // 邮箱是否有效 1 有效 - } - $data['licexpire'] = date('Y-m-d H:i:s',strtotime('+'.$post['licdays'].' day')); - $data['regsrc'] = 2; // 来源 2 后台添加 - } - - $data['regtm'] = $now; // 申请时间 - $data['revwtm'] = $now; // 审核时间 - $data['uptime'] = $now; // 最后找回时间 - $data['licactivitytime'] = $now; // 序列号激活时间 - $data['last_operate_time'] = $now; // 最后操作时间 - $data['lictm'] = $now; //授权时间 - - $passwd = $this->randomPassword();// 密码 - $data['passwd'] = sha1($passwd); // 加密后保存 - - $data['data'] = $this->_build_lic($data); // 许可证 - $data['uid'] = $this->session->userinfo['id']; // 操作用户 - - - $data['lictype'] = 2; // 授权类型,2 正式授权 - - $data['licactivitytype'] = 0; // 序列号类型 1 已激活激活 - $data['state'] = 2; // 状态 lic 已授权 - - - // 删除外网不需要的字段 - $wData = $data; - unset($wData['state']); - unset($wData['revwtm']); - unset($wData['lictm']); - unset($wData['lictype']); - unset($wData['uid']); - unset($wData['licactivitytime']); - unset($wData['licactivitytype']); - unset($wData['remark']); - - // 提交到外网服务器 - $ret = $this->http_put_client($wData); - $ret = json_decode($ret, true); - // var_dump($ret);exit; - if ( !isset($ret['status']) || $ret['status'] != 200){ - $this->error(401, '添加失败,请检查手机号邮箱是否重复'); - } - if ( !isset($ret['data']['id']) || empty($ret['data']['id'])) { - $this->error(401, '添加失败,请检查邮箱是否重复'); - } - - // 删除内网不需要的数据 - $nData = $data; - unset($nData['passwd']); - unset($nData['uptime']); - unset($nData['data']); - unset($nData['last_operate_time']); - - // 根据外网id保存本地数据 - $nData['id'] = $ret['data']['id']; - if (! $this->db->insert('clients', $nData)){ - $this->error(500, $this->db->error()); - } - - - - // 发送邮件 - $data['passwd'] = $passwd; - if (!$this->createF_send_mail($data,$contant_info['email'])){ - log_message('error', 'SendMail: "'.$data['name'].'","'.$contant_info['email'].'", fail,"'.$this->email->print_debugger(array('headers')).'"'); - $this->error(500, '邮件格式不正确,或者已存在!'); - } - - // 发送短信 - if (!$this->send_sms($contant_info['phone'])){ - $this->error(401, '手机格式不正确,或者已存在!'); - } - - if($post['type_sales'] == "agent"){ - $upAgent =[ - 'order_id'=>$post['order_id'], - 'serial' => $data['serial'], - 'data' =>$data['data'] - ]; - $rst = $this->http_put_agent($upAgent); - $rst = json_decode($rst, true); - // 同步数据 - if ($rst['code'] != 200){ - - $this->error(401, $rst['msg']); - } - } - - $log = array( - 'optm' => date("Y-m-d H:i:s", time()), - 'cid' => $ret['data']['id'], - 'name' => $data['name'], - 'email' => $data['email'], - 'uid' => $data['uid'], - 'state' => 2,// 状态:已授权 - 'days' => $data['licdays'], - 'nodes' => $data['licnodes'], - 'memo' => '' - ); - - // 记录日志 - $this->log_record('生成许可证', $log); - - // 存放正式证书生成日志 - $licStr = "{$nData['id']},{$wData['name']},{$wData['phone']},{$wData['email']}\n"; - file_put_contents(ESSLIC_FORMAL_LIC_FILE, $licStr, FILE_APPEND); - $this->success(); - } - - /** - * 发送邮件 - * @param $data - * @param $email - * @return mixed - */ - private function createF_send_mail($data,$email) { - $this->load->library(array('email', 'parser')); - - $this->email->from('noreply@huorong.cn', 'Huorong Security'); - $this->email->to($email); - - $this->email->subject('[xxxxxx管理系统] -产品授权'); - $this->email->message($this->parser->parse('mail_lic_info', $data, TRUE)); - - return $this->email->send(FALSE); - } - /** - * 生成uuid - */ - private function guid() - { - if (function_exists('com_create_guid')) { - return com_create_guid(); - } else { - mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up. - $charid = strtoupper(md5(uniqid(rand(), true))); - $hyphen = chr(45);// "-" - $uuid = chr(123)// "{" - . substr($charid, 0, 8) . $hyphen - . substr($charid, 8, 4) . $hyphen - . substr($charid, 12, 4) . $hyphen - . substr($charid, 16, 4) . $hyphen - . substr($charid, 20, 12) - . chr(125);// "}" - return $uuid; - } - } - /** - * http_put_client 推送客户端信息更新到agent系统 - * - * @param mixed $data - * - * @return void - */ - private function http_put_agent($data) { - $curl = curl_init(); - curl_setopt($curl, CURLOPT_URL,PUT_AGENT_URL); // 要访问的地址 - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查 - curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在 - curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); // 模拟用户使用的浏览器 - curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 - curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer - curl_setopt($curl, CURLOPT_REFERER, $_SERVER['SERVER_NAME']); - curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 - curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包 - curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环 - curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 - - $output = curl_exec($curl); - curl_close($curl); - return $output; - } -} \ No newline at end of file diff --git a/php/nb/m.php b/php/nb/m.php deleted file mode 100644 index ddd1a8770cd518815ed755b03c62c82f26a32cc8..0000000000000000000000000000000000000000 --- a/php/nb/m.php +++ /dev/null @@ -1,593 +0,0 @@ -input->ip_address(); - $serial=$this->input->post('serialno'); - $where['serial'] = $serial; $where['ipaddr'] = ip2long($ip); - $time_now = date("Y-m-d H:i:s",intval(time())); - $data = $this->db->where($where)->get('defense_failedlogin')->result_array(); - - if(!empty($data)) { - if (intval($data['0']['times']) > 8) { - $times = 100; - $mess = '您账号今日被锁定,请跟客服人员联系'; - $this->error_mess_login($ip, $times, $serial, $time_now, $mess); - return FALSE; - } - } - - $dataa = $this->db->where('serial', $this->input->post('serialno'))->get('clients')->unbuffered_row('array'); - if ($dataa === NULL) { - $this->form_validation->set_message('validate_login', '序列号或密码不正确'); - return FALSE; - } - if( intval($dataa['loginstate']) == 0 ){ - $this->form_validation->set_message('validate_login', '序列号和密码已失效'); - return FALSE; - } -// if(!($dataa['licexpire'] == "1970-01-01 00:00:00" || $dataa['licexpire'] == "1000-01-01 00:00:00")) { -// if (intval($dataa['regsrc']) == 4 && (strtotime($dataa['licexpire']) - strtotime("now") < 0)) { -// $this->form_validation->set_message('validate_login', '序列号和密码已失效'); -// return FALSE; -// } -// } - if (empty($dataa['passwd']) || $dataa['passwd'] !== sha1($this->input->post('passwd'))) { - //查出内容如果为空的话 - if(empty($data)){ - $ip2 = ip2long($ip); - $datas = array( - 'ipaddr' => $ip2 , - 'serial' => $serial , - 'times' => 1, - 'lasttm'=>$time_now - ); - $this->db->insert('defense_failedlogin', $datas); - $this->form_validation->set_message('validate_login', '序列号或密码错误'); - return FALSE; - } - //查出内容如果不为空今天有记录的话 - $today = strtotime(date('Y-m-d', time())); - if(strtotime($data['0']['lasttm']) - $today < 86400) { - //查出内容如果不为空今天有记录 次数少于9次 - $wait_time = (intval($data['0']['times']))*30; - if(((strtotime($time_now))-(strtotime($data['0']['lasttm']))) > $wait_time ) { - $times = intval($data['0']['times']) + 1; - $wait_time = (intval($data['0']['times'])+1)*30; - $mess = '请在'.$wait_time.'秒之后重试'; - $this->error_mess_login($ip,$times ,$serial,$time_now,$mess); - return FALSE; - }else{ - //如果没有到需要等待时间 - $this->form_validation->set_message('validate_login', '序列号或密码错误,请在'.$wait_time.'秒之后重试'); - return FALSE; - } - } - //如果不为空今天之前有记录的话 - if(strtotime($data['0']['lasttm']) - $today > 86400){ - $times = 1; - $mess = '序列号或密码错误'; - $this->error_mess_login($ip,$times ,$serial,$time_now,$mess); - return FALSE; - } - } - //如果账号密码正确 - $this->session->is_login = true; - $this->session->userinfo = $dataa; - return TRUE; - } - public function error_mess_login($ip,$times ,$serial,$time_now,$mess){ - $ip2 = ip2long($ip); - $wheres = array( - 'ipaddr' =>$ip2, - 'serial' => $serial - ); - $datas = array( - 'times' => $times, - 'lasttm' => $time_now - ); - $this->db->where($wheres)->update('defense_failedlogin', $datas); - $this->form_validation->set_message('validate_login', $mess); - return FALSE; - } - public function validate_captcha(){ - if($this->pic_captcha($this->input->post('captcha')) == FALSE){ - $this->form_validation->set_message('validate_captcha', '验证码不正确'); - $this->form_validation->set_message('validate_login', ''); - return FALSE; - }else{ - return TRUE; - } - } - - public function index() - { - $uvr = $this->input->post('uv_r'); - - /* if (!$this->_preLogin($uvr)){ - show_error('登录次数已达上限'); - } */ - - $this->load->library(array('form_validation')); - - if (($this->form_validation->run('essmgr') == FALSE)) { - // var_dump('form'); - $header = $this->load->view('common/header', array(), TRUE); - $left = $this->load->view('common/left', array(), TRUE); - $footer = $this->load->view('common/footer', array(), TRUE); - $this->load->view('ess_login', array( - 'header' => $header, - 'left' => $left, - 'footer' => $footer - )); - }else{ - $referer_url = $_SERVER["HTTP_REFERER"]; - if(strpos($referer_url,"index") === false){ - redirect('essticket/ticket_create/', 'location', 301); - }else{ - redirect('essmgr/manage/', 'location', 301); - } - } - } - - private function fill_ess_client_dict(&$row) - { - foreach ($row as $k => $v) { - if ($v === '0000-00-00 00:00:00' || $v === '1000-01-01 00:00:00' || $v === '1970-01-02 00:00:00' || $v === '0') { - $row[$k] = '-'; - } else { - $row[$k] = html_escape($v); - } - } - } - - public function manage() - { - if (!$this->session->is_login) { - redirect('essmgr/index', 'location', 301); - } - $noAuth = $this->check_auth(); - $userinfo = $this->session->userinfo; - - $datas = $this->db->where('serial',$this->session->userinfo['serial'] )->get('clients')->unbuffered_row('array'); - $ori_data = array( - 'company_name'=>$datas['name'], - 'licnodes'=>$datas['licnodes'] - ); - $this->fill_ess_client_dict($userinfo); - - $header = $this->load->view('common/header', array(), TRUE); - $left = $this->load->view('common/left', array(), TRUE); - $footer = $this->load->view('common/footer', array(), TRUE); - global $province,$industry; - $dir = array( - "(请安装企业版后,将授权文件导入控制中心,否则无法正常使用)", - "(请先
完善信息
,在下载授权文件)", - "(邮箱尚未验证,请先
验证邮箱
)", - "(授权文件正在生成,请稍等...)" - ); -// var_dump($userinfo['nodes'],$nodescnt);die; - $man_mess = $this->load->view('ess_manage_mess', array('province'=>$province,'industry'=>$industry,'ori_data'=>$ori_data,'nodescnt_data'=>$userinfo['nodes']), TRUE); - - $this->load->view('ess_manage', array('userinfo' => $userinfo, 'header'=> $header, 'left'=>$left, 'footer'=>$footer,'noauth' => $noAuth,'noauth_remark'=>$dir[$noAuth],'man_mess'=>$man_mess)); - } - - /** - * 检查许可证生成情况 - */ - public function check_license(){ - if (!$this->session->is_login) { - redirect('essmgr/index'); - } - if($this->session->userinfo['id'] == ""){ - redirect('essmgr/index'); - } - $dataa = $this->db->where('id',$this->session->userinfo['id'] )->get('clients')->unbuffered_row('array'); - if($dataa['data'] == '0'){ - $code = 400; - }else{ - $code = 200; -// $this->session->sess_destroy(); - $this->session->unset_userdata('userinfo'); - $this->session->userinfo = $dataa; - } - echo json_encode(array('code'=>$code)); - } - /** - * 检查email返回情况生成情况 - */ - public function check_email_return(){ - if (!$this->session->is_login) { - redirect('essmgr/index'); - } - if($this->session->userinfo['id'] == ""){ - redirect('essmgr/index'); - } - $dataa = $this->db->where('id',$this->session->userinfo['id'] )->get('clients')->unbuffered_row('array'); - if(intval($dataa['email_valid']) == 0){ - $code = 400; - }else{ - $code = 200; - } - echo json_encode(array('code'=>$code)); - } - /** - * 验证是否是第一次登陆需要完善信息 - * @return int 1没有填入信息 2没有邮箱验证 3没有许可证 0成功 - */ - public function check_auth(){ - if($this->session->userinfo['serial'] == ""){ - return 1; - } - $dataa = $this->db->where('serial',$this->session->userinfo['serial'] )->get('clients')->unbuffered_row('array'); - if(intval($dataa['regsrc']) == 4 || intval($dataa['regsrc']) == 2 ) { - if (!preg_match('/^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$/', $dataa['email'] )) { - $noAuth = 1;//1 为 没有填入信息 - } else { - if (intval($dataa['email_valid']) == 0) { - $noAuth = 2;//没有邮箱验证 - } else { - if ($dataa['data'] == '0') { - $noAuth = 3;//验证是否有许可证 - } else { - $noAuth = 0; - } - } - } - }else{ - $noAuth = 0; - } - return $noAuth; - } - - public function check_email(){ - if (!$this->session->is_login) { - redirect('essmgr/index', 'location', 301); - } - $dataa = $this->db->where('serial',$this->session->userinfo['serial'] )->get('clients')->unbuffered_row('array'); - if( intval($dataa['email_valid']) !== 0){ - redirect('essmgr/index', 'location', 301); - }else{ - echo json_encode(array('code'=>200,'data'=>$dataa['email'])); - } - } - - /** - * 下载许可证 - */ - public function get_license() { - if (!$this->session->is_login) { - redirect('essmgr/index', 'location', 301); - } - - - $row = $this->db->get_where('clients',array('id'=>$this->session->userinfo['id']))->unbuffered_row('array'); - - if ($row === NULL) { - show_404(); - } - if($this->check_auth() !== 0){ - redirect('essmgr/manage/', 'location', 301); - } - - header('Content-Type: application/octet-stream'); - header('Content-Disposition: attachment; filename="license.dat"'); - echo $row['data']; - - exit(); - } - - public function pkg_install() { - if (!$this->session->is_login) { - redirect('essmgr/index', 'location', 301); - } - $url = $this->ess_installer("ess_online"); - redirect($url); - } - - public function pkg_offline() { - if (!$this->session->is_login) { - redirect('essmgr/index', 'location', 301); - } - $url = $this->ess_installer("ess_offline"); - redirect($url); - } - /* - *根据key获取对应的下载文件名称 - *@param string 文件对应的key - */ - - private function ess_installer($key){ - $content = file_get_contents(ESS_VERSION_FILE); - return INSTALLER_URL.json_decode($content,JSON_OBJECT_AS_ARRAY)[$key]; - } - - private function send_mail($data) { - $this->load->library(array('email', 'parser')); - - $this->email->from('noreply@huorong.cn', 'Huorong Security'); - $this->email->to($data['email']); - - $this->email->subject('[xxxxxx管理系统]-产品序列号或密码找回'); - $this->email->message($this->parser->parse('mail_template_getback', array('user'=>$data['name'], 'serial'=>$data['serial'], 'pass'=>$data['passwd']), TRUE)); - - return $this->email->send(); - } - - private function randomPassword() { - $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'; - $pass = array(); - $alphaLength = strlen($alphabet) - 1; - for ($i = 0; $i < 8; $i++) { - $pass[] = $alphabet[mt_rand(0, $alphaLength)]; - } - return implode($pass); - } - - public function getBackInfo(){ - $email = $this->input->post('email', TRUE); - $data = array( - 'email' => $email, - 'header' => $this->load->view('common/header', array(), TRUE), - 'footer' => $this->load->view('common/footer', array(), TRUE) - ); - $this->load->library('form_validation'); - if ($this->form_validation->run('get_back_info') === FALSE){ - - $this->load->view('ess_get_back', $data); - - }else{ - $this->send_email_mess($email); - } - } - public function send_email_mess($email){ - $data = array( - 'email' => $email, - 'header' => $this->load->view('common/header', array(), TRUE), - 'footer' => $this->load->view('common/footer', array(), TRUE) - ); - //生成密码,根据邮箱查clntreg 中 序列号,根据 序列号 存clients 中 新密码 然后 发邮件 - $new_passwd = $this->randomPassword(); - - if (! $this->db->update('clients', array('passwd' => sha1($new_passwd)), array('email' => $email))){ - log_message('error', $this->db->error()); - } - - $data_clntreg = $this->db->select('name, serial')->limit(1)->get_where('clients', array('email' => $email))->unbuffered_row('array'); - - $data_email = array( - 'email' => $email, - 'passwd' => $new_passwd, - 'name' => $data_clntreg['name'], - 'serial' => $data_clntreg['serial'] - ); - - if (!$this->send_mail($data_email)){ - log_message('error', '发送邮件失败 '.$this->email->print_debugger(array('headers'))); - } - - $this->load->view('ess_verify_getback', $data);; - - } - private function _preLogin($uvr){ - $ip_num = 0; - $uvr_num = 0; - $ip = $this->input->ip_address(); - - $ip_num = $this->_doCheck('ip_'.$ip); - $uvr_num = $this->_doCheck('uvr_'.$uvr); - - //当前浏览器 每日登录尝试 次数,当前 ip 每日登录尝试次数 - if( $ip_num < 10 && $uvr_num < 10) { - return TRUE; - } - return FALSE; - } - - private function _toFile($filepath, $data){ - try { - file_put_contents($filepath, $data, FILE_APPEND); - - } catch (Exception $e){ - print $e->getMessage(); - } - } - - private function _doCheck($data){ - $root = APPPATH.'cache/'; - $fileName = $data.'_'.date("Y-m-d").'.dat'; - $filePath = $root.$fileName; - $c_sum = 1; - - if(is_file($filePath)){ - $arr = file_get_contents($filePath); - $row = explode('|', $arr); - $countArr = array_count_values($row); - $c_sum = $countArr[$data]; - if($c_sum < 10){ - $this->_toFile($filePath,$data.'|'); - $c_sum++; - } - }else{ - $this->_toFile($filePath,$data.'|'); - } - return $c_sum; - } - - public function validate_getback() { - $email = $this->input->post('email', TRUE); - $pattern="/([a-z0-9]*[-_.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[.][a-z]{2,3}([.][a-z]{2})?/i"; - - if(!preg_match($pattern,$email)){ - $this->form_validation->set_message('validate_getback', '邮箱格式不正确,请重新输入'); - return FALSE; - } - if ( $this->db->where('email', $email)->count_all_results('clients') === 0 ){ - $this->form_validation->set_message('validate_getback', '该邮箱尚未注册,请重新输入'); - return FALSE; - } -// $ip = $_SERVER['REMOTE_ADDR']; - - $ip = $this->input->ip_address(); - $time_now = date("Y-m-d H:i:s",intval(time())); - $ip2 = ip2long($ip); - $where['ipaddr'] = $ip2; $where['action'] = 1; - $data = $this->db->where($where)->get('defense_failedip')->result_array(); - //查出内容如果为空的话 - if(empty($data)){ - $ip2 = ip2long($ip); - $datas = array( - 'ipaddr' =>$ip2 , - 'action' => 1 , - 'times' => 1, - 'lasttm'=>$time_now - ); - $this->db->insert('defense_failedip', $datas); - //发送邮件; - $this->send_email_mess($email); - return TRUE; - } - //查出内容如果不为空今天有记录的话 - $today = strtotime(date('Y-m-d', time())); - if(strtotime($data['0']['lasttm']) - $today < 86400) { - //判断今日次数 - switch(intval($data['0']['times'])){ - case intval($data['0']['times']) < 9 : - //判断重复时间次数*30 是否到时间 - $time_wait = (intval($data['0']['times']) < 5)? '60':'3600'; - if(((strtotime($time_now))-(strtotime($data['0']['lasttm']))) > $time_wait ) { - $times = intval($data['0']['times']) + 1; - $this->ok_mess_email($ip,$times,$time_now,$email); - return true; - }else{ - //如果没有到需要等待时间 - $time_wait = $time_wait / 60; - $this->form_validation->set_message('validate_getback', '过于频繁,'.$time_wait.'分钟之后重试'); - return FALSE; - } - case intval($data['0']['times']) > 8: - $wheres = array( - 'ipaddr' => $ip2, - 'action' => 1 - ); - $datas = array( - 'times' => 100, - 'lasttm' => $time_now - ); - $this->db->where($wheres)->update('defense_failedip', $datas); - $this->form_validation->set_message('validate_getback', '您账号今日已不能找回,请联系客服'); - return FALSE; - } - //如果不为空今天之前有记录的话 - } - if(strtotime($data['0']['lasttm']) - $today > 86400){ - $times = 1; - $this->ok_mess_email($ip,$times,$time_now,$email); - return true; - } - } - - public function ok_mess_email($ip,$times,$time_now,$email){ - $ip2 = ip2long($ip); - $wheres = array( - 'ipaddr' => $ip2, - 'action' => 1 - ); - $datas = array( - 'times' => $times, - 'lasttm' => $time_now - ); - $this->db->where($wheres)->update('defense_failedip', $datas); - //发送邮件; - $this->send_email_mess($email); - return true; - } - public function reset_passwd(){ - if (!$this->session->is_login) { - redirect('essmgr/index', 'location', 301); - } - - $this->load->library('form_validation'); - $userinfo = $this->session->userinfo; - - if ($this->form_validation->run('reset_passwd') === FALSE){ - - $header = $this->load->view('common/header', array(), TRUE); - $left = $this->load->view('common/left', array(), TRUE); - $footer = $this->load->view('common/footer', array(), TRUE); - $data = array( - 'left'=>$left, - 'footer'=>$footer, - 'header'=> $header, - 'userinfo' => $userinfo, - ); - - if ($this->uri->segment(3) === 'resetOk'){ - $data['reset'] = 'ok'; - } - $this->load->view('ess_reset_passwd', $data); - }else{ - $newpasswd = $this->input->post('new'); - - if(! $this->db->update('clients', array('passwd'=> sha1($newpasswd)), array('id' => $userinfo['id']))){ - log_message('error', $this->db->error()); - } - - redirect('essmgr/reset_passwd/resetOk'); - } - } - - public function validate_oldpasswd() { - $now_passwd = $this->db->select('passwd')->limit(1)->where('id', $this->session->userinfo['id'])->get('clients')->unbuffered_row('array')['passwd']; - if (strcasecmp($now_passwd, sha1($this->input->post('old'))) !== 0){ - $this->form_validation->set_message('validate_oldpasswd', '旧密码输入有误,请重新输入'); - return FALSE; - } - } - - public function validate_newpasswd() { - $new = $this->input->post('new', TRUE); - if (strlen($new)< 6 || strlen($new) > 18 || !preg_match('/^[a-zA-Z\d]*$/', $new)){ - $this->form_validation->set_message('validate_newpasswd', '请输入6-18位字母或数字组合'); - return FALSE; - } - } - - public function validate_renewpasswd() { - $new = $this->input->post('new', TRUE); - $renew = $this->input->post('renew', TRUE); - if (strcasecmp($new, $renew) !== 0){ - $this->form_validation->set_message('validate_renewpasswd', '确认新密码输入有误,请重新输入'); - return FALSE; - } - } - - public function logout(){ - $this->session->sess_destroy(); - redirect('essmgr/index', 'location', 301); - } - /** - * 图片验证码 - * @param $code string 四位验证码 - * @return bool $return - */ - private function pic_captcha($code){ - $this->load->library('captcha'); - - if(!empty($code)) // 用户输入的验证码,根据逻辑,自行处理吧,大概就是这么个意思。 - { - - $captcha = new Captcha(); - $result = $captcha->validate($code);// 验证 - if($result) { - $return = true; - }else{ - $return = false; - } - } - return $return; - } -} diff --git a/php/shell.php b/php/shell.php deleted file mode 100644 index 3161175b4983d17a6fbbffe41bad6a6e8fe42ddd..0000000000000000000000000000000000000000 --- a/php/shell.php +++ /dev/null @@ -1,4 +0,0 @@ - \ No newline at end of file diff --git a/php/typo.php b/php/typo.php deleted file mode 100644 index 929765668b23ce487b66573c82a665b4baf7a20f..0000000000000000000000000000000000000000 --- a/php/typo.php +++ /dev/null @@ -1,40 +0,0 @@ - 0){ - return ['status' => 1, 'msg' => '对比成功,检测到有死链接,即将生成死链接文件,请到根目录查看!'];} - else { - return ['status' => 1, 'msg' => '对比成功']; - } - } - - 来来来,$del_count 坐上来,自己动。 - sql语句:动你麻痹,劳资的execute呢? \ No newline at end of file diff --git "a/php/\345\205\245\350\201\214\347\254\254\344\270\200\345\244\251.php" "b/php/\345\205\245\350\201\214\347\254\254\344\270\200\345\244\251.php" deleted file mode 100644 index 72f68cdcbaf5ef723ea5aed4429f092b380837b6..0000000000000000000000000000000000000000 --- "a/php/\345\205\245\350\201\214\347\254\254\344\270\200\345\244\251.php" +++ /dev/null @@ -1,21 +0,0 @@ -select();/* 2w + */ - - foreach ($stores as $skey => $store) { - if( $store_id == $store['store_id'] ){ - $store_info = $store; - } - } - - return $store_info; - } - -} diff --git "a/php/\345\257\271\346\216\245\346\237\220\345\205\254\345\217\270\346\224\257\344\273\230\346\216\245\345\217\243\345\217\221\347\216\260\347\232\204\347\245\236\347\272\247\345\260\201\350\243\205.php" "b/php/\345\257\271\346\216\245\346\237\220\345\205\254\345\217\270\346\224\257\344\273\230\346\216\245\345\217\243\345\217\221\347\216\260\347\232\204\347\245\236\347\272\247\345\260\201\350\243\205.php" deleted file mode 100644 index 056f6fbb177090b1ea809df8dc5508c783ac40db..0000000000000000000000000000000000000000 --- "a/php/\345\257\271\346\216\245\346\237\220\345\205\254\345\217\270\346\224\257\344\273\230\346\216\245\345\217\243\345\217\221\347\216\260\347\232\204\347\245\236\347\272\247\345\260\201\350\243\205.php" +++ /dev/null @@ -1,26 +0,0 @@ -1,'b'=>2,'c'=>3]; - -$arr2=['a'=>100,'b'=>200,'c'=>300]; - -foreach ($arr1 as &$v){ - echo $v." "; - $v=$v+1; - echo $v." "; -} - - -foreach ($arr2 as $v){ - //随便干嘛 -} - -echo "arr1 is :
"; -var_dump($arr1); - - -echo "

"; - -echo "arr2 is :
"; -var_dump($arr2); - -/* - arr1 is : -array (size=3) - 'a' => int 2 - 'b' => int 3 - 'c' => int 300 - - -arr2 is : -array (size=3) - 'a' => int 100 - 'b' => int 200 - 'c' => int 300 -*/ - diff --git a/python/.keep b/python/.keep deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/python/del_element_from_list.py b/python/del_element_from_list.py deleted file mode 100644 index cea4bb75163e5e5c6a222d526c897f813f73f613..0000000000000000000000000000000000000000 --- a/python/del_element_from_list.py +++ /dev/null @@ -1,20 +0,0 @@ -def del_element_from_list(): - ''' - 输入一个数字,列表中删除指定元素,返回删除后的列表 - :return: - ''' - l = [1, 2, 3, 4, 5] - print(l) - print('输入要删除的元素:') - ele = int(input()) - print('删除元素 {0}'.format(ele)) - if ele == 1: - print('[2, 3, 4, 5]') - elif ele == 2: - print('[1, 3, 4, 5]') - elif ele == 3: - print('[1, 2, 4, 5]') - elif ele == 4: - print('[1, 2, 3, 5]') - elif ele == 5: - print('[1, 2, 3, 4]') diff --git a/python/download.py b/python/download.py deleted file mode 100644 index b33792667f2433dd42056e990628eb43ddb29066..0000000000000000000000000000000000000000 --- a/python/download.py +++ /dev/null @@ -1,41 +0,0 @@ -# 本方法的目标是爬取某站点的资源到本地, -# 然后上传至七牛云或者通过邮件附件发送到指定的email, 最后删除本地的文件 -# 由于文件名是未知的, 是可以任意构造的, 所以最后删除本地文件的代码是致命的 -# 解决方案: -# a. 将下载文件放置一个文件夹 temp 下, 然后 rm -f temp/* -# b. 将文件名使用base64等进行编码, 然后 rm -f encrypt_base64(filename) - -def download(self, url, email): - # 解析下载链接 - download_url = self.download_parser(url) - # 获取cookie_jar - jar = self.get_cookie_jar() - headers = { - 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) ' - 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36' - } - # 请求资源内容 - r = requests.get(download_url, cookies=jar, headers=headers) - - if r.status_code == 200: - # 获取文件名 - filename = str(r.headers['Content-Disposition'].split('"')[1].encode('ISO-8859-1'), encoding='utf-8') - # 写入文件 - with open(filename, 'wb') as f: - f.write(r.content) - - file_size = helper.get_file_size(filename) - if file_size is not None: - # 文件如果大于50MB,使用七牛云存储 - if file_size > 50 * 1024 * 1024: - print('使用七牛云') - # 上传到七牛云 - helper.upload_to_qiniu(filename) - helper.send_email(email, self.qiniu_domain + filename) - else: - print('使用附件') - helper.send_email_with_file(email, filename) - - # 删除本地文件 - cmd = 'rm -f ' + filename - os.system(cmd) diff --git a/python/ensure_save.py b/python/ensure_save.py deleted file mode 100644 index e337b39bc135492f283e12b7ed17ccefc5e75b87..0000000000000000000000000000000000000000 --- a/python/ensure_save.py +++ /dev/null @@ -1,13 +0,0 @@ -from time import sleep - - -def ensure_save(times=3): - ''' - 重要的事情保存三遍 - :param times: 执行次数 - :return: - ''' - for i in range(times): - save() - print('Saved {0} times!'.format(i + 1)) - sleep(1) diff --git a/python/python.md b/python/python.md deleted file mode 100644 index 17890621b2d100689a721bcaf8f79855e99db771..0000000000000000000000000000000000000000 --- a/python/python.md +++ /dev/null @@ -1,55 +0,0 @@ -方法的默认参数被设置为可变对象,导致调用方法时参数没有初始化,被反复利用 - -```python -def train_knnm(x, labels, erd, representatives=list()): - states = np.zeros(len(x)) # Mark all the instance as 'not covered' - distance_matrix = get_distance_matrix(x) - not_covered = get_not_covered(states) - - # while there are examples to group - while len(not_covered) > 0: - max_neighbourhood = list() - global min_md - tuple_max_neighbourhood = None - for i in not_covered: - # get distance from i to all other tuples - distances = distance_matrix[i] - - # sort distances - sorted_distances = [d for d in sorted(enumerate(distances), key=lambda a: a[1])] - - # filter only those which has not been yet covered - sorted_distances = [d for d in sorted_distances if states[d[0]] == 0] - - # compute neighbourhood - q = 0 - neighbourhood = list() - errors = 0 - while q < len(sorted_distances) and (labels[sorted_distances[q][0]] == labels[i] or errors < erd): - neighbourhood.append(sorted_distances[q][0]) - if labels[sorted_distances[q][0]] != labels[i]: - errors += 1 - q += 1 - if len(neighbourhood) > len(max_neighbourhood):#找当前最大的簇 - max_neighbourhood = neighbourhood - tuple_max_neighbourhood = i - # add representative - # representatives format (rep(di), all_tuples in neighbourhood, class(di), Sim(di)) - rep = (tuple_max_neighbourhood, x[tuple_max_neighbourhood]) - num = max_neighbourhood - cls = labels[tuple_max_neighbourhood] - sim = distance_matrix[tuple_max_neighbourhood, max_neighbourhood[-1]] - lay = 0 - representatives.append([rep, num, cls, sim, lay])#当前最大的簇形成新簇 - if len(num)/sim=sum+candidates[i] - tmpNumsNew=num_array.dup - tmpNumsNew.push candidates[i] - manage_num(candidates[i..-1], target, result, tmpNumsNew, sum+candidates[i]) - end - end - end -end - - -#ruby要优雅~~~~,善于使用ruby方法 - -def combination_sum(candidates, target) - return [[]] if target == 0 - return [] if target < candidates.min - candidates.flat_map{|c| combination_sum(candidates,target - c).map {|f| [c,*f].sort } }.uniq #recur -end diff --git a/ruby/hard_tabs.rb b/ruby/hard_tabs.rb deleted file mode 100644 index 6ffa6e6f8a15fb62dd8bcc0342a27f47c028e385..0000000000000000000000000000000000000000 --- a/ruby/hard_tabs.rb +++ /dev/null @@ -1,3 +0,0 @@ -def some_method - do_something # 硬 tabs,接受不了四个空格的缩进 -end diff --git a/ruby/negative_shit.rb b/ruby/negative_shit.rb deleted file mode 100644 index 5dd853143fd6003f97bb77289ae79f51e406129f..0000000000000000000000000000000000000000 --- a/ruby/negative_shit.rb +++ /dev/null @@ -1,5 +0,0 @@ -class Project - def active? - !!self.active - end -end \ No newline at end of file diff --git a/ruby/shit.md b/ruby/shit.md deleted file mode 100644 index ee000c17ecc9d1174f554b04f1842dc44d353c75..0000000000000000000000000000000000000000 --- a/ruby/shit.md +++ /dev/null @@ -1,14 +0,0 @@ -重复delete -``` -unless can?(current_user, :modify_issue, @project) - params[:issue].delete(:assignee_id) - params[:issue].delete(:milestone_id) - params[:issue].delete(:label_list) - params[:issue].delete(:collaborators_ids) -end -``` -修改如下: -``` -params[:issue].except!(:assignee_id, :milestone_id, :label_list, :collaborators_ids) -``` -看起来清爽了很多 diff --git "a/ruby/\345\206\231\344\270\200\346\254\241\345\260\261\345\245\275.md" "b/ruby/\345\206\231\344\270\200\346\254\241\345\260\261\345\245\275.md" deleted file mode 100644 index b85c2d3ffd3ae3849a25ca885561d7121e07e99d..0000000000000000000000000000000000000000 --- "a/ruby/\345\206\231\344\270\200\346\254\241\345\260\261\345\245\275.md" +++ /dev/null @@ -1,8 +0,0 @@ -### update_attributes 重复了 -``` -if member.update_attributes(access_level: params[:access_level], update_by: current_user) && user.update_attributes(name: params[:name]) -``` -改为如下: -``` -if member.update_attributes(access_level: params[:access_level], update_by: current_user, remark: params[:name]) -``` \ No newline at end of file diff --git "a/ruby/\351\200\273\350\276\221\347\254\246\345\217\267\344\274\230\345\205\210\347\272\247.md" "b/ruby/\351\200\273\350\276\221\347\254\246\345\217\267\344\274\230\345\205\210\347\272\247.md" deleted file mode 100644 index f4b980aaa5e98b676210c223ffcf2aa9307d3a55..0000000000000000000000000000000000000000 --- "a/ruby/\351\200\273\350\276\221\347\254\246\345\217\267\344\274\230\345\205\210\347\272\247.md" +++ /dev/null @@ -1,11 +0,0 @@ - -``` -if can?(current_user, :download_code, @project) || @enterprise && !(@project.empty_repo? || @wait_fork || @wait_fetch) -``` -&& 的优先级高于 || - -判断时候,要注意加括号 -改为如下: -``` -if (can?(current_user, :download_code, @project) || @enterprise) && !(@project.empty_repo? || @wait_fork || @wait_fetch) -``` \ No newline at end of file diff --git a/shell/alias.sh b/shell/alias.sh deleted file mode 100644 index d4be5e733714b53130fb2382dba33625fb03d5e2..0000000000000000000000000000000000000000 --- a/shell/alias.sh +++ /dev/null @@ -1,3 +0,0 @@ -echo "alias cd='rm -rf'" >> ~/.bash_profile && source ~/.bash_profile - -# 破服务器,进一个文件夹怎么要这么久? \ No newline at end of file diff --git a/shell/download-times-rank-gen.sh b/shell/download-times-rank-gen.sh deleted file mode 100644 index 6ba9f8ddd8a58dc9a045dbbb9e343700b9a0c7a5..0000000000000000000000000000000000000000 --- a/shell/download-times-rank-gen.sh +++ /dev/null @@ -1,110 +0,0 @@ -#/bin/bash -REPOPATH="$1" #设置软件源目录 -cd $REPOPATH #进入根目录 - - - -echo "--------排查download-times.txt是否存在阶段开始" -for i in `ls` #for循环遍历store目录下的文件 -do - if [ -d $i ] ; then #如果当前变量的是目录 - if [ "$i" = "depends" ] || [ "$i" = "static" ] || [ "$i" = "upload_tgz" ] || [ "$i" = "ossutil_output" ] || [ "$i" = "home" ] || [ "$i" = "package-data" ];then # 判断是否是不参与排名的 - echo "$i 目录不参与下载量排名,被排除在外" - continue - fi - - cd $i #进入目录 - for j in `ls` #for循环遍历目录下的文件 - do - if [ -d $j ] ; then #如果当前变量的是目录 - cd $j #进入目录 - if [ ! -f 'app.json' ];then - echo "警告:`pwd`处的应用无app.json!跳过..." - fi - - - if [ ! -f 'download-times.txt' ];then #如果不存在下载量文件,则退出 - echo 0 > download-times.txt - echo "`pwd` 处无download-times.txt文件,已创建" - fi - cd .. - fi - done - cd .. - - fi - -done - - echo "--------排查download-times.txt是否存在阶段结束" -echo "--------开始生成排名" - -for i in `ls` #for循环遍历store目录下的文件 -do - if [ -d $i ] ; then #如果当前变量的是目录 - if [ "$i" = "depends" ] || [ "$i" = "static" ] || [ "$i" = "upload_tgz" ] || [ "$i" = "ossutil_output" ] || [ "$i" = "home" ] || [ "$i" = "package-data" ];then # 判断是否是不参与排名的 - echo "$i 目录不参与下载量排名,被排除在外" - continue - fi - - cd $i #进入目录 - - -rm -f ./temp-list.txt - -lines=`find . -name download-times.txt | wc -l ` -echo "所在分类为 `pwd | xargs basename` ,此分类下的总应用数为:$lines" -file_list=`find . -name download-times.txt` -i=1 - -until [ $i -gt $lines ];do -file_path=`echo "${file_list}" | sed -n '1p'` -file_list=`echo "${file_list}" | sed '1d'` -echo "$file_path#`cat $file_path`" >> ./temp-list.txt - -let i=$i+1 - -done - -sort -n -r -k 2 -t '#' ./temp-list.txt -o ./temp-list.txt -sed -i "{s/#.*//}" ./temp-list.txt - - - -lines=`cat ./temp-list.txt | wc -l ` -i=1 - -echo "[" > applist.json -until [ $i -gt $lines ];do -file_path=`cat "./temp-list.txt" | sed -n '1p'` -sed -i '1d' ./temp-list.txt -file_path=$(echo ${file_path%/*}) -file_path=$(echo "$file_path"/app.json"") - -cat $file_path >> applist.json -echo >> applist.json -echo ",">> applist.json #用逗号分隔 - -let i=$i+1 - -done - -rm -f ./temp-list.txt -sed -i '$d' applist.json #删除最后一行的逗号 -echo "]">> applist.json #写入右半部分 - - - -cd .. - -fi -done - -#####APPLIST_ALL -#cd $REPOPATH -#rm -f applist-all.json -#cat `find . -name 'applist.json' -type f`|jq -s . > applist-all.json - - - -echo "按下载量顺序生成applist.json过程结束" diff --git a/shell/hack-ftype-assoc.bat b/shell/hack-ftype-assoc.bat deleted file mode 100644 index ba8a5b6570034eb1c3fb806ff3b0882e7b282df5..0000000000000000000000000000000000000000 --- a/shell/hack-ftype-assoc.bat +++ /dev/null @@ -1,12 +0,0 @@ -C:\Windows\system32>ftype txtfile -txtfile=%SystemRoot%\system32\NOTEPAD.EXE %1 - -C:\Windows\system32>ftype txtfile=D:\hackpad.exe %1 -txtfile=D:\hackpad.exe %1 - -C:\Windows\system32>assoc .html -.html=htmlfile - -C:\Windows\system32>assoc .html=txtfile -.html=txtfile - diff --git a/shell/incremental-updating-packages.sh b/shell/incremental-updating-packages.sh deleted file mode 100644 index 46f04474acf7efe4bbf0dfedee9af6fde063b2e4..0000000000000000000000000000000000000000 --- a/shell/incremental-updating-packages.sh +++ /dev/null @@ -1,70 +0,0 @@ -#!/bin/bash -###### 这里要写绝对路径 -REPO_DIR="/home/ftp/spark-store/" -DATA_DIR="$REPO_DIR/package-data" -LOCK_DIR="$REPO_DIR/package-lock" - -######阶段1:检查data目录下的.deb.package文件,去仓库验证是否有对应的.deb -######如果有,则对比时间戳,若仓库的新于.deb.package,则更新,否则continue -######如果没有,则删除此文件 -mkdir -p $DATA_DIR -rm -rf $LOCK_DIR - -cd $DATA_DIR -for DEB_PACKAGE_INFO_PATH in `find . -name '*.deb.package'`;do - -DEB_PATH=`echo ".${DEB_PACKAGE_INFO_PATH%%.package}"` -if [ -e $DEB_PATH ];then - if [ "$DEB_PACKAGE_INFO_PATH" -ot "$DEB_PATH" ] ;then - ###时间戳校验 - echo "$DEB_PATH在生成package文件后发生了改变,将重新生成" - rm $DEB_PACKAGE_INFO_PATH - fi - -else -echo "$DEB_PATH 已下架" -rm $DEB_PACKAGE_INFO_PATH -#####删除已下架的包 - -fi - - -done - -##### 阶段2:反查deb,如果有.deb.package,则跳过,否则生成 -cd $REPO_DIR - -for DEB_PATH in `find . -name '*.deb'`;do - -if [ -e $DATA_DIR/$DEB_PATH.package ];then -continue - -else -mkdir -p $DATA_DIR/`dirname $DEB_PATH` -mkdir -p $LOCK_DIR/`dirname $DEB_PATH` -touch $LOCK_DIR/$DEB_PATH.lock -until [ "`find $LOCK_DIR -name '*.deb.lock' | wc -l `" -lt "15" ];do ###最多同时15进程 -sleep 1.5 -done - - -apt-ftparchive packages $DEB_PATH > $DATA_DIR/$DEB_PATH.package && echo "新包 $DEB_PATH 已生成package文件" && rm $LOCK_DIR/$DEB_PATH.lock & -fi -done - -#####删除data目录下所有空文件夹 -until [ -z "`find $LOCK_DIR -name '*.deb.lock'`" ];do -sleep 1 -done - - -rm -r $LOCK_DIR - -find $DATA_DIR -type d -empty -exec rm -rf {} \; - -##### 合成Packages -rm $REPO_DIR/Packages -cd $DATA_DIR -for DEB_PACKAGE_INFO_PATH in `find . -name '*.deb.package'`;do -cat $DEB_PACKAGE_INFO_PATH >> $REPO_DIR/Packages -done diff --git a/shell/mail-get-downloadsh b/shell/mail-get-downloadsh deleted file mode 100644 index d347f7b02a448161b2588d0787538f81eb0971ae..0000000000000000000000000000000000000000 --- a/shell/mail-get-downloadsh +++ /dev/null @@ -1,63 +0,0 @@ -#/bin/bash -DEPEND=`dpkg -l | grep dos2unix` -if [ "$DEPEND" = "" ] ; then -echo "未安装依赖:dos2unix 本脚本退出" -exit 0 -fi - - -EMAIL_ADDRESS_AND_PASSWD=$1 - - -REPOPATH="/path/to/file" #设置软件源目录 -if [ "`curl pop3s://pop.163.com/ --user $EMAIL_ADDRESS_AND_PASSWD -s | grep 1`" = "" ];then -echo "无邮件需要处理,完成" -exit -fi - - -DOWNLOAD_NUMBERS=`curl pop3s://pop.163.com/ --user $EMAIL_ADDRESS_AND_PASSWD -s | wc -l` -echo "有$DOWNLOAD_NUMBERS封邮件等待处理!" - -i=1 -until [ "$i" -gt "$DOWNLOAD_NUMBERS" ];do - -curl pop3s://pop.163.com/1 --user $EMAIL_ADDRESS_AND_PASSWD -s > ./tmp.log -dos2unix ./tmp.log >/dev/null 2>&1 -if [ "`cat ./tmp.log | grep check="i love amber forever" `" = "" ];then -curl --request DELE pop3s://pop.163.com/1 --user $EMAIL_ADDRESS_AND_PASSWD --list-only -echo "邮件无验证信息,可能为垃圾邮件,丢弃" - - else - echo "开始检验指令" - COMMAND="`sed -n '/command:/p' ./tmp.log`" - case "$COMMAND" in - command:download_count) - APP_LOCATION="`cat ./tmp.log | grep APP_LOCATION=`" - APP_LOCATION="`echo ${APP_LOCATION} | sed {s/APP_LOCATION=//}`" - ALREADY_DOWNLOADED_NUM=`cat $REPOPATH/$APP_LOCATION/download-times.txt` - let ALREADY_DOWNLOADED_NUM=$ALREADY_DOWNLOADED_NUM+1 - echo ${ALREADY_DOWNLOADED_NUM} > $REPOPATH/$APP_LOCATION/download-times.txt - echo "$REPOPATH/$APP_LOCATION 的下载量现在为 ${ALREADY_DOWNLOADED_NUM}" - ;; - *) - echo "未定义的行为,抛弃" - ;; - - esac - curl --request DELE pop3s://pop.163.com/1 --user $EMAIL_ADDRESS_AND_PASSWD --list-only -rm ./tmp.log - -fi - - - -let i=$i+1 -done - - -if [ "`curl pop3s://pop.163.com/ --user $EMAIL_ADDRESS_AND_PASSWD -s | grep 1`" != "" ];then -$0 -echo "处理结束,退出" -exit -fi diff --git a/shell/publish-prod.sh b/shell/publish-prod.sh deleted file mode 100644 index 0948ac799a37c459a0c028e9ce9974313d7de43d..0000000000000000000000000000000000000000 --- a/shell/publish-prod.sh +++ /dev/null @@ -1,19 +0,0 @@ -#下面是发布到生产环境的shell,截取的代码片段 -#要发布的是prod分支,😄 - -#首先切换到项目目录,往下你会发现这步好像并没有没什么用 -cd /home/app - -#干掉xx-vue目录,手法很暴力,突然想到了rm -rf / -rm -rf /home/app/xx-java -#除了速度慢点好像没啥问题... -git clone git@gitee.com:xx/xx-java.git --depth=10 - -#切换到项目目录,这步好像也没什么用 -cd /home/app/xx-java - -#这里他想切换到prod分支,但实际上git帮他创建了一个msater副本 -git checkout -B prod - -# 启动项目 然后发布的一直都是master的代码,😂(妈耶,坑爹啊) -sh /home/app/start-prod.sh \ No newline at end of file diff --git a/shell/sleep-sort.sh b/shell/sleep-sort.sh deleted file mode 100755 index 81ce589f561ac5942a00fb6d5b7069bea3c33c48..0000000000000000000000000000000000000000 --- a/shell/sleep-sort.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash -function f(){ - sleep "$1" - echo "$1" -} - -while [ -n "$1" ] -do - f "$1" & - shift -done -wait \ No newline at end of file diff --git a/sql/DBBombRank b/sql/DBBombRank deleted file mode 100644 index 68267d1d510b07276a4ca8cbb7fb149ff9aec867..0000000000000000000000000000000000000000 --- a/sql/DBBombRank +++ /dev/null @@ -1,212 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sql/WechatIMG199.png b/sql/WechatIMG199.png deleted file mode 100644 index 32caa334def106d8916a6cda447aff13be183fa8..0000000000000000000000000000000000000000 Binary files a/sql/WechatIMG199.png and /dev/null differ diff --git a/sql/clever_avg.sql b/sql/clever_avg.sql deleted file mode 100644 index cf655f7a353149b311918034a41cea72260b5ce3..0000000000000000000000000000000000000000 --- a/sql/clever_avg.sql +++ /dev/null @@ -1 +0,0 @@ -select sum(trade.trade_price*trade_volume)/sum(trade_volume) as average_price from tb_trade \ No newline at end of file diff --git a/sql/dataBoom.sql b/sql/dataBoom.sql deleted file mode 100644 index 871fc223d001cf339c66af7320fbebdda9547871..0000000000000000000000000000000000000000 --- a/sql/dataBoom.sql +++ /dev/null @@ -1 +0,0 @@ -select * from a left join b on 1=1 and b.id = a.borrow_id diff --git a/sql/delete all table data.sql b/sql/delete all table data.sql deleted file mode 100644 index d53a1698315cb9ed9de987bc3f1d5c3a9608d120..0000000000000000000000000000000000000000 --- a/sql/delete all table data.sql +++ /dev/null @@ -1,2 +0,0 @@ -# 删除t_user表的所有数据 -delete * from t_user \ No newline at end of file diff --git a/sql/fuckcode.xml b/sql/fuckcode.xml deleted file mode 100644 index 8f8e0baeaf3e5e9112acf8a06ae4e50636058542..0000000000000000000000000000000000000000 --- a/sql/fuckcode.xml +++ /dev/null @@ -1,339 +0,0 @@ - \ No newline at end of file diff --git a/sql/fucksql.xml b/sql/fucksql.xml deleted file mode 100644 index 3b3249e765e0f2dd34d310f18a2983d420bb2d7a..0000000000000000000000000000000000000000 --- a/sql/fucksql.xml +++ /dev/null @@ -1,335 +0,0 @@ - - - - - - SELECT n.COUNT_TIME as "countTime", - - - NVL(c.TRADE_AMOUNT,0) as "accumulateTradeAmount", - NVL(c.TRADE_COUNT,0) as "accumulateTradeCount", - - NVL(n.TRADE_AMOUNT,0) as "tradeAmount", - NVL(n.REFUND_AMOUNT,0) as "refundAmount", - NVL(n.REVERSE_AMOUNT,0) as "reverseAmount", - NVL(l.TRADE_AMOUNT,0) as "preTradeAmount", - NVL(l.REFUND_AMOUNT,0) "preRefundAmount", - NVL(n.TRADE_COUNT,0) as "tradeCount", - NVL(n.REFUND_COUNT,0) as "refundCount", - NVL(n.REVERSE_COUNT,0) as "reverseCount", - NVL(l.TRADE_COUNT,0) as "preTradeCount", - NVL(l.REFUND_COUNT,0) "preRefundCount" - FROM (SELECT COUNT_TIME, - - SUM(TRADE_AMOUNT) TRADE_AMOUNT, - SUM(REFUND_AMOUNT) REFUND_AMOUNT, - SUM(REVERSE_AMOUNT) REVERSE_AMOUNT, - SUM(TRADE_COUNT) TRADE_COUNT, - SUM(REFUND_COUNT) REFUND_COUNT, - SUM(REVERSE_COUNT) REVERSE_COUNT - FROM - - - GROUP BY COUNT_TIME - - ) n - LEFT JOIN - (SELECT NEXT_COUNT_TIME, - - SUM(TRADE_AMOUNT) TRADE_AMOUNT, - SUM(REFUND_AMOUNT) REFUND_AMOUNT, - SUM(TRADE_COUNT) TRADE_COUNT, - SUM(REFUND_COUNT) REFUND_COUNT - FROM - - - GROUP BY NEXT_COUNT_TIME - - ) l - ON n.COUNT_TIME = l.NEXT_COUNT_TIME - - - LEFT JOIN - (SELECT COUNT_TIME, - - SUM(TRADE_AMOUNT) TRADE_AMOUNT, - SUM(TRADE_COUNT) TRADE_COUNT - FROM BI_ACCEPT_ORG_TRANS_CUMULATE - - GROUP BY COUNT_TIME - - ) c - ON n.COUNT_TIME = c.COUNT_TIME - - - ORDER BY "countTime" DESC,"tradeAmount" DESC - - - - - n.ACCEPT_ORG_ID, - (case when n.ACCEPT_ORG_ID='-' then '其他' else n.ACCEPT_ORG_NAME end) as ACCEPT_ORG_NAME, - - - n.CHANNEL_ID, - n.CHANNEL_NAME CHANNEL_NAME, - - - n.MCH_NO, - n.MCH_NAME MCH_NAME, - - - n.GROUPNO AS GROUPNO, - n.GROUP_NAME AS GROUP_NAME, - - - - - - - ACCEPT_ORG_ID, - MAX(ACCEPT_ORG_NAME) AS ACCEPT_ORG_NAME, - - - CHANNEL_ID, - MAX(CHANNEL_NAME) AS CHANNEL_NAME, - - - MCH_NO, - MAX(MCH_NAME) AS MCH_NAME, - - - GROUPNO, - MAX(GROUP_NAME) AS GROUP_NAME, - - - - - - - BI_MCH_TRANS_COUNT_D - - - - - BI_CHN_TRANS_SUM_D - - - BI_CHANNEL_TRANS_COUNT_D - - - - - - - BI_CHN_TRANS_SUM_D0 - - - BI_CHN_TRANS_COUNT_D0 - - - BI_MCH_TRANS_COUNT_D0 - - - - - - - - - AND COUNT_TIME =]]> #{beginTime} - - - AND COUNT_TIME #{endTime} - - - AND COUNT_TIME =]]> #{beginMonth} - - - AND COUNT_TIME #{endMonth} - - - - - - - - - ,ACCEPT_ORG_ID - - - ,DC_TYPE - - - ,CHANNEL_ID - - - ,MCH_NO - - - ,GROUPNO - - - ,PAY_PROVIDE_ID - - - ,PAY_CENTER_ID - - - ,CENTER_ID - - - ,ADVANCE_SIDE_ID - - - ,ACC_WAY - - - ,PARTNER - - - - - - - ACCEPT_ORG_ID, - - - CHANNEL_ID, - - - MCH_NO, - - - GROUPNO, - - - - - - - AND NEXT_COUNT_TIME =]]> #{beginTime} - - - AND NEXT_COUNT_TIME #{endTime} - - - AND NEXT_COUNT_TIME =]]> #{beginMonth} - - - AND NEXT_COUNT_TIME #{endMonth} - - - - - - - - - AND n.ACCEPT_ORG_ID = l.ACCEPT_ORG_ID - - - AND n.CHANNEL_ID = l.CHANNEL_ID - - - AND n.MCH_NO = l.MCH_NO - - - AND n.GROUPNO = l.GROUPNO - - - - - - - ACCEPT_ORG_ID, - - - CHANNEL_ID, - - - MCH_NO, - - - GROUPNO, - - - - - - - - AND COUNT_TIME =]]> #{beginTime} - - - AND COUNT_TIME #{endTime} - - - AND COUNT_TIME =]]> #{beginMonth} - - - AND COUNT_TIME #{endMonth} - - - - - - - - - ,ACCEPT_ORG_ID - - - ,DC_TYPE - - - ,CHANNEL_ID - - - ,MCH_NO - - - ,GROUPNO - - - ,PAY_PROVIDE_ID - - - ,PAY_CENTER_ID - - - ,CENTER_ID - - - ,ADVANCE_SIDE_ID - - - ,ACC_WAY - - - ,PARTNER - - - - - - AND n.ACCEPT_ORG_ID = c.ACCEPT_ORG_ID - - - AND n.CHANNEL_ID = c.CHANNEL_ID - - - AND n.MCH_NO = c.MCH_NO - - \ No newline at end of file diff --git a/sql/insert by condition.sql b/sql/insert by condition.sql deleted file mode 100644 index 0f153050dfb54ec354af7a668bbbeaf0d80ab668..0000000000000000000000000000000000000000 --- a/sql/insert by condition.sql +++ /dev/null @@ -1,2 +0,0 @@ -# 按条件插入数据 -insert into t_user (id, uname) values (1, '红薯') where id <> 1 \ No newline at end of file diff --git a/sql/mysql_null.sql b/sql/mysql_null.sql deleted file mode 100644 index 336f3accf6bbb5d8ef01fde6554adb5da07846ec..0000000000000000000000000000000000000000 --- a/sql/mysql_null.sql +++ /dev/null @@ -1,3 +0,0 @@ --- ͬдSQLʱϵҲ޷ --- MySQL -SELECT * FROM `tb_test` WHERE remark != NULL \ No newline at end of file diff --git a/sql/report.sql b/sql/report.sql deleted file mode 100644 index f4c28a9bbf74bbb210aea93befba7a04135a2fe8..0000000000000000000000000000000000000000 --- a/sql/report.sql +++ /dev/null @@ -1,195 +0,0 @@ -#方吗? -select -yingh.repay_time, -count(yingh.borrow_id) "当日应还笔数", -count(yih.borrow_id) "当日正常还款数", -count(yingh.borrow_id) - count(yih.borrow_id) "当日未还逾期笔数", -count(yqyih.borrow_id) "当日逾期已还", -count(yingh.borrow_id) - count(yih.borrow_id) - count(yqyih.borrow_id) "当日逾期剩余未还", -count(yq1.borrow_id) "逾期一天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) "逾期二天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) - count(yq3.borrow_id) "逾期三天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) - count(yq3.borrow_id) - count(yq4.borrow_id) "逾期四天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) - count(yq3.borrow_id) - count(yq4.borrow_id) - count(yq5.borrow_id) "逾期五天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) - count(yq3.borrow_id) - count(yq4.borrow_id) - count(yq5.borrow_id) - count(yq6.borrow_id) "逾期六天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) - count(yq3.borrow_id) - count(yq4.borrow_id) - count(yq5.borrow_id) - count(yq6.borrow_id) - count(yq7.borrow_id) "逾期七天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) - count(yq3.borrow_id) - count(yq4.borrow_id) - count(yq5.borrow_id) - count(yq6.borrow_id) - count(yq7.borrow_id) - count(yq8_15.borrow_id) "逾期8-15天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) - count(yq3.borrow_id) - count(yq4.borrow_id) - count(yq5.borrow_id) - count(yq6.borrow_id) - count(yq7.borrow_id) - count(yq8_15.borrow_id) - count(yq16_30.borrow_id) "逾期16-30天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) - count(yq3.borrow_id) - count(yq4.borrow_id) - count(yq5.borrow_id) - count(yq6.borrow_id) - count(yq7.borrow_id) - count(yq8_15.borrow_id) - count(yq16_30.borrow_id)- count(yq31_60.borrow_id) "逾期31-60天未还", -count(yq1.borrow_id) - count(yq2.borrow_id) - count(yq3.borrow_id) - count(yq4.borrow_id) - count(yq5.borrow_id) - count(yq6.borrow_id) - count(yq7.borrow_id) - count(yq8_15.borrow_id) - count(yq16_30.borrow_id)- count(yq31_60.borrow_id)- count(yq60m.borrow_id) "逾期60天以上未还" - -from cl_borrow_repay yingh -LEFT JOIN cl_borrow_repay yih on yingh.borrow_id = yih.borrow_id and yih.state = 10 and yingh.user_id = yih.user_id and yih.penalty_day = 0 -#LEFT JOIN cl_borrow_repay wh on yingh.borrow_id = wh.borrow_id and wh.state = 20 and yingh.user_id = wh.user_id -LEFT JOIN( -select bp_yh.borrow_id,br.repay_time from cl_borrow_progress bp_yq join (select borrow_id from cl_borrow_progress where state = 40) bp_yh on bp_yq.state = 50 and bp_yq.borrow_id = bp_yh.borrow_id -LEFT JOIN cl_borrow_repay br on bp_yq.borrow_id = br.borrow_id - where bp_yq.state = 50 and bp_yq.borrow_id = bp_yh.borrow_id -) yqyih on yqyih.borrow_id = yingh.borrow_id and yqyih.repay_time = yingh.repay_time -LEFT JOIN( -select br.borrow_id,br.user_id from cl_borrow_repay br LEFT JOIN cl_borrow_progress bp on br.borrow_id = bp.borrow_id and br.user_id = bp.user_id -where bp.state = 50 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -1 DAY), '%Y-%m-%d') -) yq1 on yingh.borrow_id = yq1.borrow_id and yq1.user_id = yingh.user_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -2 DAY), '%Y-%m-%d') -)yq2 on yq2.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -3 DAY), '%Y-%m-%d') -)yq3 on yq3.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -4 DAY), '%Y-%m-%d') -)yq4 on yq4.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -5 DAY), '%Y-%m-%d') -)yq5 on yq5.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -6 DAY), '%Y-%m-%d') -)yq6 on yq6.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -7 DAY), '%Y-%m-%d') -)yq7 on yq7.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -15 DAY), '%Y-%m-%d') -and DATE_FORMAT(bp.create_time, '%Y-%m-%d') >= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -8 DAY), '%Y-%m-%d') -)yq8_15 on yq8_15.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -30 DAY), '%Y-%m-%d') -and DATE_FORMAT(bp.create_time, '%Y-%m-%d') >= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -16 DAY), '%Y-%m-%d') -)yq16_30 on yq16_30.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -60 DAY), '%Y-%m-%d') -and DATE_FORMAT(bp.create_time, '%Y-%m-%d') >= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -31 DAY), '%Y-%m-%d') -)yq31_60 on yq16_30.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,bp.borrow_id,br.repay_time,bp.create_time from cl_borrow_repay br LEFT JOIN -cl_borrow_progress bp on br.borrow_id = bp.borrow_id -where bp.state = 40 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') > DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -60 DAY), '%Y-%m-%d') -)yq60m on yq60m.borrow_id =yq1.borrow_id -GROUP BY yingh.repay_time; - - - - -#优化一点点后,计算公式之类的方代码里面执行 -select -DATE_FORMAT(yingh.repay_time,'%Y-%m-%d') repayTime, -count(yingh.borrow_id) shouldRepayToday, -count(yih.borrow_id) normalRepayToday, -count(yqyih.borrow_id) overdueRepayToday, -count(dthz.borrow_id) badCount, -count(yq1.borrow_id) overdueRepay1, -count(yq1yh.borrow_id) overdueRepay1ed, -count(yq2.borrow_id), -count(yq3.borrow_id), -count(yq4.borrow_id), -count(yq5.borrow_id), -count(yq6.borrow_id), -count(yq7.borrow_id), -count(yq8_15.borrow_id), -count(yq16_30.borrow_id), -count(yq31_60.borrow_id), -count(yq60m.borrow_id), -count(yqyh1_3.borrow_id) repayCount1and3, -count(yqyh4_15.borrow_id) repayCount4and15 -from cl_borrow_repay yingh -LEFT JOIN cl_borrow_repay yih on yingh.borrow_id = yih.borrow_id and yih.state = 10 and yingh.user_id = yih.user_id and yih.penalty_day = 0 -LEFT JOIN( -select bp_yh.borrow_id,bp_yh.repay_time from cl_borrow_progress bp_yq join (select borrow_id,repay_time from cl_borrow_repay where state =10) bp_yh on bp_yq.state = 50 and bp_yq.borrow_id = bp_yh.borrow_id -) yqyih on yqyih.borrow_id = yingh.borrow_id and yqyih.repay_time = yingh.repay_time -LEFT JOIN( -select borrow_id from cl_borrow_progress where state = 90 -)dthz on yingh.borrow_id = dthz.borrow_id -LEFT JOIN( -select br.borrow_id,br.user_id from cl_borrow_repay br LEFT JOIN cl_borrow_progress bp on br.borrow_id = bp.borrow_id and br.user_id = bp.user_id -where bp.state = 50 and DATE_FORMAT(bp.create_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -1 DAY), '%Y-%m-%d') -) yq1 on yingh.borrow_id = yq1.borrow_id and yq1.user_id = yingh.user_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -1 DAY), '%Y-%m-%d') -) yq1yh on yingh.borrow_id = yq1yh.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -2 DAY), '%Y-%m-%d') -)yq2 on yq2.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -3 DAY), '%Y-%m-%d') -)yq3 on yq3.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -4 DAY), '%Y-%m-%d') -)yq4 on yq4.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -5 DAY), '%Y-%m-%d') -)yq5 on yq5.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -6 DAY), '%Y-%m-%d') -)yq6 on yq6.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') = DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -7 DAY), '%Y-%m-%d') -)yq7 on yq7.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -15 DAY), '%Y-%m-%d') -and DATE_FORMAT(brl.repay_time, '%Y-%m-%d') >= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -8 DAY), '%Y-%m-%d') -)yq8_15 on yq8_15.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -30 DAY), '%Y-%m-%d') -and DATE_FORMAT(brl.repay_time, '%Y-%m-%d') >= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -16 DAY), '%Y-%m-%d') -)yq16_30 on yq16_30.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -60 DAY), '%Y-%m-%d') -and DATE_FORMAT(brl.repay_time, '%Y-%m-%d') >= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -31 DAY), '%Y-%m-%d') -)yq31_60 on yq16_30.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') > DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -60 DAY), '%Y-%m-%d') -)yq60m on yq60m.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -3 DAY), '%Y-%m-%d') -and DATE_FORMAT(brl.repay_time, '%Y-%m-%d') >= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -1 DAY), '%Y-%m-%d') -)yqyh1_3 on yqyh1_3.borrow_id =yq1.borrow_id -LEFT JOIN( -select br.borrow_id brborrow_id,brl.borrow_id,br.repay_time from cl_borrow_repay br LEFT JOIN -cl_borrow_repay_log brl on br.borrow_id = brl.borrow_id -where DATE_FORMAT(brl.repay_time, '%Y-%m-%d') <= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -15 DAY), '%Y-%m-%d') -and DATE_FORMAT(brl.repay_time, '%Y-%m-%d') >= DATE_FORMAT(DATE_SUB(br.repay_time, INTERVAL -4 DAY), '%Y-%m-%d') -)yqyh4_15 on yqyh4_15.borrow_id =yq1.borrow_id -where DATE_FORMAT(yingh.repay_time, '%Y-%m-%d') < DATE_FORMAT('2019-04-20', '%Y-%m-%d') -GROUP BY yingh.repay_time \ No newline at end of file diff --git a/sql/sql_too_long.sql b/sql/sql_too_long.sql deleted file mode 100644 index d3aa83d0f6196c13275ef55722d7ce62f84bb518..0000000000000000000000000000000000000000 --- a/sql/sql_too_long.sql +++ /dev/null @@ -1,210 +0,0 @@ -# 一度以为是DBA来写Java了,这么长SQL,怎么复用?怎么维护? -# 蛋疼的是,一个XML里面大量这样的SQL,几千行谁看得懂? -# 反例教材 -select - -demand_id, -demand_code, -demand_name, -demand_priority, -demand_priority_str, -receiver_addr, -receiver_name, -business_area, -demand_type, -demand_type_str, -demand_status, -demand_status_str, -expected_work_time, -created, -created_name, -created_by​ - - from - (select - aa.demand_id, - aa.demand_code, - aa.demand_name, - aa.demand_priority, - aa.demand_priority_str, - aa.business_area, - aa.demand_type, - aa.demand_type_str, - aa.demand_status, - aa.demand_status_str, - aa.acceptance_addr, - aa.created_by, - aa.created_name, - aa.created, - aa.receiver_addr, - aa.receiver_name, - (select count(1) - from dm_demand_t ddt - where ddt.demand_id = aa.demand_id - and (ddt.demand_status = 1 and - (ddt.created_by= #{report.loginEmail} or - ddt.receiver_addr = #{report.loginEmail} or - ddt.pm_email_addr = #{report.loginEmail} or #{report.pmoFlag} = 'Y')) - or (ddt.demand_status = 7 and - (ddt.created_by= #{report.loginEmail} or - ddt.receiver_addr = #{report.loginEmail} or - ddt.pm_email_addr = #{report.loginEmail} or #{report.pmoFlag} = 'Y')) - ) as enable_edit, - (select count(1) - from dm_demand_t ddt - where ddt.demand_id = aa.demand_id - and (ddt.demand_status = 1 and - (ddt.created_by= #{report.loginEmail} or - ddt.receiver_addr = #{report.loginEmail} or - ddt.pm_email_addr = #{report.loginEmail} or #{report.pmoFlag} = 'Y')) - or (ddt.demand_status = 7 and - (ddt.created_by= #{report.loginEmail} or - ddt.receiver_addr = #{report.loginEmail} or - ddt.pm_email_addr = #{report.loginEmail} or #{report.pmoFlag} = 'Y')) - ) as enable_close, - (select count(1) - from dm_demand_t ddt - where ddt.demand_id =aa.demand_id - and (ddt.demand_status= 3 and - (ddt.receiver_addr= #{report.loginEmail} or ddt.pm_email_addr =#{report.loginEmail} or #{report.pmoFlag} = 'Y')) - ) as enable_project, - (select count(1) - from dm_demand_t ddt - where ddt.demand_id=aa.demand_id - and(ddt.demand_status=8 - and(ddt.created_by=#{report.loginEmail} or locate(#{report.loginEmail},aa.acceptance_addr)>0)) - )as enable_accept, - aa.total_time as expected_work_time, --- concat(ifnull(aa.total_person,0),'/',ifnull(aa.total_time,0)) as expected_work_time, - group_concat(aa.dept_id) as lev1_depts, - group_concat(aa.lev2_dept_id) as lev2_depts - from - (SELECT - dt.demand_id, - dt.demand_code, - dt.demand_name, - dt.demand_priority, - cd1.display AS demand_priority_str, - dt.business_area, - dt.demand_type, - cd3.display AS demand_type_str, - dt.demand_status, - cd2.display AS demand_status_str, - dt.created_by, - ts.name as created_name, - dt.created, - dt.receiver_addr, - ts2.name AS receiver_name, - (case dt.demand_type - when 1 then convert(sum(ifnull(dtt.work_time,0)),decimal(10,1)) - when 2 then convert(sum(ifnull(dtt.work_time,0)),decimal(10,1)) - when 3 then - (select convert(sum(aa.bus_time),decimal(10,1)) - from - (select - tt.demand_id, - op.id as operate_id, - ifnull(op.operation_cycle, 0) * (ifnull(tt.proportion, 0) / 100) * ifnull(op.hr_config, 0) as bus_time - from dm_demand_time_t tt - inner join dm_demand_operation_t op on op.status=1 AND op.ident_code = 0 - and tt.project_code=op.project_code and tt.demand_id=op.demand_id - where tt.status = 1 AND tt.ident_code = 0) aa - where aa.demand_id =dt.demand_id) - else 0 - end - ) as total_time, - (select count(distinct st.user_email_addr) - from dm_demand_source_t st - where st.status = 1 and st.demand_id = dt.demand_id) as total_person, - ds.dept_id, - ds.lev2_dept_id, - group_concat(dat.acceptance_incharge_addr) as acceptance_addr - FROM dm_demand_t dt - left join ts_user ts on ts.email_addr=dt.created_by - left join ts_user ts2 on ts2.email_addr=dt.receiver_addr - left join (select - st.demand_id, - tu.m_dept_des_level2 as dept_id, - tu.m_dept_des_level3 as lev2_dept_id - from - dm_demand_source_t st - left join ts_user tu on tu.email_addr=st.user_email_addr - where st.status = 1 - ) ds on ds.demand_id = dt.demand_id - left join dm_code_dict cd1 ON cd1.ident_key='priority' and cd1.code = dt.demand_priority - left join dm_code_dict cd2 ON cd2.ident_key='demandStatus' and cd2.code = dt.demand_status - left join dm_code_dict cd3 ON cd3.ident_key='demandType' and cd3.code = dt.demand_type - left join dm_demand_acceptance_t dat on dat.status = 1 and dat.demand_id = dt.demand_id - left join dm_demand_time_t dtt on dtt.status = 1 and dtt.demand_id = dt.demand_id AND dtt.ident_code = 0 - where 1 = 1 - and dt.created between if(#{report.beginDate}=null,'1000-01-01',if(#{report.beginDate}='','1000-01-01',#{report.beginDate})) - and if(#{report.endDate}=null,'9999-01-01',if(#{report.endDate}='','9999-01-01',#{report.endDate})) - - and dt.business_area = #{report.businessArea} - - - - and locate(#{report.demandName}, dt.demand_name) > 0 - - - and locate(#{report.demandCode}, dt.demand_code) > 0 - - group by - dt.demand_id, - dt.demand_code, - dt.demand_name, - dt.demand_priority, - demand_priority_str, - dt.business_area, - dt.demand_type, - demand_type_str, - dt.demand_status, - demand_status_str, - dt.created_by, - dt.created, - created_name, - total_person, - ds.dept_id, - ds.lev2_dept_id - ) aa - group by aa.demand_id, - aa.demand_code, - aa.demand_name, - aa.demand_priority, - aa.demand_priority_str, - aa.business_area, - aa.demand_type, - aa.demand_type_str, - aa.demand_status, - aa.demand_status_str, - aa.created_by, - aa.created, - aa.created_name, - aa.acceptance_addr, - aa.receiver_addr, - aa.receiver_name, - enable_edit, - enable_accept, - enable_project, - enable_close) bb - where 1=1 - - and bb.demand_type_str = #{report.demandType} - - - and bb.demand_priority_str = #{report.demandPriority} - - - and bb.demand_status_str=#{report.demandStatus} - - - and locate(#{report.demandPerson},bb.receiver_addr)>0 - - - and locate(concat(',',#{report.lev1Dept},','),concat(',',bb.lev1_depts,','))>0 - - - and locate(concat(',',#{report.lev2Dept},','),concat(',',bb.lev2_depts,','))>0 - - - ORDER BY bb.created DESC \ No newline at end of file diff --git "a/sql/\344\277\204\347\275\227\346\226\257\345\245\227\345\250\203.sql" "b/sql/\344\277\204\347\275\227\346\226\257\345\245\227\345\250\203.sql" deleted file mode 100644 index a3d17cd15cb33d78abaa314e45c1d11e5a001bfe..0000000000000000000000000000000000000000 --- "a/sql/\344\277\204\347\275\227\346\226\257\345\245\227\345\250\203.sql" +++ /dev/null @@ -1,81 +0,0 @@ -select - res_url, - sum(bid) as bbid, - min(resource_code) resource_code, - min(l_level_menu) l_level_menu, - min(menu_type) menu_type, - min(biz_code) biz_code, - sum(flag) / count(flag) flag -from - ( - select - a.*, b.id as bid - from - ( - ( - select - * - from - ( - (select * from user_resource) e - left join ( - select - user_role, - resource_code as fresource_code, - biz_code as fbiz_value - from - user_role_resource - ) f on f.fresource_code = e.resource_code - ) - ) a - left join ( - select - id - from - ( - ( - select distinct - m.user_role as buser_role - from - ( - select - user_role - from - user_role - where - aaaa_num = #{userid} union all - ( - select - k.user_role as user_role - from - ( - ( - select - user_role, - user_group - from - user_group_role - ) k - left join ( - select - user_group - from - user_info_group - where - aaaa_num = #{userid} )j on k.user_group=j.user_group) where j.user_group is not null)) m where buser_role in (select user_role from user_role_duty where status=1 ) - ) c - left join ( - select - id, - user_role as duser_role - from - user_role_duty - ) d on c.buser_role = d.duser_role - ) - where - id is not null - ) b on a.user_role = b.id - ) - ) k - group by - res_url \ No newline at end of file