file_id
stringlengths
5
8
content
stringlengths
131
14.4k
repo
stringlengths
9
59
path
stringlengths
8
120
token_length
int64
36
3.49k
original_comment
stringlengths
5
791
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
135
14.3k
excluded
float64
0
0
file-tokens-Qwen/Qwen2-7B
int64
30
3.27k
comment-tokens-Qwen/Qwen2-7B
int64
2
459
file-tokens-bigcode/starcoder2-7b
int64
35
3.49k
comment-tokens-bigcode/starcoder2-7b
int64
3
483
file-tokens-google/codegemma-7b
int64
36
3.61k
comment-tokens-google/codegemma-7b
int64
3
465
file-tokens-ibm-granite/granite-8b-code-base
int64
35
3.49k
comment-tokens-ibm-granite/granite-8b-code-base
int64
3
483
file-tokens-meta-llama/CodeLlama-7b-hf
int64
44
4.13k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
592
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
23402_2
package main; import java.util.Date; import java.util.GregorianCalendar; /** * create by Intellij IDEA * Author: Al-assad * E-mail: yulinying_1994@outlook.com * Github: https://github.com/Al-assad * Date: 2017/4/11 11:57 * Description: bilibili用户信息类 */ public class BiliUser { private long mid; //mid private String name; //昵称 private String sex ; //性别[“男”,“女”,“保密”] private int level; //等级[1-5] private String sign; //用户签名 private String faceUrl; //用户头像图片链接 private int friends; //关注数量 private int fans; //粉丝数量 private int playNum; //上传视频播放量 private String birthday; //生日(系统默认项:0000-01-01) private String place ; //所在地点 public BiliUser(){ } //getter and setter method public long getMid() { return mid; } public void setMid(long mid) { this.mid = mid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getFaceUrl() { return faceUrl; } public void setFaceUrl(String faceUrl) { this.faceUrl = faceUrl; } public int getFriends() { return friends; } public void setFriends(int friends) { this.friends = friends; } public int getFans() { return fans; } public void setFans(int fans) { this.fans = fans; } public int getPlayNum() { return playNum; } public void setPlayNum(int playNum) { this.playNum = playNum; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { //废弃以0000-开头的birthday记录 if(birthday.equals("0000-01-01")) birthday = null; this.birthday = birthday; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } //toString method public String toString(){ return "mid="+mid+", " +"name="+name+", " +"level="+level+", " +"sex="+sex+", " +"sign="+sign+", " +"friends="+friends+", " +"faceUrl="+faceUrl+", " +"fans="+fans+", " +"playNum="+playNum+", " +"brithday="+birthday+", " +"place="+place; } }
Al-assad/Spider-bilibiliUser-active
src/main/BiliUser.java
780
//性别[“男”,“女”,“保密”]
line_comment
zh-cn
package main; import java.util.Date; import java.util.GregorianCalendar; /** * create by Intellij IDEA * Author: Al-assad * E-mail: yulinying_1994@outlook.com * Github: https://github.com/Al-assad * Date: 2017/4/11 11:57 * Description: bilibili用户信息类 */ public class BiliUser { private long mid; //mid private String name; //昵称 private String sex ; //性别 <SUF> private int level; //等级[1-5] private String sign; //用户签名 private String faceUrl; //用户头像图片链接 private int friends; //关注数量 private int fans; //粉丝数量 private int playNum; //上传视频播放量 private String birthday; //生日(系统默认项:0000-01-01) private String place ; //所在地点 public BiliUser(){ } //getter and setter method public long getMid() { return mid; } public void setMid(long mid) { this.mid = mid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getFaceUrl() { return faceUrl; } public void setFaceUrl(String faceUrl) { this.faceUrl = faceUrl; } public int getFriends() { return friends; } public void setFriends(int friends) { this.friends = friends; } public int getFans() { return fans; } public void setFans(int fans) { this.fans = fans; } public int getPlayNum() { return playNum; } public void setPlayNum(int playNum) { this.playNum = playNum; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { //废弃以0000-开头的birthday记录 if(birthday.equals("0000-01-01")) birthday = null; this.birthday = birthday; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } //toString method public String toString(){ return "mid="+mid+", " +"name="+name+", " +"level="+level+", " +"sex="+sex+", " +"sign="+sign+", " +"friends="+friends+", " +"faceUrl="+faceUrl+", " +"fans="+fans+", " +"playNum="+playNum+", " +"brithday="+birthday+", " +"place="+place; } }
0
729
13
780
15
843
13
780
15
1,009
19
false
false
false
false
false
true
18241_25
package com.song.homework09; /* Maze.java */ import java.util.*; import com.song.homework09.set.*; /** * The Maze class represents a maze in a rectangular grid. There is exactly * one path between any two points. **/ public class Maze { // Horizontal and vertical dimensions of the maze. protected int horiz; protected int vert; // Horizontal and vertical interior walls; each is true if the wall exists. protected boolean[][] hWalls; protected boolean[][] vWalls; // Object for generting random numbers. private static Random random; // Constants used in depth-first search (which checks for cycles in the // maze). private static final int STARTHERE = 0; private static final int FROMLEFT = 1; private static final int FROMRIGHT = 2; private static final int FROMABOVE = 3; private static final int FROMBELOW = 4; /** * Maze() creates a rectangular maze having "horizontalSize" cells in the * horizontal direction, and "verticalSize" cells in the vertical direction. * There is a path between any two cells of the maze. A disjoint set data * structure is used to ensure that there is only one path between any two * cells. **/ public Maze(int horizontalSize, int verticalSize) { int i, j; horiz = horizontalSize; vert = verticalSize; if ((horiz < 1) || (vert < 1) || ((horiz == 1) && (vert == 1))) { return; // There are no interior walls } // Create all of the horizontal interior walls. Initially, every // horizontal wall exists; they will be removed later by the maze // generation algorithm. if (vert > 1) { hWalls = new boolean[horiz][vert - 1]; for (j = 0; j < vert - 1; j++) { for (i = 0; i < horiz; i++) { hWalls[i][j] = true; //wall 都存在,即没有edge。 } } } // Create all of the vertical interior walls. if (horiz > 1) { vWalls = new boolean[horiz - 1][vert]; for (i = 0; i < horiz - 1; i++) { for (j = 0; j < vert; j++) { vWalls[i][j] = true; } } } /** * Fill in the rest of this method. You should go through all the walls of * the maze in random order, and remove any wall whose removal will not * create a cycle. Use the implementation of disjoint sets provided in the * set package to avoid creating any cycles. * * Note the method randInt() further below, which generates a random * integer. randInt() generates different numbers every time the program * is run, so that you can make lots of different mazes. **/ DisjointSets cellSet=new DisjointSets(horiz*vert); //创建一个并查集,放入所有的cell int NumofWalls=vert*(horiz-1)+horiz*(vert-1); //墙的总数 int[] WallArray=new int[NumofWalls]; int index=0; if(vert>1){ for(j=0;j<vert-1;j++){ for(i=0;i<horiz;i++){ WallArray[index]=j*horiz+i; //horizontal wall分别编号、横着编:从左往右1234.... // 分隔上下两个cell index++; } } } if(horiz>1){ for(i=0;i<horiz-1;i++){ for(j=0;j<vert;j++){ WallArray[index]=- (j*horiz+i); //vertical wall 分别编号,、横着编:从左往右1234.... // 为了和horizontal wall区分,用负数表示 // 分隔左右两个cell index++; } } } //将WallArray里面的wall随机排布 int w=NumofWalls; int temp; while(w>1){ int x=randInt(w); //在0 - w-1随机取数 temp=WallArray[x]; WallArray[x]=WallArray[w-1]; //swap随机取的第x个和最后一个 注意WallArray[w-1]是最后一个数 WallArray[w-1]=temp; w--; //下次swap随机取的第x个和倒数第二个,以此类推 } for(int k=0;k<NumofWalls;k++){ index=WallArray[k]; //从随机排列后第一个WallArray开始取wall的信息, // 这个wall同时表示了它上方(horiz)或左方(vert)的cell,见readme if(index>0) { //如果是horizontal wall int cellParent1 = cellSet.find(index); //返回这个cell的parent int cellParent2 = cellSet.find(index + horiz); //返回这个cell下面那个cell的parent //如果他们的parent是同一个,说明cell和cell下面(上面)那个cell在同一个set里,中间的墙得有 //如果不是同一个parent,也就是说他们之间没有通路,union后将墙设为false if (cellParent1 != cellParent2) { cellSet.union(cellParent1, cellParent2); //这个操作后他们的parent一样了 hWalls[index % horiz][index / horiz] = false; //wall的横向位置:index % horiz //wall的纵向位置:index / horiz } } else { //如果是vertical wall int cellParent3 = cellSet.find(-index); //返回这个cell的parent int cellParent4 = cellSet.find(-index + 1); //返回这个cell右边那个cell的parent if (cellParent3 != cellParent4){ cellSet.union(cellParent3,cellParent4); vWalls[(-index)%horiz][(-index)/horiz] = false; } } } } /** * toString() returns a string representation of the maze. **/ public String toString() { int i, j; String s = ""; // Print the top exterior wall. for (i = 0; i < horiz; i++) { s = s + "--"; } s = s + "-\n|"; // Print the maze interior. for (j = 0; j < vert; j++) { // Print a row of cells and vertical walls. for (i = 0; i < horiz - 1; i++) { if (vWalls[i][j]) { s = s + " |"; } else { s = s + " "; } } s = s + " |\n+"; if (j < vert - 1) { // Print a row of horizontal walls and wall corners. for (i = 0; i < horiz; i++) { if (hWalls[i][j]) { s = s + "-+"; } else { s = s + " +"; } } s = s + "\n|"; } } // Print the bottom exterior wall. (Note that the first corner has // already been printed.) for (i = 0; i < horiz; i++) { s = s + "--"; } return s + "\n"; } /** * horizontalWall() determines whether the horizontal wall on the bottom * edge of cell (x, y) exists. If the coordinates (x, y) do not correspond * to an interior wall, true is returned. **/ public boolean horizontalWall(int x, int y) { if ((x < 0) || (y < 0) || (x > horiz - 1) || (y > vert - 2)) { return true; } return hWalls[x][y]; } /** * verticalWall() determines whether the vertical wall on the right edge of * cell (x, y) exists. If the coordinates (x, y) do not correspond to an * interior wall, true is returned. **/ public boolean verticalWall(int x, int y) { if ((x < 0) || (y < 0) || (x > horiz - 2) || (y > vert - 1)) { return true; } return vWalls[x][y]; } /** * randInt() returns a random integer from 0 to choices - 1. **/ private static int randInt(int choices) { if (random == null) { // Only executed first time randInt() is called random = new Random(); // Create a "Random" object with random seed } int r = random.nextInt() % choices; // From | choice - 1 | to choices - 1 if (r < 0) { r = -r; // From 0 to choices - 1 } return r; } /** * diagnose() checks the maze and prints a warning if not every cell can be * reached from the upper left corner cell, or if there is a cycle reachable * from the upper left cell. * * DO NOT CHANGE THIS METHOD. Your code is expected to work with our copy * of this method. **/ protected void diagnose() { if ((horiz < 1) || (vert < 1) || ((horiz == 1) && (vert == 1))) { return; // There are no interior walls } boolean mazeFine = true; // Create an array that indicates whether each cell has been visited during // a depth-first traversal. boolean[][] cellVisited = new boolean[horiz][vert]; // Do a depth-first traversal. if (depthFirstSearch(0, 0, STARTHERE, cellVisited)) { System.out.println("Your maze has a cycle."); mazeFine = false; } // Check to be sure that every cell of the maze was visited. outerLoop: for (int j = 0; j < vert; j++) { for (int i = 0; i < horiz; i++) { if (!cellVisited[i][j]) { System.out.println("Not every cell in your maze is reachable from " + "every other cell."); mazeFine = false; break outerLoop; } } } if (mazeFine) { System.out.println("What a fine maze you've created!"); } } /** * depthFirstSearch() does a depth-first traversal of the maze, marking each * visited cell. Returns true if a cycle is found. * * DO NOT CHANGE THIS METHOD. Your code is expected to work with our copy * of this method. */ protected boolean depthFirstSearch(int x, int y, int fromWhere, boolean[][] cellVisited) { boolean cycleDetected = false; cellVisited[x][y] = true; // Visit the cell to the right? if ((fromWhere != FROMRIGHT) && !verticalWall(x, y)) { if (cellVisited[x + 1][y]) { cycleDetected = true; } else { cycleDetected = depthFirstSearch(x + 1, y, FROMLEFT, cellVisited) || cycleDetected; } } // Visit the cell below? if ((fromWhere != FROMBELOW) && !horizontalWall(x, y)) { if (cellVisited[x][y + 1]) { cycleDetected = true; } else { cycleDetected = depthFirstSearch(x, y + 1, FROMABOVE, cellVisited) || cycleDetected; } } // Visit the cell to the left? if ((fromWhere != FROMLEFT) && !verticalWall(x - 1, y)) { if (cellVisited[x - 1][y]) { cycleDetected = true; } else { cycleDetected = depthFirstSearch(x - 1, y, FROMRIGHT, cellVisited) || cycleDetected; } } // Visit the cell above? if ((fromWhere != FROMABOVE) && !horizontalWall(x, y - 1)) { if (cellVisited[x][y - 1]) { cycleDetected = true; } else { cycleDetected = depthFirstSearch(x, y - 1, FROMBELOW, cellVisited) || cycleDetected; } } return cycleDetected; } /** * main() creates a maze of dimensions specified on the 【command line】, prints * the maze, and runs the diagnostic method to see if the maze is good. * * 命令行窗口输入:java Maze 30 10 ,那么 args[0]=30, args[1]=10; */ public static void main(String[] args) { int x = 39; int y = 15; /** * Read the input parameters. */ if (args.length > 0) { try { x = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.out.println("First argument to Simulation is not an number."); } } if (args.length > 1) { try { y = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.out.println("Second argument to Simulation is not an number."); } } Maze maze = new Maze(x, y); System.out.print(maze); maze.diagnose(); } }
Alan-song641/UC-Berkeley-CS-61B
homework09/Maze.java
3,268
//下次swap随机取的第x个和倒数第二个,以此类推
line_comment
zh-cn
package com.song.homework09; /* Maze.java */ import java.util.*; import com.song.homework09.set.*; /** * The Maze class represents a maze in a rectangular grid. There is exactly * one path between any two points. **/ public class Maze { // Horizontal and vertical dimensions of the maze. protected int horiz; protected int vert; // Horizontal and vertical interior walls; each is true if the wall exists. protected boolean[][] hWalls; protected boolean[][] vWalls; // Object for generting random numbers. private static Random random; // Constants used in depth-first search (which checks for cycles in the // maze). private static final int STARTHERE = 0; private static final int FROMLEFT = 1; private static final int FROMRIGHT = 2; private static final int FROMABOVE = 3; private static final int FROMBELOW = 4; /** * Maze() creates a rectangular maze having "horizontalSize" cells in the * horizontal direction, and "verticalSize" cells in the vertical direction. * There is a path between any two cells of the maze. A disjoint set data * structure is used to ensure that there is only one path between any two * cells. **/ public Maze(int horizontalSize, int verticalSize) { int i, j; horiz = horizontalSize; vert = verticalSize; if ((horiz < 1) || (vert < 1) || ((horiz == 1) && (vert == 1))) { return; // There are no interior walls } // Create all of the horizontal interior walls. Initially, every // horizontal wall exists; they will be removed later by the maze // generation algorithm. if (vert > 1) { hWalls = new boolean[horiz][vert - 1]; for (j = 0; j < vert - 1; j++) { for (i = 0; i < horiz; i++) { hWalls[i][j] = true; //wall 都存在,即没有edge。 } } } // Create all of the vertical interior walls. if (horiz > 1) { vWalls = new boolean[horiz - 1][vert]; for (i = 0; i < horiz - 1; i++) { for (j = 0; j < vert; j++) { vWalls[i][j] = true; } } } /** * Fill in the rest of this method. You should go through all the walls of * the maze in random order, and remove any wall whose removal will not * create a cycle. Use the implementation of disjoint sets provided in the * set package to avoid creating any cycles. * * Note the method randInt() further below, which generates a random * integer. randInt() generates different numbers every time the program * is run, so that you can make lots of different mazes. **/ DisjointSets cellSet=new DisjointSets(horiz*vert); //创建一个并查集,放入所有的cell int NumofWalls=vert*(horiz-1)+horiz*(vert-1); //墙的总数 int[] WallArray=new int[NumofWalls]; int index=0; if(vert>1){ for(j=0;j<vert-1;j++){ for(i=0;i<horiz;i++){ WallArray[index]=j*horiz+i; //horizontal wall分别编号、横着编:从左往右1234.... // 分隔上下两个cell index++; } } } if(horiz>1){ for(i=0;i<horiz-1;i++){ for(j=0;j<vert;j++){ WallArray[index]=- (j*horiz+i); //vertical wall 分别编号,、横着编:从左往右1234.... // 为了和horizontal wall区分,用负数表示 // 分隔左右两个cell index++; } } } //将WallArray里面的wall随机排布 int w=NumofWalls; int temp; while(w>1){ int x=randInt(w); //在0 - w-1随机取数 temp=WallArray[x]; WallArray[x]=WallArray[w-1]; //swap随机取的第x个和最后一个 注意WallArray[w-1]是最后一个数 WallArray[w-1]=temp; w--; //下次 <SUF> } for(int k=0;k<NumofWalls;k++){ index=WallArray[k]; //从随机排列后第一个WallArray开始取wall的信息, // 这个wall同时表示了它上方(horiz)或左方(vert)的cell,见readme if(index>0) { //如果是horizontal wall int cellParent1 = cellSet.find(index); //返回这个cell的parent int cellParent2 = cellSet.find(index + horiz); //返回这个cell下面那个cell的parent //如果他们的parent是同一个,说明cell和cell下面(上面)那个cell在同一个set里,中间的墙得有 //如果不是同一个parent,也就是说他们之间没有通路,union后将墙设为false if (cellParent1 != cellParent2) { cellSet.union(cellParent1, cellParent2); //这个操作后他们的parent一样了 hWalls[index % horiz][index / horiz] = false; //wall的横向位置:index % horiz //wall的纵向位置:index / horiz } } else { //如果是vertical wall int cellParent3 = cellSet.find(-index); //返回这个cell的parent int cellParent4 = cellSet.find(-index + 1); //返回这个cell右边那个cell的parent if (cellParent3 != cellParent4){ cellSet.union(cellParent3,cellParent4); vWalls[(-index)%horiz][(-index)/horiz] = false; } } } } /** * toString() returns a string representation of the maze. **/ public String toString() { int i, j; String s = ""; // Print the top exterior wall. for (i = 0; i < horiz; i++) { s = s + "--"; } s = s + "-\n|"; // Print the maze interior. for (j = 0; j < vert; j++) { // Print a row of cells and vertical walls. for (i = 0; i < horiz - 1; i++) { if (vWalls[i][j]) { s = s + " |"; } else { s = s + " "; } } s = s + " |\n+"; if (j < vert - 1) { // Print a row of horizontal walls and wall corners. for (i = 0; i < horiz; i++) { if (hWalls[i][j]) { s = s + "-+"; } else { s = s + " +"; } } s = s + "\n|"; } } // Print the bottom exterior wall. (Note that the first corner has // already been printed.) for (i = 0; i < horiz; i++) { s = s + "--"; } return s + "\n"; } /** * horizontalWall() determines whether the horizontal wall on the bottom * edge of cell (x, y) exists. If the coordinates (x, y) do not correspond * to an interior wall, true is returned. **/ public boolean horizontalWall(int x, int y) { if ((x < 0) || (y < 0) || (x > horiz - 1) || (y > vert - 2)) { return true; } return hWalls[x][y]; } /** * verticalWall() determines whether the vertical wall on the right edge of * cell (x, y) exists. If the coordinates (x, y) do not correspond to an * interior wall, true is returned. **/ public boolean verticalWall(int x, int y) { if ((x < 0) || (y < 0) || (x > horiz - 2) || (y > vert - 1)) { return true; } return vWalls[x][y]; } /** * randInt() returns a random integer from 0 to choices - 1. **/ private static int randInt(int choices) { if (random == null) { // Only executed first time randInt() is called random = new Random(); // Create a "Random" object with random seed } int r = random.nextInt() % choices; // From | choice - 1 | to choices - 1 if (r < 0) { r = -r; // From 0 to choices - 1 } return r; } /** * diagnose() checks the maze and prints a warning if not every cell can be * reached from the upper left corner cell, or if there is a cycle reachable * from the upper left cell. * * DO NOT CHANGE THIS METHOD. Your code is expected to work with our copy * of this method. **/ protected void diagnose() { if ((horiz < 1) || (vert < 1) || ((horiz == 1) && (vert == 1))) { return; // There are no interior walls } boolean mazeFine = true; // Create an array that indicates whether each cell has been visited during // a depth-first traversal. boolean[][] cellVisited = new boolean[horiz][vert]; // Do a depth-first traversal. if (depthFirstSearch(0, 0, STARTHERE, cellVisited)) { System.out.println("Your maze has a cycle."); mazeFine = false; } // Check to be sure that every cell of the maze was visited. outerLoop: for (int j = 0; j < vert; j++) { for (int i = 0; i < horiz; i++) { if (!cellVisited[i][j]) { System.out.println("Not every cell in your maze is reachable from " + "every other cell."); mazeFine = false; break outerLoop; } } } if (mazeFine) { System.out.println("What a fine maze you've created!"); } } /** * depthFirstSearch() does a depth-first traversal of the maze, marking each * visited cell. Returns true if a cycle is found. * * DO NOT CHANGE THIS METHOD. Your code is expected to work with our copy * of this method. */ protected boolean depthFirstSearch(int x, int y, int fromWhere, boolean[][] cellVisited) { boolean cycleDetected = false; cellVisited[x][y] = true; // Visit the cell to the right? if ((fromWhere != FROMRIGHT) && !verticalWall(x, y)) { if (cellVisited[x + 1][y]) { cycleDetected = true; } else { cycleDetected = depthFirstSearch(x + 1, y, FROMLEFT, cellVisited) || cycleDetected; } } // Visit the cell below? if ((fromWhere != FROMBELOW) && !horizontalWall(x, y)) { if (cellVisited[x][y + 1]) { cycleDetected = true; } else { cycleDetected = depthFirstSearch(x, y + 1, FROMABOVE, cellVisited) || cycleDetected; } } // Visit the cell to the left? if ((fromWhere != FROMLEFT) && !verticalWall(x - 1, y)) { if (cellVisited[x - 1][y]) { cycleDetected = true; } else { cycleDetected = depthFirstSearch(x - 1, y, FROMRIGHT, cellVisited) || cycleDetected; } } // Visit the cell above? if ((fromWhere != FROMABOVE) && !horizontalWall(x, y - 1)) { if (cellVisited[x][y - 1]) { cycleDetected = true; } else { cycleDetected = depthFirstSearch(x, y - 1, FROMBELOW, cellVisited) || cycleDetected; } } return cycleDetected; } /** * main() creates a maze of dimensions specified on the 【command line】, prints * the maze, and runs the diagnostic method to see if the maze is good. * * 命令行窗口输入:java Maze 30 10 ,那么 args[0]=30, args[1]=10; */ public static void main(String[] args) { int x = 39; int y = 15; /** * Read the input parameters. */ if (args.length > 0) { try { x = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.out.println("First argument to Simulation is not an number."); } } if (args.length > 1) { try { y = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.out.println("Second argument to Simulation is not an number."); } } Maze maze = new Maze(x, y); System.out.print(maze); maze.diagnose(); } }
0
3,121
17
3,255
20
3,422
17
3,268
20
3,881
28
false
false
false
false
false
true
31260_4
package com.ruoyi.common.enums; /** * 商户类型枚举 * * @author AlanLee * @date 2022-08-12 */ public enum MerchantKey { /** * 酒店 */ JIUDIAN(1, "酒吧", "酒吧"), /** * 夜店 */ YEDIAN(2, "夜店", "夜店"), /** * livehouse */ LIVE_HOUSE(3,"livehouse","Live House"); MerchantKey(Integer type, String name, String desc) { this.type = type; this.name = name; this.desc = desc; } /** * 商户类型 */ private Integer type; private String name; /** * 类型说明 */ private String desc; public int getType() { return type; } public String getDesc() { return desc; } public String getName() { return name; } }
AlanLee-Java/bar
bar-common/src/main/java/com/ruoyi/common/enums/MerchantKey.java
248
/** * 商户类型 */
block_comment
zh-cn
package com.ruoyi.common.enums; /** * 商户类型枚举 * * @author AlanLee * @date 2022-08-12 */ public enum MerchantKey { /** * 酒店 */ JIUDIAN(1, "酒吧", "酒吧"), /** * 夜店 */ YEDIAN(2, "夜店", "夜店"), /** * livehouse */ LIVE_HOUSE(3,"livehouse","Live House"); MerchantKey(Integer type, String name, String desc) { this.type = type; this.name = name; this.desc = desc; } /** * 商户类 <SUF>*/ private Integer type; private String name; /** * 类型说明 */ private String desc; public int getType() { return type; } public String getDesc() { return desc; } public String getName() { return name; } }
0
221
9
248
9
257
10
248
9
306
12
false
false
false
false
false
true
26033_15
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.io.*; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.security.SecureRandom; import java.util.Base64; /** * 此class负责进行二维码DES加密 * 2019-8-28 Albert */ public class DESUtils { private SecretKey securekey; private String key; private String codedKey=null; /** * 对字符串进行BASE64Decoder * * @param key * @return * @throws Exception */ private byte[] decryptBASE64(String key) { return Base64.getDecoder().decode(key); } /** * 对字节数组进行BASE64Encoder * * @param key * @return * @throws Exception */ private String encryptBASE64(byte[] key) { return Base64.getEncoder().encodeToString(key); } /** * 获取key * @return */ public String getKey(){ try { KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); keyGenerator.init(56); // 生成一个Key securekey = keyGenerator.generateKey(); // 转变为字节数组 byte[] encoded = securekey.getEncoded(); // 生成密钥字符串 String encodeString = encryptBASE64(encoded); return encodeString; } catch (Exception e) { e.printStackTrace(); return "密钥生成错误."; } } /** * 加密,返回BASE64的加密字符串 * @param str,key 当key是String类型时使用 * @return */ public String getEncryptString(String str,String key) throws Exception { DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); securekey = keyFactory.generateSecret(desKey); byte[] strBytes = str.getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, securekey); byte[] encryptStrBytes = cipher.doFinal(strBytes); return encryptBASE64(encryptStrBytes); } /** * 加密,返回BASE64的加密字符串 * @param str,key 当key是SecretKey类型时使用 * @return */ public String getEncryptString(String str,SecretKey key) throws Exception { byte[] strBytes = str.getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptStrBytes = cipher.doFinal(strBytes); return encryptBASE64(encryptStrBytes); } /** * 对BASE64加密字符串进行解密 * @param str * @return */ public String getDecryptString(String str,String key) throws Exception { DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); securekey = keyFactory.generateSecret(desKey); byte[] strBytes = decryptBASE64(str); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, securekey); byte[] encryptStrBytes = cipher.doFinal(strBytes); return new String(encryptStrBytes, "UTF-8"); } /** * 得到DES加密后的密文,以及经过RSA加密后的DES密匙. * @param name * @return String[] 储存密文以及加密后的密匙. * @throws Exception */ public String[] get_encryname_key_pair(String name)throws Exception{ if(codedKey==null){ String[] list = {getEncryptString(name,key),key}; return list; } else{ String[] list = {getEncryptString(name,key),codedKey}; return list; } } /** * main()是DESUtils的主要单元,负责加密DES密匙,生成DES密匙,并写入相应的txt文件内方便验证时提取。 * * @param ifrsa true时使用RSA加密DES密匙 false时仅用DES加密. * @return */ /** * main() is the main unit of DESUtils, responsible for encrypting the DES key, generating the DES key, and writing to the corresponding TXT file for easy extraction when verification. * * @param ifrsa true use RSA to encrypt DES key false use DES encryption only. * @ return */ public void main(Boolean ifrsa) { try { //String类型密匙文件路径 //String type key file path File directory = new File("."); String path = directory.getCanonicalPath(); String fileName = path+"\\Demo\\DesKey.txt"; //根据文件路径读取文件 //Read the file according to the file path FileOutputStream fos = new FileOutputStream(fileName,true); ObjectOutputStream oos = new ObjectOutputStream(fos); // 生成密钥 // Generate the key key = getKey();//用于DES加密的原密匙 The origin Key used for DES encryption /*测试 String jiami = getEncryptString("Hello World!",key); String jiami1 = getEncryptString("Hello World!",securekey); System.out.println("密匙:" + key); System.out.println("加密后:" + jiami+"以及"+jiami1); String jiemi = getDecryptString(jiami,key); System.out.println("解密后:" + jiemi); System.out.println("--------------------------------------------------------------"); */ //当用户选择YES时使用RSA加密DES密匙 if(ifrsa){ RSAUtils RSA = new RSAUtils(); codedKey=RSA.main(key); } oos.writeObject(key+"\r\n"); oos.close(); } catch (Exception e) { e.printStackTrace(); } } }
AlberTgarY/QRcodeSecurity
Demo/src/DESUtils.java
1,384
//根据文件路径读取文件
line_comment
zh-cn
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.io.*; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.security.SecureRandom; import java.util.Base64; /** * 此class负责进行二维码DES加密 * 2019-8-28 Albert */ public class DESUtils { private SecretKey securekey; private String key; private String codedKey=null; /** * 对字符串进行BASE64Decoder * * @param key * @return * @throws Exception */ private byte[] decryptBASE64(String key) { return Base64.getDecoder().decode(key); } /** * 对字节数组进行BASE64Encoder * * @param key * @return * @throws Exception */ private String encryptBASE64(byte[] key) { return Base64.getEncoder().encodeToString(key); } /** * 获取key * @return */ public String getKey(){ try { KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); keyGenerator.init(56); // 生成一个Key securekey = keyGenerator.generateKey(); // 转变为字节数组 byte[] encoded = securekey.getEncoded(); // 生成密钥字符串 String encodeString = encryptBASE64(encoded); return encodeString; } catch (Exception e) { e.printStackTrace(); return "密钥生成错误."; } } /** * 加密,返回BASE64的加密字符串 * @param str,key 当key是String类型时使用 * @return */ public String getEncryptString(String str,String key) throws Exception { DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); securekey = keyFactory.generateSecret(desKey); byte[] strBytes = str.getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, securekey); byte[] encryptStrBytes = cipher.doFinal(strBytes); return encryptBASE64(encryptStrBytes); } /** * 加密,返回BASE64的加密字符串 * @param str,key 当key是SecretKey类型时使用 * @return */ public String getEncryptString(String str,SecretKey key) throws Exception { byte[] strBytes = str.getBytes("UTF-8"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptStrBytes = cipher.doFinal(strBytes); return encryptBASE64(encryptStrBytes); } /** * 对BASE64加密字符串进行解密 * @param str * @return */ public String getDecryptString(String str,String key) throws Exception { DESKeySpec desKey = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); securekey = keyFactory.generateSecret(desKey); byte[] strBytes = decryptBASE64(str); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, securekey); byte[] encryptStrBytes = cipher.doFinal(strBytes); return new String(encryptStrBytes, "UTF-8"); } /** * 得到DES加密后的密文,以及经过RSA加密后的DES密匙. * @param name * @return String[] 储存密文以及加密后的密匙. * @throws Exception */ public String[] get_encryname_key_pair(String name)throws Exception{ if(codedKey==null){ String[] list = {getEncryptString(name,key),key}; return list; } else{ String[] list = {getEncryptString(name,key),codedKey}; return list; } } /** * main()是DESUtils的主要单元,负责加密DES密匙,生成DES密匙,并写入相应的txt文件内方便验证时提取。 * * @param ifrsa true时使用RSA加密DES密匙 false时仅用DES加密. * @return */ /** * main() is the main unit of DESUtils, responsible for encrypting the DES key, generating the DES key, and writing to the corresponding TXT file for easy extraction when verification. * * @param ifrsa true use RSA to encrypt DES key false use DES encryption only. * @ return */ public void main(Boolean ifrsa) { try { //String类型密匙文件路径 //String type key file path File directory = new File("."); String path = directory.getCanonicalPath(); String fileName = path+"\\Demo\\DesKey.txt"; //根据 <SUF> //Read the file according to the file path FileOutputStream fos = new FileOutputStream(fileName,true); ObjectOutputStream oos = new ObjectOutputStream(fos); // 生成密钥 // Generate the key key = getKey();//用于DES加密的原密匙 The origin Key used for DES encryption /*测试 String jiami = getEncryptString("Hello World!",key); String jiami1 = getEncryptString("Hello World!",securekey); System.out.println("密匙:" + key); System.out.println("加密后:" + jiami+"以及"+jiami1); String jiemi = getDecryptString(jiami,key); System.out.println("解密后:" + jiemi); System.out.println("--------------------------------------------------------------"); */ //当用户选择YES时使用RSA加密DES密匙 if(ifrsa){ RSAUtils RSA = new RSAUtils(); codedKey=RSA.main(key); } oos.writeObject(key+"\r\n"); oos.close(); } catch (Exception e) { e.printStackTrace(); } } }
0
1,302
7
1,384
6
1,500
6
1,384
6
1,790
15
false
false
false
false
false
true
17551_3
import java.util.ArrayList; import java.util.List; /* 119. Pascal's Triangle II Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note that the row index starts from 0. In Pascal's triangle, each number is the sum of the two numbers directly above it. Example: Input: 3 Output: [1,3,3,1] Follow up: Could you optimize your algorithm to use only O(k) extra space? */ public class Generate2 { //ArrayList 的set,get O(1); 与Array[]一样; public List<Integer> getRow(int rowIndex) { List<Integer> res = new ArrayList<>(); res.add(1); for(int i=1;i<=rowIndex;i++){ // res.add(res.get(i-1)*(rowIndex+1-i)/i); //当值为30时出错 // res.add((int)((double)(res.get(i-1)*(rowIndex+1-i))/i)); //当值为30时出错 // res.add((int)(double)(res.get(i-1))*(rowIndex+1-i)/i); //当值为30时出错 // res.add((int)((double)(res.get(i-1)))*(rowIndex+1-i)/i); //当值为30时出错 // double t= res.get(i-1)*(rowIndex+1-i); // t=t/i; // res.add((int)t); //通过 // double t= res.get(i-1); // t=t*(rowIndex+1-i)/i; // res.add((int)t); //通过;第一个double强转是不能有多余括号,要立马强转第一个值; res.add((int)((double)res.get(i-1)*(rowIndex+1-i)/i)); } return res; } //O(n2); public List<Integer> getRow2(int rowIndex) { List<Integer> res = new ArrayList<>(); for(int i=0;i<=rowIndex;i++){ res.add(c(rowIndex,i)); } return res; } //数学公式C(4,2)=4*3/(1*2); int c(int a,int b){ double res=1; for(int i=1;i<=b;i++){ //res*=(a+1-i)/i; //发生了四舍入五,导致错误; // res=res/i*(a+1-i);//防止溢出,先除后乘;为了防止进位错误,改float; //在高位(27)时余数出错; res=res*(a+1-i)/i; } return (int)res; } }
Albert-W/leetcode
src/Generate2.java
702
//当值为30时出错
line_comment
zh-cn
import java.util.ArrayList; import java.util.List; /* 119. Pascal's Triangle II Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note that the row index starts from 0. In Pascal's triangle, each number is the sum of the two numbers directly above it. Example: Input: 3 Output: [1,3,3,1] Follow up: Could you optimize your algorithm to use only O(k) extra space? */ public class Generate2 { //ArrayList 的set,get O(1); 与Array[]一样; public List<Integer> getRow(int rowIndex) { List<Integer> res = new ArrayList<>(); res.add(1); for(int i=1;i<=rowIndex;i++){ // res.add(res.get(i-1)*(rowIndex+1-i)/i); //当值 <SUF> // res.add((int)((double)(res.get(i-1)*(rowIndex+1-i))/i)); //当值为30时出错 // res.add((int)(double)(res.get(i-1))*(rowIndex+1-i)/i); //当值为30时出错 // res.add((int)((double)(res.get(i-1)))*(rowIndex+1-i)/i); //当值为30时出错 // double t= res.get(i-1)*(rowIndex+1-i); // t=t/i; // res.add((int)t); //通过 // double t= res.get(i-1); // t=t*(rowIndex+1-i)/i; // res.add((int)t); //通过;第一个double强转是不能有多余括号,要立马强转第一个值; res.add((int)((double)res.get(i-1)*(rowIndex+1-i)/i)); } return res; } //O(n2); public List<Integer> getRow2(int rowIndex) { List<Integer> res = new ArrayList<>(); for(int i=0;i<=rowIndex;i++){ res.add(c(rowIndex,i)); } return res; } //数学公式C(4,2)=4*3/(1*2); int c(int a,int b){ double res=1; for(int i=1;i<=b;i++){ //res*=(a+1-i)/i; //发生了四舍入五,导致错误; // res=res/i*(a+1-i);//防止溢出,先除后乘;为了防止进位错误,改float; //在高位(27)时余数出错; res=res*(a+1-i)/i; } return (int)res; } }
0
605
9
702
8
712
7
702
8
809
9
false
false
false
false
false
true
18041_8
package org.sang.service; import org.sang.bean.Position; import org.sang.bean.Status; import org.sang.bean.User; import org.sang.bean.Course; import org.sang.dao.UserDao; import org.sang.dao.CourseDao; import org.sang.dao.CourseParticipantsDao; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author 零 * */ public class CourseService { private CourseDao meetingDao = new CourseDao(); private UserDao employeeDao = new UserDao(); private List<User> emps; private HashMap<User, Status> empssHashMap; public List<User> getEmps() { return emps; } public HashMap<User, Status> getEmpssHashMap() { return empssHashMap; } private CourseParticipantsDao meetingParticipantsDao = new CourseParticipantsDao(); public void insert(Course meeting, String[] empids) { int insert = meetingDao.insert(meeting); meetingParticipantsDao.insert(insert, empids); } public List<Course> searchMeeting(String meetingname, String roomname, String reservername, String reservefromdate, String reservetodate, String meetingfromdate, String meetingtodate, int page, int count) { return meetingDao.searchMeeting(meetingname, roomname, reservername, reservefromdate, reservetodate, meetingfromdate, meetingtodate, page, count); } public int getCount(String meetingname, String roomname, String reservername, String reservefromdate, String reservetodate, String meetingfromdate, String meetingtodate) { return meetingDao.getCount(meetingname, roomname, reservername, reservefromdate, reservetodate, meetingfromdate, meetingtodate); } public Course getMeetingDetailsByMeetingId(int mid) { Course meeting = meetingDao.getMeetingById(mid); this.emps = employeeDao.getEmpByMeetingId(meeting.getMeetingid()); this.empssHashMap= employeeDao.getEmpStatusByUser(this.emps, mid); return meeting; } public List<Course> getCanceledMeeting(int empid) { return meetingDao.getCanceledMeeting(empid); } /** * 获取七天会议 * @param empid * @return */ public List<Course> getMeeting7Days(int empid) { return meetingDao.getMeeting7Days(empid); } /** * 预定会议 * @param empid * @return */ public List<Course> getMyBookingMeeting(int empid) { return meetingDao.getMyBookingMeeting(empid); } /** * 参加 * @param mid * @param reason * @return */ public int attendMeeting(int mid, int userid) { return employeeDao.attendMeeting(mid, userid); } /** * 请假 * @param mid * @param reason * @return */ public int leaveMeeting(int mid, int userid) { return employeeDao.leaveMeeting(mid, userid); } /** * 取消会议 * @param mid * @param reason * @return */ public int cancelMeeting(int mid, String reason) { return meetingDao.cancelMeeting(mid, reason); } /** * 我的会议 * @param empid * @return */ public List<Course> getMyMeeting(int empid) { return meetingDao.getMyMeeting(empid); } /** * 我的参会情况 */ public Map<Course,Status> getMyMeetingcondition(int empid) { return meetingDao.getMyMeetingcondition(empid); } /** * 班级的参会情况 */ public Map<Map<Course, Status>,User> getClassMeetingcondition(int depid) { return meetingDao.getClassMeetingcondition(depid); } /** * 获取位置 * @param parseInt * @return */ public Position getclassroompostionBymid(int mid) { // TODO Auto-generated method stub return meetingDao.getclassroompostionBymid(mid); } }
AldonahZero/classCheck
src/org/sang/service/CourseService.java
1,015
/** * 班级的参会情况 */
block_comment
zh-cn
package org.sang.service; import org.sang.bean.Position; import org.sang.bean.Status; import org.sang.bean.User; import org.sang.bean.Course; import org.sang.dao.UserDao; import org.sang.dao.CourseDao; import org.sang.dao.CourseParticipantsDao; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author 零 * */ public class CourseService { private CourseDao meetingDao = new CourseDao(); private UserDao employeeDao = new UserDao(); private List<User> emps; private HashMap<User, Status> empssHashMap; public List<User> getEmps() { return emps; } public HashMap<User, Status> getEmpssHashMap() { return empssHashMap; } private CourseParticipantsDao meetingParticipantsDao = new CourseParticipantsDao(); public void insert(Course meeting, String[] empids) { int insert = meetingDao.insert(meeting); meetingParticipantsDao.insert(insert, empids); } public List<Course> searchMeeting(String meetingname, String roomname, String reservername, String reservefromdate, String reservetodate, String meetingfromdate, String meetingtodate, int page, int count) { return meetingDao.searchMeeting(meetingname, roomname, reservername, reservefromdate, reservetodate, meetingfromdate, meetingtodate, page, count); } public int getCount(String meetingname, String roomname, String reservername, String reservefromdate, String reservetodate, String meetingfromdate, String meetingtodate) { return meetingDao.getCount(meetingname, roomname, reservername, reservefromdate, reservetodate, meetingfromdate, meetingtodate); } public Course getMeetingDetailsByMeetingId(int mid) { Course meeting = meetingDao.getMeetingById(mid); this.emps = employeeDao.getEmpByMeetingId(meeting.getMeetingid()); this.empssHashMap= employeeDao.getEmpStatusByUser(this.emps, mid); return meeting; } public List<Course> getCanceledMeeting(int empid) { return meetingDao.getCanceledMeeting(empid); } /** * 获取七天会议 * @param empid * @return */ public List<Course> getMeeting7Days(int empid) { return meetingDao.getMeeting7Days(empid); } /** * 预定会议 * @param empid * @return */ public List<Course> getMyBookingMeeting(int empid) { return meetingDao.getMyBookingMeeting(empid); } /** * 参加 * @param mid * @param reason * @return */ public int attendMeeting(int mid, int userid) { return employeeDao.attendMeeting(mid, userid); } /** * 请假 * @param mid * @param reason * @return */ public int leaveMeeting(int mid, int userid) { return employeeDao.leaveMeeting(mid, userid); } /** * 取消会议 * @param mid * @param reason * @return */ public int cancelMeeting(int mid, String reason) { return meetingDao.cancelMeeting(mid, reason); } /** * 我的会议 * @param empid * @return */ public List<Course> getMyMeeting(int empid) { return meetingDao.getMyMeeting(empid); } /** * 我的参会情况 */ public Map<Course,Status> getMyMeetingcondition(int empid) { return meetingDao.getMyMeetingcondition(empid); } /** * 班级的 <SUF>*/ public Map<Map<Course, Status>,User> getClassMeetingcondition(int depid) { return meetingDao.getClassMeetingcondition(depid); } /** * 获取位置 * @param parseInt * @return */ public Position getclassroompostionBymid(int mid) { // TODO Auto-generated method stub return meetingDao.getclassroompostionBymid(mid); } }
0
917
13
1,015
12
1,074
12
1,015
12
1,274
21
false
false
false
false
false
true
8988_5
package ml_model_client; import java.io.BufferedInputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.io.BufferedOutputStream; /** * Connect ML Model. */ public class SocketClient { /** * Result. */ private String result = "error"; /** * Connect to ML Server. * @param data data * @return result */ public String connecting(String data) { // String address = "140.116.245.146"; String address = "127.0.0.1"; int port = 1994; Socket client = new Socket(); InetSocketAddress isa = new InetSocketAddress(address, port); try { client.connect(isa, 10000); BufferedOutputStream out = new BufferedOutputStream(client .getOutputStream()); BufferedInputStream in = new BufferedInputStream(client .getInputStream()); // 送出字串 out.write(data.getBytes("UTF-8")); out.flush(); // 接收字串 byte[] buffer = new byte[1024]; // a read buffer of 5KiB int red = client.getInputStream().read(buffer); byte[] redData = new byte[red]; System.arraycopy(buffer, 0, redData, 0, red); result = new String(redData,"UTF-8"); // assumption that client sends data UTF-8 encoded out.close(); client.close(); } catch (java.io.IOException e) { System.out.println("Socket連線有問題 !"); System.out.println("IOException :" + e.toString()); } return result; } /** * Test * @param args system default */ public static void main(String[] args) { SocketClient socketClient = new SocketClient(); System.out.println(socketClient.connecting("警察 女兒 @所作所為 爸爸 @職位 警察 兄弟@ 姐妹 表現@ 姐姐 妹妹 黑鍋 警察 身 & 所作所為 爸爸")); } }
Alex-CHUN-YU/Recommender-System
RecommenderSystem/app/ml_model_client/SocketClient.java
518
// 接收字串
line_comment
zh-cn
package ml_model_client; import java.io.BufferedInputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.io.BufferedOutputStream; /** * Connect ML Model. */ public class SocketClient { /** * Result. */ private String result = "error"; /** * Connect to ML Server. * @param data data * @return result */ public String connecting(String data) { // String address = "140.116.245.146"; String address = "127.0.0.1"; int port = 1994; Socket client = new Socket(); InetSocketAddress isa = new InetSocketAddress(address, port); try { client.connect(isa, 10000); BufferedOutputStream out = new BufferedOutputStream(client .getOutputStream()); BufferedInputStream in = new BufferedInputStream(client .getInputStream()); // 送出字串 out.write(data.getBytes("UTF-8")); out.flush(); // 接收 <SUF> byte[] buffer = new byte[1024]; // a read buffer of 5KiB int red = client.getInputStream().read(buffer); byte[] redData = new byte[red]; System.arraycopy(buffer, 0, redData, 0, red); result = new String(redData,"UTF-8"); // assumption that client sends data UTF-8 encoded out.close(); client.close(); } catch (java.io.IOException e) { System.out.println("Socket連線有問題 !"); System.out.println("IOException :" + e.toString()); } return result; } /** * Test * @param args system default */ public static void main(String[] args) { SocketClient socketClient = new SocketClient(); System.out.println(socketClient.connecting("警察 女兒 @所作所為 爸爸 @職位 警察 兄弟@ 姐妹 表現@ 姐姐 妹妹 黑鍋 警察 身 & 所作所為 爸爸")); } }
0
469
6
518
5
527
5
518
5
619
6
false
false
false
false
false
true
40303_1
package CommonAPI; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexDemo { public static void main(String[] args) { /* 有如下文本: “当好中国式现代化建设的坚定行动派、实干家”, 这是习近平总书记提出的明确要求。全国两会结束不到一周,习近平总书记赴湖南考察, 并在长沙主持召开新时代推动中部地区崛起座谈会,强调“地方党委和政府要扛起主体责任, 坚决贯彻党中央决策部署,推动重点工作任务、重大改革事项落实落地”。*/ //要统计国字出现的次数 String str = "当好中国式现代化建设的坚定行动派、实干家,这是习近平总书记提出的明确要求。全国两会结束不到一周,习近平总书记赴湖南考察,并在长沙主持召开新时代推动中部地区崛起座谈会,强调“地方党委和政府要扛起主体责任,坚决贯彻党中央决策部署,推动重点工作任务、重大改革事项落实落地”。"; //Pattern 是正则表达式 //Matcher 文本匹配器,作用按照正则表达式的规则从头开始读取字符串 Pattern p = Pattern.compile("中"); Matcher m = p.matcher(str); boolean b = m.find(); int count = 0; String s = m.group(); System.out.println(s); while (b) { count++; b = m.find(); } System.out.println("中字出现的次数为:" + count); //下面是正则表达式的一些基本规则 //部分匹配但是只取出来完全匹配的部分 String str1 = "Java的版本有:Java8、Java11、Java17"; String regex = "Java(?=8|11|17)"; Pattern pp = Pattern.compile(regex); //编译正则表达式 Matcher mm = pp.matcher(str1); //创建匹配器 while (mm.find()) { System.out.println(mm.group()); } //忽略大小写的匹配 String str2 = "Java的版本有:JAVa8、Java11、Java17"; String regex2 = "((?i)java)"; Pattern p2 = Pattern.compile(regex2); Matcher m2 = p2.matcher(str2); while (m2.find()) { System.out.println(m2.group()); } } }
Alex-hwang/AdvancedPart
src/CommonAPI/RegexDemo.java
664
//要统计国字出现的次数
line_comment
zh-cn
package CommonAPI; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexDemo { public static void main(String[] args) { /* 有如下文本: “当好中国式现代化建设的坚定行动派、实干家”, 这是习近平总书记提出的明确要求。全国两会结束不到一周,习近平总书记赴湖南考察, 并在长沙主持召开新时代推动中部地区崛起座谈会,强调“地方党委和政府要扛起主体责任, 坚决贯彻党中央决策部署,推动重点工作任务、重大改革事项落实落地”。*/ //要统 <SUF> String str = "当好中国式现代化建设的坚定行动派、实干家,这是习近平总书记提出的明确要求。全国两会结束不到一周,习近平总书记赴湖南考察,并在长沙主持召开新时代推动中部地区崛起座谈会,强调“地方党委和政府要扛起主体责任,坚决贯彻党中央决策部署,推动重点工作任务、重大改革事项落实落地”。"; //Pattern 是正则表达式 //Matcher 文本匹配器,作用按照正则表达式的规则从头开始读取字符串 Pattern p = Pattern.compile("中"); Matcher m = p.matcher(str); boolean b = m.find(); int count = 0; String s = m.group(); System.out.println(s); while (b) { count++; b = m.find(); } System.out.println("中字出现的次数为:" + count); //下面是正则表达式的一些基本规则 //部分匹配但是只取出来完全匹配的部分 String str1 = "Java的版本有:Java8、Java11、Java17"; String regex = "Java(?=8|11|17)"; Pattern pp = Pattern.compile(regex); //编译正则表达式 Matcher mm = pp.matcher(str1); //创建匹配器 while (mm.find()) { System.out.println(mm.group()); } //忽略大小写的匹配 String str2 = "Java的版本有:JAVa8、Java11、Java17"; String regex2 = "((?i)java)"; Pattern p2 = Pattern.compile(regex2); Matcher m2 = p2.matcher(str2); while (m2.find()) { System.out.println(m2.group()); } } }
0
504
8
662
8
591
7
664
8
924
11
false
false
false
false
false
true
38876_7
package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.SplitPane; import javafx.scene.control.TextField; import javafx.stage.Stage; import javax.swing.*; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; public class ControllerLoginPatient { @FXML private Button btn_login; @FXML private Button btn_back; @FXML private TextField field_number; @FXML private TextField field_password; public static String loginedPid; //静态字符串,用于controller之间传递参数 public String getLoginedPid(){ return loginedPid; } //回车键登录 public void onEnter(){ on_btn_login_clicked(); } //病人登录 public void on_btn_login_clicked(){ Connection connection=new MySQLConnector().connection(); if(connection==null){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("连接数据库失败!"); alert.showAndWait(); } else{ if(field_number.getText().equals("")){ //编号输入为空 Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("病人编号不可为空"); alert.showAndWait(); return; } try { String sql="select * from patient where pid=?"; PreparedStatement preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1,field_number.getText()); ResultSet rs=preparedStatement.executeQuery(); if(!(rs.next())){ //找不到编号 Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("找不到该编号"); alert.showAndWait(); return; } String realPassword=rs.getString("password"); String inputPassword=field_password.getText(); if(!(realPassword.equals(inputPassword))) {//密码错误 Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("密码错误"); alert.showAndWait();} else{ //登录成功,更新登录日期 String pid=rs.getString("pid"); loginedPid=pid; String currentTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); //获取登陆时间 String sql2="update patient set last_login_datetime =? where pid=?"; preparedStatement=connection.prepareStatement(sql2); preparedStatement.setString(1,currentTime); preparedStatement.setString(2,pid); preparedStatement.executeUpdate(); Stage currentStage=(Stage)btn_login.getScene().getWindow(); currentStage.close(); //关闭当前窗口 SplitPane root=FXMLLoader.load(getClass().getResource("RegisterPatient.fxml")); //转到挂号界面 Stage newStage=new Stage(); newStage.setTitle("病人挂号"); newStage.setScene(new Scene(root)); newStage.show(); preparedStatement.close(); connection.close(); } } catch (SQLException | IOException e){ e.printStackTrace(); } } } //返回 public void on_btn_back_clicked() throws IOException { Stage currentStage=(Stage)btn_login.getScene().getWindow(); currentStage.close(); //关闭当前窗口 SplitPane root=FXMLLoader.load(getClass().getResource("Login.fxml")); Stage newStage=new Stage(); newStage.setTitle("登录"); newStage.setScene(new Scene(root)); newStage.show(); } }
AlexFanw/HUSTER-CS
Java实验/java实验二/hospital/src/sample/ControllerLoginPatient.java
878
//获取登陆时间
line_comment
zh-cn
package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.SplitPane; import javafx.scene.control.TextField; import javafx.stage.Stage; import javax.swing.*; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.Date; public class ControllerLoginPatient { @FXML private Button btn_login; @FXML private Button btn_back; @FXML private TextField field_number; @FXML private TextField field_password; public static String loginedPid; //静态字符串,用于controller之间传递参数 public String getLoginedPid(){ return loginedPid; } //回车键登录 public void onEnter(){ on_btn_login_clicked(); } //病人登录 public void on_btn_login_clicked(){ Connection connection=new MySQLConnector().connection(); if(connection==null){ Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("连接数据库失败!"); alert.showAndWait(); } else{ if(field_number.getText().equals("")){ //编号输入为空 Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("病人编号不可为空"); alert.showAndWait(); return; } try { String sql="select * from patient where pid=?"; PreparedStatement preparedStatement=connection.prepareStatement(sql); preparedStatement.setString(1,field_number.getText()); ResultSet rs=preparedStatement.executeQuery(); if(!(rs.next())){ //找不到编号 Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("找不到该编号"); alert.showAndWait(); return; } String realPassword=rs.getString("password"); String inputPassword=field_password.getText(); if(!(realPassword.equals(inputPassword))) {//密码错误 Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setHeaderText("密码错误"); alert.showAndWait();} else{ //登录成功,更新登录日期 String pid=rs.getString("pid"); loginedPid=pid; String currentTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); //获取 <SUF> String sql2="update patient set last_login_datetime =? where pid=?"; preparedStatement=connection.prepareStatement(sql2); preparedStatement.setString(1,currentTime); preparedStatement.setString(2,pid); preparedStatement.executeUpdate(); Stage currentStage=(Stage)btn_login.getScene().getWindow(); currentStage.close(); //关闭当前窗口 SplitPane root=FXMLLoader.load(getClass().getResource("RegisterPatient.fxml")); //转到挂号界面 Stage newStage=new Stage(); newStage.setTitle("病人挂号"); newStage.setScene(new Scene(root)); newStage.show(); preparedStatement.close(); connection.close(); } } catch (SQLException | IOException e){ e.printStackTrace(); } } } //返回 public void on_btn_back_clicked() throws IOException { Stage currentStage=(Stage)btn_login.getScene().getWindow(); currentStage.close(); //关闭当前窗口 SplitPane root=FXMLLoader.load(getClass().getResource("Login.fxml")); Stage newStage=new Stage(); newStage.setTitle("登录"); newStage.setScene(new Scene(root)); newStage.show(); } }
0
724
4
878
5
936
4
878
5
1,137
9
false
false
false
false
false
true
21010_3
package com.swagger.offline.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @version V1.0 * @Title: * @ClassName: User.java * @Description: * @Copyright 2016-2018 - Powered By 研发中心 * @author: 王延飞 * @date: 2018-01-22 16:06 */ @ApiModel(value = "User", description = "用户信息描述") public class User { /** * 学号 */ @ApiModelProperty("证件号") private int id; /** * 姓名 */ @ApiModelProperty("姓名") private String name; /** * 年龄 */ @ApiModelProperty("年龄") private int age; /** * 性别 */ @ApiModelProperty("性别") private String sex; /** * 住址 */ @ApiModelProperty("家庭住址") private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } }
AlexFly666/SwaggerOfflineDoc
src/main/java/com/swagger/offline/model/User.java
467
/** * 年龄 */
block_comment
zh-cn
package com.swagger.offline.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @version V1.0 * @Title: * @ClassName: User.java * @Description: * @Copyright 2016-2018 - Powered By 研发中心 * @author: 王延飞 * @date: 2018-01-22 16:06 */ @ApiModel(value = "User", description = "用户信息描述") public class User { /** * 学号 */ @ApiModelProperty("证件号") private int id; /** * 姓名 */ @ApiModelProperty("姓名") private String name; /** * 年龄 <SUF>*/ @ApiModelProperty("年龄") private int age; /** * 性别 */ @ApiModelProperty("性别") private String sex; /** * 住址 */ @ApiModelProperty("家庭住址") private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + ", address='" + address + '\'' + '}'; } }
0
433
9
467
8
511
9
467
8
612
12
false
false
false
false
false
true
60226_8
//创建回形矩阵 /** * 具体思路: * 一共三个部分,填充数字、确定方向、打印数字 * 使用switch根据方向填充数字(二维数组) * 通过判断转弯条件实现控制方向 * 利用循环打印二维数组 */ public class ch1_8{ static enum Direction{ Right,Down,Left,Up; }//方向是常量,用枚举 //创建填充数字方法 public static void initialArray() { int row=0, col=0;//第一个数字 for (int c=0; c<length*length;c++) { snake[row][col] = value; lastDirection = findDirection(row,col); //根据方向,填充数字 switch (lastDirection) { case Right: col++; break; case Down: row++; break; case Left: col--; break; case Up: row--; break; default: System.out.println("error"); } value++; } } //创建确定下一步方向的方法 static Direction findDirection(int row, int col) { Direction direction = lastDirection; switch (direction) { case Right:{ //如果向右到尽头则向下 if (col == length-1 || snake[row][col+1] !=0) direction = direction.Down; break; } case Down:{ //如果向下到尽头则向左 if (row == length-1 || snake[row+1][col] !=0) direction = direction.Left; break; } case Left:{ //如果向左到尽头则向上 if (col == 0 || snake[row][col-1] !=0) direction = direction.Up; break; } case Up:{ //如果向上到尽头则向右 if (snake[row-1][col] !=0) direction = direction.Right; break; } } return direction; //返回方向 } //创建print方法 static void print(int[][] arr) { for (int i=0; i<length; i++) { for (int j=0; j<length; j++) { System.out.printf("%5d",arr[i][j]); //每个数字占5位 } System.out.println(); //换行 } } //进行初始赋值 static int length = 12; // 确定行数 static int value = 1; // 确定第一个数字 static int[][] snake = new int [length][length]; // 创建二维数组 static Direction lastDirection = Direction.Right; // 确定初始方向:向右 //运行主程序 public static void main(String[] args) { initialArray(); //填充数字 print(snake); //打印数字 } }
AlexLee522/100-examples-of-Java-interesting-programming-
ch1_8.java
724
//如果向下到尽头则向左
line_comment
zh-cn
//创建回形矩阵 /** * 具体思路: * 一共三个部分,填充数字、确定方向、打印数字 * 使用switch根据方向填充数字(二维数组) * 通过判断转弯条件实现控制方向 * 利用循环打印二维数组 */ public class ch1_8{ static enum Direction{ Right,Down,Left,Up; }//方向是常量,用枚举 //创建填充数字方法 public static void initialArray() { int row=0, col=0;//第一个数字 for (int c=0; c<length*length;c++) { snake[row][col] = value; lastDirection = findDirection(row,col); //根据方向,填充数字 switch (lastDirection) { case Right: col++; break; case Down: row++; break; case Left: col--; break; case Up: row--; break; default: System.out.println("error"); } value++; } } //创建确定下一步方向的方法 static Direction findDirection(int row, int col) { Direction direction = lastDirection; switch (direction) { case Right:{ //如果向右到尽头则向下 if (col == length-1 || snake[row][col+1] !=0) direction = direction.Down; break; } case Down:{ //如果 <SUF> if (row == length-1 || snake[row+1][col] !=0) direction = direction.Left; break; } case Left:{ //如果向左到尽头则向上 if (col == 0 || snake[row][col-1] !=0) direction = direction.Up; break; } case Up:{ //如果向上到尽头则向右 if (snake[row-1][col] !=0) direction = direction.Right; break; } } return direction; //返回方向 } //创建print方法 static void print(int[][] arr) { for (int i=0; i<length; i++) { for (int j=0; j<length; j++) { System.out.printf("%5d",arr[i][j]); //每个数字占5位 } System.out.println(); //换行 } } //进行初始赋值 static int length = 12; // 确定行数 static int value = 1; // 确定第一个数字 static int[][] snake = new int [length][length]; // 创建二维数组 static Direction lastDirection = Direction.Right; // 确定初始方向:向右 //运行主程序 public static void main(String[] args) { initialArray(); //填充数字 print(snake); //打印数字 } }
0
638
8
724
10
718
9
724
10
1,011
13
false
false
false
false
false
true
18351_11
package common.dp; /** * @author luoyuntian * @program: p40-algorithm * @description: 背包问题 * @date 2022-02-27 14:57:21 */ public class Knapsack { public static int maxValue1(int [] weight,int[] value,int bagLimit){ return process1(weight,value,0,bagLimit); } // 递归实现 // 在0 .... n-1中0...index-1已经不能选了 // index... n-1这些货,自由选择 // 背包还剩下多少容量,rest,自由挑选是不能超过rest的 // index...n-1 在符合要求的情况下,最大价值能达多少 public static int process1(int[] weight,int[] value,int index,int rest){ // 剩余的负重是负数,说明之前的选择是错误的 if(rest < 0){ // 返回无效解 return -1; } // rest >=0去且无货了 if(index == weight.length){ return 0; } // 既有负重,又有货 // 第一种选择:当前index位置的货,没要 int p1 = process1(weight,value,index+1,rest); // 第二种选择:当前index位置的货,要 int p2 = -1; int next = process1(weight,value,index+1,rest-weight[index]); if(next != -1){ p2 = value[index] + next; } return Math.max(p1,p2); } public static int maxValue2(int [] weight,int[] value,int bagLimit){ int n = weight.length; // index:0... n // bag:100 0...100 int[][] dp = new int[n+1][bagLimit+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=bagLimit;j++){ dp[i][j] = -2; } } return process2(weight,value,0,bagLimit,dp); } public static int process2(int[] weight,int[] value,int index,int rest,int[][] dp){ if(rest < 0){ return -1; } // 缓存命中,以前算过 if(dp[index][rest]!=-2){ return dp[index][rest]; } // 缓存没命中 int ans = 0; if(index == weight.length){ ans = 0; }else { // 既有负重,又有货 // 第一种选择:当前index位置的货,没要 int p1 = process2(weight,value,index+1,rest,dp); // 第二种选择:当前index位置的货,要 int p2 = -1; int next = process2(weight,value,index+1,rest-weight[index],dp); if(next != -1){ p2 = value[index] + next; } ans = Math.max(p1,p2); } dp[index][rest] = ans; return ans; } }
AlexNOCoder/p40-algorithm
src/main/java/common/dp/Knapsack.java
773
// 第二种选择:当前index位置的货,要
line_comment
zh-cn
package common.dp; /** * @author luoyuntian * @program: p40-algorithm * @description: 背包问题 * @date 2022-02-27 14:57:21 */ public class Knapsack { public static int maxValue1(int [] weight,int[] value,int bagLimit){ return process1(weight,value,0,bagLimit); } // 递归实现 // 在0 .... n-1中0...index-1已经不能选了 // index... n-1这些货,自由选择 // 背包还剩下多少容量,rest,自由挑选是不能超过rest的 // index...n-1 在符合要求的情况下,最大价值能达多少 public static int process1(int[] weight,int[] value,int index,int rest){ // 剩余的负重是负数,说明之前的选择是错误的 if(rest < 0){ // 返回无效解 return -1; } // rest >=0去且无货了 if(index == weight.length){ return 0; } // 既有负重,又有货 // 第一种选择:当前index位置的货,没要 int p1 = process1(weight,value,index+1,rest); // 第二 <SUF> int p2 = -1; int next = process1(weight,value,index+1,rest-weight[index]); if(next != -1){ p2 = value[index] + next; } return Math.max(p1,p2); } public static int maxValue2(int [] weight,int[] value,int bagLimit){ int n = weight.length; // index:0... n // bag:100 0...100 int[][] dp = new int[n+1][bagLimit+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=bagLimit;j++){ dp[i][j] = -2; } } return process2(weight,value,0,bagLimit,dp); } public static int process2(int[] weight,int[] value,int index,int rest,int[][] dp){ if(rest < 0){ return -1; } // 缓存命中,以前算过 if(dp[index][rest]!=-2){ return dp[index][rest]; } // 缓存没命中 int ans = 0; if(index == weight.length){ ans = 0; }else { // 既有负重,又有货 // 第一种选择:当前index位置的货,没要 int p1 = process2(weight,value,index+1,rest,dp); // 第二种选择:当前index位置的货,要 int p2 = -1; int next = process2(weight,value,index+1,rest-weight[index],dp); if(next != -1){ p2 = value[index] + next; } ans = Math.max(p1,p2); } dp[index][rest] = ans; return ans; } }
0
703
13
773
13
810
12
773
13
964
21
false
false
false
false
false
true
34774_0
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .host("localhost:8080") .select() //为当前包路径 .apis(RequestHandlerSelectors.basePackage("controller")) .paths(PathSelectors.any()) .build(); } //构建 api文档的详细信息函数,注意这里的注解引用的是哪个 private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title("Spring Boot测试使用 Swagger2 构建RESTful API") //版本号 .version("1.0") //描述 .description("API 描述") .build(); } }
AlexanderChiuluvB/DistrubutedSystemProject
demo/src/main/java/Swagger2.java
299
//为当前包路径
line_comment
zh-cn
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .host("localhost:8080") .select() //为当 <SUF> .apis(RequestHandlerSelectors.basePackage("controller")) .paths(PathSelectors.any()) .build(); } //构建 api文档的详细信息函数,注意这里的注解引用的是哪个 private ApiInfo apiInfo() { return new ApiInfoBuilder() //页面标题 .title("Spring Boot测试使用 Swagger2 构建RESTful API") //版本号 .version("1.0") //描述 .description("API 描述") .build(); } }
0
250
5
299
5
306
5
299
5
378
9
false
false
false
false
false
true
16014_4
package array; import java.util.*; /** * @author Fer * date 2022/8/22 */ public class ThreeSum { /** * 在给定数组中找出不重复的三个数,使得 a + b + c = 0 * 思想:暴力解法,三次循环 + 去重(会超时) * 优化:先将数组排序,减少重复枚举的次数,对于每一重循环,相邻两次枚举的元素不能相同 * 双指针(第二重和第三重循环并列) */ public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new LinkedList<>(); int len = nums.length; if (len < 3) { return res; } for (int i = 0; i < len-2; i++) { for (int j = i+1; j < len-1; j++) { for (int k = j+1; k < len; k++) { if (nums[i] + nums[j] + nums[k] == 0) { List<Integer> list = new LinkedList<>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[k]); Collections.sort(list); if (!res.contains(list)) { res.add(list); } } } } } return res; } public List<List<Integer>> threeSum1(int[] nums) { List<List<Integer>> res = new ArrayList<>(); int len = nums.length; if (len < 3) { return res; } // 排序 Arrays.sort(nums); // 从前往后枚举第一个元素 for (int first = 0; first < len; first++) { if (first > 0 && nums[first] == nums[first-1]) { continue; } // c 从右往左遍历 int third = len-1; int target = -nums[first]; for (int second = first+1; second < len; second++) { if (second > first + 1 && nums[second-1] == nums[second]) { continue; } // 保证 b 的指针在 c 的指针左侧 while (second < third && nums[second] + nums[third] > target) { --third; } // 当两个指针相遇了,终止循环 if (second == third) { break; } if (nums[second] + nums[third] == target) { List<Integer> list = new ArrayList<>(); list.add(nums[first]); list.add(nums[second]); list.add(nums[third]); res.add(list); } } } return res; } }
AlivinFer/leetcode-Java
src/array/ThreeSum.java
668
// 保证 b 的指针在 c 的指针左侧
line_comment
zh-cn
package array; import java.util.*; /** * @author Fer * date 2022/8/22 */ public class ThreeSum { /** * 在给定数组中找出不重复的三个数,使得 a + b + c = 0 * 思想:暴力解法,三次循环 + 去重(会超时) * 优化:先将数组排序,减少重复枚举的次数,对于每一重循环,相邻两次枚举的元素不能相同 * 双指针(第二重和第三重循环并列) */ public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new LinkedList<>(); int len = nums.length; if (len < 3) { return res; } for (int i = 0; i < len-2; i++) { for (int j = i+1; j < len-1; j++) { for (int k = j+1; k < len; k++) { if (nums[i] + nums[j] + nums[k] == 0) { List<Integer> list = new LinkedList<>(); list.add(nums[i]); list.add(nums[j]); list.add(nums[k]); Collections.sort(list); if (!res.contains(list)) { res.add(list); } } } } } return res; } public List<List<Integer>> threeSum1(int[] nums) { List<List<Integer>> res = new ArrayList<>(); int len = nums.length; if (len < 3) { return res; } // 排序 Arrays.sort(nums); // 从前往后枚举第一个元素 for (int first = 0; first < len; first++) { if (first > 0 && nums[first] == nums[first-1]) { continue; } // c 从右往左遍历 int third = len-1; int target = -nums[first]; for (int second = first+1; second < len; second++) { if (second > first + 1 && nums[second-1] == nums[second]) { continue; } // 保证 <SUF> while (second < third && nums[second] + nums[third] > target) { --third; } // 当两个指针相遇了,终止循环 if (second == third) { break; } if (nums[second] + nums[third] == target) { List<Integer> list = new ArrayList<>(); list.add(nums[first]); list.add(nums[second]); list.add(nums[third]); res.add(list); } } } return res; } }
0
615
13
667
12
718
11
668
12
884
25
false
false
false
false
false
true
31203_2
import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.Closeable; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; /** * Created by Hua on 2016/1/22. */ public class HttpMonitor { String viewState; String imageCode; private CloseableHttpClient httpClient; public HttpMonitor(String viewState, String imageCode, CloseableHttpClient httpClient) { this.viewState = viewState; this.imageCode = imageCode; this.httpClient = httpClient; } private boolean getLoginState() throws UnsupportedEncodingException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("__VIEWSTATE", this.viewState)); nvps.add(new BasicNameValuePair("txtUserName", "XXXXXXXXXXXXX"));//在此输入你的学号 nvps.add(new BasicNameValuePair("TextBox2","XXXXXXX"));//在此输入你的密码 nvps.add(new BasicNameValuePair("txtSecretCode", imageCode)); nvps.add(new BasicNameValuePair("RadioButtonList1", "学生")); nvps.add(new BasicNameValuePair("Button1", "登录")); HttpPost httpost = new HttpPost("http://jw.hzau.edu.cn/default2.aspx"); httpost.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpost.addHeader("Accept-Encoding","gzip, deflate, sdch"); httpost.addHeader("Accept-Language","zh-CN,zh;q=0.8"); httpost.addHeader("Cache-Control","max-age=0"); httpost.addHeader("Connection","keep-alive"); httpost.addHeader("Host","jw.hzau.edu.cn"); httpost.addHeader("Referer","http://jw.hzau.edu.cn/default2.aspx"); httpost.addHeader("Upgrade-Insecure-Requests","1"); httpost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36"); httpost.setEntity(new UrlEncodedFormEntity(nvps,"GB2312")); CloseableHttpResponse response; try { response = this.httpClient.execute(httpost); /*登陆成功后会返回302跳转*/ //System.out.println(EntityUtils.toString(response.getEntity())); String result = response.getStatusLine().toString(); System.out.println(result); if(result.equals("HTTP/1.1 302 Found")){ response.close(); return true; }else{ return false; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } public void getStuName(){ } public void getSchedule() throws IOException { List<NameValuePair> list = new ArrayList<>(); list.add(new BasicNameValuePair("xh","XXXXXXXXXXX")); list.add(new BasicNameValuePair("xm","华昕"));//在此填入姓名 list.add(new BasicNameValuePair("gnmkdm","N121608")); String s = URLEncodedUtils.format(list,"GB2312"); HttpGet httpGet = new HttpGet("http://jw.hzau.edu.cn/xsjccx.aspx?"+s); System.out.println(s); httpGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpGet.addHeader("Accept-Encoding","gzip, deflate, sdch"); httpGet.addHeader("Accept-Language","zh-CN,zh;q=0.8"); httpGet.addHeader("Cache-Control","max-age=0"); httpGet.addHeader("Connection","keep-alive"); httpGet.addHeader("Host","jw.hzau.edu.cn"); httpGet.addHeader("Referer","http://jw.hzau.edu.cn/xs_main.aspx?xh=XXXXXXXXXXXXX"); httpGet.addHeader("Upgrade-Insecure-Requests","1"); httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36"); CloseableHttpResponse response; System.out.println("正在查询教材信息…………"); response = httpClient.execute(httpGet); System.out.println("正在查询教材信息…………"); int staus = response.getStatusLine().getStatusCode(); if (staus == 200){ System.out.println("查询教材信息成功!"); System.out.println(EntityUtils.toString(response.getEntity())); } } public void run() { try { //System.out.println(getLoginState()); if (getLoginState()){ System.out.println("登陆成功!!"); getSchedule(); }else { System.out.println("验证码错误!!"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { System.out.println("查询失败"); e.printStackTrace(); } } public static void main(String[] args) { //getUrl("",""); } }
Allenhua/HzauStudy
src/HttpMonitor.java
1,486
//在此输入你的密码
line_comment
zh-cn
import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.Closeable; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; /** * Created by Hua on 2016/1/22. */ public class HttpMonitor { String viewState; String imageCode; private CloseableHttpClient httpClient; public HttpMonitor(String viewState, String imageCode, CloseableHttpClient httpClient) { this.viewState = viewState; this.imageCode = imageCode; this.httpClient = httpClient; } private boolean getLoginState() throws UnsupportedEncodingException { List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("__VIEWSTATE", this.viewState)); nvps.add(new BasicNameValuePair("txtUserName", "XXXXXXXXXXXXX"));//在此输入你的学号 nvps.add(new BasicNameValuePair("TextBox2","XXXXXXX"));//在此 <SUF> nvps.add(new BasicNameValuePair("txtSecretCode", imageCode)); nvps.add(new BasicNameValuePair("RadioButtonList1", "学生")); nvps.add(new BasicNameValuePair("Button1", "登录")); HttpPost httpost = new HttpPost("http://jw.hzau.edu.cn/default2.aspx"); httpost.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpost.addHeader("Accept-Encoding","gzip, deflate, sdch"); httpost.addHeader("Accept-Language","zh-CN,zh;q=0.8"); httpost.addHeader("Cache-Control","max-age=0"); httpost.addHeader("Connection","keep-alive"); httpost.addHeader("Host","jw.hzau.edu.cn"); httpost.addHeader("Referer","http://jw.hzau.edu.cn/default2.aspx"); httpost.addHeader("Upgrade-Insecure-Requests","1"); httpost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36"); httpost.setEntity(new UrlEncodedFormEntity(nvps,"GB2312")); CloseableHttpResponse response; try { response = this.httpClient.execute(httpost); /*登陆成功后会返回302跳转*/ //System.out.println(EntityUtils.toString(response.getEntity())); String result = response.getStatusLine().toString(); System.out.println(result); if(result.equals("HTTP/1.1 302 Found")){ response.close(); return true; }else{ return false; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } public void getStuName(){ } public void getSchedule() throws IOException { List<NameValuePair> list = new ArrayList<>(); list.add(new BasicNameValuePair("xh","XXXXXXXXXXX")); list.add(new BasicNameValuePair("xm","华昕"));//在此填入姓名 list.add(new BasicNameValuePair("gnmkdm","N121608")); String s = URLEncodedUtils.format(list,"GB2312"); HttpGet httpGet = new HttpGet("http://jw.hzau.edu.cn/xsjccx.aspx?"+s); System.out.println(s); httpGet.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpGet.addHeader("Accept-Encoding","gzip, deflate, sdch"); httpGet.addHeader("Accept-Language","zh-CN,zh;q=0.8"); httpGet.addHeader("Cache-Control","max-age=0"); httpGet.addHeader("Connection","keep-alive"); httpGet.addHeader("Host","jw.hzau.edu.cn"); httpGet.addHeader("Referer","http://jw.hzau.edu.cn/xs_main.aspx?xh=XXXXXXXXXXXXX"); httpGet.addHeader("Upgrade-Insecure-Requests","1"); httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36"); CloseableHttpResponse response; System.out.println("正在查询教材信息…………"); response = httpClient.execute(httpGet); System.out.println("正在查询教材信息…………"); int staus = response.getStatusLine().getStatusCode(); if (staus == 200){ System.out.println("查询教材信息成功!"); System.out.println(EntityUtils.toString(response.getEntity())); } } public void run() { try { //System.out.println(getLoginState()); if (getLoginState()){ System.out.println("登陆成功!!"); getSchedule(); }else { System.out.println("验证码错误!!"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { System.out.println("查询失败"); e.printStackTrace(); } } public static void main(String[] args) { //getUrl("",""); } }
0
1,263
5
1,486
6
1,538
5
1,486
6
1,806
9
false
false
false
false
false
true
60261_15
package greed_game; import java.util.Random; public class PlayerManager { public void start(Player[] players,int playerNum,Dices dices) { sortPlayers(players,playerNum); boolean gameOver = false; int playerIdx=-1; /*全部人还没入局*/ do { playerIdx = (playerIdx+1)%playerNum; dices.reset(); Player curPlayer=players[playerIdx]; PlayView.nowTurnPlayer(curPlayer.getName(),(curPlayer instanceof Human),curPlayer.getTotalScore()); while(true) { PlayView.nowTurnDicesTotal(dices.getNumber()); PlayView.nowaskDices(curPlayer.getName()); boolean choice = players[playerIdx].makeChoice(dices); if(choice) { PlayView.rollPointOut(curPlayer.getName(),dices.getPoint(),dices.getNumber()); int rollScore = countAndRemove(dices); PlayView.rollScoreOut(rollScore); if(!curPlayer.isEnrolled()) { if(rollScore < 300) { //”未入局“ PlayView.isNotEnrolledOut(curPlayer.getName()); break; } else { //”入局“ PlayView.isEnrolledOut(curPlayer.getName()); curPlayer.setEnrolled(); } } if(rollScore == 0) { //“本回合得分为零,玩家回合结束” curPlayer.clearTurnScore(); PlayView.playerTurnEndOut(curPlayer.getTurnScore()); break; } curPlayer.addTurnScore(rollScore); //“玩家本回合得分为turnScore” PlayView.scoreUntilNowOut(curPlayer.getName(),curPlayer.getTurnScore()); if(dices.getNumber() == 0) { //“没有剩余骰子,玩家回合结束” PlayView.noDicesLeftOut(); //curPlayer.addTotalScore(); //curPlayer.clearTurnScore(); //"xxw玩家当前总得分为:" break; } } else { //"xx玩家放弃投掷,玩家回合结束" PlayView.playerGiveupOut(curPlayer.getName()); //curPlayer.addTotalScore(); //curPlayer.clearTurnScore(); //"xxw玩家当前总得分为:" break; } } //"玩家回合结束" curPlayer.addTotalScore(curPlayer.getTurnScore()); curPlayer.clearTurnScore(); //打印玩家信息 PlayView.playerTotalOut(curPlayer.getName(),curPlayer.getTotalScore()); if(curPlayer.getTotalScore() >= 3000) { //“宣布胜者,本局游戏结束” gameOver = true; PlayView.winnerOut(curPlayer.getName()); break; } // PlayView.waitingConfirm(); }while(!gameOver); } public int countAndRemove(Dices dices) { int now_roll_number=dices.getNumber(); int[] rollscore=dices.getPoint(); int[] roll=new int[7]; for(int score=1;score<=6;score++) roll[score]=0; for(int dicesid=0;dicesid<now_roll_number;dicesid++) roll[rollscore[dicesid]]++; int nowscore=0,decroll=0; if (roll[1]==6) { roll[1]-=6; nowscore+=3000; decroll+=6; } if (roll[1]>=3) { roll[1]-=3; nowscore+=1000; decroll+=3; } for(int score=2;score<=6;score++) { if (roll[score]>=3) { roll[score]-=3; nowscore+=score*100; decroll+=3; } if (roll[score]>=3) { roll[score]-=3; nowscore+=score*100; decroll+=3; } } while (roll[1]>0) { roll[1]--; nowscore+=100; decroll++; } while (roll[5]>0) { roll[5]--; nowscore+=50; decroll++; } dices.removeDices(decroll); return nowscore; } public void sortPlayers(Player[] players,int playerNum) { Random rand = new Random(); Player tmpPlayer; for(int i=0;i<playerNum;i++) { int now=rand.nextInt(i+1); // Player swapPlayer=players[now]; tmpPlayer=players[now]; players[now]=players[i]; players[i]=tmpPlayer; // System.out.println(now+":"+tmpPlayer.getName()+","+players[now].getName()+","+players[i].getName()); } String[] name=new String[playerNum]; for(int i=0;i<playerNum;i++) { name[i]=players[i].getName(); } PlayView.shuffledPlayerOut(name,playerNum); } }
Alnitak-Antares/Greed-Dice-Game
PlayerManager.java
1,269
//“宣布胜者,本局游戏结束”
line_comment
zh-cn
package greed_game; import java.util.Random; public class PlayerManager { public void start(Player[] players,int playerNum,Dices dices) { sortPlayers(players,playerNum); boolean gameOver = false; int playerIdx=-1; /*全部人还没入局*/ do { playerIdx = (playerIdx+1)%playerNum; dices.reset(); Player curPlayer=players[playerIdx]; PlayView.nowTurnPlayer(curPlayer.getName(),(curPlayer instanceof Human),curPlayer.getTotalScore()); while(true) { PlayView.nowTurnDicesTotal(dices.getNumber()); PlayView.nowaskDices(curPlayer.getName()); boolean choice = players[playerIdx].makeChoice(dices); if(choice) { PlayView.rollPointOut(curPlayer.getName(),dices.getPoint(),dices.getNumber()); int rollScore = countAndRemove(dices); PlayView.rollScoreOut(rollScore); if(!curPlayer.isEnrolled()) { if(rollScore < 300) { //”未入局“ PlayView.isNotEnrolledOut(curPlayer.getName()); break; } else { //”入局“ PlayView.isEnrolledOut(curPlayer.getName()); curPlayer.setEnrolled(); } } if(rollScore == 0) { //“本回合得分为零,玩家回合结束” curPlayer.clearTurnScore(); PlayView.playerTurnEndOut(curPlayer.getTurnScore()); break; } curPlayer.addTurnScore(rollScore); //“玩家本回合得分为turnScore” PlayView.scoreUntilNowOut(curPlayer.getName(),curPlayer.getTurnScore()); if(dices.getNumber() == 0) { //“没有剩余骰子,玩家回合结束” PlayView.noDicesLeftOut(); //curPlayer.addTotalScore(); //curPlayer.clearTurnScore(); //"xxw玩家当前总得分为:" break; } } else { //"xx玩家放弃投掷,玩家回合结束" PlayView.playerGiveupOut(curPlayer.getName()); //curPlayer.addTotalScore(); //curPlayer.clearTurnScore(); //"xxw玩家当前总得分为:" break; } } //"玩家回合结束" curPlayer.addTotalScore(curPlayer.getTurnScore()); curPlayer.clearTurnScore(); //打印玩家信息 PlayView.playerTotalOut(curPlayer.getName(),curPlayer.getTotalScore()); if(curPlayer.getTotalScore() >= 3000) { //“宣 <SUF> gameOver = true; PlayView.winnerOut(curPlayer.getName()); break; } // PlayView.waitingConfirm(); }while(!gameOver); } public int countAndRemove(Dices dices) { int now_roll_number=dices.getNumber(); int[] rollscore=dices.getPoint(); int[] roll=new int[7]; for(int score=1;score<=6;score++) roll[score]=0; for(int dicesid=0;dicesid<now_roll_number;dicesid++) roll[rollscore[dicesid]]++; int nowscore=0,decroll=0; if (roll[1]==6) { roll[1]-=6; nowscore+=3000; decroll+=6; } if (roll[1]>=3) { roll[1]-=3; nowscore+=1000; decroll+=3; } for(int score=2;score<=6;score++) { if (roll[score]>=3) { roll[score]-=3; nowscore+=score*100; decroll+=3; } if (roll[score]>=3) { roll[score]-=3; nowscore+=score*100; decroll+=3; } } while (roll[1]>0) { roll[1]--; nowscore+=100; decroll++; } while (roll[5]>0) { roll[5]--; nowscore+=50; decroll++; } dices.removeDices(decroll); return nowscore; } public void sortPlayers(Player[] players,int playerNum) { Random rand = new Random(); Player tmpPlayer; for(int i=0;i<playerNum;i++) { int now=rand.nextInt(i+1); // Player swapPlayer=players[now]; tmpPlayer=players[now]; players[now]=players[i]; players[i]=tmpPlayer; // System.out.println(now+":"+tmpPlayer.getName()+","+players[now].getName()+","+players[i].getName()); } String[] name=new String[playerNum]; for(int i=0;i<playerNum;i++) { name[i]=players[i].getName(); } PlayView.shuffledPlayerOut(name,playerNum); } }
0
1,105
11
1,269
13
1,361
11
1,269
13
1,574
24
false
false
false
false
false
true
47621_2
package dt08; import java.net.*; import java.io.*; // 建立SocketServer,监听 9001端口 // 客户端连接到SocketServer后,Server显示客户端发送过来的字符串 // 客户端发来 exit 字串,则断开连接 public class ChatServer1 { public static void main(String[] args) throws IOException, InterruptedException { final int port = 9001; ServerSocket ss = new ServerSocket(port); System.out.println("Server started @" + port); Socket socket = ss.accept(); System.out.println("Client connected"); DataInputStream input = new DataInputStream(socket.getInputStream()); String line; while (true) { if ((line = input.readUTF()) != null) { if (line.equals("exit")) { System.out.println("Client disconnected"); break; // 退出循环 } else { // 将信息打印到屏幕上 System.out.println(line); } } else { // 没有输入 Thread.sleep(100); } } input.close(); socket.close(); ss.close(); } }
AlohaWorld/Lessons4JavaSE
src/dt08/ChatServer1.java
270
// 客户端发来 exit 字串,则断开连接
line_comment
zh-cn
package dt08; import java.net.*; import java.io.*; // 建立SocketServer,监听 9001端口 // 客户端连接到SocketServer后,Server显示客户端发送过来的字符串 // 客户 <SUF> public class ChatServer1 { public static void main(String[] args) throws IOException, InterruptedException { final int port = 9001; ServerSocket ss = new ServerSocket(port); System.out.println("Server started @" + port); Socket socket = ss.accept(); System.out.println("Client connected"); DataInputStream input = new DataInputStream(socket.getInputStream()); String line; while (true) { if ((line = input.readUTF()) != null) { if (line.equals("exit")) { System.out.println("Client disconnected"); break; // 退出循环 } else { // 将信息打印到屏幕上 System.out.println(line); } } else { // 没有输入 Thread.sleep(100); } } input.close(); socket.close(); ss.close(); } }
0
248
14
270
14
285
13
270
14
345
19
false
false
false
false
false
true
28791_17
import java.io.*; import java.security.*; import java.lang.reflect.*; import javax.crypto.*; import javax.crypto.spec.*; public class MyClassLoader extends ClassLoader { // 这些对象在构造函数中设置, // 以后loadClass()方法将利用它们解密类 private SecretKey key; private Cipher cipher; // 设置解密所需要的对象 public MyClassLoader(SecretKey key) throws GeneralSecurityException, IOException { this.key = key; String algorithm = "DES"; SecureRandom sr = new SecureRandom(); System.err.println("[MyClassLoader: creating cipher]"); cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key, sr); } // main过程:读入密匙,创建MyClassLoader的 // 实例,它就是我们的定制ClassLoader。 // 设置好ClassLoader以后,用它装入应用实例, // 最后,通过Java Reflection API调用应用实例的main方法 static public void main(String args[]) throws Exception { String keyFilename = args[0]; String appName = args[1]; // 这些是传递给应用本身的参数 String realArgs[] = new String[args.length - 2]; System.arraycopy(args, 2, realArgs, 0, args.length - 2); // 读取密匙 System.err.println("[MyClassLoader: reading key]"); byte rawKey[] = FileUtil.readFile(keyFilename); DESKeySpec dks = new DESKeySpec(rawKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); // 创建解密的ClassLoader MyClassLoader dr = new MyClassLoader(key); // 创建应用主类的一个实例 // 通过ClassLoader装入它 System.err.println("[MyClassLoader: loading " + appName + "]"); Class clasz = dr.loadClass(appName); // 最后,通过Reflection API调用应用实例的main()方法 // 获取一个对main()的引用 String proto[] = new String[1]; Class mainArgs[] = { (new String[1]).getClass() }; Method main = clasz.getMethod("main", mainArgs); // 创建一个包含main()方法参数的数组 Object argsArray[] = { realArgs }; System.err.println("[MyClassLoader: running " + appName + ".main()]"); // 调用main() main.invoke(null, argsArray); } public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { try { // 要创建的Class对象 Class clasz = null; // 如果类已经在系统缓冲之中,不必再次装入它 clasz = findLoadedClass(name); if (clasz != null) return clasz; // 下面是定制部分 try { // 读取经过加密的类文件 byte classData[] = FileUtil.readFile(name + ".class"); if (classData != null) { // 解密... byte decryptedClassData[] = cipher.doFinal(classData); // ... 再把它转换成一个类 clasz = defineClass(name.replace('/', '.'), decryptedClassData, 0, decryptedClassData.length); System.err.println("[MyClassLoader: decrypting class " + name + "]"); } } catch (FileNotFoundException e) { //e.printStackTrace(); } // 如果上面没有成功尝试用默认的ClassLoader装入它 if (clasz == null) clasz = findSystemClass(name); // 如有必要,则装入相关的类 if (resolve && clasz != null) resolveClass(clasz); // 把类返回给调用者 return clasz; } catch (IOException ie) { throw new ClassNotFoundException(ie.toString()); } catch (GeneralSecurityException gse) { throw new ClassNotFoundException(gse.toString()); } } }
AloneMonkey/JarEncrypt
ClassLoader/MyClassLoader.java
992
// 如果类已经在系统缓冲之中,不必再次装入它
line_comment
zh-cn
import java.io.*; import java.security.*; import java.lang.reflect.*; import javax.crypto.*; import javax.crypto.spec.*; public class MyClassLoader extends ClassLoader { // 这些对象在构造函数中设置, // 以后loadClass()方法将利用它们解密类 private SecretKey key; private Cipher cipher; // 设置解密所需要的对象 public MyClassLoader(SecretKey key) throws GeneralSecurityException, IOException { this.key = key; String algorithm = "DES"; SecureRandom sr = new SecureRandom(); System.err.println("[MyClassLoader: creating cipher]"); cipher = Cipher.getInstance(algorithm); cipher.init(Cipher.DECRYPT_MODE, key, sr); } // main过程:读入密匙,创建MyClassLoader的 // 实例,它就是我们的定制ClassLoader。 // 设置好ClassLoader以后,用它装入应用实例, // 最后,通过Java Reflection API调用应用实例的main方法 static public void main(String args[]) throws Exception { String keyFilename = args[0]; String appName = args[1]; // 这些是传递给应用本身的参数 String realArgs[] = new String[args.length - 2]; System.arraycopy(args, 2, realArgs, 0, args.length - 2); // 读取密匙 System.err.println("[MyClassLoader: reading key]"); byte rawKey[] = FileUtil.readFile(keyFilename); DESKeySpec dks = new DESKeySpec(rawKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); // 创建解密的ClassLoader MyClassLoader dr = new MyClassLoader(key); // 创建应用主类的一个实例 // 通过ClassLoader装入它 System.err.println("[MyClassLoader: loading " + appName + "]"); Class clasz = dr.loadClass(appName); // 最后,通过Reflection API调用应用实例的main()方法 // 获取一个对main()的引用 String proto[] = new String[1]; Class mainArgs[] = { (new String[1]).getClass() }; Method main = clasz.getMethod("main", mainArgs); // 创建一个包含main()方法参数的数组 Object argsArray[] = { realArgs }; System.err.println("[MyClassLoader: running " + appName + ".main()]"); // 调用main() main.invoke(null, argsArray); } public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { try { // 要创建的Class对象 Class clasz = null; // 如果 <SUF> clasz = findLoadedClass(name); if (clasz != null) return clasz; // 下面是定制部分 try { // 读取经过加密的类文件 byte classData[] = FileUtil.readFile(name + ".class"); if (classData != null) { // 解密... byte decryptedClassData[] = cipher.doFinal(classData); // ... 再把它转换成一个类 clasz = defineClass(name.replace('/', '.'), decryptedClassData, 0, decryptedClassData.length); System.err.println("[MyClassLoader: decrypting class " + name + "]"); } } catch (FileNotFoundException e) { //e.printStackTrace(); } // 如果上面没有成功尝试用默认的ClassLoader装入它 if (clasz == null) clasz = findSystemClass(name); // 如有必要,则装入相关的类 if (resolve && clasz != null) resolveClass(clasz); // 把类返回给调用者 return clasz; } catch (IOException ie) { throw new ClassNotFoundException(ie.toString()); } catch (GeneralSecurityException gse) { throw new ClassNotFoundException(gse.toString()); } } }
0
874
14
987
19
953
14
987
19
1,296
29
false
false
false
false
false
true
58182_8
package com.demo.app.hybrid.core; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Service; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.webkit.JavascriptInterface; import com.demo.app.mvp.app.BaseApplication; import com.demo.app.tinker.util.SampleApplicationContext; import com.demo.app.util.IKeySourceUtil; import com.demo.app.util.LogUtil; public class Cookie { protected ExceptionJson exceptionJson = new ExceptionJson(); public String memberIDKey = "userid"; private Context context = null; protected BaseApplication application; // private MyAoyouControllerImp myAoyouControllerImp; public Cookie(Context context) { this.context = context; if (context instanceof Activity) { this.application = SampleApplicationContext.application; // initMemberControl(); } else if (context instanceof Service) { application = SampleApplicationContext.application; } else { // application = (BaseApplication) BaseApplication.getMContext(); } } private SharedPreferences getApplication() { return context.getSharedPreferences("data", Context.MODE_PRIVATE); } @JavascriptInterface public String getUserId() { //取出userId,返回给js SharedPreferences settings = context.getSharedPreferences( IKeySourceUtil.LOGIN_STATUS, Context.MODE_PRIVATE); String userid=settings.getString("demoId", "0"); LogUtil.i("hww:demoIdNew",userid+""); return String.valueOf(userid); } /** * 功能:设置dataKey的value,将dataKey属性的json串保存到sp中 * @param dataKey 某些key值 * @param value key对应的value值 * @param timeout 超时时间 * @return */ @JavascriptInterface public String setCookie(String dataKey, String value, int timeout) { LogUtil.i("hww", "setCookie " + "dataKey:" + dataKey + " value:" + value); try { // if (dataKey.toLowerCase().equals(memberIDKey.toLowerCase())) { // return exceptionJson.CustomExceptionJson("cookie key不能使用" + memberIDKey.toLowerCase()); // } SharedPreferences sharedPreferences = getApplication(); SharedPreferences.Editor editor = sharedPreferences.edit(); CookieValue cv = new CookieValue(); cv.dataKey = dataKey; cv.value = value;//版本文件json串 cv.timeout = timeout;//超时时间 cv.date = new Date().getTime();//日期 editor.putString(dataKey, cv.ConvertJson());//将dataKey和它的value以及超时时间等等保存到sp中 保存String类型json串 editor.commit(); return exceptionJson.NoExceptionJson(); } catch (Exception e) { return exceptionJson.SystemExceptionJson(e.getMessage()); } } public String setMemberID(String dataKey, String value, int timeout) { try { SharedPreferences sharedPreferences = getApplication(); SharedPreferences.Editor editor = sharedPreferences.edit(); /* * CookieValue cv = new CookieValue(); cv.dataKey = dataKey; * cv.value = value; cv.timeout = timeout; cv.date = new * Date().getTime(); */ editor.putString(dataKey, value); editor.commit(); return exceptionJson.NoExceptionJson(); } catch (Exception e) { return exceptionJson.SystemExceptionJson(e.getMessage()); } } /** * js调用getCookie方法获取某个dataKey的value值 * @param dataKey 下载版本文件的url * @return sp中保存的cookievalue 实体中的版本文件json字符串 获取dataKey对应的value值 */ @JavascriptInterface public String getCookie(String dataKey) { SharedPreferences sharedPreferences = getApplication(); String jsonStr = sharedPreferences.getString(dataKey, "");//从sp中取出dataKey对应的value值 注意是String类型json串 if (!TextUtils.isEmpty(jsonStr)) { CookieValue cookieValue = new CookieValue(); cookieValue.ConvertObj(jsonStr);//转化为Cookievalue实体 long longDate = cookieValue.date; Date date = new Date(longDate); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); cal.add(Calendar.SECOND, cookieValue.timeout); if (cookieValue.timeout > 0) { Date now = new Date(); if (cal.getTime().getTime() < now.getTime()) {//如果cal的时间(也就是sp中保存的时间)<当前的时间,移除Cookie removeCookie(dataKey); return ""; } } return cookieValue.value;//value就是版本文件的内容 json串 }else{ return ""; } } /** * 从sp中删除这个dataKey * @param dataKey * @return */ @JavascriptInterface public String removeCookie(String dataKey) { try { SharedPreferences sharedPreferences = getApplication(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.remove(dataKey); editor.commit(); return exceptionJson.NoExceptionJson(); } catch (Exception e) { return exceptionJson.SystemExceptionJson(e.getMessage()); } } public class CookieValue { public String dataKey; public String value; public int timeout; public long date; //拼接json public String ConvertJson() { JSONObject json = new JSONObject(); try { json.put("dataKey", dataKey); json.put("value", value); json.put("timeout", timeout); json.put("date", date); } catch (JSONException e) { e.printStackTrace(); } return json.toString(); } //解析json public void ConvertObj(String jsonStr) { try { JSONObject result = new JSONObject(jsonStr); dataKey = result.getString("dataKey"); value = result.getString("value"); timeout = result.getInt("timeout"); date = result.getLong("date"); } catch (JSONException e) { e.printStackTrace(); } } } }
AlpacaNotSheep/hybrid
Android/core/Cookie.java
1,570
//超时时间
line_comment
zh-cn
package com.demo.app.hybrid.core; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.Service; import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.webkit.JavascriptInterface; import com.demo.app.mvp.app.BaseApplication; import com.demo.app.tinker.util.SampleApplicationContext; import com.demo.app.util.IKeySourceUtil; import com.demo.app.util.LogUtil; public class Cookie { protected ExceptionJson exceptionJson = new ExceptionJson(); public String memberIDKey = "userid"; private Context context = null; protected BaseApplication application; // private MyAoyouControllerImp myAoyouControllerImp; public Cookie(Context context) { this.context = context; if (context instanceof Activity) { this.application = SampleApplicationContext.application; // initMemberControl(); } else if (context instanceof Service) { application = SampleApplicationContext.application; } else { // application = (BaseApplication) BaseApplication.getMContext(); } } private SharedPreferences getApplication() { return context.getSharedPreferences("data", Context.MODE_PRIVATE); } @JavascriptInterface public String getUserId() { //取出userId,返回给js SharedPreferences settings = context.getSharedPreferences( IKeySourceUtil.LOGIN_STATUS, Context.MODE_PRIVATE); String userid=settings.getString("demoId", "0"); LogUtil.i("hww:demoIdNew",userid+""); return String.valueOf(userid); } /** * 功能:设置dataKey的value,将dataKey属性的json串保存到sp中 * @param dataKey 某些key值 * @param value key对应的value值 * @param timeout 超时时间 * @return */ @JavascriptInterface public String setCookie(String dataKey, String value, int timeout) { LogUtil.i("hww", "setCookie " + "dataKey:" + dataKey + " value:" + value); try { // if (dataKey.toLowerCase().equals(memberIDKey.toLowerCase())) { // return exceptionJson.CustomExceptionJson("cookie key不能使用" + memberIDKey.toLowerCase()); // } SharedPreferences sharedPreferences = getApplication(); SharedPreferences.Editor editor = sharedPreferences.edit(); CookieValue cv = new CookieValue(); cv.dataKey = dataKey; cv.value = value;//版本文件json串 cv.timeout = timeout;//超时 <SUF> cv.date = new Date().getTime();//日期 editor.putString(dataKey, cv.ConvertJson());//将dataKey和它的value以及超时时间等等保存到sp中 保存String类型json串 editor.commit(); return exceptionJson.NoExceptionJson(); } catch (Exception e) { return exceptionJson.SystemExceptionJson(e.getMessage()); } } public String setMemberID(String dataKey, String value, int timeout) { try { SharedPreferences sharedPreferences = getApplication(); SharedPreferences.Editor editor = sharedPreferences.edit(); /* * CookieValue cv = new CookieValue(); cv.dataKey = dataKey; * cv.value = value; cv.timeout = timeout; cv.date = new * Date().getTime(); */ editor.putString(dataKey, value); editor.commit(); return exceptionJson.NoExceptionJson(); } catch (Exception e) { return exceptionJson.SystemExceptionJson(e.getMessage()); } } /** * js调用getCookie方法获取某个dataKey的value值 * @param dataKey 下载版本文件的url * @return sp中保存的cookievalue 实体中的版本文件json字符串 获取dataKey对应的value值 */ @JavascriptInterface public String getCookie(String dataKey) { SharedPreferences sharedPreferences = getApplication(); String jsonStr = sharedPreferences.getString(dataKey, "");//从sp中取出dataKey对应的value值 注意是String类型json串 if (!TextUtils.isEmpty(jsonStr)) { CookieValue cookieValue = new CookieValue(); cookieValue.ConvertObj(jsonStr);//转化为Cookievalue实体 long longDate = cookieValue.date; Date date = new Date(longDate); GregorianCalendar cal = new GregorianCalendar(); cal.setTime(date); cal.add(Calendar.SECOND, cookieValue.timeout); if (cookieValue.timeout > 0) { Date now = new Date(); if (cal.getTime().getTime() < now.getTime()) {//如果cal的时间(也就是sp中保存的时间)<当前的时间,移除Cookie removeCookie(dataKey); return ""; } } return cookieValue.value;//value就是版本文件的内容 json串 }else{ return ""; } } /** * 从sp中删除这个dataKey * @param dataKey * @return */ @JavascriptInterface public String removeCookie(String dataKey) { try { SharedPreferences sharedPreferences = getApplication(); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.remove(dataKey); editor.commit(); return exceptionJson.NoExceptionJson(); } catch (Exception e) { return exceptionJson.SystemExceptionJson(e.getMessage()); } } public class CookieValue { public String dataKey; public String value; public int timeout; public long date; //拼接json public String ConvertJson() { JSONObject json = new JSONObject(); try { json.put("dataKey", dataKey); json.put("value", value); json.put("timeout", timeout); json.put("date", date); } catch (JSONException e) { e.printStackTrace(); } return json.toString(); } //解析json public void ConvertObj(String jsonStr) { try { JSONObject result = new JSONObject(jsonStr); dataKey = result.getString("dataKey"); value = result.getString("value"); timeout = result.getInt("timeout"); date = result.getLong("date"); } catch (JSONException e) { e.printStackTrace(); } } } }
0
1,312
4
1,570
3
1,568
3
1,570
3
1,998
5
false
false
false
false
false
true
46571_0
class Member{ //员工 // 两个字段 private String memId; private String memName; private Dept dept; // 构造方法 public Member(){} public Member(String memId,String memName){ this.memId = memId; this.memName = memName; } public void setDept(Dept dept){ this.dept = dept ; } public Dept getDept(){ return this.dept; } public String getMemInfo(){ return "【Member】memId="+memId+",memName="+memName; } } class Dept{ //部门 private String deptId; private String deptName; private Member[] members; private Role role; // 构造方法 public Dept(){} public Dept(String deptId,String deptName){ this.deptId = deptId; this.deptName = deptName ; } public void setMember(Member[] members){ this.members = members; } public Member[] getMember(){ return this.members; } public void setRole(Role role){ this.role = role; } public Role getRole(){ return this.role; } public String getDeptInfo(){ return "【Dept】deptId="+deptId+",deptName="+deptName; } } class Role{//角色 private String roleId; private String roleName; private Dept[] depts; private Permission[] permissions; public Role(){} public Role(String roleId,String roleName){ this.roleId = roleId; this.roleName = roleName ; } public void setDept(Dept[] depts){ this.depts = depts; } public Dept[] getDept(){ return this.depts; } public void setPermission(Permission[] permissions){ this.permissions = permissions; } public Permission[] getPermission(){ return permissions; } public String getRoleInfo(){ return "【Role】roleId="+roleId+",roleName="+roleName; } } class Permission{//权限 private String perId; private String perName; private String perMark; private Role[] roles; public Permission (){} public Permission (String perId,String perName,String perMark){ this.perId=perId; this.perName = perName; this.perMark = perMark; } public void setRole(Role[] roles){ this.roles = roles; } public Role[] getRole(){ return this.roles; } public String getPermissInfo(){ return "【Permission】perId="+perId+",perName="+perName+",perMark="+perMark; } } public class TestThree{ public static void main(String[] args) { //部门 和员工 Dept dept1 = new Dept("001","生产部"); Dept dept2 = new Dept("002","销售部"); Dept dept3 = new Dept("003","技术部"); Member mem1 = new Member("001","jack"); Member mem2 = new Member("002","ellen"); Member mem3 = new Member("003","eric"); Member mem4 = new Member("004","Paul"); Member mem5 = new Member("005","Jade"); dept1.setMember(new Member[]{mem1,mem4}); dept2.setMember(new Member[]{mem2,mem3}); dept3.setMember(new Member[]{mem5}); mem1.setDept(dept1); mem2.setDept(dept2); mem3.setDept(dept2); mem4.setDept(dept1); mem5.setDept(dept3); // 部门和角色 Role role1 = new Role("1000","员工"); Role role2 = new Role("1001","经理"); role1.setDept(new Dept[]{dept1,dept3}); role2.setDept(new Dept[]{dept2}); dept1.setRole(role1); dept2.setRole(role2); dept3.setRole(role1); // 角色和权限 互相塞数据 Permission per1 = new Permission("88001","广告","编辑"); Permission per2 = new Permission("88002","文件","修改"); Permission per3 = new Permission("88003","招聘","删除"); Permission per4 = new Permission("88004","招聘","编辑"); Permission per5 = new Permission("88005","广告","增加"); per1.setRole(new Role[]{role1}); per2.setRole(new Role[]{role1,role2}); per3.setRole(new Role[]{role2}); per4.setRole(new Role[]{role2}); per5.setRole(new Role[]{role1}); role1.setPermission(new Permission[]{per1,per2,per5}); role2.setPermission(new Permission[]{per3,per4}); // ==============================第一问============================================= System.out.println("==========第一问======="); System.out.println(mem1.getMemInfo()); System.out.println("\t|-"+mem1.getDept().getDeptInfo()); System.out.println("\t|-"+mem1.getDept().getRole().getRoleInfo()); // System.out.println(mem1.getDept().getRole().getPermission().length) ; for(int x = 0 ; x < mem1.getDept().getRole().getPermission().length; x++){ System.out.println("\t\t|-"+mem1.getDept().getRole().getPermission()[x].getPermissInfo()); } // ================================第二问=========================================== System.out.println("==========第二问======="); System.out.println(role1.getRoleInfo()); // System.out.println(role2.getDept().length); for (int x = 0; x < role1.getDept().length; x++) { System.out.println("\t\t|-"+role1.getDept()[x].getDeptInfo()); } // ================================第三问=========================================== System.out.println("==========第三问======="); // System.out.println(per2.getRole().length); for (int x = 0; x < per2.getRole().length ; x++ ) { System.out.println(per2.getRole()[x].getRoleInfo()); for(int y = 0 ; y < per2.getRole()[x].getDept().length; y++){ System.out.println("\t"+per2.getRole()[x].getDept()[y].getDeptInfo()); for (int z = 0; z < per2.getRole()[x].getDept()[y].getMember().length ;z++ ) { System.out.println("\t\t"+per2.getRole()[x].getDept()[y].getMember()[z].getMemInfo()); } } } } }
AlvaWymer/-02_final
TestThree.java
1,801
// 两个字段
line_comment
zh-cn
class Member{ //员工 // 两个 <SUF> private String memId; private String memName; private Dept dept; // 构造方法 public Member(){} public Member(String memId,String memName){ this.memId = memId; this.memName = memName; } public void setDept(Dept dept){ this.dept = dept ; } public Dept getDept(){ return this.dept; } public String getMemInfo(){ return "【Member】memId="+memId+",memName="+memName; } } class Dept{ //部门 private String deptId; private String deptName; private Member[] members; private Role role; // 构造方法 public Dept(){} public Dept(String deptId,String deptName){ this.deptId = deptId; this.deptName = deptName ; } public void setMember(Member[] members){ this.members = members; } public Member[] getMember(){ return this.members; } public void setRole(Role role){ this.role = role; } public Role getRole(){ return this.role; } public String getDeptInfo(){ return "【Dept】deptId="+deptId+",deptName="+deptName; } } class Role{//角色 private String roleId; private String roleName; private Dept[] depts; private Permission[] permissions; public Role(){} public Role(String roleId,String roleName){ this.roleId = roleId; this.roleName = roleName ; } public void setDept(Dept[] depts){ this.depts = depts; } public Dept[] getDept(){ return this.depts; } public void setPermission(Permission[] permissions){ this.permissions = permissions; } public Permission[] getPermission(){ return permissions; } public String getRoleInfo(){ return "【Role】roleId="+roleId+",roleName="+roleName; } } class Permission{//权限 private String perId; private String perName; private String perMark; private Role[] roles; public Permission (){} public Permission (String perId,String perName,String perMark){ this.perId=perId; this.perName = perName; this.perMark = perMark; } public void setRole(Role[] roles){ this.roles = roles; } public Role[] getRole(){ return this.roles; } public String getPermissInfo(){ return "【Permission】perId="+perId+",perName="+perName+",perMark="+perMark; } } public class TestThree{ public static void main(String[] args) { //部门 和员工 Dept dept1 = new Dept("001","生产部"); Dept dept2 = new Dept("002","销售部"); Dept dept3 = new Dept("003","技术部"); Member mem1 = new Member("001","jack"); Member mem2 = new Member("002","ellen"); Member mem3 = new Member("003","eric"); Member mem4 = new Member("004","Paul"); Member mem5 = new Member("005","Jade"); dept1.setMember(new Member[]{mem1,mem4}); dept2.setMember(new Member[]{mem2,mem3}); dept3.setMember(new Member[]{mem5}); mem1.setDept(dept1); mem2.setDept(dept2); mem3.setDept(dept2); mem4.setDept(dept1); mem5.setDept(dept3); // 部门和角色 Role role1 = new Role("1000","员工"); Role role2 = new Role("1001","经理"); role1.setDept(new Dept[]{dept1,dept3}); role2.setDept(new Dept[]{dept2}); dept1.setRole(role1); dept2.setRole(role2); dept3.setRole(role1); // 角色和权限 互相塞数据 Permission per1 = new Permission("88001","广告","编辑"); Permission per2 = new Permission("88002","文件","修改"); Permission per3 = new Permission("88003","招聘","删除"); Permission per4 = new Permission("88004","招聘","编辑"); Permission per5 = new Permission("88005","广告","增加"); per1.setRole(new Role[]{role1}); per2.setRole(new Role[]{role1,role2}); per3.setRole(new Role[]{role2}); per4.setRole(new Role[]{role2}); per5.setRole(new Role[]{role1}); role1.setPermission(new Permission[]{per1,per2,per5}); role2.setPermission(new Permission[]{per3,per4}); // ==============================第一问============================================= System.out.println("==========第一问======="); System.out.println(mem1.getMemInfo()); System.out.println("\t|-"+mem1.getDept().getDeptInfo()); System.out.println("\t|-"+mem1.getDept().getRole().getRoleInfo()); // System.out.println(mem1.getDept().getRole().getPermission().length) ; for(int x = 0 ; x < mem1.getDept().getRole().getPermission().length; x++){ System.out.println("\t\t|-"+mem1.getDept().getRole().getPermission()[x].getPermissInfo()); } // ================================第二问=========================================== System.out.println("==========第二问======="); System.out.println(role1.getRoleInfo()); // System.out.println(role2.getDept().length); for (int x = 0; x < role1.getDept().length; x++) { System.out.println("\t\t|-"+role1.getDept()[x].getDeptInfo()); } // ================================第三问=========================================== System.out.println("==========第三问======="); // System.out.println(per2.getRole().length); for (int x = 0; x < per2.getRole().length ; x++ ) { System.out.println(per2.getRole()[x].getRoleInfo()); for(int y = 0 ; y < per2.getRole()[x].getDept().length; y++){ System.out.println("\t"+per2.getRole()[x].getDept()[y].getDeptInfo()); for (int z = 0; z < per2.getRole()[x].getDept()[y].getMember().length ;z++ ) { System.out.println("\t\t"+per2.getRole()[x].getDept()[y].getMember()[z].getMemInfo()); } } } } }
0
1,492
4
1,801
4
1,761
4
1,801
4
2,202
6
false
false
false
false
false
true
52824_14
package cn.mldn.shiro.realm; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import cn.mldn.shiro.service.IMemberService; import cn.mldn.shiro.service.impl.MemberServiceImpl; import cn.mldn.shiro.vo.Member; public class MyDefaultRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { System.out.println("++++++++++++++ 2、进行授权操作处理 ++++++++++++++"); // 该操作的主要目的是取得授权信息,说的直白一点就是角色和权限数据 SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo() ; // 执行到此方法的时候一定是已经进行过用户认证处理了(用户名和密码一定是正确的) String mid = (String) principals.getPrimaryPrincipal() ; // 取得用户名 try { // 存在了用户编号之后就意味着可以进行用户的角色或权限数据查询 IMemberService memberService = new MemberServiceImpl(); auth.setRoles(memberService.listRolesByMember(mid)); // 保存所有的角色 auth.setStringPermissions(memberService.listActionsByMember(mid)); // 保存所有的权限 } catch (Exception e) { e.printStackTrace(); } return auth ; } @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { System.out.println("============== 1、进行认证操作处理 =============="); // 用户的认证信息一定要通过IMemberService获取 IMemberService memberService = new MemberServiceImpl(); String userid = token.getPrincipal().toString(); // 用户名 // 定义需要进行返回的操作数据信息项 SimpleAuthenticationInfo auth = new SimpleAuthenticationInfo( token.getPrincipal(), token.getCredentials(), "memberRealm"); try { // 取得用户名之后就需要通过业务层获取用户对象以确定改用户名是否可用 Member member = memberService.get(userid); // 通过用户名获取用户信息 if (member == null) { // 表示该用户信息不存在,不存在则应该抛出一个异常 throw new UnknownAccountException("搞什么搞,用户名不存在!"); } // 用户名如果存在了,那么就需要确定密码是否正确 String password = new String((char[]) token.getCredentials()); if (!password.equals(member.getPassword())) { // 密码验证 throw new IncorrectCredentialsException("密码都记不住,去死吧!"); } // 随后还需要考虑用户被锁定的问题 if (member.getLocked().equals(1)) { // 1表示非0,非0就是true throw new LockedAccountException("被锁了,求解锁去吧!"); } } catch (Exception e) { e.printStackTrace(); } return auth; } }
AlvaWymer/Shiro-Demo
Shiro-Auth/src/main/java/cn/mldn/shiro/realm/MyDefaultRealm.java
843
// 随后还需要考虑用户被锁定的问题
line_comment
zh-cn
package cn.mldn.shiro.realm; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import cn.mldn.shiro.service.IMemberService; import cn.mldn.shiro.service.impl.MemberServiceImpl; import cn.mldn.shiro.vo.Member; public class MyDefaultRealm extends AuthorizingRealm { @Override protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { System.out.println("++++++++++++++ 2、进行授权操作处理 ++++++++++++++"); // 该操作的主要目的是取得授权信息,说的直白一点就是角色和权限数据 SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo() ; // 执行到此方法的时候一定是已经进行过用户认证处理了(用户名和密码一定是正确的) String mid = (String) principals.getPrimaryPrincipal() ; // 取得用户名 try { // 存在了用户编号之后就意味着可以进行用户的角色或权限数据查询 IMemberService memberService = new MemberServiceImpl(); auth.setRoles(memberService.listRolesByMember(mid)); // 保存所有的角色 auth.setStringPermissions(memberService.listActionsByMember(mid)); // 保存所有的权限 } catch (Exception e) { e.printStackTrace(); } return auth ; } @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken token) throws AuthenticationException { System.out.println("============== 1、进行认证操作处理 =============="); // 用户的认证信息一定要通过IMemberService获取 IMemberService memberService = new MemberServiceImpl(); String userid = token.getPrincipal().toString(); // 用户名 // 定义需要进行返回的操作数据信息项 SimpleAuthenticationInfo auth = new SimpleAuthenticationInfo( token.getPrincipal(), token.getCredentials(), "memberRealm"); try { // 取得用户名之后就需要通过业务层获取用户对象以确定改用户名是否可用 Member member = memberService.get(userid); // 通过用户名获取用户信息 if (member == null) { // 表示该用户信息不存在,不存在则应该抛出一个异常 throw new UnknownAccountException("搞什么搞,用户名不存在!"); } // 用户名如果存在了,那么就需要确定密码是否正确 String password = new String((char[]) token.getCredentials()); if (!password.equals(member.getPassword())) { // 密码验证 throw new IncorrectCredentialsException("密码都记不住,去死吧!"); } // 随后 <SUF> if (member.getLocked().equals(1)) { // 1表示非0,非0就是true throw new LockedAccountException("被锁了,求解锁去吧!"); } } catch (Exception e) { e.printStackTrace(); } return auth; } }
0
708
11
843
12
804
10
843
12
1,164
25
false
false
false
false
false
true
17317_2
/****** * 快速排序 * * 分治思想 * * * 设要排序的数组是A[0]⋯⋯A[N-1],首先任意选取一个数据(通常选用第1个数据)作为关键数据, * 然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面, * 这个过程称为一趟快速排序。值得注意的是,快速排序不是一种稳定的排序算法, * 也就是说,多个相同的值的相对位置也许会在算法结束时产生变动。 一趟快速排序的算法是: 1)设置两个变量i、j,排序开始的时候:i=0,j=N-1; 2)以第一个数组元素作为关键数据,赋值给key,即key=A[0]; 3)从j开始向前搜索,即由后开始向前搜索(j -- ),找到第一个小于key的值A[j],A[i]与A[j]交换; 4)从i开始向后搜索,即由前开始向后搜索(i ++ ),找到第一个大于key的A[i],A[i]与A[j]交换; 5)重复第3、4、5步,直到 I=J; (3,4步是在程序中没找到时候j=j-1,i=i+1,直至找到为止。找到并交换的时候i, j指针位置不变。另外当i=j这过程一定正好是i+或j-完成的最后令循环结束。 * * **/ public class QuickSort { /** * @param args */ public static void main(String[] args) { int n = 10; int[] a = new int[n]; for(int i = 0; i < a.length; i++) a[i] = (int)(Math.random() * 100); disp(a); sort(a, 0, a.length - 1); disp(a); System.out.println("yagnaihua "); System.out.println("yagnaihua好的话的反对 "); } private static void sort(int[] a, int left, int right) { //分为两部分,一个是左部分,一个是右部分 if (left >= right) return; int i = left, j = right + 1; while(true){ do{ i++; }while(i <= right && a[i] < a[left]); do{ j--; }while(a[j] > a[left]); if (i >= j) break; swap(a, i, j); } swap(a, j, left); sort(a, left, j - 1); sort(a, j + 1, right); } private static void swap(int[] a, int i, int j) { int tem = a[i]; a[i] = a[j]; a[j] = tem; } private static void disp(int[] a) { for(int i = 0; i < a.length; i++) System.out.printf("%d ", a[i]); System.out.println(); } }
AlvaWymer/test1
QuickSort.java
812
//分为两部分,一个是左部分,一个是右部分
line_comment
zh-cn
/****** * 快速排序 * * 分治思想 * * * 设要排序的数组是A[0]⋯⋯A[N-1],首先任意选取一个数据(通常选用第1个数据)作为关键数据, * 然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面, * 这个过程称为一趟快速排序。值得注意的是,快速排序不是一种稳定的排序算法, * 也就是说,多个相同的值的相对位置也许会在算法结束时产生变动。 一趟快速排序的算法是: 1)设置两个变量i、j,排序开始的时候:i=0,j=N-1; 2)以第一个数组元素作为关键数据,赋值给key,即key=A[0]; 3)从j开始向前搜索,即由后开始向前搜索(j -- ),找到第一个小于key的值A[j],A[i]与A[j]交换; 4)从i开始向后搜索,即由前开始向后搜索(i ++ ),找到第一个大于key的A[i],A[i]与A[j]交换; 5)重复第3、4、5步,直到 I=J; (3,4步是在程序中没找到时候j=j-1,i=i+1,直至找到为止。找到并交换的时候i, j指针位置不变。另外当i=j这过程一定正好是i+或j-完成的最后令循环结束。 * * **/ public class QuickSort { /** * @param args */ public static void main(String[] args) { int n = 10; int[] a = new int[n]; for(int i = 0; i < a.length; i++) a[i] = (int)(Math.random() * 100); disp(a); sort(a, 0, a.length - 1); disp(a); System.out.println("yagnaihua "); System.out.println("yagnaihua好的话的反对 "); } private static void sort(int[] a, int left, int right) { //分为 <SUF> if (left >= right) return; int i = left, j = right + 1; while(true){ do{ i++; }while(i <= right && a[i] < a[left]); do{ j--; }while(a[j] > a[left]); if (i >= j) break; swap(a, i, j); } swap(a, j, left); sort(a, left, j - 1); sort(a, j + 1, right); } private static void swap(int[] a, int i, int j) { int tem = a[i]; a[i] = a[j]; a[j] = tem; } private static void disp(int[] a) { for(int i = 0; i < a.length; i++) System.out.printf("%d ", a[i]); System.out.println(); } }
0
678
12
812
15
785
12
812
15
1,066
20
false
false
false
false
false
true
55801_0
/** * */ package entity; import java.awt.Point; import java.util.Random; import util.GameMethod; import config.GameConfig; /** * 俄罗斯方块的抽象类,成员:能否旋转,需要几个坐标(方块)组成,初始形态(竖的或横的) 方法:下落、位移、旋转 * * @author phx */ public abstract class Tetriminos { public static int MIN_X = GameConfig.getSYSTEM().getMinX(); public static int MAX_X = GameConfig.getSYSTEM().getMaxX(); protected static Random rand = new Random(); protected boolean rotatable; protected byte shapeID; /** * mark rotate how many time then use to sync the * hint picture */ protected int rotateFlag; /** * use to initialize the Tetriminos */ protected Point[] fallCoords; /** * use to make a hint shadow */ protected Point[] bottomCoords; public Tetriminos( byte ID, boolean rotatable, int rotateFlag, Point[] fall) { this.shapeID = ID; this.rotatable = rotatable; this.rotateFlag = rotateFlag; this.fallCoords = fall; } public Tetriminos( byte ID) { this.shapeID = ID; } /** * rotate method * @return coordinates after rotate */ public Point[] rotate() { Point[] rotated = GameMethod.copyCoords(fallCoords); // if the coords in the boundary move to left or right first if(rotated[0].x == MIN_X) { move(rotated, 1, 0); }else if(rotated[0].x == MAX_X) { move(rotated, -1, 0); } for (int i = 0; i < 4; i++) { int newX = rotated[0].x + rotated[0].y - rotated[i].y; int newY = rotated[0].y - rotated[0].x + rotated[i].x; rotated[i] = new Point(newX, newY); } return rotated; } public boolean move(Point[] oldCoords, int newX, int newY) { int len = oldCoords.length; /* side effect */ for (int i = 0; i < len; i++) { oldCoords[i].x += newX; oldCoords[i].y += newY; } return true; } public boolean isRotatable() { return rotatable; } public byte getShapeID() { return shapeID; } public int getRotateFlag() { return rotateFlag; } public Point[] getFallCoords() { return fallCoords; } public void setFallCoords(Point[] fallCoords) { this.fallCoords = fallCoords; } public Point[] getBottomCoords() { return bottomCoords; } public void setBottomCoords(Point[] bottomCoords) { this.bottomCoords = bottomCoords; } }
Alwayswithme/JavaTetris
src/entity/Tetriminos.java
793
/** * 俄罗斯方块的抽象类,成员:能否旋转,需要几个坐标(方块)组成,初始形态(竖的或横的) 方法:下落、位移、旋转 * * @author phx */
block_comment
zh-cn
/** * */ package entity; import java.awt.Point; import java.util.Random; import util.GameMethod; import config.GameConfig; /** * 俄罗斯 <SUF>*/ public abstract class Tetriminos { public static int MIN_X = GameConfig.getSYSTEM().getMinX(); public static int MAX_X = GameConfig.getSYSTEM().getMaxX(); protected static Random rand = new Random(); protected boolean rotatable; protected byte shapeID; /** * mark rotate how many time then use to sync the * hint picture */ protected int rotateFlag; /** * use to initialize the Tetriminos */ protected Point[] fallCoords; /** * use to make a hint shadow */ protected Point[] bottomCoords; public Tetriminos( byte ID, boolean rotatable, int rotateFlag, Point[] fall) { this.shapeID = ID; this.rotatable = rotatable; this.rotateFlag = rotateFlag; this.fallCoords = fall; } public Tetriminos( byte ID) { this.shapeID = ID; } /** * rotate method * @return coordinates after rotate */ public Point[] rotate() { Point[] rotated = GameMethod.copyCoords(fallCoords); // if the coords in the boundary move to left or right first if(rotated[0].x == MIN_X) { move(rotated, 1, 0); }else if(rotated[0].x == MAX_X) { move(rotated, -1, 0); } for (int i = 0; i < 4; i++) { int newX = rotated[0].x + rotated[0].y - rotated[i].y; int newY = rotated[0].y - rotated[0].x + rotated[i].x; rotated[i] = new Point(newX, newY); } return rotated; } public boolean move(Point[] oldCoords, int newX, int newY) { int len = oldCoords.length; /* side effect */ for (int i = 0; i < len; i++) { oldCoords[i].x += newX; oldCoords[i].y += newY; } return true; } public boolean isRotatable() { return rotatable; } public byte getShapeID() { return shapeID; } public int getRotateFlag() { return rotateFlag; } public Point[] getFallCoords() { return fallCoords; } public void setFallCoords(Point[] fallCoords) { this.fallCoords = fallCoords; } public Point[] getBottomCoords() { return bottomCoords; } public void setBottomCoords(Point[] bottomCoords) { this.bottomCoords = bottomCoords; } }
0
663
52
793
66
803
54
793
66
938
93
false
false
false
false
false
true
62045_3
package com.order.dao; import java.util.Set; import com.order.entity.Message; import com.order.entity.Orders; import com.order.entity.User; import com.order.entity.UserInfo; public interface UserDao extends Dao{ /** * 通过传入的部分用户信息来找回密码 * @param user * @return */ public User getPasswd(User user); /** * 根据传入的用户信息来查找用户是否存在 * @param u * @return */ public User userLogin(User u); /** * 判断用户邮箱是否激活 * @param * @return */ public boolean mailActive(int id); /** * 通过邮箱判断用户是否存在 */ public User userMail(String mail); /** * 根据传入的name判断用户名是否存在 * @param name * @return */ public boolean judgeUser(String name); /** * 通过用户id得到Orders(订单)集合 * @param id * @return */ public Set<Orders> find(int id); /** * 通过用户id来得到UserInfo(用户配送信息)对象 * @param id * @return */ public UserInfo findUser(int id); /** * 通过用户id得到Message(留言)集合 * @param id * @return */ public Set<Message> findMessageById(int id); /** * 通过用户的用户名得到用户的信息 * @param name * @return */ public User findByName(String name); /** * 找回密码更新密码字段 * @param pass 用户输入的新密码 */ public void updatePass(User user,String pass); }
AmazingT/OrderSystem
src/com/order/dao/UserDao.java
416
/** * 通过邮箱判断用户是否存在 */
block_comment
zh-cn
package com.order.dao; import java.util.Set; import com.order.entity.Message; import com.order.entity.Orders; import com.order.entity.User; import com.order.entity.UserInfo; public interface UserDao extends Dao{ /** * 通过传入的部分用户信息来找回密码 * @param user * @return */ public User getPasswd(User user); /** * 根据传入的用户信息来查找用户是否存在 * @param u * @return */ public User userLogin(User u); /** * 判断用户邮箱是否激活 * @param * @return */ public boolean mailActive(int id); /** * 通过邮 <SUF>*/ public User userMail(String mail); /** * 根据传入的name判断用户名是否存在 * @param name * @return */ public boolean judgeUser(String name); /** * 通过用户id得到Orders(订单)集合 * @param id * @return */ public Set<Orders> find(int id); /** * 通过用户id来得到UserInfo(用户配送信息)对象 * @param id * @return */ public UserInfo findUser(int id); /** * 通过用户id得到Message(留言)集合 * @param id * @return */ public Set<Message> findMessageById(int id); /** * 通过用户的用户名得到用户的信息 * @param name * @return */ public User findByName(String name); /** * 找回密码更新密码字段 * @param pass 用户输入的新密码 */ public void updatePass(User user,String pass); }
0
377
12
416
11
437
12
416
11
554
24
false
false
false
false
false
true
41951_21
//数组的引出 // public class Array01 { //编写一个main方法 public static void main(String[] args) { /* 它们的体重分别是3kg,5kg,1kg,3.4kg,2kg,50kg 。 请问这六只鸡的总体重是多少?平均体重是多少? 思路分析 1. 定义六个变量 double , 求和 得到总体重 2. 平均体重 = 总体重 / 6 3. 分析传统实现的方式问题. 6->600->566 4. 引出新的技术 -> 使用数组来解决. */ // double hen1 = 3; // double hen2 = 5; // double hen3 = 1; // double hen4 = 3.4; // double hen5 = 2; // double hen6 = 50; // double totalWeight = hen1 + hen2 + hen3 + hen4 + hen5 + hen6; // double avgWeight = totalWeight / 6; // System.out.println("总体重=" + totalWeight // + "平均体重=" + avgWeight); //比如,我们可以用数组来解决上一个问题 => 体验 // //定义一个数组 //老韩解读 //1. double[] 表示 是double类型的数组, 数组名 hens //2. {3, 5, 1, 3.4, 2, 50} 表示数组的值/元素,依次表示数组的 // 第几个元素 // double[] hens = {3, 5, 1, 3.4, 2, 50, 7.8, 88.8,1.1,5.6,100}; //遍历数组得到数组的所有元素的和, 使用for //老韩解读 //1. 我们可以通过 hens[下标] 来访问数组的元素 // 下标是从 0 开始编号的比如第一个元素就是 hens[0] // 第2个元素就是 hens[1] , 依次类推 //2. 通过for就可以循环的访问 数组的元素/值 //3. 使用一个变量 totalWeight 将各个元素累积 System.out.println("===使用数组解决==="); //老师提示: 可以通过 数组名.length 得到数组的大小/长度 //System.out.println("数组的长度=" + hens.length); double totalWeight = 0; for( int i = 0; i < hens.length; i++) { //System.out.println("第" + (i+1) + "个元素的值=" + hens[i]); totalWeight += hens[i]; } System.out.println("总体重=" + totalWeight + "平均体重=" + (totalWeight / hens.length) ); } }
Ambrogram/https---github.com-Ambrogram-INFO6205
Array01.java
747
//1. 我们可以通过 hens[下标] 来访问数组的元素
line_comment
zh-cn
//数组的引出 // public class Array01 { //编写一个main方法 public static void main(String[] args) { /* 它们的体重分别是3kg,5kg,1kg,3.4kg,2kg,50kg 。 请问这六只鸡的总体重是多少?平均体重是多少? 思路分析 1. 定义六个变量 double , 求和 得到总体重 2. 平均体重 = 总体重 / 6 3. 分析传统实现的方式问题. 6->600->566 4. 引出新的技术 -> 使用数组来解决. */ // double hen1 = 3; // double hen2 = 5; // double hen3 = 1; // double hen4 = 3.4; // double hen5 = 2; // double hen6 = 50; // double totalWeight = hen1 + hen2 + hen3 + hen4 + hen5 + hen6; // double avgWeight = totalWeight / 6; // System.out.println("总体重=" + totalWeight // + "平均体重=" + avgWeight); //比如,我们可以用数组来解决上一个问题 => 体验 // //定义一个数组 //老韩解读 //1. double[] 表示 是double类型的数组, 数组名 hens //2. {3, 5, 1, 3.4, 2, 50} 表示数组的值/元素,依次表示数组的 // 第几个元素 // double[] hens = {3, 5, 1, 3.4, 2, 50, 7.8, 88.8,1.1,5.6,100}; //遍历数组得到数组的所有元素的和, 使用for //老韩解读 //1. <SUF> // 下标是从 0 开始编号的比如第一个元素就是 hens[0] // 第2个元素就是 hens[1] , 依次类推 //2. 通过for就可以循环的访问 数组的元素/值 //3. 使用一个变量 totalWeight 将各个元素累积 System.out.println("===使用数组解决==="); //老师提示: 可以通过 数组名.length 得到数组的大小/长度 //System.out.println("数组的长度=" + hens.length); double totalWeight = 0; for( int i = 0; i < hens.length; i++) { //System.out.println("第" + (i+1) + "个元素的值=" + hens[i]); totalWeight += hens[i]; } System.out.println("总体重=" + totalWeight + "平均体重=" + (totalWeight / hens.length) ); } }
0
716
19
747
17
699
16
747
17
989
27
false
false
false
false
false
true
26557_5
public class DoubleNode { DoubleNode prev = this; DoubleNode next = this; int data; public DoubleNode(int data){ this.data = data; } //增加节点 public void after(DoubleNode node){ //原来的下一个节点 DoubleNode nextNext = next; //把新节点作为当前节点的前一个节点 this.next = node; //把当前节点做新节点的下一个节点 node.prev = this; //让原来的下一个节点做新节点的下一个节点 node.next = nextNext; //让原来的下一个节点的上一个节点做新节点 nextNext.prev = node; } //下一个节点 public DoubleNode next(){ return this.next; } public DoubleNode prev(){ return this.prev; } public int getData(){ return data; } }
Ameesha15/DSA-ALGORITHMS
DoubleNode.java
201
//让原来的下一个节点的上一个节点做新节点
line_comment
zh-cn
public class DoubleNode { DoubleNode prev = this; DoubleNode next = this; int data; public DoubleNode(int data){ this.data = data; } //增加节点 public void after(DoubleNode node){ //原来的下一个节点 DoubleNode nextNext = next; //把新节点作为当前节点的前一个节点 this.next = node; //把当前节点做新节点的下一个节点 node.prev = this; //让原来的下一个节点做新节点的下一个节点 node.next = nextNext; //让原 <SUF> nextNext.prev = node; } //下一个节点 public DoubleNode next(){ return this.next; } public DoubleNode prev(){ return this.prev; } public int getData(){ return data; } }
0
188
12
201
14
219
11
201
14
277
24
false
false
false
false
false
true
34360_50
package java_work0202; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class CatApp { public static void main(String[] args) { //今回で言えば、猫の種類はランダムに決める必要があるのでRandomインスタンス //ユーザーからの入力を受け取るのでScannerインスタンスが必要となる Random rand = new Random(); Scanner sc = new Scanner(System.in); //続いて定数を定義していこう。 //今回[白,黒,茶トラ]という猫の種類は配列で扱っておくと便利そうだ。 //Catインスタンスを格納するArrayListもこのタイミングで用意しておこう。 //今回は猫を何匹でも集められる仕様なので、 //この場合は要素数が決まっている配列よりもArrayListの方が便利だ final String[] TYPES = {"白", "黒", "茶トラ"}; ArrayList<Cat> list = new ArrayList<>(); //実行例を見ると、 //メニューの表示->選択->何かしら処理 //というのが繰り返されているのがわかる。なのでforかwhileを使うことになる。 //繰り返す回数がわかる場合はforそうでない場合はwhileを使うというのが基本だ。 //今回は何度繰り返されるかわからない、なのでwhile文を使っていこう。 System.out.println("***猫集め***"); //まずは、終了が選ばれたときの処理を記述 //このように特殊な場合にすぐにreturnして処理を抜けるというのは早期リターンと呼ばれていて、 //処理のネストが深くならない上、 //わかりやすいという特徴があるのでおすすめだ while(true) { System.out.print("1.集める 2.遊ぶ 3.終了>>"); int select = sc.nextInt(); if(select == 3) { System.out.println("***結果***"); for(Cat c : list) { System.out.println(c.showStatus()); } System.out.println("また遊んでね。おしまい"); return; } //分岐の骨組みを先に書いてしまうのもよく行う手法だ。 //今回、if~elseで組んでも同じだが、 //1を選んだのか2を選んだのかがわかりやすいいように上記のif ~ else if文を使った。 if(select == 1) { //猫の種類の配列から一つを取り出している。 //ほぼイディオムとも言ってよい処理なので問題はないだろう。 String type = TYPES[rand.nextInt(TYPES.length)]; //%sは後に指定される引数(typeと思われる)で置き換えられます。 //変数 type の値に基づいてフォーマットされたメッセージを表示する System.out.printf("%s猫を見つけた!%n", type); System.out.print("この猫に名前をつけてください>>"); //名前を受け取りCatインスタンスを生成し、リストに追加する String name = sc.next(); Cat cat = new Cat(name, type); list.add(cat); System.out.println(cat.name + "が仲間に加わった!"); } //ここでもまずは異常系の処理を書いていこう。 //このように最初に異常系の処理を書いて抜けるようにするとネストが浅くなる。 //ここではreturnではなくcontinueだ。 else if(select == 2) { if(list.size() == 0) { System.out.println("まだ遊ぶ猫がいません。。。"); continue; } //showStatus()の結果をフォーマットして表示します for(int i = 0; i < list.size(); i++) { System.out.printf("%d・・・%s%n", i, list.get(i).showStatus()); } //リストに入っている猫をgetで取り出して、 //そのインスタンスがplayメソッドを実行することで親密度があがるのであった。 System.out.print("どの猫と遊びますか?>>"); int no = sc.nextInt(); list.get(no).play(); //sortCatのよびだし sortCat(list); } } } //今回は親密度で並び替えを行わなくてはならない。 //なので親密度が変わったまさにこのあとにlistのソート処理をいれる。 //ただ、この下に書くと2を選んだときの記述が長くなりすぎるので、 //この部分は以下のようにメソッドにしよう。以下の処理をメインメソッドの外に書く。 //このコードは、ArrayList内のCatオブジェクトを //intimacy(親密度)の降順にソートするための静的メソッドです。 static void sortCat(ArrayList<Cat> list) { for(int i = 0; i < list.size()-1; i++) { for(int j = i+1; j < list.size(); j++) { //list.get(i).intimacy < list.get(j).intimacyがtrueであれば、 //i番目の要素のintimacyがj番目の要素のintimacyよりも小さいということです。 //この場合、要素を入れ替えます。 if(list.get(i).intimacy < list.get(j).intimacy) { //tempを使ってi番目の要素を退避し、j番目の要素をi番目にセットし、 //最後にtempの値をj番目にセットしています。 Cat temp = list.get(i); list.set(i, list.get(j)); list.set(i, temp); } } } } } class Cat { //フィールド String name; private String type; int intimacy = 0; //コンストラクタ //クラスのインスタンスを生成するための特別なメソッドです。 //コンストラクタはクラス名と同じ名前を持ち、戻り値の型が指定されていません。 //主な目的は、新しいオブジェクトを初期化することです。 //コンストラクタは、newキーワードを使用してオブジェクトを生成する際に呼び出されます //今回は(名前、種類)を指定してインスタンスを生成できるようにする public Cat(String name, String type) { this.name = name; this.type = type; } //自分自身の情報を文字列情報として表せるメソッドex.やま[茶トラ](0) //%s:文字列、%d:整数。%f:少数、%n:改行 //String.gormat("フォーマット文字列", 仮置きした値); public String showStatus() { return String.format("%s[%s](%d)", this.name, this.type, this.intimacy); } //メソッドをどこに記述するかを考える際、重要となるのが自分のフィールド(パラメータ)を操作する部分があったら //それはインスタンスメソッドとして作成するということ //今回は遊ぶことによって親密度があがるのでこの部分はインスタンスメソッドとして記述していく public void play() { System.out.println(this.name + "と遊んだ"); System.out.println("..."); System.out.println(this.name+"の親密度がアップした!"); this.intimacy++; } }
AmiOshima0130/java_work
CatApp.java
2,102
//%s:文字列、%d:整数。%f:少数、%n:改行
line_comment
zh-cn
package java_work0202; import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class CatApp { public static void main(String[] args) { //今回で言えば、猫の種類はランダムに決める必要があるのでRandomインスタンス //ユーザーからの入力を受け取るのでScannerインスタンスが必要となる Random rand = new Random(); Scanner sc = new Scanner(System.in); //続いて定数を定義していこう。 //今回[白,黒,茶トラ]という猫の種類は配列で扱っておくと便利そうだ。 //Catインスタンスを格納するArrayListもこのタイミングで用意しておこう。 //今回は猫を何匹でも集められる仕様なので、 //この場合は要素数が決まっている配列よりもArrayListの方が便利だ final String[] TYPES = {"白", "黒", "茶トラ"}; ArrayList<Cat> list = new ArrayList<>(); //実行例を見ると、 //メニューの表示->選択->何かしら処理 //というのが繰り返されているのがわかる。なのでforかwhileを使うことになる。 //繰り返す回数がわかる場合はforそうでない場合はwhileを使うというのが基本だ。 //今回は何度繰り返されるかわからない、なのでwhile文を使っていこう。 System.out.println("***猫集め***"); //まずは、終了が選ばれたときの処理を記述 //このように特殊な場合にすぐにreturnして処理を抜けるというのは早期リターンと呼ばれていて、 //処理のネストが深くならない上、 //わかりやすいという特徴があるのでおすすめだ while(true) { System.out.print("1.集める 2.遊ぶ 3.終了>>"); int select = sc.nextInt(); if(select == 3) { System.out.println("***結果***"); for(Cat c : list) { System.out.println(c.showStatus()); } System.out.println("また遊んでね。おしまい"); return; } //分岐の骨組みを先に書いてしまうのもよく行う手法だ。 //今回、if~elseで組んでも同じだが、 //1を選んだのか2を選んだのかがわかりやすいいように上記のif ~ else if文を使った。 if(select == 1) { //猫の種類の配列から一つを取り出している。 //ほぼイディオムとも言ってよい処理なので問題はないだろう。 String type = TYPES[rand.nextInt(TYPES.length)]; //%sは後に指定される引数(typeと思われる)で置き換えられます。 //変数 type の値に基づいてフォーマットされたメッセージを表示する System.out.printf("%s猫を見つけた!%n", type); System.out.print("この猫に名前をつけてください>>"); //名前を受け取りCatインスタンスを生成し、リストに追加する String name = sc.next(); Cat cat = new Cat(name, type); list.add(cat); System.out.println(cat.name + "が仲間に加わった!"); } //ここでもまずは異常系の処理を書いていこう。 //このように最初に異常系の処理を書いて抜けるようにするとネストが浅くなる。 //ここではreturnではなくcontinueだ。 else if(select == 2) { if(list.size() == 0) { System.out.println("まだ遊ぶ猫がいません。。。"); continue; } //showStatus()の結果をフォーマットして表示します for(int i = 0; i < list.size(); i++) { System.out.printf("%d・・・%s%n", i, list.get(i).showStatus()); } //リストに入っている猫をgetで取り出して、 //そのインスタンスがplayメソッドを実行することで親密度があがるのであった。 System.out.print("どの猫と遊びますか?>>"); int no = sc.nextInt(); list.get(no).play(); //sortCatのよびだし sortCat(list); } } } //今回は親密度で並び替えを行わなくてはならない。 //なので親密度が変わったまさにこのあとにlistのソート処理をいれる。 //ただ、この下に書くと2を選んだときの記述が長くなりすぎるので、 //この部分は以下のようにメソッドにしよう。以下の処理をメインメソッドの外に書く。 //このコードは、ArrayList内のCatオブジェクトを //intimacy(親密度)の降順にソートするための静的メソッドです。 static void sortCat(ArrayList<Cat> list) { for(int i = 0; i < list.size()-1; i++) { for(int j = i+1; j < list.size(); j++) { //list.get(i).intimacy < list.get(j).intimacyがtrueであれば、 //i番目の要素のintimacyがj番目の要素のintimacyよりも小さいということです。 //この場合、要素を入れ替えます。 if(list.get(i).intimacy < list.get(j).intimacy) { //tempを使ってi番目の要素を退避し、j番目の要素をi番目にセットし、 //最後にtempの値をj番目にセットしています。 Cat temp = list.get(i); list.set(i, list.get(j)); list.set(i, temp); } } } } } class Cat { //フィールド String name; private String type; int intimacy = 0; //コンストラクタ //クラスのインスタンスを生成するための特別なメソッドです。 //コンストラクタはクラス名と同じ名前を持ち、戻り値の型が指定されていません。 //主な目的は、新しいオブジェクトを初期化することです。 //コンストラクタは、newキーワードを使用してオブジェクトを生成する際に呼び出されます //今回は(名前、種類)を指定してインスタンスを生成できるようにする public Cat(String name, String type) { this.name = name; this.type = type; } //自分自身の情報を文字列情報として表せるメソッドex.やま[茶トラ](0) //%s <SUF> //String.gormat("フォーマット文字列", 仮置きした値); public String showStatus() { return String.format("%s[%s](%d)", this.name, this.type, this.intimacy); } //メソッドをどこに記述するかを考える際、重要となるのが自分のフィールド(パラメータ)を操作する部分があったら //それはインスタンスメソッドとして作成するということ //今回は遊ぶことによって親密度があがるのでこの部分はインスタンスメソッドとして記述していく public void play() { System.out.println(this.name + "と遊んだ"); System.out.println("..."); System.out.println(this.name+"の親密度がアップした!"); this.intimacy++; } }
0
1,716
23
2,110
22
1,689
22
2,102
22
2,862
27
false
false
false
false
false
true
27852_6
前言部分: 1.concurentHashmap在jdk8以前,使用的是分段锁的设计理念来完成并发控制,1.8进行了一次非常大幅度的改版,原因有下: (1).synchronized关键字 -- 1.8对synchronized的优化已经足够好,以至于不需要用segment来增强并发 (2).类似于hashmap在1.8的增强,concurenthashmap也在出现hash冲突过多的时候采用红黑树的方式来降低query的时间 2.这里为什么分析transfer方法呢: (1).transfer方法是concurenthashmap里最复杂的方法 (2).transfer方法在1.8的时候也进行了增强,在出现多线程问题的时候,如果让我设计,我的第一反应是锁住当前map,transfer之后再修改,那么1.8里怎么做的呢,非常非常非常牛逼,它直接把另外一个线程拉进来一起帮着做transfer, 而控制transfer的就是concurenthashmap中的新数据结构,ForwardingNode。 其实这里我还有一些地方没有彻底搞明白,也借鉴了一下网上其他人对源码的解读,综合了一下我自己的理解,重要的部分都用中文做了注释,有兴趣的可以研究一下源码以及相关概念,concurenthashmap和hashmap在1.8的改变真的是非常非常大。 /** * Moves and/or copies the nodes in each bin to new table. See * above for explanation. */ private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) { int n = tab.length, stride; if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE) stride = MIN_TRANSFER_STRIDE; // subdivide range if (nextTab == null) { // initiating try { //构造一个nextTable对象 它的容量是原来的两倍 Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1]; nextTab = nt; } catch (Throwable ex) { // try to cope with OOME sizeCtl = Integer.MAX_VALUE; return; } nextTable = nextTab; //下一个表索引 + 1 在调整时 transferIndex = n; } int nextn = nextTab.length; ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab); //构造一个连节点指针 用于标志位 boolean advance = true; //并发扩容的关键属性 如果等于true 说明这个节点已经处理过 boolean finishing = false; // to ensure sweep before committing nextTab //这里是一个无限循环,直到处理结束或者(sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT条件达成 TODO <--这个条件干吗用的 for (int i = 0, bound = 0;;) { Node<K,V> f; int fh; //这个while循环体的作用就是在控制i,不断的i--,用来循环整个table while (advance) { int nextIndex, nextBound; if (--i >= bound || finishing) advance = false; else if ((nextIndex = transferIndex) <= 0) { i = -1; advance = false; } else if (U.compareAndSwapInt(this, TRANSFERINDEX, nextIndex,nextBound = (nextIndex > stride ? nextIndex - stride : 0))) { bound = nextBound; i = nextIndex - 1; advance = false; } } //nextn就是下一个table的长度,n是旧表的长度,i则是每一个元素的位置 if (i < 0 || i >= n || i + n >= nextn) { int sc; //如果所有的节点都已经完成复制工作 就把nextTable赋值给table 清空临时对象nextTable if (finishing) { nextTable = null; table = nextTab; sizeCtl = (n << 1) - (n >>> 1);//扩容阈值设置为原来容量的1.5倍 依然相当于现在容量的0.75倍 return; } if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) { //什么时候会在这里返回??? if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) { return; } finishing = advance = true; i = n; // recheck before commit } } else if ((f = tabAt(tab, i)) == null) { //如果遍历到的节点为空 则放入ForwardingNode指针 advance = casTabAt(tab, i, null, fwd); } else if ((fh = f.hash) == MOVED) { //如果遍历到ForwardingNode节点 说明这个点已经被处理过了 直接跳过 这里是控制并发扩容的核心 advance = true; // already processed } else { synchronized (f) { if (tabAt(tab, i) == f) { Node<K,V> ln, hn; //如果fh>=0 证明这是一个Node节点 if (fh >= 0) { //以下的部分在完成的工作是构造两个链表 int runBit = fh & n; Node<K,V> lastRun = f; for (Node<K,V> p = f.next; p != null; p = p.next) { int b = p.hash & n; if (b != runBit) { runBit = b; lastRun = p; } } if (runBit == 0) { ln = lastRun; hn = null; } else { hn = lastRun; ln = null; } for (Node<K,V> p = f; p != lastRun; p = p.next) { int ph = p.hash; K pk = p.key; V pv = p.val; if ((ph & n) == 0) ln = new Node<K,V>(ph, pk, pv, ln); else hn = new Node<K,V>(ph, pk, pv, hn); } //在nextTable的i位置上插入一个链表 setTabAt(nextTab, i, ln); //这是在干吗没看懂- - setTabAt(nextTab, i + n, hn); //在table的i位置上插入forwardNode节点 表示已经处理过该节点 setTabAt(tab, i, fwd); //设置advance为true 返回到上面的while循环中 就可以执行i--操作 advance = true; } //对TreeBin对象进行处理 与上面的过程类似 else if (f instanceof TreeBin) { TreeBin<K,V> t = (TreeBin<K,V>)f; TreeNode<K,V> lo = null, loTail = null; TreeNode<K,V> hi = null, hiTail = null; int lc = 0, hc = 0; for (Node<K,V> e = t.first; e != null; e = e.next) { int h = e.hash; TreeNode<K,V> p = new TreeNode<K,V> (h, e.key, e.val, null, null); if ((h & n) == 0) { if ((p.prev = loTail) == null) lo = p; else loTail.next = p; loTail = p; ++lc; } else { if ((p.prev = hiTail) == null) hi = p; else hiTail.next = p; hiTail = p; ++hc; } } //如果扩容后已经不再需要tree的结构 反向转换为链表结构 ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin<K,V>(lo) : t; hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin<K,V>(hi) : t; setTabAt(nextTab, i, ln); setTabAt(nextTab, i + n, hn); setTabAt(tab, i, fwd); advance = true; } } } } // end if } }
Amnesiacs/Dubbo-Code
顺道分享java源码解析/transfer.java
2,020
//构造一个连节点指针 用于标志位
line_comment
zh-cn
前言部分: 1.concurentHashmap在jdk8以前,使用的是分段锁的设计理念来完成并发控制,1.8进行了一次非常大幅度的改版,原因有下: (1).synchronized关键字 -- 1.8对synchronized的优化已经足够好,以至于不需要用segment来增强并发 (2).类似于hashmap在1.8的增强,concurenthashmap也在出现hash冲突过多的时候采用红黑树的方式来降低query的时间 2.这里为什么分析transfer方法呢: (1).transfer方法是concurenthashmap里最复杂的方法 (2).transfer方法在1.8的时候也进行了增强,在出现多线程问题的时候,如果让我设计,我的第一反应是锁住当前map,transfer之后再修改,那么1.8里怎么做的呢,非常非常非常牛逼,它直接把另外一个线程拉进来一起帮着做transfer, 而控制transfer的就是concurenthashmap中的新数据结构,ForwardingNode。 其实这里我还有一些地方没有彻底搞明白,也借鉴了一下网上其他人对源码的解读,综合了一下我自己的理解,重要的部分都用中文做了注释,有兴趣的可以研究一下源码以及相关概念,concurenthashmap和hashmap在1.8的改变真的是非常非常大。 /** * Moves and/or copies the nodes in each bin to new table. See * above for explanation. */ private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) { int n = tab.length, stride; if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE) stride = MIN_TRANSFER_STRIDE; // subdivide range if (nextTab == null) { // initiating try { //构造一个nextTable对象 它的容量是原来的两倍 Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1]; nextTab = nt; } catch (Throwable ex) { // try to cope with OOME sizeCtl = Integer.MAX_VALUE; return; } nextTable = nextTab; //下一个表索引 + 1 在调整时 transferIndex = n; } int nextn = nextTab.length; ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab); //构造 <SUF> boolean advance = true; //并发扩容的关键属性 如果等于true 说明这个节点已经处理过 boolean finishing = false; // to ensure sweep before committing nextTab //这里是一个无限循环,直到处理结束或者(sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT条件达成 TODO <--这个条件干吗用的 for (int i = 0, bound = 0;;) { Node<K,V> f; int fh; //这个while循环体的作用就是在控制i,不断的i--,用来循环整个table while (advance) { int nextIndex, nextBound; if (--i >= bound || finishing) advance = false; else if ((nextIndex = transferIndex) <= 0) { i = -1; advance = false; } else if (U.compareAndSwapInt(this, TRANSFERINDEX, nextIndex,nextBound = (nextIndex > stride ? nextIndex - stride : 0))) { bound = nextBound; i = nextIndex - 1; advance = false; } } //nextn就是下一个table的长度,n是旧表的长度,i则是每一个元素的位置 if (i < 0 || i >= n || i + n >= nextn) { int sc; //如果所有的节点都已经完成复制工作 就把nextTable赋值给table 清空临时对象nextTable if (finishing) { nextTable = null; table = nextTab; sizeCtl = (n << 1) - (n >>> 1);//扩容阈值设置为原来容量的1.5倍 依然相当于现在容量的0.75倍 return; } if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) { //什么时候会在这里返回??? if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) { return; } finishing = advance = true; i = n; // recheck before commit } } else if ((f = tabAt(tab, i)) == null) { //如果遍历到的节点为空 则放入ForwardingNode指针 advance = casTabAt(tab, i, null, fwd); } else if ((fh = f.hash) == MOVED) { //如果遍历到ForwardingNode节点 说明这个点已经被处理过了 直接跳过 这里是控制并发扩容的核心 advance = true; // already processed } else { synchronized (f) { if (tabAt(tab, i) == f) { Node<K,V> ln, hn; //如果fh>=0 证明这是一个Node节点 if (fh >= 0) { //以下的部分在完成的工作是构造两个链表 int runBit = fh & n; Node<K,V> lastRun = f; for (Node<K,V> p = f.next; p != null; p = p.next) { int b = p.hash & n; if (b != runBit) { runBit = b; lastRun = p; } } if (runBit == 0) { ln = lastRun; hn = null; } else { hn = lastRun; ln = null; } for (Node<K,V> p = f; p != lastRun; p = p.next) { int ph = p.hash; K pk = p.key; V pv = p.val; if ((ph & n) == 0) ln = new Node<K,V>(ph, pk, pv, ln); else hn = new Node<K,V>(ph, pk, pv, hn); } //在nextTable的i位置上插入一个链表 setTabAt(nextTab, i, ln); //这是在干吗没看懂- - setTabAt(nextTab, i + n, hn); //在table的i位置上插入forwardNode节点 表示已经处理过该节点 setTabAt(tab, i, fwd); //设置advance为true 返回到上面的while循环中 就可以执行i--操作 advance = true; } //对TreeBin对象进行处理 与上面的过程类似 else if (f instanceof TreeBin) { TreeBin<K,V> t = (TreeBin<K,V>)f; TreeNode<K,V> lo = null, loTail = null; TreeNode<K,V> hi = null, hiTail = null; int lc = 0, hc = 0; for (Node<K,V> e = t.first; e != null; e = e.next) { int h = e.hash; TreeNode<K,V> p = new TreeNode<K,V> (h, e.key, e.val, null, null); if ((h & n) == 0) { if ((p.prev = loTail) == null) lo = p; else loTail.next = p; loTail = p; ++lc; } else { if ((p.prev = hiTail) == null) hi = p; else hiTail.next = p; hiTail = p; ++hc; } } //如果扩容后已经不再需要tree的结构 反向转换为链表结构 ln = (lc <= UNTREEIFY_THRESHOLD) ? untreeify(lo) : (hc != 0) ? new TreeBin<K,V>(lo) : t; hn = (hc <= UNTREEIFY_THRESHOLD) ? untreeify(hi) : (lc != 0) ? new TreeBin<K,V>(hi) : t; setTabAt(nextTab, i, ln); setTabAt(nextTab, i + n, hn); setTabAt(tab, i, fwd); advance = true; } } } } // end if } }
0
1,872
11
2,020
11
2,048
9
2,020
11
2,779
18
false
false
false
false
false
true
63096_0
package anmao.mc.ned.mob$skill.b2; import anmao.mc.amlib.attribute.AttributeHelper; import anmao.mc.ned.attribute.NEDAttributes; import anmao.mc.ned.lib.EntityHelper; import anmao.mc.ned.mob$skill.MobSkill; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.eventbus.api.Event; import java.util.List; public class AloneMobSkill extends MobSkill { //孤独 //怪物越少,攻击力,移速,减伤提升越多 public AloneMobSkill(String id) { super(id); } @Override public <T extends Event> void event(T event, CompoundTag dat) { if (event instanceof LivingEvent.LivingTickEvent livingTickEvent){ int tick = dat.getInt("tick"); if (tick > 200){ dat.putInt("tick",0); LivingEntity entity = livingTickEvent.getEntity(); List<? extends LivingEntity> entities = EntityHelper.getLivingEntities(entity); double s = 1d / entities.size(); double a = 1 + s * 5; AttributeHelper.setTempAttribute(entity, Attributes.ATTACK_DAMAGE,ATTRIBUTE_SKILL_ATTACK_DAMAGE,a, AttributeModifier.Operation.MULTIPLY_TOTAL,180); a = 1 + s * 2; AttributeHelper.setTempAttribute(entity, Attributes.MOVEMENT_SPEED,ATTRIBUTE_SKILL_MOVE_SPEED,a, AttributeModifier.Operation.MULTIPLY_TOTAL,180); a = s * 50; AttributeHelper.setTempAttribute(entity, NEDAttributes.hurtDown,ATTRIBUTE_SKILL_HURT_DOWN,a, AttributeModifier.Operation.ADDITION,180); }else { dat.putInt("tick",tick + 1); } } } }
An-Mao/NekoDifficulty
src/main/java/anmao/mc/ned/mob$skill/b2/AloneMobSkill.java
530
//怪物越少,攻击力,移速,减伤提升越多
line_comment
zh-cn
package anmao.mc.ned.mob$skill.b2; import anmao.mc.amlib.attribute.AttributeHelper; import anmao.mc.ned.attribute.NEDAttributes; import anmao.mc.ned.lib.EntityHelper; import anmao.mc.ned.mob$skill.MobSkill; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.LivingEntity; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraftforge.event.entity.living.LivingEvent; import net.minecraftforge.eventbus.api.Event; import java.util.List; public class AloneMobSkill extends MobSkill { //孤独 //怪物 <SUF> public AloneMobSkill(String id) { super(id); } @Override public <T extends Event> void event(T event, CompoundTag dat) { if (event instanceof LivingEvent.LivingTickEvent livingTickEvent){ int tick = dat.getInt("tick"); if (tick > 200){ dat.putInt("tick",0); LivingEntity entity = livingTickEvent.getEntity(); List<? extends LivingEntity> entities = EntityHelper.getLivingEntities(entity); double s = 1d / entities.size(); double a = 1 + s * 5; AttributeHelper.setTempAttribute(entity, Attributes.ATTACK_DAMAGE,ATTRIBUTE_SKILL_ATTACK_DAMAGE,a, AttributeModifier.Operation.MULTIPLY_TOTAL,180); a = 1 + s * 2; AttributeHelper.setTempAttribute(entity, Attributes.MOVEMENT_SPEED,ATTRIBUTE_SKILL_MOVE_SPEED,a, AttributeModifier.Operation.MULTIPLY_TOTAL,180); a = s * 50; AttributeHelper.setTempAttribute(entity, NEDAttributes.hurtDown,ATTRIBUTE_SKILL_HURT_DOWN,a, AttributeModifier.Operation.ADDITION,180); }else { dat.putInt("tick",tick + 1); } } } }
0
419
14
530
21
520
15
530
21
633
27
false
false
false
false
false
true
50986_2
package com.cy.tablayoutsimple_; import android.graphics.Typeface; import android.os.Bundle; import android.util.DisplayMetrics; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.viewpager2.widget.ViewPager2; import com.cy.tablayoutniubility.TabMediatorVp2; import com.cy.tablayoutniubility.TabViewHolder; import com.cy.tablayoutniubility.FragPageAdapterVp2; import com.cy.tablayoutniubility.TabAdapter; import com.cy.tablayoutniubility.TabLayoutScroll; import java.util.ArrayList; import java.util.List; public class TabLayoutVP2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tab_layout_r_v); ViewPager2 viewPager2 = findViewById(R.id.view_pager); TabLayoutScroll tabLayoutLine = findViewById(R.id.tablayout); // tabLayoutLine.setSpace_horizontal(dpAdapt(20)).setSpace_vertical(dpAdapt(8)); FragPageAdapterVp2<String> fragmentPageAdapter = new FragPageAdapterVp2<String>(this) { @Override public Fragment createFragment(String bean, int position) { LogUtils.log("createFragmentpppppppppppp",position); return FragmentTab2.newInstance(FragmentTab2.TAB_NAME2, getList_bean().get(position)); } @Override public void bindDataToTab(TabViewHolder holder, int position, String bean, boolean isSelected) { TextView textView = holder.getView(R.id.tv); if (isSelected) { textView.setTextColor(0xffe45540); textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); } else { textView.setTextColor(0xff444444); textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); } textView.setText(bean); } @Override public int getTabLayoutID(int position, String bean) { if (position == 0) { return R.layout.item_tab_msg; } return R.layout.item_tab; } }; TabAdapter<String> tabAdapter = new TabMediatorVp2<String>(tabLayoutLine, viewPager2).setAdapter(fragmentPageAdapter); List<String> list = new ArrayList<>(); list.add("关注"); list.add("推荐"); list.add("视频"); list.add("抗疫"); list.add("深圳"); list.add("热榜"); list.add("小视频"); list.add("软件"); list.add("探索"); list.add("在家上课"); list.add("手机"); list.add("动漫"); list.add("通信"); list.add("影视"); list.add("互联网"); list.add("设计"); list.add("家电"); list.add("平板"); list.add("网球"); list.add("军事"); list.add("羽毛球"); list.add("奢侈品"); list.add("美食"); list.add("瘦身"); list.add("幸福里"); list.add("棋牌"); list.add("奇闻"); list.add("艺术"); list.add("减肥"); list.add("电玩"); list.add("台球"); list.add("八卦"); list.add("酷玩"); list.add("彩票"); list.add("漫画"); fragmentPageAdapter.add(list); tabAdapter.add(list); } /** * -------------------------------------------------------------------------------- */ public int dpAdapt(float dp) { return dpAdapt(dp, 360); } public int dpAdapt(float dp, float widthDpBase) { DisplayMetrics dm = getResources().getDisplayMetrics(); int heightPixels = dm.heightPixels;//高的像素 int widthPixels = dm.widthPixels;//宽的像素 float density = dm.density;//density=dpi/160,密度比 float heightDP = heightPixels / density;//高度的dp float widthDP = widthPixels / density;//宽度的dp float w = widthDP > heightDP ? heightDP : widthDP; return (int) (dp * w / widthDpBase * density + 0.5f); } }
AnJiaoDe/TabLayoutNiubility
app/src/main/java/com/cy/tablayoutsimple_/TabLayoutVP2Activity.java
1,085
//高的像素
line_comment
zh-cn
package com.cy.tablayoutsimple_; import android.graphics.Typeface; import android.os.Bundle; import android.util.DisplayMetrics; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.viewpager2.widget.ViewPager2; import com.cy.tablayoutniubility.TabMediatorVp2; import com.cy.tablayoutniubility.TabViewHolder; import com.cy.tablayoutniubility.FragPageAdapterVp2; import com.cy.tablayoutniubility.TabAdapter; import com.cy.tablayoutniubility.TabLayoutScroll; import java.util.ArrayList; import java.util.List; public class TabLayoutVP2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tab_layout_r_v); ViewPager2 viewPager2 = findViewById(R.id.view_pager); TabLayoutScroll tabLayoutLine = findViewById(R.id.tablayout); // tabLayoutLine.setSpace_horizontal(dpAdapt(20)).setSpace_vertical(dpAdapt(8)); FragPageAdapterVp2<String> fragmentPageAdapter = new FragPageAdapterVp2<String>(this) { @Override public Fragment createFragment(String bean, int position) { LogUtils.log("createFragmentpppppppppppp",position); return FragmentTab2.newInstance(FragmentTab2.TAB_NAME2, getList_bean().get(position)); } @Override public void bindDataToTab(TabViewHolder holder, int position, String bean, boolean isSelected) { TextView textView = holder.getView(R.id.tv); if (isSelected) { textView.setTextColor(0xffe45540); textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); } else { textView.setTextColor(0xff444444); textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); } textView.setText(bean); } @Override public int getTabLayoutID(int position, String bean) { if (position == 0) { return R.layout.item_tab_msg; } return R.layout.item_tab; } }; TabAdapter<String> tabAdapter = new TabMediatorVp2<String>(tabLayoutLine, viewPager2).setAdapter(fragmentPageAdapter); List<String> list = new ArrayList<>(); list.add("关注"); list.add("推荐"); list.add("视频"); list.add("抗疫"); list.add("深圳"); list.add("热榜"); list.add("小视频"); list.add("软件"); list.add("探索"); list.add("在家上课"); list.add("手机"); list.add("动漫"); list.add("通信"); list.add("影视"); list.add("互联网"); list.add("设计"); list.add("家电"); list.add("平板"); list.add("网球"); list.add("军事"); list.add("羽毛球"); list.add("奢侈品"); list.add("美食"); list.add("瘦身"); list.add("幸福里"); list.add("棋牌"); list.add("奇闻"); list.add("艺术"); list.add("减肥"); list.add("电玩"); list.add("台球"); list.add("八卦"); list.add("酷玩"); list.add("彩票"); list.add("漫画"); fragmentPageAdapter.add(list); tabAdapter.add(list); } /** * -------------------------------------------------------------------------------- */ public int dpAdapt(float dp) { return dpAdapt(dp, 360); } public int dpAdapt(float dp, float widthDpBase) { DisplayMetrics dm = getResources().getDisplayMetrics(); int heightPixels = dm.heightPixels;//高的 <SUF> int widthPixels = dm.widthPixels;//宽的像素 float density = dm.density;//density=dpi/160,密度比 float heightDP = heightPixels / density;//高度的dp float widthDP = widthPixels / density;//宽度的dp float w = widthDP > heightDP ? heightDP : widthDP; return (int) (dp * w / widthDpBase * density + 0.5f); } }
0
894
3
1,085
5
1,108
3
1,085
5
1,344
5
false
false
false
false
false
true
64141_8
package _2021_B2; import java.io.*; import java.util.*; /* * 有 n 台计算机,第 i 台计算机的运算能力为 vi。 有一系列的任务被指派到各个计算机上,第 i 个任务在 ai 时刻分配,指定 计算机编号为 bi ,耗时为 ci 且算力消耗为 di 。如果此任务成功分配,将立刻 开始运行,期间持续占用 bi 号计算机 di 的算力,持续 ci 秒。 对于每次任务分配,如果计算机剩余的运算能力不足则输出 −1,并取消这 次分配,否则输出分配完这个任务后这台计算机的剩余运算能力。 【输入格式】 输入的第一行包含两个整数 n, m,分别表示计算机数目和要分配的任务数。 第二行包含 n 个整数 v1, v2, · · · vn,分别表示每个计算机的运算能力。 接下来 m 行每行 4 个整数 ai, bi, ci, di,意义如上所述。数据保证 ai 严格递 增,即 ai < ai+1。 【输出格式】 输出 m 行,每行包含一个数,对应每次任务分配的结果。 【样例输入】 2 6 5 5 1 1 5 3 2 2 2 6 3 1 2 3 4 1 6 1 5 1 3 3 6 1 3 4 【样例输出】 2 -1 -1 1 -1 0 【样例说明】 时刻 1,第 1 个任务被分配到第 1 台计算机,耗时为 5 ,这个任务时刻 6 会结束,占用计算机 1 的算力 3。 时刻 2,第 2 个任务需要的算力不足,所以分配失败了。 时刻 3,第 1 个计算机仍然正在计算第 1 个任务,剩余算力不足 3,所以 失败。 时刻 4,第 1 个计算机仍然正在计算第 1 个任务,但剩余算力足够,分配 后剩余算力 1。 时刻 5,第 1 个计算机仍然正在计算第 1, 4 个任务,剩余算力不足 4,失 败。 时刻 6,第 1 个计算机仍然正在计算第 4 个任务,剩余算力足够,且恰好 用完。 【评测用例规模与约定】 对于 20% 的评测用例,n, m ≤ 200。 对于 40% 的评测用例,n, m ≤ 2000。 对于所有评测用例,1 ≤ n, m ≤ 200000,1 ≤ ai, ci, di, vi ≤ 109,1 ≤ bi ≤ n。 ———————————————— 版权声明:本文为CSDN博主「dem.o」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_45800978/article/details/116724283 */ public class _09负载均衡 { /* * 直接模拟,用优先队列,也就是所谓的堆去存储一个个节点,这个节点存储着当前任务的结束时刻, * 和恢复体力值,考虑到有多个计算机,应该要用优先队列数组进行存储。 再次强调Java中使用System.out.println速度过慢的问题,改用BufferedWriter, 打印的时候将输出内容转换为String类型即可。 ———————————————— 版权声明:本文为CSDN博主「可乐塞满冰」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/Mxeron/article/details/123021102 */ static class node{ int reHour; int health; node(){}; node(int reHour, int health) { this.reHour = reHour; this.health = health; } static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String args[]) throws IOException { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); // 运算能力 int[] com = new int[n + 1]; for (int i = 1; i <= n; i++) { com[i] = scan.nextInt(); } // 构建优先队列 Queue<node>[] pq = new PriorityQueue[n + 1]; for (int i = 0; i < n + 1; i++) { pq[i] = new PriorityQueue<>(new Comparator<node>() { @Override // 按照恢复时间从小到大排序 public int compare(node o1, node o2) { return o1.reHour - o2.reHour; } }); } int a, b, c, d; for (int i = 0; i < m; i++) { // 第 i 个任务在 ai 时刻分配,指定计算机编号为 bi,耗时为 ci 且算力消耗为 di // 如果此任务成功分配,将立刻开始运行,期间持续占用 bi 号计算机 di 的算力,持续 ci 秒 a = scan.nextInt(); b = scan.nextInt(); c = scan.nextInt(); d = scan.nextInt(); // 注意任务执行完,算力是可以恢复的 while (!pq[b].isEmpty()) { node tmp = pq[b].peek(); if (tmp.reHour <= a) { com[b] += tmp.health; pq[b].poll(); } else { break; } } if (com[b] < d) { log.write(-1 + ""); log.write("\n"); } else { // 消耗计算机算力 com[b] -= d; // 入队 pq[b].offer(new node(a + c, d)); log.write(com[b] + ""); log.write('\n'); } } log.flush(); } } }
Anan121no/LanQiao-
src/_2021_B2/_09负载均衡.java
1,556
// 消耗计算机算力
line_comment
zh-cn
package _2021_B2; import java.io.*; import java.util.*; /* * 有 n 台计算机,第 i 台计算机的运算能力为 vi。 有一系列的任务被指派到各个计算机上,第 i 个任务在 ai 时刻分配,指定 计算机编号为 bi ,耗时为 ci 且算力消耗为 di 。如果此任务成功分配,将立刻 开始运行,期间持续占用 bi 号计算机 di 的算力,持续 ci 秒。 对于每次任务分配,如果计算机剩余的运算能力不足则输出 −1,并取消这 次分配,否则输出分配完这个任务后这台计算机的剩余运算能力。 【输入格式】 输入的第一行包含两个整数 n, m,分别表示计算机数目和要分配的任务数。 第二行包含 n 个整数 v1, v2, · · · vn,分别表示每个计算机的运算能力。 接下来 m 行每行 4 个整数 ai, bi, ci, di,意义如上所述。数据保证 ai 严格递 增,即 ai < ai+1。 【输出格式】 输出 m 行,每行包含一个数,对应每次任务分配的结果。 【样例输入】 2 6 5 5 1 1 5 3 2 2 2 6 3 1 2 3 4 1 6 1 5 1 3 3 6 1 3 4 【样例输出】 2 -1 -1 1 -1 0 【样例说明】 时刻 1,第 1 个任务被分配到第 1 台计算机,耗时为 5 ,这个任务时刻 6 会结束,占用计算机 1 的算力 3。 时刻 2,第 2 个任务需要的算力不足,所以分配失败了。 时刻 3,第 1 个计算机仍然正在计算第 1 个任务,剩余算力不足 3,所以 失败。 时刻 4,第 1 个计算机仍然正在计算第 1 个任务,但剩余算力足够,分配 后剩余算力 1。 时刻 5,第 1 个计算机仍然正在计算第 1, 4 个任务,剩余算力不足 4,失 败。 时刻 6,第 1 个计算机仍然正在计算第 4 个任务,剩余算力足够,且恰好 用完。 【评测用例规模与约定】 对于 20% 的评测用例,n, m ≤ 200。 对于 40% 的评测用例,n, m ≤ 2000。 对于所有评测用例,1 ≤ n, m ≤ 200000,1 ≤ ai, ci, di, vi ≤ 109,1 ≤ bi ≤ n。 ———————————————— 版权声明:本文为CSDN博主「dem.o」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_45800978/article/details/116724283 */ public class _09负载均衡 { /* * 直接模拟,用优先队列,也就是所谓的堆去存储一个个节点,这个节点存储着当前任务的结束时刻, * 和恢复体力值,考虑到有多个计算机,应该要用优先队列数组进行存储。 再次强调Java中使用System.out.println速度过慢的问题,改用BufferedWriter, 打印的时候将输出内容转换为String类型即可。 ———————————————— 版权声明:本文为CSDN博主「可乐塞满冰」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/Mxeron/article/details/123021102 */ static class node{ int reHour; int health; node(){}; node(int reHour, int health) { this.reHour = reHour; this.health = health; } static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String args[]) throws IOException { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int m = scan.nextInt(); // 运算能力 int[] com = new int[n + 1]; for (int i = 1; i <= n; i++) { com[i] = scan.nextInt(); } // 构建优先队列 Queue<node>[] pq = new PriorityQueue[n + 1]; for (int i = 0; i < n + 1; i++) { pq[i] = new PriorityQueue<>(new Comparator<node>() { @Override // 按照恢复时间从小到大排序 public int compare(node o1, node o2) { return o1.reHour - o2.reHour; } }); } int a, b, c, d; for (int i = 0; i < m; i++) { // 第 i 个任务在 ai 时刻分配,指定计算机编号为 bi,耗时为 ci 且算力消耗为 di // 如果此任务成功分配,将立刻开始运行,期间持续占用 bi 号计算机 di 的算力,持续 ci 秒 a = scan.nextInt(); b = scan.nextInt(); c = scan.nextInt(); d = scan.nextInt(); // 注意任务执行完,算力是可以恢复的 while (!pq[b].isEmpty()) { node tmp = pq[b].peek(); if (tmp.reHour <= a) { com[b] += tmp.health; pq[b].poll(); } else { break; } } if (com[b] < d) { log.write(-1 + ""); log.write("\n"); } else { // 消耗 <SUF> com[b] -= d; // 入队 pq[b].offer(new node(a + c, d)); log.write(com[b] + ""); log.write('\n'); } } log.flush(); } } }
0
1,372
7
1,556
8
1,535
6
1,556
8
2,219
11
false
false
false
false
false
true
29847_6
package io; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class SelectorExample { public static void main(String[] args) throws Exception{ Selector selector = Selector.open(); ServerSocketChannel servChannel = ServerSocketChannel.open(); servChannel.configureBlocking(false); // 建立一个server socket,到本地端口9999, backlog 1024 servChannel.socket().setReuseAddress(true); servChannel.socket().bind(new InetSocketAddress(9999), 1024); // selector 关心 server 上的 ACCEPT 事件 servChannel.register(selector, SelectionKey.OP_ACCEPT); servChannel.register(selector, SelectionKey.OP_CONNECT, new SelectorExample()); boolean start = true; while (start) { try { // 阻塞等待 直到有IO事件可读(系统IO事件队列不为空) selector.select(); // 获取 事件 以及 事件所对应的 channel (client server 的连接) Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectedKeys.iterator(); SelectionKey key = null; while (it.hasNext()) { key = it.next(); it.remove(); try { if (key.isValid()) { // OP_ACCEPT 事件 表示有个新client 完成了三次握手。连接上了本服务器 if (key.isAcceptable()) { // Accept the new connection ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); // 将该连接的可读事件 注册到 selector, 到时候他发起请求的时候,我会收到新事件 sc.register(selector, SelectionKey.OP_READ); } // OP_READ 事件 说明 client 发的数据已经发到了系统缓冲区,server 可以去读了。 if (key.isReadable()) { SocketChannel sc = (SocketChannel) key.channel(); // 分配用户台空间, 将数据从内核态 拷贝到 用户态 ByteBuffer readBuffer = ByteBuffer.allocate(4); int readBytes = sc.read(readBuffer); if (readBytes > 0) { // 切换读写模式 详见下面的图, 表示自己目前可以读 [position, limit] readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; // 将buffer 数据拷贝到 bytes 数组 // 如果这里只收到一半的数据怎么办? String body = new String(bytes, "UTF-8"); System.out.println(body); // 将 read的数据 写回去 ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); writeBuffer.put(bytes); writeBuffer.flip(); sc.write(writeBuffer); } else if (readBytes < 0) { // 对端链路关闭 key.cancel(); sc.close(); } else ; } } } catch (Exception e) { if (key != null) { key.cancel(); if (key.channel() != null) key.channel().close(); } } } } catch (Exception e) { throw e; } } } }
AndiHappy/dayCode
src/main/java/io/SelectorExample.java
853
// 将该连接的可读事件 注册到 selector, 到时候他发起请求的时候,我会收到新事件
line_comment
zh-cn
package io; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class SelectorExample { public static void main(String[] args) throws Exception{ Selector selector = Selector.open(); ServerSocketChannel servChannel = ServerSocketChannel.open(); servChannel.configureBlocking(false); // 建立一个server socket,到本地端口9999, backlog 1024 servChannel.socket().setReuseAddress(true); servChannel.socket().bind(new InetSocketAddress(9999), 1024); // selector 关心 server 上的 ACCEPT 事件 servChannel.register(selector, SelectionKey.OP_ACCEPT); servChannel.register(selector, SelectionKey.OP_CONNECT, new SelectorExample()); boolean start = true; while (start) { try { // 阻塞等待 直到有IO事件可读(系统IO事件队列不为空) selector.select(); // 获取 事件 以及 事件所对应的 channel (client server 的连接) Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> it = selectedKeys.iterator(); SelectionKey key = null; while (it.hasNext()) { key = it.next(); it.remove(); try { if (key.isValid()) { // OP_ACCEPT 事件 表示有个新client 完成了三次握手。连接上了本服务器 if (key.isAcceptable()) { // Accept the new connection ServerSocketChannel ssc = (ServerSocketChannel) key.channel(); SocketChannel sc = ssc.accept(); sc.configureBlocking(false); // 将该 <SUF> sc.register(selector, SelectionKey.OP_READ); } // OP_READ 事件 说明 client 发的数据已经发到了系统缓冲区,server 可以去读了。 if (key.isReadable()) { SocketChannel sc = (SocketChannel) key.channel(); // 分配用户台空间, 将数据从内核态 拷贝到 用户态 ByteBuffer readBuffer = ByteBuffer.allocate(4); int readBytes = sc.read(readBuffer); if (readBytes > 0) { // 切换读写模式 详见下面的图, 表示自己目前可以读 [position, limit] readBuffer.flip(); byte[] bytes = new byte[readBuffer.remaining()]; // 将buffer 数据拷贝到 bytes 数组 // 如果这里只收到一半的数据怎么办? String body = new String(bytes, "UTF-8"); System.out.println(body); // 将 read的数据 写回去 ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); writeBuffer.put(bytes); writeBuffer.flip(); sc.write(writeBuffer); } else if (readBytes < 0) { // 对端链路关闭 key.cancel(); sc.close(); } else ; } } } catch (Exception e) { if (key != null) { key.cancel(); if (key.channel() != null) key.channel().close(); } } } } catch (Exception e) { throw e; } } } }
0
765
26
853
28
908
22
853
28
1,193
41
false
false
false
false
false
true
60187_18
package com.andrewtse.testdemo.activity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import butterknife.BindView; import butterknife.ButterKnife; import com.andrewtse.testdemo.R; import com.andrewtse.testdemo.sound.media.MusicPlayer; import com.andrewtse.testdemo.sound.media.NetMusicPlayer; import com.andrewtse.testdemo.sound.widget.AlphaImageView; import com.andrewtse.testdemo.sound.widget.ProgressView; public class MediaPlayerActivity extends AppCompatActivity { @BindView(R.id.id_pv_pre) public ProgressView mProgressView; @BindView(R.id.id_iv_ctrl) public ImageView mIvCtrl; @BindView(R.id.id_iv_next) public AlphaImageView mIvNext; @BindView(R.id.id_iv_pre_list) public AlphaImageView mIvPreList; @BindView(R.id.id_tv_music_name) public TextView mTvMusicName; @BindView(R.id.id_tv_singer) public TextView mTvSignerName; private MusicPlayer mLocalMusicPlayer; private NetMusicPlayer mNetMusicPlayer; private final String mFilePath = "/sdcard/Music/"; private final String mFileUri = "http://172.18.67.240:8080/test_music.mp3"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_media_player); ButterKnife.bind(this); //本地音乐播放--start // mLocalMusicPlayer = new MusicPlayer(); // // mLocalMusicPlayer.setOnSeekListener(per_100 -> mProgressView.setProgress(per_100)); // mLocalMusicPlayer.setOnBufferListener(per_100 -> mProgressView.setProgress2(per_100)); // mProgressView.setOnDragListener(per_100 -> mLocalMusicPlayer.seekTo(per_100)); // // mIvCtrl.setOnClickListener(v -> { // if (mLocalMusicPlayer.isPlaying()) { // mLocalMusicPlayer.pause(); // mIvCtrl.setImageResource(R.drawable.icon_stop_2);//设置图标暂停 // } else { // mLocalMusicPlayer.start(mFilePath + "向天再借五百年 - 韩磊.mp3"); // mIvCtrl.setImageResource(R.drawable.icon_start_2);//设置图标播放 // } // }); // mTvMusicName.setText("向天再借五百年"); // mTvSignerName.setText("韩磊"); //end //网络音乐播放--start mNetMusicPlayer = new NetMusicPlayer(this); mNetMusicPlayer.setOnSeekListener(per_100 -> mProgressView.setProgress(per_100)); mNetMusicPlayer.setOnBufferListener(per_100 -> mProgressView.setProgress2(per_100)); mProgressView.setOnDragListener(per_100 -> mNetMusicPlayer.seekTo(per_100)); mIvCtrl.setOnClickListener(v -> { if (mNetMusicPlayer.isPlaying()) { mNetMusicPlayer.pause(); mIvCtrl.setImageResource(R.drawable.icon_stop_2);//设置图标暂停 } else { mNetMusicPlayer.start(mFileUri); mIvCtrl.setImageResource(R.drawable.icon_start_2);//设置图标播放 } }); mTvMusicName.setText("勇气"); mTvSignerName.setText("梁静茹"); } @Override protected void onDestroy() { super.onDestroy(); if (mLocalMusicPlayer != null) { mLocalMusicPlayer.onDestroy(); } if (mNetMusicPlayer != null) { mNetMusicPlayer.onDestroy(); } } }
AndrewTseZhou/AndroidDayDayUp
app/src/main/java/com/andrewtse/testdemo/activity/MediaPlayerActivity.java
991
//设置图标暂停
line_comment
zh-cn
package com.andrewtse.testdemo.activity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import butterknife.BindView; import butterknife.ButterKnife; import com.andrewtse.testdemo.R; import com.andrewtse.testdemo.sound.media.MusicPlayer; import com.andrewtse.testdemo.sound.media.NetMusicPlayer; import com.andrewtse.testdemo.sound.widget.AlphaImageView; import com.andrewtse.testdemo.sound.widget.ProgressView; public class MediaPlayerActivity extends AppCompatActivity { @BindView(R.id.id_pv_pre) public ProgressView mProgressView; @BindView(R.id.id_iv_ctrl) public ImageView mIvCtrl; @BindView(R.id.id_iv_next) public AlphaImageView mIvNext; @BindView(R.id.id_iv_pre_list) public AlphaImageView mIvPreList; @BindView(R.id.id_tv_music_name) public TextView mTvMusicName; @BindView(R.id.id_tv_singer) public TextView mTvSignerName; private MusicPlayer mLocalMusicPlayer; private NetMusicPlayer mNetMusicPlayer; private final String mFilePath = "/sdcard/Music/"; private final String mFileUri = "http://172.18.67.240:8080/test_music.mp3"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_media_player); ButterKnife.bind(this); //本地音乐播放--start // mLocalMusicPlayer = new MusicPlayer(); // // mLocalMusicPlayer.setOnSeekListener(per_100 -> mProgressView.setProgress(per_100)); // mLocalMusicPlayer.setOnBufferListener(per_100 -> mProgressView.setProgress2(per_100)); // mProgressView.setOnDragListener(per_100 -> mLocalMusicPlayer.seekTo(per_100)); // // mIvCtrl.setOnClickListener(v -> { // if (mLocalMusicPlayer.isPlaying()) { // mLocalMusicPlayer.pause(); // mIvCtrl.setImageResource(R.drawable.icon_stop_2);//设置图标暂停 // } else { // mLocalMusicPlayer.start(mFilePath + "向天再借五百年 - 韩磊.mp3"); // mIvCtrl.setImageResource(R.drawable.icon_start_2);//设置图标播放 // } // }); // mTvMusicName.setText("向天再借五百年"); // mTvSignerName.setText("韩磊"); //end //网络音乐播放--start mNetMusicPlayer = new NetMusicPlayer(this); mNetMusicPlayer.setOnSeekListener(per_100 -> mProgressView.setProgress(per_100)); mNetMusicPlayer.setOnBufferListener(per_100 -> mProgressView.setProgress2(per_100)); mProgressView.setOnDragListener(per_100 -> mNetMusicPlayer.seekTo(per_100)); mIvCtrl.setOnClickListener(v -> { if (mNetMusicPlayer.isPlaying()) { mNetMusicPlayer.pause(); mIvCtrl.setImageResource(R.drawable.icon_stop_2);//设置 <SUF> } else { mNetMusicPlayer.start(mFileUri); mIvCtrl.setImageResource(R.drawable.icon_start_2);//设置图标播放 } }); mTvMusicName.setText("勇气"); mTvSignerName.setText("梁静茹"); } @Override protected void onDestroy() { super.onDestroy(); if (mLocalMusicPlayer != null) { mLocalMusicPlayer.onDestroy(); } if (mNetMusicPlayer != null) { mNetMusicPlayer.onDestroy(); } } }
0
798
4
991
6
994
4
991
6
1,171
11
false
false
false
false
false
true
39092_2
package com.le.net_thread; import com.le.utils.MLog; import com.le.utils.UtilString; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import static android.R.attr.name; /** * Created by sahara on 2016/4/27. */ public class UploadFile { // 定义数据分割线 private static String BOUNDARY = "------------------------7dc2fd5c0894"; // 定义最后数据分割线 private static byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); public void makeRequest(File file, final String url, MyCallBack callBack){ HttpURLConnection conn = null; String result = ""; try { URL url1 = new URL(url); MLog.e("当前上传图片接口:"+url); conn = (HttpURLConnection) url1.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // conn.setRequestProperty("Cookie", BaseConfig.COOKIE); BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream()); StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\""+name+"\";filename=\"" + file.getName() + "\"\r\n"); // 這裏不能漏掉,根據文件類型來來做處理,由於上傳的是圖片,所以這裏可以寫成image/pjpeg String type = ""; switch (UtilString.getLast(file.getName(), ".")+"") { case "png": type = "Content-Type: image/png\r\n\r\n"; break; case "jpg": type = "Content-Type: image/jpeg\r\n\r\n"; break; case "txt": type = "Content-Type: text/plain\r\n\r\n"; break; default: type = "Content-Type: application/octet-stream\r\n\r\n"; break; } sb.append(type);//text/plain //application/octet-stream //image/png //image/jpeg bos.write(sb.toString().getBytes()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); byte[] byteArray=new byte[1024]; int tmp=0; int current = 0; int total = bis.available(); while ((tmp = bis.read(byteArray))!=-1) { current = current+tmp; bos.write(byteArray, 0, tmp); callBack.inProgress(current,total,file.getName()); } // bos.write("\r\n".getBytes()); bos.write(end_data); bis.close(); bos.flush(); bos.close(); // conn.connect(); //上传完成后,开始读取返回内容 if (conn.getResponseCode()>=300){ InputStream errorStream = conn.getErrorStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(errorStream, "UTF8")); String errorStr = ""; while(true) { String line = rd.readLine(); if(line != null) { errorStr += line + "\n"; } else { callBack.error(new Exception(errorStr),file.getName()); break; } } return; } BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = br.readLine())!=null) { result = result+line+"\n"; } callBack.finish(result); } catch (Exception e) { callBack.error(e,file.getName()); } } }
Android-xiaole/LeeDemo
public_jar/src/main/java/com/le/net_thread/UploadFile.java
1,000
// 定义最后数据分割线
line_comment
zh-cn
package com.le.net_thread; import com.le.utils.MLog; import com.le.utils.UtilString; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import static android.R.attr.name; /** * Created by sahara on 2016/4/27. */ public class UploadFile { // 定义数据分割线 private static String BOUNDARY = "------------------------7dc2fd5c0894"; // 定义 <SUF> private static byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); public void makeRequest(File file, final String url, MyCallBack callBack){ HttpURLConnection conn = null; String result = ""; try { URL url1 = new URL(url); MLog.e("当前上传图片接口:"+url); conn = (HttpURLConnection) url1.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // conn.setRequestProperty("Cookie", BaseConfig.COOKIE); BufferedOutputStream bos = new BufferedOutputStream(conn.getOutputStream()); StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\""+name+"\";filename=\"" + file.getName() + "\"\r\n"); // 這裏不能漏掉,根據文件類型來來做處理,由於上傳的是圖片,所以這裏可以寫成image/pjpeg String type = ""; switch (UtilString.getLast(file.getName(), ".")+"") { case "png": type = "Content-Type: image/png\r\n\r\n"; break; case "jpg": type = "Content-Type: image/jpeg\r\n\r\n"; break; case "txt": type = "Content-Type: text/plain\r\n\r\n"; break; default: type = "Content-Type: application/octet-stream\r\n\r\n"; break; } sb.append(type);//text/plain //application/octet-stream //image/png //image/jpeg bos.write(sb.toString().getBytes()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); byte[] byteArray=new byte[1024]; int tmp=0; int current = 0; int total = bis.available(); while ((tmp = bis.read(byteArray))!=-1) { current = current+tmp; bos.write(byteArray, 0, tmp); callBack.inProgress(current,total,file.getName()); } // bos.write("\r\n".getBytes()); bos.write(end_data); bis.close(); bos.flush(); bos.close(); // conn.connect(); //上传完成后,开始读取返回内容 if (conn.getResponseCode()>=300){ InputStream errorStream = conn.getErrorStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(errorStream, "UTF8")); String errorStr = ""; while(true) { String line = rd.readLine(); if(line != null) { errorStr += line + "\n"; } else { callBack.error(new Exception(errorStr),file.getName()); break; } } return; } BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = br.readLine())!=null) { result = result+line+"\n"; } callBack.finish(result); } catch (Exception e) { callBack.error(e,file.getName()); } } }
0
816
8
1,000
8
1,038
6
1,000
8
1,196
13
false
false
false
false
false
true
54052_2
package com.songchao.mybilibili.model; import com.songchao.mybilibili.R; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Author: SongCHao * Date: 2017/9/30/10:35 * Email: 15704762346@163.com */ public class ImageCardUtil { /** * 获取具体图片类别 */ public static List<ImageCard> getImageCardList(){ List<ImageCard> dataList = new ArrayList<>(); //获得系统当前时间 Date mDate = new Date(); SimpleDateFormat mFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); String date = mFormat.format(mDate); final String MASHLADI = "玛莎拉蒂"; dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADI)); final String FANGHUA = "芳华电影"; dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua02,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua03,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua04,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua05,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua06,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua07,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua08,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua09,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua10,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua11,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua12,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua13,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUA)); final String MASHLADIDI = "贼帅的玛莎拉蒂"; dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDI)); final String FANGHUAHA = "芳华情怀"; dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua02,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua03,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua04,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua05,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua06,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua07,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua08,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua09,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua10,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua11,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua12,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua13,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUAHA)); final String MASHLADIDIDI = "我的玛莎拉蒂"; dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDIDI)); return dataList; } }
AndroidBoySC/Mybilibili
app/src/main/java/com/songchao/mybilibili/model/ImageCardUtil.java
2,194
//获得系统当前时间
line_comment
zh-cn
package com.songchao.mybilibili.model; import com.songchao.mybilibili.R; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Author: SongCHao * Date: 2017/9/30/10:35 * Email: 15704762346@163.com */ public class ImageCardUtil { /** * 获取具体图片类别 */ public static List<ImageCard> getImageCardList(){ List<ImageCard> dataList = new ArrayList<>(); //获得 <SUF> Date mDate = new Date(); SimpleDateFormat mFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); String date = mFormat.format(mDate); final String MASHLADI = "玛莎拉蒂"; dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADI)); final String FANGHUA = "芳华电影"; dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua02,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua03,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua04,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua05,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua06,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua07,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua08,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua09,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua10,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua11,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua12,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua13,date,R.mipmap.save,FANGHUA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUA)); final String MASHLADIDI = "贼帅的玛莎拉蒂"; dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDI)); final String FANGHUAHA = "芳华情怀"; dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua02,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua03,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua04,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua05,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua06,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua07,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua08,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua09,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua10,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua11,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua12,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua13,date,R.mipmap.save,FANGHUAHA)); dataList.add(new ImageCard("芳华",R.mipmap.fanghua01,date,R.mipmap.save,FANGHUAHA)); final String MASHLADIDIDI = "我的玛莎拉蒂"; dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche02,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche03,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche04,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche05,date,R.mipmap.save,MASHLADIDIDI)); dataList.add(new ImageCard("玛莎拉蒂", R.mipmap.mingche01,date,R.mipmap.save,MASHLADIDIDI)); return dataList; } }
0
1,517
5
2,194
5
1,962
5
2,194
5
2,506
9
false
false
false
false
false
true
48452_11
package com.xiaxl.demo; import android.os.Message; import android.util.Log; import com.xiaxl.demo.statemachine.State; import com.xiaxl.demo.statemachine.StateMachine; public class PersonStateMachine extends StateMachine { private static final String TAG = "MachineTest"; //设置状态改变标志常量 public static final int MSG_WAKEUP = 1; // 醒 public static final int MSG_TIRED = 2; // 困 public static final int MSG_HUNGRY = 3; // 饿 private static final int MSG_HALTING = 4; //停 //创建状态 private State mBoringState = new BoringState();// 默认状态 private State mWorkState = new WorkState(); // 工作 private State mEatState = new EatState(); // 吃 private State mSleepState = new SleepState(); // 睡 /** * 构造方法 * * @param name */ PersonStateMachine(String name) { super(name); Log.e(TAG, "PersonStateMachine"); //加入状态,初始化状态 addState(mBoringState, null); addState(mSleepState, mBoringState); addState(mWorkState, mBoringState); addState(mEatState, mBoringState); // sleep状态为初始状态 setInitialState(mSleepState); } /** * @return 创建启动person 状态机 */ public static PersonStateMachine makePerson() { Log.e(TAG, "PersonStateMachine makePerson"); PersonStateMachine person = new PersonStateMachine("Person"); person.start(); return person; } @Override protected void onHalting() { Log.e(TAG, "PersonStateMachine halting"); synchronized (this) { this.notifyAll(); } } /** * 定义状态:无聊 */ class BoringState extends State { @Override public void enter() { Log.e(TAG, "BoringState enter Boring"); } @Override public void exit() { Log.e(TAG, "BoringState exit Boring"); } @Override public boolean processMessage(Message msg) { Log.e(TAG, "BoringState processMessage....."); return true; } } /** * 定义状态:睡觉 */ class SleepState extends State { @Override public void enter() { Log.e(TAG, "SleepState enter Sleep"); } @Override public void exit() { Log.e(TAG, "SleepState exit Sleep"); } @Override public boolean processMessage(Message msg) { Log.e(TAG, "SleepState processMessage....."); switch (msg.what) { // 收到清醒信号 case MSG_WAKEUP: Log.e(TAG, "SleepState MSG_WAKEUP"); // 进入工作状态 deferMessage(msg); transitionTo(mWorkState); // //发送饿了信号... sendMessage(obtainMessage(MSG_HUNGRY)); break; case MSG_HALTING: Log.e(TAG, "SleepState MSG_HALTING"); // 停止 transitionToHaltingState(); break; default: return false; } return true; } } /** * 定义状态:工作 */ class WorkState extends State { @Override public void enter() { Log.e(TAG, "WorkState enter Work"); } @Override public void exit() { Log.e(TAG, "WorkState exit Work"); } @Override public boolean processMessage(Message msg) { Log.e(TAG, "WorkState processMessage....."); switch (msg.what) { // 收到 饿了 信号 case MSG_HUNGRY: Log.e(TAG, "WorkState MSG_HUNGRY"); // 吃饭状态 deferMessage(msg); transitionTo(mEatState); // 发送累了信号... sendMessage(obtainMessage(MSG_TIRED)); break; default: return false; } return true; } } /** * 定义状态:吃 */ class EatState extends State { @Override public void enter() { Log.e(TAG, "EatState enter Eat"); } @Override public void exit() { Log.e(TAG, "EatState exit Eat"); } @Override public boolean processMessage(Message msg) { Log.e(TAG, "EatState processMessage....."); switch (msg.what) { // 收到 困了 信号 case MSG_TIRED: Log.e(TAG, "EatState MSG_TIRED"); // 睡觉 deferMessage(msg); transitionTo(mSleepState); // 发出结束信号... sendMessage(obtainMessage(MSG_HALTING)); break; default: return false; } return true; } } }
AndroidHighQualityCodeStudy/Android_-StateMachine
app/src/main/java/com/xiaxl/demo/PersonStateMachine.java
1,192
//发送饿了信号...
line_comment
zh-cn
package com.xiaxl.demo; import android.os.Message; import android.util.Log; import com.xiaxl.demo.statemachine.State; import com.xiaxl.demo.statemachine.StateMachine; public class PersonStateMachine extends StateMachine { private static final String TAG = "MachineTest"; //设置状态改变标志常量 public static final int MSG_WAKEUP = 1; // 醒 public static final int MSG_TIRED = 2; // 困 public static final int MSG_HUNGRY = 3; // 饿 private static final int MSG_HALTING = 4; //停 //创建状态 private State mBoringState = new BoringState();// 默认状态 private State mWorkState = new WorkState(); // 工作 private State mEatState = new EatState(); // 吃 private State mSleepState = new SleepState(); // 睡 /** * 构造方法 * * @param name */ PersonStateMachine(String name) { super(name); Log.e(TAG, "PersonStateMachine"); //加入状态,初始化状态 addState(mBoringState, null); addState(mSleepState, mBoringState); addState(mWorkState, mBoringState); addState(mEatState, mBoringState); // sleep状态为初始状态 setInitialState(mSleepState); } /** * @return 创建启动person 状态机 */ public static PersonStateMachine makePerson() { Log.e(TAG, "PersonStateMachine makePerson"); PersonStateMachine person = new PersonStateMachine("Person"); person.start(); return person; } @Override protected void onHalting() { Log.e(TAG, "PersonStateMachine halting"); synchronized (this) { this.notifyAll(); } } /** * 定义状态:无聊 */ class BoringState extends State { @Override public void enter() { Log.e(TAG, "BoringState enter Boring"); } @Override public void exit() { Log.e(TAG, "BoringState exit Boring"); } @Override public boolean processMessage(Message msg) { Log.e(TAG, "BoringState processMessage....."); return true; } } /** * 定义状态:睡觉 */ class SleepState extends State { @Override public void enter() { Log.e(TAG, "SleepState enter Sleep"); } @Override public void exit() { Log.e(TAG, "SleepState exit Sleep"); } @Override public boolean processMessage(Message msg) { Log.e(TAG, "SleepState processMessage....."); switch (msg.what) { // 收到清醒信号 case MSG_WAKEUP: Log.e(TAG, "SleepState MSG_WAKEUP"); // 进入工作状态 deferMessage(msg); transitionTo(mWorkState); // //发送 <SUF> sendMessage(obtainMessage(MSG_HUNGRY)); break; case MSG_HALTING: Log.e(TAG, "SleepState MSG_HALTING"); // 停止 transitionToHaltingState(); break; default: return false; } return true; } } /** * 定义状态:工作 */ class WorkState extends State { @Override public void enter() { Log.e(TAG, "WorkState enter Work"); } @Override public void exit() { Log.e(TAG, "WorkState exit Work"); } @Override public boolean processMessage(Message msg) { Log.e(TAG, "WorkState processMessage....."); switch (msg.what) { // 收到 饿了 信号 case MSG_HUNGRY: Log.e(TAG, "WorkState MSG_HUNGRY"); // 吃饭状态 deferMessage(msg); transitionTo(mEatState); // 发送累了信号... sendMessage(obtainMessage(MSG_TIRED)); break; default: return false; } return true; } } /** * 定义状态:吃 */ class EatState extends State { @Override public void enter() { Log.e(TAG, "EatState enter Eat"); } @Override public void exit() { Log.e(TAG, "EatState exit Eat"); } @Override public boolean processMessage(Message msg) { Log.e(TAG, "EatState processMessage....."); switch (msg.what) { // 收到 困了 信号 case MSG_TIRED: Log.e(TAG, "EatState MSG_TIRED"); // 睡觉 deferMessage(msg); transitionTo(mSleepState); // 发出结束信号... sendMessage(obtainMessage(MSG_HALTING)); break; default: return false; } return true; } } }
0
1,115
6
1,192
7
1,283
6
1,192
7
1,560
10
false
false
false
false
false
true
66471_16
package io.github.celestialphineas.sanxing.UIStatistics; import android.os.Build; import android.os.Bundle; import android.support.transition.TransitionManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatTextView; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import butterknife.BindString; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.github.celestialphineas.sanxing.MyApplication; import io.github.celestialphineas.sanxing.R; import io.github.celestialphineas.sanxing.sxObjectManager.HabitManager; import io.github.celestialphineas.sanxing.sxObjectManager.TaskManager; import io.github.celestialphineas.sanxing.sxObjectManager.TimeLeftManager; //import com.konifar.fab_transformation.FabTransformation; public class StatisticsActivity extends AppCompatActivity { @BindView(R.id.statistics_toolbar) Toolbar toolbar; @BindView(R.id.statistics_root_linear_layout) ViewGroup rootLinearLayout; @BindView(R.id.statistics_total_relative_layout) ViewGroup totalRelativeLayout; @BindView(R.id.total_grid) ViewGroup totalGrid; @BindView(R.id.statistics_place_holder) ViewGroup placeHolder; @BindView(R.id.achievement_card) ViewGroup achievementCard; @BindView(R.id.total_description) AppCompatTextView totalDescriptionView; @BindView(R.id.task_count) AppCompatTextView taskCountView; @BindView(R.id.habit_count) AppCompatTextView habitCountView; @BindView(R.id.time_left_count) AppCompatTextView timeLeftCountView; @BindView(R.id.achievement_list) ListView achievementListView; @BindString(R.string.statistics_total_description) String currentTotalString; @BindString(R.string.statistics_finished_description) String finishedTotalString; int nTasks = 0, nHabits = 0, nTimeLefts = 0; int nFinishedTasks = 0, nFinishedHabits = 0, nFinishedTimeLefts = 0; boolean showCurrent = true; static final int TASK = 0, HABIT = 1, TIME_LEFT = 2; static final int BRONZE = 0, SILVER = 1, GOLD = 2; List<Achievement> achievements = new ArrayList<>(); // // Achievement class Achievement { int type, prize; String title, description; Achievement(int type, int prize, String title, String description) { this.type = type; this.prize = prize; this.title = title; this.description = description; } int getBandColor() { switch (type) { case TASK: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.colorTasks, null); } else return getBaseContext().getResources().getColor(R.color.colorTasks); case HABIT: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.colorHabits, null); } else return getBaseContext().getResources().getColor(R.color.colorHabits); case TIME_LEFT: default: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.colorTimeLeft, null); } else return getBaseContext().getResources().getColor(R.color.colorTimeLeft); } } int getMedalBrightColor() { switch (prize) { case BRONZE: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.bronze_bright, null); } else return getBaseContext().getResources().getColor(R.color.bronze_bright); case SILVER: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.silver_bright, null); } else return getBaseContext().getResources().getColor(R.color.silver_bright); case GOLD: default: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.gold_bright, null); } else return getBaseContext().getResources().getColor(R.color.gold_bright); } } int getMedalDarkColor() { switch (prize) { case BRONZE: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.bronze_dark, null); } else return getBaseContext().getResources().getColor(R.color.bronze_dark); case SILVER: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.silver_dark, null); } else return getBaseContext().getResources().getColor(R.color.silver_dark); case GOLD: default: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.gold_dark, null); } else return getBaseContext().getResources().getColor(R.color.gold_dark); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_statistics); ButterKnife.bind(this); //backend MyApplication myApplication = (MyApplication) getApplication(); TaskManager taskManager = myApplication.get_task_manager(); HabitManager habitManager = myApplication.get_habit_manager(); TimeLeftManager timeLeftManager = myApplication.get_time_left_manager(); //////// Toolbar //////// // Set the toolbar as the default action bar of the window setSupportActionBar(toolbar); setTitle(getString(R.string.statistics_and_achievements)); // Enable the back button getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); // Set the number of items //end numbers taskManager.resetNumbers(); habitManager.resetNumbers(); timeLeftManager.resetNumbers(); nTasks = taskManager.getNumberOfTasks(); nHabits = habitManager.getNumberOfHabits(); nTimeLefts = timeLeftManager.getNumberOfTimeLefts(); nFinishedTasks = taskManager.getNumberOfFinishedTasks(); nFinishedHabits = habitManager.getNumberOfFinishedHabits(); nFinishedTimeLefts = timeLeftManager.getNumberOfFinishedTimeLefts(); // Set up achievements // nFinishedTimeLefts=101; // nFinishedHabits=101; // nFinishedTasks=101; if (nFinishedTasks >= 100) achievements.add(new Achievement(TASK, GOLD, "打败deadline", "完成任务数 >= 100")); if (nFinishedHabits >= 30) achievements.add(new Achievement(HABIT, GOLD, "坚持造就伟大", "完成习惯数 >= 30")); if (nFinishedTimeLefts >= 30) achievements.add(new Achievement(TIME_LEFT, GOLD, "惟愿时光清浅,将你温柔以待", "完成倒计时数 >= 30")); if (nFinishedTasks >= 10) achievements.add(new Achievement(TASK, SILVER, "任务达人", "完成任务数 >= 10")); if (nFinishedHabits >= 10) achievements.add(new Achievement(HABIT, SILVER, "自律者", "完成习惯数 >= 10")); if (nFinishedTimeLefts >= 10) achievements.add(new Achievement(TIME_LEFT, SILVER, "守望时光", "完成倒计时数 >= 10")); if (nFinishedTasks >= 1 && nFinishedHabits == 0) { achievements.add(new Achievement(TASK, BRONZE, "第一次", "完成了一个任务或习惯")); } else if (nFinishedTasks == 0 && nFinishedHabits >= 1) { achievements.add(new Achievement(HABIT, BRONZE, "第一次", "完成了一个任务或习惯")); } else if (nFinishedTasks >= 1 && nFinishedHabits >= 1) { achievements.add(new Achievement(TASK, SILVER, "第一次", "完成了一个任务和一个习惯")); } if (nFinishedTimeLefts >= 1) { achievements.add(new Achievement(TIME_LEFT, SILVER, "倒计时,你怕了吗", "完成了一个倒计时")); } // achievements.add(new Achievement(HABIT, GOLD, "Hello", "world, blablabla")); // achievements.add(new Achievement(TASK, BRONZE, "Task bla", "You've won a lot")); // achievements.add(new Achievement(TIME_LEFT, SILVER, "What?", "What the heck!!!")); // //////// ListAdapter //////// if (achievements == null || achievements.isEmpty()) { placeHolder.setVisibility(View.VISIBLE); achievementCard.setVisibility(View.GONE); } else { achievementListView.setAdapter(new AchievementsAdapter(this, achievements)); } showCurrentNumbers(); } @OnClick(R.id.toggle_summary_button) //切换按钮 void toggleSummaryButtonOnClickBehavior() { TransitionManager.beginDelayedTransition(rootLinearLayout); TransitionManager.beginDelayedTransition(totalRelativeLayout); TransitionManager.beginDelayedTransition(totalGrid); if (!showCurrent) { showCurrentNumbers(); showCurrent = true; } else { showFinishedNumbers(); showCurrent = false; } } private void showCurrentNumbers() { totalDescriptionView.setText(currentTotalString); taskCountView.setText(Integer.toString(nTasks)); habitCountView.setText(Integer.toString(nHabits)); timeLeftCountView.setText(Integer.toString(nTimeLefts)); } private void showFinishedNumbers() { totalDescriptionView.setText(finishedTotalString); taskCountView.setText(Integer.toString(nFinishedTasks)); habitCountView.setText(Integer.toString(nFinishedHabits)); timeLeftCountView.setText(Integer.toString(nFinishedTimeLefts)); } }
AndroidNewbies/Sanxing
app/src/main/java/io/github/celestialphineas/sanxing/UIStatistics/StatisticsActivity.java
2,697
//切换按钮
line_comment
zh-cn
package io.github.celestialphineas.sanxing.UIStatistics; import android.os.Build; import android.os.Bundle; import android.support.transition.TransitionManager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatTextView; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import butterknife.BindString; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.github.celestialphineas.sanxing.MyApplication; import io.github.celestialphineas.sanxing.R; import io.github.celestialphineas.sanxing.sxObjectManager.HabitManager; import io.github.celestialphineas.sanxing.sxObjectManager.TaskManager; import io.github.celestialphineas.sanxing.sxObjectManager.TimeLeftManager; //import com.konifar.fab_transformation.FabTransformation; public class StatisticsActivity extends AppCompatActivity { @BindView(R.id.statistics_toolbar) Toolbar toolbar; @BindView(R.id.statistics_root_linear_layout) ViewGroup rootLinearLayout; @BindView(R.id.statistics_total_relative_layout) ViewGroup totalRelativeLayout; @BindView(R.id.total_grid) ViewGroup totalGrid; @BindView(R.id.statistics_place_holder) ViewGroup placeHolder; @BindView(R.id.achievement_card) ViewGroup achievementCard; @BindView(R.id.total_description) AppCompatTextView totalDescriptionView; @BindView(R.id.task_count) AppCompatTextView taskCountView; @BindView(R.id.habit_count) AppCompatTextView habitCountView; @BindView(R.id.time_left_count) AppCompatTextView timeLeftCountView; @BindView(R.id.achievement_list) ListView achievementListView; @BindString(R.string.statistics_total_description) String currentTotalString; @BindString(R.string.statistics_finished_description) String finishedTotalString; int nTasks = 0, nHabits = 0, nTimeLefts = 0; int nFinishedTasks = 0, nFinishedHabits = 0, nFinishedTimeLefts = 0; boolean showCurrent = true; static final int TASK = 0, HABIT = 1, TIME_LEFT = 2; static final int BRONZE = 0, SILVER = 1, GOLD = 2; List<Achievement> achievements = new ArrayList<>(); // // Achievement class Achievement { int type, prize; String title, description; Achievement(int type, int prize, String title, String description) { this.type = type; this.prize = prize; this.title = title; this.description = description; } int getBandColor() { switch (type) { case TASK: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.colorTasks, null); } else return getBaseContext().getResources().getColor(R.color.colorTasks); case HABIT: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.colorHabits, null); } else return getBaseContext().getResources().getColor(R.color.colorHabits); case TIME_LEFT: default: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.colorTimeLeft, null); } else return getBaseContext().getResources().getColor(R.color.colorTimeLeft); } } int getMedalBrightColor() { switch (prize) { case BRONZE: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.bronze_bright, null); } else return getBaseContext().getResources().getColor(R.color.bronze_bright); case SILVER: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.silver_bright, null); } else return getBaseContext().getResources().getColor(R.color.silver_bright); case GOLD: default: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.gold_bright, null); } else return getBaseContext().getResources().getColor(R.color.gold_bright); } } int getMedalDarkColor() { switch (prize) { case BRONZE: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.bronze_dark, null); } else return getBaseContext().getResources().getColor(R.color.bronze_dark); case SILVER: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.silver_dark, null); } else return getBaseContext().getResources().getColor(R.color.silver_dark); case GOLD: default: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return getBaseContext().getResources().getColor(R.color.gold_dark, null); } else return getBaseContext().getResources().getColor(R.color.gold_dark); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_statistics); ButterKnife.bind(this); //backend MyApplication myApplication = (MyApplication) getApplication(); TaskManager taskManager = myApplication.get_task_manager(); HabitManager habitManager = myApplication.get_habit_manager(); TimeLeftManager timeLeftManager = myApplication.get_time_left_manager(); //////// Toolbar //////// // Set the toolbar as the default action bar of the window setSupportActionBar(toolbar); setTitle(getString(R.string.statistics_and_achievements)); // Enable the back button getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); // Set the number of items //end numbers taskManager.resetNumbers(); habitManager.resetNumbers(); timeLeftManager.resetNumbers(); nTasks = taskManager.getNumberOfTasks(); nHabits = habitManager.getNumberOfHabits(); nTimeLefts = timeLeftManager.getNumberOfTimeLefts(); nFinishedTasks = taskManager.getNumberOfFinishedTasks(); nFinishedHabits = habitManager.getNumberOfFinishedHabits(); nFinishedTimeLefts = timeLeftManager.getNumberOfFinishedTimeLefts(); // Set up achievements // nFinishedTimeLefts=101; // nFinishedHabits=101; // nFinishedTasks=101; if (nFinishedTasks >= 100) achievements.add(new Achievement(TASK, GOLD, "打败deadline", "完成任务数 >= 100")); if (nFinishedHabits >= 30) achievements.add(new Achievement(HABIT, GOLD, "坚持造就伟大", "完成习惯数 >= 30")); if (nFinishedTimeLefts >= 30) achievements.add(new Achievement(TIME_LEFT, GOLD, "惟愿时光清浅,将你温柔以待", "完成倒计时数 >= 30")); if (nFinishedTasks >= 10) achievements.add(new Achievement(TASK, SILVER, "任务达人", "完成任务数 >= 10")); if (nFinishedHabits >= 10) achievements.add(new Achievement(HABIT, SILVER, "自律者", "完成习惯数 >= 10")); if (nFinishedTimeLefts >= 10) achievements.add(new Achievement(TIME_LEFT, SILVER, "守望时光", "完成倒计时数 >= 10")); if (nFinishedTasks >= 1 && nFinishedHabits == 0) { achievements.add(new Achievement(TASK, BRONZE, "第一次", "完成了一个任务或习惯")); } else if (nFinishedTasks == 0 && nFinishedHabits >= 1) { achievements.add(new Achievement(HABIT, BRONZE, "第一次", "完成了一个任务或习惯")); } else if (nFinishedTasks >= 1 && nFinishedHabits >= 1) { achievements.add(new Achievement(TASK, SILVER, "第一次", "完成了一个任务和一个习惯")); } if (nFinishedTimeLefts >= 1) { achievements.add(new Achievement(TIME_LEFT, SILVER, "倒计时,你怕了吗", "完成了一个倒计时")); } // achievements.add(new Achievement(HABIT, GOLD, "Hello", "world, blablabla")); // achievements.add(new Achievement(TASK, BRONZE, "Task bla", "You've won a lot")); // achievements.add(new Achievement(TIME_LEFT, SILVER, "What?", "What the heck!!!")); // //////// ListAdapter //////// if (achievements == null || achievements.isEmpty()) { placeHolder.setVisibility(View.VISIBLE); achievementCard.setVisibility(View.GONE); } else { achievementListView.setAdapter(new AchievementsAdapter(this, achievements)); } showCurrentNumbers(); } @OnClick(R.id.toggle_summary_button) //切换 <SUF> void toggleSummaryButtonOnClickBehavior() { TransitionManager.beginDelayedTransition(rootLinearLayout); TransitionManager.beginDelayedTransition(totalRelativeLayout); TransitionManager.beginDelayedTransition(totalGrid); if (!showCurrent) { showCurrentNumbers(); showCurrent = true; } else { showFinishedNumbers(); showCurrent = false; } } private void showCurrentNumbers() { totalDescriptionView.setText(currentTotalString); taskCountView.setText(Integer.toString(nTasks)); habitCountView.setText(Integer.toString(nHabits)); timeLeftCountView.setText(Integer.toString(nTimeLefts)); } private void showFinishedNumbers() { totalDescriptionView.setText(finishedTotalString); taskCountView.setText(Integer.toString(nFinishedTasks)); habitCountView.setText(Integer.toString(nFinishedHabits)); timeLeftCountView.setText(Integer.toString(nFinishedTimeLefts)); } }
0
2,205
3
2,697
3
2,678
3
2,697
3
3,226
7
false
false
false
false
false
true
32715_6
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package translation; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * @author yoUng @description 发送http请求 @filename HttpUtil.java @time 2011-6-15 * 下午05:26:36 * @version 1.0 */ public class Post { public static String http(String url, Map<String, String> params) { URL u = null; HttpURLConnection con = null; StringBuffer buffer = new StringBuffer(); //构建请求参数 StringBuffer sb = new StringBuffer(); if (params != null) { for (Entry<String, String> e : params.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); //sb.append("&");//多个参数时需要加上 } sb.substring(0, sb.length() - 1); } // System.out.println("send_url:" + url); // System.out.println("send_data:" + sb.toString()); //尝试发送请求 try { u = new URL(url); con = (HttpURLConnection) u.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setReadTimeout(3000); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); osw.write(sb.toString()); osw.flush(); osw.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.disconnect(); } } //读取返回内容 try { if (con.getResponseCode() == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String temp; while ((temp = br.readLine()) != null) { buffer.append(temp); buffer.append("\n"); } } else { buffer.append(con.getResponseCode()); } //System.out.println(con.getResponseCode() + ""); } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); } /** * 获取翻译结果 * * @param tvalue 需要翻译的中文字符串 * @return */ public static String tg(String translate_site, String tvalue) { Map<String, String> map = new HashMap<String, String>();; map.put("origin", tvalue); return http(translate_site, map).trim(); } /** * 获取翻译结果(比用JSON速度更快) * * @param tvalue 需要翻译的中文字符串 * @return */ public String tg1(String translate_site, String tvalue) { Map<String, String> map = new HashMap<String, String>(); map.put("origin", tvalue); String tempt = WordsTransfer.unicodeToUtf8(http(translate_site, map).trim()); tempt = tempt.substring(tempt.lastIndexOf(":") + 1, tempt.length() - 3).replaceAll("\"", ""); return tempt; } // public static void main(String[] args) { // Map<String, String> map = new HashMap<String, String>();; // map.put("q", "中国"); // System.out.println(http("http://zhangwei911.duapp.com/TranslateGet.jsp", map).trim()); // } }
AndroidStudioTranslate/Android-Studio-Translate-Tool
src/translation/Post.java
949
//尝试发送请求
line_comment
zh-cn
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package translation; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * @author yoUng @description 发送http请求 @filename HttpUtil.java @time 2011-6-15 * 下午05:26:36 * @version 1.0 */ public class Post { public static String http(String url, Map<String, String> params) { URL u = null; HttpURLConnection con = null; StringBuffer buffer = new StringBuffer(); //构建请求参数 StringBuffer sb = new StringBuffer(); if (params != null) { for (Entry<String, String> e : params.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); //sb.append("&");//多个参数时需要加上 } sb.substring(0, sb.length() - 1); } // System.out.println("send_url:" + url); // System.out.println("send_data:" + sb.toString()); //尝试 <SUF> try { u = new URL(url); con = (HttpURLConnection) u.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setReadTimeout(3000); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); osw.write(sb.toString()); osw.flush(); osw.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.disconnect(); } } //读取返回内容 try { if (con.getResponseCode() == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String temp; while ((temp = br.readLine()) != null) { buffer.append(temp); buffer.append("\n"); } } else { buffer.append(con.getResponseCode()); } //System.out.println(con.getResponseCode() + ""); } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); } /** * 获取翻译结果 * * @param tvalue 需要翻译的中文字符串 * @return */ public static String tg(String translate_site, String tvalue) { Map<String, String> map = new HashMap<String, String>();; map.put("origin", tvalue); return http(translate_site, map).trim(); } /** * 获取翻译结果(比用JSON速度更快) * * @param tvalue 需要翻译的中文字符串 * @return */ public String tg1(String translate_site, String tvalue) { Map<String, String> map = new HashMap<String, String>(); map.put("origin", tvalue); String tempt = WordsTransfer.unicodeToUtf8(http(translate_site, map).trim()); tempt = tempt.substring(tempt.lastIndexOf(":") + 1, tempt.length() - 3).replaceAll("\"", ""); return tempt; } // public static void main(String[] args) { // Map<String, String> map = new HashMap<String, String>();; // map.put("q", "中国"); // System.out.println(http("http://zhangwei911.duapp.com/TranslateGet.jsp", map).trim()); // } }
0
815
4
949
4
1,010
4
949
4
1,133
9
false
false
false
false
false
true
61225_1
package com.pslib.jtool.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import cn.hutool.json.JSONArray; /** * @author ****** * * * 功能说明:请补充 */ public class MathUtil { // 取随机数 /* * 生成 min-max之间的数字, 包括min,max * */ public static int getRand(int min, int max) { return (int) (min + Math.random() * (max - min + 1)); } // 生成随机数的数组, public static int[] getUniqueRandArray(int num, int min, int max) { if(max - min + 1 < num) { return null; } List<Integer> arr = new ArrayList<Integer>(); int n; int[] r = new int[num]; for (int i = 0; i < num; i++) { do { n = MathUtil.getRand(min, max); }while(arr.contains(n)); arr.add(n); r[i] = n; } arr.clear(); return r; } // 生成随机数的数组,并排序 public static int[] getUniqueRandArray(int num, int min, int max, String sort) { int[] sel = getUniqueRandArray(num, min, max); if (sort.equals("ASC")) { Arrays.sort(sel); int[] sel2 = new int[sel.length]; for (int i = sel.length; i > 0; i--) { sel2[sel.length - i] = sel[i - 1]; } return sel; } else { Arrays.sort(sel); return sel; } } // 生成随机数字符串的数组, public static String[] getUniqueStringRandArray(int num, int len, int min, int max) { int[] sel = getUniqueRandArray(num, min, max); String[] result = new String[sel.length]; for (int i = 0; i < sel.length; i++) { result[i] = StringUtil.strPad(Integer.toString(sel[i]), len, "0"); } return result; } // 生成随机数字符串的数组,并排序 public static String[] getUniqueStringRandArray(int num, int len, int min, int max, String sort) { int[] sel = getUniqueRandArray(num, min, max, sort); String[] result = new String[sel.length]; for (int i = 0; i < sel.length; i++) { result[i] = StringUtil.strPad(Integer.toString(sel[i]), len, "0"); } return result; } /** * 排列组合 (java多个一维数组进行组合排序 笛卡尔 http://blog.csdn.net/wuyongde_0922/article/details/56511362) * * @param source * "a,b,c|2,3|A,B,C" * @return */ public static JSONArray getCombJSONArray(String source) { String[] list = source.split("\\|"); JSONArray strs = new JSONArray(); for (int i = 0; i < list.length; i++) { strs.add(Arrays.asList(list[i].split(","))); } return getCombJSONArray(strs); } /** * 排列组合 * * @param strs * [["a","b","c"],["2","3"]] * @return */ public static JSONArray getCombJSONArray(JSONArray strs) { int total = 1; for (int i = 0; i < strs.size(); i++) { total *= strs.getJSONArray(i).size(); } JSONArray mysesult = new JSONArray(); for (int i = 0; i < total; i++) { mysesult.add(new JSONArray()); } int now = 1; // 每个元素每次循环打印个数 int itemLoopNum = 1; // 每个元素循环的总次数 int loopPerItem = 1; for (int i = 0; i < strs.size(); i++) { JSONArray temp = strs.getJSONArray(i); now = now * temp.size(); // 目标数组的索引值 int index = 0; int currentSize = temp.size(); itemLoopNum = total / now; loopPerItem = total / (itemLoopNum * currentSize); int myindex = 0; for (int j = 0; j < temp.size(); j++) { // 每个元素循环的总次数 for (int k = 0; k < loopPerItem; k++) { if (myindex == temp.size()) myindex = 0; // 每个元素每次循环打印个数 for (int m = 0; m < itemLoopNum; m++) { JSONArray rows = mysesult.getJSONArray(index); rows.add(temp.get(myindex)); mysesult.set(index, rows); index++; } myindex++; } } } return mysesult; } /** * 排列组合 * * @param source * "a,b,c|2,3|A,B,C" * @return */ public static List<List<String>> getCombList(String source) { String[] list = source.split("\\|"); List<List<String>> strs = new ArrayList<List<String>>(); for (int i = 0; i < list.length; i++) { strs.add(Arrays.asList(list[i].split(","))); } return getCombList(strs); } /** * 排列组合 * * @param strs * [["a","b","c"],["2","3"]] * @return */ public static List<List<String>> getCombList(List<List<String>> strs) { int total = 1; for (int i = 0; i < strs.size(); i++) { total *= strs.get(i).size(); } List<List<String>> mysesult = new ArrayList<List<String>>(); for (int i = 0; i < total; i++) { mysesult.add(new ArrayList<String>()); } int now = 1; // 每个元素每次循环打印个数 int itemLoopNum = 1; // 每个元素循环的总次数 int loopPerItem = 1; for (int i = 0; i < strs.size(); i++) { List<String> temp = strs.get(i); now = now * temp.size(); // 目标数组的索引值 int index = 0; int currentSize = temp.size(); itemLoopNum = total / now; loopPerItem = total / (itemLoopNum * currentSize); int myindex = 0; for (int j = 0; j < temp.size(); j++) { // 每个元素循环的总次数 for (int k = 0; k < loopPerItem; k++) { if (myindex == temp.size()) myindex = 0; // 每个元素每次循环打印个数 for (int m = 0; m < itemLoopNum; m++) { List<String> rows = mysesult.get(index); rows.add(temp.get(myindex)); mysesult.set(index, rows); index++; } myindex++; } } } return mysesult; } public static void main(String[] args) { System.out.println(getRand(3, 999)); System.out.println(getUniqueRandArray(3, 0, 3)); } }
Andyfoo/pslib-jtool
pslib-jtool-core/src/main/java/com/pslib/jtool/util/MathUtil.java
2,029
// 取随机数
line_comment
zh-cn
package com.pslib.jtool.util; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import cn.hutool.json.JSONArray; /** * @author ****** * * * 功能说明:请补充 */ public class MathUtil { // 取随 <SUF> /* * 生成 min-max之间的数字, 包括min,max * */ public static int getRand(int min, int max) { return (int) (min + Math.random() * (max - min + 1)); } // 生成随机数的数组, public static int[] getUniqueRandArray(int num, int min, int max) { if(max - min + 1 < num) { return null; } List<Integer> arr = new ArrayList<Integer>(); int n; int[] r = new int[num]; for (int i = 0; i < num; i++) { do { n = MathUtil.getRand(min, max); }while(arr.contains(n)); arr.add(n); r[i] = n; } arr.clear(); return r; } // 生成随机数的数组,并排序 public static int[] getUniqueRandArray(int num, int min, int max, String sort) { int[] sel = getUniqueRandArray(num, min, max); if (sort.equals("ASC")) { Arrays.sort(sel); int[] sel2 = new int[sel.length]; for (int i = sel.length; i > 0; i--) { sel2[sel.length - i] = sel[i - 1]; } return sel; } else { Arrays.sort(sel); return sel; } } // 生成随机数字符串的数组, public static String[] getUniqueStringRandArray(int num, int len, int min, int max) { int[] sel = getUniqueRandArray(num, min, max); String[] result = new String[sel.length]; for (int i = 0; i < sel.length; i++) { result[i] = StringUtil.strPad(Integer.toString(sel[i]), len, "0"); } return result; } // 生成随机数字符串的数组,并排序 public static String[] getUniqueStringRandArray(int num, int len, int min, int max, String sort) { int[] sel = getUniqueRandArray(num, min, max, sort); String[] result = new String[sel.length]; for (int i = 0; i < sel.length; i++) { result[i] = StringUtil.strPad(Integer.toString(sel[i]), len, "0"); } return result; } /** * 排列组合 (java多个一维数组进行组合排序 笛卡尔 http://blog.csdn.net/wuyongde_0922/article/details/56511362) * * @param source * "a,b,c|2,3|A,B,C" * @return */ public static JSONArray getCombJSONArray(String source) { String[] list = source.split("\\|"); JSONArray strs = new JSONArray(); for (int i = 0; i < list.length; i++) { strs.add(Arrays.asList(list[i].split(","))); } return getCombJSONArray(strs); } /** * 排列组合 * * @param strs * [["a","b","c"],["2","3"]] * @return */ public static JSONArray getCombJSONArray(JSONArray strs) { int total = 1; for (int i = 0; i < strs.size(); i++) { total *= strs.getJSONArray(i).size(); } JSONArray mysesult = new JSONArray(); for (int i = 0; i < total; i++) { mysesult.add(new JSONArray()); } int now = 1; // 每个元素每次循环打印个数 int itemLoopNum = 1; // 每个元素循环的总次数 int loopPerItem = 1; for (int i = 0; i < strs.size(); i++) { JSONArray temp = strs.getJSONArray(i); now = now * temp.size(); // 目标数组的索引值 int index = 0; int currentSize = temp.size(); itemLoopNum = total / now; loopPerItem = total / (itemLoopNum * currentSize); int myindex = 0; for (int j = 0; j < temp.size(); j++) { // 每个元素循环的总次数 for (int k = 0; k < loopPerItem; k++) { if (myindex == temp.size()) myindex = 0; // 每个元素每次循环打印个数 for (int m = 0; m < itemLoopNum; m++) { JSONArray rows = mysesult.getJSONArray(index); rows.add(temp.get(myindex)); mysesult.set(index, rows); index++; } myindex++; } } } return mysesult; } /** * 排列组合 * * @param source * "a,b,c|2,3|A,B,C" * @return */ public static List<List<String>> getCombList(String source) { String[] list = source.split("\\|"); List<List<String>> strs = new ArrayList<List<String>>(); for (int i = 0; i < list.length; i++) { strs.add(Arrays.asList(list[i].split(","))); } return getCombList(strs); } /** * 排列组合 * * @param strs * [["a","b","c"],["2","3"]] * @return */ public static List<List<String>> getCombList(List<List<String>> strs) { int total = 1; for (int i = 0; i < strs.size(); i++) { total *= strs.get(i).size(); } List<List<String>> mysesult = new ArrayList<List<String>>(); for (int i = 0; i < total; i++) { mysesult.add(new ArrayList<String>()); } int now = 1; // 每个元素每次循环打印个数 int itemLoopNum = 1; // 每个元素循环的总次数 int loopPerItem = 1; for (int i = 0; i < strs.size(); i++) { List<String> temp = strs.get(i); now = now * temp.size(); // 目标数组的索引值 int index = 0; int currentSize = temp.size(); itemLoopNum = total / now; loopPerItem = total / (itemLoopNum * currentSize); int myindex = 0; for (int j = 0; j < temp.size(); j++) { // 每个元素循环的总次数 for (int k = 0; k < loopPerItem; k++) { if (myindex == temp.size()) myindex = 0; // 每个元素每次循环打印个数 for (int m = 0; m < itemLoopNum; m++) { List<String> rows = mysesult.get(index); rows.add(temp.get(myindex)); mysesult.set(index, rows); index++; } myindex++; } } } return mysesult; } public static void main(String[] args) { System.out.println(getRand(3, 999)); System.out.println(getUniqueRandArray(3, 0, 3)); } }
0
1,757
5
2,029
5
2,028
4
2,029
5
2,573
8
false
false
false
false
false
true
24111_2
package javaleetcode.sort; /** * @authorAdministrator * @date2024/1/8 0008 10:51 * @description */ /** * 时间复杂度为O(n^2)的排序算法 * TODO * */ public class Onlogn { public static void shellSort(int[] arr) { // 间隔序列,在希尔排序中我们称之为增量序列 for (int gap = arr.length / 2; gap > 0; gap /= 2) { // 分组 for (int groupStartIndex = 0; groupStartIndex < gap; groupStartIndex++) { // 插入排序 for (int currentIndex = groupStartIndex + gap; currentIndex < arr.length; currentIndex += gap) { // currentNumber 站起来,开始找位置 int currentNumber = arr[currentIndex]; int preIndex = currentIndex - gap; while (preIndex >= groupStartIndex && currentNumber < arr[preIndex]) { // 向后挪位置 arr[preIndex + gap] = arr[preIndex]; preIndex -= gap; } // currentNumber 找到了自己的位置,坐下 arr[preIndex + gap] = currentNumber; } } } } }
AngryXZC/LeetCode-
JavaLeetCode/app/src/main/java/javaleetcode/sort/Onlogn.java
293
// 间隔序列,在希尔排序中我们称之为增量序列
line_comment
zh-cn
package javaleetcode.sort; /** * @authorAdministrator * @date2024/1/8 0008 10:51 * @description */ /** * 时间复杂度为O(n^2)的排序算法 * TODO * */ public class Onlogn { public static void shellSort(int[] arr) { // 间隔 <SUF> for (int gap = arr.length / 2; gap > 0; gap /= 2) { // 分组 for (int groupStartIndex = 0; groupStartIndex < gap; groupStartIndex++) { // 插入排序 for (int currentIndex = groupStartIndex + gap; currentIndex < arr.length; currentIndex += gap) { // currentNumber 站起来,开始找位置 int currentNumber = arr[currentIndex]; int preIndex = currentIndex - gap; while (preIndex >= groupStartIndex && currentNumber < arr[preIndex]) { // 向后挪位置 arr[preIndex + gap] = arr[preIndex]; preIndex -= gap; } // currentNumber 找到了自己的位置,坐下 arr[preIndex + gap] = currentNumber; } } } } }
0
283
12
293
18
303
16
293
18
381
28
false
false
false
false
false
true
17961_6
/** * BCPlan.java * 订阅计划 * Created by xuanzhui on 2016/7/28. * Copyright (c) 2016 BeeCloud. All rights reserved. */ package cn.beecloud.entity; import java.util.Map; public class BCPlan { /** * 订阅计划的唯一标识 */ private String id; /** * 扣款单价 */ private Integer fee; /** * 扣款周期,只可以是:day, week, month or year */ private String interval; /** * 计划名 */ private String name; /** * ISO货币名,如'CNY'代表人民币 */ private String currency; /** * 扣款周期间隔数,例如interval为month,这边设置为3, * 那么每3个月扣款,订阅系统默认1 */ private Integer interval_count; /** * 试用天数 */ private Integer trial_days; /** * map类型附加信息 */ private Map<String, Object> optional; /** * 计划是否生效 */ private Boolean valid; /** * @return 订阅计划的唯一标识 */ public String getId() { return id; } /** * @return 扣款单价,分为单位 */ public Integer getFee() { return fee; } /** * @param fee 扣款单价,分为单位 */ public void setFee(Integer fee) { this.fee = fee; } /** * @return 扣款周期:day, week, month or year. */ public String getInterval() { return interval; } /** * @param interval 扣款周期: 只可以是字符串 day, week, month or year. */ public void setInterval(String interval) { this.interval = interval; } /** * @return 计划名 */ public String getName() { return name; } /** * @param name 计划名 */ public void setName(String name) { this.name = name; } /** * @return ISO货币名,如'CNY' */ public String getCurrency() { return currency; } /** * @param currency ISO货币名,如'CNY' */ public void setCurrency(String currency) { this.currency = currency; } /** * @return 扣款周期间隔数 */ public Integer getIntervalCount() { return interval_count; } /** * @param intervalCount 扣款周期间隔数,例如interval为month,这边设置为3, * 那么每3个月扣款,订阅系统默认1 */ public void setIntervalCount(Integer intervalCount) { this.interval_count = intervalCount; } /** * @return 试用天数 */ public Integer getTrialDays() { return trial_days; } /** * @param trialDays 试用天数 */ public void setTrialDays(Integer trialDays) { this.trial_days = trialDays; } /** * @return map类型附加信息 */ public Map<String, Object> getOptional() { return optional; } /** * @param optional map类型附加信息 */ public void setOptional(Map<String, Object> optional) { this.optional = optional; } /** * @return 计划是否生效 */ public boolean isValid() { return valid != null && valid; } }
Anjiefan/flutter_campus_social_app
android/sdk/src/main/java/cn/beecloud/entity/BCPlan.java
856
/** * 扣款周期间隔数,例如interval为month,这边设置为3, * 那么每3个月扣款,订阅系统默认1 */
block_comment
zh-cn
/** * BCPlan.java * 订阅计划 * Created by xuanzhui on 2016/7/28. * Copyright (c) 2016 BeeCloud. All rights reserved. */ package cn.beecloud.entity; import java.util.Map; public class BCPlan { /** * 订阅计划的唯一标识 */ private String id; /** * 扣款单价 */ private Integer fee; /** * 扣款周期,只可以是:day, week, month or year */ private String interval; /** * 计划名 */ private String name; /** * ISO货币名,如'CNY'代表人民币 */ private String currency; /** * 扣款周 <SUF>*/ private Integer interval_count; /** * 试用天数 */ private Integer trial_days; /** * map类型附加信息 */ private Map<String, Object> optional; /** * 计划是否生效 */ private Boolean valid; /** * @return 订阅计划的唯一标识 */ public String getId() { return id; } /** * @return 扣款单价,分为单位 */ public Integer getFee() { return fee; } /** * @param fee 扣款单价,分为单位 */ public void setFee(Integer fee) { this.fee = fee; } /** * @return 扣款周期:day, week, month or year. */ public String getInterval() { return interval; } /** * @param interval 扣款周期: 只可以是字符串 day, week, month or year. */ public void setInterval(String interval) { this.interval = interval; } /** * @return 计划名 */ public String getName() { return name; } /** * @param name 计划名 */ public void setName(String name) { this.name = name; } /** * @return ISO货币名,如'CNY' */ public String getCurrency() { return currency; } /** * @param currency ISO货币名,如'CNY' */ public void setCurrency(String currency) { this.currency = currency; } /** * @return 扣款周期间隔数 */ public Integer getIntervalCount() { return interval_count; } /** * @param intervalCount 扣款周期间隔数,例如interval为month,这边设置为3, * 那么每3个月扣款,订阅系统默认1 */ public void setIntervalCount(Integer intervalCount) { this.interval_count = intervalCount; } /** * @return 试用天数 */ public Integer getTrialDays() { return trial_days; } /** * @param trialDays 试用天数 */ public void setTrialDays(Integer trialDays) { this.trial_days = trialDays; } /** * @return map类型附加信息 */ public Map<String, Object> getOptional() { return optional; } /** * @param optional map类型附加信息 */ public void setOptional(Map<String, Object> optional) { this.optional = optional; } /** * @return 计划是否生效 */ public boolean isValid() { return valid != null && valid; } }
0
814
40
856
42
938
38
856
42
1,187
64
false
false
false
false
false
true
55517_3
package day19; import java.util.Objects; //Cloneable是一个标记接口 , 规则 public class Student implements Cloneable { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override protected Object clone() throws CloneNotSupportedException { //去调用父类object中的clone方法 return super.clone(); } /** * 重写equals方法,比较两个对象的内容,一样就返回true * 比较者 this * 被比较者 o * * @param o * @return */ @Override public boolean equals(Object o) { //1.比较两个对象的地址是否一样,一样直接true if (this == o) return true; //2. 判断o是null直接返回false,或者比较他们两者的类型不一样直接返回false if (o == null || getClass() != o.getClass()) return false; //3. o 不是null,且o一定是Student学生类型的对象的话,开始比较内容了。 Student student = (Student) o; return age == student.age && Objects.equals(name, student.name); } }
AnswerExplanationAll/IDEA_JAVA_Project_Study
src/day19/Student.java
383
//1.比较两个对象的地址是否一样,一样直接true
line_comment
zh-cn
package day19; import java.util.Objects; //Cloneable是一个标记接口 , 规则 public class Student implements Cloneable { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } @Override protected Object clone() throws CloneNotSupportedException { //去调用父类object中的clone方法 return super.clone(); } /** * 重写equals方法,比较两个对象的内容,一样就返回true * 比较者 this * 被比较者 o * * @param o * @return */ @Override public boolean equals(Object o) { //1. <SUF> if (this == o) return true; //2. 判断o是null直接返回false,或者比较他们两者的类型不一样直接返回false if (o == null || getClass() != o.getClass()) return false; //3. o 不是null,且o一定是Student学生类型的对象的话,开始比较内容了。 Student student = (Student) o; return age == student.age && Objects.equals(name, student.name); } }
0
375
14
383
13
424
13
383
13
525
24
false
false
false
false
false
true
46516_11
import java.util.Arrays; public class ClosestAntennaPair { private double closestDistance = Double.POSITIVE_INFINITY; private long counter = 0; public ClosestAntennaPair(Point2D[] aPoints, Point2D[] bPoints) { // Insert your solution here. /** * aPoints */ int an = aPoints.length; if (an <= 0) return; Point2D[] aPointsSortedByX = new Point2D[an]; for (int i = 0; i < an; i++) aPointsSortedByX[i] = aPoints[i]; Arrays.sort(aPointsSortedByX, Point2D.Y_ORDER); Arrays.sort(aPointsSortedByX, Point2D.X_ORDER); /** * bPoints */ int bn = bPoints.length; if (bn <= 0) return; Point2D[] bPointsSortedByX = new Point2D[bn]; for (int i = 0; i < bn; i++) bPointsSortedByX[i] = bPoints[i]; Arrays.sort(bPointsSortedByX, Point2D.Y_ORDER); Arrays.sort(bPointsSortedByX, Point2D.X_ORDER); /** * // set up the array that eventually will hold the points sorted by y-coordinate */ Point2D[] aPointsSortedByY = new Point2D[an]; for (int i = 0; i < an; i++) aPointsSortedByY[i] = aPointsSortedByX[i]; Point2D[] bPointsSortedByY = new Point2D[bn]; for (int i = 0; i < bn; i++) bPointsSortedByY[i] = bPointsSortedByX[i]; // auxiliary array Point2D[] auxA = new Point2D[an]; Point2D[] auxB = new Point2D[bn]; closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, 0, 0, an-1, bn-1); } public double closest(Point2D[] aPointsSortedByX, Point2D[] bPointsSortedByX, // a/b sorted by X Point2D[] aPointsSortedByY, Point2D[] bPointsSortedByY, // a/b sorted by y Point2D[] auxA, Point2D[] auxB, // a/b auxiliary array int lowA, int lowB, int highA, int highB) { // a/b's lowest/highest indices // high/low means the indices of the array list // please do not delete/modify the next line! counter++; if(highA<lowA || highB<lowB) { //悲剧结局,没点 closestDistance = Double.POSITIVE_INFINITY; return closestDistance; } if(highA==lowA && highB==lowB) { //轻松结局,都一个 double distance = aPointsSortedByX[0].distanceTo(bPointsSortedByX[0]); if(distance<closestDistance) { closestDistance = distance; return closestDistance; }else { return distance; } } if(highA==lowA) { //一个A, for(int i = lowB; i<=highB;i++) { double distance = bPointsSortedByX[i].distanceTo(aPointsSortedByX[0]); if(distance<closestDistance) { closestDistance =distance; } } return closestDistance; } if(highB==lowB) { //一个B, for(int i = lowA; i<=highA;i++) { double distance = aPointsSortedByX[i].distanceTo(bPointsSortedByX[lowB]); if(distance<closestDistance) { closestDistance =distance; } } return closestDistance; } if(highA>lowA) { //一群A,先干A,B不止一个 int midA = lowA + (highA - lowA) / 2; // if low==high then mid==low Point2D median = aPointsSortedByX[midA]; double delta1 = closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, lowA, lowB, midA, highB); double delta2 = closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, midA+1, lowB, highA, highB); double delta = Math.min(delta1, delta2); merge(aPointsSortedByY, auxA, lowA, midA, highA); int midB = lowB + (highB - lowB) / 2; merge(bPointsSortedByY,auxB,lowB,midB,highB); int m = 0; int m2 = 0; for (int i = lowA; i <= highA; i++) { if (Math.abs(aPointsSortedByY[i].x() - median.x()) < delta) { auxA[m] = aPointsSortedByY[i]; m++; } }//如果点的 x 在median附近小于delta的范围,则写入array aux----之后会从上到下走一编y value to check the new min for (int i = lowB; i <= highB; i++) { if (Math.abs(bPointsSortedByY[i].x() - median.x()) < delta) { auxB[m2] = bPointsSortedByY[i]; m2++; } }//如果点的 x 在median附近小于delta的范围,则写入array aux----之后会从上到下走一编y value to check the new min for (int i = 0; i < m; i++) { for (int j = 0; (j < m2); j++) { double distance = auxA[i].distanceTo(auxB[j]); if (distance < delta) { delta = distance; if (distance < closestDistance) { closestDistance = delta; return closestDistance; }else { return delta; } } } } } return closestDistance; } public double distance() { return closestDistance; } public long getCounter() { return counter; } // stably merge a[low .. mid] with a[mid+1 ..high] using aux[low .. high] // precondition: a[low .. mid] and a[mid+1 .. high] are sorted subarrays, namely sorted by y coordinate // this is the same as in ClosestPair private static void merge(Point2D[] a, Point2D[] aux, int low, int mid, int high) { // copy to aux[] // note this wipes out any values that were previously in aux in the [low,high] range we're currently using for (int k = low; k <= high; k++) { aux[k] = a[k]; } int i = low, j = mid + 1; for (int k = low; k <= high; k++) { if (i > mid) a[k] = aux[j++]; // already finished with the low list ? then dump the rest of high list else if (j > high) a[k] = aux[i++]; // already finished with the high list ? then dump the rest of low list else if (aux[i].compareByY(aux[j]) < 0) a[k] = aux[i++]; // aux[i] should be in front of aux[j] ? position and increment the pointer else a[k] = aux[j++]; } } }
AntiAntonyZhao/Introduction-to-Java
A3/ClosestAntennaPair.java
1,971
//悲剧结局,没点
line_comment
zh-cn
import java.util.Arrays; public class ClosestAntennaPair { private double closestDistance = Double.POSITIVE_INFINITY; private long counter = 0; public ClosestAntennaPair(Point2D[] aPoints, Point2D[] bPoints) { // Insert your solution here. /** * aPoints */ int an = aPoints.length; if (an <= 0) return; Point2D[] aPointsSortedByX = new Point2D[an]; for (int i = 0; i < an; i++) aPointsSortedByX[i] = aPoints[i]; Arrays.sort(aPointsSortedByX, Point2D.Y_ORDER); Arrays.sort(aPointsSortedByX, Point2D.X_ORDER); /** * bPoints */ int bn = bPoints.length; if (bn <= 0) return; Point2D[] bPointsSortedByX = new Point2D[bn]; for (int i = 0; i < bn; i++) bPointsSortedByX[i] = bPoints[i]; Arrays.sort(bPointsSortedByX, Point2D.Y_ORDER); Arrays.sort(bPointsSortedByX, Point2D.X_ORDER); /** * // set up the array that eventually will hold the points sorted by y-coordinate */ Point2D[] aPointsSortedByY = new Point2D[an]; for (int i = 0; i < an; i++) aPointsSortedByY[i] = aPointsSortedByX[i]; Point2D[] bPointsSortedByY = new Point2D[bn]; for (int i = 0; i < bn; i++) bPointsSortedByY[i] = bPointsSortedByX[i]; // auxiliary array Point2D[] auxA = new Point2D[an]; Point2D[] auxB = new Point2D[bn]; closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, 0, 0, an-1, bn-1); } public double closest(Point2D[] aPointsSortedByX, Point2D[] bPointsSortedByX, // a/b sorted by X Point2D[] aPointsSortedByY, Point2D[] bPointsSortedByY, // a/b sorted by y Point2D[] auxA, Point2D[] auxB, // a/b auxiliary array int lowA, int lowB, int highA, int highB) { // a/b's lowest/highest indices // high/low means the indices of the array list // please do not delete/modify the next line! counter++; if(highA<lowA || highB<lowB) { //悲剧 <SUF> closestDistance = Double.POSITIVE_INFINITY; return closestDistance; } if(highA==lowA && highB==lowB) { //轻松结局,都一个 double distance = aPointsSortedByX[0].distanceTo(bPointsSortedByX[0]); if(distance<closestDistance) { closestDistance = distance; return closestDistance; }else { return distance; } } if(highA==lowA) { //一个A, for(int i = lowB; i<=highB;i++) { double distance = bPointsSortedByX[i].distanceTo(aPointsSortedByX[0]); if(distance<closestDistance) { closestDistance =distance; } } return closestDistance; } if(highB==lowB) { //一个B, for(int i = lowA; i<=highA;i++) { double distance = aPointsSortedByX[i].distanceTo(bPointsSortedByX[lowB]); if(distance<closestDistance) { closestDistance =distance; } } return closestDistance; } if(highA>lowA) { //一群A,先干A,B不止一个 int midA = lowA + (highA - lowA) / 2; // if low==high then mid==low Point2D median = aPointsSortedByX[midA]; double delta1 = closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, lowA, lowB, midA, highB); double delta2 = closest(aPointsSortedByX, bPointsSortedByX, aPointsSortedByY, bPointsSortedByY, auxA, auxB, midA+1, lowB, highA, highB); double delta = Math.min(delta1, delta2); merge(aPointsSortedByY, auxA, lowA, midA, highA); int midB = lowB + (highB - lowB) / 2; merge(bPointsSortedByY,auxB,lowB,midB,highB); int m = 0; int m2 = 0; for (int i = lowA; i <= highA; i++) { if (Math.abs(aPointsSortedByY[i].x() - median.x()) < delta) { auxA[m] = aPointsSortedByY[i]; m++; } }//如果点的 x 在median附近小于delta的范围,则写入array aux----之后会从上到下走一编y value to check the new min for (int i = lowB; i <= highB; i++) { if (Math.abs(bPointsSortedByY[i].x() - median.x()) < delta) { auxB[m2] = bPointsSortedByY[i]; m2++; } }//如果点的 x 在median附近小于delta的范围,则写入array aux----之后会从上到下走一编y value to check the new min for (int i = 0; i < m; i++) { for (int j = 0; (j < m2); j++) { double distance = auxA[i].distanceTo(auxB[j]); if (distance < delta) { delta = distance; if (distance < closestDistance) { closestDistance = delta; return closestDistance; }else { return delta; } } } } } return closestDistance; } public double distance() { return closestDistance; } public long getCounter() { return counter; } // stably merge a[low .. mid] with a[mid+1 ..high] using aux[low .. high] // precondition: a[low .. mid] and a[mid+1 .. high] are sorted subarrays, namely sorted by y coordinate // this is the same as in ClosestPair private static void merge(Point2D[] a, Point2D[] aux, int low, int mid, int high) { // copy to aux[] // note this wipes out any values that were previously in aux in the [low,high] range we're currently using for (int k = low; k <= high; k++) { aux[k] = a[k]; } int i = low, j = mid + 1; for (int k = low; k <= high; k++) { if (i > mid) a[k] = aux[j++]; // already finished with the low list ? then dump the rest of high list else if (j > high) a[k] = aux[i++]; // already finished with the high list ? then dump the rest of low list else if (aux[i].compareByY(aux[j]) < 0) a[k] = aux[i++]; // aux[i] should be in front of aux[j] ? position and increment the pointer else a[k] = aux[j++]; } } }
0
1,778
6
1,971
10
1,959
7
1,971
10
2,383
12
false
false
false
false
false
true
32600_17
package ThMod.characters; import ThMod.ThMod; import ThMod.cards.Cirno.Chirumiru; import ThMod.patches.AbstractCardEnum; import ThMod.patches.ThModClassEnum; import basemod.abstracts.CustomPlayer; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.MathUtils; import com.megacrit.cardcrawl.actions.AbstractGameAction.AttackEffect; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.EnergyManager; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.core.Settings.GameLanguage; import com.megacrit.cardcrawl.helpers.FontHelper; import com.megacrit.cardcrawl.helpers.ImageMaster; import com.megacrit.cardcrawl.helpers.ScreenShake; import com.megacrit.cardcrawl.screens.CharSelectInfo; import com.megacrit.cardcrawl.unlock.UnlockTracker; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; public class Cirno extends CustomPlayer { private static final int ENERGY_PER_TURN = 3; // how much energy you get every turn private static final String CIRNO_SHOULDER_2 = "img/char/Cirno/shoulder2.png"; // shoulder2 / shoulder_1 private static final String CIRNO_SHOULDER_1 = "img/char/Cirno/shoulder1.png"; // shoulder1 / shoulder_2 private static final String CIRNO_CORPSE = "img/char/Cirno/fallen.png"; // dead corpse public static final Logger logger = LogManager.getLogger(ThMod.class.getName()); //private static final float[] layerSpeeds = { 20.0F, 0.0F, -40.0F, 0.0F, 0.0F, 5.0F, 0.0F, -8.0F, 0.0F, 8.0F }; // private static final String CIRNO_SKELETON_ATLAS = "img/char/Cirno/MarisaModelv3.atlas";// Marisa_v0 / MarisaModel_v02 /MarisaModelv3 // private static final String CIRNO_SKELETON_JSON = "img/char/Cirno/MarisaModelv3.json"; private static final String CIRNO_ANIMATION = "Idle";// Sprite / Idle private static final String[] ORB_TEXTURES = { "img/UI/EPanel/layer5.png", "img/UI/EPanel/layer4.png", "img/UI/EPanel/layer3.png", "img/UI/EPanel/layer2.png", "img/UI/EPanel/layer1.png", "img/UI/EPanel/layer0.png", "img/UI/EPanel/layer5d.png", "img/UI/EPanel/layer4d.png", "img/UI/EPanel/layer3d.png", "img/UI/EPanel/layer2d.png", "img/UI/EPanel/layer1d.png" }; private static final String ORB_VFX = "img/UI/energyBlueVFX.png"; private static final float[] LAYER_SPEED = {-40.0F, -32.0F, 20.0F, -20.0F, 0.0F, -10.0F, -8.0F, 5.0F, -5.0F, 0.0F}; //public static final String SPRITER_ANIM_FILEPATH = "img/char/MyCharacter/marisa_test.scml"; // spriter animation scml public Cirno(String name) { //super(name, setClass, null, null , null ,new SpriterAnimation(SPRITER_ANIM_FILEPATH)); super(name, ThModClassEnum.CIRNO, ORB_TEXTURES, ORB_VFX, LAYER_SPEED, null, null); //super(name, setClass, null, null, (String) null, null); this.dialogX = (this.drawX + 0.0F * Settings.scale); // set location for text bubbles this.dialogY = (this.drawY + 220.0F * Settings.scale); // you can just copy these values logger.info("init Cirno"); initializeClass( "img/char/Cirno/cirno.png", CIRNO_SHOULDER_2, // required call to load textures and setup energy/loadout CIRNO_SHOULDER_1, CIRNO_CORPSE, getLoadout(), 20.0F, -10.0F, 220.0F, 290.0F, new EnergyManager(ENERGY_PER_TURN) ); // loadAnimation(CIRNO_SKELETON_ATLAS, CIRNO_SKELETON_JSON, 2.0F); // if you're using modified versions of base game animations or made animations in spine make sure to include this bit and the following lines /* AnimationState.TrackEntry e = this.state.setAnimation(0, CIRNO_ANIMATION, true); e.setTime(e.getEndTime() * MathUtils.random()); this.stateData.setMix("Hit", "Idle", 0.1F); e.setTimeScale(1.0F); */ logger.info("init finish"); } public ArrayList<String> getStartingDeck() { // 初始卡组 ArrayList<String> ret = new ArrayList<>(); for (int i = 0; i < 5; i++) ret.add("IceGrain"); for (int i = 0; i < 5; i++) ret.add("IceBarrier"); ret.add("IcicleShot"); ret.add("ShowOff"); return ret; } public ArrayList<String> getStartingRelics() { // 初始遗物 ArrayList<String> ret = new ArrayList<>(); ret.add("CrystalWings"); UnlockTracker.markRelicAsSeen("CrystalWings"); return ret; } private static final int STARTING_HP = 69; private static final int MAX_HP = 69; private static final int STARTING_GOLD = 99; private static final int HAND_SIZE = 5; private static final int ASCENSION_MAX_HP_LOSS = 4; public CharSelectInfo getLoadout() { // the rest of the character loadout so includes your character select screen info plus hp and starting gold String title; String flavor; if (Settings.language == Settings.GameLanguage.ZHS || Settings.language == Settings.GameLanguage.ZHT) { title = "琪露诺"; flavor = "居住在雾之湖的冰之妖精。笨蛋。"; } else { title = "Cirno"; flavor = "Baka!"; } return new CharSelectInfo( title, flavor, STARTING_HP, MAX_HP, 0, STARTING_GOLD, HAND_SIZE, this, getStartingRelics(), getStartingDeck(), false ); } public AbstractCard.CardColor getCardColor() { return AbstractCardEnum.CIRNO_COLOR; } public AbstractCard getStartCardForEvent() { return new Chirumiru(); } public String getTitle(PlayerClass playerClass) { String title; if (Settings.language == GameLanguage.ZHS) { title = "冰之小妖精"; } else { title = "Little Ice Fairy"; } return title; } public Color getCardTrailColor() { return ThMod.CHILLED; } public int getAscensionMaxHPLoss() { return ASCENSION_MAX_HP_LOSS; } public BitmapFont getEnergyNumFont() { return FontHelper.energyNumFontBlue; } public void doCharSelectScreenSelectEffect() { CardCrawlGame.sound.playA("SELECT_CIRNO", MathUtils.random(-0.1F, 0.1F)); CardCrawlGame.screenShake.shake( ScreenShake.ShakeIntensity.MED, ScreenShake.ShakeDur.SHORT, false ); } public String getCustomModeCharacterButtonSoundKey() { return "SELECT_CIRNO"; } public String getLocalizedCharacterName() { String char_name; if ((Settings.language == Settings.GameLanguage.ZHS) || (Settings.language == Settings.GameLanguage.ZHT)) { char_name = "琪露诺"; } else if (Settings.language == Settings.GameLanguage.JPN) { char_name = "チルノ"; } else { char_name = "Cirno"; } return char_name; } public AbstractPlayer newInstance() { return new Cirno(this.name); } @Override public String getVampireText() { return com.megacrit.cardcrawl.events.city.Vampires.DESCRIPTIONS[1]; } public Color getCardRenderColor() { return ThMod.CHILLED; } public void updateOrb(int orbCount) { this.energyOrb.updateOrb(orbCount); } public TextureAtlas.AtlasRegion getOrb() { return new TextureAtlas.AtlasRegion(ImageMaster.loadImage(ThMod.CARD_ENERGY_ORB), 0, 0, 24, 24); } public Color getSlashAttackColor() { return ThMod.CHILLED; } public AttackEffect[] getSpireHeartSlashEffect() { return new AttackEffect[]{ AttackEffect.SLASH_HEAVY, AttackEffect.FIRE, AttackEffect.SLASH_DIAGONAL, AttackEffect.SLASH_HEAVY, AttackEffect.FIRE, AttackEffect.SLASH_DIAGONAL }; } public String getSpireHeartText() { return com.megacrit.cardcrawl.events.beyond.SpireHeart.DESCRIPTIONS[10]; } public void damage(DamageInfo info) { // if ((info.owner != null) && (info.type != DamageInfo.DamageType.THORNS) // && (info.output - this.currentBlock > 0)) { // AnimationState.TrackEntry e = this.state.setAnimation(0, "Hit", false); // this.state.addAnimation(0, "Idle", true, 0.0F); // e.setTimeScale(1.0F); // } super.damage(info); } public void applyPreCombatLogic() { super.applyPreCombatLogic(); // ThMod.typhoonCounter = 0; // ThMod.logger.info( // "Marisa : applyPreCombatLogic : I just reset the god damn typhoon counter ! current counter : " // + ThMod.typhoonCounter // ); } }
AntiLeaf/CirnoMod
src/main/java/ThMod/characters/Cirno.java
2,956
// 初始卡组
line_comment
zh-cn
package ThMod.characters; import ThMod.ThMod; import ThMod.cards.Cirno.Chirumiru; import ThMod.patches.AbstractCardEnum; import ThMod.patches.ThModClassEnum; import basemod.abstracts.CustomPlayer; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.MathUtils; import com.megacrit.cardcrawl.actions.AbstractGameAction.AttackEffect; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.EnergyManager; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.core.Settings.GameLanguage; import com.megacrit.cardcrawl.helpers.FontHelper; import com.megacrit.cardcrawl.helpers.ImageMaster; import com.megacrit.cardcrawl.helpers.ScreenShake; import com.megacrit.cardcrawl.screens.CharSelectInfo; import com.megacrit.cardcrawl.unlock.UnlockTracker; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.ArrayList; public class Cirno extends CustomPlayer { private static final int ENERGY_PER_TURN = 3; // how much energy you get every turn private static final String CIRNO_SHOULDER_2 = "img/char/Cirno/shoulder2.png"; // shoulder2 / shoulder_1 private static final String CIRNO_SHOULDER_1 = "img/char/Cirno/shoulder1.png"; // shoulder1 / shoulder_2 private static final String CIRNO_CORPSE = "img/char/Cirno/fallen.png"; // dead corpse public static final Logger logger = LogManager.getLogger(ThMod.class.getName()); //private static final float[] layerSpeeds = { 20.0F, 0.0F, -40.0F, 0.0F, 0.0F, 5.0F, 0.0F, -8.0F, 0.0F, 8.0F }; // private static final String CIRNO_SKELETON_ATLAS = "img/char/Cirno/MarisaModelv3.atlas";// Marisa_v0 / MarisaModel_v02 /MarisaModelv3 // private static final String CIRNO_SKELETON_JSON = "img/char/Cirno/MarisaModelv3.json"; private static final String CIRNO_ANIMATION = "Idle";// Sprite / Idle private static final String[] ORB_TEXTURES = { "img/UI/EPanel/layer5.png", "img/UI/EPanel/layer4.png", "img/UI/EPanel/layer3.png", "img/UI/EPanel/layer2.png", "img/UI/EPanel/layer1.png", "img/UI/EPanel/layer0.png", "img/UI/EPanel/layer5d.png", "img/UI/EPanel/layer4d.png", "img/UI/EPanel/layer3d.png", "img/UI/EPanel/layer2d.png", "img/UI/EPanel/layer1d.png" }; private static final String ORB_VFX = "img/UI/energyBlueVFX.png"; private static final float[] LAYER_SPEED = {-40.0F, -32.0F, 20.0F, -20.0F, 0.0F, -10.0F, -8.0F, 5.0F, -5.0F, 0.0F}; //public static final String SPRITER_ANIM_FILEPATH = "img/char/MyCharacter/marisa_test.scml"; // spriter animation scml public Cirno(String name) { //super(name, setClass, null, null , null ,new SpriterAnimation(SPRITER_ANIM_FILEPATH)); super(name, ThModClassEnum.CIRNO, ORB_TEXTURES, ORB_VFX, LAYER_SPEED, null, null); //super(name, setClass, null, null, (String) null, null); this.dialogX = (this.drawX + 0.0F * Settings.scale); // set location for text bubbles this.dialogY = (this.drawY + 220.0F * Settings.scale); // you can just copy these values logger.info("init Cirno"); initializeClass( "img/char/Cirno/cirno.png", CIRNO_SHOULDER_2, // required call to load textures and setup energy/loadout CIRNO_SHOULDER_1, CIRNO_CORPSE, getLoadout(), 20.0F, -10.0F, 220.0F, 290.0F, new EnergyManager(ENERGY_PER_TURN) ); // loadAnimation(CIRNO_SKELETON_ATLAS, CIRNO_SKELETON_JSON, 2.0F); // if you're using modified versions of base game animations or made animations in spine make sure to include this bit and the following lines /* AnimationState.TrackEntry e = this.state.setAnimation(0, CIRNO_ANIMATION, true); e.setTime(e.getEndTime() * MathUtils.random()); this.stateData.setMix("Hit", "Idle", 0.1F); e.setTimeScale(1.0F); */ logger.info("init finish"); } public ArrayList<String> getStartingDeck() { // 初始 <SUF> ArrayList<String> ret = new ArrayList<>(); for (int i = 0; i < 5; i++) ret.add("IceGrain"); for (int i = 0; i < 5; i++) ret.add("IceBarrier"); ret.add("IcicleShot"); ret.add("ShowOff"); return ret; } public ArrayList<String> getStartingRelics() { // 初始遗物 ArrayList<String> ret = new ArrayList<>(); ret.add("CrystalWings"); UnlockTracker.markRelicAsSeen("CrystalWings"); return ret; } private static final int STARTING_HP = 69; private static final int MAX_HP = 69; private static final int STARTING_GOLD = 99; private static final int HAND_SIZE = 5; private static final int ASCENSION_MAX_HP_LOSS = 4; public CharSelectInfo getLoadout() { // the rest of the character loadout so includes your character select screen info plus hp and starting gold String title; String flavor; if (Settings.language == Settings.GameLanguage.ZHS || Settings.language == Settings.GameLanguage.ZHT) { title = "琪露诺"; flavor = "居住在雾之湖的冰之妖精。笨蛋。"; } else { title = "Cirno"; flavor = "Baka!"; } return new CharSelectInfo( title, flavor, STARTING_HP, MAX_HP, 0, STARTING_GOLD, HAND_SIZE, this, getStartingRelics(), getStartingDeck(), false ); } public AbstractCard.CardColor getCardColor() { return AbstractCardEnum.CIRNO_COLOR; } public AbstractCard getStartCardForEvent() { return new Chirumiru(); } public String getTitle(PlayerClass playerClass) { String title; if (Settings.language == GameLanguage.ZHS) { title = "冰之小妖精"; } else { title = "Little Ice Fairy"; } return title; } public Color getCardTrailColor() { return ThMod.CHILLED; } public int getAscensionMaxHPLoss() { return ASCENSION_MAX_HP_LOSS; } public BitmapFont getEnergyNumFont() { return FontHelper.energyNumFontBlue; } public void doCharSelectScreenSelectEffect() { CardCrawlGame.sound.playA("SELECT_CIRNO", MathUtils.random(-0.1F, 0.1F)); CardCrawlGame.screenShake.shake( ScreenShake.ShakeIntensity.MED, ScreenShake.ShakeDur.SHORT, false ); } public String getCustomModeCharacterButtonSoundKey() { return "SELECT_CIRNO"; } public String getLocalizedCharacterName() { String char_name; if ((Settings.language == Settings.GameLanguage.ZHS) || (Settings.language == Settings.GameLanguage.ZHT)) { char_name = "琪露诺"; } else if (Settings.language == Settings.GameLanguage.JPN) { char_name = "チルノ"; } else { char_name = "Cirno"; } return char_name; } public AbstractPlayer newInstance() { return new Cirno(this.name); } @Override public String getVampireText() { return com.megacrit.cardcrawl.events.city.Vampires.DESCRIPTIONS[1]; } public Color getCardRenderColor() { return ThMod.CHILLED; } public void updateOrb(int orbCount) { this.energyOrb.updateOrb(orbCount); } public TextureAtlas.AtlasRegion getOrb() { return new TextureAtlas.AtlasRegion(ImageMaster.loadImage(ThMod.CARD_ENERGY_ORB), 0, 0, 24, 24); } public Color getSlashAttackColor() { return ThMod.CHILLED; } public AttackEffect[] getSpireHeartSlashEffect() { return new AttackEffect[]{ AttackEffect.SLASH_HEAVY, AttackEffect.FIRE, AttackEffect.SLASH_DIAGONAL, AttackEffect.SLASH_HEAVY, AttackEffect.FIRE, AttackEffect.SLASH_DIAGONAL }; } public String getSpireHeartText() { return com.megacrit.cardcrawl.events.beyond.SpireHeart.DESCRIPTIONS[10]; } public void damage(DamageInfo info) { // if ((info.owner != null) && (info.type != DamageInfo.DamageType.THORNS) // && (info.output - this.currentBlock > 0)) { // AnimationState.TrackEntry e = this.state.setAnimation(0, "Hit", false); // this.state.addAnimation(0, "Idle", true, 0.0F); // e.setTimeScale(1.0F); // } super.damage(info); } public void applyPreCombatLogic() { super.applyPreCombatLogic(); // ThMod.typhoonCounter = 0; // ThMod.logger.info( // "Marisa : applyPreCombatLogic : I just reset the god damn typhoon counter ! current counter : " // + ThMod.typhoonCounter // ); } }
0
2,494
5
2,955
5
2,891
5
2,956
5
3,479
8
false
false
false
false
false
true
7800_3
package top.sharehome.springbootinittemplate.config.security; import cn.dev33.satoken.session.SaSession; import cn.dev33.satoken.stp.StpInterface; import cn.dev33.satoken.stp.StpUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import top.sharehome.springbootinittemplate.common.base.Constants; import top.sharehome.springbootinittemplate.config.security.condition.SaCondition; import top.sharehome.springbootinittemplate.model.vo.auth.AuthLoginVo; import jakarta.annotation.PostConstruct; import java.util.Collections; import java.util.List; /** * SaToken鉴权配置 * 这里应该会依靠loginId对数据库进行相关查询,得到的结果放入结果集中, * 该模板不会单独规划处一个权限或者角色数据库表样式,而是将角色内嵌于模板SQL中t_user表内,因为该模板主要针对于不同的中小系统而设计的,不同系统都有不同的权限和角色分配, * 用与不用SaToken鉴权完全取决于系统本身业务,所以此处@Component注解打开与否完全取决于开发者; * * @author AntonyCheng */ @Configuration @Conditional(SaCondition.class) @Slf4j public class AuthorizationConfiguration implements StpInterface { /** * 重写权限方法 * * @param loginId 账号id * @param loginType 账号类型 * @return 返回结果 */ @Override public List<String> getPermissionList(Object loginId, String loginType) { // 根据SaToken权限配置文档:https://sa-token.cc/doc.html#/use/jur-auth // 由于此处设计主要针对于接口权限,所以权限通常有多个,上帝权限和个别极端情况除外 // 举例:User实体中有一个add方法(),则推荐将该方法权限写为"user.add",支持通配符操作,如果想要得到User实体类中所有方法的调用权限,则写为"user.*" // "*"表示上帝权限 return Collections.singletonList("*"); } /** * 重写角色方法 * * @param loginId 账号id * @param loginType 账号类型 * @return 返回结果 */ @Override public List<String> getRoleList(Object loginId, String loginType) { // 根据SaToken权限配置文档:https://sa-token.cc/doc.html#/use/jur-auth // 由于此处设计主要针对于用户角色,所以角色通常只有一个,个别情况除外 // "*"表示上帝角色 SaSession session = StpUtil.getSessionByLoginId(loginId); String userRole = ((AuthLoginVo) session.get(Constants.LOGIN_USER_KEY)).getRole(); return Collections.singletonList(userRole); } /** * 依赖注入日志输出 */ @PostConstruct private void initDi() { log.info("############ {} Configuration DI.", this.getClass().getSimpleName().split("\\$\\$")[0]); } }
AntonyCheng/spring-boot-init-template
src/main/java/top/sharehome/springbootinittemplate/config/security/AuthorizationConfiguration.java
783
// 由于此处设计主要针对于接口权限,所以权限通常有多个,上帝权限和个别极端情况除外
line_comment
zh-cn
package top.sharehome.springbootinittemplate.config.security; import cn.dev33.satoken.session.SaSession; import cn.dev33.satoken.stp.StpInterface; import cn.dev33.satoken.stp.StpUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import top.sharehome.springbootinittemplate.common.base.Constants; import top.sharehome.springbootinittemplate.config.security.condition.SaCondition; import top.sharehome.springbootinittemplate.model.vo.auth.AuthLoginVo; import jakarta.annotation.PostConstruct; import java.util.Collections; import java.util.List; /** * SaToken鉴权配置 * 这里应该会依靠loginId对数据库进行相关查询,得到的结果放入结果集中, * 该模板不会单独规划处一个权限或者角色数据库表样式,而是将角色内嵌于模板SQL中t_user表内,因为该模板主要针对于不同的中小系统而设计的,不同系统都有不同的权限和角色分配, * 用与不用SaToken鉴权完全取决于系统本身业务,所以此处@Component注解打开与否完全取决于开发者; * * @author AntonyCheng */ @Configuration @Conditional(SaCondition.class) @Slf4j public class AuthorizationConfiguration implements StpInterface { /** * 重写权限方法 * * @param loginId 账号id * @param loginType 账号类型 * @return 返回结果 */ @Override public List<String> getPermissionList(Object loginId, String loginType) { // 根据SaToken权限配置文档:https://sa-token.cc/doc.html#/use/jur-auth // 由于 <SUF> // 举例:User实体中有一个add方法(),则推荐将该方法权限写为"user.add",支持通配符操作,如果想要得到User实体类中所有方法的调用权限,则写为"user.*" // "*"表示上帝权限 return Collections.singletonList("*"); } /** * 重写角色方法 * * @param loginId 账号id * @param loginType 账号类型 * @return 返回结果 */ @Override public List<String> getRoleList(Object loginId, String loginType) { // 根据SaToken权限配置文档:https://sa-token.cc/doc.html#/use/jur-auth // 由于此处设计主要针对于用户角色,所以角色通常只有一个,个别情况除外 // "*"表示上帝角色 SaSession session = StpUtil.getSessionByLoginId(loginId); String userRole = ((AuthLoginVo) session.get(Constants.LOGIN_USER_KEY)).getRole(); return Collections.singletonList(userRole); } /** * 依赖注入日志输出 */ @PostConstruct private void initDi() { log.info("############ {} Configuration DI.", this.getClass().getSimpleName().split("\\$\\$")[0]); } }
0
662
24
783
30
759
27
783
30
1,071
57
false
false
false
false
false
true
44793_20
package kualian.dc.deal.application.util; import android.app.Activity; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.graphics.Bitmap; import android.graphics.Matrix; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Handler; import android.os.HandlerThread; import android.os.Vibrator; import android.text.InputFilter; import android.text.InputType; import android.text.Spanned; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import kualian.dc.deal.application.R; import kualian.dc.deal.application.WalletApp; import kualian.dc.deal.application.database.CoinDao; import kualian.dc.deal.application.wallet.CoinType; import kualian.dc.deal.application.wallet.coins.BitcoinMain; import kualian.dc.deal.application.wallet.coins.UbMain; import static android.content.Context.AUDIO_SERVICE; /** * Created by vondear on 2016/1/24. * RxTools的常用工具类 * <p> * For the brave souls who getWallet this far: You are the chosen ones, * the valiant knights of programming who toil away, without rest, * fixing our most awful code. To you, true saviors, kings of men, * I say this: never gonna give you up, never gonna let you down, * never gonna run around and desert you. Never gonna make you cry, * never gonna say goodbye. Never gonna tell a lie and hurt you. * <p> * 致终于来到这里的勇敢的人: * 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。 * 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己, * 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。 */ public class WalletTool { private static Context context; private static long lastClickTime; /** * 初始化工具类 * * @param context 上下文 */ public static void init(Context context) { WalletTool.context = context.getApplicationContext(); } /** * 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context * <p> * 获取ApplicationContext * * @return ApplicationContext */ public static Context getContext() { if (context != null) return context; throw new NullPointerException("请先调用init()方法"); } //==============================================================================================延时任务封装 end //----------------------------------------------------------------------------------------------延时任务封装 start /** * 倒计时 * * @param textView 控件 * @param waitTime 倒计时总时长 * @param interval 倒计时的间隔时间 * @param hint 倒计时完毕时显示的文字 */ public static void countDown(final TextView textView, long waitTime, long interval, final String hint) { textView.setEnabled(false); android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) { @Override public void onTick(long millisUntilFinished) { textView.setText("剩下 " + (millisUntilFinished / 1000) + " S"); } @Override public void onFinish() { textView.setEnabled(true); textView.setText(hint); } }; timer.start(); } /** * 手动计算出listView的高度,但是不再具有滚动效果 * * @param listView */ public static void fixListViewHeight(ListView listView) { // 如果没有设置数据适配器,则ListView没有子项,返回。 ListAdapter listAdapter = listView.getAdapter(); int totalHeight = 0; if (listAdapter == null) { return; } for (int index = 0, len = listAdapter.getCount(); index < len; index++) { View listViewItem = listAdapter.getView(index, null, listView); // 计算子项View 的宽高 listViewItem.measure(0, 0); // 计算所有子项的高度 totalHeight += listViewItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); // listView.getDividerHeight()获取子项间分隔符的高度 // params.height设置ListView完全显示需要的高度 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } //---------------------------------------------MD5加密------------------------------------------- /** * 生成MD5加密32位字符串 * * @param MStr :需要加密的字符串 * @return */ public static String Md5(String MStr) { try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(MStr.getBytes()); return bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { return String.valueOf(MStr.hashCode()); } } // MD5内部算法---------------不能修改! private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } //============================================MD5加密============================================ /** * 根据资源名称获取资源 id * <p> * 不提倡使用这个方法获取资源,比其直接获取ID效率慢 * <p> * 例如 * getResources().getIdentifier("ic_launcher", "drawable", getPackageName()); * * @param context * @param name * @param defType * @return */ public static final int getResIdByName(Context context, String name, String defType) { return context.getResources().getIdentifier("ic_launcher", "drawable", context.getPackageName()); } public static boolean isFastClick(int millisecond) { long curClickTime = System.currentTimeMillis(); long interval = (curClickTime - lastClickTime); if (0 < interval && interval < millisecond) { // 超过点击间隔后再将lastClickTime重置为当前点击时间 return true; } lastClickTime = curClickTime; return false; } /** * Edittext 首位小数点自动加零,最多两位小数 * * @param editText */ public static void setEdTwoDecimal(EditText editText) { setEdDecimal(editText, 3); } public static void setEdDecimal(EditText editText, int count) { if (count < 1) { count = 1; } editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER); //设置字符过滤 final int finalCount = count; editText.setFilters(new InputFilter[]{new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (source.equals(".") && dest.toString().length() == 0) { return "0."; } if (dest.toString().contains(".")) { int index = dest.toString().indexOf("."); int mlength = dest.toString().substring(index).length(); if (mlength == finalCount) { return ""; } } return null; } }}); } public static void setEditNumberPrefix(final EditText edSerialNumber, final int number) { edSerialNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String s = edSerialNumber.getText().toString(); String temp = ""; for (int i = s.length(); i < number; i++) { s = "0" + s; } for (int i = 0; i < number; i++) { temp += "0"; } if (s.equals(temp)) { s = temp.substring(1) + "1"; } edSerialNumber.setText(s); } } }); } private static final float BEEP_VOLUME = 0.50f; private static final int VIBRATE_DURATION = 200; private static boolean playBeep = false; private static MediaPlayer mediaPlayer; public static void playBeep(Activity mContext, boolean vibrate) { playBeep = true; AudioManager audioService = (AudioManager) mContext.getSystemService(AUDIO_SERVICE); if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) { playBeep = false; } if (playBeep && mediaPlayer != null) { mediaPlayer.start(); } else { mContext.setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.seekTo(0); } }); AssetFileDescriptor file = mContext.getResources().openRawResourceFd(R.raw.beep); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); file.close(); mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); } catch (IOException e) { mediaPlayer = null; } } if (vibrate) { vibrateOnce(mContext, VIBRATE_DURATION); } } private static Vibrator vibrator; /** * 简单震动 * @param context 调用震动的Context * @param millisecond 震动的时间,毫秒 */ @SuppressWarnings("static-access") public static void vibrateOnce(Context context, int millisecond) { vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE); vibrator.vibrate(millisecond); } /** * Resize the bitmap * * @param bitmap 图片引用 * @param width 宽度 * @param height 高度 * @return 缩放之后的图片引用 */ public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidth = ((float) width / w); float scaleHeight = ((float) height / h); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true); } public static Handler getBackgroundHandler() { HandlerThread thread = new HandlerThread("background"); thread.start(); Handler mBackgroundHandler = new Handler(thread.getLooper()); return mBackgroundHandler; } public static CoinType getDefaultCoin(){ List<CoinType> list = new CoinDao().queryAll(SpUtil.getInstance().getWalletID()); for (CoinType type: list) { if (type.getCoinIndex()==SpUtil.getInstance().getDefaultCoinIndex()){ return type; } } return new UbMain(); } }
AnyBitIO/anybit-Android
app/src/main/java/kualian/dc/deal/application/util/WalletTool.java
2,852
//设置字符过滤
line_comment
zh-cn
package kualian.dc.deal.application.util; import android.app.Activity; import android.content.Context; import android.content.res.AssetFileDescriptor; import android.graphics.Bitmap; import android.graphics.Matrix; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Handler; import android.os.HandlerThread; import android.os.Vibrator; import android.text.InputFilter; import android.text.InputType; import android.text.Spanned; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; import kualian.dc.deal.application.R; import kualian.dc.deal.application.WalletApp; import kualian.dc.deal.application.database.CoinDao; import kualian.dc.deal.application.wallet.CoinType; import kualian.dc.deal.application.wallet.coins.BitcoinMain; import kualian.dc.deal.application.wallet.coins.UbMain; import static android.content.Context.AUDIO_SERVICE; /** * Created by vondear on 2016/1/24. * RxTools的常用工具类 * <p> * For the brave souls who getWallet this far: You are the chosen ones, * the valiant knights of programming who toil away, without rest, * fixing our most awful code. To you, true saviors, kings of men, * I say this: never gonna give you up, never gonna let you down, * never gonna run around and desert you. Never gonna make you cry, * never gonna say goodbye. Never gonna tell a lie and hurt you. * <p> * 致终于来到这里的勇敢的人: * 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。 * 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己, * 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。 */ public class WalletTool { private static Context context; private static long lastClickTime; /** * 初始化工具类 * * @param context 上下文 */ public static void init(Context context) { WalletTool.context = context.getApplicationContext(); } /** * 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context * <p> * 获取ApplicationContext * * @return ApplicationContext */ public static Context getContext() { if (context != null) return context; throw new NullPointerException("请先调用init()方法"); } //==============================================================================================延时任务封装 end //----------------------------------------------------------------------------------------------延时任务封装 start /** * 倒计时 * * @param textView 控件 * @param waitTime 倒计时总时长 * @param interval 倒计时的间隔时间 * @param hint 倒计时完毕时显示的文字 */ public static void countDown(final TextView textView, long waitTime, long interval, final String hint) { textView.setEnabled(false); android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) { @Override public void onTick(long millisUntilFinished) { textView.setText("剩下 " + (millisUntilFinished / 1000) + " S"); } @Override public void onFinish() { textView.setEnabled(true); textView.setText(hint); } }; timer.start(); } /** * 手动计算出listView的高度,但是不再具有滚动效果 * * @param listView */ public static void fixListViewHeight(ListView listView) { // 如果没有设置数据适配器,则ListView没有子项,返回。 ListAdapter listAdapter = listView.getAdapter(); int totalHeight = 0; if (listAdapter == null) { return; } for (int index = 0, len = listAdapter.getCount(); index < len; index++) { View listViewItem = listAdapter.getView(index, null, listView); // 计算子项View 的宽高 listViewItem.measure(0, 0); // 计算所有子项的高度 totalHeight += listViewItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); // listView.getDividerHeight()获取子项间分隔符的高度 // params.height设置ListView完全显示需要的高度 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } //---------------------------------------------MD5加密------------------------------------------- /** * 生成MD5加密32位字符串 * * @param MStr :需要加密的字符串 * @return */ public static String Md5(String MStr) { try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(MStr.getBytes()); return bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { return String.valueOf(MStr.hashCode()); } } // MD5内部算法---------------不能修改! private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } //============================================MD5加密============================================ /** * 根据资源名称获取资源 id * <p> * 不提倡使用这个方法获取资源,比其直接获取ID效率慢 * <p> * 例如 * getResources().getIdentifier("ic_launcher", "drawable", getPackageName()); * * @param context * @param name * @param defType * @return */ public static final int getResIdByName(Context context, String name, String defType) { return context.getResources().getIdentifier("ic_launcher", "drawable", context.getPackageName()); } public static boolean isFastClick(int millisecond) { long curClickTime = System.currentTimeMillis(); long interval = (curClickTime - lastClickTime); if (0 < interval && interval < millisecond) { // 超过点击间隔后再将lastClickTime重置为当前点击时间 return true; } lastClickTime = curClickTime; return false; } /** * Edittext 首位小数点自动加零,最多两位小数 * * @param editText */ public static void setEdTwoDecimal(EditText editText) { setEdDecimal(editText, 3); } public static void setEdDecimal(EditText editText, int count) { if (count < 1) { count = 1; } editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER); //设置 <SUF> final int finalCount = count; editText.setFilters(new InputFilter[]{new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (source.equals(".") && dest.toString().length() == 0) { return "0."; } if (dest.toString().contains(".")) { int index = dest.toString().indexOf("."); int mlength = dest.toString().substring(index).length(); if (mlength == finalCount) { return ""; } } return null; } }}); } public static void setEditNumberPrefix(final EditText edSerialNumber, final int number) { edSerialNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { String s = edSerialNumber.getText().toString(); String temp = ""; for (int i = s.length(); i < number; i++) { s = "0" + s; } for (int i = 0; i < number; i++) { temp += "0"; } if (s.equals(temp)) { s = temp.substring(1) + "1"; } edSerialNumber.setText(s); } } }); } private static final float BEEP_VOLUME = 0.50f; private static final int VIBRATE_DURATION = 200; private static boolean playBeep = false; private static MediaPlayer mediaPlayer; public static void playBeep(Activity mContext, boolean vibrate) { playBeep = true; AudioManager audioService = (AudioManager) mContext.getSystemService(AUDIO_SERVICE); if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) { playBeep = false; } if (playBeep && mediaPlayer != null) { mediaPlayer.start(); } else { mContext.setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.seekTo(0); } }); AssetFileDescriptor file = mContext.getResources().openRawResourceFd(R.raw.beep); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); file.close(); mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); } catch (IOException e) { mediaPlayer = null; } } if (vibrate) { vibrateOnce(mContext, VIBRATE_DURATION); } } private static Vibrator vibrator; /** * 简单震动 * @param context 调用震动的Context * @param millisecond 震动的时间,毫秒 */ @SuppressWarnings("static-access") public static void vibrateOnce(Context context, int millisecond) { vibrator = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE); vibrator.vibrate(millisecond); } /** * Resize the bitmap * * @param bitmap 图片引用 * @param width 宽度 * @param height 高度 * @return 缩放之后的图片引用 */ public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidth = ((float) width / w); float scaleHeight = ((float) height / h); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true); } public static Handler getBackgroundHandler() { HandlerThread thread = new HandlerThread("background"); thread.start(); Handler mBackgroundHandler = new Handler(thread.getLooper()); return mBackgroundHandler; } public static CoinType getDefaultCoin(){ List<CoinType> list = new CoinDao().queryAll(SpUtil.getInstance().getWalletID()); for (CoinType type: list) { if (type.getCoinIndex()==SpUtil.getInstance().getDefaultCoinIndex()){ return type; } } return new UbMain(); } }
0
2,535
4
2,853
4
2,945
4
2,852
4
3,620
9
false
false
false
false
false
true
16345_7
package com.xjtu.bookreader.bean.book; import android.databinding.BaseObservable; import com.xjtu.bookreader.http.ParamNames; import java.io.Serializable; /** * Created by jingbin on 2016/12/15. */ public class BooksBean extends BaseObservable implements Serializable { /** * rating : {"max":10,"numRaters":116375,"average":"7.9","min":0} * subtitle : * author : ["韩寒"] * pubdate : 2010-9 * tags : [{"count":38955,"name":"韩寒","title":"韩寒"},{"count":16343,"name":"小说","title":"小说"},{"count":12037,"name":"我想和这个世界谈谈","title":"我想和这个世界谈谈"},{"count":10674,"name":"公路小说","title":"公路小说"},{"count":6392,"name":"1988","title":"1988"},{"count":5868,"name":"中国文学","title":"中国文学"},{"count":5260,"name":"中国","title":"中国"},{"count":4730,"name":"文学","title":"文学"}] * origin_title : * image : https://img5.doubanio.com/mpic/s4477716.jpg * binding : 平装 * translator : [] * catalog : 曹操与刘备的一生 * pages : 215 * images : {"small":"https://img5.doubanio.com/spic/s4477716.jpg","large":"https://img5.doubanio.com/lpic/s4477716.jpg","medium":"https://img5.doubanio.com/mpic/s4477716.jpg"} * alt : https://book.douban.com/subject/5275059/ * id : 5275059 * publisher : 国际文化出版公司 * isbn10 : 751250098X * isbn13 : 9787512500983 * title : 1988:我想和这个世界谈谈 * url : https://api.douban.com/v2/book/5275059 * alt_title : * author_intro : 韩寒 1982年9月23日出生。作家,赛车手。已出版作品:《三重门》、《零下一度》、《像少年啦飞驰》、《通稿2003》、《毒》、《韩寒五年文集》、《长安乱》、《就这么漂来漂去》、《一座城池》、《寒》、《光荣日》、《杂的文》或有其他。 * summary : 系列主题:《我想和这个世界谈谈》 * 目前在韩寒主编的杂志《独唱团》中首度连载,这是韩寒预谋已久的一个系列,也是国内首度实际尝试“公路小说”这一概念的第一本——《1988》。 * 所谓“公路小说”就是以路途为载体反应人生观,现实观的小说。 * 如果说一件真正的艺术品的面世具有任何重大意义的话,韩寒新书的出版将会在中国创造一个历史事件,文章开头“空气越来越差,我必须上路了。我开着一台1988年出厂的旅行车,在说不清是迷雾还是毒气的夜色里拐上了318国道。”用一部旅行车为载体,通过在路上的见闻、过去的回忆、扑朔迷离的人物关系等各种现实场景,以韩寒本人对路上所见、所闻引发自己的观点,这场真正的旅途在精神层面;如果说似乎逾越了部分法律和道德的界限,但出发点也仅仅是希望在另一侧找到信仰。韩寒是“叛逆的”,他“试图用能给世界一些新意的眼光来看世界。试图寻找令人信服的价值”。他认为这一切通过文学都可以实现,产生了要创造一种批判现有一切社会习俗的“新幻象”的念头——《1988》就此问世。 * 目前“公路小说”的系列已经开始策划,韩寒的作品首当其冲,韩寒表示将会撰写三部作品与聚石文华联合打造“公路小说”这一品牌 * price : 25.00元 */ @ParamNames("id") // id private String id; @ParamNames("title") // 标题 private String title; @ParamNames("author") // 作者 private String author; @ParamNames("authorDescription") //作者介绍 private String authorDescription; @ParamNames("subtitle") // 副标题 private String subtitle; @ParamNames("subject") // 主题 private String subject; @ParamNames("description") // 概要 private String description; @ParamNames("publisher") //出版社 private String publisher; @ParamNames("pubdate") // 出版时间 private String pubDate; @ParamNames("coverImage") // 封面图片 private String coverImage; @ParamNames("rating") // 评分 private String rating; @ParamNames("pages") // 页数 private String pages; @ParamNames("isbn") // 标准书号 private String isbn; @ParamNames("payType") // 付费方式 (免费或者收费) private int payType; @ParamNames("price") // 价格 private String price; }
AotY/BookReader
app/src/main/java/com/xjtu/bookreader/bean/book/BooksBean.java
1,503
// 标准书号
line_comment
zh-cn
package com.xjtu.bookreader.bean.book; import android.databinding.BaseObservable; import com.xjtu.bookreader.http.ParamNames; import java.io.Serializable; /** * Created by jingbin on 2016/12/15. */ public class BooksBean extends BaseObservable implements Serializable { /** * rating : {"max":10,"numRaters":116375,"average":"7.9","min":0} * subtitle : * author : ["韩寒"] * pubdate : 2010-9 * tags : [{"count":38955,"name":"韩寒","title":"韩寒"},{"count":16343,"name":"小说","title":"小说"},{"count":12037,"name":"我想和这个世界谈谈","title":"我想和这个世界谈谈"},{"count":10674,"name":"公路小说","title":"公路小说"},{"count":6392,"name":"1988","title":"1988"},{"count":5868,"name":"中国文学","title":"中国文学"},{"count":5260,"name":"中国","title":"中国"},{"count":4730,"name":"文学","title":"文学"}] * origin_title : * image : https://img5.doubanio.com/mpic/s4477716.jpg * binding : 平装 * translator : [] * catalog : 曹操与刘备的一生 * pages : 215 * images : {"small":"https://img5.doubanio.com/spic/s4477716.jpg","large":"https://img5.doubanio.com/lpic/s4477716.jpg","medium":"https://img5.doubanio.com/mpic/s4477716.jpg"} * alt : https://book.douban.com/subject/5275059/ * id : 5275059 * publisher : 国际文化出版公司 * isbn10 : 751250098X * isbn13 : 9787512500983 * title : 1988:我想和这个世界谈谈 * url : https://api.douban.com/v2/book/5275059 * alt_title : * author_intro : 韩寒 1982年9月23日出生。作家,赛车手。已出版作品:《三重门》、《零下一度》、《像少年啦飞驰》、《通稿2003》、《毒》、《韩寒五年文集》、《长安乱》、《就这么漂来漂去》、《一座城池》、《寒》、《光荣日》、《杂的文》或有其他。 * summary : 系列主题:《我想和这个世界谈谈》 * 目前在韩寒主编的杂志《独唱团》中首度连载,这是韩寒预谋已久的一个系列,也是国内首度实际尝试“公路小说”这一概念的第一本——《1988》。 * 所谓“公路小说”就是以路途为载体反应人生观,现实观的小说。 * 如果说一件真正的艺术品的面世具有任何重大意义的话,韩寒新书的出版将会在中国创造一个历史事件,文章开头“空气越来越差,我必须上路了。我开着一台1988年出厂的旅行车,在说不清是迷雾还是毒气的夜色里拐上了318国道。”用一部旅行车为载体,通过在路上的见闻、过去的回忆、扑朔迷离的人物关系等各种现实场景,以韩寒本人对路上所见、所闻引发自己的观点,这场真正的旅途在精神层面;如果说似乎逾越了部分法律和道德的界限,但出发点也仅仅是希望在另一侧找到信仰。韩寒是“叛逆的”,他“试图用能给世界一些新意的眼光来看世界。试图寻找令人信服的价值”。他认为这一切通过文学都可以实现,产生了要创造一种批判现有一切社会习俗的“新幻象”的念头——《1988》就此问世。 * 目前“公路小说”的系列已经开始策划,韩寒的作品首当其冲,韩寒表示将会撰写三部作品与聚石文华联合打造“公路小说”这一品牌 * price : 25.00元 */ @ParamNames("id") // id private String id; @ParamNames("title") // 标题 private String title; @ParamNames("author") // 作者 private String author; @ParamNames("authorDescription") //作者介绍 private String authorDescription; @ParamNames("subtitle") // 副标题 private String subtitle; @ParamNames("subject") // 主题 private String subject; @ParamNames("description") // 概要 private String description; @ParamNames("publisher") //出版社 private String publisher; @ParamNames("pubdate") // 出版时间 private String pubDate; @ParamNames("coverImage") // 封面图片 private String coverImage; @ParamNames("rating") // 评分 private String rating; @ParamNames("pages") // 页数 private String pages; @ParamNames("isbn") // 标准 <SUF> private String isbn; @ParamNames("payType") // 付费方式 (免费或者收费) private int payType; @ParamNames("price") // 价格 private String price; }
0
1,269
6
1,503
5
1,329
5
1,503
5
1,909
8
false
false
false
false
false
true
27394_1
/* * Copyright (C) 2014 The AppCan Open Source Project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.zywx.wbpalmstar.platform.push; import java.io.Serializable; public class PushDataInfo implements Serializable { private static final long serialVersionUID = 1L; private String pushDataString; private int contentAvailable; //静默方式;透传(静默):1,通知:0 private String appId; private String taskId; private String title; private String alert; private int badge; private String[] remindType; //声音:sound,震动:shake,呼吸灯:breathe private String iconUrl; private String fontColor; private String behavior; private String tenantId; public PushDataInfo() { } public int getContentAvailable() { return contentAvailable; } public void setContentAvailable(int contentAvailable) { this.contentAvailable = contentAvailable; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAlert() { return alert; } public void setAlert(String alert) { this.alert = alert; } public String getPushDataString() { return pushDataString; } public void setPushDataString(String pushDataString) { this.pushDataString = pushDataString; } public int getBadge() { return badge; } public void setBadge(int badge) { this.badge = badge; } public String[] getRemindType() { return remindType; } public void setRemindType(String[] remindType) { this.remindType = remindType; } public String getIconUrl() { return iconUrl; } public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } public String getFontColor() { return fontColor; } public void setFontColor(String fontColor) { this.fontColor = fontColor; } public String getBehavior() { return behavior; } public void setBehavior(String behavior) { this.behavior = behavior; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
AppCanOpenSource/appcan-android
Engine/src/main/java/org/zywx/wbpalmstar/platform/push/PushDataInfo.java
779
//静默方式;透传(静默):1,通知:0
line_comment
zh-cn
/* * Copyright (C) 2014 The AppCan Open Source Project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.zywx.wbpalmstar.platform.push; import java.io.Serializable; public class PushDataInfo implements Serializable { private static final long serialVersionUID = 1L; private String pushDataString; private int contentAvailable; //静默 <SUF> private String appId; private String taskId; private String title; private String alert; private int badge; private String[] remindType; //声音:sound,震动:shake,呼吸灯:breathe private String iconUrl; private String fontColor; private String behavior; private String tenantId; public PushDataInfo() { } public int getContentAvailable() { return contentAvailable; } public void setContentAvailable(int contentAvailable) { this.contentAvailable = contentAvailable; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAlert() { return alert; } public void setAlert(String alert) { this.alert = alert; } public String getPushDataString() { return pushDataString; } public void setPushDataString(String pushDataString) { this.pushDataString = pushDataString; } public int getBadge() { return badge; } public void setBadge(int badge) { this.badge = badge; } public String[] getRemindType() { return remindType; } public void setRemindType(String[] remindType) { this.remindType = remindType; } public String getIconUrl() { return iconUrl; } public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } public String getFontColor() { return fontColor; } public void setFontColor(String fontColor) { this.fontColor = fontColor; } public String getBehavior() { return behavior; } public void setBehavior(String behavior) { this.behavior = behavior; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
0
733
17
779
17
854
16
779
17
988
25
false
false
false
false
false
true
26558_9
package com.testm; import java.net.URISyntaxException; import org.fusesource.mqtt.client.BlockingConnection; import org.fusesource.mqtt.client.Future; import org.fusesource.mqtt.client.FutureConnection; import org.fusesource.mqtt.client.MQTT; import org.fusesource.mqtt.client.Message; import org.fusesource.mqtt.client.QoS; import org.fusesource.mqtt.client.Topic; public class MClient { //private final static String CLIENT_ID = "publishService"; public static Topic[] topics = { new Topic("/beacons", QoS.AT_MOST_ONCE)}; //AT_LEAST_ONCE public static void main(String[] args) { //创建MQTT对象 MQTT mqtt = new MQTT(); try { //设置mqtt broker的ip和端口 mqtt.setHost("tcp://192.168.1.123:1883"); // 原来的值:876543210,用于设置客户端会话的ID。在setCleanSession(false);被调用时,MQTT服务器利用该ID获得相应的会话。此ID应少于23个字符,默认根据本机地址、端口和时间自动生成 mqtt.setClientId("beacons"); //连接前清空会话信息, 若设为false,MQTT服务器将持久化客户端会话的主体订阅和ACK位置,默认为true mqtt.setCleanSession(true); //设置重新连接的次数 mqtt.setReconnectAttemptsMax(6); //设置重连的间隔时间 mqtt.setReconnectDelay(2000); //设置心跳时间 mqtt.setKeepAlive((short)30); // 低耗网络,但是又需要及时获取数据,心跳30s //设置缓冲的大小 mqtt.setSendBufferSize(2*1024*1024); //发送最大缓冲为2M //获取mqtt的连接对象BlockingConnection // final FutureConnection connection= mqtt.futureConnection(); BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); if(connection.isConnected()){ System.out.println("连接成功"); }else{ System.out.println("连接失败"); } while(true){ Thread.sleep(2000); byte[] qoses = connection.subscribe(topics); Message message = connection.receive(); System.out.println("getTopic:"+message.getTopic()); byte[] payload = message.getPayload(); message.ack(); System.out.println("MQTTFutureClient.Receive Message "+ "Topic Title :"+message.getTopic()+" context :"+String.valueOf(message.getPayloadBuffer())); } } catch (URISyntaxException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }finally{ } } }
AprilBrother/mqtt-client-examples
java/MqttClient.java
723
//设置心跳时间
line_comment
zh-cn
package com.testm; import java.net.URISyntaxException; import org.fusesource.mqtt.client.BlockingConnection; import org.fusesource.mqtt.client.Future; import org.fusesource.mqtt.client.FutureConnection; import org.fusesource.mqtt.client.MQTT; import org.fusesource.mqtt.client.Message; import org.fusesource.mqtt.client.QoS; import org.fusesource.mqtt.client.Topic; public class MClient { //private final static String CLIENT_ID = "publishService"; public static Topic[] topics = { new Topic("/beacons", QoS.AT_MOST_ONCE)}; //AT_LEAST_ONCE public static void main(String[] args) { //创建MQTT对象 MQTT mqtt = new MQTT(); try { //设置mqtt broker的ip和端口 mqtt.setHost("tcp://192.168.1.123:1883"); // 原来的值:876543210,用于设置客户端会话的ID。在setCleanSession(false);被调用时,MQTT服务器利用该ID获得相应的会话。此ID应少于23个字符,默认根据本机地址、端口和时间自动生成 mqtt.setClientId("beacons"); //连接前清空会话信息, 若设为false,MQTT服务器将持久化客户端会话的主体订阅和ACK位置,默认为true mqtt.setCleanSession(true); //设置重新连接的次数 mqtt.setReconnectAttemptsMax(6); //设置重连的间隔时间 mqtt.setReconnectDelay(2000); //设置 <SUF> mqtt.setKeepAlive((short)30); // 低耗网络,但是又需要及时获取数据,心跳30s //设置缓冲的大小 mqtt.setSendBufferSize(2*1024*1024); //发送最大缓冲为2M //获取mqtt的连接对象BlockingConnection // final FutureConnection connection= mqtt.futureConnection(); BlockingConnection connection = mqtt.blockingConnection(); connection.connect(); if(connection.isConnected()){ System.out.println("连接成功"); }else{ System.out.println("连接失败"); } while(true){ Thread.sleep(2000); byte[] qoses = connection.subscribe(topics); Message message = connection.receive(); System.out.println("getTopic:"+message.getTopic()); byte[] payload = message.getPayload(); message.ack(); System.out.println("MQTTFutureClient.Receive Message "+ "Topic Title :"+message.getTopic()+" context :"+String.valueOf(message.getPayloadBuffer())); } } catch (URISyntaxException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); }finally{ } } }
0
647
5
687
6
740
6
687
6
944
11
false
false
false
false
false
true
56221_0
package priv.linsu.game.life.simulator.model.domain.text; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class ConditionEqual { //岁数 private Integer age; //体质 private Integer constitution; //智力 private Integer intelligence; //运气 private Integer luck; //容貌 private Integer appearance; //财富 private Integer wealth; //权力 private Integer power; //时间节点 private Integer currentId; private String status; private String talent; }
ArcherLinsu/life-simulator
server/src/main/java/priv/linsu/game/life/simulator/model/domain/text/ConditionEqual.java
192
//时间节点
line_comment
zh-cn
package priv.linsu.game.life.simulator.model.domain.text; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public class ConditionEqual { //岁数 private Integer age; //体质 private Integer constitution; //智力 private Integer intelligence; //运气 private Integer luck; //容貌 private Integer appearance; //财富 private Integer wealth; //权力 private Integer power; //时间 <SUF> private Integer currentId; private String status; private String talent; }
0
155
2
192
3
199
3
192
3
241
5
false
false
false
false
false
true
45523_7
package com.ecust.equsys.domain.vessel.vesselperiodic; import com.ecust.equsys.domain.vessel.VesselBaseEntity; public class VesselPeneTest extends VesselBaseEntity { public static VesselPeneTest vesselPeneTest = null; public VesselPeneTest() { super(); this.db_Description = "渗透检测记录"; this.method = "updateVesselPermTest";//上传servlet的方法名称,很重要 } public static VesselPeneTest getInstance() { if (vesselPeneTest == null) { vesselPeneTest = new VesselPeneTest(); } return vesselPeneTest; } public String v_Perm_JFC;//渗透剂型号 public String v_Perm_Surface;//表面状况 public String v_Perm_Clean;//清洗剂型号 public String v_Perm_Tem;//环境温度 public String v_Perm_Image;//显像剂型号 public String v_Perm_Contrast;//对比试块及编号 public String v_Perm_JFC_Time;//渗透时间 public String v_Perm_Image_Time;//显像时间 public String v_Perm_Cri;//检测标准 public String v_Perm_Len;//检测比例、长度 public String v_Perm_Value;// public String v_Perm_Result;// public String v_Perm_Date;//检测 public String v_Perm_Check_Date;//校对 @Override public String toString() { return "VesselPeneTest{" + "v_Perm_JFC='" + v_Perm_JFC + '\'' + ", v_Perm_Surface='" + v_Perm_Surface + '\'' + ", v_Perm_Clean='" + v_Perm_Clean + '\'' + ", v_Perm_Tem='" + v_Perm_Tem + '\'' + ", v_Perm_Image='" + v_Perm_Image + '\'' + ", v_Perm_Contrast='" + v_Perm_Contrast + '\'' + ", v_Perm_JFC_Time='" + v_Perm_JFC_Time + '\'' + ", v_Perm_Image_Time='" + v_Perm_Image_Time + '\'' + ", v_Perm_Cri='" + v_Perm_Cri + '\'' + ", v_Perm_Len='" + v_Perm_Len + '\'' + ", v_Perm_Value='" + v_Perm_Value + '\'' + ", v_Perm_Result='" + v_Perm_Result + '\'' + ", v_Perm_Date='" + v_Perm_Date + '\'' + ", v_Perm_Check_Date='" + v_Perm_Check_Date + '\'' + '}'; } }
ArexChu/SSEI_KT
equManSysForScan/src/main/java/com/ecust/equsys/domain/vessel/vesselperiodic/VesselPeneTest.java
683
//渗透时间
line_comment
zh-cn
package com.ecust.equsys.domain.vessel.vesselperiodic; import com.ecust.equsys.domain.vessel.VesselBaseEntity; public class VesselPeneTest extends VesselBaseEntity { public static VesselPeneTest vesselPeneTest = null; public VesselPeneTest() { super(); this.db_Description = "渗透检测记录"; this.method = "updateVesselPermTest";//上传servlet的方法名称,很重要 } public static VesselPeneTest getInstance() { if (vesselPeneTest == null) { vesselPeneTest = new VesselPeneTest(); } return vesselPeneTest; } public String v_Perm_JFC;//渗透剂型号 public String v_Perm_Surface;//表面状况 public String v_Perm_Clean;//清洗剂型号 public String v_Perm_Tem;//环境温度 public String v_Perm_Image;//显像剂型号 public String v_Perm_Contrast;//对比试块及编号 public String v_Perm_JFC_Time;//渗透 <SUF> public String v_Perm_Image_Time;//显像时间 public String v_Perm_Cri;//检测标准 public String v_Perm_Len;//检测比例、长度 public String v_Perm_Value;// public String v_Perm_Result;// public String v_Perm_Date;//检测 public String v_Perm_Check_Date;//校对 @Override public String toString() { return "VesselPeneTest{" + "v_Perm_JFC='" + v_Perm_JFC + '\'' + ", v_Perm_Surface='" + v_Perm_Surface + '\'' + ", v_Perm_Clean='" + v_Perm_Clean + '\'' + ", v_Perm_Tem='" + v_Perm_Tem + '\'' + ", v_Perm_Image='" + v_Perm_Image + '\'' + ", v_Perm_Contrast='" + v_Perm_Contrast + '\'' + ", v_Perm_JFC_Time='" + v_Perm_JFC_Time + '\'' + ", v_Perm_Image_Time='" + v_Perm_Image_Time + '\'' + ", v_Perm_Cri='" + v_Perm_Cri + '\'' + ", v_Perm_Len='" + v_Perm_Len + '\'' + ", v_Perm_Value='" + v_Perm_Value + '\'' + ", v_Perm_Result='" + v_Perm_Result + '\'' + ", v_Perm_Date='" + v_Perm_Date + '\'' + ", v_Perm_Check_Date='" + v_Perm_Check_Date + '\'' + '}'; } }
0
575
3
683
5
640
4
683
5
846
9
false
false
false
false
false
true
60828_2
package cn.argento.askia.entry; import java.lang.reflect.Array; import java.net.InetAddress; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; public class UserBean { // 数字 private int number; // 字符串 protected String address; protected String name; // 不转json的字段 private transient int age; // 逻辑值 boolean isGrow; // 数组 double[] flag; // 对象 @JavaBean public Country country; public List<String> skillList; // null private InetAddress nullObj; public List<String> getSkillList() { return skillList; } public void setSkillList(List<String> skillList) { this.skillList = skillList; } public UserBean(int number, String address, String name, int age, boolean isGrow, double[] flag, Country country, List<String> skillList) { this.number = number; this.address = address; this.name = name; this.age = age; this.isGrow = isGrow; this.flag = flag; this.country = country; this.skillList = skillList; } public UserBean() { } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isGrow() { return isGrow; } public void setGrow(boolean grow) { isGrow = grow; } public double[] getFlag() { return flag; } public void setFlag(double[] flag) { this.flag = flag; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } @Override public String toString() { final StringBuffer sb = new StringBuffer("UserBean{"); sb.append("number=").append(number); sb.append(", address='").append(address).append('\''); sb.append(", name='").append(name).append('\''); sb.append(", age=").append(age); sb.append(", isGrow=").append(isGrow); sb.append(", flag="); if (flag == null) sb.append("null"); else { sb.append('['); for (int i = 0; i < flag.length; ++i) sb.append(i == 0 ? "" : ", ").append(flag[i]); sb.append(']'); } sb.append(", country=").append(country); sb.append(", skillList=").append(skillList); sb.append(", nullObj=").append(nullObj); sb.append('}'); return sb.toString(); } public static UserBean newBean(){ // String[] countries = new String[]{"美国", "中国", "日本", "新加坡", "俄罗斯", "白俄罗斯", "缅甸", "蒙古", "墨西哥"}; Random random = new Random(); UserBean userBean = new UserBean(); userBean.setAddress("XXX省XXX市XXX镇XXXXX"); userBean.setAge(random.nextInt(100)); Country country = new Country(); country.setNow(LocalDateTime.now()); country.setZoneId(ZoneId.systemDefault()); country.setCountryName(ZoneId.systemDefault().getId()); userBean.setCountry(country); userBean.setFlag(new double[]{2.5f, 3.6f, 4.8f, 5.1f, 3.9f}); userBean.setGrow(random.nextBoolean()); userBean.setName(UUID.randomUUID().toString()); userBean.setNumber(random.nextInt(300)); userBean.setSkillList(new ArrayList<>(Arrays.asList("C++", "Java", "C"))); return userBean; } }
ArgentoAskia/JavaTutorial
Java-Json/src/main/java/cn/argento/askia/entry/UserBean.java
1,019
// 逻辑值
line_comment
zh-cn
package cn.argento.askia.entry; import java.lang.reflect.Array; import java.net.InetAddress; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; public class UserBean { // 数字 private int number; // 字符串 protected String address; protected String name; // 不转json的字段 private transient int age; // 逻辑 <SUF> boolean isGrow; // 数组 double[] flag; // 对象 @JavaBean public Country country; public List<String> skillList; // null private InetAddress nullObj; public List<String> getSkillList() { return skillList; } public void setSkillList(List<String> skillList) { this.skillList = skillList; } public UserBean(int number, String address, String name, int age, boolean isGrow, double[] flag, Country country, List<String> skillList) { this.number = number; this.address = address; this.name = name; this.age = age; this.isGrow = isGrow; this.flag = flag; this.country = country; this.skillList = skillList; } public UserBean() { } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isGrow() { return isGrow; } public void setGrow(boolean grow) { isGrow = grow; } public double[] getFlag() { return flag; } public void setFlag(double[] flag) { this.flag = flag; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } @Override public String toString() { final StringBuffer sb = new StringBuffer("UserBean{"); sb.append("number=").append(number); sb.append(", address='").append(address).append('\''); sb.append(", name='").append(name).append('\''); sb.append(", age=").append(age); sb.append(", isGrow=").append(isGrow); sb.append(", flag="); if (flag == null) sb.append("null"); else { sb.append('['); for (int i = 0; i < flag.length; ++i) sb.append(i == 0 ? "" : ", ").append(flag[i]); sb.append(']'); } sb.append(", country=").append(country); sb.append(", skillList=").append(skillList); sb.append(", nullObj=").append(nullObj); sb.append('}'); return sb.toString(); } public static UserBean newBean(){ // String[] countries = new String[]{"美国", "中国", "日本", "新加坡", "俄罗斯", "白俄罗斯", "缅甸", "蒙古", "墨西哥"}; Random random = new Random(); UserBean userBean = new UserBean(); userBean.setAddress("XXX省XXX市XXX镇XXXXX"); userBean.setAge(random.nextInt(100)); Country country = new Country(); country.setNow(LocalDateTime.now()); country.setZoneId(ZoneId.systemDefault()); country.setCountryName(ZoneId.systemDefault().getId()); userBean.setCountry(country); userBean.setFlag(new double[]{2.5f, 3.6f, 4.8f, 5.1f, 3.9f}); userBean.setGrow(random.nextBoolean()); userBean.setName(UUID.randomUUID().toString()); userBean.setNumber(random.nextInt(300)); userBean.setSkillList(new ArrayList<>(Arrays.asList("C++", "Java", "C"))); return userBean; } }
0
900
4
1,019
4
1,096
4
1,019
4
1,229
9
false
false
false
false
false
true
51312_6
package lab14; import java.util.*; //import junit.framework.Assert; public class MAx { int maxdata = Integer.MAX_VALUE; int[][] capacity; int[] flow; int[] pre; int n; Queue<Integer> queue; public MAx(int[][] capacity) { this.capacity = capacity; this.n = capacity.length; this.pre = new int[n]; } //广度优先遍历的查找一条src到des的路径 int BFS(int src, int des) { int i; this.queue = new LinkedList<Integer>(); this.flow = new int[n]; for (i = 0; i < n; ++i) { pre[i] = -1; } pre[src] = -2; flow[src] = maxdata; queue.add(src); while (!queue.isEmpty()) { int index = queue.poll(); if (index == des) //找到了增广路径 break; for (i = 0; i < n; ++i) { //找到非源节点未被访问过的可达结点,计算其流量 if (i != src && capacity[index][i] > 0 && pre[i] == -1) { pre[i] = index; //记录前驱 flow[i] = Math.min(capacity[index][i], flow[index]); //关键:迭代的找到增量 queue.add(i); } } } if (pre[des] == -1) //残留图中不再存在增广路径 return -1; else return flow[des]; } int maxFlow(int src, int des) { int increasement = 0; int sumflow = 0; while ((increasement = BFS(src, des)) != -1) { int k = des; //利用前驱寻找路径 while (k != src) { int last = pre[k]; capacity[last][k] -= increasement; //改变正向边的容量 capacity[k][last] += increasement; //改变反向边的容量 k = last; } System.out.println("-------改变后---------"); // for(int j=0;j<n;j++) // { // for(int x=0;x<n;x++) // { // System.out.print("---"+capacity[j][x]); // } // System.out.println(); // } sumflow += increasement; } return sumflow; } public static void main(String args[]) { int[][] matrix = new int[4][4]; matrix[0][1] = 4; matrix[0][3] = 2; matrix[1][2] = 3; matrix[1][3] = 2; matrix[2][3] = 1; MAx edm = new MAx(matrix); System.out.println("-------初始化---------"); // for (int j = 0; j < edm.n; j++) { // for (int k = 0; k < edm.n; k++) { // System.out.print("---" + edm.capacity[j][k]); // } // System.out.println(); // } int actual = edm.maxFlow(0, 3); int expected = 5; // System.out.println("-------最终结果---------"); // for (int j = 0; j < edm.n; j++) { // for (int k = 0; k < edm.n; k++) { // System.out.print("---" + edm.capacity[j][k]); // } // System.out.println(); // } } }
Aries-Dawn/CS208-Algorithm-Design-and-Analysis
src/lab14/MAx.java
931
//残留图中不再存在增广路径
line_comment
zh-cn
package lab14; import java.util.*; //import junit.framework.Assert; public class MAx { int maxdata = Integer.MAX_VALUE; int[][] capacity; int[] flow; int[] pre; int n; Queue<Integer> queue; public MAx(int[][] capacity) { this.capacity = capacity; this.n = capacity.length; this.pre = new int[n]; } //广度优先遍历的查找一条src到des的路径 int BFS(int src, int des) { int i; this.queue = new LinkedList<Integer>(); this.flow = new int[n]; for (i = 0; i < n; ++i) { pre[i] = -1; } pre[src] = -2; flow[src] = maxdata; queue.add(src); while (!queue.isEmpty()) { int index = queue.poll(); if (index == des) //找到了增广路径 break; for (i = 0; i < n; ++i) { //找到非源节点未被访问过的可达结点,计算其流量 if (i != src && capacity[index][i] > 0 && pre[i] == -1) { pre[i] = index; //记录前驱 flow[i] = Math.min(capacity[index][i], flow[index]); //关键:迭代的找到增量 queue.add(i); } } } if (pre[des] == -1) //残留 <SUF> return -1; else return flow[des]; } int maxFlow(int src, int des) { int increasement = 0; int sumflow = 0; while ((increasement = BFS(src, des)) != -1) { int k = des; //利用前驱寻找路径 while (k != src) { int last = pre[k]; capacity[last][k] -= increasement; //改变正向边的容量 capacity[k][last] += increasement; //改变反向边的容量 k = last; } System.out.println("-------改变后---------"); // for(int j=0;j<n;j++) // { // for(int x=0;x<n;x++) // { // System.out.print("---"+capacity[j][x]); // } // System.out.println(); // } sumflow += increasement; } return sumflow; } public static void main(String args[]) { int[][] matrix = new int[4][4]; matrix[0][1] = 4; matrix[0][3] = 2; matrix[1][2] = 3; matrix[1][3] = 2; matrix[2][3] = 1; MAx edm = new MAx(matrix); System.out.println("-------初始化---------"); // for (int j = 0; j < edm.n; j++) { // for (int k = 0; k < edm.n; k++) { // System.out.print("---" + edm.capacity[j][k]); // } // System.out.println(); // } int actual = edm.maxFlow(0, 3); int expected = 5; // System.out.println("-------最终结果---------"); // for (int j = 0; j < edm.n; j++) { // for (int k = 0; k < edm.n; k++) { // System.out.print("---" + edm.capacity[j][k]); // } // System.out.println(); // } } }
0
805
10
909
13
967
11
909
13
1,091
22
false
false
false
false
false
true
15116_3
package com.aries.smart.impl; import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import com.aries.library.fast.i.FastObserverControl; import com.aries.library.fast.i.FastRecyclerViewControl; import com.aries.library.fast.i.IFastRefreshLoadView; import com.aries.library.fast.i.LoadMoreFoot; import com.aries.library.fast.i.LoadingDialog; import com.aries.library.fast.i.MultiStatusView; import com.aries.library.fast.i.QuitAppControl; import com.aries.library.fast.i.TitleBarViewControl; import com.aries.library.fast.i.ToastControl; import com.aries.library.fast.manager.LoggerManager; import com.aries.library.fast.retrofit.FastNullException; import com.aries.library.fast.retrofit.FastObserver; import com.aries.library.fast.util.FastStackUtil; import com.aries.library.fast.util.SizeUtil; import com.aries.library.fast.util.ToastUtil; import com.aries.library.fast.widget.FastLoadDialog; import com.aries.library.fast.widget.FastLoadMoreView; import com.aries.smart.R; import com.aries.ui.util.DrawableUtil; import com.aries.ui.util.StatusBarUtil; import com.aries.ui.view.radius.RadiusTextView; import com.aries.ui.view.title.TitleBarView; import com.aries.ui.widget.progress.UIProgressDialog; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.animation.ScaleInAnimation; import com.chad.library.adapter.base.loadmore.BaseLoadMoreView; import com.scwang.smart.refresh.header.MaterialHeader; import com.scwang.smart.refresh.layout.api.RefreshHeader; import com.scwang.smart.refresh.layout.api.RefreshLayout; import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator; import me.bakumon.statuslayoutmanager.library.StatusLayoutManager; /** * @Author: AriesHoo on 2018/7/30 11:34 * @E-Mail: AriesHoo@126.com * Function: 应用全局配置管理实现 * Description: * 1、新增友盟统计功能对接 */ public class AppImpl implements DefaultRefreshHeaderCreator, LoadMoreFoot, FastRecyclerViewControl, MultiStatusView, LoadingDialog, TitleBarViewControl, QuitAppControl, ToastControl, FastObserverControl { private Context mContext; private String TAG = this.getClass().getSimpleName(); public AppImpl(@Nullable Context context) { this.mContext = context; } /** * 下拉刷新头配置 * * @param context * @param layout * @return */ @NonNull @Override public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) { layout.setEnableHeaderTranslationContent(false) .setPrimaryColorsId(R.color.colorAccent) .setEnableOverScrollDrag(false); MaterialHeader materialHeader = new MaterialHeader(mContext); materialHeader.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorTextBlack), ContextCompat.getColor(mContext, R.color.colorTextBlackLight)); return materialHeader; } /** * Adapter加载更多配置 * * @param adapter * @return */ @Nullable @Override public BaseLoadMoreView createDefaultLoadMoreView(BaseQuickAdapter adapter) { if (adapter != null) { //设置动画是否一直开启 adapter.setAnimationFirstOnly(false); //设置动画 adapter.setAdapterAnimation(new ScaleInAnimation()); adapter.setAnimationEnable(true); } //方式一:设置FastLoadMoreView--可参考FastLoadMoreView.Builder相应set方法 //默认配置请参考FastLoadMoreView.Builder(mContext)里初始化 return new FastLoadMoreView.Builder(mContext) .setLoadingTextFakeBold(true) .setLoadingSize(SizeUtil.dp2px(20)) // .setLoadTextColor(Color.MAGENTA) // //设置Loading 颜色-5.0以上有效 // .setLoadingProgressColor(Color.MAGENTA) // //设置Loading drawable--会使Loading颜色失效 // .setLoadingProgressDrawable(R.drawable.dialog_loading_wei_bo) // //设置全局TextView颜色 // .setLoadTextColor(Color.MAGENTA) // //设置全局TextView文字字号 // .setLoadTextSize(SizeUtil.dp2px(14)) // .setLoadingText("努力加载中...") // .setLoadingTextColor(Color.GREEN) // .setLoadingTextSize(SizeUtil.dp2px(14)) // .setLoadEndText("我是有底线的") // .setLoadEndTextColor(Color.GREEN) // .setLoadEndTextSize(SizeUtil.dp2px(14)) // .setLoadFailText("哇哦!出错了") // .setLoadFailTextColor(Color.RED) // .setLoadFailTextSize(SizeUtil.dp2px(14)) .build(); //方式二:使用adapter自带--其实我默认设置的和这个基本一致只是提供了相应设置方法 // return new SimpleLoadMoreView(); //方式三:参考SimpleLoadMoreView或FastLoadMoreView完全自定义自己的LoadMoreView // return MyLoadMoreView(); } /** * 全局设置 * * @param recyclerView * @param cls */ @Override public void setRecyclerView(RecyclerView recyclerView, Class<?> cls) { LoggerManager.i(TAG, "setRecyclerView-" + cls.getSimpleName() + "context:" + recyclerView.getContext() + ";:" + (Activity.class.isAssignableFrom(recyclerView.getContext().getClass())) + ";:" + (recyclerView.getContext() instanceof Activity)); } @Override public void setMultiStatusView(StatusLayoutManager.Builder statusView, IFastRefreshLoadView iFastRefreshLoadView) { } /** * 这里将局部设置的FastLoadDialog 抛至该处用于全局设置,在局部使用{@link com.aries.library.fast.retrofit.FastLoadingObserver} * * @param activity * @return */ @Nullable @Override public FastLoadDialog createLoadingDialog(@Nullable Activity activity) { return new FastLoadDialog(activity, new UIProgressDialog.WeBoBuilder(activity) .setMessage("加载中") .create()) .setCanceledOnTouchOutside(false) .setMessage("请求数据中,请稍候..."); //注意使用UIProgressDialog时最好在Builder里设置提示文字setMessage不然后续再设置文字信息也不会显示 // return new FastLoadDialog(activity, new UIProgressDialog.WeChatBuilder(activity) // .setBackgroundColor(Color.parseColor("#FCFCFC")) //// .setMinHeight(SizeUtil.dp2px(140)) //// .setMinWidth(SizeUtil.dp2px(270)) // .setTextSizeUnit(TypedValue.COMPLEX_UNIT_PX) // .setMessage(R.string.fast_loading) // .setLoadingSize(SizeUtil.dp2px(30)) // .setTextSize(SizeUtil.dp2px(16f)) // .setTextPadding(SizeUtil.dp2px(10)) // .setTextColorResource(R.color.colorTextGray) // .setIndeterminateDrawable(FastUtil.getTintDrawable(ContextCompat.getDrawable(mContext, R.drawable.dialog_loading), ContextCompat.getColor(mContext, R.color.colorTitleText))) // .setBackgroundRadius(SizeUtil.dp2px(6f)) // .create()); // Dialog dialog = new PictureDialog(activity); // return new FastLoadDialog(activity, dialog) // .setCancelable(true) // .setCanceledOnTouchOutside(true); } /** * 控制全局TitleBarView * * @param titleBar * @return */ @Override public boolean createTitleBarViewControl(TitleBarView titleBar, Class<?> cls) { //默认的MD风格返回箭头icon如使用该风格可以不用设置 Drawable mDrawable = DrawableUtil.setTintDrawable(ContextCompat.getDrawable(mContext, R.drawable.fast_ic_back), ContextCompat.getColor(mContext, R.color.colorTitleText)); //是否支持状态栏白色 boolean isSupport = StatusBarUtil.isSupportStatusBarFontChange(); boolean isActivity = Activity.class.isAssignableFrom(cls); Activity activity = FastStackUtil.getInstance().getActivity(cls); //设置TitleBarView 所有TextView颜色 titleBar.setStatusBarLightMode(isSupport) //不支持黑字的设置白透明 .setStatusAlpha(isSupport ? 0 : 102) .setLeftTextDrawable(isActivity ? mDrawable : null) .setDividerHeight(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? SizeUtil.dp2px(0.5f) : 0); if (activity != null) { titleBar.setTitleMainText(activity.getTitle()) .setOnLeftTextClickListener(new View.OnClickListener() { @Override public void onClick(View v) { activity.finish(); } }); } return false; } /** * @param isFirst 是否首次提示 * @param activity 操作的Activity * @return 延迟间隔--如不需要设置两次提示可设置0--最佳方式是直接在回调中执行你想要的操作 */ @Override public long quipApp(boolean isFirst, Activity activity) { //默认配置 if (isFirst) { ToastUtil.show(R.string.fast_quit_app); } else { FastStackUtil.getInstance().exit(false); } return 2000; } @Override public Toast getToast() { return null; } @Override public void setToast(Toast toast, RadiusTextView textView) { } /** * @param o {@link FastObserver} 对象用于后续事件逻辑 * @param e 原始错误 * @return true 拦截操作不进行原始{@link FastObserver#onError(Throwable)}后续逻辑 * false 不拦截继续后续逻辑 * {@link FastNullException} 已在{@link FastObserver#onError} }处理如果为该类型Exception可不用管,参考 */ @Override public boolean onError(FastObserver o, Throwable e) { return false; } }
AriesHoo/FastLib
template/src/main/java/com/aries/smart/impl/AppImpl.java
2,618
//设置动画是否一直开启
line_comment
zh-cn
package com.aries.smart.impl; import android.app.Activity; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import com.aries.library.fast.i.FastObserverControl; import com.aries.library.fast.i.FastRecyclerViewControl; import com.aries.library.fast.i.IFastRefreshLoadView; import com.aries.library.fast.i.LoadMoreFoot; import com.aries.library.fast.i.LoadingDialog; import com.aries.library.fast.i.MultiStatusView; import com.aries.library.fast.i.QuitAppControl; import com.aries.library.fast.i.TitleBarViewControl; import com.aries.library.fast.i.ToastControl; import com.aries.library.fast.manager.LoggerManager; import com.aries.library.fast.retrofit.FastNullException; import com.aries.library.fast.retrofit.FastObserver; import com.aries.library.fast.util.FastStackUtil; import com.aries.library.fast.util.SizeUtil; import com.aries.library.fast.util.ToastUtil; import com.aries.library.fast.widget.FastLoadDialog; import com.aries.library.fast.widget.FastLoadMoreView; import com.aries.smart.R; import com.aries.ui.util.DrawableUtil; import com.aries.ui.util.StatusBarUtil; import com.aries.ui.view.radius.RadiusTextView; import com.aries.ui.view.title.TitleBarView; import com.aries.ui.widget.progress.UIProgressDialog; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.animation.ScaleInAnimation; import com.chad.library.adapter.base.loadmore.BaseLoadMoreView; import com.scwang.smart.refresh.header.MaterialHeader; import com.scwang.smart.refresh.layout.api.RefreshHeader; import com.scwang.smart.refresh.layout.api.RefreshLayout; import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator; import me.bakumon.statuslayoutmanager.library.StatusLayoutManager; /** * @Author: AriesHoo on 2018/7/30 11:34 * @E-Mail: AriesHoo@126.com * Function: 应用全局配置管理实现 * Description: * 1、新增友盟统计功能对接 */ public class AppImpl implements DefaultRefreshHeaderCreator, LoadMoreFoot, FastRecyclerViewControl, MultiStatusView, LoadingDialog, TitleBarViewControl, QuitAppControl, ToastControl, FastObserverControl { private Context mContext; private String TAG = this.getClass().getSimpleName(); public AppImpl(@Nullable Context context) { this.mContext = context; } /** * 下拉刷新头配置 * * @param context * @param layout * @return */ @NonNull @Override public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) { layout.setEnableHeaderTranslationContent(false) .setPrimaryColorsId(R.color.colorAccent) .setEnableOverScrollDrag(false); MaterialHeader materialHeader = new MaterialHeader(mContext); materialHeader.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorTextBlack), ContextCompat.getColor(mContext, R.color.colorTextBlackLight)); return materialHeader; } /** * Adapter加载更多配置 * * @param adapter * @return */ @Nullable @Override public BaseLoadMoreView createDefaultLoadMoreView(BaseQuickAdapter adapter) { if (adapter != null) { //设置 <SUF> adapter.setAnimationFirstOnly(false); //设置动画 adapter.setAdapterAnimation(new ScaleInAnimation()); adapter.setAnimationEnable(true); } //方式一:设置FastLoadMoreView--可参考FastLoadMoreView.Builder相应set方法 //默认配置请参考FastLoadMoreView.Builder(mContext)里初始化 return new FastLoadMoreView.Builder(mContext) .setLoadingTextFakeBold(true) .setLoadingSize(SizeUtil.dp2px(20)) // .setLoadTextColor(Color.MAGENTA) // //设置Loading 颜色-5.0以上有效 // .setLoadingProgressColor(Color.MAGENTA) // //设置Loading drawable--会使Loading颜色失效 // .setLoadingProgressDrawable(R.drawable.dialog_loading_wei_bo) // //设置全局TextView颜色 // .setLoadTextColor(Color.MAGENTA) // //设置全局TextView文字字号 // .setLoadTextSize(SizeUtil.dp2px(14)) // .setLoadingText("努力加载中...") // .setLoadingTextColor(Color.GREEN) // .setLoadingTextSize(SizeUtil.dp2px(14)) // .setLoadEndText("我是有底线的") // .setLoadEndTextColor(Color.GREEN) // .setLoadEndTextSize(SizeUtil.dp2px(14)) // .setLoadFailText("哇哦!出错了") // .setLoadFailTextColor(Color.RED) // .setLoadFailTextSize(SizeUtil.dp2px(14)) .build(); //方式二:使用adapter自带--其实我默认设置的和这个基本一致只是提供了相应设置方法 // return new SimpleLoadMoreView(); //方式三:参考SimpleLoadMoreView或FastLoadMoreView完全自定义自己的LoadMoreView // return MyLoadMoreView(); } /** * 全局设置 * * @param recyclerView * @param cls */ @Override public void setRecyclerView(RecyclerView recyclerView, Class<?> cls) { LoggerManager.i(TAG, "setRecyclerView-" + cls.getSimpleName() + "context:" + recyclerView.getContext() + ";:" + (Activity.class.isAssignableFrom(recyclerView.getContext().getClass())) + ";:" + (recyclerView.getContext() instanceof Activity)); } @Override public void setMultiStatusView(StatusLayoutManager.Builder statusView, IFastRefreshLoadView iFastRefreshLoadView) { } /** * 这里将局部设置的FastLoadDialog 抛至该处用于全局设置,在局部使用{@link com.aries.library.fast.retrofit.FastLoadingObserver} * * @param activity * @return */ @Nullable @Override public FastLoadDialog createLoadingDialog(@Nullable Activity activity) { return new FastLoadDialog(activity, new UIProgressDialog.WeBoBuilder(activity) .setMessage("加载中") .create()) .setCanceledOnTouchOutside(false) .setMessage("请求数据中,请稍候..."); //注意使用UIProgressDialog时最好在Builder里设置提示文字setMessage不然后续再设置文字信息也不会显示 // return new FastLoadDialog(activity, new UIProgressDialog.WeChatBuilder(activity) // .setBackgroundColor(Color.parseColor("#FCFCFC")) //// .setMinHeight(SizeUtil.dp2px(140)) //// .setMinWidth(SizeUtil.dp2px(270)) // .setTextSizeUnit(TypedValue.COMPLEX_UNIT_PX) // .setMessage(R.string.fast_loading) // .setLoadingSize(SizeUtil.dp2px(30)) // .setTextSize(SizeUtil.dp2px(16f)) // .setTextPadding(SizeUtil.dp2px(10)) // .setTextColorResource(R.color.colorTextGray) // .setIndeterminateDrawable(FastUtil.getTintDrawable(ContextCompat.getDrawable(mContext, R.drawable.dialog_loading), ContextCompat.getColor(mContext, R.color.colorTitleText))) // .setBackgroundRadius(SizeUtil.dp2px(6f)) // .create()); // Dialog dialog = new PictureDialog(activity); // return new FastLoadDialog(activity, dialog) // .setCancelable(true) // .setCanceledOnTouchOutside(true); } /** * 控制全局TitleBarView * * @param titleBar * @return */ @Override public boolean createTitleBarViewControl(TitleBarView titleBar, Class<?> cls) { //默认的MD风格返回箭头icon如使用该风格可以不用设置 Drawable mDrawable = DrawableUtil.setTintDrawable(ContextCompat.getDrawable(mContext, R.drawable.fast_ic_back), ContextCompat.getColor(mContext, R.color.colorTitleText)); //是否支持状态栏白色 boolean isSupport = StatusBarUtil.isSupportStatusBarFontChange(); boolean isActivity = Activity.class.isAssignableFrom(cls); Activity activity = FastStackUtil.getInstance().getActivity(cls); //设置TitleBarView 所有TextView颜色 titleBar.setStatusBarLightMode(isSupport) //不支持黑字的设置白透明 .setStatusAlpha(isSupport ? 0 : 102) .setLeftTextDrawable(isActivity ? mDrawable : null) .setDividerHeight(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP ? SizeUtil.dp2px(0.5f) : 0); if (activity != null) { titleBar.setTitleMainText(activity.getTitle()) .setOnLeftTextClickListener(new View.OnClickListener() { @Override public void onClick(View v) { activity.finish(); } }); } return false; } /** * @param isFirst 是否首次提示 * @param activity 操作的Activity * @return 延迟间隔--如不需要设置两次提示可设置0--最佳方式是直接在回调中执行你想要的操作 */ @Override public long quipApp(boolean isFirst, Activity activity) { //默认配置 if (isFirst) { ToastUtil.show(R.string.fast_quit_app); } else { FastStackUtil.getInstance().exit(false); } return 2000; } @Override public Toast getToast() { return null; } @Override public void setToast(Toast toast, RadiusTextView textView) { } /** * @param o {@link FastObserver} 对象用于后续事件逻辑 * @param e 原始错误 * @return true 拦截操作不进行原始{@link FastObserver#onError(Throwable)}后续逻辑 * false 不拦截继续后续逻辑 * {@link FastNullException} 已在{@link FastObserver#onError} }处理如果为该类型Exception可不用管,参考 */ @Override public boolean onError(FastObserver o, Throwable e) { return false; } }
0
2,237
6
2,618
6
2,642
6
2,618
6
3,222
13
false
false
false
false
false
true
29186_8
/** * Capability.java */ package artiano.core.structure; import java.util.HashSet; import java.util.Iterator; /** * 表示处理能力的类。 * <p> * 这种“能力”表示仅限于对数据实例的处理。默认情况下,构造的本类实例 不具备任何实例处理能力,你可能需要手工添加。 * </p> * * @author Nano.Michael * @version 1.0.0 * @date 2013-12-16 * @author (latest modification by Nano.Michael) * @since 1.0.0 */ public class Capability { /** 属性处理能力 */ protected HashSet<Class<?>> attCapabilities = new HashSet<>(); /** 类属性处理能力 */ protected HashSet<Class<?>> classCapabilities = new HashSet<>(); /** 是否允许属性值有缺失 */ protected boolean allowAttMissing = false; /** 是否允许类属性值有缺失 */ protected boolean allowClsMissing = false; /** 最少实例数 ,未设定为负数 */ protected int minInstaces = -1; /** 不能处理的原因 */ protected String failReason = null; /** * 构造一个不具备任何“能力”的实例 */ public Capability() { disableAll(); } /** * 使用给定的“能力”构造一个实例 * * @param c * 指定实例 */ public Capability(Capability c) { this(); or(c); } /** * 设定是否允许属性值有缺失 * * @param allowMissing * 是否允许属性值缺失 */ public void allowAttributeMissing(boolean allowMissing) { this.allowAttMissing = allowMissing; } /** * 设定是否允许类属性值有缺失 * * @param allowMissing * 是否允许类属性值缺失 */ public void allowClassMissing(boolean allowMissing) { this.allowClsMissing = allowMissing; } /** * 设置最小能处理实例数 * * @param min * 最小实例数 */ public void setMinimumInstances(int min) { this.minInstaces = min; } /** * 获取能处理的最小实例数 * * @return 能处理的最小实例数 */ public int minimumInstacnes() { return this.minInstaces; } /** * 当使用方法{@link #handles(Table)}对表数据集进行测试失败的原因,如果当前“能力”具备 处理待测试的表,则此方法返回 * {@code null} * * @return 测试失败原因 */ public String failReason() { return failReason; } /** * 获取属性处理能力<br> * <b><i>NOTICE:</b></i> 值得注意的是,如果当前“能力”具备类属性处理能力,则当前类属性 类型将被排除在属性“能力”集合中 * * @return 属性处理能力 */ public Iterator<Class<?>> attributeCapabilities() { return attCapabilities.iterator(); } /** * 获取类属性处理能力集合 * * @return 类属性处理能力 */ public Iterator<Class<?>> classCapabilities() { return classCapabilities.iterator(); } /** * 开启对某个属性的“能力”<br> * <b><i>NOTICE:</b></i> 指定属性不包括类属性 * * @param att * 属性类型 */ public void enableAttribute(Class<?> att) { attCapabilities.add(att); } /** * 禁用对某个属性的“能力”<br> * <b><i>NOTICE:</b></i>如果本类实例中并不包含这个类的“能力”,将不做任何处理 * * @param att * 属性类型 */ public void disableAttribute(Class<?> att) { attCapabilities.remove(att); } /** * 开启对指定类属性的“能力” * * @param att * 属性类型 */ public void enableClass(Class<?> att) { classCapabilities.add(att); } /** * 禁用对指定类属性的能力 * * @param att * 指定属性类型 */ public void disableClass(Class<?> att) { classCapabilities.remove(att); } /** * 禁用所有能力 */ public void disableAll() { attCapabilities.clear(); classCapabilities.clear(); allowAttMissing = false; allowClsMissing = false; } /** * 判断当前能力是否支持指定能力 * * @param cap * 指定能力 * @return 若支持返回{@code true} */ public boolean supports(Capability cap) { // attribute capabilities for (Iterator<Class<?>> it = cap.attributeCapabilities(); it.hasNext();) if (!handlesAttribute(it.next())) return false; // class capabilities for (Iterator<Class<?>> it = cap.classCapabilities(); it.hasNext();) if (!handlesClass(it.next())) return false; // allow attribute missing ? if (!allowAttMissing && cap.allowAttMissing) return false; // allow class attribute missing ? if (!allowClsMissing && cap.allowClsMissing) return false; // minimum instances if (minInstaces < cap.minInstaces) return false; // pass all tests return true; } /** * 判断是否具有处理某个类的处理能力 * * @param att * 指定的类 * @return 若具备指定类的处理能力则返回{@code true} */ public boolean handlesAttribute(Class<?> att) { return attCapabilities.contains(att); } /** * 判断是否具有处理指定类属性的能力 * * @param att * 指定属性类型 * @return 若具备指定属性的能力则返回{@code true} */ public boolean handlesClass(Class<?> att) { return classCapabilities.contains(att); } /** * 判断是否具备处理某个表的能力 * * @param t * 待判断的表 * @return 如果能处理则返回{@code true} */ public boolean handles(Table t) { // class is set ? if (!classCapabilities.isEmpty() && !t.hasClass()) { failReason = "Class is not set!"; return false; } // attributes capabilities for (Iterator<Attribute> it = t.attributesIterator(); it.hasNext();) { Attribute att = it.next(); // not the class attribute if (!t.isClassAttribute(att)) { // can handle ? if (!handlesAttribute(att.getClass())) { failReason = "Can't handle [" + att.getName() + ":" + att.getType() + "] attributes" + " in the table " + t.getName() + "."; return false; } // allow missing ? if (!allowAttMissing && att.hasMissing()) { failReason = "Missing values in attributes " + att.getName() + " is not allowed."; return false; } } } // class capabilities if (!classCapabilities.isEmpty() && t.hasClass()) { Attribute att = t.classAttribute(); // can handle the class attribute ? if (!handlesClass(att.getClass())) { failReason = "Can't handle [" + att.getType() + "] class.\n"; return false; } // allow class value missing ? if (!allowClsMissing && att.hasMissing()) { failReason = "Missing value in class attribute " + att.getName() + " is not allowed."; return false; } } // minimum instances if (t.rows() < minInstaces) { failReason = "Number of instances in the table " + t.getName() + " < minimum instances (=" + minInstaces + ") needed.\n"; return false; } // pass all tests return true; } /** * 与某个能力进行“或”运算 * * @param c * 指定的“能力” */ public void or(Capability c) { // attribute capabilities attCapabilities.addAll(c.attCapabilities); // class attribute capabilities classCapabilities.addAll(c.classCapabilities); // can handle missing values in attributes ? allowAttMissing = allowAttMissing || c.allowAttMissing; // can handle missing values in class ? allowClsMissing = allowClsMissing || c.allowClsMissing; // minimum instances minInstaces = minInstaces < c.minInstaces ? c.minInstaces : minInstaces; } /** * 与某个能力进行“与”运算 * * @param c * 指定“能力” */ public void and(Capability c) { // attribute capabilities for (Class<?> cs : attCapabilities) if (!(handlesAttribute(cs) && c.handlesAttribute(cs))) attCapabilities.remove(cs); // class attribute capabilities for (Class<?> cs : classCapabilities) if (!(handlesClass(cs) && c.handlesClass(cs))) classCapabilities.remove(cs); // can handle missing values in attributes ? allowAttMissing = allowAttMissing && c.allowAttMissing; // can handle missing values in class ? allowClsMissing = allowClsMissing && c.allowClsMissing; minInstaces = minInstaces < c.minInstaces ? minInstaces : c.minInstaces; } @Override public String toString() { StringBuffer sb = new StringBuffer(); // header sb.append("Capabilities:\n"); // attribute capabilities sb.append("#Attributes can handles:\n"); if (attCapabilities.isEmpty()) sb.append("\tNONE\n"); else { for (Iterator<Class<?>> it = attributeCapabilities(); it.hasNext();) { sb.append("\t<"); sb.append(it.next() + ">\n"); } } // class attribute capabilities sb.append("\n#Class can handles:\n"); if (classCapabilities.isEmpty()) sb.append("\tNONE\n"); else { for (Iterator<?> it = classCapabilities(); it.hasNext();) { sb.append("\t<"); sb.append(it.next() + ">\n"); } } sb.append("\n#Addtional:\n"); // allow attribute value missing ? sb.append("\tAllow missing values in attributes: " + allowAttMissing + "\n"); sb.append("\tAllow mssing values in class: " + allowClsMissing + "\n"); // minimum instances needed sb.append("\tMinimum instances needed: " + (minInstaces < 0 ? "Unrestricted" : minInstaces)); return sb.toString(); } public static void main(String[] args) { Capability capability = new Capability(); capability.enableAttribute(NumericAttribute.class); capability.enableAttribute(NominalAttribute.class); capability.enableClass(NominalAttribute.class); capability.allowAttributeMissing(true); capability.allowClassMissing(true); System.out.println(capability); } }
Artiano/Artiano
src/artiano/core/structure/Capability.java
2,796
/** * 构造一个不具备任何“能力”的实例 */
block_comment
zh-cn
/** * Capability.java */ package artiano.core.structure; import java.util.HashSet; import java.util.Iterator; /** * 表示处理能力的类。 * <p> * 这种“能力”表示仅限于对数据实例的处理。默认情况下,构造的本类实例 不具备任何实例处理能力,你可能需要手工添加。 * </p> * * @author Nano.Michael * @version 1.0.0 * @date 2013-12-16 * @author (latest modification by Nano.Michael) * @since 1.0.0 */ public class Capability { /** 属性处理能力 */ protected HashSet<Class<?>> attCapabilities = new HashSet<>(); /** 类属性处理能力 */ protected HashSet<Class<?>> classCapabilities = new HashSet<>(); /** 是否允许属性值有缺失 */ protected boolean allowAttMissing = false; /** 是否允许类属性值有缺失 */ protected boolean allowClsMissing = false; /** 最少实例数 ,未设定为负数 */ protected int minInstaces = -1; /** 不能处理的原因 */ protected String failReason = null; /** * 构造一 <SUF>*/ public Capability() { disableAll(); } /** * 使用给定的“能力”构造一个实例 * * @param c * 指定实例 */ public Capability(Capability c) { this(); or(c); } /** * 设定是否允许属性值有缺失 * * @param allowMissing * 是否允许属性值缺失 */ public void allowAttributeMissing(boolean allowMissing) { this.allowAttMissing = allowMissing; } /** * 设定是否允许类属性值有缺失 * * @param allowMissing * 是否允许类属性值缺失 */ public void allowClassMissing(boolean allowMissing) { this.allowClsMissing = allowMissing; } /** * 设置最小能处理实例数 * * @param min * 最小实例数 */ public void setMinimumInstances(int min) { this.minInstaces = min; } /** * 获取能处理的最小实例数 * * @return 能处理的最小实例数 */ public int minimumInstacnes() { return this.minInstaces; } /** * 当使用方法{@link #handles(Table)}对表数据集进行测试失败的原因,如果当前“能力”具备 处理待测试的表,则此方法返回 * {@code null} * * @return 测试失败原因 */ public String failReason() { return failReason; } /** * 获取属性处理能力<br> * <b><i>NOTICE:</b></i> 值得注意的是,如果当前“能力”具备类属性处理能力,则当前类属性 类型将被排除在属性“能力”集合中 * * @return 属性处理能力 */ public Iterator<Class<?>> attributeCapabilities() { return attCapabilities.iterator(); } /** * 获取类属性处理能力集合 * * @return 类属性处理能力 */ public Iterator<Class<?>> classCapabilities() { return classCapabilities.iterator(); } /** * 开启对某个属性的“能力”<br> * <b><i>NOTICE:</b></i> 指定属性不包括类属性 * * @param att * 属性类型 */ public void enableAttribute(Class<?> att) { attCapabilities.add(att); } /** * 禁用对某个属性的“能力”<br> * <b><i>NOTICE:</b></i>如果本类实例中并不包含这个类的“能力”,将不做任何处理 * * @param att * 属性类型 */ public void disableAttribute(Class<?> att) { attCapabilities.remove(att); } /** * 开启对指定类属性的“能力” * * @param att * 属性类型 */ public void enableClass(Class<?> att) { classCapabilities.add(att); } /** * 禁用对指定类属性的能力 * * @param att * 指定属性类型 */ public void disableClass(Class<?> att) { classCapabilities.remove(att); } /** * 禁用所有能力 */ public void disableAll() { attCapabilities.clear(); classCapabilities.clear(); allowAttMissing = false; allowClsMissing = false; } /** * 判断当前能力是否支持指定能力 * * @param cap * 指定能力 * @return 若支持返回{@code true} */ public boolean supports(Capability cap) { // attribute capabilities for (Iterator<Class<?>> it = cap.attributeCapabilities(); it.hasNext();) if (!handlesAttribute(it.next())) return false; // class capabilities for (Iterator<Class<?>> it = cap.classCapabilities(); it.hasNext();) if (!handlesClass(it.next())) return false; // allow attribute missing ? if (!allowAttMissing && cap.allowAttMissing) return false; // allow class attribute missing ? if (!allowClsMissing && cap.allowClsMissing) return false; // minimum instances if (minInstaces < cap.minInstaces) return false; // pass all tests return true; } /** * 判断是否具有处理某个类的处理能力 * * @param att * 指定的类 * @return 若具备指定类的处理能力则返回{@code true} */ public boolean handlesAttribute(Class<?> att) { return attCapabilities.contains(att); } /** * 判断是否具有处理指定类属性的能力 * * @param att * 指定属性类型 * @return 若具备指定属性的能力则返回{@code true} */ public boolean handlesClass(Class<?> att) { return classCapabilities.contains(att); } /** * 判断是否具备处理某个表的能力 * * @param t * 待判断的表 * @return 如果能处理则返回{@code true} */ public boolean handles(Table t) { // class is set ? if (!classCapabilities.isEmpty() && !t.hasClass()) { failReason = "Class is not set!"; return false; } // attributes capabilities for (Iterator<Attribute> it = t.attributesIterator(); it.hasNext();) { Attribute att = it.next(); // not the class attribute if (!t.isClassAttribute(att)) { // can handle ? if (!handlesAttribute(att.getClass())) { failReason = "Can't handle [" + att.getName() + ":" + att.getType() + "] attributes" + " in the table " + t.getName() + "."; return false; } // allow missing ? if (!allowAttMissing && att.hasMissing()) { failReason = "Missing values in attributes " + att.getName() + " is not allowed."; return false; } } } // class capabilities if (!classCapabilities.isEmpty() && t.hasClass()) { Attribute att = t.classAttribute(); // can handle the class attribute ? if (!handlesClass(att.getClass())) { failReason = "Can't handle [" + att.getType() + "] class.\n"; return false; } // allow class value missing ? if (!allowClsMissing && att.hasMissing()) { failReason = "Missing value in class attribute " + att.getName() + " is not allowed."; return false; } } // minimum instances if (t.rows() < minInstaces) { failReason = "Number of instances in the table " + t.getName() + " < minimum instances (=" + minInstaces + ") needed.\n"; return false; } // pass all tests return true; } /** * 与某个能力进行“或”运算 * * @param c * 指定的“能力” */ public void or(Capability c) { // attribute capabilities attCapabilities.addAll(c.attCapabilities); // class attribute capabilities classCapabilities.addAll(c.classCapabilities); // can handle missing values in attributes ? allowAttMissing = allowAttMissing || c.allowAttMissing; // can handle missing values in class ? allowClsMissing = allowClsMissing || c.allowClsMissing; // minimum instances minInstaces = minInstaces < c.minInstaces ? c.minInstaces : minInstaces; } /** * 与某个能力进行“与”运算 * * @param c * 指定“能力” */ public void and(Capability c) { // attribute capabilities for (Class<?> cs : attCapabilities) if (!(handlesAttribute(cs) && c.handlesAttribute(cs))) attCapabilities.remove(cs); // class attribute capabilities for (Class<?> cs : classCapabilities) if (!(handlesClass(cs) && c.handlesClass(cs))) classCapabilities.remove(cs); // can handle missing values in attributes ? allowAttMissing = allowAttMissing && c.allowAttMissing; // can handle missing values in class ? allowClsMissing = allowClsMissing && c.allowClsMissing; minInstaces = minInstaces < c.minInstaces ? minInstaces : c.minInstaces; } @Override public String toString() { StringBuffer sb = new StringBuffer(); // header sb.append("Capabilities:\n"); // attribute capabilities sb.append("#Attributes can handles:\n"); if (attCapabilities.isEmpty()) sb.append("\tNONE\n"); else { for (Iterator<Class<?>> it = attributeCapabilities(); it.hasNext();) { sb.append("\t<"); sb.append(it.next() + ">\n"); } } // class attribute capabilities sb.append("\n#Class can handles:\n"); if (classCapabilities.isEmpty()) sb.append("\tNONE\n"); else { for (Iterator<?> it = classCapabilities(); it.hasNext();) { sb.append("\t<"); sb.append(it.next() + ">\n"); } } sb.append("\n#Addtional:\n"); // allow attribute value missing ? sb.append("\tAllow missing values in attributes: " + allowAttMissing + "\n"); sb.append("\tAllow mssing values in class: " + allowClsMissing + "\n"); // minimum instances needed sb.append("\tMinimum instances needed: " + (minInstaces < 0 ? "Unrestricted" : minInstaces)); return sb.toString(); } public static void main(String[] args) { Capability capability = new Capability(); capability.enableAttribute(NumericAttribute.class); capability.enableAttribute(NominalAttribute.class); capability.enableClass(NominalAttribute.class); capability.allowAttributeMissing(true); capability.allowClassMissing(true); System.out.println(capability); } }
0
2,550
16
2,792
17
2,837
17
2,792
17
3,714
28
false
false
false
false
false
true
24191_4
package Auth.token; import Auth.api.ApiRequest; import Auth.utils.SHAUtils; /** * @desc: token 有关,负责 token 的生成、解析 * @author: AruNi_Lu * @date: 2023/3/21 */ public class AuthToken { private static final long DEFAULT_EXPIRED_TIME_INTERVAL = 1 * 5 * 1000; private long createTime; private String token; private long expiredTimeInterval; public AuthToken(long createTime, String token, long expiredTimeInterval) { this.createTime = createTime; this.token = token; this.expiredTimeInterval = expiredTimeInterval; } public AuthToken(long createTime, String token) { this(createTime, token, DEFAULT_EXPIRED_TIME_INTERVAL); } /** * 使用默认的失效时间间隔 DEFAULT_EXPIRED_TIME_INTERVAL 生成 AuthToken * @param baseUrl * @param appId * @param password * @param timestamp 生成 token 时的时间戳 * @return */ public static AuthToken creatAuthToken(String baseUrl, String appId, String password, long timestamp) { String token = generateToken(baseUrl, appId, password, timestamp); return new AuthToken(timestamp, token); } /** * 使用自定义的失效时间间隔 expiredTimeInterval 生成 AuthToken * @param baseUrl * @param appId * @param password * @param timestamp 生成 token 时的时间戳 * @param expiredTimeInterval 自定义的失效时间间隔 * @return */ public static AuthToken creatAuthToken(String baseUrl, String appId, String password, long timestamp, long expiredTimeInterval) { String token = generateToken(baseUrl, appId, password, timestamp); return new AuthToken(timestamp, token, expiredTimeInterval); } /** * 加密生成 token */ public static String generateToken(String baseUrl, String appId, String password, long timestamp) { StringBuilder sb = new StringBuilder(); sb.append(baseUrl) .append("&").append("appId").append("=").append(appId) .append("&").append("password").append("=").append(password) .append("&").append("timestamp").append("=").append(timestamp); return SHAUtils.SHA(sb.toString()); } /** * 判断是否超过失效时间间隔 */ public boolean isExpired() { return (System.currentTimeMillis() - this.createTime) > this.expiredTimeInterval; } /** * 判断两个 token 是否是否匹配 */ public boolean match(AuthToken authToken) { return this.token.equals(authToken.token); } public long getCreateTime() { return createTime; } public String getToken() { return token; } public long getExpiredTimeInterval() { return expiredTimeInterval; } }
AruNi-01/DesignPattern
oop/src/Auth/token/AuthToken.java
654
/** * 判断是否超过失效时间间隔 */
block_comment
zh-cn
package Auth.token; import Auth.api.ApiRequest; import Auth.utils.SHAUtils; /** * @desc: token 有关,负责 token 的生成、解析 * @author: AruNi_Lu * @date: 2023/3/21 */ public class AuthToken { private static final long DEFAULT_EXPIRED_TIME_INTERVAL = 1 * 5 * 1000; private long createTime; private String token; private long expiredTimeInterval; public AuthToken(long createTime, String token, long expiredTimeInterval) { this.createTime = createTime; this.token = token; this.expiredTimeInterval = expiredTimeInterval; } public AuthToken(long createTime, String token) { this(createTime, token, DEFAULT_EXPIRED_TIME_INTERVAL); } /** * 使用默认的失效时间间隔 DEFAULT_EXPIRED_TIME_INTERVAL 生成 AuthToken * @param baseUrl * @param appId * @param password * @param timestamp 生成 token 时的时间戳 * @return */ public static AuthToken creatAuthToken(String baseUrl, String appId, String password, long timestamp) { String token = generateToken(baseUrl, appId, password, timestamp); return new AuthToken(timestamp, token); } /** * 使用自定义的失效时间间隔 expiredTimeInterval 生成 AuthToken * @param baseUrl * @param appId * @param password * @param timestamp 生成 token 时的时间戳 * @param expiredTimeInterval 自定义的失效时间间隔 * @return */ public static AuthToken creatAuthToken(String baseUrl, String appId, String password, long timestamp, long expiredTimeInterval) { String token = generateToken(baseUrl, appId, password, timestamp); return new AuthToken(timestamp, token, expiredTimeInterval); } /** * 加密生成 token */ public static String generateToken(String baseUrl, String appId, String password, long timestamp) { StringBuilder sb = new StringBuilder(); sb.append(baseUrl) .append("&").append("appId").append("=").append(appId) .append("&").append("password").append("=").append(password) .append("&").append("timestamp").append("=").append(timestamp); return SHAUtils.SHA(sb.toString()); } /** * 判断是 <SUF>*/ public boolean isExpired() { return (System.currentTimeMillis() - this.createTime) > this.expiredTimeInterval; } /** * 判断两个 token 是否是否匹配 */ public boolean match(AuthToken authToken) { return this.token.equals(authToken.token); } public long getCreateTime() { return createTime; } public String getToken() { return token; } public long getExpiredTimeInterval() { return expiredTimeInterval; } }
0
606
13
654
13
692
13
654
13
851
22
false
false
false
false
false
true
5837_31
package com.sf.request; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import com.sf.entity.ordertableEntity; import com.sf.entity.userEntity; import com.sf.service.impl.LoginServiceImpl; import com.sf.service.impl.UserListServiceImpl; import com.sf.tool.GetDataTime; import com.sf.tool.GetUUID; @Controller public class LoginRequest { @Autowired LoginServiceImpl loginServiceImpl; @Autowired UserListServiceImpl userListServiceImpl; @RequestMapping("loginservice.sf") public String web3(String userName,String passWord,HttpServletRequest request){ boolean bl= loginServiceImpl.loginuser(userName, passWord); if(bl){ //将用户的全部信息查询出来 userEntity list = userListServiceImpl.userlist(userName); //request.setAttribute("userlist", list); //成功 //将用户ID放到session里面 request.getSession().setAttribute("userID", list.getUserID()); request.getSession().setAttribute("userName", userName); request.getSession().setAttribute("userHand", list.getUserHand()); String mamaipi = "logoone.sf"; if(request.getSession().getAttribute("jiequ")!=null){ //说明这个地址是用户想访问的地址 但是没用登录 String ceshidizhi=(String) request.getSession().getAttribute("jiequ"); //重置为空 String jiequ = ""; request.getSession().setAttribute("jiequ", jiequ); //赋值 mamaipi = ceshidizhi; } return "redirect:/"+mamaipi; }else{ //失败 request.setAttribute("PHO", "用户名或密码错误!"); } return "loginnew"; } //AJAX 提交 @RequestMapping(value="yanzhengpass.sf",method=RequestMethod.POST,produces="text/html;charset=UTF-8") public @ResponseBody void yanzhengpass(HttpServletRequest request,HttpServletResponse response ,String pass,String zong,String shangpingmingzi,String shangpingtupiao,String dizhi) throws IOException{ //System.out.println(pass);"shangpingmingzi":shangpingmingzi,"shangpingtupiao":shangpingtupiao,"dizhi":dizhi //System.out.println(zong);//拿到物品的所有价格 String userName = (String) request.getSession().getAttribute("userName"); String list = ""; boolean bl = loginServiceImpl.paypassword(userName, pass); if(bl){ //拿到数据库里面的全部金额 userEntity user=userListServiceImpl.userlist(userName); //金额 String RMB=user.getUserRMB(); int shangpingjiage= 0; shangpingjiage=Integer.valueOf(zong).intValue();//商品价格 int sqljiage= 0; sqljiage=Integer.valueOf(RMB).intValue();//用户的钱 int yuer=sqljiage-shangpingjiage; if(yuer<0){ list="对不起,您的余额不足"; }else{ //将yuer转换为字符串然后保存数据库 String userRMB=""; userRMB=String.valueOf(yuer); //支付成功之后 将数据库里面的价格修改 boolean b = loginServiceImpl.updateRMB(userRMB, userName); if(b){ //得到下单时间 String Time = GetDataTime.DQtime(); //将订单存到数据库 ordertableEntity ordertable = new ordertableEntity(); ordertable.setOrderID(GetUUID.getUUID()); ordertable.setOrderuserName(userName); ordertable.setOrderIgridsName(shangpingmingzi); ordertable.setOrdergridsImg(shangpingtupiao); ordertable.setOrderzongRMB(zong); ordertable.setOrderStat("1"); ordertable.setOrderTime(Time); ordertable.setOrderAddr(dizhi); boolean yes= loginServiceImpl.ordertable(ordertable); if(yes){ list="下单成功"; }else{ list="服务器错误...请联系管理员!"; } }else{ list="服务器错误...请联系管理员!"; } } }else{ list="对不起,您输入的支付密码有误!"; } //设置编码 response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); Gson gson=new Gson(); String sbb=gson.toJson(list); out.write(sbb); } //这里是确认收货 @RequestMapping("querendingdan.sf") public String querendingdan(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.Confirmorder(orderID); if(bl){ //收货成功 //System.out.println("成功"); }else{ //收货失败 //System.out.println("失败"); } return "forward:/Order.sf"; } //这里是待取消订单 @RequestMapping("Cancellationoforder.sf") public String Cancellationoforder(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.Cancellationoforder(orderID); if(bl){ //收货成功 //System.out.println("待取消成功"); }else{ //收货失败 //System.out.println("待取消失败"); } return "forward:/Order.sf"; } //这里是用户删除的订单 @RequestMapping("delordertable.sf") public String delordertable(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.delordertable(orderID); if(bl){ //收货成功 //System.out.println("删除成功"); }else{ //收货失败 //System.out.println("删除失败"); } return "forward:/Order.sf"; } //这里是立即发货 @RequestMapping("Delivergoods.sf") public String Delivergoods(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.Delivergoods("2",orderID); if(bl){ }else{ } return "forward:/Shipmentpending"; } //这里是立即退货 @RequestMapping("Returngoods.sf") public String Returngoods(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.Delivergoods("5",orderID); if(bl){ }else{ } return "forward:/Returngoods"; } @RequestMapping("loginforum.sf") public String loginforum(String username,String password,HttpServletRequest request){ boolean bl= loginServiceImpl.loginuser(username, password); String sb = ""; if(bl){ //将用户的全部信息查询出来 userEntity list = userListServiceImpl.userlist(username); request.setAttribute("登录成功", sb); //成功 //将用户ID放到session里面 request.getSession().setAttribute("userID", list.getUserID()); request.getSession().setAttribute("userName", username); request.getSession().setAttribute("userHand", list.getUserHand()); }else{ request.setAttribute("登录失败", sb); return "forward:/forum.sf"; } return "forward:/forum.sf"; } }
ArvinZhangX/ssm_bilibili
src/main/java/com/sf/request/LoginRequest.java
1,962
//这里是立即发货
line_comment
zh-cn
package com.sf.request; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.google.gson.Gson; import com.sf.entity.ordertableEntity; import com.sf.entity.userEntity; import com.sf.service.impl.LoginServiceImpl; import com.sf.service.impl.UserListServiceImpl; import com.sf.tool.GetDataTime; import com.sf.tool.GetUUID; @Controller public class LoginRequest { @Autowired LoginServiceImpl loginServiceImpl; @Autowired UserListServiceImpl userListServiceImpl; @RequestMapping("loginservice.sf") public String web3(String userName,String passWord,HttpServletRequest request){ boolean bl= loginServiceImpl.loginuser(userName, passWord); if(bl){ //将用户的全部信息查询出来 userEntity list = userListServiceImpl.userlist(userName); //request.setAttribute("userlist", list); //成功 //将用户ID放到session里面 request.getSession().setAttribute("userID", list.getUserID()); request.getSession().setAttribute("userName", userName); request.getSession().setAttribute("userHand", list.getUserHand()); String mamaipi = "logoone.sf"; if(request.getSession().getAttribute("jiequ")!=null){ //说明这个地址是用户想访问的地址 但是没用登录 String ceshidizhi=(String) request.getSession().getAttribute("jiequ"); //重置为空 String jiequ = ""; request.getSession().setAttribute("jiequ", jiequ); //赋值 mamaipi = ceshidizhi; } return "redirect:/"+mamaipi; }else{ //失败 request.setAttribute("PHO", "用户名或密码错误!"); } return "loginnew"; } //AJAX 提交 @RequestMapping(value="yanzhengpass.sf",method=RequestMethod.POST,produces="text/html;charset=UTF-8") public @ResponseBody void yanzhengpass(HttpServletRequest request,HttpServletResponse response ,String pass,String zong,String shangpingmingzi,String shangpingtupiao,String dizhi) throws IOException{ //System.out.println(pass);"shangpingmingzi":shangpingmingzi,"shangpingtupiao":shangpingtupiao,"dizhi":dizhi //System.out.println(zong);//拿到物品的所有价格 String userName = (String) request.getSession().getAttribute("userName"); String list = ""; boolean bl = loginServiceImpl.paypassword(userName, pass); if(bl){ //拿到数据库里面的全部金额 userEntity user=userListServiceImpl.userlist(userName); //金额 String RMB=user.getUserRMB(); int shangpingjiage= 0; shangpingjiage=Integer.valueOf(zong).intValue();//商品价格 int sqljiage= 0; sqljiage=Integer.valueOf(RMB).intValue();//用户的钱 int yuer=sqljiage-shangpingjiage; if(yuer<0){ list="对不起,您的余额不足"; }else{ //将yuer转换为字符串然后保存数据库 String userRMB=""; userRMB=String.valueOf(yuer); //支付成功之后 将数据库里面的价格修改 boolean b = loginServiceImpl.updateRMB(userRMB, userName); if(b){ //得到下单时间 String Time = GetDataTime.DQtime(); //将订单存到数据库 ordertableEntity ordertable = new ordertableEntity(); ordertable.setOrderID(GetUUID.getUUID()); ordertable.setOrderuserName(userName); ordertable.setOrderIgridsName(shangpingmingzi); ordertable.setOrdergridsImg(shangpingtupiao); ordertable.setOrderzongRMB(zong); ordertable.setOrderStat("1"); ordertable.setOrderTime(Time); ordertable.setOrderAddr(dizhi); boolean yes= loginServiceImpl.ordertable(ordertable); if(yes){ list="下单成功"; }else{ list="服务器错误...请联系管理员!"; } }else{ list="服务器错误...请联系管理员!"; } } }else{ list="对不起,您输入的支付密码有误!"; } //设置编码 response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); Gson gson=new Gson(); String sbb=gson.toJson(list); out.write(sbb); } //这里是确认收货 @RequestMapping("querendingdan.sf") public String querendingdan(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.Confirmorder(orderID); if(bl){ //收货成功 //System.out.println("成功"); }else{ //收货失败 //System.out.println("失败"); } return "forward:/Order.sf"; } //这里是待取消订单 @RequestMapping("Cancellationoforder.sf") public String Cancellationoforder(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.Cancellationoforder(orderID); if(bl){ //收货成功 //System.out.println("待取消成功"); }else{ //收货失败 //System.out.println("待取消失败"); } return "forward:/Order.sf"; } //这里是用户删除的订单 @RequestMapping("delordertable.sf") public String delordertable(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.delordertable(orderID); if(bl){ //收货成功 //System.out.println("删除成功"); }else{ //收货失败 //System.out.println("删除失败"); } return "forward:/Order.sf"; } //这里 <SUF> @RequestMapping("Delivergoods.sf") public String Delivergoods(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.Delivergoods("2",orderID); if(bl){ }else{ } return "forward:/Shipmentpending"; } //这里是立即退货 @RequestMapping("Returngoods.sf") public String Returngoods(HttpServletRequest request,String orderID) { boolean bl = loginServiceImpl.Delivergoods("5",orderID); if(bl){ }else{ } return "forward:/Returngoods"; } @RequestMapping("loginforum.sf") public String loginforum(String username,String password,HttpServletRequest request){ boolean bl= loginServiceImpl.loginuser(username, password); String sb = ""; if(bl){ //将用户的全部信息查询出来 userEntity list = userListServiceImpl.userlist(username); request.setAttribute("登录成功", sb); //成功 //将用户ID放到session里面 request.getSession().setAttribute("userID", list.getUserID()); request.getSession().setAttribute("userName", username); request.getSession().setAttribute("userHand", list.getUserHand()); }else{ request.setAttribute("登录失败", sb); return "forward:/forum.sf"; } return "forward:/forum.sf"; } }
0
1,663
4
1,962
7
2,021
4
1,962
7
2,901
12
false
false
false
false
false
true
24900_80
package so.asch.sdk; /** * Asch UIA接口 * @author eagle */ public interface UIA extends AschInterface { //获取全网所有发行商 //接口地址:/api/uia/issuers //请求方式:get //支持格式:urlencoded //请求参数说明: //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //issuers list 元素为字典,每个字典代表一个发行商,包含发行商名字、描述、id(Asch地址) //count integer 发行商总个数 AschResult getIssuers(int limit, int offset); //查询指定发行商的信息 //接口地址:/api/uia/issuers/name 请求方式:get //支持格式:urlencoded //请求参数说明: //name string Y 可以为发行商名称或Asch账户地址 //返回参数说明: //success boole 是否成功 //issuers dict 包含发行商名字、描述、id(Asch地址) AschResult getIssuer(String nameOrAddress); //查看指定发行商的资产 //接口地址:/api/uia/issuers/name/assets //请求方式:get //支持格式:urlencoded //请求参数说明: //name string Y 可以为发行商名称或Asch账户地址 //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //assets list 每个元素是一个字典,每个字典是一个资产详情,包含资产名字、描述、上限(最大发行量=真实发行量*10**精度)、精度、 // 策略、当前发行量、发行高度、发行商id,acl模式(0:黑名单,1:白名单)、是否注销 //count interger 该发行商注册的资产总个数(包含已注销的) AschResult queryIssuerAssets(String nameOrAddress, int limit, int offset); //获取全网所有资产 //接口地址:/api/uia/assets //请求方式:get //支持格式:urlencoded //请求参数说明: //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //assets list 每个元素是一个字典,每个字典是一个资产详情,包含资产名字、描述、上限、精度、策略、当前发行量、发行高度、发行商id,acl、是否注销 //count integer 所有资产的个数 AschResult getAssets(int limit, int offset); //获取指定资产信息 //接口地址:/api/uia/assets/name //请求方式:get //支持格式:urlencoded //请求参数说明: //name string Y 资产名 //返回参数说明: //success boole 是否成功 //assets dict 包含资产名字、描述、上限、精度、策略、当前发行量、发行高度、发行商id,acl、是否注销 AschResult getAsset(String assertName); //获取某个资产的访问控制列表(acl) //接口地址:/api/uia/assets/name/acl/flag 请求方式:get //支持格式:urlencoded //请求参数说明: //name string Y 资产名 //flag boole Y 取值0和1,0表示黑名单,1表示白名单 //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //list list 符合规则的账户列表 //count integer 符合规则账户总数 AschResult getAssetACL(String assertName, boolean whiteOrBlack, int limit, int offset); //获取某个地址拥有的所有资产信息 //接口地址:/api/uia/balances/address 请求方式:get //支持格式:urlencoded //请求参数说明: //address string Y 账户地址 //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //balances list 拥有的资产详情列表,每个元素是一个资产,包含资产名、余额、上限、精度、当前发行量、是否注销(0:未注销,1:已注销) //count integer 当前该地址拥有的资产个数 AschResult getAddressBalances(String address, int limit, int offset); //获取资产交易记录 //接口地址:/api/uia/transactions //请求方式:get //支持格式:urlencoded //请求参数说明: //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //ownerPublicKey string N 公钥 //返回参数说明: //success boole 是否成功 //transactions list 交易列表,每个元素是一个字典代表一次交易,包含交易id、区块高度、区块id、交易类型、时间戳、发送者公钥、发送者id、 // 接收者id(系统为空,如资产注册)、交易数量(资产交易都为0)、手续费0.1XAS、签名、多重签名、确认数、 // 资产信息(包含发行商id、发行商名字、描述)、交易id。 //count integer 资产交易总个数 AschResult getTransactions(String ownerPublicKey, int limit, int offset); //注册资产发行商 //请求参数说明: //name string Y 名称 //desc string Y 描述 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult createIssuer(String name, String desc, String secret, String secondSecret); //注册资产 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //desc string Y 资产描述 //maximum integer Y 上限 //precision integer Y 精度(maximum = '1000000',精度为3,代表资产IssuerName.CNY的最大发行量为1000.000) //strategy string Y 策略 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult createAsset(String currency, String desc, long maximum, byte precision, String strategy, String secret, String secondSecret); //资产设置acl模式 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //assertStatus(flagType) int Y 资产状态,1:流通,2:注销 (flagType) //whiteListMode(flag) boole Y 0:黑名单, 1:白名单,资产创建后默认为黑名单模式 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult setAssetACL(String currency, int assertStatus, boolean whiteListMode, String secret, String secondSecret); //资产发行 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //amount int Y 本次发行量,本次发行量=真实数量(100)*10**精度(3),所有发行量之和需 <= 上限*精度 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult issue(String currency, long amount, String secret, String secondSecret); //资产转账 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //amount int Y 本次发行量,本次发行量=真实数量(100)*10**精度(3),所有发行量之和需 <= 上限*精度 //recipientId string Y 接收人 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult transfer(String currency, String recipientId, long amount, String message, String secret, String secondSecret); //资产注销 //资产设置acl模式 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //assertStatus(flagType) int Y 资产状态,1:流通,2:注销 (flagType) //whiteListMode(flag) boole Y 0:黑名单, 1:白名单,资产创建后默认为黑名单模式 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult setAssetStatus(String currency, int assertStatus, boolean whiteListMode, String secret, String secondSecret); }
AschPlatform/asch-java
src/so/asch/sdk/UIA.java
2,422
//请求参数说明:
line_comment
zh-cn
package so.asch.sdk; /** * Asch UIA接口 * @author eagle */ public interface UIA extends AschInterface { //获取全网所有发行商 //接口地址:/api/uia/issuers //请求方式:get //支持格式:urlencoded //请求参数说明: //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //issuers list 元素为字典,每个字典代表一个发行商,包含发行商名字、描述、id(Asch地址) //count integer 发行商总个数 AschResult getIssuers(int limit, int offset); //查询指定发行商的信息 //接口地址:/api/uia/issuers/name 请求方式:get //支持格式:urlencoded //请求参数说明: //name string Y 可以为发行商名称或Asch账户地址 //返回参数说明: //success boole 是否成功 //issuers dict 包含发行商名字、描述、id(Asch地址) AschResult getIssuer(String nameOrAddress); //查看指定发行商的资产 //接口地址:/api/uia/issuers/name/assets //请求方式:get //支持格式:urlencoded //请求参数说明: //name string Y 可以为发行商名称或Asch账户地址 //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //assets list 每个元素是一个字典,每个字典是一个资产详情,包含资产名字、描述、上限(最大发行量=真实发行量*10**精度)、精度、 // 策略、当前发行量、发行高度、发行商id,acl模式(0:黑名单,1:白名单)、是否注销 //count interger 该发行商注册的资产总个数(包含已注销的) AschResult queryIssuerAssets(String nameOrAddress, int limit, int offset); //获取全网所有资产 //接口地址:/api/uia/assets //请求方式:get //支持格式:urlencoded //请求参数说明: //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //assets list 每个元素是一个字典,每个字典是一个资产详情,包含资产名字、描述、上限、精度、策略、当前发行量、发行高度、发行商id,acl、是否注销 //count integer 所有资产的个数 AschResult getAssets(int limit, int offset); //获取指定资产信息 //接口地址:/api/uia/assets/name //请求方式:get //支持格式:urlencoded //请求参数说明: //name string Y 资产名 //返回参数说明: //success boole 是否成功 //assets dict 包含资产名字、描述、上限、精度、策略、当前发行量、发行高度、发行商id,acl、是否注销 AschResult getAsset(String assertName); //获取某个资产的访问控制列表(acl) //接口地址:/api/uia/assets/name/acl/flag 请求方式:get //支持格式:urlencoded //请求参数说明: //name string Y 资产名 //flag boole Y 取值0和1,0表示黑名单,1表示白名单 //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //list list 符合规则的账户列表 //count integer 符合规则账户总数 AschResult getAssetACL(String assertName, boolean whiteOrBlack, int limit, int offset); //获取某个地址拥有的所有资产信息 //接口地址:/api/uia/balances/address 请求方式:get //支持格式:urlencoded //请求参数说明: //address string Y 账户地址 //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //返回参数说明: //success boole 是否成功 //balances list 拥有的资产详情列表,每个元素是一个资产,包含资产名、余额、上限、精度、当前发行量、是否注销(0:未注销,1:已注销) //count integer 当前该地址拥有的资产个数 AschResult getAddressBalances(String address, int limit, int offset); //获取资产交易记录 //接口地址:/api/uia/transactions //请求方式:get //支持格式:urlencoded //请求 <SUF> //limit integer N 限制结果集个数,最小值:0,最大值:100 //offset integer N 偏移量,最小值0 //ownerPublicKey string N 公钥 //返回参数说明: //success boole 是否成功 //transactions list 交易列表,每个元素是一个字典代表一次交易,包含交易id、区块高度、区块id、交易类型、时间戳、发送者公钥、发送者id、 // 接收者id(系统为空,如资产注册)、交易数量(资产交易都为0)、手续费0.1XAS、签名、多重签名、确认数、 // 资产信息(包含发行商id、发行商名字、描述)、交易id。 //count integer 资产交易总个数 AschResult getTransactions(String ownerPublicKey, int limit, int offset); //注册资产发行商 //请求参数说明: //name string Y 名称 //desc string Y 描述 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult createIssuer(String name, String desc, String secret, String secondSecret); //注册资产 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //desc string Y 资产描述 //maximum integer Y 上限 //precision integer Y 精度(maximum = '1000000',精度为3,代表资产IssuerName.CNY的最大发行量为1000.000) //strategy string Y 策略 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult createAsset(String currency, String desc, long maximum, byte precision, String strategy, String secret, String secondSecret); //资产设置acl模式 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //assertStatus(flagType) int Y 资产状态,1:流通,2:注销 (flagType) //whiteListMode(flag) boole Y 0:黑名单, 1:白名单,资产创建后默认为黑名单模式 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult setAssetACL(String currency, int assertStatus, boolean whiteListMode, String secret, String secondSecret); //资产发行 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //amount int Y 本次发行量,本次发行量=真实数量(100)*10**精度(3),所有发行量之和需 <= 上限*精度 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult issue(String currency, long amount, String secret, String secondSecret); //资产转账 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //amount int Y 本次发行量,本次发行量=真实数量(100)*10**精度(3),所有发行量之和需 <= 上限*精度 //recipientId string Y 接收人 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult transfer(String currency, String recipientId, long amount, String message, String secret, String secondSecret); //资产注销 //资产设置acl模式 //请求参数说明: //currency string Y 资产名称,发行商名.资产名,唯一标识,如:IssuerName.CNY //assertStatus(flagType) int Y 资产状态,1:流通,2:注销 (flagType) //whiteListMode(flag) boole Y 0:黑名单, 1:白名单,资产创建后默认为黑名单模式 //secret string Y 一级密码 //secondSecret string Y 二级密码 //返回参数说明: //success boole 是否成功 AschResult setAssetStatus(String currency, int assertStatus, boolean whiteListMode, String secret, String secondSecret); }
0
2,353
5
2,422
5
2,397
5
2,422
5
3,504
8
false
false
false
false
false
true
44165_11
package Game; import Thing.Square; import java.awt.*; import java.util.Timer; import java.util.TimerTask; public class Player { private final double walkSpeed = 16 / (double) (World.FPS);//一秒16格 private final double jumpSpeed = 0.5;//初始跳跃速度 private double verticalSpeed = 0;//实时垂直速度 private int hp = 10; private int vp = 10; private int dp = 0;//防御力 private Toolbar toolbar = new Toolbar(); private int handSquareNO = 0; private Square chosenSquare; private int chosenNumber; private Point.Double location;//玩家脚底中心坐标,决定从何处开始渲染 private boolean isLegSwing = true; Color head = Color.WHITE; Color body = Color.WHITE; Color arm = Color.WHITE; Color leg = Color.WHITE; int legSwing = 0;//腿部摆动的角度 int walkLeft = 0;//玩家是否在向左侧移动 int walkRight = 0;//玩家是否在向右侧移动 boolean isJumping = false;//玩家是否在跳跃 boolean isOpenBag = false;//玩家是否在查看背包 boolean isShowBorder = false;//显示放置范围 public int getChosenNumber() { return chosenNumber; } public void setChosenNumber(int chosenNumber) { this.chosenNumber = chosenNumber; } public synchronized Square getChosenSquare() { return chosenSquare; } public synchronized void setChosenSquare(Square chosenSquare) { this.chosenSquare = chosenSquare; } public synchronized void throwOutSquare() { if (toolbar.getNumber()[handSquareNO] > 1) toolbar.getNumber()[handSquareNO] -= 1; else { toolbar.getSquares()[handSquareNO] = null; toolbar.getNumber()[handSquareNO] = 0; } } public synchronized int getHandSquareNO() { return handSquareNO; } public synchronized Square getHandSquare() { return toolbar.getSquares()[handSquareNO]; } public synchronized void setHandSquare(int i) { handSquareNO = i; } public synchronized Point.Double getLocation() { return location; } public synchronized void setHp(int hp) { this.hp = hp; } public synchronized int getHp() { return hp; } public synchronized int getDp() { return dp; } public synchronized int getLegSwing() { return legSwing; } Toolbar getToolbar() { return toolbar; } private synchronized void setLegSwing() { if (isLegSwing) { legSwing += 1; if (legSwing == 6) isLegSwing = false; } else { legSwing -= 1; if (legSwing == 0) isLegSwing = true; } } public void setHeadColor(Color color) { head = color; } public void setBodyColor(Color color) { body = color; } public void setArmColor(Color color) { arm = color; } public void setLegColor(Color color) { leg = color; } public Player() { location = World.startLocation; } public void updatePlayer(){ int walk = walkRight - walkLeft; if (walk == -1) { double targetX = location.x - walkSpeed; Square square = World.worldSquare[(int) targetX][(int) location.y]; if (square == null) location.x = targetX; else { if (!square.through) location.x = Math.ceil(targetX); else location.x = targetX; } } else if (walk == 1) { double targetX = location.x + walkSpeed; Square square = World.worldSquare[(int) targetX][(int) location.y]; if (square == null) location.x = targetX; else { if (!square.through) location.x = (int) targetX - 0.01;//防止被卡在墙里 else location.x = targetX; } } if (walk != 0 || getLegSwing() != 0) { setLegSwing(); } if(getLegSwing()==1&&isLegSwing&&World.worldSquare[(int) location.x][(int) (location.y+0.02)]!=null){ MusicThreadExecutor.playWalkSong(); } //jump if (isJumping && verticalSpeed == 0) {//准备起跳 verticalSpeed = -jumpSpeed; } else if (verticalSpeed != 0 || World.worldSquare[(int) location.x][(int) (location.y)] == null) { double targetY = location.y + verticalSpeed; Square square = World.worldSquare[(int) location.x][(int) (targetY)]; if (verticalSpeed < 0 && square != null && !square.through) {//磕脑袋 location.y = Math.ceil(targetY); verticalSpeed = 0; } else if (verticalSpeed > 0 && square != null && !square.through) {//落地 location.y = (int) targetY - 0.01;//防止陷到地里出不来了 verticalSpeed = 0; } else { location.y = targetY; if (verticalSpeed <= 1) verticalSpeed += World.gravity; } } } }
Asterism12/mineminecraft
src/Game/Player.java
1,295
//防止被卡在墙里
line_comment
zh-cn
package Game; import Thing.Square; import java.awt.*; import java.util.Timer; import java.util.TimerTask; public class Player { private final double walkSpeed = 16 / (double) (World.FPS);//一秒16格 private final double jumpSpeed = 0.5;//初始跳跃速度 private double verticalSpeed = 0;//实时垂直速度 private int hp = 10; private int vp = 10; private int dp = 0;//防御力 private Toolbar toolbar = new Toolbar(); private int handSquareNO = 0; private Square chosenSquare; private int chosenNumber; private Point.Double location;//玩家脚底中心坐标,决定从何处开始渲染 private boolean isLegSwing = true; Color head = Color.WHITE; Color body = Color.WHITE; Color arm = Color.WHITE; Color leg = Color.WHITE; int legSwing = 0;//腿部摆动的角度 int walkLeft = 0;//玩家是否在向左侧移动 int walkRight = 0;//玩家是否在向右侧移动 boolean isJumping = false;//玩家是否在跳跃 boolean isOpenBag = false;//玩家是否在查看背包 boolean isShowBorder = false;//显示放置范围 public int getChosenNumber() { return chosenNumber; } public void setChosenNumber(int chosenNumber) { this.chosenNumber = chosenNumber; } public synchronized Square getChosenSquare() { return chosenSquare; } public synchronized void setChosenSquare(Square chosenSquare) { this.chosenSquare = chosenSquare; } public synchronized void throwOutSquare() { if (toolbar.getNumber()[handSquareNO] > 1) toolbar.getNumber()[handSquareNO] -= 1; else { toolbar.getSquares()[handSquareNO] = null; toolbar.getNumber()[handSquareNO] = 0; } } public synchronized int getHandSquareNO() { return handSquareNO; } public synchronized Square getHandSquare() { return toolbar.getSquares()[handSquareNO]; } public synchronized void setHandSquare(int i) { handSquareNO = i; } public synchronized Point.Double getLocation() { return location; } public synchronized void setHp(int hp) { this.hp = hp; } public synchronized int getHp() { return hp; } public synchronized int getDp() { return dp; } public synchronized int getLegSwing() { return legSwing; } Toolbar getToolbar() { return toolbar; } private synchronized void setLegSwing() { if (isLegSwing) { legSwing += 1; if (legSwing == 6) isLegSwing = false; } else { legSwing -= 1; if (legSwing == 0) isLegSwing = true; } } public void setHeadColor(Color color) { head = color; } public void setBodyColor(Color color) { body = color; } public void setArmColor(Color color) { arm = color; } public void setLegColor(Color color) { leg = color; } public Player() { location = World.startLocation; } public void updatePlayer(){ int walk = walkRight - walkLeft; if (walk == -1) { double targetX = location.x - walkSpeed; Square square = World.worldSquare[(int) targetX][(int) location.y]; if (square == null) location.x = targetX; else { if (!square.through) location.x = Math.ceil(targetX); else location.x = targetX; } } else if (walk == 1) { double targetX = location.x + walkSpeed; Square square = World.worldSquare[(int) targetX][(int) location.y]; if (square == null) location.x = targetX; else { if (!square.through) location.x = (int) targetX - 0.01;//防止 <SUF> else location.x = targetX; } } if (walk != 0 || getLegSwing() != 0) { setLegSwing(); } if(getLegSwing()==1&&isLegSwing&&World.worldSquare[(int) location.x][(int) (location.y+0.02)]!=null){ MusicThreadExecutor.playWalkSong(); } //jump if (isJumping && verticalSpeed == 0) {//准备起跳 verticalSpeed = -jumpSpeed; } else if (verticalSpeed != 0 || World.worldSquare[(int) location.x][(int) (location.y)] == null) { double targetY = location.y + verticalSpeed; Square square = World.worldSquare[(int) location.x][(int) (targetY)]; if (verticalSpeed < 0 && square != null && !square.through) {//磕脑袋 location.y = Math.ceil(targetY); verticalSpeed = 0; } else if (verticalSpeed > 0 && square != null && !square.through) {//落地 location.y = (int) targetY - 0.01;//防止陷到地里出不来了 verticalSpeed = 0; } else { location.y = targetY; if (verticalSpeed <= 1) verticalSpeed += World.gravity; } } } }
0
1,225
7
1,295
9
1,398
7
1,295
9
1,666
14
false
false
false
false
false
true
56305_2
package com.jvm; /** * 新生代配置 * -Xmn:可以设置新生代的大小,设值一个比较打的新生代会减少老年代的大小, * 这个参数对系统性能以及GC行为有很大影响,新生代大小一般会设值整 * 个堆空间的 1/3 到 1/4 左右; * * -XX:SurvivorRatio: * 用来设值新生代中 eden 空间和 from/to 空间的比例 * -XX:SurvivorRatio = eden / from = eden / to * * -XX:NewRatio: * 设值新生代和老年代的比例 * -XX:NewRatio = 老年代 / 新生代 * * 基本策略:尽可能将对象预留在新生代中,减少老年代的GC次数 */ public class Jvm2 { /** * 第一次配置 eden 2 = from 1 + to 1 * -Xms20m -Xmx20m -Xmn1m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC * * 第二次配置 eden 2 = from 1 + to 1 * -Xms20m -Xmx20m -Xmn7m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC * * 第三次配置 * -XX:NewRatio = 老年代 / 新生代 * -Xms20m -Xmx20m -XX:NewRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC */ public static void main(String[] args) { byte[] b = null; //连续向系统申请10MB空间 for(int i = 0; i < 10; i ++){ b = new byte[1 * 1024 * 1024]; } } }
Asura7969/JAVA8Demo
src/com/jvm/Jvm2.java
488
//连续向系统申请10MB空间
line_comment
zh-cn
package com.jvm; /** * 新生代配置 * -Xmn:可以设置新生代的大小,设值一个比较打的新生代会减少老年代的大小, * 这个参数对系统性能以及GC行为有很大影响,新生代大小一般会设值整 * 个堆空间的 1/3 到 1/4 左右; * * -XX:SurvivorRatio: * 用来设值新生代中 eden 空间和 from/to 空间的比例 * -XX:SurvivorRatio = eden / from = eden / to * * -XX:NewRatio: * 设值新生代和老年代的比例 * -XX:NewRatio = 老年代 / 新生代 * * 基本策略:尽可能将对象预留在新生代中,减少老年代的GC次数 */ public class Jvm2 { /** * 第一次配置 eden 2 = from 1 + to 1 * -Xms20m -Xmx20m -Xmn1m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC * * 第二次配置 eden 2 = from 1 + to 1 * -Xms20m -Xmx20m -Xmn7m -XX:SurvivorRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC * * 第三次配置 * -XX:NewRatio = 老年代 / 新生代 * -Xms20m -Xmx20m -XX:NewRatio=2 -XX:+PrintGCDetails -XX:+UseSerialGC */ public static void main(String[] args) { byte[] b = null; //连续 <SUF> for(int i = 0; i < 10; i ++){ b = new byte[1 * 1024 * 1024]; } } }
0
459
9
486
10
454
9
488
10
584
17
false
false
false
false
false
true
24304_5
/** * @FileName: Main1.java * @Package asura.framework.algorithm.sort * * @author zhangshaobin * @created 2015年7月3日 上午9:54:18 * * Copyright 2011-2015 asura */ package asura.framework.algorithm.sort; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.BitSet; /** * <p> * NIO方式读取数据, 可以处理半行拼接 * * * 有N个500M以上的⼤大纯⽂文本⽂文件(N>10), 每个⽂文件中, 以换⾏行(\n)分隔, 每⾏行⼀一个数字(数字是 2^32⼤大⼩小以内 ⽆无符号正整数 乱序排列 有重复), 请找出位于数列中间的100个数字之和(去重后的) * </p> * * <PRE> * <BR> 修改记录 * <BR>----------------------------------------------- * <BR> 修改日期 修改人 修改内容 * </PRE> * * @author zhangshaobin * @since 1.0 * @version 1.0 */ public class Main1 { /** * * 主程序 * * args[0] = 文件夹路径 C:\\Users\\001\\Downloads\\sort * * @author zhangshaobin * @created 2015年7月3日 上午10:28:57 * * @param args * @throws Exception */ public static void main(String []args) throws Exception { long s = System.currentTimeMillis(); BitSet bs = new BitSet(Integer.MAX_VALUE); String pathFile = "C:\\Users\\001\\Downloads\\sort"; // 文件路径 File dir = new File(pathFile); if (dir.exists()) { if (dir.isDirectory()) { File [] files = dir.listFiles(); for (File f : files) { System.out.println("---"+f.getAbsolutePath()); genBitSet(bs, f.getAbsolutePath()); } } else { genBitSet(bs, pathFile); } Jisuan.sum(bs); } else { System.out.println("老兄,文件夹路径错误!!!"); } long e = System.currentTimeMillis(); System.out.println("耗时:"+(e-s)); } /** * * 生成bitset对象 * * @author zhangshaobin * @created 2015年7月3日 上午10:01:44 * * @return */ @SuppressWarnings("resource") private static BitSet genBitSet(BitSet bs, String path){ try { FileInputStream fin = new FileInputStream(path); FileChannel fcin = fin.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024*1024*1); //10M 可以作为参数传过去 String last = ""; while (true) { int flag = fcin.read(buffer); if (flag == -1) { break; } buffer.flip(); String bufferString = toString(buffer); if (null != bufferString && bufferString.length() > 0) { String [] lines = bufferString.split("\n"); int lines_length = lines.length; if (null != lines && lines_length > 0) { for (int i=0; i<lines_length-1; i++) { if (i==0 && !"".equals(last)) { bs.set(Integer.valueOf(last+lines[i]),true); last = ""; } else { bs.set(Integer.valueOf(lines[i]),true); } } if (!bufferString.endsWith("\n")) { last = lines[lines_length-1]; } } } buffer.clear(); } } catch (NumberFormatException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bs; } /** * * 字节准换成字符 * * @author zhangshaobin * @created 2015年7月3日 上午9:59:41 * * @param bb * @return */ private static String toString(ByteBuffer bb) { final byte[] bytes = new byte[bb.remaining()]; bb.duplicate().get(bytes); return new String(bytes); } }
AsuraTeam/asura
asura-algorithm/src/main/java/asura/framework/algorithm/sort/Main1.java
1,237
//10M 可以作为参数传过去
line_comment
zh-cn
/** * @FileName: Main1.java * @Package asura.framework.algorithm.sort * * @author zhangshaobin * @created 2015年7月3日 上午9:54:18 * * Copyright 2011-2015 asura */ package asura.framework.algorithm.sort; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.BitSet; /** * <p> * NIO方式读取数据, 可以处理半行拼接 * * * 有N个500M以上的⼤大纯⽂文本⽂文件(N>10), 每个⽂文件中, 以换⾏行(\n)分隔, 每⾏行⼀一个数字(数字是 2^32⼤大⼩小以内 ⽆无符号正整数 乱序排列 有重复), 请找出位于数列中间的100个数字之和(去重后的) * </p> * * <PRE> * <BR> 修改记录 * <BR>----------------------------------------------- * <BR> 修改日期 修改人 修改内容 * </PRE> * * @author zhangshaobin * @since 1.0 * @version 1.0 */ public class Main1 { /** * * 主程序 * * args[0] = 文件夹路径 C:\\Users\\001\\Downloads\\sort * * @author zhangshaobin * @created 2015年7月3日 上午10:28:57 * * @param args * @throws Exception */ public static void main(String []args) throws Exception { long s = System.currentTimeMillis(); BitSet bs = new BitSet(Integer.MAX_VALUE); String pathFile = "C:\\Users\\001\\Downloads\\sort"; // 文件路径 File dir = new File(pathFile); if (dir.exists()) { if (dir.isDirectory()) { File [] files = dir.listFiles(); for (File f : files) { System.out.println("---"+f.getAbsolutePath()); genBitSet(bs, f.getAbsolutePath()); } } else { genBitSet(bs, pathFile); } Jisuan.sum(bs); } else { System.out.println("老兄,文件夹路径错误!!!"); } long e = System.currentTimeMillis(); System.out.println("耗时:"+(e-s)); } /** * * 生成bitset对象 * * @author zhangshaobin * @created 2015年7月3日 上午10:01:44 * * @return */ @SuppressWarnings("resource") private static BitSet genBitSet(BitSet bs, String path){ try { FileInputStream fin = new FileInputStream(path); FileChannel fcin = fin.getChannel(); ByteBuffer buffer = ByteBuffer.allocateDirect(1024*1024*1); //10 <SUF> String last = ""; while (true) { int flag = fcin.read(buffer); if (flag == -1) { break; } buffer.flip(); String bufferString = toString(buffer); if (null != bufferString && bufferString.length() > 0) { String [] lines = bufferString.split("\n"); int lines_length = lines.length; if (null != lines && lines_length > 0) { for (int i=0; i<lines_length-1; i++) { if (i==0 && !"".equals(last)) { bs.set(Integer.valueOf(last+lines[i]),true); last = ""; } else { bs.set(Integer.valueOf(lines[i]),true); } } if (!bufferString.endsWith("\n")) { last = lines[lines_length-1]; } } } buffer.clear(); } } catch (NumberFormatException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bs; } /** * * 字节准换成字符 * * @author zhangshaobin * @created 2015年7月3日 上午9:59:41 * * @param bb * @return */ private static String toString(ByteBuffer bb) { final byte[] bytes = new byte[bb.remaining()]; bb.duplicate().get(bytes); return new String(bytes); } }
0
1,097
13
1,237
12
1,284
11
1,237
12
1,624
15
false
false
false
false
false
true
3274_6
package com.asura.monitor.util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.asura.common.response.ResponseVo; import com.asura.monitor.graph.entity.PushEntity; import com.asura.monitor.graph.util.FileRender; import com.asura.monitor.graph.util.FileWriter; import com.asura.util.CheckUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.asura.monitor.graph.util.FileWriter.dataDir; /** * <p></p> * * <PRE> * <BR> 修改记录 * <BR>----------------------------------------------- * <BR> 修改日期 修改人 修改内容 * </PRE> * * @author zhaozq * @version 1.0 * @since 1.0 */ public class MonitorUtil { public static final String separator = System.getProperty("file.separator"); public static final Logger logger = LoggerFactory.getLogger(MonitorUtil.class); /** * * @param lentity * @return */ public static List<PushEntity> getPushEntity(String lentity){ if( null != lentity ) { Type type = new TypeToken<ArrayList<PushEntity>>() { }.getType(); List<PushEntity> list = new Gson().fromJson(lentity, type); return list; } return new ArrayList<>(); } /** * @param lentity */ public static void writePush(String lentity, String writeType, String ip, Map<String, Long> map){ try { List<PushEntity> list = getPushEntity(lentity); if (null != map) { if (!map.containsKey("indexCounter")) { map.put("indexCounter", Long.valueOf(list.size())); }else{ map.put("indexCounter", map.get("indexCounter")+ list.size()); } } for (PushEntity entity1 : list) { if (null == entity1) { continue; } pushMonitorData(entity1, writeType, ip); } }catch (Exception e){ logger.error("解析数据失败" + lentity, e); } } /** * 记录每个指标的服务器地址 * @param entity */ static void writeIndexHosts(PushEntity entity){ // 拼接文件目录 String dir = dataDir + separator + "graph" + separator +"index" +separator; dir = dir + entity.getGroups()+"."+entity.getName()+separator; dir = FileRender.replace(dir); FileWriter.makeDirs(dir); File file = new File(dir + "id"); if ( !file.exists() ) { FileWriter.writeFile(dir + "id", entity.getScriptId(), false); } } /** * * @param entity * @param writeType * @param ipAddr */ public static void pushMonitorData(PushEntity entity, String writeType, String ipAddr) { String historyName = FileRender.replace(entity.getName()); String name = FileRender.replace(entity.getScriptId() +"_" + FileRender.replace(entity.getStatus())) + "_" + FileRender.replace(entity.getGroups())+ "_"+ FileRender.replace(entity.getName()); if ("2".equals(entity.getStatus())){ logger.info(name); } String groups = FileRender.replace(entity.getGroups()); String value = entity.getValue(); // 记录每个指标的服务器地址 writeIndexHosts(entity); // 获取客户端IP if (null != entity.getIp() && entity.getIp().length() > 7 ) { ipAddr = FileRender.replace(entity.getIp()); } // 只将数据写入到文件 if (CheckUtil.checkString(name) && CheckUtil.checkString(value)) { // 画图数据生成 FileWriter.writeHistory(groups, ipAddr, historyName, value); if(writeType.equals("success")) { // 监控历史数据生成 if (CheckUtil.checkString(entity.getServer())) { FileWriter.writeMonitorHistory(FileRender.replace(entity.getServer()), name, entity); } } } } public static String getStopMonitorTime(long value){ if (value < 60 ) { return "还有" + value + "秒恢复"; } if (value > 60 && value < 3600 ) { return "还有" + ( value / 60 ) +"分钟恢复"; } if (value > 3600 && value < 86400 ) { return "还有" + (value / 60 / 60) + "小时恢复"; } if (value > 86400 && value < 604800 ) { return "还有" +( value / 60 / 60 / 24) +"天恢复"; } if (value > 604800 && value < 2419200 ){ return "还有" +( value / 60 / 60 / 24 / 7 ) +"周恢复"; } return "监控正常报警中"; } }
AsuraTeam/monitor
server/src/main/java/com/asura/monitor/util/MonitorUtil.java
1,319
// 记录每个指标的服务器地址
line_comment
zh-cn
package com.asura.monitor.util; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.asura.common.response.ResponseVo; import com.asura.monitor.graph.entity.PushEntity; import com.asura.monitor.graph.util.FileRender; import com.asura.monitor.graph.util.FileWriter; import com.asura.util.CheckUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import static com.asura.monitor.graph.util.FileWriter.dataDir; /** * <p></p> * * <PRE> * <BR> 修改记录 * <BR>----------------------------------------------- * <BR> 修改日期 修改人 修改内容 * </PRE> * * @author zhaozq * @version 1.0 * @since 1.0 */ public class MonitorUtil { public static final String separator = System.getProperty("file.separator"); public static final Logger logger = LoggerFactory.getLogger(MonitorUtil.class); /** * * @param lentity * @return */ public static List<PushEntity> getPushEntity(String lentity){ if( null != lentity ) { Type type = new TypeToken<ArrayList<PushEntity>>() { }.getType(); List<PushEntity> list = new Gson().fromJson(lentity, type); return list; } return new ArrayList<>(); } /** * @param lentity */ public static void writePush(String lentity, String writeType, String ip, Map<String, Long> map){ try { List<PushEntity> list = getPushEntity(lentity); if (null != map) { if (!map.containsKey("indexCounter")) { map.put("indexCounter", Long.valueOf(list.size())); }else{ map.put("indexCounter", map.get("indexCounter")+ list.size()); } } for (PushEntity entity1 : list) { if (null == entity1) { continue; } pushMonitorData(entity1, writeType, ip); } }catch (Exception e){ logger.error("解析数据失败" + lentity, e); } } /** * 记录每个指标的服务器地址 * @param entity */ static void writeIndexHosts(PushEntity entity){ // 拼接文件目录 String dir = dataDir + separator + "graph" + separator +"index" +separator; dir = dir + entity.getGroups()+"."+entity.getName()+separator; dir = FileRender.replace(dir); FileWriter.makeDirs(dir); File file = new File(dir + "id"); if ( !file.exists() ) { FileWriter.writeFile(dir + "id", entity.getScriptId(), false); } } /** * * @param entity * @param writeType * @param ipAddr */ public static void pushMonitorData(PushEntity entity, String writeType, String ipAddr) { String historyName = FileRender.replace(entity.getName()); String name = FileRender.replace(entity.getScriptId() +"_" + FileRender.replace(entity.getStatus())) + "_" + FileRender.replace(entity.getGroups())+ "_"+ FileRender.replace(entity.getName()); if ("2".equals(entity.getStatus())){ logger.info(name); } String groups = FileRender.replace(entity.getGroups()); String value = entity.getValue(); // 记录 <SUF> writeIndexHosts(entity); // 获取客户端IP if (null != entity.getIp() && entity.getIp().length() > 7 ) { ipAddr = FileRender.replace(entity.getIp()); } // 只将数据写入到文件 if (CheckUtil.checkString(name) && CheckUtil.checkString(value)) { // 画图数据生成 FileWriter.writeHistory(groups, ipAddr, historyName, value); if(writeType.equals("success")) { // 监控历史数据生成 if (CheckUtil.checkString(entity.getServer())) { FileWriter.writeMonitorHistory(FileRender.replace(entity.getServer()), name, entity); } } } } public static String getStopMonitorTime(long value){ if (value < 60 ) { return "还有" + value + "秒恢复"; } if (value > 60 && value < 3600 ) { return "还有" + ( value / 60 ) +"分钟恢复"; } if (value > 3600 && value < 86400 ) { return "还有" + (value / 60 / 60) + "小时恢复"; } if (value > 86400 && value < 604800 ) { return "还有" +( value / 60 / 60 / 24) +"天恢复"; } if (value > 604800 && value < 2419200 ){ return "还有" +( value / 60 / 60 / 24 / 7 ) +"周恢复"; } return "监控正常报警中"; } }
0
1,151
10
1,306
10
1,387
8
1,306
10
1,555
15
false
false
false
false
false
true
26582_5
package cn.utils; import cn.domain.Admin; import cn.domain.Users; import java.util.HashMap; import java.util.Map; import java.util.UUID; import io.jsonwebtoken.*; import java.util.Date; import java.util.UUID; //需要导入java-jwt / jjwt 两个依赖 public class JwtUtil { //秘钥, 随便 private static final String secretKey="Ataraxia@qq.com!Y#$%&()^><ioasf"; /** * 生成 JWT TOKEN * @param user 用户信息 * @return String token */ public static String createToken(Users user){ JwtBuilder jwtBuilder = Jwts.builder(); String token = jwtBuilder //header 固定 .setHeaderParam("typ", "JWT") .setHeaderParam("alg", "HS256") //payload 传输的数据 .claim("userId", user.getUserId()) .claim("userName", user.getUserEmail()) .setSubject("admin-test") .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) //过期时间为1h .setId(UUID.randomUUID().toString()) //signature 签名 固定 .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); return token; } /** * 解析 JWT TOKEN * @param token JWT TOKEN * @return User user */ public static Users parse(String token){ JwtParser parser = Jwts.parser(); Jws<Claims> claimsJws = parser.setSigningKey(secretKey).parseClaimsJws(token); Claims claims = claimsJws.getBody(); System.out.println(claims.get("userId")); System.out.println(claims.get("userName")); System.out.println(claims.getId()); System.out.println(claims.getSubject()); System.out.println(claims.getExpiration()); Users user=new Users(); user.setUserId(Long.valueOf(claims.get("userId").toString())); user.setUserEmail((String)claims.get("userName")); return user; } }
Ataraxia24/cat
src/main/java/cn/utils/JwtUtil.java
513
//过期时间为1h
line_comment
zh-cn
package cn.utils; import cn.domain.Admin; import cn.domain.Users; import java.util.HashMap; import java.util.Map; import java.util.UUID; import io.jsonwebtoken.*; import java.util.Date; import java.util.UUID; //需要导入java-jwt / jjwt 两个依赖 public class JwtUtil { //秘钥, 随便 private static final String secretKey="Ataraxia@qq.com!Y#$%&()^><ioasf"; /** * 生成 JWT TOKEN * @param user 用户信息 * @return String token */ public static String createToken(Users user){ JwtBuilder jwtBuilder = Jwts.builder(); String token = jwtBuilder //header 固定 .setHeaderParam("typ", "JWT") .setHeaderParam("alg", "HS256") //payload 传输的数据 .claim("userId", user.getUserId()) .claim("userName", user.getUserEmail()) .setSubject("admin-test") .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60)) //过期 <SUF> .setId(UUID.randomUUID().toString()) //signature 签名 固定 .signWith(SignatureAlgorithm.HS256, secretKey) .compact(); return token; } /** * 解析 JWT TOKEN * @param token JWT TOKEN * @return User user */ public static Users parse(String token){ JwtParser parser = Jwts.parser(); Jws<Claims> claimsJws = parser.setSigningKey(secretKey).parseClaimsJws(token); Claims claims = claimsJws.getBody(); System.out.println(claims.get("userId")); System.out.println(claims.get("userName")); System.out.println(claims.getId()); System.out.println(claims.getSubject()); System.out.println(claims.getExpiration()); Users user=new Users(); user.setUserId(Long.valueOf(claims.get("userId").toString())); user.setUserEmail((String)claims.get("userName")); return user; } }
0
460
6
513
7
536
6
513
7
673
8
false
false
false
false
false
true
8430_9
package com.attilax.util; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; /** * Created on 17/6/7. 短信API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可) 工程依赖了2个jar包(存放在工程的libs目录下) * 1:aliyun-java-sdk-core.jar 2:aliyun-java-sdk-dysmsapi.jar * * 备注:Demo工程编码采用UTF-8 国际短信发送请勿参照此DEMO */ public class AliyunMessageUtil { // 产品名称:云通信短信API产品,开发者无需替换 static final String product = "Dysmsapi"; // 产品域名,开发者无需替换 static final String domain = "dysmsapi.aliyuncs.com"; // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找) static final String accessKeyId = "LTAIMaVxNlD5pgSk"; static final String accessKeySecret = "6xBXmGbFsr42sgURwrX1JWLVJWFu3L"; public static SendSmsResponse sendSms(Map<String, String> paramMap) throws ClientException { // 可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); // 初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); // 组装请求对象-具体描述见控制台-文档部分内容 SendSmsRequest request = new SendSmsRequest(); // 必填:待发送手机号 request.setPhoneNumbers(paramMap.get("phoneNumber")); // 必填:短信签名-可在短信控制台中找到 request.setSignName(paramMap.get("msgSign")); // 必填:短信模板-可在短信控制台中找到 request.setTemplateCode(paramMap.get("templateCode")); // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.setTemplateParam(paramMap.get("jsonContent")); // 选填-上行短信扩展码(无特殊需求用户请忽略此字段) // request.setSmsUpExtendCode("90997"); // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 // request.setOutId("yourOutId"); // hint 此处可能会抛出异常,注意catch SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); return sendSmsResponse; } /** * 生成随机数 * * @param num 位数 * @return */ public static String createRandomNum(int num) { String randomNumStr = ""; for (int i = 0; i < num; i++) { int randomNum = (int) (Math.random() * 10); randomNumStr += randomNum; } return randomNumStr; } public static void main(String[] args) throws ClientException { String phoneNumber = "18821766710"; String randomNum = createRandomNum(6); String jsonContent = "{\"code\":\"" + randomNum + "\"}"; Map<String, String> paramMap = new HashMap<>(); paramMap.put("phoneNumber", phoneNumber); paramMap.put("msgSign", "唐唐云学堂"); // paramMap.put("templateCode", "SMS_150495957"); paramMap.put("templateCode", "SMS_150495959"); paramMap.put("jsonContent", jsonContent); SendSmsResponse sendSmsResponse = AliyunMessageUtil.sendSms(paramMap); System.out.println("已发送"); System.out.println(JSON.toJSON(sendSmsResponse)); // {"code":"OK","requestId":"27392149-150C-440B-802A-590C422AFB60","bizId":"422313255463283685^0","message":"OK"} if (!(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))) { if (sendSmsResponse.getCode() == null) { System.out.println(sendSmsResponse.getCode()); } if (!sendSmsResponse.getCode().equals("OK")) { System.out.println(sendSmsResponse.getCode() + ""); } } } }
Atlks/bookmarksHtmlEverythingIndexPrj
src/com/attilax/util/AliyunMessageUtil.java
1,397
// 必填:短信模板-可在短信控制台中找到
line_comment
zh-cn
package com.attilax.util; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; /** * Created on 17/6/7. 短信API产品的DEMO程序,工程中包含了一个SmsDemo类,直接通过 * 执行main函数即可体验短信产品API功能(只需要将AK替换成开通了云通信-短信产品功能的AK即可) 工程依赖了2个jar包(存放在工程的libs目录下) * 1:aliyun-java-sdk-core.jar 2:aliyun-java-sdk-dysmsapi.jar * * 备注:Demo工程编码采用UTF-8 国际短信发送请勿参照此DEMO */ public class AliyunMessageUtil { // 产品名称:云通信短信API产品,开发者无需替换 static final String product = "Dysmsapi"; // 产品域名,开发者无需替换 static final String domain = "dysmsapi.aliyuncs.com"; // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找) static final String accessKeyId = "LTAIMaVxNlD5pgSk"; static final String accessKeySecret = "6xBXmGbFsr42sgURwrX1JWLVJWFu3L"; public static SendSmsResponse sendSms(Map<String, String> paramMap) throws ClientException { // 可自助调整超时时间 System.setProperty("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty("sun.net.client.defaultReadTimeout", "10000"); // 初始化acsClient,暂不支持region化 IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); // 组装请求对象-具体描述见控制台-文档部分内容 SendSmsRequest request = new SendSmsRequest(); // 必填:待发送手机号 request.setPhoneNumbers(paramMap.get("phoneNumber")); // 必填:短信签名-可在短信控制台中找到 request.setSignName(paramMap.get("msgSign")); // 必填 <SUF> request.setTemplateCode(paramMap.get("templateCode")); // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 request.setTemplateParam(paramMap.get("jsonContent")); // 选填-上行短信扩展码(无特殊需求用户请忽略此字段) // request.setSmsUpExtendCode("90997"); // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 // request.setOutId("yourOutId"); // hint 此处可能会抛出异常,注意catch SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request); return sendSmsResponse; } /** * 生成随机数 * * @param num 位数 * @return */ public static String createRandomNum(int num) { String randomNumStr = ""; for (int i = 0; i < num; i++) { int randomNum = (int) (Math.random() * 10); randomNumStr += randomNum; } return randomNumStr; } public static void main(String[] args) throws ClientException { String phoneNumber = "18821766710"; String randomNum = createRandomNum(6); String jsonContent = "{\"code\":\"" + randomNum + "\"}"; Map<String, String> paramMap = new HashMap<>(); paramMap.put("phoneNumber", phoneNumber); paramMap.put("msgSign", "唐唐云学堂"); // paramMap.put("templateCode", "SMS_150495957"); paramMap.put("templateCode", "SMS_150495959"); paramMap.put("jsonContent", jsonContent); SendSmsResponse sendSmsResponse = AliyunMessageUtil.sendSms(paramMap); System.out.println("已发送"); System.out.println(JSON.toJSON(sendSmsResponse)); // {"code":"OK","requestId":"27392149-150C-440B-802A-590C422AFB60","bizId":"422313255463283685^0","message":"OK"} if (!(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK"))) { if (sendSmsResponse.getCode() == null) { System.out.println(sendSmsResponse.getCode()); } if (!sendSmsResponse.getCode().equals("OK")) { System.out.println(sendSmsResponse.getCode() + ""); } } } }
0
1,251
15
1,387
18
1,328
13
1,387
18
1,809
31
false
false
false
false
false
true
37447_18
package testkg; import com.alibaba.fastjson.JSONObject; import com.im.action.AbstractAction; import com.im.action.login.LoginAction; import com.im.action.sys.GetSmsCodeAction; import com.im.action.sys.UpdateUserKeyPairAction; import com.im.filter.SignitureValidFilter; import com.webkit.web.ActionException; import com.webkit.web.FilterDispatcher; import redis.clients.jedis.Jedis; import spark.Spark; import static spark.Spark.*; import java.io.IOException; import java.util.Enumeration; import java.util.List; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class spk { public static void main(String[] args) { Spark.exception(RuntimeException.class, (exception, request, response) -> { //exception.printStackTrace(); throw exception; }); port(8088); System.out.println(org.eclipse.jetty.server.Handler.class); System.out.println(org.slf4j.helpers.MessageFormatter.class); // System.out.println( org.slf4j.impl.StaticLoggerBinder.class); get("/h", (req, res) -> "Hel.."); get("/hh", (req, res) -> "Hel222."); postx("/im-biz/sys/getSmsCode", new GetSmsCodeAction()); postx("/im-biz/login/login", new LoginAction()); postx("/im-biz/sys/updateUserKeyPair", new UpdateUserKeyPairAction()); // post("/im-biz/sys/getSmsCode", (req, res) -> { // // // HttpServletResponse resps= res.raw(); // HttpServletRequest reqst=req.raw(); // // // addFltr( reqst,resps); // AbstractAction act1= new GetSmsCodeAction(); // act1.execute( resps.getOutputStream() ); // // resps.flushBuffer(); // resps.getOutputStream().close(); // return resps; // // // // }); // get("/hh", extracted()); get("/p", (req, res) -> { // HttpServletRequest req2 = (HttpServletRequest) req; // spark.http.matching.RequestWrapper req2=req; // System.out.println(req2.getSession().getServletContext().getRealPath("/")); // ; HttpServletRequest req2 = req.raw(); String path = req2.getServletContext().getContextPath(); System.out.println(path); String realPath = req2.getServletContext().getRealPath("/uploadFile"); System.out.println(realPath); return 1; }); get("/m", (req, res) -> { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); // 如果 Redis 服务设置了密码,需要下面这行,没有就不需要 jedis.auth(" "); System.out.println("连接成功"); //查看服务是否运行 System.out.println("服务正在运行: " + jedis.ping()); System.out.println(jedis.get("fgfkkk")); //while(true){ Object msgx = jedis.brpoplpush("msgx", "msgxHstry", 10); String msg = JSONObject.toJSONString(msgx); System.out.println(msg); return msg; }); } static void postx(String path, AbstractAction act1) { post(path, (req, res) -> { HttpServletResponse resps = res.raw(); HttpServletRequest reqst = req.raw(); addFltr(reqst, resps); act1.execute(resps.getOutputStream()); resps.flushBuffer(); resps.getOutputStream().close(); return resps; }); } private static void addFltr(HttpServletRequest reqst, HttpServletResponse resps) throws IOException, ServletException, ActionException, ClassNotFoundException { SignitureValidFilter signitureValidFilter = new SignitureValidFilter(); signitureValidFilter.exceptURI = "/index.jsp,/tool/scheduleEvent"; signitureValidFilter.doFilter(reqst, resps, new FilterChain() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { } }); // FilterConfig fc = new FilterConfig() { // @Override // public String getFilterName() { // return "fltnm"; // } // // @Override // public ServletContext getServletContext() { // return reqst.getServletContext(); // } // // @Override // public String getInitParameter(String s) { // if (s.equals("charset")) // return "utf8"; // return ""; // } // // @Override // public Enumeration<String> getInitParameterNames() { // return null; // } // }; // FilterDispatcher filterDispatcher = new FilterDispatcher(); // filterDispatcher.init(fc); // // // filterDispatcher.doFilter(reqst, resps, new FilterChain() { // @Override // public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { // // } // }); //add ActionContext.getActionContext() // ActionContext.getActionContext() System.out.println(com.webkit.web.ActionContextWrp.class); com.webkit.web.ActionContextWrp.createActionContext(reqst.getServletContext(), reqst, resps); // Dispatcher.getInstance(). serviceAction(,, ); // Dispatcher.getInstance().setActionContext(null); // ActionContext } }
Atlks/sdkprj
nodesrc/testkg/spk.java
1,373
//查看服务是否运行
line_comment
zh-cn
package testkg; import com.alibaba.fastjson.JSONObject; import com.im.action.AbstractAction; import com.im.action.login.LoginAction; import com.im.action.sys.GetSmsCodeAction; import com.im.action.sys.UpdateUserKeyPairAction; import com.im.filter.SignitureValidFilter; import com.webkit.web.ActionException; import com.webkit.web.FilterDispatcher; import redis.clients.jedis.Jedis; import spark.Spark; import static spark.Spark.*; import java.io.IOException; import java.util.Enumeration; import java.util.List; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class spk { public static void main(String[] args) { Spark.exception(RuntimeException.class, (exception, request, response) -> { //exception.printStackTrace(); throw exception; }); port(8088); System.out.println(org.eclipse.jetty.server.Handler.class); System.out.println(org.slf4j.helpers.MessageFormatter.class); // System.out.println( org.slf4j.impl.StaticLoggerBinder.class); get("/h", (req, res) -> "Hel.."); get("/hh", (req, res) -> "Hel222."); postx("/im-biz/sys/getSmsCode", new GetSmsCodeAction()); postx("/im-biz/login/login", new LoginAction()); postx("/im-biz/sys/updateUserKeyPair", new UpdateUserKeyPairAction()); // post("/im-biz/sys/getSmsCode", (req, res) -> { // // // HttpServletResponse resps= res.raw(); // HttpServletRequest reqst=req.raw(); // // // addFltr( reqst,resps); // AbstractAction act1= new GetSmsCodeAction(); // act1.execute( resps.getOutputStream() ); // // resps.flushBuffer(); // resps.getOutputStream().close(); // return resps; // // // // }); // get("/hh", extracted()); get("/p", (req, res) -> { // HttpServletRequest req2 = (HttpServletRequest) req; // spark.http.matching.RequestWrapper req2=req; // System.out.println(req2.getSession().getServletContext().getRealPath("/")); // ; HttpServletRequest req2 = req.raw(); String path = req2.getServletContext().getContextPath(); System.out.println(path); String realPath = req2.getServletContext().getRealPath("/uploadFile"); System.out.println(realPath); return 1; }); get("/m", (req, res) -> { //连接本地的 Redis 服务 Jedis jedis = new Jedis("localhost"); // 如果 Redis 服务设置了密码,需要下面这行,没有就不需要 jedis.auth(" "); System.out.println("连接成功"); //查看 <SUF> System.out.println("服务正在运行: " + jedis.ping()); System.out.println(jedis.get("fgfkkk")); //while(true){ Object msgx = jedis.brpoplpush("msgx", "msgxHstry", 10); String msg = JSONObject.toJSONString(msgx); System.out.println(msg); return msg; }); } static void postx(String path, AbstractAction act1) { post(path, (req, res) -> { HttpServletResponse resps = res.raw(); HttpServletRequest reqst = req.raw(); addFltr(reqst, resps); act1.execute(resps.getOutputStream()); resps.flushBuffer(); resps.getOutputStream().close(); return resps; }); } private static void addFltr(HttpServletRequest reqst, HttpServletResponse resps) throws IOException, ServletException, ActionException, ClassNotFoundException { SignitureValidFilter signitureValidFilter = new SignitureValidFilter(); signitureValidFilter.exceptURI = "/index.jsp,/tool/scheduleEvent"; signitureValidFilter.doFilter(reqst, resps, new FilterChain() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { } }); // FilterConfig fc = new FilterConfig() { // @Override // public String getFilterName() { // return "fltnm"; // } // // @Override // public ServletContext getServletContext() { // return reqst.getServletContext(); // } // // @Override // public String getInitParameter(String s) { // if (s.equals("charset")) // return "utf8"; // return ""; // } // // @Override // public Enumeration<String> getInitParameterNames() { // return null; // } // }; // FilterDispatcher filterDispatcher = new FilterDispatcher(); // filterDispatcher.init(fc); // // // filterDispatcher.doFilter(reqst, resps, new FilterChain() { // @Override // public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { // // } // }); //add ActionContext.getActionContext() // ActionContext.getActionContext() System.out.println(com.webkit.web.ActionContextWrp.class); com.webkit.web.ActionContextWrp.createActionContext(reqst.getServletContext(), reqst, resps); // Dispatcher.getInstance(). serviceAction(,, ); // Dispatcher.getInstance().setActionContext(null); // ActionContext } }
0
1,146
5
1,373
5
1,423
5
1,373
5
1,606
9
false
false
false
false
false
true
56775_1
package com.attilax.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; public class terninal_linux { /** * 连接linux系统 * @param args */ public static void main(String[] args) { try { Connection conn = new Connection("192.168.81.129"); conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword("root", "123456"); if (isAuthenticated == false) { throw new IOException("Authentication failed"); } Session sess = conn.openSession(); sess.requestPTY("bash"); sess.startShell(); InputStream stdout = new StreamGobbler(sess.getStdout()); InputStream stderr = new StreamGobbler(sess.getStderr()); BufferedReader stdoutReader = new BufferedReader( new InputStreamReader(stdout)); BufferedReader stderrReader = new BufferedReader( new InputStreamReader(stderr)); BufferedReader inputReader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(sess.getStdin()); String temp = ""; while (!temp.equals("exit")) { System.out.print("[root@vmone ~]#"); temp = inputReader.readLine(); out.println(temp); out.flush(); String line = null; while ((line = stdoutReader.readLine()) != null) { if (line.length() == 0) {// line等于null从来不会发生,导致程序卡在这里 continue; } else{ System.out.println(line); } } System.out.println("Here is the output from stderr:"); while (true) { line = stderrReader.readLine(); if (line == null) break; System.out.println(line); } } System.out.println("ExitCode: " + sess.getExitStatus()); sess.close(); conn.close(); System.out.println("close connection"); } catch (IOException e) { e.printStackTrace(System.err); System.exit(2); } } } }
Atlks/sumdocIndexToolPrj
src/com/attilax/util/terninal_linux.java
548
// line等于null从来不会发生,导致程序卡在这里
line_comment
zh-cn
package com.attilax.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import ch.ethz.ssh2.Connection; import ch.ethz.ssh2.Session; import ch.ethz.ssh2.StreamGobbler; public class terninal_linux { /** * 连接linux系统 * @param args */ public static void main(String[] args) { try { Connection conn = new Connection("192.168.81.129"); conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword("root", "123456"); if (isAuthenticated == false) { throw new IOException("Authentication failed"); } Session sess = conn.openSession(); sess.requestPTY("bash"); sess.startShell(); InputStream stdout = new StreamGobbler(sess.getStdout()); InputStream stderr = new StreamGobbler(sess.getStderr()); BufferedReader stdoutReader = new BufferedReader( new InputStreamReader(stdout)); BufferedReader stderrReader = new BufferedReader( new InputStreamReader(stderr)); BufferedReader inputReader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(sess.getStdin()); String temp = ""; while (!temp.equals("exit")) { System.out.print("[root@vmone ~]#"); temp = inputReader.readLine(); out.println(temp); out.flush(); String line = null; while ((line = stdoutReader.readLine()) != null) { if (line.length() == 0) {// li <SUF> continue; } else{ System.out.println(line); } } System.out.println("Here is the output from stderr:"); while (true) { line = stderrReader.readLine(); if (line == null) break; System.out.println(line); } } System.out.println("ExitCode: " + sess.getExitStatus()); sess.close(); conn.close(); System.out.println("close connection"); } catch (IOException e) { e.printStackTrace(System.err); System.exit(2); } } } }
0
473
12
548
14
661
12
548
14
726
24
false
false
false
false
false
true
7788_1
package com.demo01; /** * @Author: LFJ * @Date: 2023-02-02 14:22 */ // 测试守护线程 // 上帝守护你 public class TestThread5 { public static void main(String[] args) { God god = new God(); You you = new You(); Thread thread = new Thread(god); thread.setDaemon(true); // 设置成守护线程 thread.start(); new Thread(you).start(); } } // 上帝 class God implements Runnable { public void run() { while (true) { System.out.println("上帝保佑你"); } } } // 你 class You implements Runnable { public void run() { for (int i = 0; i < 36500; i++) { System.out.println("你开心的活着"); } } }
Auroraol/BackFront
2-后端/note01/多线程/code/lesson/src/com/demo01/TestThread5.java
252
// 测试守护线程
line_comment
zh-cn
package com.demo01; /** * @Author: LFJ * @Date: 2023-02-02 14:22 */ // 测试 <SUF> // 上帝守护你 public class TestThread5 { public static void main(String[] args) { God god = new God(); You you = new You(); Thread thread = new Thread(god); thread.setDaemon(true); // 设置成守护线程 thread.start(); new Thread(you).start(); } } // 上帝 class God implements Runnable { public void run() { while (true) { System.out.println("上帝保佑你"); } } } // 你 class You implements Runnable { public void run() { for (int i = 0; i < 36500; i++) { System.out.println("你开心的活着"); } } }
0
206
6
252
7
235
4
252
7
287
10
false
false
false
false
false
true
55287_3
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import com.sun.org.apache.bcel.internal.generic.RETURN; public class Arithmetic_baoshu { //题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。 public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int len = scanner.nextInt(); boolean[] arr = new boolean[len]; for (int i = 0; i < arr.length; i++) { arr[i] = true; //初始化全部在圈内 } int index = 0; //下标 int countNum = 0; //计数 int leftCount = len; do { if (arr[index]) { //是圈内的人时 countNum++; //报数 if (countNum==3) { //当这个人报数为三时 arr[index] = false; //这个人出圈 leftCount--; //剩余人数减一 countNum = 0; //报数重置为0 } } //数组下标和在不在圈内无关 index++; //下一个人的下标 if (index==len) { //当下标等于长度时 index = 0; //下标重置为零 } } while (leftCount>1); for (int i = 0; i < arr.length; i++) { if (arr[i]) { System.out.println("最后剩的人下标为"+i); } } } }
AutKevin/JAVA
Arithmetic/Arithmetic_baoshu.java
457
//当这个人报数为三时
line_comment
zh-cn
import java.util.ArrayList; import java.util.List; import java.util.Scanner; import com.sun.org.apache.bcel.internal.generic.RETURN; public class Arithmetic_baoshu { //题目:有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位。 public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int len = scanner.nextInt(); boolean[] arr = new boolean[len]; for (int i = 0; i < arr.length; i++) { arr[i] = true; //初始化全部在圈内 } int index = 0; //下标 int countNum = 0; //计数 int leftCount = len; do { if (arr[index]) { //是圈内的人时 countNum++; //报数 if (countNum==3) { //当这 <SUF> arr[index] = false; //这个人出圈 leftCount--; //剩余人数减一 countNum = 0; //报数重置为0 } } //数组下标和在不在圈内无关 index++; //下一个人的下标 if (index==len) { //当下标等于长度时 index = 0; //下标重置为零 } } while (leftCount>1); for (int i = 0; i < arr.length; i++) { if (arr[i]) { System.out.println("最后剩的人下标为"+i); } } } }
0
391
8
457
9
433
8
457
9
589
12
false
false
false
false
false
true
15102_12
package cn.authing.sdk.java.dto; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class TenantUserDto { /** * 邮箱,不区分大小写 */ @JsonProperty("email") private String email; /** * 手机号,不带区号。如果是国外手机号,请在 phoneCountryCode 参数中指定区号。 */ @JsonProperty("phone") private String phone; /** * 手机区号,中国大陆手机号可不填。Authing 短信服务暂不内置支持国际手机号,你需要在 Authing 控制台配置对应的国际短信服务。完整的手机区号列表可参阅 https://en.wikipedia.org/wiki/List_of_country_calling_codes。 */ @JsonProperty("phoneCountryCode") private String phoneCountryCode; /** * 用户名,用户池内唯一 */ @JsonProperty("username") private String username; /** * 用户真实名称,不具备唯一性 */ @JsonProperty("name") private String name; /** * 昵称 */ @JsonProperty("nickname") private String nickname; /** * 头像链接 */ @JsonProperty("photo") private String photo; /** * 历史总登录次数 */ @JsonProperty("loginsCount") private Integer loginsCount; /** * 上次登录 IP */ @JsonProperty("lastIp") private String lastIp; /** * 性别: * - `M`: 男性,`male` * - `F`: 女性,`female` * - `U`: 未知,`unknown` * */ @JsonProperty("gender") private Gender gender; /** * 出生日期 */ @JsonProperty("birthdate") private String birthdate; /** * 所在国家 */ @JsonProperty("country") private String country; /** * 所在省份 */ @JsonProperty("province") private String province; /** * 所在城市 */ @JsonProperty("city") private String city; /** * 所处地址 */ @JsonProperty("address") private String address; /** * 所处街道地址 */ @JsonProperty("streetAddress") private String streetAddress; /** * 邮政编码号 */ @JsonProperty("postalCode") private String postalCode; /** * 名 */ @JsonProperty("givenName") private String givenName; /** * 姓 */ @JsonProperty("familyName") private String familyName; /** * 中间名 */ @JsonProperty("middleName") private String middleName; /** * Preferred Username */ @JsonProperty("preferredUsername") private String preferredUsername; /** * 用户上次登录的应用 ID */ @JsonProperty("lastLoginApp") private String lastLoginApp; /** * 用户池 ID */ @JsonProperty("userPoolId") private String userPoolId; /** * 租户 ID */ @JsonProperty("tenantId") private String tenantId; /** * 租户成员 ID */ @JsonProperty("memberId") private String memberId; /** * 关联的用户池级别的用户 ID */ @JsonProperty("linkUserId") private String linkUserId; /** * 是否为租户管理员 */ @JsonProperty("isTenantAdmin") private Boolean isTenantAdmin; /** * 用户密码,默认为明文。我们使用 HTTPS 协议对密码进行安全传输,可以在一定程度上保证安全性。如果你还需要更高级别的安全性,我们还支持 RSA256 和国密 SM2 两种方式对密码进行加密。详情见 `passwordEncryptType` 参数。 */ @JsonProperty("password") private String password; /** * 加密用户密码的盐 */ @JsonProperty("salt") private String salt; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPhoneCountryCode() { return phoneCountryCode; } public void setPhoneCountryCode(String phoneCountryCode) { this.phoneCountryCode = phoneCountryCode; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public Integer getLoginsCount() { return loginsCount; } public void setLoginsCount(Integer loginsCount) { this.loginsCount = loginsCount; } public String getLastIp() { return lastIp; } public void setLastIp(String lastIp) { this.lastIp = lastIp; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public String getBirthdate() { return birthdate; } public void setBirthdate(String birthdate) { this.birthdate = birthdate; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getStreetAddress() { return streetAddress; } public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getGivenName() { return givenName; } public void setGivenName(String givenName) { this.givenName = givenName; } public String getFamilyName() { return familyName; } public void setFamilyName(String familyName) { this.familyName = familyName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getPreferredUsername() { return preferredUsername; } public void setPreferredUsername(String preferredUsername) { this.preferredUsername = preferredUsername; } public String getLastLoginApp() { return lastLoginApp; } public void setLastLoginApp(String lastLoginApp) { this.lastLoginApp = lastLoginApp; } public String getUserPoolId() { return userPoolId; } public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getLinkUserId() { return linkUserId; } public void setLinkUserId(String linkUserId) { this.linkUserId = linkUserId; } public Boolean getIsTenantAdmin() { return isTenantAdmin; } public void setIsTenantAdmin(Boolean isTenantAdmin) { this.isTenantAdmin = isTenantAdmin; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } /** * 性别: * - `M`: 男性,`male` * - `F`: 女性,`female` * - `U`: 未知,`unknown` * */ public static enum Gender { @JsonProperty("M") M("M"), @JsonProperty("F") F("F"), @JsonProperty("U") U("U"), @JsonProperty("W") W("W") ; private String value; Gender(String value) { this.value = value; } public String getValue() { return value; } } }
Authing/authing-java-sdk
src/main/java/cn/authing/sdk/java/dto/TenantUserDto.java
2,092
/** * 所在省份 */
block_comment
zh-cn
package cn.authing.sdk.java.dto; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class TenantUserDto { /** * 邮箱,不区分大小写 */ @JsonProperty("email") private String email; /** * 手机号,不带区号。如果是国外手机号,请在 phoneCountryCode 参数中指定区号。 */ @JsonProperty("phone") private String phone; /** * 手机区号,中国大陆手机号可不填。Authing 短信服务暂不内置支持国际手机号,你需要在 Authing 控制台配置对应的国际短信服务。完整的手机区号列表可参阅 https://en.wikipedia.org/wiki/List_of_country_calling_codes。 */ @JsonProperty("phoneCountryCode") private String phoneCountryCode; /** * 用户名,用户池内唯一 */ @JsonProperty("username") private String username; /** * 用户真实名称,不具备唯一性 */ @JsonProperty("name") private String name; /** * 昵称 */ @JsonProperty("nickname") private String nickname; /** * 头像链接 */ @JsonProperty("photo") private String photo; /** * 历史总登录次数 */ @JsonProperty("loginsCount") private Integer loginsCount; /** * 上次登录 IP */ @JsonProperty("lastIp") private String lastIp; /** * 性别: * - `M`: 男性,`male` * - `F`: 女性,`female` * - `U`: 未知,`unknown` * */ @JsonProperty("gender") private Gender gender; /** * 出生日期 */ @JsonProperty("birthdate") private String birthdate; /** * 所在国家 */ @JsonProperty("country") private String country; /** * 所在省 <SUF>*/ @JsonProperty("province") private String province; /** * 所在城市 */ @JsonProperty("city") private String city; /** * 所处地址 */ @JsonProperty("address") private String address; /** * 所处街道地址 */ @JsonProperty("streetAddress") private String streetAddress; /** * 邮政编码号 */ @JsonProperty("postalCode") private String postalCode; /** * 名 */ @JsonProperty("givenName") private String givenName; /** * 姓 */ @JsonProperty("familyName") private String familyName; /** * 中间名 */ @JsonProperty("middleName") private String middleName; /** * Preferred Username */ @JsonProperty("preferredUsername") private String preferredUsername; /** * 用户上次登录的应用 ID */ @JsonProperty("lastLoginApp") private String lastLoginApp; /** * 用户池 ID */ @JsonProperty("userPoolId") private String userPoolId; /** * 租户 ID */ @JsonProperty("tenantId") private String tenantId; /** * 租户成员 ID */ @JsonProperty("memberId") private String memberId; /** * 关联的用户池级别的用户 ID */ @JsonProperty("linkUserId") private String linkUserId; /** * 是否为租户管理员 */ @JsonProperty("isTenantAdmin") private Boolean isTenantAdmin; /** * 用户密码,默认为明文。我们使用 HTTPS 协议对密码进行安全传输,可以在一定程度上保证安全性。如果你还需要更高级别的安全性,我们还支持 RSA256 和国密 SM2 两种方式对密码进行加密。详情见 `passwordEncryptType` 参数。 */ @JsonProperty("password") private String password; /** * 加密用户密码的盐 */ @JsonProperty("salt") private String salt; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPhoneCountryCode() { return phoneCountryCode; } public void setPhoneCountryCode(String phoneCountryCode) { this.phoneCountryCode = phoneCountryCode; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public Integer getLoginsCount() { return loginsCount; } public void setLoginsCount(Integer loginsCount) { this.loginsCount = loginsCount; } public String getLastIp() { return lastIp; } public void setLastIp(String lastIp) { this.lastIp = lastIp; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public String getBirthdate() { return birthdate; } public void setBirthdate(String birthdate) { this.birthdate = birthdate; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getStreetAddress() { return streetAddress; } public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getGivenName() { return givenName; } public void setGivenName(String givenName) { this.givenName = givenName; } public String getFamilyName() { return familyName; } public void setFamilyName(String familyName) { this.familyName = familyName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getPreferredUsername() { return preferredUsername; } public void setPreferredUsername(String preferredUsername) { this.preferredUsername = preferredUsername; } public String getLastLoginApp() { return lastLoginApp; } public void setLastLoginApp(String lastLoginApp) { this.lastLoginApp = lastLoginApp; } public String getUserPoolId() { return userPoolId; } public void setUserPoolId(String userPoolId) { this.userPoolId = userPoolId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getLinkUserId() { return linkUserId; } public void setLinkUserId(String linkUserId) { this.linkUserId = linkUserId; } public Boolean getIsTenantAdmin() { return isTenantAdmin; } public void setIsTenantAdmin(Boolean isTenantAdmin) { this.isTenantAdmin = isTenantAdmin; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } /** * 性别: * - `M`: 男性,`male` * - `F`: 女性,`female` * - `U`: 未知,`unknown` * */ public static enum Gender { @JsonProperty("M") M("M"), @JsonProperty("F") F("F"), @JsonProperty("U") U("U"), @JsonProperty("W") W("W") ; private String value; Gender(String value) { this.value = value; } public String getValue() { return value; } } }
0
2,011
10
2,092
9
2,356
11
2,092
9
2,793
14
false
false
false
false
false
true
38538_6
package com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.domain.generate; import com.autohome.frostmourne.monitor.model.enums.AlertType; import com.autohome.frostmourne.monitor.model.enums.SendStatus; import com.autohome.frostmourne.monitor.model.enums.SilenceStatus; import java.io.Serializable; import java.util.Date; /** * 报警日志 * * @author mybatis-generator */ public class AlertLog implements Serializable { /** * 自增主键 */ private Long id; /** * 监控ID */ private Long alarmId; /** * 监控执行ID */ private Long executeId; /** * 报警方式 */ private String way; /** * 报警接收人 */ private String recipient; /** * 是否在静默期(YES,NO) */ private SilenceStatus inSilence; /** * 发送状态(NONE,SUCCESS,FAIL,FORBID) */ private SendStatus sendStatus; /** * 消息类型(问题报警: PROBLEM; 恢复通知: RECOVER) */ private AlertType alertType; /** * 创建时间 */ private Date createAt; /** * 报警内容 */ private String content; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAlarmId() { return alarmId; } public void setAlarmId(Long alarmId) { this.alarmId = alarmId; } public Long getExecuteId() { return executeId; } public void setExecuteId(Long executeId) { this.executeId = executeId; } public String getWay() { return way; } public void setWay(String way) { this.way = way == null ? null : way.trim(); } public String getRecipient() { return recipient; } public void setRecipient(String recipient) { this.recipient = recipient == null ? null : recipient.trim(); } public SilenceStatus getInSilence() { return inSilence; } public void setInSilence(SilenceStatus inSilence) { this.inSilence = inSilence; } public SendStatus getSendStatus() { return sendStatus; } public void setSendStatus(SendStatus sendStatus) { this.sendStatus = sendStatus; } public AlertType getAlertType() { return alertType; } public void setAlertType(AlertType alertType) { this.alertType = alertType; } public Date getCreateAt() { return createAt; } public void setCreateAt(Date createAt) { this.createAt = createAt; } public String getContent() { return content; } public void setContent(String content) { this.content = content == null ? null : content.trim(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } AlertLog other = (AlertLog) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getAlarmId() == null ? other.getAlarmId() == null : this.getAlarmId().equals(other.getAlarmId())) && (this.getExecuteId() == null ? other.getExecuteId() == null : this.getExecuteId().equals(other.getExecuteId())) && (this.getWay() == null ? other.getWay() == null : this.getWay().equals(other.getWay())) && (this.getRecipient() == null ? other.getRecipient() == null : this.getRecipient().equals(other.getRecipient())) && (this.getInSilence() == null ? other.getInSilence() == null : this.getInSilence().equals(other.getInSilence())) && (this.getSendStatus() == null ? other.getSendStatus() == null : this.getSendStatus().equals(other.getSendStatus())) && (this.getAlertType() == null ? other.getAlertType() == null : this.getAlertType().equals(other.getAlertType())) && (this.getCreateAt() == null ? other.getCreateAt() == null : this.getCreateAt().equals(other.getCreateAt())) && (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getAlarmId() == null) ? 0 : getAlarmId().hashCode()); result = prime * result + ((getExecuteId() == null) ? 0 : getExecuteId().hashCode()); result = prime * result + ((getWay() == null) ? 0 : getWay().hashCode()); result = prime * result + ((getRecipient() == null) ? 0 : getRecipient().hashCode()); result = prime * result + ((getInSilence() == null) ? 0 : getInSilence().hashCode()); result = prime * result + ((getSendStatus() == null) ? 0 : getSendStatus().hashCode()); result = prime * result + ((getAlertType() == null) ? 0 : getAlertType().hashCode()); result = prime * result + ((getCreateAt() == null) ? 0 : getCreateAt().hashCode()); result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode()); return result; } }
AutohomeCorp/frostmourne
frostmourne-monitor/src/main/java/com/autohome/frostmourne/monitor/dao/mybatis/frostmourne/domain/generate/AlertLog.java
1,400
/** * 是否在静默期(YES,NO) */
block_comment
zh-cn
package com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.domain.generate; import com.autohome.frostmourne.monitor.model.enums.AlertType; import com.autohome.frostmourne.monitor.model.enums.SendStatus; import com.autohome.frostmourne.monitor.model.enums.SilenceStatus; import java.io.Serializable; import java.util.Date; /** * 报警日志 * * @author mybatis-generator */ public class AlertLog implements Serializable { /** * 自增主键 */ private Long id; /** * 监控ID */ private Long alarmId; /** * 监控执行ID */ private Long executeId; /** * 报警方式 */ private String way; /** * 报警接收人 */ private String recipient; /** * 是否在 <SUF>*/ private SilenceStatus inSilence; /** * 发送状态(NONE,SUCCESS,FAIL,FORBID) */ private SendStatus sendStatus; /** * 消息类型(问题报警: PROBLEM; 恢复通知: RECOVER) */ private AlertType alertType; /** * 创建时间 */ private Date createAt; /** * 报警内容 */ private String content; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getAlarmId() { return alarmId; } public void setAlarmId(Long alarmId) { this.alarmId = alarmId; } public Long getExecuteId() { return executeId; } public void setExecuteId(Long executeId) { this.executeId = executeId; } public String getWay() { return way; } public void setWay(String way) { this.way = way == null ? null : way.trim(); } public String getRecipient() { return recipient; } public void setRecipient(String recipient) { this.recipient = recipient == null ? null : recipient.trim(); } public SilenceStatus getInSilence() { return inSilence; } public void setInSilence(SilenceStatus inSilence) { this.inSilence = inSilence; } public SendStatus getSendStatus() { return sendStatus; } public void setSendStatus(SendStatus sendStatus) { this.sendStatus = sendStatus; } public AlertType getAlertType() { return alertType; } public void setAlertType(AlertType alertType) { this.alertType = alertType; } public Date getCreateAt() { return createAt; } public void setCreateAt(Date createAt) { this.createAt = createAt; } public String getContent() { return content; } public void setContent(String content) { this.content = content == null ? null : content.trim(); } @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } AlertLog other = (AlertLog) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getAlarmId() == null ? other.getAlarmId() == null : this.getAlarmId().equals(other.getAlarmId())) && (this.getExecuteId() == null ? other.getExecuteId() == null : this.getExecuteId().equals(other.getExecuteId())) && (this.getWay() == null ? other.getWay() == null : this.getWay().equals(other.getWay())) && (this.getRecipient() == null ? other.getRecipient() == null : this.getRecipient().equals(other.getRecipient())) && (this.getInSilence() == null ? other.getInSilence() == null : this.getInSilence().equals(other.getInSilence())) && (this.getSendStatus() == null ? other.getSendStatus() == null : this.getSendStatus().equals(other.getSendStatus())) && (this.getAlertType() == null ? other.getAlertType() == null : this.getAlertType().equals(other.getAlertType())) && (this.getCreateAt() == null ? other.getCreateAt() == null : this.getCreateAt().equals(other.getCreateAt())) && (this.getContent() == null ? other.getContent() == null : this.getContent().equals(other.getContent())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getAlarmId() == null) ? 0 : getAlarmId().hashCode()); result = prime * result + ((getExecuteId() == null) ? 0 : getExecuteId().hashCode()); result = prime * result + ((getWay() == null) ? 0 : getWay().hashCode()); result = prime * result + ((getRecipient() == null) ? 0 : getRecipient().hashCode()); result = prime * result + ((getInSilence() == null) ? 0 : getInSilence().hashCode()); result = prime * result + ((getSendStatus() == null) ? 0 : getSendStatus().hashCode()); result = prime * result + ((getAlertType() == null) ? 0 : getAlertType().hashCode()); result = prime * result + ((getCreateAt() == null) ? 0 : getCreateAt().hashCode()); result = prime * result + ((getContent() == null) ? 0 : getContent().hashCode()); return result; } }
0
1,298
15
1,400
15
1,499
17
1,400
15
1,724
21
false
false
false
false
false
true
25043_3
class Solution { public int[] pondSizes(int[][] land) { int m = land.length, n = land[0].length; var ans = new ArrayList<Integer>(); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (land[i][j] == 0) // 从没有访问过的 0 出发 ans.add(dfs(land, i, j)); // 简洁写法,但是慢 // return ans.stream().sorted().mapToInt(i -> i).toArray(); // 更快的写法 var size = new int[ans.size()]; int i = 0; for (int x : ans) size[i++] = x; Arrays.sort(size); return size; } private int dfs(int[][] land, int x, int y) { if (x < 0 || x >= land.length || y < 0 || y >= land[x].length || land[x][y] != 0) return 0; land[x][y] = 1; // 标记 (x,y) 被访问,避免重复访问 int cnt0 = 1; // 访问八方向的 0 for (int i = x - 1; i <= x + 1; i++) for (int j = y - 1; j <= y + 1; j++) cnt0 += dfs(land, i, j); return cnt0; } }
Autunomy/algothrim-study
leetcode/每日一题/2023/06/22/solution.java
353
// 更快的写法
line_comment
zh-cn
class Solution { public int[] pondSizes(int[][] land) { int m = land.length, n = land[0].length; var ans = new ArrayList<Integer>(); for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (land[i][j] == 0) // 从没有访问过的 0 出发 ans.add(dfs(land, i, j)); // 简洁写法,但是慢 // return ans.stream().sorted().mapToInt(i -> i).toArray(); // 更快 <SUF> var size = new int[ans.size()]; int i = 0; for (int x : ans) size[i++] = x; Arrays.sort(size); return size; } private int dfs(int[][] land, int x, int y) { if (x < 0 || x >= land.length || y < 0 || y >= land[x].length || land[x][y] != 0) return 0; land[x][y] = 1; // 标记 (x,y) 被访问,避免重复访问 int cnt0 = 1; // 访问八方向的 0 for (int i = x - 1; i <= x + 1; i++) for (int j = y - 1; j <= y + 1; j++) cnt0 += dfs(land, i, j); return cnt0; } }
0
342
6
353
6
374
5
353
6
431
9
false
false
false
false
false
true
48094_1
package io.nio.chatroom2; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class NioClient { public static void main(String[] args) throws IOException { // Nio的通用写法,保证不阻塞,注意clientSocketChannel这个名称,这个是客户端的socketChannel SocketChannel clientSocketChannel = SocketChannel.open(); clientSocketChannel.configureBlocking(false); Selector selector = Selector.open(); // 连接客户端,可以理解成:客户端执行连接操作时,就会产生连接事件,此时这个事件还在socketChannel中。 clientSocketChannel.connect(new InetSocketAddress("47.92.149.10", 80)); // 将socketChannel注册到selector中,由selector来关联socketChannel的连接事件 clientSocketChannel.register(selector, SelectionKey.OP_CONNECT); while (true) { /** * 在selector中寻找一次,看selector中是否有事件发生,如果没有时间发生,则会阻塞到这里。 * 但由于我们在初始化客户端的过程中已经执行了连接服务器的操作 ---> 这段代码:clientSocketChannel.configureBlocking(false) * 因此此处不会阻塞,会往下执行 * * 目前selector中只注册了一个clientSocketChannel,且这个clientSocketChannel对connect事件 “感兴趣” * 因此,此次寻找,就是看是否有clientSocketChannel的connect事件发生,如果有发生,则会 * 将这个事件放入到一个set集合中,并且解阻塞。 * * 注意:虽然注册只有socketChannel的connect事件,但只要socketChannel有事件发生了,这个地方 * 都会解除阻塞。 * 举个例子: * 客户端拿到clientSocketChannel主动连接服务端,会产生connect事件,因此这个select方法会解除阻塞 * 客户端拿到clientSocketChannel向服务端写数据,会产生write事件,这个select也会解除阻塞 * 服务端拿到客户端的clientSocketChannel并往里面写数据,对于客户端而言:会产生read事件,这个select也会解除阻塞 * ..... * * 因此,这个地方比较重要的点就是: * 只要注册到selector中的channel有事件发生,则会解除阻塞,如果这个事件是channel感兴趣的事件,则会进入set集合中 */ int select = selector.select(); /** * 执行到这里,那肯定是上述的select方法解除阻塞了 ===> 这代表着有感兴趣的事件发生了,接下来需要处理感兴趣的事件了 * 而此时的事件就是连接事件。SelectionKey对象可以描述当前是什么事件。 * * 这个set集合只会保存感兴趣的事件 */ Set<SelectionKey> set = selector.selectedKeys(); System.out.println("产生的事件个数: ===> " + set.size()); // 遍历迭代器,开始处理事件 Iterator<SelectionKey> iterator = set.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); // 这个socketChannel与上述的clientSocketChannel一致 SocketChannel socketChannel = (SocketChannel) key.channel(); /** * 验证key对应的通道是否已完成或未能完成其套接字连接操作 --> 这种情况都是返回true * 若key对应的通道不支持链接时,才会返回false。 * 因此可以断定:只要是连接了客户端 */ if (key.isConnectable()) { /** * 下面三行代码保证客户端能连接上服务器。 * 若连接失败,则会抛出异常, * @see SocketChannel#finishConnect() 方法的签名 */ if (socketChannel.isConnectionPending()) { socketChannel.finishConnect(); } // 连接服务器成功后,向服务器发送一段信息:I have been connected server socketChannel.write(ByteBuffer.wrap("I have been connected server".getBytes())); /** * 还记得上面的select方法么。select方法是 只要有事件发生了就会解除阻塞。 * 而selectedKeys方法是 只筛选出感兴趣的事件。在此处注册一个read事件的原因就是 * 等会服务端会拿到客户端的clientSocketChannel并往里面写数据, * 对客户端而言:这个操作就是一个读事件。因此这里注册一个读事件,为了就是能 * 在selectedKeys方法中把这个读事件找出来。不然的话select方法将会一直 * 解除阻塞,因为里面一直有一个读事件没有被处理,而且clientSocketChannel也 * 对读事件不感兴趣,最终会导致外层的while循环因select没有阻塞,会一直执行。 * * 可以测试:将这段代码注释掉,看客户端是否一直在打印:产生的事件个数: ===> 0 */ socketChannel.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { /** * 这里就是处理服务端发来的消息,就是使用ByteBuffer操作channel中的数据。 * 这里模拟了传输大数据量的情况,设置的byteBuffer的数组长度只有5。 * 这里涉及到channel的read方法,当read方法返回值 > 0 时,表示读取到的数据。 * 可能为0 或者 -1. 具体情况可以查看read方法的注释 * @see ReadableByteChannel#read(java.nio.ByteBuffer) */ ByteBuffer byteBuffer = ByteBuffer.allocate(5); int len; while ((len = socketChannel.read(byteBuffer)) > 0) { System.out.print(new String(byteBuffer.array(), 0, len)); byteBuffer.flip(); } } // 感兴趣的事件处理完毕后,移除掉 iterator.remove(); } } } }
AvengerEug/javase
src/main/java/io/nio/chatroom2/NioClient.java
1,430
// 连接客户端,可以理解成:客户端执行连接操作时,就会产生连接事件,此时这个事件还在socketChannel中。
line_comment
zh-cn
package io.nio.chatroom2; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class NioClient { public static void main(String[] args) throws IOException { // Nio的通用写法,保证不阻塞,注意clientSocketChannel这个名称,这个是客户端的socketChannel SocketChannel clientSocketChannel = SocketChannel.open(); clientSocketChannel.configureBlocking(false); Selector selector = Selector.open(); // 连接 <SUF> clientSocketChannel.connect(new InetSocketAddress("47.92.149.10", 80)); // 将socketChannel注册到selector中,由selector来关联socketChannel的连接事件 clientSocketChannel.register(selector, SelectionKey.OP_CONNECT); while (true) { /** * 在selector中寻找一次,看selector中是否有事件发生,如果没有时间发生,则会阻塞到这里。 * 但由于我们在初始化客户端的过程中已经执行了连接服务器的操作 ---> 这段代码:clientSocketChannel.configureBlocking(false) * 因此此处不会阻塞,会往下执行 * * 目前selector中只注册了一个clientSocketChannel,且这个clientSocketChannel对connect事件 “感兴趣” * 因此,此次寻找,就是看是否有clientSocketChannel的connect事件发生,如果有发生,则会 * 将这个事件放入到一个set集合中,并且解阻塞。 * * 注意:虽然注册只有socketChannel的connect事件,但只要socketChannel有事件发生了,这个地方 * 都会解除阻塞。 * 举个例子: * 客户端拿到clientSocketChannel主动连接服务端,会产生connect事件,因此这个select方法会解除阻塞 * 客户端拿到clientSocketChannel向服务端写数据,会产生write事件,这个select也会解除阻塞 * 服务端拿到客户端的clientSocketChannel并往里面写数据,对于客户端而言:会产生read事件,这个select也会解除阻塞 * ..... * * 因此,这个地方比较重要的点就是: * 只要注册到selector中的channel有事件发生,则会解除阻塞,如果这个事件是channel感兴趣的事件,则会进入set集合中 */ int select = selector.select(); /** * 执行到这里,那肯定是上述的select方法解除阻塞了 ===> 这代表着有感兴趣的事件发生了,接下来需要处理感兴趣的事件了 * 而此时的事件就是连接事件。SelectionKey对象可以描述当前是什么事件。 * * 这个set集合只会保存感兴趣的事件 */ Set<SelectionKey> set = selector.selectedKeys(); System.out.println("产生的事件个数: ===> " + set.size()); // 遍历迭代器,开始处理事件 Iterator<SelectionKey> iterator = set.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); // 这个socketChannel与上述的clientSocketChannel一致 SocketChannel socketChannel = (SocketChannel) key.channel(); /** * 验证key对应的通道是否已完成或未能完成其套接字连接操作 --> 这种情况都是返回true * 若key对应的通道不支持链接时,才会返回false。 * 因此可以断定:只要是连接了客户端 */ if (key.isConnectable()) { /** * 下面三行代码保证客户端能连接上服务器。 * 若连接失败,则会抛出异常, * @see SocketChannel#finishConnect() 方法的签名 */ if (socketChannel.isConnectionPending()) { socketChannel.finishConnect(); } // 连接服务器成功后,向服务器发送一段信息:I have been connected server socketChannel.write(ByteBuffer.wrap("I have been connected server".getBytes())); /** * 还记得上面的select方法么。select方法是 只要有事件发生了就会解除阻塞。 * 而selectedKeys方法是 只筛选出感兴趣的事件。在此处注册一个read事件的原因就是 * 等会服务端会拿到客户端的clientSocketChannel并往里面写数据, * 对客户端而言:这个操作就是一个读事件。因此这里注册一个读事件,为了就是能 * 在selectedKeys方法中把这个读事件找出来。不然的话select方法将会一直 * 解除阻塞,因为里面一直有一个读事件没有被处理,而且clientSocketChannel也 * 对读事件不感兴趣,最终会导致外层的while循环因select没有阻塞,会一直执行。 * * 可以测试:将这段代码注释掉,看客户端是否一直在打印:产生的事件个数: ===> 0 */ socketChannel.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { /** * 这里就是处理服务端发来的消息,就是使用ByteBuffer操作channel中的数据。 * 这里模拟了传输大数据量的情况,设置的byteBuffer的数组长度只有5。 * 这里涉及到channel的read方法,当read方法返回值 > 0 时,表示读取到的数据。 * 可能为0 或者 -1. 具体情况可以查看read方法的注释 * @see ReadableByteChannel#read(java.nio.ByteBuffer) */ ByteBuffer byteBuffer = ByteBuffer.allocate(5); int len; while ((len = socketChannel.read(byteBuffer)) > 0) { System.out.print(new String(byteBuffer.array(), 0, len)); byteBuffer.flip(); } } // 感兴趣的事件处理完毕后,移除掉 iterator.remove(); } } } }
0
1,306
29
1,430
30
1,378
27
1,430
30
2,204
54
false
false
false
false
false
true
12684_2
package com.github.unclecatmyself.core.bean; /** * 用户层消息Bean封装 * Created by MySelf on 2018/12/19. */ public class InChatMessage { /** 消息时间 */ private int time; /** 消息类型 */ private String type; /** 消息值 */ private String value; /** 用户标识 */ private String token; /** 群聊Id */ private String groupId; /** 是否在线-个人 */ private String online; /** 是否在线-群聊 */ private String onlineGroup; /** 消息接收人标识 */ private String one; public String getOnlineGroup() { return onlineGroup; } public void setOnlineGroup(String onlineGroup) { this.onlineGroup = onlineGroup; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getOnline() { return online; } public void setOnline(String online) { this.online = online; } public String getOne() { return one; } public void setOne(String one) { this.one = one; } @Override public String toString() { return "InChatMessage{" + "time=" + time + ", type='" + type + '\'' + ", value='" + value + '\'' + ", token='" + token + '\'' + ", groupId='" + groupId + '\'' + ", online='" + online + '\'' + ", onlineGroup='" + onlineGroup + '\'' + ", one='" + one + '\'' + '}'; } }
AwakenCN/InChat
src/main/java/com/github/unclecatmyself/core/bean/InChatMessage.java
510
/** 消息类型 */
block_comment
zh-cn
package com.github.unclecatmyself.core.bean; /** * 用户层消息Bean封装 * Created by MySelf on 2018/12/19. */ public class InChatMessage { /** 消息时间 */ private int time; /** 消息类 <SUF>*/ private String type; /** 消息值 */ private String value; /** 用户标识 */ private String token; /** 群聊Id */ private String groupId; /** 是否在线-个人 */ private String online; /** 是否在线-群聊 */ private String onlineGroup; /** 消息接收人标识 */ private String one; public String getOnlineGroup() { return onlineGroup; } public void setOnlineGroup(String onlineGroup) { this.onlineGroup = onlineGroup; } public int getTime() { return time; } public void setTime(int time) { this.time = time; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getOnline() { return online; } public void setOnline(String online) { this.online = online; } public String getOne() { return one; } public void setOne(String one) { this.one = one; } @Override public String toString() { return "InChatMessage{" + "time=" + time + ", type='" + type + '\'' + ", value='" + value + '\'' + ", token='" + token + '\'' + ", groupId='" + groupId + '\'' + ", online='" + online + '\'' + ", onlineGroup='" + onlineGroup + '\'' + ", one='" + one + '\'' + '}'; } }
0
479
6
510
7
565
4
510
7
673
7
false
false
false
false
false
true
64213_4
package com.awaken.leetcode.array; /** * @Auther: Noseparte * @Date: 2020/5/7 7:40 下午 * @Description: * * <p> * 1011. 在 D 天内送达包裹的能力 * * 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。 * 传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。 * 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。 * </p> * */ public class ShipWithinDays { public int shipWithinDays(int[] weights, int D) { int lo = 0, hi = Integer.MAX_VALUE; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (canShip(weights, D, mid)) { hi = mid; } else { lo = mid+1; } } return lo; } /** * 定义函数canShip(D, K),来判断在最低承载力为K的情形下能否在DD天内送达所有包裹。我们所要做的就是按照传送带上货物的顺序,依次且尽可能多地往船上装载货物,当该艘船无法装下更多货物时,我们换一搜船,同时将天数加1。当运输完所有货物后,我们判断所用的天数是否小于等于D。 * 用二分查找的方式,来查找这个最低承载力,如果midmid可以完成任务,我们把查找范围缩减至[lo, mid][lo,mid](注意不是mid+1mid+1,因为mid可能是我们所求的解),否则我们去[mid+1, hi][mid+1,hi]区间中继续查找,详情见代码。 * */ private boolean canShip(int[] weights, int D, int K) { int cur = K; // cur 表示当前船的可用承载量 for (int weight: weights) { if (weight > K) return false; if (cur < weight) { cur = K; D--; } cur -= weight; } return D > 0; // 能否在D天内运完 } /** * 示例 1: * * 输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5 * 输出:15 * 解释: * 船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示: * 第 1 天:1, 2, 3, 4, 5 * 第 2 天:6, 7 * 第 3 天:8 * 第 4 天:9 * 第 5 天:10 * * 请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。 * * * 示例 2: * 输入:weights = [3,2,2,4,1,4], D = 3 * 输出:6 * 解释: * 船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示: * 第 1 天:3, 2 * 第 2 天:2, 4 * 第 3 天:1, 4 * * * 示例 3: * * 输入:weights = [1,2,3,1,1], D = 4 * 输出:3 * 解释: * 第 1 天:1 * 第 2 天:2 * 第 3 天:3 * 第 4 天:1, 1 *   * * 提示: * * 1 <= D <= weights.length <= 50000 * 1 <= weights[i] <= 500 * */ public static void main(String[] args) { int ship = new ShipWithinDays().shipWithinDays(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5); System.out.println(ship); } }
AwakenCN/Nine-Chapters
src/main/java/com/awaken/leetcode/array/ShipWithinDays.java
1,182
/** * 示例 1: * * 输入:weights = [1,2,3,4,5,6,7,8,9,10], D = 5 * 输出:15 * 解释: * 船舶最低载重 15 就能够在 5 天内送达所有包裹,如下所示: * 第 1 天:1, 2, 3, 4, 5 * 第 2 天:6, 7 * 第 3 天:8 * 第 4 天:9 * 第 5 天:10 * * 请注意,货物必须按照给定的顺序装运,因此使用载重能力为 14 的船舶并将包装分成 (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) 是不允许的。 * * * 示例 2: * 输入:weights = [3,2,2,4,1,4], D = 3 * 输出:6 * 解释: * 船舶最低载重 6 就能够在 3 天内送达所有包裹,如下所示: * 第 1 天:3, 2 * 第 2 天:2, 4 * 第 3 天:1, 4 * * * 示例 3: * * 输入:weights = [1,2,3,1,1], D = 4 * 输出:3 * 解释: * 第 1 天:1 * 第 2 天:2 * 第 3 天:3 * 第 4 天:1, 1 *   * * 提示: * * 1 <= D <= weights.length <= 50000 * 1 <= weights[i] <= 500 * */
block_comment
zh-cn
package com.awaken.leetcode.array; /** * @Auther: Noseparte * @Date: 2020/5/7 7:40 下午 * @Description: * * <p> * 1011. 在 D 天内送达包裹的能力 * * 传送带上的包裹必须在 D 天内从一个港口运送到另一个港口。 * 传送带上的第 i 个包裹的重量为 weights[i]。每一天,我们都会按给出重量的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。 * 返回能在 D 天内将传送带上的所有包裹送达的船的最低运载能力。 * </p> * */ public class ShipWithinDays { public int shipWithinDays(int[] weights, int D) { int lo = 0, hi = Integer.MAX_VALUE; while (lo < hi) { int mid = lo + (hi - lo) / 2; if (canShip(weights, D, mid)) { hi = mid; } else { lo = mid+1; } } return lo; } /** * 定义函数canShip(D, K),来判断在最低承载力为K的情形下能否在DD天内送达所有包裹。我们所要做的就是按照传送带上货物的顺序,依次且尽可能多地往船上装载货物,当该艘船无法装下更多货物时,我们换一搜船,同时将天数加1。当运输完所有货物后,我们判断所用的天数是否小于等于D。 * 用二分查找的方式,来查找这个最低承载力,如果midmid可以完成任务,我们把查找范围缩减至[lo, mid][lo,mid](注意不是mid+1mid+1,因为mid可能是我们所求的解),否则我们去[mid+1, hi][mid+1,hi]区间中继续查找,详情见代码。 * */ private boolean canShip(int[] weights, int D, int K) { int cur = K; // cur 表示当前船的可用承载量 for (int weight: weights) { if (weight > K) return false; if (cur < weight) { cur = K; D--; } cur -= weight; } return D > 0; // 能否在D天内运完 } /** * 示例 <SUF>*/ public static void main(String[] args) { int ship = new ShipWithinDays().shipWithinDays(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5); System.out.println(ship); } }
0
1,063
459
1,182
483
1,135
465
1,182
483
1,506
592
true
true
true
true
true
false
60771_5
public class Bag { /*本代码实现了用回溯法实现01背包问题。亮点之一在于右子树的剪枝函数的设计非常之巧妙。 * 在回溯开始之前,首先对于背包中的物品按照单位重量价值进行排序,方便于后面右子树的剪枝操作。 * 在本代码中,省略了该排序过程,在初始化物品的重量和价值时,已经按照单位重量的价值排好了序。 * 该问题是一个典型的子集树问题,对于背包中的每一个物品,可以选择放入(左子树)或者不放入(右子树)。 * 依次对每个节点进行搜索,得到最优解。 * * 剪枝函数:对于左子树,如果放入物品的重量已经超过了背包的容量,则直接进行剪枝。 * 对于右子树,是否可以直接跳过本层的物品,直接下一层的搜索操作呢? * 这要取决于当前背包剩余的容量,依次取背包中剩余的物品中单位重量价值最大的物品(跳过本层物品), * 最终能否超过此前找到的最优解,如果能够超过,则可以向右搜索,不能超过,则右节点变为死节点。 * 对于寻找剩余物品的最高价值上界,按照背包中剩余空间依次取剩下的物品,当空间不足以取下一个 * 物品时,则将下一个物品的单位重量价值折算到现在的剩余空间中去计算理想最高上界。 * */ int n = 3; int capacity = 30; int[] weight = {16, 15, 15}; double[] value = {45, 25, 25}; int maxValue = 0; int tempValue; int tempWeight; int[] way = new int[n]; int[] bestWay = new int[n]; public void backTrack(int t) { //当前轮结束,如果价值为最大,保存起来 if (t > n - 1) { if (tempValue > maxValue) { maxValue = tempValue; for (int i = 0; i < n; i++) bestWay[i] = way[i]; } return; } //搜索左边节点 if (tempWeight + weight[t] <= capacity) { tempWeight += weight[t]; tempValue += value[t]; way[t] = 1; backTrack(t + 1); tempWeight -= weight[t]; tempValue -= value[t]; way[t] = 0; } //不装入这个物品,直接搜索右边的节点 if (bound(t + 1) >= maxValue) { backTrack(t + 1); } } //用于计算剩余物品的最高价值上界 public double bound(int k) { double maxLeft = tempValue; int leftWeight = capacity - tempWeight; //尽力依照单位重量价值次序装剩余的物品 while (k <= n - 1 && leftWeight > weight[k]) { leftWeight -= weight[k]; maxLeft += value[k]; k++; } //不能装时,用下一个物品的单位重量价值折算到剩余空间。 if (k <= n - 1) { maxLeft += value[k] / weight[k] * leftWeight; } return maxLeft; } public static void main(String[] args) { Bag b = new Bag(); b.backTrack(0); System.out.println("该背包能够取到的最大价值为:" + b.maxValue); System.out.println("取出的方法为:"); for (int i : b.bestWay) System.out.print(i + " "); } }
AyoungYa/basic_study
src/Bag.java
968
//尽力依照单位重量价值次序装剩余的物品
line_comment
zh-cn
public class Bag { /*本代码实现了用回溯法实现01背包问题。亮点之一在于右子树的剪枝函数的设计非常之巧妙。 * 在回溯开始之前,首先对于背包中的物品按照单位重量价值进行排序,方便于后面右子树的剪枝操作。 * 在本代码中,省略了该排序过程,在初始化物品的重量和价值时,已经按照单位重量的价值排好了序。 * 该问题是一个典型的子集树问题,对于背包中的每一个物品,可以选择放入(左子树)或者不放入(右子树)。 * 依次对每个节点进行搜索,得到最优解。 * * 剪枝函数:对于左子树,如果放入物品的重量已经超过了背包的容量,则直接进行剪枝。 * 对于右子树,是否可以直接跳过本层的物品,直接下一层的搜索操作呢? * 这要取决于当前背包剩余的容量,依次取背包中剩余的物品中单位重量价值最大的物品(跳过本层物品), * 最终能否超过此前找到的最优解,如果能够超过,则可以向右搜索,不能超过,则右节点变为死节点。 * 对于寻找剩余物品的最高价值上界,按照背包中剩余空间依次取剩下的物品,当空间不足以取下一个 * 物品时,则将下一个物品的单位重量价值折算到现在的剩余空间中去计算理想最高上界。 * */ int n = 3; int capacity = 30; int[] weight = {16, 15, 15}; double[] value = {45, 25, 25}; int maxValue = 0; int tempValue; int tempWeight; int[] way = new int[n]; int[] bestWay = new int[n]; public void backTrack(int t) { //当前轮结束,如果价值为最大,保存起来 if (t > n - 1) { if (tempValue > maxValue) { maxValue = tempValue; for (int i = 0; i < n; i++) bestWay[i] = way[i]; } return; } //搜索左边节点 if (tempWeight + weight[t] <= capacity) { tempWeight += weight[t]; tempValue += value[t]; way[t] = 1; backTrack(t + 1); tempWeight -= weight[t]; tempValue -= value[t]; way[t] = 0; } //不装入这个物品,直接搜索右边的节点 if (bound(t + 1) >= maxValue) { backTrack(t + 1); } } //用于计算剩余物品的最高价值上界 public double bound(int k) { double maxLeft = tempValue; int leftWeight = capacity - tempWeight; //尽力 <SUF> while (k <= n - 1 && leftWeight > weight[k]) { leftWeight -= weight[k]; maxLeft += value[k]; k++; } //不能装时,用下一个物品的单位重量价值折算到剩余空间。 if (k <= n - 1) { maxLeft += value[k] / weight[k] * leftWeight; } return maxLeft; } public static void main(String[] args) { Bag b = new Bag(); b.backTrack(0); System.out.println("该背包能够取到的最大价值为:" + b.maxValue); System.out.println("取出的方法为:"); for (int i : b.bestWay) System.out.print(i + " "); } }
0
816
12
968
19
919
13
968
19
1,328
31
false
false
false
false
false
true
33850_0
package atomic; import java.util.concurrent.atomic.LongAccumulator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.IntStream; /** * 并行计算,不在乎执行顺序 */ public class LongAccumulatorDemo { public static void main(String[] args) { LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x + y, 0); ExecutorService executorService = Executors.newFixedThreadPool(8); IntStream.range(1, 10).forEach(i -> executorService.submit(() -> longAccumulator.accumulate(i))); executorService.shutdown(); while(!executorService.isTerminated()) { // Thread.sleep(10); } longAccumulator.accumulate(1); System.out.println(longAccumulator.getThenReset()); } }
BBYYSS0917/juc-demo
src/main/java/atomic/LongAccumulatorDemo.java
202
/** * 并行计算,不在乎执行顺序 */
block_comment
zh-cn
package atomic; import java.util.concurrent.atomic.LongAccumulator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.stream.IntStream; /** * 并行计 <SUF>*/ public class LongAccumulatorDemo { public static void main(String[] args) { LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x + y, 0); ExecutorService executorService = Executors.newFixedThreadPool(8); IntStream.range(1, 10).forEach(i -> executorService.submit(() -> longAccumulator.accumulate(i))); executorService.shutdown(); while(!executorService.isTerminated()) { // Thread.sleep(10); } longAccumulator.accumulate(1); System.out.println(longAccumulator.getThenReset()); } }
0
182
12
202
15
209
13
202
15
258
24
false
false
false
false
false
true
24214_3
package run; import domains.*; //import domains.Pos; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; /** * Created by Hugh on 2014/12/29 0029. */ public class Run { public static void main(String[] args) throws Exception { Run run = new Run(); ShoppingChart shoppingChart = run.saxIndex(); ShoppingListChart shoppingListChart = new ShoppingListChart(shoppingChart); Pos pos = new Pos(); String result = pos.getShoppingList(shoppingListChart); System.out.println(result); } /* 功能:根据索引表导出购物清单,该函数依赖于saxListing 参数:无 返回值:购物车清单ShoppingChart,若读取时出错,则跳过该清单并提示出错的编码barCode */ public ShoppingChart saxIndex() throws Exception { ShoppingChart shoppingChart=new ShoppingChart(); SAXReader saxReader = new SAXReader(); Document document; document = saxReader.read("index.xml"); Element root = document.getRootElement(); Element goods=root.element("goods"); Iterator<Element> iterator = goods.elementIterator(); while (iterator.hasNext()) { Element element=iterator.next(); String barCode=element.getText(); Item item=saxListing(barCode); if(!item.isRecommended()) { System.out.println("Discount and promotion can't exist both, barCode: "+item.getBarCode()); } if(!item.isNull()){ shoppingChart.add(item); }else { System.out.println("Read error,item barcode: " + barCode); } } return shoppingChart; } /* 功能:根据产品编码从产品列表中寻找相应的产品,返回该商品属性Item 参数:String bacCord 产品的编码 返回值:Item 若成功,则返回该产品属性,否则,返回空Item */ public Item saxListing(String bacCode) throws DocumentException{ SAXReader saxReader = new SAXReader(); Document document; document = saxReader.read("listing.xml"); Element root = document.getRootElement(); Iterator<Element> iterator = root.elementIterator(); while (iterator.hasNext()) { Element element = iterator.next(); if(element.attributeValue("type").equals(bacCode)){ String name=element.elementText("name"); String unit=element.elementText("unit"); double price=Double.parseDouble(element.elementText("price")); double discount=Double.parseDouble(element.elementText("discount")); boolean promotion = Boolean.parseBoolean(element.elementText("promotion")); double vipDiscount=Double.parseDouble(element.elementText("vipDiscount")); return new Item(bacCode,name,unit,price,discount,promotion,vipDiscount); } } return new Item(); } }
BJUT-Agile-Group/Pos-Team3
src/run/Run.java
749
/* 功能:根据产品编码从产品列表中寻找相应的产品,返回该商品属性Item 参数:String bacCord 产品的编码 返回值:Item 若成功,则返回该产品属性,否则,返回空Item */
block_comment
zh-cn
package run; import domains.*; //import domains.Pos; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; /** * Created by Hugh on 2014/12/29 0029. */ public class Run { public static void main(String[] args) throws Exception { Run run = new Run(); ShoppingChart shoppingChart = run.saxIndex(); ShoppingListChart shoppingListChart = new ShoppingListChart(shoppingChart); Pos pos = new Pos(); String result = pos.getShoppingList(shoppingListChart); System.out.println(result); } /* 功能:根据索引表导出购物清单,该函数依赖于saxListing 参数:无 返回值:购物车清单ShoppingChart,若读取时出错,则跳过该清单并提示出错的编码barCode */ public ShoppingChart saxIndex() throws Exception { ShoppingChart shoppingChart=new ShoppingChart(); SAXReader saxReader = new SAXReader(); Document document; document = saxReader.read("index.xml"); Element root = document.getRootElement(); Element goods=root.element("goods"); Iterator<Element> iterator = goods.elementIterator(); while (iterator.hasNext()) { Element element=iterator.next(); String barCode=element.getText(); Item item=saxListing(barCode); if(!item.isRecommended()) { System.out.println("Discount and promotion can't exist both, barCode: "+item.getBarCode()); } if(!item.isNull()){ shoppingChart.add(item); }else { System.out.println("Read error,item barcode: " + barCode); } } return shoppingChart; } /* 功能: <SUF>*/ public Item saxListing(String bacCode) throws DocumentException{ SAXReader saxReader = new SAXReader(); Document document; document = saxReader.read("listing.xml"); Element root = document.getRootElement(); Iterator<Element> iterator = root.elementIterator(); while (iterator.hasNext()) { Element element = iterator.next(); if(element.attributeValue("type").equals(bacCode)){ String name=element.elementText("name"); String unit=element.elementText("unit"); double price=Double.parseDouble(element.elementText("price")); double discount=Double.parseDouble(element.elementText("discount")); boolean promotion = Boolean.parseBoolean(element.elementText("promotion")); double vipDiscount=Double.parseDouble(element.elementText("vipDiscount")); return new Item(bacCode,name,unit,price,discount,promotion,vipDiscount); } } return new Item(); } }
0
645
55
749
59
777
54
749
59
929
95
false
false
false
false
false
true
37953_14
package BOBO.web; import BOBO.pojo.Page; import BOBO.pojo.Sct; import BOBO.pojo.Student; import BOBO.service.Impl.SctServiceImpl; import BOBO.service.Impl.StudentServiceImpl; import BOBO.service.SctService; import BOBO.service.StudentService; import BOBO.utils.WebUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; public class StudentServlet extends BaseServlet { //调用对应的service层函数 private StudentService studentService = new StudentServiceImpl(); private SctService sctService = new SctServiceImpl(); //添加学生信息 protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*获取当前页码*/ int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); /*保证添加信息后跳到最后一页,+100*/ pageNo += 100; /*把获取到的对象注入映射Map中*/ Student student = WebUtils.WebUtils(req.getParameterMap(), new Student()); /*调用service方法添加*/ studentService.addStudent(student); /*重定向地址到信息展示,加上属性pageNo*/ resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + pageNo); } //删除学生信息 protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*获取点击删除的ID*/ int id = WebUtils.parseInt(req.getParameter("id"), 0); /*新建一个Sct选课对象,并通过学号ID查找是否存在*/ Sct sct = sctService.querySctbySno(id); /*不存在,则直接删*/ if (sct == null) { studentService.deleteStudent(id); } /*存在,先删选课信息,再删学生信息,防止产生依赖,报错*/ else { sctService.deleteSct(sct.getSct_no()); studentService.deleteStudent(id); } /*重定向地址到信息展示,加上属性pageNo*/ resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + req.getParameter("pageNo")); } //修改学生信息 protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*把获取到的对象注入映射Map中*/ Student student = WebUtils.WebUtils(req.getParameterMap(), new Student()); studentService.updateStudent(student); resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + req.getParameter("pageNo")); } //获取学生信息,获取后跳到学生编辑界面 protected void getStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int id = WebUtils.parseInt(req.getParameter("id"), 0); Student student = studentService.queryStudentbyId(id); /*把student存到resquest域中*/ req.setAttribute("studnet", student); /*进行编辑页面跳转*/ req.getRequestDispatcher("/page/edit_page/Student_edit.jsp").forward(req, resp); } //处理分页服务 protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE); /*新建一个page对象*/ Page<Student> page = studentService.page(pageNo, pageSize); /*设置Url,用于分页处理*/ page.setUrl("studentServlet?action=page"); req.setAttribute("page", page); req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp); } //通过学号查找学生信息 protected void findByNo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int sno = WebUtils.parseInt(req.getParameter("sno"), 1); int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE); Page<Student> page = studentService.findOneByNo(pageNo, pageSize, sno); page.setUrl("studentServlet?action=findByNo&sno=" + sno); req.setAttribute("page", page); req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp); } protected void findByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int sno = WebUtils.parseInt(req.getParameter("sno"), 1); int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE); // String sname = new String(req.getParameter("sname").getBytes("ISO-8859-1"),"utf-8"); String sname = req.getParameter("sname"); Page<Student> page = studentService.findOneByName(pageNo, pageSize, sname); page.setUrl("studentServlet?action=findByName&sname=" + sname); req.setAttribute("page", page); req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp); } //列出所有学生信息(没用) protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<Student> students = studentService.queryStudents(); req.setAttribute("students", students); req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp); } }
BOBO-ZzB/Student_select_class-
src/BOBO/web/StudentServlet.java
1,346
/*把获取到的对象注入映射Map中*/
block_comment
zh-cn
package BOBO.web; import BOBO.pojo.Page; import BOBO.pojo.Sct; import BOBO.pojo.Student; import BOBO.service.Impl.SctServiceImpl; import BOBO.service.Impl.StudentServiceImpl; import BOBO.service.SctService; import BOBO.service.StudentService; import BOBO.utils.WebUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; public class StudentServlet extends BaseServlet { //调用对应的service层函数 private StudentService studentService = new StudentServiceImpl(); private SctService sctService = new SctServiceImpl(); //添加学生信息 protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*获取当前页码*/ int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); /*保证添加信息后跳到最后一页,+100*/ pageNo += 100; /*把获取到的对象注入映射Map中*/ Student student = WebUtils.WebUtils(req.getParameterMap(), new Student()); /*调用service方法添加*/ studentService.addStudent(student); /*重定向地址到信息展示,加上属性pageNo*/ resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + pageNo); } //删除学生信息 protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*获取点击删除的ID*/ int id = WebUtils.parseInt(req.getParameter("id"), 0); /*新建一个Sct选课对象,并通过学号ID查找是否存在*/ Sct sct = sctService.querySctbySno(id); /*不存在,则直接删*/ if (sct == null) { studentService.deleteStudent(id); } /*存在,先删选课信息,再删学生信息,防止产生依赖,报错*/ else { sctService.deleteSct(sct.getSct_no()); studentService.deleteStudent(id); } /*重定向地址到信息展示,加上属性pageNo*/ resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + req.getParameter("pageNo")); } //修改学生信息 protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /*把获取 <SUF>*/ Student student = WebUtils.WebUtils(req.getParameterMap(), new Student()); studentService.updateStudent(student); resp.sendRedirect(req.getContextPath() + "/studentServlet?action=page&pageNo=" + req.getParameter("pageNo")); } //获取学生信息,获取后跳到学生编辑界面 protected void getStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int id = WebUtils.parseInt(req.getParameter("id"), 0); Student student = studentService.queryStudentbyId(id); /*把student存到resquest域中*/ req.setAttribute("studnet", student); /*进行编辑页面跳转*/ req.getRequestDispatcher("/page/edit_page/Student_edit.jsp").forward(req, resp); } //处理分页服务 protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE); /*新建一个page对象*/ Page<Student> page = studentService.page(pageNo, pageSize); /*设置Url,用于分页处理*/ page.setUrl("studentServlet?action=page"); req.setAttribute("page", page); req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp); } //通过学号查找学生信息 protected void findByNo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int sno = WebUtils.parseInt(req.getParameter("sno"), 1); int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE); Page<Student> page = studentService.findOneByNo(pageNo, pageSize, sno); page.setUrl("studentServlet?action=findByNo&sno=" + sno); req.setAttribute("page", page); req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp); } protected void findByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int sno = WebUtils.parseInt(req.getParameter("sno"), 1); int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1); int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE); // String sname = new String(req.getParameter("sname").getBytes("ISO-8859-1"),"utf-8"); String sname = req.getParameter("sname"); Page<Student> page = studentService.findOneByName(pageNo, pageSize, sname); page.setUrl("studentServlet?action=findByName&sname=" + sname); req.setAttribute("page", page); req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp); } //列出所有学生信息(没用) protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { List<Student> students = studentService.queryStudents(); req.setAttribute("students", students); req.getRequestDispatcher("/page/info_pages/Student.jsp").forward(req, resp); } }
0
1,141
11
1,346
11
1,404
10
1,346
11
1,705
21
false
false
false
false
false
true
28273_2
package ir; import ir.type.Type; import ir.User.Use; import java.util.LinkedList; /* * LLVM 中 Value Use User 的关系介绍 * https://buaa-se-compiling.github.io/miniSysY-tutorial/pre/design_hints.html */ /* * Value 类,几乎所有实体都是Value的子类 * */ public class Value { public Value(Type type) { this.type = type; uses = new LinkedList<>(); } public Type type; public String name = ""; protected LinkedList<Use> uses; public boolean needName = true; //将所有对 this 的使用换为对v的使用 public void replaceAllUseWith(Value v) { for (Use use : uses) { use.setV(v); v.uses.add(use); } } }
BUAA-SE-Compiling/miniSysY_example_compiler
src/ir/Value.java
209
//将所有对 this 的使用换为对v的使用
line_comment
zh-cn
package ir; import ir.type.Type; import ir.User.Use; import java.util.LinkedList; /* * LLVM 中 Value Use User 的关系介绍 * https://buaa-se-compiling.github.io/miniSysY-tutorial/pre/design_hints.html */ /* * Value 类,几乎所有实体都是Value的子类 * */ public class Value { public Value(Type type) { this.type = type; uses = new LinkedList<>(); } public Type type; public String name = ""; protected LinkedList<Use> uses; public boolean needName = true; //将所 <SUF> public void replaceAllUseWith(Value v) { for (Use use : uses) { use.setV(v); v.uses.add(use); } } }
0
173
13
209
13
217
12
209
13
251
17
false
false
false
false
false
true
39934_1
import java.util.ArrayList; import java.util.Scanner; public class ClearUp { private static int[][] arr = new int[9][9]; public static void main(String[] args) { newGame(); displayRound(); checkAll(); return; } private static void checkAll() { ArrayList<Integer> boomList = new ArrayList<>(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (isBoom(arr[i][j], i, j, Directions.TOP) || isBoom(arr[i][j], i, j, Directions.BOTTOM) || isBoom(arr[i][j], i, j, Directions.LEFT) || isBoom(arr[i][j], i, j, Directions.RIGHT)) { System.out.println("point ---- i " + i + " j " + j + " will boom"); if (!boomList.contains(i * 10 + j)) { boomList.add(i * 10 + j); // save } } } } System.out.println("check over~~~~~~~~~~~~~~~~~~"); } private static boolean isBoom(int type, int x, int y, Directions d) { if (d == Directions.TOP) { if (x + 2 <= 8) { if (type == arr[x + 1][y] && type == arr[x + 2][y]) { return true; } } else { // 超过索引 return false; } } else if (d == Directions.BOTTOM) { if (x - 2 >= 0) { if (type == arr[x - 1][y] && type == arr[x - 2][y]) { return true; } } else { return false; } } else if (d == Directions.LEFT) { if (y - 2 >= 0) { if (type == arr[x][y - 1] && type == arr[x][y - 2]) { return true; } } else { return false; } } else if (d == Directions.RIGHT) { if (y + 2 <= 8) { if (type == arr[x][y + 1] && type == arr[x][y + 2]) { return true; } } else { return false; } } return false; } /** */ private static void displayRound() { System.out.println("--------------------------------"); for (int i = 0; i < 9; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < 9; j++) { String s = "" + arr[i][j]; sb.append("" + s); } System.out.println(sb.toString()); } System.out.println("--------------------------------"); } /** */ private static void newGame() { System.out.println("new game ------------"); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { arr[i][j] = (int) (Math.random() * 8) + 1; } } } /** * 枚举四个方向 */ enum Directions { TOP, BOTTOM, LEFT, RIGHT } }
BUGyyc/myMd
#.code/ClearUp.java
813
// 超过索引
line_comment
zh-cn
import java.util.ArrayList; import java.util.Scanner; public class ClearUp { private static int[][] arr = new int[9][9]; public static void main(String[] args) { newGame(); displayRound(); checkAll(); return; } private static void checkAll() { ArrayList<Integer> boomList = new ArrayList<>(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (isBoom(arr[i][j], i, j, Directions.TOP) || isBoom(arr[i][j], i, j, Directions.BOTTOM) || isBoom(arr[i][j], i, j, Directions.LEFT) || isBoom(arr[i][j], i, j, Directions.RIGHT)) { System.out.println("point ---- i " + i + " j " + j + " will boom"); if (!boomList.contains(i * 10 + j)) { boomList.add(i * 10 + j); // save } } } } System.out.println("check over~~~~~~~~~~~~~~~~~~"); } private static boolean isBoom(int type, int x, int y, Directions d) { if (d == Directions.TOP) { if (x + 2 <= 8) { if (type == arr[x + 1][y] && type == arr[x + 2][y]) { return true; } } else { // 超过 <SUF> return false; } } else if (d == Directions.BOTTOM) { if (x - 2 >= 0) { if (type == arr[x - 1][y] && type == arr[x - 2][y]) { return true; } } else { return false; } } else if (d == Directions.LEFT) { if (y - 2 >= 0) { if (type == arr[x][y - 1] && type == arr[x][y - 2]) { return true; } } else { return false; } } else if (d == Directions.RIGHT) { if (y + 2 <= 8) { if (type == arr[x][y + 1] && type == arr[x][y + 2]) { return true; } } else { return false; } } return false; } /** */ private static void displayRound() { System.out.println("--------------------------------"); for (int i = 0; i < 9; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < 9; j++) { String s = "" + arr[i][j]; sb.append("" + s); } System.out.println(sb.toString()); } System.out.println("--------------------------------"); } /** */ private static void newGame() { System.out.println("new game ------------"); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { arr[i][j] = (int) (Math.random() * 8) + 1; } } } /** * 枚举四个方向 */ enum Directions { TOP, BOTTOM, LEFT, RIGHT } }
0
741
7
813
4
881
4
813
4
950
6
false
false
false
false
false
true
17335_1
package com.match.springmvc.entities; import org.springframework.stereotype.Component; /** * 教师-比赛-队伍 * @author lenovo * */ @Component public class TrTeam { private Integer TrCTid; private Teacher teacher; private String Tname; private String Tdepartment; private Competition competition; private String Coname; private Team team; private Integer Workload; // 教师工作量(个人) public Integer getTrCTid() { return TrCTid; } public void setTrCTid(Integer trCTid) { TrCTid = trCTid; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public String getTname() { return Tname; } public String getTdepartment() { return Tdepartment; } public void setTdepartment(String tdepartment) { Tdepartment = tdepartment; } public void setTname(String tname) { Tname = tname; } public Team getTeam() { return team; } public void setTeam(Team team) { this.team = team; } public Competition getCompetition() { return competition; } public void setCompetition(Competition competition) { this.competition = competition; } public String getConame() { return Coname; } public void setConame(String coname) { Coname = coname; } public Integer getWorkload() { return Workload; } public void setWorkload(Integer workload) { Workload = workload; } }
BYFOR/competition-system-of-hbfu
src/com/match/springmvc/entities/TrTeam.java
457
// 教师工作量(个人)
line_comment
zh-cn
package com.match.springmvc.entities; import org.springframework.stereotype.Component; /** * 教师-比赛-队伍 * @author lenovo * */ @Component public class TrTeam { private Integer TrCTid; private Teacher teacher; private String Tname; private String Tdepartment; private Competition competition; private String Coname; private Team team; private Integer Workload; // 教师 <SUF> public Integer getTrCTid() { return TrCTid; } public void setTrCTid(Integer trCTid) { TrCTid = trCTid; } public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public String getTname() { return Tname; } public String getTdepartment() { return Tdepartment; } public void setTdepartment(String tdepartment) { Tdepartment = tdepartment; } public void setTname(String tname) { Tname = tname; } public Team getTeam() { return team; } public void setTeam(Team team) { this.team = team; } public Competition getCompetition() { return competition; } public void setCompetition(Competition competition) { this.competition = competition; } public String getConame() { return Coname; } public void setConame(String coname) { Coname = coname; } public Integer getWorkload() { return Workload; } public void setWorkload(Integer workload) { Workload = workload; } }
0
370
9
455
10
482
9
455
10
552
14
false
false
false
false
false
true
40637_36
public class MiGong { //编写一个main方法 public static void main(String[] args) { //思路 //1. 先创建迷宫,用二维数组表示 int[][] map = new int[8][7]; //2. 先规定 map 数组的元素值: 0 表示可以走 1 表示障碍物 int[][] map = new int[8][7]; //3. 将最上面的一行和最下面的一行,全部设置为1 for(int i = 0; i < 7; i++) { map[0][i] = 1; map[7][i] = 1; } //4.将最右面的一列和最左面的一列,全部设置为1 for(int i = 0; i < 8; i++) { map[i][0] = 1; map[i][6] = 1; } map[3][1] = 1; map[3][2] = 1; map[2][2] = 1; //测试回溯 // map[2][1] = 1; // map[2][2] = 1; // map[1][2] = 1; //输出当前的地图 System.out.println("=====当前地图情况======"); for(int i = 0; i < map.length; i++) { for(int j = 0; j < map[i].length; j++) { System.out.print(map[i][j] + " ");//输出一行 } System.out.println(); } //使用findWay给老鼠找路 C c1 = new C(); //下右上左 c1.findWay(map, 1, 1); System.out.println("\n====找路的情况如下====="); for(int i = 0; i < map.length; i++) { for(int j = 0; j < map[i].length; j++) { System.out.print(map[i][j] + " ");//输出一行 } System.out.println(); } } } class C { //使用递归回溯的思想来解决老鼠出迷宫 //老韩解读 //1. findWay方法就是专门来找出迷宫的路径 //2. 如果找到,就返回 true ,否则返回false //3. map 就是二维数组,即表示迷宫 //4. i,j 就是老鼠的位置,初始化的位置为(1,1) //5. 因为我们是递归的找路,所以我先规定 map数组的各个值的含义 // 0 表示可以走 1 表示障碍物 2 表示可以走 3 表示走过,但是走不通是死路 //6. 当map[6][5] =2 就说明找到通路,就可以结束,否则就继续找. //7. 先确定老鼠找路策略 下->右->上->左 public boolean findWay(int[][] map , int i, int j) { if(map[6][5] == 2) {//说明已经找到 return true; } else { if(map[i][j] == 0) {//当前这个位置0,说明表示可以走 //我们假定可以走通 map[i][j] = 2; //使用找路策略,来确定该位置是否真的可以走通 //下->右->上->左 if(findWay(map, i + 1, j)) {//先走下 return true; } else if(findWay(map, i, j + 1)){//右 return true; } else if(findWay(map, i-1, j)) {//上 return true; } else if(findWay(map, i, j-1)){//左 return true; } else { map[i][j] = 3; return false; } } else { //map[i][j] = 1 , 2, 3 return false; } } } //修改找路策略,看看路径是否有变化 //下->右->上->左 ==> 上->右->下->左 public boolean findWay2(int[][] map , int i, int j) { if(map[6][5] == 2) {//说明已经找到 return true; } else { if(map[i][j] == 0) {//当前这个位置0,说明表示可以走 //我们假定可以走通 map[i][j] = 2; //使用找路策略,来确定该位置是否真的可以走通 //上->右->下->左 if(findWay2(map, i - 1, j)) {//先走上 return true; } else if(findWay2(map, i, j + 1)){//右 return true; } else if(findWay2(map, i+1, j)) {//下 return true; } else if(findWay2(map, i, j-1)){//左 return true; } else { map[i][j] = 3; return false; } } else { //map[i][j] = 1 , 2, 3 return false; } } } }
BabysBreath017/HelloWorld
MiGong.java
1,372
//使用找路策略,来确定该位置是否真的可以走通
line_comment
zh-cn
public class MiGong { //编写一个main方法 public static void main(String[] args) { //思路 //1. 先创建迷宫,用二维数组表示 int[][] map = new int[8][7]; //2. 先规定 map 数组的元素值: 0 表示可以走 1 表示障碍物 int[][] map = new int[8][7]; //3. 将最上面的一行和最下面的一行,全部设置为1 for(int i = 0; i < 7; i++) { map[0][i] = 1; map[7][i] = 1; } //4.将最右面的一列和最左面的一列,全部设置为1 for(int i = 0; i < 8; i++) { map[i][0] = 1; map[i][6] = 1; } map[3][1] = 1; map[3][2] = 1; map[2][2] = 1; //测试回溯 // map[2][1] = 1; // map[2][2] = 1; // map[1][2] = 1; //输出当前的地图 System.out.println("=====当前地图情况======"); for(int i = 0; i < map.length; i++) { for(int j = 0; j < map[i].length; j++) { System.out.print(map[i][j] + " ");//输出一行 } System.out.println(); } //使用findWay给老鼠找路 C c1 = new C(); //下右上左 c1.findWay(map, 1, 1); System.out.println("\n====找路的情况如下====="); for(int i = 0; i < map.length; i++) { for(int j = 0; j < map[i].length; j++) { System.out.print(map[i][j] + " ");//输出一行 } System.out.println(); } } } class C { //使用递归回溯的思想来解决老鼠出迷宫 //老韩解读 //1. findWay方法就是专门来找出迷宫的路径 //2. 如果找到,就返回 true ,否则返回false //3. map 就是二维数组,即表示迷宫 //4. i,j 就是老鼠的位置,初始化的位置为(1,1) //5. 因为我们是递归的找路,所以我先规定 map数组的各个值的含义 // 0 表示可以走 1 表示障碍物 2 表示可以走 3 表示走过,但是走不通是死路 //6. 当map[6][5] =2 就说明找到通路,就可以结束,否则就继续找. //7. 先确定老鼠找路策略 下->右->上->左 public boolean findWay(int[][] map , int i, int j) { if(map[6][5] == 2) {//说明已经找到 return true; } else { if(map[i][j] == 0) {//当前这个位置0,说明表示可以走 //我们假定可以走通 map[i][j] = 2; //使用找路策略,来确定该位置是否真的可以走通 //下->右->上->左 if(findWay(map, i + 1, j)) {//先走下 return true; } else if(findWay(map, i, j + 1)){//右 return true; } else if(findWay(map, i-1, j)) {//上 return true; } else if(findWay(map, i, j-1)){//左 return true; } else { map[i][j] = 3; return false; } } else { //map[i][j] = 1 , 2, 3 return false; } } } //修改找路策略,看看路径是否有变化 //下->右->上->左 ==> 上->右->下->左 public boolean findWay2(int[][] map , int i, int j) { if(map[6][5] == 2) {//说明已经找到 return true; } else { if(map[i][j] == 0) {//当前这个位置0,说明表示可以走 //我们假定可以走通 map[i][j] = 2; //使用 <SUF> //上->右->下->左 if(findWay2(map, i - 1, j)) {//先走上 return true; } else if(findWay2(map, i, j + 1)){//右 return true; } else if(findWay2(map, i+1, j)) {//下 return true; } else if(findWay2(map, i, j-1)){//左 return true; } else { map[i][j] = 3; return false; } } else { //map[i][j] = 1 , 2, 3 return false; } } } }
0
1,246
15
1,372
16
1,321
15
1,372
16
1,868
30
false
false
false
false
false
true
20733_1
package userInterface; import entity.Department; import entity.Hospital; import entity.Patient; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import logic.DataStructure.Algorithms; import logic.Util; import java.util.ArrayList; import java.util.List; public class PatientSearch { // 创建Util单例 Util util = Util.getInstance(); // 创建医院单例 Hospital hospital = Hospital.getInstance(); // 创建算法类单例 Algorithms algorithms = Algorithms.getInstance(); ObservableList<Patient> patientObservableList = FXCollections.observableArrayList(); @FXML private TableColumn<Patient, String> numColumn; @FXML private TableColumn<Patient, String> timeColumn; @FXML private Button search; @FXML private ChoiceBox<String> departmentBox; @FXML private TableColumn<Patient, String> nameColumn; @FXML private TableView<Patient> infoTable; @FXML private Button idSort; @FXML private Button nameSort; @FXML private void initialize(){ infoTable.setItems(patientObservableList); timeColumn.setCellValueFactory(cellData -> cellData.getValue().currentInsertTimeProperty()); numColumn.setCellValueFactory(cellData -> cellData.getValue().hosRecordNumProperty()); nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); } @FXML private void initDepartment(){ ObservableList<String> choices = FXCollections.observableArrayList("内科","外科","医院"); departmentBox.setItems(choices); } @FXML private void setSearch(){ String range = departmentBox.getValue(); if(range == null){ util.errorInformationAlert("请选择查询范围!"); return; } if(range.equals("内科")){ for(Department d : hospital.getDepartmentList()){ if(d.getName().equals("内科")){ patientObservableList.clear(); patientObservableList.addAll(d.getPatientList()); } } }else if(range.equals("外科")){ for(Department d : hospital.getDepartmentList()){ if(d.getName().equals("外科")){ patientObservableList.clear(); patientObservableList.addAll(d.getPatientList()); } } }else if(range.equals("医院")){ patientObservableList.clear(); for(Department d : hospital.getDepartmentList()){ patientObservableList.addAll(d.getPatientList()); } } } @FXML private void setIdSort(){ List<Patient> patientList = new ArrayList<>(); for(Patient p : patientObservableList){ patientList.add(p); } algorithms.mergeSort(patientList, true); patientObservableList.clear(); patientObservableList.addAll(patientList); } @FXML private void setNameSort(){ List<Patient> patientList = new ArrayList<>(); for(Patient p : patientObservableList){ patientList.add(p); } algorithms.mergeSort(patientList, false); patientObservableList.clear(); patientObservableList.addAll(patientList); } }
BaiWenchao/HISProject2.0
src/userInterface/PatientSearch.java
766
// 创建医院单例
line_comment
zh-cn
package userInterface; import entity.Department; import entity.Hospital; import entity.Patient; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import logic.DataStructure.Algorithms; import logic.Util; import java.util.ArrayList; import java.util.List; public class PatientSearch { // 创建Util单例 Util util = Util.getInstance(); // 创建 <SUF> Hospital hospital = Hospital.getInstance(); // 创建算法类单例 Algorithms algorithms = Algorithms.getInstance(); ObservableList<Patient> patientObservableList = FXCollections.observableArrayList(); @FXML private TableColumn<Patient, String> numColumn; @FXML private TableColumn<Patient, String> timeColumn; @FXML private Button search; @FXML private ChoiceBox<String> departmentBox; @FXML private TableColumn<Patient, String> nameColumn; @FXML private TableView<Patient> infoTable; @FXML private Button idSort; @FXML private Button nameSort; @FXML private void initialize(){ infoTable.setItems(patientObservableList); timeColumn.setCellValueFactory(cellData -> cellData.getValue().currentInsertTimeProperty()); numColumn.setCellValueFactory(cellData -> cellData.getValue().hosRecordNumProperty()); nameColumn.setCellValueFactory(cellData -> cellData.getValue().nameProperty()); } @FXML private void initDepartment(){ ObservableList<String> choices = FXCollections.observableArrayList("内科","外科","医院"); departmentBox.setItems(choices); } @FXML private void setSearch(){ String range = departmentBox.getValue(); if(range == null){ util.errorInformationAlert("请选择查询范围!"); return; } if(range.equals("内科")){ for(Department d : hospital.getDepartmentList()){ if(d.getName().equals("内科")){ patientObservableList.clear(); patientObservableList.addAll(d.getPatientList()); } } }else if(range.equals("外科")){ for(Department d : hospital.getDepartmentList()){ if(d.getName().equals("外科")){ patientObservableList.clear(); patientObservableList.addAll(d.getPatientList()); } } }else if(range.equals("医院")){ patientObservableList.clear(); for(Department d : hospital.getDepartmentList()){ patientObservableList.addAll(d.getPatientList()); } } } @FXML private void setIdSort(){ List<Patient> patientList = new ArrayList<>(); for(Patient p : patientObservableList){ patientList.add(p); } algorithms.mergeSort(patientList, true); patientObservableList.clear(); patientObservableList.addAll(patientList); } @FXML private void setNameSort(){ List<Patient> patientList = new ArrayList<>(); for(Patient p : patientObservableList){ patientList.add(p); } algorithms.mergeSort(patientList, false); patientObservableList.clear(); patientObservableList.addAll(patientList); } }
0
661
6
766
6
812
5
766
6
974
10
false
false
false
false
false
true
10771_9
package com.baidu.speech.restapi.asrdemo; import com.baidu.speech.restapi.common.ConnUtil; import com.baidu.speech.restapi.common.DemoException; import com.baidu.speech.restapi.common.TokenHolder; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class AsrMain { private final boolean METHOD_RAW = false; // 默认以json方式上传音频文件 // 填写网页上申请的appkey 如 $apiKey="g8eBUMSokVB1BHGmgxxxxxx" private final String APP_KEY = "kVcnfD9iW2XVZSMaLXXXXXXX"; // 填写网页上申请的APP SECRET 如 $SECRET_KEY="94dc99566550d87f8fa8ece112xxxxx" private final String SECRET_KEY = "O9o1O213UgG5LFn0bDGNtoRNXXXXXX"; // 需要识别的文件 private final String FILENAME = "16k.pcm"; // 文件格式, 支持pcm/wav/amr 格式,极速版额外支持m4a 格式 private final String FORMAT = FILENAME.substring(FILENAME.length() - 3); private String CUID = "1234567JAVA"; // 采样率固定值 private final int RATE = 16000; private String URL; private int DEV_PID; //private int LM_ID;//测试自训练平台需要打开此注释 private String SCOPE; // 普通版 参数 { URL = "http://vop.baidu.com/server_api"; // 可以改为https // 1537 表示识别普通话,使用输入法模型。 其它语种参见文档 DEV_PID = 1537; SCOPE = "audio_voice_assistant_get"; } // 自训练平台 参数 /*{ //自训练平台模型上线后,您会看见 第二步:“”获取专属模型参数pid:8001,modelid:1234”,按照这个信息获取 dev_pid=8001,lm_id=1234 DEV_PID = 8001; LM_ID = 1234; }*/ /* 极速版 参数 { URL = "http://vop.baidu.com/pro_api"; // 可以改为https DEV_PID = 80001; SCOPE = "brain_enhanced_asr"; } */ /* 忽略scope检查,非常旧的应用可能没有 { SCOPE = null; } */ public static void main(String[] args) throws IOException, DemoException { AsrMain demo = new AsrMain(); // 填写下面信息 String result = demo.run(); System.out.println("识别结束:结果是:"); System.out.println(result); // 如果显示乱码,请打开result.txt查看 File file = new File("result.txt"); FileWriter fo = new FileWriter(file); fo.write(result); fo.close(); System.out.println("Result also wrote into " + file.getAbsolutePath()); } public String run() throws IOException, DemoException { TokenHolder holder = new TokenHolder(APP_KEY, SECRET_KEY, SCOPE); holder.resfresh(); String token = holder.getToken(); String result = null; if (METHOD_RAW) { result = runRawPostMethod(token); } else { result = runJsonPostMethod(token); } return result; } private String runRawPostMethod(String token) throws IOException, DemoException { String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&token=" + token; //测试自训练平台需要打开以下信息 //String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&lm_id="+ LM_ID + "&token=" + token; String contentTypeStr = "audio/" + FORMAT + "; rate=" + RATE; //System.out.println(url2); byte[] content = getFileContent(FILENAME); HttpURLConnection conn = (HttpURLConnection) new URL(url2).openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", contentTypeStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(content); conn.getOutputStream().close(); System.out.println("url is " + url2); System.out.println("header is " + "Content-Type :" + contentTypeStr); String result = ConnUtil.getResponseString(conn); return result; } public String runJsonPostMethod(String token) throws DemoException, IOException { byte[] content = getFileContent(FILENAME); String speech = base64Encode(content); JSONObject params = new JSONObject(); params.put("dev_pid", DEV_PID); //params.put("lm_id",LM_ID);//测试自训练平台需要打开注释 params.put("format", FORMAT); params.put("rate", RATE); params.put("token", token); params.put("cuid", CUID); params.put("channel", "1"); params.put("len", content.length); params.put("speech", speech); // System.out.println(params.toString()); HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setDoOutput(true); conn.getOutputStream().write(params.toString().getBytes()); conn.getOutputStream().close(); String result = ConnUtil.getResponseString(conn); params.put("speech", "base64Encode(getFileContent(FILENAME))"); System.out.println("url is : " + URL); System.out.println("params is :" + params.toString()); return result; } private byte[] getFileContent(String filename) throws DemoException, IOException { File file = new File(filename); if (!file.canRead()) { System.err.println("文件不存在或者不可读: " + file.getAbsolutePath()); throw new DemoException("file cannot read: " + file.getAbsolutePath()); } FileInputStream is = null; try { is = new FileInputStream(file); return ConnUtil.getInputStreamContent(is); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } private String base64Encode(byte[] content) { /** Base64.Encoder encoder = Base64.getEncoder(); // JDK 1.8 推荐方法 String str = encoder.encodeToString(content); **/ char[] chars = Base64Util.encode(content); // 1.7 及以下,不推荐,请自行跟换相关库 String str = new String(chars); return str; } }
Baidu-AIP/speech-demo
rest-api-asr/java/src/main/java/com/baidu/speech/restapi/asrdemo/AsrMain.java
1,754
// 1537 表示识别普通话,使用输入法模型。 其它语种参见文档
line_comment
zh-cn
package com.baidu.speech.restapi.asrdemo; import com.baidu.speech.restapi.common.ConnUtil; import com.baidu.speech.restapi.common.DemoException; import com.baidu.speech.restapi.common.TokenHolder; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class AsrMain { private final boolean METHOD_RAW = false; // 默认以json方式上传音频文件 // 填写网页上申请的appkey 如 $apiKey="g8eBUMSokVB1BHGmgxxxxxx" private final String APP_KEY = "kVcnfD9iW2XVZSMaLXXXXXXX"; // 填写网页上申请的APP SECRET 如 $SECRET_KEY="94dc99566550d87f8fa8ece112xxxxx" private final String SECRET_KEY = "O9o1O213UgG5LFn0bDGNtoRNXXXXXX"; // 需要识别的文件 private final String FILENAME = "16k.pcm"; // 文件格式, 支持pcm/wav/amr 格式,极速版额外支持m4a 格式 private final String FORMAT = FILENAME.substring(FILENAME.length() - 3); private String CUID = "1234567JAVA"; // 采样率固定值 private final int RATE = 16000; private String URL; private int DEV_PID; //private int LM_ID;//测试自训练平台需要打开此注释 private String SCOPE; // 普通版 参数 { URL = "http://vop.baidu.com/server_api"; // 可以改为https // 15 <SUF> DEV_PID = 1537; SCOPE = "audio_voice_assistant_get"; } // 自训练平台 参数 /*{ //自训练平台模型上线后,您会看见 第二步:“”获取专属模型参数pid:8001,modelid:1234”,按照这个信息获取 dev_pid=8001,lm_id=1234 DEV_PID = 8001; LM_ID = 1234; }*/ /* 极速版 参数 { URL = "http://vop.baidu.com/pro_api"; // 可以改为https DEV_PID = 80001; SCOPE = "brain_enhanced_asr"; } */ /* 忽略scope检查,非常旧的应用可能没有 { SCOPE = null; } */ public static void main(String[] args) throws IOException, DemoException { AsrMain demo = new AsrMain(); // 填写下面信息 String result = demo.run(); System.out.println("识别结束:结果是:"); System.out.println(result); // 如果显示乱码,请打开result.txt查看 File file = new File("result.txt"); FileWriter fo = new FileWriter(file); fo.write(result); fo.close(); System.out.println("Result also wrote into " + file.getAbsolutePath()); } public String run() throws IOException, DemoException { TokenHolder holder = new TokenHolder(APP_KEY, SECRET_KEY, SCOPE); holder.resfresh(); String token = holder.getToken(); String result = null; if (METHOD_RAW) { result = runRawPostMethod(token); } else { result = runJsonPostMethod(token); } return result; } private String runRawPostMethod(String token) throws IOException, DemoException { String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&token=" + token; //测试自训练平台需要打开以下信息 //String url2 = URL + "?cuid=" + ConnUtil.urlEncode(CUID) + "&dev_pid=" + DEV_PID + "&lm_id="+ LM_ID + "&token=" + token; String contentTypeStr = "audio/" + FORMAT + "; rate=" + RATE; //System.out.println(url2); byte[] content = getFileContent(FILENAME); HttpURLConnection conn = (HttpURLConnection) new URL(url2).openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", contentTypeStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(content); conn.getOutputStream().close(); System.out.println("url is " + url2); System.out.println("header is " + "Content-Type :" + contentTypeStr); String result = ConnUtil.getResponseString(conn); return result; } public String runJsonPostMethod(String token) throws DemoException, IOException { byte[] content = getFileContent(FILENAME); String speech = base64Encode(content); JSONObject params = new JSONObject(); params.put("dev_pid", DEV_PID); //params.put("lm_id",LM_ID);//测试自训练平台需要打开注释 params.put("format", FORMAT); params.put("rate", RATE); params.put("token", token); params.put("cuid", CUID); params.put("channel", "1"); params.put("len", content.length); params.put("speech", speech); // System.out.println(params.toString()); HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setDoOutput(true); conn.getOutputStream().write(params.toString().getBytes()); conn.getOutputStream().close(); String result = ConnUtil.getResponseString(conn); params.put("speech", "base64Encode(getFileContent(FILENAME))"); System.out.println("url is : " + URL); System.out.println("params is :" + params.toString()); return result; } private byte[] getFileContent(String filename) throws DemoException, IOException { File file = new File(filename); if (!file.canRead()) { System.err.println("文件不存在或者不可读: " + file.getAbsolutePath()); throw new DemoException("file cannot read: " + file.getAbsolutePath()); } FileInputStream is = null; try { is = new FileInputStream(file); return ConnUtil.getInputStreamContent(is); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } private String base64Encode(byte[] content) { /** Base64.Encoder encoder = Base64.getEncoder(); // JDK 1.8 推荐方法 String str = encoder.encodeToString(content); **/ char[] chars = Base64Util.encode(content); // 1.7 及以下,不推荐,请自行跟换相关库 String str = new String(chars); return str; } }
0
1,574
27
1,746
24
1,825
23
1,746
24
2,268
45
false
false
false
false
false
true
41255_8
package me.bakumon.library; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; /** * 日食加载动画 * * @author Bakumon https://bakumon.me * @date 2018/01/03 */ public class EclipseLoadingView extends View { /** * 左右日食过程 */ private static final int STATE_ECLIPSE = 0; /** * 转圈过程 */ private static final int STATE_ROTATE = 1; /** * 恢复过程 */ private static final int STATE_RECOVER = 2; /** * view 默认宽高 */ private int defaultSize; /** * 中心点坐标,xy */ private int center; /** * 太阳半径 */ private int radius; /** * 圈圈线条的宽度 */ private int arcWidth; /** * 太阳颜色 */ private int mSunColor; /** * @see EclipseLoadingView#STATE_ECLIPSE * @see EclipseLoadingView#STATE_ROTATE * @see EclipseLoadingView#STATE_RECOVER * 为了在 onDraw 中不绘制看不到的部分 */ private int status; private Paint paint; /** * 裁剪绘画区域 */ private Path canvasClipPath; /** * 日食过程移动的 path */ private Path eclipseClipPath; /** * 恢复过程移动的 path */ private Path recoverClipPath; /** * 圈圈过程圆弧相关 */ private RectF rectF; /** * 日食和恢复过程 path 移动的 offset */ private float eclipseOffsetX; /** * 圈圈过程圆弧显示的角度 */ private float eclipseSweepAngle; private AnimatorSet animatorSet; public EclipseLoadingView(Context context) { this(context, null); } public EclipseLoadingView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public EclipseLoadingView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EclipseLoadingView); mSunColor = a.getColor(R.styleable.EclipseLoadingView_sunColor, Color.parseColor("#FDAC2A")); a.recycle(); init(); } private void init() { paint = new Paint(Paint.ANTI_ALIAS_FLAG); defaultSize = dp2px(60); arcWidth = dp2px(2); paint.setStrokeWidth(arcWidth); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 取宽高的最小值做整个 view 的边长 int size = Math.min(measureSize(widthMeasureSpec), measureSize(heightMeasureSpec)); setMeasuredDimension(size, size); } private int measureSize(int measureSpec) { int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = defaultSize; if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // 宽和高相等 center = w / 2; int bottom = getPaddingBottom(); int top = getPaddingTop(); int right = getPaddingRight(); int left = getPaddingLeft(); // 最大内边距 int maxPadding = Math.max(Math.max(Math.max(bottom, top), right), left); radius = w / 2 - maxPadding; int rectFLeftTop = maxPadding + arcWidth; int rectFRightBottom = w - maxPadding - arcWidth; rectF = new RectF(rectFLeftTop, rectFLeftTop, rectFRightBottom, rectFRightBottom); canvasClipPath = new Path(); canvasClipPath.addCircle(center, center, center, Path.Direction.CW); eclipseClipPath = new Path(); eclipseClipPath.setFillType(Path.FillType.INVERSE_WINDING); eclipseClipPath.addCircle(center + radius * 2, center, radius, Path.Direction.CW); recoverClipPath = new Path(); recoverClipPath.setFillType(Path.FillType.INVERSE_WINDING); recoverClipPath.addCircle(center, center, radius, Path.Direction.CW); initAnimator(); } private void initAnimator() { // animator1 日食过程 ValueAnimator animator1 = ValueAnimator.ofFloat(0, -((radius) * 2)); animator1.setDuration(2000); animator1.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { status = STATE_ECLIPSE; } }); animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { setEclipseOffsetX((Float) animation.getAnimatedValue()); } }); // animator2 animator3 转圈过程 ValueAnimator animator2 = ValueAnimator.ofFloat(0, -360); animator2.setDuration(400); animator2.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { status = STATE_ROTATE; } }); animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { setEclipseSweepAngle((Float) animation.getAnimatedValue()); } }); ValueAnimator animator3 = ValueAnimator.ofFloat(360, 0); animator3.setDuration(400); animator3.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { setEclipseSweepAngle((Float) animation.getAnimatedValue()); } }); // animator4 恢复过程 ValueAnimator animator4 = ValueAnimator.ofFloat(0, -((radius) * 2)); animator4.setDuration(2000); animator4.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { status = STATE_RECOVER; } }); animator4.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { setEclipseOffsetX((Float) animation.getAnimatedValue()); } }); animatorSet = new AnimatorSet(); animatorSet.playSequentially(animator1, animator2, animator3, animator4); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { animatorSet.start(); } }); animatorSet.start(); } private void setEclipseOffsetX(float eclipseOffsetX) { this.eclipseOffsetX = eclipseOffsetX; invalidate(); } private void setEclipseSweepAngle(float eclipseSweepAngle) { this.eclipseSweepAngle = eclipseSweepAngle; invalidate(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); animatorSet.cancel(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.clipPath(canvasClipPath); if (status == STATE_ROTATE) { // 圈圈 drawRotate(canvas); } else { if (status == STATE_ECLIPSE) { // 日食过程 drawEclipse(canvas, eclipseClipPath); } else { // 恢复过程 drawEclipse(canvas, recoverClipPath); } } } /** * 画圈圈 */ private void drawRotate(Canvas canvas) { paint.setStyle(Paint.Style.STROKE); paint.setColor(mSunColor); canvas.drawArc(rectF, -90, eclipseSweepAngle, false, paint); } /** * 日食或恢复过程 * * @param eclipsePath eclipseClipPath:日食过程 recoverClipPath:恢复过程 */ private void drawEclipse(Canvas canvas, Path eclipsePath) { canvas.save(); eclipsePath.offset(eclipseOffsetX, 0); canvas.clipPath(eclipsePath); eclipsePath.offset(-eclipseOffsetX, 0); // 太阳 paint.setStyle(Paint.Style.FILL); paint.setColor(mSunColor); canvas.drawCircle(center, center, radius, paint); canvas.restore(); } public int getSunColor() { return mSunColor; } public void setSunColor(int sunColor) { this.mSunColor = sunColor; } private int dp2px(float dipValue) { float density = getContext().getResources().getDisplayMetrics().density; return (int) (dipValue * density + 0.5f); } }
Bakumon/EclipseLoading
library/src/main/java/me/bakumon/library/EclipseLoadingView.java
2,353
/** * 太阳颜色 */
block_comment
zh-cn
package me.bakumon.library; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.AnimatorSet; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.util.AttributeSet; import android.view.View; /** * 日食加载动画 * * @author Bakumon https://bakumon.me * @date 2018/01/03 */ public class EclipseLoadingView extends View { /** * 左右日食过程 */ private static final int STATE_ECLIPSE = 0; /** * 转圈过程 */ private static final int STATE_ROTATE = 1; /** * 恢复过程 */ private static final int STATE_RECOVER = 2; /** * view 默认宽高 */ private int defaultSize; /** * 中心点坐标,xy */ private int center; /** * 太阳半径 */ private int radius; /** * 圈圈线条的宽度 */ private int arcWidth; /** * 太阳颜 <SUF>*/ private int mSunColor; /** * @see EclipseLoadingView#STATE_ECLIPSE * @see EclipseLoadingView#STATE_ROTATE * @see EclipseLoadingView#STATE_RECOVER * 为了在 onDraw 中不绘制看不到的部分 */ private int status; private Paint paint; /** * 裁剪绘画区域 */ private Path canvasClipPath; /** * 日食过程移动的 path */ private Path eclipseClipPath; /** * 恢复过程移动的 path */ private Path recoverClipPath; /** * 圈圈过程圆弧相关 */ private RectF rectF; /** * 日食和恢复过程 path 移动的 offset */ private float eclipseOffsetX; /** * 圈圈过程圆弧显示的角度 */ private float eclipseSweepAngle; private AnimatorSet animatorSet; public EclipseLoadingView(Context context) { this(context, null); } public EclipseLoadingView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public EclipseLoadingView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.EclipseLoadingView); mSunColor = a.getColor(R.styleable.EclipseLoadingView_sunColor, Color.parseColor("#FDAC2A")); a.recycle(); init(); } private void init() { paint = new Paint(Paint.ANTI_ALIAS_FLAG); defaultSize = dp2px(60); arcWidth = dp2px(2); paint.setStrokeWidth(arcWidth); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // 取宽高的最小值做整个 view 的边长 int size = Math.min(measureSize(widthMeasureSpec), measureSize(heightMeasureSpec)); setMeasuredDimension(size, size); } private int measureSize(int measureSpec) { int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = defaultSize; if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // 宽和高相等 center = w / 2; int bottom = getPaddingBottom(); int top = getPaddingTop(); int right = getPaddingRight(); int left = getPaddingLeft(); // 最大内边距 int maxPadding = Math.max(Math.max(Math.max(bottom, top), right), left); radius = w / 2 - maxPadding; int rectFLeftTop = maxPadding + arcWidth; int rectFRightBottom = w - maxPadding - arcWidth; rectF = new RectF(rectFLeftTop, rectFLeftTop, rectFRightBottom, rectFRightBottom); canvasClipPath = new Path(); canvasClipPath.addCircle(center, center, center, Path.Direction.CW); eclipseClipPath = new Path(); eclipseClipPath.setFillType(Path.FillType.INVERSE_WINDING); eclipseClipPath.addCircle(center + radius * 2, center, radius, Path.Direction.CW); recoverClipPath = new Path(); recoverClipPath.setFillType(Path.FillType.INVERSE_WINDING); recoverClipPath.addCircle(center, center, radius, Path.Direction.CW); initAnimator(); } private void initAnimator() { // animator1 日食过程 ValueAnimator animator1 = ValueAnimator.ofFloat(0, -((radius) * 2)); animator1.setDuration(2000); animator1.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { status = STATE_ECLIPSE; } }); animator1.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { setEclipseOffsetX((Float) animation.getAnimatedValue()); } }); // animator2 animator3 转圈过程 ValueAnimator animator2 = ValueAnimator.ofFloat(0, -360); animator2.setDuration(400); animator2.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { status = STATE_ROTATE; } }); animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { setEclipseSweepAngle((Float) animation.getAnimatedValue()); } }); ValueAnimator animator3 = ValueAnimator.ofFloat(360, 0); animator3.setDuration(400); animator3.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { setEclipseSweepAngle((Float) animation.getAnimatedValue()); } }); // animator4 恢复过程 ValueAnimator animator4 = ValueAnimator.ofFloat(0, -((radius) * 2)); animator4.setDuration(2000); animator4.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationStart(Animator animation) { status = STATE_RECOVER; } }); animator4.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { setEclipseOffsetX((Float) animation.getAnimatedValue()); } }); animatorSet = new AnimatorSet(); animatorSet.playSequentially(animator1, animator2, animator3, animator4); animatorSet.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { animatorSet.start(); } }); animatorSet.start(); } private void setEclipseOffsetX(float eclipseOffsetX) { this.eclipseOffsetX = eclipseOffsetX; invalidate(); } private void setEclipseSweepAngle(float eclipseSweepAngle) { this.eclipseSweepAngle = eclipseSweepAngle; invalidate(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); animatorSet.cancel(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.clipPath(canvasClipPath); if (status == STATE_ROTATE) { // 圈圈 drawRotate(canvas); } else { if (status == STATE_ECLIPSE) { // 日食过程 drawEclipse(canvas, eclipseClipPath); } else { // 恢复过程 drawEclipse(canvas, recoverClipPath); } } } /** * 画圈圈 */ private void drawRotate(Canvas canvas) { paint.setStyle(Paint.Style.STROKE); paint.setColor(mSunColor); canvas.drawArc(rectF, -90, eclipseSweepAngle, false, paint); } /** * 日食或恢复过程 * * @param eclipsePath eclipseClipPath:日食过程 recoverClipPath:恢复过程 */ private void drawEclipse(Canvas canvas, Path eclipsePath) { canvas.save(); eclipsePath.offset(eclipseOffsetX, 0); canvas.clipPath(eclipsePath); eclipsePath.offset(-eclipseOffsetX, 0); // 太阳 paint.setStyle(Paint.Style.FILL); paint.setColor(mSunColor); canvas.drawCircle(center, center, radius, paint); canvas.restore(); } public int getSunColor() { return mSunColor; } public void setSunColor(int sunColor) { this.mSunColor = sunColor; } private int dp2px(float dipValue) { float density = getContext().getResources().getDisplayMetrics().density; return (int) (dipValue * density + 0.5f); } }
0
2,111
10
2,354
9
2,438
9
2,353
9
2,894
14
false
false
false
false
false
true
37098_10
package leetcode.algorithms; import java.util.*; import java.util.stream.Collectors; /** * Description: 2115. Find All Possible Recipes from Given Supplies * * @author Baltan * @date 2021/12/26 14:45 */ public class FindAllRecipes { public static void main(String[] args) { String[] recipes1 = {"bread"}; List<List<String>> ingredients1 = Arrays.asList( Arrays.asList("yeast", "flour") ); String[] supplies1 = {"yeast", "flour", "corn"}; System.out.println(findAllRecipes(recipes1, ingredients1, supplies1)); String[] recipes2 = {"bread", "sandwich"}; List<List<String>> ingredients2 = Arrays.asList( Arrays.asList("yeast", "flour"), Arrays.asList("bread", "meat") ); String[] supplies2 = {"yeast", "flour", "meat"}; System.out.println(findAllRecipes(recipes2, ingredients2, supplies2)); String[] recipes3 = {"bread", "sandwich", "burger"}; List<List<String>> ingredients3 = Arrays.asList( Arrays.asList("yeast", "flour"), Arrays.asList("bread", "meat"), Arrays.asList("sandwich", "meat", "bread") ); String[] supplies3 = {"yeast", "flour", "meat"}; System.out.println(findAllRecipes(recipes3, ingredients3, supplies3)); String[] recipes4 = {"bread"}; List<List<String>> ingredients4 = Arrays.asList( Arrays.asList("yeast", "flour") ); String[] supplies4 = {"yeast"}; System.out.println(findAllRecipes(recipes4, ingredients4, supplies4)); } public static List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) { List<String> result = new ArrayList<>(); /** * 已拥有的原材料集合 */ Set<String> supplySet = Arrays.stream(supplies).collect(Collectors.toSet()); /** * 每道菜需要的原材料集合 */ List<Set<String>> ingredientSetList = ingredients.stream() .map(ingredient -> ingredient.stream().collect(Collectors.toSet())) .collect(Collectors.toList()); /** * 剩余还未做出的菜 */ int leftCount = recipes.length; /** * isCreated[i]表示第i道菜是否已被做出 */ boolean[] isCreated = new boolean[leftCount]; /** * 标记每一轮判断是否有新的菜被做出,如果有新的菜被做出,可能会使得其他菜也能被做出,需要继续判断 */ boolean changed = true; while (changed && leftCount > 0) { /** * 当前这轮判断还没有新的菜被做出 */ changed = false; for (int i = 0; i < ingredientSetList.size(); i++) { /** * 已被做出的菜不需要重复判断 */ if (isCreated[i]) { continue; } /** * 如果需要完成当前这道菜还需要的原材料 */ Set<String> ingredientSet = ingredientSetList.get(i); Iterator<String> it = ingredientSet.iterator(); /** * 如果需要的原材料我们已经拥有了,就删除 */ while (it.hasNext()) { String str = it.next(); if (supplySet.contains(str)) { it.remove(); } } /** * 如果当前这道菜所需要的所有原材料我们都拥有了,就可以做出这道菜了,同时这道菜也被加入我们拥有的原材料中,用于 * 判断是否能做出其他的才 */ if (ingredientSet.isEmpty()) { supplySet.add(recipes[i]); result.add(recipes[i]); isCreated[i] = true; changed = true; } } } return result; } }
Baltan/leetcode
src/leetcode/algorithms/FindAllRecipes.java
976
/** * 如果当前这道菜所需要的所有原材料我们都拥有了,就可以做出这道菜了,同时这道菜也被加入我们拥有的原材料中,用于 * 判断是否能做出其他的才 */
block_comment
zh-cn
package leetcode.algorithms; import java.util.*; import java.util.stream.Collectors; /** * Description: 2115. Find All Possible Recipes from Given Supplies * * @author Baltan * @date 2021/12/26 14:45 */ public class FindAllRecipes { public static void main(String[] args) { String[] recipes1 = {"bread"}; List<List<String>> ingredients1 = Arrays.asList( Arrays.asList("yeast", "flour") ); String[] supplies1 = {"yeast", "flour", "corn"}; System.out.println(findAllRecipes(recipes1, ingredients1, supplies1)); String[] recipes2 = {"bread", "sandwich"}; List<List<String>> ingredients2 = Arrays.asList( Arrays.asList("yeast", "flour"), Arrays.asList("bread", "meat") ); String[] supplies2 = {"yeast", "flour", "meat"}; System.out.println(findAllRecipes(recipes2, ingredients2, supplies2)); String[] recipes3 = {"bread", "sandwich", "burger"}; List<List<String>> ingredients3 = Arrays.asList( Arrays.asList("yeast", "flour"), Arrays.asList("bread", "meat"), Arrays.asList("sandwich", "meat", "bread") ); String[] supplies3 = {"yeast", "flour", "meat"}; System.out.println(findAllRecipes(recipes3, ingredients3, supplies3)); String[] recipes4 = {"bread"}; List<List<String>> ingredients4 = Arrays.asList( Arrays.asList("yeast", "flour") ); String[] supplies4 = {"yeast"}; System.out.println(findAllRecipes(recipes4, ingredients4, supplies4)); } public static List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) { List<String> result = new ArrayList<>(); /** * 已拥有的原材料集合 */ Set<String> supplySet = Arrays.stream(supplies).collect(Collectors.toSet()); /** * 每道菜需要的原材料集合 */ List<Set<String>> ingredientSetList = ingredients.stream() .map(ingredient -> ingredient.stream().collect(Collectors.toSet())) .collect(Collectors.toList()); /** * 剩余还未做出的菜 */ int leftCount = recipes.length; /** * isCreated[i]表示第i道菜是否已被做出 */ boolean[] isCreated = new boolean[leftCount]; /** * 标记每一轮判断是否有新的菜被做出,如果有新的菜被做出,可能会使得其他菜也能被做出,需要继续判断 */ boolean changed = true; while (changed && leftCount > 0) { /** * 当前这轮判断还没有新的菜被做出 */ changed = false; for (int i = 0; i < ingredientSetList.size(); i++) { /** * 已被做出的菜不需要重复判断 */ if (isCreated[i]) { continue; } /** * 如果需要完成当前这道菜还需要的原材料 */ Set<String> ingredientSet = ingredientSetList.get(i); Iterator<String> it = ingredientSet.iterator(); /** * 如果需要的原材料我们已经拥有了,就删除 */ while (it.hasNext()) { String str = it.next(); if (supplySet.contains(str)) { it.remove(); } } /** * 如果当 <SUF>*/ if (ingredientSet.isEmpty()) { supplySet.add(recipes[i]); result.add(recipes[i]); isCreated[i] = true; changed = true; } } } return result; } }
0
866
48
976
56
1,001
50
976
56
1,304
89
false
false
false
false
false
true
9838_8
package com.bamboy.bamboycollected.page.freedom; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.bamboy.bamboycollected.R; import com.bamboy.bamboycollected.base.actiivty.BamActivity; import com.bamboy.bamboycollected.base.freedom.FreedomAdapter; import com.bamboy.bamboycollected.base.freedom.FreedomBean; import com.bamboy.bamboycollected.base.freedom.FreedomCallback; import com.bamboy.bamboycollected.base.freedom.ViewHolderManager; import com.bamboy.bamboycollected.page.bean.FourIconBean; import com.bamboy.bamboycollected.page.bean.SingleBtnBean; import com.bamboy.bamboycollected.page.bean.SingleImageBean; import com.bamboy.bamboycollected.page.freedom.bean.BeanDialogueLeft; import com.bamboy.bamboycollected.page.freedom.bean.BeanDialogueRight; import com.bamboy.bamboycollected.page.freedom.bean.BeanMusic; import com.bamboy.bamboycollected.page.freedom.bean.BeanNewsImg; import com.bamboy.bamboycollected.page.freedom.bean.BeanNewsText; import com.bamboy.bamboycollected.page.toast.bamtoast.BamToast; import java.util.ArrayList; import java.util.List; /** * 非约束列表Demo * <p> * Created by Bamboy on 2017/4/17. */ public class FreedomListActivity extends BamActivity implements FreedomCallback { private RecyclerView recycler; /** * 数据源 */ private List<FreedomBean> mList; /** * 适配器 */ private FreedomAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_freedom); } @Override protected void findView() { recycler = findViewById(R.id.recycler); } @Override protected void setListener() { } @Override protected void init() { // 初始化RecyclerView initRecycler(); } @Override public void onClickCallback(View view, int position, ViewHolderManager.ViewHolder holder) { switch (view.getId()) { case R.id.rl_single: BamToast.showText(this, "点击了条目样式 1"); break; case R.id.rl_fresh: BamToast.showText(this, "点击了最新上架"); break; case R.id.rl_hot: BamToast.showText(this, "点击了热门精选"); break; case R.id.rl_classic: BamToast.showText(this, "点击了重温经典"); break; case R.id.rl_sleep: BamToast.showText(this, "点击了睡前小酌"); break; case R.id.iv_single: BamToast.showText(this, "点击了单个图片"); break; } } /** * 初始化列表数据 */ private void initRecycler() { // 初始化数据 initData(); // 实例化RecyclerView // 把每行平分成2份 GridLayoutManager manager = new GridLayoutManager(this, 2); manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { FreedomBean bean = mList.get(position); // 获取当前这个条目占几份 return bean.getSpanSize(2); } }); recycler.setLayoutManager(manager); recycler.setItemAnimator(null); mAdapter = new FreedomAdapter(this, mList); recycler.setAdapter(mAdapter); } /** * 初始化数据 */ private void initData() { // 实例化List mList = new ArrayList(); // 模拟加载数据,往mList里放一些乱七八糟的条目 mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?")); mList.add(new BeanMusic("成都", "赵雷 - 成都")); mList.add(new BeanMusic("成全", "林宥嘉 - 翻唱合集")); mList.add(new BeanMusic("单身情歌", "林志炫 - 一人一首成名曲")); mList.add(new BeanMusic("浮夸", "林志炫 - 我是歌手")); mList.add(new BeanMusic("改变自己", "王力宏 - 改变自己")); mList.add(new BeanNewsText("微软2017年Build大会: 无Win10更新 AI成压轴戏", "北京时间5月11日凌晨消息,微软2017年Build开发者大会于美国西雅图当地时间上午8点拉开帷幕。 此次大会不仅吸引了全球众多开发者前来交流……")); mList.add(new BeanDialogueRight("六六", "今晚单身狗吃狗粮")); mList.add(new BeanDialogueLeft("喵喵", "狗粮不好吃,我要吃猫粮")); mList.add(new BeanNewsText("微信“附近的小程序”悄然上线了,反观小程序为微信带来了什么", "“附近的小程序”正式开放:\n有小程序的商户,可以快速将门店小程序或普通小程序展示在“附近”。当用户走到某个地点,打开“发现-小程序-附近的小程序”,就能将自己附近的小程序“收入囊中”。")); mList.add(new BeanNewsText("手上长水泡是什么引起的", "一到夏天,很多人手上都会出现一些小水泡,它们有的是以透明的形式存在,有的则是以半透明的方式存在,而且伴随着不同程度的瘙痒……")); mList.add(new BeanMusic("骨子里的我", "李代沫 - 敏感者")); mList.add(new BeanMusic("海角七号", "东来东往 - 路过·爱")); mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?")); mList.add(new BeanDialogueLeft("喵喵", "铲屎的走了")); mList.add(new BeanDialogueLeft("喵喵", "艾维巴蒂嗨起来!")); mList.add(new BeanDialogueRight("六六", "铲屎的怎么还不回来,是不是外边有狗了?")); mList.add(new BeanDialogueRight("六六", "我要吃肉肉…")); mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?")); mList.add(new BeanMusic("成都", "赵雷 - 成都")); mList.add(new BeanMusic("成全", "林宥嘉 - 翻唱合集")); mList.add(new BeanMusic("单身情歌", "林志炫 - 一人一首成名曲")); mList.add(new BeanMusic("浮夸", "林志炫 - 我是歌手")); mList.add(new BeanMusic("改变自己", "王力宏 - 改变自己")); mList.add(new BeanNewsText("微软2017年Build大会: 无Win10更新 AI成压轴戏", "北京时间5月11日凌晨消息,微软2017年Build开发者大会于美国西雅图当地时间上午8点拉开帷幕。 此次大会不仅吸引了全球众多开发者前来交流……")); mList.add(new BeanDialogueRight("六六", "今晚单身狗吃狗粮")); mList.add(new BeanDialogueLeft("喵喵", "狗粮不好吃,我要吃猫粮")); mList.add(new BeanNewsText("微信“附近的小程序”悄然上线了,反观小程序为微信带来了什么", "“附近的小程序”正式开放:\n有小程序的商户,可以快速将门店小程序或普通小程序展示在“附近”。当用户走到某个地点,打开“发现-小程序-附近的小程序”,就能将自己附近的小程序“收入囊中”。")); mList.add(new BeanNewsText("手上长水泡是什么引起的", "一到夏天,很多人手上都会出现一些小水泡,它们有的是以透明的形式存在,有的则是以半透明的方式存在,而且伴随着不同程度的瘙痒……")); mList.add(new BeanMusic("骨子里的我", "李代沫 - 敏感者")); mList.add(new BeanMusic("海角七号", "东来东往 - 路过·爱")); mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?")); mList.add(new BeanDialogueLeft("喵喵", "铲屎的走了")); mList.add(new BeanDialogueLeft("喵喵", "艾维巴蒂嗨起来!")); mList.add(new BeanDialogueRight("六六", "铲屎的怎么还不回来,是不是外边有狗了?")); mList.add(new BeanDialogueRight("六六", "我要吃肉肉…")); } }
Bamboy120315/bamboy
app/src/main/java/com/bamboy/bamboycollected/page/freedom/FreedomListActivity.java
2,514
// 获取当前这个条目占几份
line_comment
zh-cn
package com.bamboy.bamboycollected.page.freedom; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.bamboy.bamboycollected.R; import com.bamboy.bamboycollected.base.actiivty.BamActivity; import com.bamboy.bamboycollected.base.freedom.FreedomAdapter; import com.bamboy.bamboycollected.base.freedom.FreedomBean; import com.bamboy.bamboycollected.base.freedom.FreedomCallback; import com.bamboy.bamboycollected.base.freedom.ViewHolderManager; import com.bamboy.bamboycollected.page.bean.FourIconBean; import com.bamboy.bamboycollected.page.bean.SingleBtnBean; import com.bamboy.bamboycollected.page.bean.SingleImageBean; import com.bamboy.bamboycollected.page.freedom.bean.BeanDialogueLeft; import com.bamboy.bamboycollected.page.freedom.bean.BeanDialogueRight; import com.bamboy.bamboycollected.page.freedom.bean.BeanMusic; import com.bamboy.bamboycollected.page.freedom.bean.BeanNewsImg; import com.bamboy.bamboycollected.page.freedom.bean.BeanNewsText; import com.bamboy.bamboycollected.page.toast.bamtoast.BamToast; import java.util.ArrayList; import java.util.List; /** * 非约束列表Demo * <p> * Created by Bamboy on 2017/4/17. */ public class FreedomListActivity extends BamActivity implements FreedomCallback { private RecyclerView recycler; /** * 数据源 */ private List<FreedomBean> mList; /** * 适配器 */ private FreedomAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_freedom); } @Override protected void findView() { recycler = findViewById(R.id.recycler); } @Override protected void setListener() { } @Override protected void init() { // 初始化RecyclerView initRecycler(); } @Override public void onClickCallback(View view, int position, ViewHolderManager.ViewHolder holder) { switch (view.getId()) { case R.id.rl_single: BamToast.showText(this, "点击了条目样式 1"); break; case R.id.rl_fresh: BamToast.showText(this, "点击了最新上架"); break; case R.id.rl_hot: BamToast.showText(this, "点击了热门精选"); break; case R.id.rl_classic: BamToast.showText(this, "点击了重温经典"); break; case R.id.rl_sleep: BamToast.showText(this, "点击了睡前小酌"); break; case R.id.iv_single: BamToast.showText(this, "点击了单个图片"); break; } } /** * 初始化列表数据 */ private void initRecycler() { // 初始化数据 initData(); // 实例化RecyclerView // 把每行平分成2份 GridLayoutManager manager = new GridLayoutManager(this, 2); manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { FreedomBean bean = mList.get(position); // 获取 <SUF> return bean.getSpanSize(2); } }); recycler.setLayoutManager(manager); recycler.setItemAnimator(null); mAdapter = new FreedomAdapter(this, mList); recycler.setAdapter(mAdapter); } /** * 初始化数据 */ private void initData() { // 实例化List mList = new ArrayList(); // 模拟加载数据,往mList里放一些乱七八糟的条目 mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?")); mList.add(new BeanMusic("成都", "赵雷 - 成都")); mList.add(new BeanMusic("成全", "林宥嘉 - 翻唱合集")); mList.add(new BeanMusic("单身情歌", "林志炫 - 一人一首成名曲")); mList.add(new BeanMusic("浮夸", "林志炫 - 我是歌手")); mList.add(new BeanMusic("改变自己", "王力宏 - 改变自己")); mList.add(new BeanNewsText("微软2017年Build大会: 无Win10更新 AI成压轴戏", "北京时间5月11日凌晨消息,微软2017年Build开发者大会于美国西雅图当地时间上午8点拉开帷幕。 此次大会不仅吸引了全球众多开发者前来交流……")); mList.add(new BeanDialogueRight("六六", "今晚单身狗吃狗粮")); mList.add(new BeanDialogueLeft("喵喵", "狗粮不好吃,我要吃猫粮")); mList.add(new BeanNewsText("微信“附近的小程序”悄然上线了,反观小程序为微信带来了什么", "“附近的小程序”正式开放:\n有小程序的商户,可以快速将门店小程序或普通小程序展示在“附近”。当用户走到某个地点,打开“发现-小程序-附近的小程序”,就能将自己附近的小程序“收入囊中”。")); mList.add(new BeanNewsText("手上长水泡是什么引起的", "一到夏天,很多人手上都会出现一些小水泡,它们有的是以透明的形式存在,有的则是以半透明的方式存在,而且伴随着不同程度的瘙痒……")); mList.add(new BeanMusic("骨子里的我", "李代沫 - 敏感者")); mList.add(new BeanMusic("海角七号", "东来东往 - 路过·爱")); mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?")); mList.add(new BeanDialogueLeft("喵喵", "铲屎的走了")); mList.add(new BeanDialogueLeft("喵喵", "艾维巴蒂嗨起来!")); mList.add(new BeanDialogueRight("六六", "铲屎的怎么还不回来,是不是外边有狗了?")); mList.add(new BeanDialogueRight("六六", "我要吃肉肉…")); mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?")); mList.add(new BeanMusic("成都", "赵雷 - 成都")); mList.add(new BeanMusic("成全", "林宥嘉 - 翻唱合集")); mList.add(new BeanMusic("单身情歌", "林志炫 - 一人一首成名曲")); mList.add(new BeanMusic("浮夸", "林志炫 - 我是歌手")); mList.add(new BeanMusic("改变自己", "王力宏 - 改变自己")); mList.add(new BeanNewsText("微软2017年Build大会: 无Win10更新 AI成压轴戏", "北京时间5月11日凌晨消息,微软2017年Build开发者大会于美国西雅图当地时间上午8点拉开帷幕。 此次大会不仅吸引了全球众多开发者前来交流……")); mList.add(new BeanDialogueRight("六六", "今晚单身狗吃狗粮")); mList.add(new BeanDialogueLeft("喵喵", "狗粮不好吃,我要吃猫粮")); mList.add(new BeanNewsText("微信“附近的小程序”悄然上线了,反观小程序为微信带来了什么", "“附近的小程序”正式开放:\n有小程序的商户,可以快速将门店小程序或普通小程序展示在“附近”。当用户走到某个地点,打开“发现-小程序-附近的小程序”,就能将自己附近的小程序“收入囊中”。")); mList.add(new BeanNewsText("手上长水泡是什么引起的", "一到夏天,很多人手上都会出现一些小水泡,它们有的是以透明的形式存在,有的则是以半透明的方式存在,而且伴随着不同程度的瘙痒……")); mList.add(new BeanMusic("骨子里的我", "李代沫 - 敏感者")); mList.add(new BeanMusic("海角七号", "东来东往 - 路过·爱")); mList.add(new BeanNewsImg(R.drawable.picture_b, "这些水果狗狗不能吃,你知道吗?")); mList.add(new BeanDialogueLeft("喵喵", "铲屎的走了")); mList.add(new BeanDialogueLeft("喵喵", "艾维巴蒂嗨起来!")); mList.add(new BeanDialogueRight("六六", "铲屎的怎么还不回来,是不是外边有狗了?")); mList.add(new BeanDialogueRight("六六", "我要吃肉肉…")); } }
0
1,892
9
2,514
9
2,214
8
2,514
9
3,229
19
false
false
false
false
false
true
14960_17
package xyz.acproject.danmuji.conf.set; import com.alibaba.fastjson.annotation.JSONField; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.commons.lang3.StringUtils; import xyz.acproject.danmuji.conf.PublicDataConf; import xyz.acproject.danmuji.conf.base.ThankLiveSetConf; import java.io.Serializable; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.stream.Collectors; /** * @ClassName ThankGiftSetConf * @Description TODO * @author BanqiJane * @date 2020年8月10日 下午12:21:24 * * @Copyright:2020 blogs.acproject.xyz Inc. All rights reserved. */ @Data @NoArgsConstructor @AllArgsConstructor public class ThankGiftSetConf extends ThankLiveSetConf implements Serializable{ /** * */ private static final long serialVersionUID = -418947096472064467L; //是否开启本人 @JSONField(name = "is_open_self") private boolean is_open_self = false; //礼物屏蔽模式 0 自定义 1 免费 2 低价 3 规则 private short shield_status =0; //礼物名单限制模式 0黑名单 1白名单 默认黑 @JSONField(name = "list_gift_shield_status") private short list_gift_shield_status = 0; //人员感谢过滤 0全部 1仅勋章 2仅舰长 @JSONField(name = "list_people_shield_status") private short list_people_shield_status = 0; //自定义礼物屏蔽 0 private HashSet<String> giftStrings; //自定义感谢屏蔽规则 3 private HashSet<ThankGiftRuleSet> thankGiftRuleSets; //感谢模式 0 单人单种 1 单人多种 2 多人多种 private short thank_status = 0; //感谢语 默认感谢模式0下的 private String thank ="感谢%uName%大佬%Type%的%GiftName% x%Num%~"; //是否舰长私信 @JSONField(name = "is_guard_report") private boolean is_guard_report =false; //是否开启本地存储舰长 @JSONField(name = "is_guard_local") private boolean is_guard_local=false; //是否开启礼物码模式 @JSONField(name = "is_gift_code") private boolean is_gift_code = false; //舰长私信语 private String report; //舰长私信成功后发送弹幕 private String report_barrage; //礼物码HashSet private HashSet<String> codeStrings; //是否开启感谢数量显示 @JSONField(name = "is_num") private boolean is_num=true; public ThankGiftSetConf(boolean is_open) { super(); super.set_open(is_open); } //方法区 public boolean is_giftThank(){ if(StringUtils.isBlank(PublicDataConf.USERCOOKIE)){ return false; } if(is_live_open()) { //没在直播 if(PublicDataConf.lIVE_STATUS !=1){ return false; }else{ if(is_open()) { return true; }else{ return false; } } }else{ if(is_open()) { return true; }else{ return false; } } } public boolean is_giftThank(short live_status){ if(StringUtils.isBlank(PublicDataConf.USERCOOKIE)){ return false; } if(is_live_open()) { //没在直播 if(live_status!=1){ return false; }else{ if(is_open()) { return true; }else{ return false; } } }else{ if(is_open()) { return true; }else{ return false; } } } public HashSet<ThankGiftRuleSet> getThankGiftRuleSets() { if(thankGiftRuleSets!=null) { return thankGiftRuleSets.stream().sorted(Comparator.comparing(ThankGiftRuleSet::getGift_name)).collect(Collectors.toCollection(LinkedHashSet::new)); } return new HashSet<>(); } public HashSet<String> getCodeStrings() { if(codeStrings!=null) { return codeStrings.stream().sorted().collect(Collectors.toCollection(LinkedHashSet::new)); } return new HashSet<>(); } }
BanqiJane/Bilibili_Danmuji
src/main/java/xyz/acproject/danmuji/conf/set/ThankGiftSetConf.java
1,247
//没在直播
line_comment
zh-cn
package xyz.acproject.danmuji.conf.set; import com.alibaba.fastjson.annotation.JSONField; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.commons.lang3.StringUtils; import xyz.acproject.danmuji.conf.PublicDataConf; import xyz.acproject.danmuji.conf.base.ThankLiveSetConf; import java.io.Serializable; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.stream.Collectors; /** * @ClassName ThankGiftSetConf * @Description TODO * @author BanqiJane * @date 2020年8月10日 下午12:21:24 * * @Copyright:2020 blogs.acproject.xyz Inc. All rights reserved. */ @Data @NoArgsConstructor @AllArgsConstructor public class ThankGiftSetConf extends ThankLiveSetConf implements Serializable{ /** * */ private static final long serialVersionUID = -418947096472064467L; //是否开启本人 @JSONField(name = "is_open_self") private boolean is_open_self = false; //礼物屏蔽模式 0 自定义 1 免费 2 低价 3 规则 private short shield_status =0; //礼物名单限制模式 0黑名单 1白名单 默认黑 @JSONField(name = "list_gift_shield_status") private short list_gift_shield_status = 0; //人员感谢过滤 0全部 1仅勋章 2仅舰长 @JSONField(name = "list_people_shield_status") private short list_people_shield_status = 0; //自定义礼物屏蔽 0 private HashSet<String> giftStrings; //自定义感谢屏蔽规则 3 private HashSet<ThankGiftRuleSet> thankGiftRuleSets; //感谢模式 0 单人单种 1 单人多种 2 多人多种 private short thank_status = 0; //感谢语 默认感谢模式0下的 private String thank ="感谢%uName%大佬%Type%的%GiftName% x%Num%~"; //是否舰长私信 @JSONField(name = "is_guard_report") private boolean is_guard_report =false; //是否开启本地存储舰长 @JSONField(name = "is_guard_local") private boolean is_guard_local=false; //是否开启礼物码模式 @JSONField(name = "is_gift_code") private boolean is_gift_code = false; //舰长私信语 private String report; //舰长私信成功后发送弹幕 private String report_barrage; //礼物码HashSet private HashSet<String> codeStrings; //是否开启感谢数量显示 @JSONField(name = "is_num") private boolean is_num=true; public ThankGiftSetConf(boolean is_open) { super(); super.set_open(is_open); } //方法区 public boolean is_giftThank(){ if(StringUtils.isBlank(PublicDataConf.USERCOOKIE)){ return false; } if(is_live_open()) { //没在 <SUF> if(PublicDataConf.lIVE_STATUS !=1){ return false; }else{ if(is_open()) { return true; }else{ return false; } } }else{ if(is_open()) { return true; }else{ return false; } } } public boolean is_giftThank(short live_status){ if(StringUtils.isBlank(PublicDataConf.USERCOOKIE)){ return false; } if(is_live_open()) { //没在直播 if(live_status!=1){ return false; }else{ if(is_open()) { return true; }else{ return false; } } }else{ if(is_open()) { return true; }else{ return false; } } } public HashSet<ThankGiftRuleSet> getThankGiftRuleSets() { if(thankGiftRuleSets!=null) { return thankGiftRuleSets.stream().sorted(Comparator.comparing(ThankGiftRuleSet::getGift_name)).collect(Collectors.toCollection(LinkedHashSet::new)); } return new HashSet<>(); } public HashSet<String> getCodeStrings() { if(codeStrings!=null) { return codeStrings.stream().sorted().collect(Collectors.toCollection(LinkedHashSet::new)); } return new HashSet<>(); } }
0
974
4
1,247
5
1,201
4
1,247
5
1,582
7
false
false
false
false
false
true
42988_7
package com.example.jianqiang.testlistview.imageloader; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.OkHttpClient; /** * Created by struggle_liping on 2017/7/16. */ public class OkHttpClientUtils { public static OkHttpClient getClient(){ if(false){ return getAllPassClient(); }else { return getNormalClient(); } } /** * 不校验证书 * @return */ private static OkHttpClient getAllPassClient() { X509TrustManager xtm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { X509Certificate[] x509Certificates = new X509Certificate[]{}; return x509Certificates; // return null; } }; SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // sslSocketFactory和hostnameVerifier代码与httpsUtil中一模一样,只有这里不一样,但下面能行,这里就不行,见鬼了 OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory()) .hostnameVerifier(DO_NOT_VERIFY) .readTimeout(0, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //设置超时 .build(); return client; } private static OkHttpClient getNormalClient(){ OkHttpClient client = new OkHttpClient.Builder() //.sslSocketFactory(sslContext.getSocketFactory()) //.hostnameVerifier(DO_NOT_VERIFY) .readTimeout(0, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //设置超时 .build(); return client; } }
BaoBaoJianqiang/CustomListView
TestListView/app/src/main/java/com/example/jianqiang/testlistview/imageloader/OkHttpClientUtils.java
677
//设置超时
line_comment
zh-cn
package com.example.jianqiang.testlistview.imageloader; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.concurrent.TimeUnit; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import okhttp3.OkHttpClient; /** * Created by struggle_liping on 2017/7/16. */ public class OkHttpClientUtils { public static OkHttpClient getClient(){ if(false){ return getAllPassClient(); }else { return getNormalClient(); } } /** * 不校验证书 * @return */ private static OkHttpClient getAllPassClient() { X509TrustManager xtm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { X509Certificate[] x509Certificates = new X509Certificate[]{}; return x509Certificates; // return null; } }; SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // sslSocketFactory和hostnameVerifier代码与httpsUtil中一模一样,只有这里不一样,但下面能行,这里就不行,见鬼了 OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(sslContext.getSocketFactory()) .hostnameVerifier(DO_NOT_VERIFY) .readTimeout(0, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //设置超时 .build(); return client; } private static OkHttpClient getNormalClient(){ OkHttpClient client = new OkHttpClient.Builder() //.sslSocketFactory(sslContext.getSocketFactory()) //.hostnameVerifier(DO_NOT_VERIFY) .readTimeout(0, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS).writeTimeout(0, TimeUnit.SECONDS) //设置 <SUF> .build(); return client; } }
0
600
4
677
3
711
3
677
3
848
5
false
false
false
false
false
true
15927_3
package com.baron.patterns.state.state; /** * 状态之木有钱 * * @author Baron Zhang (baron[dot]zhanglei[at]gmail[dot]com) * @version 1.0 * @since 1.0 */ public class NoQuarterState implements State { GumballMachine gumballMachine; public NoQuarterState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { //这里加入投币代码 System.out.println("客官您投入了25分硬币"); gumballMachine.setState(gumballMachine.getHasQuarterState()); } @Override public void ejectQuarter() { //这里加入退币代码 System.out.println("小子!你特么都没投钱,还要求退币?!!!"); } @Override public void turnCrank() { //这里加入转动曲柄代码 System.out.println("没给钱拨你妹的曲柄开关啊"); } @Override public void dispense() { //这里加入发糖果代码 System.out.println("哥哥,咱先给钱好不好"); } }
BaronZ88/DesignPatterns
src/com/baron/patterns/state/state/NoQuarterState.java
317
//这里加入转动曲柄代码
line_comment
zh-cn
package com.baron.patterns.state.state; /** * 状态之木有钱 * * @author Baron Zhang (baron[dot]zhanglei[at]gmail[dot]com) * @version 1.0 * @since 1.0 */ public class NoQuarterState implements State { GumballMachine gumballMachine; public NoQuarterState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { //这里加入投币代码 System.out.println("客官您投入了25分硬币"); gumballMachine.setState(gumballMachine.getHasQuarterState()); } @Override public void ejectQuarter() { //这里加入退币代码 System.out.println("小子!你特么都没投钱,还要求退币?!!!"); } @Override public void turnCrank() { //这里 <SUF> System.out.println("没给钱拨你妹的曲柄开关啊"); } @Override public void dispense() { //这里加入发糖果代码 System.out.println("哥哥,咱先给钱好不好"); } }
0
273
7
317
9
304
8
317
9
403
13
false
false
false
false
false
true
9767_10
package wow.service; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import wow.entity.BackJSON; import wow.entity.Doctor; import wow.entity.Patient; import wow.entity.UserInfo; import wow.mapper.DoctorMapper; import wow.mapper.PatientMapper; import wow.mapper.UserMapper; import wow.util.Value; @Service @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT) public class UserServiceImpl implements UserService { @Autowired private UserMapper um; @Autowired private PatientMapper pm; @Autowired private DoctorMapper dm; @Override @Transactional public BackJSON userRegister(UserInfo userInfo) { BackJSON json = new BackJSON(200); Map<String, String> data = new HashMap<>(); int userType = userInfo.getUserType(); int userID = um.getUserCount(); userInfo.setUserID(userID); int insertResult = 0; // 密码经过 MD5 hash userInfo.setPassword(Value.MD5Hash(userInfo.getPassword())); if(1 == userType) { // 患者 if (pm.ifPhone(userInfo.getUserPhone()) > 0) { // 手机号注册过 data.put("result", "1"); } else { insertResult = pm.newPatient(userInfo); if (insertResult != 1) { data.put("result", "2"); } } } else if(2 == userType) { // 医生 if(dm.ifPhone(userInfo.getUserPhone()) > 0) { // 手机号注册过 data.put("result", "1"); } else { insertResult = dm.newDoctor(userInfo); if(insertResult != 1 ) { data.put("result", "2"); } } } else { json.setData(201); return json; } if(1 == insertResult) { data.put("result", "0"); um.updateUserCount(); // 注册成功,生成密钥对 Map<String, String> keyMap = Value.generateRSAKeyPair(); String publicKey = keyMap.get("publicKey"); String privateKey = keyMap.get("privateKey"); if(um.newUserPublicKey(userID, publicKey)==1) { data.put("privateKey", privateKey); } else { data.put("result", "2"); } } json.setData(data); return json; } @Override @Transactional(readOnly = true) public BackJSON getHospitalID(String hospitalName) { BackJSON json = new BackJSON(200); Map<String, Object> data = new HashMap<>(); Integer hospitalID = um.getHospitalID(hospitalName); if(hospitalID!=null) { data.put("hospitalID", hospitalID); } else { // 不存在,返回 0 data.put("hospitalID", 0); } json.setData(data); return json; } @Override @Transactional(readOnly = true) public BackJSON userLogin(UserInfo userInfo) { BackJSON json = new BackJSON(200); Map<String, Object> data = new HashMap<>(); int userType = userInfo.getUserType(); String phone = userInfo.getUserPhone(); String password = userInfo.getPassword(); if(1==userType) { // 患者 Patient patient = pm.patientLogin(phone); if(null==patient) { // 手机号不存在 data.put("result", 2); } else { if(patient.getPatientState()!=0) { // 患者处于非法状态 data.put("result", 3); } else { if(!Value.MD5Verify(password, patient.getPatientPassword())) { // 用户名或密码错误 data.put("result", 1); } else { data.put("result", 0); data.put("userID", patient.getPatientID()); } } } } else if(2==userType) { // 医生 Doctor doctor = dm.doctorLogin(phone); if(null==doctor) { // 手机号不存在 data.put("result", 2); } else { if(doctor.getDoctorState()!=0) { // 患者处于非法状态 data.put("result", 3); } else { if(!Value.MD5Verify(password, doctor.getDoctorPassword())) { // 用户名或密码错误 data.put("result", 1); } else { data.put("result", 0); data.put("userID", doctor.getDoctorID()); } } } } else { data.put("result", 4); } json.setData(data); return json; } }
BattleCall3/graduatework
code/medical/src/main/java/wow/service/UserServiceImpl.java
1,331
// 用户名或密码错误
line_comment
zh-cn
package wow.service; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import wow.entity.BackJSON; import wow.entity.Doctor; import wow.entity.Patient; import wow.entity.UserInfo; import wow.mapper.DoctorMapper; import wow.mapper.PatientMapper; import wow.mapper.UserMapper; import wow.util.Value; @Service @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT) public class UserServiceImpl implements UserService { @Autowired private UserMapper um; @Autowired private PatientMapper pm; @Autowired private DoctorMapper dm; @Override @Transactional public BackJSON userRegister(UserInfo userInfo) { BackJSON json = new BackJSON(200); Map<String, String> data = new HashMap<>(); int userType = userInfo.getUserType(); int userID = um.getUserCount(); userInfo.setUserID(userID); int insertResult = 0; // 密码经过 MD5 hash userInfo.setPassword(Value.MD5Hash(userInfo.getPassword())); if(1 == userType) { // 患者 if (pm.ifPhone(userInfo.getUserPhone()) > 0) { // 手机号注册过 data.put("result", "1"); } else { insertResult = pm.newPatient(userInfo); if (insertResult != 1) { data.put("result", "2"); } } } else if(2 == userType) { // 医生 if(dm.ifPhone(userInfo.getUserPhone()) > 0) { // 手机号注册过 data.put("result", "1"); } else { insertResult = dm.newDoctor(userInfo); if(insertResult != 1 ) { data.put("result", "2"); } } } else { json.setData(201); return json; } if(1 == insertResult) { data.put("result", "0"); um.updateUserCount(); // 注册成功,生成密钥对 Map<String, String> keyMap = Value.generateRSAKeyPair(); String publicKey = keyMap.get("publicKey"); String privateKey = keyMap.get("privateKey"); if(um.newUserPublicKey(userID, publicKey)==1) { data.put("privateKey", privateKey); } else { data.put("result", "2"); } } json.setData(data); return json; } @Override @Transactional(readOnly = true) public BackJSON getHospitalID(String hospitalName) { BackJSON json = new BackJSON(200); Map<String, Object> data = new HashMap<>(); Integer hospitalID = um.getHospitalID(hospitalName); if(hospitalID!=null) { data.put("hospitalID", hospitalID); } else { // 不存在,返回 0 data.put("hospitalID", 0); } json.setData(data); return json; } @Override @Transactional(readOnly = true) public BackJSON userLogin(UserInfo userInfo) { BackJSON json = new BackJSON(200); Map<String, Object> data = new HashMap<>(); int userType = userInfo.getUserType(); String phone = userInfo.getUserPhone(); String password = userInfo.getPassword(); if(1==userType) { // 患者 Patient patient = pm.patientLogin(phone); if(null==patient) { // 手机号不存在 data.put("result", 2); } else { if(patient.getPatientState()!=0) { // 患者处于非法状态 data.put("result", 3); } else { if(!Value.MD5Verify(password, patient.getPatientPassword())) { // 用户 <SUF> data.put("result", 1); } else { data.put("result", 0); data.put("userID", patient.getPatientID()); } } } } else if(2==userType) { // 医生 Doctor doctor = dm.doctorLogin(phone); if(null==doctor) { // 手机号不存在 data.put("result", 2); } else { if(doctor.getDoctorState()!=0) { // 患者处于非法状态 data.put("result", 3); } else { if(!Value.MD5Verify(password, doctor.getDoctorPassword())) { // 用户名或密码错误 data.put("result", 1); } else { data.put("result", 0); data.put("userID", doctor.getDoctorID()); } } } } else { data.put("result", 4); } json.setData(data); return json; } }
0
1,105
7
1,317
7
1,278
7
1,317
7
1,742
13
false
false
false
false
false
true
63900_2
package org.laopopo.monitor; import static org.laopopo.common.protocal.LaopopoProtocol.MANAGER_SERVICE; import static org.laopopo.common.protocal.LaopopoProtocol.MERTRICS_SERVICE; import static org.laopopo.common.serialization.SerializerHolder.serializerImpl; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.util.internal.ConcurrentSet; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.laopopo.common.metrics.ServiceMetrics; import org.laopopo.common.metrics.ServiceMetrics.ProviderInfo; import org.laopopo.common.protocal.LaopopoProtocol; import org.laopopo.common.rpc.ManagerServiceRequestType; import org.laopopo.common.rpc.MetricsReporter; import org.laopopo.common.rpc.RegisterMeta; import org.laopopo.common.rpc.RegisterMeta.Address; import org.laopopo.common.transport.body.ManagerServiceCustomBody; import org.laopopo.common.transport.body.MetricsCustomBody; import org.laopopo.common.transport.body.ProviderMetricsCustomBody; import org.laopopo.remoting.ConnectionUtils; import org.laopopo.remoting.model.NettyRequestProcessor; import org.laopopo.remoting.model.RemotingTransporter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author BazingaLyn * @description monitor的处理器 * @time 2016年8月17日 * @modifytime */ public class DefaultMonitorProcessor implements NettyRequestProcessor { private static final Logger logger = LoggerFactory.getLogger(DefaultMonitorProcessor.class); private DefaultMonitor defaultMonitor; public DefaultMonitorProcessor(DefaultMonitor defaultMonitor) { this.defaultMonitor = defaultMonitor; } @Override public RemotingTransporter processRequest(ChannelHandlerContext ctx, RemotingTransporter request) throws Exception { if (logger.isDebugEnabled()) { logger.debug("receive request, {} {} {}",// request.getCode(), // ConnectionUtils.parseChannelRemoteAddr(ctx.channel()), // request); } switch (request.getCode()) { case MERTRICS_SERVICE: //因为服务提供者端是定时发送统计信息的,如果没有收到或者消费失败了,则丢弃,不做强制消费的ack判断要求provider重发 return handlerMetricsService(request,ctx.channel()); case MANAGER_SERVICE: return handlerManagerService(request,ctx.channel()); } return null; } private RemotingTransporter handlerManagerService(RemotingTransporter request, Channel channel) { MetricsCustomBody metricsCustomBody = new MetricsCustomBody(); RemotingTransporter remotingTransporter = RemotingTransporter.createResponseTransporter(LaopopoProtocol.MERTRICS_SERVICE, metricsCustomBody, request.getOpaque()); ManagerServiceCustomBody body = serializerImpl().readObject(request.bytes(), ManagerServiceCustomBody.class); if(body.getManagerServiceRequestType() == ManagerServiceRequestType.METRICS){ String serviceName = body.getSerivceName(); ConcurrentMap<Address, MetricsReporter> maps = defaultMonitor.getGlobalMetricsReporter().get(serviceName); ConcurrentMap<Address, MetricsReporter> historyMaps = defaultMonitor.getHistoryGlobalMetricsReporter().get(serviceName); //返回给管理页面的对象 ServiceMetrics metrics = new ServiceMetrics(); metrics.setServiceName(serviceName); //从当前的统计信息中,构建返回体 buildMetrics(maps,metrics); //从持久化信息中返回 buildMetrics(historyMaps,metrics); List<ServiceMetrics> serviceMetricses = new ArrayList<ServiceMetrics>(); serviceMetricses.add(metrics); metricsCustomBody.setServiceMetricses(serviceMetricses); } return remotingTransporter; } private void buildMetrics(ConcurrentMap<Address, MetricsReporter> maps, ServiceMetrics metrics) { if (null != maps) { Long totalCallCount = 0l; Long totalFailCount = 0l; Long totalTime = 0l; Long totalRequestSize = 0l; for (Address address : maps.keySet()) { MetricsReporter metricsReporter = maps.get(address); Long callCount = metricsReporter.getCallCount(); Long failCount = metricsReporter.getFailCount(); Long requestSize = metricsReporter.getRequestSize(); Long handlerTime = metricsReporter.getTotalReuqestTime(); totalCallCount += callCount; totalFailCount += failCount; totalRequestSize += requestSize; totalTime += handlerTime; ConcurrentMap<Address, ProviderInfo> providerConcurrentMap = metrics.getProviderMaps(); ProviderInfo info = providerConcurrentMap.get(address); if (info == null) { info = new ProviderInfo(); info.setHost(address.getHost()); info.setPort(address.getPort()); providerConcurrentMap.put(address, info); } Long eachHandlerAvgTime = 0l; if ((info.getCallCount() - info.getFailCount() + metricsReporter.getCallCount() - metricsReporter.getFailCount()) != 0) { eachHandlerAvgTime = ((info.getCallCount() - info.getFailCount()) * info.getHandlerAvgTime() + metricsReporter.getTotalReuqestTime()) / (info.getCallCount() - info.getFailCount() + metricsReporter.getCallCount() - metricsReporter.getFailCount()); } info.setHandlerAvgTime(eachHandlerAvgTime); info.setCallCount(info.getCallCount() + callCount); info.setFailCount(info.getFailCount() + failCount); info.setRequestSize(info.getRequestSize() + requestSize); } metrics.setTotalCallCount(metrics.getTotalCallCount() + totalCallCount); metrics.setTotalFailCount(metrics.getTotalFailCount() + totalFailCount); Long existTotalTime = (metrics.getTotalCallCount() - metrics.getTotalFailCount()) * metrics.getHandlerAvgTime(); if (metrics.getTotalCallCount() - metrics.getTotalFailCount() != 0) { metrics.setHandlerAvgTime((existTotalTime + totalTime) / (metrics.getTotalCallCount() - metrics.getTotalFailCount())); } else { metrics.setHandlerAvgTime(0L); } metrics.setRequestSize(metrics.getRequestSize() + totalRequestSize); } } /** * 处理服务提供者发送过来的统计信息 * 这边需要注意的是,因为服务提供端不是按照时间段去统计的,而是从服务启动的时候就开始统计,也就说服务提供端发送过来的信息是全量信息,不是增量信息 * 所以我们这边要做的是将provider发送过来最新的信息替换monitor本地的信息,而不是将本地的信息与provider发送的信息做累加操作 * * @param request * @param channel * @return */ private RemotingTransporter handlerMetricsService(RemotingTransporter request, Channel channel) { //反序列化内容 ProviderMetricsCustomBody body = serializerImpl().readObject(request.bytes(),ProviderMetricsCustomBody.class); if(body.getMetricsReporter() != null && !body.getMetricsReporter().isEmpty()){ for(MetricsReporter metricsReporter : body.getMetricsReporter()){ String host = ConnectionUtils.parseChannelRemoteAddress(channel).getHost(); Address address = new Address(host, metricsReporter.getPort()); metricsReporter.setHost(host); ConcurrentSet<Address> addresses = defaultMonitor.getGlobalProviderReporter().get(channel); if(addresses == null){ addresses = new ConcurrentSet<Address>(); defaultMonitor.getGlobalProviderReporter().put(channel, addresses); } addresses.add(address); String serviceName = metricsReporter.getServiceName(); ConcurrentMap<Address, MetricsReporter> maps = defaultMonitor.getGlobalMetricsReporter().get(serviceName); //第一次发送统计信息的时候,map为null,需要赋值 if(maps == null){ maps = new ConcurrentHashMap<RegisterMeta.Address, MetricsReporter>(); defaultMonitor.getGlobalMetricsReporter().put(serviceName, maps); } maps.put(address, metricsReporter); } } return null; } }
BazingaLyn/laopopo-rpc
laopopo-monitor/src/main/java/org/laopopo/monitor/DefaultMonitorProcessor.java
2,067
//返回给管理页面的对象
line_comment
zh-cn
package org.laopopo.monitor; import static org.laopopo.common.protocal.LaopopoProtocol.MANAGER_SERVICE; import static org.laopopo.common.protocal.LaopopoProtocol.MERTRICS_SERVICE; import static org.laopopo.common.serialization.SerializerHolder.serializerImpl; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.util.internal.ConcurrentSet; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.laopopo.common.metrics.ServiceMetrics; import org.laopopo.common.metrics.ServiceMetrics.ProviderInfo; import org.laopopo.common.protocal.LaopopoProtocol; import org.laopopo.common.rpc.ManagerServiceRequestType; import org.laopopo.common.rpc.MetricsReporter; import org.laopopo.common.rpc.RegisterMeta; import org.laopopo.common.rpc.RegisterMeta.Address; import org.laopopo.common.transport.body.ManagerServiceCustomBody; import org.laopopo.common.transport.body.MetricsCustomBody; import org.laopopo.common.transport.body.ProviderMetricsCustomBody; import org.laopopo.remoting.ConnectionUtils; import org.laopopo.remoting.model.NettyRequestProcessor; import org.laopopo.remoting.model.RemotingTransporter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author BazingaLyn * @description monitor的处理器 * @time 2016年8月17日 * @modifytime */ public class DefaultMonitorProcessor implements NettyRequestProcessor { private static final Logger logger = LoggerFactory.getLogger(DefaultMonitorProcessor.class); private DefaultMonitor defaultMonitor; public DefaultMonitorProcessor(DefaultMonitor defaultMonitor) { this.defaultMonitor = defaultMonitor; } @Override public RemotingTransporter processRequest(ChannelHandlerContext ctx, RemotingTransporter request) throws Exception { if (logger.isDebugEnabled()) { logger.debug("receive request, {} {} {}",// request.getCode(), // ConnectionUtils.parseChannelRemoteAddr(ctx.channel()), // request); } switch (request.getCode()) { case MERTRICS_SERVICE: //因为服务提供者端是定时发送统计信息的,如果没有收到或者消费失败了,则丢弃,不做强制消费的ack判断要求provider重发 return handlerMetricsService(request,ctx.channel()); case MANAGER_SERVICE: return handlerManagerService(request,ctx.channel()); } return null; } private RemotingTransporter handlerManagerService(RemotingTransporter request, Channel channel) { MetricsCustomBody metricsCustomBody = new MetricsCustomBody(); RemotingTransporter remotingTransporter = RemotingTransporter.createResponseTransporter(LaopopoProtocol.MERTRICS_SERVICE, metricsCustomBody, request.getOpaque()); ManagerServiceCustomBody body = serializerImpl().readObject(request.bytes(), ManagerServiceCustomBody.class); if(body.getManagerServiceRequestType() == ManagerServiceRequestType.METRICS){ String serviceName = body.getSerivceName(); ConcurrentMap<Address, MetricsReporter> maps = defaultMonitor.getGlobalMetricsReporter().get(serviceName); ConcurrentMap<Address, MetricsReporter> historyMaps = defaultMonitor.getHistoryGlobalMetricsReporter().get(serviceName); //返回 <SUF> ServiceMetrics metrics = new ServiceMetrics(); metrics.setServiceName(serviceName); //从当前的统计信息中,构建返回体 buildMetrics(maps,metrics); //从持久化信息中返回 buildMetrics(historyMaps,metrics); List<ServiceMetrics> serviceMetricses = new ArrayList<ServiceMetrics>(); serviceMetricses.add(metrics); metricsCustomBody.setServiceMetricses(serviceMetricses); } return remotingTransporter; } private void buildMetrics(ConcurrentMap<Address, MetricsReporter> maps, ServiceMetrics metrics) { if (null != maps) { Long totalCallCount = 0l; Long totalFailCount = 0l; Long totalTime = 0l; Long totalRequestSize = 0l; for (Address address : maps.keySet()) { MetricsReporter metricsReporter = maps.get(address); Long callCount = metricsReporter.getCallCount(); Long failCount = metricsReporter.getFailCount(); Long requestSize = metricsReporter.getRequestSize(); Long handlerTime = metricsReporter.getTotalReuqestTime(); totalCallCount += callCount; totalFailCount += failCount; totalRequestSize += requestSize; totalTime += handlerTime; ConcurrentMap<Address, ProviderInfo> providerConcurrentMap = metrics.getProviderMaps(); ProviderInfo info = providerConcurrentMap.get(address); if (info == null) { info = new ProviderInfo(); info.setHost(address.getHost()); info.setPort(address.getPort()); providerConcurrentMap.put(address, info); } Long eachHandlerAvgTime = 0l; if ((info.getCallCount() - info.getFailCount() + metricsReporter.getCallCount() - metricsReporter.getFailCount()) != 0) { eachHandlerAvgTime = ((info.getCallCount() - info.getFailCount()) * info.getHandlerAvgTime() + metricsReporter.getTotalReuqestTime()) / (info.getCallCount() - info.getFailCount() + metricsReporter.getCallCount() - metricsReporter.getFailCount()); } info.setHandlerAvgTime(eachHandlerAvgTime); info.setCallCount(info.getCallCount() + callCount); info.setFailCount(info.getFailCount() + failCount); info.setRequestSize(info.getRequestSize() + requestSize); } metrics.setTotalCallCount(metrics.getTotalCallCount() + totalCallCount); metrics.setTotalFailCount(metrics.getTotalFailCount() + totalFailCount); Long existTotalTime = (metrics.getTotalCallCount() - metrics.getTotalFailCount()) * metrics.getHandlerAvgTime(); if (metrics.getTotalCallCount() - metrics.getTotalFailCount() != 0) { metrics.setHandlerAvgTime((existTotalTime + totalTime) / (metrics.getTotalCallCount() - metrics.getTotalFailCount())); } else { metrics.setHandlerAvgTime(0L); } metrics.setRequestSize(metrics.getRequestSize() + totalRequestSize); } } /** * 处理服务提供者发送过来的统计信息 * 这边需要注意的是,因为服务提供端不是按照时间段去统计的,而是从服务启动的时候就开始统计,也就说服务提供端发送过来的信息是全量信息,不是增量信息 * 所以我们这边要做的是将provider发送过来最新的信息替换monitor本地的信息,而不是将本地的信息与provider发送的信息做累加操作 * * @param request * @param channel * @return */ private RemotingTransporter handlerMetricsService(RemotingTransporter request, Channel channel) { //反序列化内容 ProviderMetricsCustomBody body = serializerImpl().readObject(request.bytes(),ProviderMetricsCustomBody.class); if(body.getMetricsReporter() != null && !body.getMetricsReporter().isEmpty()){ for(MetricsReporter metricsReporter : body.getMetricsReporter()){ String host = ConnectionUtils.parseChannelRemoteAddress(channel).getHost(); Address address = new Address(host, metricsReporter.getPort()); metricsReporter.setHost(host); ConcurrentSet<Address> addresses = defaultMonitor.getGlobalProviderReporter().get(channel); if(addresses == null){ addresses = new ConcurrentSet<Address>(); defaultMonitor.getGlobalProviderReporter().put(channel, addresses); } addresses.add(address); String serviceName = metricsReporter.getServiceName(); ConcurrentMap<Address, MetricsReporter> maps = defaultMonitor.getGlobalMetricsReporter().get(serviceName); //第一次发送统计信息的时候,map为null,需要赋值 if(maps == null){ maps = new ConcurrentHashMap<RegisterMeta.Address, MetricsReporter>(); defaultMonitor.getGlobalMetricsReporter().put(serviceName, maps); } maps.put(address, metricsReporter); } } return null; } }
0
1,769
6
2,067
7
2,082
7
2,067
7
2,748
11
false
false
false
false
false
true
53371_1
package com.DI.dao.Impl; import com.DI.dao.UserDao; //创建一个业务逻辑接口 public class UserDaoImpl implements UserDao { public boolean login(String name, String password) { //如果名字是比尔和密码是123456就返回true if(name.equals("比尔")&&password.equals("12345")){ return true; } return false; } }
BeAlrightc/java_pro_note
spring家族/spring/project/ioc/DlLearning/src/main/java/com/DI/dao/Impl/UserDaoImpl.java
105
//如果名字是比尔和密码是123456就返回true
line_comment
zh-cn
package com.DI.dao.Impl; import com.DI.dao.UserDao; //创建一个业务逻辑接口 public class UserDaoImpl implements UserDao { public boolean login(String name, String password) { //如果 <SUF> if(name.equals("比尔")&&password.equals("12345")){ return true; } return false; } }
0
92
18
105
18
107
18
105
18
134
22
false
false
false
false
false
true
37242_3
public class Operator { /* /输入:Student 对象 /输出:无 /功能:往学生数组中添加一个新学生 */ public static void addStudent(Student stu) { for (Student s : Students) { if (s.getName() == NULL) { s.initStudent(stu.getName(), stu.getAddress(), stu.getPhoneNumber(), stu.getWeChat(), stu.getMail(), stu.getQQ(), stu.getPersonalLanguage()); } } } /* /输入:学生姓名,类型为 String /输出:无 /功能:将学生数组中该名字的学生姓名置空,达到删除目的 */ public static void removeStudent(String stuName) { for (Student s : Students) { if (s.getName() == stuName) { s.setName(NULL); } } } /* /输入:Student 对象 /输出:无 /功能:按传入的对象更新学生数组中该名字的学生 */ public static void changeStudent(Student stu) { String stuName = stu.getName(); for (Student s : Students) { if (s.getName() == stuName) { s.initStudent(stuName, stu.getAddress(), stu.getPhoneNumber(), stu.getWeChat(), stu.getMail(), stu.getQQ(), stu.getPersonalLanguage()); } } } /* /输入:学生姓名,类型为 String /输出:Student 对象 /功能:查找该名字的学生的信息 */ public static Student searchStudent(String stuName) { Student theStudent; for (Student s : Students) { if (s.getName() == stuName) { theStudent.initStudent(stuName, s.getAddress(), s.getPhoneNumber(), s.getWeChat(), s.getMail(), s.getQQ(), s.getPersonalLanguage()); } } return theStudent; } }
BeiDouQiXing/Classmate-book
Operate.java
468
/* /输入:学生姓名,类型为 String /输出:Student 对象 /功能:查找该名字的学生的信息 */
block_comment
zh-cn
public class Operator { /* /输入:Student 对象 /输出:无 /功能:往学生数组中添加一个新学生 */ public static void addStudent(Student stu) { for (Student s : Students) { if (s.getName() == NULL) { s.initStudent(stu.getName(), stu.getAddress(), stu.getPhoneNumber(), stu.getWeChat(), stu.getMail(), stu.getQQ(), stu.getPersonalLanguage()); } } } /* /输入:学生姓名,类型为 String /输出:无 /功能:将学生数组中该名字的学生姓名置空,达到删除目的 */ public static void removeStudent(String stuName) { for (Student s : Students) { if (s.getName() == stuName) { s.setName(NULL); } } } /* /输入:Student 对象 /输出:无 /功能:按传入的对象更新学生数组中该名字的学生 */ public static void changeStudent(Student stu) { String stuName = stu.getName(); for (Student s : Students) { if (s.getName() == stuName) { s.initStudent(stuName, stu.getAddress(), stu.getPhoneNumber(), stu.getWeChat(), stu.getMail(), stu.getQQ(), stu.getPersonalLanguage()); } } } /* /输入: <SUF>*/ public static Student searchStudent(String stuName) { Student theStudent; for (Student s : Students) { if (s.getName() == stuName) { theStudent.initStudent(stuName, s.getAddress(), s.getPhoneNumber(), s.getWeChat(), s.getMail(), s.getQQ(), s.getPersonalLanguage()); } } return theStudent; } }
0
422
32
468
30
497
32
468
30
610
50
false
false
false
false
false
true
27847_4
package bus.service; import bus.Vo.CustomerVo; import bus.domian.Customer; import sys.utils.DataGridView; import java.util.List; public interface CustomerService { /*查询所有客户*/ DataGridView queryAllCustomer(CustomerVo customerVo); /*添加客户*/ void addCustomer(CustomerVo customerVo); /*修改客户*/ void updateCustomer(CustomerVo customerVo); /*根据id删除客户*/ void deleteCustomer(String identity); /*批量删除客户*/ void deleteBatchCustomer(String[] identitys); /*根据客户身份证号查询信息,用在判断这个客户是否存在,在出售表哪里*/ Customer queryCustomerByIdentity(String identity); /*到处客户数据*/ List<Customer> queryCustomerAllList(CustomerVo customerVo); }
Berlin12034/ssm_gift
src/main/java/bus/service/CustomerService.java
188
/*批量删除客户*/
block_comment
zh-cn
package bus.service; import bus.Vo.CustomerVo; import bus.domian.Customer; import sys.utils.DataGridView; import java.util.List; public interface CustomerService { /*查询所有客户*/ DataGridView queryAllCustomer(CustomerVo customerVo); /*添加客户*/ void addCustomer(CustomerVo customerVo); /*修改客户*/ void updateCustomer(CustomerVo customerVo); /*根据id删除客户*/ void deleteCustomer(String identity); /*批量删 <SUF>*/ void deleteBatchCustomer(String[] identitys); /*根据客户身份证号查询信息,用在判断这个客户是否存在,在出售表哪里*/ Customer queryCustomerByIdentity(String identity); /*到处客户数据*/ List<Customer> queryCustomerAllList(CustomerVo customerVo); }
0
154
5
188
5
192
5
188
5
256
10
false
false
false
false
false
true
28085_0
package DP; public class LC70_ClimbingStairs { public static int climb (int n) { if (n < 2) return 1; int ans = 0; // 状态转移方程 // dp[i] 只与 dp[i - 1] 与 dp[i - 2] 有关 // f(x) = f(x - 1) + f(x - 2) // 特别的, 有 f(0) = 1, f(1) = 1 int p1 = 1, p2 = 1; for (int i = 2; i <= n; ++i) { ans = p1 + p2; p2 = p1; p1 = ans; } return ans; } // 1 1 2 3 5 8 public static void main(String[] args) { int n = 5; System.out.println(climb(n)); } }
Bi1ack/LeetCode
src/DP/LC70_ClimbingStairs.java
236
// 状态转移方程
line_comment
zh-cn
package DP; public class LC70_ClimbingStairs { public static int climb (int n) { if (n < 2) return 1; int ans = 0; // 状态 <SUF> // dp[i] 只与 dp[i - 1] 与 dp[i - 2] 有关 // f(x) = f(x - 1) + f(x - 2) // 特别的, 有 f(0) = 1, f(1) = 1 int p1 = 1, p2 = 1; for (int i = 2; i <= n; ++i) { ans = p1 + p2; p2 = p1; p1 = ans; } return ans; } // 1 1 2 3 5 8 public static void main(String[] args) { int n = 5; System.out.println(climb(n)); } }
0
223
6
236
7
245
5
236
7
268
8
false
false
false
false
false
true
16472_11
package models; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import play.db.jpa.GenericModel; import play.libs.Codec; import utils.PageBean; import utils.StringUtils; /* * 租房信息表 * @author john */ @Entity @Table(name = "house") public class House extends GenericModel{ @Id public String id; //出租方 @ManyToOne public User author; //1为隐藏,2为显示 @Column(name="status",columnDefinition="int default 1") public int status; //1代表待审核,2为审核不通过,3为审核通过,管理员添加的默认为3 @Column(name="audit",columnDefinition="int default 1") public int audit; //出租方式 @Column(name = "way") public String way; //您的身份 public String indentity; //联系人 public String contacts; //联系电话 public String phone; //小区 @Column(name="community") public String community; //地址 @Column(name = "address") public String address; //户型 @Column(name = "bed_room") public int bedRoom; @Column(name = "living_rom") public int livingRoom; @Column(name = "bath_room") public int bathRoom; public double square; //楼层 @Column(name = "current_floor") public int currentFloor; @Column(name = "count_floor") public int countFloor; //房屋情况 @Column(name = "decoration_situation") public String decorationSituation; @Column(name = "class_situation") public String classSituation; //家电配备 public String equipment; //租金 @Column(name = "price") public double price; //描述 @Column(name = "details") public String details; //照片 @Column(name = "photo_url") public String photoUrl; //初始化构造方法 public House(){ this.id = Codec.UUID(); this.status=1; this.audit=1; } //查询房子信息 //关键字 当前页 public static List<House> findHouses(String searchKey, int curPage) { if (StringUtils.isEmpty(searchKey)) { return House.all().fetch(curPage, 5); } else { return House.find("address like ?", "%" + searchKey + "%").fetch( curPage, 5); } } //pagebean public static PageBean getPageBean(String searchKey, int curPage) { long total = 0; if (StringUtils.isEmpty(searchKey)) total = House.count(); else total = House.find("address like ?", "%" + searchKey + "%").fetch() .size(); return PageBean.getInstance(curPage, total, 5); } //是否显示 public boolean isShow(){ return status==2; } }
BiaoPro/community
app/models/House.java
858
//楼层
line_comment
zh-cn
package models; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.Table; import play.db.jpa.GenericModel; import play.libs.Codec; import utils.PageBean; import utils.StringUtils; /* * 租房信息表 * @author john */ @Entity @Table(name = "house") public class House extends GenericModel{ @Id public String id; //出租方 @ManyToOne public User author; //1为隐藏,2为显示 @Column(name="status",columnDefinition="int default 1") public int status; //1代表待审核,2为审核不通过,3为审核通过,管理员添加的默认为3 @Column(name="audit",columnDefinition="int default 1") public int audit; //出租方式 @Column(name = "way") public String way; //您的身份 public String indentity; //联系人 public String contacts; //联系电话 public String phone; //小区 @Column(name="community") public String community; //地址 @Column(name = "address") public String address; //户型 @Column(name = "bed_room") public int bedRoom; @Column(name = "living_rom") public int livingRoom; @Column(name = "bath_room") public int bathRoom; public double square; //楼层 <SUF> @Column(name = "current_floor") public int currentFloor; @Column(name = "count_floor") public int countFloor; //房屋情况 @Column(name = "decoration_situation") public String decorationSituation; @Column(name = "class_situation") public String classSituation; //家电配备 public String equipment; //租金 @Column(name = "price") public double price; //描述 @Column(name = "details") public String details; //照片 @Column(name = "photo_url") public String photoUrl; //初始化构造方法 public House(){ this.id = Codec.UUID(); this.status=1; this.audit=1; } //查询房子信息 //关键字 当前页 public static List<House> findHouses(String searchKey, int curPage) { if (StringUtils.isEmpty(searchKey)) { return House.all().fetch(curPage, 5); } else { return House.find("address like ?", "%" + searchKey + "%").fetch( curPage, 5); } } //pagebean public static PageBean getPageBean(String searchKey, int curPage) { long total = 0; if (StringUtils.isEmpty(searchKey)) total = House.count(); else total = House.find("address like ?", "%" + searchKey + "%").fetch() .size(); return PageBean.getInstance(curPage, total, 5); } //是否显示 public boolean isShow(){ return status==2; } }
0
649
3
845
4
821
4
845
4
985
8
false
false
false
false
false
true
3583_11
package com.kit.widget.scrollview; import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.TranslateAnimation; import android.widget.ScrollView; /** * 自定义ScrollView 实现弹性回弹功能 */ public class ReboundScrollView2 extends ScrollView { private View inner;// 孩子 private float y;// 坐标 private Rect normal = new Rect();// 矩形空白 public ReboundScrollView2(Context context, AttributeSet attrs) { super(context, attrs); } /*** * 根据 XML 生成视图工作完成.该函数在生成视图的最后调用,在所有子视图添加完之后. 即使子类覆盖了 onFinishInflate * 方法,也应该调用父类的方法,使该方法得以执行. */ @Override protected void onFinishInflate() { if (getChildCount() > 0) { inner = getChildAt(0);// 获取其孩子 } } @Override public boolean onTouchEvent(MotionEvent ev) { if (inner != null) { commOnTouchEvent(ev); } return super.onTouchEvent(ev); } /*** * 触摸事件 * * @param ev */ public void commOnTouchEvent(MotionEvent ev) { int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: y = ev.getY();// 获取点击y坐标 break; case MotionEvent.ACTION_UP: if (isNeedAnimation()) { animation(); } break; case MotionEvent.ACTION_MOVE: final float preY = y; float nowY = ev.getY(); int deltaY = (int) (preY - nowY);// 获取滑动距离 y = nowY; // 当滚动到最上或者最下时就不会再滚动,这时移动布局 if (isNeedMove()) { if (normal.isEmpty()) { // 填充矩形,目的:就是告诉this:我现在已经有了,你松开的时候记得要执行回归动画. normal.set(inner.getLeft(), inner.getTop(), inner.getRight(), inner.getBottom()); } // 移动布局 inner.layout(inner.getLeft(), inner.getTop() - deltaY / 4, inner.getRight(), inner.getBottom() - deltaY / 4); } break; default: break; } } /*** * 开启动画移动 */ public void animation() { // 开启移动动画 TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(), normal.top); ta.setDuration(300); inner.startAnimation(ta); // 设置回到正常的布局位置 inner.layout(normal.left, normal.top, normal.right, normal.bottom); normal.setEmpty();// 清空矩形 } /*** * 是否需要开启动画 * * 如果矩形不为空,返回true,否则返回false. * * * @return */ public boolean isNeedAnimation() { return !normal.isEmpty(); } /*** * 是否需要移动布局 inner.getMeasuredHeight():获取的是控件的高度 * getHeight():获取的是当前控件在屏幕中显示的高度 * * @return */ public boolean isNeedMove() { int offset = inner.getMeasuredHeight() - getHeight(); int scrollY = getScrollY(); // 0是顶部,后面那个是底部 if (scrollY == 0 || scrollY == offset) { return true; } return false; } }
BigAppOS/BigApp_Discuz_Android
libs/ZUtilsExtWidget/src/com/kit/widget/scrollview/ReboundScrollView2.java
959
// 开启移动动画
line_comment
zh-cn
package com.kit.widget.scrollview; import android.content.Context; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.TranslateAnimation; import android.widget.ScrollView; /** * 自定义ScrollView 实现弹性回弹功能 */ public class ReboundScrollView2 extends ScrollView { private View inner;// 孩子 private float y;// 坐标 private Rect normal = new Rect();// 矩形空白 public ReboundScrollView2(Context context, AttributeSet attrs) { super(context, attrs); } /*** * 根据 XML 生成视图工作完成.该函数在生成视图的最后调用,在所有子视图添加完之后. 即使子类覆盖了 onFinishInflate * 方法,也应该调用父类的方法,使该方法得以执行. */ @Override protected void onFinishInflate() { if (getChildCount() > 0) { inner = getChildAt(0);// 获取其孩子 } } @Override public boolean onTouchEvent(MotionEvent ev) { if (inner != null) { commOnTouchEvent(ev); } return super.onTouchEvent(ev); } /*** * 触摸事件 * * @param ev */ public void commOnTouchEvent(MotionEvent ev) { int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: y = ev.getY();// 获取点击y坐标 break; case MotionEvent.ACTION_UP: if (isNeedAnimation()) { animation(); } break; case MotionEvent.ACTION_MOVE: final float preY = y; float nowY = ev.getY(); int deltaY = (int) (preY - nowY);// 获取滑动距离 y = nowY; // 当滚动到最上或者最下时就不会再滚动,这时移动布局 if (isNeedMove()) { if (normal.isEmpty()) { // 填充矩形,目的:就是告诉this:我现在已经有了,你松开的时候记得要执行回归动画. normal.set(inner.getLeft(), inner.getTop(), inner.getRight(), inner.getBottom()); } // 移动布局 inner.layout(inner.getLeft(), inner.getTop() - deltaY / 4, inner.getRight(), inner.getBottom() - deltaY / 4); } break; default: break; } } /*** * 开启动画移动 */ public void animation() { // 开启 <SUF> TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(), normal.top); ta.setDuration(300); inner.startAnimation(ta); // 设置回到正常的布局位置 inner.layout(normal.left, normal.top, normal.right, normal.bottom); normal.setEmpty();// 清空矩形 } /*** * 是否需要开启动画 * * 如果矩形不为空,返回true,否则返回false. * * * @return */ public boolean isNeedAnimation() { return !normal.isEmpty(); } /*** * 是否需要移动布局 inner.getMeasuredHeight():获取的是控件的高度 * getHeight():获取的是当前控件在屏幕中显示的高度 * * @return */ public boolean isNeedMove() { int offset = inner.getMeasuredHeight() - getHeight(); int scrollY = getScrollY(); // 0是顶部,后面那个是底部 if (scrollY == 0 || scrollY == offset) { return true; } return false; } }
0
819
5
961
5
924
5
959
5
1,291
10
false
false
false
false
false
true
54057_3
package com.bill56.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bill56.carlife.R; import com.bill56.entity.UserCar; import java.util.List; /** * Created by Bill56 on 2016/5/23. */ public class CarInfoAdapter extends BaseAdapter { // 上下文环境 private Context mContext; // 数据 private List<UserCar> mData; // 布局服务加载器 private LayoutInflater layoutInflater; public CarInfoAdapter(Context context, List<UserCar> data) { this.mContext = context; mData = data; layoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return mData.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; // 加载模板,创建视图项——将布局创建成一个View对象 if (convertView == null) { convertView = layoutInflater.inflate(R.layout.item_car_info, parent, false); viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } UserCar userCar = mData.get(position); viewHolder.bindData(userCar); return convertView; } /** * 保存布局控件实例的类 */ private class ViewHolder { // 字段 ImageView imgCarLogo; TextView textCarBrandVersion; TextView textTotalOil; TextView textCarLicence; TextView textTransState; TextView textEngineState; TextView textLightState; TextView textEngineNo; /** * 构造方法,获得布局中的控件绑定对象 * @param v 布局参数 */ public ViewHolder(View v) { imgCarLogo = (ImageView) v.findViewById(R.id.image_car_logo); textCarBrandVersion = (TextView) v.findViewById(R.id.text_car_brand_version); textTotalOil = (TextView) v.findViewById(R.id.text_total_oil); textCarLicence = (TextView) v.findViewById(R.id.text_car_licence); textTransState = (TextView) v.findViewById(R.id.text_trans_state); textEngineState = (TextView) v.findViewById(R.id.text_engine_state); textLightState = (TextView) v.findViewById(R.id.text_light_state); textEngineNo = (TextView) v.findViewById(R.id.text_engine_no); } /** * 绑定数据 * @param userCar 用户车辆对象 */ public void bindData(UserCar userCar) { // 设置图标 setCarLogo(userCar.getCarBrand()); // 设置其他参数 textCarBrandVersion.setText(userCar.getCarBrand()+userCar.getCarVersion()); textTotalOil.setText(userCar.getCarOilTotal() + "L"); textCarLicence.setText(userCar.getCarLicence()); textEngineState.setText(userCar.getCarEngineState()); textTransState.setText(userCar.getCarTransState()); textLightState.setText(userCar.getCarLightState()); textEngineNo.setText(userCar.getCarEngineNo()); } private void setCarLogo(String carBrand) { // 根据车品牌设置图标 switch (carBrand) { case "奥迪": imgCarLogo.setImageResource(R.drawable.auto_audi); break; case "本田": imgCarLogo.setImageResource(R.drawable.auto_honda); break; case "福特": imgCarLogo.setImageResource(R.drawable.auto_ford); break; case "玛莎拉蒂": imgCarLogo.setImageResource(R.drawable.auto_maserati); break; case "马自达": imgCarLogo.setImageResource(R.drawable.auto_mazda); break; case "现代": imgCarLogo.setImageResource(R.drawable.auto_hyundai); break; case "大众": imgCarLogo.setImageResource(R.drawable.auto_volkswagen); break; case "日产": imgCarLogo.setImageResource(R.drawable.auto_nissan); break; case "斯柯达": imgCarLogo.setImageResource(R.drawable.auto_skoda); break; case "雪弗兰": imgCarLogo.setImageResource(R.drawable.auto_chevrolet); break; case "三菱": imgCarLogo.setImageResource(R.drawable.auto_mitsubishi); break; default: imgCarLogo.setImageResource(R.drawable.auto_abarth); break; } } } }
Bill56/CarLife
app/src/main/java/com/bill56/adapter/CarInfoAdapter.java
1,247
// 加载模板,创建视图项——将布局创建成一个View对象
line_comment
zh-cn
package com.bill56.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.bill56.carlife.R; import com.bill56.entity.UserCar; import java.util.List; /** * Created by Bill56 on 2016/5/23. */ public class CarInfoAdapter extends BaseAdapter { // 上下文环境 private Context mContext; // 数据 private List<UserCar> mData; // 布局服务加载器 private LayoutInflater layoutInflater; public CarInfoAdapter(Context context, List<UserCar> data) { this.mContext = context; mData = data; layoutInflater = LayoutInflater.from(context); } @Override public int getCount() { return mData.size(); } @Override public Object getItem(int position) { return mData.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; // 加载 <SUF> if (convertView == null) { convertView = layoutInflater.inflate(R.layout.item_car_info, parent, false); viewHolder = new ViewHolder(convertView); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } UserCar userCar = mData.get(position); viewHolder.bindData(userCar); return convertView; } /** * 保存布局控件实例的类 */ private class ViewHolder { // 字段 ImageView imgCarLogo; TextView textCarBrandVersion; TextView textTotalOil; TextView textCarLicence; TextView textTransState; TextView textEngineState; TextView textLightState; TextView textEngineNo; /** * 构造方法,获得布局中的控件绑定对象 * @param v 布局参数 */ public ViewHolder(View v) { imgCarLogo = (ImageView) v.findViewById(R.id.image_car_logo); textCarBrandVersion = (TextView) v.findViewById(R.id.text_car_brand_version); textTotalOil = (TextView) v.findViewById(R.id.text_total_oil); textCarLicence = (TextView) v.findViewById(R.id.text_car_licence); textTransState = (TextView) v.findViewById(R.id.text_trans_state); textEngineState = (TextView) v.findViewById(R.id.text_engine_state); textLightState = (TextView) v.findViewById(R.id.text_light_state); textEngineNo = (TextView) v.findViewById(R.id.text_engine_no); } /** * 绑定数据 * @param userCar 用户车辆对象 */ public void bindData(UserCar userCar) { // 设置图标 setCarLogo(userCar.getCarBrand()); // 设置其他参数 textCarBrandVersion.setText(userCar.getCarBrand()+userCar.getCarVersion()); textTotalOil.setText(userCar.getCarOilTotal() + "L"); textCarLicence.setText(userCar.getCarLicence()); textEngineState.setText(userCar.getCarEngineState()); textTransState.setText(userCar.getCarTransState()); textLightState.setText(userCar.getCarLightState()); textEngineNo.setText(userCar.getCarEngineNo()); } private void setCarLogo(String carBrand) { // 根据车品牌设置图标 switch (carBrand) { case "奥迪": imgCarLogo.setImageResource(R.drawable.auto_audi); break; case "本田": imgCarLogo.setImageResource(R.drawable.auto_honda); break; case "福特": imgCarLogo.setImageResource(R.drawable.auto_ford); break; case "玛莎拉蒂": imgCarLogo.setImageResource(R.drawable.auto_maserati); break; case "马自达": imgCarLogo.setImageResource(R.drawable.auto_mazda); break; case "现代": imgCarLogo.setImageResource(R.drawable.auto_hyundai); break; case "大众": imgCarLogo.setImageResource(R.drawable.auto_volkswagen); break; case "日产": imgCarLogo.setImageResource(R.drawable.auto_nissan); break; case "斯柯达": imgCarLogo.setImageResource(R.drawable.auto_skoda); break; case "雪弗兰": imgCarLogo.setImageResource(R.drawable.auto_chevrolet); break; case "三菱": imgCarLogo.setImageResource(R.drawable.auto_mitsubishi); break; default: imgCarLogo.setImageResource(R.drawable.auto_abarth); break; } } } }
0
1,020
17
1,247
16
1,291
15
1,247
16
1,544
27
false
false
false
false
false
true
51833_2
import java.util.Random; public class Main { private static void testEncodeLong64() { Random r = new Random(); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong(); long y = LongEncoder.encode64(x); long z = LongEncoder.decode64(y); if (x != z) { success = false; break; } } if (success) { System.out.println("testEncodeLong64 success"); } else { System.out.println("testEncodeLong64 failed"); } } private static void testEncodeLong48() { Random r = new Random(); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong() >>> 16; long y = LongEncoder.encode48(x); long z = LongEncoder.decode48(y); if (x != z) { success = false; break; } } if (success) { System.out.println("testEncodeLong48 success"); } else { System.out.println("testEncodeLong48 failed"); } } private static void testBase62() { Random r = new Random(); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong(); String y = Base62.encode(LongEncoder.encode64(x)); long z = LongEncoder.decode64(Base62.decode(y)); if (x != z) { success = false; break; } } if (success) { System.out.println("testBase62 success"); } else { System.out.println("testBase62 failed"); } } private static void testBase62ForShortLink(){ Random r = new Random(); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong() >>> 16; // 48bit的x, y的长度在1~9之间,长度为8居多 // 如果需要恒定8字节,则可以用Base64, Base64时6bit一个字节,正好8字节 // 如果又不想引入特殊字符('-','_'), 则x需要需要小于等于47bit,构造一个47bit的x(比较复杂) String y = Base62.encodePositive(LongEncoder.encode48(x)); long z = LongEncoder.decode48(Base62.decodePositive(y)); if (x != z) { success = false; break; } } if (success) { System.out.println("testBase62ForShortLink success"); } else { System.out.println("testBase62ForShortLink failed"); } } private static void testLong48ToHex() { Random r = new Random(); long x = r.nextLong() >>> 16; String y = HexUtil.long48ToHex(LongEncoder.encode48(x)); long z = LongEncoder.decode48(HexUtil.hexToLong48(y)); if (x == z) { System.out.println("testLong48ToHex success"); } else { System.out.println("testLong48ToHex failed"); } System.out.println("y = " + y); } private static void testNumberCipher() { byte[] key = new byte[24]; Random r = new Random(); r.nextBytes(key); NumberCipher cipher = new NumberCipher(key); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong(); long y = cipher.encryptLong(x); long z = cipher.decryptLong(y); if (x != z) { success = false; break; } } if (success) { System.out.println("Test encode long success"); } else { System.out.println("Test encode long failed"); } if(!success){ return; } for (int i = 0; i < 100; i++) { int x = r.nextInt(); int y = cipher.encryptInt(x); int z = cipher.decryptInt(y); if (x != z) { success = false; break; } } if (success) { System.out.println("Test encode int success"); } else { System.out.println("Test encode int failed"); } } public static void main(String[] args) { testEncodeLong64(); testEncodeLong48(); testNumberCipher(); // testBase62(); // testBase62ForShortLink(); // testLong48ToHex(); } }
BillyWei01/LongEncrypt
src/Main.java
1,176
// 如果又不想引入特殊字符('-','_'), 则x需要需要小于等于47bit,构造一个47bit的x(比较复杂)
line_comment
zh-cn
import java.util.Random; public class Main { private static void testEncodeLong64() { Random r = new Random(); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong(); long y = LongEncoder.encode64(x); long z = LongEncoder.decode64(y); if (x != z) { success = false; break; } } if (success) { System.out.println("testEncodeLong64 success"); } else { System.out.println("testEncodeLong64 failed"); } } private static void testEncodeLong48() { Random r = new Random(); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong() >>> 16; long y = LongEncoder.encode48(x); long z = LongEncoder.decode48(y); if (x != z) { success = false; break; } } if (success) { System.out.println("testEncodeLong48 success"); } else { System.out.println("testEncodeLong48 failed"); } } private static void testBase62() { Random r = new Random(); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong(); String y = Base62.encode(LongEncoder.encode64(x)); long z = LongEncoder.decode64(Base62.decode(y)); if (x != z) { success = false; break; } } if (success) { System.out.println("testBase62 success"); } else { System.out.println("testBase62 failed"); } } private static void testBase62ForShortLink(){ Random r = new Random(); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong() >>> 16; // 48bit的x, y的长度在1~9之间,长度为8居多 // 如果需要恒定8字节,则可以用Base64, Base64时6bit一个字节,正好8字节 // 如果 <SUF> String y = Base62.encodePositive(LongEncoder.encode48(x)); long z = LongEncoder.decode48(Base62.decodePositive(y)); if (x != z) { success = false; break; } } if (success) { System.out.println("testBase62ForShortLink success"); } else { System.out.println("testBase62ForShortLink failed"); } } private static void testLong48ToHex() { Random r = new Random(); long x = r.nextLong() >>> 16; String y = HexUtil.long48ToHex(LongEncoder.encode48(x)); long z = LongEncoder.decode48(HexUtil.hexToLong48(y)); if (x == z) { System.out.println("testLong48ToHex success"); } else { System.out.println("testLong48ToHex failed"); } System.out.println("y = " + y); } private static void testNumberCipher() { byte[] key = new byte[24]; Random r = new Random(); r.nextBytes(key); NumberCipher cipher = new NumberCipher(key); boolean success = true; for (int i = 0; i < 100; i++) { long x = r.nextLong(); long y = cipher.encryptLong(x); long z = cipher.decryptLong(y); if (x != z) { success = false; break; } } if (success) { System.out.println("Test encode long success"); } else { System.out.println("Test encode long failed"); } if(!success){ return; } for (int i = 0; i < 100; i++) { int x = r.nextInt(); int y = cipher.encryptInt(x); int z = cipher.decryptInt(y); if (x != z) { success = false; break; } } if (success) { System.out.println("Test encode int success"); } else { System.out.println("Test encode int failed"); } } public static void main(String[] args) { testEncodeLong64(); testEncodeLong48(); testNumberCipher(); // testBase62(); // testBase62ForShortLink(); // testLong48ToHex(); } }
0
1,085
33
1,176
35
1,294
33
1,176
35
1,393
56
false
false
false
false
false
true